@aaac/runtime 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/handlebars/lib/handlebars/utils.js","../../../node_modules/handlebars/lib/handlebars/exception.js","../../../node_modules/handlebars/lib/handlebars/helpers/block-helper-missing.js","../../../node_modules/handlebars/lib/handlebars/helpers/each.js","../../../node_modules/handlebars/lib/handlebars/helpers/helper-missing.js","../../../node_modules/handlebars/lib/handlebars/helpers/if.js","../../../node_modules/handlebars/lib/handlebars/helpers/log.js","../../../node_modules/handlebars/lib/handlebars/helpers/lookup.js","../../../node_modules/handlebars/lib/handlebars/helpers/with.js","../../../node_modules/handlebars/lib/handlebars/helpers.js","../../../node_modules/handlebars/lib/handlebars/decorators/inline.js","../../../node_modules/handlebars/lib/handlebars/decorators.js","../../../node_modules/handlebars/lib/handlebars/logger.js","../../../node_modules/handlebars/lib/handlebars/internal/proto-access.js","../../../node_modules/handlebars/lib/handlebars/base.js","../../../node_modules/handlebars/lib/handlebars/safe-string.js","../../../node_modules/handlebars/lib/handlebars/internal/wrapHelper.js","../../../node_modules/handlebars/lib/handlebars/runtime.js","../../../node_modules/handlebars/lib/handlebars/no-conflict.js","../../../node_modules/handlebars/lib/handlebars.runtime.js","../../../node_modules/handlebars/lib/handlebars/compiler/ast.js","../../../node_modules/handlebars/lib/handlebars/compiler/parser.js","../../../node_modules/handlebars/lib/handlebars/compiler/visitor.js","../../../node_modules/handlebars/lib/handlebars/compiler/whitespace-control.js","../../../node_modules/handlebars/lib/handlebars/compiler/helpers.js","../../../node_modules/handlebars/lib/handlebars/compiler/base.js","../../../node_modules/handlebars/lib/handlebars/compiler/compiler.js","../../../node_modules/handlebars/node_modules/source-map/lib/base64.js","../../../node_modules/handlebars/node_modules/source-map/lib/base64-vlq.js","../../../node_modules/handlebars/node_modules/source-map/lib/util.js","../../../node_modules/handlebars/node_modules/source-map/lib/array-set.js","../../../node_modules/handlebars/node_modules/source-map/lib/mapping-list.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-map-generator.js","../../../node_modules/handlebars/node_modules/source-map/lib/binary-search.js","../../../node_modules/handlebars/node_modules/source-map/lib/quick-sort.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-map-consumer.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-node.js","../../../node_modules/handlebars/node_modules/source-map/source-map.js","../../../node_modules/handlebars/lib/handlebars/compiler/code-gen.js","../../../node_modules/handlebars/lib/handlebars/compiler/javascript-compiler.js","../../../node_modules/handlebars/lib/handlebars.js","../../../node_modules/handlebars/lib/handlebars/compiler/printer.js","../../../node_modules/handlebars/lib/index.js","../src/index.ts","../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/candidate-agents.ts","../src/lib/model-pricing.ts","../src/lib/process-axis-bridge.ts","../src/lib/toolchain-checker.ts","../src/lib/workflow-input.ts","../src/lib/workflow-runner.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts","../src/lib/model-resolver.ts","../src/lib/progress-sink.ts","../src/lib/memory-store.ts","../src/lib/file-memory-store.ts","../src/lib/agent-log-writer.ts","../src/lib/library-tool-binding.ts","../src/lib/adapter-factory.ts","../src/lib/execute.ts","../src/component-scope.ts","../src/lib/model-aware-adapter.ts","../src/component-binding.ts","../src/lib/project-runtime.ts","../src/lib/guard-commands.ts","../src/lib/claude-materialize/config.ts","../src/lib/claude-materialize/workflow-render.ts","../src/lib/claude-materialize/dsl-sources.ts","../src/lib/claude-materialize/command-render.ts","../src/lib/claude-materialize/frontmatter.ts","../src/lib/claude-materialize/agent-render.ts","../src/lib/claude-materialize/materialize.ts","../src/lib/claude-materialize/bundle-bins.ts","../src/lib/claude-materialize/claude-bundle-assets.ts","../src/lib/claude-materialize/settings-merge.ts","../src/lib/prompt-executor.ts"],"sourcesContent":["const escape = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`',\n '=': '='\n};\n\nconst badChars = /[&<>\"'`=]/g,\n possible = /[&<>\"'`=]/;\n\nfunction escapeChar(chr) {\n return escape[chr];\n}\n\nexport function extend(obj /* , ...source */) {\n for (let i = 1; i < arguments.length; i++) {\n for (let key in arguments[i]) {\n if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {\n obj[key] = arguments[i][key];\n }\n }\n }\n\n return obj;\n}\n\nexport let toString = Object.prototype.toString;\n\n// Sourced from lodash\n// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt\n/* eslint-disable func-style */\nlet isFunction = function(value) {\n return typeof value === 'function';\n};\n// fallback for older versions of Chrome and Safari\n/* istanbul ignore next */\nif (isFunction(/x/)) {\n isFunction = function(value) {\n return (\n typeof value === 'function' &&\n toString.call(value) === '[object Function]'\n );\n };\n}\nexport { isFunction };\n/* eslint-enable func-style */\n\n/* istanbul ignore next */\nexport const isArray =\n Array.isArray ||\n function(value) {\n return value && typeof value === 'object'\n ? toString.call(value) === '[object Array]'\n : false;\n };\n\n// Older IE versions do not directly support indexOf so we must implement our own, sadly.\nexport function indexOf(array, value) {\n for (let i = 0, len = array.length; i < len; i++) {\n if (array[i] === value) {\n return i;\n }\n }\n return -1;\n}\n\nexport function escapeExpression(string) {\n if (typeof string !== 'string') {\n // don't escape SafeStrings, since they're already safe\n if (string && string.toHTML) {\n return string.toHTML();\n } else if (string == null) {\n return '';\n } else if (!string) {\n return string + '';\n }\n\n // Force a string conversion as this will be done by the append regardless and\n // the regex test will do this transparently behind the scenes, causing issues if\n // an object's to string has escaped characters in it.\n string = '' + string;\n }\n\n if (!possible.test(string)) {\n return string;\n }\n return string.replace(badChars, escapeChar);\n}\n\nexport function isEmpty(value) {\n if (!value && value !== 0) {\n return true;\n } else if (isArray(value) && value.length === 0) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function createFrame(object) {\n let frame = extend({}, object);\n frame._parent = object;\n return frame;\n}\n\nexport function blockParams(params, ids) {\n params.path = ids;\n return params;\n}\n\nexport function appendContextPath(contextPath, id) {\n return (contextPath ? contextPath + '.' : '') + id;\n}\n","const errorProps = [\n 'description',\n 'fileName',\n 'lineNumber',\n 'endLineNumber',\n 'message',\n 'name',\n 'number',\n 'stack'\n];\n\nfunction Exception(message, node) {\n let loc = node && node.loc,\n line,\n endLineNumber,\n column,\n endColumn;\n\n if (loc) {\n line = loc.start.line;\n endLineNumber = loc.end.line;\n column = loc.start.column;\n endColumn = loc.end.column;\n\n message += ' - ' + line + ':' + column;\n }\n\n let tmp = Error.prototype.constructor.call(this, message);\n\n // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.\n for (let idx = 0; idx < errorProps.length; idx++) {\n this[errorProps[idx]] = tmp[errorProps[idx]];\n }\n\n /* istanbul ignore else */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Exception);\n }\n\n try {\n if (loc) {\n this.lineNumber = line;\n this.endLineNumber = endLineNumber;\n\n // Work around issue under safari where we can't directly set the column value\n /* istanbul ignore next */\n if (Object.defineProperty) {\n Object.defineProperty(this, 'column', {\n value: column,\n enumerable: true\n });\n Object.defineProperty(this, 'endColumn', {\n value: endColumn,\n enumerable: true\n });\n } else {\n this.column = column;\n this.endColumn = endColumn;\n }\n }\n } catch (nop) {\n /* Ignore if the browser is very particular */\n }\n}\n\nException.prototype = new Error();\n\nexport default Exception;\n","import { appendContextPath, createFrame, isArray } from '../utils';\n\nexport default function(instance) {\n instance.registerHelper('blockHelperMissing', function(context, options) {\n let inverse = options.inverse,\n fn = options.fn;\n\n if (context === true) {\n return fn(this);\n } else if (context === false || context == null) {\n return inverse(this);\n } else if (isArray(context)) {\n if (context.length > 0) {\n if (options.ids) {\n options.ids = [options.name];\n }\n\n return instance.helpers.each(context, options);\n } else {\n return inverse(this);\n }\n } else {\n if (options.data && options.ids) {\n let data = createFrame(options.data);\n data.contextPath = appendContextPath(\n options.data.contextPath,\n options.name\n );\n options = { data: data };\n }\n\n return fn(context, options);\n }\n });\n}\n","import {\n appendContextPath,\n blockParams,\n createFrame,\n isArray,\n isFunction\n} from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('each', function(context, options) {\n if (!options) {\n throw new Exception('Must pass iterator to #each');\n }\n\n let fn = options.fn,\n inverse = options.inverse,\n i = 0,\n ret = '',\n data,\n contextPath;\n\n if (options.data && options.ids) {\n contextPath =\n appendContextPath(options.data.contextPath, options.ids[0]) + '.';\n }\n\n if (isFunction(context)) {\n context = context.call(this);\n }\n\n if (options.data) {\n data = createFrame(options.data);\n }\n\n function execIteration(field, index, last) {\n if (data) {\n data.key = field;\n data.index = index;\n data.first = index === 0;\n data.last = !!last;\n\n if (contextPath) {\n data.contextPath = contextPath + field;\n }\n }\n\n ret =\n ret +\n fn(context[field], {\n data: data,\n blockParams: blockParams(\n [context[field], field],\n [contextPath + field, null]\n )\n });\n }\n\n if (context && typeof context === 'object') {\n if (isArray(context)) {\n for (let j = context.length; i < j; i++) {\n if (i in context) {\n execIteration(i, i, i === context.length - 1);\n }\n }\n } else if (typeof Symbol === 'function' && context[Symbol.iterator]) {\n const newContext = [];\n const iterator = context[Symbol.iterator]();\n for (let it = iterator.next(); !it.done; it = iterator.next()) {\n newContext.push(it.value);\n }\n context = newContext;\n for (let j = context.length; i < j; i++) {\n execIteration(i, i, i === context.length - 1);\n }\n } else {\n let priorKey;\n\n Object.keys(context).forEach(key => {\n // We're running the iterations one step out of sync so we can detect\n // the last iteration without have to scan the object twice and create\n // an itermediate keys array.\n if (priorKey !== undefined) {\n execIteration(priorKey, i - 1);\n }\n priorKey = key;\n i++;\n });\n if (priorKey !== undefined) {\n execIteration(priorKey, i - 1, true);\n }\n }\n }\n\n if (i === 0) {\n ret = inverse(this);\n }\n\n return ret;\n });\n}\n","import Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('helperMissing', function(/* [args, ]options */) {\n if (arguments.length === 1) {\n // A missing field in a {{foo}} construct.\n return undefined;\n } else {\n // Someone is actually trying to call something, blow up.\n throw new Exception(\n 'Missing helper: \"' + arguments[arguments.length - 1].name + '\"'\n );\n }\n });\n}\n","import { isEmpty, isFunction } from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('if', function(conditional, options) {\n if (arguments.length != 2) {\n throw new Exception('#if requires exactly one argument');\n }\n if (isFunction(conditional)) {\n conditional = conditional.call(this);\n }\n\n // Default behavior is to render the positive path if the value is truthy and not empty.\n // The `includeZero` option may be set to treat the condtional as purely not empty based on the\n // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.\n if ((!options.hash.includeZero && !conditional) || isEmpty(conditional)) {\n return options.inverse(this);\n } else {\n return options.fn(this);\n }\n });\n\n instance.registerHelper('unless', function(conditional, options) {\n if (arguments.length != 2) {\n throw new Exception('#unless requires exactly one argument');\n }\n return instance.helpers['if'].call(this, conditional, {\n fn: options.inverse,\n inverse: options.fn,\n hash: options.hash\n });\n });\n}\n","export default function(instance) {\n instance.registerHelper('log', function(/* message, options */) {\n let args = [undefined],\n options = arguments[arguments.length - 1];\n for (let i = 0; i < arguments.length - 1; i++) {\n args.push(arguments[i]);\n }\n\n let level = 1;\n if (options.hash.level != null) {\n level = options.hash.level;\n } else if (options.data && options.data.level != null) {\n level = options.data.level;\n }\n args[0] = level;\n\n instance.log(...args);\n });\n}\n","export default function(instance) {\n instance.registerHelper('lookup', function(obj, field, options) {\n if (!obj) {\n // Note for 5.0: Change to \"obj == null\" in 5.0\n return obj;\n }\n return options.lookupProperty(obj, field);\n });\n}\n","import {\n appendContextPath,\n blockParams,\n createFrame,\n isEmpty,\n isFunction\n} from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('with', function(context, options) {\n if (arguments.length != 2) {\n throw new Exception('#with requires exactly one argument');\n }\n if (isFunction(context)) {\n context = context.call(this);\n }\n\n let fn = options.fn;\n\n if (!isEmpty(context)) {\n let data = options.data;\n if (options.data && options.ids) {\n data = createFrame(options.data);\n data.contextPath = appendContextPath(\n options.data.contextPath,\n options.ids[0]\n );\n }\n\n return fn(context, {\n data: data,\n blockParams: blockParams([context], [data && data.contextPath])\n });\n } else {\n return options.inverse(this);\n }\n });\n}\n","import registerBlockHelperMissing from './helpers/block-helper-missing';\nimport registerEach from './helpers/each';\nimport registerHelperMissing from './helpers/helper-missing';\nimport registerIf from './helpers/if';\nimport registerLog from './helpers/log';\nimport registerLookup from './helpers/lookup';\nimport registerWith from './helpers/with';\n\nexport function registerDefaultHelpers(instance) {\n registerBlockHelperMissing(instance);\n registerEach(instance);\n registerHelperMissing(instance);\n registerIf(instance);\n registerLog(instance);\n registerLookup(instance);\n registerWith(instance);\n}\n\nexport function moveHelperToHooks(instance, helperName, keepHelper) {\n if (instance.helpers[helperName]) {\n instance.hooks[helperName] = instance.helpers[helperName];\n if (!keepHelper) {\n // Using delete is slow\n instance.helpers[helperName] = undefined;\n }\n }\n}\n","import { extend } from '../utils';\n\nexport default function(instance) {\n instance.registerDecorator('inline', function(fn, props, container, options) {\n let ret = fn;\n if (!props.partials) {\n props.partials = {};\n ret = function(context, options) {\n // Create a new partials stack frame prior to exec.\n let original = container.partials;\n container.partials = extend({}, original, props.partials);\n let ret = fn(context, options);\n container.partials = original;\n return ret;\n };\n }\n\n props.partials[options.args[0]] = options.fn;\n\n return ret;\n });\n}\n","import registerInline from './decorators/inline';\n\nexport function registerDefaultDecorators(instance) {\n registerInline(instance);\n}\n","import { indexOf } from './utils';\n\nlet logger = {\n methodMap: ['debug', 'info', 'warn', 'error'],\n level: 'info',\n\n // Maps a given level value to the `methodMap` indexes above.\n lookupLevel: function(level) {\n if (typeof level === 'string') {\n let levelMap = indexOf(logger.methodMap, level.toLowerCase());\n if (levelMap >= 0) {\n level = levelMap;\n } else {\n level = parseInt(level, 10);\n }\n }\n\n return level;\n },\n\n // Can be overridden in the host environment\n log: function(level, ...message) {\n level = logger.lookupLevel(level);\n\n if (\n typeof console !== 'undefined' &&\n logger.lookupLevel(logger.level) <= level\n ) {\n let method = logger.methodMap[level];\n // eslint-disable-next-line no-console\n if (!console[method]) {\n method = 'log';\n }\n console[method](...message); // eslint-disable-line no-console\n }\n }\n};\n\nexport default logger;\n","import { extend } from '../utils';\nimport logger from '../logger';\n\nconst loggedProperties = Object.create(null);\n\nexport function createProtoAccessControl(runtimeOptions) {\n // Create an object with \"null\"-prototype to avoid truthy results on\n // prototype properties.\n const propertyWhiteList = Object.create(null);\n // eslint-disable-next-line no-proto\n propertyWhiteList['__proto__'] = false;\n extend(propertyWhiteList, runtimeOptions.allowedProtoProperties);\n\n const methodWhiteList = Object.create(null);\n methodWhiteList['constructor'] = false;\n methodWhiteList['__defineGetter__'] = false;\n methodWhiteList['__defineSetter__'] = false;\n methodWhiteList['__lookupGetter__'] = false;\n methodWhiteList['__lookupSetter__'] = false;\n extend(methodWhiteList, runtimeOptions.allowedProtoMethods);\n\n return {\n properties: {\n whitelist: propertyWhiteList,\n defaultValue: runtimeOptions.allowProtoPropertiesByDefault\n },\n methods: {\n whitelist: methodWhiteList,\n defaultValue: runtimeOptions.allowProtoMethodsByDefault\n }\n };\n}\n\nexport function resultIsAllowed(result, protoAccessControl, propertyName) {\n if (typeof result === 'function') {\n return checkWhiteList(protoAccessControl.methods, propertyName);\n } else {\n return checkWhiteList(protoAccessControl.properties, propertyName);\n }\n}\n\nfunction checkWhiteList(protoAccessControlForType, propertyName) {\n if (protoAccessControlForType.whitelist[propertyName] !== undefined) {\n return protoAccessControlForType.whitelist[propertyName] === true;\n }\n if (protoAccessControlForType.defaultValue !== undefined) {\n return protoAccessControlForType.defaultValue;\n }\n logUnexpecedPropertyAccessOnce(propertyName);\n return false;\n}\n\nfunction logUnexpecedPropertyAccessOnce(propertyName) {\n if (loggedProperties[propertyName] !== true) {\n loggedProperties[propertyName] = true;\n logger.log(\n 'error',\n `Handlebars: Access has been denied to resolve the property \"${propertyName}\" because it is not an \"own property\" of its parent.\\n` +\n `You can add a runtime option to disable the check or this warning:\\n` +\n `See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`\n );\n }\n}\n\nexport function resetLoggedProperties() {\n Object.keys(loggedProperties).forEach(propertyName => {\n delete loggedProperties[propertyName];\n });\n}\n","import { createFrame, extend, toString } from './utils';\nimport Exception from './exception';\nimport { registerDefaultHelpers } from './helpers';\nimport { registerDefaultDecorators } from './decorators';\nimport logger from './logger';\nimport { resetLoggedProperties } from './internal/proto-access';\n\nexport const VERSION = '4.7.9';\nexport const COMPILER_REVISION = 8;\nexport const LAST_COMPATIBLE_COMPILER_REVISION = 7;\n\nexport const REVISION_CHANGES = {\n 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it\n 2: '== 1.0.0-rc.3',\n 3: '== 1.0.0-rc.4',\n 4: '== 1.x.x',\n 5: '== 2.0.0-alpha.x',\n 6: '>= 2.0.0-beta.1',\n 7: '>= 4.0.0 <4.3.0',\n 8: '>= 4.3.0'\n};\n\nconst objectType = '[object Object]';\n\nexport function HandlebarsEnvironment(helpers, partials, decorators) {\n this.helpers = helpers || {};\n this.partials = partials || {};\n this.decorators = decorators || {};\n\n registerDefaultHelpers(this);\n registerDefaultDecorators(this);\n}\n\nHandlebarsEnvironment.prototype = {\n constructor: HandlebarsEnvironment,\n\n logger: logger,\n log: logger.log,\n\n registerHelper: function(name, fn) {\n if (toString.call(name) === objectType) {\n if (fn) {\n throw new Exception('Arg not supported with multiple helpers');\n }\n extend(this.helpers, name);\n } else {\n this.helpers[name] = fn;\n }\n },\n unregisterHelper: function(name) {\n delete this.helpers[name];\n },\n\n registerPartial: function(name, partial) {\n if (toString.call(name) === objectType) {\n extend(this.partials, name);\n } else {\n if (typeof partial === 'undefined') {\n throw new Exception(\n `Attempting to register a partial called \"${name}\" as undefined`\n );\n }\n this.partials[name] = partial;\n }\n },\n unregisterPartial: function(name) {\n delete this.partials[name];\n },\n\n registerDecorator: function(name, fn) {\n if (toString.call(name) === objectType) {\n if (fn) {\n throw new Exception('Arg not supported with multiple decorators');\n }\n extend(this.decorators, name);\n } else {\n this.decorators[name] = fn;\n }\n },\n unregisterDecorator: function(name) {\n delete this.decorators[name];\n },\n /**\n * Reset the memory of illegal property accesses that have already been logged.\n * @deprecated should only be used in handlebars test-cases\n */\n resetLoggedPropertyAccesses() {\n resetLoggedProperties();\n }\n};\n\nexport let log = logger.log;\n\nexport { createFrame, logger };\n","// Build out our basic SafeString type\nfunction SafeString(string) {\n this.string = string;\n}\n\nSafeString.prototype.toString = SafeString.prototype.toHTML = function() {\n return '' + this.string;\n};\n\nexport default SafeString;\n","export function wrapHelper(helper, transformOptionsFn) {\n if (typeof helper !== 'function') {\n // This should not happen, but apparently it does in https://github.com/wycats/handlebars.js/issues/1639\n // We try to make the wrapper least-invasive by not wrapping it, if the helper is not a function.\n return helper;\n }\n let wrapper = function(/* dynamic arguments */) {\n const options = arguments[arguments.length - 1];\n arguments[arguments.length - 1] = transformOptionsFn(options);\n return helper.apply(this, arguments);\n };\n return wrapper;\n}\n","import * as Utils from './utils';\nimport Exception from './exception';\nimport {\n COMPILER_REVISION,\n createFrame,\n LAST_COMPATIBLE_COMPILER_REVISION,\n REVISION_CHANGES\n} from './base';\nimport { moveHelperToHooks } from './helpers';\nimport { wrapHelper } from './internal/wrapHelper';\nimport {\n createProtoAccessControl,\n resultIsAllowed\n} from './internal/proto-access';\n\nexport function checkRevision(compilerInfo) {\n const compilerRevision = (compilerInfo && compilerInfo[0]) || 1,\n currentRevision = COMPILER_REVISION;\n\n if (\n compilerRevision >= LAST_COMPATIBLE_COMPILER_REVISION &&\n compilerRevision <= COMPILER_REVISION\n ) {\n return;\n }\n\n if (compilerRevision < LAST_COMPATIBLE_COMPILER_REVISION) {\n const runtimeVersions = REVISION_CHANGES[currentRevision],\n compilerVersions = REVISION_CHANGES[compilerRevision];\n throw new Exception(\n 'Template was precompiled with an older version of Handlebars than the current runtime. ' +\n 'Please update your precompiler to a newer version (' +\n runtimeVersions +\n ') or downgrade your runtime to an older version (' +\n compilerVersions +\n ').'\n );\n } else {\n // Use the embedded version info since the runtime doesn't know about this revision yet\n throw new Exception(\n 'Template was precompiled with a newer version of Handlebars than the current runtime. ' +\n 'Please update your runtime to a newer version (' +\n compilerInfo[1] +\n ').'\n );\n }\n}\n\nexport function template(templateSpec, env) {\n /* istanbul ignore next */\n if (!env) {\n throw new Exception('No environment passed to template');\n }\n if (!templateSpec || !templateSpec.main) {\n throw new Exception('Unknown template object: ' + typeof templateSpec);\n }\n\n templateSpec.main.decorator = templateSpec.main_d;\n\n // Note: Using env.VM references rather than local var references throughout this section to allow\n // for external users to override these as pseudo-supported APIs.\n env.VM.checkRevision(templateSpec.compiler);\n\n // backwards compatibility for precompiled templates with compiler-version 7 (<4.3.0)\n const templateWasPrecompiledWithCompilerV7 =\n templateSpec.compiler && templateSpec.compiler[0] === 7;\n\n function invokePartialWrapper(partial, context, options) {\n if (options.hash) {\n context = Utils.extend({}, context, options.hash);\n if (options.ids) {\n options.ids[0] = true;\n }\n }\n partial = env.VM.resolvePartial.call(this, partial, context, options);\n\n options.hooks = this.hooks;\n options.protoAccessControl = this.protoAccessControl;\n\n let result = env.VM.invokePartial.call(this, partial, context, options);\n\n if (result == null && env.compile) {\n options.partials[options.name] = env.compile(\n partial,\n templateSpec.compilerOptions,\n env\n );\n result = options.partials[options.name](context, options);\n }\n if (result != null) {\n if (options.indent) {\n let lines = result.split('\\n');\n for (let i = 0, l = lines.length; i < l; i++) {\n if (!lines[i] && i + 1 === l) {\n break;\n }\n\n lines[i] = options.indent + lines[i];\n }\n result = lines.join('\\n');\n }\n return result;\n } else {\n throw new Exception(\n 'The partial ' +\n options.name +\n ' could not be compiled when running in runtime-only mode'\n );\n }\n }\n\n // Just add water\n let container = {\n strict: function(obj, name, loc) {\n if (!obj || !(name in obj)) {\n throw new Exception('\"' + name + '\" not defined in ' + obj, {\n loc: loc\n });\n }\n return container.lookupProperty(obj, name);\n },\n lookupProperty: function(parent, propertyName) {\n let result = parent[propertyName];\n if (result == null) {\n return result;\n }\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return result;\n }\n\n if (resultIsAllowed(result, container.protoAccessControl, propertyName)) {\n return result;\n }\n return undefined;\n },\n lookup: function(depths, name) {\n const len = depths.length;\n for (let i = 0; i < len; i++) {\n let result = depths[i] && container.lookupProperty(depths[i], name);\n if (result != null) {\n return result;\n }\n }\n },\n lambda: function(current, context) {\n return typeof current === 'function' ? current.call(context) : current;\n },\n\n escapeExpression: Utils.escapeExpression,\n invokePartial: invokePartialWrapper,\n\n fn: function(i) {\n let ret = templateSpec[i];\n ret.decorator = templateSpec[i + '_d'];\n return ret;\n },\n\n programs: [],\n program: function(i, data, declaredBlockParams, blockParams, depths) {\n let programWrapper = this.programs[i],\n fn = this.fn(i);\n if (data || depths || blockParams || declaredBlockParams) {\n programWrapper = wrapProgram(\n this,\n i,\n fn,\n data,\n declaredBlockParams,\n blockParams,\n depths\n );\n } else if (!programWrapper) {\n programWrapper = this.programs[i] = wrapProgram(this, i, fn);\n }\n return programWrapper;\n },\n\n data: function(value, depth) {\n while (value && depth--) {\n value = value._parent;\n }\n return value;\n },\n mergeIfNeeded: function(param, common) {\n let obj = param || common;\n\n if (param && common && param !== common) {\n obj = Utils.extend({}, common, param);\n }\n\n return obj;\n },\n // An empty object to use as replacement for null-contexts\n nullContext: Object.seal({}),\n\n noop: env.VM.noop,\n compilerInfo: templateSpec.compiler\n };\n\n function ret(context, options = {}) {\n let data = options.data;\n\n ret._setup(options);\n if (!options.partial && templateSpec.useData) {\n data = initData(context, data);\n }\n let depths,\n blockParams = templateSpec.useBlockParams ? [] : undefined;\n if (templateSpec.useDepths) {\n if (options.depths) {\n depths =\n context != options.depths[0]\n ? [context].concat(options.depths)\n : options.depths;\n } else {\n depths = [context];\n }\n }\n\n function main(context /*, options*/) {\n return (\n '' +\n templateSpec.main(\n container,\n context,\n container.helpers,\n container.partials,\n data,\n blockParams,\n depths\n )\n );\n }\n\n main = executeDecorators(\n templateSpec.main,\n main,\n container,\n options.depths || [],\n data,\n blockParams\n );\n return main(context, options);\n }\n\n ret.isTop = true;\n\n ret._setup = function(options) {\n if (!options.partial) {\n let mergedHelpers = {};\n addHelpers(mergedHelpers, env.helpers, container);\n addHelpers(mergedHelpers, options.helpers, container);\n container.helpers = mergedHelpers;\n\n if (templateSpec.usePartial) {\n // Use mergeIfNeeded here to prevent compiling global partials multiple times\n container.partials = container.mergeIfNeeded(\n options.partials,\n env.partials\n );\n }\n if (templateSpec.usePartial || templateSpec.useDecorators) {\n container.decorators = Utils.extend(\n {},\n env.decorators,\n options.decorators\n );\n }\n\n container.hooks = {};\n container.protoAccessControl = createProtoAccessControl(options);\n\n let keepHelperInHelpers =\n options.allowCallsToHelperMissing ||\n templateWasPrecompiledWithCompilerV7;\n moveHelperToHooks(container, 'helperMissing', keepHelperInHelpers);\n moveHelperToHooks(container, 'blockHelperMissing', keepHelperInHelpers);\n } else {\n container.protoAccessControl = options.protoAccessControl; // internal option\n container.helpers = options.helpers;\n container.partials = options.partials;\n container.decorators = options.decorators;\n container.hooks = options.hooks;\n }\n };\n\n ret._child = function(i, data, blockParams, depths) {\n if (templateSpec.useBlockParams && !blockParams) {\n throw new Exception('must pass block params');\n }\n if (templateSpec.useDepths && !depths) {\n throw new Exception('must pass parent depths');\n }\n\n return wrapProgram(\n container,\n i,\n templateSpec[i],\n data,\n 0,\n blockParams,\n depths\n );\n };\n return ret;\n}\n\nexport function wrapProgram(\n container,\n i,\n fn,\n data,\n declaredBlockParams,\n blockParams,\n depths\n) {\n function prog(context, options = {}) {\n let currentDepths = depths;\n if (\n depths &&\n context != depths[0] &&\n !(context === container.nullContext && depths[0] === null)\n ) {\n currentDepths = [context].concat(depths);\n }\n\n return fn(\n container,\n context,\n container.helpers,\n container.partials,\n options.data || data,\n blockParams && [options.blockParams].concat(blockParams),\n currentDepths\n );\n }\n\n prog = executeDecorators(fn, prog, container, depths, data, blockParams);\n\n prog.program = i;\n prog.depth = depths ? depths.length : 0;\n prog.blockParams = declaredBlockParams || 0;\n return prog;\n}\n\n/**\n * This is currently part of the official API, therefore implementation details should not be changed.\n */\nexport function resolvePartial(partial, context, options) {\n if (!partial) {\n if (options.name === '@partial-block') {\n partial = lookupOwnProperty(options.data, 'partial-block');\n } else {\n partial = lookupOwnProperty(options.partials, options.name);\n }\n } else if (!partial.call && !options.name) {\n // This is a dynamic partial that returned a string\n options.name = partial;\n partial = lookupOwnProperty(options.partials, partial);\n }\n return partial;\n}\n\nexport function invokePartial(partial, context, options) {\n // Use the current closure context to save the partial-block if this partial\n const currentPartialBlock = lookupOwnProperty(options.data, 'partial-block');\n options.partial = true;\n if (options.ids) {\n options.data.contextPath = options.ids[0] || options.data.contextPath;\n }\n\n let partialBlock;\n if (options.fn && options.fn !== noop) {\n options.data = createFrame(options.data);\n // Wrapper function to get access to currentPartialBlock from the closure\n let fn = options.fn;\n partialBlock = options.data['partial-block'] = function partialBlockWrapper(\n context,\n options = {}\n ) {\n // Restore the partial-block from the closure for the execution of the block\n // i.e. the part inside the block of the partial call.\n options.data = createFrame(options.data);\n options.data['partial-block'] = currentPartialBlock;\n return fn(context, options);\n };\n if (fn.partials) {\n options.partials = Utils.extend({}, options.partials, fn.partials);\n }\n }\n\n if (partial === undefined && partialBlock) {\n partial = partialBlock;\n }\n\n if (partial === undefined) {\n throw new Exception('The partial ' + options.name + ' could not be found');\n } else if (partial instanceof Function) {\n return partial(context, options);\n }\n}\n\nexport function noop() {\n return '';\n}\n\nfunction lookupOwnProperty(obj, name) {\n if (obj && Object.prototype.hasOwnProperty.call(obj, name)) {\n return obj[name];\n }\n}\n\nfunction initData(context, data) {\n if (!data || !('root' in data)) {\n data = data ? createFrame(data) : {};\n data.root = context;\n }\n return data;\n}\n\nfunction executeDecorators(fn, prog, container, depths, data, blockParams) {\n if (fn.decorator) {\n let props = {};\n prog = fn.decorator(\n prog,\n props,\n container,\n depths && depths[0],\n data,\n blockParams,\n depths\n );\n Utils.extend(prog, props);\n }\n return prog;\n}\n\nfunction addHelpers(mergedHelpers, helpers, container) {\n if (!helpers) return;\n Object.keys(helpers).forEach(helperName => {\n let helper = helpers[helperName];\n mergedHelpers[helperName] = passLookupPropertyOption(helper, container);\n });\n}\n\nfunction passLookupPropertyOption(helper, container) {\n const lookupProperty = container.lookupProperty;\n return wrapHelper(helper, options => {\n options.lookupProperty = lookupProperty;\n return options;\n });\n}\n","/* global globalThis */\nexport default function(Handlebars) {\n /* istanbul ignore next */\n // https://mathiasbynens.be/notes/globalthis\n (function() {\n if (typeof globalThis === 'object') return;\n Object.prototype.__defineGetter__('__magic__', function() {\n return this;\n });\n __magic__.globalThis = __magic__; // eslint-disable-line no-undef\n delete Object.prototype.__magic__;\n })();\n\n const $Handlebars = globalThis.Handlebars;\n\n /* istanbul ignore next */\n Handlebars.noConflict = function() {\n if (globalThis.Handlebars === Handlebars) {\n globalThis.Handlebars = $Handlebars;\n }\n return Handlebars;\n };\n}\n","import * as base from './handlebars/base';\n\n// Each of these augment the Handlebars object. No need to setup here.\n// (This is done to easily share code between commonjs and browse envs)\nimport SafeString from './handlebars/safe-string';\nimport Exception from './handlebars/exception';\nimport * as Utils from './handlebars/utils';\nimport * as runtime from './handlebars/runtime';\n\nimport noConflict from './handlebars/no-conflict';\n\n// For compatibility and usage outside of module systems, make the Handlebars object a namespace\nfunction create() {\n let hb = new base.HandlebarsEnvironment();\n\n Utils.extend(hb, base);\n hb.SafeString = SafeString;\n hb.Exception = Exception;\n hb.Utils = Utils;\n hb.escapeExpression = Utils.escapeExpression;\n\n hb.VM = runtime;\n hb.template = function(spec) {\n return runtime.template(spec, hb);\n };\n\n return hb;\n}\n\nlet inst = create();\ninst.create = create;\n\nnoConflict(inst);\n\ninst['default'] = inst;\n\nexport default inst;\n","let AST = {\n // Public API used to evaluate derived attributes regarding AST nodes\n helpers: {\n // a mustache is definitely a helper if:\n // * it is an eligible helper, and\n // * it has at least one parameter or hash segment\n helperExpression: function(node) {\n return (\n node.type === 'SubExpression' ||\n ((node.type === 'MustacheStatement' ||\n node.type === 'BlockStatement') &&\n !!((node.params && node.params.length) || node.hash))\n );\n },\n\n scopedId: function(path) {\n return /^\\.|this\\b/.test(path.original);\n },\n\n // an ID is simple if it only has one part, and that part is not\n // `..` or `this`.\n simpleId: function(path) {\n return (\n path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth\n );\n }\n }\n};\n\n// Must be exported as an object rather than the root of the module as the jison lexer\n// must modify the object to operate properly.\nexport default AST;\n","// File ignored in coverage tests via setting in .istanbul.yml\n/* Jison generated parser */\nvar handlebars = (function(){\nvar parser = {trace: function trace () { },\nyy: {},\nsymbols_: {\"error\":2,\"root\":3,\"program\":4,\"EOF\":5,\"program_repetition0\":6,\"statement\":7,\"mustache\":8,\"block\":9,\"rawBlock\":10,\"partial\":11,\"partialBlock\":12,\"content\":13,\"COMMENT\":14,\"CONTENT\":15,\"openRawBlock\":16,\"rawBlock_repetition0\":17,\"END_RAW_BLOCK\":18,\"OPEN_RAW_BLOCK\":19,\"helperName\":20,\"openRawBlock_repetition0\":21,\"openRawBlock_option0\":22,\"CLOSE_RAW_BLOCK\":23,\"openBlock\":24,\"block_option0\":25,\"closeBlock\":26,\"openInverse\":27,\"block_option1\":28,\"OPEN_BLOCK\":29,\"openBlock_repetition0\":30,\"openBlock_option0\":31,\"openBlock_option1\":32,\"CLOSE\":33,\"OPEN_INVERSE\":34,\"openInverse_repetition0\":35,\"openInverse_option0\":36,\"openInverse_option1\":37,\"openInverseChain\":38,\"OPEN_INVERSE_CHAIN\":39,\"openInverseChain_repetition0\":40,\"openInverseChain_option0\":41,\"openInverseChain_option1\":42,\"inverseAndProgram\":43,\"INVERSE\":44,\"inverseChain\":45,\"inverseChain_option0\":46,\"OPEN_ENDBLOCK\":47,\"OPEN\":48,\"mustache_repetition0\":49,\"mustache_option0\":50,\"OPEN_UNESCAPED\":51,\"mustache_repetition1\":52,\"mustache_option1\":53,\"CLOSE_UNESCAPED\":54,\"OPEN_PARTIAL\":55,\"partialName\":56,\"partial_repetition0\":57,\"partial_option0\":58,\"openPartialBlock\":59,\"OPEN_PARTIAL_BLOCK\":60,\"openPartialBlock_repetition0\":61,\"openPartialBlock_option0\":62,\"param\":63,\"sexpr\":64,\"OPEN_SEXPR\":65,\"sexpr_repetition0\":66,\"sexpr_option0\":67,\"CLOSE_SEXPR\":68,\"hash\":69,\"hash_repetition_plus0\":70,\"hashSegment\":71,\"ID\":72,\"EQUALS\":73,\"blockParams\":74,\"OPEN_BLOCK_PARAMS\":75,\"blockParams_repetition_plus0\":76,\"CLOSE_BLOCK_PARAMS\":77,\"path\":78,\"dataName\":79,\"STRING\":80,\"NUMBER\":81,\"BOOLEAN\":82,\"UNDEFINED\":83,\"NULL\":84,\"DATA\":85,\"pathSegments\":86,\"SEP\":87,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",5:\"EOF\",14:\"COMMENT\",15:\"CONTENT\",18:\"END_RAW_BLOCK\",19:\"OPEN_RAW_BLOCK\",23:\"CLOSE_RAW_BLOCK\",29:\"OPEN_BLOCK\",33:\"CLOSE\",34:\"OPEN_INVERSE\",39:\"OPEN_INVERSE_CHAIN\",44:\"INVERSE\",47:\"OPEN_ENDBLOCK\",48:\"OPEN\",51:\"OPEN_UNESCAPED\",54:\"CLOSE_UNESCAPED\",55:\"OPEN_PARTIAL\",60:\"OPEN_PARTIAL_BLOCK\",65:\"OPEN_SEXPR\",68:\"CLOSE_SEXPR\",72:\"ID\",73:\"EQUALS\",75:\"OPEN_BLOCK_PARAMS\",77:\"CLOSE_BLOCK_PARAMS\",80:\"STRING\",81:\"NUMBER\",82:\"BOOLEAN\",83:\"UNDEFINED\",84:\"NULL\",85:\"DATA\",87:\"SEP\"},\nproductions_: [0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],\nperformAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$\n) {\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1: return $$[$0-1]; \nbreak;\ncase 2:this.$ = yy.prepareProgram($$[$0]);\nbreak;\ncase 3:this.$ = $$[$0];\nbreak;\ncase 4:this.$ = $$[$0];\nbreak;\ncase 5:this.$ = $$[$0];\nbreak;\ncase 6:this.$ = $$[$0];\nbreak;\ncase 7:this.$ = $$[$0];\nbreak;\ncase 8:this.$ = $$[$0];\nbreak;\ncase 9:\n this.$ = {\n type: 'CommentStatement',\n value: yy.stripComment($$[$0]),\n strip: yy.stripFlags($$[$0], $$[$0]),\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 10:\n this.$ = {\n type: 'ContentStatement',\n original: $$[$0],\n value: $$[$0],\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 11:this.$ = yy.prepareRawBlock($$[$0-2], $$[$0-1], $$[$0], this._$);\nbreak;\ncase 12:this.$ = { path: $$[$0-3], params: $$[$0-2], hash: $$[$0-1] };\nbreak;\ncase 13:this.$ = yy.prepareBlock($$[$0-3], $$[$0-2], $$[$0-1], $$[$0], false, this._$);\nbreak;\ncase 14:this.$ = yy.prepareBlock($$[$0-3], $$[$0-2], $$[$0-1], $$[$0], true, this._$);\nbreak;\ncase 15:this.$ = { open: $$[$0-5], path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 16:this.$ = { path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 17:this.$ = { path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 18:this.$ = { strip: yy.stripFlags($$[$0-1], $$[$0-1]), program: $$[$0] };\nbreak;\ncase 19:\n var inverse = yy.prepareBlock($$[$0-2], $$[$0-1], $$[$0], $$[$0], false, this._$),\n program = yy.prepareProgram([inverse], $$[$0-1].loc);\n program.chained = true;\n\n this.$ = { strip: $$[$0-2].strip, program: program, chain: true };\n \nbreak;\ncase 20:this.$ = $$[$0];\nbreak;\ncase 21:this.$ = {path: $$[$0-1], strip: yy.stripFlags($$[$0-2], $$[$0])};\nbreak;\ncase 22:this.$ = yy.prepareMustache($$[$0-3], $$[$0-2], $$[$0-1], $$[$0-4], yy.stripFlags($$[$0-4], $$[$0]), this._$);\nbreak;\ncase 23:this.$ = yy.prepareMustache($$[$0-3], $$[$0-2], $$[$0-1], $$[$0-4], yy.stripFlags($$[$0-4], $$[$0]), this._$);\nbreak;\ncase 24:\n this.$ = {\n type: 'PartialStatement',\n name: $$[$0-3],\n params: $$[$0-2],\n hash: $$[$0-1],\n indent: '',\n strip: yy.stripFlags($$[$0-4], $$[$0]),\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 25:this.$ = yy.preparePartialBlock($$[$0-2], $$[$0-1], $$[$0], this._$);\nbreak;\ncase 26:this.$ = { path: $$[$0-3], params: $$[$0-2], hash: $$[$0-1], strip: yy.stripFlags($$[$0-4], $$[$0]) };\nbreak;\ncase 27:this.$ = $$[$0];\nbreak;\ncase 28:this.$ = $$[$0];\nbreak;\ncase 29:\n this.$ = {\n type: 'SubExpression',\n path: $$[$0-3],\n params: $$[$0-2],\n hash: $$[$0-1],\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 30:this.$ = {type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 31:this.$ = {type: 'HashPair', key: yy.id($$[$0-2]), value: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 32:this.$ = yy.id($$[$0-1]);\nbreak;\ncase 33:this.$ = $$[$0];\nbreak;\ncase 34:this.$ = $$[$0];\nbreak;\ncase 35:this.$ = {type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 36:this.$ = {type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$)};\nbreak;\ncase 37:this.$ = {type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$)};\nbreak;\ncase 38:this.$ = {type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$)};\nbreak;\ncase 39:this.$ = {type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$)};\nbreak;\ncase 40:this.$ = $$[$0];\nbreak;\ncase 41:this.$ = $$[$0];\nbreak;\ncase 42:this.$ = yy.preparePath(true, $$[$0], this._$);\nbreak;\ncase 43:this.$ = yy.preparePath(false, $$[$0], this._$);\nbreak;\ncase 44: $$[$0-2].push({part: yy.id($$[$0]), original: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; \nbreak;\ncase 45:this.$ = [{part: yy.id($$[$0]), original: $$[$0]}];\nbreak;\ncase 46:this.$ = [];\nbreak;\ncase 47:$$[$0-1].push($$[$0]);\nbreak;\ncase 48:this.$ = [];\nbreak;\ncase 49:$$[$0-1].push($$[$0]);\nbreak;\ncase 50:this.$ = [];\nbreak;\ncase 51:$$[$0-1].push($$[$0]);\nbreak;\ncase 58:this.$ = [];\nbreak;\ncase 59:$$[$0-1].push($$[$0]);\nbreak;\ncase 64:this.$ = [];\nbreak;\ncase 65:$$[$0-1].push($$[$0]);\nbreak;\ncase 70:this.$ = [];\nbreak;\ncase 71:$$[$0-1].push($$[$0]);\nbreak;\ncase 78:this.$ = [];\nbreak;\ncase 79:$$[$0-1].push($$[$0]);\nbreak;\ncase 82:this.$ = [];\nbreak;\ncase 83:$$[$0-1].push($$[$0]);\nbreak;\ncase 86:this.$ = [];\nbreak;\ncase 87:$$[$0-1].push($$[$0]);\nbreak;\ncase 90:this.$ = [];\nbreak;\ncase 91:$$[$0-1].push($$[$0]);\nbreak;\ncase 94:this.$ = [];\nbreak;\ncase 95:$$[$0-1].push($$[$0]);\nbreak;\ncase 98:this.$ = [$$[$0]];\nbreak;\ncase 99:$$[$0-1].push($$[$0]);\nbreak;\ncase 100:this.$ = [$$[$0]];\nbreak;\ncase 101:$$[$0-1].push($$[$0]);\nbreak;\n}\n},\ntable: [{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],\ndefaultActions: {4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},\nparseError: function parseError (str, hash) {\n throw new Error(str);\n},\nparse: function parse(input) {\n var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n this.lexer.setInput(input);\n this.lexer.yy = this.yy;\n this.yy.lexer = this.lexer;\n this.yy.parser = this;\n if (typeof this.lexer.yylloc == \"undefined\")\n this.lexer.yylloc = {};\n var yyloc = this.lexer.yylloc;\n lstack.push(yyloc);\n var ranges = this.lexer.options && this.lexer.options.ranges;\n if (typeof this.yy.parseError === \"function\")\n this.parseError = this.yy.parseError;\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n function lex() {\n var token;\n token = self.lexer.lex() || 1;\n if (typeof token !== \"number\") {\n token = self.symbols_[token] || token;\n }\n return token;\n }\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n if (!recovering) {\n expected = [];\n for (p in table[state])\n if (this.terminals_[p] && p > 2) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n if (this.lexer.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + this.lexer.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == 1?\"end of input\":\"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});\n }\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(this.lexer.yytext);\n lstack.push(this.lexer.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = this.lexer.yyleng;\n yytext = this.lexer.yytext;\n yylineno = this.lexer.yylineno;\n yyloc = this.lexer.yylloc;\n if (recovering > 0)\n recovering--;\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};\n if (ranges) {\n yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];\n }\n r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n}\n};\n/* Jison generated lexer */\nvar lexer = (function(){\nvar lexer = ({EOF:1,\nparseError:function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n },\nsetInput:function (input) {\n this._input = input;\n this._more = this._less = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = '';\n this.conditionStack = ['INITIAL'];\n this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};\n if (this.options.ranges) this.yylloc.range = [0,0];\n this.offset = 0;\n return this;\n },\ninput:function () {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) this.yylloc.range[1]++;\n\n this._input = this._input.slice(1);\n return ch;\n },\nunput:function (ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length-len-1);\n //this.yyleng -= len;\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length-1);\n this.matched = this.matched.substr(0, this.matched.length-1);\n\n if (lines.length-1) this.yylineno -= lines.length-1;\n var r = this.yylloc.range;\n\n this.yylloc = {first_line: this.yylloc.first_line,\n last_line: this.yylineno+1,\n first_column: this.yylloc.first_column,\n last_column: lines ?\n (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length:\n this.yylloc.first_column - len\n };\n\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n return this;\n },\nmore:function () {\n this._more = true;\n return this;\n },\nless:function (n) {\n this.unput(this.match.slice(n));\n },\npastInput:function () {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n },\nupcomingInput:function () {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20-next.length);\n }\n return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\\n/g, \"\");\n },\nshowPosition:function () {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c+\"^\";\n },\nnext:function () {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) this.done = true;\n\n var token,\n match,\n tempMatch,\n index,\n col,\n lines;\n if (!this._more) {\n this.yytext = '';\n this.match = '';\n }\n var rules = this._currentRules();\n for (var i=0;i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (!this.options.flex) break;\n }\n }\n if (match) {\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) this.yylineno += lines.length;\n this.yylloc = {first_line: this.yylloc.last_line,\n last_line: this.yylineno+1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length};\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);\n if (this.done && this._input) this.done = false;\n if (token) return token;\n else return;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\\n'+this.showPosition(),\n {text: \"\", token: null, line: this.yylineno});\n }\n },\nlex:function lex () {\n var r = this.next();\n if (typeof r !== 'undefined') {\n return r;\n } else {\n return this.lex();\n }\n },\nbegin:function begin (condition) {\n this.conditionStack.push(condition);\n },\npopState:function popState () {\n return this.conditionStack.pop();\n },\n_currentRules:function _currentRules () {\n return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;\n },\ntopState:function () {\n return this.conditionStack[this.conditionStack.length-2];\n },\npushState:function begin (condition) {\n this.begin(condition);\n }});\nlexer.options = {};\nlexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START\n) {\n\n\nfunction strip(start, end) {\n return yy_.yytext = yy_.yytext.substring(start, yy_.yyleng - end + start);\n}\n\n\nvar YYSTATE=YY_START\nswitch($avoiding_name_collisions) {\ncase 0:\n if(yy_.yytext.slice(-2) === \"\\\\\\\\\") {\n strip(0,1);\n this.begin(\"mu\");\n } else if(yy_.yytext.slice(-1) === \"\\\\\") {\n strip(0,1);\n this.begin(\"emu\");\n } else {\n this.begin(\"mu\");\n }\n if(yy_.yytext) return 15;\n \nbreak;\ncase 1:return 15;\nbreak;\ncase 2:\n this.popState();\n return 15;\n \nbreak;\ncase 3:this.begin('raw'); return 15;\nbreak;\ncase 4:\n this.popState();\n // Should be using `this.topState()` below, but it currently\n // returns the second top instead of the first top. Opened an\n // issue about it at https://github.com/zaach/jison/issues/291\n if (this.conditionStack[this.conditionStack.length-1] === 'raw') {\n return 15;\n } else {\n strip(5, 9);\n return 'END_RAW_BLOCK';\n }\n \nbreak;\ncase 5: return 15; \nbreak;\ncase 6:\n this.popState();\n return 14;\n\nbreak;\ncase 7:return 65;\nbreak;\ncase 8:return 68;\nbreak;\ncase 9: return 19; \nbreak;\ncase 10:\n this.popState();\n this.begin('raw');\n return 23;\n \nbreak;\ncase 11:return 55;\nbreak;\ncase 12:return 60;\nbreak;\ncase 13:return 29;\nbreak;\ncase 14:return 47;\nbreak;\ncase 15:this.popState(); return 44;\nbreak;\ncase 16:this.popState(); return 44;\nbreak;\ncase 17:return 34;\nbreak;\ncase 18:return 39;\nbreak;\ncase 19:return 51;\nbreak;\ncase 20:return 48;\nbreak;\ncase 21:\n this.unput(yy_.yytext);\n this.popState();\n this.begin('com');\n\nbreak;\ncase 22:\n this.popState();\n return 14;\n\nbreak;\ncase 23:return 48;\nbreak;\ncase 24:return 73;\nbreak;\ncase 25:return 72;\nbreak;\ncase 26:return 72;\nbreak;\ncase 27:return 87;\nbreak;\ncase 28:// ignore whitespace\nbreak;\ncase 29:this.popState(); return 54;\nbreak;\ncase 30:this.popState(); return 33;\nbreak;\ncase 31:yy_.yytext = strip(1,2).replace(/\\\\\"/g,'\"'); return 80;\nbreak;\ncase 32:yy_.yytext = strip(1,2).replace(/\\\\'/g,\"'\"); return 80;\nbreak;\ncase 33:return 85;\nbreak;\ncase 34:return 82;\nbreak;\ncase 35:return 82;\nbreak;\ncase 36:return 83;\nbreak;\ncase 37:return 84;\nbreak;\ncase 38:return 81;\nbreak;\ncase 39:return 75;\nbreak;\ncase 40:return 77;\nbreak;\ncase 41:return 72;\nbreak;\ncase 42:yy_.yytext = yy_.yytext.replace(/\\\\([\\\\\\]])/g,'$1'); return 72;\nbreak;\ncase 43:return 'INVALID';\nbreak;\ncase 44:return 5;\nbreak;\n}\n};\nlexer.rules = [/^(?:[^\\x00]*?(?=(\\{\\{)))/,/^(?:[^\\x00]+)/,/^(?:[^\\x00]{2,}?(?=(\\{\\{|\\\\\\{\\{|\\\\\\\\\\{\\{|$)))/,/^(?:\\{\\{\\{\\{(?=[^\\/]))/,/^(?:\\{\\{\\{\\{\\/[^\\s!\"#%-,\\.\\/;->@\\[-\\^`\\{-~]+(?=[=}\\s\\/.])\\}\\}\\}\\})/,/^(?:[^\\x00]+?(?=(\\{\\{\\{\\{)))/,/^(?:[\\s\\S]*?--(~)?\\}\\})/,/^(?:\\()/,/^(?:\\))/,/^(?:\\{\\{\\{\\{)/,/^(?:\\}\\}\\}\\})/,/^(?:\\{\\{(~)?>)/,/^(?:\\{\\{(~)?#>)/,/^(?:\\{\\{(~)?#\\*?)/,/^(?:\\{\\{(~)?\\/)/,/^(?:\\{\\{(~)?\\^\\s*(~)?\\}\\})/,/^(?:\\{\\{(~)?\\s*else\\s*(~)?\\}\\})/,/^(?:\\{\\{(~)?\\^)/,/^(?:\\{\\{(~)?\\s*else\\b)/,/^(?:\\{\\{(~)?\\{)/,/^(?:\\{\\{(~)?&)/,/^(?:\\{\\{(~)?!--)/,/^(?:\\{\\{(~)?![\\s\\S]*?\\}\\})/,/^(?:\\{\\{(~)?\\*?)/,/^(?:=)/,/^(?:\\.\\.)/,/^(?:\\.(?=([=~}\\s\\/.)|])))/,/^(?:[\\/.])/,/^(?:\\s+)/,/^(?:\\}(~)?\\}\\})/,/^(?:(~)?\\}\\})/,/^(?:\"(\\\\[\"]|[^\"])*\")/,/^(?:'(\\\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\\s)])))/,/^(?:false(?=([~}\\s)])))/,/^(?:undefined(?=([~}\\s)])))/,/^(?:null(?=([~}\\s)])))/,/^(?:-?[0-9]+(?:\\.[0-9]+)?(?=([~}\\s)])))/,/^(?:as\\s+\\|)/,/^(?:\\|)/,/^(?:([^\\s!\"#%-,\\.\\/;->@\\[-\\^`\\{-~]+(?=([=~}\\s\\/.)|]))))/,/^(?:\\[(\\\\\\]|[^\\]])*\\])/,/^(?:.)/,/^(?:$)/];\nlexer.conditions = {\"mu\":{\"rules\":[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],\"inclusive\":false},\"emu\":{\"rules\":[2],\"inclusive\":false},\"com\":{\"rules\":[6],\"inclusive\":false},\"raw\":{\"rules\":[3,4,5],\"inclusive\":false},\"INITIAL\":{\"rules\":[0,1,44],\"inclusive\":true}};\nreturn lexer;})()\nparser.lexer = lexer;\nfunction Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser;\nreturn new Parser;\n})();export default handlebars;\n","import Exception from '../exception';\n\nfunction Visitor() {\n this.parents = [];\n}\n\nVisitor.prototype = {\n constructor: Visitor,\n mutating: false,\n\n // Visits a given value. If mutating, will replace the value if necessary.\n acceptKey: function(node, name) {\n let value = this.accept(node[name]);\n if (this.mutating) {\n // Hacky sanity check: This may have a few false positives for type for the helper\n // methods but will generally do the right thing without a lot of overhead.\n if (value && !Visitor.prototype[value.type]) {\n throw new Exception(\n 'Unexpected node type \"' +\n value.type +\n '\" found when accepting ' +\n name +\n ' on ' +\n node.type\n );\n }\n node[name] = value;\n }\n },\n\n // Performs an accept operation with added sanity check to ensure\n // required keys are not removed.\n acceptRequired: function(node, name) {\n this.acceptKey(node, name);\n\n if (!node[name]) {\n throw new Exception(node.type + ' requires ' + name);\n }\n },\n\n // Traverses a given array. If mutating, empty respnses will be removed\n // for child elements.\n acceptArray: function(array) {\n for (let i = 0, l = array.length; i < l; i++) {\n this.acceptKey(array, i);\n\n if (!array[i]) {\n array.splice(i, 1);\n i--;\n l--;\n }\n }\n },\n\n accept: function(object) {\n if (!object) {\n return;\n }\n\n /* istanbul ignore next: Sanity code */\n if (!this[object.type]) {\n throw new Exception('Unknown type: ' + object.type, object);\n }\n\n if (this.current) {\n this.parents.unshift(this.current);\n }\n this.current = object;\n\n let ret = this[object.type](object);\n\n this.current = this.parents.shift();\n\n if (!this.mutating || ret) {\n return ret;\n } else if (ret !== false) {\n return object;\n }\n },\n\n Program: function(program) {\n this.acceptArray(program.body);\n },\n\n MustacheStatement: visitSubExpression,\n Decorator: visitSubExpression,\n\n BlockStatement: visitBlock,\n DecoratorBlock: visitBlock,\n\n PartialStatement: visitPartial,\n PartialBlockStatement: function(partial) {\n visitPartial.call(this, partial);\n\n this.acceptKey(partial, 'program');\n },\n\n ContentStatement: function(/* content */) {},\n CommentStatement: function(/* comment */) {},\n\n SubExpression: visitSubExpression,\n\n PathExpression: function(/* path */) {},\n\n StringLiteral: function(/* string */) {},\n NumberLiteral: function(/* number */) {},\n BooleanLiteral: function(/* bool */) {},\n UndefinedLiteral: function(/* literal */) {},\n NullLiteral: function(/* literal */) {},\n\n Hash: function(hash) {\n this.acceptArray(hash.pairs);\n },\n HashPair: function(pair) {\n this.acceptRequired(pair, 'value');\n }\n};\n\nfunction visitSubExpression(mustache) {\n this.acceptRequired(mustache, 'path');\n this.acceptArray(mustache.params);\n this.acceptKey(mustache, 'hash');\n}\nfunction visitBlock(block) {\n visitSubExpression.call(this, block);\n\n this.acceptKey(block, 'program');\n this.acceptKey(block, 'inverse');\n}\nfunction visitPartial(partial) {\n this.acceptRequired(partial, 'name');\n this.acceptArray(partial.params);\n this.acceptKey(partial, 'hash');\n}\n\nexport default Visitor;\n","import Visitor from './visitor';\n\nfunction WhitespaceControl(options = {}) {\n this.options = options;\n}\nWhitespaceControl.prototype = new Visitor();\n\nWhitespaceControl.prototype.Program = function(program) {\n const doStandalone = !this.options.ignoreStandalone;\n\n let isRoot = !this.isRootSeen;\n this.isRootSeen = true;\n\n let body = program.body;\n for (let i = 0, l = body.length; i < l; i++) {\n let current = body[i],\n strip = this.accept(current);\n\n if (!strip) {\n continue;\n }\n\n let _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),\n _isNextWhitespace = isNextWhitespace(body, i, isRoot),\n openStandalone = strip.openStandalone && _isPrevWhitespace,\n closeStandalone = strip.closeStandalone && _isNextWhitespace,\n inlineStandalone =\n strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;\n\n if (strip.close) {\n omitRight(body, i, true);\n }\n if (strip.open) {\n omitLeft(body, i, true);\n }\n\n if (doStandalone && inlineStandalone) {\n omitRight(body, i);\n\n if (omitLeft(body, i)) {\n // If we are on a standalone node, save the indent info for partials\n if (current.type === 'PartialStatement') {\n // Pull out the whitespace from the final line\n current.indent = /([ \\t]+$)/.exec(body[i - 1].original)[1];\n }\n }\n }\n if (doStandalone && openStandalone) {\n omitRight((current.program || current.inverse).body);\n\n // Strip out the previous content node if it's whitespace only\n omitLeft(body, i);\n }\n if (doStandalone && closeStandalone) {\n // Always strip the next node\n omitRight(body, i);\n\n omitLeft((current.inverse || current.program).body);\n }\n }\n\n return program;\n};\n\nWhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(\n block\n) {\n this.accept(block.program);\n this.accept(block.inverse);\n\n // Find the inverse program that is involed with whitespace stripping.\n let program = block.program || block.inverse,\n inverse = block.program && block.inverse,\n firstInverse = inverse,\n lastInverse = inverse;\n\n if (inverse && inverse.chained) {\n firstInverse = inverse.body[0].program;\n\n // Walk the inverse chain to find the last inverse that is actually in the chain.\n while (lastInverse.chained) {\n lastInverse = lastInverse.body[lastInverse.body.length - 1].program;\n }\n }\n\n let strip = {\n open: block.openStrip.open,\n close: block.closeStrip.close,\n\n // Determine the standalone candiacy. Basically flag our content as being possibly standalone\n // so our parent can determine if we actually are standalone\n openStandalone: isNextWhitespace(program.body),\n closeStandalone: isPrevWhitespace((firstInverse || program).body)\n };\n\n if (block.openStrip.close) {\n omitRight(program.body, null, true);\n }\n\n if (inverse) {\n let inverseStrip = block.inverseStrip;\n\n if (inverseStrip.open) {\n omitLeft(program.body, null, true);\n }\n\n if (inverseStrip.close) {\n omitRight(firstInverse.body, null, true);\n }\n if (block.closeStrip.open) {\n omitLeft(lastInverse.body, null, true);\n }\n\n // Find standalone else statments\n if (\n !this.options.ignoreStandalone &&\n isPrevWhitespace(program.body) &&\n isNextWhitespace(firstInverse.body)\n ) {\n omitLeft(program.body);\n omitRight(firstInverse.body);\n }\n } else if (block.closeStrip.open) {\n omitLeft(program.body, null, true);\n }\n\n return strip;\n};\n\nWhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(\n mustache\n) {\n return mustache.strip;\n};\n\nWhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(\n node\n) {\n /* istanbul ignore next */\n let strip = node.strip || {};\n return {\n inlineStandalone: true,\n open: strip.open,\n close: strip.close\n };\n};\n\nfunction isPrevWhitespace(body, i, isRoot) {\n if (i === undefined) {\n i = body.length;\n }\n\n // Nodes that end with newlines are considered whitespace (but are special\n // cased for strip operations)\n let prev = body[i - 1],\n sibling = body[i - 2];\n if (!prev) {\n return isRoot;\n }\n\n if (prev.type === 'ContentStatement') {\n return (sibling || !isRoot ? /\\r?\\n\\s*?$/ : /(^|\\r?\\n)\\s*?$/).test(\n prev.original\n );\n }\n}\nfunction isNextWhitespace(body, i, isRoot) {\n if (i === undefined) {\n i = -1;\n }\n\n let next = body[i + 1],\n sibling = body[i + 2];\n if (!next) {\n return isRoot;\n }\n\n if (next.type === 'ContentStatement') {\n return (sibling || !isRoot ? /^\\s*?\\r?\\n/ : /^\\s*?(\\r?\\n|$)/).test(\n next.original\n );\n }\n}\n\n// Marks the node to the right of the position as omitted.\n// I.e. {{foo}}' ' will mark the ' ' node as omitted.\n//\n// If i is undefined, then the first child will be marked as such.\n//\n// If mulitple is truthy then all whitespace will be stripped out until non-whitespace\n// content is met.\nfunction omitRight(body, i, multiple) {\n let current = body[i == null ? 0 : i + 1];\n if (\n !current ||\n current.type !== 'ContentStatement' ||\n (!multiple && current.rightStripped)\n ) {\n return;\n }\n\n let original = current.value;\n current.value = current.value.replace(\n multiple ? /^\\s+/ : /^[ \\t]*\\r?\\n?/,\n ''\n );\n current.rightStripped = current.value !== original;\n}\n\n// Marks the node to the left of the position as omitted.\n// I.e. ' '{{foo}} will mark the ' ' node as omitted.\n//\n// If i is undefined then the last child will be marked as such.\n//\n// If mulitple is truthy then all whitespace will be stripped out until non-whitespace\n// content is met.\nfunction omitLeft(body, i, multiple) {\n let current = body[i == null ? body.length - 1 : i - 1];\n if (\n !current ||\n current.type !== 'ContentStatement' ||\n (!multiple && current.leftStripped)\n ) {\n return;\n }\n\n // We omit the last node if it's whitespace only and not preceded by a non-content node.\n let original = current.value;\n current.value = current.value.replace(multiple ? /\\s+$/ : /[ \\t]+$/, '');\n current.leftStripped = current.value !== original;\n return current.leftStripped;\n}\n\nexport default WhitespaceControl;\n","import Exception from '../exception';\n\nfunction validateClose(open, close) {\n close = close.path ? close.path.original : close;\n\n if (open.path.original !== close) {\n let errorNode = { loc: open.path.loc };\n\n throw new Exception(\n open.path.original + \" doesn't match \" + close,\n errorNode\n );\n }\n}\n\nexport function SourceLocation(source, locInfo) {\n this.source = source;\n this.start = {\n line: locInfo.first_line,\n column: locInfo.first_column\n };\n this.end = {\n line: locInfo.last_line,\n column: locInfo.last_column\n };\n}\n\nexport function id(token) {\n if (/^\\[.*\\]$/.test(token)) {\n return token.substring(1, token.length - 1);\n } else {\n return token;\n }\n}\n\nexport function stripFlags(open, close) {\n return {\n open: open.charAt(2) === '~',\n close: close.charAt(close.length - 3) === '~'\n };\n}\n\nexport function stripComment(comment) {\n return comment.replace(/^\\{\\{~?!-?-?/, '').replace(/-?-?~?\\}\\}$/, '');\n}\n\nexport function preparePath(data, parts, loc) {\n loc = this.locInfo(loc);\n\n let original = data ? '@' : '',\n dig = [],\n depth = 0;\n\n for (let i = 0, l = parts.length; i < l; i++) {\n let part = parts[i].part,\n // If we have [] syntax then we do not treat path references as operators,\n // i.e. foo.[this] resolves to approximately context.foo['this']\n isLiteral = parts[i].original !== part;\n original += (parts[i].separator || '') + part;\n\n if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {\n if (dig.length > 0) {\n throw new Exception('Invalid path: ' + original, { loc });\n } else if (part === '..') {\n depth++;\n }\n } else {\n dig.push(part);\n }\n }\n\n return {\n type: 'PathExpression',\n data,\n depth,\n parts: dig,\n original,\n loc\n };\n}\n\nexport function prepareMustache(path, params, hash, open, strip, locInfo) {\n // Must use charAt to support IE pre-10\n let escapeFlag = open.charAt(3) || open.charAt(2),\n escaped = escapeFlag !== '{' && escapeFlag !== '&';\n\n let decorator = /\\*/.test(open);\n return {\n type: decorator ? 'Decorator' : 'MustacheStatement',\n path,\n params,\n hash,\n escaped,\n strip,\n loc: this.locInfo(locInfo)\n };\n}\n\nexport function prepareRawBlock(openRawBlock, contents, close, locInfo) {\n validateClose(openRawBlock, close);\n\n locInfo = this.locInfo(locInfo);\n let program = {\n type: 'Program',\n body: contents,\n strip: {},\n loc: locInfo\n };\n\n return {\n type: 'BlockStatement',\n path: openRawBlock.path,\n params: openRawBlock.params,\n hash: openRawBlock.hash,\n program,\n openStrip: {},\n inverseStrip: {},\n closeStrip: {},\n loc: locInfo\n };\n}\n\nexport function prepareBlock(\n openBlock,\n program,\n inverseAndProgram,\n close,\n inverted,\n locInfo\n) {\n if (close && close.path) {\n validateClose(openBlock, close);\n }\n\n let decorator = /\\*/.test(openBlock.open);\n\n program.blockParams = openBlock.blockParams;\n\n let inverse, inverseStrip;\n\n if (inverseAndProgram) {\n if (decorator) {\n throw new Exception(\n 'Unexpected inverse block on decorator',\n inverseAndProgram\n );\n }\n\n if (inverseAndProgram.chain) {\n inverseAndProgram.program.body[0].closeStrip = close.strip;\n }\n\n inverseStrip = inverseAndProgram.strip;\n inverse = inverseAndProgram.program;\n }\n\n if (inverted) {\n inverted = inverse;\n inverse = program;\n program = inverted;\n }\n\n return {\n type: decorator ? 'DecoratorBlock' : 'BlockStatement',\n path: openBlock.path,\n params: openBlock.params,\n hash: openBlock.hash,\n program,\n inverse,\n openStrip: openBlock.strip,\n inverseStrip,\n closeStrip: close && close.strip,\n loc: this.locInfo(locInfo)\n };\n}\n\nexport function prepareProgram(statements, loc) {\n if (!loc && statements.length) {\n const firstLoc = statements[0].loc,\n lastLoc = statements[statements.length - 1].loc;\n\n /* istanbul ignore else */\n if (firstLoc && lastLoc) {\n loc = {\n source: firstLoc.source,\n start: {\n line: firstLoc.start.line,\n column: firstLoc.start.column\n },\n end: {\n line: lastLoc.end.line,\n column: lastLoc.end.column\n }\n };\n }\n }\n\n return {\n type: 'Program',\n body: statements,\n strip: {},\n loc: loc\n };\n}\n\nexport function preparePartialBlock(open, program, close, locInfo) {\n validateClose(open, close);\n\n return {\n type: 'PartialBlockStatement',\n name: open.path,\n params: open.params,\n hash: open.hash,\n program,\n openStrip: open.strip,\n closeStrip: close && close.strip,\n loc: this.locInfo(locInfo)\n };\n}\n","import parser from './parser';\nimport WhitespaceControl from './whitespace-control';\nimport * as Helpers from './helpers';\nimport Exception from '../exception';\nimport { extend } from '../utils';\n\nexport { parser };\n\nlet yy = {};\nextend(yy, Helpers);\n\nexport function parseWithoutProcessing(input, options) {\n // Just return if an already-compiled AST was passed in.\n if (input.type === 'Program') {\n // When a pre-parsed AST is passed in, validate all node values to prevent\n // code injection via type-confused literals.\n validateInputAst(input);\n return input;\n }\n\n parser.yy = yy;\n\n // Altering the shared object here, but this is ok as parser is a sync operation\n yy.locInfo = function(locInfo) {\n return new yy.SourceLocation(options && options.srcName, locInfo);\n };\n\n let ast = parser.parse(input);\n\n return ast;\n}\n\nexport function parse(input, options) {\n let ast = parseWithoutProcessing(input, options);\n let strip = new WhitespaceControl(options);\n\n return strip.accept(ast);\n}\n\nfunction validateInputAst(ast) {\n validateAstNode(ast);\n}\n\nfunction validateAstNode(node) {\n if (node == null) {\n return;\n }\n\n if (Array.isArray(node)) {\n node.forEach(validateAstNode);\n return;\n }\n\n if (typeof node !== 'object') {\n return;\n }\n\n if (node.type === 'PathExpression') {\n if (!isValidDepth(node.depth)) {\n throw new Exception(\n 'Invalid AST: PathExpression.depth must be an integer'\n );\n }\n if (!Array.isArray(node.parts)) {\n throw new Exception('Invalid AST: PathExpression.parts must be an array');\n }\n for (let i = 0; i < node.parts.length; i++) {\n if (typeof node.parts[i] !== 'string') {\n throw new Exception(\n 'Invalid AST: PathExpression.parts must only contain strings'\n );\n }\n }\n } else if (node.type === 'NumberLiteral') {\n if (typeof node.value !== 'number' || !isFinite(node.value)) {\n throw new Exception('Invalid AST: NumberLiteral.value must be a number');\n }\n } else if (node.type === 'BooleanLiteral') {\n if (typeof node.value !== 'boolean') {\n throw new Exception(\n 'Invalid AST: BooleanLiteral.value must be a boolean'\n );\n }\n }\n\n Object.keys(node).forEach(propertyName => {\n if (propertyName === 'loc') {\n return;\n }\n validateAstNode(node[propertyName]);\n });\n}\n\nfunction isValidDepth(depth) {\n return (\n typeof depth === 'number' &&\n isFinite(depth) &&\n Math.floor(depth) === depth &&\n depth >= 0\n );\n}\n","/* eslint-disable new-cap */\n\nimport Exception from '../exception';\nimport { isArray, indexOf, extend } from '../utils';\nimport AST from './ast';\n\nconst slice = [].slice;\n\nexport function Compiler() {}\n\n// the foundHelper register will disambiguate helper lookup from finding a\n// function in a context. This is necessary for mustache compatibility, which\n// requires that context functions in blocks are evaluated by blockHelperMissing,\n// and then proceed as if the resulting value was provided to blockHelperMissing.\n\nCompiler.prototype = {\n compiler: Compiler,\n\n equals: function(other) {\n let len = this.opcodes.length;\n if (other.opcodes.length !== len) {\n return false;\n }\n\n for (let i = 0; i < len; i++) {\n let opcode = this.opcodes[i],\n otherOpcode = other.opcodes[i];\n if (\n opcode.opcode !== otherOpcode.opcode ||\n !argEquals(opcode.args, otherOpcode.args)\n ) {\n return false;\n }\n }\n\n // We know that length is the same between the two arrays because they are directly tied\n // to the opcode behavior above.\n len = this.children.length;\n for (let i = 0; i < len; i++) {\n if (!this.children[i].equals(other.children[i])) {\n return false;\n }\n }\n\n return true;\n },\n\n guid: 0,\n\n compile: function(program, options) {\n this.sourceNode = [];\n this.opcodes = [];\n this.children = [];\n this.options = options;\n this.stringParams = options.stringParams;\n this.trackIds = options.trackIds;\n\n options.blockParams = options.blockParams || [];\n\n options.knownHelpers = extend(\n Object.create(null),\n {\n helperMissing: true,\n blockHelperMissing: true,\n each: true,\n if: true,\n unless: true,\n with: true,\n log: true,\n lookup: true\n },\n options.knownHelpers\n );\n\n return this.accept(program);\n },\n\n compileProgram: function(program) {\n let childCompiler = new this.compiler(), // eslint-disable-line new-cap\n result = childCompiler.compile(program, this.options),\n guid = this.guid++;\n\n this.usePartial = this.usePartial || result.usePartial;\n\n this.children[guid] = result;\n this.useDepths = this.useDepths || result.useDepths;\n\n return guid;\n },\n\n accept: function(node) {\n /* istanbul ignore next: Sanity code */\n if (!this[node.type]) {\n throw new Exception('Unknown type: ' + node.type, node);\n }\n\n this.sourceNode.unshift(node);\n let ret = this[node.type](node);\n this.sourceNode.shift();\n return ret;\n },\n\n Program: function(program) {\n this.options.blockParams.unshift(program.blockParams);\n\n let body = program.body,\n bodyLength = body.length;\n for (let i = 0; i < bodyLength; i++) {\n this.accept(body[i]);\n }\n\n this.options.blockParams.shift();\n\n this.isSimple = bodyLength === 1;\n this.blockParams = program.blockParams ? program.blockParams.length : 0;\n\n return this;\n },\n\n BlockStatement: function(block) {\n transformLiteralToPath(block);\n\n let program = block.program,\n inverse = block.inverse;\n\n program = program && this.compileProgram(program);\n inverse = inverse && this.compileProgram(inverse);\n\n let type = this.classifySexpr(block);\n\n if (type === 'helper') {\n this.helperSexpr(block, program, inverse);\n } else if (type === 'simple') {\n this.simpleSexpr(block);\n\n // now that the simple mustache is resolved, we need to\n // evaluate it by executing `blockHelperMissing`\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n this.opcode('emptyHash');\n this.opcode('blockValue', block.path.original);\n } else {\n this.ambiguousSexpr(block, program, inverse);\n\n // now that the simple mustache is resolved, we need to\n // evaluate it by executing `blockHelperMissing`\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n this.opcode('emptyHash');\n this.opcode('ambiguousBlockValue');\n }\n\n this.opcode('append');\n },\n\n DecoratorBlock(decorator) {\n let program = decorator.program && this.compileProgram(decorator.program);\n let params = this.setupFullMustacheParams(decorator, program, undefined),\n path = decorator.path;\n\n this.useDecorators = true;\n this.opcode('registerDecorator', params.length, path.original);\n },\n\n PartialStatement: function(partial) {\n this.usePartial = true;\n\n let program = partial.program;\n if (program) {\n program = this.compileProgram(partial.program);\n }\n\n let params = partial.params;\n if (params.length > 1) {\n throw new Exception(\n 'Unsupported number of partial arguments: ' + params.length,\n partial\n );\n } else if (!params.length) {\n if (this.options.explicitPartialContext) {\n this.opcode('pushLiteral', 'undefined');\n } else {\n params.push({ type: 'PathExpression', parts: [], depth: 0 });\n }\n }\n\n let partialName = partial.name.original,\n isDynamic = partial.name.type === 'SubExpression';\n if (isDynamic) {\n this.accept(partial.name);\n }\n\n this.setupFullMustacheParams(partial, program, undefined, true);\n\n let indent = partial.indent || '';\n if (this.options.preventIndent && indent) {\n this.opcode('appendContent', indent);\n indent = '';\n }\n\n this.opcode('invokePartial', isDynamic, partialName, indent);\n this.opcode('append');\n },\n PartialBlockStatement: function(partialBlock) {\n this.PartialStatement(partialBlock);\n },\n\n MustacheStatement: function(mustache) {\n this.SubExpression(mustache);\n\n if (mustache.escaped && !this.options.noEscape) {\n this.opcode('appendEscaped');\n } else {\n this.opcode('append');\n }\n },\n Decorator(decorator) {\n this.DecoratorBlock(decorator);\n },\n\n ContentStatement: function(content) {\n if (content.value) {\n this.opcode('appendContent', content.value);\n }\n },\n\n CommentStatement: function() {},\n\n SubExpression: function(sexpr) {\n transformLiteralToPath(sexpr);\n let type = this.classifySexpr(sexpr);\n\n if (type === 'simple') {\n this.simpleSexpr(sexpr);\n } else if (type === 'helper') {\n this.helperSexpr(sexpr);\n } else {\n this.ambiguousSexpr(sexpr);\n }\n },\n ambiguousSexpr: function(sexpr, program, inverse) {\n let path = sexpr.path,\n name = path.parts[0],\n isBlock = program != null || inverse != null;\n\n this.opcode('getContext', path.depth);\n\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n\n path.strict = true;\n this.accept(path);\n\n this.opcode('invokeAmbiguous', name, isBlock);\n },\n\n simpleSexpr: function(sexpr) {\n let path = sexpr.path;\n path.strict = true;\n this.accept(path);\n this.opcode('resolvePossibleLambda');\n },\n\n helperSexpr: function(sexpr, program, inverse) {\n let params = this.setupFullMustacheParams(sexpr, program, inverse),\n path = sexpr.path,\n name = path.parts[0];\n\n if (this.options.knownHelpers[name]) {\n this.opcode('invokeKnownHelper', params.length, name);\n } else if (this.options.knownHelpersOnly) {\n throw new Exception(\n 'You specified knownHelpersOnly, but used the unknown helper ' + name,\n sexpr\n );\n } else {\n path.strict = true;\n path.falsy = true;\n\n this.accept(path);\n this.opcode(\n 'invokeHelper',\n params.length,\n path.original,\n AST.helpers.simpleId(path)\n );\n }\n },\n\n PathExpression: function(path) {\n this.addDepth(path.depth);\n this.opcode('getContext', path.depth);\n\n let name = path.parts[0],\n scoped = AST.helpers.scopedId(path),\n blockParamId = !path.depth && !scoped && this.blockParamIndex(name);\n\n if (blockParamId) {\n this.opcode('lookupBlockParam', blockParamId, path.parts);\n } else if (!name) {\n // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`\n this.opcode('pushContext');\n } else if (path.data) {\n this.options.data = true;\n this.opcode('lookupData', path.depth, path.parts, path.strict);\n } else {\n this.opcode(\n 'lookupOnContext',\n path.parts,\n path.falsy,\n path.strict,\n scoped\n );\n }\n },\n\n StringLiteral: function(string) {\n this.opcode('pushString', string.value);\n },\n\n NumberLiteral: function(number) {\n this.opcode('pushLiteral', number.value);\n },\n\n BooleanLiteral: function(bool) {\n this.opcode('pushLiteral', bool.value);\n },\n\n UndefinedLiteral: function() {\n this.opcode('pushLiteral', 'undefined');\n },\n\n NullLiteral: function() {\n this.opcode('pushLiteral', 'null');\n },\n\n Hash: function(hash) {\n let pairs = hash.pairs,\n i = 0,\n l = pairs.length;\n\n this.opcode('pushHash');\n\n for (; i < l; i++) {\n this.pushParam(pairs[i].value);\n }\n while (i--) {\n this.opcode('assignToHash', pairs[i].key);\n }\n this.opcode('popHash');\n },\n\n // HELPERS\n opcode: function(name) {\n this.opcodes.push({\n opcode: name,\n args: slice.call(arguments, 1),\n loc: this.sourceNode[0].loc\n });\n },\n\n addDepth: function(depth) {\n if (!depth) {\n return;\n }\n\n this.useDepths = true;\n },\n\n classifySexpr: function(sexpr) {\n let isSimple = AST.helpers.simpleId(sexpr.path);\n\n let isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);\n\n // a mustache is an eligible helper if:\n // * its id is simple (a single part, not `this` or `..`)\n let isHelper = !isBlockParam && AST.helpers.helperExpression(sexpr);\n\n // if a mustache is an eligible helper but not a definite\n // helper, it is ambiguous, and will be resolved in a later\n // pass or at runtime.\n let isEligible = !isBlockParam && (isHelper || isSimple);\n\n // if ambiguous, we can possibly resolve the ambiguity now\n // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.\n if (isEligible && !isHelper) {\n let name = sexpr.path.parts[0],\n options = this.options;\n if (options.knownHelpers[name]) {\n isHelper = true;\n } else if (options.knownHelpersOnly) {\n isEligible = false;\n }\n }\n\n if (isHelper) {\n return 'helper';\n } else if (isEligible) {\n return 'ambiguous';\n } else {\n return 'simple';\n }\n },\n\n pushParams: function(params) {\n for (let i = 0, l = params.length; i < l; i++) {\n this.pushParam(params[i]);\n }\n },\n\n pushParam: function(val) {\n let value = val.value != null ? val.value : val.original || '';\n\n if (this.stringParams) {\n if (value.replace) {\n value = value.replace(/^(\\.?\\.\\/)*/g, '').replace(/\\//g, '.');\n }\n\n if (val.depth) {\n this.addDepth(val.depth);\n }\n this.opcode('getContext', val.depth || 0);\n this.opcode('pushStringParam', value, val.type);\n\n if (val.type === 'SubExpression') {\n // SubExpressions get evaluated and passed in\n // in string params mode.\n this.accept(val);\n }\n } else {\n if (this.trackIds) {\n let blockParamIndex;\n if (val.parts && !AST.helpers.scopedId(val) && !val.depth) {\n blockParamIndex = this.blockParamIndex(val.parts[0]);\n }\n if (blockParamIndex) {\n let blockParamChild = val.parts.slice(1).join('.');\n this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);\n } else {\n value = val.original || value;\n if (value.replace) {\n value = value\n .replace(/^this(?:\\.|$)/, '')\n .replace(/^\\.\\//, '')\n .replace(/^\\.$/, '');\n }\n\n this.opcode('pushId', val.type, value);\n }\n }\n this.accept(val);\n }\n },\n\n setupFullMustacheParams: function(sexpr, program, inverse, omitEmpty) {\n let params = sexpr.params;\n this.pushParams(params);\n\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n\n if (sexpr.hash) {\n this.accept(sexpr.hash);\n } else {\n this.opcode('emptyHash', omitEmpty);\n }\n\n return params;\n },\n\n blockParamIndex: function(name) {\n for (\n let depth = 0, len = this.options.blockParams.length;\n depth < len;\n depth++\n ) {\n let blockParams = this.options.blockParams[depth],\n param = blockParams && indexOf(blockParams, name);\n if (blockParams && param >= 0) {\n return [depth, param];\n }\n }\n }\n};\n\nexport function precompile(input, options, env) {\n if (\n input == null ||\n (typeof input !== 'string' && input.type !== 'Program')\n ) {\n throw new Exception(\n 'You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' +\n input\n );\n }\n\n options = options || {};\n if (!('data' in options)) {\n options.data = true;\n }\n if (options.compat) {\n options.useDepths = true;\n }\n\n let ast = env.parse(input, options),\n environment = new env.Compiler().compile(ast, options);\n return new env.JavaScriptCompiler().compile(environment, options);\n}\n\nexport function compile(input, options = {}, env) {\n if (\n input == null ||\n (typeof input !== 'string' && input.type !== 'Program')\n ) {\n throw new Exception(\n 'You must pass a string or Handlebars AST to Handlebars.compile. You passed ' +\n input\n );\n }\n\n options = extend({}, options);\n if (!('data' in options)) {\n options.data = true;\n }\n if (options.compat) {\n options.useDepths = true;\n }\n\n let compiled;\n\n function compileInput() {\n let ast = env.parse(input, options),\n environment = new env.Compiler().compile(ast, options),\n templateSpec = new env.JavaScriptCompiler().compile(\n environment,\n options,\n undefined,\n true\n );\n return env.template(templateSpec);\n }\n\n // Template is only compiled on first use and cached after that point.\n function ret(context, execOptions) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled.call(this, context, execOptions);\n }\n ret._setup = function(setupOptions) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled._setup(setupOptions);\n };\n ret._child = function(i, data, blockParams, depths) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled._child(i, data, blockParams, depths);\n };\n return ret;\n}\n\nfunction argEquals(a, b) {\n if (a === b) {\n return true;\n }\n\n if (isArray(a) && isArray(b) && a.length === b.length) {\n for (let i = 0; i < a.length; i++) {\n if (!argEquals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n}\n\nfunction transformLiteralToPath(sexpr) {\n if (!sexpr.path.parts) {\n let literal = sexpr.path;\n // Casting to string here to make false and 0 literal values play nicely with the rest\n // of the system.\n sexpr.path = {\n type: 'PathExpression',\n data: false,\n depth: 0,\n parts: [literal.original + ''],\n original: literal.original + '',\n loc: literal.loc\n };\n }\n}\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '<dir>/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","/* global define, require */\nimport { isArray } from '../utils';\n\nlet SourceNode;\n\ntry {\n /* istanbul ignore next */\n if (typeof define !== 'function' || !define.amd) {\n // We don't support this in AMD environments. For these environments, we assume that\n // they are running on the browser and thus have no need for the source-map library.\n let SourceMap = require('source-map');\n SourceNode = SourceMap.SourceNode;\n }\n} catch (err) {\n /* NOP */\n}\n\n/* istanbul ignore if: tested but not covered in istanbul due to dist build */\nif (!SourceNode) {\n SourceNode = function(line, column, srcFile, chunks) {\n this.src = '';\n if (chunks) {\n this.add(chunks);\n }\n };\n /* istanbul ignore next */\n SourceNode.prototype = {\n add: function(chunks) {\n if (isArray(chunks)) {\n chunks = chunks.join('');\n }\n this.src += chunks;\n },\n prepend: function(chunks) {\n if (isArray(chunks)) {\n chunks = chunks.join('');\n }\n this.src = chunks + this.src;\n },\n toStringWithSourceMap: function() {\n return { code: this.toString() };\n },\n toString: function() {\n return this.src;\n }\n };\n}\n\nfunction castChunk(chunk, codeGen, loc) {\n if (isArray(chunk)) {\n let ret = [];\n\n for (let i = 0, len = chunk.length; i < len; i++) {\n ret.push(codeGen.wrap(chunk[i], loc));\n }\n return ret;\n } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {\n // Handle primitives that the SourceNode will throw up on\n return chunk + '';\n }\n return chunk;\n}\n\nfunction CodeGen(srcFile) {\n this.srcFile = srcFile;\n this.source = [];\n}\n\nCodeGen.prototype = {\n isEmpty() {\n return !this.source.length;\n },\n prepend: function(source, loc) {\n this.source.unshift(this.wrap(source, loc));\n },\n push: function(source, loc) {\n this.source.push(this.wrap(source, loc));\n },\n\n merge: function() {\n let source = this.empty();\n this.each(function(line) {\n source.add([' ', line, '\\n']);\n });\n return source;\n },\n\n each: function(iter) {\n for (let i = 0, len = this.source.length; i < len; i++) {\n iter(this.source[i]);\n }\n },\n\n empty: function() {\n let loc = this.currentLocation || { start: {} };\n return new SourceNode(loc.start.line, loc.start.column, this.srcFile);\n },\n wrap: function(chunk, loc = this.currentLocation || { start: {} }) {\n if (chunk instanceof SourceNode) {\n return chunk;\n }\n\n chunk = castChunk(chunk, this, loc);\n\n return new SourceNode(\n loc.start.line,\n loc.start.column,\n this.srcFile,\n chunk\n );\n },\n\n functionCall: function(fn, type, params) {\n params = this.generateList(params);\n return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);\n },\n\n quotedString: function(str) {\n return (\n '\"' +\n (str + '')\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\u2028/g, '\\\\u2028') // Per Ecma-262 7.3 + 7.8.4\n .replace(/\\u2029/g, '\\\\u2029') +\n '\"'\n );\n },\n\n objectLiteral: function(obj) {\n let pairs = [];\n\n Object.keys(obj).forEach(key => {\n let value = castChunk(obj[key], this);\n if (value !== 'undefined') {\n pairs.push([this.quotedString(key), ':', value]);\n }\n });\n\n let ret = this.generateList(pairs);\n ret.prepend('{');\n ret.add('}');\n return ret;\n },\n\n generateList: function(entries) {\n let ret = this.empty();\n\n for (let i = 0, len = entries.length; i < len; i++) {\n if (i) {\n ret.add(',');\n }\n\n ret.add(castChunk(entries[i], this));\n }\n\n return ret;\n },\n\n generateArray: function(entries) {\n let ret = this.generateList(entries);\n ret.prepend('[');\n ret.add(']');\n\n return ret;\n }\n};\n\nexport default CodeGen;\n","import { COMPILER_REVISION, REVISION_CHANGES } from '../base';\nimport Exception from '../exception';\nimport { isArray } from '../utils';\nimport CodeGen from './code-gen';\n\nfunction Literal(value) {\n this.value = value;\n}\n\nfunction JavaScriptCompiler() {}\n\nJavaScriptCompiler.prototype = {\n // PUBLIC API: You can override these methods in a subclass to provide\n // alternative compiled forms for name lookup and buffering semantics\n nameLookup: function(parent, name /*, type */) {\n return this.internalNameLookup(parent, name);\n },\n depthedLookup: function(name) {\n return [\n this.aliasable('container.lookup'),\n '(depths, ',\n JSON.stringify(name),\n ')'\n ];\n },\n\n compilerInfo: function() {\n const revision = COMPILER_REVISION,\n versions = REVISION_CHANGES[revision];\n return [revision, versions];\n },\n\n appendToBuffer: function(source, location, explicit) {\n // Force a source as this simplifies the merge logic.\n if (!isArray(source)) {\n source = [source];\n }\n source = this.source.wrap(source, location);\n\n if (this.environment.isSimple) {\n return ['return ', source, ';'];\n } else if (explicit) {\n // This is a case where the buffer operation occurs as a child of another\n // construct, generally braces. We have to explicitly output these buffer\n // operations to ensure that the emitted code goes in the correct location.\n return ['buffer += ', source, ';'];\n } else {\n source.appendToBuffer = true;\n return source;\n }\n },\n\n initializeBuffer: function() {\n return this.quotedString('');\n },\n // END PUBLIC API\n internalNameLookup: function(parent, name) {\n this.lookupPropertyFunctionIsUsed = true;\n return ['lookupProperty(', parent, ',', JSON.stringify(name), ')'];\n },\n\n lookupPropertyFunctionIsUsed: false,\n\n compile: function(environment, options, context, asObject) {\n this.environment = environment;\n this.options = options;\n this.stringParams = this.options.stringParams;\n this.trackIds = this.options.trackIds;\n this.precompile = !asObject;\n\n this.name = this.environment.name;\n this.isChild = !!context;\n this.context = context || {\n decorators: [],\n programs: [],\n environments: []\n };\n\n this.preamble();\n\n this.stackSlot = 0;\n this.stackVars = [];\n this.aliases = {};\n this.registers = { list: [] };\n this.hashes = [];\n this.compileStack = [];\n this.inlineStack = [];\n this.blockParams = [];\n\n this.compileChildren(environment, options);\n\n this.useDepths =\n this.useDepths ||\n environment.useDepths ||\n environment.useDecorators ||\n this.options.compat;\n this.useBlockParams = this.useBlockParams || environment.useBlockParams;\n\n let opcodes = environment.opcodes,\n opcode,\n firstLoc,\n i,\n l;\n\n for (i = 0, l = opcodes.length; i < l; i++) {\n opcode = opcodes[i];\n\n this.source.currentLocation = opcode.loc;\n firstLoc = firstLoc || opcode.loc;\n this[opcode.opcode].apply(this, opcode.args);\n }\n\n // Flush any trailing content that might be pending.\n this.source.currentLocation = firstLoc;\n this.pushSource('');\n\n /* istanbul ignore next */\n if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {\n throw new Exception('Compile completed with content left on stack');\n }\n\n if (!this.decorators.isEmpty()) {\n this.useDecorators = true;\n\n this.decorators.prepend([\n 'var decorators = container.decorators, ',\n this.lookupPropertyFunctionVarDeclaration(),\n ';\\n'\n ]);\n this.decorators.push('return fn;');\n\n if (asObject) {\n this.decorators = Function.apply(this, [\n 'fn',\n 'props',\n 'container',\n 'depth0',\n 'data',\n 'blockParams',\n 'depths',\n this.decorators.merge()\n ]);\n } else {\n this.decorators.prepend(\n 'function(fn, props, container, depth0, data, blockParams, depths) {\\n'\n );\n this.decorators.push('}\\n');\n this.decorators = this.decorators.merge();\n }\n } else {\n this.decorators = undefined;\n }\n\n let fn = this.createFunctionContext(asObject);\n if (!this.isChild) {\n let ret = {\n compiler: this.compilerInfo(),\n main: fn\n };\n\n if (this.decorators) {\n ret.main_d = this.decorators; // eslint-disable-line camelcase\n ret.useDecorators = true;\n }\n\n let { programs, decorators } = this.context;\n for (i = 0, l = programs.length; i < l; i++) {\n ret[i] = programs[i];\n if (decorators[i]) {\n ret[i + '_d'] = decorators[i];\n ret.useDecorators = true;\n }\n }\n\n if (this.environment.usePartial) {\n ret.usePartial = true;\n }\n if (this.options.data) {\n ret.useData = true;\n }\n if (this.useDepths) {\n ret.useDepths = true;\n }\n if (this.useBlockParams) {\n ret.useBlockParams = true;\n }\n if (this.options.compat) {\n ret.compat = true;\n }\n\n if (!asObject) {\n ret.compiler = JSON.stringify(ret.compiler);\n\n this.source.currentLocation = { start: { line: 1, column: 0 } };\n ret = this.objectLiteral(ret);\n\n if (options.srcName) {\n ret = ret.toStringWithSourceMap({ file: options.destName });\n ret.map = ret.map && ret.map.toString();\n } else {\n ret = ret.toString();\n }\n } else {\n ret.compilerOptions = this.options;\n }\n\n return ret;\n } else {\n return fn;\n }\n },\n\n preamble: function() {\n // track the last context pushed into place to allow skipping the\n // getContext opcode when it would be a noop\n this.lastContext = 0;\n this.source = new CodeGen(this.options.srcName);\n this.decorators = new CodeGen(this.options.srcName);\n },\n\n createFunctionContext: function(asObject) {\n let varDeclarations = '';\n\n let locals = this.stackVars.concat(this.registers.list);\n if (locals.length > 0) {\n varDeclarations += ', ' + locals.join(', ');\n }\n\n // Generate minimizer alias mappings\n //\n // When using true SourceNodes, this will update all references to the given alias\n // as the source nodes are reused in situ. For the non-source node compilation mode,\n // aliases will not be used, but this case is already being run on the client and\n // we aren't concern about minimizing the template size.\n let aliasCount = 0;\n Object.keys(this.aliases).forEach(alias => {\n let node = this.aliases[alias];\n if (node.children && node.referenceCount > 1) {\n varDeclarations += ', alias' + ++aliasCount + '=' + alias;\n node.children[0] = 'alias' + aliasCount;\n }\n });\n\n if (this.lookupPropertyFunctionIsUsed) {\n varDeclarations += ', ' + this.lookupPropertyFunctionVarDeclaration();\n }\n\n let params = ['container', 'depth0', 'helpers', 'partials', 'data'];\n\n if (this.useBlockParams || this.useDepths) {\n params.push('blockParams');\n }\n if (this.useDepths) {\n params.push('depths');\n }\n\n // Perform a second pass over the output to merge content when possible\n let source = this.mergeSource(varDeclarations);\n\n if (asObject) {\n params.push(source);\n\n return Function.apply(this, params);\n } else {\n return this.source.wrap([\n 'function(',\n params.join(','),\n ') {\\n ',\n source,\n '}'\n ]);\n }\n },\n mergeSource: function(varDeclarations) {\n let isSimple = this.environment.isSimple,\n appendOnly = !this.forceBuffer,\n appendFirst,\n sourceSeen,\n bufferStart,\n bufferEnd;\n this.source.each(line => {\n if (line.appendToBuffer) {\n if (bufferStart) {\n line.prepend(' + ');\n } else {\n bufferStart = line;\n }\n bufferEnd = line;\n } else {\n if (bufferStart) {\n if (!sourceSeen) {\n appendFirst = true;\n } else {\n bufferStart.prepend('buffer += ');\n }\n bufferEnd.add(';');\n bufferStart = bufferEnd = undefined;\n }\n\n sourceSeen = true;\n if (!isSimple) {\n appendOnly = false;\n }\n }\n });\n\n if (appendOnly) {\n if (bufferStart) {\n bufferStart.prepend('return ');\n bufferEnd.add(';');\n } else if (!sourceSeen) {\n this.source.push('return \"\";');\n }\n } else {\n varDeclarations +=\n ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());\n\n if (bufferStart) {\n bufferStart.prepend('return buffer + ');\n bufferEnd.add(';');\n } else {\n this.source.push('return buffer;');\n }\n }\n\n if (varDeclarations) {\n this.source.prepend(\n 'var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\\n')\n );\n }\n\n return this.source.merge();\n },\n\n lookupPropertyFunctionVarDeclaration: function() {\n return `\n lookupProperty = container.lookupProperty || function(parent, propertyName) {\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return parent[propertyName];\n }\n return undefined\n }\n `.trim();\n },\n\n // [blockValue]\n //\n // On stack, before: hash, inverse, program, value\n // On stack, after: return value of blockHelperMissing\n //\n // The purpose of this opcode is to take a block of the form\n // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and\n // replace it on the stack with the result of properly\n // invoking blockHelperMissing.\n blockValue: function(name) {\n let blockHelperMissing = this.aliasable(\n 'container.hooks.blockHelperMissing'\n ),\n params = [this.contextName(0)];\n this.setupHelperArgs(name, 0, params);\n\n let blockName = this.popStack();\n params.splice(1, 0, blockName);\n\n this.push(this.source.functionCall(blockHelperMissing, 'call', params));\n },\n\n // [ambiguousBlockValue]\n //\n // On stack, before: hash, inverse, program, value\n // Compiler value, before: lastHelper=value of last found helper, if any\n // On stack, after, if no lastHelper: same as [blockValue]\n // On stack, after, if lastHelper: value\n ambiguousBlockValue: function() {\n // We're being a bit cheeky and reusing the options value from the prior exec\n let blockHelperMissing = this.aliasable(\n 'container.hooks.blockHelperMissing'\n ),\n params = [this.contextName(0)];\n this.setupHelperArgs('', 0, params, true);\n\n this.flushInline();\n\n let current = this.topStack();\n params.splice(1, 0, current);\n\n this.pushSource([\n 'if (!',\n this.lastHelper,\n ') { ',\n current,\n ' = ',\n this.source.functionCall(blockHelperMissing, 'call', params),\n '}'\n ]);\n },\n\n // [appendContent]\n //\n // On stack, before: ...\n // On stack, after: ...\n //\n // Appends the string value of `content` to the current buffer\n appendContent: function(content) {\n if (this.pendingContent) {\n content = this.pendingContent + content;\n } else {\n this.pendingLocation = this.source.currentLocation;\n }\n\n this.pendingContent = content;\n },\n\n // [append]\n //\n // On stack, before: value, ...\n // On stack, after: ...\n //\n // Coerces `value` to a String and appends it to the current buffer.\n //\n // If `value` is truthy, or 0, it is coerced into a string and appended\n // Otherwise, the empty string is appended\n append: function() {\n if (this.isInline()) {\n this.replaceStack(current => [' != null ? ', current, ' : \"\"']);\n\n this.pushSource(this.appendToBuffer(this.popStack()));\n } else {\n let local = this.popStack();\n this.pushSource([\n 'if (',\n local,\n ' != null) { ',\n this.appendToBuffer(local, undefined, true),\n ' }'\n ]);\n if (this.environment.isSimple) {\n this.pushSource([\n 'else { ',\n this.appendToBuffer(\"''\", undefined, true),\n ' }'\n ]);\n }\n }\n },\n\n // [appendEscaped]\n //\n // On stack, before: value, ...\n // On stack, after: ...\n //\n // Escape `value` and append it to the buffer\n appendEscaped: function() {\n this.pushSource(\n this.appendToBuffer([\n this.aliasable('container.escapeExpression'),\n '(',\n this.popStack(),\n ')'\n ])\n );\n },\n\n // [getContext]\n //\n // On stack, before: ...\n // On stack, after: ...\n // Compiler value, after: lastContext=depth\n //\n // Set the value of the `lastContext` compiler value to the depth\n getContext: function(depth) {\n this.lastContext = depth;\n },\n\n // [pushContext]\n //\n // On stack, before: ...\n // On stack, after: currentContext, ...\n //\n // Pushes the value of the current context onto the stack.\n pushContext: function() {\n this.pushStackLiteral(this.contextName(this.lastContext));\n },\n\n // [lookupOnContext]\n //\n // On stack, before: ...\n // On stack, after: currentContext[name], ...\n //\n // Looks up the value of `name` on the current context and pushes\n // it onto the stack.\n lookupOnContext: function(parts, falsy, strict, scoped) {\n let i = 0;\n\n if (!scoped && this.options.compat && !this.lastContext) {\n // The depthed query is expected to handle the undefined logic for the root level that\n // is implemented below, so we evaluate that directly in compat mode\n this.push(this.depthedLookup(parts[i++]));\n } else {\n this.pushContext();\n }\n\n this.resolvePath('context', parts, i, falsy, strict);\n },\n\n // [lookupBlockParam]\n //\n // On stack, before: ...\n // On stack, after: blockParam[name], ...\n //\n // Looks up the value of `parts` on the given block param and pushes\n // it onto the stack.\n lookupBlockParam: function(blockParamId, parts) {\n this.useBlockParams = true;\n\n this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);\n this.resolvePath('context', parts, 1);\n },\n\n // [lookupData]\n //\n // On stack, before: ...\n // On stack, after: data, ...\n //\n // Push the data lookup operator\n lookupData: function(depth, parts, strict) {\n if (!depth) {\n this.pushStackLiteral('data');\n } else {\n this.pushStackLiteral('container.data(data, ' + depth + ')');\n }\n\n this.resolvePath('data', parts, 0, true, strict);\n },\n\n resolvePath: function(type, parts, startPartIndex, falsy, strict) {\n if (this.options.strict || this.options.assumeObjects) {\n this.push(\n strictLookup(\n this.options.strict && strict,\n this,\n parts,\n startPartIndex,\n type\n )\n );\n return;\n }\n\n let len = parts.length;\n for (let i = startPartIndex; i < len; i++) {\n /* eslint-disable no-loop-func */\n this.replaceStack(current => {\n let lookup = this.nameLookup(current, parts[i], type);\n // We want to ensure that zero and false are handled properly if the context (falsy flag)\n // needs to have the special handling for these values.\n if (!falsy) {\n return [' != null ? ', lookup, ' : ', current];\n } else {\n // Otherwise we can use generic falsy handling\n return [' && ', lookup];\n }\n });\n /* eslint-enable no-loop-func */\n }\n },\n\n // [resolvePossibleLambda]\n //\n // On stack, before: value, ...\n // On stack, after: resolved value, ...\n //\n // If the `value` is a lambda, replace it on the stack by\n // the return value of the lambda\n resolvePossibleLambda: function() {\n this.push([\n this.aliasable('container.lambda'),\n '(',\n this.popStack(),\n ', ',\n this.contextName(0),\n ')'\n ]);\n },\n\n // [pushStringParam]\n //\n // On stack, before: ...\n // On stack, after: string, currentContext, ...\n //\n // This opcode is designed for use in string mode, which\n // provides the string value of a parameter along with its\n // depth rather than resolving it immediately.\n pushStringParam: function(string, type) {\n this.pushContext();\n this.pushString(type);\n\n // If it's a subexpression, the string result\n // will be pushed after this opcode.\n if (type !== 'SubExpression') {\n if (typeof string === 'string') {\n this.pushString(string);\n } else {\n this.pushStackLiteral(string);\n }\n }\n },\n\n emptyHash: function(omitEmpty) {\n if (this.trackIds) {\n this.push('{}'); // hashIds\n }\n if (this.stringParams) {\n this.push('{}'); // hashContexts\n this.push('{}'); // hashTypes\n }\n this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');\n },\n pushHash: function() {\n if (this.hash) {\n this.hashes.push(this.hash);\n }\n this.hash = { values: {}, types: [], contexts: [], ids: [] };\n },\n popHash: function() {\n let hash = this.hash;\n this.hash = this.hashes.pop();\n\n if (this.trackIds) {\n this.push(this.objectLiteral(hash.ids));\n }\n if (this.stringParams) {\n this.push(this.objectLiteral(hash.contexts));\n this.push(this.objectLiteral(hash.types));\n }\n\n this.push(this.objectLiteral(hash.values));\n },\n\n // [pushString]\n //\n // On stack, before: ...\n // On stack, after: quotedString(string), ...\n //\n // Push a quoted version of `string` onto the stack\n pushString: function(string) {\n this.pushStackLiteral(this.quotedString(string));\n },\n\n // [pushLiteral]\n //\n // On stack, before: ...\n // On stack, after: value, ...\n //\n // Pushes a value onto the stack. This operation prevents\n // the compiler from creating a temporary variable to hold\n // it.\n pushLiteral: function(value) {\n this.pushStackLiteral(value);\n },\n\n // [pushProgram]\n //\n // On stack, before: ...\n // On stack, after: program(guid), ...\n //\n // Push a program expression onto the stack. This takes\n // a compile-time guid and converts it into a runtime-accessible\n // expression.\n pushProgram: function(guid) {\n if (guid != null) {\n this.pushStackLiteral(this.programExpression(guid));\n } else {\n this.pushStackLiteral(null);\n }\n },\n\n // [registerDecorator]\n //\n // On stack, before: hash, program, params..., ...\n // On stack, after: ...\n //\n // Pops off the decorator's parameters, invokes the decorator,\n // and inserts the decorator into the decorators list.\n registerDecorator(paramSize, name) {\n let foundDecorator = this.nameLookup('decorators', name, 'decorator'),\n options = this.setupHelperArgs(name, paramSize);\n\n // Store the resolved decorator in a variable and verify it is a function before\n // calling it. Without this, unregistered decorators can cause an unhandled TypeError\n // (calling undefined), which crashes the process — enabling Denial of Service.\n this.decorators.push(['var decorator = ', foundDecorator, ';']);\n this.decorators.push([\n 'if (typeof decorator !== \"function\") { throw new Error(',\n this.quotedString('Missing decorator: \"' + name + '\"'),\n '); }'\n ]);\n this.decorators.push([\n 'fn = ',\n this.decorators.functionCall('decorator', '', [\n 'fn',\n 'props',\n 'container',\n options\n ]),\n ' || fn;'\n ]);\n },\n\n // [invokeHelper]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of helper invocation\n //\n // Pops off the helper's parameters, invokes the helper,\n // and pushes the helper's return value onto the stack.\n //\n // If the helper is not found, `helperMissing` is called.\n invokeHelper: function(paramSize, name, isSimple) {\n let nonHelper = this.popStack(),\n helper = this.setupHelper(paramSize, name);\n\n let possibleFunctionCalls = [];\n\n if (isSimple) {\n // direct call to helper\n possibleFunctionCalls.push(helper.name);\n }\n // call a function from the input object\n possibleFunctionCalls.push(nonHelper);\n if (!this.options.strict) {\n possibleFunctionCalls.push(\n this.aliasable('container.hooks.helperMissing')\n );\n }\n\n let functionLookupCode = [\n '(',\n this.itemsSeparatedBy(possibleFunctionCalls, '||'),\n ')'\n ];\n let functionCall = this.source.functionCall(\n functionLookupCode,\n 'call',\n helper.callParams\n );\n this.push(functionCall);\n },\n\n itemsSeparatedBy: function(items, separator) {\n let result = [];\n result.push(items[0]);\n for (let i = 1; i < items.length; i++) {\n result.push(separator, items[i]);\n }\n return result;\n },\n // [invokeKnownHelper]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of helper invocation\n //\n // This operation is used when the helper is known to exist,\n // so a `helperMissing` fallback is not required.\n invokeKnownHelper: function(paramSize, name) {\n let helper = this.setupHelper(paramSize, name);\n this.push(this.source.functionCall(helper.name, 'call', helper.callParams));\n },\n\n // [invokeAmbiguous]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of disambiguation\n //\n // This operation is used when an expression like `{{foo}}`\n // is provided, but we don't know at compile-time whether it\n // is a helper or a path.\n //\n // This operation emits more code than the other options,\n // and can be avoided by passing the `knownHelpers` and\n // `knownHelpersOnly` flags at compile-time.\n invokeAmbiguous: function(name, helperCall) {\n this.useRegister('helper');\n\n let nonHelper = this.popStack();\n\n this.emptyHash();\n let helper = this.setupHelper(0, name, helperCall);\n\n let helperName = (this.lastHelper = this.nameLookup(\n 'helpers',\n name,\n 'helper'\n ));\n\n let lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];\n if (!this.options.strict) {\n lookup[0] = '(helper = ';\n lookup.push(\n ' != null ? helper : ',\n this.aliasable('container.hooks.helperMissing')\n );\n }\n\n this.push([\n '(',\n lookup,\n helper.paramsInit ? ['),(', helper.paramsInit] : [],\n '),',\n '(typeof helper === ',\n this.aliasable('\"function\"'),\n ' ? ',\n this.source.functionCall('helper', 'call', helper.callParams),\n ' : helper))'\n ]);\n },\n\n // [invokePartial]\n //\n // On stack, before: context, ...\n // On stack after: result of partial invocation\n //\n // This operation pops off a context, invokes a partial with that context,\n // and pushes the result of the invocation back.\n invokePartial: function(isDynamic, name, indent) {\n let params = [],\n options = this.setupParams(name, 1, params);\n\n if (isDynamic) {\n name = this.popStack();\n delete options.name;\n }\n\n if (indent) {\n options.indent = JSON.stringify(indent);\n }\n options.helpers = 'helpers';\n options.partials = 'partials';\n options.decorators = 'container.decorators';\n\n if (!isDynamic) {\n params.unshift(this.nameLookup('partials', name, 'partial'));\n } else {\n params.unshift(name);\n }\n\n if (this.options.compat) {\n options.depths = 'depths';\n }\n options = this.objectLiteral(options);\n params.push(options);\n\n this.push(this.source.functionCall('container.invokePartial', '', params));\n },\n\n // [assignToHash]\n //\n // On stack, before: value, ..., hash, ...\n // On stack, after: ..., hash, ...\n //\n // Pops a value off the stack and assigns it to the current hash\n assignToHash: function(key) {\n let value = this.popStack(),\n context,\n type,\n id;\n\n if (this.trackIds) {\n id = this.popStack();\n }\n if (this.stringParams) {\n type = this.popStack();\n context = this.popStack();\n }\n\n let hash = this.hash;\n if (context) {\n hash.contexts[key] = context;\n }\n if (type) {\n hash.types[key] = type;\n }\n if (id) {\n hash.ids[key] = id;\n }\n hash.values[key] = value;\n },\n\n pushId: function(type, name, child) {\n if (type === 'BlockParam') {\n this.pushStackLiteral(\n 'blockParams[' +\n name[0] +\n '].path[' +\n name[1] +\n ']' +\n (child ? ' + ' + JSON.stringify('.' + child) : '')\n );\n } else if (type === 'PathExpression') {\n this.pushString(name);\n } else if (type === 'SubExpression') {\n this.pushStackLiteral('true');\n } else {\n this.pushStackLiteral('null');\n }\n },\n\n // HELPERS\n\n compiler: JavaScriptCompiler,\n\n compileChildren: function(environment, options) {\n let children = environment.children,\n child,\n compiler;\n\n for (let i = 0, l = children.length; i < l; i++) {\n child = children[i];\n compiler = new this.compiler(); // eslint-disable-line new-cap\n\n let existing = this.matchExistingProgram(child);\n\n if (existing == null) {\n // Placeholder to prevent name conflicts for nested children\n let index = this.context.programs.push('') - 1;\n child.index = index;\n child.name = 'program' + index;\n this.context.programs[index] = compiler.compile(\n child,\n options,\n this.context,\n !this.precompile\n );\n this.context.decorators[index] = compiler.decorators;\n this.context.environments[index] = child;\n\n this.useDepths = this.useDepths || compiler.useDepths;\n this.useBlockParams = this.useBlockParams || compiler.useBlockParams;\n child.useDepths = this.useDepths;\n child.useBlockParams = this.useBlockParams;\n } else {\n child.index = existing.index;\n child.name = 'program' + existing.index;\n\n this.useDepths = this.useDepths || existing.useDepths;\n this.useBlockParams = this.useBlockParams || existing.useBlockParams;\n }\n }\n },\n matchExistingProgram: function(child) {\n for (let i = 0, len = this.context.environments.length; i < len; i++) {\n let environment = this.context.environments[i];\n if (environment && environment.equals(child)) {\n return environment;\n }\n }\n },\n\n programExpression: function(guid) {\n let child = this.environment.children[guid],\n programParams = [child.index, 'data', child.blockParams];\n\n if (this.useBlockParams || this.useDepths) {\n programParams.push('blockParams');\n }\n if (this.useDepths) {\n programParams.push('depths');\n }\n\n return 'container.program(' + programParams.join(', ') + ')';\n },\n\n useRegister: function(name) {\n if (!this.registers[name]) {\n this.registers[name] = true;\n this.registers.list.push(name);\n }\n },\n\n push: function(expr) {\n if (!(expr instanceof Literal)) {\n expr = this.source.wrap(expr);\n }\n\n this.inlineStack.push(expr);\n return expr;\n },\n\n pushStackLiteral: function(item) {\n this.push(new Literal(item));\n },\n\n pushSource: function(source) {\n if (this.pendingContent) {\n this.source.push(\n this.appendToBuffer(\n this.source.quotedString(this.pendingContent),\n this.pendingLocation\n )\n );\n this.pendingContent = undefined;\n }\n\n if (source) {\n this.source.push(source);\n }\n },\n\n replaceStack: function(callback) {\n let prefix = ['('],\n stack,\n createdStack,\n usedLiteral;\n\n /* istanbul ignore next */\n if (!this.isInline()) {\n throw new Exception('replaceStack on non-inline');\n }\n\n // We want to merge the inline statement into the replacement statement via ','\n let top = this.popStack(true);\n\n if (top instanceof Literal) {\n // Literals do not need to be inlined\n stack = [top.value];\n prefix = ['(', stack];\n usedLiteral = true;\n } else {\n // Get or create the current stack name for use by the inline\n createdStack = true;\n let name = this.incrStack();\n\n prefix = ['((', this.push(name), ' = ', top, ')'];\n stack = this.topStack();\n }\n\n let item = callback.call(this, stack);\n\n if (!usedLiteral) {\n this.popStack();\n }\n if (createdStack) {\n this.stackSlot--;\n }\n this.push(prefix.concat(item, ')'));\n },\n\n incrStack: function() {\n this.stackSlot++;\n if (this.stackSlot > this.stackVars.length) {\n this.stackVars.push('stack' + this.stackSlot);\n }\n return this.topStackName();\n },\n topStackName: function() {\n return 'stack' + this.stackSlot;\n },\n flushInline: function() {\n let inlineStack = this.inlineStack;\n this.inlineStack = [];\n for (let i = 0, len = inlineStack.length; i < len; i++) {\n let entry = inlineStack[i];\n /* istanbul ignore if */\n if (entry instanceof Literal) {\n this.compileStack.push(entry);\n } else {\n let stack = this.incrStack();\n this.pushSource([stack, ' = ', entry, ';']);\n this.compileStack.push(stack);\n }\n }\n },\n isInline: function() {\n return this.inlineStack.length;\n },\n\n popStack: function(wrapped) {\n let inline = this.isInline(),\n item = (inline ? this.inlineStack : this.compileStack).pop();\n\n if (!wrapped && item instanceof Literal) {\n return item.value;\n } else {\n if (!inline) {\n /* istanbul ignore next */\n if (!this.stackSlot) {\n throw new Exception('Invalid stack pop');\n }\n this.stackSlot--;\n }\n return item;\n }\n },\n\n topStack: function() {\n let stack = this.isInline() ? this.inlineStack : this.compileStack,\n item = stack[stack.length - 1];\n\n /* istanbul ignore if */\n if (item instanceof Literal) {\n return item.value;\n } else {\n return item;\n }\n },\n\n contextName: function(context) {\n if (this.useDepths && context) {\n return 'depths[' + context + ']';\n } else {\n return 'depth' + context;\n }\n },\n\n quotedString: function(str) {\n return this.source.quotedString(str);\n },\n\n objectLiteral: function(obj) {\n return this.source.objectLiteral(obj);\n },\n\n aliasable: function(name) {\n let ret = this.aliases[name];\n if (ret) {\n ret.referenceCount++;\n return ret;\n }\n\n ret = this.aliases[name] = this.source.wrap(name);\n ret.aliasable = true;\n ret.referenceCount = 1;\n\n return ret;\n },\n\n setupHelper: function(paramSize, name, blockHelper) {\n let params = [],\n paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);\n let foundHelper = this.nameLookup('helpers', name, 'helper'),\n callContext = this.aliasable(\n `${this.contextName(0)} != null ? ${this.contextName(\n 0\n )} : (container.nullContext || {})`\n );\n\n return {\n params: params,\n paramsInit: paramsInit,\n name: foundHelper,\n callParams: [callContext].concat(params)\n };\n },\n\n setupParams: function(helper, paramSize, params) {\n let options = {},\n contexts = [],\n types = [],\n ids = [],\n objectArgs = !params,\n param;\n\n if (objectArgs) {\n params = [];\n }\n\n options.name = this.quotedString(helper);\n options.hash = this.popStack();\n\n if (this.trackIds) {\n options.hashIds = this.popStack();\n }\n if (this.stringParams) {\n options.hashTypes = this.popStack();\n options.hashContexts = this.popStack();\n }\n\n let inverse = this.popStack(),\n program = this.popStack();\n\n // Avoid setting fn and inverse if neither are set. This allows\n // helpers to do a check for `if (options.fn)`\n if (program || inverse) {\n options.fn = program || 'container.noop';\n options.inverse = inverse || 'container.noop';\n }\n\n // The parameters go on to the stack in order (making sure that they are evaluated in order)\n // so we need to pop them off the stack in reverse order\n let i = paramSize;\n while (i--) {\n param = this.popStack();\n params[i] = param;\n\n if (this.trackIds) {\n ids[i] = this.popStack();\n }\n if (this.stringParams) {\n types[i] = this.popStack();\n contexts[i] = this.popStack();\n }\n }\n\n if (objectArgs) {\n options.args = this.source.generateArray(params);\n }\n\n if (this.trackIds) {\n options.ids = this.source.generateArray(ids);\n }\n if (this.stringParams) {\n options.types = this.source.generateArray(types);\n options.contexts = this.source.generateArray(contexts);\n }\n\n if (this.options.data) {\n options.data = 'data';\n }\n if (this.useBlockParams) {\n options.blockParams = 'blockParams';\n }\n return options;\n },\n\n setupHelperArgs: function(helper, paramSize, params, useRegister) {\n let options = this.setupParams(helper, paramSize, params);\n options.loc = JSON.stringify(this.source.currentLocation);\n options = this.objectLiteral(options);\n if (useRegister) {\n this.useRegister('options');\n params.push('options');\n return ['options=', options];\n } else if (params) {\n params.push(options);\n return '';\n } else {\n return options;\n }\n }\n};\n\n(function() {\n const reservedWords = (\n 'break else new var' +\n ' case finally return void' +\n ' catch for switch while' +\n ' continue function this with' +\n ' default if throw' +\n ' delete in try' +\n ' do instanceof typeof' +\n ' abstract enum int short' +\n ' boolean export interface static' +\n ' byte extends long super' +\n ' char final native synchronized' +\n ' class float package throws' +\n ' const goto private transient' +\n ' debugger implements protected volatile' +\n ' double import public let yield await' +\n ' null true false'\n ).split(' ');\n\n const compilerWords = (JavaScriptCompiler.RESERVED_WORDS = {});\n\n for (let i = 0, l = reservedWords.length; i < l; i++) {\n compilerWords[reservedWords[i]] = true;\n }\n})();\n\n/**\n * @deprecated May be removed in the next major version\n */\nJavaScriptCompiler.isValidJavaScriptVariableName = function(name) {\n return (\n !JavaScriptCompiler.RESERVED_WORDS[name] &&\n /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name)\n );\n};\n\nfunction strictLookup(requireTerminal, compiler, parts, startPartIndex, type) {\n let stack = compiler.popStack(),\n len = parts.length;\n if (requireTerminal) {\n len--;\n }\n\n for (let i = startPartIndex; i < len; i++) {\n stack = compiler.nameLookup(stack, parts[i], type);\n }\n\n if (requireTerminal) {\n return [\n compiler.aliasable('container.strict'),\n '(',\n stack,\n ', ',\n compiler.quotedString(parts[len]),\n ', ',\n JSON.stringify(compiler.source.currentLocation),\n ' )'\n ];\n } else {\n return stack;\n }\n}\n\nexport default JavaScriptCompiler;\n","import runtime from './handlebars.runtime';\n\n// Compiler imports\nimport AST from './handlebars/compiler/ast';\nimport {\n parser as Parser,\n parse,\n parseWithoutProcessing\n} from './handlebars/compiler/base';\nimport { Compiler, compile, precompile } from './handlebars/compiler/compiler';\nimport JavaScriptCompiler from './handlebars/compiler/javascript-compiler';\nimport Visitor from './handlebars/compiler/visitor';\n\nimport noConflict from './handlebars/no-conflict';\n\nlet _create = runtime.create;\nfunction create() {\n let hb = _create();\n\n hb.compile = function(input, options) {\n return compile(input, options, hb);\n };\n hb.precompile = function(input, options) {\n return precompile(input, options, hb);\n };\n\n hb.AST = AST;\n hb.Compiler = Compiler;\n hb.JavaScriptCompiler = JavaScriptCompiler;\n hb.Parser = Parser;\n hb.parse = parse;\n hb.parseWithoutProcessing = parseWithoutProcessing;\n\n return hb;\n}\n\nlet inst = create();\ninst.create = create;\n\nnoConflict(inst);\n\ninst.Visitor = Visitor;\n\ninst['default'] = inst;\n\nexport default inst;\n","/* eslint-disable new-cap */\nimport Visitor from './visitor';\n\nexport function print(ast) {\n return new PrintVisitor().accept(ast);\n}\n\nexport function PrintVisitor() {\n this.padding = 0;\n}\n\nPrintVisitor.prototype = new Visitor();\n\nPrintVisitor.prototype.pad = function(string) {\n let out = '';\n\n for (let i = 0, l = this.padding; i < l; i++) {\n out += ' ';\n }\n\n out += string + '\\n';\n return out;\n};\n\nPrintVisitor.prototype.Program = function(program) {\n let out = '',\n body = program.body,\n i,\n l;\n\n if (program.blockParams) {\n let blockParams = 'BLOCK PARAMS: [';\n for (i = 0, l = program.blockParams.length; i < l; i++) {\n blockParams += ' ' + program.blockParams[i];\n }\n blockParams += ' ]';\n out += this.pad(blockParams);\n }\n\n for (i = 0, l = body.length; i < l; i++) {\n out += this.accept(body[i]);\n }\n\n this.padding--;\n\n return out;\n};\n\nPrintVisitor.prototype.MustacheStatement = function(mustache) {\n return this.pad('{{ ' + this.SubExpression(mustache) + ' }}');\n};\nPrintVisitor.prototype.Decorator = function(mustache) {\n return this.pad('{{ DIRECTIVE ' + this.SubExpression(mustache) + ' }}');\n};\n\nPrintVisitor.prototype.BlockStatement = PrintVisitor.prototype.DecoratorBlock = function(\n block\n) {\n let out = '';\n\n out += this.pad(\n (block.type === 'DecoratorBlock' ? 'DIRECTIVE ' : '') + 'BLOCK:'\n );\n this.padding++;\n out += this.pad(this.SubExpression(block));\n if (block.program) {\n out += this.pad('PROGRAM:');\n this.padding++;\n out += this.accept(block.program);\n this.padding--;\n }\n if (block.inverse) {\n if (block.program) {\n this.padding++;\n }\n out += this.pad('{{^}}');\n this.padding++;\n out += this.accept(block.inverse);\n this.padding--;\n if (block.program) {\n this.padding--;\n }\n }\n this.padding--;\n\n return out;\n};\n\nPrintVisitor.prototype.PartialStatement = function(partial) {\n let content = 'PARTIAL:' + partial.name.original;\n if (partial.params[0]) {\n content += ' ' + this.accept(partial.params[0]);\n }\n if (partial.hash) {\n content += ' ' + this.accept(partial.hash);\n }\n return this.pad('{{> ' + content + ' }}');\n};\nPrintVisitor.prototype.PartialBlockStatement = function(partial) {\n let content = 'PARTIAL BLOCK:' + partial.name.original;\n if (partial.params[0]) {\n content += ' ' + this.accept(partial.params[0]);\n }\n if (partial.hash) {\n content += ' ' + this.accept(partial.hash);\n }\n\n content += ' ' + this.pad('PROGRAM:');\n this.padding++;\n content += this.accept(partial.program);\n this.padding--;\n\n return this.pad('{{> ' + content + ' }}');\n};\n\nPrintVisitor.prototype.ContentStatement = function(content) {\n return this.pad(\"CONTENT[ '\" + content.value + \"' ]\");\n};\n\nPrintVisitor.prototype.CommentStatement = function(comment) {\n return this.pad(\"{{! '\" + comment.value + \"' }}\");\n};\n\nPrintVisitor.prototype.SubExpression = function(sexpr) {\n let params = sexpr.params,\n paramStrings = [],\n hash;\n\n for (let i = 0, l = params.length; i < l; i++) {\n paramStrings.push(this.accept(params[i]));\n }\n\n params = '[' + paramStrings.join(', ') + ']';\n\n hash = sexpr.hash ? ' ' + this.accept(sexpr.hash) : '';\n\n return this.accept(sexpr.path) + ' ' + params + hash;\n};\n\nPrintVisitor.prototype.PathExpression = function(id) {\n let path = id.parts.join('/');\n return (id.data ? '@' : '') + 'PATH:' + path;\n};\n\nPrintVisitor.prototype.StringLiteral = function(string) {\n return '\"' + string.value + '\"';\n};\n\nPrintVisitor.prototype.NumberLiteral = function(number) {\n return 'NUMBER{' + number.value + '}';\n};\n\nPrintVisitor.prototype.BooleanLiteral = function(bool) {\n return 'BOOLEAN{' + bool.value + '}';\n};\n\nPrintVisitor.prototype.UndefinedLiteral = function() {\n return 'UNDEFINED';\n};\n\nPrintVisitor.prototype.NullLiteral = function() {\n return 'NULL';\n};\n\nPrintVisitor.prototype.Hash = function(hash) {\n let pairs = hash.pairs,\n joinedPairs = [];\n\n for (let i = 0, l = pairs.length; i < l; i++) {\n joinedPairs.push(this.accept(pairs[i]));\n }\n\n return 'HASH{' + joinedPairs.join(', ') + '}';\n};\nPrintVisitor.prototype.HashPair = function(pair) {\n return pair.key + '=' + this.accept(pair.value);\n};\n/* eslint-enable new-cap */\n","// USAGE:\n// var handlebars = require('handlebars');\n/* eslint-env node */\n/* eslint-disable no-var */\n\n// var local = handlebars.create();\n\nvar handlebars = require('../dist/cjs/handlebars')['default'];\n\nvar printer = require('../dist/cjs/handlebars/compiler/printer');\nhandlebars.PrintVisitor = printer.PrintVisitor;\nhandlebars.print = printer.print;\n\nmodule.exports = handlebars;\n\n// Publish a Node.js require() handler for .handlebars and .hbs files\nfunction extension(module, filename) {\n var fs = require('fs');\n var templateString = fs.readFileSync(filename, 'utf8');\n module.exports = handlebars.compile(templateString);\n}\n/* istanbul ignore else */\nif (typeof require !== 'undefined' && require.extensions) {\n require.extensions['.handlebars'] = extension;\n require.extensions['.hbs'] = extension;\n}\n","/**\n * @aaac/runtime — public API\n *\n * Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n */\n\nimport { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\n/** Package version string. */\nexport const version = pkg.version;\n\nexport {\n runTask,\n buildTaskPrompt,\n buildSplitTaskPrompt,\n buildRetryFollowUp,\n buildCandidateAgents,\n renderAgentSystemPrompt,\n renderNavigationIndexPrompt,\n renderAnalyzerExplorationMandatePrompt,\n collectAnalyzerToolIds,\n shouldInjectAnalyzerExplorationMandate,\n isNavigationIndex,\n extractStructuredResult,\n zodSchemaToPromptDescription,\n zodSchemaToYamlExample,\n type CandidateAgent,\n type SdkAdapter,\n type AdapterSendOptions,\n type AgentProgressEvent,\n type AgentExecutionRequest,\n type TaskContext,\n type TaskOutcome,\n type TaskRunOptions,\n type TaskRunResult,\n type RetryDecision,\n type AgentContractLike,\n type TaskContractLike,\n type PromptBuilderOptions,\n type SplitPrompt,\n type CacheConfig,\n type ObserverEmitFn,\n type ExecutionEnvelope,\n type TokenUsage,\n} from \"./lib/task-runner.js\";\n\nexport {\n runWorkflow,\n buildGateEvaluationPrompt,\n parseGateEvaluationResponse,\n type SdkAdapterFactory,\n type ModelAwareSdkAdapterFactory,\n type AdapterOrFactory,\n type WorkflowInvocation,\n type HandoffInput,\n type WorkflowRegistries,\n type WorkflowRunOptions,\n type WorkflowResult,\n type StepResult,\n type StepCompleteEvent,\n type WorkflowContractLike,\n type WorkflowStep,\n type DelegateStep,\n type GateStep,\n type EvaluateStep,\n type ConvergenceEnvelopePayload,\n type ConvergenceEnvelope,\n type ReceiveSpec,\n} from \"./lib/workflow-runner.js\";\n\nexport {\n WORKFLOW_INPUT_STEP_ID,\n buildWorkflowInputOutput,\n formatWorkflowInputContext,\n stepDependsOnWorkflowInput,\n type WorkflowInputHandoff,\n type WorkflowInputOutput,\n} from \"./lib/workflow-input.js\";\n\nexport {\n createExecutionEnvelope,\n emitSessionOpen,\n emitSessionClose,\n emitSubagentOpen,\n emitSubagentClose,\n emitIterationOpen,\n emitIterationClose,\n emitIterationMetric,\n emitToolchainOpen,\n emitToolchainClose,\n emitLlmTurnOpen,\n emitLlmTurnClose,\n emitToolExecOpen,\n emitToolExecClose,\n buildObservabilityEnv,\n OBSERVABILITY_ENV_VARS,\n serializeObserverEmit,\n type EnvelopeParams,\n type InnerSpanOptions,\n type ObservabilityIds,\n} from \"./lib/observability-bridge.js\";\n\nexport {\n emitProcessWorkflowOpen,\n emitProcessWorkflowClose,\n emitProcessTaskOpen,\n emitProcessTaskClose,\n emitProcessEdit,\n isFileEditTool,\n type ProcessWorkflowOptions,\n type ProcessTaskOptions,\n type ProcessEditOptions,\n} from \"./lib/process-axis-bridge.js\";\n\nexport {\n pluginRegistry,\n PluginRegistry,\n type AgentPlugin,\n type GuardrailResult,\n type PromptBuilderArgs,\n} from \"./lib/plugin.js\";\n\nexport {\n createGuardrailHooks,\n createGuardrailHooksFromRules,\n getBlockingViolations,\n getWarnings,\n hasBlockingViolation,\n UNRESOLVED_GUARDRAIL_ACTION,\n type GuardrailAction,\n type GuardrailCheckFunctions,\n type GuardrailHooks,\n type HookContext,\n type HookResponse,\n type GuardrailCheckResult,\n type GuardrailRule,\n type GuardrailRuleData,\n} from \"./lib/guardrail-hooks.js\";\n\nexport {\n BoundResolver,\n getEffectiveGuardrailIds,\n getGuardrailRulesForAgent,\n guardrailContextToRuleData,\n buildPerAgentGuardrails,\n type BoundResolveOptions,\n type ResolvedComponent,\n type ResolvedToolchain,\n type ArtifactBindingConfig,\n deriveToolchainsForAgents,\n} from \"./lib/bound-resolver.js\";\n\nexport {\n createRuntime,\n WorkflowBuilder,\n type Runtime,\n type RuntimeConfig,\n} from \"./lib/builder.js\";\n\nexport {\n loadPlugins,\n type PluginLoadResult,\n} from \"./lib/plugin-loader.js\";\n\nexport {\n createModelResolver,\n type ModelClass,\n type ModelResolver,\n type ModelMappingConfig,\n type ModelResolverOptions,\n type ResolvedModel,\n} from \"./lib/model-resolver.js\";\n\nexport {\n loadDslContext,\n buildRegistriesFromDsl,\n DslValidationError,\n type LoadDslOptions,\n type RequiredEntities,\n type DslContext,\n} from \"./lib/dsl-context.js\";\n\nexport { jsonSchemaToZod } from \"./lib/schema-converter.js\";\n\nexport {\n createProgressSink,\n type ProgressSink,\n type ProgressSinkOptions,\n} from \"./lib/progress-sink.js\";\n\nexport type { MemoryRef, MemoryStore } from \"./lib/memory-store.js\";\nexport { InMemoryStore } from \"./lib/memory-store.js\";\n\nexport { FileMemoryStore } from \"./lib/file-memory-store.js\";\n\nexport {\n AgentLogWriter,\n type RunLogEvent,\n type AgentLogWriterOptions,\n} from \"./lib/agent-log-writer.js\";\n\nexport {\n createLibraryToolRegistry,\n createRegistryFromSdkTools,\n type LibraryToolDefinition,\n type LibraryToolRegistry,\n} from \"./lib/library-tool-binding.js\";\n\nexport {\n buildSdkFunctionTools,\n type SdkFunctionTool,\n} from \"./lib/library-tool-sdk.js\";\n\nexport {\n createAnalyzerBridge,\n isContextPack,\n renderContextPackPrompt,\n type AnalyzerBridge,\n type AnalyzerBridgeOptions,\n type AnalyzeImpactInput,\n type GenerateContextPackInput,\n type BuildCallGraphInput,\n} from \"./lib/analyzer-bridge.js\";\n\nexport {\n createAdapter,\n type CreateAdapterOptions,\n type PermissionMode,\n} from \"./lib/adapter-factory.js\";\n\nexport {\n executeTask,\n executeWorkflow,\n type ExecuteOptions,\n type ExecuteTaskOptions,\n type ExecuteWorkflowOptions,\n type TaskHookContext,\n type WorkflowHookContext,\n} from \"./lib/execute.js\";\n\nexport {\n createRuntimeBinding,\n type AaacInvocationContext,\n type AaacRuntime,\n type AaacPolicy,\n type AaacObserver,\n type InvokedComponent,\n type OperationHandler,\n type RuntimeBinding,\n type OperationMemoryRefConfig,\n type MemoryStoreEntry,\n} from \"./component-binding.js\";\n\nexport {\n createProjectRuntime,\n findProjectConfig,\n PROJECT_CONFIG_FILENAME,\n type CreateProjectRuntimeOptions,\n type ProjectRuntime,\n type ResolvedAdapterSelection,\n} from \"./lib/project-runtime.js\";\n\nexport {\n createComponentScope,\n DEFAULT_COMPONENT_ID,\n UnresolvedScopeDeclarationError,\n type ComponentScope,\n type CreateComponentScopeOptions,\n} from \"./component-scope.js\";\n\nexport {\n buildNavigationContext,\n type NavigationContextOptions,\n type NavigationContext,\n} from \"./lib/navigation-context.js\";\n\nexport {\n resolveArtifacts,\n type ArtifactResolveOptions,\n type ArtifactResolveResult,\n} from \"./lib/artifact-resolver.js\";\n\nexport {\n evaluateGuardrail,\n listGuardrails,\n guardStatus,\n type EvaluateGuardrailOptions,\n type EvaluateGuardrailResult,\n type ListGuardrailsOptions,\n type ListGuardrailsResult,\n type GuardrailListEntry,\n type GuardStatusOptions,\n type GuardStatusResult,\n} from \"./lib/guard-commands.js\";\n\nexport {\n syncClaude,\n checkClaude,\n parseClaudeConfig,\n type SyncOptions as ClaudeSyncOptions,\n type SyncResult as ClaudeSyncResult,\n type CheckResult as ClaudeCheckResult,\n type FileAction as ClaudeFileAction,\n type ClaudeConfig,\n} from \"./lib/claude-materialize/index.js\";\n\nexport {\n executePrompt,\n operationsToTools,\n parseRouterResponse,\n type PromptResult,\n type PromptExecuteOptions,\n type OperationToolDef,\n} from \"./lib/prompt-executor.js\";\n\nexport {\n runToolchainChecks,\n ToolchainManifestSchema,\n type ToolchainCheckResult,\n type ToolchainManifest,\n type RunToolchainChecksOptions,\n} from \"./lib/toolchain-checker.js\";\n","/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport {\n isNavigationIndex,\n renderNavigationIndexPrompt,\n} from \"./navigation-index-prompt.js\";\n\nexport { isNavigationIndex, renderNavigationIndexPrompt };\nimport * as yaml from \"yaml\";\n\nimport type { MemoryRef } from \"./memory-store.js\";\nimport type { ModelClass } from \"./model-resolver.js\";\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport { pluginRegistry } from \"./plugin.js\";\nimport { toolTargetPath } from \"./guardrail-hooks.js\";\nimport { buildCandidateAgents, renderAgentSystemPrompt, type CandidateAgent } from \"./candidate-agents.js\";\nimport { isContextPack, renderContextPackPrompt } from \"./analyzer-bridge.js\";\nimport {\n createExecutionEnvelope,\n emitSubagentOpen,\n emitSubagentClose,\n type ObserverEmitFn,\n type ExecutionEnvelope,\n type InnerSpanOptions,\n type TokenUsage,\n} from \"./observability-bridge.js\";\nimport { computeCostUsd } from \"./model-pricing.js\";\nimport {\n emitProcessTaskOpen,\n emitProcessTaskClose,\n emitProcessEdit,\n isFileEditTool,\n} from \"./process-axis-bridge.js\";\n\nexport type { MemoryRef } from \"./memory-store.js\";\nexport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nexport type { CandidateAgent } from \"./candidate-agents.js\";\nexport { buildCandidateAgents, renderAgentSystemPrompt } from \"./candidate-agents.js\";\nexport type { ObserverEmitFn, ExecutionEnvelope, InnerSpanOptions, TokenUsage } from \"./observability-bridge.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n readonly rules?: readonly { readonly id: string; readonly description: string; readonly severity: string }[];\n /**\n * Agent ids this agent is allowed to delegate to. When present, it restricts\n * the candidate sub-agent set registered with the SDK for LLM-internal routing.\n */\n readonly can_invoke_agents?: readonly string[];\n /**\n * Tool names this agent may execute. When present, sub-agents receive an\n * isolated tool set instead of inheriting the parent agent's tools.\n */\n readonly can_execute_tools?: readonly string[];\n /**\n * The agent is the entry/orchestrator role: it dispatches work to other\n * agents and is never itself a delegation target. Materializing it as a\n * Claude Code subagent would contradict `buildCandidateAgents`, which\n * excludes the entry agent from the candidate set.\n */\n readonly dispatch_only?: boolean;\n /**\n * Declared artifact and handoff permissions. Optional like every other\n * non-universal field on this duck-typed contract; `buildAgentRegistry`\n * always populates them, and absent is indistinguishable from empty (unlike\n * `can_invoke_agents`, where presence itself restricts the candidate set).\n */\n readonly can_read_artifacts?: readonly string[];\n readonly can_write_artifacts?: readonly string[];\n readonly can_return_handoffs?: readonly string[];\n readonly can_perform_validations?: readonly string[];\n /**\n * The rest of what a DSL agent declares about how it must work: the failure\n * shapes it must avoid, when it must stop and escalate, the decisions it owns,\n * the checklist an audit of its output runs, and its free-form prose sections.\n *\n * They are on this contract for the same reason `rules` is — they are\n * mandatory instructions to the agent, and a renderer cannot carry what the\n * contract does not hold. None of them reached any Claude surface while the\n * Cursor binding rendered all five, so one DSL produced two harnesses telling\n * an agent different things about its own obligations (#349).\n *\n * `x-authority` / `x-audit-checklist` are `x-` prefixed in the DSL document\n * and plain here, as `x-optional` / `x-instruction` / `x-receives` already are\n * on `DelegateStep`: the prefix is a fact about the document, not about this\n * runtime's interfaces (see `buildWorkflowStep`, `dsl-context.ts`).\n */\n readonly anti_patterns?: readonly string[];\n readonly escalation_criteria?: readonly {\n readonly condition: string;\n readonly action: string;\n }[];\n readonly authority?: {\n readonly can_decide?: readonly string[];\n readonly cannot_decide?: readonly string[];\n };\n readonly audit_checklist?: readonly {\n readonly section: string;\n readonly checks: readonly string[];\n }[];\n /**\n * Already expanded: a `sections[]` entry may name a list the DSL holds\n * (`list: agents`) rather than carry prose, and resolving that needs the whole\n * document, which `buildAgentRegistry` has and a renderer taking one agent\n * does not. `expandDslSection` (@aaac/contracts) is the one expansion, shared\n * with the Cursor binding.\n */\n readonly sections?: readonly { readonly title: string; readonly content: string }[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n readonly model_class?: ModelClass;\n /**\n * When true, the adapter may enable Dynamic Workflow tools (e.g. Claude's\n * Workflow tool) so the agent can internally parallelise sub-tasks.\n * Handoff validation at the task boundary is still enforced.\n */\n readonly allow_dynamic_workflow?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Progress events\n// ---------------------------------------------------------------------------\n\n/**\n * Progress event emitted by adapters during agent execution.\n * Enables real-time visibility into what the agent is doing\n * (tool calls, text output, status changes).\n */\nexport interface AgentProgressEvent {\n type: \"tool_use\" | \"tool_result\" | \"text\" | \"status\" | \"cache_metrics\";\n tool_name?: string;\n /** Tool invocation arguments (e.g. file path, command). */\n input?: Record<string, unknown>;\n message?: string;\n /** SDK session ID for correlating events within a single adapter call. */\n session_id?: string;\n /** Cache utilization metrics from the SDK response. */\n cacheMetrics?: {\n cachedInputTokens?: number;\n totalInputTokens?: number;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Prompt caching\n// ---------------------------------------------------------------------------\n\n/**\n * A prompt split into static (cacheable) and dynamic (per-invocation) sections.\n * Adapters that support prompt caching can use the `system` sections as\n * provider-specific system prompts, reducing token costs on repeated calls.\n */\nexport interface SplitPrompt {\n /** Static sections: role, responsibilities, constraints, rules, task, schema, recovery. */\n system: string[];\n /** Dynamic sections: user request, handoff input, prior context, files, acceptance criteria. */\n user: string;\n}\n\n/**\n * Optional cache configuration for adapters that support prompt caching.\n * Provider-specific defaults apply when individual fields are omitted.\n */\nexport interface CacheConfig {\n /** Enable prompt caching. Defaults to true when the adapter supports it. */\n enabled?: boolean;\n /** Provider-specific TTL (e.g. \"5m\", \"1h\", \"24h\"). */\n ttl?: string;\n /** Stable key for cross-session cache reuse (provider-specific). */\n cacheKey?: string;\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n /**\n * Optional callback invoked with intermediate progress events during execution.\n * Adapters that consume an internal event stream (e.g. Claude SDK's AsyncGenerator)\n * call this for each non-result message, enabling callers to display live progress.\n */\n onProgress?: (event: AgentProgressEvent) => void;\n /**\n * Split prompt for prompt caching support. When provided, adapters that support\n * caching can separate static (cacheable) instructions from dynamic content.\n * Adapters without caching support can ignore this and use the prompt argument.\n */\n splitPrompt?: SplitPrompt;\n /**\n * Candidate sub-agents the entry agent's LLM may delegate to (model B,\n * LLM-internal routing). Adapters register these via their native subagent\n * mechanism (Claude `agents`, OpenAI `handoffs`, ADK `subAgents`). When\n * omitted or empty, adapters behave exactly as before (single agent).\n */\n agents?: CandidateAgent[];\n /**\n * When true, adapters that support dynamic workflow tools (e.g. Claude's\n * Workflow tool for agent()/pipeline()/parallel()) should enable them.\n * The task's final output is still validated against the handoff schema.\n */\n allowDynamicWorkflow?: boolean;\n /**\n * In-process library tools to register with the SDK as function tools.\n * Adapters convert these to their native tool format (Claude MCP, OpenAI\n * function tools, ADK tools). I/O is validated against the tool's schemas.\n */\n libraryTools?: LibraryToolRegistry;\n /**\n * Optional observer emit function for inner turn-level spans\n * (agent.llm_turn, agent.tool_exec). When undefined, adapters skip\n * instrumentation entirely (no-op).\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID for inner turn-level spans. Typically the subagent span ID\n * so that LLM turn and tool execution spans are correlated as children.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded so\n * inner agent.llm_turn / agent.tool_exec spans carry a non-NULL session_id and\n * join the cross-axis correlation rules (#143 / #140).\n */\n sessionId?: string;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n\n /**\n * Split prompt for prompt caching support. When provided, adapters can\n * separate static instructions (system) from dynamic content (user).\n */\n splitPrompt?: SplitPrompt;\n\n /**\n * Candidate sub-agents for LLM-internal routing (model B). Mirrors\n * `AdapterSendOptions.agents`; also forwarded via `options.agents`.\n */\n agents?: CandidateAgent[];\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n\n /** Return the memory_ref produced by the last send/sendExecution call. */\n getLastMemoryRef?(): MemoryRef | null;\n\n /** Return the token usage from the last send/sendExecution call. */\n getLastTokenUsage?(): TokenUsage | null;\n\n /** Check if this adapter is compatible with the given compat tag. */\n isCompatible?(compat: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string; memoryRef?: MemoryRef }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n /**\n * Writable stream for real-time progress output during agent execution.\n * When provided, intermediate adapter events (tool use, status, etc.)\n * are formatted and written here. Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n /**\n * Optional observer emit function for agent-axis spans (agent.subagent open/close).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID (typically the enclosing agent.session span's run_id).\n * Used to correlate agent.subagent spans with their parent session.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded from\n * the workflow runner so the subagent span and all inner spans share one\n * non-NULL session_id, even when parentSpanId is an evaluate iteration span\n * rather than the session span (#143 / #140).\n */\n sessionId?: string;\n /** LLM adapter identifier for the execution envelope (gen_ai.system). */\n envelopeAdapter?: string;\n /** LLM model identifier for the execution envelope (gen_ai.request.model). */\n envelopeModel?: string;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n tokenUsage?: TokenUsage;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n constraints?: string;\n}\n\ntype ZodCheckEntry = {\n kind?: string;\n value?: number;\n regex?: RegExp;\n isInt?: boolean;\n _zod?: { def?: Record<string, unknown> };\n};\n\nfunction getZodChecks(schema: z.ZodType): ZodCheckEntry[] {\n const def = (schema as z.ZodType & { _def?: { checks?: ZodCheckEntry[] } })._def;\n return def?.checks ?? [];\n}\n\n/** Extract validation constraints from Zod's internal checks for prompt display. */\nfunction extractZodConstraints(schema: z.ZodType): string | undefined {\n const inner = unwrapOptional(schema);\n const parts: string[] = [];\n\n if (inner instanceof z.ZodString) {\n const str = inner as z.ZodString & {\n minLength?: number | null;\n maxLength?: number | null;\n };\n if (str.minLength != null) parts.push(`min: ${str.minLength}`);\n if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.kind === \"regex\" && check.regex) parts.push(`regex: ${check.regex}`);\n const def = check._zod?.def;\n if (def?.format === \"regex\" && def.pattern instanceof RegExp) {\n parts.push(`regex: ${def.pattern}`);\n }\n }\n } else if (inner instanceof z.ZodNumber) {\n let hasInt = false;\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"int\") hasInt = true;\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.isInt) hasInt = true;\n const def = check._zod?.def;\n if (def?.check === \"number_format\" && def.format === \"safeint\") hasInt = true;\n if (def?.check === \"greater_than\") parts.push(`min: ${def.value}`);\n if (def?.check === \"less_than\") parts.push(`max: ${def.value}`);\n }\n if (hasInt) parts.unshift(\"int\");\n } else if (inner instanceof z.ZodArray) {\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n const def = check._zod?.def;\n if (def?.check === \"min_length\") parts.push(`min: ${def.minimum}`);\n if (def?.check === \"max_length\") parts.push(`max: ${def.maximum}`);\n }\n }\n\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const element = (schema as z.ZodArray<z.ZodType>)._def.element;\n const inner = zodTypeToString(element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\n/** Unwrap ZodOptional to get the inner type. */\nfunction unwrapOptional(schema: z.ZodType): z.ZodType {\n if (schema instanceof z.ZodOptional) {\n return (schema as z.ZodOptional<z.ZodType>)._def.innerType;\n }\n return schema;\n}\n\n/** Get the element schema from an array type. */\nfunction getArrayElement(schema: z.ZodType): z.ZodType | null {\n const inner = unwrapOptional(schema);\n if (inner instanceof z.ZodArray) {\n return (inner as z.ZodArray<z.ZodType>)._def.element;\n }\n return null;\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n constraints: extractZodConstraints(innerField as z.ZodType),\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n * Recursively generates sub-tables for nested objects and array elements.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const tables: string[] = [];\n collectFieldTables(schema, \"\", tables);\n return tables.join(\"\\n\\n\");\n}\n\nfunction collectFieldTables(\n schema: z.ZodType,\n pathPrefix: string,\n tables: string[],\n): void {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return;\n\n const title = pathPrefix ? `**${pathPrefix}**\\n\\n` : \"\";\n const header = \"| Field | Type | Required | Constraints | Description |\";\n const sep = \"|-------|------|----------|-------------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.constraints ?? \"\"} | ${f.description ?? \"\"} |`,\n );\n tables.push(`${title}${[header, sep, ...rows].join(\"\\n\")}`);\n\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n if (!shape) return;\n\n for (const f of fields) {\n const rawField = shape[f.name];\n const inner = unwrapOptional(rawField);\n\n if (inner instanceof z.ZodObject) {\n collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);\n } else if (inner instanceof z.ZodArray) {\n const element = (inner as z.ZodArray<z.ZodType>)._def.element;\n if (element instanceof z.ZodObject) {\n collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);\n }\n }\n }\n}\n\n/**\n * Generate a YAML example from a Zod schema shape, recursively expanding\n * nested objects and arrays up to a configurable depth.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType, maxDepth = 3): string {\n return renderYamlObject(schema, 0, maxDepth);\n}\n\nfunction renderYamlObject(schema: z.ZodType, indent: number, maxDepth: number): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const prefix = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const f of fields) {\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n const rawField = shape?.[f.name];\n\n if (f.type.endsWith(\"[]\")) {\n lines.push(`${prefix}${f.name}:`);\n const element = rawField ? getArrayElement(rawField) : null;\n if (element && element instanceof z.ZodObject && indent < maxDepth) {\n const nested = renderYamlObject(element, indent + 2, maxDepth);\n if (nested) {\n const basePrefix = \" \".repeat(indent + 2);\n const nestedLines = nested.split(\"\\n\");\n lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);\n for (let i = 1; i < nestedLines.length; i++) {\n lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);\n }\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"string[]\") {\n lines.push(`${prefix} - \"example\"`);\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"object\" && indent < maxDepth) {\n const inner = rawField ? unwrapOptional(rawField) : null;\n if (inner && inner instanceof z.ZodObject) {\n lines.push(`${prefix}${f.name}:`);\n const nested = renderYamlObject(inner, indent + 1, maxDepth);\n if (nested) {\n lines.push(nested);\n } else {\n lines.push(`${prefix} key: \"value\"`);\n }\n } else {\n lines.push(`${prefix}${f.name}:`);\n lines.push(`${prefix} key: \"value\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${prefix}${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${prefix}${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${prefix}${f.name}: false`);\n } else if (f.type.startsWith(\"enum(\")) {\n const enumVals = f.type.slice(5, -1).split(\", \");\n lines.push(`${prefix}${f.name}: \"${enumVals[0]}\"`);\n } else {\n lines.push(`${prefix}${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/** Collect analyzer.* tool ids from a wired library tool registry. */\nexport function collectAnalyzerToolIds(\n registry?: LibraryToolRegistry,\n): string[] {\n if (!registry) return [];\n return registry\n .getAll()\n .map((def) => def.toolId)\n .filter((id) => id.startsWith(\"analyzer.\"));\n}\n\n/**\n * Level 1 exploration mandate applies when the runtime injected a navigation\n * index (codebase map) — the signal that artifact-scoped investigation is active.\n */\nexport function shouldInjectAnalyzerExplorationMandate(\n context: TaskContext,\n): boolean {\n return isNavigationIndex(context.variables?.navigationIndex);\n}\n\n/**\n * System-prompt section mandating analyzer MCP tools before ad-hoc file reads.\n * Injected automatically by runTask when Level 1 context is present.\n */\nexport function renderAnalyzerExplorationMandatePrompt(\n toolIds: readonly string[],\n): string {\n const tools = toolIds.length > 0\n ? toolIds.map((id) => `- \\`${id}\\``).join(\"\\n\")\n : \"- `analyzer.getContextMap`\\n- `analyzer.analyzeImpact`\\n- `analyzer.generateContextPack`\\n- `analyzer.buildCallGraph`\";\n\n return [\n \"## Codebase Exploration Protocol (Level 2)\",\n \"\",\n \"A Project Navigation Index is provided in the user prompt. When you need to\",\n \"investigate the codebase (locate affected files, trace dependencies, or scope\",\n \"changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:\",\n \"\",\n \"1. Use the navigation index to pick candidate artifacts and path patterns.\",\n \"2. Call `analyzer.getContextMap` with your `instruction` and `candidates[]`.\",\n \"3. Review suggestedReadTargets / suggestedEditTargets / suggestedValidationTargets.\",\n \"4. Call `analyzer.analyzeImpact` when you need a flat impact report.\",\n \"5. Use Read/Grep/Glob only for gaps the analyzer output did not cover.\",\n \"\",\n \"Available analyzer tools:\",\n tools,\n ].join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n /** When set, injects Level 1 analyzer exploration mandate into the system prompt. */\n analyzerExploration?: {\n toolIds: readonly string[];\n };\n}\n\n/**\n * Build a prompt split into static (cacheable) and dynamic (per-invocation) parts.\n *\n * Static (system): the agent's declaration (`renderAgentSystemPrompt`), Task\n * description, Completion Criteria, Output Format / Schema, Recovery\n * Instructions.\n *\n * Dynamic (user): User Request, Handoff Input, Prior Context,\n * Relevant Files, Acceptance Criteria.\n */\nexport function buildSplitTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): SplitPrompt {\n const system: string[] = [];\n\n // The agent's declaration — shared with candidate sub-agent prompts and the\n // Claude Code subagent files via renderAgentSystemPrompt so all stay in sync.\n system.push(renderAgentSystemPrompt(agent));\n\n if (\n options?.analyzerExploration?.toolIds.length &&\n shouldInjectAnalyzerExplorationMandate(context)\n ) {\n system.push(\n renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds),\n );\n }\n\n system.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n system.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n system.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n system.push(recoverySection);\n }\n\n // Dynamic sections (per-invocation)\n const userSections: string[] = [];\n\n // `user_request` and `handoff_input` are independent context fields, so each\n // is emitted on its own terms. Writing the request inside both arms of the\n // handoff branch said the same thing twice and made the request's presence\n // read as if it depended on the handoff.\n userSections.push(`## User Request\\n\\n${context.user_request}`);\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n userSections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n }\n\n if (context.prior_context) {\n userSections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n userSections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n userSections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.variables && Object.keys(context.variables).length > 0) {\n const contextPack = context.variables.analyzerContextPack;\n if (isContextPack(contextPack)) {\n userSections.push(renderContextPackPrompt(contextPack));\n }\n\n const navigationIndex = context.variables.navigationIndex;\n if (isNavigationIndex(navigationIndex)) {\n userSections.push(renderNavigationIndexPrompt(navigationIndex));\n }\n\n const otherVars = Object.entries(context.variables).filter(\n ([k]) => k !== \"analyzerContextPack\" && k !== \"navigationIndex\",\n );\n if (otherVars.length > 0) {\n const varLines = otherVars\n .map(([k, v]) => `- ${k}: ${typeof v === \"string\" ? v : JSON.stringify(v)}`)\n .join(\"\\n\");\n userSections.push(`## Context Variables\\n\\n${varLines}`);\n }\n }\n\n return {\n system,\n user: userSections.join(\"\\n\\n---\\n\\n\"),\n };\n}\n\n/** Join a SplitPrompt back into a single monolithic prompt string. */\nfunction joinSplitPrompt(split: SplitPrompt): string {\n return [...split.system, split.user].join(\"\\n\\n---\\n\\n\");\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\nfunction attachMemoryRef(outcome: TaskOutcome, adapter: SdkAdapter): TaskOutcome {\n if (outcome.status !== \"success\") return outcome;\n const ref = adapter.getLastMemoryRef?.();\n if (!ref) return outcome;\n return { ...outcome, memoryRef: ref };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Progress formatting\n// ---------------------------------------------------------------------------\n\nfunction summarizeToolInput(input?: Record<string, unknown>): string {\n if (!input) return \"\";\n const path = toolTargetPath(input);\n if (path) return ` — ${path}`;\n const cmd = input.command ?? input.cmd;\n if (typeof cmd === \"string\") return ` — ${cmd.length > 80 ? cmd.slice(0, 77) + \"...\" : cmd}`;\n const query = input.query ?? input.search ?? input.pattern;\n if (typeof query === \"string\") return ` — \"${query}\"`;\n return \"\";\n}\n\nfunction timestamp(): string {\n return new Date().toISOString();\n}\n\nfunction formatProgressPrefix(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const ts = timestamp();\n const sid = event.session_id ? event.session_id.slice(0, 8) : \"-\";\n const agent = agentId ?? \"-\";\n return `[${ts},${sid},${agent},${taskId}]`;\n}\n\nfunction formatProgressEvent(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const prefix = formatProgressPrefix(event, taskId, agentId);\n switch (event.type) {\n case \"tool_use\":\n return `${prefix} ⚙ ${event.tool_name ?? \"tool\"}${summarizeToolInput(event.input)}\\n`;\n case \"tool_result\":\n return \"\";\n case \"text\": {\n if (!event.message) return \"\";\n const trimmed = event.message.trim();\n if (!trimmed) return \"\";\n const firstLine = trimmed.split(\"\\n\")[0];\n const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + \"...\" : firstLine;\n return `${prefix} 💭 ${preview}\\n`;\n }\n case \"status\":\n return event.message ? `${prefix} ● ${event.message}\\n` : \"\";\n default:\n return \"\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n libraryTools?: LibraryToolRegistry;\n /**\n * Each agent's effective tool grant, from the executing component's\n * `ComponentScope.toolsByAgent` (#338). Travels with `agentRegistry`\n * because the two are consumed together, by `buildCandidateAgents` below.\n */\n toolsByAgent?: Map<string, string[]>;\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n // ── ExecutionEnvelope (Phase 1-1) ──────────────────────────────────────────\n // Create a standard envelope for this task execution. run_id is a UUIDv7.\n // parent_run_id is set to the enclosing session's spanId (from workflow-runner).\n const taskEnvelope: ExecutionEnvelope = createExecutionEnvelope({\n taskInstanceId: taskId,\n componentId: agentContract.id,\n fromAgent: agentContract.id,\n parentRunId: options?.parentSpanId, // correlates to agent.session run_id\n adapter: options?.envelopeAdapter,\n model: options?.envelopeModel,\n });\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);\n const promptOpts: PromptBuilderOptions = {\n handoffSchemas: schemas,\n retry: options?.retry,\n ...(analyzerToolIds.length > 0 &&\n shouldInjectAnalyzerExplorationMandate(enrichedContext)\n ? { analyzerExploration: { toolIds: analyzerToolIds } }\n : {}),\n };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n\n let prompt: string;\n let splitPrompt: SplitPrompt | undefined;\n\n const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);\n if (pluginPrompt) {\n prompt = pluginPrompt;\n } else {\n const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n splitPrompt = split;\n prompt = joinSplitPrompt(split);\n }\n\n const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n if (enhancedPrompt !== prompt) {\n splitPrompt = undefined;\n prompt = enhancedPrompt;\n }\n\n const isReadonly = agentContract.mode === \"read-only\";\n const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;\n\n // Build candidate sub-agents for LLM-internal routing (model B). The entry\n // agent (this task's target_agent) gets every other registry agent as a\n // candidate, restricted to its can_invoke_agents allow-list when present.\n // Empty registry → undefined (adapters then behave exactly as before).\n const candidateAgents = Object.keys(agentReg).length > 0\n ? buildCandidateAgents(agentReg, {\n entryAgentId: agentContract.id,\n allowedAgentIds: agentContract.can_invoke_agents,\n toolsByAgent: options?.toolsByAgent,\n })\n : [];\n const agents = candidateAgents.length > 0 ? candidateAgents : undefined;\n\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n // ── Process axis instrumentation (R3/R5 cross-axis correlation, #167) ───────\n // The Process axis must be instrumented in the LIVE runtime so the enrich\n // rules R3/R4 accumulate this task's modified files and R5 can link the commit\n // that materializes them. `effectiveSessionId` (below) is the SAME id\n // propagated to the git post-commit hook via AAAC_SESSION_ID, so the runtime\n // accumulation and the hook's promotion.commit correlate across processes.\n // All emit* helpers no-op when options.observer is undefined.\n const taskExecStart = Date.now();\n // The agent session id correlates every span emitted for this task (the\n // subagent span and all inner llm_turn/tool_exec spans) and joins the agent\n // axis to the cursor/git axes (#143 / #140). Prefer the explicit session id\n // threaded by the workflow runner; fall back to the parent session span, then\n // to this task's own run_id so the session_id is NEVER NULL — even when\n // runTask is invoked standalone (no workflow, no parent span).\n const effectiveSessionId =\n options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;\n // process.task open is emitted just after the agent.subagent open below, so\n // the agent span stays the first span for this task. The id is captured here\n // (let) so the finally can close it. Dedupe repeated edits to the same path to\n // limit write volume on the shared SqliteSink (R3 also dedupes, but this\n // avoids needless emit() round-trips).\n let processTaskSpanId: string | undefined;\n const emittedEditPaths = new Set<string>();\n\n const onProgress =\n options?.progressOutput || options?.observer\n ? (event: AgentProgressEvent) => {\n if (options?.progressOutput) {\n const line = formatProgressEvent(event, taskId, agentContract.id);\n if (line) options.progressOutput.write(line);\n }\n // Emit a process.edit for each file-mutating tool call so R3 can\n // accumulate this task's modified files for cross-axis linking (#167).\n if (\n options?.observer &&\n event.type === \"tool_use\" &&\n isFileEditTool(event.tool_name)\n ) {\n const p = toolTargetPath(event.input);\n if (p && !emittedEditPaths.has(p)) {\n emittedEditPaths.add(p);\n // IMPORTANT: do NOT set parentSpanId here. The enrich rule R3\n // resolves the parent task AND accumulates this file into the\n // per-task modified-files set (which R5 intersects with the\n // commit) ONLY when process.edit arrives WITHOUT a parentSpanId\n // (process.ts returns early otherwise). Leaving it unresolved is\n // what makes the cross-axis link materialize (#167).\n emitProcessEdit({\n filePath: p,\n sessionId: effectiveSessionId,\n observer: options.observer,\n });\n }\n }\n }\n : undefined;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n let memoryRef = enrichedContext.memoryRef;\n if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {\n console.warn(\n `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`,\n );\n memoryRef = undefined;\n }\n\n // ── agent.subagent open (Phase 1-3) ────────────────────────────────────────\n // Emit agent.subagent open span. subagentSpanId = taskEnvelope.run_id.\n // parentSpanId = options.parentSpanId (agent.session span from runWorkflow).\n // No-op when options.observer is undefined. taskExecStart / effectiveSessionId\n // are computed above with the Process axis instrumentation so both axes share\n // one session id and a single start clock.\n const subagentSpanId = emitSubagentOpen(\n options?.observer,\n taskEnvelope,\n options?.parentSpanId,\n taskId,\n agentContract.role_name,\n effectiveSessionId,\n );\n\n // ── process.task open (#167) ───────────────────────────────────────────────\n // Emitted after agent.subagent open so the agent span remains first, but\n // before any tool runs so R3/R4 see this task on the active-task stack when\n // process.edit events arrive. No-op when options.observer is undefined.\n processTaskSpanId = emitProcessTaskOpen({\n taskId,\n targetAgent: task.target_agent,\n sessionId: effectiveSessionId,\n parentSpanId: subagentSpanId ?? options?.parentSpanId,\n observer: options?.observer,\n });\n\n // ── Exception-safe subagent lifecycle ──────────────────────────────────────\n // Everything between the agent.subagent open span and its close span (initial\n // send, validation/afterTask hooks and the recovery loop) can throw or return\n // early. Wrap that region in try/finally so the close span is emitted EXACTLY\n // ONCE on EVERY exit path — success, a returned failure AND a thrown exception\n // — leaving no span stuck 'open'. This mirrors runWorkflow's session lifecycle.\n // A `closed` guard prevents double emission; closeStatus/closeCause carry the\n // outcome into the finally. The original exception is always re-thrown\n // unchanged (the finally never swallows it) to preserve propagation semantics.\n let closeStatus = \"error\";\n let closeCause: string | undefined;\n let spanClosed = false;\n const closeSubagentSpan = (): void => {\n if (spanClosed) return;\n spanClosed = true;\n const durationMs = Date.now() - taskExecStart;\n const lastTokenUsage = adapter.getLastTokenUsage?.();\n taskEnvelope.execution_metadata = {\n ...(taskEnvelope.execution_metadata ?? {}),\n duration_ms: durationMs,\n ...(lastTokenUsage ? {\n token_usage: {\n input_tokens: lastTokenUsage.inputTokens,\n output_tokens: lastTokenUsage.outputTokens,\n ...(lastTokenUsage.totalTokens !== undefined ? { total_tokens: lastTokenUsage.totalTokens } : {}),\n ...(lastTokenUsage.cacheReadTokens !== undefined ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {}),\n ...(lastTokenUsage.cacheCreationTokens !== undefined ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}),\n },\n } : {}),\n };\n if (lastTokenUsage) {\n const costUsd = computeCostUsd(\n taskEnvelope.model,\n lastTokenUsage.inputTokens,\n lastTokenUsage.outputTokens,\n );\n if (costUsd !== undefined) {\n taskEnvelope.execution_metadata = {\n ...taskEnvelope.execution_metadata,\n cost_usd: costUsd,\n };\n }\n }\n emitSubagentClose(\n options?.observer,\n subagentSpanId ?? taskEnvelope.run_id,\n taskEnvelope,\n durationMs,\n closeStatus,\n agentContract.role_name,\n closeCause,\n effectiveSessionId,\n );\n // ── process.task close (#167) ─────────────────────────────────────────────\n // Pop this task off the enrich active-task stack (R3/R4). Guarded by the\n // same `spanClosed` flag so it is emitted EXACTLY ONCE on every exit path.\n if (processTaskSpanId) {\n emitProcessTaskClose(processTaskSpanId, {\n status: closeStatus,\n durationMs,\n observer: options?.observer,\n });\n }\n };\n\n try {\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n memoryRef,\n splitPrompt,\n agents,\n options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });\n }\n } catch (err) {\n // SDK errors on the initial send are returned as an error outcome (NOT\n // re-thrown) — preserve that semantics. The finally emits the close span.\n closeStatus = \"error\";\n closeCause = `SDK error: ${(err as Error).message}`;\n return { outcome: { status: \"error\", message: closeCause }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n // Normal exit: record the final outcome status for the close span.\n closeStatus = outcome.status;\n const finalTokenUsage = adapter.getLastTokenUsage?.() ?? undefined;\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };\n } catch (err) {\n // Post-send / recovery threw (e.g. validation, afterTask hook or decide()).\n // Record the cause and re-throw unchanged — the finally still emits close.\n closeStatus = \"error\";\n closeCause = (err as Error).message;\n throw err;\n } finally {\n // ── agent.subagent close (Phase 1-3) ─────────────────────────────────────\n closeSubagentSpan();\n }\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type {\n GuardrailCheckFunctions,\n GuardrailCheckResult,\n} from \"./guardrail-hooks.js\";\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\n/**\n * One plugin verdict in the guardrail evaluator's shape.\n *\n * The two types say the same thing in opposite polarity — a plugin reports what\n * it MATCHED, the evaluator records what PASSED — and `severity` has no reader\n * on the evaluator side, which grades by `action` alone. So the translation is\n * real and belongs to whichever side owns `GuardrailResult`: this one. It sat in\n * `guardrail-hooks` while that module imported the registry, and cost an\n * `action as GuardrailCheckResult[\"action\"]` cast to get there, because it was\n * written against a structural `{ action: string }` rather than the declared\n * union. `GuardrailResult[\"action\"]` is a strict subset of `GuardrailAction`\n * (which adds only `unresolved`, a state no plugin can be in), so naming the\n * type makes the assignment check instead of asserting.\n */\nfunction toCheckResult(result: GuardrailResult): GuardrailCheckResult {\n return {\n guardrail_id: result.guardrail_id,\n passed: !result.matched,\n action: result.action,\n message: result.matched ? result.message : \"\",\n };\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n /**\n * Whether `guardrailChecks()` would supply anything.\n *\n * The execution layer has to know this BEFORE it builds hooks, because it\n * decides whether hooks exist at all and the source it gets back is three\n * closures either way, indistinguishable from an empty one. It gated on the\n * resolved rules instead, so a project whose ONLY guardrails came from a\n * plugin got no hooks and its plugin was consulted nowhere (#332).\n *\n * The question is asked of the three EVALUATORS, not of `customGuardrails`\n * itself, because that is what the three aggregators above ask: each skips a\n * plugin whose own method is absent, so `customGuardrails: {}` — legal under\n * the type — contributes to no check. Answering `true` for it would report a\n * source that grades nothing, and the execution layer would give a project\n * one adapter per agent to carry hooks with nothing in them.\n *\n * Answering it belongs here for the same reason `guardrailChecks` does: the\n * shape of `AgentPlugin.customGuardrails` is this module's to know, and it is\n * read nowhere else.\n */\n hasGuardrails(): boolean {\n return this.plugins.some(\n ({ customGuardrails: g }) =>\n Boolean(g?.evaluateCommand) ||\n Boolean(g?.evaluateFilePath) ||\n Boolean(g?.evaluateFileContent),\n );\n }\n\n /**\n * These plugins' `customGuardrails`, as a check source `createGuardrailHooks`\n * takes alongside the rules a software binding resolved.\n *\n * The evaluator used to reach for the `pluginRegistry` singleton itself. That\n * is an ambient dependency pointing the wrong way — a shared leaf module\n * reaching up into an application-level registry — and it had a measurable\n * price, because `guardrail-hooks` is on the LEAN graph: a class gets no\n * per-method tree-shaking, so the whole registry, task and workflow hooks\n * included, was 1,481 B of the 12,496 B `check-artifact-edit` parses on every\n * single tool call (#331). Handing the source in reverses the edge (this\n * module knows the evaluator's shape; the evaluator knows nothing of plugins)\n * and takes the class off that graph entirely.\n *\n * WHO passes it is the whole design, so it is stated here rather than left to\n * be inferred from call sites:\n *\n * - The EXECUTION layer does — `execute.ts`, for the hooks it hands each\n * agent's adapter. That is the process `loadPlugins` ran in\n * (`project-runtime.ts` → `plugin-loader.ts`), and plugin guardrails guard\n * what this runtime itself executes, exactly like every other\n * `AgentPlugin` hook, all of which the task and workflow runners consume.\n * - The HOOK routes do NOT — the two Claude Code PreToolUse bins and\n * `guard evaluate`. Those answer \"may this editor do this?\", and they have\n * to answer it identically or a project's rule means one thing in a Claude\n * Code session and another under `guard evaluate` (#316). Two of the three\n * CANNOT consult plugins at any price: they run on the lean bundle, which\n * deliberately excludes the project-manifest resolver, so the `plugins:`\n * list that `loadPlugins` needs is unreachable there — the shipped lean\n * bundle contains neither this class nor any `loadPlugins` or `register`\n * caller, so those processes hold no registry to consult at all. Feeding\n * the third one a source the other two structurally lack is what would\n * split the verdict; passing none keeps the three equal by construction\n * instead of by the accident of no project declaring a plugin.\n *\n * The closures consult `this.plugins` when a check runs, not when the source\n * is built. That is not a promise that a plugin registering later is picked\n * up: the caller asks `hasGuardrails()` first and never comes back for the\n * source when the answer was no, so a registration after that point reaches\n * no hooks. What holds instead is the order — `loadPlugins` runs once, while\n * `createProjectRuntime` builds the runtime, before anything can execute.\n */\n guardrailChecks(): GuardrailCheckFunctions {\n return {\n checkCommand: (command) => this.evaluateCommandGuardrails(command).map(toCheckResult),\n checkFilePath: (filePath) => this.evaluateFilePathGuardrails(filePath).map(toCheckResult),\n checkContent: (filePath, content) =>\n this.evaluateFileContentGuardrails(filePath, content).map(toCheckResult),\n };\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Candidate Agents — backend-neutral bridge for LLM-internal routing (model B)\n *\n * The runtime registers a set of *candidate sub-agents* with the SDK so the\n * entry/main agent's LLM can delegate to them internally via the SDK's native\n * subagent mechanism:\n *\n * - Claude `Options.agents: Record<string, AgentDefinition>`\n * - OpenAI `Agent.handoffs: Agent[]`\n * - ADK `LlmAgent.subAgents: BaseAgent[]`\n *\n * `CandidateAgent` is the common, SDK-independent contract. Each adapter maps it\n * onto its provider's native shape. The selection rule (which agents become\n * candidates) lives here so all adapters stay backend-agnostic.\n */\n\nimport type { AgentContractLike } from \"./task-runner.js\";\n\n/**\n * SDK-independent description of a sub-agent the entry agent's LLM may delegate\n * to. Adapters translate this into their provider's native subagent shape.\n */\nexport interface CandidateAgent {\n /** Agent id (used as the SDK subagent key / name). */\n name: string;\n /** When to use this agent — the routing hint shown to the delegating LLM. */\n description: string;\n /** The agent's system prompt — everything the DSL declares about its work. */\n prompt: string;\n /** Optional allowed tool names (omit to inherit from the parent agent). */\n tools?: string[];\n /** Optional model id (omit to inherit from the parent agent). */\n model?: string;\n}\n\n/**\n * Render an agent contract into its system-prompt string: everything the DSL\n * declares about how the agent must work.\n *\n * The ONE renderer of a declared agent for every Claude surface — the in-process\n * system prompt (`buildSplitTaskPrompt`), the SDK candidate agents\n * (`buildCandidateAgents`), and the Claude Code subagent body\n * (`claude-materialize/agent-render.ts`) — so one DSL agent cannot be described\n * differently depending on which of them a prompt came through.\n *\n * That is also why the sections below are not a subset. It rendered role,\n * responsibilities, constraints and rules and stopped there, so an agent's\n * anti-patterns, escalation criteria, authority boundaries, audit checklist and\n * prose sections reached no Claude surface at all while the Cursor binding\n * rendered every one of them: the dev-team architect's \"issue-fix AC Derivation\"\n * procedure was in the Cursor prompt and in no Claude prompt (#349). Nothing\n * failed — a prompt that is missing an instruction is still a valid prompt.\n *\n * Permissions are NOT here: they are the file-form's `permissionSections`, which\n * an agent receiving only its own `.claude/agents/*.md` needs and an in-process\n * agent has enforced around it by the runtime.\n */\nexport function renderAgentSystemPrompt(agent: AgentContractLike): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.rules && agent.rules.length > 0) {\n const ruleLines = agent.rules.map(\n (r) => `- **${r.id}** [${r.severity}]: ${r.description}`,\n );\n sections.push(`## Rules\\n\\n${ruleLines.join(\"\\n\")}`);\n }\n\n if (agent.anti_patterns && agent.anti_patterns.length > 0) {\n sections.push(\n `## Anti-patterns\\n\\n${agent.anti_patterns.map((a) => `- ${a}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.escalation_criteria && agent.escalation_criteria.length > 0) {\n const lines = agent.escalation_criteria.map((e) => `- **${e.condition}** → ${e.action}`);\n sections.push(`## Escalation Criteria\\n\\n${lines.join(\"\\n\")}`);\n }\n\n // Either half on its own is a boundary worth stating, so the section appears\n // when the DSL declared the field with anything in it.\n const canDecide = agent.authority?.can_decide ?? [];\n const cannotDecide = agent.authority?.cannot_decide ?? [];\n if (canDecide.length > 0 || cannotDecide.length > 0) {\n const lines: string[] = [];\n if (canDecide.length > 0) lines.push(`- **Can decide**: ${canDecide.join(\", \")}`);\n if (cannotDecide.length > 0) lines.push(`- **Cannot decide**: ${cannotDecide.join(\", \")}`);\n sections.push(`## Authority Boundaries\\n\\n${lines.join(\"\\n\")}`);\n }\n\n if (agent.audit_checklist && agent.audit_checklist.length > 0) {\n const groups = agent.audit_checklist.map(\n (group) => `### ${group.section}\\n\\n${group.checks.map((c) => `- [ ] ${c}`).join(\"\\n\")}`,\n );\n sections.push(`## Audit Checklist\\n\\n${groups.join(\"\\n\\n\")}`);\n }\n\n // Last, as the DSL orders them: a section carries the agent's own prose, often\n // a multi-step procedure, and it reads as a continuation of the terse\n // declarations above rather than an interruption of them.\n for (const section of agent.sections ?? []) {\n sections.push(`## ${section.title}\\n\\n${section.content}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Derive a concise routing description (first sentence/line) from a purpose. */\nfunction deriveDescription(purpose: string): string {\n const firstLine = purpose.split(\"\\n\").map((l) => l.trim()).find((l) => l.length > 0) ?? \"\";\n // Prefer the first sentence when the line packs several together.\n const sentenceEnd = firstLine.search(/[.!?](\\s|$)/);\n if (sentenceEnd !== -1) {\n return firstLine.slice(0, sentenceEnd + 1).trim();\n }\n return firstLine;\n}\n\nexport interface BuildCandidateAgentsOptions {\n /** The entry/main agent id. Excluded from the candidate set. */\n entryAgentId?: string;\n /**\n * When provided (typically the entry agent's `can_invoke_agents`), restrict\n * candidates to these agent ids. Omit to allow every non-entry agent.\n */\n allowedAgentIds?: readonly string[];\n /**\n * Each agent's effective tool grant — `ComponentScope.toolsByAgent`\n * (component-scope.ts), the one place `tools[*].invokable_by`,\n * `agents[*].can_execute_tools` and the toolchains derived for the agent are\n * resolved into names. Read, not recomputed: this function used to merge\n * `can_execute_tools` with the derived toolchain ids itself, which is the\n * same statement in a second place — and the two read `can_execute_tools` in\n * different namespaces until #337 made them agree. An agent absent from the\n * map gets no `tools`, i.e. inherits the parent agent's.\n */\n toolsByAgent?: Map<string, string[]>;\n}\n\n/**\n * Build the candidate sub-agent set from an agent registry.\n *\n * Selection rule: every agent EXCEPT the entry agent; if `allowedAgentIds` is\n * given, further restrict to that allow-list.\n */\nexport function buildCandidateAgents(\n agentRegistry: Record<string, AgentContractLike>,\n opts?: BuildCandidateAgentsOptions,\n): CandidateAgent[] {\n const entryId = opts?.entryAgentId;\n const allowed = opts?.allowedAgentIds;\n const allowSet = allowed ? new Set(allowed) : undefined;\n\n const candidates: CandidateAgent[] = [];\n for (const [id, agent] of Object.entries(agentRegistry)) {\n if (id === entryId) continue;\n if (allowSet && !allowSet.has(id)) continue;\n\n const agentTools = opts?.toolsByAgent?.get(id) ?? [];\n\n candidates.push({\n name: id,\n description: deriveDescription(agent.purpose),\n prompt: renderAgentSystemPrompt(agent),\n ...(agentTools.length > 0 ? { tools: agentTools } : {}),\n });\n }\n return candidates;\n}\n","/**\n * Model pricing table for cost_usd computation (#210).\n *\n * Prices are USD per 1M tokens. Unknown models fail open (return undefined).\n */\n\nexport interface ModelPricing {\n inputPerMillion: number;\n outputPerMillion: number;\n}\n\n/** Normalise model id for lookup (strip provider prefixes / version suffixes). */\nexport function normalizeModelId(model: string): string {\n return model.trim().toLowerCase();\n}\n\nconst PRICING_TABLE: Record<string, ModelPricing> = {\n // Anthropic Claude\n \"claude-opus-4-6\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-opus-4\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-sonnet-4\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-sonnet-4-6\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-haiku-4\": { inputPerMillion: 0.8, outputPerMillion: 4 },\n // OpenAI GPT\n \"gpt-5.5\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-5.3-codex\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4.1\": { inputPerMillion: 2, outputPerMillion: 8 },\n \"gpt-4o\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4o-mini\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n // Google Gemini\n \"gemini-2.5-pro\": { inputPerMillion: 1.25, outputPerMillion: 10 },\n \"gemini-2.5-flash\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n \"gemini-2.0-flash\": { inputPerMillion: 0.1, outputPerMillion: 0.4 },\n};\n\nexport function resolveModelPricing(model: string | undefined): ModelPricing | undefined {\n if (!model) return undefined;\n const key = normalizeModelId(model);\n if (PRICING_TABLE[key]) return PRICING_TABLE[key];\n // Prefix match for versioned ids (e.g. claude-sonnet-4-20250514)\n for (const [known, pricing] of Object.entries(PRICING_TABLE)) {\n if (key.startsWith(known)) return pricing;\n }\n return undefined;\n}\n\nexport function computeCostUsd(\n model: string | undefined,\n inputTokens: number,\n outputTokens: number,\n): number | undefined {\n const pricing = resolveModelPricing(model);\n if (!pricing) return undefined;\n if (inputTokens <= 0 && outputTokens <= 0) return undefined;\n const cost =\n (inputTokens * pricing.inputPerMillion + outputTokens * pricing.outputPerMillion) /\n 1_000_000;\n return Math.round(cost * 1_000_000) / 1_000_000;\n}\n","/**\n * Process axis emit helpers for runtime integration.\n * These wrap @aaac/observability's EventCollector for structured process axis events.\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { AttrValue } from \"@aaac/observability\";\nimport type { ObserverEmitFn } from \"./observability-bridge.js\";\n\nexport interface ProcessWorkflowOptions {\n workflowId: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessTaskOptions {\n taskId: string;\n targetAgent: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessEditOptions {\n filePath: string;\n artifactId?: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\n/** Build attribute record; omits keys with undefined/empty-string values. */\nfunction attrs(base: Record<string, AttrValue | undefined>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && v !== \"\") out[k] = v;\n }\n return out;\n}\n\n/**\n * Tool names that mutate files on disk and therefore should produce a\n * process.edit event for cross-axis correlation (enrich R3/R5).\n *\n * Read/search/shell tools are intentionally excluded — only file writes count\n * as edits. Matched case-insensitively so adapter-specific casing variants\n * (Write/write, MultiEdit/multi_edit) are all recognised.\n */\nconst FILE_EDIT_TOOL_NAMES = new Set([\n \"write\",\n \"edit\",\n \"multiedit\",\n \"multi_edit\",\n \"notebookedit\",\n \"notebook_edit\",\n]);\n\n/**\n * True when a tool name denotes a file-mutating edit, so a process.edit event\n * should be emitted for it. Used by the task runner to instrument the Process\n * axis from live tool-use progress events (#167).\n */\nexport function isFileEditTool(toolName: string | undefined): boolean {\n if (!toolName) return false;\n return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());\n}\n\n/**\n * Emit process.workflow open span.\n */\nexport function emitProcessWorkflowOpen(options: ProcessWorkflowOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"workflow.id\": options.workflowId,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.workflow close span.\n */\nexport function emitProcessWorkflowClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"workflow.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"workflow.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.task open span.\n */\nexport function emitProcessTaskOpen(options: ProcessTaskOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"task.id\": options.taskId,\n \"task.type\": \"implement\",\n \"task.target_agent\": options.targetAgent,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.task close span.\n */\nexport function emitProcessTaskClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"task.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"task.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.edit instant span.\n */\nexport function emitProcessEdit(options: ProcessEditOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.edit\",\n lifecycle: \"instant\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"edit.path\": options.filePath,\n \"edit.artifact_id\": options.artifactId,\n }),\n });\n return spanId;\n}\n","/**\n * Toolchain Checker — runs check commands defined in toolchain-contracts\n * and returns structured pass/fail results.\n *\n * Each toolchain may declare a `checks` map (checkType → shell command).\n * This module iterates all checks, executes them via subprocess, and\n * returns a ToolchainCheckResult[].\n *\n * For \"drift\" check types, a manifest-based fast path is available:\n * if a .toolchain-manifest.json exists and the toolchain_id matches,\n * the command execution can be skipped when the source hash is current.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { parseToolchainFile } from \"@aaac/toolchain\";\nimport {\n emitToolchainOpen,\n emitToolchainClose,\n buildObservabilityEnv,\n type ObserverEmitFn,\n type ObservabilityIds,\n} from \"./observability-bridge.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst SUBPROCESS_TIMEOUT_MS = 30_000;\nconst MANIFEST_FILENAME = \".toolchain-manifest.json\";\n\n// ---------------------------------------------------------------------------\n// Manifest schema (Phase 7 full validation; schema + read logic placed here)\n// ---------------------------------------------------------------------------\n\nexport const ToolchainManifestSchema = z.object({\n schema: z.string(),\n toolchain_id: z.string(),\n generated_at: z.string(),\n source_hash: z.string(),\n output_hash: z.string(),\n source_globs: z.array(z.string()).optional(),\n output_globs: z.array(z.string()).optional(),\n files: z\n .array(\n z.object({\n path: z.string(),\n hash: z.string(),\n }),\n )\n .optional(),\n});\n\nexport type ToolchainManifest = z.infer<typeof ToolchainManifestSchema>;\n\n// ---------------------------------------------------------------------------\n// Check result types\n// ---------------------------------------------------------------------------\n\nexport interface ToolchainCheckResult {\n toolchainId: string;\n checkType: string;\n status: \"pass\" | \"fail\" | \"skip\" | \"error\";\n action: \"block\" | \"warn\" | \"shadow\";\n message?: string;\n durationMs?: number;\n}\n\nexport interface RunToolchainChecksOptions {\n /** Absolute path to toolchain-contracts YAML */\n toolchainsPath: string;\n /** Absolute path to artifact-contracts YAML (optional, for manifest fast path) */\n artifactsPath?: string;\n /** Working directory for subprocess execution */\n cwd?: string;\n /** Filter: only run these check types */\n checkTypes?: string[];\n /** Filter: only run checks for these toolchain IDs */\n toolchainFilter?: string[];\n /** Policy-resolved action per check type. Key = check type, value = action. Special key \"_default\" for fallback. */\n checkTypeActions?: Record<string, \"block\" | \"warn\" | \"shadow\">;\n /** Default action when no policy match */\n defaultAction?: \"block\" | \"warn\" | \"shadow\";\n /**\n * Optional observer emit function. When provided, each check execution emits a\n * toolchain.execution span (open before the check, close after) so the check is\n * recorded on the agent axis. No-op when undefined (observer is optional).\n * This is OBSERVATION ONLY — emitting spans never alters the returned results\n * nor the resolved action, so workflow success/failure semantics are unchanged.\n */\n observer?: ObserverEmitFn;\n /** Parent span id (typically the enclosing agent.session run_id) for correlation. */\n parentSpanId?: string;\n /** Component id recorded on toolchain.execution spans (agent.component_id). */\n componentId?: string;\n /**\n * Observability correlation ids propagated to spawned check subprocesses as\n * AAAC_SESSION_ID / AAAC_TRACE_ID / AAAC_RUN_ID (#115). A check that spawns\n * `git commit`/`git push` lets the resulting git `post-commit` hook attribute\n * its promotion.* events back to this session. No-op when undefined.\n */\n observabilityIds?: ObservabilityIds;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveAction(\n checkType: string,\n checkTypeActions?: Record<string, \"block\" | \"warn\" | \"shadow\">,\n defaultAction?: \"block\" | \"warn\" | \"shadow\",\n): \"block\" | \"warn\" | \"shadow\" {\n if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];\n if (checkTypeActions?.[\"_default\"]) return checkTypeActions[\"_default\"];\n return defaultAction ?? \"warn\";\n}\n\nasync function tryManifestFastPath(\n toolchainId: string,\n cwd: string,\n): Promise<ToolchainCheckResult | null> {\n const manifestPath = resolve(cwd, MANIFEST_FILENAME);\n if (!existsSync(manifestPath)) return null;\n\n try {\n const raw = await readFile(manifestPath, \"utf-8\");\n const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));\n\n if (parsed.toolchain_id !== toolchainId) return null;\n\n // Manifest found and toolchain_id matches — Phase 7 will add full\n // hash comparison; for now we treat a matching manifest as a pass.\n return {\n toolchainId,\n checkType: \"drift\",\n status: \"pass\",\n action: \"warn\",\n message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,\n durationMs: 0,\n };\n } catch {\n return null;\n }\n}\n\nasync function executeCheck(\n command: string,\n cwd: string,\n observabilityIds?: ObservabilityIds,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n const env = observabilityIds\n ? buildObservabilityEnv(observabilityIds)\n : undefined;\n try {\n const { stdout, stderr } = await execFileAsync(\"sh\", [\"-c\", command], {\n cwd,\n timeout: SUBPROCESS_TIMEOUT_MS,\n ...(env ? { env } : {}),\n });\n return { exitCode: 0, stdout, stderr };\n } catch (err: unknown) {\n const execErr = err as { code?: number | string; killed?: boolean; stdout?: string; stderr?: string };\n if (execErr.killed) {\n throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);\n }\n const exitCode = typeof execErr.code === \"number\" ? execErr.code : 1;\n return {\n exitCode,\n stdout: execErr.stdout ?? \"\",\n stderr: execErr.stderr ?? \"\",\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main entry\n// ---------------------------------------------------------------------------\n\nexport async function runToolchainChecks(\n options: RunToolchainChecksOptions,\n): Promise<ToolchainCheckResult[]> {\n const {\n toolchainsPath,\n cwd: workingDir,\n checkTypes,\n toolchainFilter,\n checkTypeActions,\n defaultAction,\n observer,\n parentSpanId,\n componentId,\n observabilityIds,\n } = options;\n\n const cwd = workingDir ?? process.cwd();\n const contracts = await parseToolchainFile(toolchainsPath);\n const results: ToolchainCheckResult[] = [];\n\n for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {\n if (!toolchain.checks) continue;\n if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;\n\n for (const [checkType, command] of Object.entries(toolchain.checks)) {\n if (checkTypes && !checkTypes.includes(checkType)) continue;\n\n const action = resolveAction(checkType, checkTypeActions, defaultAction);\n const start = performance.now();\n\n // ── toolchain.execution open ────────────────────────────────────────\n // Open the span BEFORE running the check so the close span's duration\n // reflects real wall-clock time. No-op when observer is undefined.\n const spanId = emitToolchainOpen(\n observer,\n parentSpanId,\n toolchainId,\n checkType,\n [],\n componentId,\n );\n\n let result: ToolchainCheckResult;\n\n // Drift fast path via manifest\n const fastResult =\n checkType === \"drift\" && options.artifactsPath\n ? await tryManifestFastPath(toolchainId, cwd)\n : null;\n\n if (fastResult) {\n fastResult.action = action;\n result = fastResult;\n } else {\n try {\n const { exitCode, stderr } = await executeCheck(command, cwd, observabilityIds);\n const durationMs = Math.round(performance.now() - start);\n result = {\n toolchainId,\n checkType,\n status: exitCode === 0 ? \"pass\" : \"fail\",\n action,\n message: exitCode === 0 ? undefined : stderr.trim() || `exit code ${exitCode}`,\n durationMs,\n };\n } catch (err) {\n const durationMs = Math.round(performance.now() - start);\n result = {\n toolchainId,\n checkType,\n status: \"error\",\n action,\n message: (err as Error).message,\n durationMs,\n };\n }\n }\n\n results.push(result);\n\n // ── toolchain.execution close ───────────────────────────────────────\n // Status is derived from the check result: pass → success, otherwise\n // failure (carrying the message). The action (\"block\"/\"warn\"/\"shadow\")\n // is recorded as data only and never gates the workflow here.\n emitToolchainClose(\n observer,\n spanId ?? \"\",\n toolchainId,\n checkType,\n result.durationMs ?? Math.round(performance.now() - start),\n result.status === \"pass\" ? \"success\" : \"failure\",\n result.status === \"pass\" ? undefined : result.message,\n );\n }\n }\n\n return results;\n}\n","/**\n * Virtual workflow entry step — materializes WorkflowInvocation input as a\n * DAG-addressable output so downstream steps can use depends_on / receives.\n */\n\n/** Step id referenced in workflow DSL depends_on / receives.from. */\nexport const WORKFLOW_INPUT_STEP_ID = \"workflow-input\";\n\nexport interface WorkflowInputHandoff {\n readonly type: string;\n readonly version?: number;\n readonly payload: unknown;\n}\n\nexport interface WorkflowInputOutput {\n readonly user_request: string;\n readonly handoff?: WorkflowInputHandoff;\n}\n\nexport function buildWorkflowInputOutput(\n userRequest: string,\n handoff?: WorkflowInputHandoff,\n): WorkflowInputOutput {\n return {\n user_request: userRequest,\n ...(handoff\n ? {\n handoff: {\n type: handoff.type,\n ...(handoff.version !== undefined ? { version: handoff.version } : {}),\n payload: handoff.payload,\n },\n }\n : {}),\n };\n}\n\nexport function stepDependsOnWorkflowInput(\n dependsOn: readonly string[] | undefined,\n): boolean {\n return dependsOn?.includes(WORKFLOW_INPUT_STEP_ID) ?? false;\n}\n\nexport function formatWorkflowInputContext(output: WorkflowInputOutput): string {\n return `\\n\\n--- Step: ${WORKFLOW_INPUT_STEP_ID} ---\\n${JSON.stringify(output, null, 2)}`;\n}\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike, type TokenUsage } from \"./task-runner.js\";\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport type { ModelClass, ResolvedModel } from \"./model-resolver.js\";\nimport type { z } from \"zod\";\nimport {\n createExecutionEnvelope,\n emitSessionOpen,\n emitSessionClose,\n emitIterationOpen,\n emitIterationClose,\n emitIterationMetric,\n type ObserverEmitFn,\n} from \"./observability-bridge.js\";\nimport { computeCostUsd } from \"./model-pricing.js\";\nimport { runToolchainChecks, type RunToolchainChecksOptions } from \"./toolchain-checker.js\";\nimport {\n WORKFLOW_INPUT_STEP_ID,\n buildWorkflowInputOutput,\n formatWorkflowInputContext,\n stepDependsOnWorkflowInput,\n type WorkflowInputOutput,\n} from \"./workflow-input.js\";\n\nexport type { ObserverEmitFn } from \"./observability-bridge.js\";\n\n// ---------------------------------------------------------------------------\n// Adapter factory — enables true parallelism with stateful adapters\n// ---------------------------------------------------------------------------\n\n/**\n * A factory that creates independent SdkAdapter instances.\n * Used by runWorkflow to allocate one adapter per parallel step,\n * avoiding session-level serialization in stateful SDK adapters.\n */\nexport type SdkAdapterFactory = () => SdkAdapter;\n\n/**\n * Model-aware adapter factory. Accepts a model_class and returns an adapter\n * configured for that capability level (possibly a different provider/model).\n */\nexport type ModelAwareSdkAdapterFactory = (\n modelClass?: ModelClass,\n /**\n * Agent the step runs as (a task's `target_agent`). Guardrail hooks are fixed at\n * adapter construction, so an agent-scoped factory returns a distinct adapter per\n * agent (#269). Ignored by factories that do not scope guardrails.\n */\n agentId?: string,\n) => SdkAdapter | Promise<SdkAdapter>;\n\n/** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */\nexport type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;\n\nfunction isAdapterFactory(v: AdapterOrFactory): v is SdkAdapterFactory | ModelAwareSdkAdapterFactory {\n return typeof v === \"function\" && !(\"send\" in v);\n}\n\nfunction resolveAdapter(adapterOrFactory: AdapterOrFactory): { adapter: SdkAdapter; factory: (SdkAdapterFactory | ModelAwareSdkAdapterFactory) | undefined } {\n if (isAdapterFactory(adapterOrFactory)) {\n const result = adapterOrFactory();\n if (result && typeof (result as Promise<SdkAdapter>).then === \"function\") {\n throw new Error(\"ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.\");\n }\n return { adapter: result as SdkAdapter, factory: adapterOrFactory };\n }\n return { adapter: adapterOrFactory, factory: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\n/** Specification for what a step receives from a dependency. */\nexport interface ReceiveSpec {\n /** The task id of the dependency step to receive from. If omitted, alias is used as task id. */\n readonly from?: string;\n /** JSONPath-like dotted path to extract from the step result (e.g. \"$.changed_files\"). Simplified: just use dot notation like \"changed_files\" or \"checks_performed\". If omitted, entire result is received. */\n readonly path?: string;\n}\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly depends_on?: readonly string[];\n readonly instruction?: string;\n readonly receives?: Record<string, ReceiveSpec>;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n readonly depends_on?: readonly string[];\n}\n\n/**\n * Evaluate step — runs a task that returns a convergence-envelope, then either\n * proceeds (verdict=pass) or loops back to `loop_to` with feedback injected\n * (verdict=fail, iteration < max_iterations), or applies `on_exhausted`.\n */\nexport interface EvaluateStep {\n readonly type: \"evaluate\";\n readonly task: string;\n readonly from_agent: string;\n readonly evaluator_agent?: string;\n readonly description?: string;\n readonly loop_to: string;\n readonly max_iterations: number;\n readonly inject_as?: string;\n readonly on_exhausted?: \"abort\" | \"fail_partial\" | \"escalate\";\n readonly depends_on?: readonly string[];\n}\n\n/**\n * Payload returned by an evaluate task in a convergence-envelope handoff.\n * The runtime reads `verdict` to decide whether to proceed or loop back.\n */\nexport interface ConvergenceEnvelopePayload {\n /** \"pass\" means quality gate passed; \"fail\" triggers a loop-back. */\n readonly verdict: \"pass\" | \"fail\";\n /** Human-readable feedback injected into the next iteration via `inject_as`. */\n readonly feedback?: string;\n}\n\n/** Typed handoff envelope produced by an evaluate task. */\nexport type ConvergenceEnvelope = HandoffInput<\"convergence-envelope\", ConvergenceEnvelopePayload>;\n\nexport type WorkflowStep = DelegateStep | GateStep | EvaluateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n /** Variables propagated to every TaskContext in the workflow (from WorkflowInvocation.context). */\n variables?: Record<string, unknown>;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n /**\n * Writable stream for real-time progress output during agent execution.\n * Intermediate events from adapters are formatted and written here.\n * Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n /**\n * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Optional toolchain-check observation config. When set together with `observer`,\n * runWorkflow runs the configured toolchain checks AFTER the workflow body (a\n * single post-run observation pass) and emits one toolchain.execution span per\n * check, correlated to this run's agent.session span.\n *\n * OBSERVATION ONLY (non-destructive): the checks never alter the WorkflowResult\n * — a failing check does not fail the workflow. `observer` and `parentSpanId`\n * are injected by runWorkflow; callers supply `toolchainsPath` (+ optional\n * artifactsPath/cwd/policy actions).\n */\n toolchain?: RunToolchainChecksOptions;\n /**\n * In-process library tools to register with every task in this workflow.\n * Passed through to each runTask() call. Adapters convert these to their\n * native tool format (Claude MCP, OpenAI function tools, ADK tools).\n */\n libraryTools?: LibraryToolRegistry;\n /**\n * Each agent's effective tool grant — the executing component's\n * `ComponentScope.toolsByAgent` (#338). Passed through to each runTask()\n * call, which is where an agent's candidate tool list is built.\n */\n toolsByAgent?: Map<string, string[]>;\n /**\n * Resolves adapter + model for execution envelopes (agent.session / agent.subagent).\n * When undefined, envelopes omit adapter/model (observer spans lack gen_ai attrs).\n */\n resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;\n /**\n * Request each step's adapter from the factory scoped to the step's agent, so\n * per-agent guardrails apply to the agent actually doing the work (#269). Set\n * by executeWorkflow when the run has ANY guardrail to enforce — the rules a\n * binding resolved per agent, or the process's plugin guardrails, which are\n * the same for every agent yet reach a step's adapter only through this\n * scoping (#332). Without it, adapters are shared exactly as before.\n */\n perAgentAdapters?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (openaiThreadId,\n * sessionId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n /**\n * Writable stream for real-time progress output during agent execution.\n * Intermediate events from adapters are formatted and written here.\n * Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n\n /**\n * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Optional toolchain-check observation config (see WorkflowRunOptions.toolchain).\n * OBSERVATION ONLY — never changes the workflow outcome.\n */\n toolchain?: RunToolchainChecksOptions;\n /**\n * In-process library tools to register with every task in this workflow.\n * Created once per execution and shared across all steps.\n */\n libraryTools?: LibraryToolRegistry;\n /** See WorkflowRunOptions.toolsByAgent (#338). Injected by executeWorkflow. */\n toolsByAgent?: Map<string, string[]>;\n /**\n * Resolves adapter + model for execution envelopes. Injected by executeWorkflow;\n * not typically set by external callers.\n */\n resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;\n /** See WorkflowRunOptions.perAgentAdapters (#269). Injected by executeWorkflow. */\n perAgentAdapters?: boolean;\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n /** Resolved model_class for delegate/evaluate steps (from task registry). */\n model_class?: ModelClass;\n /** Concrete adapter name used for this step's LLM calls. */\n adapter?: string;\n /** Concrete model name used for this step's LLM calls. */\n model?: string;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\" | \"evaluate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n const ctx = invocation.context;\n const variables: Record<string, unknown> = { ...ctx?.variables };\n if (ctx?.cwd) variables.cwd = ctx.cwd;\n if (ctx?.environment) variables.environment = ctx.environment;\n if (ctx?.artifacts) variables.artifacts = ctx.artifacts;\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n variables: Object.keys(variables).length > 0 ? variables : undefined,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n progressOutput: invocation.progressOutput,\n observer: invocation.observer,\n toolchain: invocation.toolchain,\n libraryTools: invocation.libraryTools,\n toolsByAgent: invocation.toolsByAgent,\n resolveModelMeta: invocation.resolveModelMeta,\n perAgentAdapters: invocation.perAgentAdapters,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: AdapterOrFactory,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: AdapterOrFactory,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapterOrFactory: AdapterOrFactory,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(adapterOrFactory);\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n // ── ExecutionEnvelope + agent.session open (Phase 1-1, 1-3) ────────────────\n // Create a standard envelope for this workflow session. run_id is a UUIDv7.\n // The sessionSpanId is used as parentSpanId for child agent.subagent spans.\n // Resolve session-open meta as the \"standard\" model class (NOT undefined).\n // resolve(undefined) short-circuits to the bare fallback and never consults\n // env / model_mapping, so the open span dropped gen_ai.request.model (and\n // gen_ai.system) whenever fallbackModel was unset (e.g. --adapter mock / no\n // --model). Using \"standard\" mirrors how subagent spans resolve their meta\n // (workflow-runner passes the step's model_class), keeping the session open\n // span's model/adapter consistent with the standard model_mapping entry. (#166)\n const sessionMeta = options.resolveModelMeta?.(\"standard\");\n const sessionEnvelope = createExecutionEnvelope({\n componentId: workflowId,\n adapter: sessionMeta?.adapter,\n model: sessionMeta?.model,\n });\n const sessionSpanId = emitSessionOpen(options.observer, sessionEnvelope, workflowId);\n\n const workflowStart = Date.now();\n\n // ── Exception-safe session lifecycle ───────────────────────────────────────\n // The workflow body can throw (e.g. an invalid depends_on graph) AFTER the\n // agent.session open span has been emitted. Wrap the body in try/finally so\n // the close span is ALWAYS emitted — on success, on a returned failure\n // (escalated/error) AND on a thrown exception — leaving no span stuck 'open'.\n // (The body retains its original indentation; only the try/finally frame is new.)\n let wfResult: WorkflowResult | undefined;\n let sessionError: Error | undefined;\n\n // Token usage accumulation across all steps (declared outside try so finally can read)\n const tokenAccumulator: TokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n let hasTokenData = false;\n\n try {\n\n // Build step identity map: step index → task ID (delegate) or gate_kind (gate)\n const stepId = (i: number): string => {\n const s = workflow.steps[i];\n if (s.type === \"delegate\" || s.type === \"evaluate\") return s.task;\n return `gate:${s.gate_kind}`;\n };\n\n // Resolve depends_on: if specified (even as empty array) use it, otherwise depend on all preceding steps.\n // WORKFLOW_INPUT_STEP_ID is a virtual entry node — always satisfied, not a workflow step index.\n const workflowInputOutput: WorkflowInputOutput = buildWorkflowInputOutput(\n options.user_request,\n invocationHandoff,\n );\n\n const depsByIndex: number[][] = workflow.steps.map((step, i) => {\n if (step.depends_on !== undefined) {\n return step.depends_on\n .filter((dep) => dep !== WORKFLOW_INPUT_STEP_ID)\n .map((dep) => {\n const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);\n if (idx === -1) {\n throw new Error(`depends_on \"${dep}\" in step ${i} (${stepId(i)}) not found among preceding steps`);\n }\n return idx;\n });\n }\n // Default: depend on all preceding steps (preserves sequential behaviour)\n return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);\n });\n\n // DAG scheduler state\n const completed = new Set<number>();\n const stepResults: StepResult[] = new Array(workflow.steps.length);\n const stepContexts: string[] = new Array(workflow.steps.length).fill(\"\");\n const stepOutputs: Array<unknown> = new Array(workflow.steps.length).fill(undefined);\n let abortResult: WorkflowResult | undefined;\n\n // Evaluate-step loop state\n /** Tracks how many times each evaluate step (by index) has executed so far. */\n const evaluateExecCount = new Map<number, number>();\n /** Tracks the current iteration span ID per evaluate step index. */\n const iterationSpanIds = new Map<number, string>();\n /**\n * Variables injected by evaluate steps via `inject_as`.\n * Merged into every subsequent step's TaskContext.variables on loop-back.\n */\n const loopInjectedVars: Record<string, unknown> = {};\n\n /** Extract a dotted path from a structured object. */\n function extractPath(obj: unknown, path: string): unknown {\n const cleanPath = path.startsWith(\"$.\") ? path.slice(2) : path;\n const segments = cleanPath.split(\".\");\n let current: unknown = obj;\n for (const seg of segments) {\n if (current == null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[seg];\n }\n return current;\n }\n\n /** Build typed handoff input from receives declarations. */\n function projectHandoffs(\n stepIndex: number,\n step: DelegateStep,\n ): Record<string, unknown> | undefined {\n if (!step.receives) return undefined;\n\n const projected: Record<string, unknown> = {};\n\n for (const [alias, spec] of Object.entries(step.receives)) {\n const fromTaskId = spec.from ?? alias;\n\n if (fromTaskId === WORKFLOW_INPUT_STEP_ID) {\n if (spec.path) {\n projected[alias] = extractPath(workflowInputOutput, spec.path);\n } else {\n projected[alias] = workflowInputOutput;\n }\n continue;\n }\n\n const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);\n if (depIdx === -1) continue;\n\n const output = stepOutputs[depIdx];\n if (output === undefined) continue;\n\n if (spec.path) {\n projected[alias] = extractPath(output, spec.path);\n } else {\n projected[alias] = output;\n }\n }\n\n return Object.keys(projected).length > 0 ? projected : undefined;\n }\n\n /** Build accumulated context for a step from its dependency chain. */\n function contextFor(stepIndex: number): string {\n const step = workflow.steps[stepIndex];\n const parts: string[] = [];\n\n if (stepDependsOnWorkflowInput(step.depends_on)) {\n parts.push(formatWorkflowInputContext(workflowInputOutput));\n }\n\n const deps = depsByIndex[stepIndex];\n if (deps.length > 0) {\n parts.push(\n ...deps\n .filter((d) => completed.has(d))\n .map((d) => stepContexts[d])\n .filter(Boolean),\n );\n }\n\n return parts.join(\"\");\n }\n\n type StepResultWithTokens = StepResult & { tokenUsage?: TokenUsage };\n\n function stepModelFields(\n modelClass: ModelClass | undefined,\n envelopeMeta?: ResolvedModel,\n ): Pick<StepResult, \"model_class\" | \"adapter\" | \"model\"> {\n if (!modelClass && !envelopeMeta) return {};\n return {\n ...(modelClass ? { model_class: modelClass } : {}),\n ...(envelopeMeta?.adapter ? { adapter: envelopeMeta.adapter } : {}),\n ...(envelopeMeta?.model ? { model: envelopeMeta.model } : {}),\n };\n }\n\n /** Execute a single step (delegate or gate). */\n async function executeStep(\n i: number,\n stepAdapter: SdkAdapter,\n envelopeMeta?: ResolvedModel,\n modelClass?: ModelClass,\n ): Promise<StepResultWithTokens> {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);\n }\n\n // ── Evaluate step ────────────────────────────────────────────────────────\n if (step.type === \"evaluate\") {\n const evaluateStep = step as EvaluateStep;\n const iterationNumber = (evaluateExecCount.get(i) ?? 0) + 1;\n const iterationSpanId = emitIterationOpen(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n evaluateStep.loop_to,\n iterationNumber,\n evaluateStep.max_iterations,\n );\n if (iterationSpanId) {\n iterationSpanIds.set(i, iterationSpanId);\n }\n // Merge workflow variables with any loop-injected feedback variables\n const effectiveVariables = mergeVariables(options.variables, loopInjectedVars);\n const context: TaskContext = {\n user_request: evaluateStep.description ?? options.user_request,\n prior_context: contextFor(i),\n ...(effectiveVariables ? { variables: effectiveVariables } : {}),\n };\n const taskResult: TaskRunResult = await runTask(stepAdapter, evaluateStep.task, context, {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: 0, // evaluate steps do not retry\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n progressOutput: options.progressOutput,\n observer: options.observer,\n parentSpanId: iterationSpanId ?? sessionSpanId,\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n libraryTools: options.libraryTools,\n toolsByAgent: options.toolsByAgent,\n envelopeAdapter: envelopeMeta?.adapter,\n envelopeModel: envelopeMeta?.model,\n });\n return {\n step_index: i,\n task_id: evaluateStep.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n tokenUsage: taskResult.tokenUsage,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n\n const delegateStep = step as DelegateStep;\n\n // Optional steps\n if (step.optional) {\n const stepUserRequest = delegateStep.instruction ?? options.user_request;\n // Merge workflow variables with any loop-injected feedback variables\n const ctxVars = mergeVariables(options.variables, loopInjectedVars);\n const ctx: TaskContext = {\n user_request: stepUserRequest,\n prior_context: contextFor(i),\n ...(ctxVars ? { variables: ctxVars } : {}),\n };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n return {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n }\n\n // Execute task with followUp/retry recovery\n const stepUserRequest = delegateStep.instruction ?? options.user_request;\n\n let handoffInput: TaskContext[\"handoff_input\"] | undefined;\n const projected = projectHandoffs(i, delegateStep);\n if (projected) {\n handoffInput = {\n type: \"step-projection\",\n payload: projected,\n };\n } else if (i === 0 && invocationHandoff) {\n handoffInput = invocationHandoff;\n }\n\n const useLegacyContext = !delegateStep.receives;\n // Merge workflow variables with any loop-injected feedback variables\n const delegateVars = mergeVariables(options.variables, loopInjectedVars);\n\n const context: TaskContext = {\n user_request: stepUserRequest,\n ...(useLegacyContext ? { prior_context: contextFor(i) } : {}),\n ...(delegateVars ? { variables: delegateVars } : {}),\n ...(handoffInput ? { handoff_input: handoffInput } : {}),\n };\n const taskResult: TaskRunResult = await runTask(stepAdapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n progressOutput: options.progressOutput,\n observer: options.observer,\n parentSpanId: sessionSpanId,\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n libraryTools: options.libraryTools,\n toolsByAgent: options.toolsByAgent,\n envelopeAdapter: envelopeMeta?.adapter,\n envelopeModel: envelopeMeta?.model,\n });\n return {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n tokenUsage: taskResult.tokenUsage,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n\n // DAG execution loop: on each iteration, find all steps whose deps are satisfied\n // and run them concurrently.\n while (completed.size < workflow.steps.length) {\n const ready: number[] = [];\n for (let i = 0; i < workflow.steps.length; i++) {\n if (completed.has(i)) continue;\n if (depsByIndex[i].every((d) => completed.has(d))) {\n ready.push(i);\n }\n }\n\n if (ready.length === 0) {\n // Should not happen with valid DAG; safeguard against cycles\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: \"Dependency cycle detected: no steps are ready to execute\",\n };\n break;\n }\n\n const batchResults = await Promise.all(ready.map(async (i) => {\n const step = workflow.steps[i];\n const stepTask = (step.type === \"delegate\" || step.type === \"evaluate\")\n ? registries?.taskRegistry?.[step.task]\n : undefined;\n const modelClass = stepTask?.model_class as ModelClass | undefined;\n // The agent doing the work — the same one executeTask scopes guardrails to.\n const stepAgentId = options.perAgentAdapters ? stepTask?.target_agent : undefined;\n\n let stepAdapter: SdkAdapter;\n if (adapterFactory && (ready.length > 1 || modelClass || stepAgentId)) {\n const result = adapterFactory(modelClass, stepAgentId);\n stepAdapter = (result && typeof (result as Promise<SdkAdapter>).then === \"function\")\n ? await (result as Promise<SdkAdapter>)\n : result as SdkAdapter;\n } else {\n stepAdapter = primaryAdapter;\n }\n const envelopeMeta = options.resolveModelMeta?.(modelClass);\n return executeStep(i, stepAdapter, envelopeMeta, modelClass);\n }));\n\n for (let b = 0; b < ready.length; b++) {\n const i = ready[b];\n const result = batchResults[b];\n const step = workflow.steps[i];\n\n // Accumulate token usage from this step\n if (result.tokenUsage) {\n tokenAccumulator.inputTokens += result.tokenUsage.inputTokens;\n tokenAccumulator.outputTokens += result.tokenUsage.outputTokens;\n tokenAccumulator.totalTokens = (tokenAccumulator.totalTokens ?? 0) + (result.tokenUsage.totalTokens ?? 0);\n if (result.tokenUsage.cacheReadTokens) {\n tokenAccumulator.cacheReadTokens = (tokenAccumulator.cacheReadTokens ?? 0) + result.tokenUsage.cacheReadTokens;\n }\n if (result.tokenUsage.cacheCreationTokens) {\n tokenAccumulator.cacheCreationTokens = (tokenAccumulator.cacheCreationTokens ?? 0) + result.tokenUsage.cacheCreationTokens;\n }\n hasTokenData = true;\n }\n\n // ── Evaluate step post-processing ─────────────────────────────────────\n if (step.type === \"evaluate\") {\n const evaluateStep = step as EvaluateStep;\n\n // Extract verdict from the evaluate task's structured output\n const data = result.outcome.status === \"success\"\n ? (result.outcome as { status: \"success\"; data: unknown }).data as Record<string, unknown>\n : undefined;\n const verdict = (typeof data?.verdict === \"string\" ? data.verdict : \"fail\") as string;\n\n const execCount = (evaluateExecCount.get(i) ?? 0) + 1;\n\n // Close iteration span for this execution\n const currentIterationSpanId = iterationSpanIds.get(i);\n if (currentIterationSpanId) {\n const willLoopBack = verdict !== \"pass\" && execCount < evaluateStep.max_iterations;\n const feedbackInjected = willLoopBack && !!evaluateStep.inject_as;\n emitIterationClose(\n options.observer,\n currentIterationSpanId,\n evaluateStep.task,\n execCount,\n verdict,\n result.elapsed_ms,\n feedbackInjected,\n );\n iterationSpanIds.delete(i);\n }\n\n if (verdict === \"pass\") {\n // Quality gate passed — record result and proceed\n emitIterationMetric(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n execCount,\n \"pass\",\n );\n stepResults[i] = result;\n completed.add(i);\n emitStepEvent(options, workflow.id, i, step, result);\n if (data !== undefined) {\n stepOutputs[i] = data;\n stepContexts[i] = `\\n\\n--- Step ${i + 1}: ${stepId(i)} ---\\n${JSON.stringify(data, null, 2)}`;\n }\n } else if (execCount < evaluateStep.max_iterations) {\n // Quality gate failed but iterations remain — inject feedback and loop back\n evaluateExecCount.set(i, execCount);\n\n if (evaluateStep.inject_as) {\n const feedback = typeof data?.feedback === \"string\"\n ? data.feedback\n : (data !== undefined ? JSON.stringify(data) : \"Evaluate step returned no feedback\");\n loopInjectedVars[evaluateStep.inject_as] = feedback;\n }\n\n // Find the loop_to step (must precede this evaluate step)\n const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);\n if (loopToIdx === -1) {\n stepResults[i] = result;\n completed.add(i);\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: `Evaluate step \"${evaluateStep.task}\" references unknown loop_to \"${evaluateStep.loop_to}\"`,\n };\n } else {\n // Reset all steps in the loop range [loopToIdx, i] so they re-execute\n for (let k = loopToIdx; k <= i; k++) {\n completed.delete(k);\n stepOutputs[k] = undefined;\n stepContexts[k] = \"\";\n }\n // Evaluate step result is intermediate — do not persist it\n }\n } else {\n // Max iterations exhausted — apply on_exhausted policy\n evaluateExecCount.set(i, execCount);\n stepResults[i] = result;\n completed.add(i);\n\n const exhaustedPolicy = evaluateStep.on_exhausted ?? \"escalate\";\n emitIterationMetric(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n execCount,\n `exhausted-${exhaustedPolicy}`,\n );\n\n switch (exhaustedPolicy) {\n case \"abort\":\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: `Evaluate step \"${evaluateStep.task}\" exhausted ${evaluateStep.max_iterations} iterations without passing`,\n };\n break;\n case \"fail_partial\":\n // Degraded success — continue workflow without evaluate outputs\n emitStepEvent(options, workflow.id, i, step, result);\n break;\n case \"escalate\":\n default:\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Evaluate step \"${evaluateStep.task}\" exhausted ${evaluateStep.max_iterations} iterations without passing`,\n };\n break;\n }\n }\n continue; // Skip generic post-processing below\n }\n\n // ── Generic delegate / gate post-processing ───────────────────────────\n stepResults[i] = result;\n completed.add(i);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Store context fragment and structured output for dependants\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n stepOutputs[i] = data;\n stepContexts[i] = `\\n\\n--- Step ${i + 1}: ${stepId(i)} ---\\n` +\n (typeof data === \"string\" ? data : JSON.stringify(data, null, 2));\n }\n\n // Abort-worthy outcomes\n if (result.outcome.status === \"gate_rejected\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n };\n } else if (result.outcome.status === \"escalation\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n } else if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const taskId = step.type === \"delegate\" ? step.task : (step as GateStep).gate_kind;\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${taskId}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n }\n }\n\n if (abortResult) break;\n }\n\n wfResult = abortResult ?? {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n\n // ── toolchain.execution observation pass (post-run, non-destructive) ───────\n // Integration point: a single observation pass AFTER the workflow body, rather\n // than per-step. Rationale — toolchain checks (lint/format/drift) inspect the\n // artifacts a run produced, so the natural correlation is the run as a whole;\n // running once post-body keeps the spans children of the still-open session and\n // avoids coupling toolchain config to individual step semantics. The observer\n // and parent span are injected here so checks emit toolchain.execution spans\n // correlated to this session. Wrapped in its own try/catch so a toolchain or\n // subprocess failure can NEVER change the workflow outcome (observation only).\n if (options.toolchain && options.observer) {\n try {\n await runToolchainChecks({\n ...options.toolchain,\n observer: options.observer,\n parentSpanId: sessionSpanId,\n // Propagate session correlation to any git spawned by a check (#115):\n // the session id is the agent.session run_id (== sessionSpanId).\n observabilityIds: {\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n runId: sessionEnvelope.run_id,\n },\n });\n } catch {\n // Observation must never affect the workflow result — swallow.\n }\n }\n\n return wfResult;\n } catch (err) {\n sessionError = err as Error;\n throw err;\n } finally {\n // ── agent.session close (Phase 1-3) ──────────────────────────────────────\n // Emit close span for the workflow session on EVERY exit path. No-op when\n // observer is undefined. On a thrown exception wfResult is undefined → the\n // status is recorded as 'error' with the cause in `agent.error`.\n if (sessionSpanId) {\n const durationMs = wfResult?.total_elapsed_ms ?? (Date.now() - workflowStart);\n sessionEnvelope.execution_metadata = {\n duration_ms: durationMs,\n ...(hasTokenData ? {\n token_usage: {\n input_tokens: tokenAccumulator.inputTokens,\n output_tokens: tokenAccumulator.outputTokens,\n total_tokens: tokenAccumulator.totalTokens ?? (tokenAccumulator.inputTokens + tokenAccumulator.outputTokens),\n ...(tokenAccumulator.cacheReadTokens ? { cache_read_input_tokens: tokenAccumulator.cacheReadTokens } : {}),\n ...(tokenAccumulator.cacheCreationTokens ? { cache_creation_input_tokens: tokenAccumulator.cacheCreationTokens } : {}),\n },\n } : {}),\n };\n if (hasTokenData) {\n const costUsd = computeCostUsd(\n sessionEnvelope.model,\n tokenAccumulator.inputTokens,\n tokenAccumulator.outputTokens,\n );\n if (costUsd !== undefined) {\n sessionEnvelope.execution_metadata = {\n ...sessionEnvelope.execution_metadata,\n cost_usd: costUsd,\n };\n }\n }\n emitSessionClose(\n options.observer,\n sessionSpanId,\n sessionEnvelope,\n durationMs,\n wfResult?.status ?? \"error\",\n sessionError?.message,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Merge base variables with injected loop variables.\n * Returns undefined when the merged result is empty (avoids adding an empty\n * `variables: {}` to TaskContext which would be misleading).\n */\nfunction mergeVariables(\n base: Record<string, unknown> | undefined,\n injected: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged = { ...base, ...injected };\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n adapter?: SdkAdapter,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (options.onGate) {\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n // LLM-based gate evaluation using the description as the condition\n if (adapter && step.description) {\n const approved = await evaluateGateWithLlm(adapter, step, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n // Fallback: no onGate, no adapter or no description — auto-approve with warning\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\n/**\n * Use the LLM adapter to evaluate a gate condition.\n * Sends a lightweight prompt with the gate description and prior step outcomes,\n * expecting a JSON response with { \"approved\": boolean, \"reason\": string }.\n */\nasync function evaluateGateWithLlm(\n adapter: SdkAdapter,\n step: GateStep,\n priorResults: StepResult[],\n): Promise<boolean> {\n const priorContext = priorResults\n .map((r) => {\n const id = r.task_id ?? r.gate_kind ?? `step_${r.step_index}`;\n const data = \"data\" in r.outcome ? (r.outcome as { data: unknown }).data : undefined;\n return `- ${id}: status=${r.outcome.status}${data ? `, data=${typeof data === \"string\" ? data : JSON.stringify(data)}` : \"\"}`;\n })\n .join(\"\\n\");\n\n const prompt = buildGateEvaluationPrompt(step, priorContext);\n\n try {\n const response = await adapter.send(prompt, { readonly: true });\n return parseGateEvaluationResponse(response);\n } catch {\n // On LLM failure, reject the gate (fail-closed)\n return false;\n }\n}\n\nexport function buildGateEvaluationPrompt(step: GateStep, priorContext: string): string {\n return `You are a gate evaluator in a workflow pipeline. Your job is to decide whether the workflow should proceed based on prior step results.\n\n## Gate\n- kind: ${step.gate_kind}\n- condition: ${step.description}\n\n## Prior Step Results\n${priorContext || \"(no prior results)\"}\n\n## Instructions\nEvaluate whether the gate condition is satisfied based on the prior step results.\nRespond with ONLY a JSON object (no markdown fences, no extra text):\n\n{\"approved\": true, \"reason\": \"brief explanation\"}\n\nor\n\n{\"approved\": false, \"reason\": \"brief explanation\"}`;\n}\n\nexport function parseGateEvaluationResponse(response: string): boolean {\n // Try to extract JSON from the response\n const jsonMatch = response.match(/\\{[\\s\\S]*?\"approved\"\\s*:\\s*(true|false)[\\s\\S]*?\\}/);\n if (jsonMatch) {\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n return parsed.approved === true;\n } catch {\n // fall through\n }\n }\n\n // Heuristic fallback: look for explicit approval/rejection keywords\n const lower = response.toLowerCase();\n if (lower.includes('\"approved\": true') || lower.includes('\"approved\":true')) {\n return true;\n }\n if (lower.includes('\"approved\": false') || lower.includes('\"approved\":false')) {\n return false;\n }\n\n // Fail-closed: if we can't parse, reject\n return false;\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: WorkflowStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n /** Set progress output sink for real-time execution visibility. */\n progressOutput(sink: { write(chunk: string): unknown }): this {\n this.invocation = { ...this.invocation, progressOutput: sink };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — registers the plugin modules a project manifest declares.\n *\n * Discovery is the manifest and nothing else: `plugins:` in `project.yaml`\n * lists the modules to load, and `createProjectRuntime` calls this once while\n * building the runtime. Each path is dynamically import()'d and every export\n * satisfying the AgentPlugin interface (an `id` string property) is registered\n * with the pluginRegistry singleton, which the task runner, the workflow runner\n * and `execute.ts` read at execution time. All three are in THIS process; the\n * guardrail evaluator itself holds no reference to the registry, because it is\n * shared with hook-bin processes this loader never runs in (#331).\n *\n * A declared path that cannot be loaded throws: a plugin the manifest asks for\n * and the runtime silently skips is indistinguishable from one that ran.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n /** Number of AgentPlugin exports registered across all loaded modules. */\n loaded: number;\n /** Absolute paths of the modules that were imported. */\n files: string[];\n}\n\n/**\n * Load and register every plugin module the project manifest declares.\n * `paths` are manifest-relative; `baseDir` is the manifest's directory.\n */\nexport async function loadPlugins(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n throw new Error(\n `Plugin not found: ${absPath} (declared by the project manifest's \\`plugins:\\`).`,\n );\n }\n\n try {\n result.loaded += await loadPluginModule(absPath);\n result.files.push(absPath);\n } catch (err) {\n throw new Error(\n `Failed to load plugin ${absPath} (declared by the project manifest's ` +\n `\\`plugins:\\`): ${(err as Error).message}`,\n );\n }\n }\n\n return result;\n}\n","/**\n * ModelResolver — resolves a model_class to a concrete adapter + model pair.\n *\n * Resolution priority (highest wins):\n * 1. AGENT_RUNTIME_MODEL_<CLASS> env var (class name upper-cased)\n * 2. AGENT_RUNTIME_MODEL env var (catch-all fallback)\n * 3. project.yaml model_mapping.<class>\n * 4. CLI --adapter + adapter default model\n */\n\nimport type { ModelClass, ProjectModelMapping } from \"@aaac/contracts\";\n\n/**\n * The model-class vocabulary, declared by @aaac/contracts as the key set of the\n * `model_mapping` section — restating it here is what let a class exist in the\n * manifest that no runtime path could see.\n */\nexport type { ModelClass };\n\nexport interface ResolvedModel {\n adapter: string;\n model?: string;\n}\n\nexport interface ModelResolver {\n resolve(modelClass: ModelClass | undefined): ResolvedModel;\n}\n\n/**\n * The `model_mapping` section this resolver reads, as declared by\n * @aaac/contracts — restating its shape here is what forced every caller to\n * bridge the two with an `as`.\n */\nexport type ModelMappingConfig = ProjectModelMapping;\n\nexport interface ModelResolverOptions {\n modelMapping?: ModelMappingConfig;\n fallbackAdapter: string;\n fallbackModel?: string;\n env?: Record<string, string | undefined>;\n /**\n * When set, always use this adapter name. Model is still resolved per class\n * from mapping / env (e.g. CLI `--adapter mock` with project model_mapping).\n */\n pinnedAdapter?: string;\n}\n\nconst ENV_PREFIX = \"AGENT_RUNTIME_MODEL\";\n\n/** The per-class env override for {@link modelClass}, e.g. `..._THINKING`. */\nfunction classEnvKey(modelClass: ModelClass): string {\n return `${ENV_PREFIX}_${modelClass.toUpperCase()}`;\n}\n\n/**\n * Parse an \"adapter:model\" string.\n * - \"claude:claude-sonnet-4-20250514\" → { adapter: \"claude\", model: \"claude-sonnet-4-20250514\" }\n * - \"claude:\" → { adapter: \"claude\" }\n * - \"claude-sonnet-4-20250514\" (no colon) → { model: \"claude-sonnet-4-20250514\" } (adapter from fallback)\n */\nfunction parseEnvValue(\n value: string,\n fallbackAdapter: string,\n): ResolvedModel {\n const colonIdx = value.indexOf(\":\");\n if (colonIdx === -1) {\n return { adapter: fallbackAdapter, model: value || undefined };\n }\n const adapter = value.slice(0, colonIdx) || fallbackAdapter;\n const model = value.slice(colonIdx + 1) || undefined;\n return { adapter, model };\n}\n\nexport function createModelResolver(\n options: ModelResolverOptions,\n): ModelResolver {\n const env = options.env ?? process.env;\n\n return {\n resolve(modelClass: ModelClass | undefined): ResolvedModel {\n const fallback: ResolvedModel = {\n adapter: options.pinnedAdapter ?? options.fallbackAdapter,\n model: options.fallbackModel,\n };\n\n if (!modelClass) return fallback;\n\n // 1. Class-specific env var\n const classEnv = env[classEnvKey(modelClass)];\n if (classEnv) {\n const parsed = parseEnvValue(classEnv, options.fallbackAdapter);\n return options.pinnedAdapter\n ? { adapter: options.pinnedAdapter, model: parsed.model }\n : parsed;\n }\n\n // 2. Catch-all env var\n const catchAllEnv = env[ENV_PREFIX];\n if (catchAllEnv) {\n const parsed = parseEnvValue(catchAllEnv, options.fallbackAdapter);\n return options.pinnedAdapter\n ? { adapter: options.pinnedAdapter, model: parsed.model }\n : parsed;\n }\n\n // 3. Config file model_mapping\n const entry = options.modelMapping?.[modelClass];\n if (entry) {\n return {\n adapter: options.pinnedAdapter ?? entry.adapter,\n model: entry.model,\n };\n }\n\n // 4. Fallback\n return fallback;\n },\n };\n}\n","/**\n * Progress Sink — configurable output target for agent execution progress.\n *\n * Supports writing to stderr, file, or both (tee). File naming strategies\n * allow single-file append, per-invocation unique files, or daily rotation.\n */\n\nimport { openSync, writeSync, closeSync, mkdirSync } from \"node:fs\";\nimport { dirname, join, basename, extname } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\n\nexport interface ProgressSinkOptions {\n /** Write to process.stderr. Default: false */\n stderr?: boolean;\n /** Base file path for log output. */\n file?: string;\n /**\n * File naming strategy:\n * - \"single\": always append to `file` (default)\n * - \"per-invocation\": {dir}/{base}-{YYYY-MM-DDTHHmmss}-{label}{ext}\n * - \"daily\": {dir}/{base}-{YYYY-MM-DD}{ext}\n */\n naming?: \"single\" | \"per-invocation\" | \"daily\";\n /**\n * Identity of the invocation, used only by `per-invocation` naming. The\n * timestamp in that name is second-granular, so this is what keeps two runs\n * that start in the same second in separate files. `executeTask` /\n * `executeWorkflow` pass the task / workflow id.\n *\n * It becomes a component of the resolved file name, so it must be usable as\n * one — `pathSegmentForId` rejects anything that would resolve the log\n * outside the directory `file` declares.\n */\n label?: string;\n}\n\nexport interface ProgressSink {\n write(chunk: string): void;\n close(): void;\n /** Resolved file path (undefined if file output is disabled). */\n readonly filePath?: string;\n}\n\nfunction resolveFilePath(\n base: string,\n naming: \"single\" | \"per-invocation\" | \"daily\",\n label?: string,\n): string {\n if (naming === \"single\") return base;\n\n const dir = dirname(base);\n const ext = extname(base);\n const stem = basename(base, ext);\n const now = new Date();\n\n if (naming === \"daily\") {\n const date = now.toISOString().slice(0, 10);\n return join(dir, `${stem}-${date}${ext}`);\n }\n\n // per-invocation\n const pad = (n: number) => String(n).padStart(2, \"0\");\n const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}T${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;\n const suffix = label ? `-${pathSegmentForId(\"progress-log label\", label)}` : \"\";\n return join(dir, `${stem}-${ts}${suffix}${ext}`);\n}\n\nexport function createProgressSink(options: ProgressSinkOptions): ProgressSink {\n const useStderr = options.stderr ?? false;\n let fd: number | null = null;\n let resolvedPath: string | undefined;\n\n if (options.file) {\n const naming = options.naming ?? \"single\";\n resolvedPath = resolveFilePath(options.file, naming, options.label);\n mkdirSync(dirname(resolvedPath), { recursive: true });\n fd = openSync(resolvedPath, \"a\");\n }\n\n if (!useStderr && fd === null) {\n return { write() {}, close() {} };\n }\n\n return {\n write(chunk: string) {\n if (useStderr) process.stderr.write(chunk);\n if (fd !== null) writeSync(fd, chunk);\n },\n close() {\n if (fd !== null) {\n closeSync(fd);\n fd = null;\n }\n },\n get filePath() {\n return resolvedPath;\n },\n };\n}\n","/**\n * MemoryRef — opaque typed reference for resumable agent context.\n *\n * The ref itself is a lightweight pointer; the actual memory content\n * is managed by the MemoryStore or held server-side by the provider.\n */\nexport interface MemoryRef {\n /** Opaque identifier (e.g. session UUID, response ID, agent ID). */\n id: string;\n /** Provider that generated this ref (e.g. \"claude-agent-sdk\", \"openai-responses\"). */\n provider: string;\n /** Compatibility tag for format validation across versions. */\n compat: string;\n /** ISO 8601 timestamp of ref creation. */\n created_at: string;\n /** ID of the run that produced this ref, for chain tracking. */\n parent_run_id?: string;\n}\n\n/**\n * Pluggable store for memory content that backs MemoryRef pointers.\n *\n * Adapters that use server-side state (OpenAI, Gemini) may not need\n * the store — the ref ID alone is sufficient for resume. Adapters\n * with local state (Claude transcript, Gemini chat history) use the\n * store to persist and retrieve content.\n */\nexport interface MemoryStore {\n save(ref: MemoryRef, content: unknown): Promise<void>;\n load(ref: MemoryRef): Promise<unknown | null>;\n delete(ref: MemoryRef): Promise<void>;\n}\n\n/**\n * In-memory store for testing. State is lost when the process exits.\n */\nexport class InMemoryStore implements MemoryStore {\n private data = new Map<string, unknown>();\n\n async save(ref: MemoryRef, content: unknown): Promise<void> {\n this.data.set(ref.id, content);\n }\n\n async load(ref: MemoryRef): Promise<unknown | null> {\n return this.data.get(ref.id) ?? null;\n }\n\n async delete(ref: MemoryRef): Promise<void> {\n this.data.delete(ref.id);\n }\n}\n","import { mkdir, readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport type { MemoryRef, MemoryStore } from \"./memory-store.js\";\n\nexport interface FileMemoryStoreOptions {\n baseDir?: string;\n}\n\nfunction resolveFilePath(baseDir: string, ref: MemoryRef): string {\n const runId = ref.parent_run_id ?? \"unknown\";\n // Neither half is authored here: `id` is a provider session/response id or a\n // caller-supplied `memoryRef`, `parent_run_id` a caller-supplied run id. Both\n // become the file name, so both are checked before they can name one.\n return join(\n baseDir,\n `${pathSegmentForId(\"memory ref parent_run_id\", runId)}` +\n `_${pathSegmentForId(\"memory ref id\", ref.id)}.json`,\n );\n}\n\n/**\n * File-backed MemoryStore. Persists memory content as JSON files under\n * `<baseDir>/` (default: `.agent-logs/memories/`).\n */\nexport class FileMemoryStore implements MemoryStore {\n readonly baseDir: string;\n\n constructor(options?: FileMemoryStoreOptions) {\n this.baseDir = options?.baseDir ?? \".agent-logs/memories\";\n }\n\n async save(ref: MemoryRef, content: unknown): Promise<void> {\n await mkdir(this.baseDir, { recursive: true });\n const filePath = resolveFilePath(this.baseDir, ref);\n await writeFile(filePath, JSON.stringify(content, null, 2), \"utf-8\");\n }\n\n async load(ref: MemoryRef): Promise<unknown | null> {\n const filePath = resolveFilePath(this.baseDir, ref);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n }\n\n async delete(ref: MemoryRef): Promise<void> {\n const filePath = resolveFilePath(this.baseDir, ref);\n try {\n await unlink(filePath);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return;\n }\n throw error;\n }\n }\n}\n","import { mkdir, readFile, readdir, stat, unlink, writeFile, appendFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { FileMemoryStore } from \"./file-memory-store.js\";\n\nexport interface RunLogEvent {\n timestamp: string;\n type:\n | \"operation_start\"\n | \"operation_end\"\n | \"operation_error\"\n | \"workflow_start\"\n | \"workflow_end\"\n | \"task_start\"\n | \"task_end\"\n | \"handoff\";\n runId: string;\n operationName?: string;\n agentId?: string;\n data?: unknown;\n durationMs?: number;\n error?: string;\n}\n\nconst RUN_LOG_EVENT_TYPES: ReadonlyArray<RunLogEvent[\"type\"]> = [\n \"operation_start\",\n \"operation_end\",\n \"operation_error\",\n \"workflow_start\",\n \"workflow_end\",\n \"task_start\",\n \"task_end\",\n \"handoff\",\n];\n\nconst optionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\n/**\n * The gate between one line of a run log and {@link RunLogEvent}.\n *\n * Every declared field is checked. The log is append-only text an earlier run\n * (possibly an earlier build) wrote, so a line that is not an event is not one\n * this reader may return typed as one — `data` is the exception, declared\n * `unknown`, which promises nothing to check.\n */\nfunction isRunLogEvent(value: unknown): value is RunLogEvent {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const event = value as Record<string, unknown>;\n return (\n typeof event.timestamp === \"string\" &&\n RUN_LOG_EVENT_TYPES.includes(event.type as RunLogEvent[\"type\"]) &&\n typeof event.runId === \"string\" &&\n optionalString(event.operationName) &&\n optionalString(event.agentId) &&\n (event.durationMs === undefined || typeof event.durationMs === \"number\") &&\n optionalString(event.error)\n );\n}\n\nexport interface AgentLogWriterOptions {\n baseDir?: string;\n}\n\nexport class AgentLogWriter {\n readonly baseDir: string;\n private memoryStore: FileMemoryStore;\n\n constructor(options?: AgentLogWriterOptions) {\n this.baseDir = options?.baseDir ?? \".agent-logs\";\n this.memoryStore = new FileMemoryStore({\n baseDir: join(this.baseDir, \"memories\"),\n });\n }\n\n getMemoryStore(): FileMemoryStore {\n return this.memoryStore;\n }\n\n /**\n * Where one run's event log lives. The writer and the reader must agree on\n * the name, so both derive it here rather than each spelling it out — and\n * with it, the check that keeps a run id inside `baseDir`.\n */\n private runLogPath(runId: string): string {\n return join(this.baseDir, \"runs\", `${pathSegmentForId(\"run id\", runId)}.jsonl`);\n }\n\n /** Where one run's handoff payload lives. Shared by the writer and reader. */\n private handoffPath(runId: string, step: string): string {\n return join(\n this.baseDir,\n \"handoffs\",\n `${pathSegmentForId(\"run id\", runId)}_${pathSegmentForId(\"handoff step\", step)}.json`,\n );\n }\n\n async writeRunEvent(runId: string, event: RunLogEvent): Promise<void> {\n const filePath = this.runLogPath(runId);\n await mkdir(join(this.baseDir, \"runs\"), { recursive: true });\n await appendFile(filePath, `${JSON.stringify(event)}\\n`, \"utf-8\");\n }\n\n async readRunLog(runId: string): Promise<RunLogEvent[]> {\n const filePath = this.runLogPath(runId);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n // A line that does not parse, or does not read as an event, is not one:\n // the same answer a missing log gets below, rather than a typed lie.\n const events: RunLogEvent[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (line.trim().length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n if (isRunLogEvent(parsed)) events.push(parsed);\n }\n return events;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return [];\n }\n throw error;\n }\n }\n\n async writeHandoff(\n runId: string,\n step: string,\n data: unknown,\n ): Promise<void> {\n const filePath = this.handoffPath(runId, step);\n await mkdir(join(this.baseDir, \"handoffs\"), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2), \"utf-8\");\n }\n\n async readHandoff(\n runId: string,\n step: string,\n ): Promise<unknown | null> {\n const filePath = this.handoffPath(runId, step);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n }\n\n async cleanOlderThan(maxAgeMs: number): Promise<{ deleted: number }> {\n const cutoff = Date.now() - maxAgeMs;\n let deleted = 0;\n\n const subdirs = [\"memories\", \"runs\", \"handoffs\"];\n for (const subdir of subdirs) {\n const dirPath = join(this.baseDir, subdir);\n let entries: string[];\n try {\n entries = await readdir(dirPath);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n continue;\n }\n throw error;\n }\n\n for (const entry of entries) {\n const filePath = join(dirPath, entry);\n const fileStat = await stat(filePath);\n if (fileStat.mtimeMs < cutoff) {\n await unlink(filePath);\n deleted++;\n }\n }\n }\n\n return { deleted };\n }\n}\n","import { jsonSchemaToZod } from \"./schema-converter.js\";\nimport type { SdkFunctionTool } from \"./library-tool-sdk.js\";\n\nexport interface LibraryToolDefinition {\n toolId: string;\n description: string;\n module: string;\n exportName: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n}\n\nexport interface LibraryToolRegistry {\n register(def: LibraryToolDefinition): void;\n get(toolId: string): LibraryToolDefinition | undefined;\n getAll(): LibraryToolDefinition[];\n execute(toolId: string, input: unknown): Promise<unknown>;\n}\n\nexport function createLibraryToolRegistry(): LibraryToolRegistry {\n const definitions = new Map<string, LibraryToolDefinition>();\n const moduleCache = new Map<string, Record<string, unknown>>();\n\n return {\n register(def: LibraryToolDefinition): void {\n definitions.set(def.toolId, def);\n },\n\n get(toolId: string): LibraryToolDefinition | undefined {\n return definitions.get(toolId);\n },\n\n getAll(): LibraryToolDefinition[] {\n return [...definitions.values()];\n },\n\n async execute(toolId: string, input: unknown): Promise<unknown> {\n const def = definitions.get(toolId);\n if (!def) {\n throw new Error(`Library tool not found: ${toolId}`);\n }\n\n if (def.inputSchema) {\n const schema = jsonSchemaToZod(def.inputSchema);\n const result = schema.safeParse(input);\n if (!result.success) {\n throw new Error(\n `Input validation failed for tool \"${toolId}\": ${result.error.message}`,\n );\n }\n input = result.data;\n }\n\n let mod = moduleCache.get(def.module);\n if (!mod) {\n try {\n mod = (await import(def.module)) as Record<string, unknown>;\n moduleCache.set(def.module, mod);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to import module \"${def.module}\" for tool \"${toolId}\": ${message}`,\n );\n }\n }\n\n const fn = mod[def.exportName];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Export \"${def.exportName}\" not found in module \"${def.module}\" for tool \"${toolId}\"`,\n );\n }\n\n const output = await (fn as (input: unknown) => Promise<unknown>)(input);\n\n if (def.outputSchema) {\n const schema = jsonSchemaToZod(def.outputSchema);\n const result = schema.safeParse(output);\n if (!result.success) {\n throw new Error(\n `Output validation failed for tool \"${toolId}\": ${result.error.message}`,\n );\n }\n }\n\n return output;\n },\n };\n}\n\n/**\n * Create a LibraryToolRegistry backed by pre-built SdkFunctionTool handlers.\n * Unlike createLibraryToolRegistry (which resolves tools via dynamic import),\n * this variant delegates execute() directly to the tool's in-process handler.\n */\nexport function createRegistryFromSdkTools(\n tools: SdkFunctionTool[],\n): LibraryToolRegistry {\n const handlers = new Map<string, SdkFunctionTool>();\n const definitions = new Map<string, LibraryToolDefinition>();\n\n for (const tool of tools) {\n handlers.set(tool.name, tool);\n definitions.set(tool.name, {\n toolId: tool.name,\n description: tool.description,\n module: \"__inline__\",\n exportName: \"__handler__\",\n inputSchema: tool.inputSchema,\n });\n }\n\n return {\n register(def: LibraryToolDefinition): void {\n definitions.set(def.toolId, def);\n },\n\n get(toolId: string): LibraryToolDefinition | undefined {\n return definitions.get(toolId);\n },\n\n getAll(): LibraryToolDefinition[] {\n return [...definitions.values()];\n },\n\n async execute(toolId: string, input: unknown): Promise<unknown> {\n const handler = handlers.get(toolId);\n if (handler) {\n return handler.handler((input ?? {}) as Record<string, unknown>);\n }\n throw new Error(`Library tool not found: ${toolId}`);\n },\n };\n}\n","/**\n * Adapter Factory — public API for creating SDK adapters by name.\n *\n * Centralises the adapter-name → SDK-class mapping so that consumers\n * no longer need a local switch statement with dynamic imports.\n */\n\nimport type { SdkAdapter } from \"./task-runner.js\";\nimport type { GuardrailHooks } from \"./guardrail-hooks.js\";\n\nexport type PermissionMode = \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n\nexport interface CreateAdapterOptions {\n model?: string;\n cwd?: string;\n tools?: string[];\n permissionMode?: PermissionMode;\n guardrailHooks?: GuardrailHooks;\n}\n\nconst ADAPTER_PACKAGES: Record<string, string> = {\n claude: \"@anthropic-ai/claude-agent-sdk\",\n gemini: \"@google/adk\",\n openai: \"@openai/agents\",\n};\n\n/**\n * Create an SDK adapter instance by name.\n *\n * @param name - One of: \"mock\", \"claude\", \"openai\", \"gemini\"\n * @param options - Adapter-specific configuration\n */\nexport async function createAdapter(\n name: string,\n options?: CreateAdapterOptions,\n): Promise<SdkAdapter> {\n const { model, cwd, tools, permissionMode, guardrailHooks } = options ?? {};\n\n switch (name) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n try {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n ...(cwd ? { cwd } : {}),\n ...(tools ? { tools } : {}),\n ...(permissionMode ? { permissionMode } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"claude\", err);\n }\n }\n case \"gemini\": {\n try {\n const { AdkSdkAdapter } = await import(\"../adapters/adk-sdk.js\");\n return new AdkSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"gemini\", err);\n }\n }\n case \"openai\": {\n try {\n const { OpenAIAgentsSdkAdapter } = await import(\"../adapters/openai-agents-sdk.js\");\n return new OpenAIAgentsSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"openai\", err);\n }\n }\n default:\n throw new Error(\n `Unknown adapter: \"${name}\". Available: mock, claude, openai, gemini`,\n );\n }\n}\n\nfunction throwMissingPackageError(adapter: string, err: unknown): never {\n const message = err instanceof Error ? err.message : String(err);\n if (message.includes(\"Cannot find package\")) {\n const pkg = ADAPTER_PACKAGES[adapter];\n throw new Error(\n `Adapter \"${adapter}\" requires package \"${pkg}\" which is not installed.\\n` +\n `Install it with: npm install ${pkg}`,\n );\n }\n throw err;\n}\n","/**\n * High-level execution APIs — executeTask / executeWorkflow\n *\n * Encapsulates the common boilerplate shared across all CLI consumers:\n * 1. Adapter creation\n * 2. DSL context loading (registries)\n * 3. Progress sink setup\n * 4. Task/workflow invocation with retry policy\n *\n * CLI consumers only need to provide:\n * - domain-specific context (user_request)\n * - adapter name + options\n * - DSL blob (resolvedDsl from codegen)\n */\n\nimport { resolve } from \"node:path\";\nimport { type CreateAdapterOptions } from \"./adapter-factory.js\";\nimport {\n BoundResolver,\n type ArtifactBindingConfig,\n type ResolvedComponent,\n} from \"./bound-resolver.js\";\nimport {\n createComponentScope,\n DEFAULT_COMPONENT_ID,\n type ComponentScope,\n} from \"../component-scope.js\";\nimport type { InvokedComponent } from \"../component-binding.js\";\nimport { loadDslContext } from \"./dsl-context.js\";\nimport {\n createGuardrailHooks,\n createGuardrailHooksFromRules,\n type GuardrailCheckFunctions,\n type GuardrailHooks,\n} from \"./guardrail-hooks.js\";\nimport { pluginRegistry } from \"./plugin.js\";\nimport { createProgressSink, type ProgressSink } from \"./progress-sink.js\";\nimport type { ProgressLogConfig } from \"../generator/config.js\";\nimport { runTask, type TaskRunResult, type SdkAdapter, type ObserverEmitFn } from \"./task-runner.js\";\nimport { runWorkflow, type WorkflowResult, type WorkflowInvocation, type HandoffInput, type StepCompleteEvent, type StepResult, type WorkflowRegistries, type DelegateStep } from \"./workflow-runner.js\";\nimport type { RunToolchainChecksOptions } from \"./toolchain-checker.js\";\nimport type { TaskContext } from \"./task-runner.js\";\nimport type { ModelClass, ModelMappingConfig } from \"./model-resolver.js\";\nimport { createModelAwareAdapterSetup } from \"./model-aware-adapter.js\";\nimport { createAnalyzerBridge } from \"./analyzer-bridge.js\";\nimport { createRegistryFromSdkTools, type LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport { buildNavigationContext, type NavigationContext } from \"./navigation-context.js\";\n\n// ---------------------------------------------------------------------------\n// Shared options\n// ---------------------------------------------------------------------------\n\nexport interface ExecuteOptions {\n adapter: string;\n model?: string;\n dsl: Record<string, unknown>;\n projectDslPath?: string;\n /**\n * Progress-log settings from the project manifest's `logging.progress_log`,\n * auto-wired by createProjectRuntime. Absent → stderr only.\n */\n progressLog?: ProgressLogConfig;\n adapterOptions?: Partial<CreateAdapterOptions>;\n maxFollowUps?: number;\n maxRetries?: number;\n /** Pre-resolved component from BoundResolver (skips runtime resolve). */\n resolvedComponent?: ResolvedComponent;\n /**\n * The component whose operation is being executed, carried here by\n * `createProjectRuntime` from the invocation context `createRuntimeBinding`\n * built (component-binding.ts). It is what makes the run's `ComponentScope` a\n * scope of something: the component's operation names are one of the two\n * namespaces `toolsByAgent` resolves declarations in, and its id is what says\n * which toolchains write their `operations` in it (#338).\n *\n * Absent only when `executeTask` / `executeWorkflow` are called directly, by\n * a caller that named no component. The scope is still built — guardrails,\n * library tools and the tool-id namespace do not depend on the IR — with no\n * component operations to wire.\n */\n component?: InvokedComponent;\n /** Component id for BoundResolver cache keying. */\n componentId?: string;\n /** Software binding paths for runtime guardrail resolution. */\n bindingPaths?: string[];\n /** Active guardrail policy name. */\n activeGuardrailPolicy?: string;\n /** Artifact binding config for runtime resolveBound(). */\n artifactBinding?: ArtifactBindingConfig;\n /** Path substitutions for artifact binding. */\n paths?: Record<string, string>;\n /**\n * Observer emit function for agent-axis spans (agent.session / agent.subagent /\n * toolchain.execution / evaluate.*). When undefined, all emission is a no-op.\n * Auto-wired from project.yaml `bindings.observability` by createProjectRuntime —\n * callers do NOT hand-write this.\n */\n observer?: ObserverEmitFn;\n /**\n * The project manifest's `toolchains:`, auto-wired by createProjectRuntime.\n *\n * Two consumers on this path, both driven from this one value:\n * - `resolveExecutionContext` hands `toolchainsPath` to `BoundResolver`,\n * which derives each agent's toolchains from the artifacts it may touch\n * and so decides what reaches `buildCandidateAgents` (#336).\n * - `runWorkflow` runs the declared `checks` once post-run and emits one\n * toolchain.execution span per check (OBSERVATION ONLY — never changes\n * the workflow outcome), which is why it also gates itself on `observer`.\n * `observer`/`parentSpanId` are injected there.\n */\n toolchain?: RunToolchainChecksOptions;\n /** Per-class adapter/model mapping from project.yaml (used by executeWorkflow / executeTask). */\n modelMapping?: ModelMappingConfig;\n /**\n * When true, `adapter` is used for all model classes; only the model name\n * varies per class (CLI `--adapter mock` override).\n */\n pinAdapter?: boolean;\n}\n\n/**\n * The one place `logging.progress_log` becomes a ProgressSink, shared by\n * executeTask and executeWorkflow. `destination` decides the targets and\n * `naming` the file rotation; both are meaningless unless read here.\n *\n * `invocationId` is the task or workflow id the caller was asked to run — the\n * only identity an invocation has at this seam, and what `naming:\n * per-invocation` needs to keep runs apart: its timestamp is second-granular,\n * so without the id two invocations that start in the same second resolve to\n * the same file and the strategy degrades to `daily` with a longer name.\n */\nfunction createExecutionProgressSink(\n invocationId: string,\n progressLog?: ProgressLogConfig,\n): ProgressSink {\n if (!progressLog) return createProgressSink({ stderr: true });\n\n const { destination, file, naming } = progressLog;\n const wantsFile = destination === \"file\" || destination === \"both\";\n\n return createProgressSink({\n stderr: destination === \"stderr\" || destination === \"both\",\n // The schema requires `file` whenever destination selects file output.\n ...(wantsFile && file ? { file: resolve(file), naming, label: invocationId } : {}),\n });\n}\n\n// ---------------------------------------------------------------------------\n// Shared context resolution\n// ---------------------------------------------------------------------------\n\ninterface ExecutionContext {\n registries: WorkflowRegistries;\n dsl: Record<string, unknown>;\n /** Level 1 navigation index, when one could be built for this DSL. */\n navigationIndex?: Record<string, unknown>;\n /**\n * This invocation's component scope. Built here because this is where both\n * halves exist: the `ResolvedComponent` this function resolves, and the\n * component the binding named. Everything the scope isolates —\n * per-agent tools, per-agent guardrails, the in-process tool registry — is\n * consumed below from the scope and from nowhere else, so an invocation\n * cannot half-use it (#338).\n */\n scope: ComponentScope;\n}\n\nasync function resolveExecutionContext(\n options: ExecuteOptions,\n requiredEntities?: { workflows?: string[]; tasks?: string[] },\n): Promise<ExecutionContext> {\n // Every input BoundResolver is the only one to read. `toolchain` belongs here\n // for the same reason `bindingPaths` and `artifactBinding` do: a manifest that\n // declares only `toolchains:` still has something to resolve, and leaving it\n // out is what kept the derivation from ever running (#336).\n const useBoundResolver =\n options.resolvedComponent ||\n (options.bindingPaths && options.bindingPaths.length > 0) ||\n options.artifactBinding ||\n options.toolchain;\n\n if (useBoundResolver) {\n // Merge the project-level DSL overlay (which may `extends: /$embedded/`)\n // over the embedded base BEFORE binding, so guardrail/artifact binding\n // operates on the fully-resolved DSL — not just the embedded base.\n let baseDsl = options.dsl;\n if (!options.resolvedComponent && options.projectDslPath) {\n const merged = await loadDslContext({\n embeddedDsl: options.dsl,\n projectDslPath: options.projectDslPath,\n });\n baseDsl = merged.dsl;\n }\n\n const component =\n options.resolvedComponent ??\n (await new BoundResolver().resolve({\n // The component the binding named is this run's identity, so it is also\n // what the resolver is keyed on: two components resolved in one process\n // are two entries, not one shared \"default\".\n id: options.component?.ir.info.id ?? options.componentId ?? DEFAULT_COMPONENT_ID,\n embeddedDsl: baseDsl,\n bindingPaths: options.bindingPaths,\n activeGuardrailPolicy: options.activeGuardrailPolicy,\n artifactBinding: options.artifactBinding,\n paths: options.paths,\n toolchainContractsPath: options.toolchain?.toolchainsPath,\n }));\n\n const registries = requiredEntities\n ? (await loadDslContext({ embeddedDsl: component.dsl, requiredEntities })).registries\n : component.registries;\n\n return scopeExecution(options, registries, component.dsl, component);\n }\n\n const ctx = await loadDslContext({\n embeddedDsl: options.dsl,\n projectDslPath: options.projectDslPath,\n requiredEntities,\n });\n return scopeExecution(options, ctx.registries, ctx.dsl);\n}\n\n/**\n * The tail every branch above shares: build the Level 1 navigation context, the\n * in-process analyzer tools it scopes, and the component scope that owns them.\n *\n * One place, because a second one is a second answer: `executeTask` and\n * `executeWorkflow` each used to build the navigation context and the analyzer\n * registry for themselves.\n */\nasync function scopeExecution(\n options: ExecuteOptions,\n registries: WorkflowRegistries,\n dsl: Record<string, unknown>,\n resolvedComponent?: ResolvedComponent,\n): Promise<ExecutionContext> {\n const navigationIndex = (await buildNavigationContextSafely(dsl))?.navigationIndex;\n const scope = createComponentScope({\n component: options.component,\n dsl,\n resolvedComponent,\n libraryTools: buildAnalyzerToolRegistry({\n navigationIndex,\n artifactPatterns: deriveArtifactPatterns(navigationIndex),\n }),\n });\n\n return { registries, dsl, navigationIndex, scope };\n}\n\n/**\n * Guardrail hooks for one agent, or undefined when nothing would check it.\n *\n * The ONE constructor of per-agent hooks. `guardrail-hooks.ts` builds an\n * evaluator out of the check sources it is handed and names no agent anywhere\n * (see `HookContext`), so which rules an agent is checked against is decided\n * here — it has to be, because deciding it needs the two things that module is\n * deliberately kept away from: this run's `ComponentScope`, which carries the\n * rules a binding resolved, and this process's plugin registry.\n *\n * It was decided in two places once. That module also exported a per-agent\n * constructor, re-exported from the barrel and called by nobody, which took the\n * `perAgent` map directly; it memoised nothing where this one caches per agent,\n * and handed an agent with no rules an evaluator that denies nothing where this\n * one returns undefined. Nothing failed when the two drifted, because nothing\n * ran the other one (#333).\n *\n * \"The ONE\" is a DECLARATION, and this comment is the whole of its enforcement.\n * Deleting `HookContext.agentId` took away the affordance that duplicate used,\n * so it cannot be pasted back as it was (TS2353) — but that is a bound on one\n * spelling, not on the invariant. A second per-agent constructor that never\n * writes an agent id typechecks, builds and passes every test in this\n * repository, and `check:reachability` calls it reachable as soon as a barrel\n * re-exports it, because reachable is not consumed. There is no gate to add\n * here: \"is this another way to answer the same question\" is a question about\n * intent, and a check that decided it from the shape of the code would report\n * green for the cases it failed to enumerate. So this is enforced by being\n * read, which is why it sits on the declaration that makes the decision rather\n * than in a document beside it.\n *\n * TWO independent sources feed those hooks, so they are gated independently:\n *\n * - RULES, which exist only where a software binding resolved them\n * (BoundResolver); there is no second, DSL-embedded source of rules (#267).\n * They are per-agent, so they are looked up per agent — in the run's\n * `ComponentScope` and nowhere else, which is what makes the rules this run\n * enforces the calling component's and not the process's. That map was\n * built through `getGuardrailRulesForAgent` (component-scope.ts), the\n * predicate `dev-team guard list` answers with, so reading it here is\n * reading that predicate rather than holding a second opinion beside it\n * (#338).\n * - The `customGuardrails` of the plugins the project manifest declared.\n * Those belong to the PROCESS, not to an agent: nothing about them is\n * scoped, and a project can declare them while no binding resolves a single\n * rule for anyone.\n *\n * Gating both on the rules is what put plugin guardrails out of reach: a\n * plugin-only project has no per-agent rule anywhere, so no hooks were built,\n * so the adapter never called `runChecks` and the plugin was consulted in no\n * process at all (#332). Memoised because the workflow path asks once per step.\n *\n * This is where the process's plugin guardrails enter the evaluator, and the\n * only place they do. `createProjectRuntime` ran `loadPlugins` for THIS process\n * before anything could execute, so the registry here holds what the project\n * manifest declared — whereas the hook routes answer for an editor and are\n * evaluated in processes that cannot have run it (see\n * `PluginRegistry.guardrailChecks`). Passed rather than reached for: the\n * evaluator is shared with the lean hot path, where the registry is dead weight\n * on every tool call (#331).\n *\n * Returning a factory is also what makes `executeWorkflow` scope adapters per\n * agent, so the gate has to stay shut for a project that declares neither kind\n * of guardrail — otherwise every project would split its adapter cache to carry\n * hooks with nothing to check.\n */\nfunction createAgentGuardrailHooks(\n execCtx: ExecutionContext,\n): ((agentId: string) => GuardrailHooks | undefined) | undefined {\n // Already only the agents that have rules: the scope applied\n // `getGuardrailRulesForAgent` to every key of the resolved `perAgent` map\n // when it built this one (component-scope.ts), so an empty map is \"no agent\n // on this run has a rule\" and not \"no component was resolved\".\n const guardrailsByAgent = execCtx.scope.guardrailsByAgent;\n // Whether there is a plugin source is decided once; WHAT it reports is still\n // read when a check runs (see `PluginRegistry.guardrailChecks`).\n const pluginSources: GuardrailCheckFunctions[] = pluginRegistry.hasGuardrails()\n ? [pluginRegistry.guardrailChecks()]\n : [];\n if (pluginSources.length === 0 && guardrailsByAgent.size === 0) return undefined;\n\n // What an agent the binding resolved no rule for gets. Agent-independent, so\n // it is one object rather than one per agent.\n const pluginOnlyHooks =\n pluginSources.length > 0 ? createGuardrailHooks(...pluginSources) : undefined;\n\n const cache = new Map<string, GuardrailHooks | undefined>();\n return (agentId: string) => {\n if (cache.has(agentId)) return cache.get(agentId);\n\n const rules = guardrailsByAgent.get(agentId);\n const hooks = rules\n ? createGuardrailHooksFromRules(rules, ...pluginSources)\n : pluginOnlyHooks;\n cache.set(agentId, hooks);\n return hooks;\n };\n}\n\nfunction injectGuardrailHooks(\n adapterOptions: Partial<CreateAdapterOptions>,\n execCtx: ExecutionContext,\n targetAgentId?: string,\n): void {\n if (adapterOptions.guardrailHooks || !targetAgentId) return;\n\n const hooks = createAgentGuardrailHooks(execCtx)?.(targetAgentId);\n if (hooks) {\n adapterOptions.guardrailHooks = hooks;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared navigation context (Level 1) → analyzer bridge + task prompt\n// ---------------------------------------------------------------------------\n\ninterface AnalyzerToolRegistryOptions {\n navigationIndex?: Record<string, unknown>;\n artifactPatterns?: Map<string, string[]>;\n projectRoot?: string;\n}\n\nfunction buildAnalyzerToolRegistry(\n options: AnalyzerToolRegistryOptions = {},\n): LibraryToolRegistry {\n const bridge = createAnalyzerBridge({\n projectRoot: options.projectRoot ?? process.cwd(),\n navigationIndex: options.navigationIndex,\n artifactPatterns: options.artifactPatterns,\n });\n const tools = bridge.buildAnalyzerTools();\n return createRegistryFromSdkTools(tools);\n}\n\n/**\n * Derive the artifactId → path_patterns map the analyzer needs to scope its\n * AST/dependency graph build, from the Level 1 navigation index. Returns an\n * empty map when no usable artifacts are present.\n */\nfunction deriveArtifactPatterns(\n navigationIndex?: Record<string, unknown>,\n): Map<string, string[]> {\n const patterns = new Map<string, string[]>();\n const artifacts = navigationIndex?.artifacts as\n | Record<string, { files?: { path_patterns?: unknown } }>\n | undefined;\n if (!artifacts) return patterns;\n for (const [id, node] of Object.entries(artifacts)) {\n const pp = node?.files?.path_patterns;\n if (Array.isArray(pp) && pp.length > 0) {\n patterns.set(id, pp as string[]);\n }\n }\n return patterns;\n}\n\n/**\n * Build the Level 1 navigation context for an execution. Best-effort: when the\n * DSL is absent or navigation cannot be built (e.g. agent-contracts unavailable,\n * validation failure), execution degrades gracefully and proceeds without it\n * rather than throwing.\n */\nasync function buildNavigationContextSafely(\n dsl: Record<string, unknown>,\n): Promise<NavigationContext | undefined> {\n if (!dsl) return undefined;\n try {\n // `dsl` is already the fully merged + artifact-bound DSL, so we feed it\n // directly as the embedded DSL (no further overlay/binding required).\n return await buildNavigationContext({ embeddedDsl: dsl });\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// executeTask\n// ---------------------------------------------------------------------------\n\nexport interface TaskHookContext {\n adapter: SdkAdapter;\n registries: WorkflowRegistries;\n taskId: string;\n}\n\nexport interface ExecuteTaskOptions extends ExecuteOptions {\n request: string;\n hooks?: {\n beforeTask?: (ctx: TaskHookContext) => Promise<void>;\n afterTask?: (result: TaskRunResult) => Promise<void>;\n };\n}\n\nexport async function executeTask(\n taskId: string,\n options: ExecuteTaskOptions,\n): Promise<TaskRunResult> {\n const execCtx = await resolveExecutionContext(options, { tasks: [taskId] });\n const taskDef = execCtx.registries.taskRegistry?.[taskId];\n const targetAgentId = taskDef?.target_agent;\n const modelClass = taskDef?.model_class as ModelClass | undefined;\n\n const adapterOptions = { ...options.adapterOptions };\n injectGuardrailHooks(adapterOptions, execCtx, targetAgentId);\n\n const { resolveAdapter: resolveTaskAdapter, modelResolver } = await createModelAwareAdapterSetup({\n fallbackAdapter: options.adapter,\n fallbackModel: options.model,\n modelMapping: options.modelMapping,\n adapterOptions,\n pinAdapter: options.pinAdapter,\n });\n const resolved = modelResolver.resolve(modelClass);\n const adapter = await resolveTaskAdapter(modelClass);\n\n const progressSink = createExecutionProgressSink(taskId, options.progressLog);\n\n const taskContext: TaskContext = { user_request: options.request };\n if (execCtx.navigationIndex) {\n taskContext.variables = { navigationIndex: execCtx.navigationIndex };\n }\n\n try {\n if (options.hooks?.beforeTask) {\n await options.hooks.beforeTask({ adapter, registries: execCtx.registries, taskId });\n }\n\n const result = await runTask(adapter, taskId, taskContext, {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: options.maxRetries ?? 0,\n progressOutput: progressSink,\n observer: options.observer,\n libraryTools: execCtx.scope.libraryTools,\n toolsByAgent: execCtx.scope.toolsByAgent,\n envelopeAdapter: resolved.adapter,\n envelopeModel: resolved.model,\n ...execCtx.registries,\n });\n\n if (options.hooks?.afterTask) {\n await options.hooks.afterTask(result);\n }\n\n return result;\n } finally {\n progressSink.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// executeWorkflow\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowHookContext {\n adapter: SdkAdapter;\n registries: WorkflowRegistries;\n workflowId: string;\n}\n\nexport interface ExecuteWorkflowOptions extends ExecuteOptions {\n request?: string;\n handoff?: HandoffInput<string>;\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n autoApproveGates?: boolean;\n hooks?: {\n beforeWorkflow?: (ctx: WorkflowHookContext) => Promise<void>;\n afterWorkflow?: (result: WorkflowResult) => Promise<void>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n}\n\nexport async function executeWorkflow(\n workflowId: string,\n options: ExecuteWorkflowOptions,\n): Promise<WorkflowResult> {\n const execCtx = await resolveExecutionContext(options, { workflows: [workflowId] });\n\n const adapterOptions = { ...options.adapterOptions };\n // A workflow's steps run as different agents, and guardrail hooks are fixed at\n // adapter construction — so the scope is applied per step by the factory rather\n // than once for the whole run (#269).\n const guardrailHooksForAgent = adapterOptions.guardrailHooks\n ? undefined\n : createAgentGuardrailHooks(execCtx);\n\n const { factory: adapterOrFactory, defaultAdapter: adapter, modelResolver } =\n await createModelAwareAdapterSetup({\n fallbackAdapter: options.adapter,\n fallbackModel: options.model,\n modelMapping: options.modelMapping,\n adapterOptions,\n pinAdapter: options.pinAdapter,\n guardrailHooksForAgent,\n });\n\n const progressSink = createExecutionProgressSink(workflowId, options.progressLog);\n\n // Propagate the navigation index to every step's TaskContext.variables via\n // the workflow invocation context (workflow-runner spreads context.variables\n // onto each delegate/evaluate step).\n const workflowContext = execCtx.navigationIndex\n ? {\n ...options.context,\n variables: {\n ...options.context?.variables,\n navigationIndex: execCtx.navigationIndex,\n },\n }\n : options.context;\n\n try {\n if (options.hooks?.beforeWorkflow) {\n await options.hooks.beforeWorkflow({ adapter, registries: execCtx.registries, workflowId });\n }\n\n const invocation: WorkflowInvocation = {\n workflow: workflowId,\n user_request: options.request,\n handoff: options.handoff,\n progressOutput: progressSink,\n observer: options.observer,\n toolchain: options.toolchain,\n libraryTools: execCtx.scope.libraryTools,\n toolsByAgent: execCtx.scope.toolsByAgent,\n resolveModelMeta: (modelClass) => modelResolver.resolve(modelClass),\n perAgentAdapters: Boolean(guardrailHooksForAgent),\n runtime: {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: options.maxRetries ?? 0,\n },\n hooks: {\n onStepComplete: options.hooks?.onStepComplete,\n onGate: options.hooks?.onGate ?? (options.autoApproveGates ? async () => true : undefined),\n onOptionalStep: options.hooks?.onOptionalStep,\n },\n context: workflowContext,\n };\n\n const result = await runWorkflow(adapterOrFactory, invocation, execCtx.registries);\n\n if (options.hooks?.afterWorkflow) {\n await options.hooks.afterWorkflow(result);\n }\n\n return result;\n } finally {\n progressSink.close();\n }\n}\n","import type { ComponentIR } from \"@aaac/contracts\";\nimport type { InvokedComponent, RuntimeBinding } from \"./component-binding.js\";\nimport {\n getGuardrailRulesForAgent,\n type ResolvedComponent,\n type ResolvedToolchain,\n} from \"./lib/bound-resolver.js\";\nimport type { GuardrailRuleData } from \"./lib/guardrail-hooks.js\";\nimport type { LibraryToolRegistry } from \"./lib/library-tool-binding.js\";\n\n/**\n * The component id an invocation that named no component runs under. Shared\n * with `resolveExecutionContext` (lib/execute.ts), which keys `BoundResolver`\n * on the same value, so the scope's id and the resolved component's id are one\n * name and not two.\n */\nexport const DEFAULT_COMPONENT_ID = \"default\";\n\nexport interface ComponentScope {\n componentId: string;\n /**\n * Present when the invocation named a component — i.e. when it was dispatched\n * through a `createRuntimeBinding` binding, which is every invocation the\n * generated component client makes. Absent when `executeTask` /\n * `executeWorkflow` are called directly with no component to scope to; there\n * are then no operation names to wire and nothing to check them against.\n */\n componentIR?: ComponentIR;\n binding?: RuntimeBinding;\n toolsByAgent: Map<string, string[]>;\n guardrailsByAgent: Map<string, GuardrailRuleData>;\n libraryTools?: LibraryToolRegistry;\n toolchainsByAgent?: Map<string, ResolvedToolchain[]>;\n}\n\nexport interface CreateComponentScopeOptions {\n /** The component whose operation is being executed (component-binding.ts). */\n component?: InvokedComponent;\n /**\n * The effective DSL — merged overlay, artifact-bound — that declares `tools`\n * and `agents`. It is where both halves of the tool-id namespace are written,\n * and it exists whether or not a software binding was resolved, so it is an\n * input of its own rather than a field read off `resolvedComponent`.\n */\n dsl?: Record<string, unknown>;\n resolvedComponent?: ResolvedComponent;\n /**\n * The in-process tool registry this scope owns. Held rather than built: a\n * registry is constructed by `createLibraryToolRegistry` /\n * `createRegistryFromSdkTools` (lib/library-tool-binding.ts), and what §5.2 of\n * the architecture asks of the scope is that the registry be the calling\n * component's rather than a process-wide one.\n */\n libraryTools?: LibraryToolRegistry;\n}\n\n/**\n * A declaration that reaches `toolsByAgent` named something the namespace it is\n * written in does not contain.\n *\n * Two declarations reach it, each in its own namespace:\n *\n * - `toolchains[*].operations` of a toolchain naming THIS component — this\n * component's operation names (#335).\n * - `agents[*].can_execute_tools` — a tool id: a DSL `tools` key or the id of\n * a toolchain the resolver loaded (#337).\n *\n * Both used to be matched against the operation names and whatever missed was\n * dropped without a word: `agents/toolchain-contracts.yaml` could ask for\n * `audit-governance` while the operation is `auditGovernance`, and\n * `reflector.can_execute_tools: [observ-query]` — a correctly spelled tool id —\n * was thrown away for not being an operation name. Either way an agent shipped\n * a tool short and nothing failed.\n *\n * One error for both because there is one defect: a name that resolves to\n * nothing. It carries both namespaces so the reader can see which one the\n * offending line was meant to be written in.\n */\nexport class UnresolvedScopeDeclarationError extends Error {\n readonly componentId: string;\n readonly unresolved: string[];\n readonly operationNames: string[];\n readonly toolIds: string[];\n\n constructor(\n componentId: string,\n unresolved: string[],\n operationNames: string[],\n toolIds: string[],\n ) {\n super(\n `Declarations do not resolve against component \"${componentId}\":\\n` +\n unresolved.map((u) => ` - ${u}`).join(\"\\n\") +\n `\\nComponent operations: ${operationNames.join(\", \")}` +\n `\\nTool ids: ${toolIds.join(\", \")}`,\n );\n this.name = \"UnresolvedScopeDeclarationError\";\n this.componentId = componentId;\n this.unresolved = unresolved;\n this.operationNames = operationNames;\n this.toolIds = toolIds;\n }\n}\n\ninterface DslToolEntry {\n invokable_by?: string[];\n}\n\ninterface DslAgentEntry {\n can_execute_tools?: string[];\n}\n\nfunction buildToolsByAgent(\n dsl?: Record<string, unknown>,\n resolved?: ResolvedComponent,\n componentIR?: ComponentIR,\n): Map<string, string[]> {\n const operationNames = new Set(Object.keys(componentIR?.operations ?? {}));\n const toolsByAgent = new Map<string, string[]>();\n\n const tools = (dsl?.tools ?? {}) as Record<string, DslToolEntry>;\n // The tool-id namespace: a tool is named by its DSL `tools` key or by the id\n // of a toolchain the resolver loaded. Those two, and only those two, are what\n // `mergeDerivedWithAgentTools` (lib/bound-resolver.ts) already resolves\n // `can_execute_tools` against, so an id that means something there means the\n // same thing here.\n const toolIds = new Set([\n ...Object.keys(tools),\n ...Object.keys(resolved?.toolchains ?? {}),\n ]);\n\n const unresolved: string[] = [];\n\n // A tool is identified by its id — the `tools` key. `command` names a unit\n // inside the contract the tool binds: a sub-command of its `cli_contract`\n // (`compile`), or an operation of the component its `component_contract`\n // names (`review`). Either way that is a name in the bound contract's\n // namespace, not in this one, so it is neither checked against this namespace\n // nor wired from it.\n for (const [toolId, tool] of Object.entries(tools)) {\n for (const agentId of tool.invokable_by ?? []) {\n appendToolForAgent(toolsByAgent, agentId, toolId);\n }\n }\n\n const agents = (dsl?.agents ?? {}) as Record<string, DslAgentEntry>;\n for (const [agentId, agent] of Object.entries(agents)) {\n for (const toolId of agent.can_execute_tools ?? []) {\n if (toolIds.has(toolId)) {\n appendToolForAgent(toolsByAgent, agentId, toolId);\n } else {\n unresolved.push(`${agentId}.can_execute_tools: ${toolId}`);\n }\n }\n }\n\n if (resolved?.toolchainsByAgent) {\n for (const [agentId, toolchains] of resolved.toolchainsByAgent) {\n for (const tc of toolchains) {\n // The toolchain itself is a tool id — the same namespace `toolIds` is\n // built from — and `deriveToolchainsForAgents` (lib/bound-resolver.ts)\n // already decided which agents may reach it, from the artifacts they\n // may touch merged with their own declarations. So it is wired here\n // unconditionally, and `buildCandidateAgents` reads this map instead of\n // re-deriving the same grant from `can_execute_tools` a second time.\n appendToolForAgent(toolsByAgent, agentId, tc.id);\n\n // A toolchain's `operations` are written in the namespace of whatever\n // the toolchain names. Only a toolchain that names THIS component\n // writes them in `operationNames`; a cli/library toolchain lists its\n // own verbs (`lint`, `test`, `format`) and a toolchain naming another\n // component lists that component's operations. Neither is a name in\n // this namespace, so neither is checked against it or wired from it —\n // and an invocation that named no component has no such namespace at\n // all, so nothing is written in it.\n if (!componentIR || tc.componentId !== componentIR.info.id) continue;\n\n for (const op of tc.operations ?? []) {\n if (operationNames.has(op)) {\n appendToolForAgent(toolsByAgent, agentId, op);\n } else {\n // Keyed by the declaration, not the agent: the same toolchain is\n // derived for every agent whose artifacts it touches, and the\n // defect is one line of toolchain-contracts either way.\n unresolved.push(`${tc.id}.operations: ${op}`);\n }\n }\n }\n }\n }\n\n if (unresolved.length > 0) {\n throw new UnresolvedScopeDeclarationError(\n componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,\n [...new Set(unresolved)].sort(),\n [...operationNames].sort(),\n [...toolIds].sort(),\n );\n }\n\n return toolsByAgent;\n}\n\nfunction appendToolForAgent(\n toolsByAgent: Map<string, string[]>,\n agentId: string,\n toolName: string,\n): void {\n const existing = toolsByAgent.get(agentId) ?? [];\n if (existing.includes(toolName)) {\n return;\n }\n toolsByAgent.set(agentId, [...existing, toolName]);\n}\n\n/**\n * Per-agent guardrail rules, read through `getGuardrailRulesForAgent`\n * (lib/bound-resolver.ts) — the one predicate for \"does this agent have rules\",\n * so the scope and `dev-team guard list` cannot disagree about an agent whose\n * every rule was filtered out by the active policy.\n */\nfunction buildGuardrailsByAgent(\n resolved?: ResolvedComponent,\n): Map<string, GuardrailRuleData> {\n const guardrailsByAgent = new Map<string, GuardrailRuleData>();\n\n if (!resolved) {\n return guardrailsByAgent;\n }\n\n for (const agentId of resolved.guardrails.perAgent.keys()) {\n const rules = getGuardrailRulesForAgent(resolved, agentId);\n if (rules) {\n guardrailsByAgent.set(agentId, rules);\n }\n }\n\n return guardrailsByAgent;\n}\n\nexport function createComponentScope(\n options: CreateComponentScopeOptions = {},\n): ComponentScope {\n const resolved = options.resolvedComponent;\n const componentIR = options.component?.ir;\n\n return {\n componentId: componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,\n ...(options.component\n ? { componentIR: options.component.ir, binding: options.component.binding }\n : {}),\n toolsByAgent: buildToolsByAgent(options.dsl, resolved, componentIR),\n guardrailsByAgent: buildGuardrailsByAgent(resolved),\n ...(options.libraryTools ? { libraryTools: options.libraryTools } : {}),\n ...(resolved?.toolchainsByAgent\n ? { toolchainsByAgent: resolved.toolchainsByAgent }\n : {}),\n };\n}\n","/**\n * Model-aware adapter factory — resolves model_class (and, when guardrails are\n * agent-scoped, the executing agent) to cached SdkAdapter instances.\n *\n * Used by executeWorkflow (per-step routing) and shares cache across steps.\n * The factory's no-arg / standard call must return synchronously (workflow-runner\n * resolveAdapter contract); other model classes may return a Promise on first use.\n *\n * Guardrail hooks are fixed at adapter construction, so a workflow whose steps run\n * as different agents needs one adapter per (model, agent) pair — otherwise the\n * first step's agent scope would leak to every later step, or (as before #269) no\n * guardrails would apply at all.\n */\n\nimport { createAdapter, type CreateAdapterOptions } from \"./adapter-factory.js\";\nimport {\n createModelResolver,\n type ModelClass,\n type ModelMappingConfig,\n type ModelResolver,\n type ResolvedModel,\n} from \"./model-resolver.js\";\nimport type { ModelAwareSdkAdapterFactory } from \"./workflow-runner.js\";\nimport type { SdkAdapter } from \"./task-runner.js\";\nimport type { GuardrailHooks } from \"./guardrail-hooks.js\";\n\nexport interface ModelAwareAdapterSetup {\n factory: ModelAwareSdkAdapterFactory;\n defaultAdapter: SdkAdapter;\n modelResolver: ModelResolver;\n /** Resolve (and cache) the adapter for a model_class (+ agent scope). */\n resolveAdapter: (modelClass?: ModelClass, agentId?: string) => Promise<SdkAdapter>;\n}\n\nfunction cacheKey(resolved: ResolvedModel, agentId?: string): string {\n const base = `${resolved.adapter}:${resolved.model ?? \"\"}`;\n return agentId ? `${base}:${agentId}` : base;\n}\n\nexport async function createModelAwareAdapterSetup(options: {\n fallbackAdapter: string;\n fallbackModel?: string;\n modelMapping?: ModelMappingConfig;\n adapterOptions?: Partial<CreateAdapterOptions>;\n pinAdapter?: boolean;\n /**\n * Guardrail hooks for the agent a step runs as. When provided, adapters are\n * cached per (model, agent) and each gets that agent's hooks. Ignored when the\n * caller already supplied `adapterOptions.guardrailHooks` (an explicit override\n * wins, as it does for executeTask).\n */\n guardrailHooksForAgent?: (agentId: string) => GuardrailHooks | undefined;\n}): Promise<ModelAwareAdapterSetup> {\n const modelResolver = createModelResolver({\n modelMapping: options.modelMapping,\n fallbackAdapter: options.fallbackAdapter,\n fallbackModel: options.fallbackModel,\n pinnedAdapter: options.pinAdapter ? options.fallbackAdapter : undefined,\n });\n\n const cache = new Map<string, SdkAdapter>();\n const inflight = new Map<string, Promise<SdkAdapter>>();\n\n // An explicit caller override disables agent scoping outright: there is then one\n // hook set for the whole run, so per-agent adapters would only fragment the cache.\n const scopeHooks = options.adapterOptions?.guardrailHooks\n ? undefined\n : options.guardrailHooksForAgent;\n\n function scopeKey(agentId?: string): string | undefined {\n return scopeHooks && agentId ? agentId : undefined;\n }\n\n async function ensureAdapter(\n modelClass?: ModelClass,\n agentId?: string,\n ): Promise<SdkAdapter> {\n const resolved = modelResolver.resolve(modelClass);\n const scope = scopeKey(agentId);\n const key = cacheKey(resolved, scope);\n const hit = cache.get(key);\n if (hit) return hit;\n\n let pending = inflight.get(key);\n if (!pending) {\n const agentHooks = scope ? scopeHooks!(scope) : undefined;\n pending = createAdapter(resolved.adapter, {\n model: resolved.model,\n ...options.adapterOptions,\n ...(agentHooks ? { guardrailHooks: agentHooks } : {}),\n });\n inflight.set(key, pending);\n }\n\n try {\n const adapter = await pending;\n cache.set(key, adapter);\n return adapter;\n } finally {\n inflight.delete(key);\n }\n }\n\n const defaultAdapter = await ensureAdapter(\"standard\");\n\n const factory: ModelAwareSdkAdapterFactory = (\n modelClass?: ModelClass,\n agentId?: string,\n ) => {\n const effectiveClass: ModelClass = modelClass ?? \"standard\";\n const resolved = modelResolver.resolve(effectiveClass);\n const scope = scopeKey(agentId);\n const hit = cache.get(cacheKey(resolved, scope));\n if (hit) return hit;\n\n // workflow-runner resolveAdapter() calls factory() synchronously for primary.\n // An agent-scoped request always needs its own adapter, so it never takes this\n // shortcut (the default adapter carries no agent's hooks).\n if (effectiveClass === \"standard\" && !scope) {\n return defaultAdapter;\n }\n\n return ensureAdapter(effectiveClass, agentId);\n };\n\n return {\n factory,\n defaultAdapter,\n modelResolver,\n resolveAdapter: ensureAdapter,\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { ComponentIR, OperationIR } from \"@aaac/contracts\";\nimport type { AgentLogWriter } from \"./lib/agent-log-writer.js\";\nimport type { MemoryRef, MemoryStore } from \"./lib/memory-store.js\";\nimport type { ObserverEmitFn } from \"./lib/observability-bridge.js\";\n\nexport interface OperationMemoryRefConfig {\n output?: boolean;\n input?: boolean;\n provider?: string;\n compat?: string;\n}\n\ntype OperationWithMemoryRef = OperationIR & {\n memoryRef?: OperationMemoryRefConfig;\n};\n\nexport interface MemoryStoreEntry {\n result: unknown;\n memoryRef: MemoryRef;\n}\n\n/**\n * The component an invocation is for: the IR that declares its operations and\n * the binding that dispatches them.\n *\n * `createRuntimeBinding` is the only place that holds both — it is handed the IR\n * and returns the binding — and `dispatchOperation` is the only call from here\n * into `ctx.runtime`. So this pair is how the execution path below learns which\n * component it is executing, which is what `createComponentScope` needs to scope\n * tools and guardrails to it (#338).\n */\nexport interface InvokedComponent {\n ir: ComponentIR;\n binding: RuntimeBinding;\n}\n\nexport interface AaacInvocationContext {\n runtime: AaacRuntime;\n /** The component whose operation is being dispatched. Set by createRuntimeBinding. */\n component?: InvokedComponent;\n policy?: AaacPolicy;\n observer?: AaacObserver;\n parentRunId?: string;\n abortSignal?: AbortSignal;\n memoryRef?: MemoryRef;\n memoryStore?: MemoryStore;\n logWriter?: AgentLogWriter;\n /** Populated when resuming from a previous memory_ref. */\n resumedState?: unknown;\n /** Current run ID for this invocation chain. */\n runId?: string;\n}\n\nexport interface AaacRuntime {\n runWorkflow(\n workflowId: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n runTask(\n taskId: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n}\n\nexport interface AaacPolicy {\n assertAllowed(operationName: string): void | Promise<void>;\n}\n\nexport interface AaacObserver {\n onOperationStart?(operationName: string, input: unknown): void;\n onOperationEnd?(operationName: string, output: unknown): void;\n onOperationError?(operationName: string, error: Error): void;\n /**\n * Emit an agent-axis event to the observability pipeline.\n * Structurally matches EventCollector.emit() from @aaac/observability.\n * Pass an EventCollector instance to wire up the full pipeline.\n * When undefined, emission is a no-op (observer is optional).\n */\n emit?: ObserverEmitFn;\n}\n\nexport type OperationHandler = (\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n) => Promise<unknown>;\n\nexport interface RuntimeBinding {\n execute(\n operationName: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n getOperationNames(): string[];\n getOperationIR(name: string): OperationIR | undefined;\n}\n\nconst DEFAULT_MEMORY_PROVIDER = \"aaac-runtime\";\nconst DEFAULT_MEMORY_COMPAT = \"aaac/0.1\";\n\nfunction getMemoryRefConfig(\n op: OperationIR,\n): OperationMemoryRefConfig | undefined {\n return (op as OperationWithMemoryRef).memoryRef;\n}\n\nfunction attachMemoryRef(result: unknown, memoryRef: MemoryRef): unknown {\n if (result !== null && typeof result === \"object\" && !Array.isArray(result)) {\n return { ...result, _memoryRef: memoryRef };\n }\n return { value: result, _memoryRef: memoryRef };\n}\n\nexport function createRuntimeBinding(\n component: ComponentIR,\n handlers?: Record<string, OperationHandler>,\n): RuntimeBinding {\n const operations = component.operations;\n\n const binding: RuntimeBinding = {\n getOperationNames(): string[] {\n return Object.keys(operations);\n },\n\n getOperationIR(name: string): OperationIR | undefined {\n return operations[name];\n },\n\n async execute(\n operationName: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown> {\n const op = operations[operationName];\n if (!op) {\n throw new Error(`Unknown operation: ${operationName}`);\n }\n\n const memoryConfig = getMemoryRefConfig(op);\n const runId = ctx.runId ?? ctx.parentRunId ?? randomUUID();\n const execCtx: AaacInvocationContext = {\n ...ctx,\n runId,\n component: { ir: component, binding },\n };\n\n if (ctx.memoryRef && ctx.memoryStore) {\n const stored = await ctx.memoryStore.load(ctx.memoryRef);\n if (stored !== null) {\n const entry = stored as MemoryStoreEntry;\n execCtx.resumedState = entry.result ?? stored;\n }\n }\n\n await ctx.policy?.assertAllowed(operationName);\n ctx.observer?.onOperationStart?.(operationName, input);\n\n const startTime = Date.now();\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_start\",\n runId,\n operationName,\n data: { input },\n });\n }\n\n try {\n const result = await dispatchOperation(\n operationName,\n op,\n options,\n input,\n execCtx,\n handlers,\n );\n\n let finalResult = result;\n let newMemoryRef: MemoryRef | undefined;\n\n if (memoryConfig?.output && ctx.memoryStore) {\n newMemoryRef = {\n id: randomUUID(),\n provider: memoryConfig.provider ?? DEFAULT_MEMORY_PROVIDER,\n compat: memoryConfig.compat ?? DEFAULT_MEMORY_COMPAT,\n created_at: new Date().toISOString(),\n parent_run_id: runId,\n };\n\n const entry: MemoryStoreEntry = {\n result,\n memoryRef: newMemoryRef,\n };\n await ctx.memoryStore.save(newMemoryRef, entry);\n finalResult = attachMemoryRef(result, newMemoryRef);\n }\n\n ctx.observer?.onOperationEnd?.(operationName, finalResult);\n\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_end\",\n runId,\n operationName,\n durationMs: Date.now() - startTime,\n data: { output: finalResult },\n });\n }\n\n return finalResult;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.observer?.onOperationError?.(operationName, err);\n\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_error\",\n runId,\n operationName,\n durationMs: Date.now() - startTime,\n error: err.message,\n });\n }\n\n throw err;\n }\n },\n };\n\n return binding;\n}\n\nasync function dispatchOperation(\n operationName: string,\n op: OperationIR,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n handlers?: Record<string, OperationHandler>,\n): Promise<unknown> {\n if (op.agentWorkflow) {\n return ctx.runtime.runWorkflow(op.agentWorkflow, options, input, ctx);\n }\n\n if (op.agentTask) {\n return ctx.runtime.runTask(op.agentTask, options, input, ctx);\n }\n\n if (op.handler) {\n const handler = handlers?.[operationName];\n if (!handler) {\n throw new Error(\n `No handler provided for deterministic operation \"${operationName}\"`,\n );\n }\n return handler(options, input, ctx);\n }\n\n throw new Error(`Operation \"${operationName}\" has no dispatch target`);\n}\n","/**\n * Standard project runtime — the reusable, CLI-facing `AaacRuntime` that every\n * generated component CLI uses, so that NO caller hand-writes `ctx.runtime`.\n * Named \"project\" because it is driven by the external `project.yaml` manifest.\n *\n * It:\n * - discovers/loads the external `project.yaml` (walk up from cwd, or explicit\n * config path) via loadProjectConfig,\n * - resolves the effective DSL = project `agents` overlay merged over the\n * bundled `/$embedded/` component DSL (reusing executeWorkflow/executeTask's\n * loadDslContext merge — the overlay may `extends: /$embedded/` or be\n * self-contained),\n * - selects adapter/model from the project model_mapping (env/flag overrides)\n * via createModelResolver,\n * - implements runWorkflow → executeWorkflow and runTask → executeTask,\n * passing bindingPaths / activeGuardrailPolicy / artifactBinding so machine\n * guardrails operate on the merged DSL.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { createPipeline, type OtelEmitter } from \"@aaac/observability\";\nimport {\n loadProjectConfig,\n PROJECT_CONFIG_FILENAME,\n type ResolvedConfig,\n} from \"../generator/config.js\";\nimport { createModelResolver } from \"./model-resolver.js\";\nimport { executeWorkflow, executeTask } from \"./execute.js\";\nimport { loadPlugins } from \"./plugin-loader.js\";\nimport { serializeObserverEmit, type ObserverEmitFn } from \"./observability-bridge.js\";\nimport type { AaacRuntime, AaacInvocationContext } from \"../component-binding.js\";\n\nexport { PROJECT_CONFIG_FILENAME } from \"../generator/config.js\";\n\nconst DEFAULT_ADAPTER = \"claude\";\n\n/**\n * Walk up from `startDir` to the filesystem root looking for the nearest\n * `project.yaml`. Returns the absolute path, or undefined if none is found.\n */\nexport function findProjectConfig(\n startDir: string,\n filename: string = PROJECT_CONFIG_FILENAME,\n): string | undefined {\n let dir = resolve(startDir);\n for (;;) {\n const candidate = resolve(dir, filename);\n if (existsSync(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\nexport interface CreateProjectRuntimeOptions {\n /** The bundled `/$embedded/` component DSL (the component's own agent-contracts). */\n embeddedDsl: Record<string, unknown>;\n /** Explicit project.yaml path; when omitted, discovered by walking up from cwd. */\n configPath?: string;\n /** Launch directory for config discovery (defaults to process.cwd()). */\n cwd?: string;\n /** Adapter override (CLI `--adapter`); falls back to env + model_mapping. */\n adapter?: string;\n /** Model override (CLI `--model`). */\n model?: string;\n /** Environment for adapter/model resolution (defaults to process.env). */\n env?: Record<string, string | undefined>;\n /** Auto-approve workflow gates (CLI is non-interactive by default). */\n autoApproveGates?: boolean;\n}\n\nexport interface ResolvedAdapterSelection {\n adapter: string;\n model?: string;\n}\n\nexport interface ProjectRuntime {\n /** The standard AaacRuntime — assign to `ctx.runtime` (or use `.context`). */\n runtime: AaacRuntime;\n /** A ready-made invocation context with `runtime` wired in. */\n context: AaacInvocationContext;\n /** The loaded, resolved project config. */\n config: ResolvedConfig;\n /** Absolute path to the discovered/explicit project.yaml. */\n configPath: string;\n /** Absolute path to the project's `agents` overlay DSL (cfg.dslPath). */\n dslSource: string;\n /** Resolve the effective adapter + model (for --dry-run reporting). */\n resolveAdapter(): ResolvedAdapterSelection;\n /**\n * The in-process OtelEmitter created by createPipeline, when observability\n * is configured. Exposed for test verification that the otel config is\n * actually wired through to the emitter (F-002 / issue #125).\n * Undefined when bindings.observability is absent or disabled.\n */\n otelEmitter?: OtelEmitter;\n}\n\nfunction serializeRequest(input: unknown): string {\n if (typeof input === \"string\") return input;\n return JSON.stringify(input ?? {});\n}\n\n/**\n * Build the standard component runtime from the bundled embedded DSL + the\n * discovered/explicit project.yaml. Throws a clear error when no config exists.\n */\nexport async function createProjectRuntime(\n options: CreateProjectRuntimeOptions,\n): Promise<ProjectRuntime> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = options.configPath\n ? resolve(cwd, options.configPath)\n : findProjectConfig(cwd);\n\n if (!configPath || !existsSync(configPath)) {\n const where = options.configPath\n ? `config path \"${options.configPath}\"`\n : `${PROJECT_CONFIG_FILENAME} from ${cwd} upward`;\n throw new Error(\n `No ${PROJECT_CONFIG_FILENAME} found (${where}). Pass --config <path> to a project manifest.`,\n );\n }\n\n const config = await loadProjectConfig(configPath);\n const env = options.env ?? process.env;\n\n // Only overlay the project `agents` DSL when it is EXPLICITLY declared. When\n // omitted, the bundled `/$embedded/` component DSL is used as-is (no overlay).\n if (config.dslDeclared && !existsSync(config.dslPath)) {\n throw new Error(\n `Project agents DSL not found: ${config.dslPath} (referenced by ${configPath}).`,\n );\n }\n const projectDslPath = config.dslDeclared ? config.dslPath : undefined;\n\n // Manifest `plugins:` -> pluginRegistry, once, before anything can run. The\n // registry is a singleton the task/workflow runners read at execution time,\n // and which `execute.ts` hands the guardrail evaluator as a check source\n // (#331 — the evaluator holds no reference to it, being shared with hook-bin\n // processes this line never runs in). So this is the only moment it can be\n // populated from config without a caller hand-registering plugins.\n await loadPlugins(config.plugins, dirname(configPath));\n\n // In-process observability: when project.yaml declares `bindings.observability`\n // we auto-wire an in-process pipeline (config-driven, like the guardrail binding)\n // so agent-axis spans (agent.session / agent.subagent / toolchain.execution /\n // evaluate.*) are recorded to SQLite WITHOUT git/Cursor hooks. Defaults to ON\n // when the binding exists; `bindings.observability.enabled: false` opts out.\n // The DB path defaults to DEFAULT_DB_PATH and is overridable via `db_path`.\n // Build the pipeline ONCE here and flow `observer` through ExecuteOptions.\n let observer: ObserverEmitFn | undefined;\n let observerSink: { close(): void } | undefined;\n let observerClosed = false;\n let observerOtelEmitter: OtelEmitter | undefined;\n if (config.observability && config.observability.enabled !== false) {\n const pipeline = createPipeline({\n ...(config.observability.dbPath ? { dbPath: config.observability.dbPath } : {}),\n // Wire OTel endpoint from project.yaml bindings.observability.otel.\n // Falls back to OTEL_EXPORTER_OTLP_ENDPOINT env var inside OtelEmitter when absent.\n // When neither is set, OtelEmitter is a no-op (fail-open, no regression).\n otel: config.observability.otel,\n });\n observer = serializeObserverEmit(pipeline.collector.emit.bind(pipeline.collector));\n observerSink = pipeline.sink;\n observerOtelEmitter = pipeline.otelEmitter;\n }\n\n /** Close the observability sink once (idempotent). Safe when no sink was built. */\n function closeObserver(): void {\n if (observerSink && !observerClosed) {\n observerClosed = true;\n observerSink.close();\n }\n }\n\n function resolveAdapter(): ResolvedAdapterSelection {\n const explicit = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;\n if (explicit) {\n return { adapter: explicit, model: options.model };\n }\n const resolver = createModelResolver({\n modelMapping: config.model_mapping,\n fallbackAdapter: DEFAULT_ADAPTER,\n fallbackModel: options.model,\n env,\n });\n const resolved = resolver.resolve(\"standard\");\n return { adapter: resolved.adapter, model: options.model ?? resolved.model };\n }\n\n function sharedExecuteOptions() {\n const { adapter, model } = resolveAdapter();\n const explicitAdapter = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;\n return {\n adapter,\n model,\n pinAdapter: Boolean(explicitAdapter),\n dsl: options.embeddedDsl,\n projectDslPath,\n bindingPaths: config.bindingPaths,\n activeGuardrailPolicy: config.active_guardrail_policy,\n artifactBinding: config.artifactsPath\n ? { source: config.artifactsPath }\n : undefined,\n maxFollowUps: config.recovery.max_follow_ups,\n maxRetries: config.recovery.max_retries,\n modelMapping: config.model_mapping,\n progressLog: config.logging.progress_log,\n observer,\n // The manifest's `toolchains:`, for every consumer of it on the execution\n // path — `BoundResolver` derives each agent's toolchains from it (#336),\n // and `runWorkflow` runs the declared `checks` as a post-run observation\n // pass. Gating this on `observer` would have made the derivation depend on\n // whether observability happens to be configured; the observation pass\n // gates itself on `observer` where it is run (workflow-runner.ts), which\n // is the only consumer that needs the gate.\n toolchain: config.toolchainsPath\n ? {\n toolchainsPath: config.toolchainsPath,\n artifactsPath: config.artifactsPath,\n cwd,\n }\n : undefined,\n };\n }\n\n // `ctx.component` is the one thing here that is per-invocation rather than\n // per-manifest, so it is read at the call and not in sharedExecuteOptions():\n // `createRuntimeBinding` sets it to the component it dispatches for, and two\n // components sharing one project runtime must each get their own scope (#338).\n const runtime: AaacRuntime = {\n async runWorkflow(workflowId, _options, input, ctx) {\n try {\n return await executeWorkflow(workflowId, {\n ...sharedExecuteOptions(),\n component: ctx?.component,\n request: serializeRequest(input),\n autoApproveGates: options.autoApproveGates ?? true,\n });\n } finally {\n // Flush/close the in-process sink on completion (success AND exception).\n closeObserver();\n }\n },\n async runTask(taskId, _options, input, ctx) {\n try {\n return await executeTask(taskId, {\n ...sharedExecuteOptions(),\n component: ctx?.component,\n request: serializeRequest(input),\n });\n } finally {\n closeObserver();\n }\n },\n };\n\n return {\n runtime,\n context: { runtime },\n config,\n configPath,\n dslSource: projectDslPath ?? \"/$embedded/\",\n resolveAdapter,\n otelEmitter: observerOtelEmitter,\n };\n}\n","/**\n * Guard CLI commands — evaluate/list/status for guardrail enforcement.\n *\n * These functions back the `guard evaluate`, `guard list`, and `guard status`\n * sub-commands that are auto-injected by @aaac/contracts cli-generator\n * whenever `governance.guardrails: true` is declared in component.yaml.\n *\n * exit code contract (evaluate):\n * 0 = allowed / pass / warn\n * 2 = denied (permission === \"deny\")\n */\n\nimport { readFile, readdir } from \"node:fs/promises\";\nimport YAML from \"yaml\";\nimport type {\n GuardrailCheckEntry,\n GuardrailDiagnostic,\n} from \"../generator/context.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailCheckResult,\n type GuardrailRuleData,\n type HookResponse,\n toolTargetPath,\n} from \"./guardrail-hooks.js\";\nimport {\n guardrailContextToRuleData,\n resolveGuardrailContext,\n} from \"./bound-resolver.js\";\n\n// ---------------------------------------------------------------------------\n// guard evaluate\n// ---------------------------------------------------------------------------\n\nexport interface EvaluateGuardrailOptions {\n /** Raw JSON string read from stdin (HookContext format). */\n hookJson: string;\n /** Component agent-contracts DSL (contains guardrails + guardrail_policies). */\n dsl: Record<string, unknown>;\n /** Paths to software binding YAML files (contain guardrail_impl matchers). */\n bindingPaths: string[];\n /** Active guardrail policy name (from project.yaml active_guardrail_policy). */\n activeGuardrailPolicy?: string;\n}\n\nexport interface EvaluateGuardrailResult {\n /** HookResponse to write to stdout. */\n response: HookResponse;\n /**\n * CLI exit code.\n * 0 = allowed (pass or warn)\n * 2 = denied (permission === \"deny\")\n */\n exitCode: 0 | 2;\n /** All check results from all matchers. */\n checks: GuardrailCheckResult[];\n}\n\n/**\n * Evaluate a guardrail hook from a JSON string (typically stdin).\n *\n * Detects the hook type from which fields are present in the input:\n * - `command` → beforeShellExecution\n * - `tool_name` / `tool_input` → preToolUse\n * - `file_path` (without command) → afterFileEdit\n */\nexport async function evaluateGuardrail(\n opts: EvaluateGuardrailOptions,\n): Promise<EvaluateGuardrailResult> {\n let document: unknown;\n try {\n document = JSON.parse(opts.hookJson);\n } catch (cause) {\n throw new Error(\n `Invalid hook JSON: input must be valid JSON. ${(cause as Error).message}`,\n );\n }\n if (typeof document !== \"object\" || document === null || Array.isArray(document)) {\n throw new Error(\"Invalid hook JSON: input must be a JSON object.\");\n }\n const hookInput = document as Record<string, unknown>;\n\n // Same resolver as the execution path and the Claude hooks, so all three agree\n // and every declared binding contributes its checks (#267 / #268).\n const guardrailCtx = await resolveGuardrailContext(\n opts.dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n { skipMissing: true },\n );\n\n const ruleData: GuardrailRuleData = guardrailContextToRuleData(guardrailCtx);\n const hooks = createGuardrailHooksFromRules(ruleData);\n\n // Dispatch to the appropriate hook based on input fields\n const command = hookInput.command as string | undefined;\n const toolName = hookInput.tool_name as string | undefined;\n const toolInput = hookInput.tool_input as Record<string, unknown> | undefined;\n const filePath = hookInput.file_path as string | undefined;\n const content = hookInput.content as string | undefined;\n\n let response: HookResponse = {};\n let checks: GuardrailCheckResult[] = [];\n\n // A Claude Code PreToolUse payload carries the shell command in\n // `tool_input.command`; only Cursor puts it at the top level. Reading just the\n // top-level field meant `guard evaluate` silently passed every Bash command\n // Claude Code submitted (#270).\n const shellCommand = command ?? (toolInput?.command as string | undefined);\n\n if (shellCommand !== undefined) {\n // Shell execution hook\n response = hooks.beforeShellExecution({ command: shellCommand });\n checks = hooks.runChecks({ command: shellCommand });\n } else if (toolName !== undefined || toolInput !== undefined) {\n // Pre-tool-use hook\n response = hooks.preToolUse({ tool_name: toolName, tool_input: toolInput });\n const checkFilePath = toolTargetPath(toolInput);\n if (checkFilePath) {\n checks = hooks.runChecks({ filePath: checkFilePath });\n }\n } else if (filePath !== undefined) {\n // After-file-edit hook\n response = hooks.afterFileEdit({ file_path: filePath, content });\n checks = hooks.runChecks({ filePath, content });\n }\n // If no recognizable fields, response stays {} (pass)\n\n const exitCode: 0 | 2 = response.permission === \"deny\" ? 2 : 0;\n return { response, exitCode, checks };\n}\n\n// ---------------------------------------------------------------------------\n// guard list\n// ---------------------------------------------------------------------------\n\nexport interface ListGuardrailsOptions {\n /** Component agent-contracts DSL. */\n dsl: Record<string, unknown>;\n /** Paths to software binding YAML files. */\n bindingPaths: string[];\n /** Active guardrail policy name. */\n activeGuardrailPolicy?: string;\n}\n\nexport interface GuardrailListEntry {\n guardrail_id: string;\n description: string;\n matcher_type: string;\n action: string;\n severity: string;\n pattern: string;\n}\n\nexport interface ListGuardrailsResult {\n policy: string | undefined;\n entries: GuardrailListEntry[];\n /**\n * Guardrail-configuration findings. An entry whose `action` is `unresolved`\n * is explained here — without them the report shows the symptom and hides\n * the cause (#293).\n */\n diagnostics: GuardrailDiagnostic[];\n}\n\n/**\n * List all active guardrails and their enforcement settings.\n *\n * Reads DSL + binding files and builds the guardrail context for the active\n * policy, returning a flat list of guardrail_id / matcher_type / action /\n * severity rows for display.\n */\nexport async function listGuardrails(\n opts: ListGuardrailsOptions,\n): Promise<ListGuardrailsResult> {\n const guardrailCtx = await resolveGuardrailContext(\n opts.dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n { skipMissing: true },\n );\n\n const entries: GuardrailListEntry[] = guardrailCtx.allChecks.map(\n (c: GuardrailCheckEntry) => ({\n guardrail_id: c.guardrail_id,\n description: c.description,\n matcher_type: c.matcher_type,\n action: c.action,\n severity: c.severity,\n pattern: c.pattern,\n }),\n );\n\n return {\n policy: opts.activeGuardrailPolicy,\n entries,\n diagnostics: guardrailCtx.diagnostics,\n };\n}\n\n// ---------------------------------------------------------------------------\n// guard status\n// ---------------------------------------------------------------------------\n\nexport interface GuardStatusOptions {\n /** Base directory for agent logs (defaults to \".agent-logs\"). */\n baseDir?: string;\n /** Maximum number of recent run events to return (defaults to 10). */\n limit?: number;\n}\n\nexport interface GuardStatusResult {\n hasHistory: boolean;\n message: string;\n /** Recent run log events (operation_start/end, etc.). */\n recentEvents: unknown[];\n}\n\n/**\n * Show recent guardrail evaluation summary.\n *\n * Phase 1 limitation: RunLogEvent does not yet include a `guardrail_evaluate`\n * event type, so this command reports general run history from .agent-logs/runs/.\n * Guard-specific event tracking will be added in a future phase.\n *\n * Gracefully returns \"no evaluation history\" when .agent-logs/ does not exist.\n */\nexport async function guardStatus(\n opts: GuardStatusOptions = {},\n): Promise<GuardStatusResult> {\n const baseDir = opts.baseDir ?? \".agent-logs\";\n const runsDir = `${baseDir}/runs`;\n const limit = opts.limit ?? 10;\n\n let files: string[] = [];\n try {\n files = await readdir(runsDir);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return {\n hasHistory: false,\n message:\n \"No evaluation history. Note: guardrail_evaluate event type is not yet tracked in Phase 1.\",\n recentEvents: [],\n };\n }\n throw err;\n }\n\n const jsonlFiles = files\n .filter((f) => f.endsWith(\".jsonl\"))\n .sort()\n .reverse()\n .slice(0, limit);\n\n if (jsonlFiles.length === 0) {\n return {\n hasHistory: false,\n message: \"No evaluation history.\",\n recentEvents: [],\n };\n }\n\n const recentEvents: unknown[] = [];\n for (const file of jsonlFiles) {\n const filePath = `${runsDir}/${file}`;\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch {\n continue;\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as unknown;\n } catch {\n return null;\n }\n })\n .filter(Boolean);\n recentEvents.push(...events);\n if (recentEvents.length >= limit) break;\n }\n\n const count = recentEvents.length;\n return {\n hasHistory: count > 0,\n message:\n count > 0\n ? `${count} recent run event(s) found. Note: guardrail_evaluate events are not yet tracked in Phase 1.`\n : \"No evaluation history.\",\n recentEvents: recentEvents.slice(0, limit),\n };\n}\n","import { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// ClaudeConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Per-workflow slash-command emission (#249).\n *\n * Renders ONE Handlebars-templated file per agent-contracts `workflow` to a\n * `{name}`-placeholder output path (default use case: Claude Code slash commands\n * at `.claude/commands/aidev/{name}.md`). Symmetric with `emit.workflows` (#235)\n * and wired into the SAME sync/check machinery.\n *\n * Shape: accepts either a bare `true` (use all defaults) or an object with\n * optional overrides. `false`/absent = disabled (backward compatible). A bundled\n * default template ships in `command-render.ts` so the default use case needs no\n * consumer-authored template; `template` (a project-root-relative path) overrides it.\n */\nconst ClaudeCommandsEmitSchema = z\n .object({\n /**\n * Project-root-relative output path with a required `{name}` placeholder.\n * Defaults to `.claude/commands/aidev/{name}.md` (resolved in materialize.ts\n * against DEFAULT_COMMAND_OUTPUT so the default lives with the renderer).\n */\n output: z.string().optional(),\n /**\n * Project-root-relative path to a custom Handlebars template. When omitted,\n * the bundled default template (command-render.ts) is used.\n */\n template: z.string().optional(),\n })\n .strip();\n\nexport type ClaudeCommandsEmit = z.infer<typeof ClaudeCommandsEmitSchema>;\n\n/**\n * Normalize the `commands` toggle: a bare `true` becomes an empty override object\n * (all defaults); `false`/absent becomes disabled (undefined).\n */\nconst ClaudeCommandsToggle = z\n .union([z.boolean(), ClaudeCommandsEmitSchema])\n .optional()\n .transform((v): ClaudeCommandsEmit | undefined => {\n if (v === undefined || v === false) return undefined;\n if (v === true) return {};\n return v;\n });\n\n/**\n * Emission toggles for additive Claude artifacts.\n *\n * Backward compatible: with all toggles off (the defaults) the generator emits\n * ONLY the existing `.claude/*` hooks/CLAUDE.md output, byte-for-byte unchanged.\n * - `workflows: true` → one Dynamic Workflow script per workflow (#235).\n * - `commands` (true or an override object) → one slash-command file per\n * workflow (#249).\n * - `agents: true` → one Claude Code subagent file per agent (#272).\n */\nconst ClaudeEmitSchema = z\n .object({\n /** When true, materialize `<output_dir>/workflows/<id>.js` per workflow. */\n workflows: z.boolean().default(false),\n /** When set, materialize one slash-command file per workflow (#249). */\n commands: ClaudeCommandsToggle,\n /**\n * When true, materialize `<output_dir>/agents/<id>.md` per DSL agent, so\n * DSL-declared agents are real Claude Code subagents (#272). In a workspace\n * every member's agents are merged into the single root directory.\n */\n agents: z.boolean().default(false),\n })\n .strip();\n\nexport type ClaudeEmit = z.infer<typeof ClaudeEmitSchema>;\n\nexport const ClaudeConfigSchema = z\n .object({\n /** Root directory for Claude artifacts (relative to the project root). */\n output_dir: z.string().default(\".claude\"),\n /**\n * Agents DSL path (relative to the project root) baked into the generated\n * nav hook bins as the FALLBACK for a project root with no `project.yaml`\n * (a bare component checkout). When a manifest exists it is authoritative:\n * the hooks resolve `agents:` and `artifacts:` from it at hook runtime\n * (#260), so this value is not consulted.\n */\n config_path: z.string().default(\"./agent-contracts.yaml\"),\n /**\n * Additive-artifact emission toggles. Defaults keep the historical\n * behavior (no workflow scripts) so existing output is byte-preserved.\n */\n emit: ClaudeEmitSchema.default({ workflows: false, commands: undefined, agents: false }),\n /**\n * Command wired into guardrail hooks (e.g. \"dev-team guard evaluate\").\n * Reserved for future hook integration; validated for config parity.\n */\n guard_command: z.string().optional(),\n /** Override component id; defaults to `dsl.system.id`. */\n component_id: z.string().optional(),\n })\n .strip();\n\nexport type ClaudeConfig = z.infer<typeof ClaudeConfigSchema>;\n\n/** Parse and default-fill an opaque config payload from component.yaml. */\nexport function parseClaudeConfig(raw: unknown): ClaudeConfig {\n return ClaudeConfigSchema.parse(raw ?? {});\n}\n","/**\n * Claude Dynamic Workflow script codegen (#235).\n *\n * Compiles each agent-contracts workflow in a resolved DSL into ONE Claude\n * Dynamic Workflow script (`<output_dir>/workflows/<id>.js`) — a static\n * artifact, symmetric in spirit to `@aaac/binding-cursor`'s `.cursor/*`\n * output but wired into the existing `claude sync`/`check` commands.\n *\n * The generated `.js` is executed by the Claude Code harness, NOT by aaac's\n * own runtime. It conforms to the target format in the spec (docs/proposal/\n * claude-workflow-codegen.md §2): a pure `meta` object literal plus a body\n * that uses only the documented globals (`agent`/`pipeline`/`parallel`/\n * `phase`/`log`/`workflow`/`args`/`budget`). No `Date.now`/`Math.random`/\n * argless `new Date()`.\n *\n * The DSL→script mapping mirrors `workflow-runner.ts` semantics:\n * - delegate → `agent(renderedPrompt, { schema, label, phase, model, effort })`\n * - gate → LLM-evaluator `agent()` (reusing `buildGateEvaluationPrompt`)\n * followed by a plain JS `if` branch\n * - evaluate → a bounded `while` loop honoring loop_to/max_iterations/on_exhausted\n * - depends_on → parallel()/sequential grouping via the runner's DAG rules\n * - model_class → model/effort\n *\n * `decision`/`team_task` are OUT OF SCOPE: the codegen throws a clear error so\n * they are never silently dropped.\n */\n\nimport { resolveSchemaRefs } from \"agent-contracts\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport {\n buildTaskPrompt,\n type AgentContractLike,\n type TaskContractLike,\n} from \"../task-runner.js\";\nimport type { ModelClass } from \"../model-resolver.js\";\nimport { buildAgentRegistry } from \"../dsl-context.js\";\nimport { buildGateEvaluationPrompt, type GateStep } from \"../workflow-runner.js\";\nimport { WORKFLOW_INPUT_STEP_ID, stepDependsOnWorkflowInput } from \"../workflow-input.js\";\nimport { mergeSourceFiles, originLabel, type DslSource } from \"./dsl-sources.js\";\n\n/** A file to be materialized (path relative to project root). */\nexport interface RenderedFile {\n path: string;\n content: string;\n}\n\n/**\n * Auto-generated banner. Mirrors the cursor binding's `render.ts` convention so\n * `check` can detect hand edits. A leading `//` line keeps the file valid JS.\n */\nconst GENERATED_MARKER =\n \"// Auto-generated by @aaac/runtime claude-materialize (#235). Do not edit; run `claude sync` instead.\";\n\n/**\n * model_class → model/effort mapping (spec §3.4). Absent model_class → omit\n * (inherit from the harness default).\n *\n * Keyed by the declared vocabulary: a class added to the `model_mapping`\n * declaration and left out here is a compile error, not a generated workflow\n * that silently drops the class's routing. Which Claude model a new class maps\n * to is a choice this file cannot derive.\n */\nconst MODEL_CLASS_MAP: Record<ModelClass, { model: string; effort?: string }> = {\n fast: { model: \"haiku\" },\n standard: { model: \"sonnet\" },\n thinking: { model: \"opus\", effort: \"high\" },\n};\n\n// ---------------------------------------------------------------------------\n// Minimal duck-typed views of the resolved DSL\n// ---------------------------------------------------------------------------\n\nexport interface RawStep {\n type: string;\n task?: string;\n from_agent?: string;\n gate_kind?: string;\n description?: string;\n depends_on?: string[];\n /** See the note on `buildWorkflowStep` (dsl-context.ts) for the `x-` prefix. */\n \"x-instruction\"?: string;\n loop_to?: string;\n max_iterations?: number;\n inject_as?: string;\n on_exhausted?: \"abort\" | \"fail_partial\" | \"escalate\";\n}\n\nexport interface RawWorkflow {\n description?: string;\n trigger?: string;\n steps?: RawStep[];\n}\n\ninterface RawHandoffType {\n schema?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/** Thrown when a workflow contains an out-of-scope or malformed step. */\nexport class WorkflowCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WorkflowCodegenError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// JS literal emission (plain-JS-safe, single-quoted, no interpolation)\n// ---------------------------------------------------------------------------\n\n/** Emit a JS string literal (single-quoted) for an arbitrary string. */\nfunction jsString(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\")}'`;\n}\n\n/** Emit a JS value literal (recursively) — used for `meta` and schemas. */\nfunction jsLiteral(value: unknown, indent = 0): string {\n const pad = \" \".repeat(indent);\n const padIn = \" \".repeat(indent + 1);\n\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"null\";\n if (typeof value === \"string\") return jsString(value);\n\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n const items = value.map((v) => `${padIn}${jsLiteral(v, indent + 1)}`);\n return `[\\n${items.join(\",\\n\")}\\n${pad}]`;\n }\n\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n if (entries.length === 0) return \"{}\";\n const lines = entries.map(\n ([k, v]) => `${padIn}${jsKey(k)}: ${jsLiteral(v, indent + 1)}`,\n );\n return `{\\n${lines.join(\",\\n\")}\\n${pad}}`;\n }\n\n return \"null\";\n}\n\n/** Emit an object key: a bare identifier when safe, otherwise a quoted string. */\nfunction jsKey(key: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : jsString(key);\n}\n\n// ---------------------------------------------------------------------------\n// DAG grouping (mirrors workflow-runner.ts depends_on resolution)\n// ---------------------------------------------------------------------------\n\n/** Stable identity of a step for depends_on resolution (matches the runner). */\nfunction stepIdentity(step: RawStep): string {\n if (step.type === \"gate\") return `gate:${step.gate_kind ?? \"\"}`;\n return step.task ?? \"\";\n}\n\n/**\n * Resolve each step's dependency indices exactly as `runWorkflow` does:\n * if `depends_on` is set, map each named dep to the preceding step index\n * (dropping the virtual `workflow-input` entry node); otherwise depend on all\n * preceding steps (sequential default).\n */\nfunction resolveDeps(steps: RawStep[]): number[][] {\n return steps.map((step, i) => {\n if (step.depends_on !== undefined) {\n return step.depends_on\n .filter((dep) => dep !== \"workflow-input\")\n .map((dep) => {\n const idx = steps.findIndex((s, j) => j < i && stepIdentity(s) === dep);\n if (idx === -1) {\n throw new WorkflowCodegenError(\n `depends_on \"${dep}\" in step ${i} (${stepIdentity(step)}) not found among preceding steps`,\n );\n }\n return idx;\n });\n }\n return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);\n });\n}\n\n/**\n * Topologically group steps into ordered \"waves\". Each wave is the set of steps\n * whose dependencies are all satisfied by earlier waves — the same readiness\n * rule the runner uses to batch steps into a `Promise.all`. A wave with more\n * than one member compiles to `parallel([...])`; a singleton wave runs inline.\n */\nfunction computeWaves(steps: RawStep[], deps: number[][]): number[][] {\n const completed = new Set<number>();\n const waves: number[][] = [];\n while (completed.size < steps.length) {\n const ready: number[] = [];\n for (let i = 0; i < steps.length; i++) {\n if (completed.has(i)) continue;\n if (deps[i].every((d) => completed.has(d))) ready.push(i);\n }\n if (ready.length === 0) {\n throw new WorkflowCodegenError(\n \"Dependency cycle detected: no steps are ready to schedule\",\n );\n }\n waves.push(ready);\n for (const i of ready) completed.add(i);\n }\n return waves;\n}\n\n// ---------------------------------------------------------------------------\n// Prompt / schema helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build the STATIC part of the rendered delegate prompt the runtime sends via\n * runTask (buildTaskPrompt over the resolved agent + task contracts). The step's\n * `instruction` (falling back to a generic placeholder) plays the role of the\n * per-invocation user_request.\n *\n * Prior-step context is deliberately NOT baked in here: in the Claude Workflow\n * harness each `agent()` is an independent subagent that does NOT auto-inherit\n * upstream outputs. The generated script therefore threads the accumulated\n * prior-step context into each call at RUN TIME (see `priorContextExpr` /\n * `withPriorContext`), mirroring how `workflow-runner.ts` builds `prior_context`\n * from the dependency chain and passes it to each step.\n */\nfunction renderDelegatePrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n step: RawStep,\n): string {\n const userRequest = (step[\"x-instruction\"] ?? step.description ?? \"\").trim() || \"Perform the task described above.\";\n return buildTaskPrompt(agent, task, { user_request: userRequest });\n}\n\n/**\n * The runtime prefix that introduces threaded prior-step context, matching the\n * `## Prior Context` section `buildSplitTaskPrompt` emits (a section separated\n * from the static prompt by `\\n\\n---\\n\\n`). Concatenated with the runtime\n * context string when a step has upstream dependencies.\n */\nconst PRIOR_CONTEXT_PREFIX = \"\\n\\n---\\n\\n## Prior Context\\n\";\n\nconst GATE_SCHEMA = {\n type: \"object\",\n properties: {\n approved: { type: \"boolean\" },\n reason: { type: \"string\" },\n },\n required: [\"approved\"],\n} as const;\n\n/**\n * Resolve a task's result-handoff JSON Schema into a self-contained\n * (`$ref`-free) schema via agent-contracts' resolveSchemaRefs. Returns\n * undefined when the task has no handoff or the type is unknown.\n */\nfunction resolveHandoffSchema(\n task: TaskContractLike,\n handoffTypes: Record<string, RawHandoffType>,\n components: Record<string, Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n const id = task.result_handoff;\n if (!id) return undefined;\n const ht = handoffTypes[id];\n if (!ht?.schema) return undefined;\n return resolveSchemaRefs(ht.schema, components);\n}\n\n// ---------------------------------------------------------------------------\n// Registries derived from the resolved DSL\n// ---------------------------------------------------------------------------\n\ninterface Registries {\n agents: Record<string, AgentContractLike>;\n tasks: Record<string, TaskContractLike>;\n handoffTypes: Record<string, RawHandoffType>;\n components: Record<string, Record<string, unknown>>;\n}\n\nfunction toTaskContract(id: string, raw: Record<string, unknown>): TaskContractLike {\n return {\n id,\n description: (raw.description as string) ?? \"\",\n target_agent: (raw.target_agent as string) ?? \"\",\n result_handoff: (raw.result_handoff as string) ?? \"\",\n completion_criteria: (raw.completion_criteria as string[]) ?? [],\n model_class: raw.model_class as ModelClass | undefined,\n };\n}\n\nfunction buildRegistries(dsl: Record<string, unknown>): Registries {\n const rawTasks = (dsl.tasks as Record<string, Record<string, unknown>>) ?? {};\n // Agent normalization is shared with the execution path and with the\n // `.claude/agents/*.md` emitter — one definition in dsl-context.ts.\n const agents = buildAgentRegistry(dsl);\n const tasks: Record<string, TaskContractLike> = {};\n for (const [id, t] of Object.entries(rawTasks)) tasks[id] = toTaskContract(id, t);\n const componentsRoot = (dsl.components as Record<string, unknown>) ?? {};\n const components =\n (componentsRoot.schemas as Record<string, Record<string, unknown>>) ??\n (componentsRoot as Record<string, Record<string, unknown>>);\n return {\n agents,\n tasks,\n handoffTypes: (dsl.handoff_types as Record<string, RawHandoffType>) ?? {},\n components,\n };\n}\n\n// ---------------------------------------------------------------------------\n// meta header\n// ---------------------------------------------------------------------------\n\n/**\n * Phase groups: one `phases[]` entry per emitted phase title, in emission\n * order. Delegate steps map to a phase named after their step; gate steps map\n * to a single \"Gate\" phase.\n */\nfunction phaseTitle(step: RawStep): string {\n if (step.type === \"gate\") return \"Gate\";\n return step.task ?? \"Step\";\n}\n\nfunction buildMeta(\n id: string,\n wf: RawWorkflow,\n steps: RawStep[],\n): Record<string, unknown> {\n const seen = new Set<string>();\n const phases: Array<{ title: string; detail?: string }> = [];\n for (const step of steps) {\n const title = phaseTitle(step);\n if (seen.has(title)) continue;\n seen.add(title);\n const detail = (step.description ?? \"\").trim().split(\"\\n\")[0]?.trim();\n phases.push(detail ? { title, detail } : { title });\n }\n\n const meta: Record<string, unknown> = {\n name: id,\n description: (wf.description ?? \"\").trim() || id,\n };\n if (wf.trigger) meta.whenToUse = wf.trigger.trim();\n if (phases.length > 0) meta.phases = phases;\n return meta;\n}\n\n// ---------------------------------------------------------------------------\n// Per-step body emission\n// ---------------------------------------------------------------------------\n\nfunction agentOpts(\n task: TaskContractLike,\n step: RawStep,\n handoffSchema: Record<string, unknown> | undefined,\n indent: number,\n): string {\n const opts: Record<string, unknown> = {};\n if (handoffSchema) opts.schema = handoffSchema;\n opts.label = task.id;\n opts.phase = phaseTitle(step);\n const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : undefined;\n if (mc) {\n opts.model = mc.model;\n if (mc.effort) opts.effort = mc.effort;\n }\n return jsLiteral(opts, indent);\n}\n\n/** The result-variable name a step's captured `agent()`/gate output binds to. */\nfunction resultVar(i: number): string {\n return `step${i}Result`;\n}\n\n/**\n * Emit the run-time expression that reconstructs the accumulated prior-step\n * context for step `i`, mirroring `workflow-runner.ts` `contextFor`/`stepContexts`.\n *\n * The runner formats each dependency's output as\n * `\\n\\n--- Step {d+1}: {stepId(d)} ---\\n{data as string or pretty JSON}`\n * and joins the chain. Here each dependency's captured result variable is\n * formatted by the emitted `_ctx` helper and the fragments are concatenated. A\n * gate step contributes no output fragment (it is a control-flow branch), so\n * gate indices are excluded from every downstream dependency chain — matching\n * the runner, where a gate result carries no `data`.\n *\n * When the step DSL-declares `depends_on: [workflow-input]`, the runtime\n * `contextFor` prepends `formatWorkflowInputContext(workflowInputOutput)` to the\n * chain (BEFORE the output-bearing deps). We mirror that here by emitting a\n * leading `_wfInput(args)` fragment — the run-time equivalent of materializing\n * the Workflow tool's `args` global as the `workflow-input` output node (#244).\n *\n * Returns `\"\"` when the step has neither workflow-input nor any output-bearing\n * dependency (the runner passes an empty prior_context in that case).\n */\nfunction priorContextExpr(i: number, steps: RawStep[], deps: number[][]): string {\n const fragments: string[] = [];\n if (stepDependsOnWorkflowInput(steps[i].depends_on)) {\n fragments.push(\"_wfInput(args)\");\n }\n const contribs = deps[i].filter((d) => steps[d].type !== \"gate\");\n for (const d of contribs) {\n fragments.push(`_ctx(${d + 1}, ${jsString(stepIdentity(steps[d]))}, ${resultVar(d)})`);\n }\n if (fragments.length === 0) return \"\";\n return fragments.join(\" + \");\n}\n\n/**\n * Emit the `_wfInput` helper — the run-time equivalent of materializing the\n * Workflow tool's `args` global as the virtual `workflow-input` output node and\n * formatting it for injection into a step's prior context (#244).\n *\n * Faithfully mirrors `workflow-input.ts`:\n * - `buildWorkflowInputOutput(user_request, handoff?)` →\n * `{ user_request, ...(handoff ? { handoff: { type, [version], payload } } : {}) }`\n * - `formatWorkflowInputContext(output)` →\n * `\\n\\n--- Step: workflow-input ---\\n${JSON.stringify(output, null, 2)}`\n *\n * `args` shapes (mirroring WorkflowInvocation → resolveInvocation → buildWorkflowInputOutput):\n * - string → user_request (the simple-string convenience input)\n * - object with `user_request` and/or `handoff` → those fields carried through\n * (a typed handoff: user_request falls back to the stringified payload, as\n * resolveInvocation does)\n * - any other object → treated as a typed handoff payload of type\n * `workflow-input`, with user_request = its pretty-printed JSON\n * - undefined/null → '' (no injection; backward-compatible static fallback)\n */\nfunction emitWorkflowInputHelper(pad: string): string[] {\n const id = WORKFLOW_INPUT_STEP_ID;\n // A single arrow function, authored at column 0 then indented, so the whole\n // helper is one emitted statement (const _wfInput = (args) => { ... }).\n return [\n `${pad}const _wfInput = (args) => {`,\n `${pad} if (args === undefined || args === null) return ''`,\n `${pad} let output`,\n `${pad} if (typeof args === 'string') {`,\n `${pad} output = { user_request: args }`,\n `${pad} } else if (typeof args === 'object' && ('user_request' in args || 'handoff' in args)) {`,\n `${pad} const h = args.handoff`,\n `${pad} const userRequest = typeof args.user_request === 'string'`,\n `${pad} ? args.user_request`,\n `${pad} : h`,\n `${pad} ? (typeof h.payload === 'string' ? h.payload : JSON.stringify(h.payload, null, 2))`,\n `${pad} : ''`,\n `${pad} output = h`,\n `${pad} ? { user_request: userRequest, handoff: (h.version !== undefined ? { type: h.type, version: h.version, payload: h.payload } : { type: h.type, payload: h.payload }) }`,\n `${pad} : { user_request: userRequest }`,\n `${pad} } else {`,\n `${pad} output = { user_request: JSON.stringify(args, null, 2), handoff: { type: ${jsString(id)}, payload: args } }`,\n `${pad} }`,\n `${pad} return '\\\\n\\\\n--- Step: ${id} ---\\\\n' + JSON.stringify(output, null, 2)`,\n `${pad}}`,\n ];\n}\n\n/**\n * A loop-injected feedback variable to append to a step's prompt, matching the\n * runner merging `inject_as` feedback into a step's `variables` (rendered as a\n * `## Context Variables` line). Present only for steps re-run inside an\n * evaluate loop that declares `inject_as`.\n */\ninterface FeedbackInjection {\n /** The `inject_as` key (the context-variable name). */\n injectAs: string;\n /** The JS variable holding the current iteration's feedback text. */\n feedbackVar: string;\n}\n\n/**\n * Wrap a static base prompt so the threaded prior-step context (and, inside an\n * evaluate loop, the injected feedback) is appended at run time — mirroring the\n * runner passing `prior_context` + merged `variables` into each step. When the\n * step has neither upstream output nor injected feedback, the base prompt is\n * emitted verbatim.\n *\n * The `## Prior Context` header is only appended when the run-time context\n * string is non-empty, mirroring workflow-runner/buildSplitTaskPrompt which\n * emits the section only `if (context.prior_context)`. This matters for a step\n * that depends ONLY on `workflow-input`: when the `args` global is undefined\n * (backward-compat static invocation), `_wfInput(args)` yields '' and the step\n * falls back to its static prompt with no dangling header (#244).\n */\nfunction withPriorContext(\n basePromptLiteral: string,\n ctxExpr: string,\n feedback?: FeedbackInjection,\n): string {\n let expr = basePromptLiteral;\n if (ctxExpr) {\n // Guard on the run-time context value so an empty context (e.g. undefined\n // `args` for a workflow-input-only step) omits the section entirely.\n expr = `${expr} + ((${ctxExpr}) ? ${jsString(PRIOR_CONTEXT_PREFIX)} + (${ctxExpr}) : '')`;\n }\n if (feedback) {\n // Emitted only inside the loop, so the guard skips the first iteration\n // (feedbackVar is still undefined then) — matching the runner, which only\n // injects feedback on loop-back, not on the initial pass.\n const varSection = `${jsString(`\\n\\n---\\n\\n## Context Variables\\n\\n- ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;\n expr = `${expr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;\n }\n return expr;\n}\n\n/**\n * Resolve the (agent, task) pair for a delegate/evaluate step, throwing the\n * appropriate WorkflowCodegenError when unknown.\n */\nfunction resolveStepAgentTask(\n step: RawStep,\n reg: Registries,\n kind: \"delegate\" | \"evaluate\",\n): { agent: AgentContractLike; task: TaskContractLike; taskId: string } {\n const taskId = step.task ?? \"\";\n const task = reg.tasks[taskId];\n if (!task) {\n throw new WorkflowCodegenError(`${kind} step references unknown task \"${taskId}\"`);\n }\n const agent = reg.agents[task.target_agent] ?? reg.agents[step.from_agent ?? \"\"];\n if (!agent) {\n throw new WorkflowCodegenError(\n `${kind} task \"${taskId}\" targets unknown agent \"${task.target_agent}\"`,\n );\n }\n return { agent, task, taskId };\n}\n\n/**\n * Emit the JS expression that runs a single delegate step (an `agent()` call),\n * threading the step's accumulated prior-step context into the prompt at run\n * time.\n */\nfunction emitDelegateExpr(\n step: RawStep,\n reg: Registries,\n i: number,\n steps: RawStep[],\n deps: number[][],\n indent: number,\n feedback?: FeedbackInjection,\n): string {\n const { agent, task } = resolveStepAgentTask(step, reg, \"delegate\");\n const prompt = renderDelegatePrompt(agent, task, step);\n const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);\n const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);\n const opts = agentOpts(task, step, schema, indent);\n return `agent(${promptExpr}, ${opts})`;\n}\n\n/**\n * Emit the statements for a gate step: an LLM-evaluator `agent()` call reusing\n * buildGateEvaluationPrompt, then a plain JS `if` branch (spec §3.2).\n *\n * The gate evaluator receives the ACTUAL accumulated prior-step results,\n * threaded at run time (mirroring `evaluateGateWithLlm`, which feeds prior\n * results into `buildGateEvaluationPrompt`). The static template only holds the\n * gate kind + condition; the prior-results section is appended at run time.\n */\nfunction emitGateStatements(\n step: RawStep,\n i: number,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n feedback?: FeedbackInjection,\n): string[] {\n const gateStep: GateStep = {\n type: \"gate\",\n gate_kind: step.gate_kind ?? \"\",\n description: step.description ?? \"\",\n };\n // Split buildGateEvaluationPrompt at its \"## Prior Step Results\" section so\n // the run-time prior context (the same fragments delegate steps receive) can\n // be spliced in where the runner puts prior results.\n const marker = \"## Prior Step Results\\n\";\n const full = buildGateEvaluationPrompt(gateStep, \"__PRIOR__\");\n const at = full.indexOf(marker) + marker.length;\n const head = full.slice(0, at);\n const tail = full.slice(at).replace(/^__PRIOR__/, \"\");\n const ctxExpr = priorContextExpr(i, steps, deps);\n let promptExpr = ctxExpr\n ? `${jsLiteral(head)} + (${ctxExpr}) + ${jsLiteral(tail)}`\n : jsLiteral(full.replace(\"__PRIOR__\", \"(no prior results)\"));\n if (feedback) {\n const varSection = `${jsString(`\\n\\n## Context Variables\\n\\n- ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;\n promptExpr = `${promptExpr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;\n }\n const label = `gate:${gateStep.gate_kind}`;\n const lines: string[] = [];\n lines.push(`${pad}const gate = await agent(${promptExpr}, {`);\n lines.push(`${pad} schema: ${jsLiteral(GATE_SCHEMA, 0).replace(/\\n/g, `\\n${pad} `)},`);\n lines.push(`${pad} label: ${jsString(label)},`);\n lines.push(`${pad} phase: 'Gate',`);\n lines.push(`${pad}})`);\n lines.push(`${pad}if (!gate.approved) {`);\n lines.push(`${pad} return { blocked: true, gate: ${jsString(gateStep.gate_kind)}, reason: gate.reason }`);\n lines.push(`${pad}}`);\n return lines;\n}\n\n/**\n * Emit the `await agent(...)` call for the evaluate step's convergence task.\n * The evaluate task, like a delegate, receives the accumulated prior-step\n * context threaded at run time, plus any feedback injected on loop-back.\n */\nfunction emitEvaluateAgentCall(\n step: RawStep,\n reg: Registries,\n i: number,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n feedback?: FeedbackInjection,\n): string {\n const { agent, task } = resolveStepAgentTask(step, reg, \"evaluate\");\n const prompt = renderDelegatePrompt(agent, task, step);\n const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);\n const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);\n const opts: Record<string, unknown> = {};\n if (schema) opts.schema = schema;\n opts.label = task.id;\n opts.phase = phaseTitle(step);\n const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : undefined;\n if (mc) {\n opts.model = mc.model;\n if (mc.effort) opts.effort = mc.effort;\n }\n const optsLiteral = jsLiteral(opts, 0).replace(/\\n/g, `\\n${pad}`);\n return `await agent(${promptExpr}, ${optsLiteral})`;\n}\n\n/**\n * Emit the statements for a single non-evaluate step (delegate or gate),\n * capturing the step's output into its result variable so downstream steps can\n * thread it as prior context. Used both in the linear body and inside an\n * evaluate loop body when re-running the `loop_to..evaluate` span.\n */\nfunction emitStepStatements(\n i: number,\n reg: Registries,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n opts?: { assign?: boolean; feedback?: FeedbackInjection },\n): string[] {\n const step = steps[i];\n const feedback = opts?.feedback;\n if (step.type === \"delegate\") {\n const expr = emitDelegateExpr(step, reg, i, steps, deps, pad.length / 2 + 1, feedback);\n // `assign` mode: the result var is pre-declared with `let` (span steps\n // re-run inside an evaluate loop). Otherwise declare with `const`.\n const lhs = opts?.assign ? resultVar(i) : `const ${resultVar(i)}`;\n return [`${pad}${lhs} = await ${expr}`];\n }\n if (step.type === \"gate\") {\n // A gate never loops back and yields no output fragment; emit its branch.\n return emitGateStatements(step, i, steps, deps, pad, feedback);\n }\n throw new WorkflowCodegenError(`emitStepStatements called with non-simple step type \"${step.type}\"`);\n}\n\n/**\n * Emit an evaluate step as a bounded loop that RE-RUNS the `loop_to..evaluate`\n * span on each failing iteration (mirroring `workflow-runner.ts`, which resets\n * and re-executes steps `[loopToIdx, i]`). Steps before `loop_to` have already\n * run once in the linear body; only the span is re-executed here.\n *\n * Iteration bound matches the runner: `max_iterations = N` → up to N executions\n * of the span, escalating/aborting only once the Nth evaluation still fails.\n * The gap feedback from the failed evaluation is injected (via `inject_as`)\n * into the re-run so the upstream step sees it.\n */\nfunction emitEvaluateLoop(\n evalIdx: number,\n reg: Registries,\n steps: RawStep[],\n deps: number[][],\n): string[] {\n const step = steps[evalIdx];\n const taskId = step.task ?? \"\";\n const loopTo = step.loop_to ?? \"\";\n const maxIter = step.max_iterations ?? 1;\n const onExhausted = step.on_exhausted ?? \"escalate\";\n const injectAs = step.inject_as;\n\n // Locate the loop_to target among preceding steps (matches the runner).\n const loopToIdx = steps.findIndex((s, j) => j < evalIdx && stepIdentity(s) === loopTo);\n if (loopToIdx === -1) {\n throw new WorkflowCodegenError(\n `evaluate step \"${taskId}\" references unknown loop_to \"${loopTo}\"`,\n );\n }\n\n // The span [loopToIdx, evalIdx-1] is re-run inside the loop; the evaluate\n // agent call is the last statement of the loop body.\n const spanIndices: number[] = [];\n for (let k = loopToIdx; k < evalIdx; k++) spanIndices.push(k);\n\n const iterVar = `${resultVar(evalIdx)}Iteration`;\n const feedbackVar = injectAs ? `${resultVar(evalIdx)}Feedback` : undefined;\n const feedback: FeedbackInjection | undefined =\n injectAs && feedbackVar ? { injectAs, feedbackVar } : undefined;\n\n const lines: string[] = [];\n lines.push(` // evaluate: ${taskId} — bounded convergence loop, re-runs steps ${loopTo}..${taskId} (max ${maxIter})`);\n // Pre-declare span result vars with `let` so they are visible to steps after\n // the loop (which may depend_on them) and reassignable across iterations.\n for (const k of spanIndices) {\n if (steps[k].type !== \"gate\") lines.push(` let ${resultVar(k)}`);\n }\n lines.push(` let ${resultVar(evalIdx)}`);\n lines.push(` let ${iterVar} = 0`);\n if (feedbackVar) lines.push(` let ${feedbackVar}`);\n lines.push(` while (true) {`);\n lines.push(` ${iterVar} = ${iterVar} + 1`);\n // Re-run the loop_to..evaluate span. On iterations after the first, the\n // upstream steps see the injected feedback appended to their prior context.\n for (const k of spanIndices) {\n for (const stmt of emitStepStatements(k, reg, steps, deps, \" \", { assign: true, feedback })) {\n lines.push(stmt);\n }\n }\n // The evaluate agent call itself, receiving prior context + injected feedback.\n const evalCall = emitEvaluateAgentCall(step, reg, evalIdx, steps, deps, \" \", feedback);\n lines.push(` ${resultVar(evalIdx)} = ${evalCall}`);\n lines.push(` if (${resultVar(evalIdx)}.verdict === 'pass') break`);\n lines.push(` if (${iterVar} >= ${maxIter}) {`);\n if (onExhausted === \"abort\") {\n lines.push(` throw new Error('evaluate \"${taskId}\" exhausted ${maxIter} iterations without passing')`);\n } else if (onExhausted === \"fail_partial\") {\n lines.push(` log('evaluate \"${taskId}\" exhausted iterations — proceeding with partial result')`);\n lines.push(` break`);\n } else {\n lines.push(` return { escalated: true, evaluate: ${jsString(taskId)}, reason: 'exhausted ' + ${iterVar} + ' iterations without passing' }`);\n }\n lines.push(` }`);\n // Inject the failed evaluation's feedback so the re-run of the span sees it.\n if (feedbackVar) {\n lines.push(` ${feedbackVar} = typeof ${resultVar(evalIdx)}.feedback === 'string' ? ${resultVar(evalIdx)}.feedback : JSON.stringify(${resultVar(evalIdx)})`);\n lines.push(` log('evaluate \"${taskId}\" failed — re-running ${loopTo}..${taskId} with feedback as ${injectAs} (' + ${iterVar} + '/' + ${maxIter} + ')')`);\n } else {\n lines.push(` log('evaluate \"${taskId}\" failed — re-running ${loopTo}..${taskId} (' + ${iterVar} + '/' + ${maxIter} + ')')`);\n }\n lines.push(` }`);\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Workflow → script\n// ---------------------------------------------------------------------------\n\nfunction assertInScope(step: RawStep): void {\n if (step.type === \"decision\" || step.type === \"team_task\") {\n throw new WorkflowCodegenError(\n `Step type \"${step.type}\" is out of scope for #235 (only delegate/gate/evaluate are supported). ` +\n `Remove it from the workflow or extend the codegen before enabling workflow output.`,\n );\n }\n if (step.type !== \"delegate\" && step.type !== \"gate\" && step.type !== \"evaluate\") {\n throw new WorkflowCodegenError(`Unknown workflow step type \"${step.type}\"`);\n }\n}\n\n/**\n * Compile a single workflow into a Dynamic Workflow script string.\n *\n * `dsl` is the resolved DSL (agents/tasks/handoff_types/components); registries\n * are derived from it. Exported for unit testing individual workflows.\n */\nexport function renderWorkflowScript(\n id: string,\n wf: RawWorkflow,\n dsl: Record<string, unknown>,\n): string {\n const reg = buildRegistries(dsl);\n const steps = wf.steps ?? [];\n for (const step of steps) assertInScope(step);\n\n const deps = resolveDeps(steps);\n const waves = computeWaves(steps, deps);\n const meta = buildMeta(id, wf, steps);\n\n // Map each step index to the parallel wave it belongs to (a wave with >1\n // member of all-delegate steps compiles to a `parallel([...])`).\n const waveOf = new Map<number, number>();\n waves.forEach((wave, w) => wave.forEach((i) => waveOf.set(i, w)));\n\n // Loop spans owned by evaluate steps: [loopToIdx, evalIdx]. Steps inside a\n // span are emitted by emitEvaluateLoop (re-run per iteration), NOT by the\n // linear body. `spanOwner[k]` = evalIdx that owns step k (if any).\n const spanOwner = new Map<number, number>();\n for (let e = 0; e < steps.length; e++) {\n if (steps[e].type !== \"evaluate\") continue;\n const loopTo = steps[e].loop_to ?? \"\";\n const loopToIdx = steps.findIndex((s, j) => j < e && stepIdentity(s) === loopTo);\n if (loopToIdx === -1) {\n throw new WorkflowCodegenError(\n `evaluate step \"${steps[e].task ?? \"\"}\" references unknown loop_to \"${loopTo}\"`,\n );\n }\n for (let k = loopToIdx; k <= e; k++) spanOwner.set(k, e);\n }\n\n // Does any step consume upstream output (has an output-bearing dependency)?\n // If so, emit the `_ctx` helper that formats each dependency result exactly\n // as workflow-runner.ts `stepContexts` does.\n const usesStepContext = steps.some(\n (_, i) => deps[i].some((d) => steps[d].type !== \"gate\"),\n );\n // Does any step DSL-declare `depends_on: [workflow-input]`? If so, emit the\n // `_wfInput` helper that materializes the Workflow tool's `args` global as the\n // `workflow-input` output and formats it exactly as workflow-input.ts\n // `buildWorkflowInputOutput` + `formatWorkflowInputContext` do (#244).\n const usesWorkflowInput = steps.some((step) =>\n stepDependsOnWorkflowInput(step.depends_on),\n );\n\n const body: string[] = [];\n if (usesStepContext) {\n // Mirrors workflow-runner.ts: `\\n\\n--- Step N: <id> ---\\n<data>` where\n // string data is used verbatim and structured data is pretty-printed JSON.\n body.push(\n \" const _ctx = (n, id, r) => '\\\\n\\\\n--- Step ' + n + ': ' + id + ' ---\\\\n' + (typeof r === 'string' ? r : JSON.stringify(r, null, 2))\",\n );\n }\n if (usesWorkflowInput) {\n body.push(...emitWorkflowInputHelper(\" \"));\n }\n const emittedWaves = new Set<number>();\n\n for (let i = 0; i < steps.length; i++) {\n // Steps strictly inside a loop span (before its evaluate) are emitted by\n // the evaluate loop; skip them in the linear pass.\n if (spanOwner.has(i) && spanOwner.get(i) !== i) continue;\n\n const step = steps[i];\n if (step.type === \"evaluate\") {\n body.push(...emitEvaluateLoop(i, reg, steps, deps));\n continue;\n }\n\n // Parallel wave: emit the whole wave once, only when it batches >1\n // all-delegate steps that are NOT part of any loop span.\n const w = waveOf.get(i)!;\n const wave = waves[w];\n const batchable =\n wave.length > 1 &&\n wave.every((j) => steps[j].type === \"delegate\" && !spanOwner.has(j));\n if (batchable) {\n if (emittedWaves.has(w)) continue;\n emittedWaves.add(w);\n // Capture the barrier results into each step's result var (parallel()\n // resolves to an array in wave order) so downstream steps can thread them\n // as prior context — mirroring the runner recording each step's output.\n const lhs = wave.map((j) => resultVar(j)).join(\", \");\n body.push(` const [${lhs}] = await parallel([`);\n for (const j of wave) {\n const expr = emitDelegateExpr(steps[j], reg, j, steps, deps, 2);\n body.push(` () => ${expr},`);\n }\n body.push(\" ])\");\n continue;\n }\n\n {\n if (step.type === \"delegate\") {\n body.push(...emitStepStatements(i, reg, steps, deps, \" \"));\n } else if (step.type === \"gate\") {\n body.push(...emitGateStatements(step, i, steps, deps, \" \"));\n }\n }\n }\n\n body.push(\" return { completed: true, workflow: \" + jsString(id) + \" }\");\n\n const metaLiteral = jsLiteral(meta, 0);\n // The Claude Workflow tool extracts `export const meta = {...}` and runs the\n // REMAINDER as a top-level async function body — so the body must be emitted\n // as top-level statements (const/let/await agent()/if/while/return), NOT\n // wrapped in `export default async function () {...}` (#240). The wrapper\n // caused `SyntaxError: Unexpected keyword 'export'` and no workflow launched.\n // De-indent the body one level (it was authored at 2-space base indent for\n // the old function wrapper) so top-level statements sit at column 0.\n const topLevelBody = body\n .map((line) => (line.startsWith(\" \") ? line.slice(2) : line))\n .join(\"\\n\");\n return (\n `${GENERATED_MARKER}\\n\\n` +\n `export const meta = ${metaLiteral}\\n\\n` +\n `${topLevelBody}\\n`\n );\n}\n\n/**\n * Render one Dynamic Workflow script per workflow in each resolved DSL. Returns\n * project-root-relative paths under `<outputDir>/workflows/`.\n *\n * Takes the source list `resolveDslSources()` produces — the SAME input the\n * command and agent emitters receive (#274), so all three materialize the\n * project's effective DSL rather than the bare embedded one. `.claude/workflows/`\n * is a single harness-root directory, so several sources rendering the same path\n * are merged by `mergeSourceFiles` and a genuine difference is a hard error.\n */\nexport function renderWorkflowFiles(\n sources: readonly DslSource[],\n outputDir: string,\n): RenderedFile[] {\n const dir = workflowsDirFor(outputDir);\n return mergeSourceFiles(\n sources.map((source) => ({\n origin: originLabel(source),\n files: Object.entries(\n (source.dsl.workflow as Record<string, RawWorkflow>) ?? {},\n ).map(([id, wf]) => ({\n path: `${dir}/${pathSegmentForId(\"workflow id\", id)}${WORKFLOW_FILE_EXT}`,\n content: renderWorkflowScript(id, wf, source.dsl),\n })),\n })),\n (message) => new WorkflowCodegenError(message),\n );\n}\n\n/** Extension of every emitted Dynamic Workflow script. */\nexport const WORKFLOW_FILE_EXT = \".js\";\n\n/**\n * Directory the workflow scripts are emitted into. Exported so the drift/orphan\n * scan looks in the same place this renderer writes to, rather than rebuilding\n * the path.\n */\nexport function workflowsDirFor(outputDir: string): string {\n return `${outputDir.replace(/\\/+$/, \"\")}/workflows`;\n}\n","/**\n * The DSLs the `.claude/*` emitters materialize from — ONE resolution rule for\n * every emitter and for both project shapes (#274).\n *\n * `syncClaude` is handed the component's bundled `/$embedded/` DSL, NOT the\n * project's effective one: what a project actually runs is that DSL overlaid\n * with its manifest's `agents:`. Resolving the overlay is therefore part of\n * emitting `.claude/*`, not something the caller can be expected to have done —\n * and it is the same resolution the navigation-index hooks perform, so the\n * `.claude/` contents and the index cannot disagree about which agents exist.\n *\n * A workspace resolves one source per member and a single project resolves one\n * source for itself, but both go through `resolveNavigationSources()` +\n * `resolveNavigationDsl()`. Before #274 only the workspace branch did, so an\n * overlay-declared agent/workflow/command was silently dropped from a single\n * project while the navigation index listed it.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { WorkspaceMemberGenerateConfig } from \"@aaac/contracts\";\nimport {\n loadWorkspaceMembers,\n PROJECT_CONFIG_FILENAME,\n} from \"../../generator/config.js\";\nimport { resolveNavigationSources } from \"../claude-native/navigation-sources.js\";\nimport { resolveNavigationDsl } from \"../navigation-context.js\";\nimport type { ClaudeConfig } from \"./config.js\";\n\n/** One resolved DSL to materialize from, labelled by its origin. */\nexport interface DslSource {\n /**\n * Workspace member this DSL came from, used in collision messages. Absent for\n * a single project, where the project itself is the only origin.\n */\n member?: string;\n /** Resolved DSL: the embedded one overlaid with this root's `agents:`. */\n dsl: Record<string, unknown>;\n}\n\n/** How a source is named in a collision message. */\nexport function originLabel(source: DslSource): string {\n return source.member ?? \"project\";\n}\n\n/**\n * Workspace members for the generator, derived from the project manifest's\n * `workspace:` — the same loader the CLI uses (#263). Members were previously\n * hand-listed in the claude binding config, which meant two sources of truth for\n * the member set and silent staleness when `project.yaml` gained a member.\n *\n * Returns [] when the root declares no workspace, which selects the\n * single-component branch in the generator.\n */\nexport async function workspaceMembersForProject(\n root: string,\n): Promise<WorkspaceMemberGenerateConfig[]> {\n const manifestPath = join(root, PROJECT_CONFIG_FILENAME);\n if (!existsSync(manifestPath)) return [];\n\n const members = await loadWorkspaceMembers(manifestPath);\n return members.map((m) => ({\n name: m.name,\n path: m.path,\n cacheKey: m.cacheKey,\n }));\n}\n\n/**\n * Resolve the DSL sources every `.claude/*` emitter materializes from.\n *\n * The project roots that contribute are the workspace members when the manifest\n * declares a workspace, and otherwise the project root itself — a single project\n * is its own only member, not a different kind of thing. Each root is then\n * resolved by the SAME rule: `resolveNavigationSources()` reads its manifest and\n * `resolveNavigationDsl()` overlays its `agents:` onto the embedded DSL. A root\n * that declares no overlay resolves to the embedded DSL unchanged, so a project\n * without an `agents:` manifest entry emits byte-identical output.\n *\n * This is deliberately NOT what `renderFiles` bakes into the generated hook bins:\n * those carry the EMBEDDED DSL and re-run this resolution at hook time, so a\n * manifest edit takes effect without re-running `claude sync`\n * (navigation-sources.ts). Baking the overlaid DSL there would freeze the\n * overlay at sync time and re-apply it on top of itself.\n */\nexport async function resolveDslSources(\n root: string,\n embeddedDsl: Record<string, unknown>,\n config: ClaudeConfig,\n): Promise<DslSource[]> {\n const members = await workspaceMembersForProject(root);\n const roots: Array<{ member?: string; root: string }> =\n members.length > 0\n ? members.map((m) => ({ member: m.name, root: resolve(root, m.path) }))\n : [{ root }];\n\n return Promise.all(\n roots.map(async ({ member, root: projectRoot }) => {\n const { navigationOptions } = await resolveNavigationSources({\n projectRoot,\n embeddedDsl,\n dslPath: config.config_path,\n });\n const dsl = await resolveNavigationDsl(navigationOptions);\n return member === undefined ? { dsl } : { member, dsl };\n }),\n );\n}\n\n/**\n * Merge what several sources render into the ONE harness-root directory.\n *\n * Claude Code reads `.claude/workflows/` and `.claude/commands/` from the\n * harness root only — the same constraint that forces the agents merge — so in a\n * workspace two members can render to the same path. Identical bytes are the\n * same artifact (the common case: both inherit it unmodified from the shared\n * `/$embedded/` DSL) and merge; different bytes are a conflict that must be\n * loud, because whichever source happened to be rendered last would otherwise\n * silently win.\n *\n * Agents are NOT merged here: an agent's identity is its DSL definition rather\n * than the rendered markdown — the file projects only part of `AgentSchema`, so\n * comparing bytes would let a difference in a non-projected field through in\n * silence. `renderAgentFiles` therefore compares the definitions itself.\n *\n * With a single source this is order-preserving and content-preserving, so a\n * non-workspace project's output is unchanged by the merge existing.\n */\nexport function mergeSourceFiles<T extends { path: string; content: string }>(\n rendered: ReadonlyArray<{ origin: string; files: readonly T[] }>,\n conflict: (message: string) => Error,\n): T[] {\n const merged = new Map<string, { file: T; origin: string }>();\n\n for (const { origin, files } of rendered) {\n for (const file of files) {\n const existing = merged.get(file.path);\n if (existing === undefined) {\n merged.set(file.path, { file, origin });\n continue;\n }\n if (existing.file.content !== file.content) {\n throw conflict(\n `\"${file.path}\" is generated differently by \"${existing.origin}\" and \"${origin}\"; ` +\n `Claude Code reads this directory from the harness root only, so it can hold ` +\n `just one version of the file. Align the two definitions, or rename one of ` +\n `them in the DSL.`,\n );\n }\n }\n }\n\n return [...merged.values()].map((entry) => entry.file);\n}\n","/**\n * Claude Code slash-command artifact codegen (#249).\n *\n * Renders ONE output file per agent-contracts `workflow` from a Handlebars\n * template with a per-workflow context. Symmetric in spirit to the `emit.workflows`\n * codegen (#235, `workflow-render.ts`): a fully-generated, overwrite-owned artifact\n * wired into the SAME `claude sync`/`check` machinery, over the DSL sources\n * `resolveDslSources()` hands it (`dsl-sources.ts`) — this module renders, it\n * never resolves packages or overlays itself.\n *\n * Default use case: turn each workflow into a Claude Code slash command file\n * `.claude/commands/aidev/{name}.md`, so the already-emitted workflows (written\n * `trigger: 'User invokes /aidev.<name> ...'`) become real `/aidev:<name>` slash\n * commands, DSL-driven and regenerable.\n *\n * Handlebars is a build-time devDependency of THIS package: tsup externalizes only\n * `dependencies`/`peerDependencies`, so Handlebars is inlined into `dist/` — and into\n * the self-contained `dist/claude-bundles/full.js`, which runs with no node_modules —\n * rather than resolved from a consumer's install. See `@aaac/binding-cursor`'s\n * `render.ts` for the in-repo usage convention: `Handlebars.create()` +\n * `compile(tpl, { noEscape })` so markdown/frontmatter is emitted verbatim, not\n * HTML-escaped.\n */\n\nimport Handlebars from \"handlebars\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { mergeSourceFiles, originLabel, type DslSource } from \"./dsl-sources.js\";\nimport { yamlScalar } from \"./frontmatter.js\";\nimport type { RenderedFile } from \"./workflow-render.js\";\n\n// Re-export so callers can import the shared type from one place.\nexport type { RenderedFile };\n\n/**\n * Thrown when a workflow is malformed for command generation (e.g. a workflow\n * missing the data the template context requires), or when the config's output\n * path template lacks the required per-item placeholder. Never silently drop —\n * mirrors `WorkflowCodegenError`'s loud-failure convention (workflow-render.ts).\n */\nexport class CommandCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CommandCodegenError\";\n }\n}\n\n/**\n * The per-item placeholder every command output-path template must contain, so\n * one file is produced per workflow at a distinct path. Substituted with the\n * workflow name (its DSL key).\n */\nconst NAME_PLACEHOLDER = \"{name}\";\n\n/** Default output-path template (project-root-relative) for the slash-command use case. */\nexport const DEFAULT_COMMAND_OUTPUT = \".claude/commands/aidev/{name}.md\";\n\n/**\n * Bundled default Handlebars template — the slash-command use case from #249.\n *\n * Emitted verbatim (noEscape). Produces valid Claude Code slash-command markdown:\n * YAML frontmatter with `description` and an `argument-hint`, plus a body that\n * references the workflow name and `$ARGUMENTS`. `whenToUse` (the workflow\n * `trigger`) is surfaced in the body so the command self-documents its intent.\n *\n * Bundled (not a mandatory config path) so the default use case works with a bare\n * `emit.commands: true` — consistent with how the cursor binding ships its\n * templates in-package (`templates.ts`) rather than requiring the consumer to\n * author them. A consumer may override via `emit.commands.template` (a path).\n */\nexport const DEFAULT_COMMAND_TEMPLATE = `---\ndescription: {{yaml description}}\nargument-hint: <request>\n---\n{{#if whenToUse}}{{whenToUse}}\n\n{{/if}}Run the dev-team \\`{{name}}\\` workflow with the following request:\n\n$ARGUMENTS\n`;\n\n/**\n * The per-workflow template context. Exposes at least `name`, `description`, and\n * the workflow trigger (as `whenToUse`, matching the workflow-script `meta`\n * field name), plus `trigger` as an alias so either name works in a custom template.\n */\nexport interface CommandContext {\n /** Workflow name = its DSL key (used for `{name}` substitution too). */\n name: string;\n /** Workflow `description`, trimmed; falls back to the name when absent. */\n description: string;\n /** Workflow `trigger`, trimmed; undefined when the workflow declares none. */\n whenToUse?: string;\n /** Alias of `whenToUse` so a custom template may use either field name. */\n trigger?: string;\n}\n\n/** Minimal duck-typed view of a resolved workflow (subset of RawWorkflow). */\ninterface RawWorkflow {\n description?: string;\n trigger?: string;\n}\n\nconst hb = Handlebars.create();\n\n/**\n * `{{yaml value}}` — emit a value as a valid YAML scalar for use inside YAML\n * frontmatter. #249's purpose is reuse by ARBITRARY embedded-DSL repos, so a\n * workflow `description`/trigger may contain colons, quotes, or embedded\n * newlines that would break raw interpolation into frontmatter (the template\n * renders with `noEscape` for the markdown body). The escaping rule itself is\n * shared with the agent frontmatter emitter — see `frontmatter.ts`.\n */\nhb.registerHelper(\"yaml\", (value: unknown) => new Handlebars.SafeString(yamlScalar(value)));\n\n/** Build the per-workflow context from the resolved workflow definition. */\nexport function buildCommandContext(name: string, wf: RawWorkflow): CommandContext {\n if (!name) {\n throw new CommandCodegenError(\"Workflow has an empty name; cannot generate a command file.\");\n }\n const description = (wf.description ?? \"\").trim() || name;\n const whenToUse = (wf.trigger ?? \"\").trim() || undefined;\n return { name, description, whenToUse, trigger: whenToUse };\n}\n\n/**\n * Substitute the `{name}` placeholder in the output-path template. The\n * placeholder is a path component of the template, so what replaces it must be\n * one too — otherwise a workflow id decides how deep, or how far out of the\n * configured directory, the command file lands.\n */\nfunction substituteName(outputTemplate: string, name: string): string {\n return outputTemplate.split(NAME_PLACEHOLDER).join(pathSegmentForId(\"workflow id\", name));\n}\n\n/**\n * Render one command file per workflow of ONE resolved DSL.\n *\n * The `seenPaths` guard is per-DSL on purpose: two workflows of the same DSL\n * colliding on one output path means the template's placeholder does not\n * separate them, which no merge can fix. Two SOURCES colliding is a different\n * question — answered by `mergeSourceFiles` in the caller.\n */\nfunction renderOneDsl(\n dsl: Record<string, unknown>,\n outputTemplate: string,\n render: (context: CommandContext) => string,\n): RenderedFile[] {\n const workflows = (dsl.workflow as Record<string, RawWorkflow>) ?? {};\n const files: RenderedFile[] = [];\n const seenPaths = new Set<string>();\n\n for (const [name, wf] of Object.entries(workflows)) {\n const context = buildCommandContext(name, wf);\n const path = substituteName(outputTemplate, name);\n if (seenPaths.has(path)) {\n throw new CommandCodegenError(\n `Two workflows resolve to the same command output path \"${path}\"; ` +\n `ensure the output template's \"${NAME_PLACEHOLDER}\" placeholder yields distinct paths.`,\n );\n }\n seenPaths.add(path);\n files.push({ path, content: render(context) });\n }\n return files;\n}\n\n/**\n * Render one command file per workflow in each resolved DSL.\n *\n * Takes the source list `resolveDslSources()` produces — the SAME input the\n * workflow and agent emitters receive (#274), so all three materialize the\n * project's effective DSL rather than the bare embedded one. The command output\n * dir is a single harness-root directory, so several sources rendering the same\n * path are merged by `mergeSourceFiles` and a genuine difference is a hard error.\n *\n * @param sources resolved DSLs, each labelled by its origin\n * @param outputTemplate project-root-relative output path with a `{name}` placeholder\n * @param templateSource Handlebars template source (bundled default or config-provided)\n */\nexport function renderCommandFiles(\n sources: readonly DslSource[],\n outputTemplate: string,\n templateSource: string,\n): RenderedFile[] {\n if (!outputTemplate.includes(NAME_PLACEHOLDER)) {\n throw new CommandCodegenError(\n `Command output path \"${outputTemplate}\" is missing the required per-workflow ` +\n `placeholder \"${NAME_PLACEHOLDER}\"; every workflow would collide on one path.`,\n );\n }\n\n const render = hb.compile(templateSource, { noEscape: true });\n return mergeSourceFiles(\n sources.map((source) => ({\n origin: originLabel(source),\n files: renderOneDsl(source.dsl, outputTemplate, render),\n })),\n (message) => new CommandCodegenError(message),\n );\n}\n","/**\n * YAML frontmatter emission for generated Claude Code markdown artifacts.\n *\n * Both generated Claude artifacts that carry frontmatter — per-workflow slash\n * commands (#249, `command-render.ts`) and per-agent subagent definitions\n * (#272, `agent-render.ts`) — interpolate arbitrary DSL prose into YAML, so the\n * scalar-escaping rule must exist exactly once.\n */\n\n/**\n * Emit a value as a valid YAML scalar.\n *\n * `JSON.stringify` of a string produces a double-quoted flow scalar (`\"...\"`\n * with `\\n` / `\\\"` / `\\\\` escaped). YAML 1.2 is a JSON superset, so a JSON\n * string literal is always a valid YAML double-quoted scalar and round-trips.\n * Single-line values stay readable (e.g. `\"Implement a feature\"`); only\n * genuinely unsafe content (colons, quotes, embedded newlines) is escaped.\n * Non-string values are coerced to string first so the result is always a scalar.\n */\nexport function yamlScalar(value: unknown): string {\n const str = value === undefined || value === null ? \"\" : String(value);\n return JSON.stringify(str);\n}\n\n/**\n * Render a `---`-delimited YAML frontmatter block from ordered key/value pairs.\n * Entries whose value is `undefined` are omitted, so an optional key is simply\n * absent rather than emitted empty.\n */\nexport function renderFrontmatter(\n fields: ReadonlyArray<readonly [key: string, value: string | undefined]>,\n): string {\n const lines = [\"---\"];\n for (const [key, value] of fields) {\n if (value === undefined) continue;\n lines.push(`${key}: ${value}`);\n }\n lines.push(\"---\");\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * Claude Code subagent materialization (#272).\n *\n * Renders ONE `.claude/agents/<id>.md` per agent-contracts `agents:` entry, so a\n * DSL-declared agent is usable as a real Claude Code subagent instead of being\n * transcribed into markdown by hand. Fully generated and overwrite-owned, wired\n * into the SAME `claude sync` / `claude check` machinery as the workflow scripts\n * (#235) and slash commands (#249) — the third artifact of the same shape, so it\n * reuses their drift-detection point rather than introducing a new one.\n *\n * ## What is shared, and what is specific to the file form\n *\n * The body is `renderAgentSystemPrompt` (`lib/candidate-agents.ts`), the same\n * renderer that produces an agent's system prompt in-process, so the two cannot\n * describe one DSL agent differently. The tool grant is `toolGrantForAgent`\n * (`lib/claude-tool-grants.ts`), shared with the Claude adapter.\n *\n * The `description` is NOT `deriveDescription`: that helper takes only the first\n * sentence of `purpose`, which is right for in-process routing (the delegating\n * agent already holds the full DSL context) but not here — a Claude Code\n * subagent is picked from its `description` alone, and purposes written as\n * \"You are the X. Your job is to ...\" collapse to \"You are the X.\" The file form\n * therefore carries `role_name` + the whole `purpose`, which is what the issue's\n * mapping table specifies.\n *\n * ## frontmatter `tools` is the mode grant, not `can_execute_tools`\n *\n * A DSL `can_execute_tools` entry is a DSL tool id (`gh-cli`,\n * `agent-contracts-cli`), not a Claude Code tool name. `tools:` is an allowlist\n * resolved against the available tool pool, so DSL ids there would grant nothing\n * and, if they were the only entries, leave the subagent with an unresolvable\n * list. What decides an agent's Claude Code tool grant is its `mode` plus\n * whether it may invoke other agents, exactly as in-process. The declared DSL\n * tools are surfaced in the body instead, where they belong — they are executed\n * through `Bash`.\n *\n * ## Which agents are materialized, and where\n *\n * `dispatch_only` decides the SURFACE an agent's declared content is rendered\n * to, never whether it is rendered at all. `.claude/agents/` is Claude Code's\n * delegation-target registry, so it holds every agent except the dispatch-only\n * ones: a dispatch-only agent is the entry role that hands work to the others\n * (`buildCandidateAgents` excludes the entry agent from the candidate set for\n * the same reason), and a file there would register the orchestrator as a\n * delegation target of itself.\n *\n * The entry role is the MAIN agent, and the Claude surface a main agent reads is\n * CLAUDE.md — so its body goes into the generated `aaac:claude-native` block\n * instead (`renderEntryAgentPrompt`). Both surfaces are rendered by the one\n * `renderAgentBody`, so the same DSL agent cannot be described two ways.\n *\n * Skipping the file used to be the whole story, and the content had nowhere to\n * go: an agent could declare `dispatch_only: true` alongside mandatory rules and\n * the Claude harness dropped every one of them without a diagnostic, while the\n * Cursor binding — which has no such filter — rendered them. Two bindings, one\n * DSL, two answers to what `dispatch_only` means (#345).\n *\n * The split happens AFTER every source has been compared, never during the\n * merge: whether an agent is dispatch-only is itself part of its definition, so\n * two members disagreeing about it is a conflict — and the most consequential\n * kind, since it decides which surface the orchestrator's prompt lands on.\n *\n * ## Workspace merge\n *\n * Claude Code reads `.claude/agents/` only from the harness root, so in a\n * workspace every member's agents are merged into the single root directory.\n * Two members contributing the same agent name are only compatible when their\n * DSL definitions are identical (the common case: both inherit it unmodified\n * from the shared `/$embedded/` component DSL). A genuine difference is a hard\n * error — `name` is the invocation key, so a file rename cannot separate them\n * and whichever file Claude Code happened to read last would silently win.\n */\n\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { renderAgentSystemPrompt } from \"../candidate-agents.js\";\nimport { buildAgentRegistry } from \"../dsl-context.js\";\nimport { toolGrantForAgent } from \"../claude-tool-grants.js\";\nimport type { AgentContractLike } from \"../task-runner.js\";\nimport { originLabel, type DslSource } from \"./dsl-sources.js\";\nimport { renderFrontmatter, yamlScalar } from \"./frontmatter.js\";\nimport type { RenderedFile } from \"./workflow-render.js\";\n\n// Re-export so callers can import the shared type from one place.\nexport type { RenderedFile };\n\n/**\n * Thrown when the DSL cannot be materialized into Claude Code subagents: an\n * agent id that is not a legal subagent `name`, or a workspace name collision.\n * Never silently drop or overwrite — mirrors `WorkflowCodegenError` /\n * `CommandCodegenError`.\n */\nexport class AgentCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AgentCodegenError\";\n }\n}\n\n/** Subdirectory of the Claude output dir that holds subagent definitions. */\nexport const AGENTS_SUBDIR = \"agents\";\n\n/** Extension of a Claude Code subagent definition file. */\nexport const AGENT_FILE_EXT = \".md\";\n\n/**\n * Claude Code subagent `name` grammar: lowercase letters, digits and hyphens.\n * A `:` is reserved for plugin-scoped names and makes Claude Code reject the\n * file, so an id that cannot be a name is an error rather than a mangled slug.\n *\n * This is Claude Code's naming contract, not a filesystem one — whether the id\n * may be a path component is `pathSegmentForId`'s single answer, asked where\n * the path is built. Narrower than that rule, and for a different reason.\n */\nconst AGENT_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nconst GENERATED_MARKER =\n \"<!-- Auto-generated from the agent-contracts DSL. Do not edit; run `claude sync`. -->\";\n\n/**\n * The project-root-relative directory this emitter owns. Every `*.md` directly\n * inside it is generated; `syncClaude` removes the ones the DSL no longer\n * declares and `checkClaude` reports them.\n */\nexport function agentsDirFor(outputDir: string): string {\n return `${outputDir.replace(/\\/+$/, \"\")}/${AGENTS_SUBDIR}`;\n}\n\n/**\n * Stable serialization of an arbitrary DSL value: object keys sorted, array\n * order preserved. Used as the identity of an agent definition when merging\n * workspace members, so that two members are compared on what the DSL SAYS\n * rather than on what this emitter happens to project into markdown — otherwise\n * a difference in a field the file does not render (`own_artifacts`,\n * `x-copilot`, `x-cursor-exclude`, …) would be dropped in silence.\n */\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (value !== null && typeof value === \"object\") {\n const source = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(source).sort()) {\n out[key] = canonicalize(source[key]);\n }\n return out;\n }\n return value;\n}\n\n/**\n * Bullet list section, omitted when the DSL declares nothing. Absent and empty\n * are the same thing for a permission list, so both are handled here rather\n * than by defaulting each field at its call site.\n */\nfunction listSection(title: string, items: readonly string[] | undefined): string | undefined {\n if (!items || items.length === 0) return undefined;\n return `## ${title}\\n\\n${items.map((i) => `- ${i}`).join(\"\\n\")}`;\n}\n\n/**\n * The sections the shared `renderAgentSystemPrompt` does not carry: the agent's\n * mode and its declared artifact / tool / handoff / validation permissions. They\n * describe what this agent is allowed to touch, which is exactly what a subagent\n * receiving only its own file needs in order to stay inside its lane.\n */\nfunction permissionSections(agent: AgentContractLike): string[] {\n return [\n `## Mode\\n\\n${agent.mode}`,\n listSection(\"Readable Artifacts\", agent.can_read_artifacts),\n listSection(\"Writable Artifacts\", agent.can_write_artifacts),\n listSection(\"Executable Tools\", agent.can_execute_tools),\n listSection(\"Invokable Agents\", agent.can_invoke_agents),\n listSection(\"Returnable Handoffs\", agent.can_return_handoffs),\n listSection(\"Performable Validations\", agent.can_perform_validations),\n ].filter((s): s is string => s !== undefined);\n}\n\n/**\n * The routing hint Claude Code shows when choosing a subagent: the agent's role\n * name followed by its full purpose, flattened to one line.\n */\nfunction agentDescription(agent: AgentContractLike): string {\n const purpose = agent.purpose.replace(/\\s+/g, \" \").trim();\n if (!purpose) return agent.role_name;\n return `${agent.role_name} — ${purpose}`;\n}\n\n/**\n * An agent's prompt body: the shared system prompt plus the permission sections.\n *\n * The ONE renderer for both Claude surfaces — the subagent file below and the\n * CLAUDE.md block an entry agent lands in (`renderEntryAgentPrompt`). Only the\n * envelope differs: frontmatter is Claude Code's subagent-registry syntax, which\n * an entry agent has no entry in, so it belongs to the file form alone.\n */\nfunction renderAgentBody(agent: AgentContractLike): string {\n return [renderAgentSystemPrompt(agent), ...permissionSections(agent)]\n .join(\"\\n\\n\")\n .replace(/\\s+$/, \"\");\n}\n\n/**\n * Render one agent into Claude Code subagent markdown: YAML frontmatter\n * (`name` / `description` / `tools`) followed by the system prompt as the body.\n *\n * No `model` key is emitted: the agent-contracts `AgentSchema` has no\n * agent-level model field (`model_class` is declared per TASK), and per-task\n * model selection is already emitted per `agent()` call by the workflow codegen.\n * Omitting it is Claude Code's documented `inherit`.\n */\nfunction renderAgentFile(name: string, agent: AgentContractLike): string {\n const frontmatter = renderFrontmatter([\n // `name` is validated against AGENT_NAME_PATTERN, so it is always a plain\n // YAML scalar and needs no quoting. `description` is arbitrary DSL prose.\n [\"name\", name],\n [\"description\", yamlScalar(agentDescription(agent))],\n // The Claude Code tool grant follows the contract, never the DSL tool ids.\n [\"tools\", toolGrantForAgent(agent).join(\", \")],\n ]);\n\n const body = [GENERATED_MARKER, renderAgentBody(agent)].join(\"\\n\\n\");\n\n return `${frontmatter}\\n${body}\\n`;\n}\n\n/** Contribution of one source to the merged agent set. */\ninterface AgentContribution {\n /** Normalized contract every source agreed on, used to render the file. */\n agent: AgentContractLike;\n /** Canonical DSL definition — the identity two members are compared on. */\n identity: string;\n /** Origin that produced it, for collision reporting. */\n origin: string;\n}\n\n/**\n * `dispatch_only: true` — the entry/orchestrator role. The ONE spelling of the\n * question, read by both halves of the split below so they cannot answer it\n * differently: an agent is materialized as a subagent file or as the CLAUDE.md\n * main-agent prompt, never as neither and never as both.\n */\nfunction isEntryAgent(agent: AgentContractLike): boolean {\n return agent.dispatch_only === true;\n}\n\n/**\n * Phase 1 — agree. EVERY declared agent is merged, including dispatch-only\n * ones: `dispatch_only` is part of an agent's definition, so two members\n * disagreeing about it must be caught here. Filtering first would let that one\n * field differ in silence, which is the whole failure mode this compare exists\n * to prevent — and it is the field that decides which surface the agent is\n * rendered to.\n *\n * @param dir the agents directory, named in the collision message because it\n * is what can hold only one definition of a given name.\n * @throws {AgentCodegenError} when two sources define the same agent differently.\n */\nfunction mergeAgents(\n sources: readonly DslSource[],\n dir: string,\n): Map<string, AgentContribution> {\n const merged = new Map<string, AgentContribution>();\n\n for (const source of sources) {\n const rawAgents =\n (source.dsl.agents as Record<string, Record<string, unknown>> | undefined) ?? {};\n const registry = buildAgentRegistry(source.dsl);\n\n for (const [name, agent] of Object.entries(registry)) {\n // Compared on the DSL definition, not on the rendered markdown: the file\n // projects only part of AgentSchema, so members differing ONLY in a\n // non-projected field would otherwise merge silently.\n const identity = JSON.stringify(canonicalize(rawAgents[name]));\n const existing = merged.get(name);\n if (existing && existing.identity !== identity) {\n throw new AgentCodegenError(\n `Agent \"${name}\" is defined differently by \"${existing.origin}\" and ` +\n `\"${originLabel(source)}\"; Claude Code keys subagents by frontmatter \\`name\\`, so ` +\n `${dir}/ can hold only one definition of it — including which surface it is ` +\n `materialized to. Align the two definitions, or rename one of them in the DSL.`,\n );\n }\n if (!existing) {\n merged.set(name, { agent, identity, origin: originLabel(source) });\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Render the `.claude/agents/*.md` set for one or more DSLs — the delegatable\n * half of the split. The entry agent's half is `renderEntryAgentPrompt`, and\n * `syncClaude`/`checkClaude` emit both from the one merge, so a dispatch-only\n * agent leaves this set only by arriving in that one.\n *\n * @param sources the DSLs to merge, as resolved by `resolveDslSources()` —\n * one for a single project, one per member for a workspace\n * (each already overlaid on the component's `/$embedded/` DSL).\n * @param outputDir the Claude output dir (project-root-relative, e.g. `.claude`).\n * @throws {AgentCodegenError} on an illegal agent name, or on two sources\n * defining the same agent differently.\n */\nexport function renderAgentFiles(\n sources: readonly DslSource[],\n outputDir: string,\n): RenderedFile[] {\n const dir = agentsDirFor(outputDir);\n\n // Phase 2 — materialize. The entry/orchestrator role is not a delegation\n // target, so it is split off only now, once every source has been compared.\n const files: RenderedFile[] = [];\n for (const [name, { agent, origin }] of mergeAgents(sources, dir)) {\n if (isEntryAgent(agent)) continue;\n\n if (!AGENT_NAME_PATTERN.test(name)) {\n throw new AgentCodegenError(\n `Agent id \"${name}\" (${origin}) is not a valid Claude Code subagent name; ` +\n `names must match ${AGENT_NAME_PATTERN.source} (lowercase letters, digits and hyphens).`,\n );\n }\n files.push({\n path: `${dir}/${pathSegmentForId(\"agent id\", name)}${AGENT_FILE_EXT}`,\n content: renderAgentFile(name, agent),\n });\n }\n\n return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\n/**\n * Render the dispatch-only agents' prompt for the CLAUDE.md `aaac:claude-native`\n * block — the entry half of the same split, from the same merge and the same\n * `renderAgentBody` as the subagent files.\n *\n * `undefined` when the DSL declares no dispatch-only agent, which is what keeps\n * the block byte-identical for a project that has none. Ordered by agent id so a\n * workspace contributing several produces a stable block.\n *\n * No frontmatter and no per-file generated marker: both are subagent-registry\n * syntax, and the block's own `aaac:claude-native` markers already declare the\n * region generated.\n *\n * @param sources as `renderAgentFiles`.\n * @param outputDir as `renderAgentFiles`; the merge names it when reporting a\n * collision, so both halves report one directory.\n * @throws {AgentCodegenError} when two sources define the same agent differently.\n */\nexport function renderEntryAgentPrompt(\n sources: readonly DslSource[],\n outputDir: string,\n): string | undefined {\n const entries = [...mergeAgents(sources, agentsDirFor(outputDir))]\n .filter(([, { agent }]) => isEntryAgent(agent))\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\n if (entries.length === 0) return undefined;\n return entries.map(([, { agent }]) => renderAgentBody(agent)).join(\"\\n\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n claudeGenerator,\n generatedFileRelPath,\n isOwnedByExtension,\n orphanGeneratedFiles,\n type ComponentIR,\n type GeneratedFile,\n} from \"@aaac/contracts\";\nimport {\n AGENT_FILE_EXT,\n agentsDirFor,\n renderAgentFiles,\n renderEntryAgentPrompt,\n} from \"./agent-render.js\";\nimport { parseClaudeConfig, type ClaudeConfig } from \"./config.js\";\nimport {\n resolveDslSources,\n workspaceMembersForProject,\n type DslSource,\n} from \"./dsl-sources.js\";\nimport {\n renderWorkflowFiles,\n workflowsDirFor,\n WORKFLOW_FILE_EXT,\n type RenderedFile,\n} from \"./workflow-render.js\";\nimport {\n renderCommandFiles,\n DEFAULT_COMMAND_OUTPUT,\n DEFAULT_COMMAND_TEMPLATE,\n} from \"./command-render.js\";\nimport {\n HOOK_BIN_DIR,\n isHookBin,\n readBundleMarker,\n recomputeMarkerFromDisk,\n withAssembledHookBins,\n} from \"./bundle-bins.js\";\nimport { mergedSettingsText } from \"./settings-merge.js\";\n\n/**\n * `deleted` is reported for a generated file removed because the DSL no longer\n * declares it (a stale `.claude/agents/*.md` is a live Claude Code subagent, so\n * leaving it behind is the very DSL/harness divergence this generator exists to\n * remove).\n */\nexport type FileAction = \"created\" | \"updated\" | \"unchanged\" | \"deleted\";\n\nexport interface SyncOptions {\n projectRoot: string;\n /** Opaque config payload from component.yaml (validated here). */\n config: unknown;\n /**\n * The component's bundled `/$embedded/` DSL — the value the runtime embeds,\n * BEFORE any project overlay. What a project actually runs is this DSL\n * overlaid with its manifest's `agents:`, and resolving that overlay is this\n * module's job (`resolveDslSources`), not the caller's: the caller cannot know\n * the workspace members, and one caller resolving it differently from another\n * is exactly how `.claude/` came to disagree with the navigation index (#274).\n */\n dsl: Record<string, unknown>;\n /** When true, compute changes without writing. */\n dryRun?: boolean;\n}\n\nexport interface SyncResult {\n files: Array<{ path: string; action: FileAction }>;\n}\n\nexport interface CheckResult {\n inSync: boolean;\n /** `orphaned` = present on disk inside a generated directory, absent from the DSL. */\n drift: Array<{ path: string; reason: \"missing\" | \"changed\" | \"orphaned\" }>;\n}\n\nconst CLAUDE_BLOCK_BEGIN = \"<!-- aaac:claude-native:begin -->\";\nconst CLAUDE_BLOCK_END = \"<!-- aaac:claude-native:end -->\";\n\nfunction buildComponentIR(dsl: Record<string, unknown>, config: ClaudeConfig): ComponentIR {\n const system = dsl.system as { id?: string; version?: string } | undefined;\n const componentId = config.component_id ?? system?.id ?? \"component\";\n\n return {\n schema: \"aaac/0.1\",\n info: {\n id: componentId,\n version: system?.version ?? \"1.0.0\",\n },\n implementation: config.config_path,\n projections: [\"claude\"],\n operations: {},\n };\n}\n\nfunction absPath(root: string, file: GeneratedFile): string {\n return join(root, generatedFileRelPath(file));\n}\n\nasync function readIfExists(path: string): Promise<string | undefined> {\n if (!existsSync(path)) return undefined;\n return readFile(path, \"utf8\");\n}\n\nasync function renderFiles(\n root: string,\n dsl: Record<string, unknown>,\n config: ClaudeConfig,\n entryAgentPrompt: string | undefined,\n): Promise<GeneratedFile[]> {\n const ir = buildComponentIR(dsl, config);\n\n const members = await workspaceMembersForProject(root);\n const workspaceOptions = members.length > 0 ? { members } : undefined;\n\n // #241/#278: `.claude/bin` is the one place the generator's output is not the\n // final byte stream — each bin is assembled self-contained against a shared\n // runtime chunk that is emitted alongside it. Doing that here, at the single\n // point both syncClaude and checkClaude read, is what lets bins and chunks\n // travel the identical write/drift path below.\n return withAssembledHookBins(\n claudeGenerator.generate(ir, {\n outputDir: \"\",\n componentPath: \"\",\n // Bake the resolved DSL into the nav hook bins so a consumer project DSL\n // that `extends: /$embedded/` resolves at hook runtime (#255 follow-up).\n resolvedDslData: dsl,\n workspace: workspaceOptions,\n // The other half of the agent render: a dispatch-only agent has no\n // subagent file, so the CLAUDE.md block is where its prompt reaches\n // Claude (#345). Resolved by the caller from the SAME merge that produced\n // the subagent files.\n entryAgentPrompt,\n }),\n );\n}\n\nfunction mergeClaudeMdBlock(\n existing: string | undefined,\n block: string,\n): { content: string; action: FileAction } {\n const normalizedBlock = block.trimStart();\n\n if (existing === undefined) {\n return { content: normalizedBlock, action: \"created\" };\n }\n\n const beginIdx = existing.indexOf(CLAUDE_BLOCK_BEGIN);\n const endIdx = existing.indexOf(CLAUDE_BLOCK_END);\n\n if (beginIdx === -1 || endIdx === -1) {\n const needsSeparator = existing.length > 0 && !existing.endsWith(\"\\n\");\n const content = existing + (needsSeparator ? \"\\n\" : \"\") + normalizedBlock;\n return { content, action: \"updated\" };\n }\n\n const before = existing.slice(0, beginIdx);\n let after = existing.slice(endIdx + CLAUDE_BLOCK_END.length);\n // `normalizedBlock` already ends with the template's trailing newline, so the\n // matching boundary newline that opens `after` must be dropped — otherwise it\n // is re-added every sync and accumulates one blank line per run (#251). This\n // must fire whether or not the user appended content after the block; the\n // earlier `after === \"\\n\"` guard only covered the no-user-content case.\n if (after.startsWith(\"\\n\")) {\n after = after.slice(1);\n }\n const content = before + normalizedBlock + after;\n\n if (content === existing) {\n return { content: existing, action: \"unchanged\" };\n }\n return { content, action: \"updated\" };\n}\n\nfunction expectedClaudeMdContent(existing: string | undefined, block: string): string {\n return mergeClaudeMdBlock(existing, block).content;\n}\n\nfunction actionForOverwriteTrue(existing: string | undefined, next: string): FileAction {\n if (existing === undefined) return \"created\";\n return existing === next ? \"unchanged\" : \"updated\";\n}\n\n/**\n * `.claude/settings.json` is emitted with `overwrite: true`, but it must NOT be\n * fully clobbered (#248): user-added non-managed hooks are preserved via a\n * JSON managed-region merge (see settings-merge.ts). The managed region is\n * regenerated identically each run, so this stays idempotent, and a fresh\n * project produces byte-identical managed output.\n */\nfunction isSettingsJson(file: GeneratedFile): boolean {\n return file.path === \"settings.json\" && file.targetDir === \".claude\";\n}\n\nfunction resolveContent(\n file: GeneratedFile,\n existing: string | undefined,\n): { content: string; action: FileAction } {\n if (file.path === \"CLAUDE.md\" && file.targetDir === \".\" && !file.overwrite) {\n return mergeClaudeMdBlock(existing, file.content);\n }\n\n if (isSettingsJson(file)) {\n const content = mergedSettingsText(existing, file.content);\n return { content, action: actionForOverwriteTrue(existing, content) };\n }\n\n if (!file.overwrite) {\n if (existing !== undefined) {\n return { content: existing, action: \"unchanged\" };\n }\n if (!file.content) {\n return { content: \"\", action: \"unchanged\" };\n }\n return { content: file.content, action: \"created\" };\n }\n\n const action = actionForOverwriteTrue(existing, file.content);\n return { content: file.content, action };\n}\n\nfunction checkContent(\n file: GeneratedFile,\n existing: string | undefined,\n): \"missing\" | \"changed\" | null {\n if (file.path === \"CLAUDE.md\" && file.targetDir === \".\" && !file.overwrite) {\n if (existing === undefined) return \"missing\";\n const expected = expectedClaudeMdContent(existing, file.content);\n return existing === expected ? null : \"changed\";\n }\n\n if (isSettingsJson(file)) {\n if (existing === undefined) return \"missing\";\n // Drift = the on-disk file does not equal the merged managed region + its\n // own non-managed additions. A user-added hook produces no drift (it is\n // reproduced by the merge); a removed/mutated managed entry does.\n const expected = mergedSettingsText(existing, file.content);\n return existing === expected ? null : \"changed\";\n }\n\n if (!file.overwrite) {\n if (existing === undefined && file.content) return \"missing\";\n return null;\n }\n\n if (existing === undefined) return \"missing\";\n if (existing !== file.content) return \"changed\";\n return null;\n}\n\n/**\n * Additive Claude Dynamic Workflow scripts (#235). Emitted ONLY when\n * `config.emit.workflows` is true; otherwise returns [] so the existing\n * `.claude/*` output is byte-preserved (backward compatible).\n */\nfunction workflowFiles(sources: readonly DslSource[], config: ClaudeConfig): RenderedFile[] {\n if (!config.emit.workflows) return [];\n return renderWorkflowFiles(sources, config.output_dir);\n}\n\n/**\n * The project-root-relative output path template for slash commands, or\n * undefined when commands are not emitted.\n *\n * One source for both the renderer and the orphan scan: the template is what\n * declares which directory the emitter owns, so the two must never resolve it\n * differently.\n */\nfunction commandOutputTemplate(config: ClaudeConfig): string | undefined {\n const commands = config.emit.commands;\n if (!commands) return undefined;\n return commands.output ?? DEFAULT_COMMAND_OUTPUT;\n}\n\n/**\n * Additive per-workflow slash-command files (#249). Emitted ONLY when\n * `config.emit.commands` is set; otherwise returns [] so existing output is\n * byte-preserved (backward compatible).\n *\n * The output path defaults to DEFAULT_COMMAND_OUTPUT and the template to the\n * bundled DEFAULT_COMMAND_TEMPLATE; both are overridable via config. A\n * config-provided template path is read from disk (relative to the project root)\n * — this is the ONE async step, so the helper is async and the caller awaits it.\n */\nasync function commandFiles(\n sources: readonly DslSource[],\n config: ClaudeConfig,\n root: string,\n): Promise<RenderedFile[]> {\n const commands = config.emit.commands;\n if (!commands) return [];\n const outputTemplate = commandOutputTemplate(config)!;\n let templateSource = DEFAULT_COMMAND_TEMPLATE;\n if (commands.template) {\n const templatePath = resolve(root, commands.template);\n // A configured template path that cannot be read is a loud error, never a\n // silent fallback to the default (no silent drops).\n templateSource = await readFile(templatePath, \"utf8\");\n }\n return renderCommandFiles(sources, outputTemplate, templateSource);\n}\n\n/**\n * Additive Claude Code subagent files (#272). Emitted ONLY when\n * `config.emit.agents` is true; otherwise returns [] so existing output is\n * byte-preserved.\n *\n * Claude Code reads `.claude/agents/` only from the harness root, so in a\n * workspace the members' agents must be merged into the single root directory.\n */\nfunction agentFiles(sources: readonly DslSource[], config: ClaudeConfig): RenderedFile[] {\n if (!config.emit.agents) return [];\n return renderAgentFiles(sources, config.output_dir);\n}\n\n/**\n * The other half of `agentFiles` (#345): the dispatch-only agents' prompt for\n * the CLAUDE.md block. A dispatch-only agent is absent from `.claude/agents/`\n * precisely because it belongs here, so the two are called together at every\n * call site — dropping this one restores the silent drop it exists to close.\n *\n * Gated on the same `emit.agents` switch: it is the same emitter deciding where\n * one declared agent goes, not a second feature that could be turned on alone.\n */\nfunction entryAgentPromptFor(\n sources: readonly DslSource[],\n config: ClaudeConfig,\n): string | undefined {\n if (!config.emit.agents) return undefined;\n return renderEntryAgentPrompt(sources, config.output_dir);\n}\n\n/**\n * A `.claude/bin` entry this emitter owns: one carrying the bundle marker.\n *\n * Name is not usable here — bins are extensionless and arbitrarily named by the\n * generator, so a name rule would either miss stale bins or match a consumer's\n * scripts. The marker is written by `withAssembledHookBins` onto every file it\n * emits into this directory and by nothing else, which makes it the exact\n * ownership record. An unreadable entry (a broken symlink) is not ours.\n */\nasync function isOwnedHookBinFile(_name: string, absPath: string): Promise<boolean> {\n const content = await readIfExists(absPath).catch(() => undefined);\n return content !== undefined && readBundleMarker(content) !== undefined;\n}\n\n/**\n * Directory and extension the command output template declares as the emitter's.\n * Both come from the template because it is configurable: hard-coding either\n * would scan the wrong place the moment a project overrides `emit.commands.output`.\n * Paths in the template are project-root-relative with `/` separators.\n */\nfunction templateDir(outputTemplate: string): string {\n const slash = outputTemplate.lastIndexOf(\"/\");\n return slash === -1 ? \".\" : outputTemplate.slice(0, slash);\n}\n\nfunction templateExt(outputTemplate: string): string {\n const base = outputTemplate.slice(outputTemplate.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : base.slice(dot);\n}\n\n/**\n * Every stale generated file across the directories this emitter owns.\n *\n * A directory qualifies when the render is the COMPLETE truth for it, which is\n * the case for each of these:\n *\n * .claude/bin — the bins plus the chunks they import, nothing else\n * .claude/agents — one `.md` per DSL agent\n * .claude/workflows — one `.js` per DSL workflow (renderWorkflowFiles)\n * <command template> — one `.md` per DSL workflow (renderCommandFiles); the\n * configured output path is what declares this directory\n * as the emitter's namespace, so it is derived from the\n * template rather than hard-coded\n *\n * Dropping a workflow from the DSL therefore removes its script and its command,\n * exactly as dropping an agent removes its subagent file. A leftover is not\n * inert: `.claude/workflows/<id>.js` stays a Dynamic Workflow the harness can\n * still launch with no DSL behind it.\n *\n * `.claude/hooks` is the one generated directory deliberately NOT scanned, and\n * not because its set is open-ended in principle: the generator emits a constant\n * three wrappers that never shrink, so no orphan class exists there. It is also\n * shared space — #248 preserves consumer-added hooks, whose scripts live in that\n * same directory (`pre-tool-use-git-guard.sh` in the settings-merge tests) — so\n * scanning it could only ever delete someone else's file.\n */\nasync function orphanFiles(\n root: string,\n config: ClaudeConfig,\n rendered: readonly GeneratedFile[],\n workflows: readonly RenderedFile[],\n commands: readonly RenderedFile[],\n agents: readonly RenderedFile[],\n): Promise<string[]> {\n const orphans = await orphanGeneratedFiles(\n root,\n HOOK_BIN_DIR,\n rendered.filter((f) => isHookBin(f.targetDir, f.path)).map(generatedFileRelPath),\n isOwnedHookBinFile,\n );\n\n if (config.emit.workflows) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n workflowsDirFor(config.output_dir),\n workflows.map((f) => f.path),\n isOwnedByExtension(WORKFLOW_FILE_EXT),\n )),\n );\n }\n\n const commandTemplate = commandOutputTemplate(config);\n if (commandTemplate) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n templateDir(commandTemplate),\n commands.map((f) => f.path),\n isOwnedByExtension(templateExt(commandTemplate)),\n )),\n );\n }\n\n if (config.emit.agents) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n agentsDirFor(config.output_dir),\n agents.map((f) => f.path),\n isOwnedByExtension(AGENT_FILE_EXT),\n )),\n );\n }\n\n return orphans;\n}\n\nfunction actionForOverwrite(existing: string | undefined, next: string): FileAction {\n if (existing === undefined) return \"created\";\n return existing === next ? \"unchanged\" : \"updated\";\n}\n\n/**\n * Mode for artifacts the generator declares `executable` (#277).\n */\nconst EXECUTABLE_MODE = 0o755;\n\n/**\n * Only the owner-execute bit distinguishes a `100755` blob from a `100644` one,\n * and `git checkout` applies the user's umask to the group/other bits — so the\n * owner bit is the one that is both authoritative and stable across checkouts.\n */\nconst OWNER_EXEC_BIT = 0o100;\n\n/**\n * True when an existing file is missing its executable bit. Absent files report\n * false: there is no mode to repair, and the write path creates them with the\n * right mode anyway.\n */\nasync function execBitMissing(abs: string): Promise<boolean> {\n try {\n const { mode } = await stat(abs);\n return (mode & OWNER_EXEC_BIT) === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * The ONE write site for every materialized artifact — hook bins, generated\n * `.claude/*` files and the additive workflow/command/agent renders all pass\n * through here, so the executable bit is applied in a single place rather than\n * per writer (#277).\n *\n * Mode is part of the artifact, not a property of the bytes: a file whose\n * content already matches but which lost its executable bit is still out of\n * date (Claude Code execs `.claude/hooks/*.sh` and `.claude/bin/file-suggestion`\n * by path, so a 644 file makes the hook die with EACCES). Such a file is\n * repaired with a chmod alone and reported as `updated` — reporting it\n * `unchanged` would leave `claude check` permanently red with nothing able to\n * fix it.\n *\n * @param content Resolved lazily so an unchanged hook bin is never re-assembled.\n */\nasync function writeArtifact(opts: {\n abs: string;\n content: () => string;\n action: FileAction;\n executable: boolean;\n dryRun: boolean;\n}): Promise<FileAction> {\n const modeOnly =\n opts.action === \"unchanged\" && opts.executable && (await execBitMissing(opts.abs));\n const action: FileAction = modeOnly ? \"updated\" : opts.action;\n\n if (action === \"unchanged\" || opts.dryRun) return action;\n\n if (!modeOnly) {\n await mkdir(dirname(opts.abs), { recursive: true });\n await writeFile(opts.abs, opts.content(), \"utf8\");\n }\n if (opts.executable) await chmod(opts.abs, EXECUTABLE_MODE);\n return action;\n}\n\n/**\n * Drift for a self-contained hook bin (#241), detected without re-reading\n * node_modules by comparing markers. Two independent checks:\n * (a) stored marker vs expected marker for the current source/version\n * (catches generator/runtime-version changes), and\n * (b) stored marker vs the marker recomputed from the file's own bytes\n * (catches body tampering even when the marker line is left intact —\n * the weakness the prior audit flagged).\n */\nfunction checkHookBin(\n file: GeneratedFile,\n existing: string | undefined,\n): \"missing\" | \"changed\" | null {\n if (existing === undefined) return \"missing\";\n const stored = readBundleMarker(existing);\n const expected = readBundleMarker(file.content);\n const onDisk = recomputeMarkerFromDisk(existing);\n return stored !== expected || stored !== onDisk ? \"changed\" : null;\n}\n\n/**\n * Materialize `.claude/*` and the CLAUDE.md integration block from the embedded DSL.\n *\n * Idempotent: re-running with no changes writes nothing. CLAUDE.md uses a\n * marker-delimited block merge so user content outside the block is preserved.\n */\nexport async function syncClaude(opts: SyncOptions): Promise<SyncResult> {\n const config = parseClaudeConfig(opts.config);\n const root = resolve(opts.projectRoot);\n const result: SyncResult = { files: [] };\n\n // Resolved before the generator runs, not after: the CLAUDE.md block it\n // renders carries the dispatch-only agents' prompt, and these sources are the\n // only thing that knows which agents those are (#345).\n const sources = await resolveDslSources(root, opts.dsl, config);\n\n const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));\n for (const file of rendered) {\n const rel = generatedFileRelPath(file);\n const abs = absPath(root, file);\n const existing = await readIfExists(abs);\n\n // `.claude/bin` holds self-contained ESM — bins assembled against a shared\n // runtime chunk, so nothing needs node_modules resolution at hook runtime.\n // `renderFiles` already produced the final bytes (NO esbuild runs here; it\n // is pure string work), each carrying a marker line. A file is up to date\n // only when its stored marker matches BOTH the marker of the content we\n // would write AND the marker recomputed from its own on-disk content (so\n // body tampering forces a re-sync). The write itself goes through\n // writeArtifact, which also repairs a missing exec bit.\n if (isHookBin(file.targetDir, file.path)) {\n const drift = checkHookBin(file, existing);\n const action: FileAction =\n drift === \"missing\" ? \"created\" : drift === \"changed\" ? \"updated\" : \"unchanged\";\n result.files.push({\n path: rel,\n action: await writeArtifact({\n abs,\n content: () => file.content,\n action,\n executable: file.executable === true,\n dryRun: opts.dryRun === true,\n }),\n });\n continue;\n }\n\n const { content, action } = resolveContent(file, existing);\n\n result.files.push({\n path: rel,\n action: await writeArtifact({\n abs,\n content: () => content,\n action,\n executable: file.executable === true,\n dryRun: opts.dryRun === true,\n }),\n });\n }\n\n // Additive fully-generated, overwrite-owned files (Dynamic Workflow scripts\n // #235 + per-workflow slash commands #249 + subagents #272). Same handling:\n // overwrite-owned, drift = missing or hand-edited.\n //\n // All three emitters read the SAME resolved sources (#274): the project's\n // effective DSL, not the bare embedded one they used to be handed.\n //\n // Each emitter's output is kept as its own list because it is also the\n // EXPECTED set the orphan scan subtracts from its directory (#278) — deriving\n // that set from anything but this render is how a stale file survives.\n const workflows = workflowFiles(sources, config);\n const commands = await commandFiles(sources, config, root);\n const agents = agentFiles(sources, config);\n const additive = [...workflows, ...commands, ...agents];\n for (const file of additive) {\n const abs = join(root, file.path);\n const existing = await readIfExists(abs);\n result.files.push({\n path: file.path,\n // Workflow scripts, slash commands and subagent files are read by the\n // harness, never exec'd by path, so none of them is executable.\n action: await writeArtifact({\n abs,\n content: () => file.content,\n action: actionForOverwrite(existing, file.content),\n executable: false,\n dryRun: opts.dryRun === true,\n }),\n });\n }\n\n // Anything dropped from the render must be dropped from the harness: until\n // the file is gone Claude Code still lists and can invoke a stale subagent,\n // and a stale `.claude/bin` chunk stays committed dead weight.\n for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {\n if (!opts.dryRun) {\n await rm(join(root, path));\n }\n result.files.push({ path, action: \"deleted\" });\n }\n\n return result;\n}\n\n/**\n * Read-only drift gate. Reports files whose on-disk content differs from a\n * fresh render. For CLAUDE.md, drift means the aaac:claude-native block is\n * missing or stale (content outside the block is ignored).\n */\nexport async function checkClaude(opts: SyncOptions): Promise<CheckResult> {\n const config = parseClaudeConfig(opts.config);\n const root = resolve(opts.projectRoot);\n const drift: CheckResult[\"drift\"] = [];\n\n // Same resolution, same order and same position as `syncClaude`: the block\n // this compares against carries the dispatch-only agents' prompt (#345).\n const sources = await resolveDslSources(root, opts.dsl, config);\n\n const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));\n for (const file of rendered) {\n const rel = generatedFileRelPath(file);\n const abs = absPath(root, file);\n const existing = await readIfExists(abs);\n\n const contentReason = isHookBin(file.targetDir, file.path)\n ? checkHookBin(file, existing)\n : checkContent(file, existing);\n\n // Mode is part of the artifact (#277): a file whose bytes match but whose\n // executable bit was dropped is exactly the failure this gate exists to\n // catch — Claude Code execs the hook by path and it dies with EACCES, and a\n // content-only comparison stays green forever. `sync` repairs it, so it is\n // reported as `changed` like any other repairable divergence.\n const modeDrift =\n contentReason === null &&\n file.executable === true &&\n existing !== undefined &&\n (await execBitMissing(abs));\n\n const reason = contentReason ?? (modeDrift ? \"changed\" : null);\n if (reason) {\n drift.push({ path: rel, reason });\n }\n }\n\n // Additive files (Dynamic Workflow scripts #235 + slash commands #249 +\n // subagents #272): drift = missing or hand-edited. Same resolved sources as\n // sync, so `check` cannot disagree with what `sync` would write (#274), and\n // the same per-emitter lists, so the orphan scan below subtracts exactly the\n // set `sync` would have written (#278).\n const workflows = workflowFiles(sources, config);\n const commands = await commandFiles(sources, config, root);\n const agents = agentFiles(sources, config);\n const additive = [...workflows, ...commands, ...agents];\n for (const file of additive) {\n const existing = await readIfExists(join(root, file.path));\n if (existing === undefined) {\n drift.push({ path: file.path, reason: \"missing\" });\n } else if (existing !== file.content) {\n drift.push({ path: file.path, reason: \"changed\" });\n }\n }\n\n // A generated file the render no longer produces is drift too — the loop\n // above walks the EXPECTED set and so can never see it.\n for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {\n drift.push({ path, reason: \"orphaned\" });\n }\n\n return { inSync: drift.length === 0, drift };\n}\n","/**\n * Self-contained hook-bin assembler (#241, #278).\n *\n * The Claude generator (`@aaac/contracts`) emits thin Node ESM bin scripts that\n * `import { … } from \"@aaac/runtime/claude-native\"` (or `.../hooks-lite`) using\n * a bare specifier plus a small per-project parameter body (componentId,\n * configPath, MEMBERS, …). Those bare specifiers require `node_modules/@aaac`\n * to be resolvable at the bin's location at runtime — which fails with\n * `ERR_MODULE_NOT_FOUND` in project roots that do not carry a hoisted\n * `node_modules/@aaac` (the workspace/dogfood case). NODE_PATH (#233) does NOT\n * help because it is ignored for bare ESM specifier resolution.\n *\n * Fix (build-time bundle + sync-time templating): the \"flatten @aaac/runtime\n * into a self-contained file\" step runs ONCE at @aaac/runtime BUILD time\n * (scripts/build-claude-bundles.mjs, esbuild as a build-time devDependency),\n * producing two pre-built ESM bundles shipped in the package:\n *\n * dist/claude-bundles/lean.js (from hooks-lite — hot path, ~10KB)\n * dist/claude-bundles/full.js (from claude-native — per-session bins)\n *\n * At `claude sync` time there is NO esbuild. Each pre-built bundle is written\n * verbatim as ONE shared chunk in `.claude/bin/`, and every bin that needs it\n * keeps its own import statement with only the SPECIFIER rewritten to that\n * chunk's relative path. A relative specifier needs no `node_modules` and no\n * package resolution at all, so the #241 self-contained property holds while\n * the multi-megabyte runtime exists once per project instead of once per bin —\n * the 75% byte-identical duplication #278 measured.\n *\n * Everything emitted here carries a marker line (see MARKER_PREFIX), so the\n * drift gate treats bins and shared chunks identically.\n */\n\nimport {\n HOOK_BIN_CHUNK_PREFIX,\n isHookBinChunk,\n type GeneratedFile,\n} from \"@aaac/contracts\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, parse } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadPrebuiltBundle, type BundleKind } from \"./claude-bundle-assets.js\";\n\n/** Directory the Claude generator targets its bin scripts at. */\nexport const HOOK_BIN_DIR = \".claude/bin\";\n\n/**\n * Bundle kinds in emission order. Iterating this rather than a Set's insertion\n * order keeps the emitted file list stable no matter what order the generator\n * returns bins in — the drift gate compares exact bytes.\n */\nconst BUNDLE_KINDS: readonly BundleKind[] = [\"lean\", \"prompt\", \"full\"];\n\n/**\n * Resolve @aaac/runtime's own version by walking upward until a package.json\n * named `@aaac/runtime` is found. Used only for the bundle marker's version\n * component; the marker's full-file content hash does the real drift work, so a\n * \"bundled\" fallback (in the self-contained CLI, where no package dir exists)\n * is harmless.\n */\nfunction resolveRuntimeVersion(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n const root = parse(dir).root;\n while (true) {\n try {\n const manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n if (typeof manifest === \"object\" && manifest !== null) {\n const pkg = manifest as Record<string, unknown>;\n if (pkg.name === \"@aaac/runtime\" && typeof pkg.version === \"string\") return pkg.version;\n }\n } catch {\n // keep walking\n }\n if (dir === root) break;\n dir = dirname(dir);\n }\n return \"bundled\";\n}\n\nconst RUNTIME_VERSION = resolveRuntimeVersion();\n\n/**\n * Read a pre-built bundle. Cached per kind so a single sync run does not\n * re-materialize the (multi-MB) full bundle repeatedly. The actual asset load\n * lives in claude-bundle-assets (which the CLI build embeds inline).\n */\nconst bundleCache = new Map<BundleKind, string>();\n\nfunction readPrebuiltBundle(kind: BundleKind): string {\n const cached = bundleCache.get(kind);\n if (cached !== undefined) return cached;\n const content = loadPrebuiltBundle(kind);\n bundleCache.set(kind, content);\n return content;\n}\n\n/**\n * Marker line embedded at the top of every emitted file. It records the\n * runtime version + a hash of the FULL emitted file so the drift gate\n * (`checkClaude`) detects ANY content change — including body tampering below\n * the marker — not just a change in the generated source.\n */\nconst MARKER_PREFIX = \"//__aaac_bundle__:\";\n\n/** True when a generated file's path targets `.claude/bin`. */\nexport function isHookBin(targetDir: string | undefined, path: string): boolean {\n return targetDir === HOOK_BIN_DIR && !path.includes(\"/\");\n}\n\n/**\n * The generated bin's bare runtime import. Group 1 is everything up to the\n * specifier (so it can be re-emitted verbatim); group 2 is present only for the\n * lean subpath. ONE regex serves both readers — which bundle a bin needs, and\n * where to repoint it — so they can never disagree about a given source.\n *\n * Global: the count matters, see requireRuntimeImport.\n */\nconst RUNTIME_IMPORT_RE =\n /(import\\s*\\{[^}]*\\}\\s*from\\s*)[\"']@aaac\\/runtime\\/claude-native(?:\\/(hooks-lite|hooks-prompt))?[\"']/g;\n\n/**\n * Locate a hook entry script's bare runtime import.\n *\n * Callers must already know the file IS an entry script (`isHookBinChunk` is\n * false for it). This never decides that question: the shared modules in this\n * directory carry the project's DSL as arbitrary user text, and matching import\n * syntax against content would read that data as code.\n *\n * Exactly one is required. Zero means the generator emitted an entry script that\n * cannot reach the runtime at all. More than one is a silent corruption: only\n * the first would be repointed at the shared chunk and every later specifier\n * would ship bare, needing `node_modules` at hook runtime — the exact #241\n * failure this module exists to prevent. Neither is visible to the drift gate,\n * which compares markers over content this module itself produced, so a bad bin\n * is \"in sync\" with its own bad bytes. Fail loud instead.\n */\nfunction requireRuntimeImport(source: string): RegExpMatchArray {\n const matches = [...source.matchAll(RUNTIME_IMPORT_RE)];\n if (matches.length !== 1) {\n throw new Error(\n `A generated hook bin must import @aaac/runtime/claude-native exactly once; found ` +\n `${matches.length}${\n matches.length > 0 ? `: ${matches.map((m) => JSON.stringify(m[0])).join(\", \")}` : \"\"\n }. Only one can be repointed at the shared chunk; any other would ship as a bare ` +\n `specifier that needs node_modules at hook runtime.`,\n );\n }\n return matches[0];\n}\n\n/** Runtime subpath -> the pre-built bundle that serves it. */\nconst KIND_BY_SUBPATH: Record<string, BundleKind> = {\n \"hooks-lite\": \"lean\",\n \"hooks-prompt\": \"prompt\",\n};\n\n/**\n * Which pre-built bundle a hook entry script needs, read straight off the\n * specifier the generator chose. `BIN_RUNTIME_SUBPATH` (in @aaac/contracts'\n * claude-generator) is the single source of truth for which barrel each bin\n * imports; this only maps that emitted subpath to its bundle. No bin name\n * appears here, so the two cannot drift apart the way `file-suggestion` did\n * (#278).\n */\nexport function bundleKindFor(source: string): BundleKind {\n const subpath = requireRuntimeImport(source)[2];\n return subpath ? KIND_BY_SUBPATH[subpath]! : \"full\";\n}\n\n/**\n * File name of the shared runtime chunk for each bundle kind. `.mjs` so the\n * chunk parses as ESM regardless of the consuming project's package.json `type`.\n *\n * Written out per kind rather than templated from `kind`, because these names are\n * the set `.gitattributes`' `aaac-bundled` mark is checked against\n * (`.github/scripts/lib/workspace.mjs`). A name assembled inside a function from\n * a parameter is a name only this module can produce, so the check had nothing to\n * compare against but `HOOK_BIN_CHUNK_PREFIX` — which accepted any `_`-prefixed\n * file anyone dropped in {@link HOOK_BIN_DIR} (#341).\n *\n * The set is finite because `BundleKind` is a closed union: `Record<BundleKind,\n * …>` does not compile until a new kind is named here. The value type keeps the\n * prefix from drifting away from the classifier that reads it — a name not\n * starting with `HOOK_BIN_CHUNK_PREFIX` does not compile either.\n */\nconst RUNTIME_CHUNK_FILE = {\n lean: \"_aaac-runtime-lean.mjs\",\n prompt: \"_aaac-runtime-prompt.mjs\",\n full: \"_aaac-runtime-full.mjs\",\n} as const satisfies Record<BundleKind, `${typeof HOOK_BIN_CHUNK_PREFIX}${string}`>;\n\n/** File name of the shared runtime chunk for a bundle kind. */\nexport function chunkFileName(kind: BundleKind): string {\n return RUNTIME_CHUNK_FILE[kind];\n}\n\n/**\n * Stamp the content-hash marker in as line 2, so `readBundleMarker` finds it at\n * a fixed position in bins (after the shebang) and chunks (after their banner\n * comment) alike.\n */\nfunction withMarker(bodyWithoutMarker: string): string {\n const firstNl = bodyWithoutMarker.indexOf(\"\\n\");\n return (\n bodyWithoutMarker.slice(0, firstNl + 1) +\n markerFor(bodyWithoutMarker) +\n \"\\n\" +\n bodyWithoutMarker.slice(firstNl + 1)\n );\n}\n\n/**\n * Assemble a single generated bin into a self-contained ESM script by string\n * templating (NO esbuild). Layout:\n *\n * #!/usr/bin/env node\n * //__aaac_bundle__:<version>:<fullFileHash>\n * <bin body: shebang stripped, the bare `@aaac/…` specifier repointed at\n * `./_aaac-runtime-<kind>.mjs`; the bin's own node:* imports are kept>\n *\n * The runtime itself is NOT inlined here — it lives in the shared chunk\n * `assembleRuntimeChunk` emits alongside.\n */\nfunction assembleHookBin(source: string, kind: BundleKind): string {\n // Strip the generated shebang; a single canonical one is re-added below.\n const withoutShebang = source.replace(/^#![^\\n]*\\n/, \"\");\n\n // Repoint the bare specifier at the shared chunk. The imported names, and\n // everything else about the statement, stay exactly as generated. Re-located\n // after stripping the shebang so the offsets are the ones we replace at.\n const match = requireRuntimeImport(withoutShebang);\n const binBody = withoutShebang.replace(\n match[0],\n () => `${match[1]}\"./${chunkFileName(kind)}\"`,\n );\n\n return withMarker(\n [\n \"#!/usr/bin/env node\",\n \"// Auto-generated by @aaac/runtime claude sync (#241). Do not edit — self-contained bundle.\",\n binBody.trimStart(),\n ].join(\"\\n\"),\n );\n}\n\n/**\n * The shared runtime chunk for a bundle kind: the pre-built ESM bundle verbatim,\n * behind the same banner + marker every emitted file carries. Bins reach it by\n * relative specifier, so it needs no `node_modules` and no package resolution.\n */\nfunction assembleRuntimeChunk(kind: BundleKind): string {\n return withMarker(\n [\n `// Auto-generated by @aaac/runtime claude sync (#278). Do not edit — shared ${kind} runtime chunk.`,\n readPrebuiltBundle(kind).trimEnd(),\n \"\",\n ].join(\"\\n\"),\n );\n}\n\n/**\n * Turn the generator's raw output into the bytes `.claude/bin` should hold:\n * every bin assembled against a shared runtime chunk, the generator's own\n * shared data chunks marker-stamped, and one runtime chunk per bundle kind the\n * bins actually import — a kind no bin imports is never emitted.\n *\n * That last point is only a claim about what this function EMITS. Nothing here\n * removes a chunk a previous sync wrote that the current one no longer needs;\n * see `orphanGeneratedFiles` in materialize.ts, which is what actually reports\n * and deletes those, because it scans the directory instead of the expected set.\n *\n * Every `.claude/bin` file leaves here carrying a marker line, including the\n * ones this module did not generate the body of. That is load-bearing: the\n * drift gate compares markers, so an unstamped file would make the stored,\n * expected and recomputed markers all `undefined` — trivially equal — and its\n * content changes would be invisible.\n */\nexport function withAssembledHookBins(files: readonly GeneratedFile[]): GeneratedFile[] {\n const out: GeneratedFile[] = [];\n const needed = new Set<BundleKind>();\n\n for (const file of files) {\n if (!isHookBin(file.targetDir, file.path)) {\n out.push(file);\n continue;\n }\n\n if (isHookBinChunk(file.path)) {\n // A shared module (the project's embedded DSL). Its body is user data, so\n // it is never parsed as code here — it only needs the marker every file\n // in this directory carries.\n out.push({ ...file, content: withMarker(file.content) });\n continue;\n }\n\n const kind = bundleKindFor(file.content);\n needed.add(kind);\n out.push({ ...file, content: assembleHookBin(file.content, kind) });\n }\n\n for (const kind of BUNDLE_KINDS) {\n if (!needed.has(kind)) continue;\n out.push({\n path: chunkFileName(kind),\n content: assembleRuntimeChunk(kind),\n overwrite: true,\n targetDir: HOOK_BIN_DIR,\n });\n }\n\n return out;\n}\n\nfunction markerFor(fullFileMinusMarker: string): string {\n const hash = createHash(\"sha256\").update(fullFileMinusMarker).digest(\"hex\").slice(0, 16);\n return `${MARKER_PREFIX}${RUNTIME_VERSION}:${hash}`;\n}\n\n/**\n * Extract the bundle marker from already-emitted content, if present.\n * The marker is always the second line.\n */\nexport function readBundleMarker(content: string): string | undefined {\n const nl = content.indexOf(\"\\n\");\n if (nl === -1) return undefined;\n const secondNl = content.indexOf(\"\\n\", nl + 1);\n const line = content.slice(nl + 1, secondNl === -1 ? undefined : secondNl);\n return line.startsWith(MARKER_PREFIX) ? line : undefined;\n}\n\n/**\n * Recompute the content hash of an on-disk file (its full content with the\n * marker line removed) and return the marker that content *should* carry.\n *\n * This is what makes body-tamper detection work: the drift gate compares this\n * against the marker actually stored in the file. If the body was edited but\n * the marker line left intact, the recomputed marker no longer matches the\n * stored one — so drift is reported even though the generated source is\n * unchanged. (The prior implementation only hashed the generator source, so an\n * appended/edited body with an intact marker went undetected.)\n */\nexport function recomputeMarkerFromDisk(content: string): string | undefined {\n const nl = content.indexOf(\"\\n\");\n if (nl === -1) return undefined;\n const secondNl = content.indexOf(\"\\n\", nl + 1);\n if (secondNl === -1) return undefined;\n const markerLine = content.slice(nl + 1, secondNl);\n if (!markerLine.startsWith(MARKER_PREFIX)) return undefined;\n // Reconstruct the file with the marker line removed, exactly as withMarker\n // hashed it before inserting the marker.\n const firstLine = content.slice(0, nl + 1);\n const rest = content.slice(secondNl + 1);\n return markerFor(firstLine + rest);\n}\n","/**\n * Pre-built Claude-runtime bundle asset loader (#241).\n *\n * Returns the self-contained ESM bundles produced at @aaac/runtime BUILD time\n * (scripts/build-claude-bundles.mjs) and shipped in the package dist/.\n *\n * Two deployment shapes are supported:\n *\n * 1. npm package consumer — the bundles live at\n * `<@aaac/runtime>/dist/claude-bundles/{lean,full}.js`; this module reads\n * them from disk relative to its own compiled location.\n *\n * 2. Self-contained CLI (examples/dev-team → bin/dev-team.mjs) — there is no\n * `@aaac/runtime` package dir at runtime, so the CLI's esbuild build\n * (examples/dev-team/esbuild.bundle.mjs) replaces this ENTIRE module via an\n * onLoad plugin that embeds the two bundle strings inline. The disk read\n * below is never executed in that shape.\n *\n * This is a deliberately tiny, single-purpose module so the CLI build's\n * whole-file replacement stays simple and robust.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, parse } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type BundleKind = \"lean\" | \"prompt\" | \"full\";\n\n/**\n * Resolve the @aaac/runtime package dist directory by walking upward from this\n * module until the package.json named `@aaac/runtime` is found. Robust to\n * tsup's chunk hoisting.\n */\nfunction resolveRuntimeDistDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n const root = parse(dir).root;\n while (true) {\n try {\n const manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n (manifest as Record<string, unknown>).name === \"@aaac/runtime\"\n ) {\n return join(dir, \"dist\", \"claude-bundles\");\n }\n } catch {\n // keep walking\n }\n if (dir === root) break;\n dir = dirname(dir);\n }\n // Fallback: assume bundles sit alongside this module's dist tree.\n return join(dirname(fileURLToPath(import.meta.url)), \"claude-bundles\");\n}\n\n/**\n * Read a pre-built runtime bundle by kind. In the CLI build this whole function\n * body is replaced with an embedded-string return (see the module doc comment).\n */\nexport function loadPrebuiltBundle(kind: BundleKind): string {\n const path = join(resolveRuntimeDistDir(), `${kind}.js`);\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n throw new Error(\n `Missing pre-built Claude runtime bundle: ${path}. ` +\n `Run \\`npm run build\\` in @aaac/runtime (build-claude-bundles.mjs) first.`,\n );\n }\n}\n","/**\n * `.claude/settings.json` managed-region merge (#248).\n *\n * The claude generator emits settings.json with `overwrite: true`, which used to\n * clobber the whole file on every `claude sync`. That destroyed any custom hook a\n * project added by hand (e.g. a git-command guard on `PreToolUse`) and made\n * `claude check` report permanent false drift.\n *\n * This module merges the aaac-managed region into the user's existing file\n * non-destructively — the same principle as the `CLAUDE.md` marker-block merge,\n * but for JSON. aaac owns a fixed, self-describing region; everything else the\n * user put in the file is preserved verbatim.\n *\n * ## Managed-vs-non-managed discriminator (why command-path, not a marker)\n *\n * A JSON settings file cannot carry comment markers, and a side-car \"managed\n * keys\" list would drift out of sync with the generator. Instead we key on the\n * one thing that is intrinsic to an aaac-generated entry and survives round\n * trips: **the command string points at an aaac-managed launcher under\n * `.claude/`** — `${CLAUDE_PROJECT_DIR}/.claude/hooks/*.sh` for the hook events\n * and `${CLAUDE_PROJECT_DIR}/.claude/bin/file-suggestion` for `fileSuggestion`.\n *\n * A command hook is \"managed\" iff its `command` matches a command produced by\n * the current generator render (we read them straight out of the freshly\n * generated settings object — no hardcoded list to drift). Concretely:\n * • `fileSuggestion` — fully owned by aaac (single managed command).\n * • each generated hook event (SessionStart / UserPromptSubmit / PreToolUse):\n * managed entries = groups/hooks whose command is one the generator emits;\n * every other group/hook in that event is a user addition and is kept.\n * • hook events the generator does NOT emit (PostToolUse, Stop, …) and every\n * other top-level key are user-owned and passed through untouched.\n *\n * This is robust: it survives round-trips (managed commands are regenerated\n * identically), it needs no marker the JSON format can't hold, and it is\n * computed the SAME way for `sync` (produce merged content) and `check` (compare\n * on-disk against the merged content), so a user-added hook is never drift while\n * a mutated/removed managed entry always is.\n */\n\nexport interface CommandHook {\n type?: string;\n command?: string;\n [key: string]: unknown;\n}\n\nexport interface HookGroup {\n matcher?: string;\n hooks?: CommandHook[];\n [key: string]: unknown;\n}\n\nfunction commandOf(hook: CommandHook): string | undefined {\n return typeof hook.command === \"string\" ? hook.command : undefined;\n}\n\n/**\n * An entry inside a `hooks.<Event>` array. Claude Code accepts BOTH shapes and\n * both occur in the wild:\n * • a bare command hook — `{ \"type\": \"command\", \"command\": \"…\" }`\n * (this is what the aaac generator emits today), and\n * • a matcher group of hooks — `{ \"matcher\": \"Bash\", \"hooks\": [ … ] }`\n * (the shape the global installer / Claude docs use).\n * The merge must classify managed-vs-user at the command level regardless of\n * which envelope carries the command.\n */\nexport type HookEntry = CommandHook | HookGroup;\n\nexport interface ClaudeSettings {\n fileSuggestion?: unknown;\n hooks?: Record<string, HookEntry[]>;\n [key: string]: unknown;\n}\n\n/** A group entry is one that carries a nested `hooks` array. */\nfunction isGroup(entry: HookEntry): entry is HookGroup {\n return Array.isArray((entry as HookGroup).hooks);\n}\n\n/** Every command string reachable from a single event-array entry. */\nfunction commandsInEntry(entry: HookEntry): string[] {\n if (isGroup(entry)) {\n return (entry.hooks ?? [])\n .map((h) => commandOf(h))\n .filter((c): c is string => c !== undefined);\n }\n const c = commandOf(entry);\n return c === undefined ? [] : [c];\n}\n\nfunction isCommandHook(value: unknown): value is CommandHook {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const hook = value as Record<string, unknown>;\n return (\n (hook.type === undefined || typeof hook.type === \"string\") &&\n (hook.command === undefined || typeof hook.command === \"string\")\n );\n}\n\n/**\n * Either envelope of {@link HookEntry}, with every field the two declare.\n *\n * The index signature on both is `unknown`, so the fields checked here are the\n * whole of what the type promises — and each one is a field this merge walks:\n * `hooks` decides the envelope, `command` decides managed-vs-user. An entry that\n * fails is not a hook entry, and `null` is the shape that actually arrived:\n * `TypeError: … reading 'hooks'` from `isGroup`, one line into the merge.\n */\nfunction isHookEntry(value: unknown): value is HookEntry {\n if (!isCommandHook(value)) return false;\n const entry = value as Record<string, unknown>;\n return (\n (entry.matcher === undefined || typeof entry.matcher === \"string\") &&\n (entry.hooks === undefined ||\n (Array.isArray(entry.hooks) && entry.hooks.every(isCommandHook)))\n );\n}\n\n/**\n * The single gate in front of {@link ClaudeSettings}.\n *\n * `hooks` is the only field the type makes a structural promise about —\n * `fileSuggestion` is declared `unknown` and every other key reaches the index\n * signature, which is why the merge copies them verbatim and needs no claim\n * about them.\n */\nfunction isClaudeSettings(value: unknown): value is ClaudeSettings {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const settings = value as Record<string, unknown>;\n if (settings.hooks === undefined) return true;\n if (typeof settings.hooks !== \"object\" || settings.hooks === null) return false;\n return Object.values(settings.hooks as Record<string, unknown>).every(\n (entries) => Array.isArray(entries) && entries.every(isHookEntry),\n );\n}\n\n/**\n * Parse settings.json text; fail-open to `{}` for empty/invalid input.\n *\n * Text that parses but is not a settings document is invalid input for this\n * reader and gets the same answer, rather than being asserted into the type and\n * walked. `claude check` reports the resulting difference as drift, which is how\n * a file this merge cannot read reaches the user — before this gate existed both\n * `check` and `sync` died inside `mergeSettings` instead.\n */\nexport function parseSettings(raw: string | undefined): ClaudeSettings {\n if (!raw || !raw.trim()) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {};\n }\n return isClaudeSettings(parsed) ? parsed : {};\n}\n\n/** Serialize with the exact shape the generator uses (2-space indent + trailing newline). */\nexport function serializeSettings(settings: ClaudeSettings): string {\n return JSON.stringify(settings, null, 2) + \"\\n\";\n}\n\n/**\n * Managed command strings, scoped PER EVENT.\n *\n * Discrimination MUST be per-event, not a global flat set: the same launcher\n * command could legitimately be registered by a user under a DIFFERENT event\n * than the one aaac emits it for (e.g. the `pre-tool-use.sh` launcher placed\n * under `PostToolUse`). A global set would silently strip that user entry. An\n * entry is \"managed\" only if its command matches one the generator emits for\n * that same event; under an event where aaac emits nothing, nothing is managed\n * so every user entry is preserved. `fileSuggestion` stays top-level-managed.\n */\nfunction managedCommandsByEvent(managed: ClaudeSettings): Map<string, Set<string>> {\n const byEvent = new Map<string, Set<string>>();\n for (const [event, entries] of Object.entries(managed.hooks ?? {})) {\n const cmds = new Set<string>();\n for (const entry of entries) {\n for (const c of commandsInEntry(entry)) cmds.add(c);\n }\n byEvent.set(event, cmds);\n }\n return byEvent;\n}\n\n/**\n * Merge the aaac-managed settings into the user's existing settings.\n *\n * The result is: managed region rendered fresh, every non-managed part of the\n * existing file preserved. When `existing` is undefined this returns exactly the\n * managed object (byte-identical to the previous overwrite behaviour for fresh\n * projects — backward compatible).\n */\nexport function mergeSettings(\n existing: ClaudeSettings | undefined,\n managed: ClaudeSettings,\n): ClaudeSettings {\n if (existing === undefined) {\n // Fresh project: emit the managed object as-is (byte-stable with pre-#248).\n return managed;\n }\n\n const managedCmdsByEvent = managedCommandsByEvent(managed);\n\n // Start from a shallow clone of the user's file so unknown top-level keys and\n // ordering of user keys are preserved.\n const out: ClaudeSettings = { ...existing };\n\n // fileSuggestion is fully aaac-owned.\n if (\"fileSuggestion\" in managed) {\n out.fileSuggestion = managed.fileSuggestion;\n }\n\n // hooks: rebuild each event as [managed entries] + [surviving user entries].\n const existingHooks = existing.hooks ?? {};\n const managedHooks = managed.hooks ?? {};\n const mergedHooks: Record<string, HookEntry[]> = {};\n\n // Preserve the union of events. Event-array order is not semantically\n // significant to Claude (it reads by key), but we keep managed entries first\n // then surviving user entries so a fresh project is byte-identical to the\n // pure managed render.\n const eventNames = new Set<string>([\n ...Object.keys(existingHooks),\n ...Object.keys(managedHooks),\n ]);\n\n for (const event of eventNames) {\n const managedEntries = managedHooks[event] ?? [];\n const userEntries = existingHooks[event] ?? [];\n // Managed commands for THIS event only. Empty for events aaac doesn't emit,\n // so a user entry there is never stripped even if its command collides with\n // a launcher aaac manages under a different event.\n const managedCmds = managedCmdsByEvent.get(event) ?? new Set<string>();\n\n // Keep only the parts of each user entry that are NOT aaac-managed (the\n // generator re-supplies managed commands). Works for both entry shapes:\n // • bare command hook → dropped iff its command is managed\n // • matcher group → managed hooks stripped; group kept iff any\n // non-managed hook remains\n const survivingUserEntries: HookEntry[] = [];\n for (const entry of userEntries) {\n if (isGroup(entry)) {\n const keptHooks = (entry.hooks ?? []).filter((h) => {\n const c = commandOf(h);\n return c === undefined || !managedCmds.has(c);\n });\n if (keptHooks.length > 0) {\n survivingUserEntries.push({ ...entry, hooks: keptHooks });\n }\n } else {\n const c = commandOf(entry);\n if (c === undefined || !managedCmds.has(c)) {\n survivingUserEntries.push(entry);\n }\n }\n }\n\n const combined = [...managedEntries, ...survivingUserEntries];\n if (combined.length > 0) {\n mergedHooks[event] = combined;\n }\n }\n\n if (Object.keys(mergedHooks).length > 0) {\n out.hooks = mergedHooks;\n } else {\n delete out.hooks;\n }\n\n return out;\n}\n\n/**\n * Compute the merged settings.json TEXT for a project.\n *\n * @param existingRaw on-disk settings.json text (or undefined if absent)\n * @param managedRaw the freshly generated (managed) settings.json text\n */\nexport function mergedSettingsText(\n existingRaw: string | undefined,\n managedRaw: string,\n): string {\n const managed = parseSettings(managedRaw);\n const existing = existingRaw === undefined ? undefined : parseSettings(existingRaw);\n return serializeSettings(mergeSettings(existing, managed));\n}\n","/**\n * Prompt Executor — natural language routing via LLM tool selection.\n *\n * Converts component operations into tool descriptions, sends them to an LLM\n * for routing, and dispatches the selected operation through the existing\n * component binding.\n */\n\nimport * as YAML from \"yaml\";\nimport type { ComponentIR, JSONSchemaRef } from \"@aaac/contracts\";\nimport type { RuntimeBinding, AaacInvocationContext } from \"../component-binding.js\";\nimport { createAdapter } from \"./adapter-factory.js\";\n\nexport interface OperationToolDef {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nexport interface PromptResult {\n selectedOperation: string;\n mappedInput: Record<string, unknown>;\n output?: unknown;\n dryRun?: boolean;\n model?: string;\n}\n\nexport interface PromptExecuteOptions {\n dryRun?: boolean;\n adapter: string;\n model?: string;\n}\n\nfunction unwrapInputSchema(\n input: JSONSchemaRef | undefined,\n): Record<string, unknown> {\n if (!input) {\n return { type: \"object\", properties: {} };\n }\n if (\"schema\" in input && input.schema && typeof input.schema === \"object\") {\n return input.schema as Record<string, unknown>;\n }\n if (\"$ref\" in input) {\n return { type: \"object\", properties: {} };\n }\n return input as Record<string, unknown>;\n}\n\n/**\n * Convert non-handler, non-prompt operations from ComponentIR into tool definitions\n * for LLM routing.\n */\nexport function operationsToTools(ir: ComponentIR): OperationToolDef[] {\n return Object.entries(ir.operations)\n .filter(([name, op]) => name !== \"prompt\" && !op.handler)\n .map(([name, op]) => ({\n name,\n description: op.description,\n inputSchema: unwrapInputSchema(op.input),\n }));\n}\n\nfunction buildRouterPrompt(\n componentId: string,\n tools: OperationToolDef[],\n message: string,\n): string {\n const toolDescriptions = tools\n .map((t) => {\n const schema = JSON.stringify(t.inputSchema, null, 2);\n return `### ${t.name}\\n${t.description}\\nInput schema:\\n\\`\\`\\`json\\n${schema}\\n\\`\\`\\``;\n })\n .join(\"\\n\\n\");\n\n return [\n `You are an operation router for the \"${componentId}\" CLI.`,\n `Understand the user request and call the appropriate operation.`,\n `Always select exactly one operation. Extract parameters from the user message.`,\n ``,\n `## Available Operations`,\n ``,\n toolDescriptions,\n ``,\n `## Response Format`,\n ``,\n `Respond with ONLY the following YAML:`,\n ``,\n \"```yaml\",\n `operation: <operation_name>`,\n `input:`,\n ` <key>: <value>`,\n \"```\",\n ``,\n `## User Request`,\n ``,\n message,\n ].join(\"\\n\");\n}\n\n/**\n * Parse the LLM router response to extract selected operation and mapped input.\n */\nexport function parseRouterResponse(\n response: string,\n validNames: string[],\n): { selectedOperation: string; mappedInput: Record<string, unknown> } {\n const yamlMatch = response.match(/```(?:yaml)?\\n([\\s\\S]*?)```/);\n const content = yamlMatch ? yamlMatch[1].trim() : response.trim();\n\n const asMapping = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n let parsed: Record<string, unknown> | undefined;\n try {\n parsed = asMapping(YAML.parse(content));\n } catch {\n // fall through to the JSON attempt below\n }\n if (parsed === undefined) {\n const jsonMatch = response.match(/\\{[\\s\\S]*\"operation\"[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n parsed = asMapping(JSON.parse(jsonMatch[0]));\n } catch {\n // fall through to error below\n }\n }\n }\n\n if (parsed?.operation && typeof parsed.operation === \"string\") {\n if (!validNames.includes(parsed.operation)) {\n throw new Error(\n `Router selected unknown operation \"${parsed.operation}\". Available: ${validNames.join(\", \")}`,\n );\n }\n return {\n selectedOperation: parsed.operation,\n mappedInput: (parsed.input ?? {}) as Record<string, unknown>,\n };\n }\n\n throw new Error(\n `Could not parse operation routing from LLM response. ` +\n `Expected YAML with \"operation\" and \"input\" fields.\\n` +\n `Response:\\n${response.slice(0, 500)}`,\n );\n}\n\n/**\n * Execute a natural language prompt by routing to the appropriate operation.\n */\nexport async function executePrompt(\n message: string,\n ir: ComponentIR,\n binding: RuntimeBinding,\n ctx: AaacInvocationContext,\n opts: PromptExecuteOptions,\n): Promise<PromptResult> {\n const tools = operationsToTools(ir);\n if (tools.length < 2) {\n throw new Error(\n `prompt command requires at least 2 routable operations, found ${tools.length}`,\n );\n }\n\n const prompt = buildRouterPrompt(ir.info.id, tools, message);\n const adapter = await createAdapter(opts.adapter, { model: opts.model });\n const response = await adapter.send(prompt, { readonly: true });\n const { selectedOperation, mappedInput } = parseRouterResponse(\n response,\n tools.map((t) => t.name),\n );\n\n if (opts.dryRun) {\n return {\n selectedOperation,\n mappedInput,\n dryRun: true,\n model: opts.model,\n };\n }\n\n const output = await binding.execute(selectedOperation, {}, mappedInput, ctx);\n return { selectedOperation, mappedInput, output };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,QAAM,SAAS;MACb,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;;AAGP,QAAM,WAAW;AAAjB,QACE,WAAW;AAEb,aAAS,WAAW,KAAK;AACvB,aAAO,OAAO,GAAG;;AAGZ,aAAS,OAAO,KAAuB;AAC5C,eAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,iBAAS,OAAO,UAAU,CAAC,GAAG;AAC5B,cAAI,OAAO,UAAU,eAAe,KAAK,UAAU,CAAC,GAAG,GAAG,GAAG;AAC3D,gBAAI,GAAG,IAAI,UAAU,CAAC,EAAE,GAAG;;;;AAKjC,aAAO;;AAGF,QAAI,WAAW,OAAO,UAAU;;AAKvC,QAAI,aAAa,SA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BAAmB,YAAY,IAAI;AAAA,IACzC;AAAA,IACA,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,EACzB;AAEA,MAAI,KAAK,QAAQ;AACf,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR,OAAO,KAAK;AAAA,IACd;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,QAAQ,QAAQ,mBAAmB,CAAC,GAAG,aAAa,GAAG;AAC5E,SAAO,EAAE,mBAAmB,aAAa,OAAO;AAClD;;;AlClLA,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,MAAMA,SAAQ,iBAAiB;AAG9B,IAAM,UAAU,IAAI;","names":["isFunction","options","ret","wrapper","ret","context","options","Handlebars","hb","parse","lexer","parse","compile","join","sourceFile","version","needle","section","i","hb","module","z","z","extractPath","projectHandoffs","contextFor","stepModelFields","context","taskResult","stepUserRequest","existsSync","resolve","absPath","resolve","existsSync","readFile","join","pathSegmentForId","resolveFilePath","mkdir","readFile","unlink","writeFile","join","pathSegmentForId","join","pathSegmentForId","mkdir","readFile","writeFile","unlink","pkg","resolve","resolve","attachMemoryRef","existsSync","resolve","dirname","resolve","existsSync","dirname","resolveAdapter","readFile","readdir","readdir","readFile","z","pathSegmentForId","existsSync","join","resolve","join","existsSync","resolve","pathSegmentForId","pathSegmentForId","Handlebars","pathSegmentForId","pathSegmentForId","GENERATED_MARKER","pathSegmentForId","existsSync","mkdir","readFile","stat","writeFile","dirname","join","resolve","readFileSync","dirname","join","parse","fileURLToPath","dirname","join","parse","dirname","fileURLToPath","parse","readFileSync","join","pkg","c","join","existsSync","readFile","content","resolve","absPath","stat","mkdir","dirname","writeFile","action","YAML","require"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/handlebars/lib/handlebars/utils.js","../../../node_modules/handlebars/lib/handlebars/exception.js","../../../node_modules/handlebars/lib/handlebars/helpers/block-helper-missing.js","../../../node_modules/handlebars/lib/handlebars/helpers/each.js","../../../node_modules/handlebars/lib/handlebars/helpers/helper-missing.js","../../../node_modules/handlebars/lib/handlebars/helpers/if.js","../../../node_modules/handlebars/lib/handlebars/helpers/log.js","../../../node_modules/handlebars/lib/handlebars/helpers/lookup.js","../../../node_modules/handlebars/lib/handlebars/helpers/with.js","../../../node_modules/handlebars/lib/handlebars/helpers.js","../../../node_modules/handlebars/lib/handlebars/decorators/inline.js","../../../node_modules/handlebars/lib/handlebars/decorators.js","../../../node_modules/handlebars/lib/handlebars/logger.js","../../../node_modules/handlebars/lib/handlebars/internal/proto-access.js","../../../node_modules/handlebars/lib/handlebars/base.js","../../../node_modules/handlebars/lib/handlebars/safe-string.js","../../../node_modules/handlebars/lib/handlebars/internal/wrapHelper.js","../../../node_modules/handlebars/lib/handlebars/runtime.js","../../../node_modules/handlebars/lib/handlebars/no-conflict.js","../../../node_modules/handlebars/lib/handlebars.runtime.js","../../../node_modules/handlebars/lib/handlebars/compiler/ast.js","../../../node_modules/handlebars/lib/handlebars/compiler/parser.js","../../../node_modules/handlebars/lib/handlebars/compiler/visitor.js","../../../node_modules/handlebars/lib/handlebars/compiler/whitespace-control.js","../../../node_modules/handlebars/lib/handlebars/compiler/helpers.js","../../../node_modules/handlebars/lib/handlebars/compiler/base.js","../../../node_modules/handlebars/lib/handlebars/compiler/compiler.js","../../../node_modules/handlebars/node_modules/source-map/lib/base64.js","../../../node_modules/handlebars/node_modules/source-map/lib/base64-vlq.js","../../../node_modules/handlebars/node_modules/source-map/lib/util.js","../../../node_modules/handlebars/node_modules/source-map/lib/array-set.js","../../../node_modules/handlebars/node_modules/source-map/lib/mapping-list.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-map-generator.js","../../../node_modules/handlebars/node_modules/source-map/lib/binary-search.js","../../../node_modules/handlebars/node_modules/source-map/lib/quick-sort.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-map-consumer.js","../../../node_modules/handlebars/node_modules/source-map/lib/source-node.js","../../../node_modules/handlebars/node_modules/source-map/source-map.js","../../../node_modules/handlebars/lib/handlebars/compiler/code-gen.js","../../../node_modules/handlebars/lib/handlebars/compiler/javascript-compiler.js","../../../node_modules/handlebars/lib/handlebars.js","../../../node_modules/handlebars/lib/handlebars/compiler/printer.js","../../../node_modules/handlebars/lib/index.js","../src/index.ts","../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/candidate-agents.ts","../src/lib/model-pricing.ts","../src/lib/process-axis-bridge.ts","../src/lib/toolchain-checker.ts","../src/lib/workflow-input.ts","../src/lib/workflow-runner.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts","../src/lib/model-resolver.ts","../src/lib/progress-sink.ts","../src/lib/memory-store.ts","../src/lib/file-memory-store.ts","../src/lib/agent-log-writer.ts","../src/lib/library-tool-binding.ts","../src/lib/adapter-factory.ts","../src/lib/execute.ts","../src/component-scope.ts","../src/lib/model-aware-adapter.ts","../src/component-binding.ts","../src/lib/project-runtime.ts","../src/lib/guard-commands.ts","../src/lib/claude-materialize/config.ts","../src/lib/claude-materialize/workflow-render.ts","../src/lib/claude-materialize/dsl-sources.ts","../src/lib/claude-materialize/command-render.ts","../src/lib/claude-materialize/frontmatter.ts","../src/lib/claude-materialize/agent-render.ts","../src/lib/claude-materialize/materialize.ts","../src/lib/claude-materialize/bundle-bins.ts","../src/lib/claude-materialize/claude-bundle-assets.ts","../src/lib/claude-materialize/settings-merge.ts","../src/lib/prompt-executor.ts"],"sourcesContent":["const escape = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`',\n '=': '='\n};\n\nconst badChars = /[&<>\"'`=]/g,\n possible = /[&<>\"'`=]/;\n\nfunction escapeChar(chr) {\n return escape[chr];\n}\n\nexport function extend(obj /* , ...source */) {\n for (let i = 1; i < arguments.length; i++) {\n for (let key in arguments[i]) {\n if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {\n obj[key] = arguments[i][key];\n }\n }\n }\n\n return obj;\n}\n\nexport let toString = Object.prototype.toString;\n\n// Sourced from lodash\n// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt\n/* eslint-disable func-style */\nlet isFunction = function(value) {\n return typeof value === 'function';\n};\n// fallback for older versions of Chrome and Safari\n/* istanbul ignore next */\nif (isFunction(/x/)) {\n isFunction = function(value) {\n return (\n typeof value === 'function' &&\n toString.call(value) === '[object Function]'\n );\n };\n}\nexport { isFunction };\n/* eslint-enable func-style */\n\n/* istanbul ignore next */\nexport const isArray =\n Array.isArray ||\n function(value) {\n return value && typeof value === 'object'\n ? toString.call(value) === '[object Array]'\n : false;\n };\n\n// Older IE versions do not directly support indexOf so we must implement our own, sadly.\nexport function indexOf(array, value) {\n for (let i = 0, len = array.length; i < len; i++) {\n if (array[i] === value) {\n return i;\n }\n }\n return -1;\n}\n\nexport function escapeExpression(string) {\n if (typeof string !== 'string') {\n // don't escape SafeStrings, since they're already safe\n if (string && string.toHTML) {\n return string.toHTML();\n } else if (string == null) {\n return '';\n } else if (!string) {\n return string + '';\n }\n\n // Force a string conversion as this will be done by the append regardless and\n // the regex test will do this transparently behind the scenes, causing issues if\n // an object's to string has escaped characters in it.\n string = '' + string;\n }\n\n if (!possible.test(string)) {\n return string;\n }\n return string.replace(badChars, escapeChar);\n}\n\nexport function isEmpty(value) {\n if (!value && value !== 0) {\n return true;\n } else if (isArray(value) && value.length === 0) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function createFrame(object) {\n let frame = extend({}, object);\n frame._parent = object;\n return frame;\n}\n\nexport function blockParams(params, ids) {\n params.path = ids;\n return params;\n}\n\nexport function appendContextPath(contextPath, id) {\n return (contextPath ? contextPath + '.' : '') + id;\n}\n","const errorProps = [\n 'description',\n 'fileName',\n 'lineNumber',\n 'endLineNumber',\n 'message',\n 'name',\n 'number',\n 'stack'\n];\n\nfunction Exception(message, node) {\n let loc = node && node.loc,\n line,\n endLineNumber,\n column,\n endColumn;\n\n if (loc) {\n line = loc.start.line;\n endLineNumber = loc.end.line;\n column = loc.start.column;\n endColumn = loc.end.column;\n\n message += ' - ' + line + ':' + column;\n }\n\n let tmp = Error.prototype.constructor.call(this, message);\n\n // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.\n for (let idx = 0; idx < errorProps.length; idx++) {\n this[errorProps[idx]] = tmp[errorProps[idx]];\n }\n\n /* istanbul ignore else */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Exception);\n }\n\n try {\n if (loc) {\n this.lineNumber = line;\n this.endLineNumber = endLineNumber;\n\n // Work around issue under safari where we can't directly set the column value\n /* istanbul ignore next */\n if (Object.defineProperty) {\n Object.defineProperty(this, 'column', {\n value: column,\n enumerable: true\n });\n Object.defineProperty(this, 'endColumn', {\n value: endColumn,\n enumerable: true\n });\n } else {\n this.column = column;\n this.endColumn = endColumn;\n }\n }\n } catch (nop) {\n /* Ignore if the browser is very particular */\n }\n}\n\nException.prototype = new Error();\n\nexport default Exception;\n","import { appendContextPath, createFrame, isArray } from '../utils';\n\nexport default function(instance) {\n instance.registerHelper('blockHelperMissing', function(context, options) {\n let inverse = options.inverse,\n fn = options.fn;\n\n if (context === true) {\n return fn(this);\n } else if (context === false || context == null) {\n return inverse(this);\n } else if (isArray(context)) {\n if (context.length > 0) {\n if (options.ids) {\n options.ids = [options.name];\n }\n\n return instance.helpers.each(context, options);\n } else {\n return inverse(this);\n }\n } else {\n if (options.data && options.ids) {\n let data = createFrame(options.data);\n data.contextPath = appendContextPath(\n options.data.contextPath,\n options.name\n );\n options = { data: data };\n }\n\n return fn(context, options);\n }\n });\n}\n","import {\n appendContextPath,\n blockParams,\n createFrame,\n isArray,\n isFunction\n} from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('each', function(context, options) {\n if (!options) {\n throw new Exception('Must pass iterator to #each');\n }\n\n let fn = options.fn,\n inverse = options.inverse,\n i = 0,\n ret = '',\n data,\n contextPath;\n\n if (options.data && options.ids) {\n contextPath =\n appendContextPath(options.data.contextPath, options.ids[0]) + '.';\n }\n\n if (isFunction(context)) {\n context = context.call(this);\n }\n\n if (options.data) {\n data = createFrame(options.data);\n }\n\n function execIteration(field, index, last) {\n if (data) {\n data.key = field;\n data.index = index;\n data.first = index === 0;\n data.last = !!last;\n\n if (contextPath) {\n data.contextPath = contextPath + field;\n }\n }\n\n ret =\n ret +\n fn(context[field], {\n data: data,\n blockParams: blockParams(\n [context[field], field],\n [contextPath + field, null]\n )\n });\n }\n\n if (context && typeof context === 'object') {\n if (isArray(context)) {\n for (let j = context.length; i < j; i++) {\n if (i in context) {\n execIteration(i, i, i === context.length - 1);\n }\n }\n } else if (typeof Symbol === 'function' && context[Symbol.iterator]) {\n const newContext = [];\n const iterator = context[Symbol.iterator]();\n for (let it = iterator.next(); !it.done; it = iterator.next()) {\n newContext.push(it.value);\n }\n context = newContext;\n for (let j = context.length; i < j; i++) {\n execIteration(i, i, i === context.length - 1);\n }\n } else {\n let priorKey;\n\n Object.keys(context).forEach(key => {\n // We're running the iterations one step out of sync so we can detect\n // the last iteration without have to scan the object twice and create\n // an itermediate keys array.\n if (priorKey !== undefined) {\n execIteration(priorKey, i - 1);\n }\n priorKey = key;\n i++;\n });\n if (priorKey !== undefined) {\n execIteration(priorKey, i - 1, true);\n }\n }\n }\n\n if (i === 0) {\n ret = inverse(this);\n }\n\n return ret;\n });\n}\n","import Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('helperMissing', function(/* [args, ]options */) {\n if (arguments.length === 1) {\n // A missing field in a {{foo}} construct.\n return undefined;\n } else {\n // Someone is actually trying to call something, blow up.\n throw new Exception(\n 'Missing helper: \"' + arguments[arguments.length - 1].name + '\"'\n );\n }\n });\n}\n","import { isEmpty, isFunction } from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('if', function(conditional, options) {\n if (arguments.length != 2) {\n throw new Exception('#if requires exactly one argument');\n }\n if (isFunction(conditional)) {\n conditional = conditional.call(this);\n }\n\n // Default behavior is to render the positive path if the value is truthy and not empty.\n // The `includeZero` option may be set to treat the condtional as purely not empty based on the\n // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.\n if ((!options.hash.includeZero && !conditional) || isEmpty(conditional)) {\n return options.inverse(this);\n } else {\n return options.fn(this);\n }\n });\n\n instance.registerHelper('unless', function(conditional, options) {\n if (arguments.length != 2) {\n throw new Exception('#unless requires exactly one argument');\n }\n return instance.helpers['if'].call(this, conditional, {\n fn: options.inverse,\n inverse: options.fn,\n hash: options.hash\n });\n });\n}\n","export default function(instance) {\n instance.registerHelper('log', function(/* message, options */) {\n let args = [undefined],\n options = arguments[arguments.length - 1];\n for (let i = 0; i < arguments.length - 1; i++) {\n args.push(arguments[i]);\n }\n\n let level = 1;\n if (options.hash.level != null) {\n level = options.hash.level;\n } else if (options.data && options.data.level != null) {\n level = options.data.level;\n }\n args[0] = level;\n\n instance.log(...args);\n });\n}\n","export default function(instance) {\n instance.registerHelper('lookup', function(obj, field, options) {\n if (!obj) {\n // Note for 5.0: Change to \"obj == null\" in 5.0\n return obj;\n }\n return options.lookupProperty(obj, field);\n });\n}\n","import {\n appendContextPath,\n blockParams,\n createFrame,\n isEmpty,\n isFunction\n} from '../utils';\nimport Exception from '../exception';\n\nexport default function(instance) {\n instance.registerHelper('with', function(context, options) {\n if (arguments.length != 2) {\n throw new Exception('#with requires exactly one argument');\n }\n if (isFunction(context)) {\n context = context.call(this);\n }\n\n let fn = options.fn;\n\n if (!isEmpty(context)) {\n let data = options.data;\n if (options.data && options.ids) {\n data = createFrame(options.data);\n data.contextPath = appendContextPath(\n options.data.contextPath,\n options.ids[0]\n );\n }\n\n return fn(context, {\n data: data,\n blockParams: blockParams([context], [data && data.contextPath])\n });\n } else {\n return options.inverse(this);\n }\n });\n}\n","import registerBlockHelperMissing from './helpers/block-helper-missing';\nimport registerEach from './helpers/each';\nimport registerHelperMissing from './helpers/helper-missing';\nimport registerIf from './helpers/if';\nimport registerLog from './helpers/log';\nimport registerLookup from './helpers/lookup';\nimport registerWith from './helpers/with';\n\nexport function registerDefaultHelpers(instance) {\n registerBlockHelperMissing(instance);\n registerEach(instance);\n registerHelperMissing(instance);\n registerIf(instance);\n registerLog(instance);\n registerLookup(instance);\n registerWith(instance);\n}\n\nexport function moveHelperToHooks(instance, helperName, keepHelper) {\n if (instance.helpers[helperName]) {\n instance.hooks[helperName] = instance.helpers[helperName];\n if (!keepHelper) {\n // Using delete is slow\n instance.helpers[helperName] = undefined;\n }\n }\n}\n","import { extend } from '../utils';\n\nexport default function(instance) {\n instance.registerDecorator('inline', function(fn, props, container, options) {\n let ret = fn;\n if (!props.partials) {\n props.partials = {};\n ret = function(context, options) {\n // Create a new partials stack frame prior to exec.\n let original = container.partials;\n container.partials = extend({}, original, props.partials);\n let ret = fn(context, options);\n container.partials = original;\n return ret;\n };\n }\n\n props.partials[options.args[0]] = options.fn;\n\n return ret;\n });\n}\n","import registerInline from './decorators/inline';\n\nexport function registerDefaultDecorators(instance) {\n registerInline(instance);\n}\n","import { indexOf } from './utils';\n\nlet logger = {\n methodMap: ['debug', 'info', 'warn', 'error'],\n level: 'info',\n\n // Maps a given level value to the `methodMap` indexes above.\n lookupLevel: function(level) {\n if (typeof level === 'string') {\n let levelMap = indexOf(logger.methodMap, level.toLowerCase());\n if (levelMap >= 0) {\n level = levelMap;\n } else {\n level = parseInt(level, 10);\n }\n }\n\n return level;\n },\n\n // Can be overridden in the host environment\n log: function(level, ...message) {\n level = logger.lookupLevel(level);\n\n if (\n typeof console !== 'undefined' &&\n logger.lookupLevel(logger.level) <= level\n ) {\n let method = logger.methodMap[level];\n // eslint-disable-next-line no-console\n if (!console[method]) {\n method = 'log';\n }\n console[method](...message); // eslint-disable-line no-console\n }\n }\n};\n\nexport default logger;\n","import { extend } from '../utils';\nimport logger from '../logger';\n\nconst loggedProperties = Object.create(null);\n\nexport function createProtoAccessControl(runtimeOptions) {\n // Create an object with \"null\"-prototype to avoid truthy results on\n // prototype properties.\n const propertyWhiteList = Object.create(null);\n // eslint-disable-next-line no-proto\n propertyWhiteList['__proto__'] = false;\n extend(propertyWhiteList, runtimeOptions.allowedProtoProperties);\n\n const methodWhiteList = Object.create(null);\n methodWhiteList['constructor'] = false;\n methodWhiteList['__defineGetter__'] = false;\n methodWhiteList['__defineSetter__'] = false;\n methodWhiteList['__lookupGetter__'] = false;\n methodWhiteList['__lookupSetter__'] = false;\n extend(methodWhiteList, runtimeOptions.allowedProtoMethods);\n\n return {\n properties: {\n whitelist: propertyWhiteList,\n defaultValue: runtimeOptions.allowProtoPropertiesByDefault\n },\n methods: {\n whitelist: methodWhiteList,\n defaultValue: runtimeOptions.allowProtoMethodsByDefault\n }\n };\n}\n\nexport function resultIsAllowed(result, protoAccessControl, propertyName) {\n if (typeof result === 'function') {\n return checkWhiteList(protoAccessControl.methods, propertyName);\n } else {\n return checkWhiteList(protoAccessControl.properties, propertyName);\n }\n}\n\nfunction checkWhiteList(protoAccessControlForType, propertyName) {\n if (protoAccessControlForType.whitelist[propertyName] !== undefined) {\n return protoAccessControlForType.whitelist[propertyName] === true;\n }\n if (protoAccessControlForType.defaultValue !== undefined) {\n return protoAccessControlForType.defaultValue;\n }\n logUnexpecedPropertyAccessOnce(propertyName);\n return false;\n}\n\nfunction logUnexpecedPropertyAccessOnce(propertyName) {\n if (loggedProperties[propertyName] !== true) {\n loggedProperties[propertyName] = true;\n logger.log(\n 'error',\n `Handlebars: Access has been denied to resolve the property \"${propertyName}\" because it is not an \"own property\" of its parent.\\n` +\n `You can add a runtime option to disable the check or this warning:\\n` +\n `See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`\n );\n }\n}\n\nexport function resetLoggedProperties() {\n Object.keys(loggedProperties).forEach(propertyName => {\n delete loggedProperties[propertyName];\n });\n}\n","import { createFrame, extend, toString } from './utils';\nimport Exception from './exception';\nimport { registerDefaultHelpers } from './helpers';\nimport { registerDefaultDecorators } from './decorators';\nimport logger from './logger';\nimport { resetLoggedProperties } from './internal/proto-access';\n\nexport const VERSION = '4.7.9';\nexport const COMPILER_REVISION = 8;\nexport const LAST_COMPATIBLE_COMPILER_REVISION = 7;\n\nexport const REVISION_CHANGES = {\n 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it\n 2: '== 1.0.0-rc.3',\n 3: '== 1.0.0-rc.4',\n 4: '== 1.x.x',\n 5: '== 2.0.0-alpha.x',\n 6: '>= 2.0.0-beta.1',\n 7: '>= 4.0.0 <4.3.0',\n 8: '>= 4.3.0'\n};\n\nconst objectType = '[object Object]';\n\nexport function HandlebarsEnvironment(helpers, partials, decorators) {\n this.helpers = helpers || {};\n this.partials = partials || {};\n this.decorators = decorators || {};\n\n registerDefaultHelpers(this);\n registerDefaultDecorators(this);\n}\n\nHandlebarsEnvironment.prototype = {\n constructor: HandlebarsEnvironment,\n\n logger: logger,\n log: logger.log,\n\n registerHelper: function(name, fn) {\n if (toString.call(name) === objectType) {\n if (fn) {\n throw new Exception('Arg not supported with multiple helpers');\n }\n extend(this.helpers, name);\n } else {\n this.helpers[name] = fn;\n }\n },\n unregisterHelper: function(name) {\n delete this.helpers[name];\n },\n\n registerPartial: function(name, partial) {\n if (toString.call(name) === objectType) {\n extend(this.partials, name);\n } else {\n if (typeof partial === 'undefined') {\n throw new Exception(\n `Attempting to register a partial called \"${name}\" as undefined`\n );\n }\n this.partials[name] = partial;\n }\n },\n unregisterPartial: function(name) {\n delete this.partials[name];\n },\n\n registerDecorator: function(name, fn) {\n if (toString.call(name) === objectType) {\n if (fn) {\n throw new Exception('Arg not supported with multiple decorators');\n }\n extend(this.decorators, name);\n } else {\n this.decorators[name] = fn;\n }\n },\n unregisterDecorator: function(name) {\n delete this.decorators[name];\n },\n /**\n * Reset the memory of illegal property accesses that have already been logged.\n * @deprecated should only be used in handlebars test-cases\n */\n resetLoggedPropertyAccesses() {\n resetLoggedProperties();\n }\n};\n\nexport let log = logger.log;\n\nexport { createFrame, logger };\n","// Build out our basic SafeString type\nfunction SafeString(string) {\n this.string = string;\n}\n\nSafeString.prototype.toString = SafeString.prototype.toHTML = function() {\n return '' + this.string;\n};\n\nexport default SafeString;\n","export function wrapHelper(helper, transformOptionsFn) {\n if (typeof helper !== 'function') {\n // This should not happen, but apparently it does in https://github.com/wycats/handlebars.js/issues/1639\n // We try to make the wrapper least-invasive by not wrapping it, if the helper is not a function.\n return helper;\n }\n let wrapper = function(/* dynamic arguments */) {\n const options = arguments[arguments.length - 1];\n arguments[arguments.length - 1] = transformOptionsFn(options);\n return helper.apply(this, arguments);\n };\n return wrapper;\n}\n","import * as Utils from './utils';\nimport Exception from './exception';\nimport {\n COMPILER_REVISION,\n createFrame,\n LAST_COMPATIBLE_COMPILER_REVISION,\n REVISION_CHANGES\n} from './base';\nimport { moveHelperToHooks } from './helpers';\nimport { wrapHelper } from './internal/wrapHelper';\nimport {\n createProtoAccessControl,\n resultIsAllowed\n} from './internal/proto-access';\n\nexport function checkRevision(compilerInfo) {\n const compilerRevision = (compilerInfo && compilerInfo[0]) || 1,\n currentRevision = COMPILER_REVISION;\n\n if (\n compilerRevision >= LAST_COMPATIBLE_COMPILER_REVISION &&\n compilerRevision <= COMPILER_REVISION\n ) {\n return;\n }\n\n if (compilerRevision < LAST_COMPATIBLE_COMPILER_REVISION) {\n const runtimeVersions = REVISION_CHANGES[currentRevision],\n compilerVersions = REVISION_CHANGES[compilerRevision];\n throw new Exception(\n 'Template was precompiled with an older version of Handlebars than the current runtime. ' +\n 'Please update your precompiler to a newer version (' +\n runtimeVersions +\n ') or downgrade your runtime to an older version (' +\n compilerVersions +\n ').'\n );\n } else {\n // Use the embedded version info since the runtime doesn't know about this revision yet\n throw new Exception(\n 'Template was precompiled with a newer version of Handlebars than the current runtime. ' +\n 'Please update your runtime to a newer version (' +\n compilerInfo[1] +\n ').'\n );\n }\n}\n\nexport function template(templateSpec, env) {\n /* istanbul ignore next */\n if (!env) {\n throw new Exception('No environment passed to template');\n }\n if (!templateSpec || !templateSpec.main) {\n throw new Exception('Unknown template object: ' + typeof templateSpec);\n }\n\n templateSpec.main.decorator = templateSpec.main_d;\n\n // Note: Using env.VM references rather than local var references throughout this section to allow\n // for external users to override these as pseudo-supported APIs.\n env.VM.checkRevision(templateSpec.compiler);\n\n // backwards compatibility for precompiled templates with compiler-version 7 (<4.3.0)\n const templateWasPrecompiledWithCompilerV7 =\n templateSpec.compiler && templateSpec.compiler[0] === 7;\n\n function invokePartialWrapper(partial, context, options) {\n if (options.hash) {\n context = Utils.extend({}, context, options.hash);\n if (options.ids) {\n options.ids[0] = true;\n }\n }\n partial = env.VM.resolvePartial.call(this, partial, context, options);\n\n options.hooks = this.hooks;\n options.protoAccessControl = this.protoAccessControl;\n\n let result = env.VM.invokePartial.call(this, partial, context, options);\n\n if (result == null && env.compile) {\n options.partials[options.name] = env.compile(\n partial,\n templateSpec.compilerOptions,\n env\n );\n result = options.partials[options.name](context, options);\n }\n if (result != null) {\n if (options.indent) {\n let lines = result.split('\\n');\n for (let i = 0, l = lines.length; i < l; i++) {\n if (!lines[i] && i + 1 === l) {\n break;\n }\n\n lines[i] = options.indent + lines[i];\n }\n result = lines.join('\\n');\n }\n return result;\n } else {\n throw new Exception(\n 'The partial ' +\n options.name +\n ' could not be compiled when running in runtime-only mode'\n );\n }\n }\n\n // Just add water\n let container = {\n strict: function(obj, name, loc) {\n if (!obj || !(name in obj)) {\n throw new Exception('\"' + name + '\" not defined in ' + obj, {\n loc: loc\n });\n }\n return container.lookupProperty(obj, name);\n },\n lookupProperty: function(parent, propertyName) {\n let result = parent[propertyName];\n if (result == null) {\n return result;\n }\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return result;\n }\n\n if (resultIsAllowed(result, container.protoAccessControl, propertyName)) {\n return result;\n }\n return undefined;\n },\n lookup: function(depths, name) {\n const len = depths.length;\n for (let i = 0; i < len; i++) {\n let result = depths[i] && container.lookupProperty(depths[i], name);\n if (result != null) {\n return result;\n }\n }\n },\n lambda: function(current, context) {\n return typeof current === 'function' ? current.call(context) : current;\n },\n\n escapeExpression: Utils.escapeExpression,\n invokePartial: invokePartialWrapper,\n\n fn: function(i) {\n let ret = templateSpec[i];\n ret.decorator = templateSpec[i + '_d'];\n return ret;\n },\n\n programs: [],\n program: function(i, data, declaredBlockParams, blockParams, depths) {\n let programWrapper = this.programs[i],\n fn = this.fn(i);\n if (data || depths || blockParams || declaredBlockParams) {\n programWrapper = wrapProgram(\n this,\n i,\n fn,\n data,\n declaredBlockParams,\n blockParams,\n depths\n );\n } else if (!programWrapper) {\n programWrapper = this.programs[i] = wrapProgram(this, i, fn);\n }\n return programWrapper;\n },\n\n data: function(value, depth) {\n while (value && depth--) {\n value = value._parent;\n }\n return value;\n },\n mergeIfNeeded: function(param, common) {\n let obj = param || common;\n\n if (param && common && param !== common) {\n obj = Utils.extend({}, common, param);\n }\n\n return obj;\n },\n // An empty object to use as replacement for null-contexts\n nullContext: Object.seal({}),\n\n noop: env.VM.noop,\n compilerInfo: templateSpec.compiler\n };\n\n function ret(context, options = {}) {\n let data = options.data;\n\n ret._setup(options);\n if (!options.partial && templateSpec.useData) {\n data = initData(context, data);\n }\n let depths,\n blockParams = templateSpec.useBlockParams ? [] : undefined;\n if (templateSpec.useDepths) {\n if (options.depths) {\n depths =\n context != options.depths[0]\n ? [context].concat(options.depths)\n : options.depths;\n } else {\n depths = [context];\n }\n }\n\n function main(context /*, options*/) {\n return (\n '' +\n templateSpec.main(\n container,\n context,\n container.helpers,\n container.partials,\n data,\n blockParams,\n depths\n )\n );\n }\n\n main = executeDecorators(\n templateSpec.main,\n main,\n container,\n options.depths || [],\n data,\n blockParams\n );\n return main(context, options);\n }\n\n ret.isTop = true;\n\n ret._setup = function(options) {\n if (!options.partial) {\n let mergedHelpers = {};\n addHelpers(mergedHelpers, env.helpers, container);\n addHelpers(mergedHelpers, options.helpers, container);\n container.helpers = mergedHelpers;\n\n if (templateSpec.usePartial) {\n // Use mergeIfNeeded here to prevent compiling global partials multiple times\n container.partials = container.mergeIfNeeded(\n options.partials,\n env.partials\n );\n }\n if (templateSpec.usePartial || templateSpec.useDecorators) {\n container.decorators = Utils.extend(\n {},\n env.decorators,\n options.decorators\n );\n }\n\n container.hooks = {};\n container.protoAccessControl = createProtoAccessControl(options);\n\n let keepHelperInHelpers =\n options.allowCallsToHelperMissing ||\n templateWasPrecompiledWithCompilerV7;\n moveHelperToHooks(container, 'helperMissing', keepHelperInHelpers);\n moveHelperToHooks(container, 'blockHelperMissing', keepHelperInHelpers);\n } else {\n container.protoAccessControl = options.protoAccessControl; // internal option\n container.helpers = options.helpers;\n container.partials = options.partials;\n container.decorators = options.decorators;\n container.hooks = options.hooks;\n }\n };\n\n ret._child = function(i, data, blockParams, depths) {\n if (templateSpec.useBlockParams && !blockParams) {\n throw new Exception('must pass block params');\n }\n if (templateSpec.useDepths && !depths) {\n throw new Exception('must pass parent depths');\n }\n\n return wrapProgram(\n container,\n i,\n templateSpec[i],\n data,\n 0,\n blockParams,\n depths\n );\n };\n return ret;\n}\n\nexport function wrapProgram(\n container,\n i,\n fn,\n data,\n declaredBlockParams,\n blockParams,\n depths\n) {\n function prog(context, options = {}) {\n let currentDepths = depths;\n if (\n depths &&\n context != depths[0] &&\n !(context === container.nullContext && depths[0] === null)\n ) {\n currentDepths = [context].concat(depths);\n }\n\n return fn(\n container,\n context,\n container.helpers,\n container.partials,\n options.data || data,\n blockParams && [options.blockParams].concat(blockParams),\n currentDepths\n );\n }\n\n prog = executeDecorators(fn, prog, container, depths, data, blockParams);\n\n prog.program = i;\n prog.depth = depths ? depths.length : 0;\n prog.blockParams = declaredBlockParams || 0;\n return prog;\n}\n\n/**\n * This is currently part of the official API, therefore implementation details should not be changed.\n */\nexport function resolvePartial(partial, context, options) {\n if (!partial) {\n if (options.name === '@partial-block') {\n partial = lookupOwnProperty(options.data, 'partial-block');\n } else {\n partial = lookupOwnProperty(options.partials, options.name);\n }\n } else if (!partial.call && !options.name) {\n // This is a dynamic partial that returned a string\n options.name = partial;\n partial = lookupOwnProperty(options.partials, partial);\n }\n return partial;\n}\n\nexport function invokePartial(partial, context, options) {\n // Use the current closure context to save the partial-block if this partial\n const currentPartialBlock = lookupOwnProperty(options.data, 'partial-block');\n options.partial = true;\n if (options.ids) {\n options.data.contextPath = options.ids[0] || options.data.contextPath;\n }\n\n let partialBlock;\n if (options.fn && options.fn !== noop) {\n options.data = createFrame(options.data);\n // Wrapper function to get access to currentPartialBlock from the closure\n let fn = options.fn;\n partialBlock = options.data['partial-block'] = function partialBlockWrapper(\n context,\n options = {}\n ) {\n // Restore the partial-block from the closure for the execution of the block\n // i.e. the part inside the block of the partial call.\n options.data = createFrame(options.data);\n options.data['partial-block'] = currentPartialBlock;\n return fn(context, options);\n };\n if (fn.partials) {\n options.partials = Utils.extend({}, options.partials, fn.partials);\n }\n }\n\n if (partial === undefined && partialBlock) {\n partial = partialBlock;\n }\n\n if (partial === undefined) {\n throw new Exception('The partial ' + options.name + ' could not be found');\n } else if (partial instanceof Function) {\n return partial(context, options);\n }\n}\n\nexport function noop() {\n return '';\n}\n\nfunction lookupOwnProperty(obj, name) {\n if (obj && Object.prototype.hasOwnProperty.call(obj, name)) {\n return obj[name];\n }\n}\n\nfunction initData(context, data) {\n if (!data || !('root' in data)) {\n data = data ? createFrame(data) : {};\n data.root = context;\n }\n return data;\n}\n\nfunction executeDecorators(fn, prog, container, depths, data, blockParams) {\n if (fn.decorator) {\n let props = {};\n prog = fn.decorator(\n prog,\n props,\n container,\n depths && depths[0],\n data,\n blockParams,\n depths\n );\n Utils.extend(prog, props);\n }\n return prog;\n}\n\nfunction addHelpers(mergedHelpers, helpers, container) {\n if (!helpers) return;\n Object.keys(helpers).forEach(helperName => {\n let helper = helpers[helperName];\n mergedHelpers[helperName] = passLookupPropertyOption(helper, container);\n });\n}\n\nfunction passLookupPropertyOption(helper, container) {\n const lookupProperty = container.lookupProperty;\n return wrapHelper(helper, options => {\n options.lookupProperty = lookupProperty;\n return options;\n });\n}\n","/* global globalThis */\nexport default function(Handlebars) {\n /* istanbul ignore next */\n // https://mathiasbynens.be/notes/globalthis\n (function() {\n if (typeof globalThis === 'object') return;\n Object.prototype.__defineGetter__('__magic__', function() {\n return this;\n });\n __magic__.globalThis = __magic__; // eslint-disable-line no-undef\n delete Object.prototype.__magic__;\n })();\n\n const $Handlebars = globalThis.Handlebars;\n\n /* istanbul ignore next */\n Handlebars.noConflict = function() {\n if (globalThis.Handlebars === Handlebars) {\n globalThis.Handlebars = $Handlebars;\n }\n return Handlebars;\n };\n}\n","import * as base from './handlebars/base';\n\n// Each of these augment the Handlebars object. No need to setup here.\n// (This is done to easily share code between commonjs and browse envs)\nimport SafeString from './handlebars/safe-string';\nimport Exception from './handlebars/exception';\nimport * as Utils from './handlebars/utils';\nimport * as runtime from './handlebars/runtime';\n\nimport noConflict from './handlebars/no-conflict';\n\n// For compatibility and usage outside of module systems, make the Handlebars object a namespace\nfunction create() {\n let hb = new base.HandlebarsEnvironment();\n\n Utils.extend(hb, base);\n hb.SafeString = SafeString;\n hb.Exception = Exception;\n hb.Utils = Utils;\n hb.escapeExpression = Utils.escapeExpression;\n\n hb.VM = runtime;\n hb.template = function(spec) {\n return runtime.template(spec, hb);\n };\n\n return hb;\n}\n\nlet inst = create();\ninst.create = create;\n\nnoConflict(inst);\n\ninst['default'] = inst;\n\nexport default inst;\n","let AST = {\n // Public API used to evaluate derived attributes regarding AST nodes\n helpers: {\n // a mustache is definitely a helper if:\n // * it is an eligible helper, and\n // * it has at least one parameter or hash segment\n helperExpression: function(node) {\n return (\n node.type === 'SubExpression' ||\n ((node.type === 'MustacheStatement' ||\n node.type === 'BlockStatement') &&\n !!((node.params && node.params.length) || node.hash))\n );\n },\n\n scopedId: function(path) {\n return /^\\.|this\\b/.test(path.original);\n },\n\n // an ID is simple if it only has one part, and that part is not\n // `..` or `this`.\n simpleId: function(path) {\n return (\n path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth\n );\n }\n }\n};\n\n// Must be exported as an object rather than the root of the module as the jison lexer\n// must modify the object to operate properly.\nexport default AST;\n","// File ignored in coverage tests via setting in .istanbul.yml\n/* Jison generated parser */\nvar handlebars = (function(){\nvar parser = {trace: function trace () { },\nyy: {},\nsymbols_: {\"error\":2,\"root\":3,\"program\":4,\"EOF\":5,\"program_repetition0\":6,\"statement\":7,\"mustache\":8,\"block\":9,\"rawBlock\":10,\"partial\":11,\"partialBlock\":12,\"content\":13,\"COMMENT\":14,\"CONTENT\":15,\"openRawBlock\":16,\"rawBlock_repetition0\":17,\"END_RAW_BLOCK\":18,\"OPEN_RAW_BLOCK\":19,\"helperName\":20,\"openRawBlock_repetition0\":21,\"openRawBlock_option0\":22,\"CLOSE_RAW_BLOCK\":23,\"openBlock\":24,\"block_option0\":25,\"closeBlock\":26,\"openInverse\":27,\"block_option1\":28,\"OPEN_BLOCK\":29,\"openBlock_repetition0\":30,\"openBlock_option0\":31,\"openBlock_option1\":32,\"CLOSE\":33,\"OPEN_INVERSE\":34,\"openInverse_repetition0\":35,\"openInverse_option0\":36,\"openInverse_option1\":37,\"openInverseChain\":38,\"OPEN_INVERSE_CHAIN\":39,\"openInverseChain_repetition0\":40,\"openInverseChain_option0\":41,\"openInverseChain_option1\":42,\"inverseAndProgram\":43,\"INVERSE\":44,\"inverseChain\":45,\"inverseChain_option0\":46,\"OPEN_ENDBLOCK\":47,\"OPEN\":48,\"mustache_repetition0\":49,\"mustache_option0\":50,\"OPEN_UNESCAPED\":51,\"mustache_repetition1\":52,\"mustache_option1\":53,\"CLOSE_UNESCAPED\":54,\"OPEN_PARTIAL\":55,\"partialName\":56,\"partial_repetition0\":57,\"partial_option0\":58,\"openPartialBlock\":59,\"OPEN_PARTIAL_BLOCK\":60,\"openPartialBlock_repetition0\":61,\"openPartialBlock_option0\":62,\"param\":63,\"sexpr\":64,\"OPEN_SEXPR\":65,\"sexpr_repetition0\":66,\"sexpr_option0\":67,\"CLOSE_SEXPR\":68,\"hash\":69,\"hash_repetition_plus0\":70,\"hashSegment\":71,\"ID\":72,\"EQUALS\":73,\"blockParams\":74,\"OPEN_BLOCK_PARAMS\":75,\"blockParams_repetition_plus0\":76,\"CLOSE_BLOCK_PARAMS\":77,\"path\":78,\"dataName\":79,\"STRING\":80,\"NUMBER\":81,\"BOOLEAN\":82,\"UNDEFINED\":83,\"NULL\":84,\"DATA\":85,\"pathSegments\":86,\"SEP\":87,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",5:\"EOF\",14:\"COMMENT\",15:\"CONTENT\",18:\"END_RAW_BLOCK\",19:\"OPEN_RAW_BLOCK\",23:\"CLOSE_RAW_BLOCK\",29:\"OPEN_BLOCK\",33:\"CLOSE\",34:\"OPEN_INVERSE\",39:\"OPEN_INVERSE_CHAIN\",44:\"INVERSE\",47:\"OPEN_ENDBLOCK\",48:\"OPEN\",51:\"OPEN_UNESCAPED\",54:\"CLOSE_UNESCAPED\",55:\"OPEN_PARTIAL\",60:\"OPEN_PARTIAL_BLOCK\",65:\"OPEN_SEXPR\",68:\"CLOSE_SEXPR\",72:\"ID\",73:\"EQUALS\",75:\"OPEN_BLOCK_PARAMS\",77:\"CLOSE_BLOCK_PARAMS\",80:\"STRING\",81:\"NUMBER\",82:\"BOOLEAN\",83:\"UNDEFINED\",84:\"NULL\",85:\"DATA\",87:\"SEP\"},\nproductions_: [0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],\nperformAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$\n) {\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1: return $$[$0-1]; \nbreak;\ncase 2:this.$ = yy.prepareProgram($$[$0]);\nbreak;\ncase 3:this.$ = $$[$0];\nbreak;\ncase 4:this.$ = $$[$0];\nbreak;\ncase 5:this.$ = $$[$0];\nbreak;\ncase 6:this.$ = $$[$0];\nbreak;\ncase 7:this.$ = $$[$0];\nbreak;\ncase 8:this.$ = $$[$0];\nbreak;\ncase 9:\n this.$ = {\n type: 'CommentStatement',\n value: yy.stripComment($$[$0]),\n strip: yy.stripFlags($$[$0], $$[$0]),\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 10:\n this.$ = {\n type: 'ContentStatement',\n original: $$[$0],\n value: $$[$0],\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 11:this.$ = yy.prepareRawBlock($$[$0-2], $$[$0-1], $$[$0], this._$);\nbreak;\ncase 12:this.$ = { path: $$[$0-3], params: $$[$0-2], hash: $$[$0-1] };\nbreak;\ncase 13:this.$ = yy.prepareBlock($$[$0-3], $$[$0-2], $$[$0-1], $$[$0], false, this._$);\nbreak;\ncase 14:this.$ = yy.prepareBlock($$[$0-3], $$[$0-2], $$[$0-1], $$[$0], true, this._$);\nbreak;\ncase 15:this.$ = { open: $$[$0-5], path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 16:this.$ = { path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 17:this.$ = { path: $$[$0-4], params: $$[$0-3], hash: $$[$0-2], blockParams: $$[$0-1], strip: yy.stripFlags($$[$0-5], $$[$0]) };\nbreak;\ncase 18:this.$ = { strip: yy.stripFlags($$[$0-1], $$[$0-1]), program: $$[$0] };\nbreak;\ncase 19:\n var inverse = yy.prepareBlock($$[$0-2], $$[$0-1], $$[$0], $$[$0], false, this._$),\n program = yy.prepareProgram([inverse], $$[$0-1].loc);\n program.chained = true;\n\n this.$ = { strip: $$[$0-2].strip, program: program, chain: true };\n \nbreak;\ncase 20:this.$ = $$[$0];\nbreak;\ncase 21:this.$ = {path: $$[$0-1], strip: yy.stripFlags($$[$0-2], $$[$0])};\nbreak;\ncase 22:this.$ = yy.prepareMustache($$[$0-3], $$[$0-2], $$[$0-1], $$[$0-4], yy.stripFlags($$[$0-4], $$[$0]), this._$);\nbreak;\ncase 23:this.$ = yy.prepareMustache($$[$0-3], $$[$0-2], $$[$0-1], $$[$0-4], yy.stripFlags($$[$0-4], $$[$0]), this._$);\nbreak;\ncase 24:\n this.$ = {\n type: 'PartialStatement',\n name: $$[$0-3],\n params: $$[$0-2],\n hash: $$[$0-1],\n indent: '',\n strip: yy.stripFlags($$[$0-4], $$[$0]),\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 25:this.$ = yy.preparePartialBlock($$[$0-2], $$[$0-1], $$[$0], this._$);\nbreak;\ncase 26:this.$ = { path: $$[$0-3], params: $$[$0-2], hash: $$[$0-1], strip: yy.stripFlags($$[$0-4], $$[$0]) };\nbreak;\ncase 27:this.$ = $$[$0];\nbreak;\ncase 28:this.$ = $$[$0];\nbreak;\ncase 29:\n this.$ = {\n type: 'SubExpression',\n path: $$[$0-3],\n params: $$[$0-2],\n hash: $$[$0-1],\n loc: yy.locInfo(this._$)\n };\n \nbreak;\ncase 30:this.$ = {type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 31:this.$ = {type: 'HashPair', key: yy.id($$[$0-2]), value: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 32:this.$ = yy.id($$[$0-1]);\nbreak;\ncase 33:this.$ = $$[$0];\nbreak;\ncase 34:this.$ = $$[$0];\nbreak;\ncase 35:this.$ = {type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$)};\nbreak;\ncase 36:this.$ = {type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$)};\nbreak;\ncase 37:this.$ = {type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$)};\nbreak;\ncase 38:this.$ = {type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$)};\nbreak;\ncase 39:this.$ = {type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$)};\nbreak;\ncase 40:this.$ = $$[$0];\nbreak;\ncase 41:this.$ = $$[$0];\nbreak;\ncase 42:this.$ = yy.preparePath(true, $$[$0], this._$);\nbreak;\ncase 43:this.$ = yy.preparePath(false, $$[$0], this._$);\nbreak;\ncase 44: $$[$0-2].push({part: yy.id($$[$0]), original: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; \nbreak;\ncase 45:this.$ = [{part: yy.id($$[$0]), original: $$[$0]}];\nbreak;\ncase 46:this.$ = [];\nbreak;\ncase 47:$$[$0-1].push($$[$0]);\nbreak;\ncase 48:this.$ = [];\nbreak;\ncase 49:$$[$0-1].push($$[$0]);\nbreak;\ncase 50:this.$ = [];\nbreak;\ncase 51:$$[$0-1].push($$[$0]);\nbreak;\ncase 58:this.$ = [];\nbreak;\ncase 59:$$[$0-1].push($$[$0]);\nbreak;\ncase 64:this.$ = [];\nbreak;\ncase 65:$$[$0-1].push($$[$0]);\nbreak;\ncase 70:this.$ = [];\nbreak;\ncase 71:$$[$0-1].push($$[$0]);\nbreak;\ncase 78:this.$ = [];\nbreak;\ncase 79:$$[$0-1].push($$[$0]);\nbreak;\ncase 82:this.$ = [];\nbreak;\ncase 83:$$[$0-1].push($$[$0]);\nbreak;\ncase 86:this.$ = [];\nbreak;\ncase 87:$$[$0-1].push($$[$0]);\nbreak;\ncase 90:this.$ = [];\nbreak;\ncase 91:$$[$0-1].push($$[$0]);\nbreak;\ncase 94:this.$ = [];\nbreak;\ncase 95:$$[$0-1].push($$[$0]);\nbreak;\ncase 98:this.$ = [$$[$0]];\nbreak;\ncase 99:$$[$0-1].push($$[$0]);\nbreak;\ncase 100:this.$ = [$$[$0]];\nbreak;\ncase 101:$$[$0-1].push($$[$0]);\nbreak;\n}\n},\ntable: [{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],\ndefaultActions: {4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},\nparseError: function parseError (str, hash) {\n throw new Error(str);\n},\nparse: function parse(input) {\n var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n this.lexer.setInput(input);\n this.lexer.yy = this.yy;\n this.yy.lexer = this.lexer;\n this.yy.parser = this;\n if (typeof this.lexer.yylloc == \"undefined\")\n this.lexer.yylloc = {};\n var yyloc = this.lexer.yylloc;\n lstack.push(yyloc);\n var ranges = this.lexer.options && this.lexer.options.ranges;\n if (typeof this.yy.parseError === \"function\")\n this.parseError = this.yy.parseError;\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n function lex() {\n var token;\n token = self.lexer.lex() || 1;\n if (typeof token !== \"number\") {\n token = self.symbols_[token] || token;\n }\n return token;\n }\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n if (!recovering) {\n expected = [];\n for (p in table[state])\n if (this.terminals_[p] && p > 2) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n if (this.lexer.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + this.lexer.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == 1?\"end of input\":\"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});\n }\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(this.lexer.yytext);\n lstack.push(this.lexer.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = this.lexer.yyleng;\n yytext = this.lexer.yytext;\n yylineno = this.lexer.yylineno;\n yyloc = this.lexer.yylloc;\n if (recovering > 0)\n recovering--;\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};\n if (ranges) {\n yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];\n }\n r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n}\n};\n/* Jison generated lexer */\nvar lexer = (function(){\nvar lexer = ({EOF:1,\nparseError:function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n },\nsetInput:function (input) {\n this._input = input;\n this._more = this._less = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = '';\n this.conditionStack = ['INITIAL'];\n this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};\n if (this.options.ranges) this.yylloc.range = [0,0];\n this.offset = 0;\n return this;\n },\ninput:function () {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) this.yylloc.range[1]++;\n\n this._input = this._input.slice(1);\n return ch;\n },\nunput:function (ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length-len-1);\n //this.yyleng -= len;\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length-1);\n this.matched = this.matched.substr(0, this.matched.length-1);\n\n if (lines.length-1) this.yylineno -= lines.length-1;\n var r = this.yylloc.range;\n\n this.yylloc = {first_line: this.yylloc.first_line,\n last_line: this.yylineno+1,\n first_column: this.yylloc.first_column,\n last_column: lines ?\n (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length:\n this.yylloc.first_column - len\n };\n\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n return this;\n },\nmore:function () {\n this._more = true;\n return this;\n },\nless:function (n) {\n this.unput(this.match.slice(n));\n },\npastInput:function () {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n },\nupcomingInput:function () {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20-next.length);\n }\n return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\\n/g, \"\");\n },\nshowPosition:function () {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c+\"^\";\n },\nnext:function () {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) this.done = true;\n\n var token,\n match,\n tempMatch,\n index,\n col,\n lines;\n if (!this._more) {\n this.yytext = '';\n this.match = '';\n }\n var rules = this._currentRules();\n for (var i=0;i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (!this.options.flex) break;\n }\n }\n if (match) {\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) this.yylineno += lines.length;\n this.yylloc = {first_line: this.yylloc.last_line,\n last_line: this.yylineno+1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length};\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);\n if (this.done && this._input) this.done = false;\n if (token) return token;\n else return;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\\n'+this.showPosition(),\n {text: \"\", token: null, line: this.yylineno});\n }\n },\nlex:function lex () {\n var r = this.next();\n if (typeof r !== 'undefined') {\n return r;\n } else {\n return this.lex();\n }\n },\nbegin:function begin (condition) {\n this.conditionStack.push(condition);\n },\npopState:function popState () {\n return this.conditionStack.pop();\n },\n_currentRules:function _currentRules () {\n return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;\n },\ntopState:function () {\n return this.conditionStack[this.conditionStack.length-2];\n },\npushState:function begin (condition) {\n this.begin(condition);\n }});\nlexer.options = {};\nlexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START\n) {\n\n\nfunction strip(start, end) {\n return yy_.yytext = yy_.yytext.substring(start, yy_.yyleng - end + start);\n}\n\n\nvar YYSTATE=YY_START\nswitch($avoiding_name_collisions) {\ncase 0:\n if(yy_.yytext.slice(-2) === \"\\\\\\\\\") {\n strip(0,1);\n this.begin(\"mu\");\n } else if(yy_.yytext.slice(-1) === \"\\\\\") {\n strip(0,1);\n this.begin(\"emu\");\n } else {\n this.begin(\"mu\");\n }\n if(yy_.yytext) return 15;\n \nbreak;\ncase 1:return 15;\nbreak;\ncase 2:\n this.popState();\n return 15;\n \nbreak;\ncase 3:this.begin('raw'); return 15;\nbreak;\ncase 4:\n this.popState();\n // Should be using `this.topState()` below, but it currently\n // returns the second top instead of the first top. Opened an\n // issue about it at https://github.com/zaach/jison/issues/291\n if (this.conditionStack[this.conditionStack.length-1] === 'raw') {\n return 15;\n } else {\n strip(5, 9);\n return 'END_RAW_BLOCK';\n }\n \nbreak;\ncase 5: return 15; \nbreak;\ncase 6:\n this.popState();\n return 14;\n\nbreak;\ncase 7:return 65;\nbreak;\ncase 8:return 68;\nbreak;\ncase 9: return 19; \nbreak;\ncase 10:\n this.popState();\n this.begin('raw');\n return 23;\n \nbreak;\ncase 11:return 55;\nbreak;\ncase 12:return 60;\nbreak;\ncase 13:return 29;\nbreak;\ncase 14:return 47;\nbreak;\ncase 15:this.popState(); return 44;\nbreak;\ncase 16:this.popState(); return 44;\nbreak;\ncase 17:return 34;\nbreak;\ncase 18:return 39;\nbreak;\ncase 19:return 51;\nbreak;\ncase 20:return 48;\nbreak;\ncase 21:\n this.unput(yy_.yytext);\n this.popState();\n this.begin('com');\n\nbreak;\ncase 22:\n this.popState();\n return 14;\n\nbreak;\ncase 23:return 48;\nbreak;\ncase 24:return 73;\nbreak;\ncase 25:return 72;\nbreak;\ncase 26:return 72;\nbreak;\ncase 27:return 87;\nbreak;\ncase 28:// ignore whitespace\nbreak;\ncase 29:this.popState(); return 54;\nbreak;\ncase 30:this.popState(); return 33;\nbreak;\ncase 31:yy_.yytext = strip(1,2).replace(/\\\\\"/g,'\"'); return 80;\nbreak;\ncase 32:yy_.yytext = strip(1,2).replace(/\\\\'/g,\"'\"); return 80;\nbreak;\ncase 33:return 85;\nbreak;\ncase 34:return 82;\nbreak;\ncase 35:return 82;\nbreak;\ncase 36:return 83;\nbreak;\ncase 37:return 84;\nbreak;\ncase 38:return 81;\nbreak;\ncase 39:return 75;\nbreak;\ncase 40:return 77;\nbreak;\ncase 41:return 72;\nbreak;\ncase 42:yy_.yytext = yy_.yytext.replace(/\\\\([\\\\\\]])/g,'$1'); return 72;\nbreak;\ncase 43:return 'INVALID';\nbreak;\ncase 44:return 5;\nbreak;\n}\n};\nlexer.rules = [/^(?:[^\\x00]*?(?=(\\{\\{)))/,/^(?:[^\\x00]+)/,/^(?:[^\\x00]{2,}?(?=(\\{\\{|\\\\\\{\\{|\\\\\\\\\\{\\{|$)))/,/^(?:\\{\\{\\{\\{(?=[^\\/]))/,/^(?:\\{\\{\\{\\{\\/[^\\s!\"#%-,\\.\\/;->@\\[-\\^`\\{-~]+(?=[=}\\s\\/.])\\}\\}\\}\\})/,/^(?:[^\\x00]+?(?=(\\{\\{\\{\\{)))/,/^(?:[\\s\\S]*?--(~)?\\}\\})/,/^(?:\\()/,/^(?:\\))/,/^(?:\\{\\{\\{\\{)/,/^(?:\\}\\}\\}\\})/,/^(?:\\{\\{(~)?>)/,/^(?:\\{\\{(~)?#>)/,/^(?:\\{\\{(~)?#\\*?)/,/^(?:\\{\\{(~)?\\/)/,/^(?:\\{\\{(~)?\\^\\s*(~)?\\}\\})/,/^(?:\\{\\{(~)?\\s*else\\s*(~)?\\}\\})/,/^(?:\\{\\{(~)?\\^)/,/^(?:\\{\\{(~)?\\s*else\\b)/,/^(?:\\{\\{(~)?\\{)/,/^(?:\\{\\{(~)?&)/,/^(?:\\{\\{(~)?!--)/,/^(?:\\{\\{(~)?![\\s\\S]*?\\}\\})/,/^(?:\\{\\{(~)?\\*?)/,/^(?:=)/,/^(?:\\.\\.)/,/^(?:\\.(?=([=~}\\s\\/.)|])))/,/^(?:[\\/.])/,/^(?:\\s+)/,/^(?:\\}(~)?\\}\\})/,/^(?:(~)?\\}\\})/,/^(?:\"(\\\\[\"]|[^\"])*\")/,/^(?:'(\\\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\\s)])))/,/^(?:false(?=([~}\\s)])))/,/^(?:undefined(?=([~}\\s)])))/,/^(?:null(?=([~}\\s)])))/,/^(?:-?[0-9]+(?:\\.[0-9]+)?(?=([~}\\s)])))/,/^(?:as\\s+\\|)/,/^(?:\\|)/,/^(?:([^\\s!\"#%-,\\.\\/;->@\\[-\\^`\\{-~]+(?=([=~}\\s\\/.)|]))))/,/^(?:\\[(\\\\\\]|[^\\]])*\\])/,/^(?:.)/,/^(?:$)/];\nlexer.conditions = {\"mu\":{\"rules\":[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],\"inclusive\":false},\"emu\":{\"rules\":[2],\"inclusive\":false},\"com\":{\"rules\":[6],\"inclusive\":false},\"raw\":{\"rules\":[3,4,5],\"inclusive\":false},\"INITIAL\":{\"rules\":[0,1,44],\"inclusive\":true}};\nreturn lexer;})()\nparser.lexer = lexer;\nfunction Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser;\nreturn new Parser;\n})();export default handlebars;\n","import Exception from '../exception';\n\nfunction Visitor() {\n this.parents = [];\n}\n\nVisitor.prototype = {\n constructor: Visitor,\n mutating: false,\n\n // Visits a given value. If mutating, will replace the value if necessary.\n acceptKey: function(node, name) {\n let value = this.accept(node[name]);\n if (this.mutating) {\n // Hacky sanity check: This may have a few false positives for type for the helper\n // methods but will generally do the right thing without a lot of overhead.\n if (value && !Visitor.prototype[value.type]) {\n throw new Exception(\n 'Unexpected node type \"' +\n value.type +\n '\" found when accepting ' +\n name +\n ' on ' +\n node.type\n );\n }\n node[name] = value;\n }\n },\n\n // Performs an accept operation with added sanity check to ensure\n // required keys are not removed.\n acceptRequired: function(node, name) {\n this.acceptKey(node, name);\n\n if (!node[name]) {\n throw new Exception(node.type + ' requires ' + name);\n }\n },\n\n // Traverses a given array. If mutating, empty respnses will be removed\n // for child elements.\n acceptArray: function(array) {\n for (let i = 0, l = array.length; i < l; i++) {\n this.acceptKey(array, i);\n\n if (!array[i]) {\n array.splice(i, 1);\n i--;\n l--;\n }\n }\n },\n\n accept: function(object) {\n if (!object) {\n return;\n }\n\n /* istanbul ignore next: Sanity code */\n if (!this[object.type]) {\n throw new Exception('Unknown type: ' + object.type, object);\n }\n\n if (this.current) {\n this.parents.unshift(this.current);\n }\n this.current = object;\n\n let ret = this[object.type](object);\n\n this.current = this.parents.shift();\n\n if (!this.mutating || ret) {\n return ret;\n } else if (ret !== false) {\n return object;\n }\n },\n\n Program: function(program) {\n this.acceptArray(program.body);\n },\n\n MustacheStatement: visitSubExpression,\n Decorator: visitSubExpression,\n\n BlockStatement: visitBlock,\n DecoratorBlock: visitBlock,\n\n PartialStatement: visitPartial,\n PartialBlockStatement: function(partial) {\n visitPartial.call(this, partial);\n\n this.acceptKey(partial, 'program');\n },\n\n ContentStatement: function(/* content */) {},\n CommentStatement: function(/* comment */) {},\n\n SubExpression: visitSubExpression,\n\n PathExpression: function(/* path */) {},\n\n StringLiteral: function(/* string */) {},\n NumberLiteral: function(/* number */) {},\n BooleanLiteral: function(/* bool */) {},\n UndefinedLiteral: function(/* literal */) {},\n NullLiteral: function(/* literal */) {},\n\n Hash: function(hash) {\n this.acceptArray(hash.pairs);\n },\n HashPair: function(pair) {\n this.acceptRequired(pair, 'value');\n }\n};\n\nfunction visitSubExpression(mustache) {\n this.acceptRequired(mustache, 'path');\n this.acceptArray(mustache.params);\n this.acceptKey(mustache, 'hash');\n}\nfunction visitBlock(block) {\n visitSubExpression.call(this, block);\n\n this.acceptKey(block, 'program');\n this.acceptKey(block, 'inverse');\n}\nfunction visitPartial(partial) {\n this.acceptRequired(partial, 'name');\n this.acceptArray(partial.params);\n this.acceptKey(partial, 'hash');\n}\n\nexport default Visitor;\n","import Visitor from './visitor';\n\nfunction WhitespaceControl(options = {}) {\n this.options = options;\n}\nWhitespaceControl.prototype = new Visitor();\n\nWhitespaceControl.prototype.Program = function(program) {\n const doStandalone = !this.options.ignoreStandalone;\n\n let isRoot = !this.isRootSeen;\n this.isRootSeen = true;\n\n let body = program.body;\n for (let i = 0, l = body.length; i < l; i++) {\n let current = body[i],\n strip = this.accept(current);\n\n if (!strip) {\n continue;\n }\n\n let _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),\n _isNextWhitespace = isNextWhitespace(body, i, isRoot),\n openStandalone = strip.openStandalone && _isPrevWhitespace,\n closeStandalone = strip.closeStandalone && _isNextWhitespace,\n inlineStandalone =\n strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;\n\n if (strip.close) {\n omitRight(body, i, true);\n }\n if (strip.open) {\n omitLeft(body, i, true);\n }\n\n if (doStandalone && inlineStandalone) {\n omitRight(body, i);\n\n if (omitLeft(body, i)) {\n // If we are on a standalone node, save the indent info for partials\n if (current.type === 'PartialStatement') {\n // Pull out the whitespace from the final line\n current.indent = /([ \\t]+$)/.exec(body[i - 1].original)[1];\n }\n }\n }\n if (doStandalone && openStandalone) {\n omitRight((current.program || current.inverse).body);\n\n // Strip out the previous content node if it's whitespace only\n omitLeft(body, i);\n }\n if (doStandalone && closeStandalone) {\n // Always strip the next node\n omitRight(body, i);\n\n omitLeft((current.inverse || current.program).body);\n }\n }\n\n return program;\n};\n\nWhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(\n block\n) {\n this.accept(block.program);\n this.accept(block.inverse);\n\n // Find the inverse program that is involed with whitespace stripping.\n let program = block.program || block.inverse,\n inverse = block.program && block.inverse,\n firstInverse = inverse,\n lastInverse = inverse;\n\n if (inverse && inverse.chained) {\n firstInverse = inverse.body[0].program;\n\n // Walk the inverse chain to find the last inverse that is actually in the chain.\n while (lastInverse.chained) {\n lastInverse = lastInverse.body[lastInverse.body.length - 1].program;\n }\n }\n\n let strip = {\n open: block.openStrip.open,\n close: block.closeStrip.close,\n\n // Determine the standalone candiacy. Basically flag our content as being possibly standalone\n // so our parent can determine if we actually are standalone\n openStandalone: isNextWhitespace(program.body),\n closeStandalone: isPrevWhitespace((firstInverse || program).body)\n };\n\n if (block.openStrip.close) {\n omitRight(program.body, null, true);\n }\n\n if (inverse) {\n let inverseStrip = block.inverseStrip;\n\n if (inverseStrip.open) {\n omitLeft(program.body, null, true);\n }\n\n if (inverseStrip.close) {\n omitRight(firstInverse.body, null, true);\n }\n if (block.closeStrip.open) {\n omitLeft(lastInverse.body, null, true);\n }\n\n // Find standalone else statments\n if (\n !this.options.ignoreStandalone &&\n isPrevWhitespace(program.body) &&\n isNextWhitespace(firstInverse.body)\n ) {\n omitLeft(program.body);\n omitRight(firstInverse.body);\n }\n } else if (block.closeStrip.open) {\n omitLeft(program.body, null, true);\n }\n\n return strip;\n};\n\nWhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(\n mustache\n) {\n return mustache.strip;\n};\n\nWhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(\n node\n) {\n /* istanbul ignore next */\n let strip = node.strip || {};\n return {\n inlineStandalone: true,\n open: strip.open,\n close: strip.close\n };\n};\n\nfunction isPrevWhitespace(body, i, isRoot) {\n if (i === undefined) {\n i = body.length;\n }\n\n // Nodes that end with newlines are considered whitespace (but are special\n // cased for strip operations)\n let prev = body[i - 1],\n sibling = body[i - 2];\n if (!prev) {\n return isRoot;\n }\n\n if (prev.type === 'ContentStatement') {\n return (sibling || !isRoot ? /\\r?\\n\\s*?$/ : /(^|\\r?\\n)\\s*?$/).test(\n prev.original\n );\n }\n}\nfunction isNextWhitespace(body, i, isRoot) {\n if (i === undefined) {\n i = -1;\n }\n\n let next = body[i + 1],\n sibling = body[i + 2];\n if (!next) {\n return isRoot;\n }\n\n if (next.type === 'ContentStatement') {\n return (sibling || !isRoot ? /^\\s*?\\r?\\n/ : /^\\s*?(\\r?\\n|$)/).test(\n next.original\n );\n }\n}\n\n// Marks the node to the right of the position as omitted.\n// I.e. {{foo}}' ' will mark the ' ' node as omitted.\n//\n// If i is undefined, then the first child will be marked as such.\n//\n// If mulitple is truthy then all whitespace will be stripped out until non-whitespace\n// content is met.\nfunction omitRight(body, i, multiple) {\n let current = body[i == null ? 0 : i + 1];\n if (\n !current ||\n current.type !== 'ContentStatement' ||\n (!multiple && current.rightStripped)\n ) {\n return;\n }\n\n let original = current.value;\n current.value = current.value.replace(\n multiple ? /^\\s+/ : /^[ \\t]*\\r?\\n?/,\n ''\n );\n current.rightStripped = current.value !== original;\n}\n\n// Marks the node to the left of the position as omitted.\n// I.e. ' '{{foo}} will mark the ' ' node as omitted.\n//\n// If i is undefined then the last child will be marked as such.\n//\n// If mulitple is truthy then all whitespace will be stripped out until non-whitespace\n// content is met.\nfunction omitLeft(body, i, multiple) {\n let current = body[i == null ? body.length - 1 : i - 1];\n if (\n !current ||\n current.type !== 'ContentStatement' ||\n (!multiple && current.leftStripped)\n ) {\n return;\n }\n\n // We omit the last node if it's whitespace only and not preceded by a non-content node.\n let original = current.value;\n current.value = current.value.replace(multiple ? /\\s+$/ : /[ \\t]+$/, '');\n current.leftStripped = current.value !== original;\n return current.leftStripped;\n}\n\nexport default WhitespaceControl;\n","import Exception from '../exception';\n\nfunction validateClose(open, close) {\n close = close.path ? close.path.original : close;\n\n if (open.path.original !== close) {\n let errorNode = { loc: open.path.loc };\n\n throw new Exception(\n open.path.original + \" doesn't match \" + close,\n errorNode\n );\n }\n}\n\nexport function SourceLocation(source, locInfo) {\n this.source = source;\n this.start = {\n line: locInfo.first_line,\n column: locInfo.first_column\n };\n this.end = {\n line: locInfo.last_line,\n column: locInfo.last_column\n };\n}\n\nexport function id(token) {\n if (/^\\[.*\\]$/.test(token)) {\n return token.substring(1, token.length - 1);\n } else {\n return token;\n }\n}\n\nexport function stripFlags(open, close) {\n return {\n open: open.charAt(2) === '~',\n close: close.charAt(close.length - 3) === '~'\n };\n}\n\nexport function stripComment(comment) {\n return comment.replace(/^\\{\\{~?!-?-?/, '').replace(/-?-?~?\\}\\}$/, '');\n}\n\nexport function preparePath(data, parts, loc) {\n loc = this.locInfo(loc);\n\n let original = data ? '@' : '',\n dig = [],\n depth = 0;\n\n for (let i = 0, l = parts.length; i < l; i++) {\n let part = parts[i].part,\n // If we have [] syntax then we do not treat path references as operators,\n // i.e. foo.[this] resolves to approximately context.foo['this']\n isLiteral = parts[i].original !== part;\n original += (parts[i].separator || '') + part;\n\n if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {\n if (dig.length > 0) {\n throw new Exception('Invalid path: ' + original, { loc });\n } else if (part === '..') {\n depth++;\n }\n } else {\n dig.push(part);\n }\n }\n\n return {\n type: 'PathExpression',\n data,\n depth,\n parts: dig,\n original,\n loc\n };\n}\n\nexport function prepareMustache(path, params, hash, open, strip, locInfo) {\n // Must use charAt to support IE pre-10\n let escapeFlag = open.charAt(3) || open.charAt(2),\n escaped = escapeFlag !== '{' && escapeFlag !== '&';\n\n let decorator = /\\*/.test(open);\n return {\n type: decorator ? 'Decorator' : 'MustacheStatement',\n path,\n params,\n hash,\n escaped,\n strip,\n loc: this.locInfo(locInfo)\n };\n}\n\nexport function prepareRawBlock(openRawBlock, contents, close, locInfo) {\n validateClose(openRawBlock, close);\n\n locInfo = this.locInfo(locInfo);\n let program = {\n type: 'Program',\n body: contents,\n strip: {},\n loc: locInfo\n };\n\n return {\n type: 'BlockStatement',\n path: openRawBlock.path,\n params: openRawBlock.params,\n hash: openRawBlock.hash,\n program,\n openStrip: {},\n inverseStrip: {},\n closeStrip: {},\n loc: locInfo\n };\n}\n\nexport function prepareBlock(\n openBlock,\n program,\n inverseAndProgram,\n close,\n inverted,\n locInfo\n) {\n if (close && close.path) {\n validateClose(openBlock, close);\n }\n\n let decorator = /\\*/.test(openBlock.open);\n\n program.blockParams = openBlock.blockParams;\n\n let inverse, inverseStrip;\n\n if (inverseAndProgram) {\n if (decorator) {\n throw new Exception(\n 'Unexpected inverse block on decorator',\n inverseAndProgram\n );\n }\n\n if (inverseAndProgram.chain) {\n inverseAndProgram.program.body[0].closeStrip = close.strip;\n }\n\n inverseStrip = inverseAndProgram.strip;\n inverse = inverseAndProgram.program;\n }\n\n if (inverted) {\n inverted = inverse;\n inverse = program;\n program = inverted;\n }\n\n return {\n type: decorator ? 'DecoratorBlock' : 'BlockStatement',\n path: openBlock.path,\n params: openBlock.params,\n hash: openBlock.hash,\n program,\n inverse,\n openStrip: openBlock.strip,\n inverseStrip,\n closeStrip: close && close.strip,\n loc: this.locInfo(locInfo)\n };\n}\n\nexport function prepareProgram(statements, loc) {\n if (!loc && statements.length) {\n const firstLoc = statements[0].loc,\n lastLoc = statements[statements.length - 1].loc;\n\n /* istanbul ignore else */\n if (firstLoc && lastLoc) {\n loc = {\n source: firstLoc.source,\n start: {\n line: firstLoc.start.line,\n column: firstLoc.start.column\n },\n end: {\n line: lastLoc.end.line,\n column: lastLoc.end.column\n }\n };\n }\n }\n\n return {\n type: 'Program',\n body: statements,\n strip: {},\n loc: loc\n };\n}\n\nexport function preparePartialBlock(open, program, close, locInfo) {\n validateClose(open, close);\n\n return {\n type: 'PartialBlockStatement',\n name: open.path,\n params: open.params,\n hash: open.hash,\n program,\n openStrip: open.strip,\n closeStrip: close && close.strip,\n loc: this.locInfo(locInfo)\n };\n}\n","import parser from './parser';\nimport WhitespaceControl from './whitespace-control';\nimport * as Helpers from './helpers';\nimport Exception from '../exception';\nimport { extend } from '../utils';\n\nexport { parser };\n\nlet yy = {};\nextend(yy, Helpers);\n\nexport function parseWithoutProcessing(input, options) {\n // Just return if an already-compiled AST was passed in.\n if (input.type === 'Program') {\n // When a pre-parsed AST is passed in, validate all node values to prevent\n // code injection via type-confused literals.\n validateInputAst(input);\n return input;\n }\n\n parser.yy = yy;\n\n // Altering the shared object here, but this is ok as parser is a sync operation\n yy.locInfo = function(locInfo) {\n return new yy.SourceLocation(options && options.srcName, locInfo);\n };\n\n let ast = parser.parse(input);\n\n return ast;\n}\n\nexport function parse(input, options) {\n let ast = parseWithoutProcessing(input, options);\n let strip = new WhitespaceControl(options);\n\n return strip.accept(ast);\n}\n\nfunction validateInputAst(ast) {\n validateAstNode(ast);\n}\n\nfunction validateAstNode(node) {\n if (node == null) {\n return;\n }\n\n if (Array.isArray(node)) {\n node.forEach(validateAstNode);\n return;\n }\n\n if (typeof node !== 'object') {\n return;\n }\n\n if (node.type === 'PathExpression') {\n if (!isValidDepth(node.depth)) {\n throw new Exception(\n 'Invalid AST: PathExpression.depth must be an integer'\n );\n }\n if (!Array.isArray(node.parts)) {\n throw new Exception('Invalid AST: PathExpression.parts must be an array');\n }\n for (let i = 0; i < node.parts.length; i++) {\n if (typeof node.parts[i] !== 'string') {\n throw new Exception(\n 'Invalid AST: PathExpression.parts must only contain strings'\n );\n }\n }\n } else if (node.type === 'NumberLiteral') {\n if (typeof node.value !== 'number' || !isFinite(node.value)) {\n throw new Exception('Invalid AST: NumberLiteral.value must be a number');\n }\n } else if (node.type === 'BooleanLiteral') {\n if (typeof node.value !== 'boolean') {\n throw new Exception(\n 'Invalid AST: BooleanLiteral.value must be a boolean'\n );\n }\n }\n\n Object.keys(node).forEach(propertyName => {\n if (propertyName === 'loc') {\n return;\n }\n validateAstNode(node[propertyName]);\n });\n}\n\nfunction isValidDepth(depth) {\n return (\n typeof depth === 'number' &&\n isFinite(depth) &&\n Math.floor(depth) === depth &&\n depth >= 0\n );\n}\n","/* eslint-disable new-cap */\n\nimport Exception from '../exception';\nimport { isArray, indexOf, extend } from '../utils';\nimport AST from './ast';\n\nconst slice = [].slice;\n\nexport function Compiler() {}\n\n// the foundHelper register will disambiguate helper lookup from finding a\n// function in a context. This is necessary for mustache compatibility, which\n// requires that context functions in blocks are evaluated by blockHelperMissing,\n// and then proceed as if the resulting value was provided to blockHelperMissing.\n\nCompiler.prototype = {\n compiler: Compiler,\n\n equals: function(other) {\n let len = this.opcodes.length;\n if (other.opcodes.length !== len) {\n return false;\n }\n\n for (let i = 0; i < len; i++) {\n let opcode = this.opcodes[i],\n otherOpcode = other.opcodes[i];\n if (\n opcode.opcode !== otherOpcode.opcode ||\n !argEquals(opcode.args, otherOpcode.args)\n ) {\n return false;\n }\n }\n\n // We know that length is the same between the two arrays because they are directly tied\n // to the opcode behavior above.\n len = this.children.length;\n for (let i = 0; i < len; i++) {\n if (!this.children[i].equals(other.children[i])) {\n return false;\n }\n }\n\n return true;\n },\n\n guid: 0,\n\n compile: function(program, options) {\n this.sourceNode = [];\n this.opcodes = [];\n this.children = [];\n this.options = options;\n this.stringParams = options.stringParams;\n this.trackIds = options.trackIds;\n\n options.blockParams = options.blockParams || [];\n\n options.knownHelpers = extend(\n Object.create(null),\n {\n helperMissing: true,\n blockHelperMissing: true,\n each: true,\n if: true,\n unless: true,\n with: true,\n log: true,\n lookup: true\n },\n options.knownHelpers\n );\n\n return this.accept(program);\n },\n\n compileProgram: function(program) {\n let childCompiler = new this.compiler(), // eslint-disable-line new-cap\n result = childCompiler.compile(program, this.options),\n guid = this.guid++;\n\n this.usePartial = this.usePartial || result.usePartial;\n\n this.children[guid] = result;\n this.useDepths = this.useDepths || result.useDepths;\n\n return guid;\n },\n\n accept: function(node) {\n /* istanbul ignore next: Sanity code */\n if (!this[node.type]) {\n throw new Exception('Unknown type: ' + node.type, node);\n }\n\n this.sourceNode.unshift(node);\n let ret = this[node.type](node);\n this.sourceNode.shift();\n return ret;\n },\n\n Program: function(program) {\n this.options.blockParams.unshift(program.blockParams);\n\n let body = program.body,\n bodyLength = body.length;\n for (let i = 0; i < bodyLength; i++) {\n this.accept(body[i]);\n }\n\n this.options.blockParams.shift();\n\n this.isSimple = bodyLength === 1;\n this.blockParams = program.blockParams ? program.blockParams.length : 0;\n\n return this;\n },\n\n BlockStatement: function(block) {\n transformLiteralToPath(block);\n\n let program = block.program,\n inverse = block.inverse;\n\n program = program && this.compileProgram(program);\n inverse = inverse && this.compileProgram(inverse);\n\n let type = this.classifySexpr(block);\n\n if (type === 'helper') {\n this.helperSexpr(block, program, inverse);\n } else if (type === 'simple') {\n this.simpleSexpr(block);\n\n // now that the simple mustache is resolved, we need to\n // evaluate it by executing `blockHelperMissing`\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n this.opcode('emptyHash');\n this.opcode('blockValue', block.path.original);\n } else {\n this.ambiguousSexpr(block, program, inverse);\n\n // now that the simple mustache is resolved, we need to\n // evaluate it by executing `blockHelperMissing`\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n this.opcode('emptyHash');\n this.opcode('ambiguousBlockValue');\n }\n\n this.opcode('append');\n },\n\n DecoratorBlock(decorator) {\n let program = decorator.program && this.compileProgram(decorator.program);\n let params = this.setupFullMustacheParams(decorator, program, undefined),\n path = decorator.path;\n\n this.useDecorators = true;\n this.opcode('registerDecorator', params.length, path.original);\n },\n\n PartialStatement: function(partial) {\n this.usePartial = true;\n\n let program = partial.program;\n if (program) {\n program = this.compileProgram(partial.program);\n }\n\n let params = partial.params;\n if (params.length > 1) {\n throw new Exception(\n 'Unsupported number of partial arguments: ' + params.length,\n partial\n );\n } else if (!params.length) {\n if (this.options.explicitPartialContext) {\n this.opcode('pushLiteral', 'undefined');\n } else {\n params.push({ type: 'PathExpression', parts: [], depth: 0 });\n }\n }\n\n let partialName = partial.name.original,\n isDynamic = partial.name.type === 'SubExpression';\n if (isDynamic) {\n this.accept(partial.name);\n }\n\n this.setupFullMustacheParams(partial, program, undefined, true);\n\n let indent = partial.indent || '';\n if (this.options.preventIndent && indent) {\n this.opcode('appendContent', indent);\n indent = '';\n }\n\n this.opcode('invokePartial', isDynamic, partialName, indent);\n this.opcode('append');\n },\n PartialBlockStatement: function(partialBlock) {\n this.PartialStatement(partialBlock);\n },\n\n MustacheStatement: function(mustache) {\n this.SubExpression(mustache);\n\n if (mustache.escaped && !this.options.noEscape) {\n this.opcode('appendEscaped');\n } else {\n this.opcode('append');\n }\n },\n Decorator(decorator) {\n this.DecoratorBlock(decorator);\n },\n\n ContentStatement: function(content) {\n if (content.value) {\n this.opcode('appendContent', content.value);\n }\n },\n\n CommentStatement: function() {},\n\n SubExpression: function(sexpr) {\n transformLiteralToPath(sexpr);\n let type = this.classifySexpr(sexpr);\n\n if (type === 'simple') {\n this.simpleSexpr(sexpr);\n } else if (type === 'helper') {\n this.helperSexpr(sexpr);\n } else {\n this.ambiguousSexpr(sexpr);\n }\n },\n ambiguousSexpr: function(sexpr, program, inverse) {\n let path = sexpr.path,\n name = path.parts[0],\n isBlock = program != null || inverse != null;\n\n this.opcode('getContext', path.depth);\n\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n\n path.strict = true;\n this.accept(path);\n\n this.opcode('invokeAmbiguous', name, isBlock);\n },\n\n simpleSexpr: function(sexpr) {\n let path = sexpr.path;\n path.strict = true;\n this.accept(path);\n this.opcode('resolvePossibleLambda');\n },\n\n helperSexpr: function(sexpr, program, inverse) {\n let params = this.setupFullMustacheParams(sexpr, program, inverse),\n path = sexpr.path,\n name = path.parts[0];\n\n if (this.options.knownHelpers[name]) {\n this.opcode('invokeKnownHelper', params.length, name);\n } else if (this.options.knownHelpersOnly) {\n throw new Exception(\n 'You specified knownHelpersOnly, but used the unknown helper ' + name,\n sexpr\n );\n } else {\n path.strict = true;\n path.falsy = true;\n\n this.accept(path);\n this.opcode(\n 'invokeHelper',\n params.length,\n path.original,\n AST.helpers.simpleId(path)\n );\n }\n },\n\n PathExpression: function(path) {\n this.addDepth(path.depth);\n this.opcode('getContext', path.depth);\n\n let name = path.parts[0],\n scoped = AST.helpers.scopedId(path),\n blockParamId = !path.depth && !scoped && this.blockParamIndex(name);\n\n if (blockParamId) {\n this.opcode('lookupBlockParam', blockParamId, path.parts);\n } else if (!name) {\n // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`\n this.opcode('pushContext');\n } else if (path.data) {\n this.options.data = true;\n this.opcode('lookupData', path.depth, path.parts, path.strict);\n } else {\n this.opcode(\n 'lookupOnContext',\n path.parts,\n path.falsy,\n path.strict,\n scoped\n );\n }\n },\n\n StringLiteral: function(string) {\n this.opcode('pushString', string.value);\n },\n\n NumberLiteral: function(number) {\n this.opcode('pushLiteral', number.value);\n },\n\n BooleanLiteral: function(bool) {\n this.opcode('pushLiteral', bool.value);\n },\n\n UndefinedLiteral: function() {\n this.opcode('pushLiteral', 'undefined');\n },\n\n NullLiteral: function() {\n this.opcode('pushLiteral', 'null');\n },\n\n Hash: function(hash) {\n let pairs = hash.pairs,\n i = 0,\n l = pairs.length;\n\n this.opcode('pushHash');\n\n for (; i < l; i++) {\n this.pushParam(pairs[i].value);\n }\n while (i--) {\n this.opcode('assignToHash', pairs[i].key);\n }\n this.opcode('popHash');\n },\n\n // HELPERS\n opcode: function(name) {\n this.opcodes.push({\n opcode: name,\n args: slice.call(arguments, 1),\n loc: this.sourceNode[0].loc\n });\n },\n\n addDepth: function(depth) {\n if (!depth) {\n return;\n }\n\n this.useDepths = true;\n },\n\n classifySexpr: function(sexpr) {\n let isSimple = AST.helpers.simpleId(sexpr.path);\n\n let isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);\n\n // a mustache is an eligible helper if:\n // * its id is simple (a single part, not `this` or `..`)\n let isHelper = !isBlockParam && AST.helpers.helperExpression(sexpr);\n\n // if a mustache is an eligible helper but not a definite\n // helper, it is ambiguous, and will be resolved in a later\n // pass or at runtime.\n let isEligible = !isBlockParam && (isHelper || isSimple);\n\n // if ambiguous, we can possibly resolve the ambiguity now\n // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.\n if (isEligible && !isHelper) {\n let name = sexpr.path.parts[0],\n options = this.options;\n if (options.knownHelpers[name]) {\n isHelper = true;\n } else if (options.knownHelpersOnly) {\n isEligible = false;\n }\n }\n\n if (isHelper) {\n return 'helper';\n } else if (isEligible) {\n return 'ambiguous';\n } else {\n return 'simple';\n }\n },\n\n pushParams: function(params) {\n for (let i = 0, l = params.length; i < l; i++) {\n this.pushParam(params[i]);\n }\n },\n\n pushParam: function(val) {\n let value = val.value != null ? val.value : val.original || '';\n\n if (this.stringParams) {\n if (value.replace) {\n value = value.replace(/^(\\.?\\.\\/)*/g, '').replace(/\\//g, '.');\n }\n\n if (val.depth) {\n this.addDepth(val.depth);\n }\n this.opcode('getContext', val.depth || 0);\n this.opcode('pushStringParam', value, val.type);\n\n if (val.type === 'SubExpression') {\n // SubExpressions get evaluated and passed in\n // in string params mode.\n this.accept(val);\n }\n } else {\n if (this.trackIds) {\n let blockParamIndex;\n if (val.parts && !AST.helpers.scopedId(val) && !val.depth) {\n blockParamIndex = this.blockParamIndex(val.parts[0]);\n }\n if (blockParamIndex) {\n let blockParamChild = val.parts.slice(1).join('.');\n this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);\n } else {\n value = val.original || value;\n if (value.replace) {\n value = value\n .replace(/^this(?:\\.|$)/, '')\n .replace(/^\\.\\//, '')\n .replace(/^\\.$/, '');\n }\n\n this.opcode('pushId', val.type, value);\n }\n }\n this.accept(val);\n }\n },\n\n setupFullMustacheParams: function(sexpr, program, inverse, omitEmpty) {\n let params = sexpr.params;\n this.pushParams(params);\n\n this.opcode('pushProgram', program);\n this.opcode('pushProgram', inverse);\n\n if (sexpr.hash) {\n this.accept(sexpr.hash);\n } else {\n this.opcode('emptyHash', omitEmpty);\n }\n\n return params;\n },\n\n blockParamIndex: function(name) {\n for (\n let depth = 0, len = this.options.blockParams.length;\n depth < len;\n depth++\n ) {\n let blockParams = this.options.blockParams[depth],\n param = blockParams && indexOf(blockParams, name);\n if (blockParams && param >= 0) {\n return [depth, param];\n }\n }\n }\n};\n\nexport function precompile(input, options, env) {\n if (\n input == null ||\n (typeof input !== 'string' && input.type !== 'Program')\n ) {\n throw new Exception(\n 'You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' +\n input\n );\n }\n\n options = options || {};\n if (!('data' in options)) {\n options.data = true;\n }\n if (options.compat) {\n options.useDepths = true;\n }\n\n let ast = env.parse(input, options),\n environment = new env.Compiler().compile(ast, options);\n return new env.JavaScriptCompiler().compile(environment, options);\n}\n\nexport function compile(input, options = {}, env) {\n if (\n input == null ||\n (typeof input !== 'string' && input.type !== 'Program')\n ) {\n throw new Exception(\n 'You must pass a string or Handlebars AST to Handlebars.compile. You passed ' +\n input\n );\n }\n\n options = extend({}, options);\n if (!('data' in options)) {\n options.data = true;\n }\n if (options.compat) {\n options.useDepths = true;\n }\n\n let compiled;\n\n function compileInput() {\n let ast = env.parse(input, options),\n environment = new env.Compiler().compile(ast, options),\n templateSpec = new env.JavaScriptCompiler().compile(\n environment,\n options,\n undefined,\n true\n );\n return env.template(templateSpec);\n }\n\n // Template is only compiled on first use and cached after that point.\n function ret(context, execOptions) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled.call(this, context, execOptions);\n }\n ret._setup = function(setupOptions) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled._setup(setupOptions);\n };\n ret._child = function(i, data, blockParams, depths) {\n if (!compiled) {\n compiled = compileInput();\n }\n return compiled._child(i, data, blockParams, depths);\n };\n return ret;\n}\n\nfunction argEquals(a, b) {\n if (a === b) {\n return true;\n }\n\n if (isArray(a) && isArray(b) && a.length === b.length) {\n for (let i = 0; i < a.length; i++) {\n if (!argEquals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n}\n\nfunction transformLiteralToPath(sexpr) {\n if (!sexpr.path.parts) {\n let literal = sexpr.path;\n // Casting to string here to make false and 0 literal values play nicely with the rest\n // of the system.\n sexpr.path = {\n type: 'PathExpression',\n data: false,\n depth: 0,\n parts: [literal.original + ''],\n original: literal.original + '',\n loc: literal.loc\n };\n }\n}\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '<dir>/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","/* global define, require */\nimport { isArray } from '../utils';\n\nlet SourceNode;\n\ntry {\n /* istanbul ignore next */\n if (typeof define !== 'function' || !define.amd) {\n // We don't support this in AMD environments. For these environments, we assume that\n // they are running on the browser and thus have no need for the source-map library.\n let SourceMap = require('source-map');\n SourceNode = SourceMap.SourceNode;\n }\n} catch (err) {\n /* NOP */\n}\n\n/* istanbul ignore if: tested but not covered in istanbul due to dist build */\nif (!SourceNode) {\n SourceNode = function(line, column, srcFile, chunks) {\n this.src = '';\n if (chunks) {\n this.add(chunks);\n }\n };\n /* istanbul ignore next */\n SourceNode.prototype = {\n add: function(chunks) {\n if (isArray(chunks)) {\n chunks = chunks.join('');\n }\n this.src += chunks;\n },\n prepend: function(chunks) {\n if (isArray(chunks)) {\n chunks = chunks.join('');\n }\n this.src = chunks + this.src;\n },\n toStringWithSourceMap: function() {\n return { code: this.toString() };\n },\n toString: function() {\n return this.src;\n }\n };\n}\n\nfunction castChunk(chunk, codeGen, loc) {\n if (isArray(chunk)) {\n let ret = [];\n\n for (let i = 0, len = chunk.length; i < len; i++) {\n ret.push(codeGen.wrap(chunk[i], loc));\n }\n return ret;\n } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {\n // Handle primitives that the SourceNode will throw up on\n return chunk + '';\n }\n return chunk;\n}\n\nfunction CodeGen(srcFile) {\n this.srcFile = srcFile;\n this.source = [];\n}\n\nCodeGen.prototype = {\n isEmpty() {\n return !this.source.length;\n },\n prepend: function(source, loc) {\n this.source.unshift(this.wrap(source, loc));\n },\n push: function(source, loc) {\n this.source.push(this.wrap(source, loc));\n },\n\n merge: function() {\n let source = this.empty();\n this.each(function(line) {\n source.add([' ', line, '\\n']);\n });\n return source;\n },\n\n each: function(iter) {\n for (let i = 0, len = this.source.length; i < len; i++) {\n iter(this.source[i]);\n }\n },\n\n empty: function() {\n let loc = this.currentLocation || { start: {} };\n return new SourceNode(loc.start.line, loc.start.column, this.srcFile);\n },\n wrap: function(chunk, loc = this.currentLocation || { start: {} }) {\n if (chunk instanceof SourceNode) {\n return chunk;\n }\n\n chunk = castChunk(chunk, this, loc);\n\n return new SourceNode(\n loc.start.line,\n loc.start.column,\n this.srcFile,\n chunk\n );\n },\n\n functionCall: function(fn, type, params) {\n params = this.generateList(params);\n return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);\n },\n\n quotedString: function(str) {\n return (\n '\"' +\n (str + '')\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\u2028/g, '\\\\u2028') // Per Ecma-262 7.3 + 7.8.4\n .replace(/\\u2029/g, '\\\\u2029') +\n '\"'\n );\n },\n\n objectLiteral: function(obj) {\n let pairs = [];\n\n Object.keys(obj).forEach(key => {\n let value = castChunk(obj[key], this);\n if (value !== 'undefined') {\n pairs.push([this.quotedString(key), ':', value]);\n }\n });\n\n let ret = this.generateList(pairs);\n ret.prepend('{');\n ret.add('}');\n return ret;\n },\n\n generateList: function(entries) {\n let ret = this.empty();\n\n for (let i = 0, len = entries.length; i < len; i++) {\n if (i) {\n ret.add(',');\n }\n\n ret.add(castChunk(entries[i], this));\n }\n\n return ret;\n },\n\n generateArray: function(entries) {\n let ret = this.generateList(entries);\n ret.prepend('[');\n ret.add(']');\n\n return ret;\n }\n};\n\nexport default CodeGen;\n","import { COMPILER_REVISION, REVISION_CHANGES } from '../base';\nimport Exception from '../exception';\nimport { isArray } from '../utils';\nimport CodeGen from './code-gen';\n\nfunction Literal(value) {\n this.value = value;\n}\n\nfunction JavaScriptCompiler() {}\n\nJavaScriptCompiler.prototype = {\n // PUBLIC API: You can override these methods in a subclass to provide\n // alternative compiled forms for name lookup and buffering semantics\n nameLookup: function(parent, name /*, type */) {\n return this.internalNameLookup(parent, name);\n },\n depthedLookup: function(name) {\n return [\n this.aliasable('container.lookup'),\n '(depths, ',\n JSON.stringify(name),\n ')'\n ];\n },\n\n compilerInfo: function() {\n const revision = COMPILER_REVISION,\n versions = REVISION_CHANGES[revision];\n return [revision, versions];\n },\n\n appendToBuffer: function(source, location, explicit) {\n // Force a source as this simplifies the merge logic.\n if (!isArray(source)) {\n source = [source];\n }\n source = this.source.wrap(source, location);\n\n if (this.environment.isSimple) {\n return ['return ', source, ';'];\n } else if (explicit) {\n // This is a case where the buffer operation occurs as a child of another\n // construct, generally braces. We have to explicitly output these buffer\n // operations to ensure that the emitted code goes in the correct location.\n return ['buffer += ', source, ';'];\n } else {\n source.appendToBuffer = true;\n return source;\n }\n },\n\n initializeBuffer: function() {\n return this.quotedString('');\n },\n // END PUBLIC API\n internalNameLookup: function(parent, name) {\n this.lookupPropertyFunctionIsUsed = true;\n return ['lookupProperty(', parent, ',', JSON.stringify(name), ')'];\n },\n\n lookupPropertyFunctionIsUsed: false,\n\n compile: function(environment, options, context, asObject) {\n this.environment = environment;\n this.options = options;\n this.stringParams = this.options.stringParams;\n this.trackIds = this.options.trackIds;\n this.precompile = !asObject;\n\n this.name = this.environment.name;\n this.isChild = !!context;\n this.context = context || {\n decorators: [],\n programs: [],\n environments: []\n };\n\n this.preamble();\n\n this.stackSlot = 0;\n this.stackVars = [];\n this.aliases = {};\n this.registers = { list: [] };\n this.hashes = [];\n this.compileStack = [];\n this.inlineStack = [];\n this.blockParams = [];\n\n this.compileChildren(environment, options);\n\n this.useDepths =\n this.useDepths ||\n environment.useDepths ||\n environment.useDecorators ||\n this.options.compat;\n this.useBlockParams = this.useBlockParams || environment.useBlockParams;\n\n let opcodes = environment.opcodes,\n opcode,\n firstLoc,\n i,\n l;\n\n for (i = 0, l = opcodes.length; i < l; i++) {\n opcode = opcodes[i];\n\n this.source.currentLocation = opcode.loc;\n firstLoc = firstLoc || opcode.loc;\n this[opcode.opcode].apply(this, opcode.args);\n }\n\n // Flush any trailing content that might be pending.\n this.source.currentLocation = firstLoc;\n this.pushSource('');\n\n /* istanbul ignore next */\n if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {\n throw new Exception('Compile completed with content left on stack');\n }\n\n if (!this.decorators.isEmpty()) {\n this.useDecorators = true;\n\n this.decorators.prepend([\n 'var decorators = container.decorators, ',\n this.lookupPropertyFunctionVarDeclaration(),\n ';\\n'\n ]);\n this.decorators.push('return fn;');\n\n if (asObject) {\n this.decorators = Function.apply(this, [\n 'fn',\n 'props',\n 'container',\n 'depth0',\n 'data',\n 'blockParams',\n 'depths',\n this.decorators.merge()\n ]);\n } else {\n this.decorators.prepend(\n 'function(fn, props, container, depth0, data, blockParams, depths) {\\n'\n );\n this.decorators.push('}\\n');\n this.decorators = this.decorators.merge();\n }\n } else {\n this.decorators = undefined;\n }\n\n let fn = this.createFunctionContext(asObject);\n if (!this.isChild) {\n let ret = {\n compiler: this.compilerInfo(),\n main: fn\n };\n\n if (this.decorators) {\n ret.main_d = this.decorators; // eslint-disable-line camelcase\n ret.useDecorators = true;\n }\n\n let { programs, decorators } = this.context;\n for (i = 0, l = programs.length; i < l; i++) {\n ret[i] = programs[i];\n if (decorators[i]) {\n ret[i + '_d'] = decorators[i];\n ret.useDecorators = true;\n }\n }\n\n if (this.environment.usePartial) {\n ret.usePartial = true;\n }\n if (this.options.data) {\n ret.useData = true;\n }\n if (this.useDepths) {\n ret.useDepths = true;\n }\n if (this.useBlockParams) {\n ret.useBlockParams = true;\n }\n if (this.options.compat) {\n ret.compat = true;\n }\n\n if (!asObject) {\n ret.compiler = JSON.stringify(ret.compiler);\n\n this.source.currentLocation = { start: { line: 1, column: 0 } };\n ret = this.objectLiteral(ret);\n\n if (options.srcName) {\n ret = ret.toStringWithSourceMap({ file: options.destName });\n ret.map = ret.map && ret.map.toString();\n } else {\n ret = ret.toString();\n }\n } else {\n ret.compilerOptions = this.options;\n }\n\n return ret;\n } else {\n return fn;\n }\n },\n\n preamble: function() {\n // track the last context pushed into place to allow skipping the\n // getContext opcode when it would be a noop\n this.lastContext = 0;\n this.source = new CodeGen(this.options.srcName);\n this.decorators = new CodeGen(this.options.srcName);\n },\n\n createFunctionContext: function(asObject) {\n let varDeclarations = '';\n\n let locals = this.stackVars.concat(this.registers.list);\n if (locals.length > 0) {\n varDeclarations += ', ' + locals.join(', ');\n }\n\n // Generate minimizer alias mappings\n //\n // When using true SourceNodes, this will update all references to the given alias\n // as the source nodes are reused in situ. For the non-source node compilation mode,\n // aliases will not be used, but this case is already being run on the client and\n // we aren't concern about minimizing the template size.\n let aliasCount = 0;\n Object.keys(this.aliases).forEach(alias => {\n let node = this.aliases[alias];\n if (node.children && node.referenceCount > 1) {\n varDeclarations += ', alias' + ++aliasCount + '=' + alias;\n node.children[0] = 'alias' + aliasCount;\n }\n });\n\n if (this.lookupPropertyFunctionIsUsed) {\n varDeclarations += ', ' + this.lookupPropertyFunctionVarDeclaration();\n }\n\n let params = ['container', 'depth0', 'helpers', 'partials', 'data'];\n\n if (this.useBlockParams || this.useDepths) {\n params.push('blockParams');\n }\n if (this.useDepths) {\n params.push('depths');\n }\n\n // Perform a second pass over the output to merge content when possible\n let source = this.mergeSource(varDeclarations);\n\n if (asObject) {\n params.push(source);\n\n return Function.apply(this, params);\n } else {\n return this.source.wrap([\n 'function(',\n params.join(','),\n ') {\\n ',\n source,\n '}'\n ]);\n }\n },\n mergeSource: function(varDeclarations) {\n let isSimple = this.environment.isSimple,\n appendOnly = !this.forceBuffer,\n appendFirst,\n sourceSeen,\n bufferStart,\n bufferEnd;\n this.source.each(line => {\n if (line.appendToBuffer) {\n if (bufferStart) {\n line.prepend(' + ');\n } else {\n bufferStart = line;\n }\n bufferEnd = line;\n } else {\n if (bufferStart) {\n if (!sourceSeen) {\n appendFirst = true;\n } else {\n bufferStart.prepend('buffer += ');\n }\n bufferEnd.add(';');\n bufferStart = bufferEnd = undefined;\n }\n\n sourceSeen = true;\n if (!isSimple) {\n appendOnly = false;\n }\n }\n });\n\n if (appendOnly) {\n if (bufferStart) {\n bufferStart.prepend('return ');\n bufferEnd.add(';');\n } else if (!sourceSeen) {\n this.source.push('return \"\";');\n }\n } else {\n varDeclarations +=\n ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());\n\n if (bufferStart) {\n bufferStart.prepend('return buffer + ');\n bufferEnd.add(';');\n } else {\n this.source.push('return buffer;');\n }\n }\n\n if (varDeclarations) {\n this.source.prepend(\n 'var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\\n')\n );\n }\n\n return this.source.merge();\n },\n\n lookupPropertyFunctionVarDeclaration: function() {\n return `\n lookupProperty = container.lookupProperty || function(parent, propertyName) {\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return parent[propertyName];\n }\n return undefined\n }\n `.trim();\n },\n\n // [blockValue]\n //\n // On stack, before: hash, inverse, program, value\n // On stack, after: return value of blockHelperMissing\n //\n // The purpose of this opcode is to take a block of the form\n // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and\n // replace it on the stack with the result of properly\n // invoking blockHelperMissing.\n blockValue: function(name) {\n let blockHelperMissing = this.aliasable(\n 'container.hooks.blockHelperMissing'\n ),\n params = [this.contextName(0)];\n this.setupHelperArgs(name, 0, params);\n\n let blockName = this.popStack();\n params.splice(1, 0, blockName);\n\n this.push(this.source.functionCall(blockHelperMissing, 'call', params));\n },\n\n // [ambiguousBlockValue]\n //\n // On stack, before: hash, inverse, program, value\n // Compiler value, before: lastHelper=value of last found helper, if any\n // On stack, after, if no lastHelper: same as [blockValue]\n // On stack, after, if lastHelper: value\n ambiguousBlockValue: function() {\n // We're being a bit cheeky and reusing the options value from the prior exec\n let blockHelperMissing = this.aliasable(\n 'container.hooks.blockHelperMissing'\n ),\n params = [this.contextName(0)];\n this.setupHelperArgs('', 0, params, true);\n\n this.flushInline();\n\n let current = this.topStack();\n params.splice(1, 0, current);\n\n this.pushSource([\n 'if (!',\n this.lastHelper,\n ') { ',\n current,\n ' = ',\n this.source.functionCall(blockHelperMissing, 'call', params),\n '}'\n ]);\n },\n\n // [appendContent]\n //\n // On stack, before: ...\n // On stack, after: ...\n //\n // Appends the string value of `content` to the current buffer\n appendContent: function(content) {\n if (this.pendingContent) {\n content = this.pendingContent + content;\n } else {\n this.pendingLocation = this.source.currentLocation;\n }\n\n this.pendingContent = content;\n },\n\n // [append]\n //\n // On stack, before: value, ...\n // On stack, after: ...\n //\n // Coerces `value` to a String and appends it to the current buffer.\n //\n // If `value` is truthy, or 0, it is coerced into a string and appended\n // Otherwise, the empty string is appended\n append: function() {\n if (this.isInline()) {\n this.replaceStack(current => [' != null ? ', current, ' : \"\"']);\n\n this.pushSource(this.appendToBuffer(this.popStack()));\n } else {\n let local = this.popStack();\n this.pushSource([\n 'if (',\n local,\n ' != null) { ',\n this.appendToBuffer(local, undefined, true),\n ' }'\n ]);\n if (this.environment.isSimple) {\n this.pushSource([\n 'else { ',\n this.appendToBuffer(\"''\", undefined, true),\n ' }'\n ]);\n }\n }\n },\n\n // [appendEscaped]\n //\n // On stack, before: value, ...\n // On stack, after: ...\n //\n // Escape `value` and append it to the buffer\n appendEscaped: function() {\n this.pushSource(\n this.appendToBuffer([\n this.aliasable('container.escapeExpression'),\n '(',\n this.popStack(),\n ')'\n ])\n );\n },\n\n // [getContext]\n //\n // On stack, before: ...\n // On stack, after: ...\n // Compiler value, after: lastContext=depth\n //\n // Set the value of the `lastContext` compiler value to the depth\n getContext: function(depth) {\n this.lastContext = depth;\n },\n\n // [pushContext]\n //\n // On stack, before: ...\n // On stack, after: currentContext, ...\n //\n // Pushes the value of the current context onto the stack.\n pushContext: function() {\n this.pushStackLiteral(this.contextName(this.lastContext));\n },\n\n // [lookupOnContext]\n //\n // On stack, before: ...\n // On stack, after: currentContext[name], ...\n //\n // Looks up the value of `name` on the current context and pushes\n // it onto the stack.\n lookupOnContext: function(parts, falsy, strict, scoped) {\n let i = 0;\n\n if (!scoped && this.options.compat && !this.lastContext) {\n // The depthed query is expected to handle the undefined logic for the root level that\n // is implemented below, so we evaluate that directly in compat mode\n this.push(this.depthedLookup(parts[i++]));\n } else {\n this.pushContext();\n }\n\n this.resolvePath('context', parts, i, falsy, strict);\n },\n\n // [lookupBlockParam]\n //\n // On stack, before: ...\n // On stack, after: blockParam[name], ...\n //\n // Looks up the value of `parts` on the given block param and pushes\n // it onto the stack.\n lookupBlockParam: function(blockParamId, parts) {\n this.useBlockParams = true;\n\n this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);\n this.resolvePath('context', parts, 1);\n },\n\n // [lookupData]\n //\n // On stack, before: ...\n // On stack, after: data, ...\n //\n // Push the data lookup operator\n lookupData: function(depth, parts, strict) {\n if (!depth) {\n this.pushStackLiteral('data');\n } else {\n this.pushStackLiteral('container.data(data, ' + depth + ')');\n }\n\n this.resolvePath('data', parts, 0, true, strict);\n },\n\n resolvePath: function(type, parts, startPartIndex, falsy, strict) {\n if (this.options.strict || this.options.assumeObjects) {\n this.push(\n strictLookup(\n this.options.strict && strict,\n this,\n parts,\n startPartIndex,\n type\n )\n );\n return;\n }\n\n let len = parts.length;\n for (let i = startPartIndex; i < len; i++) {\n /* eslint-disable no-loop-func */\n this.replaceStack(current => {\n let lookup = this.nameLookup(current, parts[i], type);\n // We want to ensure that zero and false are handled properly if the context (falsy flag)\n // needs to have the special handling for these values.\n if (!falsy) {\n return [' != null ? ', lookup, ' : ', current];\n } else {\n // Otherwise we can use generic falsy handling\n return [' && ', lookup];\n }\n });\n /* eslint-enable no-loop-func */\n }\n },\n\n // [resolvePossibleLambda]\n //\n // On stack, before: value, ...\n // On stack, after: resolved value, ...\n //\n // If the `value` is a lambda, replace it on the stack by\n // the return value of the lambda\n resolvePossibleLambda: function() {\n this.push([\n this.aliasable('container.lambda'),\n '(',\n this.popStack(),\n ', ',\n this.contextName(0),\n ')'\n ]);\n },\n\n // [pushStringParam]\n //\n // On stack, before: ...\n // On stack, after: string, currentContext, ...\n //\n // This opcode is designed for use in string mode, which\n // provides the string value of a parameter along with its\n // depth rather than resolving it immediately.\n pushStringParam: function(string, type) {\n this.pushContext();\n this.pushString(type);\n\n // If it's a subexpression, the string result\n // will be pushed after this opcode.\n if (type !== 'SubExpression') {\n if (typeof string === 'string') {\n this.pushString(string);\n } else {\n this.pushStackLiteral(string);\n }\n }\n },\n\n emptyHash: function(omitEmpty) {\n if (this.trackIds) {\n this.push('{}'); // hashIds\n }\n if (this.stringParams) {\n this.push('{}'); // hashContexts\n this.push('{}'); // hashTypes\n }\n this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');\n },\n pushHash: function() {\n if (this.hash) {\n this.hashes.push(this.hash);\n }\n this.hash = { values: {}, types: [], contexts: [], ids: [] };\n },\n popHash: function() {\n let hash = this.hash;\n this.hash = this.hashes.pop();\n\n if (this.trackIds) {\n this.push(this.objectLiteral(hash.ids));\n }\n if (this.stringParams) {\n this.push(this.objectLiteral(hash.contexts));\n this.push(this.objectLiteral(hash.types));\n }\n\n this.push(this.objectLiteral(hash.values));\n },\n\n // [pushString]\n //\n // On stack, before: ...\n // On stack, after: quotedString(string), ...\n //\n // Push a quoted version of `string` onto the stack\n pushString: function(string) {\n this.pushStackLiteral(this.quotedString(string));\n },\n\n // [pushLiteral]\n //\n // On stack, before: ...\n // On stack, after: value, ...\n //\n // Pushes a value onto the stack. This operation prevents\n // the compiler from creating a temporary variable to hold\n // it.\n pushLiteral: function(value) {\n this.pushStackLiteral(value);\n },\n\n // [pushProgram]\n //\n // On stack, before: ...\n // On stack, after: program(guid), ...\n //\n // Push a program expression onto the stack. This takes\n // a compile-time guid and converts it into a runtime-accessible\n // expression.\n pushProgram: function(guid) {\n if (guid != null) {\n this.pushStackLiteral(this.programExpression(guid));\n } else {\n this.pushStackLiteral(null);\n }\n },\n\n // [registerDecorator]\n //\n // On stack, before: hash, program, params..., ...\n // On stack, after: ...\n //\n // Pops off the decorator's parameters, invokes the decorator,\n // and inserts the decorator into the decorators list.\n registerDecorator(paramSize, name) {\n let foundDecorator = this.nameLookup('decorators', name, 'decorator'),\n options = this.setupHelperArgs(name, paramSize);\n\n // Store the resolved decorator in a variable and verify it is a function before\n // calling it. Without this, unregistered decorators can cause an unhandled TypeError\n // (calling undefined), which crashes the process — enabling Denial of Service.\n this.decorators.push(['var decorator = ', foundDecorator, ';']);\n this.decorators.push([\n 'if (typeof decorator !== \"function\") { throw new Error(',\n this.quotedString('Missing decorator: \"' + name + '\"'),\n '); }'\n ]);\n this.decorators.push([\n 'fn = ',\n this.decorators.functionCall('decorator', '', [\n 'fn',\n 'props',\n 'container',\n options\n ]),\n ' || fn;'\n ]);\n },\n\n // [invokeHelper]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of helper invocation\n //\n // Pops off the helper's parameters, invokes the helper,\n // and pushes the helper's return value onto the stack.\n //\n // If the helper is not found, `helperMissing` is called.\n invokeHelper: function(paramSize, name, isSimple) {\n let nonHelper = this.popStack(),\n helper = this.setupHelper(paramSize, name);\n\n let possibleFunctionCalls = [];\n\n if (isSimple) {\n // direct call to helper\n possibleFunctionCalls.push(helper.name);\n }\n // call a function from the input object\n possibleFunctionCalls.push(nonHelper);\n if (!this.options.strict) {\n possibleFunctionCalls.push(\n this.aliasable('container.hooks.helperMissing')\n );\n }\n\n let functionLookupCode = [\n '(',\n this.itemsSeparatedBy(possibleFunctionCalls, '||'),\n ')'\n ];\n let functionCall = this.source.functionCall(\n functionLookupCode,\n 'call',\n helper.callParams\n );\n this.push(functionCall);\n },\n\n itemsSeparatedBy: function(items, separator) {\n let result = [];\n result.push(items[0]);\n for (let i = 1; i < items.length; i++) {\n result.push(separator, items[i]);\n }\n return result;\n },\n // [invokeKnownHelper]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of helper invocation\n //\n // This operation is used when the helper is known to exist,\n // so a `helperMissing` fallback is not required.\n invokeKnownHelper: function(paramSize, name) {\n let helper = this.setupHelper(paramSize, name);\n this.push(this.source.functionCall(helper.name, 'call', helper.callParams));\n },\n\n // [invokeAmbiguous]\n //\n // On stack, before: hash, inverse, program, params..., ...\n // On stack, after: result of disambiguation\n //\n // This operation is used when an expression like `{{foo}}`\n // is provided, but we don't know at compile-time whether it\n // is a helper or a path.\n //\n // This operation emits more code than the other options,\n // and can be avoided by passing the `knownHelpers` and\n // `knownHelpersOnly` flags at compile-time.\n invokeAmbiguous: function(name, helperCall) {\n this.useRegister('helper');\n\n let nonHelper = this.popStack();\n\n this.emptyHash();\n let helper = this.setupHelper(0, name, helperCall);\n\n let helperName = (this.lastHelper = this.nameLookup(\n 'helpers',\n name,\n 'helper'\n ));\n\n let lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];\n if (!this.options.strict) {\n lookup[0] = '(helper = ';\n lookup.push(\n ' != null ? helper : ',\n this.aliasable('container.hooks.helperMissing')\n );\n }\n\n this.push([\n '(',\n lookup,\n helper.paramsInit ? ['),(', helper.paramsInit] : [],\n '),',\n '(typeof helper === ',\n this.aliasable('\"function\"'),\n ' ? ',\n this.source.functionCall('helper', 'call', helper.callParams),\n ' : helper))'\n ]);\n },\n\n // [invokePartial]\n //\n // On stack, before: context, ...\n // On stack after: result of partial invocation\n //\n // This operation pops off a context, invokes a partial with that context,\n // and pushes the result of the invocation back.\n invokePartial: function(isDynamic, name, indent) {\n let params = [],\n options = this.setupParams(name, 1, params);\n\n if (isDynamic) {\n name = this.popStack();\n delete options.name;\n }\n\n if (indent) {\n options.indent = JSON.stringify(indent);\n }\n options.helpers = 'helpers';\n options.partials = 'partials';\n options.decorators = 'container.decorators';\n\n if (!isDynamic) {\n params.unshift(this.nameLookup('partials', name, 'partial'));\n } else {\n params.unshift(name);\n }\n\n if (this.options.compat) {\n options.depths = 'depths';\n }\n options = this.objectLiteral(options);\n params.push(options);\n\n this.push(this.source.functionCall('container.invokePartial', '', params));\n },\n\n // [assignToHash]\n //\n // On stack, before: value, ..., hash, ...\n // On stack, after: ..., hash, ...\n //\n // Pops a value off the stack and assigns it to the current hash\n assignToHash: function(key) {\n let value = this.popStack(),\n context,\n type,\n id;\n\n if (this.trackIds) {\n id = this.popStack();\n }\n if (this.stringParams) {\n type = this.popStack();\n context = this.popStack();\n }\n\n let hash = this.hash;\n if (context) {\n hash.contexts[key] = context;\n }\n if (type) {\n hash.types[key] = type;\n }\n if (id) {\n hash.ids[key] = id;\n }\n hash.values[key] = value;\n },\n\n pushId: function(type, name, child) {\n if (type === 'BlockParam') {\n this.pushStackLiteral(\n 'blockParams[' +\n name[0] +\n '].path[' +\n name[1] +\n ']' +\n (child ? ' + ' + JSON.stringify('.' + child) : '')\n );\n } else if (type === 'PathExpression') {\n this.pushString(name);\n } else if (type === 'SubExpression') {\n this.pushStackLiteral('true');\n } else {\n this.pushStackLiteral('null');\n }\n },\n\n // HELPERS\n\n compiler: JavaScriptCompiler,\n\n compileChildren: function(environment, options) {\n let children = environment.children,\n child,\n compiler;\n\n for (let i = 0, l = children.length; i < l; i++) {\n child = children[i];\n compiler = new this.compiler(); // eslint-disable-line new-cap\n\n let existing = this.matchExistingProgram(child);\n\n if (existing == null) {\n // Placeholder to prevent name conflicts for nested children\n let index = this.context.programs.push('') - 1;\n child.index = index;\n child.name = 'program' + index;\n this.context.programs[index] = compiler.compile(\n child,\n options,\n this.context,\n !this.precompile\n );\n this.context.decorators[index] = compiler.decorators;\n this.context.environments[index] = child;\n\n this.useDepths = this.useDepths || compiler.useDepths;\n this.useBlockParams = this.useBlockParams || compiler.useBlockParams;\n child.useDepths = this.useDepths;\n child.useBlockParams = this.useBlockParams;\n } else {\n child.index = existing.index;\n child.name = 'program' + existing.index;\n\n this.useDepths = this.useDepths || existing.useDepths;\n this.useBlockParams = this.useBlockParams || existing.useBlockParams;\n }\n }\n },\n matchExistingProgram: function(child) {\n for (let i = 0, len = this.context.environments.length; i < len; i++) {\n let environment = this.context.environments[i];\n if (environment && environment.equals(child)) {\n return environment;\n }\n }\n },\n\n programExpression: function(guid) {\n let child = this.environment.children[guid],\n programParams = [child.index, 'data', child.blockParams];\n\n if (this.useBlockParams || this.useDepths) {\n programParams.push('blockParams');\n }\n if (this.useDepths) {\n programParams.push('depths');\n }\n\n return 'container.program(' + programParams.join(', ') + ')';\n },\n\n useRegister: function(name) {\n if (!this.registers[name]) {\n this.registers[name] = true;\n this.registers.list.push(name);\n }\n },\n\n push: function(expr) {\n if (!(expr instanceof Literal)) {\n expr = this.source.wrap(expr);\n }\n\n this.inlineStack.push(expr);\n return expr;\n },\n\n pushStackLiteral: function(item) {\n this.push(new Literal(item));\n },\n\n pushSource: function(source) {\n if (this.pendingContent) {\n this.source.push(\n this.appendToBuffer(\n this.source.quotedString(this.pendingContent),\n this.pendingLocation\n )\n );\n this.pendingContent = undefined;\n }\n\n if (source) {\n this.source.push(source);\n }\n },\n\n replaceStack: function(callback) {\n let prefix = ['('],\n stack,\n createdStack,\n usedLiteral;\n\n /* istanbul ignore next */\n if (!this.isInline()) {\n throw new Exception('replaceStack on non-inline');\n }\n\n // We want to merge the inline statement into the replacement statement via ','\n let top = this.popStack(true);\n\n if (top instanceof Literal) {\n // Literals do not need to be inlined\n stack = [top.value];\n prefix = ['(', stack];\n usedLiteral = true;\n } else {\n // Get or create the current stack name for use by the inline\n createdStack = true;\n let name = this.incrStack();\n\n prefix = ['((', this.push(name), ' = ', top, ')'];\n stack = this.topStack();\n }\n\n let item = callback.call(this, stack);\n\n if (!usedLiteral) {\n this.popStack();\n }\n if (createdStack) {\n this.stackSlot--;\n }\n this.push(prefix.concat(item, ')'));\n },\n\n incrStack: function() {\n this.stackSlot++;\n if (this.stackSlot > this.stackVars.length) {\n this.stackVars.push('stack' + this.stackSlot);\n }\n return this.topStackName();\n },\n topStackName: function() {\n return 'stack' + this.stackSlot;\n },\n flushInline: function() {\n let inlineStack = this.inlineStack;\n this.inlineStack = [];\n for (let i = 0, len = inlineStack.length; i < len; i++) {\n let entry = inlineStack[i];\n /* istanbul ignore if */\n if (entry instanceof Literal) {\n this.compileStack.push(entry);\n } else {\n let stack = this.incrStack();\n this.pushSource([stack, ' = ', entry, ';']);\n this.compileStack.push(stack);\n }\n }\n },\n isInline: function() {\n return this.inlineStack.length;\n },\n\n popStack: function(wrapped) {\n let inline = this.isInline(),\n item = (inline ? this.inlineStack : this.compileStack).pop();\n\n if (!wrapped && item instanceof Literal) {\n return item.value;\n } else {\n if (!inline) {\n /* istanbul ignore next */\n if (!this.stackSlot) {\n throw new Exception('Invalid stack pop');\n }\n this.stackSlot--;\n }\n return item;\n }\n },\n\n topStack: function() {\n let stack = this.isInline() ? this.inlineStack : this.compileStack,\n item = stack[stack.length - 1];\n\n /* istanbul ignore if */\n if (item instanceof Literal) {\n return item.value;\n } else {\n return item;\n }\n },\n\n contextName: function(context) {\n if (this.useDepths && context) {\n return 'depths[' + context + ']';\n } else {\n return 'depth' + context;\n }\n },\n\n quotedString: function(str) {\n return this.source.quotedString(str);\n },\n\n objectLiteral: function(obj) {\n return this.source.objectLiteral(obj);\n },\n\n aliasable: function(name) {\n let ret = this.aliases[name];\n if (ret) {\n ret.referenceCount++;\n return ret;\n }\n\n ret = this.aliases[name] = this.source.wrap(name);\n ret.aliasable = true;\n ret.referenceCount = 1;\n\n return ret;\n },\n\n setupHelper: function(paramSize, name, blockHelper) {\n let params = [],\n paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);\n let foundHelper = this.nameLookup('helpers', name, 'helper'),\n callContext = this.aliasable(\n `${this.contextName(0)} != null ? ${this.contextName(\n 0\n )} : (container.nullContext || {})`\n );\n\n return {\n params: params,\n paramsInit: paramsInit,\n name: foundHelper,\n callParams: [callContext].concat(params)\n };\n },\n\n setupParams: function(helper, paramSize, params) {\n let options = {},\n contexts = [],\n types = [],\n ids = [],\n objectArgs = !params,\n param;\n\n if (objectArgs) {\n params = [];\n }\n\n options.name = this.quotedString(helper);\n options.hash = this.popStack();\n\n if (this.trackIds) {\n options.hashIds = this.popStack();\n }\n if (this.stringParams) {\n options.hashTypes = this.popStack();\n options.hashContexts = this.popStack();\n }\n\n let inverse = this.popStack(),\n program = this.popStack();\n\n // Avoid setting fn and inverse if neither are set. This allows\n // helpers to do a check for `if (options.fn)`\n if (program || inverse) {\n options.fn = program || 'container.noop';\n options.inverse = inverse || 'container.noop';\n }\n\n // The parameters go on to the stack in order (making sure that they are evaluated in order)\n // so we need to pop them off the stack in reverse order\n let i = paramSize;\n while (i--) {\n param = this.popStack();\n params[i] = param;\n\n if (this.trackIds) {\n ids[i] = this.popStack();\n }\n if (this.stringParams) {\n types[i] = this.popStack();\n contexts[i] = this.popStack();\n }\n }\n\n if (objectArgs) {\n options.args = this.source.generateArray(params);\n }\n\n if (this.trackIds) {\n options.ids = this.source.generateArray(ids);\n }\n if (this.stringParams) {\n options.types = this.source.generateArray(types);\n options.contexts = this.source.generateArray(contexts);\n }\n\n if (this.options.data) {\n options.data = 'data';\n }\n if (this.useBlockParams) {\n options.blockParams = 'blockParams';\n }\n return options;\n },\n\n setupHelperArgs: function(helper, paramSize, params, useRegister) {\n let options = this.setupParams(helper, paramSize, params);\n options.loc = JSON.stringify(this.source.currentLocation);\n options = this.objectLiteral(options);\n if (useRegister) {\n this.useRegister('options');\n params.push('options');\n return ['options=', options];\n } else if (params) {\n params.push(options);\n return '';\n } else {\n return options;\n }\n }\n};\n\n(function() {\n const reservedWords = (\n 'break else new var' +\n ' case finally return void' +\n ' catch for switch while' +\n ' continue function this with' +\n ' default if throw' +\n ' delete in try' +\n ' do instanceof typeof' +\n ' abstract enum int short' +\n ' boolean export interface static' +\n ' byte extends long super' +\n ' char final native synchronized' +\n ' class float package throws' +\n ' const goto private transient' +\n ' debugger implements protected volatile' +\n ' double import public let yield await' +\n ' null true false'\n ).split(' ');\n\n const compilerWords = (JavaScriptCompiler.RESERVED_WORDS = {});\n\n for (let i = 0, l = reservedWords.length; i < l; i++) {\n compilerWords[reservedWords[i]] = true;\n }\n})();\n\n/**\n * @deprecated May be removed in the next major version\n */\nJavaScriptCompiler.isValidJavaScriptVariableName = function(name) {\n return (\n !JavaScriptCompiler.RESERVED_WORDS[name] &&\n /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name)\n );\n};\n\nfunction strictLookup(requireTerminal, compiler, parts, startPartIndex, type) {\n let stack = compiler.popStack(),\n len = parts.length;\n if (requireTerminal) {\n len--;\n }\n\n for (let i = startPartIndex; i < len; i++) {\n stack = compiler.nameLookup(stack, parts[i], type);\n }\n\n if (requireTerminal) {\n return [\n compiler.aliasable('container.strict'),\n '(',\n stack,\n ', ',\n compiler.quotedString(parts[len]),\n ', ',\n JSON.stringify(compiler.source.currentLocation),\n ' )'\n ];\n } else {\n return stack;\n }\n}\n\nexport default JavaScriptCompiler;\n","import runtime from './handlebars.runtime';\n\n// Compiler imports\nimport AST from './handlebars/compiler/ast';\nimport {\n parser as Parser,\n parse,\n parseWithoutProcessing\n} from './handlebars/compiler/base';\nimport { Compiler, compile, precompile } from './handlebars/compiler/compiler';\nimport JavaScriptCompiler from './handlebars/compiler/javascript-compiler';\nimport Visitor from './handlebars/compiler/visitor';\n\nimport noConflict from './handlebars/no-conflict';\n\nlet _create = runtime.create;\nfunction create() {\n let hb = _create();\n\n hb.compile = function(input, options) {\n return compile(input, options, hb);\n };\n hb.precompile = function(input, options) {\n return precompile(input, options, hb);\n };\n\n hb.AST = AST;\n hb.Compiler = Compiler;\n hb.JavaScriptCompiler = JavaScriptCompiler;\n hb.Parser = Parser;\n hb.parse = parse;\n hb.parseWithoutProcessing = parseWithoutProcessing;\n\n return hb;\n}\n\nlet inst = create();\ninst.create = create;\n\nnoConflict(inst);\n\ninst.Visitor = Visitor;\n\ninst['default'] = inst;\n\nexport default inst;\n","/* eslint-disable new-cap */\nimport Visitor from './visitor';\n\nexport function print(ast) {\n return new PrintVisitor().accept(ast);\n}\n\nexport function PrintVisitor() {\n this.padding = 0;\n}\n\nPrintVisitor.prototype = new Visitor();\n\nPrintVisitor.prototype.pad = function(string) {\n let out = '';\n\n for (let i = 0, l = this.padding; i < l; i++) {\n out += ' ';\n }\n\n out += string + '\\n';\n return out;\n};\n\nPrintVisitor.prototype.Program = function(program) {\n let out = '',\n body = program.body,\n i,\n l;\n\n if (program.blockParams) {\n let blockParams = 'BLOCK PARAMS: [';\n for (i = 0, l = program.blockParams.length; i < l; i++) {\n blockParams += ' ' + program.blockParams[i];\n }\n blockParams += ' ]';\n out += this.pad(blockParams);\n }\n\n for (i = 0, l = body.length; i < l; i++) {\n out += this.accept(body[i]);\n }\n\n this.padding--;\n\n return out;\n};\n\nPrintVisitor.prototype.MustacheStatement = function(mustache) {\n return this.pad('{{ ' + this.SubExpression(mustache) + ' }}');\n};\nPrintVisitor.prototype.Decorator = function(mustache) {\n return this.pad('{{ DIRECTIVE ' + this.SubExpression(mustache) + ' }}');\n};\n\nPrintVisitor.prototype.BlockStatement = PrintVisitor.prototype.DecoratorBlock = function(\n block\n) {\n let out = '';\n\n out += this.pad(\n (block.type === 'DecoratorBlock' ? 'DIRECTIVE ' : '') + 'BLOCK:'\n );\n this.padding++;\n out += this.pad(this.SubExpression(block));\n if (block.program) {\n out += this.pad('PROGRAM:');\n this.padding++;\n out += this.accept(block.program);\n this.padding--;\n }\n if (block.inverse) {\n if (block.program) {\n this.padding++;\n }\n out += this.pad('{{^}}');\n this.padding++;\n out += this.accept(block.inverse);\n this.padding--;\n if (block.program) {\n this.padding--;\n }\n }\n this.padding--;\n\n return out;\n};\n\nPrintVisitor.prototype.PartialStatement = function(partial) {\n let content = 'PARTIAL:' + partial.name.original;\n if (partial.params[0]) {\n content += ' ' + this.accept(partial.params[0]);\n }\n if (partial.hash) {\n content += ' ' + this.accept(partial.hash);\n }\n return this.pad('{{> ' + content + ' }}');\n};\nPrintVisitor.prototype.PartialBlockStatement = function(partial) {\n let content = 'PARTIAL BLOCK:' + partial.name.original;\n if (partial.params[0]) {\n content += ' ' + this.accept(partial.params[0]);\n }\n if (partial.hash) {\n content += ' ' + this.accept(partial.hash);\n }\n\n content += ' ' + this.pad('PROGRAM:');\n this.padding++;\n content += this.accept(partial.program);\n this.padding--;\n\n return this.pad('{{> ' + content + ' }}');\n};\n\nPrintVisitor.prototype.ContentStatement = function(content) {\n return this.pad(\"CONTENT[ '\" + content.value + \"' ]\");\n};\n\nPrintVisitor.prototype.CommentStatement = function(comment) {\n return this.pad(\"{{! '\" + comment.value + \"' }}\");\n};\n\nPrintVisitor.prototype.SubExpression = function(sexpr) {\n let params = sexpr.params,\n paramStrings = [],\n hash;\n\n for (let i = 0, l = params.length; i < l; i++) {\n paramStrings.push(this.accept(params[i]));\n }\n\n params = '[' + paramStrings.join(', ') + ']';\n\n hash = sexpr.hash ? ' ' + this.accept(sexpr.hash) : '';\n\n return this.accept(sexpr.path) + ' ' + params + hash;\n};\n\nPrintVisitor.prototype.PathExpression = function(id) {\n let path = id.parts.join('/');\n return (id.data ? '@' : '') + 'PATH:' + path;\n};\n\nPrintVisitor.prototype.StringLiteral = function(string) {\n return '\"' + string.value + '\"';\n};\n\nPrintVisitor.prototype.NumberLiteral = function(number) {\n return 'NUMBER{' + number.value + '}';\n};\n\nPrintVisitor.prototype.BooleanLiteral = function(bool) {\n return 'BOOLEAN{' + bool.value + '}';\n};\n\nPrintVisitor.prototype.UndefinedLiteral = function() {\n return 'UNDEFINED';\n};\n\nPrintVisitor.prototype.NullLiteral = function() {\n return 'NULL';\n};\n\nPrintVisitor.prototype.Hash = function(hash) {\n let pairs = hash.pairs,\n joinedPairs = [];\n\n for (let i = 0, l = pairs.length; i < l; i++) {\n joinedPairs.push(this.accept(pairs[i]));\n }\n\n return 'HASH{' + joinedPairs.join(', ') + '}';\n};\nPrintVisitor.prototype.HashPair = function(pair) {\n return pair.key + '=' + this.accept(pair.value);\n};\n/* eslint-enable new-cap */\n","// USAGE:\n// var handlebars = require('handlebars');\n/* eslint-env node */\n/* eslint-disable no-var */\n\n// var local = handlebars.create();\n\nvar handlebars = require('../dist/cjs/handlebars')['default'];\n\nvar printer = require('../dist/cjs/handlebars/compiler/printer');\nhandlebars.PrintVisitor = printer.PrintVisitor;\nhandlebars.print = printer.print;\n\nmodule.exports = handlebars;\n\n// Publish a Node.js require() handler for .handlebars and .hbs files\nfunction extension(module, filename) {\n var fs = require('fs');\n var templateString = fs.readFileSync(filename, 'utf8');\n module.exports = handlebars.compile(templateString);\n}\n/* istanbul ignore else */\nif (typeof require !== 'undefined' && require.extensions) {\n require.extensions['.handlebars'] = extension;\n require.extensions['.hbs'] = extension;\n}\n","/**\n * @aaac/runtime — public API\n *\n * Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n */\n\nimport { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\n/** Package version string. */\nexport const version = pkg.version;\n\nexport {\n runTask,\n buildTaskPrompt,\n buildSplitTaskPrompt,\n buildRetryFollowUp,\n buildCandidateAgents,\n renderAgentSystemPrompt,\n renderNavigationIndexPrompt,\n renderAnalyzerExplorationMandatePrompt,\n collectAnalyzerToolIds,\n shouldInjectAnalyzerExplorationMandate,\n isNavigationIndex,\n extractStructuredResult,\n zodSchemaToPromptDescription,\n zodSchemaToYamlExample,\n type CandidateAgent,\n type SdkAdapter,\n type AdapterSendOptions,\n type AgentProgressEvent,\n type AgentExecutionRequest,\n type TaskContext,\n type TaskOutcome,\n type TaskRunOptions,\n type TaskRunResult,\n type RetryDecision,\n type AgentContractLike,\n type TaskContractLike,\n type PromptBuilderOptions,\n type SplitPrompt,\n type CacheConfig,\n type ObserverEmitFn,\n type ExecutionEnvelope,\n type TokenUsage,\n} from \"./lib/task-runner.js\";\n\nexport {\n runWorkflow,\n buildGateEvaluationPrompt,\n parseGateEvaluationResponse,\n type SdkAdapterFactory,\n type ModelAwareSdkAdapterFactory,\n type AdapterOrFactory,\n type WorkflowInvocation,\n type HandoffInput,\n type WorkflowRegistries,\n type WorkflowRunOptions,\n type WorkflowResult,\n type StepResult,\n type StepCompleteEvent,\n type WorkflowContractLike,\n type WorkflowStep,\n type DelegateStep,\n type GateStep,\n type EvaluateStep,\n type ConvergenceEnvelopePayload,\n type ConvergenceEnvelope,\n type ReceiveSpec,\n} from \"./lib/workflow-runner.js\";\n\nexport {\n WORKFLOW_INPUT_STEP_ID,\n buildWorkflowInputOutput,\n formatWorkflowInputContext,\n stepDependsOnWorkflowInput,\n type WorkflowInputHandoff,\n type WorkflowInputOutput,\n} from \"./lib/workflow-input.js\";\n\nexport {\n createExecutionEnvelope,\n emitSessionOpen,\n emitSessionClose,\n emitSubagentOpen,\n emitSubagentClose,\n emitIterationOpen,\n emitIterationClose,\n emitIterationMetric,\n emitToolchainOpen,\n emitToolchainClose,\n emitLlmTurnOpen,\n emitLlmTurnClose,\n emitToolExecOpen,\n emitToolExecClose,\n buildObservabilityEnv,\n OBSERVABILITY_ENV_VARS,\n serializeObserverEmit,\n type EnvelopeParams,\n type InnerSpanOptions,\n type ObservabilityIds,\n} from \"./lib/observability-bridge.js\";\n\nexport {\n emitProcessWorkflowOpen,\n emitProcessWorkflowClose,\n emitProcessTaskOpen,\n emitProcessTaskClose,\n emitProcessEdit,\n isFileEditTool,\n type ProcessWorkflowOptions,\n type ProcessTaskOptions,\n type ProcessEditOptions,\n} from \"./lib/process-axis-bridge.js\";\n\nexport {\n pluginRegistry,\n PluginRegistry,\n type AgentPlugin,\n type GuardrailResult,\n type PromptBuilderArgs,\n} from \"./lib/plugin.js\";\n\nexport {\n createGuardrailHooks,\n createGuardrailHooksFromRules,\n getBlockingViolations,\n getWarnings,\n hasBlockingViolation,\n UNRESOLVED_GUARDRAIL_ACTION,\n type GuardrailAction,\n type GuardrailCheckFunctions,\n type GuardrailHooks,\n type HookContext,\n type HookResponse,\n type GuardrailCheckResult,\n type GuardrailRule,\n type GuardrailRuleData,\n} from \"./lib/guardrail-hooks.js\";\n\nexport {\n BoundResolver,\n getEffectiveGuardrailIds,\n getGuardrailRulesForAgent,\n guardrailContextToRuleData,\n buildPerAgentGuardrails,\n type BoundResolveOptions,\n type ResolvedComponent,\n type ResolvedToolchain,\n type ArtifactBindingConfig,\n deriveToolchainsForAgents,\n} from \"./lib/bound-resolver.js\";\n\nexport {\n createRuntime,\n WorkflowBuilder,\n type Runtime,\n type RuntimeConfig,\n} from \"./lib/builder.js\";\n\nexport {\n loadPlugins,\n type PluginLoadResult,\n} from \"./lib/plugin-loader.js\";\n\nexport {\n createModelResolver,\n type ModelClass,\n type ModelResolver,\n type ModelMappingConfig,\n type ModelResolverOptions,\n type ResolvedModel,\n} from \"./lib/model-resolver.js\";\n\nexport {\n loadDslContext,\n buildRegistriesFromDsl,\n DslValidationError,\n type LoadDslOptions,\n type RequiredEntities,\n type DslContext,\n} from \"./lib/dsl-context.js\";\n\nexport { jsonSchemaToZod } from \"./lib/schema-converter.js\";\n\nexport {\n createProgressSink,\n type ProgressSink,\n type ProgressSinkOptions,\n} from \"./lib/progress-sink.js\";\n\nexport type { MemoryRef, MemoryStore } from \"./lib/memory-store.js\";\nexport { InMemoryStore } from \"./lib/memory-store.js\";\n\nexport { FileMemoryStore } from \"./lib/file-memory-store.js\";\n\nexport {\n AgentLogWriter,\n type RunLogEvent,\n type AgentLogWriterOptions,\n} from \"./lib/agent-log-writer.js\";\n\nexport {\n createLibraryToolRegistry,\n createRegistryFromSdkTools,\n type LibraryToolDefinition,\n type LibraryToolRegistry,\n} from \"./lib/library-tool-binding.js\";\n\nexport {\n buildSdkFunctionTools,\n type SdkFunctionTool,\n} from \"./lib/library-tool-sdk.js\";\n\nexport {\n createAnalyzerBridge,\n isContextPack,\n renderContextPackPrompt,\n type AnalyzerBridge,\n type AnalyzerBridgeOptions,\n type AnalyzeImpactInput,\n type GenerateContextPackInput,\n type BuildCallGraphInput,\n} from \"./lib/analyzer-bridge.js\";\n\nexport {\n createAdapter,\n type CreateAdapterOptions,\n type PermissionMode,\n} from \"./lib/adapter-factory.js\";\n\nexport {\n executeTask,\n executeWorkflow,\n type ExecuteOptions,\n type ExecuteTaskOptions,\n type ExecuteWorkflowOptions,\n type TaskHookContext,\n type WorkflowHookContext,\n} from \"./lib/execute.js\";\n\nexport {\n createRuntimeBinding,\n type AaacInvocationContext,\n type AaacRuntime,\n type AaacPolicy,\n type AaacObserver,\n type InvokedComponent,\n type OperationHandler,\n type RuntimeBinding,\n type OperationMemoryRefConfig,\n type MemoryStoreEntry,\n} from \"./component-binding.js\";\n\nexport {\n createProjectRuntime,\n findProjectConfig,\n PROJECT_CONFIG_FILENAME,\n type CreateProjectRuntimeOptions,\n type ProjectRuntime,\n type ResolvedAdapterSelection,\n} from \"./lib/project-runtime.js\";\n\nexport {\n createComponentScope,\n DEFAULT_COMPONENT_ID,\n UnresolvedScopeDeclarationError,\n type ComponentScope,\n type CreateComponentScopeOptions,\n} from \"./component-scope.js\";\n\nexport {\n buildNavigationContext,\n type NavigationContextOptions,\n type NavigationContext,\n} from \"./lib/navigation-context.js\";\n\nexport {\n resolveArtifacts,\n type ArtifactResolveOptions,\n type ArtifactResolveResult,\n} from \"./lib/artifact-resolver.js\";\n\nexport {\n evaluateGuardrail,\n listGuardrails,\n guardStatus,\n type EvaluateGuardrailOptions,\n type EvaluateGuardrailResult,\n type ListGuardrailsOptions,\n type ListGuardrailsResult,\n type GuardrailListEntry,\n type GuardStatusOptions,\n type GuardStatusResult,\n} from \"./lib/guard-commands.js\";\n\nexport {\n syncClaude,\n checkClaude,\n parseClaudeConfig,\n type SyncOptions as ClaudeSyncOptions,\n type SyncResult as ClaudeSyncResult,\n type CheckResult as ClaudeCheckResult,\n type FileAction as ClaudeFileAction,\n type ClaudeConfig,\n} from \"./lib/claude-materialize/index.js\";\n\nexport {\n executePrompt,\n operationsToTools,\n parseRouterResponse,\n type PromptResult,\n type PromptExecuteOptions,\n type OperationToolDef,\n} from \"./lib/prompt-executor.js\";\n\nexport {\n runToolchainChecks,\n ToolchainManifestSchema,\n type ToolchainCheckResult,\n type ToolchainManifest,\n type RunToolchainChecksOptions,\n} from \"./lib/toolchain-checker.js\";\n","/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport {\n isNavigationIndex,\n renderNavigationIndexPrompt,\n} from \"./navigation-index-prompt.js\";\n\nexport { isNavigationIndex, renderNavigationIndexPrompt };\nimport * as yaml from \"yaml\";\n\nimport type { MemoryRef } from \"./memory-store.js\";\nimport type { ModelClass } from \"./model-resolver.js\";\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport { pluginRegistry } from \"./plugin.js\";\nimport { toolTargetPath } from \"./guardrail-hooks.js\";\nimport { buildCandidateAgents, renderAgentSystemPrompt, type CandidateAgent } from \"./candidate-agents.js\";\nimport { isContextPack, renderContextPackPrompt } from \"./analyzer-bridge.js\";\nimport {\n createExecutionEnvelope,\n emitSubagentOpen,\n emitSubagentClose,\n type ObserverEmitFn,\n type ExecutionEnvelope,\n type InnerSpanOptions,\n type TokenUsage,\n} from \"./observability-bridge.js\";\nimport { computeCostUsd } from \"./model-pricing.js\";\nimport {\n emitProcessTaskOpen,\n emitProcessTaskClose,\n emitProcessEdit,\n isFileEditTool,\n} from \"./process-axis-bridge.js\";\n\nexport type { MemoryRef } from \"./memory-store.js\";\nexport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nexport type { CandidateAgent } from \"./candidate-agents.js\";\nexport { buildCandidateAgents, renderAgentSystemPrompt } from \"./candidate-agents.js\";\nexport type { ObserverEmitFn, ExecutionEnvelope, InnerSpanOptions, TokenUsage } from \"./observability-bridge.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n readonly rules?: readonly { readonly id: string; readonly description: string; readonly severity: string }[];\n /**\n * Agent ids this agent is allowed to delegate to. When present, it restricts\n * the candidate sub-agent set registered with the SDK for LLM-internal routing.\n */\n readonly can_invoke_agents?: readonly string[];\n /**\n * Tool names this agent may execute. When present, sub-agents receive an\n * isolated tool set instead of inheriting the parent agent's tools.\n */\n readonly can_execute_tools?: readonly string[];\n /**\n * The agent is the entry/orchestrator role: it dispatches work to other\n * agents and is never itself a delegation target. Materializing it as a\n * Claude Code subagent would contradict `buildCandidateAgents`, which\n * excludes the entry agent from the candidate set.\n */\n readonly dispatch_only?: boolean;\n /**\n * Declared artifact and handoff permissions. Optional like every other\n * non-universal field on this duck-typed contract; `buildAgentRegistry`\n * always populates them, and absent is indistinguishable from empty (unlike\n * `can_invoke_agents`, where presence itself restricts the candidate set).\n */\n readonly can_read_artifacts?: readonly string[];\n readonly can_write_artifacts?: readonly string[];\n readonly can_return_handoffs?: readonly string[];\n readonly can_perform_validations?: readonly string[];\n /**\n * The rest of what a DSL agent declares about how it must work: the failure\n * shapes it must avoid, when it must stop and escalate, the decisions it owns,\n * the checklist an audit of its output runs, and its free-form prose sections.\n *\n * They are on this contract for the same reason `rules` is — they are\n * mandatory instructions to the agent, and a renderer cannot carry what the\n * contract does not hold. None of them reached any Claude surface while the\n * Cursor binding rendered all five, so one DSL produced two harnesses telling\n * an agent different things about its own obligations (#349).\n *\n * `x-authority` / `x-audit-checklist` are `x-` prefixed in the DSL document\n * and plain here, as `x-optional` / `x-instruction` / `x-receives` already are\n * on `DelegateStep`: the prefix is a fact about the document, not about this\n * runtime's interfaces (see `buildWorkflowStep`, `dsl-context.ts`).\n */\n readonly anti_patterns?: readonly string[];\n readonly escalation_criteria?: readonly {\n readonly condition: string;\n readonly action: string;\n }[];\n readonly authority?: {\n readonly can_decide?: readonly string[];\n readonly cannot_decide?: readonly string[];\n };\n readonly audit_checklist?: readonly {\n readonly section: string;\n readonly checks: readonly string[];\n }[];\n /**\n * Already expanded: a `sections[]` entry may name a list the DSL holds\n * (`list: agents`) rather than carry prose, and resolving that needs the whole\n * document, which `buildAgentRegistry` has and a renderer taking one agent\n * does not. `expandDslSection` (@aaac/contracts) is the one expansion, shared\n * with the Cursor binding.\n */\n readonly sections?: readonly { readonly title: string; readonly content: string }[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n readonly model_class?: ModelClass;\n /**\n * When true, the adapter may enable Dynamic Workflow tools (e.g. Claude's\n * Workflow tool) so the agent can internally parallelise sub-tasks.\n * Handoff validation at the task boundary is still enforced.\n */\n readonly allow_dynamic_workflow?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Progress events\n// ---------------------------------------------------------------------------\n\n/**\n * Progress event emitted by adapters during agent execution.\n * Enables real-time visibility into what the agent is doing\n * (tool calls, text output, status changes).\n */\nexport interface AgentProgressEvent {\n type: \"tool_use\" | \"tool_result\" | \"text\" | \"status\" | \"cache_metrics\";\n tool_name?: string;\n /** Tool invocation arguments (e.g. file path, command). */\n input?: Record<string, unknown>;\n message?: string;\n /** SDK session ID for correlating events within a single adapter call. */\n session_id?: string;\n /** Cache utilization metrics from the SDK response. */\n cacheMetrics?: {\n cachedInputTokens?: number;\n totalInputTokens?: number;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Prompt caching\n// ---------------------------------------------------------------------------\n\n/**\n * A prompt split into static (cacheable) and dynamic (per-invocation) sections.\n * Adapters that support prompt caching can use the `system` sections as\n * provider-specific system prompts, reducing token costs on repeated calls.\n */\nexport interface SplitPrompt {\n /** Static sections: role, responsibilities, constraints, rules, task, schema, recovery. */\n system: string[];\n /** Dynamic sections: user request, handoff input, prior context, files, acceptance criteria. */\n user: string;\n}\n\n/**\n * Optional cache configuration for adapters that support prompt caching.\n * Provider-specific defaults apply when individual fields are omitted.\n */\nexport interface CacheConfig {\n /** Enable prompt caching. Defaults to true when the adapter supports it. */\n enabled?: boolean;\n /** Provider-specific TTL (e.g. \"5m\", \"1h\", \"24h\"). */\n ttl?: string;\n /** Stable key for cross-session cache reuse (provider-specific). */\n cacheKey?: string;\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n /**\n * Optional callback invoked with intermediate progress events during execution.\n * Adapters that consume an internal event stream (e.g. Claude SDK's AsyncGenerator)\n * call this for each non-result message, enabling callers to display live progress.\n */\n onProgress?: (event: AgentProgressEvent) => void;\n /**\n * Split prompt for prompt caching support. When provided, adapters that support\n * caching can separate static (cacheable) instructions from dynamic content.\n * Adapters without caching support can ignore this and use the prompt argument.\n */\n splitPrompt?: SplitPrompt;\n /**\n * Candidate sub-agents the entry agent's LLM may delegate to (model B,\n * LLM-internal routing). Adapters register these via their native subagent\n * mechanism (Claude `agents`, OpenAI `handoffs`, ADK `subAgents`). When\n * omitted or empty, adapters behave exactly as before (single agent).\n */\n agents?: CandidateAgent[];\n /**\n * When true, adapters that support dynamic workflow tools (e.g. Claude's\n * Workflow tool for agent()/pipeline()/parallel()) should enable them.\n * The task's final output is still validated against the handoff schema.\n */\n allowDynamicWorkflow?: boolean;\n /**\n * In-process library tools to register with the SDK as function tools.\n * Adapters convert these to their native tool format (Claude MCP, OpenAI\n * function tools, ADK tools). I/O is validated against the tool's schemas.\n */\n libraryTools?: LibraryToolRegistry;\n /**\n * Optional observer emit function for inner turn-level spans\n * (agent.llm_turn, agent.tool_exec). When undefined, adapters skip\n * instrumentation entirely (no-op).\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID for inner turn-level spans. Typically the subagent span ID\n * so that LLM turn and tool execution spans are correlated as children.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded so\n * inner agent.llm_turn / agent.tool_exec spans carry a non-NULL session_id and\n * join the cross-axis correlation rules (#143 / #140).\n */\n sessionId?: string;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n\n /**\n * Split prompt for prompt caching support. When provided, adapters can\n * separate static instructions (system) from dynamic content (user).\n */\n splitPrompt?: SplitPrompt;\n\n /**\n * Candidate sub-agents for LLM-internal routing (model B). Mirrors\n * `AdapterSendOptions.agents`; also forwarded via `options.agents`.\n */\n agents?: CandidateAgent[];\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n\n /** Return the memory_ref produced by the last send/sendExecution call. */\n getLastMemoryRef?(): MemoryRef | null;\n\n /** Return the token usage from the last send/sendExecution call. */\n getLastTokenUsage?(): TokenUsage | null;\n\n /** Check if this adapter is compatible with the given compat tag. */\n isCompatible?(compat: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string; memoryRef?: MemoryRef }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n /**\n * Writable stream for real-time progress output during agent execution.\n * When provided, intermediate adapter events (tool use, status, etc.)\n * are formatted and written here. Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n /**\n * Optional observer emit function for agent-axis spans (agent.subagent open/close).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID (typically the enclosing agent.session span's run_id).\n * Used to correlate agent.subagent spans with their parent session.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded from\n * the workflow runner so the subagent span and all inner spans share one\n * non-NULL session_id, even when parentSpanId is an evaluate iteration span\n * rather than the session span (#143 / #140).\n */\n sessionId?: string;\n /** LLM adapter identifier for the execution envelope (gen_ai.system). */\n envelopeAdapter?: string;\n /** LLM model identifier for the execution envelope (gen_ai.request.model). */\n envelopeModel?: string;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n tokenUsage?: TokenUsage;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n constraints?: string;\n}\n\ntype ZodCheckEntry = {\n kind?: string;\n value?: number;\n regex?: RegExp;\n isInt?: boolean;\n _zod?: { def?: Record<string, unknown> };\n};\n\nfunction getZodChecks(schema: z.ZodType): ZodCheckEntry[] {\n const def = (schema as z.ZodType & { _def?: { checks?: ZodCheckEntry[] } })._def;\n return def?.checks ?? [];\n}\n\n/** Extract validation constraints from Zod's internal checks for prompt display. */\nfunction extractZodConstraints(schema: z.ZodType): string | undefined {\n const inner = unwrapOptional(schema);\n const parts: string[] = [];\n\n if (inner instanceof z.ZodString) {\n const str = inner as z.ZodString & {\n minLength?: number | null;\n maxLength?: number | null;\n };\n if (str.minLength != null) parts.push(`min: ${str.minLength}`);\n if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.kind === \"regex\" && check.regex) parts.push(`regex: ${check.regex}`);\n const def = check._zod?.def;\n if (def?.format === \"regex\" && def.pattern instanceof RegExp) {\n parts.push(`regex: ${def.pattern}`);\n }\n }\n } else if (inner instanceof z.ZodNumber) {\n let hasInt = false;\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"int\") hasInt = true;\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.isInt) hasInt = true;\n const def = check._zod?.def;\n if (def?.check === \"number_format\" && def.format === \"safeint\") hasInt = true;\n if (def?.check === \"greater_than\") parts.push(`min: ${def.value}`);\n if (def?.check === \"less_than\") parts.push(`max: ${def.value}`);\n }\n if (hasInt) parts.unshift(\"int\");\n } else if (inner instanceof z.ZodArray) {\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n const def = check._zod?.def;\n if (def?.check === \"min_length\") parts.push(`min: ${def.minimum}`);\n if (def?.check === \"max_length\") parts.push(`max: ${def.maximum}`);\n }\n }\n\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const element = (schema as z.ZodArray<z.ZodType>)._def.element;\n const inner = zodTypeToString(element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\n/** Unwrap ZodOptional to get the inner type. */\nfunction unwrapOptional(schema: z.ZodType): z.ZodType {\n if (schema instanceof z.ZodOptional) {\n return (schema as z.ZodOptional<z.ZodType>)._def.innerType;\n }\n return schema;\n}\n\n/** Get the element schema from an array type. */\nfunction getArrayElement(schema: z.ZodType): z.ZodType | null {\n const inner = unwrapOptional(schema);\n if (inner instanceof z.ZodArray) {\n return (inner as z.ZodArray<z.ZodType>)._def.element;\n }\n return null;\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n constraints: extractZodConstraints(innerField as z.ZodType),\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n * Recursively generates sub-tables for nested objects and array elements.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const tables: string[] = [];\n collectFieldTables(schema, \"\", tables);\n return tables.join(\"\\n\\n\");\n}\n\nfunction collectFieldTables(\n schema: z.ZodType,\n pathPrefix: string,\n tables: string[],\n): void {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return;\n\n const title = pathPrefix ? `**${pathPrefix}**\\n\\n` : \"\";\n const header = \"| Field | Type | Required | Constraints | Description |\";\n const sep = \"|-------|------|----------|-------------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.constraints ?? \"\"} | ${f.description ?? \"\"} |`,\n );\n tables.push(`${title}${[header, sep, ...rows].join(\"\\n\")}`);\n\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n if (!shape) return;\n\n for (const f of fields) {\n const rawField = shape[f.name];\n const inner = unwrapOptional(rawField);\n\n if (inner instanceof z.ZodObject) {\n collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);\n } else if (inner instanceof z.ZodArray) {\n const element = (inner as z.ZodArray<z.ZodType>)._def.element;\n if (element instanceof z.ZodObject) {\n collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);\n }\n }\n }\n}\n\n/**\n * Generate a YAML example from a Zod schema shape, recursively expanding\n * nested objects and arrays up to a configurable depth.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType, maxDepth = 3): string {\n return renderYamlObject(schema, 0, maxDepth);\n}\n\nfunction renderYamlObject(schema: z.ZodType, indent: number, maxDepth: number): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const prefix = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const f of fields) {\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n const rawField = shape?.[f.name];\n\n if (f.type.endsWith(\"[]\")) {\n lines.push(`${prefix}${f.name}:`);\n const element = rawField ? getArrayElement(rawField) : null;\n if (element && element instanceof z.ZodObject && indent < maxDepth) {\n const nested = renderYamlObject(element, indent + 2, maxDepth);\n if (nested) {\n const basePrefix = \" \".repeat(indent + 2);\n const nestedLines = nested.split(\"\\n\");\n lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);\n for (let i = 1; i < nestedLines.length; i++) {\n lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);\n }\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"string[]\") {\n lines.push(`${prefix} - \"example\"`);\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"object\" && indent < maxDepth) {\n const inner = rawField ? unwrapOptional(rawField) : null;\n if (inner && inner instanceof z.ZodObject) {\n lines.push(`${prefix}${f.name}:`);\n const nested = renderYamlObject(inner, indent + 1, maxDepth);\n if (nested) {\n lines.push(nested);\n } else {\n lines.push(`${prefix} key: \"value\"`);\n }\n } else {\n lines.push(`${prefix}${f.name}:`);\n lines.push(`${prefix} key: \"value\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${prefix}${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${prefix}${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${prefix}${f.name}: false`);\n } else if (f.type.startsWith(\"enum(\")) {\n const enumVals = f.type.slice(5, -1).split(\", \");\n lines.push(`${prefix}${f.name}: \"${enumVals[0]}\"`);\n } else {\n lines.push(`${prefix}${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/** Collect analyzer.* tool ids from a wired library tool registry. */\nexport function collectAnalyzerToolIds(\n registry?: LibraryToolRegistry,\n): string[] {\n if (!registry) return [];\n return registry\n .getAll()\n .map((def) => def.toolId)\n .filter((id) => id.startsWith(\"analyzer.\"));\n}\n\n/**\n * Level 1 exploration mandate applies when the runtime injected a navigation\n * index (codebase map) — the signal that artifact-scoped investigation is active.\n */\nexport function shouldInjectAnalyzerExplorationMandate(\n context: TaskContext,\n): boolean {\n return isNavigationIndex(context.variables?.navigationIndex);\n}\n\n/**\n * System-prompt section mandating analyzer MCP tools before ad-hoc file reads.\n * Injected automatically by runTask when Level 1 context is present.\n */\nexport function renderAnalyzerExplorationMandatePrompt(\n toolIds: readonly string[],\n): string {\n const tools = toolIds.length > 0\n ? toolIds.map((id) => `- \\`${id}\\``).join(\"\\n\")\n : \"- `analyzer.getContextMap`\\n- `analyzer.analyzeImpact`\\n- `analyzer.generateContextPack`\\n- `analyzer.buildCallGraph`\";\n\n return [\n \"## Codebase Exploration Protocol (Level 2)\",\n \"\",\n \"A Project Navigation Index is provided in the user prompt. When you need to\",\n \"investigate the codebase (locate affected files, trace dependencies, or scope\",\n \"changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:\",\n \"\",\n \"1. Use the navigation index to pick candidate artifacts and path patterns.\",\n \"2. Call `analyzer.getContextMap` with your `instruction` and `candidates[]`.\",\n \"3. Review suggestedReadTargets / suggestedEditTargets / suggestedValidationTargets.\",\n \"4. Call `analyzer.analyzeImpact` when you need a flat impact report.\",\n \"5. Use Read/Grep/Glob only for gaps the analyzer output did not cover.\",\n \"\",\n \"Available analyzer tools:\",\n tools,\n ].join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n /** When set, injects Level 1 analyzer exploration mandate into the system prompt. */\n analyzerExploration?: {\n toolIds: readonly string[];\n };\n}\n\n/**\n * Build a prompt split into static (cacheable) and dynamic (per-invocation) parts.\n *\n * Static (system): the agent's declaration (`renderAgentSystemPrompt`), Task\n * description, Completion Criteria, Output Format / Schema, Recovery\n * Instructions.\n *\n * Dynamic (user): User Request, Handoff Input, Prior Context,\n * Relevant Files, Acceptance Criteria.\n */\nexport function buildSplitTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): SplitPrompt {\n const system: string[] = [];\n\n // The agent's declaration — shared with candidate sub-agent prompts and the\n // Claude Code subagent files via renderAgentSystemPrompt so all stay in sync.\n system.push(renderAgentSystemPrompt(agent));\n\n if (\n options?.analyzerExploration?.toolIds.length &&\n shouldInjectAnalyzerExplorationMandate(context)\n ) {\n system.push(\n renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds),\n );\n }\n\n system.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n system.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n system.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n system.push(recoverySection);\n }\n\n // Dynamic sections (per-invocation)\n const userSections: string[] = [];\n\n // `user_request` and `handoff_input` are independent context fields, so each\n // is emitted on its own terms. Writing the request inside both arms of the\n // handoff branch said the same thing twice and made the request's presence\n // read as if it depended on the handoff.\n userSections.push(`## User Request\\n\\n${context.user_request}`);\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n userSections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n }\n\n if (context.prior_context) {\n userSections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n userSections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n userSections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.variables && Object.keys(context.variables).length > 0) {\n const contextPack = context.variables.analyzerContextPack;\n if (isContextPack(contextPack)) {\n userSections.push(renderContextPackPrompt(contextPack));\n }\n\n const navigationIndex = context.variables.navigationIndex;\n if (isNavigationIndex(navigationIndex)) {\n userSections.push(renderNavigationIndexPrompt(navigationIndex));\n }\n\n const otherVars = Object.entries(context.variables).filter(\n ([k]) => k !== \"analyzerContextPack\" && k !== \"navigationIndex\",\n );\n if (otherVars.length > 0) {\n const varLines = otherVars\n .map(([k, v]) => `- ${k}: ${typeof v === \"string\" ? v : JSON.stringify(v)}`)\n .join(\"\\n\");\n userSections.push(`## Context Variables\\n\\n${varLines}`);\n }\n }\n\n return {\n system,\n user: userSections.join(\"\\n\\n---\\n\\n\"),\n };\n}\n\n/** Join a SplitPrompt back into a single monolithic prompt string. */\nfunction joinSplitPrompt(split: SplitPrompt): string {\n return [...split.system, split.user].join(\"\\n\\n---\\n\\n\");\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\nfunction attachMemoryRef(outcome: TaskOutcome, adapter: SdkAdapter): TaskOutcome {\n if (outcome.status !== \"success\") return outcome;\n const ref = adapter.getLastMemoryRef?.();\n if (!ref) return outcome;\n return { ...outcome, memoryRef: ref };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Progress formatting\n// ---------------------------------------------------------------------------\n\nfunction summarizeToolInput(input?: Record<string, unknown>): string {\n if (!input) return \"\";\n const path = toolTargetPath(input);\n if (path) return ` — ${path}`;\n const cmd = input.command ?? input.cmd;\n if (typeof cmd === \"string\") return ` — ${cmd.length > 80 ? cmd.slice(0, 77) + \"...\" : cmd}`;\n const query = input.query ?? input.search ?? input.pattern;\n if (typeof query === \"string\") return ` — \"${query}\"`;\n return \"\";\n}\n\nfunction timestamp(): string {\n return new Date().toISOString();\n}\n\nfunction formatProgressPrefix(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const ts = timestamp();\n const sid = event.session_id ? event.session_id.slice(0, 8) : \"-\";\n const agent = agentId ?? \"-\";\n return `[${ts},${sid},${agent},${taskId}]`;\n}\n\nfunction formatProgressEvent(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const prefix = formatProgressPrefix(event, taskId, agentId);\n switch (event.type) {\n case \"tool_use\":\n return `${prefix} ⚙ ${event.tool_name ?? \"tool\"}${summarizeToolInput(event.input)}\\n`;\n case \"tool_result\":\n return \"\";\n case \"text\": {\n if (!event.message) return \"\";\n const trimmed = event.message.trim();\n if (!trimmed) return \"\";\n const firstLine = trimmed.split(\"\\n\")[0];\n const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + \"...\" : firstLine;\n return `${prefix} 💭 ${preview}\\n`;\n }\n case \"status\":\n return event.message ? `${prefix} ● ${event.message}\\n` : \"\";\n default:\n return \"\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n libraryTools?: LibraryToolRegistry;\n /**\n * Each agent's effective tool grant, from the executing component's\n * `ComponentScope.toolsByAgent` (#338). Travels with `agentRegistry`\n * because the two are consumed together, by `buildCandidateAgents` below.\n */\n toolsByAgent?: Map<string, string[]>;\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n // ── ExecutionEnvelope (Phase 1-1) ──────────────────────────────────────────\n // Create a standard envelope for this task execution. run_id is a UUIDv7.\n // parent_run_id is set to the enclosing session's spanId (from workflow-runner).\n const taskEnvelope: ExecutionEnvelope = createExecutionEnvelope({\n taskInstanceId: taskId,\n componentId: agentContract.id,\n fromAgent: agentContract.id,\n parentRunId: options?.parentSpanId, // correlates to agent.session run_id\n adapter: options?.envelopeAdapter,\n model: options?.envelopeModel,\n });\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);\n const promptOpts: PromptBuilderOptions = {\n handoffSchemas: schemas,\n retry: options?.retry,\n ...(analyzerToolIds.length > 0 &&\n shouldInjectAnalyzerExplorationMandate(enrichedContext)\n ? { analyzerExploration: { toolIds: analyzerToolIds } }\n : {}),\n };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n\n let prompt: string;\n let splitPrompt: SplitPrompt | undefined;\n\n const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);\n if (pluginPrompt) {\n prompt = pluginPrompt;\n } else {\n const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n splitPrompt = split;\n prompt = joinSplitPrompt(split);\n }\n\n const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n if (enhancedPrompt !== prompt) {\n splitPrompt = undefined;\n prompt = enhancedPrompt;\n }\n\n const isReadonly = agentContract.mode === \"read-only\";\n const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;\n\n // Build candidate sub-agents for LLM-internal routing (model B). The entry\n // agent (this task's target_agent) gets every other registry agent as a\n // candidate, restricted to its can_invoke_agents allow-list when present.\n // Empty registry → undefined (adapters then behave exactly as before).\n const candidateAgents = Object.keys(agentReg).length > 0\n ? buildCandidateAgents(agentReg, {\n entryAgentId: agentContract.id,\n allowedAgentIds: agentContract.can_invoke_agents,\n toolsByAgent: options?.toolsByAgent,\n })\n : [];\n const agents = candidateAgents.length > 0 ? candidateAgents : undefined;\n\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n // ── Process axis instrumentation (R3/R5 cross-axis correlation, #167) ───────\n // The Process axis must be instrumented in the LIVE runtime so the enrich\n // rules R3/R4 accumulate this task's modified files and R5 can link the commit\n // that materializes them. `effectiveSessionId` (below) is the SAME id\n // propagated to the git post-commit hook via AAAC_SESSION_ID, so the runtime\n // accumulation and the hook's promotion.commit correlate across processes.\n // All emit* helpers no-op when options.observer is undefined.\n const taskExecStart = Date.now();\n // The agent session id correlates every span emitted for this task (the\n // subagent span and all inner llm_turn/tool_exec spans) and joins the agent\n // axis to the cursor/git axes (#143 / #140). Prefer the explicit session id\n // threaded by the workflow runner; fall back to the parent session span, then\n // to this task's own run_id so the session_id is NEVER NULL — even when\n // runTask is invoked standalone (no workflow, no parent span).\n const effectiveSessionId =\n options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;\n // process.task open is emitted just after the agent.subagent open below, so\n // the agent span stays the first span for this task. The id is captured here\n // (let) so the finally can close it. Dedupe repeated edits to the same path to\n // limit write volume on the shared SqliteSink (R3 also dedupes, but this\n // avoids needless emit() round-trips).\n let processTaskSpanId: string | undefined;\n const emittedEditPaths = new Set<string>();\n\n const onProgress =\n options?.progressOutput || options?.observer\n ? (event: AgentProgressEvent) => {\n if (options?.progressOutput) {\n const line = formatProgressEvent(event, taskId, agentContract.id);\n if (line) options.progressOutput.write(line);\n }\n // Emit a process.edit for each file-mutating tool call so R3 can\n // accumulate this task's modified files for cross-axis linking (#167).\n if (\n options?.observer &&\n event.type === \"tool_use\" &&\n isFileEditTool(event.tool_name)\n ) {\n const p = toolTargetPath(event.input);\n if (p && !emittedEditPaths.has(p)) {\n emittedEditPaths.add(p);\n // IMPORTANT: do NOT set parentSpanId here. The enrich rule R3\n // resolves the parent task AND accumulates this file into the\n // per-task modified-files set (which R5 intersects with the\n // commit) ONLY when process.edit arrives WITHOUT a parentSpanId\n // (process.ts returns early otherwise). Leaving it unresolved is\n // what makes the cross-axis link materialize (#167).\n emitProcessEdit({\n filePath: p,\n sessionId: effectiveSessionId,\n observer: options.observer,\n });\n }\n }\n }\n : undefined;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n let memoryRef = enrichedContext.memoryRef;\n if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {\n console.warn(\n `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`,\n );\n memoryRef = undefined;\n }\n\n // ── agent.subagent open (Phase 1-3) ────────────────────────────────────────\n // Emit agent.subagent open span. subagentSpanId = taskEnvelope.run_id.\n // parentSpanId = options.parentSpanId (agent.session span from runWorkflow).\n // No-op when options.observer is undefined. taskExecStart / effectiveSessionId\n // are computed above with the Process axis instrumentation so both axes share\n // one session id and a single start clock.\n const subagentSpanId = emitSubagentOpen(\n options?.observer,\n taskEnvelope,\n options?.parentSpanId,\n taskId,\n agentContract.role_name,\n effectiveSessionId,\n );\n\n // ── process.task open (#167) ───────────────────────────────────────────────\n // Emitted after agent.subagent open so the agent span remains first, but\n // before any tool runs so R3/R4 see this task on the active-task stack when\n // process.edit events arrive. No-op when options.observer is undefined.\n processTaskSpanId = emitProcessTaskOpen({\n taskId,\n targetAgent: task.target_agent,\n sessionId: effectiveSessionId,\n parentSpanId: subagentSpanId ?? options?.parentSpanId,\n observer: options?.observer,\n });\n\n // ── Exception-safe subagent lifecycle ──────────────────────────────────────\n // Everything between the agent.subagent open span and its close span (initial\n // send, validation/afterTask hooks and the recovery loop) can throw or return\n // early. Wrap that region in try/finally so the close span is emitted EXACTLY\n // ONCE on EVERY exit path — success, a returned failure AND a thrown exception\n // — leaving no span stuck 'open'. This mirrors runWorkflow's session lifecycle.\n // A `closed` guard prevents double emission; closeStatus/closeCause carry the\n // outcome into the finally. The original exception is always re-thrown\n // unchanged (the finally never swallows it) to preserve propagation semantics.\n let closeStatus = \"error\";\n let closeCause: string | undefined;\n let spanClosed = false;\n const closeSubagentSpan = (): void => {\n if (spanClosed) return;\n spanClosed = true;\n const durationMs = Date.now() - taskExecStart;\n const lastTokenUsage = adapter.getLastTokenUsage?.();\n taskEnvelope.execution_metadata = {\n ...(taskEnvelope.execution_metadata ?? {}),\n duration_ms: durationMs,\n ...(lastTokenUsage ? {\n token_usage: {\n input_tokens: lastTokenUsage.inputTokens,\n output_tokens: lastTokenUsage.outputTokens,\n ...(lastTokenUsage.totalTokens !== undefined ? { total_tokens: lastTokenUsage.totalTokens } : {}),\n ...(lastTokenUsage.cacheReadTokens !== undefined ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {}),\n ...(lastTokenUsage.cacheCreationTokens !== undefined ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}),\n },\n } : {}),\n };\n if (lastTokenUsage) {\n const costUsd = computeCostUsd(\n taskEnvelope.model,\n lastTokenUsage.inputTokens,\n lastTokenUsage.outputTokens,\n );\n if (costUsd !== undefined) {\n taskEnvelope.execution_metadata = {\n ...taskEnvelope.execution_metadata,\n cost_usd: costUsd,\n };\n }\n }\n emitSubagentClose(\n options?.observer,\n subagentSpanId ?? taskEnvelope.run_id,\n taskEnvelope,\n durationMs,\n closeStatus,\n agentContract.role_name,\n closeCause,\n effectiveSessionId,\n );\n // ── process.task close (#167) ─────────────────────────────────────────────\n // Pop this task off the enrich active-task stack (R3/R4). Guarded by the\n // same `spanClosed` flag so it is emitted EXACTLY ONCE on every exit path.\n if (processTaskSpanId) {\n emitProcessTaskClose(processTaskSpanId, {\n status: closeStatus,\n durationMs,\n observer: options?.observer,\n });\n }\n };\n\n try {\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n memoryRef,\n splitPrompt,\n agents,\n options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });\n }\n } catch (err) {\n // SDK errors on the initial send are returned as an error outcome (NOT\n // re-thrown) — preserve that semantics. The finally emits the close span.\n closeStatus = \"error\";\n closeCause = `SDK error: ${(err as Error).message}`;\n return { outcome: { status: \"error\", message: closeCause }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n // Normal exit: record the final outcome status for the close span.\n closeStatus = outcome.status;\n const finalTokenUsage = adapter.getLastTokenUsage?.() ?? undefined;\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };\n } catch (err) {\n // Post-send / recovery threw (e.g. validation, afterTask hook or decide()).\n // Record the cause and re-throw unchanged — the finally still emits close.\n closeStatus = \"error\";\n closeCause = (err as Error).message;\n throw err;\n } finally {\n // ── agent.subagent close (Phase 1-3) ─────────────────────────────────────\n closeSubagentSpan();\n }\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type {\n GuardrailCheckFunctions,\n GuardrailCheckResult,\n} from \"./guardrail-hooks.js\";\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\n/**\n * One plugin verdict in the guardrail evaluator's shape.\n *\n * The two types say the same thing in opposite polarity — a plugin reports what\n * it MATCHED, the evaluator records what PASSED — and `severity` has no reader\n * on the evaluator side, which grades by `action` alone. So the translation is\n * real and belongs to whichever side owns `GuardrailResult`: this one. It sat in\n * `guardrail-hooks` while that module imported the registry, and cost an\n * `action as GuardrailCheckResult[\"action\"]` cast to get there, because it was\n * written against a structural `{ action: string }` rather than the declared\n * union. `GuardrailResult[\"action\"]` is a strict subset of `GuardrailAction`\n * (which adds only `unresolved`, a state no plugin can be in), so naming the\n * type makes the assignment check instead of asserting.\n */\nfunction toCheckResult(result: GuardrailResult): GuardrailCheckResult {\n return {\n guardrail_id: result.guardrail_id,\n passed: !result.matched,\n action: result.action,\n message: result.matched ? result.message : \"\",\n };\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n /**\n * Whether `guardrailChecks()` would supply anything.\n *\n * The execution layer has to know this BEFORE it builds hooks, because it\n * decides whether hooks exist at all and the source it gets back is three\n * closures either way, indistinguishable from an empty one. It gated on the\n * resolved rules instead, so a project whose ONLY guardrails came from a\n * plugin got no hooks and its plugin was consulted nowhere (#332).\n *\n * The question is asked of the three EVALUATORS, not of `customGuardrails`\n * itself, because that is what the three aggregators above ask: each skips a\n * plugin whose own method is absent, so `customGuardrails: {}` — legal under\n * the type — contributes to no check. Answering `true` for it would report a\n * source that grades nothing, and the execution layer would give a project\n * one adapter per agent to carry hooks with nothing in them.\n *\n * Answering it belongs here for the same reason `guardrailChecks` does: the\n * shape of `AgentPlugin.customGuardrails` is this module's to know, and it is\n * read nowhere else.\n */\n hasGuardrails(): boolean {\n return this.plugins.some(\n ({ customGuardrails: g }) =>\n Boolean(g?.evaluateCommand) ||\n Boolean(g?.evaluateFilePath) ||\n Boolean(g?.evaluateFileContent),\n );\n }\n\n /**\n * These plugins' `customGuardrails`, as a check source `createGuardrailHooks`\n * takes alongside the rules a software binding resolved.\n *\n * The evaluator used to reach for the `pluginRegistry` singleton itself. That\n * is an ambient dependency pointing the wrong way — a shared leaf module\n * reaching up into an application-level registry — and it had a measurable\n * price, because `guardrail-hooks` is on the LEAN graph: a class gets no\n * per-method tree-shaking, so the whole registry, task and workflow hooks\n * included, was 1,481 B of the 12,496 B `check-artifact-edit` parses on every\n * single tool call (#331). Handing the source in reverses the edge (this\n * module knows the evaluator's shape; the evaluator knows nothing of plugins)\n * and takes the class off that graph entirely.\n *\n * WHO passes it is the whole design, so it is stated here rather than left to\n * be inferred from call sites:\n *\n * - The EXECUTION layer does — `execute.ts`, for the hooks it hands each\n * agent's adapter. That is the process `loadPlugins` ran in\n * (`project-runtime.ts` → `plugin-loader.ts`), and plugin guardrails guard\n * what this runtime itself executes, exactly like every other\n * `AgentPlugin` hook, all of which the task and workflow runners consume.\n * - The HOOK routes do NOT — the two Claude Code PreToolUse bins and\n * `guard evaluate`. Those answer \"may this editor do this?\", and they have\n * to answer it identically or a project's rule means one thing in a Claude\n * Code session and another under `guard evaluate` (#316). Two of the three\n * CANNOT consult plugins at any price: they run on the lean bundle, which\n * deliberately excludes the project-manifest resolver, so the `plugins:`\n * list that `loadPlugins` needs is unreachable there — the shipped lean\n * bundle contains neither this class nor any `loadPlugins` or `register`\n * caller, so those processes hold no registry to consult at all. Feeding\n * the third one a source the other two structurally lack is what would\n * split the verdict; passing none keeps the three equal by construction\n * instead of by the accident of no project declaring a plugin.\n *\n * The closures consult `this.plugins` when a check runs, not when the source\n * is built. That is not a promise that a plugin registering later is picked\n * up: the caller asks `hasGuardrails()` first and never comes back for the\n * source when the answer was no, so a registration after that point reaches\n * no hooks. What holds instead is the order — `loadPlugins` runs once, while\n * `createProjectRuntime` builds the runtime, before anything can execute.\n */\n guardrailChecks(): GuardrailCheckFunctions {\n return {\n checkCommand: (command) => this.evaluateCommandGuardrails(command).map(toCheckResult),\n checkFilePath: (filePath) => this.evaluateFilePathGuardrails(filePath).map(toCheckResult),\n checkContent: (filePath, content) =>\n this.evaluateFileContentGuardrails(filePath, content).map(toCheckResult),\n };\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Candidate Agents — backend-neutral bridge for LLM-internal routing (model B)\n *\n * The runtime registers a set of *candidate sub-agents* with the SDK so the\n * entry/main agent's LLM can delegate to them internally via the SDK's native\n * subagent mechanism:\n *\n * - Claude `Options.agents: Record<string, AgentDefinition>`\n * - OpenAI `Agent.handoffs: Agent[]`\n * - ADK `LlmAgent.subAgents: BaseAgent[]`\n *\n * `CandidateAgent` is the common, SDK-independent contract. Each adapter maps it\n * onto its provider's native shape. The selection rule (which agents become\n * candidates) lives here so all adapters stay backend-agnostic.\n */\n\nimport type { AgentContractLike } from \"./task-runner.js\";\n\n/**\n * SDK-independent description of a sub-agent the entry agent's LLM may delegate\n * to. Adapters translate this into their provider's native subagent shape.\n */\nexport interface CandidateAgent {\n /** Agent id (used as the SDK subagent key / name). */\n name: string;\n /** When to use this agent — the routing hint shown to the delegating LLM. */\n description: string;\n /** The agent's system prompt — everything the DSL declares about its work. */\n prompt: string;\n /** Optional allowed tool names (omit to inherit from the parent agent). */\n tools?: string[];\n /** Optional model id (omit to inherit from the parent agent). */\n model?: string;\n}\n\n/**\n * Render an agent contract into its system-prompt string: everything the DSL\n * declares about how the agent must work.\n *\n * The ONE renderer of a declared agent for every Claude surface — the in-process\n * system prompt (`buildSplitTaskPrompt`), the SDK candidate agents\n * (`buildCandidateAgents`), and the Claude Code subagent body\n * (`claude-materialize/agent-render.ts`) — so one DSL agent cannot be described\n * differently depending on which of them a prompt came through.\n *\n * That is also why the sections below are not a subset. It rendered role,\n * responsibilities, constraints and rules and stopped there, so an agent's\n * anti-patterns, escalation criteria, authority boundaries, audit checklist and\n * prose sections reached no Claude surface at all while the Cursor binding\n * rendered every one of them: the dev-team architect's \"issue-fix AC Derivation\"\n * procedure was in the Cursor prompt and in no Claude prompt (#349). Nothing\n * failed — a prompt that is missing an instruction is still a valid prompt.\n *\n * Permissions are NOT here: they are the file-form's `permissionSections`, which\n * an agent receiving only its own `.claude/agents/*.md` needs and an in-process\n * agent has enforced around it by the runtime.\n */\nexport function renderAgentSystemPrompt(agent: AgentContractLike): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.rules && agent.rules.length > 0) {\n const ruleLines = agent.rules.map(\n (r) => `- **${r.id}** [${r.severity}]: ${r.description}`,\n );\n sections.push(`## Rules\\n\\n${ruleLines.join(\"\\n\")}`);\n }\n\n if (agent.anti_patterns && agent.anti_patterns.length > 0) {\n sections.push(\n `## Anti-patterns\\n\\n${agent.anti_patterns.map((a) => `- ${a}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.escalation_criteria && agent.escalation_criteria.length > 0) {\n const lines = agent.escalation_criteria.map((e) => `- **${e.condition}** → ${e.action}`);\n sections.push(`## Escalation Criteria\\n\\n${lines.join(\"\\n\")}`);\n }\n\n // Either half on its own is a boundary worth stating, so the section appears\n // when the DSL declared the field with anything in it.\n const canDecide = agent.authority?.can_decide ?? [];\n const cannotDecide = agent.authority?.cannot_decide ?? [];\n if (canDecide.length > 0 || cannotDecide.length > 0) {\n const lines: string[] = [];\n if (canDecide.length > 0) lines.push(`- **Can decide**: ${canDecide.join(\", \")}`);\n if (cannotDecide.length > 0) lines.push(`- **Cannot decide**: ${cannotDecide.join(\", \")}`);\n sections.push(`## Authority Boundaries\\n\\n${lines.join(\"\\n\")}`);\n }\n\n if (agent.audit_checklist && agent.audit_checklist.length > 0) {\n const groups = agent.audit_checklist.map(\n (group) => `### ${group.section}\\n\\n${group.checks.map((c) => `- [ ] ${c}`).join(\"\\n\")}`,\n );\n sections.push(`## Audit Checklist\\n\\n${groups.join(\"\\n\\n\")}`);\n }\n\n // Last, as the DSL orders them: a section carries the agent's own prose, often\n // a multi-step procedure, and it reads as a continuation of the terse\n // declarations above rather than an interruption of them.\n for (const section of agent.sections ?? []) {\n sections.push(`## ${section.title}\\n\\n${section.content}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Derive a concise routing description (first sentence/line) from a purpose. */\nfunction deriveDescription(purpose: string): string {\n const firstLine = purpose.split(\"\\n\").map((l) => l.trim()).find((l) => l.length > 0) ?? \"\";\n // Prefer the first sentence when the line packs several together.\n const sentenceEnd = firstLine.search(/[.!?](\\s|$)/);\n if (sentenceEnd !== -1) {\n return firstLine.slice(0, sentenceEnd + 1).trim();\n }\n return firstLine;\n}\n\nexport interface BuildCandidateAgentsOptions {\n /** The entry/main agent id. Excluded from the candidate set. */\n entryAgentId?: string;\n /**\n * When provided (typically the entry agent's `can_invoke_agents`), restrict\n * candidates to these agent ids. Omit to allow every non-entry agent.\n */\n allowedAgentIds?: readonly string[];\n /**\n * Each agent's effective tool grant — `ComponentScope.toolsByAgent`\n * (component-scope.ts), the one place `tools[*].invokable_by`,\n * `agents[*].can_execute_tools` and the toolchains derived for the agent are\n * resolved into names. Read, not recomputed: this function used to merge\n * `can_execute_tools` with the derived toolchain ids itself, which is the\n * same statement in a second place — and the two read `can_execute_tools` in\n * different namespaces until #337 made them agree. An agent absent from the\n * map gets no `tools`, i.e. inherits the parent agent's.\n */\n toolsByAgent?: Map<string, string[]>;\n}\n\n/**\n * Build the candidate sub-agent set from an agent registry.\n *\n * Selection rule: every agent EXCEPT the entry agent; if `allowedAgentIds` is\n * given, further restrict to that allow-list.\n */\nexport function buildCandidateAgents(\n agentRegistry: Record<string, AgentContractLike>,\n opts?: BuildCandidateAgentsOptions,\n): CandidateAgent[] {\n const entryId = opts?.entryAgentId;\n const allowed = opts?.allowedAgentIds;\n const allowSet = allowed ? new Set(allowed) : undefined;\n\n const candidates: CandidateAgent[] = [];\n for (const [id, agent] of Object.entries(agentRegistry)) {\n if (id === entryId) continue;\n if (allowSet && !allowSet.has(id)) continue;\n\n const agentTools = opts?.toolsByAgent?.get(id) ?? [];\n\n candidates.push({\n name: id,\n description: deriveDescription(agent.purpose),\n prompt: renderAgentSystemPrompt(agent),\n ...(agentTools.length > 0 ? { tools: agentTools } : {}),\n });\n }\n return candidates;\n}\n","/**\n * Model pricing table for cost_usd computation (#210).\n *\n * Prices are USD per 1M tokens. Unknown models fail open (return undefined).\n */\n\nexport interface ModelPricing {\n inputPerMillion: number;\n outputPerMillion: number;\n}\n\n/** Normalise model id for lookup (strip provider prefixes / version suffixes). */\nexport function normalizeModelId(model: string): string {\n return model.trim().toLowerCase();\n}\n\nconst PRICING_TABLE: Record<string, ModelPricing> = {\n // Anthropic Claude\n \"claude-opus-4-6\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-opus-4\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-sonnet-4\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-sonnet-4-6\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-haiku-4\": { inputPerMillion: 0.8, outputPerMillion: 4 },\n // OpenAI GPT\n \"gpt-5.5\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-5.3-codex\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4.1\": { inputPerMillion: 2, outputPerMillion: 8 },\n \"gpt-4o\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4o-mini\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n // Google Gemini\n \"gemini-2.5-pro\": { inputPerMillion: 1.25, outputPerMillion: 10 },\n \"gemini-2.5-flash\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n \"gemini-2.0-flash\": { inputPerMillion: 0.1, outputPerMillion: 0.4 },\n};\n\nexport function resolveModelPricing(model: string | undefined): ModelPricing | undefined {\n if (!model) return undefined;\n const key = normalizeModelId(model);\n if (PRICING_TABLE[key]) return PRICING_TABLE[key];\n // Prefix match for versioned ids (e.g. claude-sonnet-4-20250514)\n for (const [known, pricing] of Object.entries(PRICING_TABLE)) {\n if (key.startsWith(known)) return pricing;\n }\n return undefined;\n}\n\nexport function computeCostUsd(\n model: string | undefined,\n inputTokens: number,\n outputTokens: number,\n): number | undefined {\n const pricing = resolveModelPricing(model);\n if (!pricing) return undefined;\n if (inputTokens <= 0 && outputTokens <= 0) return undefined;\n const cost =\n (inputTokens * pricing.inputPerMillion + outputTokens * pricing.outputPerMillion) /\n 1_000_000;\n return Math.round(cost * 1_000_000) / 1_000_000;\n}\n","/**\n * Process axis emit helpers for runtime integration.\n * These wrap @aaac/observability's EventCollector for structured process axis events.\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { AttrValue } from \"@aaac/observability\";\nimport type { ObserverEmitFn } from \"./observability-bridge.js\";\n\nexport interface ProcessWorkflowOptions {\n workflowId: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessTaskOptions {\n taskId: string;\n targetAgent: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessEditOptions {\n filePath: string;\n artifactId?: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\n/** Build attribute record; omits keys with undefined/empty-string values. */\nfunction attrs(base: Record<string, AttrValue | undefined>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && v !== \"\") out[k] = v;\n }\n return out;\n}\n\n/**\n * Tool names that mutate files on disk and therefore should produce a\n * process.edit event for cross-axis correlation (enrich R3/R5).\n *\n * Read/search/shell tools are intentionally excluded — only file writes count\n * as edits. Matched case-insensitively so adapter-specific casing variants\n * (Write/write, MultiEdit/multi_edit) are all recognised.\n */\nconst FILE_EDIT_TOOL_NAMES = new Set([\n \"write\",\n \"edit\",\n \"multiedit\",\n \"multi_edit\",\n \"notebookedit\",\n \"notebook_edit\",\n]);\n\n/**\n * True when a tool name denotes a file-mutating edit, so a process.edit event\n * should be emitted for it. Used by the task runner to instrument the Process\n * axis from live tool-use progress events (#167).\n */\nexport function isFileEditTool(toolName: string | undefined): boolean {\n if (!toolName) return false;\n return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());\n}\n\n/**\n * Emit process.workflow open span.\n */\nexport function emitProcessWorkflowOpen(options: ProcessWorkflowOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"workflow.id\": options.workflowId,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.workflow close span.\n */\nexport function emitProcessWorkflowClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"workflow.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"workflow.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.task open span.\n */\nexport function emitProcessTaskOpen(options: ProcessTaskOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"task.id\": options.taskId,\n \"task.type\": \"implement\",\n \"task.target_agent\": options.targetAgent,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.task close span.\n */\nexport function emitProcessTaskClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"task.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"task.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.edit instant span.\n */\nexport function emitProcessEdit(options: ProcessEditOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.edit\",\n lifecycle: \"instant\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"edit.path\": options.filePath,\n \"edit.artifact_id\": options.artifactId,\n }),\n });\n return spanId;\n}\n","/**\n * Toolchain Checker — runs check commands defined in toolchain-contracts\n * and returns structured pass/fail results.\n *\n * Each toolchain may declare a `checks` map (checkType → shell command).\n * This module iterates all checks, executes them via subprocess, and\n * returns a ToolchainCheckResult[].\n *\n * For \"drift\" check types, a manifest-based fast path is available:\n * if a .toolchain-manifest.json exists and the toolchain_id matches,\n * the command execution can be skipped when the source hash is current.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { parseToolchainFile } from \"@aaac/toolchain\";\nimport {\n emitToolchainOpen,\n emitToolchainClose,\n buildObservabilityEnv,\n type ObserverEmitFn,\n type ObservabilityIds,\n} from \"./observability-bridge.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst SUBPROCESS_TIMEOUT_MS = 30_000;\nconst MANIFEST_FILENAME = \".toolchain-manifest.json\";\n\n// ---------------------------------------------------------------------------\n// Manifest schema (Phase 7 full validation; schema + read logic placed here)\n// ---------------------------------------------------------------------------\n\nexport const ToolchainManifestSchema = z.object({\n schema: z.string(),\n toolchain_id: z.string(),\n generated_at: z.string(),\n source_hash: z.string(),\n output_hash: z.string(),\n source_globs: z.array(z.string()).optional(),\n output_globs: z.array(z.string()).optional(),\n files: z\n .array(\n z.object({\n path: z.string(),\n hash: z.string(),\n }),\n )\n .optional(),\n});\n\nexport type ToolchainManifest = z.infer<typeof ToolchainManifestSchema>;\n\n// ---------------------------------------------------------------------------\n// Check result types\n// ---------------------------------------------------------------------------\n\nexport interface ToolchainCheckResult {\n toolchainId: string;\n checkType: string;\n status: \"pass\" | \"fail\" | \"skip\" | \"error\";\n action: \"block\" | \"warn\" | \"shadow\";\n message?: string;\n durationMs?: number;\n}\n\nexport interface RunToolchainChecksOptions {\n /** Absolute path to toolchain-contracts YAML */\n toolchainsPath: string;\n /** Absolute path to artifact-contracts YAML (optional, for manifest fast path) */\n artifactsPath?: string;\n /** Working directory for subprocess execution */\n cwd?: string;\n /** Filter: only run these check types */\n checkTypes?: string[];\n /** Filter: only run checks for these toolchain IDs */\n toolchainFilter?: string[];\n /** Policy-resolved action per check type. Key = check type, value = action. Special key \"_default\" for fallback. */\n checkTypeActions?: Record<string, \"block\" | \"warn\" | \"shadow\">;\n /** Default action when no policy match */\n defaultAction?: \"block\" | \"warn\" | \"shadow\";\n /**\n * Optional observer emit function. When provided, each check execution emits a\n * toolchain.execution span (open before the check, close after) so the check is\n * recorded on the agent axis. No-op when undefined (observer is optional).\n * This is OBSERVATION ONLY — emitting spans never alters the returned results\n * nor the resolved action, so workflow success/failure semantics are unchanged.\n */\n observer?: ObserverEmitFn;\n /** Parent span id (typically the enclosing agent.session run_id) for correlation. */\n parentSpanId?: string;\n /** Component id recorded on toolchain.execution spans (agent.component_id). */\n componentId?: string;\n /**\n * Observability correlation ids propagated to spawned check subprocesses as\n * AAAC_SESSION_ID / AAAC_TRACE_ID / AAAC_RUN_ID (#115). A check that spawns\n * `git commit`/`git push` lets the resulting git `post-commit` hook attribute\n * its promotion.* events back to this session. No-op when undefined.\n */\n observabilityIds?: ObservabilityIds;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveAction(\n checkType: string,\n checkTypeActions?: Record<string, \"block\" | \"warn\" | \"shadow\">,\n defaultAction?: \"block\" | \"warn\" | \"shadow\",\n): \"block\" | \"warn\" | \"shadow\" {\n if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];\n if (checkTypeActions?.[\"_default\"]) return checkTypeActions[\"_default\"];\n return defaultAction ?? \"warn\";\n}\n\nasync function tryManifestFastPath(\n toolchainId: string,\n cwd: string,\n): Promise<ToolchainCheckResult | null> {\n const manifestPath = resolve(cwd, MANIFEST_FILENAME);\n if (!existsSync(manifestPath)) return null;\n\n try {\n const raw = await readFile(manifestPath, \"utf-8\");\n const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));\n\n if (parsed.toolchain_id !== toolchainId) return null;\n\n // Manifest found and toolchain_id matches — Phase 7 will add full\n // hash comparison; for now we treat a matching manifest as a pass.\n return {\n toolchainId,\n checkType: \"drift\",\n status: \"pass\",\n action: \"warn\",\n message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,\n durationMs: 0,\n };\n } catch {\n return null;\n }\n}\n\nasync function executeCheck(\n command: string,\n cwd: string,\n observabilityIds?: ObservabilityIds,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n const env = observabilityIds\n ? buildObservabilityEnv(observabilityIds)\n : undefined;\n try {\n const { stdout, stderr } = await execFileAsync(\"sh\", [\"-c\", command], {\n cwd,\n timeout: SUBPROCESS_TIMEOUT_MS,\n ...(env ? { env } : {}),\n });\n return { exitCode: 0, stdout, stderr };\n } catch (err: unknown) {\n const execErr = err as { code?: number | string; killed?: boolean; stdout?: string; stderr?: string };\n if (execErr.killed) {\n throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);\n }\n const exitCode = typeof execErr.code === \"number\" ? execErr.code : 1;\n return {\n exitCode,\n stdout: execErr.stdout ?? \"\",\n stderr: execErr.stderr ?? \"\",\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main entry\n// ---------------------------------------------------------------------------\n\nexport async function runToolchainChecks(\n options: RunToolchainChecksOptions,\n): Promise<ToolchainCheckResult[]> {\n const {\n toolchainsPath,\n cwd: workingDir,\n checkTypes,\n toolchainFilter,\n checkTypeActions,\n defaultAction,\n observer,\n parentSpanId,\n componentId,\n observabilityIds,\n } = options;\n\n const cwd = workingDir ?? process.cwd();\n const contracts = await parseToolchainFile(toolchainsPath);\n const results: ToolchainCheckResult[] = [];\n\n for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {\n if (!toolchain.checks) continue;\n if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;\n\n for (const [checkType, command] of Object.entries(toolchain.checks)) {\n if (checkTypes && !checkTypes.includes(checkType)) continue;\n\n const action = resolveAction(checkType, checkTypeActions, defaultAction);\n const start = performance.now();\n\n // ── toolchain.execution open ────────────────────────────────────────\n // Open the span BEFORE running the check so the close span's duration\n // reflects real wall-clock time. No-op when observer is undefined.\n const spanId = emitToolchainOpen(\n observer,\n parentSpanId,\n toolchainId,\n checkType,\n [],\n componentId,\n );\n\n let result: ToolchainCheckResult;\n\n // Drift fast path via manifest\n const fastResult =\n checkType === \"drift\" && options.artifactsPath\n ? await tryManifestFastPath(toolchainId, cwd)\n : null;\n\n if (fastResult) {\n fastResult.action = action;\n result = fastResult;\n } else {\n try {\n const { exitCode, stderr } = await executeCheck(command, cwd, observabilityIds);\n const durationMs = Math.round(performance.now() - start);\n result = {\n toolchainId,\n checkType,\n status: exitCode === 0 ? \"pass\" : \"fail\",\n action,\n message: exitCode === 0 ? undefined : stderr.trim() || `exit code ${exitCode}`,\n durationMs,\n };\n } catch (err) {\n const durationMs = Math.round(performance.now() - start);\n result = {\n toolchainId,\n checkType,\n status: \"error\",\n action,\n message: (err as Error).message,\n durationMs,\n };\n }\n }\n\n results.push(result);\n\n // ── toolchain.execution close ───────────────────────────────────────\n // Status is derived from the check result: pass → success, otherwise\n // failure (carrying the message). The action (\"block\"/\"warn\"/\"shadow\")\n // is recorded as data only and never gates the workflow here.\n emitToolchainClose(\n observer,\n spanId ?? \"\",\n toolchainId,\n checkType,\n result.durationMs ?? Math.round(performance.now() - start),\n result.status === \"pass\" ? \"success\" : \"failure\",\n result.status === \"pass\" ? undefined : result.message,\n );\n }\n }\n\n return results;\n}\n","/**\n * Virtual workflow entry step — materializes WorkflowInvocation input as a\n * DAG-addressable output so downstream steps can use depends_on / receives.\n */\n\n/** Step id referenced in workflow DSL depends_on / receives.from. */\nexport const WORKFLOW_INPUT_STEP_ID = \"workflow-input\";\n\nexport interface WorkflowInputHandoff {\n readonly type: string;\n readonly version?: number;\n readonly payload: unknown;\n}\n\nexport interface WorkflowInputOutput {\n readonly user_request: string;\n readonly handoff?: WorkflowInputHandoff;\n}\n\nexport function buildWorkflowInputOutput(\n userRequest: string,\n handoff?: WorkflowInputHandoff,\n): WorkflowInputOutput {\n return {\n user_request: userRequest,\n ...(handoff\n ? {\n handoff: {\n type: handoff.type,\n ...(handoff.version !== undefined ? { version: handoff.version } : {}),\n payload: handoff.payload,\n },\n }\n : {}),\n };\n}\n\nexport function stepDependsOnWorkflowInput(\n dependsOn: readonly string[] | undefined,\n): boolean {\n return dependsOn?.includes(WORKFLOW_INPUT_STEP_ID) ?? false;\n}\n\nexport function formatWorkflowInputContext(output: WorkflowInputOutput): string {\n return `\\n\\n--- Step: ${WORKFLOW_INPUT_STEP_ID} ---\\n${JSON.stringify(output, null, 2)}`;\n}\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike, type TokenUsage } from \"./task-runner.js\";\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport type { ModelClass, ResolvedModel } from \"./model-resolver.js\";\nimport type { z } from \"zod\";\nimport {\n createExecutionEnvelope,\n emitSessionOpen,\n emitSessionClose,\n emitIterationOpen,\n emitIterationClose,\n emitIterationMetric,\n type ObserverEmitFn,\n} from \"./observability-bridge.js\";\nimport { computeCostUsd } from \"./model-pricing.js\";\nimport { runToolchainChecks, type RunToolchainChecksOptions } from \"./toolchain-checker.js\";\nimport {\n WORKFLOW_INPUT_STEP_ID,\n buildWorkflowInputOutput,\n formatWorkflowInputContext,\n stepDependsOnWorkflowInput,\n type WorkflowInputOutput,\n} from \"./workflow-input.js\";\n\nexport type { ObserverEmitFn } from \"./observability-bridge.js\";\n\n// ---------------------------------------------------------------------------\n// Adapter factory — enables true parallelism with stateful adapters\n// ---------------------------------------------------------------------------\n\n/**\n * A factory that creates independent SdkAdapter instances.\n * Used by runWorkflow to allocate one adapter per parallel step,\n * avoiding session-level serialization in stateful SDK adapters.\n */\nexport type SdkAdapterFactory = () => SdkAdapter;\n\n/**\n * Model-aware adapter factory. Accepts a model_class and returns an adapter\n * configured for that capability level (possibly a different provider/model).\n */\nexport type ModelAwareSdkAdapterFactory = (\n modelClass?: ModelClass,\n /**\n * Agent the step runs as (a task's `target_agent`). Guardrail hooks are fixed at\n * adapter construction, so an agent-scoped factory returns a distinct adapter per\n * agent (#269). Ignored by factories that do not scope guardrails.\n */\n agentId?: string,\n) => SdkAdapter | Promise<SdkAdapter>;\n\n/** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */\nexport type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;\n\nfunction isAdapterFactory(v: AdapterOrFactory): v is SdkAdapterFactory | ModelAwareSdkAdapterFactory {\n return typeof v === \"function\" && !(\"send\" in v);\n}\n\nfunction resolveAdapter(adapterOrFactory: AdapterOrFactory): { adapter: SdkAdapter; factory: (SdkAdapterFactory | ModelAwareSdkAdapterFactory) | undefined } {\n if (isAdapterFactory(adapterOrFactory)) {\n const result = adapterOrFactory();\n if (result && typeof (result as Promise<SdkAdapter>).then === \"function\") {\n throw new Error(\"ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.\");\n }\n return { adapter: result as SdkAdapter, factory: adapterOrFactory };\n }\n return { adapter: adapterOrFactory, factory: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\n/** Specification for what a step receives from a dependency. */\nexport interface ReceiveSpec {\n /** The task id of the dependency step to receive from. If omitted, alias is used as task id. */\n readonly from?: string;\n /** JSONPath-like dotted path to extract from the step result (e.g. \"$.changed_files\"). Simplified: just use dot notation like \"changed_files\" or \"checks_performed\". If omitted, entire result is received. */\n readonly path?: string;\n}\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly depends_on?: readonly string[];\n readonly instruction?: string;\n readonly receives?: Record<string, ReceiveSpec>;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n readonly depends_on?: readonly string[];\n}\n\n/**\n * Evaluate step — runs a task that returns a convergence-envelope, then either\n * proceeds (verdict=pass) or loops back to `loop_to` with feedback injected\n * (verdict=fail, iteration < max_iterations), or applies `on_exhausted`.\n */\nexport interface EvaluateStep {\n readonly type: \"evaluate\";\n readonly task: string;\n readonly from_agent: string;\n readonly evaluator_agent?: string;\n readonly description?: string;\n readonly loop_to: string;\n readonly max_iterations: number;\n readonly inject_as?: string;\n readonly on_exhausted?: \"abort\" | \"fail_partial\" | \"escalate\";\n readonly depends_on?: readonly string[];\n}\n\n/**\n * Payload returned by an evaluate task in a convergence-envelope handoff.\n * The runtime reads `verdict` to decide whether to proceed or loop back.\n */\nexport interface ConvergenceEnvelopePayload {\n /** \"pass\" means quality gate passed; \"fail\" triggers a loop-back. */\n readonly verdict: \"pass\" | \"fail\";\n /** Human-readable feedback injected into the next iteration via `inject_as`. */\n readonly feedback?: string;\n}\n\n/** Typed handoff envelope produced by an evaluate task. */\nexport type ConvergenceEnvelope = HandoffInput<\"convergence-envelope\", ConvergenceEnvelopePayload>;\n\nexport type WorkflowStep = DelegateStep | GateStep | EvaluateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n /** Variables propagated to every TaskContext in the workflow (from WorkflowInvocation.context). */\n variables?: Record<string, unknown>;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n /**\n * Writable stream for real-time progress output during agent execution.\n * Intermediate events from adapters are formatted and written here.\n * Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n /**\n * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Optional toolchain-check observation config. When set together with `observer`,\n * runWorkflow runs the configured toolchain checks AFTER the workflow body (a\n * single post-run observation pass) and emits one toolchain.execution span per\n * check, correlated to this run's agent.session span.\n *\n * OBSERVATION ONLY (non-destructive): the checks never alter the WorkflowResult\n * — a failing check does not fail the workflow. `observer` and `parentSpanId`\n * are injected by runWorkflow; callers supply `toolchainsPath` (+ optional\n * artifactsPath/cwd/policy actions).\n */\n toolchain?: RunToolchainChecksOptions;\n /**\n * In-process library tools to register with every task in this workflow.\n * Passed through to each runTask() call. Adapters convert these to their\n * native tool format (Claude MCP, OpenAI function tools, ADK tools).\n */\n libraryTools?: LibraryToolRegistry;\n /**\n * Each agent's effective tool grant — the executing component's\n * `ComponentScope.toolsByAgent` (#338). Passed through to each runTask()\n * call, which is where an agent's candidate tool list is built.\n */\n toolsByAgent?: Map<string, string[]>;\n /**\n * Resolves adapter + model for execution envelopes (agent.session / agent.subagent).\n * When undefined, envelopes omit adapter/model (observer spans lack gen_ai attrs).\n */\n resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;\n /**\n * Request each step's adapter from the factory scoped to the step's agent, so\n * per-agent guardrails apply to the agent actually doing the work (#269). Set\n * by executeWorkflow when the run has ANY guardrail to enforce — the rules a\n * binding resolved per agent, or the process's plugin guardrails, which are\n * the same for every agent yet reach a step's adapter only through this\n * scoping (#332). Without it, adapters are shared exactly as before.\n */\n perAgentAdapters?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (openaiThreadId,\n * sessionId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n /**\n * Writable stream for real-time progress output during agent execution.\n * Intermediate events from adapters are formatted and written here.\n * Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n\n /**\n * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Optional toolchain-check observation config (see WorkflowRunOptions.toolchain).\n * OBSERVATION ONLY — never changes the workflow outcome.\n */\n toolchain?: RunToolchainChecksOptions;\n /**\n * In-process library tools to register with every task in this workflow.\n * Created once per execution and shared across all steps.\n */\n libraryTools?: LibraryToolRegistry;\n /** See WorkflowRunOptions.toolsByAgent (#338). Injected by executeWorkflow. */\n toolsByAgent?: Map<string, string[]>;\n /**\n * Resolves adapter + model for execution envelopes. Injected by executeWorkflow;\n * not typically set by external callers.\n */\n resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;\n /** See WorkflowRunOptions.perAgentAdapters (#269). Injected by executeWorkflow. */\n perAgentAdapters?: boolean;\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n /** Resolved model_class for delegate/evaluate steps (from task registry). */\n model_class?: ModelClass;\n /** Concrete adapter name used for this step's LLM calls. */\n adapter?: string;\n /** Concrete model name used for this step's LLM calls. */\n model?: string;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\" | \"evaluate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n const ctx = invocation.context;\n const variables: Record<string, unknown> = { ...ctx?.variables };\n if (ctx?.cwd) variables.cwd = ctx.cwd;\n if (ctx?.environment) variables.environment = ctx.environment;\n if (ctx?.artifacts) variables.artifacts = ctx.artifacts;\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n variables: Object.keys(variables).length > 0 ? variables : undefined,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n progressOutput: invocation.progressOutput,\n observer: invocation.observer,\n toolchain: invocation.toolchain,\n libraryTools: invocation.libraryTools,\n toolsByAgent: invocation.toolsByAgent,\n resolveModelMeta: invocation.resolveModelMeta,\n perAgentAdapters: invocation.perAgentAdapters,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: AdapterOrFactory,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: AdapterOrFactory,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapterOrFactory: AdapterOrFactory,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(adapterOrFactory);\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n // ── ExecutionEnvelope + agent.session open (Phase 1-1, 1-3) ────────────────\n // Create a standard envelope for this workflow session. run_id is a UUIDv7.\n // The sessionSpanId is used as parentSpanId for child agent.subagent spans.\n // Resolve session-open meta as the \"standard\" model class (NOT undefined).\n // resolve(undefined) short-circuits to the bare fallback and never consults\n // env / model_mapping, so the open span dropped gen_ai.request.model (and\n // gen_ai.system) whenever fallbackModel was unset (e.g. --adapter mock / no\n // --model). Using \"standard\" mirrors how subagent spans resolve their meta\n // (workflow-runner passes the step's model_class), keeping the session open\n // span's model/adapter consistent with the standard model_mapping entry. (#166)\n const sessionMeta = options.resolveModelMeta?.(\"standard\");\n const sessionEnvelope = createExecutionEnvelope({\n componentId: workflowId,\n adapter: sessionMeta?.adapter,\n model: sessionMeta?.model,\n });\n const sessionSpanId = emitSessionOpen(options.observer, sessionEnvelope, workflowId);\n\n const workflowStart = Date.now();\n\n // ── Exception-safe session lifecycle ───────────────────────────────────────\n // The workflow body can throw (e.g. an invalid depends_on graph) AFTER the\n // agent.session open span has been emitted. Wrap the body in try/finally so\n // the close span is ALWAYS emitted — on success, on a returned failure\n // (escalated/error) AND on a thrown exception — leaving no span stuck 'open'.\n // (The body retains its original indentation; only the try/finally frame is new.)\n let wfResult: WorkflowResult | undefined;\n let sessionError: Error | undefined;\n\n // Token usage accumulation across all steps (declared outside try so finally can read)\n const tokenAccumulator: TokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n let hasTokenData = false;\n\n try {\n\n // Build step identity map: step index → task ID (delegate) or gate_kind (gate)\n const stepId = (i: number): string => {\n const s = workflow.steps[i];\n if (s.type === \"delegate\" || s.type === \"evaluate\") return s.task;\n return `gate:${s.gate_kind}`;\n };\n\n // Resolve depends_on: if specified (even as empty array) use it, otherwise depend on all preceding steps.\n // WORKFLOW_INPUT_STEP_ID is a virtual entry node — always satisfied, not a workflow step index.\n const workflowInputOutput: WorkflowInputOutput = buildWorkflowInputOutput(\n options.user_request,\n invocationHandoff,\n );\n\n const depsByIndex: number[][] = workflow.steps.map((step, i) => {\n if (step.depends_on !== undefined) {\n return step.depends_on\n .filter((dep) => dep !== WORKFLOW_INPUT_STEP_ID)\n .map((dep) => {\n const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);\n if (idx === -1) {\n throw new Error(`depends_on \"${dep}\" in step ${i} (${stepId(i)}) not found among preceding steps`);\n }\n return idx;\n });\n }\n // Default: depend on all preceding steps (preserves sequential behaviour)\n return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);\n });\n\n // DAG scheduler state\n const completed = new Set<number>();\n const stepResults: StepResult[] = new Array(workflow.steps.length);\n const stepContexts: string[] = new Array(workflow.steps.length).fill(\"\");\n const stepOutputs: Array<unknown> = new Array(workflow.steps.length).fill(undefined);\n let abortResult: WorkflowResult | undefined;\n\n // Evaluate-step loop state\n /** Tracks how many times each evaluate step (by index) has executed so far. */\n const evaluateExecCount = new Map<number, number>();\n /** Tracks the current iteration span ID per evaluate step index. */\n const iterationSpanIds = new Map<number, string>();\n /**\n * Variables injected by evaluate steps via `inject_as`.\n * Merged into every subsequent step's TaskContext.variables on loop-back.\n */\n const loopInjectedVars: Record<string, unknown> = {};\n\n /** Extract a dotted path from a structured object. */\n function extractPath(obj: unknown, path: string): unknown {\n const cleanPath = path.startsWith(\"$.\") ? path.slice(2) : path;\n const segments = cleanPath.split(\".\");\n let current: unknown = obj;\n for (const seg of segments) {\n if (current == null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[seg];\n }\n return current;\n }\n\n /** Build typed handoff input from receives declarations. */\n function projectHandoffs(\n stepIndex: number,\n step: DelegateStep,\n ): Record<string, unknown> | undefined {\n if (!step.receives) return undefined;\n\n const projected: Record<string, unknown> = {};\n\n for (const [alias, spec] of Object.entries(step.receives)) {\n const fromTaskId = spec.from ?? alias;\n\n if (fromTaskId === WORKFLOW_INPUT_STEP_ID) {\n if (spec.path) {\n projected[alias] = extractPath(workflowInputOutput, spec.path);\n } else {\n projected[alias] = workflowInputOutput;\n }\n continue;\n }\n\n const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);\n if (depIdx === -1) continue;\n\n const output = stepOutputs[depIdx];\n if (output === undefined) continue;\n\n if (spec.path) {\n projected[alias] = extractPath(output, spec.path);\n } else {\n projected[alias] = output;\n }\n }\n\n return Object.keys(projected).length > 0 ? projected : undefined;\n }\n\n /** Build accumulated context for a step from its dependency chain. */\n function contextFor(stepIndex: number): string {\n const step = workflow.steps[stepIndex];\n const parts: string[] = [];\n\n if (stepDependsOnWorkflowInput(step.depends_on)) {\n parts.push(formatWorkflowInputContext(workflowInputOutput));\n }\n\n const deps = depsByIndex[stepIndex];\n if (deps.length > 0) {\n parts.push(\n ...deps\n .filter((d) => completed.has(d))\n .map((d) => stepContexts[d])\n .filter(Boolean),\n );\n }\n\n return parts.join(\"\");\n }\n\n type StepResultWithTokens = StepResult & { tokenUsage?: TokenUsage };\n\n function stepModelFields(\n modelClass: ModelClass | undefined,\n envelopeMeta?: ResolvedModel,\n ): Pick<StepResult, \"model_class\" | \"adapter\" | \"model\"> {\n if (!modelClass && !envelopeMeta) return {};\n return {\n ...(modelClass ? { model_class: modelClass } : {}),\n ...(envelopeMeta?.adapter ? { adapter: envelopeMeta.adapter } : {}),\n ...(envelopeMeta?.model ? { model: envelopeMeta.model } : {}),\n };\n }\n\n /** Execute a single step (delegate or gate). */\n async function executeStep(\n i: number,\n stepAdapter: SdkAdapter,\n envelopeMeta?: ResolvedModel,\n modelClass?: ModelClass,\n ): Promise<StepResultWithTokens> {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);\n }\n\n // ── Evaluate step ────────────────────────────────────────────────────────\n if (step.type === \"evaluate\") {\n const evaluateStep = step as EvaluateStep;\n const iterationNumber = (evaluateExecCount.get(i) ?? 0) + 1;\n const iterationSpanId = emitIterationOpen(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n evaluateStep.loop_to,\n iterationNumber,\n evaluateStep.max_iterations,\n );\n if (iterationSpanId) {\n iterationSpanIds.set(i, iterationSpanId);\n }\n // Merge workflow variables with any loop-injected feedback variables\n const effectiveVariables = mergeVariables(options.variables, loopInjectedVars);\n const context: TaskContext = {\n user_request: evaluateStep.description ?? options.user_request,\n prior_context: contextFor(i),\n ...(effectiveVariables ? { variables: effectiveVariables } : {}),\n };\n const taskResult: TaskRunResult = await runTask(stepAdapter, evaluateStep.task, context, {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: 0, // evaluate steps do not retry\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n progressOutput: options.progressOutput,\n observer: options.observer,\n parentSpanId: iterationSpanId ?? sessionSpanId,\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n libraryTools: options.libraryTools,\n toolsByAgent: options.toolsByAgent,\n envelopeAdapter: envelopeMeta?.adapter,\n envelopeModel: envelopeMeta?.model,\n });\n return {\n step_index: i,\n task_id: evaluateStep.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n tokenUsage: taskResult.tokenUsage,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n\n const delegateStep = step as DelegateStep;\n\n // Optional steps\n if (step.optional) {\n const stepUserRequest = delegateStep.instruction ?? options.user_request;\n // Merge workflow variables with any loop-injected feedback variables\n const ctxVars = mergeVariables(options.variables, loopInjectedVars);\n const ctx: TaskContext = {\n user_request: stepUserRequest,\n prior_context: contextFor(i),\n ...(ctxVars ? { variables: ctxVars } : {}),\n };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n return {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n }\n\n // Execute task with followUp/retry recovery\n const stepUserRequest = delegateStep.instruction ?? options.user_request;\n\n let handoffInput: TaskContext[\"handoff_input\"] | undefined;\n const projected = projectHandoffs(i, delegateStep);\n if (projected) {\n handoffInput = {\n type: \"step-projection\",\n payload: projected,\n };\n } else if (i === 0 && invocationHandoff) {\n handoffInput = invocationHandoff;\n }\n\n const useLegacyContext = !delegateStep.receives;\n // Merge workflow variables with any loop-injected feedback variables\n const delegateVars = mergeVariables(options.variables, loopInjectedVars);\n\n const context: TaskContext = {\n user_request: stepUserRequest,\n ...(useLegacyContext ? { prior_context: contextFor(i) } : {}),\n ...(delegateVars ? { variables: delegateVars } : {}),\n ...(handoffInput ? { handoff_input: handoffInput } : {}),\n };\n const taskResult: TaskRunResult = await runTask(stepAdapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n progressOutput: options.progressOutput,\n observer: options.observer,\n parentSpanId: sessionSpanId,\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n libraryTools: options.libraryTools,\n toolsByAgent: options.toolsByAgent,\n envelopeAdapter: envelopeMeta?.adapter,\n envelopeModel: envelopeMeta?.model,\n });\n return {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n tokenUsage: taskResult.tokenUsage,\n ...stepModelFields(modelClass, envelopeMeta),\n };\n }\n\n // DAG execution loop: on each iteration, find all steps whose deps are satisfied\n // and run them concurrently.\n while (completed.size < workflow.steps.length) {\n const ready: number[] = [];\n for (let i = 0; i < workflow.steps.length; i++) {\n if (completed.has(i)) continue;\n if (depsByIndex[i].every((d) => completed.has(d))) {\n ready.push(i);\n }\n }\n\n if (ready.length === 0) {\n // Should not happen with valid DAG; safeguard against cycles\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: \"Dependency cycle detected: no steps are ready to execute\",\n };\n break;\n }\n\n const batchResults = await Promise.all(ready.map(async (i) => {\n const step = workflow.steps[i];\n const stepTask = (step.type === \"delegate\" || step.type === \"evaluate\")\n ? registries?.taskRegistry?.[step.task]\n : undefined;\n const modelClass = stepTask?.model_class as ModelClass | undefined;\n // The agent doing the work — the same one executeTask scopes guardrails to.\n const stepAgentId = options.perAgentAdapters ? stepTask?.target_agent : undefined;\n\n let stepAdapter: SdkAdapter;\n if (adapterFactory && (ready.length > 1 || modelClass || stepAgentId)) {\n const result = adapterFactory(modelClass, stepAgentId);\n stepAdapter = (result && typeof (result as Promise<SdkAdapter>).then === \"function\")\n ? await (result as Promise<SdkAdapter>)\n : result as SdkAdapter;\n } else {\n stepAdapter = primaryAdapter;\n }\n const envelopeMeta = options.resolveModelMeta?.(modelClass);\n return executeStep(i, stepAdapter, envelopeMeta, modelClass);\n }));\n\n for (let b = 0; b < ready.length; b++) {\n const i = ready[b];\n const result = batchResults[b];\n const step = workflow.steps[i];\n\n // Accumulate token usage from this step\n if (result.tokenUsage) {\n tokenAccumulator.inputTokens += result.tokenUsage.inputTokens;\n tokenAccumulator.outputTokens += result.tokenUsage.outputTokens;\n tokenAccumulator.totalTokens = (tokenAccumulator.totalTokens ?? 0) + (result.tokenUsage.totalTokens ?? 0);\n if (result.tokenUsage.cacheReadTokens) {\n tokenAccumulator.cacheReadTokens = (tokenAccumulator.cacheReadTokens ?? 0) + result.tokenUsage.cacheReadTokens;\n }\n if (result.tokenUsage.cacheCreationTokens) {\n tokenAccumulator.cacheCreationTokens = (tokenAccumulator.cacheCreationTokens ?? 0) + result.tokenUsage.cacheCreationTokens;\n }\n hasTokenData = true;\n }\n\n // ── Evaluate step post-processing ─────────────────────────────────────\n if (step.type === \"evaluate\") {\n const evaluateStep = step as EvaluateStep;\n\n // Extract verdict from the evaluate task's structured output\n const data = result.outcome.status === \"success\"\n ? (result.outcome as { status: \"success\"; data: unknown }).data as Record<string, unknown>\n : undefined;\n const verdict = (typeof data?.verdict === \"string\" ? data.verdict : \"fail\") as string;\n\n const execCount = (evaluateExecCount.get(i) ?? 0) + 1;\n\n // Close iteration span for this execution\n const currentIterationSpanId = iterationSpanIds.get(i);\n if (currentIterationSpanId) {\n const willLoopBack = verdict !== \"pass\" && execCount < evaluateStep.max_iterations;\n const feedbackInjected = willLoopBack && !!evaluateStep.inject_as;\n emitIterationClose(\n options.observer,\n currentIterationSpanId,\n evaluateStep.task,\n execCount,\n verdict,\n result.elapsed_ms,\n feedbackInjected,\n );\n iterationSpanIds.delete(i);\n }\n\n if (verdict === \"pass\") {\n // Quality gate passed — record result and proceed\n emitIterationMetric(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n execCount,\n \"pass\",\n );\n stepResults[i] = result;\n completed.add(i);\n emitStepEvent(options, workflow.id, i, step, result);\n if (data !== undefined) {\n stepOutputs[i] = data;\n stepContexts[i] = `\\n\\n--- Step ${i + 1}: ${stepId(i)} ---\\n${JSON.stringify(data, null, 2)}`;\n }\n } else if (execCount < evaluateStep.max_iterations) {\n // Quality gate failed but iterations remain — inject feedback and loop back\n evaluateExecCount.set(i, execCount);\n\n if (evaluateStep.inject_as) {\n const feedback = typeof data?.feedback === \"string\"\n ? data.feedback\n : (data !== undefined ? JSON.stringify(data) : \"Evaluate step returned no feedback\");\n loopInjectedVars[evaluateStep.inject_as] = feedback;\n }\n\n // Find the loop_to step (must precede this evaluate step)\n const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);\n if (loopToIdx === -1) {\n stepResults[i] = result;\n completed.add(i);\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: `Evaluate step \"${evaluateStep.task}\" references unknown loop_to \"${evaluateStep.loop_to}\"`,\n };\n } else {\n // Reset all steps in the loop range [loopToIdx, i] so they re-execute\n for (let k = loopToIdx; k <= i; k++) {\n completed.delete(k);\n stepOutputs[k] = undefined;\n stepContexts[k] = \"\";\n }\n // Evaluate step result is intermediate — do not persist it\n }\n } else {\n // Max iterations exhausted — apply on_exhausted policy\n evaluateExecCount.set(i, execCount);\n stepResults[i] = result;\n completed.add(i);\n\n const exhaustedPolicy = evaluateStep.on_exhausted ?? \"escalate\";\n emitIterationMetric(\n options.observer,\n sessionSpanId,\n evaluateStep.task,\n execCount,\n `exhausted-${exhaustedPolicy}`,\n );\n\n switch (exhaustedPolicy) {\n case \"abort\":\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: `Evaluate step \"${evaluateStep.task}\" exhausted ${evaluateStep.max_iterations} iterations without passing`,\n };\n break;\n case \"fail_partial\":\n // Degraded success — continue workflow without evaluate outputs\n emitStepEvent(options, workflow.id, i, step, result);\n break;\n case \"escalate\":\n default:\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Evaluate step \"${evaluateStep.task}\" exhausted ${evaluateStep.max_iterations} iterations without passing`,\n };\n break;\n }\n }\n continue; // Skip generic post-processing below\n }\n\n // ── Generic delegate / gate post-processing ───────────────────────────\n stepResults[i] = result;\n completed.add(i);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Store context fragment and structured output for dependants\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n stepOutputs[i] = data;\n stepContexts[i] = `\\n\\n--- Step ${i + 1}: ${stepId(i)} ---\\n` +\n (typeof data === \"string\" ? data : JSON.stringify(data, null, 2));\n }\n\n // Abort-worthy outcomes\n if (result.outcome.status === \"gate_rejected\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n };\n } else if (result.outcome.status === \"escalation\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n } else if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const taskId = step.type === \"delegate\" ? step.task : (step as GateStep).gate_kind;\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${taskId}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n }\n }\n\n if (abortResult) break;\n }\n\n wfResult = abortResult ?? {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n\n // ── toolchain.execution observation pass (post-run, non-destructive) ───────\n // Integration point: a single observation pass AFTER the workflow body, rather\n // than per-step. Rationale — toolchain checks (lint/format/drift) inspect the\n // artifacts a run produced, so the natural correlation is the run as a whole;\n // running once post-body keeps the spans children of the still-open session and\n // avoids coupling toolchain config to individual step semantics. The observer\n // and parent span are injected here so checks emit toolchain.execution spans\n // correlated to this session. Wrapped in its own try/catch so a toolchain or\n // subprocess failure can NEVER change the workflow outcome (observation only).\n if (options.toolchain && options.observer) {\n try {\n await runToolchainChecks({\n ...options.toolchain,\n observer: options.observer,\n parentSpanId: sessionSpanId,\n // Propagate session correlation to any git spawned by a check (#115):\n // the session id is the agent.session run_id (== sessionSpanId).\n observabilityIds: {\n sessionId: sessionSpanId ?? sessionEnvelope.run_id,\n runId: sessionEnvelope.run_id,\n },\n });\n } catch {\n // Observation must never affect the workflow result — swallow.\n }\n }\n\n return wfResult;\n } catch (err) {\n sessionError = err as Error;\n throw err;\n } finally {\n // ── agent.session close (Phase 1-3) ──────────────────────────────────────\n // Emit close span for the workflow session on EVERY exit path. No-op when\n // observer is undefined. On a thrown exception wfResult is undefined → the\n // status is recorded as 'error' with the cause in `agent.error`.\n if (sessionSpanId) {\n const durationMs = wfResult?.total_elapsed_ms ?? (Date.now() - workflowStart);\n sessionEnvelope.execution_metadata = {\n duration_ms: durationMs,\n ...(hasTokenData ? {\n token_usage: {\n input_tokens: tokenAccumulator.inputTokens,\n output_tokens: tokenAccumulator.outputTokens,\n total_tokens: tokenAccumulator.totalTokens ?? (tokenAccumulator.inputTokens + tokenAccumulator.outputTokens),\n ...(tokenAccumulator.cacheReadTokens ? { cache_read_input_tokens: tokenAccumulator.cacheReadTokens } : {}),\n ...(tokenAccumulator.cacheCreationTokens ? { cache_creation_input_tokens: tokenAccumulator.cacheCreationTokens } : {}),\n },\n } : {}),\n };\n if (hasTokenData) {\n const costUsd = computeCostUsd(\n sessionEnvelope.model,\n tokenAccumulator.inputTokens,\n tokenAccumulator.outputTokens,\n );\n if (costUsd !== undefined) {\n sessionEnvelope.execution_metadata = {\n ...sessionEnvelope.execution_metadata,\n cost_usd: costUsd,\n };\n }\n }\n emitSessionClose(\n options.observer,\n sessionSpanId,\n sessionEnvelope,\n durationMs,\n wfResult?.status ?? \"error\",\n sessionError?.message,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Merge base variables with injected loop variables.\n * Returns undefined when the merged result is empty (avoids adding an empty\n * `variables: {}` to TaskContext which would be misleading).\n */\nfunction mergeVariables(\n base: Record<string, unknown> | undefined,\n injected: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged = { ...base, ...injected };\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n adapter?: SdkAdapter,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (options.onGate) {\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n // LLM-based gate evaluation using the description as the condition\n if (adapter && step.description) {\n const approved = await evaluateGateWithLlm(adapter, step, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n // Fallback: no onGate, no adapter or no description — auto-approve with warning\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\n/**\n * Use the LLM adapter to evaluate a gate condition.\n * Sends a lightweight prompt with the gate description and prior step outcomes,\n * expecting a JSON response with { \"approved\": boolean, \"reason\": string }.\n */\nasync function evaluateGateWithLlm(\n adapter: SdkAdapter,\n step: GateStep,\n priorResults: StepResult[],\n): Promise<boolean> {\n const priorContext = priorResults\n .map((r) => {\n const id = r.task_id ?? r.gate_kind ?? `step_${r.step_index}`;\n const data = \"data\" in r.outcome ? (r.outcome as { data: unknown }).data : undefined;\n return `- ${id}: status=${r.outcome.status}${data ? `, data=${typeof data === \"string\" ? data : JSON.stringify(data)}` : \"\"}`;\n })\n .join(\"\\n\");\n\n const prompt = buildGateEvaluationPrompt(step, priorContext);\n\n try {\n const response = await adapter.send(prompt, { readonly: true });\n return parseGateEvaluationResponse(response);\n } catch {\n // On LLM failure, reject the gate (fail-closed)\n return false;\n }\n}\n\nexport function buildGateEvaluationPrompt(step: GateStep, priorContext: string): string {\n return `You are a gate evaluator in a workflow pipeline. Your job is to decide whether the workflow should proceed based on prior step results.\n\n## Gate\n- kind: ${step.gate_kind}\n- condition: ${step.description}\n\n## Prior Step Results\n${priorContext || \"(no prior results)\"}\n\n## Instructions\nEvaluate whether the gate condition is satisfied based on the prior step results.\nRespond with ONLY a JSON object (no markdown fences, no extra text):\n\n{\"approved\": true, \"reason\": \"brief explanation\"}\n\nor\n\n{\"approved\": false, \"reason\": \"brief explanation\"}`;\n}\n\nexport function parseGateEvaluationResponse(response: string): boolean {\n // Try to extract JSON from the response\n const jsonMatch = response.match(/\\{[\\s\\S]*?\"approved\"\\s*:\\s*(true|false)[\\s\\S]*?\\}/);\n if (jsonMatch) {\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n return parsed.approved === true;\n } catch {\n // fall through\n }\n }\n\n // Heuristic fallback: look for explicit approval/rejection keywords\n const lower = response.toLowerCase();\n if (lower.includes('\"approved\": true') || lower.includes('\"approved\":true')) {\n return true;\n }\n if (lower.includes('\"approved\": false') || lower.includes('\"approved\":false')) {\n return false;\n }\n\n // Fail-closed: if we can't parse, reject\n return false;\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: WorkflowStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n /** Set progress output sink for real-time execution visibility. */\n progressOutput(sink: { write(chunk: string): unknown }): this {\n this.invocation = { ...this.invocation, progressOutput: sink };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — registers the plugin modules a project manifest declares.\n *\n * Discovery is the manifest and nothing else: `plugins:` in `project.yaml`\n * lists the modules to load, and `createProjectRuntime` calls this once while\n * building the runtime. Each path is dynamically import()'d and every export\n * satisfying the AgentPlugin interface (an `id` string property) is registered\n * with the pluginRegistry singleton, which the task runner, the workflow runner\n * and `execute.ts` read at execution time. All three are in THIS process; the\n * guardrail evaluator itself holds no reference to the registry, because it is\n * shared with hook-bin processes this loader never runs in (#331).\n *\n * A declared path that cannot be loaded throws: a plugin the manifest asks for\n * and the runtime silently skips is indistinguishable from one that ran.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n /** Number of AgentPlugin exports registered across all loaded modules. */\n loaded: number;\n /** Absolute paths of the modules that were imported. */\n files: string[];\n}\n\n/**\n * Load and register every plugin module the project manifest declares.\n * `paths` are manifest-relative; `baseDir` is the manifest's directory.\n */\nexport async function loadPlugins(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n throw new Error(\n `Plugin not found: ${absPath} (declared by the project manifest's \\`plugins:\\`).`,\n );\n }\n\n try {\n result.loaded += await loadPluginModule(absPath);\n result.files.push(absPath);\n } catch (err) {\n throw new Error(\n `Failed to load plugin ${absPath} (declared by the project manifest's ` +\n `\\`plugins:\\`): ${(err as Error).message}`,\n );\n }\n }\n\n return result;\n}\n","/**\n * ModelResolver — resolves a model_class to a concrete adapter + model pair.\n *\n * Resolution priority (highest wins):\n * 1. AGENT_RUNTIME_MODEL_<CLASS> env var (class name upper-cased)\n * 2. AGENT_RUNTIME_MODEL env var (catch-all fallback)\n * 3. project.yaml model_mapping.<class>\n * 4. CLI --adapter + adapter default model\n */\n\nimport type { ModelClass, ProjectModelMapping } from \"@aaac/contracts\";\n\n/**\n * The model-class vocabulary, declared by @aaac/contracts as the key set of the\n * `model_mapping` section — restating it here is what let a class exist in the\n * manifest that no runtime path could see.\n */\nexport type { ModelClass };\n\nexport interface ResolvedModel {\n adapter: string;\n model?: string;\n}\n\nexport interface ModelResolver {\n resolve(modelClass: ModelClass | undefined): ResolvedModel;\n}\n\n/**\n * The `model_mapping` section this resolver reads, as declared by\n * @aaac/contracts — restating its shape here is what forced every caller to\n * bridge the two with an `as`.\n */\nexport type ModelMappingConfig = ProjectModelMapping;\n\nexport interface ModelResolverOptions {\n modelMapping?: ModelMappingConfig;\n fallbackAdapter: string;\n fallbackModel?: string;\n env?: Record<string, string | undefined>;\n /**\n * When set, always use this adapter name. Model is still resolved per class\n * from mapping / env (e.g. CLI `--adapter mock` with project model_mapping).\n */\n pinnedAdapter?: string;\n}\n\nconst ENV_PREFIX = \"AGENT_RUNTIME_MODEL\";\n\n/** The per-class env override for {@link modelClass}, e.g. `..._THINKING`. */\nfunction classEnvKey(modelClass: ModelClass): string {\n return `${ENV_PREFIX}_${modelClass.toUpperCase()}`;\n}\n\n/**\n * Parse an \"adapter:model\" string.\n * - \"claude:claude-sonnet-4-20250514\" → { adapter: \"claude\", model: \"claude-sonnet-4-20250514\" }\n * - \"claude:\" → { adapter: \"claude\" }\n * - \"claude-sonnet-4-20250514\" (no colon) → { model: \"claude-sonnet-4-20250514\" } (adapter from fallback)\n */\nfunction parseEnvValue(\n value: string,\n fallbackAdapter: string,\n): ResolvedModel {\n const colonIdx = value.indexOf(\":\");\n if (colonIdx === -1) {\n return { adapter: fallbackAdapter, model: value || undefined };\n }\n const adapter = value.slice(0, colonIdx) || fallbackAdapter;\n const model = value.slice(colonIdx + 1) || undefined;\n return { adapter, model };\n}\n\nexport function createModelResolver(\n options: ModelResolverOptions,\n): ModelResolver {\n const env = options.env ?? process.env;\n\n return {\n resolve(modelClass: ModelClass | undefined): ResolvedModel {\n const fallback: ResolvedModel = {\n adapter: options.pinnedAdapter ?? options.fallbackAdapter,\n model: options.fallbackModel,\n };\n\n if (!modelClass) return fallback;\n\n // 1. Class-specific env var\n const classEnv = env[classEnvKey(modelClass)];\n if (classEnv) {\n const parsed = parseEnvValue(classEnv, options.fallbackAdapter);\n return options.pinnedAdapter\n ? { adapter: options.pinnedAdapter, model: parsed.model }\n : parsed;\n }\n\n // 2. Catch-all env var\n const catchAllEnv = env[ENV_PREFIX];\n if (catchAllEnv) {\n const parsed = parseEnvValue(catchAllEnv, options.fallbackAdapter);\n return options.pinnedAdapter\n ? { adapter: options.pinnedAdapter, model: parsed.model }\n : parsed;\n }\n\n // 3. Config file model_mapping\n const entry = options.modelMapping?.[modelClass];\n if (entry) {\n return {\n adapter: options.pinnedAdapter ?? entry.adapter,\n model: entry.model,\n };\n }\n\n // 4. Fallback\n return fallback;\n },\n };\n}\n","/**\n * Progress Sink — configurable output target for agent execution progress.\n *\n * Supports writing to stderr, file, or both (tee). File naming strategies\n * allow single-file append, per-invocation unique files, or daily rotation.\n */\n\nimport { openSync, writeSync, closeSync, mkdirSync } from \"node:fs\";\nimport { dirname, join, basename, extname } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\n\nexport interface ProgressSinkOptions {\n /** Write to process.stderr. Default: false */\n stderr?: boolean;\n /** Base file path for log output. */\n file?: string;\n /**\n * File naming strategy:\n * - \"single\": always append to `file` (default)\n * - \"per-invocation\": {dir}/{base}-{YYYY-MM-DDTHHmmss}-{label}{ext}\n * - \"daily\": {dir}/{base}-{YYYY-MM-DD}{ext}\n */\n naming?: \"single\" | \"per-invocation\" | \"daily\";\n /**\n * Identity of the invocation, used only by `per-invocation` naming. The\n * timestamp in that name is second-granular, so this is what keeps two runs\n * that start in the same second in separate files. `executeTask` /\n * `executeWorkflow` pass the task / workflow id.\n *\n * It becomes a component of the resolved file name, so it must be usable as\n * one — `pathSegmentForId` rejects anything that would resolve the log\n * outside the directory `file` declares.\n */\n label?: string;\n}\n\nexport interface ProgressSink {\n write(chunk: string): void;\n close(): void;\n /** Resolved file path (undefined if file output is disabled). */\n readonly filePath?: string;\n}\n\nfunction resolveFilePath(\n base: string,\n naming: \"single\" | \"per-invocation\" | \"daily\",\n label?: string,\n): string {\n if (naming === \"single\") return base;\n\n const dir = dirname(base);\n const ext = extname(base);\n const stem = basename(base, ext);\n const now = new Date();\n\n if (naming === \"daily\") {\n const date = now.toISOString().slice(0, 10);\n return join(dir, `${stem}-${date}${ext}`);\n }\n\n // per-invocation\n const pad = (n: number) => String(n).padStart(2, \"0\");\n const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}T${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;\n const suffix = label ? `-${pathSegmentForId(\"progress-log label\", label)}` : \"\";\n return join(dir, `${stem}-${ts}${suffix}${ext}`);\n}\n\nexport function createProgressSink(options: ProgressSinkOptions): ProgressSink {\n const useStderr = options.stderr ?? false;\n let fd: number | null = null;\n let resolvedPath: string | undefined;\n\n if (options.file) {\n const naming = options.naming ?? \"single\";\n resolvedPath = resolveFilePath(options.file, naming, options.label);\n mkdirSync(dirname(resolvedPath), { recursive: true });\n fd = openSync(resolvedPath, \"a\");\n }\n\n if (!useStderr && fd === null) {\n return { write() {}, close() {} };\n }\n\n return {\n write(chunk: string) {\n if (useStderr) process.stderr.write(chunk);\n if (fd !== null) writeSync(fd, chunk);\n },\n close() {\n if (fd !== null) {\n closeSync(fd);\n fd = null;\n }\n },\n get filePath() {\n return resolvedPath;\n },\n };\n}\n","/**\n * MemoryRef — opaque typed reference for resumable agent context.\n *\n * The ref itself is a lightweight pointer; the actual memory content\n * is managed by the MemoryStore or held server-side by the provider.\n */\nexport interface MemoryRef {\n /** Opaque identifier (e.g. session UUID, response ID, agent ID). */\n id: string;\n /** Provider that generated this ref (e.g. \"claude-agent-sdk\", \"openai-responses\"). */\n provider: string;\n /** Compatibility tag for format validation across versions. */\n compat: string;\n /** ISO 8601 timestamp of ref creation. */\n created_at: string;\n /** ID of the run that produced this ref, for chain tracking. */\n parent_run_id?: string;\n}\n\n/**\n * Pluggable store for memory content that backs MemoryRef pointers.\n *\n * Adapters that use server-side state (OpenAI, Gemini) may not need\n * the store — the ref ID alone is sufficient for resume. Adapters\n * with local state (Claude transcript, Gemini chat history) use the\n * store to persist and retrieve content.\n */\nexport interface MemoryStore {\n save(ref: MemoryRef, content: unknown): Promise<void>;\n load(ref: MemoryRef): Promise<unknown | null>;\n delete(ref: MemoryRef): Promise<void>;\n}\n\n/**\n * In-memory store for testing. State is lost when the process exits.\n */\nexport class InMemoryStore implements MemoryStore {\n private data = new Map<string, unknown>();\n\n async save(ref: MemoryRef, content: unknown): Promise<void> {\n this.data.set(ref.id, content);\n }\n\n async load(ref: MemoryRef): Promise<unknown | null> {\n return this.data.get(ref.id) ?? null;\n }\n\n async delete(ref: MemoryRef): Promise<void> {\n this.data.delete(ref.id);\n }\n}\n","import { mkdir, readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport type { MemoryRef, MemoryStore } from \"./memory-store.js\";\n\nexport interface FileMemoryStoreOptions {\n baseDir?: string;\n}\n\nfunction resolveFilePath(baseDir: string, ref: MemoryRef): string {\n const runId = ref.parent_run_id ?? \"unknown\";\n // Neither half is authored here: `id` is a provider session/response id or a\n // caller-supplied `memoryRef`, `parent_run_id` a caller-supplied run id. Both\n // become the file name, so both are checked before they can name one.\n return join(\n baseDir,\n `${pathSegmentForId(\"memory ref parent_run_id\", runId)}` +\n `_${pathSegmentForId(\"memory ref id\", ref.id)}.json`,\n );\n}\n\n/**\n * File-backed MemoryStore. Persists memory content as JSON files under\n * `<baseDir>/` (default: `.agent-logs/memories/`).\n */\nexport class FileMemoryStore implements MemoryStore {\n readonly baseDir: string;\n\n constructor(options?: FileMemoryStoreOptions) {\n this.baseDir = options?.baseDir ?? \".agent-logs/memories\";\n }\n\n async save(ref: MemoryRef, content: unknown): Promise<void> {\n await mkdir(this.baseDir, { recursive: true });\n const filePath = resolveFilePath(this.baseDir, ref);\n await writeFile(filePath, JSON.stringify(content, null, 2), \"utf-8\");\n }\n\n async load(ref: MemoryRef): Promise<unknown | null> {\n const filePath = resolveFilePath(this.baseDir, ref);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n }\n\n async delete(ref: MemoryRef): Promise<void> {\n const filePath = resolveFilePath(this.baseDir, ref);\n try {\n await unlink(filePath);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return;\n }\n throw error;\n }\n }\n}\n","import { mkdir, readFile, readdir, stat, unlink, writeFile, appendFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { FileMemoryStore } from \"./file-memory-store.js\";\n\nexport interface RunLogEvent {\n timestamp: string;\n type:\n | \"operation_start\"\n | \"operation_end\"\n | \"operation_error\"\n | \"workflow_start\"\n | \"workflow_end\"\n | \"task_start\"\n | \"task_end\"\n | \"handoff\";\n runId: string;\n operationName?: string;\n agentId?: string;\n data?: unknown;\n durationMs?: number;\n error?: string;\n}\n\nconst RUN_LOG_EVENT_TYPES: ReadonlyArray<RunLogEvent[\"type\"]> = [\n \"operation_start\",\n \"operation_end\",\n \"operation_error\",\n \"workflow_start\",\n \"workflow_end\",\n \"task_start\",\n \"task_end\",\n \"handoff\",\n];\n\nconst optionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\n/**\n * The gate between one line of a run log and {@link RunLogEvent}.\n *\n * Every declared field is checked. The log is append-only text an earlier run\n * (possibly an earlier build) wrote, so a line that is not an event is not one\n * this reader may return typed as one — `data` is the exception, declared\n * `unknown`, which promises nothing to check.\n */\nfunction isRunLogEvent(value: unknown): value is RunLogEvent {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const event = value as Record<string, unknown>;\n return (\n typeof event.timestamp === \"string\" &&\n RUN_LOG_EVENT_TYPES.includes(event.type as RunLogEvent[\"type\"]) &&\n typeof event.runId === \"string\" &&\n optionalString(event.operationName) &&\n optionalString(event.agentId) &&\n (event.durationMs === undefined || typeof event.durationMs === \"number\") &&\n optionalString(event.error)\n );\n}\n\nexport interface AgentLogWriterOptions {\n baseDir?: string;\n}\n\nexport class AgentLogWriter {\n readonly baseDir: string;\n private memoryStore: FileMemoryStore;\n\n constructor(options?: AgentLogWriterOptions) {\n this.baseDir = options?.baseDir ?? \".agent-logs\";\n this.memoryStore = new FileMemoryStore({\n baseDir: join(this.baseDir, \"memories\"),\n });\n }\n\n getMemoryStore(): FileMemoryStore {\n return this.memoryStore;\n }\n\n /**\n * Where one run's event log lives. The writer and the reader must agree on\n * the name, so both derive it here rather than each spelling it out — and\n * with it, the check that keeps a run id inside `baseDir`.\n */\n private runLogPath(runId: string): string {\n return join(this.baseDir, \"runs\", `${pathSegmentForId(\"run id\", runId)}.jsonl`);\n }\n\n /** Where one run's handoff payload lives. Shared by the writer and reader. */\n private handoffPath(runId: string, step: string): string {\n return join(\n this.baseDir,\n \"handoffs\",\n `${pathSegmentForId(\"run id\", runId)}_${pathSegmentForId(\"handoff step\", step)}.json`,\n );\n }\n\n async writeRunEvent(runId: string, event: RunLogEvent): Promise<void> {\n const filePath = this.runLogPath(runId);\n await mkdir(join(this.baseDir, \"runs\"), { recursive: true });\n await appendFile(filePath, `${JSON.stringify(event)}\\n`, \"utf-8\");\n }\n\n async readRunLog(runId: string): Promise<RunLogEvent[]> {\n const filePath = this.runLogPath(runId);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n // A line that does not parse, or does not read as an event, is not one:\n // the same answer a missing log gets below, rather than a typed lie.\n const events: RunLogEvent[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (line.trim().length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n if (isRunLogEvent(parsed)) events.push(parsed);\n }\n return events;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return [];\n }\n throw error;\n }\n }\n\n async writeHandoff(\n runId: string,\n step: string,\n data: unknown,\n ): Promise<void> {\n const filePath = this.handoffPath(runId, step);\n await mkdir(join(this.baseDir, \"handoffs\"), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2), \"utf-8\");\n }\n\n async readHandoff(\n runId: string,\n step: string,\n ): Promise<unknown | null> {\n const filePath = this.handoffPath(runId, step);\n try {\n const raw = await readFile(filePath, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n }\n\n async cleanOlderThan(maxAgeMs: number): Promise<{ deleted: number }> {\n const cutoff = Date.now() - maxAgeMs;\n let deleted = 0;\n\n const subdirs = [\"memories\", \"runs\", \"handoffs\"];\n for (const subdir of subdirs) {\n const dirPath = join(this.baseDir, subdir);\n let entries: string[];\n try {\n entries = await readdir(dirPath);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n continue;\n }\n throw error;\n }\n\n for (const entry of entries) {\n const filePath = join(dirPath, entry);\n const fileStat = await stat(filePath);\n if (fileStat.mtimeMs < cutoff) {\n await unlink(filePath);\n deleted++;\n }\n }\n }\n\n return { deleted };\n }\n}\n","import { jsonSchemaToZod } from \"./schema-converter.js\";\nimport type { SdkFunctionTool } from \"./library-tool-sdk.js\";\n\nexport interface LibraryToolDefinition {\n toolId: string;\n description: string;\n module: string;\n exportName: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n}\n\nexport interface LibraryToolRegistry {\n register(def: LibraryToolDefinition): void;\n get(toolId: string): LibraryToolDefinition | undefined;\n getAll(): LibraryToolDefinition[];\n execute(toolId: string, input: unknown): Promise<unknown>;\n}\n\nexport function createLibraryToolRegistry(): LibraryToolRegistry {\n const definitions = new Map<string, LibraryToolDefinition>();\n const moduleCache = new Map<string, Record<string, unknown>>();\n\n return {\n register(def: LibraryToolDefinition): void {\n definitions.set(def.toolId, def);\n },\n\n get(toolId: string): LibraryToolDefinition | undefined {\n return definitions.get(toolId);\n },\n\n getAll(): LibraryToolDefinition[] {\n return [...definitions.values()];\n },\n\n async execute(toolId: string, input: unknown): Promise<unknown> {\n const def = definitions.get(toolId);\n if (!def) {\n throw new Error(`Library tool not found: ${toolId}`);\n }\n\n if (def.inputSchema) {\n const schema = jsonSchemaToZod(def.inputSchema);\n const result = schema.safeParse(input);\n if (!result.success) {\n throw new Error(\n `Input validation failed for tool \"${toolId}\": ${result.error.message}`,\n );\n }\n input = result.data;\n }\n\n let mod = moduleCache.get(def.module);\n if (!mod) {\n try {\n mod = (await import(def.module)) as Record<string, unknown>;\n moduleCache.set(def.module, mod);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to import module \"${def.module}\" for tool \"${toolId}\": ${message}`,\n );\n }\n }\n\n const fn = mod[def.exportName];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Export \"${def.exportName}\" not found in module \"${def.module}\" for tool \"${toolId}\"`,\n );\n }\n\n const output = await (fn as (input: unknown) => Promise<unknown>)(input);\n\n if (def.outputSchema) {\n const schema = jsonSchemaToZod(def.outputSchema);\n const result = schema.safeParse(output);\n if (!result.success) {\n throw new Error(\n `Output validation failed for tool \"${toolId}\": ${result.error.message}`,\n );\n }\n }\n\n return output;\n },\n };\n}\n\n/**\n * Create a LibraryToolRegistry backed by pre-built SdkFunctionTool handlers.\n * Unlike createLibraryToolRegistry (which resolves tools via dynamic import),\n * this variant delegates execute() directly to the tool's in-process handler.\n */\nexport function createRegistryFromSdkTools(\n tools: SdkFunctionTool[],\n): LibraryToolRegistry {\n const handlers = new Map<string, SdkFunctionTool>();\n const definitions = new Map<string, LibraryToolDefinition>();\n\n for (const tool of tools) {\n handlers.set(tool.name, tool);\n definitions.set(tool.name, {\n toolId: tool.name,\n description: tool.description,\n module: \"__inline__\",\n exportName: \"__handler__\",\n inputSchema: tool.inputSchema,\n });\n }\n\n return {\n register(def: LibraryToolDefinition): void {\n definitions.set(def.toolId, def);\n },\n\n get(toolId: string): LibraryToolDefinition | undefined {\n return definitions.get(toolId);\n },\n\n getAll(): LibraryToolDefinition[] {\n return [...definitions.values()];\n },\n\n async execute(toolId: string, input: unknown): Promise<unknown> {\n const handler = handlers.get(toolId);\n if (handler) {\n return handler.handler((input ?? {}) as Record<string, unknown>);\n }\n throw new Error(`Library tool not found: ${toolId}`);\n },\n };\n}\n","/**\n * Adapter Factory — public API for creating SDK adapters by name.\n *\n * Centralises the adapter-name → SDK-class mapping so that consumers\n * no longer need a local switch statement with dynamic imports.\n */\n\nimport type { SdkAdapter } from \"./task-runner.js\";\nimport type { GuardrailHooks } from \"./guardrail-hooks.js\";\n\nexport type PermissionMode = \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n\nexport interface CreateAdapterOptions {\n model?: string;\n cwd?: string;\n tools?: string[];\n permissionMode?: PermissionMode;\n guardrailHooks?: GuardrailHooks;\n}\n\nconst ADAPTER_PACKAGES: Record<string, string> = {\n claude: \"@anthropic-ai/claude-agent-sdk\",\n gemini: \"@google/adk\",\n openai: \"@openai/agents\",\n};\n\n/**\n * Create an SDK adapter instance by name.\n *\n * @param name - One of: \"mock\", \"claude\", \"openai\", \"gemini\"\n * @param options - Adapter-specific configuration\n */\nexport async function createAdapter(\n name: string,\n options?: CreateAdapterOptions,\n): Promise<SdkAdapter> {\n const { model, cwd, tools, permissionMode, guardrailHooks } = options ?? {};\n\n switch (name) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n try {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n ...(cwd ? { cwd } : {}),\n ...(tools ? { tools } : {}),\n ...(permissionMode ? { permissionMode } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"claude\", err);\n }\n }\n case \"gemini\": {\n try {\n const { AdkSdkAdapter } = await import(\"../adapters/adk-sdk.js\");\n return new AdkSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"gemini\", err);\n }\n }\n case \"openai\": {\n try {\n const { OpenAIAgentsSdkAdapter } = await import(\"../adapters/openai-agents-sdk.js\");\n return new OpenAIAgentsSdkAdapter({\n guardrailHooks,\n ...(model ? { model } : {}),\n });\n } catch (err) {\n throwMissingPackageError(\"openai\", err);\n }\n }\n default:\n throw new Error(\n `Unknown adapter: \"${name}\". Available: mock, claude, openai, gemini`,\n );\n }\n}\n\nfunction throwMissingPackageError(adapter: string, err: unknown): never {\n const message = err instanceof Error ? err.message : String(err);\n if (message.includes(\"Cannot find package\")) {\n const pkg = ADAPTER_PACKAGES[adapter];\n throw new Error(\n `Adapter \"${adapter}\" requires package \"${pkg}\" which is not installed.\\n` +\n `Install it with: npm install ${pkg}`,\n );\n }\n throw err;\n}\n","/**\n * High-level execution APIs — executeTask / executeWorkflow\n *\n * Encapsulates the common boilerplate shared across all CLI consumers:\n * 1. Adapter creation\n * 2. DSL context loading (registries)\n * 3. Progress sink setup\n * 4. Task/workflow invocation with retry policy\n *\n * CLI consumers only need to provide:\n * - domain-specific context (user_request)\n * - adapter name + options\n * - DSL blob (resolvedDsl from codegen)\n */\n\nimport { resolve } from \"node:path\";\nimport { type CreateAdapterOptions } from \"./adapter-factory.js\";\nimport {\n BoundResolver,\n type ArtifactBindingConfig,\n type ResolvedComponent,\n} from \"./bound-resolver.js\";\nimport {\n createComponentScope,\n DEFAULT_COMPONENT_ID,\n type ComponentScope,\n} from \"../component-scope.js\";\nimport type { InvokedComponent } from \"../component-binding.js\";\nimport { loadDslContext } from \"./dsl-context.js\";\nimport {\n createGuardrailHooks,\n createGuardrailHooksFromRules,\n type GuardrailCheckFunctions,\n type GuardrailHooks,\n} from \"./guardrail-hooks.js\";\nimport { pluginRegistry } from \"./plugin.js\";\nimport { createProgressSink, type ProgressSink } from \"./progress-sink.js\";\nimport type { ProgressLogConfig } from \"../generator/config.js\";\nimport { runTask, type TaskRunResult, type SdkAdapter, type ObserverEmitFn } from \"./task-runner.js\";\nimport { runWorkflow, type WorkflowResult, type WorkflowInvocation, type HandoffInput, type StepCompleteEvent, type StepResult, type WorkflowRegistries, type DelegateStep } from \"./workflow-runner.js\";\nimport type { RunToolchainChecksOptions } from \"./toolchain-checker.js\";\nimport type { TaskContext } from \"./task-runner.js\";\nimport type { ModelClass, ModelMappingConfig } from \"./model-resolver.js\";\nimport { createModelAwareAdapterSetup } from \"./model-aware-adapter.js\";\nimport { createAnalyzerBridge } from \"./analyzer-bridge.js\";\nimport { createRegistryFromSdkTools, type LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport { buildNavigationContext, type NavigationContext } from \"./navigation-context.js\";\n\n// ---------------------------------------------------------------------------\n// Shared options\n// ---------------------------------------------------------------------------\n\nexport interface ExecuteOptions {\n adapter: string;\n model?: string;\n dsl: Record<string, unknown>;\n projectDslPath?: string;\n /**\n * Progress-log settings from the project manifest's `logging.progress_log`,\n * auto-wired by createProjectRuntime. Absent → stderr only.\n */\n progressLog?: ProgressLogConfig;\n adapterOptions?: Partial<CreateAdapterOptions>;\n maxFollowUps?: number;\n maxRetries?: number;\n /** Pre-resolved component from BoundResolver (skips runtime resolve). */\n resolvedComponent?: ResolvedComponent;\n /**\n * The component whose operation is being executed, carried here by\n * `createProjectRuntime` from the invocation context `createRuntimeBinding`\n * built (component-binding.ts). It is what makes the run's `ComponentScope` a\n * scope of something: the component's operation names are one of the two\n * namespaces `toolsByAgent` resolves declarations in, and its id is what says\n * which toolchains write their `operations` in it (#338).\n *\n * Absent only when `executeTask` / `executeWorkflow` are called directly, by\n * a caller that named no component. The scope is still built — guardrails,\n * library tools and the tool-id namespace do not depend on the IR — with no\n * component operations to wire.\n */\n component?: InvokedComponent;\n /** Component id for BoundResolver cache keying. */\n componentId?: string;\n /** Software binding paths for runtime guardrail resolution. */\n bindingPaths?: string[];\n /** Active guardrail policy name. */\n activeGuardrailPolicy?: string;\n /** Artifact binding config for runtime resolveBound(). */\n artifactBinding?: ArtifactBindingConfig;\n /** Path substitutions for artifact binding. */\n paths?: Record<string, string>;\n /**\n * Observer emit function for agent-axis spans (agent.session / agent.subagent /\n * toolchain.execution / evaluate.*). When undefined, all emission is a no-op.\n * Auto-wired from project.yaml `bindings.observability` by createProjectRuntime —\n * callers do NOT hand-write this.\n */\n observer?: ObserverEmitFn;\n /**\n * The project manifest's `toolchains:`, auto-wired by createProjectRuntime.\n *\n * Two consumers on this path, both driven from this one value:\n * - `resolveExecutionContext` hands `toolchainsPath` to `BoundResolver`,\n * which derives each agent's toolchains from the artifacts it may touch\n * and so decides what reaches `buildCandidateAgents` (#336).\n * - `runWorkflow` runs the declared `checks` once post-run and emits one\n * toolchain.execution span per check (OBSERVATION ONLY — never changes\n * the workflow outcome), which is why it also gates itself on `observer`.\n * `observer`/`parentSpanId` are injected there.\n */\n toolchain?: RunToolchainChecksOptions;\n /** Per-class adapter/model mapping from project.yaml (used by executeWorkflow / executeTask). */\n modelMapping?: ModelMappingConfig;\n /**\n * When true, `adapter` is used for all model classes; only the model name\n * varies per class (CLI `--adapter mock` override).\n */\n pinAdapter?: boolean;\n}\n\n/**\n * The one place `logging.progress_log` becomes a ProgressSink, shared by\n * executeTask and executeWorkflow. `destination` decides the targets and\n * `naming` the file rotation; both are meaningless unless read here.\n *\n * `invocationId` is the task or workflow id the caller was asked to run — the\n * only identity an invocation has at this seam, and what `naming:\n * per-invocation` needs to keep runs apart: its timestamp is second-granular,\n * so without the id two invocations that start in the same second resolve to\n * the same file and the strategy degrades to `daily` with a longer name.\n */\nfunction createExecutionProgressSink(\n invocationId: string,\n progressLog?: ProgressLogConfig,\n): ProgressSink {\n if (!progressLog) return createProgressSink({ stderr: true });\n\n const { destination, file, naming } = progressLog;\n const wantsFile = destination === \"file\" || destination === \"both\";\n\n return createProgressSink({\n stderr: destination === \"stderr\" || destination === \"both\",\n // The schema requires `file` whenever destination selects file output.\n ...(wantsFile && file ? { file: resolve(file), naming, label: invocationId } : {}),\n });\n}\n\n// ---------------------------------------------------------------------------\n// Shared context resolution\n// ---------------------------------------------------------------------------\n\ninterface ExecutionContext {\n registries: WorkflowRegistries;\n dsl: Record<string, unknown>;\n /** Level 1 navigation index, when one could be built for this DSL. */\n navigationIndex?: Record<string, unknown>;\n /**\n * This invocation's component scope. Built here because this is where both\n * halves exist: the `ResolvedComponent` this function resolves, and the\n * component the binding named. Everything the scope isolates —\n * per-agent tools, per-agent guardrails, the in-process tool registry — is\n * consumed below from the scope and from nowhere else, so an invocation\n * cannot half-use it (#338).\n */\n scope: ComponentScope;\n}\n\nasync function resolveExecutionContext(\n options: ExecuteOptions,\n requiredEntities?: { workflows?: string[]; tasks?: string[] },\n): Promise<ExecutionContext> {\n // Every input BoundResolver is the only one to read. `toolchain` belongs here\n // for the same reason `bindingPaths` and `artifactBinding` do: a manifest that\n // declares only `toolchains:` still has something to resolve, and leaving it\n // out is what kept the derivation from ever running (#336).\n const useBoundResolver =\n options.resolvedComponent ||\n (options.bindingPaths && options.bindingPaths.length > 0) ||\n options.artifactBinding ||\n options.toolchain;\n\n if (useBoundResolver) {\n // Merge the project-level DSL overlay (which may `extends: /$embedded/`)\n // over the embedded base BEFORE binding, so guardrail/artifact binding\n // operates on the fully-resolved DSL — not just the embedded base.\n let baseDsl = options.dsl;\n if (!options.resolvedComponent && options.projectDslPath) {\n const merged = await loadDslContext({\n embeddedDsl: options.dsl,\n projectDslPath: options.projectDslPath,\n });\n baseDsl = merged.dsl;\n }\n\n const component =\n options.resolvedComponent ??\n (await new BoundResolver().resolve({\n // The component the binding named is this run's identity, so it is also\n // what the resolver is keyed on: two components resolved in one process\n // are two entries, not one shared \"default\".\n id: options.component?.ir.info.id ?? options.componentId ?? DEFAULT_COMPONENT_ID,\n embeddedDsl: baseDsl,\n bindingPaths: options.bindingPaths,\n activeGuardrailPolicy: options.activeGuardrailPolicy,\n artifactBinding: options.artifactBinding,\n paths: options.paths,\n toolchainContractsPath: options.toolchain?.toolchainsPath,\n }));\n\n const registries = requiredEntities\n ? (await loadDslContext({ embeddedDsl: component.dsl, requiredEntities })).registries\n : component.registries;\n\n return scopeExecution(options, registries, component.dsl, component);\n }\n\n const ctx = await loadDslContext({\n embeddedDsl: options.dsl,\n projectDslPath: options.projectDslPath,\n requiredEntities,\n });\n return scopeExecution(options, ctx.registries, ctx.dsl);\n}\n\n/**\n * The tail every branch above shares: build the Level 1 navigation context, the\n * in-process analyzer tools it scopes, and the component scope that owns them.\n *\n * One place, because a second one is a second answer: `executeTask` and\n * `executeWorkflow` each used to build the navigation context and the analyzer\n * registry for themselves.\n */\nasync function scopeExecution(\n options: ExecuteOptions,\n registries: WorkflowRegistries,\n dsl: Record<string, unknown>,\n resolvedComponent?: ResolvedComponent,\n): Promise<ExecutionContext> {\n const navigationIndex = (await buildNavigationContextSafely(dsl))?.navigationIndex;\n const scope = createComponentScope({\n component: options.component,\n dsl,\n resolvedComponent,\n libraryTools: buildAnalyzerToolRegistry({\n navigationIndex,\n artifactPatterns: deriveArtifactPatterns(navigationIndex),\n }),\n });\n\n return { registries, dsl, navigationIndex, scope };\n}\n\n/**\n * Guardrail hooks for one agent, or undefined when nothing would check it.\n *\n * The ONE constructor of per-agent hooks. `guardrail-hooks.ts` builds an\n * evaluator out of the check sources it is handed and names no agent anywhere\n * (see `HookContext`), so which rules an agent is checked against is decided\n * here — it has to be, because deciding it needs the two things that module is\n * deliberately kept away from: this run's `ComponentScope`, which carries the\n * rules a binding resolved, and this process's plugin registry.\n *\n * It was decided in two places once. That module also exported a per-agent\n * constructor, re-exported from the barrel and called by nobody, which took the\n * `perAgent` map directly; it memoised nothing where this one caches per agent,\n * and handed an agent with no rules an evaluator that denies nothing where this\n * one returns undefined. Nothing failed when the two drifted, because nothing\n * ran the other one (#333).\n *\n * \"The ONE\" is a DECLARATION, and this comment is the whole of its enforcement.\n * Deleting `HookContext.agentId` took away the affordance that duplicate used,\n * so it cannot be pasted back as it was (TS2353) — but that is a bound on one\n * spelling, not on the invariant. A second per-agent constructor that never\n * writes an agent id typechecks, builds and passes every test in this\n * repository, and `check:reachability` calls it reachable as soon as a barrel\n * re-exports it, because reachable is not consumed. There is no gate to add\n * here: \"is this another way to answer the same question\" is a question about\n * intent, and a check that decided it from the shape of the code would report\n * green for the cases it failed to enumerate. So this is enforced by being\n * read, which is why it sits on the declaration that makes the decision rather\n * than in a document beside it.\n *\n * TWO independent sources feed those hooks, so they are gated independently:\n *\n * - RULES, which exist only where a software binding resolved them\n * (BoundResolver); there is no second, DSL-embedded source of rules (#267).\n * They are per-agent, so they are looked up per agent — in the run's\n * `ComponentScope` and nowhere else, which is what makes the rules this run\n * enforces the calling component's and not the process's. That map was\n * built through `getGuardrailRulesForAgent` (component-scope.ts), the\n * predicate `dev-team guard list` answers with, so reading it here is\n * reading that predicate rather than holding a second opinion beside it\n * (#338).\n * - The `customGuardrails` of the plugins the project manifest declared.\n * Those belong to the PROCESS, not to an agent: nothing about them is\n * scoped, and a project can declare them while no binding resolves a single\n * rule for anyone.\n *\n * Gating both on the rules is what put plugin guardrails out of reach: a\n * plugin-only project has no per-agent rule anywhere, so no hooks were built,\n * so the adapter never called `runChecks` and the plugin was consulted in no\n * process at all (#332). Memoised because the workflow path asks once per step.\n *\n * This is where the process's plugin guardrails enter the evaluator, and the\n * only place they do. `createProjectRuntime` ran `loadPlugins` for THIS process\n * before anything could execute, so the registry here holds what the project\n * manifest declared — whereas the hook routes answer for an editor and are\n * evaluated in processes that cannot have run it (see\n * `PluginRegistry.guardrailChecks`). Passed rather than reached for: the\n * evaluator is shared with the lean hot path, where the registry is dead weight\n * on every tool call (#331).\n *\n * Returning a factory is also what makes `executeWorkflow` scope adapters per\n * agent, so the gate has to stay shut for a project that declares neither kind\n * of guardrail — otherwise every project would split its adapter cache to carry\n * hooks with nothing to check.\n */\nfunction createAgentGuardrailHooks(\n execCtx: ExecutionContext,\n): ((agentId: string) => GuardrailHooks | undefined) | undefined {\n // Already only the agents that have rules: the scope applied\n // `getGuardrailRulesForAgent` to every key of the resolved `perAgent` map\n // when it built this one (component-scope.ts), so an empty map is \"no agent\n // on this run has a rule\" and not \"no component was resolved\".\n const guardrailsByAgent = execCtx.scope.guardrailsByAgent;\n // Whether there is a plugin source is decided once; WHAT it reports is still\n // read when a check runs (see `PluginRegistry.guardrailChecks`).\n const pluginSources: GuardrailCheckFunctions[] = pluginRegistry.hasGuardrails()\n ? [pluginRegistry.guardrailChecks()]\n : [];\n if (pluginSources.length === 0 && guardrailsByAgent.size === 0) return undefined;\n\n // What an agent the binding resolved no rule for gets. Agent-independent, so\n // it is one object rather than one per agent.\n const pluginOnlyHooks =\n pluginSources.length > 0 ? createGuardrailHooks(...pluginSources) : undefined;\n\n const cache = new Map<string, GuardrailHooks | undefined>();\n return (agentId: string) => {\n if (cache.has(agentId)) return cache.get(agentId);\n\n const rules = guardrailsByAgent.get(agentId);\n const hooks = rules\n ? createGuardrailHooksFromRules(rules, ...pluginSources)\n : pluginOnlyHooks;\n cache.set(agentId, hooks);\n return hooks;\n };\n}\n\nfunction injectGuardrailHooks(\n adapterOptions: Partial<CreateAdapterOptions>,\n execCtx: ExecutionContext,\n targetAgentId?: string,\n): void {\n if (adapterOptions.guardrailHooks || !targetAgentId) return;\n\n const hooks = createAgentGuardrailHooks(execCtx)?.(targetAgentId);\n if (hooks) {\n adapterOptions.guardrailHooks = hooks;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared navigation context (Level 1) → analyzer bridge + task prompt\n// ---------------------------------------------------------------------------\n\ninterface AnalyzerToolRegistryOptions {\n navigationIndex?: Record<string, unknown>;\n artifactPatterns?: Map<string, string[]>;\n projectRoot?: string;\n}\n\nfunction buildAnalyzerToolRegistry(\n options: AnalyzerToolRegistryOptions = {},\n): LibraryToolRegistry {\n const bridge = createAnalyzerBridge({\n projectRoot: options.projectRoot ?? process.cwd(),\n navigationIndex: options.navigationIndex,\n artifactPatterns: options.artifactPatterns,\n });\n const tools = bridge.buildAnalyzerTools();\n return createRegistryFromSdkTools(tools);\n}\n\n/**\n * Derive the artifactId → path_patterns map the analyzer needs to scope its\n * AST/dependency graph build, from the Level 1 navigation index. Returns an\n * empty map when no usable artifacts are present.\n */\nfunction deriveArtifactPatterns(\n navigationIndex?: Record<string, unknown>,\n): Map<string, string[]> {\n const patterns = new Map<string, string[]>();\n const artifacts = navigationIndex?.artifacts as\n | Record<string, { files?: { path_patterns?: unknown } }>\n | undefined;\n if (!artifacts) return patterns;\n for (const [id, node] of Object.entries(artifacts)) {\n const pp = node?.files?.path_patterns;\n if (Array.isArray(pp) && pp.length > 0) {\n patterns.set(id, pp as string[]);\n }\n }\n return patterns;\n}\n\n/**\n * Build the Level 1 navigation context for an execution. Best-effort: when the\n * DSL is absent or navigation cannot be built (e.g. agent-contracts unavailable,\n * validation failure), execution degrades gracefully and proceeds without it\n * rather than throwing.\n */\nasync function buildNavigationContextSafely(\n dsl: Record<string, unknown>,\n): Promise<NavigationContext | undefined> {\n if (!dsl) return undefined;\n try {\n // `dsl` is already the fully merged + artifact-bound DSL, so we feed it\n // directly as the embedded DSL (no further overlay/binding required).\n return await buildNavigationContext({ embeddedDsl: dsl });\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// executeTask\n// ---------------------------------------------------------------------------\n\nexport interface TaskHookContext {\n adapter: SdkAdapter;\n registries: WorkflowRegistries;\n taskId: string;\n}\n\nexport interface ExecuteTaskOptions extends ExecuteOptions {\n request: string;\n hooks?: {\n beforeTask?: (ctx: TaskHookContext) => Promise<void>;\n afterTask?: (result: TaskRunResult) => Promise<void>;\n };\n}\n\nexport async function executeTask(\n taskId: string,\n options: ExecuteTaskOptions,\n): Promise<TaskRunResult> {\n const execCtx = await resolveExecutionContext(options, { tasks: [taskId] });\n const taskDef = execCtx.registries.taskRegistry?.[taskId];\n const targetAgentId = taskDef?.target_agent;\n const modelClass = taskDef?.model_class as ModelClass | undefined;\n\n const adapterOptions = { ...options.adapterOptions };\n injectGuardrailHooks(adapterOptions, execCtx, targetAgentId);\n\n const { resolveAdapter: resolveTaskAdapter, modelResolver } = await createModelAwareAdapterSetup({\n fallbackAdapter: options.adapter,\n fallbackModel: options.model,\n modelMapping: options.modelMapping,\n adapterOptions,\n pinAdapter: options.pinAdapter,\n });\n const resolved = modelResolver.resolve(modelClass);\n const adapter = await resolveTaskAdapter(modelClass);\n\n const progressSink = createExecutionProgressSink(taskId, options.progressLog);\n\n const taskContext: TaskContext = { user_request: options.request };\n if (execCtx.navigationIndex) {\n taskContext.variables = { navigationIndex: execCtx.navigationIndex };\n }\n\n try {\n if (options.hooks?.beforeTask) {\n await options.hooks.beforeTask({ adapter, registries: execCtx.registries, taskId });\n }\n\n const result = await runTask(adapter, taskId, taskContext, {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: options.maxRetries ?? 0,\n progressOutput: progressSink,\n observer: options.observer,\n libraryTools: execCtx.scope.libraryTools,\n toolsByAgent: execCtx.scope.toolsByAgent,\n envelopeAdapter: resolved.adapter,\n envelopeModel: resolved.model,\n ...execCtx.registries,\n });\n\n if (options.hooks?.afterTask) {\n await options.hooks.afterTask(result);\n }\n\n return result;\n } finally {\n progressSink.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// executeWorkflow\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowHookContext {\n adapter: SdkAdapter;\n registries: WorkflowRegistries;\n workflowId: string;\n}\n\nexport interface ExecuteWorkflowOptions extends ExecuteOptions {\n request?: string;\n handoff?: HandoffInput<string>;\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n autoApproveGates?: boolean;\n hooks?: {\n beforeWorkflow?: (ctx: WorkflowHookContext) => Promise<void>;\n afterWorkflow?: (result: WorkflowResult) => Promise<void>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n}\n\nexport async function executeWorkflow(\n workflowId: string,\n options: ExecuteWorkflowOptions,\n): Promise<WorkflowResult> {\n const execCtx = await resolveExecutionContext(options, { workflows: [workflowId] });\n\n const adapterOptions = { ...options.adapterOptions };\n // A workflow's steps run as different agents, and guardrail hooks are fixed at\n // adapter construction — so the scope is applied per step by the factory rather\n // than once for the whole run (#269).\n const guardrailHooksForAgent = adapterOptions.guardrailHooks\n ? undefined\n : createAgentGuardrailHooks(execCtx);\n\n const { factory: adapterOrFactory, defaultAdapter: adapter, modelResolver } =\n await createModelAwareAdapterSetup({\n fallbackAdapter: options.adapter,\n fallbackModel: options.model,\n modelMapping: options.modelMapping,\n adapterOptions,\n pinAdapter: options.pinAdapter,\n guardrailHooksForAgent,\n });\n\n const progressSink = createExecutionProgressSink(workflowId, options.progressLog);\n\n // Propagate the navigation index to every step's TaskContext.variables via\n // the workflow invocation context (workflow-runner spreads context.variables\n // onto each delegate/evaluate step).\n const workflowContext = execCtx.navigationIndex\n ? {\n ...options.context,\n variables: {\n ...options.context?.variables,\n navigationIndex: execCtx.navigationIndex,\n },\n }\n : options.context;\n\n try {\n if (options.hooks?.beforeWorkflow) {\n await options.hooks.beforeWorkflow({ adapter, registries: execCtx.registries, workflowId });\n }\n\n const invocation: WorkflowInvocation = {\n workflow: workflowId,\n user_request: options.request,\n handoff: options.handoff,\n progressOutput: progressSink,\n observer: options.observer,\n toolchain: options.toolchain,\n libraryTools: execCtx.scope.libraryTools,\n toolsByAgent: execCtx.scope.toolsByAgent,\n resolveModelMeta: (modelClass) => modelResolver.resolve(modelClass),\n perAgentAdapters: Boolean(guardrailHooksForAgent),\n runtime: {\n maxFollowUps: options.maxFollowUps ?? 2,\n maxRetries: options.maxRetries ?? 0,\n },\n hooks: {\n onStepComplete: options.hooks?.onStepComplete,\n onGate: options.hooks?.onGate ?? (options.autoApproveGates ? async () => true : undefined),\n onOptionalStep: options.hooks?.onOptionalStep,\n },\n context: workflowContext,\n };\n\n const result = await runWorkflow(adapterOrFactory, invocation, execCtx.registries);\n\n if (options.hooks?.afterWorkflow) {\n await options.hooks.afterWorkflow(result);\n }\n\n return result;\n } finally {\n progressSink.close();\n }\n}\n","import type { ComponentIR } from \"@aaac/contracts\";\nimport type { InvokedComponent, RuntimeBinding } from \"./component-binding.js\";\nimport {\n getGuardrailRulesForAgent,\n type ResolvedComponent,\n type ResolvedToolchain,\n} from \"./lib/bound-resolver.js\";\nimport type { GuardrailRuleData } from \"./lib/guardrail-hooks.js\";\nimport type { LibraryToolRegistry } from \"./lib/library-tool-binding.js\";\n\n/**\n * The component id an invocation that named no component runs under. Shared\n * with `resolveExecutionContext` (lib/execute.ts), which keys `BoundResolver`\n * on the same value, so the scope's id and the resolved component's id are one\n * name and not two.\n */\nexport const DEFAULT_COMPONENT_ID = \"default\";\n\nexport interface ComponentScope {\n componentId: string;\n /**\n * Present when the invocation named a component — i.e. when it was dispatched\n * through a `createRuntimeBinding` binding, which is every invocation the\n * generated component client makes. Absent when `executeTask` /\n * `executeWorkflow` are called directly with no component to scope to; there\n * are then no operation names to wire and nothing to check them against.\n */\n componentIR?: ComponentIR;\n binding?: RuntimeBinding;\n toolsByAgent: Map<string, string[]>;\n guardrailsByAgent: Map<string, GuardrailRuleData>;\n libraryTools?: LibraryToolRegistry;\n toolchainsByAgent?: Map<string, ResolvedToolchain[]>;\n}\n\nexport interface CreateComponentScopeOptions {\n /** The component whose operation is being executed (component-binding.ts). */\n component?: InvokedComponent;\n /**\n * The effective DSL — merged overlay, artifact-bound — that declares `tools`\n * and `agents`. It is where both halves of the tool-id namespace are written,\n * and it exists whether or not a software binding was resolved, so it is an\n * input of its own rather than a field read off `resolvedComponent`.\n */\n dsl?: Record<string, unknown>;\n resolvedComponent?: ResolvedComponent;\n /**\n * The in-process tool registry this scope owns. Held rather than built: a\n * registry is constructed by `createLibraryToolRegistry` /\n * `createRegistryFromSdkTools` (lib/library-tool-binding.ts), and what §5.2 of\n * the architecture asks of the scope is that the registry be the calling\n * component's rather than a process-wide one.\n */\n libraryTools?: LibraryToolRegistry;\n}\n\n/**\n * A declaration that reaches `toolsByAgent` named something the namespace it is\n * written in does not contain.\n *\n * Two declarations reach it, each in its own namespace:\n *\n * - `toolchains[*].operations` of a toolchain naming THIS component — this\n * component's operation names (#335).\n * - `agents[*].can_execute_tools` — a tool id: a DSL `tools` key or the id of\n * a toolchain the resolver loaded (#337).\n *\n * Both used to be matched against the operation names and whatever missed was\n * dropped without a word: `agents/toolchain-contracts.yaml` could ask for\n * `audit-governance` while the operation is `auditGovernance`, and\n * `reflector.can_execute_tools: [observ-query]` — a correctly spelled tool id —\n * was thrown away for not being an operation name. Either way an agent shipped\n * a tool short and nothing failed.\n *\n * One error for both because there is one defect: a name that resolves to\n * nothing. It carries both namespaces so the reader can see which one the\n * offending line was meant to be written in.\n */\nexport class UnresolvedScopeDeclarationError extends Error {\n readonly componentId: string;\n readonly unresolved: string[];\n readonly operationNames: string[];\n readonly toolIds: string[];\n\n constructor(\n componentId: string,\n unresolved: string[],\n operationNames: string[],\n toolIds: string[],\n ) {\n super(\n `Declarations do not resolve against component \"${componentId}\":\\n` +\n unresolved.map((u) => ` - ${u}`).join(\"\\n\") +\n `\\nComponent operations: ${operationNames.join(\", \")}` +\n `\\nTool ids: ${toolIds.join(\", \")}`,\n );\n this.name = \"UnresolvedScopeDeclarationError\";\n this.componentId = componentId;\n this.unresolved = unresolved;\n this.operationNames = operationNames;\n this.toolIds = toolIds;\n }\n}\n\ninterface DslToolEntry {\n invokable_by?: string[];\n}\n\ninterface DslAgentEntry {\n can_execute_tools?: string[];\n}\n\nfunction buildToolsByAgent(\n dsl?: Record<string, unknown>,\n resolved?: ResolvedComponent,\n componentIR?: ComponentIR,\n): Map<string, string[]> {\n const operationNames = new Set(Object.keys(componentIR?.operations ?? {}));\n const toolsByAgent = new Map<string, string[]>();\n\n const tools = (dsl?.tools ?? {}) as Record<string, DslToolEntry>;\n // The tool-id namespace: a tool is named by its DSL `tools` key or by the id\n // of a toolchain the resolver loaded. Those two, and only those two, are what\n // `mergeDerivedWithAgentTools` (lib/bound-resolver.ts) already resolves\n // `can_execute_tools` against, so an id that means something there means the\n // same thing here.\n const toolIds = new Set([\n ...Object.keys(tools),\n ...Object.keys(resolved?.toolchains ?? {}),\n ]);\n\n const unresolved: string[] = [];\n\n // A tool is identified by its id — the `tools` key. `command` names a unit\n // inside the contract the tool binds: a sub-command of its `cli_contract`\n // (`compile`), or an operation of the component its `component_contract`\n // names (`review`). Either way that is a name in the bound contract's\n // namespace, not in this one, so it is neither checked against this namespace\n // nor wired from it.\n for (const [toolId, tool] of Object.entries(tools)) {\n for (const agentId of tool.invokable_by ?? []) {\n appendToolForAgent(toolsByAgent, agentId, toolId);\n }\n }\n\n const agents = (dsl?.agents ?? {}) as Record<string, DslAgentEntry>;\n for (const [agentId, agent] of Object.entries(agents)) {\n for (const toolId of agent.can_execute_tools ?? []) {\n if (toolIds.has(toolId)) {\n appendToolForAgent(toolsByAgent, agentId, toolId);\n } else {\n unresolved.push(`${agentId}.can_execute_tools: ${toolId}`);\n }\n }\n }\n\n if (resolved?.toolchainsByAgent) {\n for (const [agentId, toolchains] of resolved.toolchainsByAgent) {\n for (const tc of toolchains) {\n // The toolchain itself is a tool id — the same namespace `toolIds` is\n // built from — and `deriveToolchainsForAgents` (lib/bound-resolver.ts)\n // already decided which agents may reach it, from the artifacts they\n // may touch merged with their own declarations. So it is wired here\n // unconditionally, and `buildCandidateAgents` reads this map instead of\n // re-deriving the same grant from `can_execute_tools` a second time.\n appendToolForAgent(toolsByAgent, agentId, tc.id);\n\n // A toolchain's `operations` are written in the namespace of whatever\n // the toolchain names. Only a toolchain that names THIS component\n // writes them in `operationNames`; a cli/library toolchain lists its\n // own verbs (`lint`, `test`, `format`) and a toolchain naming another\n // component lists that component's operations. Neither is a name in\n // this namespace, so neither is checked against it or wired from it —\n // and an invocation that named no component has no such namespace at\n // all, so nothing is written in it.\n if (!componentIR || tc.componentId !== componentIR.info.id) continue;\n\n for (const op of tc.operations ?? []) {\n if (operationNames.has(op)) {\n appendToolForAgent(toolsByAgent, agentId, op);\n } else {\n // Keyed by the declaration, not the agent: the same toolchain is\n // derived for every agent whose artifacts it touches, and the\n // defect is one line of toolchain-contracts either way.\n unresolved.push(`${tc.id}.operations: ${op}`);\n }\n }\n }\n }\n }\n\n if (unresolved.length > 0) {\n throw new UnresolvedScopeDeclarationError(\n componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,\n [...new Set(unresolved)].sort(),\n [...operationNames].sort(),\n [...toolIds].sort(),\n );\n }\n\n return toolsByAgent;\n}\n\nfunction appendToolForAgent(\n toolsByAgent: Map<string, string[]>,\n agentId: string,\n toolName: string,\n): void {\n const existing = toolsByAgent.get(agentId) ?? [];\n if (existing.includes(toolName)) {\n return;\n }\n toolsByAgent.set(agentId, [...existing, toolName]);\n}\n\n/**\n * Per-agent guardrail rules, read through `getGuardrailRulesForAgent`\n * (lib/bound-resolver.ts) — the one predicate for \"does this agent have rules\",\n * so the scope and `dev-team guard list` cannot disagree about an agent whose\n * every rule was filtered out by the active policy.\n */\nfunction buildGuardrailsByAgent(\n resolved?: ResolvedComponent,\n): Map<string, GuardrailRuleData> {\n const guardrailsByAgent = new Map<string, GuardrailRuleData>();\n\n if (!resolved) {\n return guardrailsByAgent;\n }\n\n for (const agentId of resolved.guardrails.perAgent.keys()) {\n const rules = getGuardrailRulesForAgent(resolved, agentId);\n if (rules) {\n guardrailsByAgent.set(agentId, rules);\n }\n }\n\n return guardrailsByAgent;\n}\n\nexport function createComponentScope(\n options: CreateComponentScopeOptions = {},\n): ComponentScope {\n const resolved = options.resolvedComponent;\n const componentIR = options.component?.ir;\n\n return {\n componentId: componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,\n ...(options.component\n ? { componentIR: options.component.ir, binding: options.component.binding }\n : {}),\n toolsByAgent: buildToolsByAgent(options.dsl, resolved, componentIR),\n guardrailsByAgent: buildGuardrailsByAgent(resolved),\n ...(options.libraryTools ? { libraryTools: options.libraryTools } : {}),\n ...(resolved?.toolchainsByAgent\n ? { toolchainsByAgent: resolved.toolchainsByAgent }\n : {}),\n };\n}\n","/**\n * Model-aware adapter factory — resolves model_class (and, when guardrails are\n * agent-scoped, the executing agent) to cached SdkAdapter instances.\n *\n * Used by executeWorkflow (per-step routing) and shares cache across steps.\n * The factory's no-arg / standard call must return synchronously (workflow-runner\n * resolveAdapter contract); other model classes may return a Promise on first use.\n *\n * Guardrail hooks are fixed at adapter construction, so a workflow whose steps run\n * as different agents needs one adapter per (model, agent) pair — otherwise the\n * first step's agent scope would leak to every later step, or (as before #269) no\n * guardrails would apply at all.\n */\n\nimport { createAdapter, type CreateAdapterOptions } from \"./adapter-factory.js\";\nimport {\n createModelResolver,\n type ModelClass,\n type ModelMappingConfig,\n type ModelResolver,\n type ResolvedModel,\n} from \"./model-resolver.js\";\nimport type { ModelAwareSdkAdapterFactory } from \"./workflow-runner.js\";\nimport type { SdkAdapter } from \"./task-runner.js\";\nimport type { GuardrailHooks } from \"./guardrail-hooks.js\";\n\nexport interface ModelAwareAdapterSetup {\n factory: ModelAwareSdkAdapterFactory;\n defaultAdapter: SdkAdapter;\n modelResolver: ModelResolver;\n /** Resolve (and cache) the adapter for a model_class (+ agent scope). */\n resolveAdapter: (modelClass?: ModelClass, agentId?: string) => Promise<SdkAdapter>;\n}\n\nfunction cacheKey(resolved: ResolvedModel, agentId?: string): string {\n const base = `${resolved.adapter}:${resolved.model ?? \"\"}`;\n return agentId ? `${base}:${agentId}` : base;\n}\n\nexport async function createModelAwareAdapterSetup(options: {\n fallbackAdapter: string;\n fallbackModel?: string;\n modelMapping?: ModelMappingConfig;\n adapterOptions?: Partial<CreateAdapterOptions>;\n pinAdapter?: boolean;\n /**\n * Guardrail hooks for the agent a step runs as. When provided, adapters are\n * cached per (model, agent) and each gets that agent's hooks. Ignored when the\n * caller already supplied `adapterOptions.guardrailHooks` (an explicit override\n * wins, as it does for executeTask).\n */\n guardrailHooksForAgent?: (agentId: string) => GuardrailHooks | undefined;\n}): Promise<ModelAwareAdapterSetup> {\n const modelResolver = createModelResolver({\n modelMapping: options.modelMapping,\n fallbackAdapter: options.fallbackAdapter,\n fallbackModel: options.fallbackModel,\n pinnedAdapter: options.pinAdapter ? options.fallbackAdapter : undefined,\n });\n\n const cache = new Map<string, SdkAdapter>();\n const inflight = new Map<string, Promise<SdkAdapter>>();\n\n // An explicit caller override disables agent scoping outright: there is then one\n // hook set for the whole run, so per-agent adapters would only fragment the cache.\n const scopeHooks = options.adapterOptions?.guardrailHooks\n ? undefined\n : options.guardrailHooksForAgent;\n\n function scopeKey(agentId?: string): string | undefined {\n return scopeHooks && agentId ? agentId : undefined;\n }\n\n async function ensureAdapter(\n modelClass?: ModelClass,\n agentId?: string,\n ): Promise<SdkAdapter> {\n const resolved = modelResolver.resolve(modelClass);\n const scope = scopeKey(agentId);\n const key = cacheKey(resolved, scope);\n const hit = cache.get(key);\n if (hit) return hit;\n\n let pending = inflight.get(key);\n if (!pending) {\n const agentHooks = scope ? scopeHooks!(scope) : undefined;\n pending = createAdapter(resolved.adapter, {\n model: resolved.model,\n ...options.adapterOptions,\n ...(agentHooks ? { guardrailHooks: agentHooks } : {}),\n });\n inflight.set(key, pending);\n }\n\n try {\n const adapter = await pending;\n cache.set(key, adapter);\n return adapter;\n } finally {\n inflight.delete(key);\n }\n }\n\n const defaultAdapter = await ensureAdapter(\"standard\");\n\n const factory: ModelAwareSdkAdapterFactory = (\n modelClass?: ModelClass,\n agentId?: string,\n ) => {\n const effectiveClass: ModelClass = modelClass ?? \"standard\";\n const resolved = modelResolver.resolve(effectiveClass);\n const scope = scopeKey(agentId);\n const hit = cache.get(cacheKey(resolved, scope));\n if (hit) return hit;\n\n // workflow-runner resolveAdapter() calls factory() synchronously for primary.\n // An agent-scoped request always needs its own adapter, so it never takes this\n // shortcut (the default adapter carries no agent's hooks).\n if (effectiveClass === \"standard\" && !scope) {\n return defaultAdapter;\n }\n\n return ensureAdapter(effectiveClass, agentId);\n };\n\n return {\n factory,\n defaultAdapter,\n modelResolver,\n resolveAdapter: ensureAdapter,\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { ComponentIR, OperationIR } from \"@aaac/contracts\";\nimport type { AgentLogWriter } from \"./lib/agent-log-writer.js\";\nimport type { MemoryRef, MemoryStore } from \"./lib/memory-store.js\";\nimport type { ObserverEmitFn } from \"./lib/observability-bridge.js\";\n\nexport interface OperationMemoryRefConfig {\n output?: boolean;\n input?: boolean;\n provider?: string;\n compat?: string;\n}\n\ntype OperationWithMemoryRef = OperationIR & {\n memoryRef?: OperationMemoryRefConfig;\n};\n\nexport interface MemoryStoreEntry {\n result: unknown;\n memoryRef: MemoryRef;\n}\n\n/**\n * The component an invocation is for: the IR that declares its operations and\n * the binding that dispatches them.\n *\n * `createRuntimeBinding` is the only place that holds both — it is handed the IR\n * and returns the binding — and `dispatchOperation` is the only call from here\n * into `ctx.runtime`. So this pair is how the execution path below learns which\n * component it is executing, which is what `createComponentScope` needs to scope\n * tools and guardrails to it (#338).\n */\nexport interface InvokedComponent {\n ir: ComponentIR;\n binding: RuntimeBinding;\n}\n\nexport interface AaacInvocationContext {\n runtime: AaacRuntime;\n /** The component whose operation is being dispatched. Set by createRuntimeBinding. */\n component?: InvokedComponent;\n policy?: AaacPolicy;\n observer?: AaacObserver;\n parentRunId?: string;\n abortSignal?: AbortSignal;\n memoryRef?: MemoryRef;\n memoryStore?: MemoryStore;\n logWriter?: AgentLogWriter;\n /** Populated when resuming from a previous memory_ref. */\n resumedState?: unknown;\n /** Current run ID for this invocation chain. */\n runId?: string;\n}\n\nexport interface AaacRuntime {\n runWorkflow(\n workflowId: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n runTask(\n taskId: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n}\n\nexport interface AaacPolicy {\n assertAllowed(operationName: string): void | Promise<void>;\n}\n\nexport interface AaacObserver {\n onOperationStart?(operationName: string, input: unknown): void;\n onOperationEnd?(operationName: string, output: unknown): void;\n onOperationError?(operationName: string, error: Error): void;\n /**\n * Emit an agent-axis event to the observability pipeline.\n * Structurally matches EventCollector.emit() from @aaac/observability.\n * Pass an EventCollector instance to wire up the full pipeline.\n * When undefined, emission is a no-op (observer is optional).\n */\n emit?: ObserverEmitFn;\n}\n\nexport type OperationHandler = (\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n) => Promise<unknown>;\n\nexport interface RuntimeBinding {\n execute(\n operationName: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown>;\n getOperationNames(): string[];\n getOperationIR(name: string): OperationIR | undefined;\n}\n\nconst DEFAULT_MEMORY_PROVIDER = \"aaac-runtime\";\nconst DEFAULT_MEMORY_COMPAT = \"aaac/0.1\";\n\nfunction getMemoryRefConfig(\n op: OperationIR,\n): OperationMemoryRefConfig | undefined {\n return (op as OperationWithMemoryRef).memoryRef;\n}\n\nfunction attachMemoryRef(result: unknown, memoryRef: MemoryRef): unknown {\n if (result !== null && typeof result === \"object\" && !Array.isArray(result)) {\n return { ...result, _memoryRef: memoryRef };\n }\n return { value: result, _memoryRef: memoryRef };\n}\n\nexport function createRuntimeBinding(\n component: ComponentIR,\n handlers?: Record<string, OperationHandler>,\n): RuntimeBinding {\n const operations = component.operations;\n\n const binding: RuntimeBinding = {\n getOperationNames(): string[] {\n return Object.keys(operations);\n },\n\n getOperationIR(name: string): OperationIR | undefined {\n return operations[name];\n },\n\n async execute(\n operationName: string,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n ): Promise<unknown> {\n const op = operations[operationName];\n if (!op) {\n throw new Error(`Unknown operation: ${operationName}`);\n }\n\n const memoryConfig = getMemoryRefConfig(op);\n const runId = ctx.runId ?? ctx.parentRunId ?? randomUUID();\n const execCtx: AaacInvocationContext = {\n ...ctx,\n runId,\n component: { ir: component, binding },\n };\n\n if (ctx.memoryRef && ctx.memoryStore) {\n const stored = await ctx.memoryStore.load(ctx.memoryRef);\n if (stored !== null) {\n const entry = stored as MemoryStoreEntry;\n execCtx.resumedState = entry.result ?? stored;\n }\n }\n\n await ctx.policy?.assertAllowed(operationName);\n ctx.observer?.onOperationStart?.(operationName, input);\n\n const startTime = Date.now();\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_start\",\n runId,\n operationName,\n data: { input },\n });\n }\n\n try {\n const result = await dispatchOperation(\n operationName,\n op,\n options,\n input,\n execCtx,\n handlers,\n );\n\n let finalResult = result;\n let newMemoryRef: MemoryRef | undefined;\n\n if (memoryConfig?.output && ctx.memoryStore) {\n newMemoryRef = {\n id: randomUUID(),\n provider: memoryConfig.provider ?? DEFAULT_MEMORY_PROVIDER,\n compat: memoryConfig.compat ?? DEFAULT_MEMORY_COMPAT,\n created_at: new Date().toISOString(),\n parent_run_id: runId,\n };\n\n const entry: MemoryStoreEntry = {\n result,\n memoryRef: newMemoryRef,\n };\n await ctx.memoryStore.save(newMemoryRef, entry);\n finalResult = attachMemoryRef(result, newMemoryRef);\n }\n\n ctx.observer?.onOperationEnd?.(operationName, finalResult);\n\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_end\",\n runId,\n operationName,\n durationMs: Date.now() - startTime,\n data: { output: finalResult },\n });\n }\n\n return finalResult;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.observer?.onOperationError?.(operationName, err);\n\n if (ctx.logWriter) {\n await ctx.logWriter.writeRunEvent(runId, {\n timestamp: new Date().toISOString(),\n type: \"operation_error\",\n runId,\n operationName,\n durationMs: Date.now() - startTime,\n error: err.message,\n });\n }\n\n throw err;\n }\n },\n };\n\n return binding;\n}\n\nasync function dispatchOperation(\n operationName: string,\n op: OperationIR,\n options: Record<string, unknown>,\n input: unknown,\n ctx: AaacInvocationContext,\n handlers?: Record<string, OperationHandler>,\n): Promise<unknown> {\n if (op.agentWorkflow) {\n return ctx.runtime.runWorkflow(op.agentWorkflow, options, input, ctx);\n }\n\n if (op.agentTask) {\n return ctx.runtime.runTask(op.agentTask, options, input, ctx);\n }\n\n if (op.handler) {\n const handler = handlers?.[operationName];\n if (!handler) {\n throw new Error(\n `No handler provided for deterministic operation \"${operationName}\"`,\n );\n }\n return handler(options, input, ctx);\n }\n\n throw new Error(`Operation \"${operationName}\" has no dispatch target`);\n}\n","/**\n * Standard project runtime — the reusable, CLI-facing `AaacRuntime` that every\n * generated component CLI uses, so that NO caller hand-writes `ctx.runtime`.\n * Named \"project\" because it is driven by the external `project.yaml` manifest.\n *\n * It:\n * - discovers/loads the external `project.yaml` (walk up from cwd, or explicit\n * config path) via loadProjectConfig,\n * - resolves the effective DSL = project `agents` overlay merged over the\n * bundled `/$embedded/` component DSL (reusing executeWorkflow/executeTask's\n * loadDslContext merge — the overlay may `extends: /$embedded/` or be\n * self-contained),\n * - selects adapter/model from the project model_mapping (env/flag overrides)\n * via createModelResolver,\n * - implements runWorkflow → executeWorkflow and runTask → executeTask,\n * passing bindingPaths / activeGuardrailPolicy / artifactBinding so machine\n * guardrails operate on the merged DSL.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { createPipeline, type OtelEmitter } from \"@aaac/observability\";\nimport {\n loadProjectConfig,\n PROJECT_CONFIG_FILENAME,\n type ResolvedConfig,\n} from \"../generator/config.js\";\nimport { createModelResolver } from \"./model-resolver.js\";\nimport { executeWorkflow, executeTask } from \"./execute.js\";\nimport { loadPlugins } from \"./plugin-loader.js\";\nimport { serializeObserverEmit, type ObserverEmitFn } from \"./observability-bridge.js\";\nimport type { AaacRuntime, AaacInvocationContext } from \"../component-binding.js\";\n\nexport { PROJECT_CONFIG_FILENAME } from \"../generator/config.js\";\n\nconst DEFAULT_ADAPTER = \"claude\";\n\n/**\n * Walk up from `startDir` to the filesystem root looking for the nearest\n * `project.yaml`. Returns the absolute path, or undefined if none is found.\n */\nexport function findProjectConfig(\n startDir: string,\n filename: string = PROJECT_CONFIG_FILENAME,\n): string | undefined {\n let dir = resolve(startDir);\n for (;;) {\n const candidate = resolve(dir, filename);\n if (existsSync(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\nexport interface CreateProjectRuntimeOptions {\n /** The bundled `/$embedded/` component DSL (the component's own agent-contracts). */\n embeddedDsl: Record<string, unknown>;\n /** Explicit project.yaml path; when omitted, discovered by walking up from cwd. */\n configPath?: string;\n /** Launch directory for config discovery (defaults to process.cwd()). */\n cwd?: string;\n /** Adapter override (CLI `--adapter`); falls back to env + model_mapping. */\n adapter?: string;\n /** Model override (CLI `--model`). */\n model?: string;\n /** Environment for adapter/model resolution (defaults to process.env). */\n env?: Record<string, string | undefined>;\n /** Auto-approve workflow gates (CLI is non-interactive by default). */\n autoApproveGates?: boolean;\n}\n\nexport interface ResolvedAdapterSelection {\n adapter: string;\n model?: string;\n}\n\nexport interface ProjectRuntime {\n /** The standard AaacRuntime — assign to `ctx.runtime` (or use `.context`). */\n runtime: AaacRuntime;\n /** A ready-made invocation context with `runtime` wired in. */\n context: AaacInvocationContext;\n /** The loaded, resolved project config. */\n config: ResolvedConfig;\n /** Absolute path to the discovered/explicit project.yaml. */\n configPath: string;\n /** Absolute path to the project's `agents` overlay DSL (cfg.dslPath). */\n dslSource: string;\n /** Resolve the effective adapter + model (for --dry-run reporting). */\n resolveAdapter(): ResolvedAdapterSelection;\n /**\n * The in-process OtelEmitter created by createPipeline, when observability\n * is configured. Exposed for test verification that the otel config is\n * actually wired through to the emitter (F-002 / issue #125).\n * Undefined when bindings.observability is absent or disabled.\n */\n otelEmitter?: OtelEmitter;\n}\n\nfunction serializeRequest(input: unknown): string {\n if (typeof input === \"string\") return input;\n return JSON.stringify(input ?? {});\n}\n\n/**\n * Build the standard component runtime from the bundled embedded DSL + the\n * discovered/explicit project.yaml. Throws a clear error when no config exists.\n */\nexport async function createProjectRuntime(\n options: CreateProjectRuntimeOptions,\n): Promise<ProjectRuntime> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = options.configPath\n ? resolve(cwd, options.configPath)\n : findProjectConfig(cwd);\n\n if (!configPath || !existsSync(configPath)) {\n const where = options.configPath\n ? `config path \"${options.configPath}\"`\n : `${PROJECT_CONFIG_FILENAME} from ${cwd} upward`;\n throw new Error(\n `No ${PROJECT_CONFIG_FILENAME} found (${where}). Pass --config <path> to a project manifest.`,\n );\n }\n\n const config = await loadProjectConfig(configPath);\n const env = options.env ?? process.env;\n\n // Only overlay the project `agents` DSL when it is EXPLICITLY declared. When\n // omitted, the bundled `/$embedded/` component DSL is used as-is (no overlay).\n if (config.dslDeclared && !existsSync(config.dslPath)) {\n throw new Error(\n `Project agents DSL not found: ${config.dslPath} (referenced by ${configPath}).`,\n );\n }\n const projectDslPath = config.dslDeclared ? config.dslPath : undefined;\n\n // Manifest `plugins:` -> pluginRegistry, once, before anything can run. The\n // registry is a singleton the task/workflow runners read at execution time,\n // and which `execute.ts` hands the guardrail evaluator as a check source\n // (#331 — the evaluator holds no reference to it, being shared with hook-bin\n // processes this line never runs in). So this is the only moment it can be\n // populated from config without a caller hand-registering plugins.\n await loadPlugins(config.plugins, dirname(configPath));\n\n // In-process observability: when project.yaml declares `bindings.observability`\n // we auto-wire an in-process pipeline (config-driven, like the guardrail binding)\n // so agent-axis spans (agent.session / agent.subagent / toolchain.execution /\n // evaluate.*) are recorded to SQLite WITHOUT git/Cursor hooks. Defaults to ON\n // when the binding exists; `bindings.observability.enabled: false` opts out.\n // The DB path defaults to DEFAULT_DB_PATH and is overridable via `db_path`.\n // Build the pipeline ONCE here and flow `observer` through ExecuteOptions.\n let observer: ObserverEmitFn | undefined;\n let observerSink: { close(): void } | undefined;\n let observerClosed = false;\n let observerOtelEmitter: OtelEmitter | undefined;\n if (config.observability && config.observability.enabled !== false) {\n const pipeline = createPipeline({\n ...(config.observability.dbPath ? { dbPath: config.observability.dbPath } : {}),\n // Wire OTel endpoint from project.yaml bindings.observability.otel.\n // Falls back to OTEL_EXPORTER_OTLP_ENDPOINT env var inside OtelEmitter when absent.\n // When neither is set, OtelEmitter is a no-op (fail-open, no regression).\n otel: config.observability.otel,\n });\n observer = serializeObserverEmit(pipeline.collector.emit.bind(pipeline.collector));\n observerSink = pipeline.sink;\n observerOtelEmitter = pipeline.otelEmitter;\n }\n\n /** Close the observability sink once (idempotent). Safe when no sink was built. */\n function closeObserver(): void {\n if (observerSink && !observerClosed) {\n observerClosed = true;\n observerSink.close();\n }\n }\n\n function resolveAdapter(): ResolvedAdapterSelection {\n const explicit = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;\n if (explicit) {\n return { adapter: explicit, model: options.model };\n }\n const resolver = createModelResolver({\n modelMapping: config.model_mapping,\n fallbackAdapter: DEFAULT_ADAPTER,\n fallbackModel: options.model,\n env,\n });\n const resolved = resolver.resolve(\"standard\");\n return { adapter: resolved.adapter, model: options.model ?? resolved.model };\n }\n\n function sharedExecuteOptions() {\n const { adapter, model } = resolveAdapter();\n const explicitAdapter = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;\n return {\n adapter,\n model,\n pinAdapter: Boolean(explicitAdapter),\n dsl: options.embeddedDsl,\n projectDslPath,\n bindingPaths: config.bindingPaths,\n activeGuardrailPolicy: config.active_guardrail_policy,\n artifactBinding: config.artifactsPath\n ? { source: config.artifactsPath }\n : undefined,\n maxFollowUps: config.recovery.max_follow_ups,\n maxRetries: config.recovery.max_retries,\n modelMapping: config.model_mapping,\n progressLog: config.logging.progress_log,\n observer,\n // The manifest's `toolchains:`, for every consumer of it on the execution\n // path — `BoundResolver` derives each agent's toolchains from it (#336),\n // and `runWorkflow` runs the declared `checks` as a post-run observation\n // pass. Gating this on `observer` would have made the derivation depend on\n // whether observability happens to be configured; the observation pass\n // gates itself on `observer` where it is run (workflow-runner.ts), which\n // is the only consumer that needs the gate.\n toolchain: config.toolchainsPath\n ? {\n toolchainsPath: config.toolchainsPath,\n artifactsPath: config.artifactsPath,\n cwd,\n }\n : undefined,\n };\n }\n\n // `ctx.component` is the one thing here that is per-invocation rather than\n // per-manifest, so it is read at the call and not in sharedExecuteOptions():\n // `createRuntimeBinding` sets it to the component it dispatches for, and two\n // components sharing one project runtime must each get their own scope (#338).\n const runtime: AaacRuntime = {\n async runWorkflow(workflowId, _options, input, ctx) {\n try {\n return await executeWorkflow(workflowId, {\n ...sharedExecuteOptions(),\n component: ctx?.component,\n request: serializeRequest(input),\n autoApproveGates: options.autoApproveGates ?? true,\n });\n } finally {\n // Flush/close the in-process sink on completion (success AND exception).\n closeObserver();\n }\n },\n async runTask(taskId, _options, input, ctx) {\n try {\n return await executeTask(taskId, {\n ...sharedExecuteOptions(),\n component: ctx?.component,\n request: serializeRequest(input),\n });\n } finally {\n closeObserver();\n }\n },\n };\n\n return {\n runtime,\n context: { runtime },\n config,\n configPath,\n dslSource: projectDslPath ?? \"/$embedded/\",\n resolveAdapter,\n otelEmitter: observerOtelEmitter,\n };\n}\n","/**\n * Guard CLI commands — evaluate/list/status for guardrail enforcement.\n *\n * These functions back the `guard evaluate`, `guard list`, and `guard status`\n * sub-commands that are auto-injected by @aaac/contracts cli-generator\n * whenever `governance.guardrails: true` is declared in component.yaml.\n *\n * exit code contract (evaluate):\n * 0 = allowed / pass / warn\n * 2 = denied (permission === \"deny\")\n */\n\nimport { readFile, readdir } from \"node:fs/promises\";\nimport YAML from \"yaml\";\nimport type {\n GuardrailCheckEntry,\n GuardrailDiagnostic,\n} from \"../generator/context.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailCheckResult,\n type GuardrailRuleData,\n type HookResponse,\n toolTargetPath,\n} from \"./guardrail-hooks.js\";\nimport {\n guardrailContextToRuleData,\n resolveGuardrailContext,\n} from \"./bound-resolver.js\";\n\n// ---------------------------------------------------------------------------\n// guard evaluate\n// ---------------------------------------------------------------------------\n\nexport interface EvaluateGuardrailOptions {\n /** Raw JSON string read from stdin (HookContext format). */\n hookJson: string;\n /** Component agent-contracts DSL (contains guardrails + guardrail_policies). */\n dsl: Record<string, unknown>;\n /** Paths to software binding YAML files (contain guardrail_impl matchers). */\n bindingPaths: string[];\n /** Active guardrail policy name (from project.yaml active_guardrail_policy). */\n activeGuardrailPolicy?: string;\n}\n\nexport interface EvaluateGuardrailResult {\n /** HookResponse to write to stdout. */\n response: HookResponse;\n /**\n * CLI exit code.\n * 0 = allowed (pass or warn)\n * 2 = denied (permission === \"deny\")\n */\n exitCode: 0 | 2;\n /** All check results from all matchers. */\n checks: GuardrailCheckResult[];\n}\n\n/**\n * Evaluate a guardrail hook from a JSON string (typically stdin).\n *\n * Detects the hook type from which fields are present in the input:\n * - `command` → beforeShellExecution\n * - `tool_name` / `tool_input` → preToolUse\n * - `file_path` (without command) → afterFileEdit\n */\nexport async function evaluateGuardrail(\n opts: EvaluateGuardrailOptions,\n): Promise<EvaluateGuardrailResult> {\n let document: unknown;\n try {\n document = JSON.parse(opts.hookJson);\n } catch (cause) {\n throw new Error(\n `Invalid hook JSON: input must be valid JSON. ${(cause as Error).message}`,\n );\n }\n if (typeof document !== \"object\" || document === null || Array.isArray(document)) {\n throw new Error(\"Invalid hook JSON: input must be a JSON object.\");\n }\n const hookInput = document as Record<string, unknown>;\n\n // Same resolver as the execution path and the Claude hooks, so all three agree\n // and every declared binding contributes its checks (#267 / #268).\n const guardrailCtx = await resolveGuardrailContext(\n opts.dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n { skipMissing: true },\n );\n\n const ruleData: GuardrailRuleData = guardrailContextToRuleData(guardrailCtx);\n const hooks = createGuardrailHooksFromRules(ruleData);\n\n // Dispatch to the appropriate hook based on input fields\n const command = hookInput.command as string | undefined;\n const toolName = hookInput.tool_name as string | undefined;\n const toolInput = hookInput.tool_input as Record<string, unknown> | undefined;\n const filePath = hookInput.file_path as string | undefined;\n const content = hookInput.content as string | undefined;\n\n let response: HookResponse = {};\n let checks: GuardrailCheckResult[] = [];\n\n // A Claude Code PreToolUse payload carries the shell command in\n // `tool_input.command`; only Cursor puts it at the top level. Reading just the\n // top-level field meant `guard evaluate` silently passed every Bash command\n // Claude Code submitted (#270).\n const shellCommand = command ?? (toolInput?.command as string | undefined);\n\n if (shellCommand !== undefined) {\n // Shell execution hook\n response = hooks.beforeShellExecution({ command: shellCommand });\n checks = hooks.runChecks({ command: shellCommand });\n } else if (toolName !== undefined || toolInput !== undefined) {\n // Pre-tool-use hook\n response = hooks.preToolUse({ tool_name: toolName, tool_input: toolInput });\n const checkFilePath = toolTargetPath(toolInput);\n if (checkFilePath) {\n checks = hooks.runChecks({ filePath: checkFilePath });\n }\n } else if (filePath !== undefined) {\n // After-file-edit hook\n response = hooks.afterFileEdit({ file_path: filePath, content });\n checks = hooks.runChecks({ filePath, content });\n }\n // If no recognizable fields, response stays {} (pass)\n\n const exitCode: 0 | 2 = response.permission === \"deny\" ? 2 : 0;\n return { response, exitCode, checks };\n}\n\n// ---------------------------------------------------------------------------\n// guard list\n// ---------------------------------------------------------------------------\n\nexport interface ListGuardrailsOptions {\n /** Component agent-contracts DSL. */\n dsl: Record<string, unknown>;\n /** Paths to software binding YAML files. */\n bindingPaths: string[];\n /** Active guardrail policy name. */\n activeGuardrailPolicy?: string;\n}\n\nexport interface GuardrailListEntry {\n guardrail_id: string;\n description: string;\n matcher_type: string;\n action: string;\n severity: string;\n pattern: string;\n}\n\nexport interface ListGuardrailsResult {\n policy: string | undefined;\n entries: GuardrailListEntry[];\n /**\n * Guardrail-configuration findings. An entry whose `action` is `unresolved`\n * is explained here — without them the report shows the symptom and hides\n * the cause (#293).\n */\n diagnostics: GuardrailDiagnostic[];\n}\n\n/**\n * List all active guardrails and their enforcement settings.\n *\n * Reads DSL + binding files and builds the guardrail context for the active\n * policy, returning a flat list of guardrail_id / matcher_type / action /\n * severity rows for display.\n */\nexport async function listGuardrails(\n opts: ListGuardrailsOptions,\n): Promise<ListGuardrailsResult> {\n const guardrailCtx = await resolveGuardrailContext(\n opts.dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n { skipMissing: true },\n );\n\n const entries: GuardrailListEntry[] = guardrailCtx.allChecks.map(\n (c: GuardrailCheckEntry) => ({\n guardrail_id: c.guardrail_id,\n description: c.description,\n matcher_type: c.matcher_type,\n action: c.action,\n severity: c.severity,\n pattern: c.pattern,\n }),\n );\n\n return {\n policy: opts.activeGuardrailPolicy,\n entries,\n diagnostics: guardrailCtx.diagnostics,\n };\n}\n\n// ---------------------------------------------------------------------------\n// guard status\n// ---------------------------------------------------------------------------\n\nexport interface GuardStatusOptions {\n /** Base directory for agent logs (defaults to \".agent-logs\"). */\n baseDir?: string;\n /** Maximum number of recent run events to return (defaults to 10). */\n limit?: number;\n}\n\nexport interface GuardStatusResult {\n hasHistory: boolean;\n message: string;\n /** Recent run log events (operation_start/end, etc.). */\n recentEvents: unknown[];\n}\n\n/**\n * Show recent guardrail evaluation summary.\n *\n * Phase 1 limitation: RunLogEvent does not yet include a `guardrail_evaluate`\n * event type, so this command reports general run history from .agent-logs/runs/.\n * Guard-specific event tracking will be added in a future phase.\n *\n * Gracefully returns \"no evaluation history\" when .agent-logs/ does not exist.\n */\nexport async function guardStatus(\n opts: GuardStatusOptions = {},\n): Promise<GuardStatusResult> {\n const baseDir = opts.baseDir ?? \".agent-logs\";\n const runsDir = `${baseDir}/runs`;\n const limit = opts.limit ?? 10;\n\n let files: string[] = [];\n try {\n files = await readdir(runsDir);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return {\n hasHistory: false,\n message:\n \"No evaluation history. Note: guardrail_evaluate event type is not yet tracked in Phase 1.\",\n recentEvents: [],\n };\n }\n throw err;\n }\n\n const jsonlFiles = files\n .filter((f) => f.endsWith(\".jsonl\"))\n .sort()\n .reverse()\n .slice(0, limit);\n\n if (jsonlFiles.length === 0) {\n return {\n hasHistory: false,\n message: \"No evaluation history.\",\n recentEvents: [],\n };\n }\n\n const recentEvents: unknown[] = [];\n for (const file of jsonlFiles) {\n const filePath = `${runsDir}/${file}`;\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch {\n continue;\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as unknown;\n } catch {\n return null;\n }\n })\n .filter(Boolean);\n recentEvents.push(...events);\n if (recentEvents.length >= limit) break;\n }\n\n const count = recentEvents.length;\n return {\n hasHistory: count > 0,\n message:\n count > 0\n ? `${count} recent run event(s) found. Note: guardrail_evaluate events are not yet tracked in Phase 1.`\n : \"No evaluation history.\",\n recentEvents: recentEvents.slice(0, limit),\n };\n}\n","import { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// ClaudeConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Per-workflow slash-command emission (#249).\n *\n * Renders ONE Handlebars-templated file per agent-contracts `workflow` to a\n * `{name}`-placeholder output path (default use case: Claude Code slash commands\n * at `.claude/commands/aidev/{name}.md`). Symmetric with `emit.workflows` (#235)\n * and wired into the SAME sync/check machinery.\n *\n * Shape: accepts either a bare `true` (use all defaults) or an object with\n * optional overrides. `false`/absent = disabled (backward compatible). A bundled\n * default template ships in `command-render.ts` so the default use case needs no\n * consumer-authored template; `template` (a project-root-relative path) overrides it.\n */\nconst ClaudeCommandsEmitSchema = z\n .object({\n /**\n * Project-root-relative output path with a required `{name}` placeholder.\n * Defaults to `.claude/commands/aidev/{name}.md` (resolved in materialize.ts\n * against DEFAULT_COMMAND_OUTPUT so the default lives with the renderer).\n */\n output: z.string().optional(),\n /**\n * Project-root-relative path to a custom Handlebars template. When omitted,\n * the bundled default template (command-render.ts) is used.\n */\n template: z.string().optional(),\n })\n .strip();\n\nexport type ClaudeCommandsEmit = z.infer<typeof ClaudeCommandsEmitSchema>;\n\n/**\n * Normalize the `commands` toggle: a bare `true` becomes an empty override object\n * (all defaults); `false`/absent becomes disabled (undefined).\n */\nconst ClaudeCommandsToggle = z\n .union([z.boolean(), ClaudeCommandsEmitSchema])\n .optional()\n .transform((v): ClaudeCommandsEmit | undefined => {\n if (v === undefined || v === false) return undefined;\n if (v === true) return {};\n return v;\n });\n\n/**\n * Emission toggles for additive Claude artifacts.\n *\n * Backward compatible: with all toggles off (the defaults) the generator emits\n * ONLY the existing `.claude/*` hooks/CLAUDE.md output, byte-for-byte unchanged.\n * - `workflows: true` → one Dynamic Workflow script per workflow (#235).\n * - `commands` (true or an override object) → one slash-command file per\n * workflow (#249).\n * - `agents: true` → one Claude Code subagent file per agent (#272).\n */\nconst ClaudeEmitSchema = z\n .object({\n /** When true, materialize `<output_dir>/workflows/<id>.js` per workflow. */\n workflows: z.boolean().default(false),\n /** When set, materialize one slash-command file per workflow (#249). */\n commands: ClaudeCommandsToggle,\n /**\n * When true, materialize `<output_dir>/agents/<id>.md` per DSL agent, so\n * DSL-declared agents are real Claude Code subagents (#272). In a workspace\n * every member's agents are merged into the single root directory.\n */\n agents: z.boolean().default(false),\n })\n .strip();\n\nexport type ClaudeEmit = z.infer<typeof ClaudeEmitSchema>;\n\nexport const ClaudeConfigSchema = z\n .object({\n /** Root directory for Claude artifacts (relative to the project root). */\n output_dir: z.string().default(\".claude\"),\n /**\n * Agents DSL path (relative to the project root) baked into the generated\n * nav hook bins as the FALLBACK for a project root with no `project.yaml`\n * (a bare component checkout). When a manifest exists it is authoritative:\n * the hooks resolve `agents:` and `artifacts:` from it at hook runtime\n * (#260), so this value is not consulted.\n */\n config_path: z.string().default(\"./agent-contracts.yaml\"),\n /**\n * Additive-artifact emission toggles. Defaults keep the historical\n * behavior (no workflow scripts) so existing output is byte-preserved.\n */\n emit: ClaudeEmitSchema.default({ workflows: false, commands: undefined, agents: false }),\n /**\n * Command wired into guardrail hooks (e.g. \"dev-team guard evaluate\").\n * Reserved for future hook integration; validated for config parity.\n */\n guard_command: z.string().optional(),\n /** Override component id; defaults to `dsl.system.id`. */\n component_id: z.string().optional(),\n })\n .strip();\n\nexport type ClaudeConfig = z.infer<typeof ClaudeConfigSchema>;\n\n/** Parse and default-fill an opaque config payload from component.yaml. */\nexport function parseClaudeConfig(raw: unknown): ClaudeConfig {\n return ClaudeConfigSchema.parse(raw ?? {});\n}\n","/**\n * Claude Dynamic Workflow script codegen (#235).\n *\n * Compiles each agent-contracts workflow in a resolved DSL into ONE Claude\n * Dynamic Workflow script (`<output_dir>/workflows/<id>.js`) — a static\n * artifact, symmetric in spirit to `@aaac/binding-cursor`'s `.cursor/*`\n * output but wired into the existing `claude sync`/`check` commands.\n *\n * The generated `.js` is executed by the Claude Code harness, NOT by aaac's\n * own runtime. It conforms to the target format in the spec (docs/proposal/\n * claude-workflow-codegen.md §2): a pure `meta` object literal plus a body\n * that uses only the documented globals (`agent`/`pipeline`/`parallel`/\n * `phase`/`log`/`workflow`/`args`/`budget`). No `Date.now`/`Math.random`/\n * argless `new Date()`.\n *\n * The DSL→script mapping mirrors `workflow-runner.ts` semantics:\n * - delegate → `agent(renderedPrompt, { schema, label, phase, model, effort })`\n * - gate → LLM-evaluator `agent()` (reusing `buildGateEvaluationPrompt`)\n * followed by a plain JS `if` branch\n * - evaluate → a bounded `while` loop honoring loop_to/max_iterations/on_exhausted\n * - depends_on → parallel()/sequential grouping via the runner's DAG rules\n * - model_class → model/effort\n *\n * `decision`/`team_task` are OUT OF SCOPE: the codegen throws a clear error so\n * they are never silently dropped.\n */\n\nimport { resolveSchemaRefs } from \"agent-contracts\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport {\n buildTaskPrompt,\n type AgentContractLike,\n type TaskContractLike,\n} from \"../task-runner.js\";\nimport type { ModelClass } from \"../model-resolver.js\";\nimport { buildAgentRegistry } from \"../dsl-context.js\";\nimport { buildGateEvaluationPrompt, type GateStep } from \"../workflow-runner.js\";\nimport { WORKFLOW_INPUT_STEP_ID, stepDependsOnWorkflowInput } from \"../workflow-input.js\";\nimport { mergeSourceFiles, originLabel, type DslSource } from \"./dsl-sources.js\";\n\n/** A file to be materialized (path relative to project root). */\nexport interface RenderedFile {\n path: string;\n content: string;\n}\n\n/**\n * Auto-generated banner. Mirrors the cursor binding's `render.ts` convention so\n * `check` can detect hand edits. A leading `//` line keeps the file valid JS.\n */\nconst GENERATED_MARKER =\n \"// Auto-generated by @aaac/runtime claude-materialize (#235). Do not edit; run `claude sync` instead.\";\n\n/**\n * model_class → model/effort mapping (spec §3.4). Absent model_class → omit\n * (inherit from the harness default).\n *\n * Keyed by the declared vocabulary: a class added to the `model_mapping`\n * declaration and left out here is a compile error, not a generated workflow\n * that silently drops the class's routing. Which Claude model a new class maps\n * to is a choice this file cannot derive.\n */\nconst MODEL_CLASS_MAP: Record<ModelClass, { model: string; effort?: string }> = {\n fast: { model: \"haiku\" },\n standard: { model: \"sonnet\" },\n thinking: { model: \"opus\", effort: \"high\" },\n};\n\n// ---------------------------------------------------------------------------\n// Minimal duck-typed views of the resolved DSL\n// ---------------------------------------------------------------------------\n\nexport interface RawStep {\n type: string;\n task?: string;\n from_agent?: string;\n gate_kind?: string;\n description?: string;\n depends_on?: string[];\n /** See the note on `buildWorkflowStep` (dsl-context.ts) for the `x-` prefix. */\n \"x-instruction\"?: string;\n loop_to?: string;\n max_iterations?: number;\n inject_as?: string;\n on_exhausted?: \"abort\" | \"fail_partial\" | \"escalate\";\n}\n\nexport interface RawWorkflow {\n description?: string;\n trigger?: string;\n steps?: RawStep[];\n}\n\ninterface RawHandoffType {\n schema?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/** Thrown when a workflow contains an out-of-scope or malformed step. */\nexport class WorkflowCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WorkflowCodegenError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// JS literal emission (plain-JS-safe, single-quoted, no interpolation)\n// ---------------------------------------------------------------------------\n\n/** Emit a JS string literal (single-quoted) for an arbitrary string. */\nfunction jsString(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\")}'`;\n}\n\n/** Emit a JS value literal (recursively) — used for `meta` and schemas. */\nfunction jsLiteral(value: unknown, indent = 0): string {\n const pad = \" \".repeat(indent);\n const padIn = \" \".repeat(indent + 1);\n\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"null\";\n if (typeof value === \"string\") return jsString(value);\n\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n const items = value.map((v) => `${padIn}${jsLiteral(v, indent + 1)}`);\n return `[\\n${items.join(\",\\n\")}\\n${pad}]`;\n }\n\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n if (entries.length === 0) return \"{}\";\n const lines = entries.map(\n ([k, v]) => `${padIn}${jsKey(k)}: ${jsLiteral(v, indent + 1)}`,\n );\n return `{\\n${lines.join(\",\\n\")}\\n${pad}}`;\n }\n\n return \"null\";\n}\n\n/** Emit an object key: a bare identifier when safe, otherwise a quoted string. */\nfunction jsKey(key: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : jsString(key);\n}\n\n// ---------------------------------------------------------------------------\n// DAG grouping (mirrors workflow-runner.ts depends_on resolution)\n// ---------------------------------------------------------------------------\n\n/** Stable identity of a step for depends_on resolution (matches the runner). */\nfunction stepIdentity(step: RawStep): string {\n if (step.type === \"gate\") return `gate:${step.gate_kind ?? \"\"}`;\n return step.task ?? \"\";\n}\n\n/**\n * Resolve each step's dependency indices exactly as `runWorkflow` does:\n * if `depends_on` is set, map each named dep to the preceding step index\n * (dropping the virtual `workflow-input` entry node); otherwise depend on all\n * preceding steps (sequential default).\n */\nfunction resolveDeps(steps: RawStep[]): number[][] {\n return steps.map((step, i) => {\n if (step.depends_on !== undefined) {\n return step.depends_on\n .filter((dep) => dep !== \"workflow-input\")\n .map((dep) => {\n const idx = steps.findIndex((s, j) => j < i && stepIdentity(s) === dep);\n if (idx === -1) {\n throw new WorkflowCodegenError(\n `depends_on \"${dep}\" in step ${i} (${stepIdentity(step)}) not found among preceding steps`,\n );\n }\n return idx;\n });\n }\n return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);\n });\n}\n\n/**\n * Topologically group steps into ordered \"waves\". Each wave is the set of steps\n * whose dependencies are all satisfied by earlier waves — the same readiness\n * rule the runner uses to batch steps into a `Promise.all`. A wave with more\n * than one member compiles to `parallel([...])`; a singleton wave runs inline.\n */\nfunction computeWaves(steps: RawStep[], deps: number[][]): number[][] {\n const completed = new Set<number>();\n const waves: number[][] = [];\n while (completed.size < steps.length) {\n const ready: number[] = [];\n for (let i = 0; i < steps.length; i++) {\n if (completed.has(i)) continue;\n if (deps[i].every((d) => completed.has(d))) ready.push(i);\n }\n if (ready.length === 0) {\n throw new WorkflowCodegenError(\n \"Dependency cycle detected: no steps are ready to schedule\",\n );\n }\n waves.push(ready);\n for (const i of ready) completed.add(i);\n }\n return waves;\n}\n\n// ---------------------------------------------------------------------------\n// Prompt / schema helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build the STATIC part of the rendered delegate prompt the runtime sends via\n * runTask (buildTaskPrompt over the resolved agent + task contracts). The step's\n * `instruction` (falling back to a generic placeholder) plays the role of the\n * per-invocation user_request.\n *\n * Prior-step context is deliberately NOT baked in here: in the Claude Workflow\n * harness each `agent()` is an independent subagent that does NOT auto-inherit\n * upstream outputs. The generated script therefore threads the accumulated\n * prior-step context into each call at RUN TIME (see `priorContextExpr` /\n * `withPriorContext`), mirroring how `workflow-runner.ts` builds `prior_context`\n * from the dependency chain and passes it to each step.\n */\nfunction renderDelegatePrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n step: RawStep,\n): string {\n const userRequest = (step[\"x-instruction\"] ?? step.description ?? \"\").trim() || \"Perform the task described above.\";\n return buildTaskPrompt(agent, task, { user_request: userRequest });\n}\n\n/**\n * The runtime prefix that introduces threaded prior-step context, matching the\n * `## Prior Context` section `buildSplitTaskPrompt` emits (a section separated\n * from the static prompt by `\\n\\n---\\n\\n`). Concatenated with the runtime\n * context string when a step has upstream dependencies.\n */\nconst PRIOR_CONTEXT_PREFIX = \"\\n\\n---\\n\\n## Prior Context\\n\";\n\nconst GATE_SCHEMA = {\n type: \"object\",\n properties: {\n approved: { type: \"boolean\" },\n reason: { type: \"string\" },\n },\n required: [\"approved\"],\n} as const;\n\n/**\n * Resolve a task's result-handoff JSON Schema into a self-contained\n * (`$ref`-free) schema via agent-contracts' resolveSchemaRefs. Returns\n * undefined when the task has no handoff or the type is unknown.\n */\nfunction resolveHandoffSchema(\n task: TaskContractLike,\n handoffTypes: Record<string, RawHandoffType>,\n components: Record<string, Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n const id = task.result_handoff;\n if (!id) return undefined;\n const ht = handoffTypes[id];\n if (!ht?.schema) return undefined;\n return resolveSchemaRefs(ht.schema, components);\n}\n\n// ---------------------------------------------------------------------------\n// Registries derived from the resolved DSL\n// ---------------------------------------------------------------------------\n\ninterface Registries {\n agents: Record<string, AgentContractLike>;\n tasks: Record<string, TaskContractLike>;\n handoffTypes: Record<string, RawHandoffType>;\n components: Record<string, Record<string, unknown>>;\n}\n\nfunction toTaskContract(id: string, raw: Record<string, unknown>): TaskContractLike {\n return {\n id,\n description: (raw.description as string) ?? \"\",\n target_agent: (raw.target_agent as string) ?? \"\",\n result_handoff: (raw.result_handoff as string) ?? \"\",\n completion_criteria: (raw.completion_criteria as string[]) ?? [],\n model_class: raw.model_class as ModelClass | undefined,\n };\n}\n\nfunction buildRegistries(dsl: Record<string, unknown>): Registries {\n const rawTasks = (dsl.tasks as Record<string, Record<string, unknown>>) ?? {};\n // Agent normalization is shared with the execution path and with the\n // `.claude/agents/*.md` emitter — one definition in dsl-context.ts.\n const agents = buildAgentRegistry(dsl);\n const tasks: Record<string, TaskContractLike> = {};\n for (const [id, t] of Object.entries(rawTasks)) tasks[id] = toTaskContract(id, t);\n const componentsRoot = (dsl.components as Record<string, unknown>) ?? {};\n const components =\n (componentsRoot.schemas as Record<string, Record<string, unknown>>) ??\n (componentsRoot as Record<string, Record<string, unknown>>);\n return {\n agents,\n tasks,\n handoffTypes: (dsl.handoff_types as Record<string, RawHandoffType>) ?? {},\n components,\n };\n}\n\n// ---------------------------------------------------------------------------\n// meta header\n// ---------------------------------------------------------------------------\n\n/**\n * Phase groups: one `phases[]` entry per emitted phase title, in emission\n * order. Delegate steps map to a phase named after their step; gate steps map\n * to a single \"Gate\" phase.\n */\nfunction phaseTitle(step: RawStep): string {\n if (step.type === \"gate\") return \"Gate\";\n return step.task ?? \"Step\";\n}\n\nfunction buildMeta(\n id: string,\n wf: RawWorkflow,\n steps: RawStep[],\n): Record<string, unknown> {\n const seen = new Set<string>();\n const phases: Array<{ title: string; detail?: string }> = [];\n for (const step of steps) {\n const title = phaseTitle(step);\n if (seen.has(title)) continue;\n seen.add(title);\n const detail = (step.description ?? \"\").trim().split(\"\\n\")[0]?.trim();\n phases.push(detail ? { title, detail } : { title });\n }\n\n const meta: Record<string, unknown> = {\n name: id,\n description: (wf.description ?? \"\").trim() || id,\n };\n if (wf.trigger) meta.whenToUse = wf.trigger.trim();\n if (phases.length > 0) meta.phases = phases;\n return meta;\n}\n\n// ---------------------------------------------------------------------------\n// Per-step body emission\n// ---------------------------------------------------------------------------\n\nfunction agentOpts(\n task: TaskContractLike,\n step: RawStep,\n handoffSchema: Record<string, unknown> | undefined,\n indent: number,\n): string {\n const opts: Record<string, unknown> = {};\n if (handoffSchema) opts.schema = handoffSchema;\n opts.label = task.id;\n opts.phase = phaseTitle(step);\n const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : undefined;\n if (mc) {\n opts.model = mc.model;\n if (mc.effort) opts.effort = mc.effort;\n }\n return jsLiteral(opts, indent);\n}\n\n/** The result-variable name a step's captured `agent()`/gate output binds to. */\nfunction resultVar(i: number): string {\n return `step${i}Result`;\n}\n\n/**\n * Emit the run-time expression that reconstructs the accumulated prior-step\n * context for step `i`, mirroring `workflow-runner.ts` `contextFor`/`stepContexts`.\n *\n * The runner formats each dependency's output as\n * `\\n\\n--- Step {d+1}: {stepId(d)} ---\\n{data as string or pretty JSON}`\n * and joins the chain. Here each dependency's captured result variable is\n * formatted by the emitted `_ctx` helper and the fragments are concatenated. A\n * gate step contributes no output fragment (it is a control-flow branch), so\n * gate indices are excluded from every downstream dependency chain — matching\n * the runner, where a gate result carries no `data`.\n *\n * When the step DSL-declares `depends_on: [workflow-input]`, the runtime\n * `contextFor` prepends `formatWorkflowInputContext(workflowInputOutput)` to the\n * chain (BEFORE the output-bearing deps). We mirror that here by emitting a\n * leading `_wfInput(args)` fragment — the run-time equivalent of materializing\n * the Workflow tool's `args` global as the `workflow-input` output node (#244).\n *\n * Returns `\"\"` when the step has neither workflow-input nor any output-bearing\n * dependency (the runner passes an empty prior_context in that case).\n */\nfunction priorContextExpr(i: number, steps: RawStep[], deps: number[][]): string {\n const fragments: string[] = [];\n if (stepDependsOnWorkflowInput(steps[i].depends_on)) {\n fragments.push(\"_wfInput(args)\");\n }\n const contribs = deps[i].filter((d) => steps[d].type !== \"gate\");\n for (const d of contribs) {\n fragments.push(`_ctx(${d + 1}, ${jsString(stepIdentity(steps[d]))}, ${resultVar(d)})`);\n }\n if (fragments.length === 0) return \"\";\n return fragments.join(\" + \");\n}\n\n/**\n * Emit the `_wfInput` helper — the run-time equivalent of materializing the\n * Workflow tool's `args` global as the virtual `workflow-input` output node and\n * formatting it for injection into a step's prior context (#244).\n *\n * Faithfully mirrors `workflow-input.ts`:\n * - `buildWorkflowInputOutput(user_request, handoff?)` →\n * `{ user_request, ...(handoff ? { handoff: { type, [version], payload } } : {}) }`\n * - `formatWorkflowInputContext(output)` →\n * `\\n\\n--- Step: workflow-input ---\\n${JSON.stringify(output, null, 2)}`\n *\n * `args` shapes (mirroring WorkflowInvocation → resolveInvocation → buildWorkflowInputOutput):\n * - string → user_request (the simple-string convenience input)\n * - object with `user_request` and/or `handoff` → those fields carried through\n * (a typed handoff: user_request falls back to the stringified payload, as\n * resolveInvocation does)\n * - any other object → treated as a typed handoff payload of type\n * `workflow-input`, with user_request = its pretty-printed JSON\n * - undefined/null → '' (no injection; backward-compatible static fallback)\n */\nfunction emitWorkflowInputHelper(pad: string): string[] {\n const id = WORKFLOW_INPUT_STEP_ID;\n // A single arrow function, authored at column 0 then indented, so the whole\n // helper is one emitted statement (const _wfInput = (args) => { ... }).\n return [\n `${pad}const _wfInput = (args) => {`,\n `${pad} if (args === undefined || args === null) return ''`,\n `${pad} let output`,\n `${pad} if (typeof args === 'string') {`,\n `${pad} output = { user_request: args }`,\n `${pad} } else if (typeof args === 'object' && ('user_request' in args || 'handoff' in args)) {`,\n `${pad} const h = args.handoff`,\n `${pad} const userRequest = typeof args.user_request === 'string'`,\n `${pad} ? args.user_request`,\n `${pad} : h`,\n `${pad} ? (typeof h.payload === 'string' ? h.payload : JSON.stringify(h.payload, null, 2))`,\n `${pad} : ''`,\n `${pad} output = h`,\n `${pad} ? { user_request: userRequest, handoff: (h.version !== undefined ? { type: h.type, version: h.version, payload: h.payload } : { type: h.type, payload: h.payload }) }`,\n `${pad} : { user_request: userRequest }`,\n `${pad} } else {`,\n `${pad} output = { user_request: JSON.stringify(args, null, 2), handoff: { type: ${jsString(id)}, payload: args } }`,\n `${pad} }`,\n `${pad} return '\\\\n\\\\n--- Step: ${id} ---\\\\n' + JSON.stringify(output, null, 2)`,\n `${pad}}`,\n ];\n}\n\n/**\n * A loop-injected feedback variable to append to a step's prompt, matching the\n * runner merging `inject_as` feedback into a step's `variables` (rendered as a\n * `## Context Variables` line). Present only for steps re-run inside an\n * evaluate loop that declares `inject_as`.\n */\ninterface FeedbackInjection {\n /** The `inject_as` key (the context-variable name). */\n injectAs: string;\n /** The JS variable holding the current iteration's feedback text. */\n feedbackVar: string;\n}\n\n/**\n * Wrap a static base prompt so the threaded prior-step context (and, inside an\n * evaluate loop, the injected feedback) is appended at run time — mirroring the\n * runner passing `prior_context` + merged `variables` into each step. When the\n * step has neither upstream output nor injected feedback, the base prompt is\n * emitted verbatim.\n *\n * The `## Prior Context` header is only appended when the run-time context\n * string is non-empty, mirroring workflow-runner/buildSplitTaskPrompt which\n * emits the section only `if (context.prior_context)`. This matters for a step\n * that depends ONLY on `workflow-input`: when the `args` global is undefined\n * (backward-compat static invocation), `_wfInput(args)` yields '' and the step\n * falls back to its static prompt with no dangling header (#244).\n */\nfunction withPriorContext(\n basePromptLiteral: string,\n ctxExpr: string,\n feedback?: FeedbackInjection,\n): string {\n let expr = basePromptLiteral;\n if (ctxExpr) {\n // Guard on the run-time context value so an empty context (e.g. undefined\n // `args` for a workflow-input-only step) omits the section entirely.\n expr = `${expr} + ((${ctxExpr}) ? ${jsString(PRIOR_CONTEXT_PREFIX)} + (${ctxExpr}) : '')`;\n }\n if (feedback) {\n // Emitted only inside the loop, so the guard skips the first iteration\n // (feedbackVar is still undefined then) — matching the runner, which only\n // injects feedback on loop-back, not on the initial pass.\n const varSection = `${jsString(`\\n\\n---\\n\\n## Context Variables\\n\\n- ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;\n expr = `${expr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;\n }\n return expr;\n}\n\n/**\n * Resolve the (agent, task) pair for a delegate/evaluate step, throwing the\n * appropriate WorkflowCodegenError when unknown.\n */\nfunction resolveStepAgentTask(\n step: RawStep,\n reg: Registries,\n kind: \"delegate\" | \"evaluate\",\n): { agent: AgentContractLike; task: TaskContractLike; taskId: string } {\n const taskId = step.task ?? \"\";\n const task = reg.tasks[taskId];\n if (!task) {\n throw new WorkflowCodegenError(`${kind} step references unknown task \"${taskId}\"`);\n }\n const agent = reg.agents[task.target_agent] ?? reg.agents[step.from_agent ?? \"\"];\n if (!agent) {\n throw new WorkflowCodegenError(\n `${kind} task \"${taskId}\" targets unknown agent \"${task.target_agent}\"`,\n );\n }\n return { agent, task, taskId };\n}\n\n/**\n * Emit the JS expression that runs a single delegate step (an `agent()` call),\n * threading the step's accumulated prior-step context into the prompt at run\n * time.\n */\nfunction emitDelegateExpr(\n step: RawStep,\n reg: Registries,\n i: number,\n steps: RawStep[],\n deps: number[][],\n indent: number,\n feedback?: FeedbackInjection,\n): string {\n const { agent, task } = resolveStepAgentTask(step, reg, \"delegate\");\n const prompt = renderDelegatePrompt(agent, task, step);\n const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);\n const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);\n const opts = agentOpts(task, step, schema, indent);\n return `agent(${promptExpr}, ${opts})`;\n}\n\n/**\n * Emit the statements for a gate step: an LLM-evaluator `agent()` call reusing\n * buildGateEvaluationPrompt, then a plain JS `if` branch (spec §3.2).\n *\n * The gate evaluator receives the ACTUAL accumulated prior-step results,\n * threaded at run time (mirroring `evaluateGateWithLlm`, which feeds prior\n * results into `buildGateEvaluationPrompt`). The static template only holds the\n * gate kind + condition; the prior-results section is appended at run time.\n */\nfunction emitGateStatements(\n step: RawStep,\n i: number,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n feedback?: FeedbackInjection,\n): string[] {\n const gateStep: GateStep = {\n type: \"gate\",\n gate_kind: step.gate_kind ?? \"\",\n description: step.description ?? \"\",\n };\n // Split buildGateEvaluationPrompt at its \"## Prior Step Results\" section so\n // the run-time prior context (the same fragments delegate steps receive) can\n // be spliced in where the runner puts prior results.\n const marker = \"## Prior Step Results\\n\";\n const full = buildGateEvaluationPrompt(gateStep, \"__PRIOR__\");\n const at = full.indexOf(marker) + marker.length;\n const head = full.slice(0, at);\n const tail = full.slice(at).replace(/^__PRIOR__/, \"\");\n const ctxExpr = priorContextExpr(i, steps, deps);\n let promptExpr = ctxExpr\n ? `${jsLiteral(head)} + (${ctxExpr}) + ${jsLiteral(tail)}`\n : jsLiteral(full.replace(\"__PRIOR__\", \"(no prior results)\"));\n if (feedback) {\n const varSection = `${jsString(`\\n\\n## Context Variables\\n\\n- ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;\n promptExpr = `${promptExpr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;\n }\n const label = `gate:${gateStep.gate_kind}`;\n const lines: string[] = [];\n lines.push(`${pad}const gate = await agent(${promptExpr}, {`);\n lines.push(`${pad} schema: ${jsLiteral(GATE_SCHEMA, 0).replace(/\\n/g, `\\n${pad} `)},`);\n lines.push(`${pad} label: ${jsString(label)},`);\n lines.push(`${pad} phase: 'Gate',`);\n lines.push(`${pad}})`);\n lines.push(`${pad}if (!gate.approved) {`);\n lines.push(`${pad} return { blocked: true, gate: ${jsString(gateStep.gate_kind)}, reason: gate.reason }`);\n lines.push(`${pad}}`);\n return lines;\n}\n\n/**\n * Emit the `await agent(...)` call for the evaluate step's convergence task.\n * The evaluate task, like a delegate, receives the accumulated prior-step\n * context threaded at run time, plus any feedback injected on loop-back.\n */\nfunction emitEvaluateAgentCall(\n step: RawStep,\n reg: Registries,\n i: number,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n feedback?: FeedbackInjection,\n): string {\n const { agent, task } = resolveStepAgentTask(step, reg, \"evaluate\");\n const prompt = renderDelegatePrompt(agent, task, step);\n const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);\n const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);\n const opts: Record<string, unknown> = {};\n if (schema) opts.schema = schema;\n opts.label = task.id;\n opts.phase = phaseTitle(step);\n const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : undefined;\n if (mc) {\n opts.model = mc.model;\n if (mc.effort) opts.effort = mc.effort;\n }\n const optsLiteral = jsLiteral(opts, 0).replace(/\\n/g, `\\n${pad}`);\n return `await agent(${promptExpr}, ${optsLiteral})`;\n}\n\n/**\n * Emit the statements for a single non-evaluate step (delegate or gate),\n * capturing the step's output into its result variable so downstream steps can\n * thread it as prior context. Used both in the linear body and inside an\n * evaluate loop body when re-running the `loop_to..evaluate` span.\n */\nfunction emitStepStatements(\n i: number,\n reg: Registries,\n steps: RawStep[],\n deps: number[][],\n pad: string,\n opts?: { assign?: boolean; feedback?: FeedbackInjection },\n): string[] {\n const step = steps[i];\n const feedback = opts?.feedback;\n if (step.type === \"delegate\") {\n const expr = emitDelegateExpr(step, reg, i, steps, deps, pad.length / 2 + 1, feedback);\n // `assign` mode: the result var is pre-declared with `let` (span steps\n // re-run inside an evaluate loop). Otherwise declare with `const`.\n const lhs = opts?.assign ? resultVar(i) : `const ${resultVar(i)}`;\n return [`${pad}${lhs} = await ${expr}`];\n }\n if (step.type === \"gate\") {\n // A gate never loops back and yields no output fragment; emit its branch.\n return emitGateStatements(step, i, steps, deps, pad, feedback);\n }\n throw new WorkflowCodegenError(`emitStepStatements called with non-simple step type \"${step.type}\"`);\n}\n\n/**\n * Emit an evaluate step as a bounded loop that RE-RUNS the `loop_to..evaluate`\n * span on each failing iteration (mirroring `workflow-runner.ts`, which resets\n * and re-executes steps `[loopToIdx, i]`). Steps before `loop_to` have already\n * run once in the linear body; only the span is re-executed here.\n *\n * Iteration bound matches the runner: `max_iterations = N` → up to N executions\n * of the span, escalating/aborting only once the Nth evaluation still fails.\n * The gap feedback from the failed evaluation is injected (via `inject_as`)\n * into the re-run so the upstream step sees it.\n */\nfunction emitEvaluateLoop(\n evalIdx: number,\n reg: Registries,\n steps: RawStep[],\n deps: number[][],\n): string[] {\n const step = steps[evalIdx];\n const taskId = step.task ?? \"\";\n const loopTo = step.loop_to ?? \"\";\n const maxIter = step.max_iterations ?? 1;\n const onExhausted = step.on_exhausted ?? \"escalate\";\n const injectAs = step.inject_as;\n\n // Locate the loop_to target among preceding steps (matches the runner).\n const loopToIdx = steps.findIndex((s, j) => j < evalIdx && stepIdentity(s) === loopTo);\n if (loopToIdx === -1) {\n throw new WorkflowCodegenError(\n `evaluate step \"${taskId}\" references unknown loop_to \"${loopTo}\"`,\n );\n }\n\n // The span [loopToIdx, evalIdx-1] is re-run inside the loop; the evaluate\n // agent call is the last statement of the loop body.\n const spanIndices: number[] = [];\n for (let k = loopToIdx; k < evalIdx; k++) spanIndices.push(k);\n\n const iterVar = `${resultVar(evalIdx)}Iteration`;\n const feedbackVar = injectAs ? `${resultVar(evalIdx)}Feedback` : undefined;\n const feedback: FeedbackInjection | undefined =\n injectAs && feedbackVar ? { injectAs, feedbackVar } : undefined;\n\n const lines: string[] = [];\n lines.push(` // evaluate: ${taskId} — bounded convergence loop, re-runs steps ${loopTo}..${taskId} (max ${maxIter})`);\n // Pre-declare span result vars with `let` so they are visible to steps after\n // the loop (which may depend_on them) and reassignable across iterations.\n for (const k of spanIndices) {\n if (steps[k].type !== \"gate\") lines.push(` let ${resultVar(k)}`);\n }\n lines.push(` let ${resultVar(evalIdx)}`);\n lines.push(` let ${iterVar} = 0`);\n if (feedbackVar) lines.push(` let ${feedbackVar}`);\n lines.push(` while (true) {`);\n lines.push(` ${iterVar} = ${iterVar} + 1`);\n // Re-run the loop_to..evaluate span. On iterations after the first, the\n // upstream steps see the injected feedback appended to their prior context.\n for (const k of spanIndices) {\n for (const stmt of emitStepStatements(k, reg, steps, deps, \" \", { assign: true, feedback })) {\n lines.push(stmt);\n }\n }\n // The evaluate agent call itself, receiving prior context + injected feedback.\n const evalCall = emitEvaluateAgentCall(step, reg, evalIdx, steps, deps, \" \", feedback);\n lines.push(` ${resultVar(evalIdx)} = ${evalCall}`);\n lines.push(` if (${resultVar(evalIdx)}.verdict === 'pass') break`);\n lines.push(` if (${iterVar} >= ${maxIter}) {`);\n if (onExhausted === \"abort\") {\n lines.push(` throw new Error('evaluate \"${taskId}\" exhausted ${maxIter} iterations without passing')`);\n } else if (onExhausted === \"fail_partial\") {\n lines.push(` log('evaluate \"${taskId}\" exhausted iterations — proceeding with partial result')`);\n lines.push(` break`);\n } else {\n lines.push(` return { escalated: true, evaluate: ${jsString(taskId)}, reason: 'exhausted ' + ${iterVar} + ' iterations without passing' }`);\n }\n lines.push(` }`);\n // Inject the failed evaluation's feedback so the re-run of the span sees it.\n if (feedbackVar) {\n lines.push(` ${feedbackVar} = typeof ${resultVar(evalIdx)}.feedback === 'string' ? ${resultVar(evalIdx)}.feedback : JSON.stringify(${resultVar(evalIdx)})`);\n lines.push(` log('evaluate \"${taskId}\" failed — re-running ${loopTo}..${taskId} with feedback as ${injectAs} (' + ${iterVar} + '/' + ${maxIter} + ')')`);\n } else {\n lines.push(` log('evaluate \"${taskId}\" failed — re-running ${loopTo}..${taskId} (' + ${iterVar} + '/' + ${maxIter} + ')')`);\n }\n lines.push(` }`);\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Workflow → script\n// ---------------------------------------------------------------------------\n\nfunction assertInScope(step: RawStep): void {\n if (step.type === \"decision\" || step.type === \"team_task\") {\n throw new WorkflowCodegenError(\n `Step type \"${step.type}\" is out of scope for #235 (only delegate/gate/evaluate are supported). ` +\n `Remove it from the workflow or extend the codegen before enabling workflow output.`,\n );\n }\n if (step.type !== \"delegate\" && step.type !== \"gate\" && step.type !== \"evaluate\") {\n throw new WorkflowCodegenError(`Unknown workflow step type \"${step.type}\"`);\n }\n}\n\n/**\n * Compile a single workflow into a Dynamic Workflow script string.\n *\n * `dsl` is the resolved DSL (agents/tasks/handoff_types/components); registries\n * are derived from it. Exported for unit testing individual workflows.\n */\nexport function renderWorkflowScript(\n id: string,\n wf: RawWorkflow,\n dsl: Record<string, unknown>,\n): string {\n const reg = buildRegistries(dsl);\n const steps = wf.steps ?? [];\n for (const step of steps) assertInScope(step);\n\n const deps = resolveDeps(steps);\n const waves = computeWaves(steps, deps);\n const meta = buildMeta(id, wf, steps);\n\n // Map each step index to the parallel wave it belongs to (a wave with >1\n // member of all-delegate steps compiles to a `parallel([...])`).\n const waveOf = new Map<number, number>();\n waves.forEach((wave, w) => wave.forEach((i) => waveOf.set(i, w)));\n\n // Loop spans owned by evaluate steps: [loopToIdx, evalIdx]. Steps inside a\n // span are emitted by emitEvaluateLoop (re-run per iteration), NOT by the\n // linear body. `spanOwner[k]` = evalIdx that owns step k (if any).\n const spanOwner = new Map<number, number>();\n for (let e = 0; e < steps.length; e++) {\n if (steps[e].type !== \"evaluate\") continue;\n const loopTo = steps[e].loop_to ?? \"\";\n const loopToIdx = steps.findIndex((s, j) => j < e && stepIdentity(s) === loopTo);\n if (loopToIdx === -1) {\n throw new WorkflowCodegenError(\n `evaluate step \"${steps[e].task ?? \"\"}\" references unknown loop_to \"${loopTo}\"`,\n );\n }\n for (let k = loopToIdx; k <= e; k++) spanOwner.set(k, e);\n }\n\n // Does any step consume upstream output (has an output-bearing dependency)?\n // If so, emit the `_ctx` helper that formats each dependency result exactly\n // as workflow-runner.ts `stepContexts` does.\n const usesStepContext = steps.some(\n (_, i) => deps[i].some((d) => steps[d].type !== \"gate\"),\n );\n // Does any step DSL-declare `depends_on: [workflow-input]`? If so, emit the\n // `_wfInput` helper that materializes the Workflow tool's `args` global as the\n // `workflow-input` output and formats it exactly as workflow-input.ts\n // `buildWorkflowInputOutput` + `formatWorkflowInputContext` do (#244).\n const usesWorkflowInput = steps.some((step) =>\n stepDependsOnWorkflowInput(step.depends_on),\n );\n\n const body: string[] = [];\n if (usesStepContext) {\n // Mirrors workflow-runner.ts: `\\n\\n--- Step N: <id> ---\\n<data>` where\n // string data is used verbatim and structured data is pretty-printed JSON.\n body.push(\n \" const _ctx = (n, id, r) => '\\\\n\\\\n--- Step ' + n + ': ' + id + ' ---\\\\n' + (typeof r === 'string' ? r : JSON.stringify(r, null, 2))\",\n );\n }\n if (usesWorkflowInput) {\n body.push(...emitWorkflowInputHelper(\" \"));\n }\n const emittedWaves = new Set<number>();\n\n for (let i = 0; i < steps.length; i++) {\n // Steps strictly inside a loop span (before its evaluate) are emitted by\n // the evaluate loop; skip them in the linear pass.\n if (spanOwner.has(i) && spanOwner.get(i) !== i) continue;\n\n const step = steps[i];\n if (step.type === \"evaluate\") {\n body.push(...emitEvaluateLoop(i, reg, steps, deps));\n continue;\n }\n\n // Parallel wave: emit the whole wave once, only when it batches >1\n // all-delegate steps that are NOT part of any loop span.\n const w = waveOf.get(i)!;\n const wave = waves[w];\n const batchable =\n wave.length > 1 &&\n wave.every((j) => steps[j].type === \"delegate\" && !spanOwner.has(j));\n if (batchable) {\n if (emittedWaves.has(w)) continue;\n emittedWaves.add(w);\n // Capture the barrier results into each step's result var (parallel()\n // resolves to an array in wave order) so downstream steps can thread them\n // as prior context — mirroring the runner recording each step's output.\n const lhs = wave.map((j) => resultVar(j)).join(\", \");\n body.push(` const [${lhs}] = await parallel([`);\n for (const j of wave) {\n const expr = emitDelegateExpr(steps[j], reg, j, steps, deps, 2);\n body.push(` () => ${expr},`);\n }\n body.push(\" ])\");\n continue;\n }\n\n {\n if (step.type === \"delegate\") {\n body.push(...emitStepStatements(i, reg, steps, deps, \" \"));\n } else if (step.type === \"gate\") {\n body.push(...emitGateStatements(step, i, steps, deps, \" \"));\n }\n }\n }\n\n body.push(\" return { completed: true, workflow: \" + jsString(id) + \" }\");\n\n const metaLiteral = jsLiteral(meta, 0);\n // The Claude Workflow tool extracts `export const meta = {...}` and runs the\n // REMAINDER as a top-level async function body — so the body must be emitted\n // as top-level statements (const/let/await agent()/if/while/return), NOT\n // wrapped in `export default async function () {...}` (#240). The wrapper\n // caused `SyntaxError: Unexpected keyword 'export'` and no workflow launched.\n // De-indent the body one level (it was authored at 2-space base indent for\n // the old function wrapper) so top-level statements sit at column 0.\n const topLevelBody = body\n .map((line) => (line.startsWith(\" \") ? line.slice(2) : line))\n .join(\"\\n\");\n return (\n `${GENERATED_MARKER}\\n\\n` +\n `export const meta = ${metaLiteral}\\n\\n` +\n `${topLevelBody}\\n`\n );\n}\n\n/**\n * Render one Dynamic Workflow script per workflow in each resolved DSL. Returns\n * project-root-relative paths under `<outputDir>/workflows/`.\n *\n * Takes the source list `resolveDslSources()` produces — the SAME input the\n * command and agent emitters receive (#274), so all three materialize the\n * project's effective DSL rather than the bare embedded one. `.claude/workflows/`\n * is a single harness-root directory, so several sources rendering the same path\n * are merged by `mergeSourceFiles` and a genuine difference is a hard error.\n */\nexport function renderWorkflowFiles(\n sources: readonly DslSource[],\n outputDir: string,\n): RenderedFile[] {\n const dir = workflowsDirFor(outputDir);\n return mergeSourceFiles(\n sources.map((source) => ({\n origin: originLabel(source),\n files: Object.entries(\n (source.dsl.workflow as Record<string, RawWorkflow>) ?? {},\n ).map(([id, wf]) => ({\n path: `${dir}/${pathSegmentForId(\"workflow id\", id)}${WORKFLOW_FILE_EXT}`,\n content: renderWorkflowScript(id, wf, source.dsl),\n })),\n })),\n (message) => new WorkflowCodegenError(message),\n );\n}\n\n/** Extension of every emitted Dynamic Workflow script. */\nexport const WORKFLOW_FILE_EXT = \".js\";\n\n/**\n * Directory the workflow scripts are emitted into. Exported so the drift/orphan\n * scan looks in the same place this renderer writes to, rather than rebuilding\n * the path.\n */\nexport function workflowsDirFor(outputDir: string): string {\n return `${outputDir.replace(/\\/+$/, \"\")}/workflows`;\n}\n","/**\n * The DSLs the `.claude/*` emitters materialize from — ONE resolution rule for\n * every emitter and for both project shapes (#274).\n *\n * `syncClaude` is handed the component's bundled `/$embedded/` DSL, NOT the\n * project's effective one: what a project actually runs is that DSL overlaid\n * with its manifest's `agents:`. Resolving the overlay is therefore part of\n * emitting `.claude/*`, not something the caller can be expected to have done —\n * and it is the same resolution the navigation-index hooks perform, so the\n * `.claude/` contents and the index cannot disagree about which agents exist.\n *\n * A workspace resolves one source per member and a single project resolves one\n * source for itself, but both go through `resolveNavigationSources()` +\n * `resolveNavigationDsl()`. Before #274 only the workspace branch did, so an\n * overlay-declared agent/workflow/command was silently dropped from a single\n * project while the navigation index listed it.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { WorkspaceMemberGenerateConfig } from \"@aaac/contracts\";\nimport {\n loadWorkspaceMembers,\n PROJECT_CONFIG_FILENAME,\n} from \"../../generator/config.js\";\nimport { resolveNavigationSources } from \"../claude-native/navigation-sources.js\";\nimport { resolveNavigationDsl } from \"../navigation-context.js\";\nimport type { ClaudeConfig } from \"./config.js\";\n\n/** One resolved DSL to materialize from, labelled by its origin. */\nexport interface DslSource {\n /**\n * Workspace member this DSL came from, used in collision messages. Absent for\n * a single project, where the project itself is the only origin.\n */\n member?: string;\n /** Resolved DSL: the embedded one overlaid with this root's `agents:`. */\n dsl: Record<string, unknown>;\n}\n\n/** How a source is named in a collision message. */\nexport function originLabel(source: DslSource): string {\n return source.member ?? \"project\";\n}\n\n/**\n * Workspace members for the generator, derived from the project manifest's\n * `workspace:` — the same loader the CLI uses (#263). Members were previously\n * hand-listed in the claude binding config, which meant two sources of truth for\n * the member set and silent staleness when `project.yaml` gained a member.\n *\n * Returns [] when the root declares no workspace, which selects the\n * single-component branch in the generator.\n */\nexport async function workspaceMembersForProject(\n root: string,\n): Promise<WorkspaceMemberGenerateConfig[]> {\n const manifestPath = join(root, PROJECT_CONFIG_FILENAME);\n if (!existsSync(manifestPath)) return [];\n\n const members = await loadWorkspaceMembers(manifestPath);\n return members.map((m) => ({\n name: m.name,\n path: m.path,\n cacheKey: m.cacheKey,\n }));\n}\n\n/**\n * Resolve the DSL sources every `.claude/*` emitter materializes from.\n *\n * The project roots that contribute are the workspace members when the manifest\n * declares a workspace, and otherwise the project root itself — a single project\n * is its own only member, not a different kind of thing. Each root is then\n * resolved by the SAME rule: `resolveNavigationSources()` reads its manifest and\n * `resolveNavigationDsl()` overlays its `agents:` onto the embedded DSL. A root\n * that declares no overlay resolves to the embedded DSL unchanged, so a project\n * without an `agents:` manifest entry emits byte-identical output.\n *\n * This is deliberately NOT what `renderFiles` bakes into the generated hook bins:\n * those carry the EMBEDDED DSL and re-run this resolution at hook time, so a\n * manifest edit takes effect without re-running `claude sync`\n * (navigation-sources.ts). Baking the overlaid DSL there would freeze the\n * overlay at sync time and re-apply it on top of itself.\n */\nexport async function resolveDslSources(\n root: string,\n embeddedDsl: Record<string, unknown>,\n config: ClaudeConfig,\n): Promise<DslSource[]> {\n const members = await workspaceMembersForProject(root);\n const roots: Array<{ member?: string; root: string }> =\n members.length > 0\n ? members.map((m) => ({ member: m.name, root: resolve(root, m.path) }))\n : [{ root }];\n\n return Promise.all(\n roots.map(async ({ member, root: projectRoot }) => {\n const { navigationOptions } = await resolveNavigationSources({\n projectRoot,\n embeddedDsl,\n dslPath: config.config_path,\n });\n const dsl = await resolveNavigationDsl(navigationOptions);\n return member === undefined ? { dsl } : { member, dsl };\n }),\n );\n}\n\n/**\n * Merge what several sources render into the ONE harness-root directory.\n *\n * Claude Code reads `.claude/workflows/` and `.claude/commands/` from the\n * harness root only — the same constraint that forces the agents merge — so in a\n * workspace two members can render to the same path. Identical bytes are the\n * same artifact (the common case: both inherit it unmodified from the shared\n * `/$embedded/` DSL) and merge; different bytes are a conflict that must be\n * loud, because whichever source happened to be rendered last would otherwise\n * silently win.\n *\n * Agents are NOT merged here: an agent's identity is its DSL definition rather\n * than the rendered markdown — the file projects only part of `AgentSchema`, so\n * comparing bytes would let a difference in a non-projected field through in\n * silence. `renderAgentFiles` therefore compares the definitions itself.\n *\n * With a single source this is order-preserving and content-preserving, so a\n * non-workspace project's output is unchanged by the merge existing.\n */\nexport function mergeSourceFiles<T extends { path: string; content: string }>(\n rendered: ReadonlyArray<{ origin: string; files: readonly T[] }>,\n conflict: (message: string) => Error,\n): T[] {\n const merged = new Map<string, { file: T; origin: string }>();\n\n for (const { origin, files } of rendered) {\n for (const file of files) {\n const existing = merged.get(file.path);\n if (existing === undefined) {\n merged.set(file.path, { file, origin });\n continue;\n }\n if (existing.file.content !== file.content) {\n throw conflict(\n `\"${file.path}\" is generated differently by \"${existing.origin}\" and \"${origin}\"; ` +\n `Claude Code reads this directory from the harness root only, so it can hold ` +\n `just one version of the file. Align the two definitions, or rename one of ` +\n `them in the DSL.`,\n );\n }\n }\n }\n\n return [...merged.values()].map((entry) => entry.file);\n}\n","/**\n * Claude Code slash-command artifact codegen (#249).\n *\n * Renders ONE output file per agent-contracts `workflow` from a Handlebars\n * template with a per-workflow context. Symmetric in spirit to the `emit.workflows`\n * codegen (#235, `workflow-render.ts`): a fully-generated, overwrite-owned artifact\n * wired into the SAME `claude sync`/`check` machinery, over the DSL sources\n * `resolveDslSources()` hands it (`dsl-sources.ts`) — this module renders, it\n * never resolves packages or overlays itself.\n *\n * Default use case: turn each workflow into a Claude Code slash command file\n * `.claude/commands/aidev/{name}.md`, so the already-emitted workflows (written\n * `trigger: 'User invokes /aidev.<name> ...'`) become real `/aidev:<name>` slash\n * commands, DSL-driven and regenerable.\n *\n * Handlebars is a build-time devDependency of THIS package: tsup externalizes only\n * `dependencies`/`peerDependencies`, so Handlebars is inlined into `dist/` — and into\n * the self-contained `dist/claude-bundles/full.js`, which runs with no node_modules —\n * rather than resolved from a consumer's install. See `@aaac/binding-cursor`'s\n * `render.ts` for the in-repo usage convention: `Handlebars.create()` +\n * `compile(tpl, { noEscape })` so markdown/frontmatter is emitted verbatim, not\n * HTML-escaped.\n */\n\nimport Handlebars from \"handlebars\";\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { mergeSourceFiles, originLabel, type DslSource } from \"./dsl-sources.js\";\nimport { yamlScalar } from \"./frontmatter.js\";\nimport type { RenderedFile } from \"./workflow-render.js\";\n\n// Re-export so callers can import the shared type from one place.\nexport type { RenderedFile };\n\n/**\n * Thrown when a workflow is malformed for command generation (e.g. a workflow\n * missing the data the template context requires), or when the config's output\n * path template lacks the required per-item placeholder. Never silently drop —\n * mirrors `WorkflowCodegenError`'s loud-failure convention (workflow-render.ts).\n */\nexport class CommandCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CommandCodegenError\";\n }\n}\n\n/**\n * The per-item placeholder every command output-path template must contain, so\n * one file is produced per workflow at a distinct path. Substituted with the\n * workflow name (its DSL key).\n */\nconst NAME_PLACEHOLDER = \"{name}\";\n\n/** Default output-path template (project-root-relative) for the slash-command use case. */\nexport const DEFAULT_COMMAND_OUTPUT = \".claude/commands/aidev/{name}.md\";\n\n/**\n * Bundled default Handlebars template — the slash-command use case from #249.\n *\n * Emitted verbatim (noEscape). Produces valid Claude Code slash-command markdown:\n * YAML frontmatter with `description` and an `argument-hint`, plus a body that\n * references the workflow name and `$ARGUMENTS`. `whenToUse` (the workflow\n * `trigger`) is surfaced in the body so the command self-documents its intent.\n *\n * Bundled (not a mandatory config path) so the default use case works with a bare\n * `emit.commands: true` — consistent with how the cursor binding ships its\n * templates in-package (`templates.ts`) rather than requiring the consumer to\n * author them. A consumer may override via `emit.commands.template` (a path).\n */\nexport const DEFAULT_COMMAND_TEMPLATE = `---\ndescription: {{yaml description}}\nargument-hint: <request>\n---\n{{#if whenToUse}}{{whenToUse}}\n\n{{/if}}Run the dev-team \\`{{name}}\\` workflow with the following request:\n\n$ARGUMENTS\n`;\n\n/**\n * The per-workflow template context. Exposes at least `name`, `description`, and\n * the workflow trigger (as `whenToUse`, matching the workflow-script `meta`\n * field name), plus `trigger` as an alias so either name works in a custom template.\n */\nexport interface CommandContext {\n /** Workflow name = its DSL key (used for `{name}` substitution too). */\n name: string;\n /** Workflow `description`, trimmed; falls back to the name when absent. */\n description: string;\n /** Workflow `trigger`, trimmed; undefined when the workflow declares none. */\n whenToUse?: string;\n /** Alias of `whenToUse` so a custom template may use either field name. */\n trigger?: string;\n}\n\n/** Minimal duck-typed view of a resolved workflow (subset of RawWorkflow). */\ninterface RawWorkflow {\n description?: string;\n trigger?: string;\n}\n\nconst hb = Handlebars.create();\n\n/**\n * `{{yaml value}}` — emit a value as a valid YAML scalar for use inside YAML\n * frontmatter. #249's purpose is reuse by ARBITRARY embedded-DSL repos, so a\n * workflow `description`/trigger may contain colons, quotes, or embedded\n * newlines that would break raw interpolation into frontmatter (the template\n * renders with `noEscape` for the markdown body). The escaping rule itself is\n * shared with the agent frontmatter emitter — see `frontmatter.ts`.\n */\nhb.registerHelper(\"yaml\", (value: unknown) => new Handlebars.SafeString(yamlScalar(value)));\n\n/** Build the per-workflow context from the resolved workflow definition. */\nexport function buildCommandContext(name: string, wf: RawWorkflow): CommandContext {\n if (!name) {\n throw new CommandCodegenError(\"Workflow has an empty name; cannot generate a command file.\");\n }\n const description = (wf.description ?? \"\").trim() || name;\n const whenToUse = (wf.trigger ?? \"\").trim() || undefined;\n return { name, description, whenToUse, trigger: whenToUse };\n}\n\n/**\n * Substitute the `{name}` placeholder in the output-path template. The\n * placeholder is a path component of the template, so what replaces it must be\n * one too — otherwise a workflow id decides how deep, or how far out of the\n * configured directory, the command file lands.\n */\nfunction substituteName(outputTemplate: string, name: string): string {\n return outputTemplate.split(NAME_PLACEHOLDER).join(pathSegmentForId(\"workflow id\", name));\n}\n\n/**\n * Render one command file per workflow of ONE resolved DSL.\n *\n * The `seenPaths` guard is per-DSL on purpose: two workflows of the same DSL\n * colliding on one output path means the template's placeholder does not\n * separate them, which no merge can fix. Two SOURCES colliding is a different\n * question — answered by `mergeSourceFiles` in the caller.\n */\nfunction renderOneDsl(\n dsl: Record<string, unknown>,\n outputTemplate: string,\n render: (context: CommandContext) => string,\n): RenderedFile[] {\n const workflows = (dsl.workflow as Record<string, RawWorkflow>) ?? {};\n const files: RenderedFile[] = [];\n const seenPaths = new Set<string>();\n\n for (const [name, wf] of Object.entries(workflows)) {\n const context = buildCommandContext(name, wf);\n const path = substituteName(outputTemplate, name);\n if (seenPaths.has(path)) {\n throw new CommandCodegenError(\n `Two workflows resolve to the same command output path \"${path}\"; ` +\n `ensure the output template's \"${NAME_PLACEHOLDER}\" placeholder yields distinct paths.`,\n );\n }\n seenPaths.add(path);\n files.push({ path, content: render(context) });\n }\n return files;\n}\n\n/**\n * Render one command file per workflow in each resolved DSL.\n *\n * Takes the source list `resolveDslSources()` produces — the SAME input the\n * workflow and agent emitters receive (#274), so all three materialize the\n * project's effective DSL rather than the bare embedded one. The command output\n * dir is a single harness-root directory, so several sources rendering the same\n * path are merged by `mergeSourceFiles` and a genuine difference is a hard error.\n *\n * @param sources resolved DSLs, each labelled by its origin\n * @param outputTemplate project-root-relative output path with a `{name}` placeholder\n * @param templateSource Handlebars template source (bundled default or config-provided)\n */\nexport function renderCommandFiles(\n sources: readonly DslSource[],\n outputTemplate: string,\n templateSource: string,\n): RenderedFile[] {\n if (!outputTemplate.includes(NAME_PLACEHOLDER)) {\n throw new CommandCodegenError(\n `Command output path \"${outputTemplate}\" is missing the required per-workflow ` +\n `placeholder \"${NAME_PLACEHOLDER}\"; every workflow would collide on one path.`,\n );\n }\n\n const render = hb.compile(templateSource, { noEscape: true });\n return mergeSourceFiles(\n sources.map((source) => ({\n origin: originLabel(source),\n files: renderOneDsl(source.dsl, outputTemplate, render),\n })),\n (message) => new CommandCodegenError(message),\n );\n}\n","/**\n * YAML frontmatter emission for generated Claude Code markdown artifacts.\n *\n * Both generated Claude artifacts that carry frontmatter — per-workflow slash\n * commands (#249, `command-render.ts`) and per-agent subagent definitions\n * (#272, `agent-render.ts`) — interpolate arbitrary DSL prose into YAML, so the\n * scalar-escaping rule must exist exactly once.\n */\n\n/**\n * Emit a value as a valid YAML scalar.\n *\n * `JSON.stringify` of a string produces a double-quoted flow scalar (`\"...\"`\n * with `\\n` / `\\\"` / `\\\\` escaped). YAML 1.2 is a JSON superset, so a JSON\n * string literal is always a valid YAML double-quoted scalar and round-trips.\n * Single-line values stay readable (e.g. `\"Implement a feature\"`); only\n * genuinely unsafe content (colons, quotes, embedded newlines) is escaped.\n * Non-string values are coerced to string first so the result is always a scalar.\n */\nexport function yamlScalar(value: unknown): string {\n const str = value === undefined || value === null ? \"\" : String(value);\n return JSON.stringify(str);\n}\n\n/**\n * Render a `---`-delimited YAML frontmatter block from ordered key/value pairs.\n * Entries whose value is `undefined` are omitted, so an optional key is simply\n * absent rather than emitted empty.\n */\nexport function renderFrontmatter(\n fields: ReadonlyArray<readonly [key: string, value: string | undefined]>,\n): string {\n const lines = [\"---\"];\n for (const [key, value] of fields) {\n if (value === undefined) continue;\n lines.push(`${key}: ${value}`);\n }\n lines.push(\"---\");\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * Claude Code subagent materialization (#272).\n *\n * Renders ONE `.claude/agents/<id>.md` per agent-contracts `agents:` entry, so a\n * DSL-declared agent is usable as a real Claude Code subagent instead of being\n * transcribed into markdown by hand. Fully generated and overwrite-owned, wired\n * into the SAME `claude sync` / `claude check` machinery as the workflow scripts\n * (#235) and slash commands (#249) — the third artifact of the same shape, so it\n * reuses their drift-detection point rather than introducing a new one.\n *\n * ## What is shared, and what is specific to the file form\n *\n * The body is `renderAgentSystemPrompt` (`lib/candidate-agents.ts`), the same\n * renderer that produces an agent's system prompt in-process, so the two cannot\n * describe one DSL agent differently. The tool grant is `toolGrantForAgent`\n * (`lib/claude-tool-grants.ts`), shared with the Claude adapter.\n *\n * The `description` is NOT `deriveDescription`: that helper takes only the first\n * sentence of `purpose`, which is right for in-process routing (the delegating\n * agent already holds the full DSL context) but not here — a Claude Code\n * subagent is picked from its `description` alone, and purposes written as\n * \"You are the X. Your job is to ...\" collapse to \"You are the X.\" The file form\n * therefore carries `role_name` + the whole `purpose`, which is what the issue's\n * mapping table specifies.\n *\n * ## frontmatter `tools` is the mode grant, not `can_execute_tools`\n *\n * A DSL `can_execute_tools` entry is a DSL tool id (`gh-cli`,\n * `agent-contracts-cli`), not a Claude Code tool name. `tools:` is an allowlist\n * resolved against the available tool pool, so DSL ids there would grant nothing\n * and, if they were the only entries, leave the subagent with an unresolvable\n * list. What decides an agent's Claude Code tool grant is its `mode` plus\n * whether it may invoke other agents, exactly as in-process. The declared DSL\n * tools are surfaced in the body instead, where they belong — they are executed\n * through `Bash`.\n *\n * ## Which agents are materialized, and where\n *\n * `dispatch_only` decides the SURFACE an agent's declared content is rendered\n * to, never whether it is rendered at all. `.claude/agents/` is Claude Code's\n * delegation-target registry, so it holds every agent except the dispatch-only\n * ones: a dispatch-only agent is the entry role that hands work to the others\n * (`buildCandidateAgents` excludes the entry agent from the candidate set for\n * the same reason), and a file there would register the orchestrator as a\n * delegation target of itself.\n *\n * The entry role is the MAIN agent, and the Claude surface a main agent reads is\n * CLAUDE.md — so its body goes into the generated `aaac:claude-native` block\n * instead (`renderEntryAgentPrompt`). Both surfaces are rendered by the one\n * `renderAgentBody`, so the same DSL agent cannot be described two ways.\n *\n * Skipping the file used to be the whole story, and the content had nowhere to\n * go: an agent could declare `dispatch_only: true` alongside mandatory rules and\n * the Claude harness dropped every one of them without a diagnostic, while the\n * Cursor binding — which has no such filter — rendered them. Two bindings, one\n * DSL, two answers to what `dispatch_only` means (#345).\n *\n * The split happens AFTER every source has been compared, never during the\n * merge: whether an agent is dispatch-only is itself part of its definition, so\n * two members disagreeing about it is a conflict — and the most consequential\n * kind, since it decides which surface the orchestrator's prompt lands on.\n *\n * ## Workspace merge\n *\n * Claude Code reads `.claude/agents/` only from the harness root, so in a\n * workspace every member's agents are merged into the single root directory.\n * Two members contributing the same agent name are only compatible when their\n * DSL definitions are identical (the common case: both inherit it unmodified\n * from the shared `/$embedded/` component DSL). A genuine difference is a hard\n * error — `name` is the invocation key, so a file rename cannot separate them\n * and whichever file Claude Code happened to read last would silently win.\n */\n\nimport { pathSegmentForId } from \"@aaac/contracts\";\nimport { renderAgentSystemPrompt } from \"../candidate-agents.js\";\nimport { buildAgentRegistry } from \"../dsl-context.js\";\nimport { toolGrantForAgent } from \"../claude-tool-grants.js\";\nimport type { AgentContractLike } from \"../task-runner.js\";\nimport { originLabel, type DslSource } from \"./dsl-sources.js\";\nimport { renderFrontmatter, yamlScalar } from \"./frontmatter.js\";\nimport type { RenderedFile } from \"./workflow-render.js\";\n\n// Re-export so callers can import the shared type from one place.\nexport type { RenderedFile };\n\n/**\n * Thrown when the DSL cannot be materialized into Claude Code subagents: an\n * agent id that is not a legal subagent `name`, or a workspace name collision.\n * Never silently drop or overwrite — mirrors `WorkflowCodegenError` /\n * `CommandCodegenError`.\n */\nexport class AgentCodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AgentCodegenError\";\n }\n}\n\n/** Subdirectory of the Claude output dir that holds subagent definitions. */\nexport const AGENTS_SUBDIR = \"agents\";\n\n/** Extension of a Claude Code subagent definition file. */\nexport const AGENT_FILE_EXT = \".md\";\n\n/**\n * Claude Code subagent `name` grammar: lowercase letters, digits and hyphens.\n * A `:` is reserved for plugin-scoped names and makes Claude Code reject the\n * file, so an id that cannot be a name is an error rather than a mangled slug.\n *\n * This is Claude Code's naming contract, not a filesystem one — whether the id\n * may be a path component is `pathSegmentForId`'s single answer, asked where\n * the path is built. Narrower than that rule, and for a different reason.\n */\nconst AGENT_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nconst GENERATED_MARKER =\n \"<!-- Auto-generated from the agent-contracts DSL. Do not edit; run `claude sync`. -->\";\n\n/**\n * The project-root-relative directory this emitter owns. Every `*.md` directly\n * inside it is generated; `syncClaude` removes the ones the DSL no longer\n * declares and `checkClaude` reports them.\n */\nexport function agentsDirFor(outputDir: string): string {\n return `${outputDir.replace(/\\/+$/, \"\")}/${AGENTS_SUBDIR}`;\n}\n\n/**\n * Stable serialization of an arbitrary DSL value: object keys sorted, array\n * order preserved. Used as the identity of an agent definition when merging\n * workspace members, so that two members are compared on what the DSL SAYS\n * rather than on what this emitter happens to project into markdown — otherwise\n * a difference in a field the file does not render (`own_artifacts`,\n * `x-copilot`, `x-cursor-exclude`, …) would be dropped in silence.\n */\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (value !== null && typeof value === \"object\") {\n const source = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(source).sort()) {\n out[key] = canonicalize(source[key]);\n }\n return out;\n }\n return value;\n}\n\n/**\n * Bullet list section, omitted when the DSL declares nothing. Absent and empty\n * are the same thing for a permission list, so both are handled here rather\n * than by defaulting each field at its call site.\n */\nfunction listSection(title: string, items: readonly string[] | undefined): string | undefined {\n if (!items || items.length === 0) return undefined;\n return `## ${title}\\n\\n${items.map((i) => `- ${i}`).join(\"\\n\")}`;\n}\n\n/**\n * The sections the shared `renderAgentSystemPrompt` does not carry: the agent's\n * mode and its declared artifact / tool / handoff / validation permissions. They\n * describe what this agent is allowed to touch, which is exactly what a subagent\n * receiving only its own file needs in order to stay inside its lane.\n */\nfunction permissionSections(agent: AgentContractLike): string[] {\n return [\n `## Mode\\n\\n${agent.mode}`,\n listSection(\"Readable Artifacts\", agent.can_read_artifacts),\n listSection(\"Writable Artifacts\", agent.can_write_artifacts),\n listSection(\"Executable Tools\", agent.can_execute_tools),\n listSection(\"Invokable Agents\", agent.can_invoke_agents),\n listSection(\"Returnable Handoffs\", agent.can_return_handoffs),\n listSection(\"Performable Validations\", agent.can_perform_validations),\n ].filter((s): s is string => s !== undefined);\n}\n\n/**\n * The routing hint Claude Code shows when choosing a subagent: the agent's role\n * name followed by its full purpose, flattened to one line.\n */\nfunction agentDescription(agent: AgentContractLike): string {\n const purpose = agent.purpose.replace(/\\s+/g, \" \").trim();\n if (!purpose) return agent.role_name;\n return `${agent.role_name} — ${purpose}`;\n}\n\n/**\n * An agent's prompt body: the shared system prompt plus the permission sections.\n *\n * The ONE renderer for both Claude surfaces — the subagent file below and the\n * CLAUDE.md block an entry agent lands in (`renderEntryAgentPrompt`). Only the\n * envelope differs: frontmatter is Claude Code's subagent-registry syntax, which\n * an entry agent has no entry in, so it belongs to the file form alone.\n */\nfunction renderAgentBody(agent: AgentContractLike): string {\n return [renderAgentSystemPrompt(agent), ...permissionSections(agent)]\n .join(\"\\n\\n\")\n .replace(/\\s+$/, \"\");\n}\n\n/**\n * Render one agent into Claude Code subagent markdown: YAML frontmatter\n * (`name` / `description` / `tools`) followed by the system prompt as the body.\n *\n * No `model` key is emitted: the agent-contracts `AgentSchema` has no\n * agent-level model field (`model_class` is declared per TASK), and per-task\n * model selection is already emitted per `agent()` call by the workflow codegen.\n * Omitting it is Claude Code's documented `inherit`.\n */\nfunction renderAgentFile(name: string, agent: AgentContractLike): string {\n const frontmatter = renderFrontmatter([\n // `name` is validated against AGENT_NAME_PATTERN, so it is always a plain\n // YAML scalar and needs no quoting. `description` is arbitrary DSL prose.\n [\"name\", name],\n [\"description\", yamlScalar(agentDescription(agent))],\n // The Claude Code tool grant follows the contract, never the DSL tool ids.\n [\"tools\", toolGrantForAgent(agent).join(\", \")],\n ]);\n\n const body = [GENERATED_MARKER, renderAgentBody(agent)].join(\"\\n\\n\");\n\n return `${frontmatter}\\n${body}\\n`;\n}\n\n/** Contribution of one source to the merged agent set. */\ninterface AgentContribution {\n /** Normalized contract every source agreed on, used to render the file. */\n agent: AgentContractLike;\n /** Canonical DSL definition — the identity two members are compared on. */\n identity: string;\n /** Origin that produced it, for collision reporting. */\n origin: string;\n}\n\n/**\n * `dispatch_only: true` — the entry/orchestrator role. The ONE spelling of the\n * question, read by both halves of the split below so they cannot answer it\n * differently: an agent is materialized as a subagent file or as the CLAUDE.md\n * main-agent prompt, never as neither and never as both.\n */\nfunction isEntryAgent(agent: AgentContractLike): boolean {\n return agent.dispatch_only === true;\n}\n\n/**\n * Phase 1 — agree. EVERY declared agent is merged, including dispatch-only\n * ones: `dispatch_only` is part of an agent's definition, so two members\n * disagreeing about it must be caught here. Filtering first would let that one\n * field differ in silence, which is the whole failure mode this compare exists\n * to prevent — and it is the field that decides which surface the agent is\n * rendered to.\n *\n * @param dir the agents directory, named in the collision message because it\n * is what can hold only one definition of a given name.\n * @throws {AgentCodegenError} when two sources define the same agent differently.\n */\nfunction mergeAgents(\n sources: readonly DslSource[],\n dir: string,\n): Map<string, AgentContribution> {\n const merged = new Map<string, AgentContribution>();\n\n for (const source of sources) {\n const rawAgents =\n (source.dsl.agents as Record<string, Record<string, unknown>> | undefined) ?? {};\n const registry = buildAgentRegistry(source.dsl);\n\n for (const [name, agent] of Object.entries(registry)) {\n // Compared on the DSL definition, not on the rendered markdown: the file\n // projects only part of AgentSchema, so members differing ONLY in a\n // non-projected field would otherwise merge silently.\n const identity = JSON.stringify(canonicalize(rawAgents[name]));\n const existing = merged.get(name);\n if (existing && existing.identity !== identity) {\n throw new AgentCodegenError(\n `Agent \"${name}\" is defined differently by \"${existing.origin}\" and ` +\n `\"${originLabel(source)}\"; Claude Code keys subagents by frontmatter \\`name\\`, so ` +\n `${dir}/ can hold only one definition of it — including which surface it is ` +\n `materialized to. Align the two definitions, or rename one of them in the DSL.`,\n );\n }\n if (!existing) {\n merged.set(name, { agent, identity, origin: originLabel(source) });\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Render the `.claude/agents/*.md` set for one or more DSLs — the delegatable\n * half of the split. The entry agent's half is `renderEntryAgentPrompt`, and\n * `syncClaude`/`checkClaude` emit both from the one merge, so a dispatch-only\n * agent leaves this set only by arriving in that one.\n *\n * @param sources the DSLs to merge, as resolved by `resolveDslSources()` —\n * one for a single project, one per member for a workspace\n * (each already overlaid on the component's `/$embedded/` DSL).\n * @param outputDir the Claude output dir (project-root-relative, e.g. `.claude`).\n * @throws {AgentCodegenError} on an illegal agent name, or on two sources\n * defining the same agent differently.\n */\nexport function renderAgentFiles(\n sources: readonly DslSource[],\n outputDir: string,\n): RenderedFile[] {\n const dir = agentsDirFor(outputDir);\n\n // Phase 2 — materialize. The entry/orchestrator role is not a delegation\n // target, so it is split off only now, once every source has been compared.\n const files: RenderedFile[] = [];\n for (const [name, { agent, origin }] of mergeAgents(sources, dir)) {\n if (isEntryAgent(agent)) continue;\n\n if (!AGENT_NAME_PATTERN.test(name)) {\n throw new AgentCodegenError(\n `Agent id \"${name}\" (${origin}) is not a valid Claude Code subagent name; ` +\n `names must match ${AGENT_NAME_PATTERN.source} (lowercase letters, digits and hyphens).`,\n );\n }\n files.push({\n path: `${dir}/${pathSegmentForId(\"agent id\", name)}${AGENT_FILE_EXT}`,\n content: renderAgentFile(name, agent),\n });\n }\n\n return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\n/**\n * Render the dispatch-only agents' prompt for the CLAUDE.md `aaac:claude-native`\n * block — the entry half of the same split, from the same merge and the same\n * `renderAgentBody` as the subagent files.\n *\n * `undefined` when the DSL declares no dispatch-only agent, which is what keeps\n * the block byte-identical for a project that has none. Ordered by agent id so a\n * workspace contributing several produces a stable block.\n *\n * No frontmatter and no per-file generated marker: both are subagent-registry\n * syntax, and the block's own `aaac:claude-native` markers already declare the\n * region generated.\n *\n * @param sources as `renderAgentFiles`.\n * @param outputDir as `renderAgentFiles`; the merge names it when reporting a\n * collision, so both halves report one directory.\n * @throws {AgentCodegenError} when two sources define the same agent differently.\n */\nexport function renderEntryAgentPrompt(\n sources: readonly DslSource[],\n outputDir: string,\n): string | undefined {\n const entries = [...mergeAgents(sources, agentsDirFor(outputDir))]\n .filter(([, { agent }]) => isEntryAgent(agent))\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\n if (entries.length === 0) return undefined;\n return entries.map(([, { agent }]) => renderAgentBody(agent)).join(\"\\n\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n claudeGenerator,\n generatedFileRelPath,\n isOwnedByExtension,\n orphanGeneratedFiles,\n type ComponentIR,\n type GeneratedFile,\n} from \"@aaac/contracts\";\nimport {\n AGENT_FILE_EXT,\n agentsDirFor,\n renderAgentFiles,\n renderEntryAgentPrompt,\n} from \"./agent-render.js\";\nimport { parseClaudeConfig, type ClaudeConfig } from \"./config.js\";\nimport {\n resolveDslSources,\n workspaceMembersForProject,\n type DslSource,\n} from \"./dsl-sources.js\";\nimport {\n renderWorkflowFiles,\n workflowsDirFor,\n WORKFLOW_FILE_EXT,\n type RenderedFile,\n} from \"./workflow-render.js\";\nimport {\n renderCommandFiles,\n DEFAULT_COMMAND_OUTPUT,\n DEFAULT_COMMAND_TEMPLATE,\n} from \"./command-render.js\";\nimport {\n HOOK_BIN_DIR,\n isHookBin,\n readBundleMarker,\n recomputeMarkerFromDisk,\n withAssembledHookBins,\n} from \"./bundle-bins.js\";\nimport { mergedSettingsText } from \"./settings-merge.js\";\n\n/**\n * `deleted` is reported for a generated file removed because the DSL no longer\n * declares it (a stale `.claude/agents/*.md` is a live Claude Code subagent, so\n * leaving it behind is the very DSL/harness divergence this generator exists to\n * remove).\n */\nexport type FileAction = \"created\" | \"updated\" | \"unchanged\" | \"deleted\";\n\nexport interface SyncOptions {\n projectRoot: string;\n /** Opaque config payload from component.yaml (validated here). */\n config: unknown;\n /**\n * The component's bundled `/$embedded/` DSL — the value the runtime embeds,\n * BEFORE any project overlay. What a project actually runs is this DSL\n * overlaid with its manifest's `agents:`, and resolving that overlay is this\n * module's job (`resolveDslSources`), not the caller's: the caller cannot know\n * the workspace members, and one caller resolving it differently from another\n * is exactly how `.claude/` came to disagree with the navigation index (#274).\n */\n dsl: Record<string, unknown>;\n /** When true, compute changes without writing. */\n dryRun?: boolean;\n}\n\nexport interface SyncResult {\n files: Array<{ path: string; action: FileAction }>;\n}\n\nexport interface CheckResult {\n inSync: boolean;\n /** `orphaned` = present on disk inside a generated directory, absent from the DSL. */\n drift: Array<{ path: string; reason: \"missing\" | \"changed\" | \"orphaned\" }>;\n}\n\nconst CLAUDE_BLOCK_BEGIN = \"<!-- aaac:claude-native:begin -->\";\nconst CLAUDE_BLOCK_END = \"<!-- aaac:claude-native:end -->\";\n\nfunction buildComponentIR(dsl: Record<string, unknown>, config: ClaudeConfig): ComponentIR {\n const system = dsl.system as { id?: string; version?: string } | undefined;\n const componentId = config.component_id ?? system?.id ?? \"component\";\n\n return {\n schema: \"aaac/0.1\",\n info: {\n id: componentId,\n version: system?.version ?? \"1.0.0\",\n },\n implementation: config.config_path,\n projections: [\"claude\"],\n operations: {},\n };\n}\n\nfunction absPath(root: string, file: GeneratedFile): string {\n return join(root, generatedFileRelPath(file));\n}\n\nasync function readIfExists(path: string): Promise<string | undefined> {\n if (!existsSync(path)) return undefined;\n return readFile(path, \"utf8\");\n}\n\nasync function renderFiles(\n root: string,\n dsl: Record<string, unknown>,\n config: ClaudeConfig,\n entryAgentPrompt: string | undefined,\n): Promise<GeneratedFile[]> {\n const ir = buildComponentIR(dsl, config);\n\n const members = await workspaceMembersForProject(root);\n const workspaceOptions = members.length > 0 ? { members } : undefined;\n\n // #241/#278: `.claude/bin` is the one place the generator's output is not the\n // final byte stream — each bin is assembled self-contained against a shared\n // runtime chunk that is emitted alongside it. Doing that here, at the single\n // point both syncClaude and checkClaude read, is what lets bins and chunks\n // travel the identical write/drift path below.\n return withAssembledHookBins(\n claudeGenerator.generate(ir, {\n outputDir: \"\",\n componentPath: \"\",\n // Bake the resolved DSL into the nav hook bins so a consumer project DSL\n // that `extends: /$embedded/` resolves at hook runtime (#255 follow-up).\n resolvedDslData: dsl,\n workspace: workspaceOptions,\n // The other half of the agent render: a dispatch-only agent has no\n // subagent file, so the CLAUDE.md block is where its prompt reaches\n // Claude (#345). Resolved by the caller from the SAME merge that produced\n // the subagent files.\n entryAgentPrompt,\n }),\n );\n}\n\nfunction mergeClaudeMdBlock(\n existing: string | undefined,\n block: string,\n): { content: string; action: FileAction } {\n const normalizedBlock = block.trimStart();\n\n if (existing === undefined) {\n return { content: normalizedBlock, action: \"created\" };\n }\n\n const beginIdx = existing.indexOf(CLAUDE_BLOCK_BEGIN);\n const endIdx = existing.indexOf(CLAUDE_BLOCK_END);\n\n if (beginIdx === -1 || endIdx === -1) {\n const needsSeparator = existing.length > 0 && !existing.endsWith(\"\\n\");\n const content = existing + (needsSeparator ? \"\\n\" : \"\") + normalizedBlock;\n return { content, action: \"updated\" };\n }\n\n const before = existing.slice(0, beginIdx);\n let after = existing.slice(endIdx + CLAUDE_BLOCK_END.length);\n // `normalizedBlock` already ends with the template's trailing newline, so the\n // matching boundary newline that opens `after` must be dropped — otherwise it\n // is re-added every sync and accumulates one blank line per run (#251). This\n // must fire whether or not the user appended content after the block; the\n // earlier `after === \"\\n\"` guard only covered the no-user-content case.\n if (after.startsWith(\"\\n\")) {\n after = after.slice(1);\n }\n const content = before + normalizedBlock + after;\n\n if (content === existing) {\n return { content: existing, action: \"unchanged\" };\n }\n return { content, action: \"updated\" };\n}\n\nfunction expectedClaudeMdContent(existing: string | undefined, block: string): string {\n return mergeClaudeMdBlock(existing, block).content;\n}\n\nfunction actionForOverwriteTrue(existing: string | undefined, next: string): FileAction {\n if (existing === undefined) return \"created\";\n return existing === next ? \"unchanged\" : \"updated\";\n}\n\n/**\n * `.claude/settings.json` is emitted with `overwrite: true`, but it must NOT be\n * fully clobbered (#248): user-added non-managed hooks are preserved via a\n * JSON managed-region merge (see settings-merge.ts). The managed region is\n * regenerated identically each run, so this stays idempotent, and a fresh\n * project produces byte-identical managed output.\n */\nfunction isSettingsJson(file: GeneratedFile): boolean {\n return file.path === \"settings.json\" && file.targetDir === \".claude\";\n}\n\nfunction resolveContent(\n file: GeneratedFile,\n existing: string | undefined,\n): { content: string; action: FileAction } {\n if (file.path === \"CLAUDE.md\" && file.targetDir === \".\" && !file.overwrite) {\n return mergeClaudeMdBlock(existing, file.content);\n }\n\n if (isSettingsJson(file)) {\n const content = mergedSettingsText(existing, file.content);\n return { content, action: actionForOverwriteTrue(existing, content) };\n }\n\n if (!file.overwrite) {\n if (existing !== undefined) {\n return { content: existing, action: \"unchanged\" };\n }\n if (!file.content) {\n return { content: \"\", action: \"unchanged\" };\n }\n return { content: file.content, action: \"created\" };\n }\n\n const action = actionForOverwriteTrue(existing, file.content);\n return { content: file.content, action };\n}\n\nfunction checkContent(\n file: GeneratedFile,\n existing: string | undefined,\n): \"missing\" | \"changed\" | null {\n if (file.path === \"CLAUDE.md\" && file.targetDir === \".\" && !file.overwrite) {\n if (existing === undefined) return \"missing\";\n const expected = expectedClaudeMdContent(existing, file.content);\n return existing === expected ? null : \"changed\";\n }\n\n if (isSettingsJson(file)) {\n if (existing === undefined) return \"missing\";\n // Drift = the on-disk file does not equal the merged managed region + its\n // own non-managed additions. A user-added hook produces no drift (it is\n // reproduced by the merge); a removed/mutated managed entry does.\n const expected = mergedSettingsText(existing, file.content);\n return existing === expected ? null : \"changed\";\n }\n\n if (!file.overwrite) {\n if (existing === undefined && file.content) return \"missing\";\n return null;\n }\n\n if (existing === undefined) return \"missing\";\n if (existing !== file.content) return \"changed\";\n return null;\n}\n\n/**\n * Additive Claude Dynamic Workflow scripts (#235). Emitted ONLY when\n * `config.emit.workflows` is true; otherwise returns [] so the existing\n * `.claude/*` output is byte-preserved (backward compatible).\n */\nfunction workflowFiles(sources: readonly DslSource[], config: ClaudeConfig): RenderedFile[] {\n if (!config.emit.workflows) return [];\n return renderWorkflowFiles(sources, config.output_dir);\n}\n\n/**\n * The project-root-relative output path template for slash commands, or\n * undefined when commands are not emitted.\n *\n * One source for both the renderer and the orphan scan: the template is what\n * declares which directory the emitter owns, so the two must never resolve it\n * differently.\n */\nfunction commandOutputTemplate(config: ClaudeConfig): string | undefined {\n const commands = config.emit.commands;\n if (!commands) return undefined;\n return commands.output ?? DEFAULT_COMMAND_OUTPUT;\n}\n\n/**\n * Additive per-workflow slash-command files (#249). Emitted ONLY when\n * `config.emit.commands` is set; otherwise returns [] so existing output is\n * byte-preserved (backward compatible).\n *\n * The output path defaults to DEFAULT_COMMAND_OUTPUT and the template to the\n * bundled DEFAULT_COMMAND_TEMPLATE; both are overridable via config. A\n * config-provided template path is read from disk (relative to the project root)\n * — this is the ONE async step, so the helper is async and the caller awaits it.\n */\nasync function commandFiles(\n sources: readonly DslSource[],\n config: ClaudeConfig,\n root: string,\n): Promise<RenderedFile[]> {\n const commands = config.emit.commands;\n if (!commands) return [];\n const outputTemplate = commandOutputTemplate(config)!;\n let templateSource = DEFAULT_COMMAND_TEMPLATE;\n if (commands.template) {\n const templatePath = resolve(root, commands.template);\n // A configured template path that cannot be read is a loud error, never a\n // silent fallback to the default (no silent drops).\n templateSource = await readFile(templatePath, \"utf8\");\n }\n return renderCommandFiles(sources, outputTemplate, templateSource);\n}\n\n/**\n * Additive Claude Code subagent files (#272). Emitted ONLY when\n * `config.emit.agents` is true; otherwise returns [] so existing output is\n * byte-preserved.\n *\n * Claude Code reads `.claude/agents/` only from the harness root, so in a\n * workspace the members' agents must be merged into the single root directory.\n */\nfunction agentFiles(sources: readonly DslSource[], config: ClaudeConfig): RenderedFile[] {\n if (!config.emit.agents) return [];\n return renderAgentFiles(sources, config.output_dir);\n}\n\n/**\n * The other half of `agentFiles` (#345): the dispatch-only agents' prompt for\n * the CLAUDE.md block. A dispatch-only agent is absent from `.claude/agents/`\n * precisely because it belongs here, so the two are called together at every\n * call site — dropping this one restores the silent drop it exists to close.\n *\n * Gated on the same `emit.agents` switch: it is the same emitter deciding where\n * one declared agent goes, not a second feature that could be turned on alone.\n */\nfunction entryAgentPromptFor(\n sources: readonly DslSource[],\n config: ClaudeConfig,\n): string | undefined {\n if (!config.emit.agents) return undefined;\n return renderEntryAgentPrompt(sources, config.output_dir);\n}\n\n/**\n * A `.claude/bin` entry this emitter owns: one carrying the bundle marker.\n *\n * Name is not usable here — bins are extensionless and arbitrarily named by the\n * generator, so a name rule would either miss stale bins or match a consumer's\n * scripts. The marker is written by `withAssembledHookBins` onto every file it\n * emits into this directory and by nothing else, which makes it the exact\n * ownership record. An unreadable entry (a broken symlink) is not ours.\n */\nasync function isOwnedHookBinFile(_name: string, absPath: string): Promise<boolean> {\n const content = await readIfExists(absPath).catch(() => undefined);\n return content !== undefined && readBundleMarker(content) !== undefined;\n}\n\n/**\n * Directory and extension the command output template declares as the emitter's.\n * Both come from the template because it is configurable: hard-coding either\n * would scan the wrong place the moment a project overrides `emit.commands.output`.\n * Paths in the template are project-root-relative with `/` separators.\n */\nfunction templateDir(outputTemplate: string): string {\n const slash = outputTemplate.lastIndexOf(\"/\");\n return slash === -1 ? \".\" : outputTemplate.slice(0, slash);\n}\n\nfunction templateExt(outputTemplate: string): string {\n const base = outputTemplate.slice(outputTemplate.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : base.slice(dot);\n}\n\n/**\n * Every stale generated file across the directories this emitter owns.\n *\n * A directory qualifies when the render is the COMPLETE truth for it, which is\n * the case for each of these:\n *\n * .claude/bin — the bins plus the chunks they import, nothing else\n * .claude/agents — one `.md` per DSL agent\n * .claude/workflows — one `.js` per DSL workflow (renderWorkflowFiles)\n * <command template> — one `.md` per DSL workflow (renderCommandFiles); the\n * configured output path is what declares this directory\n * as the emitter's namespace, so it is derived from the\n * template rather than hard-coded\n *\n * Dropping a workflow from the DSL therefore removes its script and its command,\n * exactly as dropping an agent removes its subagent file. A leftover is not\n * inert: `.claude/workflows/<id>.js` stays a Dynamic Workflow the harness can\n * still launch with no DSL behind it.\n *\n * `.claude/hooks` is the one generated directory deliberately NOT scanned, and\n * not because its set is open-ended in principle: the generator emits a constant\n * three wrappers that never shrink, so no orphan class exists there. It is also\n * shared space — #248 preserves consumer-added hooks, whose scripts live in that\n * same directory (`pre-tool-use-git-guard.sh` in the settings-merge tests) — so\n * scanning it could only ever delete someone else's file.\n */\nasync function orphanFiles(\n root: string,\n config: ClaudeConfig,\n rendered: readonly GeneratedFile[],\n workflows: readonly RenderedFile[],\n commands: readonly RenderedFile[],\n agents: readonly RenderedFile[],\n): Promise<string[]> {\n const orphans = await orphanGeneratedFiles(\n root,\n HOOK_BIN_DIR,\n rendered.filter((f) => isHookBin(f.targetDir, f.path)).map(generatedFileRelPath),\n isOwnedHookBinFile,\n );\n\n if (config.emit.workflows) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n workflowsDirFor(config.output_dir),\n workflows.map((f) => f.path),\n isOwnedByExtension(WORKFLOW_FILE_EXT),\n )),\n );\n }\n\n const commandTemplate = commandOutputTemplate(config);\n if (commandTemplate) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n templateDir(commandTemplate),\n commands.map((f) => f.path),\n isOwnedByExtension(templateExt(commandTemplate)),\n )),\n );\n }\n\n if (config.emit.agents) {\n orphans.push(\n ...(await orphanGeneratedFiles(\n root,\n agentsDirFor(config.output_dir),\n agents.map((f) => f.path),\n isOwnedByExtension(AGENT_FILE_EXT),\n )),\n );\n }\n\n return orphans;\n}\n\nfunction actionForOverwrite(existing: string | undefined, next: string): FileAction {\n if (existing === undefined) return \"created\";\n return existing === next ? \"unchanged\" : \"updated\";\n}\n\n/**\n * Mode for artifacts the generator declares `executable` (#277).\n */\nconst EXECUTABLE_MODE = 0o755;\n\n/**\n * Only the owner-execute bit distinguishes a `100755` blob from a `100644` one,\n * and `git checkout` applies the user's umask to the group/other bits — so the\n * owner bit is the one that is both authoritative and stable across checkouts.\n */\nconst OWNER_EXEC_BIT = 0o100;\n\n/**\n * True when an existing file is missing its executable bit. Absent files report\n * false: there is no mode to repair, and the write path creates them with the\n * right mode anyway.\n */\nasync function execBitMissing(abs: string): Promise<boolean> {\n try {\n const { mode } = await stat(abs);\n return (mode & OWNER_EXEC_BIT) === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * The ONE write site for every materialized artifact — hook bins, generated\n * `.claude/*` files and the additive workflow/command/agent renders all pass\n * through here, so the executable bit is applied in a single place rather than\n * per writer (#277).\n *\n * Mode is part of the artifact, not a property of the bytes: a file whose\n * content already matches but which lost its executable bit is still out of\n * date (Claude Code execs `.claude/hooks/*.sh` and `.claude/bin/file-suggestion`\n * by path, so a 644 file makes the hook die with EACCES). Such a file is\n * repaired with a chmod alone and reported as `updated` — reporting it\n * `unchanged` would leave `claude check` permanently red with nothing able to\n * fix it.\n *\n * @param content Resolved lazily so an unchanged hook bin is never re-assembled.\n */\nasync function writeArtifact(opts: {\n abs: string;\n content: () => string;\n action: FileAction;\n executable: boolean;\n dryRun: boolean;\n}): Promise<FileAction> {\n const modeOnly =\n opts.action === \"unchanged\" && opts.executable && (await execBitMissing(opts.abs));\n const action: FileAction = modeOnly ? \"updated\" : opts.action;\n\n if (action === \"unchanged\" || opts.dryRun) return action;\n\n if (!modeOnly) {\n await mkdir(dirname(opts.abs), { recursive: true });\n await writeFile(opts.abs, opts.content(), \"utf8\");\n }\n if (opts.executable) await chmod(opts.abs, EXECUTABLE_MODE);\n return action;\n}\n\n/**\n * Drift for a self-contained hook bin (#241), detected without re-reading\n * node_modules by comparing markers. Two independent checks:\n * (a) stored marker vs expected marker for the current source/version\n * (catches generator/runtime-version changes), and\n * (b) stored marker vs the marker recomputed from the file's own bytes\n * (catches body tampering even when the marker line is left intact —\n * the weakness the prior audit flagged).\n */\nfunction checkHookBin(\n file: GeneratedFile,\n existing: string | undefined,\n): \"missing\" | \"changed\" | null {\n if (existing === undefined) return \"missing\";\n const stored = readBundleMarker(existing);\n const expected = readBundleMarker(file.content);\n const onDisk = recomputeMarkerFromDisk(existing);\n return stored !== expected || stored !== onDisk ? \"changed\" : null;\n}\n\n/**\n * Materialize `.claude/*` and the CLAUDE.md integration block from the embedded DSL.\n *\n * Idempotent: re-running with no changes writes nothing. CLAUDE.md uses a\n * marker-delimited block merge so user content outside the block is preserved.\n */\nexport async function syncClaude(opts: SyncOptions): Promise<SyncResult> {\n const config = parseClaudeConfig(opts.config);\n const root = resolve(opts.projectRoot);\n const result: SyncResult = { files: [] };\n\n // Resolved before the generator runs, not after: the CLAUDE.md block it\n // renders carries the dispatch-only agents' prompt, and these sources are the\n // only thing that knows which agents those are (#345).\n const sources = await resolveDslSources(root, opts.dsl, config);\n\n const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));\n for (const file of rendered) {\n const rel = generatedFileRelPath(file);\n const abs = absPath(root, file);\n const existing = await readIfExists(abs);\n\n // `.claude/bin` holds self-contained ESM — bins assembled against a shared\n // runtime chunk, so nothing needs node_modules resolution at hook runtime.\n // `renderFiles` already produced the final bytes (NO esbuild runs here; it\n // is pure string work), each carrying a marker line. A file is up to date\n // only when its stored marker matches BOTH the marker of the content we\n // would write AND the marker recomputed from its own on-disk content (so\n // body tampering forces a re-sync). The write itself goes through\n // writeArtifact, which also repairs a missing exec bit.\n if (isHookBin(file.targetDir, file.path)) {\n const drift = checkHookBin(file, existing);\n const action: FileAction =\n drift === \"missing\" ? \"created\" : drift === \"changed\" ? \"updated\" : \"unchanged\";\n result.files.push({\n path: rel,\n action: await writeArtifact({\n abs,\n content: () => file.content,\n action,\n executable: file.executable === true,\n dryRun: opts.dryRun === true,\n }),\n });\n continue;\n }\n\n const { content, action } = resolveContent(file, existing);\n\n result.files.push({\n path: rel,\n action: await writeArtifact({\n abs,\n content: () => content,\n action,\n executable: file.executable === true,\n dryRun: opts.dryRun === true,\n }),\n });\n }\n\n // Additive fully-generated, overwrite-owned files (Dynamic Workflow scripts\n // #235 + per-workflow slash commands #249 + subagents #272). Same handling:\n // overwrite-owned, drift = missing or hand-edited.\n //\n // All three emitters read the SAME resolved sources (#274): the project's\n // effective DSL, not the bare embedded one they used to be handed.\n //\n // Each emitter's output is kept as its own list because it is also the\n // EXPECTED set the orphan scan subtracts from its directory (#278) — deriving\n // that set from anything but this render is how a stale file survives.\n const workflows = workflowFiles(sources, config);\n const commands = await commandFiles(sources, config, root);\n const agents = agentFiles(sources, config);\n const additive = [...workflows, ...commands, ...agents];\n for (const file of additive) {\n const abs = join(root, file.path);\n const existing = await readIfExists(abs);\n result.files.push({\n path: file.path,\n // Workflow scripts, slash commands and subagent files are read by the\n // harness, never exec'd by path, so none of them is executable.\n action: await writeArtifact({\n abs,\n content: () => file.content,\n action: actionForOverwrite(existing, file.content),\n executable: false,\n dryRun: opts.dryRun === true,\n }),\n });\n }\n\n // Anything dropped from the render must be dropped from the harness: until\n // the file is gone Claude Code still lists and can invoke a stale subagent,\n // and a stale `.claude/bin` chunk stays committed dead weight.\n for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {\n if (!opts.dryRun) {\n await rm(join(root, path));\n }\n result.files.push({ path, action: \"deleted\" });\n }\n\n return result;\n}\n\n/**\n * Read-only drift gate. Reports files whose on-disk content differs from a\n * fresh render. For CLAUDE.md, drift means the aaac:claude-native block is\n * missing or stale (content outside the block is ignored).\n */\nexport async function checkClaude(opts: SyncOptions): Promise<CheckResult> {\n const config = parseClaudeConfig(opts.config);\n const root = resolve(opts.projectRoot);\n const drift: CheckResult[\"drift\"] = [];\n\n // Same resolution, same order and same position as `syncClaude`: the block\n // this compares against carries the dispatch-only agents' prompt (#345).\n const sources = await resolveDslSources(root, opts.dsl, config);\n\n const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));\n for (const file of rendered) {\n const rel = generatedFileRelPath(file);\n const abs = absPath(root, file);\n const existing = await readIfExists(abs);\n\n const contentReason = isHookBin(file.targetDir, file.path)\n ? checkHookBin(file, existing)\n : checkContent(file, existing);\n\n // Mode is part of the artifact (#277): a file whose bytes match but whose\n // executable bit was dropped is exactly the failure this gate exists to\n // catch — Claude Code execs the hook by path and it dies with EACCES, and a\n // content-only comparison stays green forever. `sync` repairs it, so it is\n // reported as `changed` like any other repairable divergence.\n const modeDrift =\n contentReason === null &&\n file.executable === true &&\n existing !== undefined &&\n (await execBitMissing(abs));\n\n const reason = contentReason ?? (modeDrift ? \"changed\" : null);\n if (reason) {\n drift.push({ path: rel, reason });\n }\n }\n\n // Additive files (Dynamic Workflow scripts #235 + slash commands #249 +\n // subagents #272): drift = missing or hand-edited. Same resolved sources as\n // sync, so `check` cannot disagree with what `sync` would write (#274), and\n // the same per-emitter lists, so the orphan scan below subtracts exactly the\n // set `sync` would have written (#278).\n const workflows = workflowFiles(sources, config);\n const commands = await commandFiles(sources, config, root);\n const agents = agentFiles(sources, config);\n const additive = [...workflows, ...commands, ...agents];\n for (const file of additive) {\n const existing = await readIfExists(join(root, file.path));\n if (existing === undefined) {\n drift.push({ path: file.path, reason: \"missing\" });\n } else if (existing !== file.content) {\n drift.push({ path: file.path, reason: \"changed\" });\n }\n }\n\n // A generated file the render no longer produces is drift too — the loop\n // above walks the EXPECTED set and so can never see it.\n for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {\n drift.push({ path, reason: \"orphaned\" });\n }\n\n return { inSync: drift.length === 0, drift };\n}\n","/**\n * Self-contained hook-bin assembler (#241, #278).\n *\n * The Claude generator (`@aaac/contracts`) emits thin Node ESM bin scripts that\n * `import { … } from \"@aaac/runtime/claude-native\"` (or `.../hooks-lite`) using\n * a bare specifier plus a small per-project parameter body (componentId,\n * configPath, MEMBERS, …). Those bare specifiers require `node_modules/@aaac`\n * to be resolvable at the bin's location at runtime — which fails with\n * `ERR_MODULE_NOT_FOUND` in project roots that do not carry a hoisted\n * `node_modules/@aaac` (the workspace/dogfood case). NODE_PATH (#233) does NOT\n * help because it is ignored for bare ESM specifier resolution.\n *\n * Fix (build-time bundle + sync-time templating): the \"flatten @aaac/runtime\n * into a self-contained file\" step runs ONCE at @aaac/runtime BUILD time\n * (scripts/build-claude-bundles.mjs, esbuild as a build-time devDependency),\n * producing two pre-built ESM bundles shipped in the package:\n *\n * dist/claude-bundles/lean.js (from hooks-lite — hot path, ~10KB)\n * dist/claude-bundles/full.js (from claude-native — per-session bins)\n *\n * At `claude sync` time there is NO esbuild. Each pre-built bundle is written\n * verbatim as ONE shared chunk in `.claude/bin/`, and every bin that needs it\n * keeps its own import statement with only the SPECIFIER rewritten to that\n * chunk's relative path. A relative specifier needs no `node_modules` and no\n * package resolution at all, so the #241 self-contained property holds while\n * the multi-megabyte runtime exists once per project instead of once per bin —\n * the 75% byte-identical duplication #278 measured.\n *\n * Everything emitted here carries a marker line (see MARKER_PREFIX), so the\n * drift gate treats bins and shared chunks identically.\n */\n\nimport {\n HOOK_BIN_CHUNK_PREFIX,\n isHookBinChunk,\n type GeneratedFile,\n} from \"@aaac/contracts\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, parse } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadPrebuiltBundle, type BundleKind } from \"./claude-bundle-assets.js\";\n\n/** Directory the Claude generator targets its bin scripts at. */\nexport const HOOK_BIN_DIR = \".claude/bin\";\n\n/**\n * Bundle kinds in emission order. Iterating this rather than a Set's insertion\n * order keeps the emitted file list stable no matter what order the generator\n * returns bins in — the drift gate compares exact bytes.\n */\nconst BUNDLE_KINDS: readonly BundleKind[] = [\"lean\", \"prompt\", \"full\"];\n\n/**\n * Resolve @aaac/runtime's own version by walking upward until a package.json\n * named `@aaac/runtime` is found. Used only for the bundle marker's version\n * component; the marker's full-file content hash does the real drift work, so a\n * \"bundled\" fallback (in the self-contained CLI, where no package dir exists)\n * is harmless.\n */\nfunction resolveRuntimeVersion(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n const root = parse(dir).root;\n while (true) {\n try {\n const manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n if (typeof manifest === \"object\" && manifest !== null) {\n const pkg = manifest as Record<string, unknown>;\n if (pkg.name === \"@aaac/runtime\" && typeof pkg.version === \"string\") return pkg.version;\n }\n } catch {\n // keep walking\n }\n if (dir === root) break;\n dir = dirname(dir);\n }\n return \"bundled\";\n}\n\nconst RUNTIME_VERSION = resolveRuntimeVersion();\n\n/**\n * Read a pre-built bundle. Cached per kind so a single sync run does not\n * re-materialize the (multi-MB) full bundle repeatedly. The actual asset load\n * lives in claude-bundle-assets (which the CLI build embeds inline).\n */\nconst bundleCache = new Map<BundleKind, string>();\n\nfunction readPrebuiltBundle(kind: BundleKind): string {\n const cached = bundleCache.get(kind);\n if (cached !== undefined) return cached;\n const content = loadPrebuiltBundle(kind);\n bundleCache.set(kind, content);\n return content;\n}\n\n/**\n * Marker line embedded at the top of every emitted file. It records the\n * runtime version + a hash of the FULL emitted file so the drift gate\n * (`checkClaude`) detects ANY content change — including body tampering below\n * the marker — not just a change in the generated source.\n */\nconst MARKER_PREFIX = \"//__aaac_bundle__:\";\n\n/** True when a generated file's path targets `.claude/bin`. */\nexport function isHookBin(targetDir: string | undefined, path: string): boolean {\n return targetDir === HOOK_BIN_DIR && !path.includes(\"/\");\n}\n\n/**\n * The generated bin's bare runtime import. Group 1 is everything up to the\n * specifier (so it can be re-emitted verbatim); group 2 is present only for the\n * lean subpath. ONE regex serves both readers — which bundle a bin needs, and\n * where to repoint it — so they can never disagree about a given source.\n *\n * Global: the count matters, see requireRuntimeImport.\n */\nconst RUNTIME_IMPORT_RE =\n /(import\\s*\\{[^}]*\\}\\s*from\\s*)[\"']@aaac\\/runtime\\/claude-native(?:\\/(hooks-lite|hooks-prompt))?[\"']/g;\n\n/**\n * Locate a hook entry script's bare runtime import.\n *\n * Callers must already know the file IS an entry script (`isHookBinChunk` is\n * false for it). This never decides that question: the shared modules in this\n * directory carry the project's DSL as arbitrary user text, and matching import\n * syntax against content would read that data as code.\n *\n * Exactly one is required. Zero means the generator emitted an entry script that\n * cannot reach the runtime at all. More than one is a silent corruption: only\n * the first would be repointed at the shared chunk and every later specifier\n * would ship bare, needing `node_modules` at hook runtime — the exact #241\n * failure this module exists to prevent. Neither is visible to the drift gate,\n * which compares markers over content this module itself produced, so a bad bin\n * is \"in sync\" with its own bad bytes. Fail loud instead.\n */\nfunction requireRuntimeImport(source: string): RegExpMatchArray {\n const matches = [...source.matchAll(RUNTIME_IMPORT_RE)];\n if (matches.length !== 1) {\n throw new Error(\n `A generated hook bin must import @aaac/runtime/claude-native exactly once; found ` +\n `${matches.length}${\n matches.length > 0 ? `: ${matches.map((m) => JSON.stringify(m[0])).join(\", \")}` : \"\"\n }. Only one can be repointed at the shared chunk; any other would ship as a bare ` +\n `specifier that needs node_modules at hook runtime.`,\n );\n }\n return matches[0];\n}\n\n/** Runtime subpath -> the pre-built bundle that serves it. */\nconst KIND_BY_SUBPATH: Record<string, BundleKind> = {\n \"hooks-lite\": \"lean\",\n \"hooks-prompt\": \"prompt\",\n};\n\n/**\n * Which pre-built bundle a hook entry script needs, read straight off the\n * specifier the generator chose. `BIN_RUNTIME_SUBPATH` (in @aaac/contracts'\n * claude-generator) is the single source of truth for which barrel each bin\n * imports; this only maps that emitted subpath to its bundle. No bin name\n * appears here, so the two cannot drift apart the way `file-suggestion` did\n * (#278).\n */\nexport function bundleKindFor(source: string): BundleKind {\n const subpath = requireRuntimeImport(source)[2];\n return subpath ? KIND_BY_SUBPATH[subpath]! : \"full\";\n}\n\n/**\n * File name of the shared runtime chunk for each bundle kind. `.mjs` so the\n * chunk parses as ESM regardless of the consuming project's package.json `type`.\n *\n * Written out per kind rather than templated from `kind`, because these names are\n * the set `.gitattributes`' `aaac-bundled` mark is checked against\n * (`.github/scripts/lib/workspace.mjs`). A name assembled inside a function from\n * a parameter is a name only this module can produce, so the check had nothing to\n * compare against but `HOOK_BIN_CHUNK_PREFIX` — which accepted any `_`-prefixed\n * file anyone dropped in {@link HOOK_BIN_DIR} (#341).\n *\n * The set is finite because `BundleKind` is a closed union: `Record<BundleKind,\n * …>` does not compile until a new kind is named here. The value type keeps the\n * prefix from drifting away from the classifier that reads it — a name not\n * starting with `HOOK_BIN_CHUNK_PREFIX` does not compile either.\n */\nconst RUNTIME_CHUNK_FILE = {\n lean: \"_aaac-runtime-lean.mjs\",\n prompt: \"_aaac-runtime-prompt.mjs\",\n full: \"_aaac-runtime-full.mjs\",\n} as const satisfies Record<BundleKind, `${typeof HOOK_BIN_CHUNK_PREFIX}${string}`>;\n\n/** File name of the shared runtime chunk for a bundle kind. */\nexport function chunkFileName(kind: BundleKind): string {\n return RUNTIME_CHUNK_FILE[kind];\n}\n\n/**\n * Stamp the content-hash marker in as line 2, so `readBundleMarker` finds it at\n * a fixed position in bins (after the shebang) and chunks (after their banner\n * comment) alike.\n */\nfunction withMarker(bodyWithoutMarker: string): string {\n const firstNl = bodyWithoutMarker.indexOf(\"\\n\");\n return (\n bodyWithoutMarker.slice(0, firstNl + 1) +\n markerFor(bodyWithoutMarker) +\n \"\\n\" +\n bodyWithoutMarker.slice(firstNl + 1)\n );\n}\n\n/**\n * Assemble a single generated bin into a self-contained ESM script by string\n * templating (NO esbuild). Layout:\n *\n * #!/usr/bin/env node\n * //__aaac_bundle__:<version>:<fullFileHash>\n * <bin body: shebang stripped, the bare `@aaac/…` specifier repointed at\n * `./_aaac-runtime-<kind>.mjs`; the bin's own node:* imports are kept>\n *\n * The runtime itself is NOT inlined here — it lives in the shared chunk\n * `assembleRuntimeChunk` emits alongside.\n */\nfunction assembleHookBin(source: string, kind: BundleKind): string {\n // Strip the generated shebang; a single canonical one is re-added below.\n const withoutShebang = source.replace(/^#![^\\n]*\\n/, \"\");\n\n // Repoint the bare specifier at the shared chunk. The imported names, and\n // everything else about the statement, stay exactly as generated. Re-located\n // after stripping the shebang so the offsets are the ones we replace at.\n const match = requireRuntimeImport(withoutShebang);\n const binBody = withoutShebang.replace(\n match[0],\n () => `${match[1]}\"./${chunkFileName(kind)}\"`,\n );\n\n return withMarker(\n [\n \"#!/usr/bin/env node\",\n \"// Auto-generated by @aaac/runtime claude sync (#241). Do not edit — self-contained bundle.\",\n binBody.trimStart(),\n ].join(\"\\n\"),\n );\n}\n\n/**\n * The shared runtime chunk for a bundle kind: the pre-built ESM bundle verbatim,\n * behind the same banner + marker every emitted file carries. Bins reach it by\n * relative specifier, so it needs no `node_modules` and no package resolution.\n */\nfunction assembleRuntimeChunk(kind: BundleKind): string {\n return withMarker(\n [\n `// Auto-generated by @aaac/runtime claude sync (#278). Do not edit — shared ${kind} runtime chunk.`,\n readPrebuiltBundle(kind).trimEnd(),\n \"\",\n ].join(\"\\n\"),\n );\n}\n\n/**\n * Turn the generator's raw output into the bytes `.claude/bin` should hold:\n * every bin assembled against a shared runtime chunk, the generator's own\n * shared data chunks marker-stamped, and one runtime chunk per bundle kind the\n * bins actually import — a kind no bin imports is never emitted.\n *\n * That last point is only a claim about what this function EMITS. Nothing here\n * removes a chunk a previous sync wrote that the current one no longer needs;\n * see `orphanGeneratedFiles` in materialize.ts, which is what actually reports\n * and deletes those, because it scans the directory instead of the expected set.\n *\n * Every `.claude/bin` file leaves here carrying a marker line, including the\n * ones this module did not generate the body of. That is load-bearing: the\n * drift gate compares markers, so an unstamped file would make the stored,\n * expected and recomputed markers all `undefined` — trivially equal — and its\n * content changes would be invisible.\n */\nexport function withAssembledHookBins(files: readonly GeneratedFile[]): GeneratedFile[] {\n const out: GeneratedFile[] = [];\n const needed = new Set<BundleKind>();\n\n for (const file of files) {\n if (!isHookBin(file.targetDir, file.path)) {\n out.push(file);\n continue;\n }\n\n if (isHookBinChunk(file.path)) {\n // A shared module (the project's embedded DSL). Its body is user data, so\n // it is never parsed as code here — it only needs the marker every file\n // in this directory carries.\n out.push({ ...file, content: withMarker(file.content) });\n continue;\n }\n\n const kind = bundleKindFor(file.content);\n needed.add(kind);\n out.push({ ...file, content: assembleHookBin(file.content, kind) });\n }\n\n for (const kind of BUNDLE_KINDS) {\n if (!needed.has(kind)) continue;\n out.push({\n path: chunkFileName(kind),\n content: assembleRuntimeChunk(kind),\n overwrite: true,\n targetDir: HOOK_BIN_DIR,\n });\n }\n\n return out;\n}\n\nfunction markerFor(fullFileMinusMarker: string): string {\n const hash = createHash(\"sha256\").update(fullFileMinusMarker).digest(\"hex\").slice(0, 16);\n return `${MARKER_PREFIX}${RUNTIME_VERSION}:${hash}`;\n}\n\n/**\n * Extract the bundle marker from already-emitted content, if present.\n * The marker is always the second line.\n */\nexport function readBundleMarker(content: string): string | undefined {\n const nl = content.indexOf(\"\\n\");\n if (nl === -1) return undefined;\n const secondNl = content.indexOf(\"\\n\", nl + 1);\n const line = content.slice(nl + 1, secondNl === -1 ? undefined : secondNl);\n return line.startsWith(MARKER_PREFIX) ? line : undefined;\n}\n\n/**\n * Recompute the content hash of an on-disk file (its full content with the\n * marker line removed) and return the marker that content *should* carry.\n *\n * This is what makes body-tamper detection work: the drift gate compares this\n * against the marker actually stored in the file. If the body was edited but\n * the marker line left intact, the recomputed marker no longer matches the\n * stored one — so drift is reported even though the generated source is\n * unchanged. (The prior implementation only hashed the generator source, so an\n * appended/edited body with an intact marker went undetected.)\n */\nexport function recomputeMarkerFromDisk(content: string): string | undefined {\n const nl = content.indexOf(\"\\n\");\n if (nl === -1) return undefined;\n const secondNl = content.indexOf(\"\\n\", nl + 1);\n if (secondNl === -1) return undefined;\n const markerLine = content.slice(nl + 1, secondNl);\n if (!markerLine.startsWith(MARKER_PREFIX)) return undefined;\n // Reconstruct the file with the marker line removed, exactly as withMarker\n // hashed it before inserting the marker.\n const firstLine = content.slice(0, nl + 1);\n const rest = content.slice(secondNl + 1);\n return markerFor(firstLine + rest);\n}\n","/**\n * Pre-built Claude-runtime bundle asset loader (#241).\n *\n * Returns the self-contained ESM bundles produced at @aaac/runtime BUILD time\n * (scripts/build-claude-bundles.mjs) and shipped in the package dist/.\n *\n * Two deployment shapes are supported:\n *\n * 1. npm package consumer — the bundles live at\n * `<@aaac/runtime>/dist/claude-bundles/{lean,full}.js`; this module reads\n * them from disk relative to its own compiled location.\n *\n * 2. Self-contained CLI (examples/dev-team → bin/dev-team.mjs) — there is no\n * `@aaac/runtime` package dir at runtime, so the CLI's esbuild build\n * (examples/dev-team/esbuild.bundle.mjs) replaces this ENTIRE module via an\n * onLoad plugin that embeds the two bundle strings inline. The disk read\n * below is never executed in that shape.\n *\n * This is a deliberately tiny, single-purpose module so the CLI build's\n * whole-file replacement stays simple and robust.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, parse } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type BundleKind = \"lean\" | \"prompt\" | \"full\";\n\n/**\n * Resolve the @aaac/runtime package dist directory by walking upward from this\n * module until the package.json named `@aaac/runtime` is found. Robust to\n * tsup's chunk hoisting.\n */\nfunction resolveRuntimeDistDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n const root = parse(dir).root;\n while (true) {\n try {\n const manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n (manifest as Record<string, unknown>).name === \"@aaac/runtime\"\n ) {\n return join(dir, \"dist\", \"claude-bundles\");\n }\n } catch {\n // keep walking\n }\n if (dir === root) break;\n dir = dirname(dir);\n }\n // Fallback: assume bundles sit alongside this module's dist tree.\n return join(dirname(fileURLToPath(import.meta.url)), \"claude-bundles\");\n}\n\n/**\n * Read a pre-built runtime bundle by kind. In the CLI build this whole function\n * body is replaced with an embedded-string return (see the module doc comment).\n */\nexport function loadPrebuiltBundle(kind: BundleKind): string {\n const path = join(resolveRuntimeDistDir(), `${kind}.js`);\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n throw new Error(\n `Missing pre-built Claude runtime bundle: ${path}. ` +\n `Run \\`npm run build\\` in @aaac/runtime (build-claude-bundles.mjs) first.`,\n );\n }\n}\n","/**\n * `.claude/settings.json` managed-region merge (#248).\n *\n * The claude generator emits settings.json with `overwrite: true`, which used to\n * clobber the whole file on every `claude sync`. That destroyed any custom hook a\n * project added by hand (e.g. a git-command guard on `PreToolUse`) and made\n * `claude check` report permanent false drift.\n *\n * This module merges the aaac-managed region into the user's existing file\n * non-destructively — the same principle as the `CLAUDE.md` marker-block merge,\n * but for JSON. aaac owns a fixed, self-describing region; everything else the\n * user put in the file is preserved verbatim.\n *\n * ## Managed-vs-non-managed discriminator (why command-path, not a marker)\n *\n * A JSON settings file cannot carry comment markers, and a side-car \"managed\n * keys\" list would drift out of sync with the generator. Instead we key on the\n * one thing that is intrinsic to an aaac-generated entry and survives round\n * trips: **the command string points at an aaac-managed launcher under\n * `.claude/`** — `${CLAUDE_PROJECT_DIR}/.claude/hooks/*.sh` for the hook events\n * and `${CLAUDE_PROJECT_DIR}/.claude/bin/file-suggestion` for `fileSuggestion`.\n *\n * A command hook is \"managed\" iff its `command` matches a command produced by\n * the current generator render (we read them straight out of the freshly\n * generated settings object — no hardcoded list to drift). Concretely:\n * • `fileSuggestion` — fully owned by aaac (single managed command).\n * • each generated hook event (SessionStart / UserPromptSubmit / PreToolUse):\n * managed entries = groups/hooks whose command is one the generator emits;\n * every other group/hook in that event is a user addition and is kept.\n * • hook events the generator does NOT emit (PostToolUse, Stop, …) and every\n * other top-level key are user-owned and passed through untouched.\n *\n * This is robust: it survives round-trips (managed commands are regenerated\n * identically), it needs no marker the JSON format can't hold, and it is\n * computed the SAME way for `sync` (produce merged content) and `check` (compare\n * on-disk against the merged content), so a user-added hook is never drift while\n * a mutated/removed managed entry always is.\n */\n\nexport interface CommandHook {\n type?: string;\n command?: string;\n [key: string]: unknown;\n}\n\nexport interface HookGroup {\n matcher?: string;\n hooks?: CommandHook[];\n [key: string]: unknown;\n}\n\nfunction commandOf(hook: CommandHook): string | undefined {\n return typeof hook.command === \"string\" ? hook.command : undefined;\n}\n\n/**\n * An entry inside a `hooks.<Event>` array. Only ONE of these two shapes is valid\n * to Claude Code, but both reach this merge:\n * • a matcher group of hooks — `{ \"matcher\": \"Bash\", \"hooks\": [ … ] }`\n * — the only shape Claude Code accepts, and what the generator emits (#352),\n * • a bare command hook — `{ \"type\": \"command\", \"command\": \"…\" }`\n * — invalid, and invalid FATALLY: one bare entry makes Claude Code discard\n * every hook in the file. It reaches the merge because the generator emitted\n * it until #352, so an on-disk file written by an older sync still carries\n * managed entries in that shape, and they have to be recognised to be\n * replaced.\n * The merge therefore classifies managed-vs-user at the command level regardless\n * of which envelope carries the command; it does not treat the bare envelope as\n * legitimate.\n */\nexport type HookEntry = CommandHook | HookGroup;\n\nexport interface ClaudeSettings {\n fileSuggestion?: unknown;\n hooks?: Record<string, HookEntry[]>;\n [key: string]: unknown;\n}\n\n/** A group entry is one that carries a nested `hooks` array. */\nfunction isGroup(entry: HookEntry): entry is HookGroup {\n return Array.isArray((entry as HookGroup).hooks);\n}\n\n/** Every command string reachable from a single event-array entry. */\nfunction commandsInEntry(entry: HookEntry): string[] {\n if (isGroup(entry)) {\n return (entry.hooks ?? [])\n .map((h) => commandOf(h))\n .filter((c): c is string => c !== undefined);\n }\n const c = commandOf(entry);\n return c === undefined ? [] : [c];\n}\n\nfunction isCommandHook(value: unknown): value is CommandHook {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const hook = value as Record<string, unknown>;\n return (\n (hook.type === undefined || typeof hook.type === \"string\") &&\n (hook.command === undefined || typeof hook.command === \"string\")\n );\n}\n\n/**\n * Either envelope of {@link HookEntry}, with every field the two declare.\n *\n * The index signature on both is `unknown`, so the fields checked here are the\n * whole of what the type promises — and each one is a field this merge walks:\n * `hooks` decides the envelope, `command` decides managed-vs-user. An entry that\n * fails is not a hook entry, and `null` is the shape that actually arrived:\n * `TypeError: … reading 'hooks'` from `isGroup`, one line into the merge.\n */\nfunction isHookEntry(value: unknown): value is HookEntry {\n if (!isCommandHook(value)) return false;\n const entry = value as Record<string, unknown>;\n return (\n (entry.matcher === undefined || typeof entry.matcher === \"string\") &&\n (entry.hooks === undefined ||\n (Array.isArray(entry.hooks) && entry.hooks.every(isCommandHook)))\n );\n}\n\n/**\n * The single gate in front of {@link ClaudeSettings}.\n *\n * `hooks` is the only field the type makes a structural promise about —\n * `fileSuggestion` is declared `unknown` and every other key reaches the index\n * signature, which is why the merge copies them verbatim and needs no claim\n * about them.\n */\nfunction isClaudeSettings(value: unknown): value is ClaudeSettings {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const settings = value as Record<string, unknown>;\n if (settings.hooks === undefined) return true;\n if (typeof settings.hooks !== \"object\" || settings.hooks === null) return false;\n return Object.values(settings.hooks as Record<string, unknown>).every(\n (entries) => Array.isArray(entries) && entries.every(isHookEntry),\n );\n}\n\n/**\n * Parse settings.json text; fail-open to `{}` for empty/invalid input.\n *\n * Text that parses but is not a settings document is invalid input for this\n * reader and gets the same answer, rather than being asserted into the type and\n * walked. `claude check` reports the resulting difference as drift, which is how\n * a file this merge cannot read reaches the user — before this gate existed both\n * `check` and `sync` died inside `mergeSettings` instead.\n */\nexport function parseSettings(raw: string | undefined): ClaudeSettings {\n if (!raw || !raw.trim()) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {};\n }\n return isClaudeSettings(parsed) ? parsed : {};\n}\n\n/** Serialize with the exact shape the generator uses (2-space indent + trailing newline). */\nexport function serializeSettings(settings: ClaudeSettings): string {\n return JSON.stringify(settings, null, 2) + \"\\n\";\n}\n\n/**\n * Managed command strings, scoped PER EVENT.\n *\n * Discrimination MUST be per-event, not a global flat set: the same launcher\n * command could legitimately be registered by a user under a DIFFERENT event\n * than the one aaac emits it for (e.g. the `pre-tool-use.sh` launcher placed\n * under `PostToolUse`). A global set would silently strip that user entry. An\n * entry is \"managed\" only if its command matches one the generator emits for\n * that same event; under an event where aaac emits nothing, nothing is managed\n * so every user entry is preserved. `fileSuggestion` stays top-level-managed.\n */\nfunction managedCommandsByEvent(managed: ClaudeSettings): Map<string, Set<string>> {\n const byEvent = new Map<string, Set<string>>();\n for (const [event, entries] of Object.entries(managed.hooks ?? {})) {\n const cmds = new Set<string>();\n for (const entry of entries) {\n for (const c of commandsInEntry(entry)) cmds.add(c);\n }\n byEvent.set(event, cmds);\n }\n return byEvent;\n}\n\n/**\n * Merge the aaac-managed settings into the user's existing settings.\n *\n * The result is: managed region rendered fresh, every non-managed part of the\n * existing file preserved. When `existing` is undefined this returns exactly the\n * managed object (byte-identical to the previous overwrite behaviour for fresh\n * projects — backward compatible).\n */\nexport function mergeSettings(\n existing: ClaudeSettings | undefined,\n managed: ClaudeSettings,\n): ClaudeSettings {\n if (existing === undefined) {\n // Fresh project: emit the managed object as-is (byte-stable with pre-#248).\n return managed;\n }\n\n const managedCmdsByEvent = managedCommandsByEvent(managed);\n\n // Start from a shallow clone of the user's file so unknown top-level keys and\n // ordering of user keys are preserved.\n const out: ClaudeSettings = { ...existing };\n\n // fileSuggestion is fully aaac-owned.\n if (\"fileSuggestion\" in managed) {\n out.fileSuggestion = managed.fileSuggestion;\n }\n\n // hooks: rebuild each event as [managed entries] + [surviving user entries].\n const existingHooks = existing.hooks ?? {};\n const managedHooks = managed.hooks ?? {};\n const mergedHooks: Record<string, HookEntry[]> = {};\n\n // Preserve the union of events. Event-array order is not semantically\n // significant to Claude (it reads by key), but we keep managed entries first\n // then surviving user entries so a fresh project is byte-identical to the\n // pure managed render.\n const eventNames = new Set<string>([\n ...Object.keys(existingHooks),\n ...Object.keys(managedHooks),\n ]);\n\n for (const event of eventNames) {\n const managedEntries = managedHooks[event] ?? [];\n const userEntries = existingHooks[event] ?? [];\n // Managed commands for THIS event only. Empty for events aaac doesn't emit,\n // so a user entry there is never stripped even if its command collides with\n // a launcher aaac manages under a different event.\n const managedCmds = managedCmdsByEvent.get(event) ?? new Set<string>();\n\n // Keep only the parts of each user entry that are NOT aaac-managed (the\n // generator re-supplies managed commands). Works for both entry shapes:\n // • bare command hook → dropped iff its command is managed\n // • matcher group → managed hooks stripped; group kept iff any\n // non-managed hook remains\n const survivingUserEntries: HookEntry[] = [];\n for (const entry of userEntries) {\n if (isGroup(entry)) {\n const keptHooks = (entry.hooks ?? []).filter((h) => {\n const c = commandOf(h);\n return c === undefined || !managedCmds.has(c);\n });\n if (keptHooks.length > 0) {\n survivingUserEntries.push({ ...entry, hooks: keptHooks });\n }\n } else {\n const c = commandOf(entry);\n if (c === undefined || !managedCmds.has(c)) {\n survivingUserEntries.push(entry);\n }\n }\n }\n\n const combined = [...managedEntries, ...survivingUserEntries];\n if (combined.length > 0) {\n mergedHooks[event] = combined;\n }\n }\n\n if (Object.keys(mergedHooks).length > 0) {\n out.hooks = mergedHooks;\n } else {\n delete out.hooks;\n }\n\n return out;\n}\n\n/**\n * Compute the merged settings.json TEXT for a project.\n *\n * @param existingRaw on-disk settings.json text (or undefined if absent)\n * @param managedRaw the freshly generated (managed) settings.json text\n */\nexport function mergedSettingsText(\n existingRaw: string | undefined,\n managedRaw: string,\n): string {\n const managed = parseSettings(managedRaw);\n const existing = existingRaw === undefined ? undefined : parseSettings(existingRaw);\n return serializeSettings(mergeSettings(existing, managed));\n}\n","/**\n * Prompt Executor — natural language routing via LLM tool selection.\n *\n * Converts component operations into tool descriptions, sends them to an LLM\n * for routing, and dispatches the selected operation through the existing\n * component binding.\n */\n\nimport * as YAML from \"yaml\";\nimport type { ComponentIR, JSONSchemaRef } from \"@aaac/contracts\";\nimport type { RuntimeBinding, AaacInvocationContext } from \"../component-binding.js\";\nimport { createAdapter } from \"./adapter-factory.js\";\n\nexport interface OperationToolDef {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nexport interface PromptResult {\n selectedOperation: string;\n mappedInput: Record<string, unknown>;\n output?: unknown;\n dryRun?: boolean;\n model?: string;\n}\n\nexport interface PromptExecuteOptions {\n dryRun?: boolean;\n adapter: string;\n model?: string;\n}\n\nfunction unwrapInputSchema(\n input: JSONSchemaRef | undefined,\n): Record<string, unknown> {\n if (!input) {\n return { type: \"object\", properties: {} };\n }\n if (\"schema\" in input && input.schema && typeof input.schema === \"object\") {\n return input.schema as Record<string, unknown>;\n }\n if (\"$ref\" in input) {\n return { type: \"object\", properties: {} };\n }\n return input as Record<string, unknown>;\n}\n\n/**\n * Convert non-handler, non-prompt operations from ComponentIR into tool definitions\n * for LLM routing.\n */\nexport function operationsToTools(ir: ComponentIR): OperationToolDef[] {\n return Object.entries(ir.operations)\n .filter(([name, op]) => name !== \"prompt\" && !op.handler)\n .map(([name, op]) => ({\n name,\n description: op.description,\n inputSchema: unwrapInputSchema(op.input),\n }));\n}\n\nfunction buildRouterPrompt(\n componentId: string,\n tools: OperationToolDef[],\n message: string,\n): string {\n const toolDescriptions = tools\n .map((t) => {\n const schema = JSON.stringify(t.inputSchema, null, 2);\n return `### ${t.name}\\n${t.description}\\nInput schema:\\n\\`\\`\\`json\\n${schema}\\n\\`\\`\\``;\n })\n .join(\"\\n\\n\");\n\n return [\n `You are an operation router for the \"${componentId}\" CLI.`,\n `Understand the user request and call the appropriate operation.`,\n `Always select exactly one operation. Extract parameters from the user message.`,\n ``,\n `## Available Operations`,\n ``,\n toolDescriptions,\n ``,\n `## Response Format`,\n ``,\n `Respond with ONLY the following YAML:`,\n ``,\n \"```yaml\",\n `operation: <operation_name>`,\n `input:`,\n ` <key>: <value>`,\n \"```\",\n ``,\n `## User Request`,\n ``,\n message,\n ].join(\"\\n\");\n}\n\n/**\n * Parse the LLM router response to extract selected operation and mapped input.\n */\nexport function parseRouterResponse(\n response: string,\n validNames: string[],\n): { selectedOperation: string; mappedInput: Record<string, unknown> } {\n const yamlMatch = response.match(/```(?:yaml)?\\n([\\s\\S]*?)```/);\n const content = yamlMatch ? yamlMatch[1].trim() : response.trim();\n\n const asMapping = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n let parsed: Record<string, unknown> | undefined;\n try {\n parsed = asMapping(YAML.parse(content));\n } catch {\n // fall through to the JSON attempt below\n }\n if (parsed === undefined) {\n const jsonMatch = response.match(/\\{[\\s\\S]*\"operation\"[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n parsed = asMapping(JSON.parse(jsonMatch[0]));\n } catch {\n // fall through to error below\n }\n }\n }\n\n if (parsed?.operation && typeof parsed.operation === \"string\") {\n if (!validNames.includes(parsed.operation)) {\n throw new Error(\n `Router selected unknown operation \"${parsed.operation}\". Available: ${validNames.join(\", \")}`,\n );\n }\n return {\n selectedOperation: parsed.operation,\n mappedInput: (parsed.input ?? {}) as Record<string, unknown>,\n };\n }\n\n throw new Error(\n `Could not parse operation routing from LLM response. ` +\n `Expected YAML with \"operation\" and \"input\" fields.\\n` +\n `Response:\\n${response.slice(0, 500)}`,\n );\n}\n\n/**\n * Execute a natural language prompt by routing to the appropriate operation.\n */\nexport async function executePrompt(\n message: string,\n ir: ComponentIR,\n binding: RuntimeBinding,\n ctx: AaacInvocationContext,\n opts: PromptExecuteOptions,\n): Promise<PromptResult> {\n const tools = operationsToTools(ir);\n if (tools.length < 2) {\n throw new Error(\n `prompt command requires at least 2 routable operations, found ${tools.length}`,\n );\n }\n\n const prompt = buildRouterPrompt(ir.info.id, tools, message);\n const adapter = await createAdapter(opts.adapter, { model: opts.model });\n const response = await adapter.send(prompt, { readonly: true });\n const { selectedOperation, mappedInput } = parseRouterResponse(\n response,\n tools.map((t) => t.name),\n );\n\n if (opts.dryRun) {\n return {\n selectedOperation,\n mappedInput,\n dryRun: true,\n model: opts.model,\n };\n }\n\n const output = await binding.execute(selectedOperation, {}, mappedInput, ctx);\n return { selectedOperation, mappedInput, output };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,QAAM,SAAS;MACb,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;MACL,KAAK;;AAGP,QAAM,WAAW;AAAjB,QACE,WAAW;AAEb,aAAS,WAAW,KAAK;AACvB,aAAO,OAAO,GAAG;;AAGZ,aAAS,OAAO,KAAuB;AAC5C,eAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,iBAAS,OAAO,UAAU,CAAC,GAAG;AAC5B,cAAI,OAAO,UAAU,eAAe,KAAK,UAAU,CAAC,GAAG,GAAG,GAAG;AAC3D,gBAAI,GAAG,IAAI,UAAU,CAAC,EAAE,GAAG;;;;AAKjC,aAAO;;AAGF,QAAI,WAAW,OAAO,UAAU;;AAKvC,QAAI,aAAa,SAAAA,YAAS,OAAO;AAC/B,aAAO,OAAO,UAAU;;AAI1B,QAAI,WAAW,GAAG,GAAG;AACnB,cAOO,aAPP,aAAa,SAAS,OAAO;AAC3B,eACE,OAAO,UAAU,cACjB,SAAS,KAAK,KAAK,MAAM;;;YAItB,aAAA;AAIF,QAAM,UACX,MAAM,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AA,EACF;AAEA,QAAM,SAAS,MAAM,QAAQ,QAAQ,mBAAmB,CAAC,GAAG,aAAa,GAAG;AAC5E,SAAO,EAAE,mBAAmB,aAAa,OAAO;AAClD;;;AlClLA,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,MAAMA,SAAQ,iBAAiB;AAG9B,IAAM,UAAU,IAAI;","names":["isFunction","options","ret","wrapper","ret","context","options","Handlebars","hb","parse","lexer","parse","compile","join","sourceFile","version","needle","section","i","hb","module","z","z","extractPath","projectHandoffs","contextFor","stepModelFields","context","taskResult","stepUserRequest","existsSync","resolve","absPath","resolve","existsSync","readFile","join","pathSegmentForId","resolveFilePath","mkdir","readFile","unlink","writeFile","join","pathSegmentForId","join","pathSegmentForId","mkdir","readFile","writeFile","unlink","pkg","resolve","resolve","attachMemoryRef","existsSync","resolve","dirname","resolve","existsSync","dirname","resolveAdapter","readFile","readdir","readdir","readFile","z","pathSegmentForId","existsSync","join","resolve","join","existsSync","resolve","pathSegmentForId","pathSegmentForId","Handlebars","pathSegmentForId","pathSegmentForId","GENERATED_MARKER","pathSegmentForId","existsSync","mkdir","readFile","stat","writeFile","dirname","join","resolve","readFileSync","dirname","join","parse","fileURLToPath","dirname","join","parse","dirname","fileURLToPath","parse","readFileSync","join","pkg","c","join","existsSync","readFile","content","resolve","absPath","stat","mkdir","dirname","writeFile","action","YAML","require"]}
|