agent-contracts-runtime 0.36.17 → 0.36.19
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/cli-contract.yaml +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +2 -0
- package/dist/adapters/claude-agent-sdk.js +21 -7
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/mock.js +3 -37
- package/dist/adapters/mock.js.map +1 -1
- package/dist/agent-runtime.bundle.mjs +221 -219
- package/dist/agent-runtime.bundle.mjs.map +4 -4
- package/dist/{bound-resolver-I7WLYGC6.js → bound-resolver-RPJYAOCW.js} +4 -4
- package/dist/{chunk-S7MTKPBF.js → chunk-CFOEW6XJ.js} +4 -25
- package/dist/chunk-CFOEW6XJ.js.map +1 -0
- package/dist/chunk-KB4VDAAQ.js +740 -0
- package/dist/chunk-KB4VDAAQ.js.map +1 -0
- package/dist/chunk-L5OAGF7D.js +42 -0
- package/dist/chunk-L5OAGF7D.js.map +1 -0
- package/dist/{chunk-VKCNOSMQ.js → chunk-UHHKLLA3.js} +68 -57
- package/dist/chunk-UHHKLLA3.js.map +1 -0
- package/dist/cli/index.js +29 -40
- package/dist/cli/index.js.map +1 -1
- package/dist/generator/index.js +2 -2
- package/dist/{guardrail-hooks-CFd3a8tQ.d.ts → guardrail-hooks-BiLI9u9-.d.ts} +12 -6
- package/dist/index.d.ts +12 -5
- package/dist/index.js +10 -12
- package/dist/{task-runner-DJW49UGZ.d.ts → task-runner-Ba4kLv7O.d.ts} +2 -0
- package/docs/cli-reference.md +1 -1
- package/package.json +1 -1
- package/dist/chunk-2E2LWE6C.js +0 -171
- package/dist/chunk-2E2LWE6C.js.map +0 -1
- package/dist/chunk-D2QTXQB2.js +0 -266
- package/dist/chunk-D2QTXQB2.js.map +0 -1
- package/dist/chunk-KKJW4TE5.js +0 -302
- package/dist/chunk-KKJW4TE5.js.map +0 -1
- package/dist/chunk-S7MTKPBF.js.map +0 -1
- package/dist/chunk-VKCNOSMQ.js.map +0 -1
- package/dist/dsl-context-LACANPO4.js +0 -13
- package/dist/dsl-context-LACANPO4.js.map +0 -1
- /package/dist/{bound-resolver-I7WLYGC6.js.map → bound-resolver-RPJYAOCW.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/bound-resolver.ts","../src/generator/template-engine.ts","../src/generator/context.ts","../src/lib/dsl-context.ts","../src/lib/schema-converter.ts"],"sourcesContent":["/**\n * BoundResolver — runtime binding + policy resolution with per-agent isolation.\n *\n * Resolves artifact binding and guardrail/policy in one pass at runtime,\n * producing a per-agent scoped ResolvedComponent. Reuses existing\n * resolveBound(), buildGuardrailContext(), and agent scope resolution.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport YAML from \"yaml\";\nimport { buildGuardrailContext, type GuardrailCheckEntry, type GuardrailContext } from \"../generator/context.js\";\nimport { buildRegistriesFromDsl, buildGuardrailRulesFromDsl } from \"./dsl-context.js\";\nimport type { GuardrailRuleData } from \"./guardrail-hooks.js\";\nimport type { WorkflowRegistries } from \"./workflow-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface ArtifactBindingConfig {\n source: string;\n mappings?: Record<string, string>;\n}\n\nexport interface BoundResolveOptions {\n /** Component identifier — used for cache keying. */\n id: string;\n /** Pre-resolved DSL (e.g. embedded from codegen). */\n embeddedDsl?: Record<string, unknown>;\n /** Path to DSL file — resolved via agent-contracts when no embeddedDsl. */\n dslPath?: string;\n /** Paths to software binding YAML files (guardrail_impl, etc.). */\n bindingPaths?: string[];\n /** Active guardrail policy name from DSL guardrail_policies. */\n activeGuardrailPolicy?: string;\n /** Artifact binding config — resolved via agent-contracts resolveBound(). */\n artifactBinding?: ArtifactBindingConfig;\n /** Path substitutions for artifact binding. */\n paths?: Record<string, string>;\n}\n\nexport interface ResolvedComponent {\n id: string;\n dsl: Record<string, unknown>;\n registries: WorkflowRegistries;\n guardrails: {\n perAgent: Map<string, GuardrailRuleData>;\n };\n diagnostics: Array<{ path?: string; message: string; severity?: string }>;\n}\n\n// ---------------------------------------------------------------------------\n// Guardrail scope helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side\n * bindings ∪ the guardrails attributed to no agent. A guardrail without\n * `scope.agents` that no `agents[].guardrails` references applies to every\n * agent run in-process, as it does on every other route.\n */\nexport function getEffectiveGuardrailIds(\n dsl: Record<string, unknown>,\n agentId: string,\n): Set<string> {\n const ids = new Set<string>();\n\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const agent = agents[agentId];\n if (agent) {\n for (const ref of (agent.guardrails as string[]) ?? []) {\n ids.add(ref);\n }\n }\n\n const referenced = new Set(\n Object.values(agents).flatMap((a) => (a.guardrails as string[] | undefined) ?? []),\n );\n const guardrails = (dsl.guardrails ?? {}) as Record<\n string,\n { scope?: { agents?: string[] } }\n >;\n for (const [guardrailId, guardrail] of Object.entries(guardrails)) {\n const scopedAgents = guardrail.scope?.agents;\n if (scopedAgents ? scopedAgents.includes(agentId) : !referenced.has(guardrailId)) {\n ids.add(guardrailId);\n }\n }\n\n return ids;\n}\n\nfunction guardrailCheckToCommandRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"commandRules\"][number][\"action\"],\n message: c.message,\n };\n}\n\nfunction guardrailCheckToFileRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"fileRules\"][number][\"action\"],\n message: c.message,\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nfunction guardrailCheckToContentRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"contentRules\"][number][\"action\"],\n message: c.message,\n ...(c.file_glob ? { file_glob: c.file_glob } : {}),\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nexport function guardrailContextToRuleData(\n ctx: GuardrailContext,\n effectiveIds?: Set<string>,\n): GuardrailRuleData {\n const filter = (checks: GuardrailCheckEntry[]) =>\n effectiveIds ? checks.filter((c) => effectiveIds.has(c.guardrail_id)) : checks;\n\n return {\n commandRules: filter(ctx.commandChecks).map(guardrailCheckToCommandRule),\n fileRules: filter(ctx.fileChecks).map(guardrailCheckToFileRule),\n contentRules: filter(ctx.contentChecks).map(guardrailCheckToContentRule),\n };\n}\n\nexport function buildPerAgentGuardrails(\n dsl: Record<string, unknown>,\n guardrailCtx: GuardrailContext,\n): Map<string, GuardrailRuleData> {\n const perAgent = new Map<string, GuardrailRuleData>();\n const agents = (dsl.agents ?? {}) as Record<string, unknown>;\n\n for (const agentId of Object.keys(agents)) {\n const effectiveIds = getEffectiveGuardrailIds(dsl, agentId);\n const rules = guardrailContextToRuleData(guardrailCtx, effectiveIds);\n if (\n rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0\n ) {\n perAgent.set(agentId, rules);\n }\n }\n\n return perAgent;\n}\n\nfunction hasGuardrailRules(rules: GuardrailRuleData): boolean {\n return (\n rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// BoundResolver\n// ---------------------------------------------------------------------------\n\nexport class BoundResolver {\n private readonly cache = new Map<string, ResolvedComponent>();\n\n /**\n * Resolve binding + policy in one pass. Results are cached by component id.\n */\n async resolve(opts: BoundResolveOptions): Promise<ResolvedComponent> {\n const cached = this.cache.get(opts.id);\n if (cached) return cached;\n\n const diagnostics: ResolvedComponent[\"diagnostics\"] = [];\n let dsl: Record<string, unknown>;\n\n if (opts.embeddedDsl) {\n dsl = opts.embeddedDsl;\n } else if (opts.dslPath) {\n const { resolve: resolveDsl } = await import(\"agent-contracts\");\n const result = await resolveDsl(opts.dslPath);\n dsl = result.data;\n } else {\n throw new Error(\"BoundResolver.resolve requires embeddedDsl or dslPath\");\n }\n\n // Artifact binding (resolveBound)\n if (opts.artifactBinding) {\n const { resolveBound } = await import(\"agent-contracts\");\n const boundResult = await resolveBound(dsl, {\n artifactBinding: opts.artifactBinding,\n paths: opts.paths,\n });\n dsl = boundResult.data;\n for (const d of boundResult.diagnostics) {\n diagnostics.push({\n path: d.rule,\n message: d.message,\n severity: d.severity,\n });\n }\n }\n\n // Guardrail + policy from bindings\n let guardrailCtx: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (opts.bindingPaths && opts.bindingPaths.length > 0) {\n for (const bindingPath of opts.bindingPaths) {\n const raw = await readFile(bindingPath, \"utf8\");\n const binding = YAML.parse(raw) as Record<string, unknown>;\n guardrailCtx = buildGuardrailContext(\n dsl,\n binding,\n opts.activeGuardrailPolicy,\n );\n }\n }\n\n const perAgent = guardrailCtx.hasGuardrails\n ? buildPerAgentGuardrails(dsl, guardrailCtx)\n : new Map<string, GuardrailRuleData>();\n\n const component: ResolvedComponent = {\n id: opts.id,\n dsl,\n registries: buildRegistriesFromDsl(dsl),\n guardrails: { perAgent },\n diagnostics,\n };\n\n this.cache.set(opts.id, component);\n return component;\n }\n\n /** Clear cached components (e.g. for testing). */\n clearCache(): void {\n this.cache.clear();\n }\n}\n\n/**\n * Get guardrail rules for a specific agent from a ResolvedComponent.\n * Falls back to embedded _guardrailRules when no per-agent rules exist.\n */\nexport function getGuardrailRulesForAgent(\n component: ResolvedComponent,\n agentId: string,\n fallbackDsl?: Record<string, unknown>,\n): GuardrailRuleData | undefined {\n const perAgent = component.guardrails.perAgent.get(agentId);\n if (perAgent && hasGuardrailRules(perAgent)) {\n return perAgent;\n }\n\n return fallbackDsl ? buildGuardrailRulesFromDsl(fallbackDsl) : undefined;\n}\n\n/**\n * Get the guardrail rules for a run whose agent is decided per step (a workflow\n * sharing one adapter): the embedded _guardrailRules `generate` wrote, else the\n * rules of every agent resolved at runtime.\n */\nexport function getGuardrailRulesForComponent(\n component: ResolvedComponent,\n embeddedDsl?: Record<string, unknown>,\n): GuardrailRuleData | undefined {\n const embedded = embeddedDsl ? buildGuardrailRulesFromDsl(embeddedDsl) : undefined;\n if (embedded || component.guardrails.perAgent.size === 0) return embedded;\n const union: GuardrailRuleData = { commandRules: [], fileRules: [], contentRules: [] };\n const seen = new Set<string>();\n for (const rules of component.guardrails.perAgent.values()) {\n for (const kind of [\"commandRules\", \"fileRules\", \"contentRules\"] as const) {\n for (const rule of rules[kind]) {\n const key = `${kind}\\0${rule.guardrail_id}\\0${rule.pattern}`;\n if (seen.has(key)) continue;\n seen.add(key);\n union[kind].push(rule);\n }\n }\n }\n return union;\n}\n","/**\n * Handlebars template engine with custom helpers for TypeScript code generation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport Handlebars from \"handlebars\";\n\nimport { existsSync } from \"node:fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\nfunction findPackageRoot(): string {\n let dir = __dirname;\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n dir = resolve(dir, \"..\");\n }\n return resolve(__dirname, \"..\");\n}\n\nconst BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), \"templates\");\n\nfunction toCamelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction toPascalCase(str: string): string {\n const camel = toCamelCase(str);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nconst hbs = Handlebars.create();\n\nhbs.registerHelper(\"camelCase\", (str: string) => toCamelCase(str));\nhbs.registerHelper(\"PascalCase\", (str: string) => toPascalCase(str));\n\nhbs.registerHelper(\"eq\", (a: unknown, b: unknown) => a === b);\nhbs.registerHelper(\"notEmpty\", (arr: unknown) =>\n Array.isArray(arr) ? arr.length > 0 : !!arr,\n);\n\nhbs.registerHelper(\"json\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value, null, 2)),\n);\n\n/**\n * Specifier for importing a sibling generated module: `agents.ts` → `./agents.js`.\n *\n * A relative ES-module import names the emitted `.js` file. `node16`/`nodenext` module\n * resolution rejects a specifier without the extension (TS2835); `bundler` resolution, tsx\n * and Vite resolve the `.js` specifier to the `.ts` source, so this one form compiles and\n * loads in every consumer setup.\n */\nhbs.registerHelper(\"relativeImport\", (fileName: string) => {\n if (typeof fileName !== \"string\" || !fileName.endsWith(\".ts\")) {\n throw new Error(`relativeImport expects a generated .ts file name, got ${JSON.stringify(fileName)}`);\n }\n return `./${fileName.slice(0, -\".ts\".length)}.js`;\n});\n\nhbs.registerHelper(\"hasDependsOn\", (step: Record<string, unknown>) =>\n \"depends_on\" in step && Array.isArray(step.depends_on),\n);\n\nhbs.registerHelper(\"jsonInline\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value)),\n);\n\nhbs.registerHelper(\"indent\", (text: string, spaces: number) => {\n if (typeof text !== \"string\") return text;\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map((line, i) => (i === 0 ? line : pad + line))\n .join(\"\\n\");\n});\n\n/** Escape a JSON Schema pattern for safe inclusion in a JS regex literal (/.../). */\nfunction escapeRegexPatternForSource(pattern: string): string {\n return pattern.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\//g, \"\\\\/\");\n}\n\nfunction appendStringValidations(base: string, schema: Record<string, unknown>): string {\n let result = base;\n if (schema.minLength !== undefined) result += `.min(${schema.minLength})`;\n if (schema.maxLength !== undefined) result += `.max(${schema.maxLength})`;\n if (schema.pattern !== undefined) {\n const escaped = escapeRegexPatternForSource(schema.pattern as string);\n result += `.regex(/${escaped}/)`;\n }\n return result;\n}\n\nfunction appendNumberValidations(\n base: string,\n schema: Record<string, unknown>,\n isInteger: boolean,\n): string {\n let result = base;\n if (isInteger) result += \".int()\";\n if (schema.minimum !== undefined) result += `.min(${schema.minimum})`;\n if (schema.maximum !== undefined) result += `.max(${schema.maximum})`;\n return result;\n}\n\nfunction appendArrayValidations(base: string, schema: Record<string, unknown>): string {\n let result = base;\n if (schema.minItems !== undefined) result += `.min(${schema.minItems})`;\n if (schema.maxItems !== undefined) result += `.max(${schema.maxItems})`;\n return result;\n}\n\nhbs.registerHelper(\"zodType\", function zodType(schema: Record<string, unknown>): string {\n if (!schema || typeof schema !== \"object\") return \"z.unknown()\";\n\n if (schema.enum) {\n const vals = (schema.enum as string[]).map((v) => `\"${v}\"`).join(\", \");\n return `z.enum([${vals}])`;\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})`;\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return appendStringValidations(\"z.string()\", schema);\n if (type === \"integer\") return appendNumberValidations(\"z.number()\", schema, true);\n if (type === \"number\") return appendNumberValidations(\"z.number()\", schema, false);\n if (type === \"boolean\") return \"z.boolean()\";\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? zodType(items) : \"z.unknown()\";\n return appendArrayValidations(`z.array(${inner})`, schema);\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return \"z.record(z.string(), z.unknown())\";\n\n const required = (schema.required as string[]) ?? [];\n const fields = Object.entries(props)\n .map(([key, val]) => {\n const base = zodType(val);\n const opt = required.includes(key) ? \"\" : \".optional()\";\n const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `\"${key}\"`;\n return ` ${safeKey}: ${base}${opt},`;\n })\n .join(\"\\n\");\n return `z.object({\\n${fields}\\n})`;\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(zodType);\n if (parts.length === 1) return parts[0];\n return parts.reduce((acc, part) => `${acc}.extend(${part}.shape)`);\n }\n\n return \"z.unknown()\";\n});\n\nhbs.registerHelper(\"regexEscape\", (str: string) => {\n if (typeof str !== \"string\") return str;\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n});\n\nhbs.registerHelper(\"stringArray\", (arr: unknown) => {\n if (!Array.isArray(arr)) return \"[]\";\n return \"[\" + arr.map((s) => `\"${s}\"`).join(\", \") + \"]\";\n});\n\n/**\n * Load a template by name, with custom dir override fallback to built-in.\n */\nasync function loadTemplate(\n name: string,\n customDir?: string,\n): Promise<string> {\n if (customDir) {\n try {\n return await readFile(join(customDir, name), \"utf8\");\n } catch {\n // fallback to built-in\n }\n }\n return readFile(join(BUILTIN_TEMPLATES_DIR, name), \"utf8\");\n}\n\nexport async function renderTemplate(\n name: string,\n context: Record<string, unknown>,\n customDir?: string,\n): Promise<string> {\n const source = await loadTemplate(name, customDir);\n const compiled = hbs.compile(source, { noEscape: true });\n return compiled(context);\n}\n\nexport { hbs, toCamelCase, toPascalCase };\n","/**\n * Build template contexts from resolved DSL data\n */\n\nimport { toCamelCase, toPascalCase } from \"./template-engine.js\";\n\nexport interface AgentEntry {\n id: string;\n varName: string;\n role_name: string;\n purpose: string;\n mode: string;\n dispatch_only: boolean;\n can_read_artifacts: string[];\n can_write_artifacts: string[];\n can_execute_tools: string[];\n can_invoke_agents: string[];\n can_return_handoffs: string[];\n responsibilities: string[];\n constraints: string[];\n rules: Array<{ id: string; description: string; severity: string }>;\n escalation_criteria: Array<{ condition: string; action: string }>;\n}\n\nexport interface TaskEntry {\n id: string;\n varName: string;\n description: string;\n target_agent: string;\n allowed_from_agents: string[];\n workflow: string;\n invocation_handoff: string;\n result_handoff: string;\n input_artifacts: string[];\n responsibilities: string[];\n completion_criteria: string[];\n optional: boolean;\n model_class?: string;\n}\n\nexport interface WorkflowStepEntry {\n type: string;\n task?: string;\n from_agent?: string;\n description?: string;\n optional?: boolean;\n max_retries?: number;\n max_follow_ups?: number;\n depends_on?: string[];\n gate_kind?: string;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n}\n\nexport interface WorkflowEntry {\n id: string;\n varName: string;\n description: string;\n trigger: string;\n entry_conditions: string[];\n steps: WorkflowStepEntry[];\n}\n\nexport interface HandoffEntry {\n id: string;\n varName: string;\n pascalName: string;\n schemaName: string;\n description: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ContractContext {\n agentEntries: AgentEntry[];\n taskEntries: TaskEntry[];\n workflowEntries: WorkflowEntry[];\n handoffEntries: HandoffEntry[];\n}\n\n/**\n * Determine if a task is optional by checking if any workflow step referencing it is optional.\n */\nfunction isTaskOptional(\n taskId: string,\n workflows: Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n): boolean {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId && step.optional) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Compute max_retries from workflow step or fallback to 0.\n */\nfunction getMaxRetries(\n taskId: string,\n workflows: Record<string, { steps: Array<Record<string, unknown>> }>,\n): number {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId) {\n const retry = step.retry as { condition: string } | undefined;\n return retry ? 1 : 0;\n }\n }\n }\n return 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function buildContractContext(dsl: any): ContractContext {\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const tasks = (dsl.tasks ?? {}) as Record<string, Record<string, unknown>>;\n const workflows = (dsl.workflow ?? {}) as Record<string, Record<string, unknown>>;\n const handoffTypes = (dsl.handoff_types ?? {}) as Record<string, Record<string, unknown>>;\n\n const agentEntries: AgentEntry[] = Object.entries(agents).map(([id, agent]) => ({\n id,\n varName: toCamelCase(id),\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode: (agent.mode as string) ?? \"read-write\",\n dispatch_only: (agent.dispatch_only as boolean) ?? false,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_execute_tools: (agent.can_execute_tools as string[]) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as AgentEntry[\"rules\"]) ?? [],\n escalation_criteria: (agent.escalation_criteria as AgentEntry[\"escalation_criteria\"]) ?? [],\n }));\n\n const taskEntries: TaskEntry[] = Object.entries(tasks).map(([id, task]) => ({\n id,\n varName: toCamelCase(id),\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n allowed_from_agents: (task.allowed_from_agents as string[]) ?? [],\n workflow: (task.workflow as string) ?? \"\",\n invocation_handoff: (task.invocation_handoff as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n input_artifacts: (task.input_artifacts as string[]) ?? [],\n responsibilities: (task.responsibilities as string[]) ?? [],\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n optional: isTaskOptional(id, workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>),\n ...(task.model_class ? { model_class: task.model_class as string } : {}),\n }));\n\n const workflowEntries: WorkflowEntry[] = Object.entries(workflows).map(\n ([id, wf]) => {\n const steps = ((wf.steps as Array<Record<string, unknown>>) ?? []).map((step) => {\n const entry: WorkflowStepEntry = { type: step.type as string };\n if (step.type === \"delegate\") {\n entry.task = step.task as string;\n entry.from_agent = step.from_agent as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n const wfStep = step as Record<string, unknown>;\n entry.optional = isTaskOptional(\n step.task as string,\n workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n );\n entry.max_retries = (wfStep.max_retries as number | undefined) ?? (wfStep.retry ? 1 : 0);\n entry.max_follow_ups = wfStep.max_follow_ups as number | undefined;\n if (wfStep.depends_on !== undefined) {\n entry.depends_on = wfStep.depends_on as string[];\n }\n if (wfStep.retry) {\n const r = wfStep.retry as Record<string, unknown>;\n entry.retry = {\n condition: r.condition as string,\n fix_task: r.fix_task as string,\n revalidate_task: r.revalidate_task as string | undefined,\n };\n }\n } else if (step.type === \"gate\") {\n entry.gate_kind = step.gate_kind as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n if (step.depends_on !== undefined) {\n entry.depends_on = step.depends_on as string[];\n }\n }\n return entry;\n });\n\n return {\n id,\n varName: toCamelCase(id),\n description: (wf.description as string) ?? \"\",\n trigger: (wf.trigger as string) ?? \"\",\n entry_conditions: (wf.entry_conditions as string[]) ?? [],\n steps,\n };\n },\n );\n\n const handoffEntries: HandoffEntry[] = Object.entries(handoffTypes).map(\n ([id, ht]) => ({\n id,\n varName: toCamelCase(id),\n pascalName: toPascalCase(id),\n schemaName: toPascalCase(id) + \"Schema\",\n description: (ht.description as string) ?? \"\",\n schema: (ht.schema as Record<string, unknown>) ?? {},\n }),\n );\n\n return { agentEntries, taskEntries, workflowEntries, handoffEntries };\n}\n\nexport interface GuardrailCheckEntry {\n guardrail_id: string;\n description: string;\n severity: string;\n action: string;\n matcher_type: string;\n pattern: string;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailContext {\n commandChecks: GuardrailCheckEntry[];\n fileChecks: GuardrailCheckEntry[];\n contentChecks: GuardrailCheckEntry[];\n allChecks: GuardrailCheckEntry[];\n hasGuardrails: boolean;\n}\n\n/**\n * Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.\n * Mirrors the agent-contracts resolveChecks pattern.\n */\nexport function buildGuardrailContext(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dsl: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n binding: any,\n policyName?: string,\n): GuardrailContext {\n const empty: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (!binding?.guardrail_impl) return empty;\n\n const guardrails = dsl.guardrails ?? {};\n const policies = dsl.guardrail_policies ?? {};\n const policy = policyName ? policies[policyName] : undefined;\n\n const allChecks: GuardrailCheckEntry[] = [];\n\n for (const [guardrailId, impl] of Object.entries(\n binding.guardrail_impl as Record<string, { checks: Array<Record<string, unknown>> }>,\n )) {\n const guardrail = guardrails[guardrailId] as Record<string, unknown> | undefined;\n const description = (guardrail?.description as string) ?? guardrailId;\n\n const policyRule = policy?.rules?.find(\n (r: Record<string, unknown>) => r.guardrail === guardrailId,\n );\n const severity = (policyRule?.severity as string) ?? \"warning\";\n const action = (policyRule?.action as string) ?? \"warn\";\n\n for (const check of impl.checks) {\n const matcher = check.matcher as Record<string, unknown> | undefined;\n if (!matcher) continue;\n\n allChecks.push({\n guardrail_id: guardrailId,\n description,\n severity,\n action,\n matcher_type: matcher.type as string,\n pattern: matcher.pattern as string,\n message: (check.message as string) ?? description,\n file_glob: matcher.file_glob as string | undefined,\n exclude_glob: matcher.exclude_glob as string | undefined,\n });\n }\n }\n\n return {\n commandChecks: allChecks.filter((c) => c.matcher_type === \"command_regex\"),\n fileChecks: allChecks.filter((c) => c.matcher_type === \"file_glob\"),\n contentChecks: allChecks.filter((c) => c.matcher_type === \"content_regex\"),\n allChecks,\n hasGuardrails: allChecks.length > 0,\n };\n}\n","/**\n * Runtime DSL Context — builds WorkflowRegistries from embedded DSL data,\n * optionally merging with project-level DSL extensions.\n *\n * Default flow:\n * CLI binary embeds resolved DSL data (from code generation) →\n * loadDslContext() builds registries from it.\n *\n * Extended flow:\n * Project provides a DSL that extends/overrides the embedded base →\n * loadDslContext() merges via agent-contracts' mergeDsl() →\n * builds registries from the merged result.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\nimport type { WorkflowRegistries, WorkflowContractLike, WorkflowStep } from \"./workflow-runner.js\";\nimport type { AgentContractLike, TaskContractLike } from \"./task-runner.js\";\nimport { jsonSchemaToZod } from \"./schema-converter.js\";\nimport type { GuardrailRule, GuardrailRuleData } from \"./guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface LoadDslOptions {\n /**\n * Pre-resolved DSL data embedded in the CLI binary.\n * Produced by the code generator alongside TypeScript contracts.\n * This is the default DSL — used as-is when no project extension exists.\n */\n embeddedDsl: Record<string, unknown>;\n\n /**\n * Path to a project-level DSL file that extends/overrides the embedded DSL.\n * When provided, the project DSL is resolved (including its own extends chain)\n * and merged with embeddedDsl via mergeDsl().\n */\n projectDslPath?: string;\n\n /** Entities the CLI depends on — validated after merge. */\n requiredEntities?: RequiredEntities;\n}\n\nexport interface RequiredEntities {\n workflows?: string[];\n tasks?: string[];\n}\n\nexport interface DslContext {\n readonly registries: WorkflowRegistries;\n readonly dsl: Record<string, unknown>;\n readonly guardrailRules?: GuardrailRuleData;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class DslValidationError extends Error {\n readonly missing: string[];\n constructor(missing: string[]) {\n super(\n \"Required entities missing after DSL merge:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\"),\n );\n this.name = \"DslValidationError\";\n this.missing = missing;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build registries from resolved DSL\n// ---------------------------------------------------------------------------\n\nfunction buildAgentRegistry(\n agents: Record<string, Record<string, unknown>>,\n): Record<string, AgentContractLike> {\n const registry: Record<string, AgentContractLike> = {};\n for (const [id, agent] of Object.entries(agents)) {\n const rawMode = (agent.mode as string) ?? \"read-only\";\n const mode: \"read-write\" | \"read-only\" = rawMode === \"read-write\" ? \"read-write\" : \"read-only\";\n registry[id] = {\n id,\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode,\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as Array<{ id: string; description: string; severity: string }>) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? undefined,\n can_execute_tools: (agent.can_execute_tools as string[]) ?? undefined,\n };\n }\n return registry;\n}\n\nfunction buildTaskRegistry(\n tasks: Record<string, Record<string, unknown>>,\n): Record<string, TaskContractLike> {\n const registry: Record<string, TaskContractLike> = {};\n for (const [id, task] of Object.entries(tasks)) {\n registry[id] = {\n id,\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n model_class: task.model_class as \"fast\" | \"standard\" | \"thinking\" | undefined,\n };\n }\n return registry;\n}\n\nfunction buildWorkflowStep(step: Record<string, unknown>): WorkflowStep {\n if (step.type === \"gate\") {\n return {\n type: \"gate\" as const,\n gate_kind: (step.gate_kind as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n return {\n type: \"delegate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n optional: (step.optional as boolean) ?? false,\n max_retries: (step.max_retries as number) ?? 0,\n max_follow_ups: step.max_follow_ups as number | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n retry: step.retry as { condition: string; fix_task: string; revalidate_task?: string } | undefined,\n };\n}\n\nfunction buildWorkflowRegistry(\n workflows: Record<string, Record<string, unknown>>,\n): Record<string, WorkflowContractLike> {\n const registry: Record<string, WorkflowContractLike> = {};\n for (const [id, wf] of Object.entries(workflows)) {\n const steps = ((wf.steps as Record<string, unknown>[]) ?? []).map(buildWorkflowStep);\n registry[id] = { id, description: (wf.description as string) ?? \"\", steps };\n }\n return registry;\n}\n\nfunction buildHandoffSchemas(\n handoffTypes: Record<string, Record<string, unknown>>,\n): Record<string, z.ZodType> {\n const schemas: Record<string, z.ZodType> = {};\n for (const [id, ht] of Object.entries(handoffTypes)) {\n const schema = ht.schema as Record<string, unknown> | undefined;\n if (schema) {\n schemas[id] = jsonSchemaToZod(schema);\n }\n }\n return schemas;\n}\n\n// ---------------------------------------------------------------------------\n// Build registries from a resolved DSL object\n// ---------------------------------------------------------------------------\n\nexport function buildGuardrailRulesFromDsl(\n dsl: Record<string, unknown>,\n): GuardrailRuleData | undefined {\n const raw = dsl._guardrailRules as Record<string, unknown> | undefined;\n if (!raw) return undefined;\n return {\n commandRules: (raw.commandRules as GuardrailRule[]) ?? [],\n fileRules: (raw.fileRules as GuardrailRule[]) ?? [],\n contentRules: (raw.contentRules as GuardrailRule[]) ?? [],\n };\n}\n\nexport function buildRegistriesFromDsl(\n dsl: Record<string, unknown>,\n): WorkflowRegistries {\n const agents = (dsl.agents as Record<string, Record<string, unknown>>) ?? {};\n const tasks = (dsl.tasks as Record<string, Record<string, unknown>>) ?? {};\n const workflows = (dsl.workflow as Record<string, Record<string, unknown>>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, Record<string, unknown>>) ?? {};\n\n return {\n agentRegistry: buildAgentRegistry(agents),\n taskRegistry: buildTaskRegistry(tasks),\n workflowRegistry: buildWorkflowRegistry(workflows),\n handoffSchemas: buildHandoffSchemas(handoffTypes),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nfunction validateRequiredEntities(\n dsl: Record<string, unknown>,\n required: RequiredEntities,\n): void {\n const missing: string[] = [];\n\n const workflows = (dsl.workflow as Record<string, unknown>) ?? {};\n const tasks = (dsl.tasks as Record<string, unknown>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, unknown>) ?? {};\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) {\n missing.push(`workflow \"${wfId}\" is required by the CLI but not found in the resolved DSL`);\n }\n }\n }\n\n if (required.tasks) {\n for (const taskId of required.tasks) {\n if (!(taskId in tasks)) {\n missing.push(`task \"${taskId}\" is required by the CLI but not found in the resolved DSL`);\n continue;\n }\n const task = tasks[taskId] as Record<string, unknown>;\n const invHandoff = task.invocation_handoff as string | undefined;\n const resHandoff = task.result_handoff as string | undefined;\n if (invHandoff && !(invHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${invHandoff}\" (invocation_handoff of task \"${taskId}\") not found`);\n }\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result_handoff of task \"${taskId}\") not found`);\n }\n }\n }\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) continue;\n const wf = workflows[wfId] as Record<string, unknown>;\n const steps = (wf.steps as Array<Record<string, unknown>>) ?? [];\n for (const step of steps) {\n if (step.type !== \"delegate\") continue;\n const taskId = step.task as string;\n if (taskId && taskId in tasks) {\n const task = tasks[taskId] as Record<string, unknown>;\n const resHandoff = task.result_handoff as string | undefined;\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result of task \"${taskId}\" in workflow \"${wfId}\") not found`);\n }\n }\n }\n }\n }\n\n if (missing.length > 0) {\n throw new DslValidationError(missing);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main API\n// ---------------------------------------------------------------------------\n\n/**\n * Build a DslContext from embedded DSL data, optionally merging with\n * a project-level DSL extension.\n *\n * Default (no projectDslPath):\n * Builds registries directly from embeddedDsl — no filesystem access.\n *\n * Extended (with projectDslPath):\n * Resolves the project DSL from filesystem, merges it over embeddedDsl\n * via agent-contracts' mergeDsl(), then builds registries from the result.\n */\nexport async function loadDslContext(\n options: LoadDslOptions,\n): Promise<DslContext> {\n let dsl: Record<string, unknown>;\n\n if (options.projectDslPath) {\n const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import(\"agent-contracts\");\n const raw = await readFile(options.projectDslPath, \"utf8\");\n const projectData = YAML.parse(raw) as Record<string, unknown>;\n\n if (projectData.extends === \"/$embedded/\") {\n const { extends: _extends, ...projectOverrides } = projectData;\n const merged = mergeDsl(options.embeddedDsl, projectOverrides);\n dsl = expandDefaults(merged);\n } else {\n const projectResult = await resolveDsl(options.projectDslPath);\n const merged = mergeDsl(options.embeddedDsl, projectResult.data);\n dsl = expandDefaults(merged);\n }\n } else {\n dsl = options.embeddedDsl;\n }\n\n if (options.requiredEntities) {\n validateRequiredEntities(dsl, options.requiredEntities);\n }\n\n const registries = buildRegistriesFromDsl(dsl);\n const guardrailRules = buildGuardrailRulesFromDsl(dsl);\n\n return { registries, dsl, guardrailRules };\n}\n","/**\n * Runtime JSON Schema → Zod converter.\n *\n * Mirrors the compile-time zodType Handlebars helper in\n * generator/template-engine.ts but produces live z.ZodType\n * objects instead of code strings.\n */\n\nimport { z } from \"zod\";\n\nfunction applyStringValidations(schema: z.ZodString, def: Record<string, unknown>): z.ZodType {\n let s: z.ZodString = schema;\n if (typeof def.minLength === \"number\") s = s.min(def.minLength);\n if (typeof def.maxLength === \"number\") s = s.max(def.maxLength);\n if (typeof def.pattern === \"string\") s = s.regex(new RegExp(def.pattern));\n return s;\n}\n\nfunction applyNumberValidations(schema: z.ZodNumber, def: Record<string, unknown>, isInteger: boolean): z.ZodType {\n let n: z.ZodNumber = schema;\n if (isInteger) n = n.int();\n if (typeof def.minimum === \"number\") n = n.min(def.minimum);\n if (typeof def.maximum === \"number\") n = n.max(def.maximum);\n return n;\n}\n\nfunction applyArrayValidations(schema: z.ZodArray<z.ZodType>, def: Record<string, unknown>): z.ZodType {\n let a: z.ZodArray<z.ZodType> = schema;\n if (typeof def.minItems === \"number\") a = a.min(def.minItems);\n if (typeof def.maxItems === \"number\") a = a.max(def.maxItems);\n return a;\n}\n\n/**\n * Convert a JSON Schema definition to a Zod schema object at runtime.\n *\n * Supports the same subset as the compile-time zodType helper:\n * object, array, string, number, integer, boolean, enum, const, allOf.\n */\nexport function jsonSchemaToZod(schema: Record<string, unknown>): z.ZodType {\n if (!schema || typeof schema !== \"object\") return z.unknown();\n\n if (schema.enum) {\n const vals = schema.enum as [string, ...string[]];\n if (vals.length === 0) return z.unknown();\n return z.enum(vals);\n }\n\n if (schema.const !== undefined) {\n const val = schema.const;\n if (typeof val === \"string\" || typeof val === \"number\" || typeof val === \"boolean\") {\n return z.literal(val);\n }\n return z.unknown();\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return applyStringValidations(z.string(), schema);\n if (type === \"integer\") return applyNumberValidations(z.number(), schema, true);\n if (type === \"number\") return applyNumberValidations(z.number(), schema, false);\n if (type === \"boolean\") return z.boolean();\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? jsonSchemaToZod(items) : z.unknown();\n return applyArrayValidations(z.array(inner), schema);\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return z.record(z.string(), z.unknown());\n\n const required = new Set((schema.required as string[]) ?? []);\n const shape: Record<string, z.ZodType> = {};\n for (const [key, val] of Object.entries(props)) {\n const fieldSchema = jsonSchemaToZod(val);\n shape[key] = required.has(key) ? fieldSchema : fieldSchema.optional();\n }\n return z.object(shape).passthrough();\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(jsonSchemaToZod);\n if (parts.length === 0) return z.unknown();\n if (parts.length === 1) return parts[0];\n let merged = parts[0];\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (merged instanceof z.ZodObject && part instanceof z.ZodObject) {\n merged = merged.merge(part);\n }\n }\n return merged;\n }\n\n return z.unknown();\n}\n"],"mappings":";AAQA,SAAS,YAAAA,iBAAgB;AACzB,OAAOC,WAAU;;;ACLjB,SAAS,gBAAgB;AACzB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,OAAO,gBAAgB;AAEvB,SAAS,kBAAkB;AAE3B,IAAM,YAAY,cAAc,IAAI,IAAI,KAAK,YAAY,GAAG,CAAC;AAE7D,SAAS,kBAA0B;AACjC,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,WAAW,KAAK,KAAK,cAAc,CAAC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3C,WAAO;AAAA,EACT;AAEA,SAAO,cAAc,2BAA2B,WAAW,IAAI;AACjE;AAOO,SAAS,8BACd,WACA,aAC+B;AAC/B,QAAM,WAAW,cAAc,2BAA2B,WAAW,IAAI;AACzE,MAAI,YAAY,UAAU,WAAW,SAAS,SAAS,EAAG,QAAO;AACjE,QAAM,QAA2B,EAAE,cAAc,CAAC,GAAG,WAAW,CAAC,GAAG,cAAc,CAAC,EAAE;AACrF,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,UAAU,WAAW,SAAS,OAAO,GAAG;AAC1D,eAAW,QAAQ,CAAC,gBAAgB,aAAa,cAAc,GAAY;AACzE,iBAAW,QAAQ,MAAM,IAAI,GAAG;AAC9B,cAAM,MAAM,GAAG,IAAI,KAAK,KAAK,YAAY,KAAK,KAAK,OAAO;AAC1D,YAAI,KAAK,IAAI,GAAG,EAAG;AACnB,aAAK,IAAI,GAAG;AACZ,cAAM,IAAI,EAAE,KAAK,IAAI;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":["readFile","YAML","readFile","readFile","readFile","YAML"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/adapters/mock.ts
|
|
2
|
+
var MockAdapter = class {
|
|
3
|
+
responses;
|
|
4
|
+
defaultLatencyMs;
|
|
5
|
+
lastMemoryRef = null;
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.responses = options?.responses ?? {};
|
|
8
|
+
this.defaultLatencyMs = options?.defaultLatencyMs ?? 0;
|
|
9
|
+
}
|
|
10
|
+
async send(prompt, _options) {
|
|
11
|
+
const match = prompt.match(/## Task: (\S+)/);
|
|
12
|
+
const taskId = match?.[1] ?? "unknown";
|
|
13
|
+
const reqMatch = prompt.match(/## User Request\n\n([\s\S]*?)(?:\n\n---|$)/);
|
|
14
|
+
const userRequest = reqMatch?.[1]?.trim() ?? "";
|
|
15
|
+
if (this.defaultLatencyMs > 0) {
|
|
16
|
+
await new Promise((r) => setTimeout(r, this.defaultLatencyMs));
|
|
17
|
+
}
|
|
18
|
+
const responseFn = this.responses[taskId];
|
|
19
|
+
if (!responseFn) {
|
|
20
|
+
return `Task "${taskId}" completed but no structured output available.`;
|
|
21
|
+
}
|
|
22
|
+
const result = responseFn(userRequest);
|
|
23
|
+
this.lastMemoryRef = {
|
|
24
|
+
id: `mock-ref-${Date.now()}`,
|
|
25
|
+
provider: "mock",
|
|
26
|
+
compat: "mock@1",
|
|
27
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
28
|
+
};
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
getLastMemoryRef() {
|
|
32
|
+
return this.lastMemoryRef;
|
|
33
|
+
}
|
|
34
|
+
isCompatible(compat) {
|
|
35
|
+
return compat.startsWith("mock@");
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
MockAdapter
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=chunk-L5OAGF7D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/mock.ts"],"sourcesContent":["/**\n * Mock SDK Adapter — for testing and demo purposes\n */\n\nimport type { SdkAdapter } from \"../lib/task-runner.js\";\nimport type { MemoryRef } from \"../lib/memory-store.js\";\n\nexport class MockAdapter implements SdkAdapter {\n private responses: Record<string, (userRequest: string) => string>;\n private defaultLatencyMs: number;\n private lastMemoryRef: MemoryRef | null = null;\n\n constructor(options?: {\n responses?: Record<string, (userRequest: string) => string>;\n defaultLatencyMs?: number;\n }) {\n this.responses = options?.responses ?? {};\n this.defaultLatencyMs = options?.defaultLatencyMs ?? 0;\n }\n\n async send(prompt: string, _options: import(\"../lib/task-runner.js\").AdapterSendOptions): Promise<string> {\n const match = prompt.match(/## Task: (\\S+)/);\n const taskId = match?.[1] ?? \"unknown\";\n\n const reqMatch = prompt.match(/## User Request\\n\\n([\\s\\S]*?)(?:\\n\\n---|$)/);\n const userRequest = reqMatch?.[1]?.trim() ?? \"\";\n\n if (this.defaultLatencyMs > 0) {\n await new Promise((r) => setTimeout(r, this.defaultLatencyMs));\n }\n\n const responseFn = this.responses[taskId];\n if (!responseFn) {\n return `Task \"${taskId}\" completed but no structured output available.`;\n }\n\n const result = responseFn(userRequest);\n this.lastMemoryRef = {\n id: `mock-ref-${Date.now()}`,\n provider: \"mock\",\n compat: \"mock@1\",\n created_at: new Date().toISOString(),\n };\n return result;\n }\n\n getLastMemoryRef(): MemoryRef | null {\n return this.lastMemoryRef;\n }\n\n isCompatible(compat: string): boolean {\n return compat.startsWith(\"mock@\");\n }\n}\n"],"mappings":";AAOO,IAAM,cAAN,MAAwC;AAAA,EACrC;AAAA,EACA;AAAA,EACA,gBAAkC;AAAA,EAE1C,YAAY,SAGT;AACD,SAAK,YAAY,SAAS,aAAa,CAAC;AACxC,SAAK,mBAAmB,SAAS,oBAAoB;AAAA,EACvD;AAAA,EAEA,MAAM,KAAK,QAAgB,UAA+E;AACxG,UAAM,QAAQ,OAAO,MAAM,gBAAgB;AAC3C,UAAM,SAAS,QAAQ,CAAC,KAAK;AAE7B,UAAM,WAAW,OAAO,MAAM,4CAA4C;AAC1E,UAAM,cAAc,WAAW,CAAC,GAAG,KAAK,KAAK;AAE7C,QAAI,KAAK,mBAAmB,GAAG;AAC7B,YAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,KAAK,gBAAgB,CAAC;AAAA,IAC/D;AAEA,UAAM,aAAa,KAAK,UAAU,MAAM;AACxC,QAAI,CAAC,YAAY;AACf,aAAO,SAAS,MAAM;AAAA,IACxB;AAEA,UAAM,SAAS,WAAW,WAAW;AACrC,SAAK,gBAAgB;AAAA,MACnB,IAAI,YAAY,KAAK,IAAI,CAAC;AAAA,MAC1B,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,IACrC;AACA,WAAO;AAAA,EACT;AAAA,EAEA,mBAAqC;AACnC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,aAAa,QAAyB;AACpC,WAAO,OAAO,WAAW,OAAO;AAAA,EAClC;AACF;","names":[]}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "./chunk-2E2LWE6C.js";
|
|
2
|
+
MockAdapter
|
|
3
|
+
} from "./chunk-L5OAGF7D.js";
|
|
5
4
|
import {
|
|
5
|
+
BoundResolver,
|
|
6
6
|
buildGuardrailRulesFromDsl,
|
|
7
|
+
getGuardrailRulesForAgent,
|
|
8
|
+
getGuardrailRulesForComponent,
|
|
7
9
|
loadDslContext
|
|
8
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-KB4VDAAQ.js";
|
|
9
11
|
|
|
10
12
|
// src/lib/task-runner.ts
|
|
11
13
|
import { z } from "zod";
|
|
@@ -270,11 +272,11 @@ function collectFieldTables(schema, pathPrefix, tables) {
|
|
|
270
272
|
|
|
271
273
|
` : "";
|
|
272
274
|
const header = "| Field | Type | Required | Constraints | Description |";
|
|
273
|
-
const
|
|
275
|
+
const sep2 = "|-------|------|----------|-------------|-------------|";
|
|
274
276
|
const rows = fields.map(
|
|
275
277
|
(f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
|
|
276
278
|
);
|
|
277
|
-
tables.push(`${title}${[header,
|
|
279
|
+
tables.push(`${title}${[header, sep2, ...rows].join("\n")}`);
|
|
278
280
|
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
279
281
|
if (!shape) return;
|
|
280
282
|
for (const f of fields) {
|
|
@@ -624,7 +626,7 @@ async function runTask(adapter, taskId, context, options) {
|
|
|
624
626
|
splitPrompt = void 0;
|
|
625
627
|
prompt = enhancedPrompt;
|
|
626
628
|
}
|
|
627
|
-
const isReadonly = agentContract.mode === "read-only";
|
|
629
|
+
const isReadonly = agentContract.mode === "read-only" || options?.readonly === true;
|
|
628
630
|
const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
|
|
629
631
|
const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
|
|
630
632
|
entryAgentId: agentContract.id,
|
|
@@ -764,6 +766,8 @@ function resolveInvocation(invocation) {
|
|
|
764
766
|
user_request: userRequest,
|
|
765
767
|
maxFollowUps: invocation.runtime?.maxFollowUps,
|
|
766
768
|
maxRetries: invocation.runtime?.maxRetries,
|
|
769
|
+
readonly: invocation.runtime?.readonly,
|
|
770
|
+
dryRun: invocation.runtime?.dryRun,
|
|
767
771
|
variables: Object.keys(variables).length > 0 ? variables : void 0,
|
|
768
772
|
onGate: invocation.hooks?.onGate,
|
|
769
773
|
onStepComplete: invocation.hooks?.onStepComplete,
|
|
@@ -773,7 +777,6 @@ function resolveInvocation(invocation) {
|
|
|
773
777
|
};
|
|
774
778
|
}
|
|
775
779
|
async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRegistries, maybeRegistries) {
|
|
776
|
-
const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(adapterOrFactory);
|
|
777
780
|
let workflowId;
|
|
778
781
|
let options;
|
|
779
782
|
let registries;
|
|
@@ -789,6 +792,9 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
|
|
|
789
792
|
registries = optionsOrRegistries;
|
|
790
793
|
invocationHandoff = workflowIdOrInvocation.handoff;
|
|
791
794
|
}
|
|
795
|
+
const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(
|
|
796
|
+
options.dryRun ? new MockAdapter() : adapterOrFactory
|
|
797
|
+
);
|
|
792
798
|
if (invocationHandoff && registries?.handoffSchemas) {
|
|
793
799
|
const inputSchema = registries.handoffSchemas[invocationHandoff.type];
|
|
794
800
|
if (inputSchema) {
|
|
@@ -875,7 +881,8 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
|
|
|
875
881
|
agentRegistry: registries?.agentRegistry,
|
|
876
882
|
handoffSchemas: registries?.handoffSchemas,
|
|
877
883
|
retry: step.retry,
|
|
878
|
-
progressOutput: options.progressOutput
|
|
884
|
+
progressOutput: options.progressOutput,
|
|
885
|
+
readonly: options.readonly
|
|
879
886
|
});
|
|
880
887
|
return {
|
|
881
888
|
step_index: i,
|
|
@@ -997,7 +1004,7 @@ async function handleGateStep(step, priorResults, options, stepIndex, adapter) {
|
|
|
997
1004
|
return {
|
|
998
1005
|
step_index: stepIndex,
|
|
999
1006
|
gate_kind: step.gate_kind,
|
|
1000
|
-
outcome: { status: "
|
|
1007
|
+
outcome: { status: "gate_rejected" },
|
|
1001
1008
|
follow_ups_used: 0,
|
|
1002
1009
|
retries_used: 0,
|
|
1003
1010
|
elapsed_ms: Date.now() - start
|
|
@@ -1070,6 +1077,8 @@ function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
|
1070
1077
|
}
|
|
1071
1078
|
|
|
1072
1079
|
// src/lib/guardrail-hooks.ts
|
|
1080
|
+
import { realpathSync } from "fs";
|
|
1081
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
|
|
1073
1082
|
function globFragmentToRegex(fragment) {
|
|
1074
1083
|
let out = "";
|
|
1075
1084
|
for (const ch of fragment) {
|
|
@@ -1116,6 +1125,26 @@ function matchGlob(pattern, path) {
|
|
|
1116
1125
|
}
|
|
1117
1126
|
return new RegExp("^" + regex + "$").test(path);
|
|
1118
1127
|
}
|
|
1128
|
+
function realPathAsFarAsItExists(path) {
|
|
1129
|
+
const missing = [];
|
|
1130
|
+
let head = path;
|
|
1131
|
+
for (; ; ) {
|
|
1132
|
+
try {
|
|
1133
|
+
return join(realpathSync(head), ...missing);
|
|
1134
|
+
} catch {
|
|
1135
|
+
const parent = dirname(head);
|
|
1136
|
+
if (parent === head) return path;
|
|
1137
|
+
missing.unshift(basename(head));
|
|
1138
|
+
head = parent;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
function rootRelativeTarget(path, root) {
|
|
1143
|
+
const absolute = resolve(root, path);
|
|
1144
|
+
const rel = relative(realPathAsFarAsItExists(root), realPathAsFarAsItExists(absolute));
|
|
1145
|
+
const outside = rel === "" || isAbsolute(rel) || rel.split(sep)[0] === "..";
|
|
1146
|
+
return outside ? absolute : rel.split(sep).join("/");
|
|
1147
|
+
}
|
|
1119
1148
|
function getBlockingViolations(results) {
|
|
1120
1149
|
return results.filter((r) => !r.passed && r.action === "block");
|
|
1121
1150
|
}
|
|
@@ -1173,10 +1202,11 @@ function createGuardrailHooks(checks) {
|
|
|
1173
1202
|
}
|
|
1174
1203
|
return {};
|
|
1175
1204
|
}
|
|
1176
|
-
function preToolUse(input) {
|
|
1177
|
-
const
|
|
1178
|
-
if (!
|
|
1179
|
-
const
|
|
1205
|
+
function preToolUse(input, root) {
|
|
1206
|
+
const target = input.tool_input?.file_path ?? input.tool_input?.path ?? "";
|
|
1207
|
+
if (!target) return {};
|
|
1208
|
+
const filePath = rootRelativeTarget(target, root ?? process.cwd());
|
|
1209
|
+
const results = runChecks({ filePath, content: input.tool_input?.content });
|
|
1180
1210
|
const blocks = getBlockingViolations(results);
|
|
1181
1211
|
if (blocks.length > 0) {
|
|
1182
1212
|
const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
|
|
@@ -1199,15 +1229,7 @@ function createGuardrailHooks(checks) {
|
|
|
1199
1229
|
return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };
|
|
1200
1230
|
}
|
|
1201
1231
|
function createGuardrailHooksForAgent(agentId, perAgent) {
|
|
1202
|
-
const
|
|
1203
|
-
if (!rules) {
|
|
1204
|
-
return createGuardrailHooks({
|
|
1205
|
-
checkCommand: () => [],
|
|
1206
|
-
checkFilePath: () => [],
|
|
1207
|
-
checkContent: () => []
|
|
1208
|
-
});
|
|
1209
|
-
}
|
|
1210
|
-
const hooks = createGuardrailHooksFromRules(rules);
|
|
1232
|
+
const hooks = createGuardrailHooksFromRules(perAgent.get(agentId));
|
|
1211
1233
|
const baseRunChecks = hooks.runChecks;
|
|
1212
1234
|
return {
|
|
1213
1235
|
...hooks,
|
|
@@ -1221,14 +1243,14 @@ function compileRulePattern(pattern) {
|
|
|
1221
1243
|
return inline ? new RegExp(pattern.slice(inline[0].length), inline[1]) : new RegExp(pattern);
|
|
1222
1244
|
}
|
|
1223
1245
|
function createGuardrailHooksFromRules(rules) {
|
|
1224
|
-
const commandChecks = rules
|
|
1246
|
+
const commandChecks = (rules?.commandRules ?? []).map((rule) => ({
|
|
1225
1247
|
guardrail_id: rule.guardrail_id,
|
|
1226
1248
|
pattern: compileRulePattern(rule.pattern),
|
|
1227
1249
|
action: rule.action,
|
|
1228
1250
|
message: rule.message
|
|
1229
1251
|
}));
|
|
1230
|
-
const fileChecks = rules
|
|
1231
|
-
const contentChecks = rules
|
|
1252
|
+
const fileChecks = rules?.fileRules ?? [];
|
|
1253
|
+
const contentChecks = (rules?.contentRules ?? []).map((rule) => ({
|
|
1232
1254
|
guardrail_id: rule.guardrail_id,
|
|
1233
1255
|
pattern: compileRulePattern(rule.pattern),
|
|
1234
1256
|
action: rule.action,
|
|
@@ -1363,7 +1385,7 @@ var WorkflowBuilder = class {
|
|
|
1363
1385
|
// src/lib/plugin-loader.ts
|
|
1364
1386
|
import { existsSync } from "fs";
|
|
1365
1387
|
import { readdir } from "fs/promises";
|
|
1366
|
-
import { resolve, join } from "path";
|
|
1388
|
+
import { resolve as resolve2, join as join2 } from "path";
|
|
1367
1389
|
var PLUGIN_EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
|
|
1368
1390
|
function isPluginLike(obj) {
|
|
1369
1391
|
return typeof obj === "object" && obj !== null && typeof obj.id === "string";
|
|
@@ -1373,7 +1395,7 @@ async function scanDirectory(dir) {
|
|
|
1373
1395
|
const entries = await readdir(dir, { withFileTypes: true });
|
|
1374
1396
|
return entries.filter(
|
|
1375
1397
|
(e) => e.isFile() && PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) && !e.name.startsWith("_") && !e.name.endsWith(".d.ts") && !e.name.endsWith(".test.ts") && !e.name.endsWith(".spec.ts")
|
|
1376
|
-
).map((e) =>
|
|
1398
|
+
).map((e) => resolve2(dir, e.name));
|
|
1377
1399
|
}
|
|
1378
1400
|
async function loadPluginModule(modulePath) {
|
|
1379
1401
|
const mod = await import(new URL(`file://${modulePath}`).href);
|
|
@@ -1392,7 +1414,7 @@ async function loadPluginModule(modulePath) {
|
|
|
1392
1414
|
async function loadPluginsFromPaths(paths, baseDir) {
|
|
1393
1415
|
const result = { loaded: 0, files: [], errors: [] };
|
|
1394
1416
|
for (const p of paths) {
|
|
1395
|
-
const absPath =
|
|
1417
|
+
const absPath = resolve2(baseDir, p);
|
|
1396
1418
|
if (!existsSync(absPath)) {
|
|
1397
1419
|
result.errors.push({ file: p, error: `File not found: ${absPath}` });
|
|
1398
1420
|
continue;
|
|
@@ -1431,27 +1453,27 @@ async function loadPlugins(options) {
|
|
|
1431
1453
|
if (options.pluginPaths && options.pluginPaths.length > 0) {
|
|
1432
1454
|
return loadPluginsFromPaths(options.pluginPaths, options.projectDir);
|
|
1433
1455
|
}
|
|
1434
|
-
const conventionDir =
|
|
1456
|
+
const conventionDir = join2(options.projectDir, "src", "plugins");
|
|
1435
1457
|
return loadPluginsFromDirectory(conventionDir);
|
|
1436
1458
|
}
|
|
1437
1459
|
|
|
1438
1460
|
// src/lib/progress-sink.ts
|
|
1439
1461
|
import { openSync, writeSync, closeSync, mkdirSync } from "fs";
|
|
1440
|
-
import { dirname, join as
|
|
1462
|
+
import { dirname as dirname2, join as join3, basename as basename2, extname } from "path";
|
|
1441
1463
|
function resolveFilePath(base, naming, label) {
|
|
1442
1464
|
if (naming === "single") return base;
|
|
1443
|
-
const dir =
|
|
1465
|
+
const dir = dirname2(base);
|
|
1444
1466
|
const ext = extname(base);
|
|
1445
|
-
const stem =
|
|
1467
|
+
const stem = basename2(base, ext);
|
|
1446
1468
|
const now = /* @__PURE__ */ new Date();
|
|
1447
1469
|
if (naming === "daily") {
|
|
1448
1470
|
const date = now.toISOString().slice(0, 10);
|
|
1449
|
-
return
|
|
1471
|
+
return join3(dir, `${stem}-${date}${ext}`);
|
|
1450
1472
|
}
|
|
1451
1473
|
const pad = (n) => String(n).padStart(2, "0");
|
|
1452
1474
|
const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}T${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
1453
1475
|
const suffix = label ? `-${label}` : "";
|
|
1454
|
-
return
|
|
1476
|
+
return join3(dir, `${stem}-${ts}${suffix}${ext}`);
|
|
1455
1477
|
}
|
|
1456
1478
|
function createProgressSink(options) {
|
|
1457
1479
|
const useStderr = options.stderr ?? false;
|
|
@@ -1460,7 +1482,7 @@ function createProgressSink(options) {
|
|
|
1460
1482
|
if (options.file) {
|
|
1461
1483
|
const naming = options.naming ?? "single";
|
|
1462
1484
|
resolvedPath = resolveFilePath(options.file, naming, options.label);
|
|
1463
|
-
mkdirSync(
|
|
1485
|
+
mkdirSync(dirname2(resolvedPath), { recursive: true });
|
|
1464
1486
|
fd = openSync(resolvedPath, "a");
|
|
1465
1487
|
}
|
|
1466
1488
|
if (!useStderr && fd === null) {
|
|
@@ -1508,8 +1530,8 @@ async function createAdapter(name, options) {
|
|
|
1508
1530
|
const { model, cwd, tools, permissionMode, guardrailHooks } = options ?? {};
|
|
1509
1531
|
switch (name) {
|
|
1510
1532
|
case "mock": {
|
|
1511
|
-
const { MockAdapter } = await import("./adapters/mock.js");
|
|
1512
|
-
return new
|
|
1533
|
+
const { MockAdapter: MockAdapter2 } = await import("./adapters/mock.js");
|
|
1534
|
+
return new MockAdapter2();
|
|
1513
1535
|
}
|
|
1514
1536
|
case "claude": {
|
|
1515
1537
|
try {
|
|
@@ -1555,7 +1577,7 @@ Install it with: npm install ${pkg}`
|
|
|
1555
1577
|
}
|
|
1556
1578
|
|
|
1557
1579
|
// src/lib/execute.ts
|
|
1558
|
-
import { resolve as
|
|
1580
|
+
import { resolve as resolve3 } from "path";
|
|
1559
1581
|
async function resolveExecutionContext(options, requiredEntities) {
|
|
1560
1582
|
const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
|
|
1561
1583
|
if (useBoundResolver) {
|
|
@@ -1589,21 +1611,10 @@ async function resolveExecutionContext(options, requiredEntities) {
|
|
|
1589
1611
|
}
|
|
1590
1612
|
function injectGuardrailHooks(adapterOptions, execCtx, targetAgentId) {
|
|
1591
1613
|
if (adapterOptions.guardrailHooks) return;
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
execCtx.dsl
|
|
1597
|
-
);
|
|
1598
|
-
if (rules2 && (rules2.commandRules.length > 0 || rules2.fileRules.length > 0 || rules2.contentRules.length > 0)) {
|
|
1599
|
-
adapterOptions.guardrailHooks = createGuardrailHooksFromRules(rules2);
|
|
1600
|
-
}
|
|
1601
|
-
return;
|
|
1602
|
-
}
|
|
1603
|
-
const rules = buildGuardrailRulesFromDsl(execCtx.dsl);
|
|
1604
|
-
if (rules && (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0)) {
|
|
1605
|
-
adapterOptions.guardrailHooks = createGuardrailHooksFromRules(rules);
|
|
1606
|
-
}
|
|
1614
|
+
const component = execCtx.resolvedComponent;
|
|
1615
|
+
adapterOptions.guardrailHooks = createGuardrailHooksFromRules(
|
|
1616
|
+
!component ? buildGuardrailRulesFromDsl(execCtx.dsl) : targetAgentId ? getGuardrailRulesForAgent(component, targetAgentId, execCtx.dsl) : getGuardrailRulesForComponent(component, execCtx.dsl)
|
|
1617
|
+
);
|
|
1607
1618
|
}
|
|
1608
1619
|
async function executeTask(taskId, options) {
|
|
1609
1620
|
const execCtx = await resolveExecutionContext(options, { tasks: [taskId] });
|
|
@@ -1615,7 +1626,7 @@ async function executeTask(taskId, options) {
|
|
|
1615
1626
|
...adapterOptions
|
|
1616
1627
|
});
|
|
1617
1628
|
const progressSink = createProgressSink(
|
|
1618
|
-
options.logFile ? { stderr: true, file:
|
|
1629
|
+
options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
|
|
1619
1630
|
);
|
|
1620
1631
|
try {
|
|
1621
1632
|
if (options.hooks?.beforeTask) {
|
|
@@ -1644,7 +1655,7 @@ async function executeWorkflow(workflowId, options) {
|
|
|
1644
1655
|
...adapterOptions
|
|
1645
1656
|
});
|
|
1646
1657
|
const progressSink = createProgressSink(
|
|
1647
|
-
options.logFile ? { stderr: true, file:
|
|
1658
|
+
options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
|
|
1648
1659
|
);
|
|
1649
1660
|
try {
|
|
1650
1661
|
if (options.hooks?.beforeWorkflow) {
|
|
@@ -1708,4 +1719,4 @@ export {
|
|
|
1708
1719
|
executeTask,
|
|
1709
1720
|
executeWorkflow
|
|
1710
1721
|
};
|
|
1711
|
-
//# sourceMappingURL=chunk-
|
|
1722
|
+
//# sourceMappingURL=chunk-UHHKLLA3.js.map
|