@hilbras/omninode 2.0.0-alpha.13 → 2.0.0-alpha.14
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/README.md +8 -1
- package/dist/cli/chunk-6Z6O63SS.js +708 -0
- package/dist/cli/chunk-6Z6O63SS.js.map +1 -0
- package/dist/cli/index.js +1163 -1572
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/providers-OYXBAQTX.js +36 -0
- package/dist/cli/providers-OYXBAQTX.js.map +1 -0
- package/dist/index.d.ts +80 -31
- package/dist/index.js +149 -48
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/task.ts","../src/errors/index.ts","../src/logger/index.ts","../src/config/schema.ts","../src/config/secrets.ts","../src/config/loader.ts","../src/config/default.ts","../src/providers/auth.ts","../src/providers/http.ts","../src/providers/errors.ts","../src/providers/openai-compatible/index.ts","../src/providers/omnihilbras/index.ts","../src/providers/factory.ts","../src/registry/index.ts","../src/agents/process/index.ts","../src/agent-protocol/version.ts","../src/agent-protocol/types.ts","../src/agent-protocol/codec.ts","../src/agent-protocol/handshake.ts","../src/agent-protocol/session.ts","../src/agents/cwd.ts","../src/agents/env.ts","../src/agents/adapters.ts","../src/agents/registry.ts","../src/agents/factory.ts","../src/roles/index.ts","../src/persistence/json-file-store.ts","../src/tasks/store.ts","../src/tasks/engine.ts","../src/audit/index.ts","../src/memory/base.ts","../src/memory/local.ts","../src/memory/remembera.ts","../src/memory/factory.ts","../src/memory/service.ts","../src/tasks/engine-factory.ts","../src/pipelines/engine.ts","../src/reports/aggregate.ts","../src/reports/schema.ts","../src/planner/heuristic.ts","../src/planner/model.ts","../src/planner/schema.ts","../src/planner/context.ts","../src/pipelines/store.ts","../src/planner/store.ts","../src/planner/factory.ts","../src/reports/extract.ts","../src/reports/service.ts","../src/reports/store.ts","../src/pipelines/engine-factory.ts","../src/persistence/index.ts","../src/version.ts"],"sourcesContent":["/** Task system: every operation becomes a Task (§13). */\nimport type { Report } from \"./report.js\";\n\n/**\n * Execution states (v2 Phase 2, roadmap §6.1).\n *\n * The crucial distinction: `unknown` means \"we cannot prove the outcome\" —\n * e.g. a process timeout after the agent may already have performed side\n * effects. It is deliberately NOT `failed`: retrying blindly could duplicate\n * work, and reporting failure would be a lie. Resolve it explicitly with\n * `task retry` (which starts a fresh execution) or by inspecting artifacts.\n */\nexport type TaskStatus =\n | \"created\"\n | \"queued\"\n | \"running\"\n | \"waiting\"\n | \"completed\"\n | \"failed\"\n | \"timed_out\"\n | \"cancelled\"\n | \"unknown\"\n | \"partially_completed\";\n\n/** States from which no further automatic transition happens. */\nexport const TERMINAL_TASK_STATUSES: readonly TaskStatus[] = [\n \"completed\",\n \"failed\",\n \"timed_out\",\n \"cancelled\",\n \"partially_completed\",\n];\n\n/** One execution attempt (roadmap §6.5 identity: task + attempt + execution id). */\nexport interface ExecutionRecord {\n executionId: string;\n attempt: number;\n startedAt: string;\n finishedAt: string;\n outcome: \"completed\" | \"failed\" | \"timed_out\" | \"unknown\" | \"cancelled\";\n error?: string;\n}\n\nexport interface TaskContext {\n project?: string;\n /** Paths or globs relevant to the task. */\n files?: string[];\n /** Free-form background injected into the prompt. */\n background?: string;\n /** Keys of memory entries pulled from the memory provider. */\n memoryKeys?: string[];\n}\n\nexport interface TaskResult {\n summary?: string;\n artifacts?: string[];\n reportId?: string;\n /** Structured reports produced by protocol-mode agents (Phase 6 builds on this). */\n reports?: Report[];\n /** Truncated verbatim agent output, kept for report extraction and audit. */\n rawOutput?: string;\n error?: string;\n finishedAt?: string;\n}\n\nexport interface Task {\n id: string;\n project?: string;\n objective: string;\n /** Role id from the role system. */\n role?: string;\n /** Agent name from the agent registry. */\n agent?: string;\n context?: TaskContext;\n status: TaskStatus;\n createdAt: string;\n updatedAt: string;\n /** Number of engine.run attempts so far (0 = never executed). */\n attempt: number;\n /** Error from the most recent failed/unknown attempt. */\n lastError?: string;\n /** Recent execution attempts, newest last, bounded in length. */\n executions?: ExecutionRecord[];\n result?: TaskResult;\n}\n","/** Typed error hierarchy shared across the whole codebase (§4.1 — error model). */\n\nexport type OmniNodeErrorCode =\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n | \"PROVIDER_NOT_FOUND\"\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\"\n | \"AGENT_NOT_FOUND\"\n | \"AGENT_FAILED\"\n | \"AGENT_TIMEOUT\"\n | \"TASK_INVALID\"\n | \"TASK_NOT_FOUND\"\n | \"TASK_FAILED\"\n | \"PIPELINE_NOT_FOUND\"\n | \"PIPELINE_INVALID\"\n | \"PIPELINE_FAILED\"\n | \"PLANNER_FAILED\"\n | \"PLAN_INVALID\"\n | \"PROTOCOL_VIOLATION\"\n | \"MEMORY_UNAVAILABLE\"\n | \"REPORT_NOT_FOUND\"\n | \"NOT_IMPLEMENTED\"\n | \"CLI_USAGE\"\n | \"INTERNAL\";\n\nexport interface OmniNodeErrorOptions {\n cause?: unknown;\n details?: Record<string, unknown>;\n}\n\nexport class OmniNodeError extends Error {\n readonly code: OmniNodeErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: OmniNodeErrorCode, message: string, options: OmniNodeErrorOptions = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.code = code;\n this.details = options.details;\n }\n}\n\nexport class ConfigError extends OmniNodeError {\n constructor(\n code: \"CONFIG_NOT_FOUND\" | \"CONFIG_INVALID\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class ProviderError extends OmniNodeError {\n constructor(\n code:\n | \"PROVIDER_NOT_FOUND\"\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class AgentError extends OmniNodeError {\n constructor(\n code: \"AGENT_NOT_FOUND\" | \"AGENT_FAILED\" | \"AGENT_TIMEOUT\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class TaskError extends OmniNodeError {\n constructor(\n code: \"TASK_INVALID\" | \"TASK_NOT_FOUND\" | \"TASK_FAILED\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class PipelineError extends OmniNodeError {\n constructor(\n code: \"PIPELINE_NOT_FOUND\" | \"PIPELINE_INVALID\" | \"PIPELINE_FAILED\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class ProtocolError extends OmniNodeError {\n constructor(message: string, options: OmniNodeErrorOptions = {}) {\n super(\"PROTOCOL_VIOLATION\", message, options);\n }\n}\n\nexport class PlannerError extends OmniNodeError {\n constructor(\n code: \"PLANNER_FAILED\" | \"PLAN_INVALID\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class MemoryError extends OmniNodeError {\n constructor(message: string, options: OmniNodeErrorOptions = {}) {\n super(\"MEMORY_UNAVAILABLE\", message, options);\n }\n}\n\nexport function isOmniNodeError(value: unknown): value is OmniNodeError {\n return value instanceof OmniNodeError;\n}\n","/** Leveled logger with a pluggable sink and child loggers (§4.1 — logging). */\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LogSink {\n write(level: LogLevel, line: string): void;\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\nexport interface WritableLike {\n write(chunk: string): unknown;\n}\n\nexport class ConsoleLogSink implements LogSink {\n constructor(private readonly stream: WritableLike = process.stderr) {}\n\n write(_level: LogLevel, line: string): void {\n this.stream.write(line + \"\\n\");\n }\n}\n\nexport interface LoggerOptions {\n level?: LogLevel;\n sink?: LogSink;\n /** Structured fields attached to every line, e.g. { component: \"config\" }. */\n context?: Record<string, unknown>;\n}\n\nexport class Logger {\n private readonly level: LogLevel;\n private readonly sink: LogSink;\n private readonly context: Record<string, unknown>;\n\n constructor(options: LoggerOptions = {}) {\n this.level = options.level ?? \"info\";\n this.sink = options.sink ?? new ConsoleLogSink();\n this.context = options.context ?? {};\n }\n\n child(context: Record<string, unknown>): Logger {\n return new Logger({\n level: this.level,\n sink: this.sink,\n context: { ...this.context, ...context },\n });\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log(\"debug\", message, data);\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log(\"info\", message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log(\"warn\", message, data);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log(\"error\", message, data);\n }\n\n private log(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) return;\n const parts = [new Date().toISOString(), level.toUpperCase(), message];\n const merged = { ...this.context, ...data };\n if (Object.keys(merged).length > 0) {\n parts.push(JSON.stringify(merged));\n }\n this.sink.write(level, parts.join(\" \"));\n }\n}\n\n/** Default application logger. Writes to stderr so stdout stays clean for CLI output. */\nexport const logger = new Logger();\n","/**\n * Configuration schema. The project file (omninode.yaml) uses snake_case keys\n * as shown in DEVELOPMENT_PLAN.md §7 and §23; the loader maps them onto the\n * camelCase TypeScript contracts in src/types.\n */\nimport { z } from \"zod\";\n\nexport const providerConfigSchema = z\n .object({\n name: z.string().min(1),\n type: z.enum([\"openai-compatible\", \"omnihilbras\", \"openrouter\", \"local\", \"custom\"]),\n base_url: z.string().url(),\n api_key_env_var: z.string().min(1).optional(),\n timeout_ms: z.number().int().positive().optional(),\n headers: z.record(z.string()).optional(),\n enabled: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const agentConfigSchema = z\n .object({\n name: z.string().min(1),\n /** \"cli\" agents communicate over stdin/stdout (process adapter). */\n type: z.enum([\"cli\", \"native\", \"process\"]).default(\"cli\"),\n command: z.string().min(1).optional(),\n args: z.array(z.string()).optional(),\n cwd: z.string().optional(),\n env: z.record(z.string()).optional(),\n input_mode: z.enum([\"stdin\", \"arg\", \"protocol\"]).default(\"stdin\"),\n timeout_ms: z.number().int().positive().optional(),\n inherit_env: z.boolean().optional(),\n env_policy: z.enum([\"inherit\", \"allowlist\", \"denylist\", \"explicit\"]).optional(),\n env_allowlist: z.array(z.string()).optional(),\n env_denylist: z.array(z.string()).optional(),\n max_output_bytes: z.number().int().positive().optional(),\n allow_external_cwd: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const roleConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"role id must be kebab-case\"),\n name: z.string().min(1),\n description: z.string().optional(),\n responsibilities: z.array(z.string()).default([]),\n expected_outputs: z.array(z.string()).default([]),\n preferred_agents: z.array(z.string()).optional(),\n system_prompt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const pipelineStepConfigSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"research\", \"collect\", \"analyze\", \"plan\", \"execute\", \"custom\"]),\n agents: z.array(z.string()).optional(),\n agent: z.string().optional(),\n model: z.string().optional(),\n depends_on: z.array(z.string()).optional(),\n retries: z.number().int().min(0).max(10).optional(),\n condition: z.enum([\"always\", \"on-success\", \"on-failure\"]).optional(),\n /** Constraints passed to the planner for plan steps (§15). */\n constraints: z.array(z.string()).optional(),\n })\n .strict();\n\nexport const pipelineConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"pipeline id must be kebab-case\"),\n name: z.string().optional(),\n objective: z.string().optional(),\n role: z.string().optional(),\n steps: z.array(pipelineStepConfigSchema).min(1),\n })\n .strict();\n\nexport const plannerConfigSchema = z\n .object({\n kind: z.enum([\"model\", \"heuristic\"]).default(\"model\"),\n model: z.string().optional(),\n instruction: z.string().optional(),\n })\n .strict();\n\nexport const projectConfigSchema = z\n .object({\n name: z.string().min(1),\n providers: z.array(providerConfigSchema).default([]),\n agents: z.array(agentConfigSchema).default([]),\n roles: z.array(roleConfigSchema).default([]),\n pipelines: z.array(pipelineConfigSchema).default([]),\n planner: plannerConfigSchema.optional(),\n memory: z\n .object({\n provider: z.string().min(1).default(\"local\"),\n base_url: z.string().url().optional(),\n api_key_env_var: z.string().min(1).optional(),\n /** When true, memory failures fail tasks instead of being tolerated (§12). */\n required: z.boolean().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const appConfigSchema = z\n .object({\n project: projectConfigSchema,\n logging: z\n .object({ level: z.enum([\"debug\", \"info\", \"warn\", \"error\"]) })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type ProviderConfigYaml = z.infer<typeof providerConfigSchema>;\nexport type AgentConfigYaml = z.infer<typeof agentConfigSchema>;\nexport type RoleConfigYaml = z.infer<typeof roleConfigSchema>;\nexport type PipelineConfigYaml = z.infer<typeof pipelineConfigSchema>;\nexport type PipelineStepConfigYaml = z.infer<typeof pipelineStepConfigSchema>;\nexport type PlannerConfigYaml = z.infer<typeof plannerConfigSchema>;\nexport type ProjectConfigYaml = z.infer<typeof projectConfigSchema>;\nexport type AppConfigYaml = z.infer<typeof appConfigSchema>;\n","/**\n * Inline secret detection (roadmap §17, Secrets).\n *\n * OmniNode configuration must never contain literal credentials — only\n * environment-variable *references*. This scanner runs before the config is\n * parsed and reports anything that looks like an inline secret, so the file\n * is rejected before it can be committed or persisted.\n */\n\nexport interface SecretFinding {\n /** 1-based line number in the source. */\n line: number;\n /** The offending key, e.g. `api_key`. */\n key: string;\n /** Redacted excerpt — never echoes the value. */\n excerpt: string;\n}\n\n/** Keys that are references or placeholders, not secrets. */\nconst SAFE_KEY_SUFFIXES = [\"_env\", \"_env_var\", \"_file\", \"_path\", \"_ref\", \"_id\", \"_url\", \"_command\"];\n\nconst SECRET_KEY = /^\\s*([A-Za-z0-9_-]*(?:api[_-]?key|token|password|passwd|secret|credential)[A-Za-z0-9_-]*)\\s*:\\s*(.*)$/i;\n\n/** Values that are clearly references, not credentials. */\nconst SAFE_VALUE = /^\\s*(?:\\$\\{[^}]*\\}|\\$[A-Z_][A-Z0-9_]*|<[^>]*>|\"\"|''|null|~)\\s*$/i;\n\nexport function scanForInlineSecrets(source: string): SecretFinding[] {\n const findings: SecretFinding[] = [];\n source.split(\"\\n\").forEach((line, index) => {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\")) return; // comments are not credentials\n const match = SECRET_KEY.exec(line);\n if (!match) return;\n const key = match[1] ?? \"\";\n const rawValue = (match[2] ?? \"\").trim().replace(/,\\s*$/, \"\");\n const keyIsReference = SAFE_KEY_SUFFIXES.some((suffix) => key.toLowerCase().endsWith(suffix));\n if (keyIsReference) return;\n const value = rawValue.replace(/^[\"']|[\"']$/g, \"\");\n if (value.length === 0 || SAFE_VALUE.test(rawValue)) return;\n // Very short values are almost always placeholders, not credentials.\n if (value.length < 8) return;\n findings.push({\n line: index + 1,\n key,\n excerpt: `${key}: ${value.slice(0, 3)}… (${value.length} chars, redacted)`,\n });\n });\n return findings;\n}\n\n/** Formats findings as an actionable configuration error message. */\nexport function describeSecretFindings(file: string, findings: SecretFinding[]): string {\n const lines = findings.map((f) => ` line ${f.line}: ${f.excerpt}`).join(\"\\n\");\n return (\n `${file} appears to contain ${findings.length} inline secret(s):\\n${lines}\\n` +\n `OmniNode never stores credentials in configuration. Replace each value with an ` +\n `environment-variable reference, e.g. api_key_env_var: MY_API_KEY.`\n );\n}\n","/**\n * Configuration loader: discovers omninode.yaml, expands ${ENV_VAR}\n * references (so credentials never live in project files, §24), validates it\n * and maps it onto the core TypeScript contracts.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport { ConfigError } from \"../errors/index.js\";\nimport { describeSecretFindings, scanForInlineSecrets } from \"./secrets.js\";\nimport type { AgentConfig, AgentIntegrationType } from \"../types/agent.js\";\nimport type { ProviderConfig } from \"../types/provider.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type { LogLevel } from \"../logger/index.js\";\nimport { appConfigSchema } from \"./schema.js\";\nimport type { AgentConfigYaml, PipelineConfigYaml, ProviderConfigYaml, RoleConfigYaml } from \"./schema.js\";\nimport type { PipelineDefinition } from \"../types/pipeline.js\";\n\nconst CONFIG_FILENAMES = [\"omninode.yaml\", \"omninode.yml\", \"omninode.json\"];\n\nexport interface AppConfig {\n project: {\n name: string;\n providers: ProviderConfig[];\n agents: AgentConfig[];\n roles: RoleDefinition[];\n pipelines: PipelineDefinition[];\n planner?: {\n kind: \"model\" | \"heuristic\";\n model?: string;\n instruction?: string;\n };\n memory?: {\n provider: string;\n baseUrl?: string;\n apiKeyEnvVar?: string;\n required?: boolean;\n };\n };\n logging?: {\n level: LogLevel;\n };\n}\n\nexport interface LoadConfigOptions {\n /** Explicit path; otherwise omninode.yaml/yml/json is looked up in the given directory. */\n path?: string;\n directory?: string;\n /** Environment used for ${VAR} expansion; defaults to process.env. */\n env?: Record<string, string | undefined>;\n}\n\nexport function findConfigFile(directory = process.cwd()): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const candidate = `${directory}/${filename}`;\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/**\n * Replaces ${VAR} and ${VAR:-fallback} references. Unset variables without a\n * fallback abort loading: a half-resolved config could silently misroute\n * authentication.\n */\nexport function expandEnvRefs(\n text: string,\n env: Record<string, string | undefined>,\n source = \"config\",\n): string {\n return text.replace(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g,\n (_match, name: string, fallback?: string) => {\n const value = env[name] ?? fallback;\n if (value === undefined) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Environment variable \"${name}\" is referenced in ${source} but is not set and has no default.`,\n );\n }\n return value;\n },\n );\n}\n\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n const env = options.env ?? process.env;\n const path = options.path ?? (options.directory ? findConfigFile(options.directory) : findConfigFile());\n if (!path) {\n throw new ConfigError(\n \"CONFIG_NOT_FOUND\",\n \"No omninode.yaml found. Run `omninode init` to create one, or pass an explicit path.\",\n );\n }\n\n const raw = readFileSync(path, \"utf8\");\n // §13 Security: refuse inline credentials before anything is persisted.\n const secretFindings = scanForInlineSecrets(raw);\n if (secretFindings.length > 0) {\n throw new ConfigError(\"CONFIG_INVALID\", describeSecretFindings(path, secretFindings));\n }\n const expanded = expandEnvRefs(raw, env, path);\n\n let data: unknown;\n try {\n data = parseYaml(expanded);\n } catch (error) {\n throw new ConfigError(\"CONFIG_INVALID\", `Failed to parse ${path}.`, { cause: error });\n }\n\n const parsed = appConfigSchema.safeParse(data);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => {\n const location = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n return `${location}: ${issue.message}`;\n });\n throw new ConfigError(\"CONFIG_INVALID\", `Invalid configuration in ${path}.`, {\n details: { issues },\n });\n }\n\n return toAppConfig(parsed.data);\n}\n\nfunction toAppConfig(yaml: ReturnType<typeof appConfigSchema.parse>): AppConfig {\n return {\n project: {\n name: yaml.project.name,\n providers: yaml.project.providers.map(toProviderConfig),\n agents: yaml.project.agents.map(toAgentConfig),\n roles: yaml.project.roles.map(toRoleDefinition),\n pipelines: yaml.project.pipelines.map(toPipelineDefinition),\n ...(yaml.project.planner !== undefined\n ? {\n planner: {\n kind: yaml.project.planner.kind,\n model: yaml.project.planner.model,\n instruction: yaml.project.planner.instruction,\n },\n }\n : {}),\n ...(yaml.project.memory !== undefined\n ? {\n memory: {\n provider: yaml.project.memory.provider,\n baseUrl: yaml.project.memory.base_url,\n apiKeyEnvVar: yaml.project.memory.api_key_env_var,\n required: yaml.project.memory.required,\n },\n }\n : {}),\n },\n ...(yaml.logging !== undefined ? { logging: yaml.logging } : {}),\n };\n}\n\nfunction toPipelineDefinition(raw: PipelineConfigYaml): PipelineDefinition {\n return {\n id: raw.id,\n name: raw.name,\n objective: raw.objective,\n role: raw.role,\n steps: raw.steps.map((step) => ({\n id: step.id,\n kind: step.kind,\n agents: step.agents,\n agent: step.agent,\n model: step.model,\n dependsOn: step.depends_on,\n retries: step.retries,\n condition: step.condition,\n constraints: step.constraints,\n })),\n };\n}\n\nfunction toProviderConfig(raw: ProviderConfigYaml): ProviderConfig {\n return {\n name: raw.name,\n type: raw.type,\n baseUrl: raw.base_url,\n apiKeyEnvVar: raw.api_key_env_var,\n timeoutMs: raw.timeout_ms,\n headers: raw.headers,\n enabled: raw.enabled,\n metadata: raw.metadata,\n };\n}\n\nfunction toAgentConfig(raw: AgentConfigYaml): AgentConfig {\n const integration: AgentIntegrationType =\n raw.type === \"native\" ? \"native\" : \"process\";\n return {\n name: raw.name,\n integration,\n command: raw.command,\n args: raw.args,\n cwd: raw.cwd,\n env: raw.env,\n inputMode: raw.input_mode,\n timeoutMs: raw.timeout_ms,\n inheritEnv: raw.inherit_env,\n envPolicy: raw.env_policy,\n envAllowlist: raw.env_allowlist,\n envDenylist: raw.env_denylist,\n maxOutputBytes: raw.max_output_bytes,\n allowExternalCwd: raw.allow_external_cwd,\n metadata: raw.metadata,\n };\n}\n\nfunction toRoleDefinition(raw: RoleConfigYaml): RoleDefinition {\n return {\n id: raw.id,\n name: raw.name,\n description: raw.description,\n responsibilities: raw.responsibilities,\n expectedOutputs: raw.expected_outputs,\n preferredAgents: raw.preferred_agents,\n systemPrompt: raw.system_prompt,\n metadata: raw.metadata,\n };\n}\n\n","/** Template written by `omninode init` (§22, §23). */\n\nexport function defaultProjectConfigYaml(projectName = \"My Project\"): string {\n return `project:\n name: ${projectName}\n\n # Providers connect OmniNode to AI model gateways (Phase 1+).\n # Credentials are referenced by environment variable, never stored in this file.\n providers: []\n # - name: my-gateway\n # type: openai-compatible\n # base_url: https://example.com/v1\n # api_key_env_var: MY_API_KEY\n\n # CLI agents registered with OmniNode (Phase 3 wires them up).\n agents: []\n # - name: opencode\n # type: cli\n # command: opencode\n\n # Roles describe what an AI is supposed to do (Phase 4).\n roles: []\n # - id: architecture-reviewer\n # name: Architecture Reviewer\n # responsibilities:\n # - architecture analysis\n # expected_outputs:\n # - findings\n # - recommendations\n\n # Memory is optional; Remembera is the preferred integration (Phase 7).\n # memory:\n # provider: remembera\n`;\n}\n","/**\n * Authentication resolution (§24): API keys live in the environment and are\n * referenced from configuration by variable name — never stored in files.\n */\nimport { ProviderError } from \"../errors/index.js\";\n// AuthRef is structurally satisfied by ProviderConfig.\n\n/** Minimal provider identity — any config object with a name and optional env var reference. */\nexport interface AuthRef {\n name: string;\n apiKeyEnvVar?: string;\n headers?: Record<string, string>;\n}\n\nexport function resolveApiKey(\n config: AuthRef,\n env: Record<string, string | undefined> = process.env,\n): string | undefined {\n if (!config.apiKeyEnvVar) return undefined;\n const value = env[config.apiKeyEnvVar];\n if (!value) {\n throw new ProviderError(\n \"PROVIDER_AUTH_FAILED\",\n `Environment variable \"${config.apiKeyEnvVar}\" (referenced by provider \"${config.name}\") is not set.`,\n );\n }\n return value;\n}\n\nexport function authHeaders(\n config: AuthRef,\n env: Record<string, string | undefined> = process.env,\n): Record<string, string> {\n const key = resolveApiKey(config, env);\n const base = { ...(config.headers ?? {}) };\n return key ? { ...base, authorization: `Bearer ${key}` } : base;\n}\n","/**\n * Thin JSON HTTP layer over global fetch. HTTP error statuses are returned to\n * the caller, not thrown — provider methods interpret them; only transport\n * failures (network, timeout, unparseable body) throw.\n */\n/** Raised for malformed provider responses so adapters can classify them. */\nexport class HttpResponseError extends Error {\n constructor(message: string, readonly status: number, cause?: unknown) {\n super(message, { cause });\n this.name = \"HttpResponseError\";\n }\n}\n\nexport interface HttpRequestOptions {\n method?: \"GET\" | \"POST\";\n headers?: Record<string, string>;\n body?: unknown;\n timeoutMs?: number;\n}\n\nexport interface HttpResponse {\n status: number;\n body: unknown;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nexport async function requestJson(\n url: string,\n options: HttpRequestOptions = {},\n): Promise<HttpResponse> {\n const { method = \"GET\", headers = {}, body, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\n // Transport failures propagate raw: adapters normalize them into provider\n // error kinds (roadmap §10).\n const response: Response = await fetch(url, {\n method,\n headers: {\n accept: \"application/json\",\n ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n ...headers,\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch (error) {\n throw new HttpResponseError(`Response from ${url} was not valid JSON.`, response.status, error);\n }\n\n return { status: response.status, body: parsed };\n}\n","/**\n * Provider error normalization (roadmap §10).\n *\n * Every provider failure is mapped to one stable kind, so callers can react\n * (retry a rate limit, surface an auth problem, treat a missing model\n * differently) without string-matching provider-specific payloads.\n */\nimport { ProviderError } from \"../errors/index.js\";\n\nexport type ProviderErrorKind =\n | \"AUTHENTICATION_ERROR\"\n | \"RATE_LIMIT_ERROR\"\n | \"INVALID_REQUEST\"\n | \"MODEL_NOT_FOUND\"\n | \"TIMEOUT\"\n | \"NETWORK_ERROR\"\n | \"SERVER_ERROR\"\n | \"UNKNOWN_ERROR\";\n\nexport interface ProviderErrorContext {\n provider: string;\n operation: string;\n status?: number;\n body?: unknown;\n retryAfterMs?: number;\n cause?: unknown;\n /** Maps the normalized kind onto the legacy stable error code. */\n code?:\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\";\n}\n\nfunction kindToCode(kind: ProviderErrorKind): NonNullable<ProviderErrorContext[\"code\"]> {\n switch (kind) {\n case \"AUTHENTICATION_ERROR\":\n return \"PROVIDER_AUTH_FAILED\";\n case \"MODEL_NOT_FOUND\":\n return \"MODEL_NOT_FOUND\";\n default:\n return \"PROVIDER_UNAVAILABLE\";\n }\n}\n\n/** Kinds worth retrying automatically (rate limits and transient server errors). */\nexport function isRetryable(kind: ProviderErrorKind): boolean {\n return kind === \"RATE_LIMIT_ERROR\" || kind === \"SERVER_ERROR\" || kind === \"NETWORK_ERROR\";\n}\n\n/** Maps an HTTP status (and optional body) to a normalized kind. */\nexport function kindFromStatus(status: number): ProviderErrorKind {\n if (status === 401 || status === 403) return \"AUTHENTICATION_ERROR\";\n if (status === 429) return \"RATE_LIMIT_ERROR\";\n if (status === 404) return \"MODEL_NOT_FOUND\";\n if (status === 408 || status === 504) return \"TIMEOUT\";\n if (status >= 500) return \"SERVER_ERROR\";\n if (status >= 400) return \"INVALID_REQUEST\";\n return \"UNKNOWN_ERROR\";\n}\n\n/** Extracts a human message from common provider error body shapes. */\nexport function extractMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const root = body as Record<string, unknown>;\n const error = (root.error ?? root) as Record<string, unknown>;\n const message = error.message ?? error.detail ?? root.message;\n return typeof message === \"string\" ? message : undefined;\n}\n\n/** Parses `Retry-After` (seconds or HTTP-date) into milliseconds. */\nexport function parseRetryAfter(value: string | null | undefined, now = Date.now()): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/** True for the abort/timeout errors raised by fetch's AbortSignal.timeout. */\nexport function isTimeoutError(error: unknown): boolean {\n return (\n (error instanceof Error && (error.name === \"TimeoutError\" || error.name === \"AbortError\")) ||\n (typeof (error as { code?: string })?.code === \"string\" &&\n (error as { code?: string }).code === \"ABORT_ERR\")\n );\n}\n\n/** True for transport failures (DNS, refused, TLS, offline). */\nexport function isNetworkError(error: unknown): boolean {\n return error instanceof TypeError || (typeof (error as { cause?: unknown })?.cause === \"object\" && error instanceof Error && !(error as { code?: string }).code);\n}\n\n/**\n * Builds a normalized ProviderError from an HTTP failure.\n */\n/** Actionable fallback text per kind (used when the provider sent no message). */\nfunction fallbackMessage(kind: ProviderErrorKind, context: ProviderErrorContext, status: number): string {\n const { provider, operation } = context;\n switch (kind) {\n case \"AUTHENTICATION_ERROR\":\n return `Authentication with provider \"${provider}\" failed (HTTP ${status}). Check that the referenced API key is set and valid.`;\n case \"RATE_LIMIT_ERROR\":\n return `Provider \"${provider}\" rate-limited ${operation} (HTTP ${status}). Retry later.`;\n case \"MODEL_NOT_FOUND\":\n return `Provider \"${provider}\" does not expose the requested model (HTTP ${status}).`;\n case \"TIMEOUT\":\n return `Provider \"${provider}\" timed out during ${operation} (HTTP ${status}).`;\n case \"SERVER_ERROR\":\n return `Provider \"${provider}\" returned a server error during ${operation} (HTTP ${status}).`;\n case \"INVALID_REQUEST\":\n return `Provider \"${provider}\" rejected ${operation} as invalid (HTTP ${status}).`;\n default:\n return `Provider \"${provider}\" failed during ${operation} (HTTP ${status}).`;\n }\n}\n\nexport function providerHttpError(context: ProviderErrorContext): ProviderError {\n const status = context.status ?? 0;\n const kind = kindFromStatus(status);\n const detail = extractMessage(context.body);\n const retryAfterMs = context.retryAfterMs ?? parseRetryAfter(undefined);\n return new ProviderError(\n context.code ?? kindToCode(kind),\n detail ?? fallbackMessage(kind, context, status),\n {\n cause: context.cause,\n details: {\n kind,\n provider: context.provider,\n operation: context.operation,\n status,\n retryable: isRetryable(kind),\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n ...(detail ? { providerMessage: detail } : {}),\n },\n },\n );\n}\n\n/** Wraps a thrown transport/abort error into a normalized ProviderError. */\nexport function providerTransportError(context: Omit<ProviderErrorContext, \"status\" | \"body\">): ProviderError {\n const cause = context.cause;\n const kind: ProviderErrorKind = isTimeoutError(cause)\n ? \"TIMEOUT\"\n : cause instanceof SyntaxError || (cause as { name?: string })?.name === \"HttpResponseError\"\n ? \"UNKNOWN_ERROR\"\n : \"NETWORK_ERROR\";\n const message = context.cause instanceof Error ? context.cause.message : String(context.cause);\n return new ProviderError(\"PROVIDER_UNAVAILABLE\", `Provider request failed: ${message}`, {\n cause: context.cause,\n details: {\n kind,\n provider: context.provider,\n operation: context.operation,\n retryable: isRetryable(kind),\n },\n });\n}","/**\n * OpenAI-compatible provider adapter (§5, §7): works with OpenAI, OpenRouter,\n * local runtimes (Ollama/LM Studio/vLLM) and custom gateways that expose the\n * /models and /chat/completions endpoints.\n */\nimport { ProviderError } from \"../../errors/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\n\n/** Default provider request timeout when the config does not set one. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nimport type { ChatRequest, ChatResponse, ChatStreamChunk } from \"../../types/chat.js\";\nimport type { Modality, ModelInfo } from \"../../types/model.js\";\nimport type { IChatProvider, ProviderConfig, ProviderStatus } from \"../../types/provider.js\";\nimport { authHeaders } from \"../auth.js\";\nimport { requestJson } from \"../http.js\";\nimport { providerHttpError, providerTransportError } from \"../errors.js\";\nimport type { ProviderAuthentication } from \"../../types/provider.js\";\n\ninterface OpenAIModelEntry {\n id?: unknown;\n name?: unknown;\n owned_by?: unknown;\n created?: unknown;\n context_length?: unknown;\n context_window?: unknown;\n input_modalities?: unknown;\n output_modalities?: unknown;\n supported_parameters?: unknown;\n}\n\ninterface OpenAIChatResponse {\n model?: unknown;\n choices?: unknown;\n usage?: unknown;\n}\n\nexport class OpenAICompatibleProvider implements IChatProvider {\n readonly config: ProviderConfig;\n readonly providerId: string;\n readonly authentication: ProviderAuthentication;\n private readonly log: Logger;\n /** Discovered models, so getModel() answers without another round-trip. */\n private discovered?: ModelInfo[];\n\n private readonly env: Record<string, string | undefined>;\n\n constructor(config: ProviderConfig, log: Logger = logger, env: Record<string, string | undefined> = process.env) {\n this.config = { ...config, baseUrl: normalizeBaseUrl(config.baseUrl) };\n this.env = env;\n this.providerId = config.providerId ?? config.name;\n this.authentication = {\n method: config.apiKeyEnvVar ? \"bearer\" : \"none\",\n ...(config.apiKeyEnvVar ? { envVar: config.apiKeyEnvVar } : {}),\n configured: config.apiKeyEnvVar ? Boolean(env[config.apiKeyEnvVar]) : true,\n };\n this.log = log.child({ provider: config.name });\n }\n\n /** Provider-level request timeout (roadmap §6.6/§11) with the shared default. */\n private get requestTimeoutMs(): number {\n return this.config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n }\n\n /** Authenticate + discover (roadmap §10, Model Discovery). */\n async connect(): Promise<ModelInfo[]> {\n authHeaders(this.config, this.env); // throws PROVIDER_AUTH_FAILED when the env var is unset\n const models = await this.listModels();\n this.discovered = models;\n return models;\n }\n\n async getModel(modelId: string): Promise<ModelInfo | undefined> {\n const models = this.discovered ?? (await this.connect());\n return models.find((m) => m.id === modelId);\n }\n\n /** Raw /models body (protected so adapters can capture gateway-level metadata). */\n protected async rawModelsResponse(): Promise<unknown> {\n const response = await this.modelsRequest();\n return response.body;\n }\n\n private async modelsRequest(): Promise<{ status: number; body: unknown }> {\n let response: { status: number; body: unknown };\n try {\n response = await requestJson(`${this.config.baseUrl}/models`, {\n headers: authHeaders(this.config, this.env),\n timeoutMs: this.requestTimeoutMs,\n });\n } catch (error) {\n if (error instanceof ProviderError) throw error; // auth problem — keep the precise error\n throw providerTransportError({ provider: this.config.name, operation: \"listModels\", cause: error });\n }\n const { status, body } = response;\n if (status !== 200) {\n throw providerHttpError({\n provider: this.config.name,\n operation: \"listModels\",\n status,\n body,\n });\n }\n return response;\n }\n\n async listModels(): Promise<ModelInfo[]> {\n const body = await this.rawModelsResponse();\n\n const entries = extractModelEntries(body, this.config);\n const models: ModelInfo[] = [];\n let skipped = 0;\n for (const entry of entries) {\n if (typeof entry.id !== \"string\" || entry.id.length === 0) {\n skipped += 1;\n continue;\n }\n models.push(this.toModelInfo(entry as OpenAIModelEntry & { id: string }));\n }\n if (skipped > 0) {\n this.log.warn(`Skipped ${skipped} model entr(y/ies) without a valid id.`);\n }\n return models;\n }\n\n /** Maps a raw model entry onto the normalized metadata shape (§10). */\n private toModelInfo(entry: OpenAIModelEntry & { id: string }): ModelInfo {\n const parameters = Array.isArray(entry.supported_parameters)\n ? (entry.supported_parameters.filter((p): p is string => typeof p === \"string\") as string[])\n : undefined;\n const contextWindow =\n typeof entry.context_length === \"number\"\n ? entry.context_length\n : typeof entry.context_window === \"number\"\n ? entry.context_window\n : undefined;\n const inputTypes = normalizeModalities(entry.input_modalities);\n const outputTypes = normalizeModalities(entry.output_modalities);\n return {\n provider: this.config.name,\n id: entry.id,\n displayName: entry.id,\n ...(typeof entry.name === \"string\" ? { name: entry.name } : {}),\n status: \"available\",\n ...(contextWindow !== undefined ? { contextWindow } : {}),\n ...(inputTypes !== undefined ? { inputTypes } : {}),\n ...(outputTypes !== undefined ? { outputTypes } : {}),\n ...(parameters !== undefined\n ? {\n supportsTools: parameters.includes(\"tools\") || parameters.includes(\"tool_choice\"),\n supportsStructuredOutput: parameters.includes(\"response_format\"),\n supportsStreaming: parameters.includes(\"stream\"),\n }\n : {}),\n metadata: {\n ...(typeof entry.owned_by === \"string\" ? { ownedBy: entry.owned_by } : {}),\n ...(typeof entry.created === \"number\" ? { createdAt: entry.created } : {}),\n ...(parameters !== undefined ? { supportedParameters: parameters } : {}),\n },\n };\n }\n\n /** Streaming where the gateway supports it (§11). */\n stream(request: ChatRequest, onChunk: (chunk: ChatStreamChunk) => void): Promise<ChatResponse> {\n return streamChatCompletion(this.config, request, onChunk, this.env);\n }\n\n async healthCheck(): Promise<ProviderStatus> {\n const lastCheckedAt = new Date().toISOString();\n try {\n const started = Date.now();\n const models = await this.listModels();\n return {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: \"healthy\",\n connected: true,\n modelCount: models.length,\n lastCheckedAt,\n message: `Discovered ${models.length} model(s) in ${Date.now() - started}ms.`,\n };\n } catch (error) {\n return {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: inferHealth(error),\n connected: false,\n modelCount: 0,\n lastCheckedAt,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async chat(request: ChatRequest): Promise<ChatResponse> {\n let response: { status: number; body: unknown };\n try {\n response = await requestJson(`${this.config.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: authHeaders(this.config, this.env),\n timeoutMs: this.requestTimeoutMs,\n body: {\n model: request.model,\n messages: request.messages,\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.maxTokens !== undefined ? { max_tokens: request.maxTokens } : {}),\n ...(request.stop !== undefined ? { stop: request.stop } : {}),\n },\n });\n } catch (error) {\n if (error instanceof ProviderError) throw error;\n throw providerTransportError({ provider: this.config.name, operation: \"chat\", cause: error });\n }\n const { status, body } = response;\n\n if (status !== 200) {\n throw providerHttpError({\n provider: this.config.name,\n operation: \"chat\",\n status,\n body,\n ...(status === 404\n ? {\n code: \"MODEL_NOT_FOUND\" as const,\n }\n : {}),\n });\n }\n\n const payload = body as OpenAIChatResponse;\n const choices = Array.isArray(payload.choices) ? payload.choices : [];\n const first = choices[0] as { message?: { content?: unknown }; finish_reason?: unknown } | undefined;\n if (!first || typeof first.message?.content !== \"string\") {\n throw unavailable(this.config, \"Chat completion response had no message content.\", status);\n }\n\n const usage = (payload.usage ?? {}) as {\n prompt_tokens?: unknown;\n completion_tokens?: unknown;\n total_tokens?: unknown;\n };\n\n return {\n model: typeof payload.model === \"string\" ? payload.model : request.model,\n content: first.message.content,\n finishReason: typeof first.finish_reason === \"string\" ? first.finish_reason : undefined,\n usage: {\n promptTokens: typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : undefined,\n completionTokens:\n typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : undefined,\n totalTokens: typeof usage.total_tokens === \"number\" ? usage.total_tokens : undefined,\n },\n raw: body,\n };\n }\n}\n\n/**\n * Streams a chat completion from an OpenAI-compatible SSE endpoint (§11).\n * Emits deltas through `onChunk` and returns the assembled response.\n */\nexport async function streamChatCompletion(\n config: ProviderConfig,\n request: ChatRequest,\n onChunk: (chunk: ChatStreamChunk) => void,\n env: Record<string, string | undefined> = process.env,\n): Promise<ChatResponse> {\n const baseUrl = normalizeBaseUrl(config.baseUrl);\n const timeoutMs = config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...authHeaders(config, env),\n },\n body: JSON.stringify({\n model: request.model,\n messages: request.messages,\n stream: true,\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.maxTokens !== undefined ? { max_tokens: request.maxTokens } : {}),\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw providerTransportError({ provider: config.name, operation: \"stream\", cause: error });\n }\n if (!response.ok) {\n const body: unknown = await response.json().catch(() => undefined);\n throw providerHttpError({ provider: config.name, operation: \"stream\", status: response.status, body });\n }\n if (!response.body) {\n throw providerHttpError({\n provider: config.name,\n operation: \"stream\",\n status: 500,\n body: { error: { message: \"streaming is not supported by this endpoint\" } },\n });\n }\n\n let content = \"\";\n let model = request.model;\n let finishReason: string | undefined;\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n for await (const piece of response.body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(piece, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n newline = buffer.indexOf(\"\\n\");\n if (line.length === 0 || line.startsWith(\":\")) continue;\n const data = line.startsWith(\"data:\") ? line.slice(5).trim() : line;\n if (data === \"[DONE]\") continue;\n let event: Record<string, unknown>;\n try {\n event = JSON.parse(data) as Record<string, unknown>;\n } catch {\n continue; // tolerate non-JSON SSE noise\n }\n if (typeof event.model === \"string\") model = event.model;\n const choices = Array.isArray(event.choices) ? event.choices : [];\n const first = choices[0] as { delta?: { content?: unknown }; finish_reason?: unknown } | undefined;\n const delta = typeof first?.delta?.content === \"string\" ? first.delta.content : \"\";\n if (delta.length > 0) content += delta;\n if (typeof first?.finish_reason === \"string\") finishReason = first.finish_reason;\n onChunk({ delta, ...(finishReason !== undefined ? { finishReason } : {}), raw: event });\n }\n }\n\n return { model, content, ...(finishReason !== undefined ? { finishReason } : {}) };\n}\n\n/** Normalizes provider modality lists (\"text\", [\"text\",\"image\"], …). */\nfunction normalizeModalities(value: unknown): Modality[] | undefined {\n const list = Array.isArray(value) ? value : typeof value === \"string\" ? [value] : undefined;\n if (!list) return undefined;\n const allowed = new Set<Modality>([\"text\", \"image\", \"audio\", \"video\", \"embedding\"]);\n const modalities = list.filter((m): m is Modality => typeof m === \"string\" && allowed.has(m as Modality));\n return modalities.length > 0 ? modalities : undefined;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction extractModelEntries(body: unknown, config: ProviderConfig): OpenAIModelEntry[] {\n if (Array.isArray(body)) return body as OpenAIModelEntry[];\n if (body !== null && typeof body === \"object\" && Array.isArray((body as { data?: unknown }).data)) {\n return (body as { data: OpenAIModelEntry[] }).data;\n }\n throw new ProviderError(\n \"PROVIDER_UNAVAILABLE\",\n `Provider \"${config.name}\" returned an unrecognized model list shape.`,\n { details: { endpoint: \"models\" } },\n );\n}\n\nfunction unavailable(config: ProviderConfig, message: string, status: number): ProviderError {\n return new ProviderError(\"PROVIDER_UNAVAILABLE\", `Provider \"${config.name}\": ${message}`, {\n details: { status },\n });\n}\n\nfunction inferHealth(error: unknown): \"degraded\" | \"unreachable\" {\n const status =\n error instanceof ProviderError && typeof error.details?.status === \"number\"\n ? error.details.status\n : undefined;\n return status !== undefined && status >= 500 ? \"degraded\" : \"unreachable\";\n}\n","/**\n * OmniHilbras provider adapter (§6, Phase 2).\n *\n * OmniHilbras is one provider source among many — always optional (§2: the\n * core runs with zero Hilbras dependencies). The gateway exposes an\n * OpenAI-compatible API surface, so this adapter rides the OpenAI-compatible\n * transport and implements the plan's connect flow on top of it:\n *\n * Connect → Authenticate → Fetch Models → Validate Models → Register\n */\nimport { resolveApiKey } from \"../auth.js\";\nimport { OpenAICompatibleProvider } from \"../openai-compatible/index.js\";\nimport type { ModelRegistry } from \"../../registry/index.js\";\nimport type { ModelInfo } from \"../../types/model.js\";\nimport type { ProviderStatus } from \"../../types/provider.js\";\n\nexport interface OmniHilbrasConnectionResult {\n status: ProviderStatus;\n /** Validated, deduplicated models — registered when a registry was given. */\n models: ModelInfo[];\n /** Model ids that appeared more than once in the gateway's list. */\n duplicates: string[];\n /** Number of models written into the registry (0 when no registry given). */\n registered: number;\n}\n\nexport class OmniHilbrasProvider extends OpenAICompatibleProvider {\n private gateway?: Record<string, unknown>;\n\n override async listModels(): Promise<ModelInfo[]> {\n // Capture gateway-level metadata from the discovery response, then\n // delegate to the shared OpenAI-compatible discovery.\n const raw = await this.rawModelsResponse();\n await this.extractGatewayMetadata(raw);\n const models = await super.listModels();\n return this.gateway\n ? models.map((model) => ({ ...model, metadata: { ...model.metadata, gateway: this.gateway } }))\n : models;\n }\n /**\n * Run the full connect flow. Throws on authentication or transport failure\n * (use healthCheck() for a non-throwing probe).\n */\n /**\n * Gateway metadata reported alongside the model list (gateway version, tier,\n * region…), kept separate from per-model metadata (§11 — provider metadata).\n */\n gatewayMetadata(): Record<string, unknown> | undefined {\n return this.gateway;\n }\n\n protected async extractGatewayMetadata(body: unknown): Promise<void> {\n if (body !== null && typeof body === \"object\") {\n const gateway = (body as Record<string, unknown>).gateway;\n if (gateway !== null && typeof gateway === \"object\") {\n this.gateway = gateway as Record<string, unknown>;\n }\n }\n }\n\n async connectAndRegister(registry?: ModelRegistry): Promise<OmniHilbrasConnectionResult> {\n // Authenticate — throws PROVIDER_AUTH_FAILED when the referenced env var is unset.\n const apiKey = resolveApiKey(this.config);\n\n // Fetch models — throws on transport errors and non-2xx responses.\n const discovered = await this.listModels();\n\n // Validate — deduplicate ids, annotate gateway metadata, force availability.\n const seen = new Set<string>();\n const models: ModelInfo[] = [];\n const duplicates: string[] = [];\n for (const model of discovered) {\n if (seen.has(model.id)) {\n duplicates.push(model.id);\n continue;\n }\n seen.add(model.id);\n models.push({\n ...model,\n provider: this.config.name,\n status: \"available\",\n metadata: { ...model.metadata, gateway: \"omnihilbras\" },\n });\n }\n\n // Register.\n if (registry) {\n for (const model of models) registry.register(model);\n }\n\n const message =\n `Authenticated${apiKey ? \" with API key\" : \" (no API key configured)\"}; ` +\n `validated ${models.length} unique model(s)` +\n (duplicates.length > 0 ? `, skipped ${duplicates.length} duplicate(s)` : \"\") +\n \".\";\n\n const status: ProviderStatus = {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: \"healthy\",\n connected: true,\n modelCount: models.length,\n lastCheckedAt: new Date().toISOString(),\n message,\n };\n\n return { status, models, duplicates, registered: registry ? models.length : 0 };\n }\n}\n","/**\n * Provider factory: builds adapter instances from configuration (§5, §7).\n * Custom and local gateways ride the OpenAI-compatible adapter unless a\n * dedicated one exists.\n */\nimport { OmniNodeError } from \"../errors/index.js\";\nimport type { IChatProvider, ProviderConfig, ProviderType } from \"../types/provider.js\";\nimport { OmniHilbrasProvider } from \"./omnihilbras/index.js\";\nimport { OpenAICompatibleProvider } from \"./openai-compatible/index.js\";\n\n/** Provider types served by the OpenAI-compatible adapter. */\nexport const OPENAI_COMPATIBLE_TYPES: readonly ProviderType[] = [\n \"openai-compatible\",\n \"openrouter\",\n \"local\",\n \"custom\",\n];\n\nexport function createProvider(config: ProviderConfig): IChatProvider {\n if (config.type === \"omnihilbras\") {\n return new OmniHilbrasProvider(config);\n }\n if (OPENAI_COMPATIBLE_TYPES.includes(config.type)) {\n return new OpenAICompatibleProvider(config);\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Provider type \"${config.type}\" has no adapter yet.`);\n}\n","/**\n * Normalized model registry (§8): aggregates models discovered from all\n * configured providers under \"provider:model\" keys.\n */\nimport type { ModelCapabilities, ModelInfo } from \"../types/model.js\";\nimport type { IProvider } from \"../types/provider.js\";\n\nexport interface ModelFilter {\n provider?: string;\n capability?: keyof ModelCapabilities;\n}\n\nexport interface DiscoveryResult {\n provider: string;\n models: ModelInfo[];\n error?: Error;\n}\n\nexport function registryKey(provider: string, id: string): string {\n return `${provider}:${id}`;\n}\n\nexport class ModelRegistry {\n private readonly models = new Map<string, ModelInfo>();\n\n register(model: ModelInfo): void {\n this.models.set(registryKey(model.provider, model.id), model);\n }\n\n get(provider: string, id: string): ModelInfo | undefined {\n return this.models.get(registryKey(provider, id));\n }\n\n list(filter: ModelFilter = {}): ModelInfo[] {\n return [...this.models.values()]\n .filter((model) => (filter.provider ? model.provider === filter.provider : true))\n .filter((model) =>\n filter.capability ? model.capabilities?.[filter.capability] === true : true,\n )\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id));\n }\n\n /** Availability validation (§27 Phase 1): present in the registry and not retired. */\n isAvailable(provider: string, id: string): boolean {\n const model = this.get(provider, id);\n return model !== undefined && (model.status ?? \"available\") === \"available\";\n }\n\n /** Discover models from one provider and register them. */\n async discoverFrom(provider: IProvider): Promise<ModelInfo[]> {\n const discovered = await provider.listModels();\n for (const model of discovered) this.register(model);\n return discovered;\n }\n\n /** Discover from many providers; a failing provider does not abort the rest. */\n async discoverAll(providers: IProvider[]): Promise<DiscoveryResult[]> {\n return Promise.all(\n providers.map(async (provider) => {\n try {\n return {\n provider: provider.config.name,\n models: await this.discoverFrom(provider),\n };\n } catch (error) {\n return {\n provider: provider.config.name,\n models: [],\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n }\n}\n","/**\n * Process adapter (§9): runs CLI agents as child processes and communicates\n * over stdin/stdout, managing the process lifecycle, working directory,\n * environment, exit codes, logs and timeouts.\n *\n * Three input modes (§9, §21):\n * - \"stdin\": the composed task text is written to the agent's stdin.\n * - \"arg\": the composed task text is appended as the last command argument.\n * - \"protocol\": NodeToAgentMessage envelopes as JSON lines on stdin; the\n * agent answers with AgentToNodeMessage JSON lines (REPORT,\n * COMPLETION, ERROR, ...) whose structured payloads are parsed\n * into reports.\n */\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { AgentError } from \"../../errors/index.js\";\nimport { PROTOCOL_V2, ProtocolSession, type QuestionResponder } from \"../../agent-protocol/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\nimport type {\n AgentConfig,\n AgentInfo,\n AgentTaskInput,\n AgentTaskOutput,\n IAgent,\n} from \"../../types/agent.js\";\nimport type { Report } from \"../../types/report.js\";\nimport { validateWorkingDirectory } from \"../cwd.js\";\nimport { buildChildEnv } from \"../env.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\n/** Per-stream byte budget before output is truncated and the agent killed. */\nexport const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\nexport function composeTaskText(input: AgentTaskInput): string {\n const sections: string[] = [`# Objective\\n${input.objective}`];\n if (input.role) {\n const lines = [\"# Role\", `${input.role.name} (${input.role.id})`];\n if (input.role.responsibilities.length > 0) {\n lines.push(\"\", \"Responsibilities:\", ...input.role.responsibilities.map((r) => `- ${r}`));\n }\n if (input.role.expectedOutputs.length > 0) {\n lines.push(\"\", \"Expected outputs:\", ...input.role.expectedOutputs.map((o) => `- ${o}`));\n }\n sections.push(lines.join(\"\\n\"));\n }\n if (input.context) sections.push(`# Context\\n${input.context}`);\n if (input.instruction) sections.push(`# Instruction\\n${input.instruction}`);\n return sections.join(\"\\n\\n\");\n}\n\nfunction buildProtocolMessages(input: AgentTaskInput, agentName: string): string[] {\n // Protocol v2 envelopes with full correlation (roadmap §7.2, §7.4).\n const session = new ProtocolSession({\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n });\n return session.taskMessages(\n input.objective,\n input.role,\n input.context,\n input.instruction,\n );\n}\n\nexport class ProcessAgent implements IAgent {\n readonly config: AgentConfig;\n readonly info: AgentInfo;\n private readonly log: Logger;\n private readonly running = new Map<string, ChildProcess>();\n\n constructor(config: AgentConfig, log: Logger = logger) {\n if (!config.command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${config.name}\" has no command configured.`);\n }\n this.config = config;\n this.log = log.child({ agent: config.name });\n this.info = {\n name: config.name,\n integration: \"process\",\n command: config.command,\n cwd: config.cwd,\n status: \"ready\",\n capabilities: [config.inputMode ?? \"stdin\"],\n };\n }\n\n async run(input: AgentTaskInput): Promise<AgentTaskOutput> {\n const command = this.config.command;\n if (!command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${this.config.name}\" has no command configured.`);\n }\n const mode = this.config.inputMode ?? \"stdin\";\n const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n return new Promise<AgentTaskOutput>((resolve, reject) => {\n // Validate the working directory BEFORE spawning (roadmap §8): never\n // silently fall back to the OmniNode cwd.\n let cwd: string | undefined;\n try {\n cwd = validateWorkingDirectory(this.config.cwd, {\n allowExternal: this.config.allowExternalCwd,\n })?.cwd;\n } catch (error) {\n // Invalid working directory — fail before spawning anything.\n reject(error);\n return;\n }\n\n const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n ...(cwd !== undefined ? { cwd } : {}),\n env: buildChildEnv(this.config),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // Own process group so the whole tree can be terminated together\n // (roadmap §8: no orphaned children).\n ...(process.platform === \"win32\" ? {} : { detached: true }),\n },\n );\n this.running.set(input.taskId, child);\n GLOBAL_RUNNING.add(child);\n installSignalForwarding();\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let outputLimitExceeded = false;\n let settled = false;\n const maxOutputBytes = this.config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process tree.`);\n killTree(child, \"SIGTERM\");\n setTimeout(() => killTree(child, \"SIGKILL\"), KILL_GRACE_MS).unref();\n }, timeoutMs);\n\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n this.running.delete(input.taskId);\n GLOBAL_RUNNING.delete(child);\n finish();\n };\n\n // Output protection (roadmap §8): runaway/binary output is truncated at\n // a byte budget, and a flooding agent is killed rather than allowed to\n // exhaust memory.\n const collect = (into: \"stdout\" | \"stderr\", chunk: Buffer): void => {\n if (outputLimitExceeded) return;\n const text = sanitizeChunk(chunk);\n if (into === \"stdout\") {\n if (stdout.length + text.length > maxOutputBytes) {\n stdout = (stdout + text).slice(0, maxOutputBytes);\n outputLimitExceeded = true;\n this.log.warn(`Agent \"${this.config.name}\" exceeded the ${maxOutputBytes} byte output limit — killing it.`);\n killTree(child, \"SIGKILL\");\n return;\n }\n stdout += text;\n } else {\n if (stderr.length + text.length > maxOutputBytes) {\n stderr = (stderr + text).slice(0, maxOutputBytes);\n return;\n }\n stderr += text;\n }\n };\n child.stdout?.on(\"data\", (chunk: Buffer) => collect(\"stdout\", chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => collect(\"stderr\", chunk));\n\n // Agents that exit without reading stdin raise EPIPE on write — that is\n // not an agent failure, so the stream error is ignored.\n child.stdin?.on(\"error\", () => {});\n if (mode !== \"arg\") {\n const payload =\n mode === \"protocol\"\n ? buildProtocolMessages(input, this.config.name).join(\"\\n\") + \"\\n\"\n : composeTaskText(input) + \"\\n\";\n child.stdin?.write(payload);\n child.stdin?.end();\n }\n\n child.on(\"error\", (error) => {\n settle(() => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${this.config.name}\": command \"${command}\" was not found. Is it installed and on PATH?`,\n { cause: error },\n ),\n );\n return;\n }\n reject(\n new AgentError(\"AGENT_FAILED\", `Agent \"${this.config.name}\" failed to start: ${error.message}.`, {\n cause: error,\n }),\n );\n });\n });\n\n child.on(\"close\", (code, signal) => {\n settle(() => {\n if (timedOut) {\n reject(\n new AgentError(\n \"AGENT_TIMEOUT\",\n `Agent \"${this.config.name}\" timed out after ${timeoutMs}ms and was killed.`,\n {\n details: {\n operation: \"agent.run\",\n agent: this.config.name,\n durationMs: timeoutMs,\n // The process was started and may have performed side\n // effects before being killed — the outcome is unknown,\n // not failed (roadmap §6.3).\n dispatched: true,\n stdout: stdout.slice(0, 4000),\n stderr: stderr.slice(0, 2000),\n },\n },\n ),\n );\n return;\n }\n\n const logs = stderr.trim().length > 0 ? stderr.split(\"\\n\") : undefined;\n if (mode === \"protocol\") {\n // interpretProtocolRun can reject (e.g. protocol violations); throwing\n // inside this event callback would escape the promise entirely.\n try {\n resolve(\n interpretProtocolRun({\n input,\n agentName: this.config.name,\n stdout,\n exitCode: code,\n logs,\n }),\n );\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n const trimmed = stdout.trim();\n resolve({\n taskId: input.taskId,\n status: code === 0 && !outputLimitExceeded ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n ...(outputLimitExceeded\n ? { error: `Agent exceeded the ${maxOutputBytes} byte output limit and was terminated.` }\n : code === 0\n ? {}\n : { error: describeExit(code, signal) }),\n });\n });\n });\n });\n }\n\n /** Ask the agent to stop current work (SIGTERM). */\n async cancel(taskId: string): Promise<void> {\n const child = this.running.get(taskId);\n if (child) killTree(child, \"SIGTERM\");\n }\n\n runningTaskIds(): string[] {\n return [...this.running.keys()];\n }\n}\n\ninterface ProtocolRunInput {\n input: AgentTaskInput;\n agentName: string;\n stdout: string;\n exitCode: number | null;\n logs?: string[];\n responder?: QuestionResponder;\n}\n\nfunction interpretProtocolRun({\n input,\n agentName,\n stdout,\n exitCode,\n logs,\n responder,\n}: ProtocolRunInput): AgentTaskOutput {\n const session = new ProtocolSession(\n {\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n },\n { ...(responder !== undefined ? { responder } : {}) },\n );\n\n // The stream was drained line-by-line already; re-decode deterministically.\n for (const result of session.decoder.push(stdout)) {\n // handled synchronously below via handle(); questions are resolved eagerly\n session.handle(result);\n }\n for (const result of session.decoder.flush()) {\n session.handle(result);\n }\n\n const reports = session.reports\n .flatMap((payload) => (Array.isArray(payload) ? payload : [payload]))\n .map((payload, index) => normalizeReport(payload, input.taskId, agentName, index))\n .filter((report): report is NonNullable<typeof report> => report !== undefined);\n\n const trimmed = stdout.trim();\n const protocolBlock = {\n protocol: session.descriptor?.protocol ?? PROTOCOL_V2,\n legacy: !session.sawV2 && session.descriptor === undefined,\n ...(session.descriptor !== undefined ? { descriptor: session.descriptor } : {}),\n questions: session.questions,\n violations: session.violations.map((v) => `${v.code}: ${v.message}`),\n };\n\n if (session.errorMessage !== undefined) {\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: session.errorMessage,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n };\n }\n\n if (session.descriptor === undefined && session.violations.length > 0 && session.reports.length === 0 && session.completionSummary === undefined) {\n // Nothing usable parsed: protocol violation rather than silent success.\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: `agent produced no valid protocol messages: ${protocolBlock.violations.join(\"; \")}`,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n };\n }\n\n const completed = exitCode === 0 && session.completionSummary !== undefined;\n return {\n taskId: input.taskId,\n status: completed || exitCode === 0 ? (completed ? \"completed\" : \"completed\") : \"failed\",\n summary: session.completionSummary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n ...(exitCode !== 0 ? { error: `Process exited with code ${exitCode ?? \"unknown\"}` } : {}),\n };\n}\n\n/**\n * Every live agent process, so Ctrl-C / SIGTERM on OmniNode reaches the whole\n * tree instead of orphaning children (roadmap §8, signal handling).\n */\nconst GLOBAL_RUNNING = new Set<ChildProcess>();\nlet signalForwardingInstalled = false;\n\nfunction installSignalForwarding(): void {\n if (signalForwardingInstalled) return;\n signalForwardingInstalled = true;\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n for (const child of GLOBAL_RUNNING) {\n killTree(child, \"SIGTERM\");\n }\n });\n }\n}\n\n/** Kills a child and, on POSIX, its whole process group (roadmap §8 tree cleanup). */\nexport function killTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // Group already gone — fall through to direct kill.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // Process already exited.\n }\n}\n\n/** Human-readable exit reason, including signal terminations. */\nexport function describeExit(code: number | null, signal: NodeJS.Signals | null): string {\n if (signal !== null) {\n return signal === \"SIGKILL\"\n ? \"Process was killed (SIGKILL) — usually an external kill or OOM.\"\n : `Process terminated by signal ${signal}.`;\n }\n if (code === null) return \"Process terminated without an exit code.\";\n return `Process exited with code ${code}.`;\n}\n\n/**\n * Decodes a stdout/stderr chunk safely: invalid UTF-8 becomes replacement\n * characters and NUL bytes are stripped, so binary noise cannot poison the\n * protocol decoder or the terminal (roadmap §8, encoding hardening).\n */\nexport function sanitizeChunk(chunk: Buffer): string {\n return [...chunk.toString(\"utf8\")].filter((char) => char.charCodeAt(0) !== 0).join(\"\");\n}\n\n/** Normalizes a loose REPORT payload into a strict Report; drops malformed entries. */\nfunction normalizeReport(\n payload: unknown,\n taskId: string,\n agentName: string,\n index: number,\n): Report | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const raw = payload as Record<string, unknown>;\n if (typeof raw.summary !== \"string\") return undefined;\n return {\n id: typeof raw.id === \"string\" ? raw.id : `${taskId}-report-${index}`,\n taskId: typeof raw.taskId === \"string\" ? raw.taskId : taskId,\n agent: typeof raw.agent === \"string\" ? raw.agent : agentName,\n summary: raw.summary,\n findings: Array.isArray(raw.findings) ? (raw.findings as Report[\"findings\"]) : [],\n recommendations: Array.isArray(raw.recommendations) ? (raw.recommendations as string[]) : [],\n createdAt: typeof raw.createdAt === \"string\" ? raw.createdAt : new Date().toISOString(),\n };\n}\n\nfunction firstLine(text: string, maxLength = 200): string {\n const line = text.split(\"\\n\", 1)[0] ?? text;\n return line.length > maxLength ? `${line.slice(0, maxLength)}…` : line;\n}\n","/**\n * OmniNode Agent Protocol v2 — versioning (roadmap §7.1).\n *\n * Protocol identifiers are namespaced strings so an agent can negotiate the\n * dialect it speaks: `omninode-agent-protocol/2`.\n */\nexport const PROTOCOL_V2 = \"omninode-agent-protocol/2\";\n\n/** Versions this build accepts. v1 is the unversioned dialect shipped with OmniNode 1.x. */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n \"omninode-agent-protocol/1\",\n PROTOCOL_V2,\n];\n\nexport const MAX_MESSAGE_BYTES = 1_048_576; // 1 MiB per message line\n\nexport function isSupportedProtocol(protocol: string): boolean {\n return SUPPORTED_PROTOCOL_VERSIONS.includes(protocol);\n}","/**\n * OmniNode Agent Protocol v2 — message model (roadmap §7.2–§7.4, §7.7).\n *\n * Every message is a JSON line carrying a `ProtocolEnvelope`. All ids are\n * optional for inbound tolerance but OmniNode always emits them, so every\n * message is traceable to agent / task / pipeline / execution / request.\n */\nimport type { Report } from \"../types/report.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\n\n/** Messages OmniNode sends to an agent. */\nexport type ProtocolNodeToAgentType =\n | \"TASK\"\n | \"HELLO_ACK\"\n | \"CONTEXT\"\n | \"INSTRUCTION\"\n | \"RESPONSE\"\n | \"CANCEL\";\n\n/** Messages an agent sends to OmniNode. */\nexport type ProtocolAgentToNodeType =\n | \"HELLO\"\n | \"TASK_REQUEST\"\n | \"TASK_ACCEPTED\"\n | \"TASK_STARTED\"\n | \"STATUS\"\n | \"QUESTION\"\n | \"REPORT\"\n | \"ARTIFACT\"\n | \"COMPLETION\"\n | \"ERROR\"\n | \"CANCELLED\";\n\nexport type ProtocolMessageType = ProtocolNodeToAgentType | ProtocolAgentToNodeType;\n\nexport interface ProtocolEnvelope<T extends ProtocolMessageType = ProtocolMessageType> {\n /** `omninode-agent-protocol/2`. Inbound messages without it are treated as v1. */\n protocol: string;\n /** Unique id of this message. */\n messageId: string;\n /** Id of the request/thread this message belongs to. */\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n /** Execution identity (roadmap §6.5) — ties the message to one attempt. */\n executionId?: string;\n timestamp: string;\n type: T;\n payload: unknown;\n metadata?: Record<string, unknown>;\n}\n\n/** Standard artifact kinds (roadmap §7.7). */\nexport type ArtifactKind =\n | \"file\"\n | \"patch\"\n | \"report\"\n | \"log\"\n | \"screenshot\"\n | \"document\"\n | \"data\";\n\nexport interface ArtifactPayload {\n kind: ArtifactKind;\n /** Path, URL or logical name. */\n ref: string;\n description?: string;\n mediaType?: string;\n bytes?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface QuestionPayload {\n /** Question id to answer. */\n questionId: string;\n question: string;\n /** What kind of answer is expected (free text, file path, options…). */\n expected?: \"text\" | \"path\" | \"choice\";\n options?: string[];\n}\n\nexport interface TaskPayload {\n taskId: string;\n objective: string;\n}\n\nexport interface ReportPayload {\n report: Report | Report[];\n}\n\n/** A question an agent asked during a run, with the answer OmniNode gave (if any). */\nexport interface AskedQuestion {\n questionId: string;\n question: string;\n answer?: string;\n}\n\nexport function newMessageId(prefix = \"msg\"): string {\n const random = Math.random().toString(36).slice(2, 10);\n return `${prefix}-${Date.now().toString(36)}-${random}`;\n}\n\n/** Builds a v2 envelope with ids and timestamp filled in. */\nexport function envelope<T extends ProtocolMessageType>(\n type: T,\n payload: unknown,\n ids: {\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n executionId?: string;\n metadata?: Record<string, unknown>;\n } = {},\n): ProtocolEnvelope<T> {\n return {\n protocol: PROTOCOL_V2,\n messageId: newMessageId(),\n ...(ids.requestId !== undefined ? { requestId: ids.requestId } : {}),\n ...(ids.taskId !== undefined ? { taskId: ids.taskId } : {}),\n ...(ids.agentId !== undefined ? { agentId: ids.agentId } : {}),\n ...(ids.pipelineId !== undefined ? { pipelineId: ids.pipelineId } : {}),\n ...(ids.executionId !== undefined ? { executionId: ids.executionId } : {}),\n timestamp: new Date().toISOString(),\n type,\n payload,\n ...(ids.metadata !== undefined ? { metadata: ids.metadata } : {}),\n };\n}","/**\n * OmniNode Agent Protocol v2 — codec and validation (roadmap §7.5).\n *\n * Decoding NEVER throws: every failure is returned as a typed\n * `ProtocolViolation` with a machine-readable code, so a misbehaving agent\n * can never crash OmniNode.\n */\nimport {\n MAX_MESSAGE_BYTES,\n PROTOCOL_V2,\n isSupportedProtocol,\n} from \"./version.js\";\nimport type { ProtocolEnvelope, ProtocolMessageType } from \"./types.js\";\n\nexport type ProtocolViolationCode =\n | \"INVALID_JSON\"\n | \"NOT_AN_OBJECT\"\n | \"UNKNOWN_TYPE\"\n | \"MISSING_FIELD\"\n | \"UNSUPPORTED_VERSION\"\n | \"OVERSIZED\"\n | \"INVALID_PAYLOAD\";\n\nexport interface ProtocolViolation {\n code: ProtocolViolationCode;\n message: string;\n /** Raw line (truncated) for diagnostics. */\n sample?: string;\n}\n\nexport type DecodeResult =\n | { ok: true; envelope: ProtocolEnvelope; legacy: boolean }\n | { ok: false; error: ProtocolViolation };\n\nconst KNOWN_TYPES = new Set<string>([\n // node → agent\n \"TASK\", \"HELLO_ACK\", \"CONTEXT\", \"INSTRUCTION\", \"RESPONSE\", \"CANCEL\",\n // agent → node\n \"HELLO\", \"TASK_REQUEST\", \"TASK_ACCEPTED\", \"TASK_STARTED\", \"STATUS\",\n \"QUESTION\", \"REPORT\", \"ARTIFACT\", \"COMPLETION\", \"ERROR\", \"CANCELLED\",\n]);\n\nconst PAYLOAD_REQUIRED_TYPES = new Set<string>([\"TASK\", \"REPORT\", \"COMPLETION\", \"ERROR\", \"QUESTION\", \"ARTIFACT\", \"HELLO\"]);\n\n/** Validates one decoded JSON value as a protocol envelope. */\nexport function validateEnvelope(value: unknown, line?: string): DecodeResult {\n const sample = line?.slice(0, 200);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { ok: false, error: { code: \"NOT_AN_OBJECT\", message: \"message must be a JSON object\", ...(sample ? { sample } : {}) } };\n }\n const raw = value as Record<string, unknown>;\n\n // Version negotiation: absent protocol = v1 (OmniNode 1.x agents), else must be supported.\n const protocol = raw.protocol;\n if (protocol === undefined) {\n // legacy v1: requires a bare {type, payload} shape\n const type = raw.type;\n if (typeof type !== \"string\" || !KNOWN_TYPES.has(type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(type)}`, ...(sample ? { sample } : {}) } };\n }\n return {\n ok: true,\n legacy: true,\n envelope: {\n protocol: \"omninode-agent-protocol/1\",\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"legacy\",\n timestamp: new Date().toISOString(),\n type: type as ProtocolMessageType,\n payload: raw.payload,\n },\n };\n }\n if (typeof protocol !== \"string\" || !isSupportedProtocol(protocol)) {\n return {\n ok: false,\n error: { code: \"UNSUPPORTED_VERSION\", message: `unsupported protocol \"${String(protocol)}\"`, ...(sample ? { sample } : {}) },\n };\n }\n\n if (raw.type === undefined) {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"message is missing 'type'\", ...(sample ? { sample } : {}) } };\n }\n if (typeof raw.type !== \"string\" || !KNOWN_TYPES.has(raw.type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(raw.type)}`, ...(sample ? { sample } : {}) } };\n }\n if (raw.timestamp !== undefined && typeof raw.timestamp !== \"string\") {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"'timestamp' must be a string\", ...(sample ? { sample } : {}) } };\n }\n if (PAYLOAD_REQUIRED_TYPES.has(raw.type) && (raw.payload === undefined || raw.payload === null)) {\n return { ok: false, error: { code: \"INVALID_PAYLOAD\", message: `${raw.type} requires a payload`, ...(sample ? { sample } : {}) } };\n }\n\n return {\n ok: true,\n legacy: protocol !== PROTOCOL_V2,\n envelope: {\n protocol,\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"unknown\",\n ...(typeof raw.requestId === \"string\" ? { requestId: raw.requestId } : {}),\n ...(typeof raw.taskId === \"string\" ? { taskId: raw.taskId } : {}),\n ...(typeof raw.agentId === \"string\" ? { agentId: raw.agentId } : {}),\n ...(typeof raw.pipelineId === \"string\" ? { pipelineId: raw.pipelineId } : {}),\n ...(typeof raw.executionId === \"string\" ? { executionId: raw.executionId } : {}),\n timestamp: typeof raw.timestamp === \"string\" ? raw.timestamp : new Date().toISOString(),\n type: raw.type as ProtocolMessageType,\n payload: raw.payload,\n ...(raw.metadata !== null && typeof raw.metadata === \"object\" ? { metadata: raw.metadata as Record<string, unknown> } : {}),\n },\n };\n}\n\n/** Decodes one protocol line (no trailing newline). */\nexport function decodeMessage(line: string, maxBytes = MAX_MESSAGE_BYTES): DecodeResult {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n return { ok: false, error: { code: \"INVALID_JSON\", message: \"empty line\" } };\n }\n if (trimmed.length > maxBytes) {\n return {\n ok: false,\n error: { code: \"OVERSIZED\", message: `message of ${trimmed.length} bytes exceeds the ${maxBytes} byte limit`, sample: trimmed.slice(0, 200) },\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(trimmed);\n } catch (error) {\n return {\n ok: false,\n error: { code: \"INVALID_JSON\", message: error instanceof Error ? error.message : \"invalid JSON\", sample: trimmed.slice(0, 200) },\n };\n }\n return validateEnvelope(value, trimmed);\n}\n\n/** Serializes an envelope to a single JSON line. */\nexport function encodeMessage(envelope: ProtocolEnvelope, maxBytes = MAX_MESSAGE_BYTES): string {\n const line = JSON.stringify(envelope);\n if (line.length > maxBytes) {\n throw new Error(`outbound protocol message of ${line.length} bytes exceeds the ${maxBytes} byte limit`);\n }\n return line;\n}\n\n/**\n * Streaming line decoder for agent stdout. Feed chunks; receive decoded\n * envelopes and violations in order. Survives garbage: a bad line yields a\n * violation and the stream continues.\n */\nexport class ProtocolDecoder {\n private buffer = \"\";\n private readonly maxBytes: number;\n\n constructor(maxBytes = MAX_MESSAGE_BYTES) {\n this.maxBytes = maxBytes;\n }\n\n push(chunk: string): DecodeResult[] {\n this.buffer += chunk;\n const results: DecodeResult[] = [];\n let index = this.buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = this.buffer.slice(0, index);\n this.buffer = this.buffer.slice(index + 1);\n if (line.trim().length > 0) results.push(decodeMessage(line, this.maxBytes));\n index = this.buffer.indexOf(\"\\n\");\n }\n // Guard against an agent emitting an endless line with no newline.\n if (this.buffer.length > this.maxBytes) {\n results.push({\n ok: false,\n error: { code: \"OVERSIZED\", message: `line exceeded ${this.maxBytes} bytes without a newline`, sample: this.buffer.slice(0, 200) },\n });\n this.buffer = \"\";\n }\n return results;\n }\n\n /** Flush any trailing line when the process exits. */\n flush(): DecodeResult[] {\n if (this.buffer.trim().length === 0) {\n this.buffer = \"\";\n return [];\n }\n const result = decodeMessage(this.buffer, this.maxBytes);\n this.buffer = \"\";\n return [result];\n }\n}","/**\n * OmniNode Agent Protocol v2 — handshake (roadmap §7.1).\n *\n * An agent announces itself with HELLO; OmniNode replies with HELLO_ACK.\n * Handshakes are optional for v1-style agents (no HELLO = legacy dialect).\n */\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type ProtocolEnvelope } from \"./types.js\";\n\nexport interface AgentDescriptor {\n /** Protocol the agent speaks. */\n protocol: string;\n name: string;\n version?: string;\n capabilities: string[];\n /** Message types the agent can emit. */\n supports: string[];\n}\n\nexport type HelloResult =\n | { ok: true; descriptor: AgentDescriptor }\n | { ok: false; reason: string };\n\nexport function parseHello(envelopeValue: ProtocolEnvelope): HelloResult {\n if (envelopeValue.type !== \"HELLO\") {\n return { ok: false, reason: `expected HELLO, received ${envelopeValue.type}` };\n }\n const payload = envelopeValue.payload;\n if (payload === null || typeof payload !== \"object\") {\n return { ok: false, reason: \"HELLO payload must be an object\" };\n }\n const p = payload as Record<string, unknown>;\n if (typeof p.name !== \"string\" || p.name.length === 0) {\n return { ok: false, reason: \"HELLO payload is missing 'name'\" };\n }\n return {\n ok: true,\n descriptor: {\n protocol: envelopeValue.protocol,\n name: p.name,\n ...(typeof p.version === \"string\" ? { version: p.version } : {}),\n capabilities: Array.isArray(p.capabilities) ? p.capabilities.filter((c): c is string => typeof c === \"string\") : [],\n supports: Array.isArray(p.supports) ? p.supports.filter((s): s is string => typeof s === \"string\") : [],\n },\n };\n}\n\nexport function buildHello(descriptor: Omit<AgentDescriptor, \"protocol\">): ProtocolEnvelope<\"HELLO\"> {\n return envelope(\"HELLO\", descriptor, { agentId: descriptor.name });\n}\n\nexport function buildHelloAck(descriptor: AgentDescriptor): ProtocolEnvelope<\"HELLO_ACK\"> {\n return envelope(\"HELLO_ACK\", {\n ok: true,\n protocol: PROTOCOL_V2,\n agent: descriptor.name,\n ...(descriptor.version !== undefined ? { agentVersion: descriptor.version } : {}),\n supportedProtocols: [PROTOCOL_V2],\n }, { agentId: descriptor.name });\n}\n","/**\n * OmniNode Agent Protocol v2 — session (roadmap §7.6).\n *\n * A session drives a protocol-mode agent: it emits v2 envelopes with\n * correlation ids, tolerates legacy (unversioned) replies, answers agent\n * questions through a responder callback, and collects reports, artifacts\n * and the completion — never throwing on malformed input.\n */\nimport { decodeMessage, encodeMessage, ProtocolDecoder, type DecodeResult, type ProtocolViolation } from \"./codec.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type AskedQuestion, type ProtocolEnvelope } from \"./types.js\";\nimport { parseHello, buildHelloAck, type AgentDescriptor } from \"./handshake.js\";\nimport { ProtocolError } from \"../errors/index.js\";\n\nexport interface SessionIds {\n requestId: string;\n taskId: string;\n agentId: string;\n pipelineId?: string;\n executionId?: string;\n}\n\nexport interface QuestionResponder {\n (question: { questionId: string; question: string; expected?: string }): Promise<string> | string;\n}\n\nexport class ProtocolSession {\n readonly decoder: ProtocolDecoder;\n private readonly ids: SessionIds;\n private readonly responder: QuestionResponder | undefined;\n readonly violations: ProtocolViolation[] = [];\n readonly questions: AskedQuestion[] = [];\n readonly artifacts: ProtocolEnvelope[\"payload\"][] = [];\n reports: ProtocolEnvelope[\"payload\"][] = [];\n descriptor?: AgentDescriptor;\n completionSummary?: string;\n errorMessage?: string;\n\n constructor(ids: SessionIds, options: { responder?: QuestionResponder; maxBytes?: number } = {}) {\n this.ids = ids;\n this.responder = options.responder;\n this.decoder = new ProtocolDecoder(options.maxBytes);\n }\n\n /** The v2 messages OmniNode sends to open a task (written to the agent's stdin). */\n taskMessages(objective: string, role?: unknown, context?: string, instruction?: string): string[] {\n const ids = this.ids;\n const messages: ProtocolEnvelope[] = [envelope(\"TASK\", { taskId: ids.taskId, objective }, ids)];\n if (role !== undefined) messages.push(envelope(\"CONTEXT\", { role }, ids));\n if (context !== undefined && context.length > 0) messages.push(envelope(\"CONTEXT\", { body: context }, ids));\n if (instruction !== undefined && instruction.length > 0) messages.push(envelope(\"INSTRUCTION\", { text: instruction }, ids));\n return messages.map((m) => encodeMessage(m));\n }\n\n helloAck(descriptor: AgentDescriptor): string {\n return encodeMessage(buildHelloAck(descriptor));\n }\n\n /** Consumes decoded stdout, answering questions as they arrive. */\n async handle(decoded: DecodeResult): Promise<void> {\n if (!decoded.ok) {\n // Agent misbehavior is recorded, never fatal (§7.5).\n this.violations.push(decoded.error);\n return;\n }\n const message = decoded.envelope;\n if (message.protocol === PROTOCOL_V2) this.sawV2 = true;\n if (message.type === \"HELLO\") {\n const hello = parseHello(message);\n if (hello.ok) this.descriptor = hello.descriptor;\n else this.violations.push({ code: \"INVALID_PAYLOAD\", message: `bad HELLO: ${hello.reason}` });\n return;\n }\n if (message.type === \"QUESTION\") {\n await this.answerQuestion(message);\n return;\n }\n if (message.type === \"REPORT\") {\n this.reports.push(message.payload);\n return;\n }\n if (message.type === \"ARTIFACT\") {\n this.artifacts.push(message.payload);\n return;\n }\n if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n this.completionSummary = typeof payload?.summary === \"string\" ? payload.summary : \"\";\n return;\n }\n if (message.type === \"ERROR\") {\n const payload = message.payload as { message?: unknown; code?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"agent reported an error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n this.errorMessage = `Agent error${code}: ${detail}`;\n return;\n }\n if (message.type === \"TASK_ACCEPTED\" || message.type === \"TASK_STARTED\" || message.type === \"STATUS\") {\n // Lifecycle acknowledgements: observed, no action needed by the core.\n return;\n }\n this.violations.push({\n code: \"UNKNOWN_TYPE\",\n message: `unexpected message type ${message.type} from agent`,\n });\n }\n\n private async answerQuestion(message: ProtocolEnvelope): Promise<void> {\n const payload = (message.payload ?? {}) as { questionId?: unknown; question?: unknown; expected?: unknown };\n const questionId = typeof payload.questionId === \"string\" ? payload.questionId : message.messageId;\n const question = typeof payload.question === \"string\" ? payload.question : \"\";\n const expected = typeof payload.expected === \"string\" ? payload.expected : \"text\";\n\n let answer: string | undefined;\n if (this.responder) {\n try {\n answer = await this.responder({ questionId, question, expected });\n } catch (error) {\n this.violations.push({\n code: \"INVALID_PAYLOAD\",\n message: `question responder failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n this.questions.push({ questionId, question, ...(answer !== undefined ? { answer } : {}) });\n // Answer on stdout via the write callback supplied by the caller.\n this.pendingAnswers.push(\n encodeMessage(\n envelope(\"RESPONSE\", { questionId, ...(answer !== undefined ? { body: answer } : {}) }, {\n ...this.ids,\n requestId: message.requestId ?? this.ids.requestId,\n }),\n ),\n );\n }\n\n readonly pendingAnswers: string[] = [];\n /** True once any inbound message carried the v2 protocol field. */\n sawV2 = false;\n}\n\nexport async function decodeStream(session: ProtocolSession, chunk: string): Promise<string[]> {\n const decoded = session.decoder.push(chunk);\n for (const result of decoded) {\n await session.handle(result);\n }\n return session.pendingAnswers.splice(0);\n}\n\nexport function requireCompletion(session: ProtocolSession): void {\n if (session.errorMessage !== undefined) {\n throw new ProtocolError(session.errorMessage);\n }\n}\n\nexport { decodeMessage };","/**\n * Working-directory validation for agent processes (roadmap §8): existence,\n * directory-ness, access, path normalization and project boundaries.\n */\nimport { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { AgentError } from \"../errors/index.js\";\n\nexport interface CwdValidation {\n /** Normalized absolute path. */\n cwd: string;\n /** True when the directory sits outside the project root (project boundary). */\n outsideProject: boolean;\n}\n\nexport function validateWorkingDirectory(\n cwd: string | undefined,\n options: { projectRoot?: string; allowExternal?: boolean } = {},\n): CwdValidation | undefined {\n if (!cwd) return undefined;\n\n const normalized = isAbsolute(cwd) ? resolve(cwd) : resolve(process.cwd(), cwd);\n let stats;\n try {\n stats = statSync(normalized);\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" does not exist or is not accessible.`,\n { cause: error, details: { cwd: normalized } },\n );\n }\n if (!stats.isDirectory()) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Working directory \"${normalized}\" is not a directory.`, {\n details: { cwd: normalized },\n });\n }\n // Access check: attempt to list it.\n try {\n statSync(resolve(normalized, \".\"));\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is not accessible.`,\n { cause: error },\n );\n }\n\n const projectRoot = resolve(options.projectRoot ?? process.cwd());\n const rel = relative(projectRoot, normalized);\n const outsideProject = rel.startsWith(\"..\") || isAbsolute(rel);\n if (outsideProject && options.allowExternal !== true) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is outside the project root \"${projectRoot}\". ` +\n `Set allow_external_cwd: true on the agent to permit this.`,\n { details: { cwd: normalized, projectRoot } },\n );\n }\n return { cwd: normalized, outsideProject };\n}","/**\n * Agent environment policies (roadmap §8, Environment Isolation).\n *\n * Four explicit policies, so operators decide exactly what an agent can see:\n * - `inherit` (default, backwards compatible): the full parent environment\n * - `allowlist`: only the allow-listed variables (+ PATH/HOME)\n * - `denylist`: the parent environment minus the deny-listed variables\n * - `explicit`: nothing from the parent; only PATH/HOME and `env`\n *\n * The v1 boolean `inherit_env: false` is still honored and maps to `explicit`.\n */\nimport type { AgentConfig } from \"../types/agent.js\";\n\nexport type EnvPolicy = \"inherit\" | \"allowlist\" | \"denylist\" | \"explicit\";\n\n/** Variables always provided so shells and runtimes keep working. */\nconst BASELINE_KEYS = [\"PATH\", \"HOME\"] as const;\n\nexport function resolveEnvPolicy(config: Partial<AgentConfig>): EnvPolicy {\n if (config.envPolicy !== undefined) return config.envPolicy;\n if (config.inheritEnv === false) return \"explicit\"; // v1 compatibility\n return \"inherit\";\n}\n\nexport function buildChildEnv(config: AgentConfig): NodeJS.ProcessEnv {\n const configured = config.env ?? {};\n const policy = resolveEnvPolicy(config);\n\n if (policy === \"inherit\") {\n return { ...process.env, ...configured };\n }\n\n const base: NodeJS.ProcessEnv = {};\n for (const key of BASELINE_KEYS) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n\n switch (policy) {\n case \"explicit\":\n return { ...base, ...configured };\n case \"allowlist\": {\n const allowed: NodeJS.ProcessEnv = { ...base };\n for (const key of config.envAllowlist ?? []) {\n const value = process.env[key];\n if (value !== undefined) allowed[key] = value;\n }\n return { ...allowed, ...configured };\n }\n case \"denylist\": {\n const denied = new Set((config.envDenylist ?? []).map((k) => k.toUpperCase()));\n const filtered: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (denied.has(key.toUpperCase())) continue;\n filtered[key] = value;\n }\n return { ...filtered, ...configured };\n }\n }\n}","/**\n * Agent adapter registry (roadmap §8, Native Adapters).\n *\n * New integration styles (native/API-level agents) plug in here without\n * changing OmniNode core: register an `IAgentAdapter` and `createAgent`\n * consults the registry before falling back to the process adapter.\n */\nimport { AgentError } from \"../errors/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\n\nexport interface IAgentAdapter {\n /** Integration type this adapter serves, e.g. \"native\" or \"process\". */\n readonly integration: string;\n create(config: AgentConfig): IAgent;\n}\n\nexport class AgentAdapterRegistry {\n private readonly adapters = new Map<string, IAgentAdapter>();\n\n register(adapter: IAgentAdapter): void {\n this.adapters.set(adapter.integration, adapter);\n }\n\n get(integration: string): IAgentAdapter | undefined {\n return this.adapters.get(integration);\n }\n\n list(): IAgentAdapter[] {\n return [...this.adapters.values()];\n }\n\n create(config: AgentConfig): IAgent {\n const adapter = this.get(config.integration);\n if (!adapter) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `No agent adapter registered for integration \"${config.integration}\". ` +\n `Registered: ${[...this.adapters.keys()].join(\", \") || \"(none)\"}.`,\n );\n }\n return adapter.create(config);\n }\n}\n\n/** Process-level adapter — the built-in CLI integration. */\nexport class ProcessAgentAdapter implements IAgentAdapter {\n readonly integration = \"process\";\n\n constructor(private readonly factory: (config: AgentConfig) => IAgent) {}\n\n create(config: AgentConfig): IAgent {\n return this.factory(config);\n }\n}","/** Agent registry (§10): the set of agents connected to OmniNode. */\nimport type { IAgent } from \"../types/agent.js\";\n\nexport class AgentRegistry {\n private readonly agents = new Map<string, IAgent>();\n\n register(agent: IAgent): void {\n this.agents.set(agent.info.name, agent);\n }\n\n get(name: string): IAgent | undefined {\n return this.agents.get(name);\n }\n\n list(): IAgent[] {\n return [...this.agents.values()].sort((a, b) => a.info.name.localeCompare(b.info.name));\n }\n}\n","/**\n * Agent factory (§9–§10): builds adapter instances from configuration.\n * \"cli\" agent configs are mapped to the process integration by the loader.\n */\nimport type { AppConfig } from \"../config/index.js\";\nimport { OmniNodeError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\nimport { ProcessAgent } from \"./process/index.js\";\nimport { AgentRegistry } from \"./registry.js\";\nimport { AgentAdapterRegistry, ProcessAgentAdapter } from \"./adapters.js\";\n\n/**\n * Registry consulted first so native/API-level integrations plug in without\n * touching core (roadmap §8, Native Adapters).\n */\nexport const defaultAgentAdapters = new AgentAdapterRegistry();\ndefaultAgentAdapters.register(new ProcessAgentAdapter((config) => new ProcessAgent(config)));\n\nexport function createAgent(config: AgentConfig, adapters: AgentAdapterRegistry = defaultAgentAdapters): IAgent {\n const registered = adapters.get(config.integration);\n if (registered) return registered.create(config);\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `No native adapter is registered for \"${config.name}\". Register an IAgentAdapter ` +\n `(createAgent(config, adapters)) or use input over stdin/stdout (type \"cli\").`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\n\nexport { AgentAdapterRegistry } from \"./adapters.js\";\nexport type { IAgentAdapter } from \"./adapters.js\";\n\n/** Builds an agent registry from the project configuration, skipping agents that fail to construct. */\nexport function buildAgentRegistry(config: AppConfig, log: Logger = logger): AgentRegistry {\n const registry = new AgentRegistry();\n for (const agentConfig of config.project.agents) {\n try {\n registry.register(createAgent(agentConfig));\n } catch (error) {\n log.warn(\n `Skipping agent \"${agentConfig.name}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return registry;\n}\n","/** Role registry (§11): the set of roles available for task assignment. */\nimport type { AppConfig } from \"../config/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\n\nexport class RoleRegistry {\n private readonly roles = new Map<string, RoleDefinition>();\n\n register(role: RoleDefinition): void {\n this.roles.set(role.id, role);\n }\n\n registerAll(roles: RoleDefinition[]): void {\n for (const role of roles) this.register(role);\n }\n\n get(id: string): RoleDefinition | undefined {\n return this.roles.get(id);\n }\n\n list(): RoleDefinition[] {\n return [...this.roles.values()].sort((a, b) => a.id.localeCompare(b.id));\n }\n}\n\n/** Builds a role registry from the project configuration. */\nexport function buildRoleRegistry(config: AppConfig): RoleRegistry {\n const registry = new RoleRegistry();\n registry.registerAll(config.project.roles);\n return registry;\n}\n","/**\n * Shared JSON file persistence (v2 Phase 12 — Persistence Layer).\n *\n * Guarantees:\n * - **Atomic writes**: temp file → fsync → rename → directory fsync, so a\n * crash never leaves a half-written store.\n * - **Corruption detection**: unparseable files are *quarantined* (renamed,\n * never deleted) and the store continues empty.\n * - **Schema versioning**: documents carry `schemaVersion`; v1 documents are\n * migrated on read, future versions are refused rather than misread.\n */\nimport { open, mkdir, readFile, rename, stat } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\n/** Current on-disk schema version. */\nexport const SCHEMA_VERSION = 2;\n\nexport interface JsonDocument<T> {\n schemaVersion?: number;\n items: T[];\n}\n\nexport type DocumentState =\n | { status: \"missing\" }\n | { status: \"empty\" }\n | { status: \"v1-legacy\" }\n | { status: \"current\"; schemaVersion: number; count: number }\n | { status: \"future\"; schemaVersion: number }\n | { status: \"corrupt\"; detail: string };\n\nexport interface JsonFileStoreOptions {\n directory?: string;\n fileName: string;\n /** Schema version to write (defaults to the current version). */\n schemaVersion?: number;\n /** Called when a persisted file is corrupt (after quarantine). */\n onCorrupt?: (path: string, error: unknown) => void;\n /** Disable file moves (used by dry runs / tests that inspect in place). */\n quarantine?: boolean;\n}\n\n/** Durably writes a file: temp → fsync → rename → directory fsync. */\nexport async function writeFileAtomic(target: string, contents: string): Promise<void> {\n const tmp = `${target}.tmp`;\n await mkdir(dirname(target), { recursive: true });\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(contents, \"utf8\");\n await handle.sync(); // flush data before the rename becomes visible\n } finally {\n await handle.close();\n }\n await rename(tmp, target);\n // Sync the directory entry so the rename itself survives a crash.\n try {\n const dir = await open(dirname(target), \"r\");\n try {\n await dir.sync();\n } finally {\n await dir.close();\n }\n } catch {\n // Directory fsync is unsupported on some platforms — the rename is still atomic.\n }\n}\n\n/** Reads and classifies a persisted document without modifying it. */\nexport async function inspectDocument(path: string): Promise<DocumentState> {\n let raw: string;\n try {\n await stat(path);\n } catch {\n return { status: \"missing\" };\n }\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n return { status: \"corrupt\", detail: `unreadable: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (raw.trim().length === 0) return { status: \"empty\" };\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return { status: \"corrupt\", detail: error instanceof Error ? error.message : \"invalid JSON\" };\n }\n if (Array.isArray(parsed)) return { status: \"v1-legacy\" }; // v1 stored bare arrays\n if (parsed === null || typeof parsed !== \"object\") return { status: \"corrupt\", detail: \"not an object\" };\n const doc = parsed as JsonDocument<unknown>;\n if (!Array.isArray(doc.items)) return { status: \"corrupt\", detail: \"missing items array\" };\n const version = typeof doc.schemaVersion === \"number\" ? doc.schemaVersion : 1;\n if (version > SCHEMA_VERSION) return { status: \"future\", schemaVersion: version };\n if (version < SCHEMA_VERSION) return { status: \"v1-legacy\" };\n return { status: \"current\", schemaVersion: version, count: doc.items.length };\n}\n\n/** Reads a document, migrating v1 shapes and quarantining corruption. */\nexport async function readDocument<T>(\n path: string,\n onCorrupt?: (path: string, error: unknown) => void,\n quarantine = true,\n): Promise<T[]> {\n const state = await inspectDocument(path);\n if (state.status === \"missing\" || state.status === \"empty\") return [];\n if (state.status === \"future\") {\n const error = new Error(\n `${path} was written by a newer OmniNode (schema v${state.schemaVersion} > v${SCHEMA_VERSION})`,\n );\n onCorrupt?.(path, error);\n return [];\n }\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n onCorrupt?.(path, error);\n return [];\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as T[]; // v1 legacy: bare array\n return (parsed as JsonDocument<T>).items ?? [];\n } catch (error) {\n // Preserve the damaged file for inspection instead of overwriting it.\n if (quarantine) {\n const quarantinePath = `${path}.corrupt-${Date.now()}`;\n try {\n await rename(path, quarantinePath);\n logger.child({ component: \"persistence\" }).warn(\n `Quarantined unreadable store file ${path} → ${quarantinePath}`,\n );\n } catch {\n // Quarantine is best effort.\n }\n }\n onCorrupt?.(path, error);\n return [];\n }\n}\n\nexport class JsonFileStore<T> {\n private readonly filePath: string;\n private readonly schemaVersion: number;\n private readonly onCorrupt?: (path: string, error: unknown) => void;\n private readonly quarantine: boolean;\n private readonly log: Logger;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(options: JsonFileStoreOptions) {\n this.filePath = `${options.directory ?? `${process.cwd()}/.omninode`}/${options.fileName}`;\n this.schemaVersion = options.schemaVersion ?? SCHEMA_VERSION;\n this.onCorrupt = options.onCorrupt;\n this.quarantine = options.quarantine ?? true;\n this.log = logger.child({ component: \"persistence\", file: options.fileName });\n }\n\n get path(): string {\n return this.filePath;\n }\n\n /** All items, or [] when missing/migrated-from-v1/corrupt. */\n protected async readAll(): Promise<T[]> {\n return readDocument<T>(this.filePath, this.onCorrupt, this.quarantine);\n }\n\n protected async writeAll(items: T[]): Promise<void> {\n const document: JsonDocument<T> = { schemaVersion: this.schemaVersion, items };\n await writeFileAtomic(this.filePath, `${JSON.stringify(document, null, 2)}\\n`);\n }\n\n /** Serializes an async operation against this file. */\n protected synchronized<R>(operation: () => Promise<R>): Promise<R> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /** Read-modify-write helper: applies `mutate` to the current items. */\n protected async mutate<R>(mutate: (items: T[]) => Promise<[T[], R]> | [T[], R]): Promise<R> {\n return this.synchronized(async () => {\n const items = await this.readAll();\n const [next, result] = await mutate(items);\n await this.writeAll(next);\n return result;\n });\n }\n}\n","/**\n * Task persistence (§4.1 — execution state). The store is replaceable\n * (§2 — Modular); the default implementation is a local JSON file so\n * OmniNode stays local-first (§25).\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Task, TaskStatus } from \"../types/task.js\";\n\nexport interface TaskStoreFilter {\n status?: TaskStatus;\n project?: string;\n}\n\nexport interface TaskStore {\n save(task: Task): Promise<void>;\n get(id: string): Promise<Task | undefined>;\n list(filter?: TaskStoreFilter): Promise<Task[]>;\n}\n\nexport class FileTaskStore extends JsonFileStore<Task> implements TaskStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"tasks.json\" });\n }\n\n save(task: Task): Promise<void> {\n return this.mutate((tasks) => {\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n return [tasks, undefined];\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n const tasks = await this.readAll();\n return tasks.find((t) => t.id === id);\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n const tasks = await this.readAll();\n return tasks\n .filter((task) => (filter.status ? task.status === filter.status : true))\n .filter((task) => (filter.project ? task.project === filter.project : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/**\n * Task engine (§13, §27 Phase 4): owns the task lifecycle — create, queue,\n * run, cancel — validates role/agent assignment against the registries and\n * persists every transition through the task store.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { AgentError, TaskError } from \"../errors/index.js\";\nimport type { AuditAction, AuditSink } from \"../audit/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type {\n ExecutionRecord,\n Task,\n TaskContext,\n TaskResult,\n TaskStatus,\n} from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\n/**\n * Strict state machine (roadmap §6.2). Invalid transitions are rejected —\n * engines never mutate state directly.\n *\n * created ──▶ queued ──▶ running ──┬─▶ completed\n * │ │ │ ├─▶ failed\n * │ │ │ ├─▶ timed_out (no side effects possible)\n * └───────────┴─────────┴────────┼─▶ unknown (outcome unprovable — e.g. killed after dispatch)\n * ├─▶ cancelled\n * └─▶ partially_completed (fan-out where some units succeeded)\n */\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"timed_out\", \"unknown\", \"cancelled\", \"partially_completed\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n // failed → running is the only re-entry: bounded automatic retry (§6.4).\n failed: [\"running\"],\n timed_out: [],\n cancelled: [],\n unknown: [],\n partially_completed: [],\n};\n\n/**\n * Error codes safe to retry automatically: a transient agent crash before any\n * report was produced. Timeouts/unknown outcomes are NEVER auto-retried\n * because the agent may already have performed side effects (roadmap §6.4).\n */\nconst RETRYABLE_ERROR_CODES: readonly string[] = [\"AGENT_FAILED\"];\nconst EXECUTION_HISTORY_LIMIT = 10;\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\n}\n\nexport interface RunTaskOptions {\n /** Total attempts (1 = no automatic retry). Retries apply to retryable errors only. */\n maxAttempts?: number;\n /** Linear backoff base in ms: waits backoffMs × attempt between attempts. */\n retryBackoffMs?: number;\n}\n\nexport interface TaskEngineOptions {\n agents: AgentRegistry;\n roles: RoleRegistry;\n store: TaskStore;\n /** When present, tasks gather relevant memory before running and record outcomes after (§20). */\n memory?: MemoryService;\n /** When present, task lifecycle transitions are appended to the audit log (§24). */\n audit?: AuditSink;\n log?: Logger;\n}\n\nexport class TaskEngine {\n private readonly log: Logger;\n\n constructor(private readonly options: TaskEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"tasks\" });\n }\n\n get store(): TaskStore {\n return this.options.store;\n }\n\n async create(input: CreateTaskInput): Promise<Task> {\n if (!input.objective || input.objective.trim().length === 0) {\n throw new TaskError(\"TASK_INVALID\", \"Task objective must not be empty.\");\n }\n if (input.role && !this.options.roles.get(input.role)) {\n throw new TaskError(\"TASK_INVALID\", \n `Role \"${input.role}\" is not defined. Add it under project.roles in omninode.yaml.`,\n );\n }\n if (input.agent && !this.options.agents.get(input.agent)) {\n throw new TaskError(\"TASK_INVALID\", \n `Agent \"${input.agent}\" is not registered. Add it with \\`omninode agent add\\`.`,\n );\n }\n\n const now = new Date().toISOString();\n const task: Task = {\n id: generateTaskId(),\n objective: input.objective.trim(),\n status: \"created\",\n attempt: 0,\n createdAt: now,\n updatedAt: now,\n ...(input.project !== undefined ? { project: input.project } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n ...(input.agent !== undefined ? { agent: input.agent } : {}),\n ...(input.context !== undefined ? { context: input.context } : {}),\n };\n await this.options.store.save(task);\n this.log.info(`Created task ${task.id}.`);\n await this.audit(\"task.created\", task.id, { objective: task.objective, project: task.project });\n return task;\n }\n\n async queue(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n return this.transition(task, \"queued\");\n }\n\n /** Runs the task through its assigned agent and records the result.\n * `maxAttempts` enables bounded automatic retries of *retryable* errors\n * with linear backoff; unknown/timed_out outcomes are never auto-retried. */\n async run(id: string, options: RunTaskOptions = {}): Promise<Task> {\n const task = await this.mustGet(id);\n if (task.status !== \"created\" && task.status !== \"queued\") {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be run.`);\n }\n if (!task.agent) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} has no agent assigned. Re-create it with --agent.`);\n }\n const agent = this.options.agents.get(task.agent);\n if (!agent) {\n throw new TaskError(\"TASK_INVALID\", `Agent \"${task.agent}\" is not registered anymore.`);\n }\n const role = task.role ? this.options.roles.get(task.role) : undefined;\n\n this.log.info(`Running task ${task.id} on agent \"${task.agent}\".`);\n\n // §20: relevant memory is gathered before the agent receives context.\n let background = task.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: task.objective,\n ...(task.role ? { role: task.role } : {}),\n ...(task.project ? { project: task.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n const maxAttempts = Math.max(1, options.maxAttempts ?? 1);\n const backoffMs = options.retryBackoffMs ?? 0;\n\n let current = task;\n for (let i = 0; i < maxAttempts; i += 1) {\n // Attempt numbers are cumulative for the task (roadmap §6.5).\n const attempt = current.attempt + 1;\n const executionId = `exec-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n const startedAt = new Date().toISOString();\n current = await this.transition(current, \"running\", { attempt });\n\n let output;\n let thrown: unknown;\n try {\n output = await agent.run({\n taskId: current.id,\n objective: current.objective,\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n thrown = error;\n }\n\n const finishedAt = new Date().toISOString();\n if (thrown !== undefined || output === undefined) {\n const outcome = classifyThrown(thrown);\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n const retryable =\n outcome === \"failed\" &&\n RETRYABLE_ERROR_CODES.includes(errorCode(thrown)) &&\n i < maxAttempts - 1;\n current = await this.transition(current, outcome, {\n attempt,\n lastError: message,\n execution: {\n executionId,\n attempt,\n startedAt,\n finishedAt,\n outcome,\n error: message,\n },\n });\n this.log.warn(`Task ${current.id} attempt ${attempt} → ${outcome}: ${message}`);\n if (retryable) {\n if (backoffMs > 0) await sleep(backoffMs * attempt);\n continue;\n }\n if (this.options.memory) await this.options.memory.recordTaskOutcome(current);\n return current;\n }\n\n // The task may have been cancelled while the agent was finishing —\n // respect the terminal state instead of forcing a completed transition.\n const currentState = await this.options.store.get(current.id);\n if (currentState?.status === \"cancelled\") {\n current = currentState;\n break;\n }\n\n const result: TaskResult = {\n ...(output.summary !== undefined ? { summary: output.summary } : {}),\n ...(output.reports !== undefined && output.reports.length > 0 ? { reports: output.reports } : {}),\n // Keep the verbatim output (bounded) for report extraction and audit.\n ...(output.rawOutput !== undefined && output.rawOutput.length > 0\n ? { rawOutput: output.rawOutput.slice(0, 10_000) }\n : {}),\n ...(output.error !== undefined ? { error: output.error } : {}),\n finishedAt,\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n current = await this.transition(current, finalStatus, {\n attempt,\n result,\n execution: { executionId, attempt, startedAt, finishedAt, outcome: finalStatus },\n });\n this.log.info(`Task ${current.id} finished: ${finalStatus}.`);\n break;\n }\n\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(current);\n }\n return current;\n }\n\n async cancel(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n if (!ALLOWED_TRANSITIONS[task.status].includes(\"cancelled\")) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be cancelled.`);\n }\n if (task.agent) {\n const agent = this.options.agents.get(task.agent);\n await agent?.cancel?.(task.id);\n }\n return this.transition(task, \"cancelled\");\n }\n\n /** Error recovery: reset a failed/cancelled/unknown/timed_out task so it can run again. */\n async retry(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n const retryableStates: TaskStatus[] = [\"failed\", \"cancelled\", \"unknown\", \"timed_out\"];\n if (!retryableStates.includes(task.status)) {\n throw new TaskError(\n \"TASK_INVALID\",\n `Only failed, timed out, unknown or cancelled tasks can be retried — task ${id} is \"${task.status}\".`,\n );\n }\n const { result: _discarded, ...rest } = task;\n const reset: Task = {\n ...rest,\n status: \"created\",\n updatedAt: new Date().toISOString(),\n };\n await this.options.store.save(reset);\n await this.audit(\"task.retry\", id, { from: task.status });\n this.log.info(`Task ${id} reset for retry.`);\n return reset;\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.options.store.get(id);\n }\n\n async list(filter?: TaskStoreFilter): Promise<Task[]> {\n return this.options.store.list(filter);\n }\n\n private async mustGet(id: string): Promise<Task> {\n const task = await this.options.store.get(id);\n if (!task) {\n throw new TaskError(\"TASK_NOT_FOUND\", `Task \"${id}\" does not exist in this project's task store.`);\n }\n return task;\n }\n\n private async transition(\n task: Task,\n to: TaskStatus,\n extra: { result?: TaskResult; attempt?: number; lastError?: string; execution?: ExecutionRecord } = {},\n ): Promise<Task> {\n const allowed = ALLOWED_TRANSITIONS[task.status] ?? [];\n if (!allowed.includes(to)) {\n throw new TaskError(\"TASK_INVALID\", `Task ${task.id} cannot move from \"${task.status}\" to \"${to}\".`);\n }\n const executions = extra.execution\n ? [...(task.executions ?? []), extra.execution].slice(-EXECUTION_HISTORY_LIMIT)\n : task.executions;\n const updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.attempt !== undefined ? { attempt: extra.attempt } : {}),\n ...(extra.lastError !== undefined ? { lastError: extra.lastError } : {}),\n ...(executions !== undefined ? { executions } : {}),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n await this.audit(`task.${to === \"queued\" ? \"queued\" : to}` as AuditAction, updated.id, {\n from: task.status,\n });\n return updated;\n }\n\n private async audit(action: AuditAction, id: string, detail?: Record<string, unknown>): Promise<void> {\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action,\n id,\n ...(detail !== undefined ? { detail } : {}),\n });\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nfunction errorCode(error: unknown): string {\n return (error as { code?: string } | undefined)?.code ?? \"\";\n}\n\n/**\n * Classifies a thrown adapter error into a terminal state.\n *\n * §6.3: a timeout is NOT assumed to be a failure. If the operation was\n * dispatched, the remote side may have completed it, so the outcome is\n * `unknown`. Only a timeout provably raised *before* dispatch becomes\n * `timed_out`.\n */\nfunction classifyThrown(error: unknown): \"failed\" | \"timed_out\" | \"unknown\" {\n if (error instanceof AgentError && error.code === \"AGENT_TIMEOUT\") {\n const dispatched = (error.details as { dispatched?: unknown } | undefined)?.dispatched;\n return dispatched === false ? \"timed_out\" : \"unknown\";\n }\n return \"failed\";\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Audit logging (§24): append-only JSONL record of lifecycle events\n * (task/pipeline transitions) in the project's .omninode directory. Useful\n * for compliance reviews and debugging multi-agent runs.\n */\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport type AuditAction =\n | \"task.created\"\n | \"task.queued\"\n | \"task.running\"\n | \"task.completed\"\n | \"task.failed\"\n | \"task.cancelled\"\n | \"task.retry\"\n | \"pipeline.run.started\"\n | \"pipeline.run.finished\"\n | \"plan.generated\"\n | \"memory.context.gathered\"\n | \"memory.outcome.recorded\";\n\nexport interface AuditEvent {\n at: string;\n action: AuditAction;\n project?: string;\n id?: string;\n actor?: string;\n detail?: Record<string, unknown>;\n}\n\nexport interface AuditSink {\n record(event: AuditEvent): Promise<void>;\n}\n\n/** Append-only JSONL sink. Failures are logged, never propagated. */\nexport class FileAuditLog implements AuditSink {\n private readonly filePath: string;\n private readonly log: Logger;\n\n constructor(directory = `${process.cwd()}/.omninode`, log: Logger = logger) {\n this.filePath = `${directory}/audit.jsonl`;\n this.log = log.child({ component: \"audit\" });\n }\n\n async record(event: AuditEvent): Promise<void> {\n try {\n await mkdir(dirname(this.filePath), { recursive: true });\n // fsync the append so audit entries survive a crash (roadmap §12 durability).\n const { open } = await import(\"node:fs/promises\");\n const handle = await open(this.filePath, \"a\");\n try {\n await handle.appendFile(`${JSON.stringify(event)}\\n`, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n } catch (error) {\n this.log.warn(\n `Audit write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Recent events, oldest first; used by the CLI. */\n async recent(limit = 20): Promise<AuditEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf8\");\n } catch {\n return [];\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as AuditEvent;\n } catch {\n return undefined;\n }\n })\n .filter((event): event is AuditEvent => event !== undefined);\n return events.slice(-limit);\n }\n}","/**\n * Shared memory-contract helpers (roadmap §12). Adapters implement\n * `retrieve` / `store`; these helpers supply the defaults for `search`,\n * `metadata` and the v1 `query` / `write` aliases, so the contract is\n * defined once.\n */\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\n/** Free-text search defaults to a relevance retrieve. */\nexport function defaultSearch(\n provider: Pick<IMemoryProvider, \"retrieve\">,\n text: string,\n options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {},\n): Promise<MemoryEntry[]> {\n return provider.retrieve({\n text,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n}\n\nexport function defaultMetadata(\n name: string,\n options: {\n capabilities?: MemoryProviderMetadata[\"capabilities\"];\n relevanceRanking?: boolean;\n backend?: Record<string, unknown>;\n } = {},\n): MemoryProviderMetadata {\n return {\n name,\n capabilities: options.capabilities ?? [\"retrieve\", \"store\", \"search\"],\n relevanceRanking: options.relevanceRanking ?? false,\n ...(options.backend !== undefined ? { backend: options.backend } : {}),\n };\n}","/**\n * Local file-based memory provider: the default implementation so persistent\n * memory works out of the box, locally (§25), with no external service.\n * Relevance is scored by keyword overlap and tag matches — deterministic and\n * dependency-free.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"this\", \"that\", \"from\", \"into\", \"was\", \"were\",\n \"have\", \"has\", \"had\", \"are\", \"but\", \"not\", \"you\", \"his\", \"her\", \"its\",\n \"their\", \"them\", \"then\", \"than\", \"when\", \"what\", \"which\", \"will\", \"would\",\n \"been\", \"were\", \"also\", \"because\", \"about\", \"after\", \"before\",\n]);\n\nexport function keywords(text: string): Set<string> {\n return new Set(\n (text ?? \"\")\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 4 && !STOPWORDS.has(t)),\n );\n}\n\nfunction relevanceScore(queryKeywords: Set<string>, entry: MemoryEntry): number {\n if (queryKeywords.size === 0) return 0;\n const entryKeywords = keywords(`${entry.content} ${entry.key}`);\n let overlap = 0;\n for (const keyword of queryKeywords) {\n if (entryKeywords.has(keyword)) overlap += 1;\n }\n let tagMatches = 0;\n for (const tag of entry.tags ?? []) {\n if (queryKeywords.has(tag.toLowerCase())) tagMatches += 1;\n }\n return overlap * 2 + tagMatches * 1.5;\n}\n\nexport class LocalMemoryProvider extends JsonFileStore<MemoryEntry> implements IMemoryProvider {\n readonly name = \"local\";\n\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"memory.json\" });\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"json-file\", deterministicScoring: true },\n });\n }\n\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(this, text, options);\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const entries = await this.readAll();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : true))\n .filter((entry) => (query.category ? entry.category === query.category : true))\n .filter((entry) =>\n query.tags && query.tags.length > 0\n ? query.tags.every((tag) => (entry.tags ?? []).includes(tag))\n : true,\n );\n\n if (!query.text || query.text.trim().length === 0) {\n return filtered\n .sort((a, b) => (b.updatedAt ?? b.createdAt ?? \"\").localeCompare(a.updatedAt ?? a.createdAt ?? \"\"))\n .slice(0, query.limit ?? 10);\n }\n\n const queryKeywords = keywords(query.text);\n return filtered\n .map((entry) => ({ entry, score: relevanceScore(queryKeywords, entry) }))\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, query.limit ?? 10)\n .map(({ entry }) => entry);\n }\n\n store(entry: MemoryEntry): Promise<void> {\n return this.mutate((entries) => {\n const index = entries.findIndex((e) => e.key === entry.key);\n const stamped: MemoryEntry = {\n ...entry,\n createdAt: entry.createdAt ?? new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n if (index >= 0) entries[index] = stamped;\n else entries.push(stamped);\n return [entries, undefined];\n });\n }\n\n async count(): Promise<number> {\n return (await this.readAll()).length;\n }\n}\n","/**\n * Remembera memory provider (§19): the preferred Hilbras memory integration,\n * reached over HTTP. Remembera is strictly optional — the core also runs with\n * the local memory provider or none at all (§2).\n *\n * API convention assumed by this adapter (adjust here if the real API differs):\n * write: POST {baseUrl}/api/memory body: MemoryEntry JSON → 2xx\n * query: POST {baseUrl}/api/memory/query body: MemoryQuery JSON → { entries: MemoryEntry[] }\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { resolveApiKey } from \"../providers/auth.js\";\nimport { requestJson } from \"../providers/http.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\n\nexport interface RememberaConfig {\n baseUrl: string;\n apiKeyEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nexport class RememberaMemoryProvider implements IMemoryProvider {\n readonly name = \"remembera\";\n private readonly baseUrl: string;\n private readonly apiKeyEnvVar?: string;\n private readonly env: Record<string, string | undefined>;\n private readonly log: Logger;\n\n constructor(config: RememberaConfig, log: Logger = logger) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.apiKeyEnvVar = config.apiKeyEnvVar;\n this.env = config.env ?? process.env;\n this.log = log.child({ component: \"remembera\" });\n }\n\n private get authenticationConfigured(): boolean {\n return this.apiKeyEnvVar === undefined || Boolean(this.env[this.apiKeyEnvVar]);\n }\n\n private headers(): Record<string, string> {\n const key = this.apiKeyEnvVar\n ? resolveApiKey({ name: \"remembera\", apiKeyEnvVar: this.apiKeyEnvVar }, this.env)\n : undefined;\n return key ? { authorization: `Bearer ${key}` } : {};\n }\n\n /** Search delegates to the gateway's relevance query. */\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(\n this,\n text,\n {\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n },\n );\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"http\", baseUrl: this.baseUrl, authenticated: this.authenticationConfigured },\n });\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const { status, body } = await this.request(`${this.baseUrl}/api/memory/query`, query);\n if (status !== 200) {\n throw new MemoryError(`Remembera query returned HTTP ${status}.`);\n }\n const entries = (body as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new MemoryError(\"Remembera query response had no entries array.\");\n }\n return entries.map((entry) => this.toEntry(entry)).filter((entry): entry is MemoryEntry => entry !== undefined);\n }\n\n async store(entry: MemoryEntry): Promise<void> {\n const { status } = await this.request(`${this.baseUrl}/api/memory`, entry);\n if (status !== 200 && status !== 201) {\n throw new MemoryError(`Remembera write returned HTTP ${status}.`);\n }\n }\n\n private async request(url: string, body: unknown): Promise<{ status: number; body: unknown }> {\n // Resolved outside the try so auth failures propagate as-is.\n const headers = this.headers();\n try {\n return await requestJson(url, {\n method: \"POST\",\n headers,\n body,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MemoryError(`Remembera request to ${url} failed: ${message}`, { cause: error });\n }\n }\n\n private toEntry(raw: unknown): MemoryEntry | undefined {\n if (raw === null || typeof raw !== \"object\") {\n this.log.warn(\"Skipping malformed Remembera memory entry.\");\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n if (typeof entry.key !== \"string\" || typeof entry.content !== \"string\") {\n this.log.warn(\"Skipping Remembera memory entry without key/content.\");\n return undefined;\n }\n const scope = entry.scope;\n return {\n key: entry.key,\n content: entry.content,\n scope:\n scope === \"project\" || scope === \"role\" || scope === \"task\" || scope === \"knowledge\"\n ? scope\n : \"knowledge\",\n ...(Array.isArray(entry.tags) ? { tags: entry.tags.filter((t): t is string => typeof t === \"string\") } : {}),\n ...(typeof entry.category === \"string\"\n ? { category: entry.category as MemoryEntry[\"category\"] }\n : {}),\n ...(typeof entry.createdAt === \"string\" ? { createdAt: entry.createdAt } : {}),\n ...(typeof entry.updatedAt === \"string\" ? { updatedAt: entry.updatedAt } : {}),\n };\n }\n}\n","/** Memory provider factory: memory is optional; local is the default. */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { IMemoryProvider } from \"../types/memory.js\";\nimport { LocalMemoryProvider } from \"./local.js\";\nimport { RememberaMemoryProvider } from \"./remembera.js\";\n\nexport type MemoryProviderConfig = NonNullable<AppConfig[\"project\"][\"memory\"]>;\n\nexport function createMemoryProvider(config?: MemoryProviderConfig): IMemoryProvider {\n if (!config || config.provider === \"local\") {\n return new LocalMemoryProvider();\n }\n if (config.provider === \"remembera\") {\n if (!config.baseUrl) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Memory provider \"remembera\" needs a base_url in omninode.yaml.`,\n );\n }\n return new RememberaMemoryProvider({\n baseUrl: config.baseUrl,\n apiKeyEnvVar: config.apiKeyEnvVar,\n });\n }\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Unknown memory provider \"${config.provider}\". Available: local, remembera.`,\n );\n}\n","/**\n * Memory service + context manager (§12, Context Retrieval):\n *\n * Task → context query → relevant memory → context → agent/planner\n *\n * Retrieval is task-oriented and budgeted — OmniNode never loads all memory\n * into a prompt. Failures are best-effort by default; when memory is marked\n * `required`, they become fatal instead (§12, Failure Handling).\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry } from \"../types/memory.js\";\nimport type { Task } from \"../types/task.js\";\n\nexport interface MemoryContextQuery {\n objective: string;\n role?: string;\n project?: string;\n /** Maximum entries to consider (relevance-ranked by the provider). */\n limit?: number;\n}\n\nexport interface MemoryTaskContext {\n /** Prompt-ready context text (\"\" when nothing relevant was found). */\n text: string;\n entries: MemoryEntry[];\n /** True when the character budget cut the context short. */\n truncated: boolean;\n}\n\nconst DEFAULT_ENTRY_LIMIT = 8;\nexport const MAX_CONTEXT_CHARS = 4_000;\n\nexport interface MemoryServiceOptions {\n /** When true, backend failures propagate instead of being logged. */\n required?: boolean;\n maxContextChars?: number;\n}\n\nexport class MemoryService {\n private readonly log: Logger;\n private readonly required: boolean;\n private readonly maxContextChars: number;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n options: MemoryServiceOptions = {},\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n this.required = options.required ?? false;\n this.maxContextChars = options.maxContextChars ?? MAX_CONTEXT_CHARS;\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n get isRequired(): boolean {\n return this.required;\n }\n\n /** Structured, budgeted context for a task (§12 — avoid loading all memory). */\n async contextFor(query: MemoryContextQuery): Promise<MemoryTaskContext> {\n let entries: MemoryEntry[];\n try {\n entries = await this.provider.retrieve({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: query.limit ?? DEFAULT_ENTRY_LIMIT,\n });\n } catch (error) {\n return this.handleFailure(\"retrieve\", error, { text: \"\", entries: [], truncated: false });\n }\n return this.format(entries);\n }\n\n /** Prompt-ready context text (v1 convenience wrapper). */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n return (await this.contextFor(query)).text;\n }\n\n /** Records a finished task's outcome — task history plus \"known problems\" (§12). */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.store({\n key: `task:${task.id}`,\n scope: \"task\",\n category: \"tasks\",\n content: `Objective: ${task.objective}\\nStatus: ${task.status}\\nOutcome: ${outcome}`,\n tags: [\"task\", ...(task.agent ? [task.agent] : []), ...(task.role ? [task.role] : [])],\n createdAt: task.createdAt,\n });\n const significant = (task.result?.reports ?? []).flatMap((report) =>\n report.findings\n .filter((finding) => finding.severity === \"high\" || finding.severity === \"critical\")\n .map((finding) => ({ report, finding })),\n );\n for (const { report, finding } of significant) {\n await this.provider.store({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n category: \"problems\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.handleFailure(\"store\", error, undefined);\n }\n }\n\n private format(entries: MemoryEntry[]): MemoryTaskContext {\n if (entries.length === 0) return { text: \"\", entries, truncated: false };\n const byScope = new Map<string, MemoryEntry[]>();\n for (const entry of entries) {\n byScope.set(entry.scope, [...(byScope.get(entry.scope) ?? []), entry]);\n }\n const parts: string[] = [];\n for (const scope of [\"project\", \"task\", \"role\", \"knowledge\"]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries\n .map((entry) => {\n const category = entry.category ? `[${entry.category}] ` : \"\";\n return `- ${category}${entry.content}`;\n })\n .join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n let text = parts.join(\"\\n\\n\");\n const truncated = text.length > this.maxContextChars;\n if (truncated) text = `${text.slice(0, this.maxContextChars - 1)}…`;\n return { text, entries, truncated };\n }\n\n /**\n * Failure policy (§12): continue unless memory is explicitly required.\n */\n private handleFailure(operation: string, error: unknown, fallback?: MemoryTaskContext): MemoryTaskContext {\n const message = error instanceof Error ? error.message : String(error);\n if (this.required) {\n throw new MemoryError(\n `Memory is marked required, but ${operation} failed: ${message}`,\n { cause: error },\n );\n }\n this.log.warn(`Memory ${operation} failed (continuing without memory): ${message}`);\n return fallback ?? { text: \"\", entries: [], truncated: false };\n }\n}","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { TaskEngine } from \"./engine.js\";\nimport { FileTaskStore } from \"./store.js\";\n\nexport function createTaskEngine(config: AppConfig, log: Logger = logger, directory?: string): TaskEngine {\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n return new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(directory),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n}\n","/**\n * Pipeline engine (§14, §15, §27 Phase 5): validates pipeline definitions,\n * schedules steps over their dependency DAG (implicit sequential chain by\n * default, parallel where the DAG allows), fans research steps out to several\n * agents, hands combined context to plan steps (via a chat model) and to the\n * final execution agent. Every task runs through the TaskEngine, so tasks,\n * results and reports are persisted normally.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport { PipelineError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { createProvider } from \"../providers/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type {\n IPipelineExecutor,\n PipelineDefinition,\n PipelineRun,\n PipelineRunOptions,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatFn } from \"../types/chat.js\";\n// Re-exported for v1 compatibility: ChatFn now lives in the neutral types layer.\nexport type { ChatFn };\nimport type { Plan } from \"../types/plan.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/index.js\";\nimport { aggregateReports } from \"../reports/aggregate.js\";\nimport type { AuditSink } from \"../audit/index.js\";\nimport type { IPlanner } from \"../planner/index.js\";\nimport type { PlanStore } from \"../planner/store.js\";\nimport { HeuristicPlanner } from \"../planner/heuristic.js\";\nimport { ModelPlanner } from \"../planner/model.js\";\nimport type { TaskEngine } from \"../tasks/index.js\";\nimport type { PipelineRunStore } from \"./store.js\";\n\nexport interface PipelineEngineOptions {\n tasks: TaskEngine;\n agents: AgentRegistry;\n roles: RoleRegistry;\n providers: AppConfig[\"project\"][\"providers\"];\n store: PipelineRunStore;\n chat?: ChatFn;\n /** Default planner used by plan steps without their own model (§18). */\n planner?: IPlanner;\n /** When present, plans produced by plan steps are persisted. */\n plans?: PlanStore;\n /** When present, pipeline lifecycle events are appended to the audit log (§24). */\n audit?: AuditSink;\n /** When present, finished runs have their reports collected, stored and combined (§16–§17). */\n reports?: ReportService;\n log?: Logger;\n}\n\nexport interface RunPipelineOptions {\n objective?: string;\n onStep?: (stepRun: PipelineStepRun) => void;\n}\n\ninterface StepOutcome {\n status: \"completed\" | \"failed\" | \"partial\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n /** Execution ids of created tasks, for correlation (§6.5). */\n executionIds?: string[];\n /** Step attempt that produced this outcome (1 = first try). */\n attempt?: number;\n planId?: string;\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n runId?: string;\n role?: RoleDefinition;\n combinedContext: string;\n reports: Report[];\n pipelineRunId?: string;\n}\n\nexport class PipelineEngine implements IPipelineExecutor {\n private readonly log: Logger;\n /** Runs executing in THIS process — cancellation can terminate them directly. */\n private readonly activeRuns = new Map<\n string,\n { taskIds: Set<string>; cancelTasks: () => Promise<void> }\n >();\n\n constructor(private readonly options: PipelineEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"pipelines\" });\n }\n\n get store(): PipelineRunStore {\n return this.options.store;\n }\n\n /**\n * Saves the run while preserving fields that may be set by another process\n * (e.g. a cancellation request) — an in-memory snapshot must never clobber\n * externally requested cancellation (§9.2).\n */\n private async persist(run: PipelineRun): Promise<void> {\n const current = await this.options.store.get(run.id);\n await this.options.store.save({\n ...run,\n ...(current?.cancellationRequested === true\n ? { cancellationRequested: true, cancellationRequestedAt: current.cancellationRequestedAt }\n : {}),\n });\n }\n\n /** Structural + semantic validation (§27 Phase 5 — pipeline parser). */\n validate(def: PipelineDefinition): void {\n const ids = new Set<string>();\n for (const step of def.steps) {\n if (ids.has(step.id)) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Duplicate step id \"${step.id}\".`);\n }\n ids.add(step.id);\n }\n for (const step of def.steps) {\n for (const dep of step.dependsOn ?? []) {\n if (!ids.has(dep)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" depends on unknown step \"${dep}\".`,\n );\n }\n }\n if ((step.kind === \"research\") && (step.agents ?? []).length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Research step \"${step.id}\" needs at least one agent.`,\n );\n }\n if ((step.kind === \"execute\" || step.kind === \"custom\") && !step.agent) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Step \"${step.id}\" (${step.kind}) needs an agent.`);\n }\n }\n this.assertAcyclic(def);\n }\n\n private assertAcyclic(def: PipelineDefinition): void {\n const deps = this.effectiveDependencies(def);\n const remaining = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n for (const [id, list] of deps) {\n remaining.set(id, list.length);\n for (const d of list) {\n dependents.set(d, [...(dependents.get(d) ?? []), id]);\n }\n }\n const queue = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) === 0);\n let processed = 0;\n while (queue.length > 0) {\n const id = queue.shift()!;\n processed += 1;\n for (const next of dependents.get(id) ?? []) {\n const left = (remaining.get(next) ?? 0) - 1;\n remaining.set(next, left);\n if (left === 0) queue.push(next);\n }\n }\n if (processed < deps.size) {\n const stuck = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) > 0);\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" has a dependency cycle involving: ${stuck.join(\", \")}.`,\n );\n }\n }\n\n /**\n * Steps run sequentially in definition order unless they declare explicit\n * dependencies, which enable parallel branches.\n */\n private effectiveDependencies(def: PipelineDefinition): Map<string, string[]> {\n const deps = new Map<string, string[]>();\n def.steps.forEach((step, index) => {\n const explicit = step.dependsOn ?? [];\n deps.set(\n step.id,\n explicit.length > 0 ? explicit : index > 0 ? [def.steps[index - 1]!.id] : [],\n );\n });\n return deps;\n }\n\n async run(def: PipelineDefinition, options: PipelineRunOptions = {}): Promise<PipelineRun> {\n this.validate(def);\n\n const objective = (options.objective ?? def.objective ?? \"\").trim();\n if (objective.length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" needs an objective — pass one or set it in the definition.`,\n );\n }\n const role = def.role ? this.options.roles.get(def.role) : undefined;\n if (def.role && !role) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Role \"${def.role}\" (pipeline \"${def.id}\") is not defined in project.roles.`,\n );\n }\n // Agents referenced by steps must be registered, and plan-step models\n // must resolve to a configured provider — both before anything runs (§9.5).\n for (const step of def.steps) {\n for (const name of [...(step.agents ?? []), ...(step.agent ? [step.agent] : [])]) {\n if (!this.options.agents.get(name)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" references unregistered agent \"${name}\".`,\n );\n }\n }\n if (step.model) {\n const separator = step.model.indexOf(\":\");\n if (separator <= 0 || separator === step.model.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" has an invalid model reference \"${step.model}\" — use \"provider:model-id\".`,\n );\n }\n const providerName = step.model.slice(0, separator);\n if (!this.options.providers.some((p) => p.name === providerName)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" uses model \"${step.model}\" but provider \"${providerName}\" is not configured.`,\n );\n }\n }\n }\n\n const now = new Date().toISOString();\n const run: PipelineRun = {\n id: `run-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n pipelineId: def.id,\n attempt: 1,\n objective,\n status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n const liveTaskIds = new Set<string>();\n this.activeRuns.set(run.id, {\n taskIds: liveTaskIds,\n cancelTasks: async () => {\n for (const taskId of liveTaskIds) {\n await this.options.tasks.cancel(taskId).catch(() => undefined);\n }\n },\n });\n this.log.info(`Running pipeline ${def.id} as ${run.id} (attempt ${run.attempt}).`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"pipeline.run.started\",\n id: run.id,\n detail: { pipeline: def.id, objective },\n });\n\n const deps = this.effectiveDependencies(def);\n const outcomes = new Map<string, StepOutcome>();\n const pending = new Set(def.steps.map((s) => s.id));\n const contextParts: string[] = [];\n const allReports: Report[] = [];\n let cancelled = false;\n\n while (pending.size > 0) {\n // §9.2 cancellation check point: stop scheduling, terminate what runs.\n const persisted = await this.options.store.get(run.id);\n if (persisted?.cancellationRequested === true) {\n cancelled = true;\n run.cancellationRequested = true;\n run.cancellationRequestedAt = persisted.cancellationRequestedAt;\n await this.activeRuns.get(run.id)?.cancelTasks();\n for (const step of def.steps.filter((s) => pending.has(s.id))) {\n const stepRun: PipelineStepRun = { stepId: step.id, status: \"cancelled\" };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n }\n pending.clear();\n break;\n }\n\n const ready = def.steps.filter(\n (step) => pending.has(step.id) && (deps.get(step.id) ?? []).every((d) => outcomes.has(d)),\n );\n if (ready.length === 0) {\n // Cycle — already rejected by validate(), but never hang.\n throw new PipelineError(\"PIPELINE_FAILED\", `Pipeline \"${def.id}\" scheduling stalled.`);\n }\n\n const settled = await Promise.all(\n ready.map(async (step): Promise<StepOutcome> => {\n if (!this.shouldRun(step, deps.get(step.id) ?? [], outcomes)) {\n return { status: \"skipped\", summary: \"\", taskIds: [], reports: [] };\n }\n const ctx: StepContext = {\n objective,\n ...(role ? { role } : {}),\n combinedContext: contextParts.join(\"\\n\\n\"),\n reports: [...allReports],\n pipelineRunId: run.id,\n runId: run.id,\n };\n return this.executeStep(step, ctx);\n }),\n );\n\n ready.forEach((step, index) => {\n const outcome = settled[index]!;\n outcomes.set(step.id, outcome);\n pending.delete(step.id);\n allReports.push(...outcome.reports);\n if (outcome.status !== \"skipped\" && outcome.summary.length > 0) {\n const contribution = outcome.contextContribution ?? outcome.summary;\n contextParts.push(`## Step \"${step.id}\" (${step.kind})\\n${contribution}`);\n }\n const stepRun: PipelineStepRun = {\n stepId: step.id,\n attempt: outcome.attempt ?? 1,\n ...(outcome.executionIds && outcome.executionIds.length > 0\n ? { executionIds: outcome.executionIds }\n : {}),\n status:\n outcome.status === \"skipped\"\n ? \"cancelled\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : outcome.status === \"partial\"\n ? \"partially_completed\"\n : \"completed\",\n ...(outcome.taskIds.length > 0 ? { taskIds: outcome.taskIds } : {}),\n ...(outcome.planId !== undefined ? { planId: outcome.planId } : {}),\n ...(outcome.error !== undefined ? { error: outcome.error } : {}),\n };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n });\n run.reports = [...allReports];\n await this.persist(run);\n }\n\n const allOutcomes = [...outcomes.values()];\n const failed = !cancelled && allOutcomes.some((o) => o.status === \"failed\");\n const partial = !cancelled && !failed && allOutcomes.some((o) => o.status === \"partial\");\n const finalStatus: PipelineRunStatus = cancelled\n ? \"cancelled\"\n : failed\n ? \"failed\"\n : partial\n ? \"partial\"\n : \"completed\";\n const planId = [...outcomes.values()].find((o) => o.planId !== undefined)?.planId;\n\n // §28 — Result: the outcome of the last completed step with tasks.\n let resultSummary: string | undefined;\n for (let i = def.steps.length - 1; i >= 0; i -= 1) {\n const step = def.steps[i]!;\n const outcome = outcomes.get(step.id);\n if (outcome?.status !== \"completed\" || outcome.taskIds.length === 0) continue;\n const stepTasks = (\n await Promise.all(outcome.taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const summaries = stepTasks\n .map((task) => task.result?.summary)\n .filter((summary): summary is string => summary !== undefined);\n if (summaries.length > 0) resultSummary = summaries.join(\"\\n\");\n break;\n }\n\n // Report system (§16–§17): collect, store and combine reports from the\n // analysis tasks (research/analyze) — execution output is a result, not a report.\n let combinedReportId: string | undefined;\n if (this.options.reports) {\n const taskIds = def.steps\n .filter((step) => step.kind === \"research\" || step.kind === \"analyze\")\n .flatMap((step) => outcomes.get(step.id)?.taskIds ?? []);\n const tasks = (\n await Promise.all(taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const collected = await this.options.reports.collectFromTasks(tasks);\n await this.options.reports.saveReports(collected);\n const combined = await this.options.reports.generateCombined(collected, {\n objective,\n pipelineRunId: run.id,\n taskIds,\n });\n combinedReportId = combined?.id;\n if (collected.length > 0) {\n run.reports = collected;\n }\n }\n\n const finishedAt = new Date().toISOString();\n this.activeRuns.delete(run.id);\n const finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt,\n attempts: [...(run.attempts ?? []), { attempt: run.attempt, startedAt: run.startedAt ?? finishedAt, finishedAt, status: finalStatus }],\n ...(run.reports !== undefined && run.reports.length > 0 ? { reports: run.reports } : {}),\n ...(combinedReportId !== undefined ? { combinedReportId } : {}),\n ...(planId !== undefined ? { planId } : {}),\n ...(resultSummary !== undefined ? { resultSummary } : {}),\n };\n await this.persist(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"pipeline.run.finished\",\n id: run.id,\n detail: { pipeline: def.id, status: finalStatus },\n });\n return finished;\n }\n\n /** First-class cancellation (§9.2): requests cancellation and terminates\n * tasks that are running in this process immediately. */\n async cancel(runId: string): Promise<void> {\n const run = await this.options.store.get(runId);\n if (!run) {\n throw new PipelineError(\"PIPELINE_NOT_FOUND\", `Pipeline run \"${runId}\" does not exist.`);\n }\n await this.options.store.save({\n ...run,\n cancellationRequested: true,\n cancellationRequestedAt: new Date().toISOString(),\n });\n const active = this.activeRuns.get(runId);\n if (active) {\n await active.cancelTasks();\n }\n }\n\n async get(runId: string): Promise<PipelineRun | undefined> {\n return this.options.store.get(runId);\n }\n\n async listRuns(filter?: { pipelineId?: string }): Promise<PipelineRun[]> {\n return this.options.store.list(filter);\n }\n\n private shouldRun(\n step: PipelineStep,\n deps: string[],\n outcomes: Map<string, StepOutcome>,\n ): boolean {\n const condition = step.condition ?? \"on-success\";\n const depStatuses = deps.map((d) => outcomes.get(d)?.status);\n const anyFailed = depStatuses.includes(\"failed\");\n // A partial dependency carries real output, so it does not block.\n const anySkipped = depStatuses.includes(\"skipped\");\n if (condition === \"always\") return true;\n if (condition === \"on-failure\") return anyFailed;\n return !anyFailed && !anySkipped;\n }\n\n private async executeStep(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const retries = step.retries ?? 0;\n let last: StepOutcome | undefined;\n for (let attempt = 0; attempt <= retries; attempt += 1) {\n if (attempt > 0) {\n this.log.warn(`Step \"${step.id}\" failed — retry ${attempt}/${retries}.`);\n }\n last = await this.executeStepOnce(step, ctx);\n if (last.status !== \"failed\") return { ...last, attempt: attempt + 1 };\n }\n return { ...last!, attempt: retries + 1 };\n }\n\n /** Registers tasks created for a step as live, so cancellation can terminate them (§9.2). */\n private trackLiveTasks(runId: string | undefined, taskIds: string[]): void {\n if (!runId) return;\n const active = this.activeRuns.get(runId);\n if (!active) return;\n for (const id of taskIds) active.taskIds.add(id);\n }\n\n private async executeStepOnce(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n switch (step.kind) {\n case \"research\":\n return this.runFanOut(step, ctx);\n case \"collect\":\n return { status: \"completed\", summary: \"(collect: outputs gathered from previous steps)\", taskIds: [], reports: [] };\n case \"analyze\":\n if (!step.agent) {\n return { status: \"completed\", summary: \"(analyze: pass-through, no agent assigned)\", taskIds: [], reports: [] };\n }\n return this.runSingle(step, ctx, step.agent);\n case \"plan\":\n return this.runPlan(step, ctx);\n case \"execute\":\n case \"custom\":\n return this.runSingle(step, ctx, step.agent!);\n }\n }\n\n /** Research fan-out: one task per agent, in parallel (§15). */\n private async runFanOut(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const agentNames = step.agents ?? [];\n const created = await Promise.all(\n agentNames.map((name) =>\n this.options.tasks.create({\n objective: ctx.objective,\n agent: name,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0\n ? { context: { background: ctx.combinedContext } }\n : {}),\n }),\n ),\n );\n this.trackLiveTasks(ctx.runId, created.map((t) => t.id));\n const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n const executionIds = results.map((r) => r.executions?.at(-1)?.executionId).filter((id): id is string => id !== undefined);\n\n const completedTasks = results.filter((r) => r.status === \"completed\");\n const failedTasks = results.filter((r) => r.status !== \"completed\");\n const lines = results.map((result, index) => {\n const agentName = agentNames[index] ?? \"unknown\";\n const outcome = result.result?.summary ?? result.result?.error ?? \"(no output)\";\n return `- ${agentName}: ${outcome}`;\n });\n const reports = results.flatMap((r) => r.result?.reports ?? []);\n const summary = lines.join(\"\\n\");\n\n if (failedTasks.length > 0) {\n const firstError = failedTasks[0]?.result?.error ?? failedTasks[0]?.lastError ?? \"unknown outcome\";\n const states = failedTasks.map((r) => r.status).join(\", \");\n return {\n // Some agents succeeded → the step produced usable but incomplete\n // intelligence: partial, not failed (roadmap §9.3).\n status: completedTasks.length > 0 ? \"partial\" : \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) incomplete (${states}) — ${firstError}`,\n reports,\n };\n }\n return {\n status: \"completed\",\n summary,\n taskIds: created.map((t) => t.id),\n ...(executionIds.length > 0 ? { executionIds } : {}),\n reports,\n };\n }\n\n private async runSingle(\n step: PipelineStep,\n ctx: StepContext,\n agentName: string,\n ): Promise<StepOutcome> {\n const task = await this.options.tasks.create({\n objective: ctx.objective,\n agent: agentName,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: { background: ctx.combinedContext } } : {}),\n });\n this.trackLiveTasks(ctx.runId, [task.id]);\n const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n // Unknown/timed_out outcomes are not failures — the work may have\n // happened remotely; the step is incomplete, not broken.\n status: result.status === \"unknown\" || result.status === \"timed_out\" ? \"partial\" : \"failed\",\n summary: result.result?.summary ?? \"\",\n taskIds: [task.id],\n error: result.result?.error ?? `task ${task.id} did not complete`,\n reports: result.result?.reports ?? [],\n };\n }\n return {\n status: \"completed\",\n summary: result.result?.summary ?? \"(no output)\",\n taskIds: [task.id],\n reports: result.result?.reports ?? [],\n };\n }\n\n private async runPlan(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n // §15 Planner Input: task, reports, aggregated findings (consensus +\n // conflicts), context, role and step constraints.\n const aggregated = ctx.reports.length > 0 ? aggregateReports(ctx.reports) : undefined;\n const request = {\n objective: ctx.objective,\n reports: ctx.reports,\n ...(aggregated !== undefined ? { aggregated } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: ctx.combinedContext } : {}),\n ...(ctx.role ? { role: ctx.role } : {}),\n ...(step.constraints !== undefined && step.constraints.length > 0\n ? { constraints: step.constraints }\n : {}),\n ...(ctx.pipelineRunId !== undefined ? { pipelineRunId: ctx.pipelineRunId } : {}),\n };\n\n // Selection order: an explicit step model wins, then the configured\n // default planner, then a pass-through (nothing to plan with).\n let planner: IPlanner;\n if (step.model) {\n planner = new ModelPlanner({\n model: step.model,\n chat: this.getChat(),\n fallback: new HeuristicPlanner(),\n log: this.log,\n });\n } else if (this.options.planner) {\n planner = this.options.planner;\n } else {\n return {\n status: \"completed\",\n summary: \"(plan: no model or planner configured — skipped)\",\n taskIds: [],\n reports: [],\n };\n }\n\n let plan: Plan;\n try {\n plan = await planner.plan(request);\n } catch (error) {\n return {\n status: \"failed\",\n summary: \"\",\n taskIds: [],\n error: error instanceof Error ? error.message : String(error),\n reports: [],\n };\n }\n\n await this.options.plans?.save(plan);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"plan.generated\",\n id: plan.id,\n detail: { generatedBy: plan.generatedBy, steps: plan.steps.length },\n });\n return {\n status: \"completed\",\n summary: plan.summary,\n contextContribution: formatPlan(plan),\n taskIds: [],\n planId: plan.id,\n reports: [],\n };\n }\n\n private getChat(): ChatFn {\n if (this.options.chat) return this.options.chat;\n throw new PipelineError(\n \"PIPELINE_FAILED\",\n \"No chat function available — configure a provider for plan steps.\",\n );\n }\n}\n\nfunction formatPlan(plan: Plan): string {\n const lines = [\n `# Implementation Plan (by ${plan.generatedBy})`,\n plan.summary,\n \"Steps:\",\n ...plan.steps.map((step) => {\n const targets = step.targets && step.targets.length > 0 ? ` [targets: ${step.targets.join(\", \")}]` : \"\";\n return `${step.order}. ${step.title}${targets}`;\n }),\n ];\n if (plan.risks && plan.risks.length > 0) {\n lines.push(\"Risks:\", ...plan.risks.map((risk) => `- ${risk}`));\n }\n return lines.join(\"\\n\");\n}\n\n/** Default chat function: resolves \"provider:model\" against the configured providers. */\nexport function createDefaultChatFn(\n providers: AppConfig[\"project\"][\"providers\"],\n): ChatFn {\n return async (modelRef, messages) => {\n const separator = modelRef.indexOf(\":\");\n if (separator <= 0 || separator === modelRef.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Invalid model reference \"${modelRef}\". Use \"provider:model-id\".`,\n );\n }\n const providerName = modelRef.slice(0, separator);\n const modelId = modelRef.slice(separator + 1);\n const providerConfig = providers.find((p) => p.name === providerName);\n if (!providerConfig) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Provider \"${providerName}\" (model \"${modelRef}\") is not configured.`,\n );\n }\n const provider = createProvider(providerConfig);\n const response = await provider.chat({ model: modelId, messages });\n return response.content;\n };\n}\n","/**\n * Report aggregation (§17): normalizes formats, groups duplicate and similar\n * findings, preserves source attribution, and produces one CombinedReport.\n * Grouping uses deterministic token-set similarity so results are testable.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AggregatedFinding,\n AggregatedRecommendation,\n CombinedReport,\n Confidence,\n ConflictPosition,\n Finding,\n FindingSeverity,\n FindingSource,\n Report,\n ReportConflict,\n} from \"../types/report.js\";\nimport { normalizeEvidence } from \"./schema.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nexport interface AggregateOptions {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n /** Token-set Jaccard similarity above which findings are merged. */\n similarityThreshold?: number;\n}\n\nexport function aggregateReports(reports: Report[], options: AggregateOptions = {}): CombinedReport {\n const threshold = options.similarityThreshold ?? 0.7;\n\n const findingGroups: AggregatedFinding[] = [];\n const recommendationGroups: AggregatedRecommendation[] = [];\n\n for (const report of reports) {\n for (const finding of report.findings) {\n mergeFinding(findingGroups, finding, report, threshold);\n }\n for (const text of report.recommendations) {\n mergeRecommendation(recommendationGroups, text, report, threshold);\n }\n }\n\n const sources = [...new Set(reports.map((r) => r.agent))].sort();\n const totalRawFindings = reports.reduce((sum, r) => sum + r.findings.length, 0);\n const conflicts = detectConflicts(findingGroups);\n // Agreement = independently reported by 2+ agents with the same severity.\n const agreements = findingGroups.filter(\n (group) =>\n group.sources.length > 1 &&\n group.severity !== undefined &&\n new Set(Object.values(group.severityBySource ?? {})).size === 1,\n );\n const disputed = conflicts.length;\n const summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\n `${agreements.length} agreement(s), ${disputed} conflict(s), ` +\n `${recommendationGroups.length} recommendation group(s).`;\n\n return {\n id: `combined-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n title: options.objective !== undefined ? truncate(options.objective, 120) : \"Combined report\",\n ...(options.objective !== undefined ? { objective: options.objective } : {}),\n ...(options.pipelineRunId !== undefined ? { pipelineRunId: options.pipelineRunId } : {}),\n taskIds: options.taskIds ?? [],\n summary,\n findings: findingGroups.sort((a, b) => rank(b) - rank(a)),\n agreements,\n conflicts,\n recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\n metadata: {\n agents: sources.length,\n reports: reports.length,\n rawFindings: totalRawFindings,\n findingGroups: findingGroups.length,\n agreements: agreements.length,\n conflicts: conflicts.length,\n },\n };\n}\n\nfunction rankConfidence(confidence: Confidence | undefined): number {\n return confidence ? { low: 1, medium: 2, high: 3 }[confidence] : 0;\n}\n\n/**\n * Conflict detection (§14): agents disagreeing about the same finding is a\n * first-class result. Both positions are preserved — OmniNode never silently\n * chooses one.\n */\nexport function detectConflicts(groups: AggregatedFinding[]): ReportConflict[] {\n const conflicts: ReportConflict[] = [];\n for (const group of groups) {\n if (group.sources.length < 2) continue;\n\n const severities = new Set(Object.values(group.severityBySource ?? {}));\n if (severities.size > 1) {\n conflicts.push({\n type: \"severity\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note:\n `Agents disagree on severity (${[...severities].sort((a, b) => SEVERITY_RANK[a] - SEVERITY_RANK[b]).join(\", \")}); ` +\n `the highest severity is shown, every position is preserved.`,\n });\n }\n\n const recommendations = (group.recommendations ?? []).filter((r) => r.length > 0);\n if (recommendations.length > 1) {\n conflicts.push({\n type: \"recommendation\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note: `Agents proposed ${recommendations.length} different fixes; none was discarded.`,\n });\n }\n }\n return conflicts;\n}\n\nfunction position(\n source: FindingSource,\n group: AggregatedFinding,\n): ConflictPosition {\n return {\n agent: source.agent,\n reportId: source.reportId,\n ...(group.severityBySource?.[source.agent] !== undefined\n ? { severity: group.severityBySource[source.agent] }\n : {}),\n ...(group.confidenceBySource?.[source.agent] !== undefined\n ? { confidence: group.confidenceBySource[source.agent] }\n : {}),\n ...(group.recommendations?.[0] !== undefined ? { recommendation: group.recommendations[0] } : {}),\n };\n}\n\nfunction rank(finding: AggregatedFinding): number {\n return finding.severity ? SEVERITY_RANK[finding.severity] : -1;\n}\n\nfunction mergeFinding(groups: AggregatedFinding[], finding: Finding, report: Report, threshold: number): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.title, finding.title, threshold));\n if (group) {\n group.occurrences += 1;\n group.details.push(finding.detail);\n group.sources.push(source);\n group.evidence.push(...(normalizeEvidence(finding.evidence) ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\n }\n // Confidence preservation (§14): keep the strongest, and record per source.\n if (finding.confidence && rankConfidence(finding.confidence) > rankConfidence(group.confidence)) {\n group.confidence = finding.confidence;\n }\n if (finding.severity) {\n group.severityBySource = { ...group.severityBySource, [report.agent]: finding.severity };\n }\n if (finding.confidence) {\n group.confidenceBySource = { ...group.confidenceBySource, [report.agent]: finding.confidence };\n }\n if (finding.recommendation && !group.recommendations?.includes(finding.recommendation)) {\n group.recommendations = [...(group.recommendations ?? []), finding.recommendation];\n }\n return;\n }\n groups.push({\n title: finding.title,\n details: [finding.detail],\n sources: [source],\n occurrences: 1,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.confidence ? { confidence: finding.confidence } : {}),\n ...(finding.severity ? { severityBySource: { [report.agent]: finding.severity } } : {}),\n ...(finding.confidence ? { confidenceBySource: { [report.agent]: finding.confidence } } : {}),\n ...(finding.recommendation ? { recommendations: [finding.recommendation] } : {}),\n evidence: [...(normalizeEvidence(finding.evidence) ?? [])],\n });\n}\n\nfunction mergeRecommendation(\n groups: AggregatedRecommendation[],\n text: string,\n report: Report,\n threshold: number,\n): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.text, text, threshold));\n if (group) {\n group.occurrences += 1;\n group.sources.push(source);\n return;\n }\n groups.push({ text, sources: [source], occurrences: 1 });\n}\n\nexport function similar(a: string, b: string, threshold: number): boolean {\n const left = tokens(a);\n const right = tokens(b);\n if (left.size === 0 || right.size === 0) return false;\n let intersection = 0;\n for (const token of left) {\n if (right.has(token)) intersection += 1;\n }\n const union = left.size + right.size - intersection;\n return intersection / union >= threshold;\n}\n\nfunction tokens(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 3),\n );\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report validation and normalization (roadmap §13, Report Validation).\n *\n * Reports are machine-readable objects: they are schema-validated before they\n * can enter aggregation, and legacy string evidence / `detail` fields are\n * normalized into the v2 shape on the way in.\n */\nimport { z } from \"zod\";\nimport type { Confidence, Evidence, EvidenceInput, Finding, Report } from \"../types/report.js\";\n\nconst evidenceSchema = z.union([\n z.string().transform((excerpt): Evidence => ({ kind: \"observation\", excerpt })),\n z.object({\n kind: z.enum([\"file\", \"line\", \"url\", \"command\", \"observation\", \"artifact\"]),\n ref: z.string().optional(),\n line: z.number().int().optional(),\n excerpt: z.string().optional(),\n agent: z.string().optional(),\n }),\n]);\n\nconst findingSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n detail: z.string().default(\"\"),\n description: z.string().optional(),\n severity: z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]).optional(),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n severityBySource: z.record(z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"])).optional(),\n confidenceBySource: z.record(z.enum([\"low\", \"medium\", \"high\"])).optional(),\n recommendations: z.array(z.string()).optional(),\n evidence: z.array(evidenceSchema).optional(),\n location: z.string().optional(),\n tags: z.array(z.string()).optional(),\n source: z.object({ agent: z.string().optional(), reportId: z.string().optional(), pipelineRunId: z.string().optional() }).optional(),\n recommendation: z.string().optional(),\n});\n\nconst artifactSchema = z.object({\n kind: z.enum([\"file\", \"patch\", \"log\", \"screenshot\", \"document\", \"data\"]),\n ref: z.string().min(1),\n description: z.string().optional(),\n mediaType: z.string().optional(),\n bytes: z.number().int().optional(),\n});\n\nconst reportSchema = z.object({\n id: z.string().min(1),\n taskId: z.string().min(1),\n agent: z.string().min(1),\n agentId: z.string().optional(),\n pipelineRunId: z.string().optional(),\n model: z.string().optional(),\n summary: z.string(),\n findings: z.array(findingSchema),\n recommendations: z.array(z.string()),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n evidence: z.array(evidenceSchema).optional(),\n artifacts: z.array(artifactSchema).optional(),\n createdAt: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n});\n\nexport interface ReportValidationIssue {\n path: string;\n message: string;\n}\n\nexport type ReportValidationResult =\n | { valid: true; report: Report }\n | { valid: false; issues: ReportValidationIssue[]; reason: string };\n\n/** Validates (and normalizes) a report; malformed reports are rejected. */\nexport function validateReport(value: unknown): ReportValidationResult {\n const parsed = reportSchema.safeParse(value);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n }));\n return {\n valid: false,\n issues,\n reason: `report failed schema validation (${issues.length} issue(s))`,\n };\n }\n const report = parsed.data as Report;\n // Cross-field normalization: description mirrors detail, source carries provenance.\n report.findings = report.findings.map((finding) => ({\n ...finding,\n description: finding.description ?? finding.detail,\n ...(finding.source === undefined\n ? { source: { agent: report.agent, reportId: report.id, ...(report.pipelineRunId !== undefined ? { pipelineRunId: report.pipelineRunId } : {}) } }\n : {}),\n }));\n return { valid: true, report };\n}\n\n/** Normalizes evidence entries (strings or objects) to typed evidence. */\nexport function normalizeEvidence(input: EvidenceInput[] | undefined): Evidence[] | undefined {\n if (input === undefined) return undefined;\n return input.map((item) =>\n typeof item === \"string\" ? { kind: \"observation\" as const, excerpt: item } : item,\n );\n}\n\nexport function normalizeFinding(finding: Finding): Finding {\n return {\n ...finding,\n description: finding.description ?? finding.detail,\n evidence: normalizeEvidence(finding.evidence),\n };\n}\n\nexport type { Confidence };","/**\n * HeuristicPlanner: a deterministic, dependency-free planner that derives an\n * implementation plan from recommendations and significant findings.\n * Used as the no-model option and as the graceful fallback when a model's\n * output is rejected (§15).\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { Finding, FindingSeverity } from \"../types/report.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\ninterface ContributedFinding {\n finding: Finding;\n agent: string;\n}\n\nexport class HeuristicPlanner implements IPlanner {\n readonly name = \"heuristic\";\n\n async plan(request: PlanRequest): Promise<Plan> {\n const steps: PlanStep[] = [];\n\n // One step per distinct recommendation (deduped by text).\n const recommendations = dedupe(request.reports.flatMap((r) => r.recommendations));\n for (const text of recommendations) {\n steps.push({\n id: `step-${steps.length + 1}`,\n title: truncate(text, 120),\n order: steps.length + 1,\n ...(steps.length > 0 ? { dependsOn: [`step-${steps.length}`] } : {}),\n });\n }\n\n // Remediation steps for significant findings, most severe first. Aggregated\n // findings (with consensus/conflicts) take precedence when available.\n const contributed: ContributedFinding[] = request.aggregated\n ? request.aggregated.findings.map((finding) => ({\n finding: {\n id: `agg-${slug(finding.title)}`,\n title: finding.title,\n detail: finding.details[0] ?? finding.title,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.recommendations && finding.recommendations.length > 0\n ? { recommendation: finding.recommendations[0] }\n : {}),\n },\n agent: finding.sources.map((s) => s.agent).join(\"+\"),\n }))\n : request.reports.flatMap((report) =>\n report.findings.map((finding) => ({ finding, agent: report.agent })),\n );\n\n const significant = contributed\n .filter(({ finding }) =>\n finding.severity ? SEVERITY_RANK[finding.severity] >= SEVERITY_RANK.high : false,\n )\n .sort(\n (a, b) =>\n SEVERITY_RANK[b.finding.severity ?? \"info\"] - SEVERITY_RANK[a.finding.severity ?? \"info\"],\n );\n for (const { finding } of significant) {\n steps.push(remediationStep(finding, steps.length + 1));\n }\n\n if (steps.length === 0) {\n steps.push({\n id: \"step-1\",\n title: \"Gather additional information\",\n description:\n \"The research reports contained no actionable recommendations or significant findings. \" +\n \"Investigate the objective further before planning implementation work.\",\n order: 1,\n });\n }\n\n const risks = significant\n .filter(({ finding }) => finding.severity === \"critical\")\n .map(({ finding }) => `Critical finding unaddressed until its step completes: ${finding.title}`);\n const conflicts = request.aggregated?.conflicts ?? [];\n if (conflicts.length > 0) {\n risks.push(\n `${conflicts.length} unresolved agent disagreement(s): ${conflicts.map((c) => c.findingTitle).join(\"; \")}`,\n );\n }\n\n return {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: request.aggregated?.title ?? truncate(request.objective, 120),\n summary:\n `Derived from ${request.reports.length} report(s): ` +\n `${recommendations.length} recommendation step(s), ${significant.length} remediation step(s).`,\n steps,\n ...(risks.length > 0 ? { risks } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: \"heuristic\",\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n }\n}\n\nfunction remediationStep(finding: Finding, order: number): PlanStep {\n return {\n id: `step-${order}`,\n title: `Fix: ${truncate(finding.title, 100)}`,\n description: finding.detail,\n order,\n dependsOn: order > 1 ? [`step-${order - 1}`] : [],\n sourceFindings: [finding.id],\n ...(finding.recommendation ? { recommendation: finding.recommendation } : {}),\n };\n}\n\nfunction dedupe(texts: string[]): string[] {\n return [...new Set(texts.map((t) => t.trim()).filter((t) => t.length > 0))];\n}\n\nfunction slug(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\").slice(0, 40);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * ModelPlanner (§18): uses a chat model (\"provider:model-id\" through the chat\n * layer) to produce an implementation plan. The model is asked for JSON\n * matching the plan contract; unparseable output degrades gracefully to the\n * heuristic fallback rather than failing the pipeline.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { PlannerError } from \"../errors/index.js\";\nimport { planJsonSchema, validatePlan } from \"./schema.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { ChatFn, ChatMessage } from \"../types/chat.js\";\n\nimport { buildPlannerContext } from \"./context.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nexport interface ModelPlannerOptions {\n model: string;\n chat: ChatFn;\n /** Extra instruction appended to the system prompt. */\n instruction?: string;\n /** Used when the model output is unparseable (or the call fails, if tolerateErrors). */\n fallback?: IPlanner;\n log?: Logger;\n}\n\nexport class ModelPlanner implements IPlanner {\n readonly name = \"model\";\n private readonly log: Logger;\n\n constructor(private readonly options: ModelPlannerOptions) {\n this.log = (options.log ?? logger).child({ component: \"planner\", model: options.model });\n }\n\n async plan(request: PlanRequest): Promise<Plan> {\n const context = buildPlannerContext(request);\n const messages: ChatMessage[] = [\n {\n role: \"system\",\n content:\n \"You are the OmniNode planner. Given the objective and the combined research context, \" +\n \"produce a final analysis and a prioritized, actionable implementation plan. \" +\n \"Respond with JSON ONLY (no prose, no code fences) matching exactly this shape: \" +\n '{\"goal\": string, \"summary\": string, \"steps\": [{\"id\": string, \"title\": string, \"description\": string, ' +\n '\"order\": number, \"targets\": string[], \"acceptance_criteria\": string[], \"source_findings\": string[]}], ' +\n '\"risks\": string[], \"notes\": string[]}. ' +\n (this.options.instruction ?? \"\"),\n },\n { role: \"user\", content: context },\n ];\n\n let responseText: string;\n try {\n responseText = await this.options.chat(this.options.model, messages);\n } catch (error) {\n return this.degrade(request, `planner model call failed: ${describe(error)}`);\n }\n\n const parsed = parsePlanJson(responseText);\n if (!parsed.ok) {\n return this.degrade(request, `planner model output rejected: ${parsed.reason}`, parsed.issues);\n }\n\n const plan: Plan = {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: parsed.goal,\n summary: parsed.summary,\n steps: parsed.steps,\n ...(parsed.risks !== undefined ? { risks: parsed.risks } : {}),\n ...(parsed.notes !== undefined ? { notes: parsed.notes } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: `model:${this.options.model}`,\n model: this.options.model,\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n\n // §15 Validation: every generated plan passes schema validation.\n const validation = validatePlan(plan);\n if (!validation.valid) {\n return this.degrade(request, `generated plan rejected: ${validation.reason}`, validation.issues);\n }\n return validation.plan;\n }\n\n private async degrade(\n request: PlanRequest,\n reason: string,\n issues: Array<{ path: string; message: string }> = [],\n ): Promise<Plan> {\n if (this.options.fallback) {\n this.log.warn(`${reason} — using the heuristic fallback planner.`);\n return this.options.fallback.plan(request);\n }\n // Structured error: the caller sees exactly what was rejected (§15).\n throw new PlannerError(\"PLAN_INVALID\", `Planner failed: ${reason}.`, {\n details: { reason, issues },\n });\n }\n}\n\nexport type PlanJsonResult =\n | { ok: true; goal: string; summary: string; steps: PlanStep[]; risks?: string[]; notes?: string[] }\n | { ok: false; reason: string; issues: Array<{ path: string; message: string }> };\n\n/** Extracts and validates plan JSON from arbitrary model output (§15). */\nexport function parsePlanJson(text: string): PlanJsonResult {\n const unfenced = text.replace(/```(?:json)?/gi, \"\");\n const start = unfenced.indexOf(\"{\");\n const end = unfenced.lastIndexOf(\"}\");\n if (start < 0 || end <= start) {\n return { ok: false, reason: \"planner output contained no JSON object\", issues: [] };\n }\n let json: unknown;\n try {\n json = JSON.parse(unfenced.slice(start, end + 1));\n } catch (error) {\n return {\n ok: false,\n reason: `planner output was not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n issues: [],\n };\n }\n const parsed = planJsonSchema.safeParse(json);\n if (!parsed.success) {\n return {\n ok: false,\n reason: \"planner output did not match the plan schema\",\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n }\n const steps: PlanStep[] = parsed.data.steps\n .map((step, index) => ({\n id: step.id ?? `step-${index + 1}`,\n title: step.title,\n description: step.description,\n order: step.order ?? index + 1,\n targets: step.targets,\n acceptanceCriteria: step.acceptance_criteria,\n dependsOn: step.depends_on,\n sourceFindings: step.source_findings,\n }))\n .sort((a, b) => a.order - b.order);\n return {\n ok: true,\n goal: parsed.data.goal,\n summary: parsed.data.summary,\n steps,\n risks: parsed.data.risks,\n notes: parsed.data.notes,\n };\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Plan validation (roadmap §15, Validation): every generated plan passes\n * schema validation. Invalid plans are rejected with structured issues and\n * — where a fallback is configured — fall back to heuristic planning.\n */\nimport { z } from \"zod\";\nimport type { Plan } from \"../types/plan.js\";\n\nconst planStepSchema = z.object({\n id: z.string().min(1).optional(),\n title: z.string().min(1),\n description: z.string().optional(),\n order: z.number().int().optional(),\n targets: z.array(z.string()).optional(),\n acceptance_criteria: z.array(z.string()).optional(),\n depends_on: z.array(z.string()).optional(),\n source_findings: z.array(z.string()).optional(),\n});\n\nexport const planJsonSchema = z.object({\n goal: z.string().min(1),\n summary: z.string().min(1),\n steps: z.array(planStepSchema).min(1),\n risks: z.array(z.string()).optional(),\n notes: z.array(z.string()).optional(),\n});\n\nexport interface PlanValidationIssue {\n path: string;\n message: string;\n}\n\nexport type PlanValidationResult =\n | { valid: true; plan: Plan }\n | { valid: false; issues: PlanValidationIssue[]; reason: string };\n\n/** Validates a plan object (ids/order filled by the caller). */\nexport function validatePlan(plan: Plan): PlanValidationResult {\n const issues: PlanValidationIssue[] = [];\n const stepIds = new Set<string>();\n\n for (const [index, step] of plan.steps.entries()) {\n if (stepIds.has(step.id)) {\n issues.push({ path: `steps.${index}.id`, message: `duplicate step id \"${step.id}\"` });\n }\n stepIds.add(step.id);\n if (!step.title || step.title.trim().length === 0) {\n issues.push({ path: `steps.${index}.title`, message: \"title must not be empty\" });\n }\n for (const dep of step.dependsOn ?? []) {\n if (!stepIds.has(dep) && !plan.steps.some((s) => s.id === dep)) {\n issues.push({ path: `steps.${index}.dependsOn`, message: `unknown step dependency \"${dep}\"` });\n }\n }\n }\n\n if (plan.steps.length === 0) {\n issues.push({ path: \"steps\", message: \"a plan needs at least one step\" });\n }\n if (!plan.summary || plan.summary.trim().length === 0) {\n issues.push({ path: \"summary\", message: \"summary must not be empty\" });\n }\n\n return issues.length > 0\n ? { valid: false, issues, reason: `plan failed validation (${issues.length} issue(s))` }\n : { valid: true, plan };\n}\n\n/** Builds the parser input type for model-produced plan JSON. */\nexport type PlanJsonInput = z.input<typeof planJsonSchema>;\n","/**\n * Planner context builder (§15, Planner Input): assembles the original task,\n * project context, agent reports, aggregated findings, relevant memory and\n * constraints into one structured input, in that order.\n */\nimport type { PlanRequest } from \"./types.js\";\nimport type { Report } from \"../types/report.js\";\n\nexport function buildPlannerContext(request: PlanRequest): string {\n const parts: string[] = [`# Task\\n${request.objective}`];\n\n if (request.projectContext) {\n parts.push(`# Project context\\n${request.projectContext}`);\n }\n\n if (request.role) {\n const roleLines = [`# Role\\n${request.role.name} (${request.role.id})`];\n if (request.role.responsibilities.length > 0) {\n roleLines.push(\"Responsibilities:\", ...request.role.responsibilities.map((r) => `- ${r}`));\n }\n if (request.role.expectedOutputs.length > 0) {\n roleLines.push(\"Expected outputs:\", ...request.role.expectedOutputs.map((o) => `- ${o}`));\n }\n parts.push(roleLines.join(\"\\n\"));\n }\n\n if (request.reports.length > 0) {\n const agents = [...new Set(request.reports.map((r) => r.agent))].join(\", \");\n const findingLines = request.reports.flatMap((report: Report) =>\n report.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (source: ${report.agent}, finding: ${finding.id})` +\n (finding.detail ? ` — ${finding.detail}` : \"\"),\n ),\n );\n parts.push(\n `# Agent reports (${request.reports.length} by ${agents})\\n` +\n (findingLines.length > 0 ? findingLines.join(\"\\n\") : \"(no findings reported)\"),\n );\n\n const recommendationLines = request.reports.flatMap((report) =>\n report.recommendations.map((text) => `- ${text} (source: ${report.agent})`),\n );\n if (recommendationLines.length > 0) {\n parts.push(`# Recommendations\\n${recommendationLines.join(\"\\n\")}`);\n }\n }\n\n if (request.aggregated) {\n const aggregatedLines = [\n `- findings: ${request.aggregated.findings.length} (agreements: ${request.aggregated.agreements.length}, conflicts: ${request.aggregated.conflicts.length})`,\n ...request.aggregated.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences})`,\n ),\n // Conflicts stay visible to the planner — it must plan around disagreement.\n ...request.aggregated.conflicts.map(\n (conflict) => `- CONFLICT (${conflict.type}) on \"${conflict.findingTitle}\": ${conflict.note}`,\n ),\n ];\n parts.push(`# Aggregated findings\\n${aggregatedLines.join(\"\\n\")}`);\n }\n\n if (request.memory && request.memory.length > 0) {\n parts.push(\n `# Relevant memory\\n` +\n request.memory.map((entry) => `- [${entry.scope}] ${entry.content}`).join(\"\\n\"),\n );\n }\n\n if (request.constraints && request.constraints.length > 0) {\n parts.push(`# Constraints\\n${request.constraints.map((c) => `- ${c}`).join(\"\\n\")}`);\n }\n\n if (request.context) {\n parts.push(`# Research context\\n${request.context}`);\n }\n\n return parts.join(\"\\n\\n\");\n}\n","/**\n * Pipeline run persistence (§27 Phase 5 — pipeline state). Same\n * replaceable-store pattern as the task store, local-first JSON file.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { PipelineRun, PipelineRunStatus } from \"../types/pipeline.js\";\n\nexport interface PipelineRunFilter {\n pipelineId?: string;\n status?: PipelineRunStatus;\n}\n\nexport interface PipelineRunStore {\n save(run: PipelineRun): Promise<void>;\n get(id: string): Promise<PipelineRun | undefined>;\n list(filter?: PipelineRunFilter): Promise<PipelineRun[]>;\n}\n\nexport class FilePipelineRunStore extends JsonFileStore<PipelineRun> implements PipelineRunStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"pipelines.json\" });\n }\n\n save(run: PipelineRun): Promise<void> {\n return this.mutate((runs) => {\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n return [runs, undefined];\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return (await this.readAll()).find((r) => r.id === id);\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return (await this.readAll())\n .filter((run) => (filter.pipelineId ? run.pipelineId === filter.pipelineId : true))\n .filter((run) => (filter.status ? run.status === filter.status : true))\n .sort((a, b) => (a.startedAt ?? \"\").localeCompare(b.startedAt ?? \"\"));\n }\n}\n","/**\n * Plan persistence (§27 Phase 8 — planner result storage). Same\n * replaceable-store pattern as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Plan } from \"../types/plan.js\";\n\nexport interface PlanFilter {\n pipelineRunId?: string;\n taskId?: string;\n}\n\nexport interface PlanStore {\n save(plan: Plan): Promise<void>;\n get(id: string): Promise<Plan | undefined>;\n list(filter?: PlanFilter): Promise<Plan[]>;\n}\n\nexport class FilePlanStore extends JsonFileStore<Plan> implements PlanStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"plans.json\" });\n }\n\n save(plan: Plan): Promise<void> {\n return this.mutate((plans) => {\n const index = plans.findIndex((p) => p.id === plan.id);\n if (index >= 0) plans[index] = plan;\n else plans.push(plan);\n return [plans, undefined];\n });\n }\n\n async get(id: string): Promise<Plan | undefined> {\n return (await this.readAll()).find((p) => p.id === id);\n }\n\n async list(filter: PlanFilter = {}): Promise<Plan[]> {\n return (await this.readAll())\n .filter((plan) => (filter.pipelineRunId ? plan.pipelineRunId === filter.pipelineRunId : true))\n .filter((plan) => (filter.taskId ? plan.taskId === filter.taskId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/** Planner factory from project configuration (§18 — planner provider support). */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { ChatFn } from \"../types/chat.js\";\nimport { HeuristicPlanner } from \"./heuristic.js\";\nimport { ModelPlanner } from \"./model.js\";\nimport type { IPlanner } from \"./types.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport function buildPlanner(\n plannerConfig: AppConfig[\"project\"][\"planner\"],\n chat: ChatFn,\n log: Logger = logger,\n): IPlanner | undefined {\n if (!plannerConfig) return undefined;\n if (plannerConfig.kind === \"heuristic\") {\n return new HeuristicPlanner();\n }\n if (!plannerConfig.model) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n 'Planner kind \"model\" needs a model reference (\"provider:model-id\") in omninode.yaml.',\n );\n }\n return new ModelPlanner({\n model: plannerConfig.model,\n chat,\n ...(plannerConfig.instruction !== undefined ? { instruction: plannerConfig.instruction } : {}),\n fallback: new HeuristicPlanner(),\n log,\n });\n}\n","/**\n * Report normalization (§17): turns an agent's text output into a structured\n * Report by extracting findings, recommendations and evidence from\n * markdown-style sections. Deterministic heuristics; AI-assisted extraction\n * can layer on top later via the planner.\n */\nimport type { Finding, FindingSeverity, Report } from \"../types/report.js\";\n\nexport interface ExtractionMeta {\n taskId: string;\n agent: string;\n model?: string;\n}\n\nconst BULLET = /^(?:[-*•]|\\d+[.)])\\s+(.*)$/;\n\ninterface Section {\n heading: string;\n bullets: string[];\n}\n\nfunction parseSections(raw: string): Section[] {\n const sections: Section[] = [];\n let current: Section = { heading: \"\", bullets: [] };\n for (const line of raw.split(\"\\n\")) {\n const heading = /^(#{1,6})\\s+(.*)$/.exec(line.trim());\n if (heading) {\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n current = { heading: heading[2]?.toLowerCase() ?? \"\", bullets: [] };\n continue;\n }\n const bullet = BULLET.exec(line.trim());\n if (bullet && current.heading.length > 0) {\n current.bullets.push(bullet[1]?.trim() ?? \"\");\n }\n }\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n return sections;\n}\n\nfunction collectBullets(sections: Section[], patterns: RegExp[]): string[] {\n const matches = sections.filter((section) => patterns.some((p) => p.test(section.heading)));\n return matches.flatMap((section) => section.bullets).filter((b) => b.length > 0);\n}\n\nfunction guessSeverity(text: string): FindingSeverity | undefined {\n if (/critical|severe/i.test(text)) return \"critical\";\n if (/\\bhigh\\b|major/i.test(text)) return \"high\";\n if (/medium|moderate/i.test(text)) return \"medium\";\n if (/\\blow\\b|minor/i.test(text)) return \"low\";\n return undefined;\n}\n\nexport function extractReportFromText(raw: string, meta: ExtractionMeta): Report {\n const trimmed = raw.trim();\n const nonEmpty = trimmed\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n // Prefer a prose line over markdown headings/bullets for the summary.\n const proseLine =\n nonEmpty.find((line) => !line.startsWith(\"#\") && !BULLET.test(line)) ?? nonEmpty[0] ?? \"\";\n const cleaned = proseLine.replace(/^#{1,6}\\s+/, \"\").replace(BULLET, \"$1\");\n const summary = cleaned.length > 0 ? truncate(cleaned, 200) : \"(no output)\";\n\n const sections = parseSections(trimmed);\n const findingTexts = collectBullets(sections, [/finding/, /issue/, /problem/, /vulnerab/]);\n const recommendationTexts = collectBullets(sections, [/recommend/, /suggestion/, /next step/, /action/]);\n const evidenceTexts = collectBullets(sections, [/evidence/, /proof/, /log/]);\n\n const findings: Finding[] = findingTexts.map((text, index) => ({\n id: `${meta.taskId}-f-${index + 1}`,\n title: truncate(text, 120),\n detail: text,\n description: text,\n severity: guessSeverity(text),\n }));\n\n return {\n id: `${meta.taskId}-report`,\n taskId: meta.taskId,\n agent: meta.agent,\n ...(meta.model !== undefined ? { model: meta.model } : {}),\n summary,\n findings,\n recommendations: recommendationTexts.map((t) => truncate(t, 200)),\n ...(evidenceTexts.length > 0\n ? { evidence: evidenceTexts.map((excerpt) => ({ kind: \"observation\" as const, excerpt })) }\n : {}),\n metadata: evidenceTexts.length > 0 ? { evidenceCount: evidenceTexts.length } : undefined,\n createdAt: new Date().toISOString(),\n };\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report service (§16–§17): collects reports from finished tasks (structured\n * protocol reports when present, extraction from text otherwise), persists\n * them with source attribution and generates combined reports.\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Task } from \"../types/task.js\";\nimport type { Report, CombinedReport } from \"../types/report.js\";\nimport { aggregateReports, type AggregateOptions } from \"./aggregate.js\";\nimport { extractReportFromText } from \"./extract.js\";\nimport { validateReport } from \"./schema.js\";\nimport type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\n/** Serialized size budget for a single report (roadmap §17 — output limits). */\nexport const MAX_REPORT_BYTES = 256 * 1024;\n\nexport interface CollectionDiagnostics {\n collected: number;\n accepted: number;\n rejected: Array<{ key: string; reason: string; issues: string[] }>;\n}\n\nexport class ReportService {\n private readonly log: Logger;\n /** Rejected reports from the last collection (§13 — malformed never enters aggregation). */\n lastDiagnostics: CollectionDiagnostics = { collected: 0, accepted: 0, rejected: [] };\n\n constructor(\n private readonly store: ReportStore,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"reports\" });\n }\n\n get storeRef(): ReportStore {\n return this.store;\n }\n\n /** Normalizes finished tasks into reports (§17 — normalizer), validating each\n * one so malformed reports never reach aggregation (§13). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const candidates: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n candidates.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n candidates.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\n\n const reports: Report[] = [];\n const rejected: CollectionDiagnostics[\"rejected\"] = [];\n for (const candidate of candidates) {\n const size = Buffer.byteLength(JSON.stringify(candidate), \"utf8\");\n if (size > MAX_REPORT_BYTES) {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: `report exceeds the ${MAX_REPORT_BYTES} byte limit (${size} bytes)`,\n issues: [],\n });\n this.log.warn(`Rejected oversized report (${size} bytes).`);\n continue;\n }\n const result = validateReport(candidate);\n if (result.valid) {\n reports.push(result.report);\n } else {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: result.reason,\n issues: result.issues.map((issue) => `${issue.path}: ${issue.message}`),\n });\n this.log.warn(`Rejected malformed report: ${result.reason}`);\n }\n }\n this.lastDiagnostics = { collected: candidates.length, accepted: reports.length, rejected };\n return reports;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n if (reports.length === 0) return;\n await this.store.saveReports(reports);\n this.log.info(`Stored ${reports.length} report(s).`);\n }\n\n async generateCombined(reports: Report[], meta: CombinedMeta = {}): Promise<CombinedReport | undefined> {\n if (reports.length === 0) return undefined;\n const options: AggregateOptions = {\n ...(meta.objective !== undefined ? { objective: meta.objective } : {}),\n ...(meta.pipelineRunId !== undefined ? { pipelineRunId: meta.pipelineRunId } : {}),\n ...(meta.taskIds !== undefined ? { taskIds: meta.taskIds } : {}),\n };\n const combined = aggregateReports(reports, options);\n await this.store.saveCombined(combined);\n this.log.info(`Generated combined report ${combined.id}.`);\n return combined;\n }\n}\n","/**\n * Report persistence (§16 — report storage). Same replaceable-store and\n * serialized-write patterns as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { CombinedReport, Report } from \"../types/report.js\";\n\nexport interface ReportFilter {\n taskId?: string;\n agent?: string;\n}\n\nexport interface CombinedReportFilter {\n pipelineRunId?: string;\n}\n\nexport interface ReportStore {\n saveReports(reports: Report[]): Promise<void>;\n listReports(filter?: ReportFilter): Promise<Report[]>;\n saveCombined(combined: CombinedReport): Promise<void>;\n getCombined(id: string): Promise<CombinedReport | undefined>;\n listCombined(filter?: CombinedReportFilter): Promise<CombinedReport[]>;\n}\n\ntype StoreEntry = { kind: \"report\"; report: Report } | { kind: \"combined\"; combined: CombinedReport };\n\nexport class FileReportStore extends JsonFileStore<StoreEntry> implements ReportStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"reports.json\" });\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n await this.mutate((entries) => {\n for (const report of reports) {\n const index = entries.findIndex((e) => e.kind === \"report\" && e.report.id === report.id);\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n return [entries, undefined];\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"report\"; report: Report } => e.kind === \"report\")\n .map((e) => e.report)\n .filter((report) => (filter.taskId ? report.taskId === filter.taskId : true))\n .filter((report) => (filter.agent ? report.agent === filter.agent : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n\n async saveCombined(combined: CombinedReport): Promise<void> {\n await this.mutate((entries) => {\n const index = entries.findIndex((e) => e.kind === \"combined\" && e.combined.id === combined.id);\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n return [entries, undefined];\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n const found = (await this.readAll()).find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) => (filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","import type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildPlanner } from \"../planner/index.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { ReportService } from \"../reports/index.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { TaskEngine } from \"../tasks/index.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport { PipelineEngine, createDefaultChatFn } from \"./engine.js\";\nimport { FilePipelineRunStore } from \"./store.js\";\n\nexport function buildPipelineEngine(config: AppConfig, log: Logger = logger): PipelineEngine {\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n const chat = createDefaultChatFn(config.project.providers);\n const tasks = new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n return new PipelineEngine({\n tasks,\n agents,\n roles,\n providers: config.project.providers,\n store: new FilePipelineRunStore(),\n chat,\n ...(config.project.planner !== undefined\n ? { planner: buildPlanner(config.project.planner, chat, log) }\n : {}),\n plans: new FilePlanStore(),\n reports: new ReportService(new FileReportStore(), log),\n audit: new FileAuditLog(),\n log,\n });\n}\n","/**\n * Persistence layer (v2 Phase 12): one entry point to every local store,\n * the canonical storage interface names, and the migration path that upgrades\n * v1 data in place.\n */\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { LocalMemoryProvider } from \"../memory/local.js\";\nimport { FilePipelineRunStore } from \"../pipelines/store.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport {\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n type DocumentState,\n} from \"./json-file-store.js\";\nexport {\n JsonFileStore,\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n} from \"./json-file-store.js\";\nexport type { JsonDocument, DocumentState, JsonFileStoreOptions } from \"./json-file-store.js\";\n\n// Canonical storage interface names (roadmap §16). The v1 names above remain\n// the exported API; these aliases document the mapping.\nexport type { TaskStore, PipelineStore, ReportStore, PlanStore, MemoryStore, AuditStore } from \"./store-types.js\";\n\n/** Bundles every store for a single project directory. */\nexport class ProjectStores {\n readonly tasks: FileTaskStore;\n readonly pipelineRuns: FilePipelineRunStore;\n readonly reports: FileReportStore;\n readonly plans: FilePlanStore;\n readonly memory: LocalMemoryProvider;\n readonly audit: FileAuditLog;\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.tasks = new FileTaskStore(directory);\n this.pipelineRuns = new FilePipelineRunStore(directory);\n this.reports = new FileReportStore(directory);\n this.plans = new FilePlanStore(directory);\n this.memory = new LocalMemoryProvider(directory);\n this.audit = new FileAuditLog(directory);\n }\n}\n\nexport interface MigrationReport {\n file: string;\n state: DocumentState[\"status\"];\n before?: number;\n after?: number;\n migrated: boolean;\n note?: string;\n}\n\n/** Every persisted store file OmniNode manages in a project. */\nexport const STORE_FILES = [\n \"tasks.json\",\n \"pipelines.json\",\n \"reports.json\",\n \"plans.json\",\n \"memory.json\",\n] as const;\n\n/**\n * Migration (roadmap §16): inspects every store file, reports its schema\n * state, and — unless `checkOnly` — rewrites v1 documents at the current\n * schema version. Idempotent and safe: unknown/future versions are reported,\n * never rewritten.\n */\nexport async function migrateProjectStores(\n directory = `${process.cwd()}/.omninode`,\n options: { checkOnly?: boolean } = {},\n): Promise<MigrationReport[]> {\n const reports: MigrationReport[] = [];\n for (const file of STORE_FILES) {\n const path = `${directory}/${file}`;\n const state = await inspectDocument(path);\n if (state.status === \"missing\") {\n reports.push({ file, state: state.status, migrated: false });\n continue;\n }\n if (state.status === \"current\") {\n reports.push({ file, state: state.status, before: state.count, after: state.count, migrated: false });\n continue;\n }\n if (state.status === \"future\") {\n reports.push({\n file,\n state: state.status,\n migrated: false,\n note: `written by a newer OmniNode (schema v${state.schemaVersion}); not touched`,\n });\n continue;\n }\n if (state.status === \"corrupt\") {\n reports.push({ file, state: state.status, migrated: false, note: state.detail });\n continue;\n }\n // v1-legacy or empty: rewrite at the current schema version.\n const items = await readDocument<unknown>(path, undefined, false);\n if (!options.checkOnly) {\n await writeFileAtomic(path, `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, items }, null, 2)}\\n`);\n }\n const beforeCount = items.length;\n reports.push({\n file,\n state: state.status,\n before: beforeCount,\n after: items.length,\n migrated: !options.checkOnly,\n ...(options.checkOnly ? { note: \"would migrate\" } : {}),\n });\n }\n return reports;\n}\n","export const OMNINODE_VERSION = \"2.0.0-alpha.13\";\n"],"mappings":";AAyBO,IAAM,yBAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACCO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EAET,YAAY,MAAyB,SAAiB,UAAgC,CAAC,GAAG;AACxF,UAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AACvC,SAAK,OAAO,WAAW;AACvB,SAAK,OAAO;AACZ,SAAK,UAAU,QAAQ;AAAA,EACzB;AACF;AAEO,IAAM,cAAN,cAA0B,cAAc;AAAA,EAC7C,YACE,MACA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,gBAAN,cAA4B,cAAc;AAAA,EAC/C,YACE,MAKA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,aAAN,cAAyB,cAAc;AAAA,EAC5C,YACE,MACA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,YAAN,cAAwB,cAAc;AAAA,EAC3C,YACE,MACA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,gBAAN,cAA4B,cAAc;AAAA,EAC/C,YACE,MACA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,gBAA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nB,GAAI,QAAQ,YAAY,EAAE,MAAM,gBAAgB,IAAI,CAAC;AAAA,IACvD,CAAC;AAAA,EACH;AACA,SAAO;AACT;;;ACvHO,IAAM,mBAAmB;","names":["envelope","DEFAULT_TIMEOUT_MS","resolve","resolve","mkdir","readFile","dirname","mkdir","dirname","open","readFile","randomBytes","randomBytes","z","randomBytes","randomBytes","SEVERITY_RANK","truncate","randomBytes","z","randomBytes","randomBytes","truncate"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/task.ts","../src/errors/index.ts","../src/logger/index.ts","../src/config/schema.ts","../src/config/secrets.ts","../src/config/loader.ts","../src/config/default.ts","../src/providers/auth.ts","../src/providers/http.ts","../src/providers/errors.ts","../src/providers/openai-compatible/index.ts","../src/providers/omnihilbras/index.ts","../src/providers/factory.ts","../src/registry/index.ts","../src/agents/process/index.ts","../src/agent-protocol/version.ts","../src/agent-protocol/types.ts","../src/agent-protocol/codec.ts","../src/agent-protocol/handshake.ts","../src/agent-protocol/session.ts","../src/agents/cwd.ts","../src/agents/env.ts","../src/agents/adapters.ts","../src/agents/registry.ts","../src/agents/factory.ts","../src/roles/index.ts","../src/persistence/json-file-store.ts","../src/tasks/store.ts","../src/tasks/engine.ts","../src/audit/index.ts","../src/memory/base.ts","../src/memory/local.ts","../src/memory/remembera.ts","../src/memory/factory.ts","../src/memory/service.ts","../src/tasks/engine-factory.ts","../src/pipelines/engine.ts","../src/reports/aggregate.ts","../src/reports/schema.ts","../src/planner/heuristic.ts","../src/planner/model.ts","../src/planner/schema.ts","../src/planner/context.ts","../src/pipelines/store.ts","../src/planner/store.ts","../src/planner/factory.ts","../src/reports/extract.ts","../src/reports/service.ts","../src/reports/store.ts","../src/pipelines/engine-factory.ts","../src/persistence/index.ts","../src/version.ts"],"sourcesContent":["/** Task system: every operation becomes a Task (§13). */\nimport type { Report } from \"./report.js\";\n\n/**\n * Execution states (v2 Phase 2, roadmap §6.1).\n *\n * The crucial distinction: `unknown` means \"we cannot prove the outcome\" —\n * e.g. a process timeout after the agent may already have performed side\n * effects. It is deliberately NOT `failed`: retrying blindly could duplicate\n * work, and reporting failure would be a lie. Resolve it explicitly with\n * `task retry` (which starts a fresh execution) or by inspecting artifacts.\n */\nexport type TaskStatus =\n | \"created\"\n | \"queued\"\n | \"running\"\n | \"waiting\"\n | \"completed\"\n | \"failed\"\n | \"timed_out\"\n | \"cancelled\"\n | \"unknown\"\n | \"partially_completed\";\n\n/** States from which no further automatic transition happens. */\nexport const TERMINAL_TASK_STATUSES: readonly TaskStatus[] = [\n \"completed\",\n \"failed\",\n \"timed_out\",\n \"cancelled\",\n \"partially_completed\",\n];\n\n/** One execution attempt (roadmap §6.5 identity: task + attempt + execution id). */\nexport interface ExecutionRecord {\n executionId: string;\n attempt: number;\n startedAt: string;\n finishedAt: string;\n outcome: \"completed\" | \"failed\" | \"timed_out\" | \"unknown\" | \"cancelled\";\n error?: string;\n}\n\nexport interface TaskContext {\n project?: string;\n /** Paths or globs relevant to the task. */\n files?: string[];\n /** Free-form background injected into the prompt. */\n background?: string;\n /** Keys of memory entries pulled from the memory provider. */\n memoryKeys?: string[];\n}\n\nexport interface TaskResult {\n summary?: string;\n artifacts?: string[];\n reportId?: string;\n /** Structured reports produced by protocol-mode agents (Phase 6 builds on this). */\n reports?: Report[];\n /** Truncated verbatim agent output, kept for report extraction and audit. */\n rawOutput?: string;\n error?: string;\n finishedAt?: string;\n}\n\nexport interface Task {\n id: string;\n project?: string;\n /** Pipeline run that owns this task, when created by a pipeline. */\n pipelineId?: string;\n objective: string;\n /** Role id from the role system. */\n role?: string;\n /** Agent name from the agent registry. */\n agent?: string;\n context?: TaskContext;\n status: TaskStatus;\n createdAt: string;\n updatedAt: string;\n /** Number of engine.run attempts so far (0 = never executed). */\n attempt: number;\n /** Error from the most recent failed/unknown attempt. */\n lastError?: string;\n /** Recent execution attempts, newest last, bounded in length. */\n executions?: ExecutionRecord[];\n result?: TaskResult;\n}\n","/** Typed error hierarchy shared across the whole codebase (§4.1 — error model). */\n\nexport type OmniNodeErrorCode =\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n | \"PROVIDER_NOT_FOUND\"\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\"\n | \"AGENT_NOT_FOUND\"\n | \"AGENT_FAILED\"\n | \"AGENT_TIMEOUT\"\n | \"TASK_INVALID\"\n | \"TASK_NOT_FOUND\"\n | \"TASK_FAILED\"\n | \"PIPELINE_NOT_FOUND\"\n | \"PIPELINE_INVALID\"\n | \"PIPELINE_FAILED\"\n | \"PLANNER_FAILED\"\n | \"PLAN_INVALID\"\n | \"TASK_NOT_FOUND\"\n | \"PROVIDER_NOT_FOUND\"\n | \"PROTOCOL_VIOLATION\"\n | \"MEMORY_UNAVAILABLE\"\n | \"REPORT_NOT_FOUND\"\n | \"NOT_IMPLEMENTED\"\n | \"CLI_USAGE\"\n | \"INTERNAL\";\n\nexport interface OmniNodeErrorOptions {\n cause?: unknown;\n details?: Record<string, unknown>;\n}\n\nexport class OmniNodeError extends Error {\n readonly code: OmniNodeErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: OmniNodeErrorCode, message: string, options: OmniNodeErrorOptions = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.code = code;\n this.details = options.details;\n }\n}\n\nexport class ConfigError extends OmniNodeError {\n constructor(\n code: \"CONFIG_NOT_FOUND\" | \"CONFIG_INVALID\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class ProviderError extends OmniNodeError {\n constructor(\n code:\n | \"PROVIDER_NOT_FOUND\"\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class AgentError extends OmniNodeError {\n constructor(\n code: \"AGENT_NOT_FOUND\" | \"AGENT_FAILED\" | \"AGENT_TIMEOUT\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class TaskError extends OmniNodeError {\n constructor(\n code: \"TASK_INVALID\" | \"TASK_NOT_FOUND\" | \"TASK_FAILED\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class PipelineError extends OmniNodeError {\n constructor(\n code: \"PIPELINE_NOT_FOUND\" | \"PIPELINE_INVALID\" | \"PIPELINE_FAILED\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class ProtocolError extends OmniNodeError {\n constructor(message: string, options: OmniNodeErrorOptions = {}) {\n super(\"PROTOCOL_VIOLATION\", message, options);\n }\n}\n\nexport class PlannerError extends OmniNodeError {\n constructor(\n code: \"PLANNER_FAILED\" | \"PLAN_INVALID\",\n message: string,\n options: OmniNodeErrorOptions = {},\n ) {\n super(code, message, options);\n }\n}\n\nexport class MemoryError extends OmniNodeError {\n constructor(message: string, options: OmniNodeErrorOptions = {}) {\n super(\"MEMORY_UNAVAILABLE\", message, options);\n }\n}\n\nexport function isOmniNodeError(value: unknown): value is OmniNodeError {\n return value instanceof OmniNodeError;\n}\n","/** Leveled logger with a pluggable sink and child loggers (§4.1 — logging). */\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LogSink {\n write(level: LogLevel, line: string): void;\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\nexport interface WritableLike {\n write(chunk: string): unknown;\n}\n\nexport class ConsoleLogSink implements LogSink {\n constructor(private readonly stream: WritableLike = process.stderr) {}\n\n write(_level: LogLevel, line: string): void {\n this.stream.write(line + \"\\n\");\n }\n}\n\nexport type LogFormat = \"text\" | \"json\";\n\nexport interface LoggerOptions {\n level?: LogLevel;\n sink?: LogSink;\n /** \"text\" (default) or machine-readable \"json\" lines (roadmap §18). */\n format?: LogFormat;\n /** Structured fields attached to every line, e.g. { component: \"config\" }. */\n context?: Record<string, unknown>;\n}\n\nexport class Logger {\n level: LogLevel;\n format: LogFormat;\n private readonly sink: LogSink;\n private readonly context: Record<string, unknown>;\n\n constructor(options: LoggerOptions = {}) {\n this.level = options.level ?? \"info\";\n this.format = options.format ?? \"text\";\n this.sink = options.sink ?? new ConsoleLogSink();\n this.context = options.context ?? {};\n }\n\n child(context: Record<string, unknown>): Logger {\n return new Logger({\n level: this.level,\n format: this.format,\n sink: this.sink,\n context: { ...this.context, ...context },\n });\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log(\"debug\", message, data);\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log(\"info\", message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log(\"warn\", message, data);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log(\"error\", message, data);\n }\n\n private log(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) return;\n const at = new Date().toISOString();\n const merged = { ...this.context, ...data };\n if (this.format === \"json\") {\n this.sink.write(level, JSON.stringify({ at, level, message, ...merged }));\n return;\n }\n const parts = [at, level.toUpperCase(), message];\n if (Object.keys(merged).length > 0) {\n parts.push(JSON.stringify(merged));\n }\n this.sink.write(level, parts.join(\" \"));\n }\n}\n\n/** Default application logger. Writes to stderr so stdout stays clean for CLI output. */\nexport const logger = new Logger();\n\n/** Applies configuration (level/format) to the default logger — used by the CLI. */\nexport function configureLogger(options: { level?: LogLevel; format?: LogFormat }): void {\n if (options.level !== undefined) logger.level = options.level;\n if (options.format !== undefined) logger.format = options.format;\n}\n","/**\n * Configuration schema. The project file (omninode.yaml) uses snake_case keys\n * as shown in DEVELOPMENT_PLAN.md §7 and §23; the loader maps them onto the\n * camelCase TypeScript contracts in src/types.\n */\nimport { z } from \"zod\";\n\nexport const providerConfigSchema = z\n .object({\n name: z.string().min(1),\n type: z.enum([\"openai-compatible\", \"omnihilbras\", \"openrouter\", \"local\", \"custom\"]),\n base_url: z.string().url(),\n api_key_env_var: z.string().min(1).optional(),\n timeout_ms: z.number().int().positive().optional(),\n headers: z.record(z.string()).optional(),\n enabled: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const agentConfigSchema = z\n .object({\n name: z.string().min(1),\n /** \"cli\" agents communicate over stdin/stdout (process adapter). */\n type: z.enum([\"cli\", \"native\", \"process\"]).default(\"cli\"),\n command: z.string().min(1).optional(),\n args: z.array(z.string()).optional(),\n cwd: z.string().optional(),\n env: z.record(z.string()).optional(),\n input_mode: z.enum([\"stdin\", \"arg\", \"protocol\"]).default(\"stdin\"),\n timeout_ms: z.number().int().positive().optional(),\n inherit_env: z.boolean().optional(),\n env_policy: z.enum([\"inherit\", \"allowlist\", \"denylist\", \"explicit\"]).optional(),\n env_allowlist: z.array(z.string()).optional(),\n env_denylist: z.array(z.string()).optional(),\n max_output_bytes: z.number().int().positive().optional(),\n allow_external_cwd: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const roleConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"role id must be kebab-case\"),\n name: z.string().min(1),\n description: z.string().optional(),\n responsibilities: z.array(z.string()).default([]),\n expected_outputs: z.array(z.string()).default([]),\n preferred_agents: z.array(z.string()).optional(),\n system_prompt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const pipelineStepConfigSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"research\", \"collect\", \"analyze\", \"plan\", \"execute\", \"custom\"]),\n agents: z.array(z.string()).optional(),\n agent: z.string().optional(),\n model: z.string().optional(),\n depends_on: z.array(z.string()).optional(),\n retries: z.number().int().min(0).max(10).optional(),\n condition: z.enum([\"always\", \"on-success\", \"on-failure\"]).optional(),\n /** Constraints passed to the planner for plan steps (§15). */\n constraints: z.array(z.string()).optional(),\n })\n .strict();\n\nexport const pipelineConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"pipeline id must be kebab-case\"),\n name: z.string().optional(),\n objective: z.string().optional(),\n role: z.string().optional(),\n steps: z.array(pipelineStepConfigSchema).min(1),\n })\n .strict();\n\nexport const plannerConfigSchema = z\n .object({\n kind: z.enum([\"model\", \"heuristic\"]).default(\"model\"),\n model: z.string().optional(),\n instruction: z.string().optional(),\n })\n .strict();\n\nexport const projectConfigSchema = z\n .object({\n name: z.string().min(1),\n providers: z.array(providerConfigSchema).default([]),\n agents: z.array(agentConfigSchema).default([]),\n roles: z.array(roleConfigSchema).default([]),\n pipelines: z.array(pipelineConfigSchema).default([]),\n planner: plannerConfigSchema.optional(),\n memory: z\n .object({\n provider: z.string().min(1).default(\"local\"),\n base_url: z.string().url().optional(),\n api_key_env_var: z.string().min(1).optional(),\n /** When true, memory failures fail tasks instead of being tolerated (§12). */\n required: z.boolean().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const appConfigSchema = z\n .object({\n project: projectConfigSchema,\n logging: z\n .object({\n level: z.enum([\"debug\", \"info\", \"warn\", \"error\"]),\n format: z.enum([\"text\", \"json\"]).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type ProviderConfigYaml = z.infer<typeof providerConfigSchema>;\nexport type AgentConfigYaml = z.infer<typeof agentConfigSchema>;\nexport type RoleConfigYaml = z.infer<typeof roleConfigSchema>;\nexport type PipelineConfigYaml = z.infer<typeof pipelineConfigSchema>;\nexport type PipelineStepConfigYaml = z.infer<typeof pipelineStepConfigSchema>;\nexport type PlannerConfigYaml = z.infer<typeof plannerConfigSchema>;\nexport type ProjectConfigYaml = z.infer<typeof projectConfigSchema>;\nexport type AppConfigYaml = z.infer<typeof appConfigSchema>;\n","/**\n * Inline secret detection (roadmap §17, Secrets).\n *\n * OmniNode configuration must never contain literal credentials — only\n * environment-variable *references*. This scanner runs before the config is\n * parsed and reports anything that looks like an inline secret, so the file\n * is rejected before it can be committed or persisted.\n */\n\nexport interface SecretFinding {\n /** 1-based line number in the source. */\n line: number;\n /** The offending key, e.g. `api_key`. */\n key: string;\n /** Redacted excerpt — never echoes the value. */\n excerpt: string;\n}\n\n/** Keys that are references or placeholders, not secrets. */\nconst SAFE_KEY_SUFFIXES = [\"_env\", \"_env_var\", \"_file\", \"_path\", \"_ref\", \"_id\", \"_url\", \"_command\"];\n\nconst SECRET_KEY = /^\\s*([A-Za-z0-9_-]*(?:api[_-]?key|token|password|passwd|secret|credential)[A-Za-z0-9_-]*)\\s*:\\s*(.*)$/i;\n\n/** Values that are clearly references, not credentials. */\nconst SAFE_VALUE = /^\\s*(?:\\$\\{[^}]*\\}|\\$[A-Z_][A-Z0-9_]*|<[^>]*>|\"\"|''|null|~)\\s*$/i;\n\nexport function scanForInlineSecrets(source: string): SecretFinding[] {\n const findings: SecretFinding[] = [];\n source.split(\"\\n\").forEach((line, index) => {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\")) return; // comments are not credentials\n const match = SECRET_KEY.exec(line);\n if (!match) return;\n const key = match[1] ?? \"\";\n const rawValue = (match[2] ?? \"\").trim().replace(/,\\s*$/, \"\");\n const keyIsReference = SAFE_KEY_SUFFIXES.some((suffix) => key.toLowerCase().endsWith(suffix));\n if (keyIsReference) return;\n const value = rawValue.replace(/^[\"']|[\"']$/g, \"\");\n if (value.length === 0 || SAFE_VALUE.test(rawValue)) return;\n // Very short values are almost always placeholders, not credentials.\n if (value.length < 8) return;\n findings.push({\n line: index + 1,\n key,\n excerpt: `${key}: ${value.slice(0, 3)}… (${value.length} chars, redacted)`,\n });\n });\n return findings;\n}\n\n/** Formats findings as an actionable configuration error message. */\nexport function describeSecretFindings(file: string, findings: SecretFinding[]): string {\n const lines = findings.map((f) => ` line ${f.line}: ${f.excerpt}`).join(\"\\n\");\n return (\n `${file} appears to contain ${findings.length} inline secret(s):\\n${lines}\\n` +\n `OmniNode never stores credentials in configuration. Replace each value with an ` +\n `environment-variable reference, e.g. api_key_env_var: MY_API_KEY.`\n );\n}\n","/**\n * Configuration loader: discovers omninode.yaml, expands ${ENV_VAR}\n * references (so credentials never live in project files, §24), validates it\n * and maps it onto the core TypeScript contracts.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport { ConfigError } from \"../errors/index.js\";\nimport { describeSecretFindings, scanForInlineSecrets } from \"./secrets.js\";\nimport type { AgentConfig, AgentIntegrationType } from \"../types/agent.js\";\nimport type { ProviderConfig } from \"../types/provider.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type { LogLevel } from \"../logger/index.js\";\nimport { appConfigSchema } from \"./schema.js\";\nimport type { AgentConfigYaml, PipelineConfigYaml, ProviderConfigYaml, RoleConfigYaml } from \"./schema.js\";\nimport type { PipelineDefinition } from \"../types/pipeline.js\";\n\nconst CONFIG_FILENAMES = [\"omninode.yaml\", \"omninode.yml\", \"omninode.json\"];\n\nexport interface AppConfig {\n project: {\n name: string;\n providers: ProviderConfig[];\n agents: AgentConfig[];\n roles: RoleDefinition[];\n pipelines: PipelineDefinition[];\n planner?: {\n kind: \"model\" | \"heuristic\";\n model?: string;\n instruction?: string;\n };\n memory?: {\n provider: string;\n baseUrl?: string;\n apiKeyEnvVar?: string;\n required?: boolean;\n };\n };\n logging?: {\n level: LogLevel;\n };\n}\n\nexport interface LoadConfigOptions {\n /** Explicit path; otherwise omninode.yaml/yml/json is looked up in the given directory. */\n path?: string;\n directory?: string;\n /** Environment used for ${VAR} expansion; defaults to process.env. */\n env?: Record<string, string | undefined>;\n}\n\nexport function findConfigFile(directory = process.cwd()): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const candidate = `${directory}/${filename}`;\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/**\n * Replaces ${VAR} and ${VAR:-fallback} references. Unset variables without a\n * fallback abort loading: a half-resolved config could silently misroute\n * authentication.\n */\nexport function expandEnvRefs(\n text: string,\n env: Record<string, string | undefined>,\n source = \"config\",\n): string {\n return text.replace(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g,\n (_match, name: string, fallback?: string) => {\n const value = env[name] ?? fallback;\n if (value === undefined) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Environment variable \"${name}\" is referenced in ${source} but is not set and has no default.`,\n );\n }\n return value;\n },\n );\n}\n\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n const env = options.env ?? process.env;\n const path = options.path ?? (options.directory ? findConfigFile(options.directory) : findConfigFile());\n if (!path) {\n throw new ConfigError(\n \"CONFIG_NOT_FOUND\",\n \"No omninode.yaml found. Run `omninode init` to create one, or pass an explicit path.\",\n );\n }\n\n const raw = readFileSync(path, \"utf8\");\n // §13 Security: refuse inline credentials before anything is persisted.\n const secretFindings = scanForInlineSecrets(raw);\n if (secretFindings.length > 0) {\n throw new ConfigError(\"CONFIG_INVALID\", describeSecretFindings(path, secretFindings));\n }\n const expanded = expandEnvRefs(raw, env, path);\n\n let data: unknown;\n try {\n data = parseYaml(expanded);\n } catch (error) {\n throw new ConfigError(\"CONFIG_INVALID\", `Failed to parse ${path}.`, { cause: error });\n }\n\n const parsed = appConfigSchema.safeParse(data);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => {\n const location = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n return `${location}: ${issue.message}`;\n });\n throw new ConfigError(\"CONFIG_INVALID\", `Invalid configuration in ${path}.`, {\n details: { issues },\n });\n }\n\n return toAppConfig(parsed.data);\n}\n\nfunction toAppConfig(yaml: ReturnType<typeof appConfigSchema.parse>): AppConfig {\n return {\n project: {\n name: yaml.project.name,\n providers: yaml.project.providers.map(toProviderConfig),\n agents: yaml.project.agents.map(toAgentConfig),\n roles: yaml.project.roles.map(toRoleDefinition),\n pipelines: yaml.project.pipelines.map(toPipelineDefinition),\n ...(yaml.project.planner !== undefined\n ? {\n planner: {\n kind: yaml.project.planner.kind,\n model: yaml.project.planner.model,\n instruction: yaml.project.planner.instruction,\n },\n }\n : {}),\n ...(yaml.project.memory !== undefined\n ? {\n memory: {\n provider: yaml.project.memory.provider,\n baseUrl: yaml.project.memory.base_url,\n apiKeyEnvVar: yaml.project.memory.api_key_env_var,\n required: yaml.project.memory.required,\n },\n }\n : {}),\n },\n ...(yaml.logging !== undefined ? { logging: yaml.logging } : {}),\n };\n}\n\nfunction toPipelineDefinition(raw: PipelineConfigYaml): PipelineDefinition {\n return {\n id: raw.id,\n name: raw.name,\n objective: raw.objective,\n role: raw.role,\n steps: raw.steps.map((step) => ({\n id: step.id,\n kind: step.kind,\n agents: step.agents,\n agent: step.agent,\n model: step.model,\n dependsOn: step.depends_on,\n retries: step.retries,\n condition: step.condition,\n constraints: step.constraints,\n })),\n };\n}\n\nfunction toProviderConfig(raw: ProviderConfigYaml): ProviderConfig {\n return {\n name: raw.name,\n type: raw.type,\n baseUrl: raw.base_url,\n apiKeyEnvVar: raw.api_key_env_var,\n timeoutMs: raw.timeout_ms,\n headers: raw.headers,\n enabled: raw.enabled,\n metadata: raw.metadata,\n };\n}\n\nfunction toAgentConfig(raw: AgentConfigYaml): AgentConfig {\n const integration: AgentIntegrationType =\n raw.type === \"native\" ? \"native\" : \"process\";\n return {\n name: raw.name,\n integration,\n command: raw.command,\n args: raw.args,\n cwd: raw.cwd,\n env: raw.env,\n inputMode: raw.input_mode,\n timeoutMs: raw.timeout_ms,\n inheritEnv: raw.inherit_env,\n envPolicy: raw.env_policy,\n envAllowlist: raw.env_allowlist,\n envDenylist: raw.env_denylist,\n maxOutputBytes: raw.max_output_bytes,\n allowExternalCwd: raw.allow_external_cwd,\n metadata: raw.metadata,\n };\n}\n\nfunction toRoleDefinition(raw: RoleConfigYaml): RoleDefinition {\n return {\n id: raw.id,\n name: raw.name,\n description: raw.description,\n responsibilities: raw.responsibilities,\n expectedOutputs: raw.expected_outputs,\n preferredAgents: raw.preferred_agents,\n systemPrompt: raw.system_prompt,\n metadata: raw.metadata,\n };\n}\n\n","/** Template written by `omninode init` (§22, §23). */\n\nexport function defaultProjectConfigYaml(projectName = \"My Project\"): string {\n return `project:\n name: ${projectName}\n\n # Providers connect OmniNode to AI model gateways (Phase 1+).\n # Credentials are referenced by environment variable, never stored in this file.\n providers: []\n # - name: my-gateway\n # type: openai-compatible\n # base_url: https://example.com/v1\n # api_key_env_var: MY_API_KEY\n\n # CLI agents registered with OmniNode (Phase 3 wires them up).\n agents: []\n # - name: opencode\n # type: cli\n # command: opencode\n\n # Roles describe what an AI is supposed to do (Phase 4).\n roles: []\n # - id: architecture-reviewer\n # name: Architecture Reviewer\n # responsibilities:\n # - architecture analysis\n # expected_outputs:\n # - findings\n # - recommendations\n\n # Memory is optional; Remembera is the preferred integration (Phase 7).\n # memory:\n # provider: remembera\n`;\n}\n","/**\n * Authentication resolution (§24): API keys live in the environment and are\n * referenced from configuration by variable name — never stored in files.\n */\nimport { ProviderError } from \"../errors/index.js\";\n// AuthRef is structurally satisfied by ProviderConfig.\n\n/** Minimal provider identity — any config object with a name and optional env var reference. */\nexport interface AuthRef {\n name: string;\n apiKeyEnvVar?: string;\n headers?: Record<string, string>;\n}\n\nexport function resolveApiKey(\n config: AuthRef,\n env: Record<string, string | undefined> = process.env,\n): string | undefined {\n if (!config.apiKeyEnvVar) return undefined;\n const value = env[config.apiKeyEnvVar];\n if (!value) {\n throw new ProviderError(\n \"PROVIDER_AUTH_FAILED\",\n `Environment variable \"${config.apiKeyEnvVar}\" (referenced by provider \"${config.name}\") is not set.`,\n );\n }\n return value;\n}\n\nexport function authHeaders(\n config: AuthRef,\n env: Record<string, string | undefined> = process.env,\n): Record<string, string> {\n const key = resolveApiKey(config, env);\n const base = { ...(config.headers ?? {}) };\n return key ? { ...base, authorization: `Bearer ${key}` } : base;\n}\n","/**\n * Thin JSON HTTP layer over global fetch. HTTP error statuses are returned to\n * the caller, not thrown — provider methods interpret them; only transport\n * failures (network, timeout, unparseable body) throw.\n */\n/** Raised for malformed provider responses so adapters can classify them. */\nexport class HttpResponseError extends Error {\n constructor(message: string, readonly status: number, cause?: unknown) {\n super(message, { cause });\n this.name = \"HttpResponseError\";\n }\n}\n\nexport interface HttpRequestOptions {\n method?: \"GET\" | \"POST\";\n headers?: Record<string, string>;\n body?: unknown;\n timeoutMs?: number;\n}\n\nexport interface HttpResponse {\n status: number;\n body: unknown;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nexport async function requestJson(\n url: string,\n options: HttpRequestOptions = {},\n): Promise<HttpResponse> {\n const { method = \"GET\", headers = {}, body, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\n // Transport failures propagate raw: adapters normalize them into provider\n // error kinds (roadmap §10).\n const response: Response = await fetch(url, {\n method,\n headers: {\n accept: \"application/json\",\n ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n ...headers,\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch (error) {\n throw new HttpResponseError(`Response from ${url} was not valid JSON.`, response.status, error);\n }\n\n return { status: response.status, body: parsed };\n}\n","/**\n * Provider error normalization (roadmap §10).\n *\n * Every provider failure is mapped to one stable kind, so callers can react\n * (retry a rate limit, surface an auth problem, treat a missing model\n * differently) without string-matching provider-specific payloads.\n */\nimport { ProviderError } from \"../errors/index.js\";\n\nexport type ProviderErrorKind =\n | \"AUTHENTICATION_ERROR\"\n | \"RATE_LIMIT_ERROR\"\n | \"INVALID_REQUEST\"\n | \"MODEL_NOT_FOUND\"\n | \"TIMEOUT\"\n | \"NETWORK_ERROR\"\n | \"SERVER_ERROR\"\n | \"UNKNOWN_ERROR\";\n\nexport interface ProviderErrorContext {\n provider: string;\n operation: string;\n status?: number;\n body?: unknown;\n retryAfterMs?: number;\n cause?: unknown;\n /** Maps the normalized kind onto the legacy stable error code. */\n code?:\n | \"PROVIDER_UNAVAILABLE\"\n | \"PROVIDER_AUTH_FAILED\"\n | \"MODEL_NOT_FOUND\";\n}\n\nfunction kindToCode(kind: ProviderErrorKind): NonNullable<ProviderErrorContext[\"code\"]> {\n switch (kind) {\n case \"AUTHENTICATION_ERROR\":\n return \"PROVIDER_AUTH_FAILED\";\n case \"MODEL_NOT_FOUND\":\n return \"MODEL_NOT_FOUND\";\n default:\n return \"PROVIDER_UNAVAILABLE\";\n }\n}\n\n/** Kinds worth retrying automatically (rate limits and transient server errors). */\nexport function isRetryable(kind: ProviderErrorKind): boolean {\n return kind === \"RATE_LIMIT_ERROR\" || kind === \"SERVER_ERROR\" || kind === \"NETWORK_ERROR\";\n}\n\n/** Maps an HTTP status (and optional body) to a normalized kind. */\nexport function kindFromStatus(status: number): ProviderErrorKind {\n if (status === 401 || status === 403) return \"AUTHENTICATION_ERROR\";\n if (status === 429) return \"RATE_LIMIT_ERROR\";\n if (status === 404) return \"MODEL_NOT_FOUND\";\n if (status === 408 || status === 504) return \"TIMEOUT\";\n if (status >= 500) return \"SERVER_ERROR\";\n if (status >= 400) return \"INVALID_REQUEST\";\n return \"UNKNOWN_ERROR\";\n}\n\n/** Extracts a human message from common provider error body shapes. */\nexport function extractMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const root = body as Record<string, unknown>;\n const error = (root.error ?? root) as Record<string, unknown>;\n const message = error.message ?? error.detail ?? root.message;\n return typeof message === \"string\" ? message : undefined;\n}\n\n/** Parses `Retry-After` (seconds or HTTP-date) into milliseconds. */\nexport function parseRetryAfter(value: string | null | undefined, now = Date.now()): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/** True for the abort/timeout errors raised by fetch's AbortSignal.timeout. */\nexport function isTimeoutError(error: unknown): boolean {\n return (\n (error instanceof Error && (error.name === \"TimeoutError\" || error.name === \"AbortError\")) ||\n (typeof (error as { code?: string })?.code === \"string\" &&\n (error as { code?: string }).code === \"ABORT_ERR\")\n );\n}\n\n/** True for transport failures (DNS, refused, TLS, offline). */\nexport function isNetworkError(error: unknown): boolean {\n return error instanceof TypeError || (typeof (error as { cause?: unknown })?.cause === \"object\" && error instanceof Error && !(error as { code?: string }).code);\n}\n\n/**\n * Builds a normalized ProviderError from an HTTP failure.\n */\n/** Actionable fallback text per kind (used when the provider sent no message). */\nfunction fallbackMessage(kind: ProviderErrorKind, context: ProviderErrorContext, status: number): string {\n const { provider, operation } = context;\n switch (kind) {\n case \"AUTHENTICATION_ERROR\":\n return `Authentication with provider \"${provider}\" failed (HTTP ${status}). Check that the referenced API key is set and valid.`;\n case \"RATE_LIMIT_ERROR\":\n return `Provider \"${provider}\" rate-limited ${operation} (HTTP ${status}). Retry later.`;\n case \"MODEL_NOT_FOUND\":\n return `Provider \"${provider}\" does not expose the requested model (HTTP ${status}).`;\n case \"TIMEOUT\":\n return `Provider \"${provider}\" timed out during ${operation} (HTTP ${status}).`;\n case \"SERVER_ERROR\":\n return `Provider \"${provider}\" returned a server error during ${operation} (HTTP ${status}).`;\n case \"INVALID_REQUEST\":\n return `Provider \"${provider}\" rejected ${operation} as invalid (HTTP ${status}).`;\n default:\n return `Provider \"${provider}\" failed during ${operation} (HTTP ${status}).`;\n }\n}\n\nexport function providerHttpError(context: ProviderErrorContext): ProviderError {\n const status = context.status ?? 0;\n const kind = kindFromStatus(status);\n const detail = extractMessage(context.body);\n const retryAfterMs = context.retryAfterMs ?? parseRetryAfter(undefined);\n return new ProviderError(\n context.code ?? kindToCode(kind),\n detail ?? fallbackMessage(kind, context, status),\n {\n cause: context.cause,\n details: {\n kind,\n provider: context.provider,\n operation: context.operation,\n status,\n retryable: isRetryable(kind),\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n ...(detail ? { providerMessage: detail } : {}),\n },\n },\n );\n}\n\n/** Wraps a thrown transport/abort error into a normalized ProviderError. */\nexport function providerTransportError(context: Omit<ProviderErrorContext, \"status\" | \"body\">): ProviderError {\n const cause = context.cause;\n const kind: ProviderErrorKind = isTimeoutError(cause)\n ? \"TIMEOUT\"\n : cause instanceof SyntaxError || (cause as { name?: string })?.name === \"HttpResponseError\"\n ? \"UNKNOWN_ERROR\"\n : \"NETWORK_ERROR\";\n const message = context.cause instanceof Error ? context.cause.message : String(context.cause);\n return new ProviderError(\"PROVIDER_UNAVAILABLE\", `Provider request failed: ${message}`, {\n cause: context.cause,\n details: {\n kind,\n provider: context.provider,\n operation: context.operation,\n retryable: isRetryable(kind),\n },\n });\n}","/**\n * OpenAI-compatible provider adapter (§5, §7): works with OpenAI, OpenRouter,\n * local runtimes (Ollama/LM Studio/vLLM) and custom gateways that expose the\n * /models and /chat/completions endpoints.\n */\nimport { ProviderError } from \"../../errors/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\n\n/** Default provider request timeout when the config does not set one. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nimport type { ChatRequest, ChatResponse, ChatStreamChunk } from \"../../types/chat.js\";\nimport type { AuditSink } from \"../../audit/index.js\";\nimport type { Modality, ModelInfo } from \"../../types/model.js\";\nimport type { IChatProvider, ProviderConfig, ProviderStatus } from \"../../types/provider.js\";\nimport { authHeaders } from \"../auth.js\";\nimport { requestJson } from \"../http.js\";\nimport { providerHttpError, providerTransportError } from \"../errors.js\";\nimport type { ProviderAuthentication } from \"../../types/provider.js\";\n\ninterface OpenAIModelEntry {\n id?: unknown;\n name?: unknown;\n owned_by?: unknown;\n created?: unknown;\n context_length?: unknown;\n context_window?: unknown;\n input_modalities?: unknown;\n output_modalities?: unknown;\n supported_parameters?: unknown;\n}\n\ninterface OpenAIChatResponse {\n model?: unknown;\n choices?: unknown;\n usage?: unknown;\n}\n\nexport class OpenAICompatibleProvider implements IChatProvider {\n readonly config: ProviderConfig;\n readonly providerId: string;\n readonly authentication: ProviderAuthentication;\n private readonly log: Logger;\n /** Discovered models, so getModel() answers without another round-trip. */\n private discovered?: ModelInfo[];\n\n private readonly env: Record<string, string | undefined>;\n\n private readonly audit?: AuditSink;\n\n constructor(\n config: ProviderConfig,\n log: Logger = logger,\n env: Record<string, string | undefined> = process.env,\n audit?: AuditSink,\n ) {\n this.audit = audit;\n this.config = { ...config, baseUrl: normalizeBaseUrl(config.baseUrl) };\n this.env = env;\n this.providerId = config.providerId ?? config.name;\n this.authentication = {\n method: config.apiKeyEnvVar ? \"bearer\" : \"none\",\n ...(config.apiKeyEnvVar ? { envVar: config.apiKeyEnvVar } : {}),\n configured: config.apiKeyEnvVar ? Boolean(env[config.apiKeyEnvVar]) : true,\n };\n this.log = log.child({ provider: config.name });\n }\n\n /** Provider-level request timeout (roadmap §6.6/§11) with the shared default. */\n private get requestTimeoutMs(): number {\n return this.config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n }\n\n /** Authenticate + discover (roadmap §10, Model Discovery). */\n async connect(): Promise<ModelInfo[]> {\n authHeaders(this.config, this.env); // throws PROVIDER_AUTH_FAILED when the env var is unset\n const models = await this.listModels();\n this.discovered = models;\n return models;\n }\n\n async getModel(modelId: string): Promise<ModelInfo | undefined> {\n const models = this.discovered ?? (await this.connect());\n return models.find((m) => m.id === modelId);\n }\n\n /** Raw /models body (protected so adapters can capture gateway-level metadata). */\n protected async rawModelsResponse(): Promise<unknown> {\n const response = await this.modelsRequest();\n return response.body;\n }\n\n private async modelsRequest(): Promise<{ status: number; body: unknown }> {\n let response: { status: number; body: unknown };\n try {\n response = await requestJson(`${this.config.baseUrl}/models`, {\n headers: authHeaders(this.config, this.env),\n timeoutMs: this.requestTimeoutMs,\n });\n } catch (error) {\n if (error instanceof ProviderError) {\n await this.recordProviderError(\"listModels\", error);\n throw error; // auth problem — keep the precise error\n }\n const normalized = providerTransportError({\n provider: this.config.name,\n operation: \"listModels\",\n cause: error,\n });\n await this.recordProviderError(\"listModels\", normalized);\n throw normalized;\n }\n const { status, body } = response;\n if (status !== 200) {\n const httpError = providerHttpError({\n provider: this.config.name,\n operation: \"listModels\",\n status,\n body,\n });\n await this.recordProviderError(\"listModels\", httpError);\n throw httpError;\n }\n return response;\n }\n\n async listModels(): Promise<ModelInfo[]> {\n const body = await this.rawModelsResponse();\n\n const entries = extractModelEntries(body, this.config);\n const models: ModelInfo[] = [];\n let skipped = 0;\n for (const entry of entries) {\n if (typeof entry.id !== \"string\" || entry.id.length === 0) {\n skipped += 1;\n continue;\n }\n models.push(this.toModelInfo(entry as OpenAIModelEntry & { id: string }));\n }\n if (skipped > 0) {\n this.log.warn(`Skipped ${skipped} model entr(y/ies) without a valid id.`);\n }\n return models;\n }\n\n /** Maps a raw model entry onto the normalized metadata shape (§10). */\n private toModelInfo(entry: OpenAIModelEntry & { id: string }): ModelInfo {\n const parameters = Array.isArray(entry.supported_parameters)\n ? (entry.supported_parameters.filter((p): p is string => typeof p === \"string\") as string[])\n : undefined;\n const contextWindow =\n typeof entry.context_length === \"number\"\n ? entry.context_length\n : typeof entry.context_window === \"number\"\n ? entry.context_window\n : undefined;\n const inputTypes = normalizeModalities(entry.input_modalities);\n const outputTypes = normalizeModalities(entry.output_modalities);\n return {\n provider: this.config.name,\n id: entry.id,\n displayName: entry.id,\n ...(typeof entry.name === \"string\" ? { name: entry.name } : {}),\n status: \"available\",\n ...(contextWindow !== undefined ? { contextWindow } : {}),\n ...(inputTypes !== undefined ? { inputTypes } : {}),\n ...(outputTypes !== undefined ? { outputTypes } : {}),\n ...(parameters !== undefined\n ? {\n supportsTools: parameters.includes(\"tools\") || parameters.includes(\"tool_choice\"),\n supportsStructuredOutput: parameters.includes(\"response_format\"),\n supportsStreaming: parameters.includes(\"stream\"),\n }\n : {}),\n metadata: {\n ...(typeof entry.owned_by === \"string\" ? { ownedBy: entry.owned_by } : {}),\n ...(typeof entry.created === \"number\" ? { createdAt: entry.created } : {}),\n ...(parameters !== undefined ? { supportedParameters: parameters } : {}),\n },\n };\n }\n\n /** Streaming where the gateway supports it (§11). */\n stream(request: ChatRequest, onChunk: (chunk: ChatStreamChunk) => void): Promise<ChatResponse> {\n return streamChatCompletion(this.config, request, onChunk, this.env);\n }\n\n /** Provider errors are part of the audit trail (§14 correlation, §18 observability). */\n private async recordProviderError(operation: string, error: ProviderError): Promise<void> {\n await this.audit?.record({\n at: new Date().toISOString(),\n action: \"provider.error\",\n id: this.providerId,\n providerId: this.providerId,\n detail: {\n operation,\n code: error.code,\n kind: (error.details as { kind?: string } | undefined)?.kind,\n message: error.message,\n },\n });\n }\n\n async healthCheck(): Promise<ProviderStatus> {\n const lastCheckedAt = new Date().toISOString();\n try {\n const started = Date.now();\n const models = await this.listModels();\n return {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: \"healthy\",\n connected: true,\n modelCount: models.length,\n lastCheckedAt,\n message: `Discovered ${models.length} model(s) in ${Date.now() - started}ms.`,\n };\n } catch (error) {\n return {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: inferHealth(error),\n connected: false,\n modelCount: 0,\n lastCheckedAt,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async chat(request: ChatRequest): Promise<ChatResponse> {\n let response: { status: number; body: unknown };\n try {\n response = await requestJson(`${this.config.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: authHeaders(this.config, this.env),\n timeoutMs: this.requestTimeoutMs,\n body: {\n model: request.model,\n messages: request.messages,\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.maxTokens !== undefined ? { max_tokens: request.maxTokens } : {}),\n ...(request.stop !== undefined ? { stop: request.stop } : {}),\n },\n });\n } catch (error) {\n if (error instanceof ProviderError) {\n await this.recordProviderError(\"chat\", error);\n throw error;\n }\n const normalized = providerTransportError({ provider: this.config.name, operation: \"chat\", cause: error });\n await this.recordProviderError(\"chat\", normalized);\n throw normalized;\n }\n const { status, body } = response;\n\n if (status !== 200) {\n const httpError = providerHttpError({\n provider: this.config.name,\n operation: \"chat\",\n status,\n body,\n ...(status === 404\n ? {\n code: \"MODEL_NOT_FOUND\" as const,\n }\n : {}),\n });\n await this.recordProviderError(\"chat\", httpError);\n throw httpError;\n }\n\n const payload = body as OpenAIChatResponse;\n const choices = Array.isArray(payload.choices) ? payload.choices : [];\n const first = choices[0] as { message?: { content?: unknown }; finish_reason?: unknown } | undefined;\n if (!first || typeof first.message?.content !== \"string\") {\n throw unavailable(this.config, \"Chat completion response had no message content.\", status);\n }\n\n const usage = (payload.usage ?? {}) as {\n prompt_tokens?: unknown;\n completion_tokens?: unknown;\n total_tokens?: unknown;\n };\n\n return {\n model: typeof payload.model === \"string\" ? payload.model : request.model,\n content: first.message.content,\n finishReason: typeof first.finish_reason === \"string\" ? first.finish_reason : undefined,\n usage: {\n promptTokens: typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : undefined,\n completionTokens:\n typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : undefined,\n totalTokens: typeof usage.total_tokens === \"number\" ? usage.total_tokens : undefined,\n },\n raw: body,\n };\n }\n}\n\n/**\n * Streams a chat completion from an OpenAI-compatible SSE endpoint (§11).\n * Emits deltas through `onChunk` and returns the assembled response.\n */\nexport async function streamChatCompletion(\n config: ProviderConfig,\n request: ChatRequest,\n onChunk: (chunk: ChatStreamChunk) => void,\n env: Record<string, string | undefined> = process.env,\n): Promise<ChatResponse> {\n const baseUrl = normalizeBaseUrl(config.baseUrl);\n const timeoutMs = config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...authHeaders(config, env),\n },\n body: JSON.stringify({\n model: request.model,\n messages: request.messages,\n stream: true,\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.maxTokens !== undefined ? { max_tokens: request.maxTokens } : {}),\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw providerTransportError({ provider: config.name, operation: \"stream\", cause: error });\n }\n if (!response.ok) {\n const body: unknown = await response.json().catch(() => undefined);\n throw providerHttpError({ provider: config.name, operation: \"stream\", status: response.status, body });\n }\n if (!response.body) {\n throw providerHttpError({\n provider: config.name,\n operation: \"stream\",\n status: 500,\n body: { error: { message: \"streaming is not supported by this endpoint\" } },\n });\n }\n\n let content = \"\";\n let model = request.model;\n let finishReason: string | undefined;\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n for await (const piece of response.body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(piece, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n newline = buffer.indexOf(\"\\n\");\n if (line.length === 0 || line.startsWith(\":\")) continue;\n const data = line.startsWith(\"data:\") ? line.slice(5).trim() : line;\n if (data === \"[DONE]\") continue;\n let event: Record<string, unknown>;\n try {\n event = JSON.parse(data) as Record<string, unknown>;\n } catch {\n continue; // tolerate non-JSON SSE noise\n }\n if (typeof event.model === \"string\") model = event.model;\n const choices = Array.isArray(event.choices) ? event.choices : [];\n const first = choices[0] as { delta?: { content?: unknown }; finish_reason?: unknown } | undefined;\n const delta = typeof first?.delta?.content === \"string\" ? first.delta.content : \"\";\n if (delta.length > 0) content += delta;\n if (typeof first?.finish_reason === \"string\") finishReason = first.finish_reason;\n onChunk({ delta, ...(finishReason !== undefined ? { finishReason } : {}), raw: event });\n }\n }\n\n return { model, content, ...(finishReason !== undefined ? { finishReason } : {}) };\n}\n\n/** Normalizes provider modality lists (\"text\", [\"text\",\"image\"], …). */\nfunction normalizeModalities(value: unknown): Modality[] | undefined {\n const list = Array.isArray(value) ? value : typeof value === \"string\" ? [value] : undefined;\n if (!list) return undefined;\n const allowed = new Set<Modality>([\"text\", \"image\", \"audio\", \"video\", \"embedding\"]);\n const modalities = list.filter((m): m is Modality => typeof m === \"string\" && allowed.has(m as Modality));\n return modalities.length > 0 ? modalities : undefined;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction extractModelEntries(body: unknown, config: ProviderConfig): OpenAIModelEntry[] {\n if (Array.isArray(body)) return body as OpenAIModelEntry[];\n if (body !== null && typeof body === \"object\" && Array.isArray((body as { data?: unknown }).data)) {\n return (body as { data: OpenAIModelEntry[] }).data;\n }\n throw new ProviderError(\n \"PROVIDER_UNAVAILABLE\",\n `Provider \"${config.name}\" returned an unrecognized model list shape.`,\n { details: { endpoint: \"models\" } },\n );\n}\n\nfunction unavailable(config: ProviderConfig, message: string, status: number): ProviderError {\n return new ProviderError(\"PROVIDER_UNAVAILABLE\", `Provider \"${config.name}\": ${message}`, {\n details: { status },\n });\n}\n\nfunction inferHealth(error: unknown): \"degraded\" | \"unreachable\" {\n const status =\n error instanceof ProviderError && typeof error.details?.status === \"number\"\n ? error.details.status\n : undefined;\n return status !== undefined && status >= 500 ? \"degraded\" : \"unreachable\";\n}\n","/**\n * OmniHilbras provider adapter (§6, Phase 2).\n *\n * OmniHilbras is one provider source among many — always optional (§2: the\n * core runs with zero Hilbras dependencies). The gateway exposes an\n * OpenAI-compatible API surface, so this adapter rides the OpenAI-compatible\n * transport and implements the plan's connect flow on top of it:\n *\n * Connect → Authenticate → Fetch Models → Validate Models → Register\n */\nimport { resolveApiKey } from \"../auth.js\";\nimport { OpenAICompatibleProvider } from \"../openai-compatible/index.js\";\nimport type { ModelRegistry } from \"../../registry/index.js\";\nimport type { ModelInfo } from \"../../types/model.js\";\nimport type { ProviderStatus } from \"../../types/provider.js\";\n\nexport interface OmniHilbrasConnectionResult {\n status: ProviderStatus;\n /** Validated, deduplicated models — registered when a registry was given. */\n models: ModelInfo[];\n /** Model ids that appeared more than once in the gateway's list. */\n duplicates: string[];\n /** Number of models written into the registry (0 when no registry given). */\n registered: number;\n}\n\nexport class OmniHilbrasProvider extends OpenAICompatibleProvider {\n private gateway?: Record<string, unknown>;\n\n override async listModels(): Promise<ModelInfo[]> {\n // Capture gateway-level metadata from the discovery response, then\n // delegate to the shared OpenAI-compatible discovery.\n const raw = await this.rawModelsResponse();\n await this.extractGatewayMetadata(raw);\n const models = await super.listModels();\n return this.gateway\n ? models.map((model) => ({ ...model, metadata: { ...model.metadata, gateway: this.gateway } }))\n : models;\n }\n /**\n * Run the full connect flow. Throws on authentication or transport failure\n * (use healthCheck() for a non-throwing probe).\n */\n /**\n * Gateway metadata reported alongside the model list (gateway version, tier,\n * region…), kept separate from per-model metadata (§11 — provider metadata).\n */\n gatewayMetadata(): Record<string, unknown> | undefined {\n return this.gateway;\n }\n\n protected async extractGatewayMetadata(body: unknown): Promise<void> {\n if (body !== null && typeof body === \"object\") {\n const gateway = (body as Record<string, unknown>).gateway;\n if (gateway !== null && typeof gateway === \"object\") {\n this.gateway = gateway as Record<string, unknown>;\n }\n }\n }\n\n async connectAndRegister(registry?: ModelRegistry): Promise<OmniHilbrasConnectionResult> {\n // Authenticate — throws PROVIDER_AUTH_FAILED when the referenced env var is unset.\n const apiKey = resolveApiKey(this.config);\n\n // Fetch models — throws on transport errors and non-2xx responses.\n const discovered = await this.listModels();\n\n // Validate — deduplicate ids, annotate gateway metadata, force availability.\n const seen = new Set<string>();\n const models: ModelInfo[] = [];\n const duplicates: string[] = [];\n for (const model of discovered) {\n if (seen.has(model.id)) {\n duplicates.push(model.id);\n continue;\n }\n seen.add(model.id);\n models.push({\n ...model,\n provider: this.config.name,\n status: \"available\",\n metadata: { ...model.metadata, gateway: \"omnihilbras\" },\n });\n }\n\n // Register.\n if (registry) {\n for (const model of models) registry.register(model);\n }\n\n const message =\n `Authenticated${apiKey ? \" with API key\" : \" (no API key configured)\"}; ` +\n `validated ${models.length} unique model(s)` +\n (duplicates.length > 0 ? `, skipped ${duplicates.length} duplicate(s)` : \"\") +\n \".\";\n\n const status: ProviderStatus = {\n name: this.config.name,\n type: this.config.type,\n baseUrl: this.config.baseUrl,\n health: \"healthy\",\n connected: true,\n modelCount: models.length,\n lastCheckedAt: new Date().toISOString(),\n message,\n };\n\n return { status, models, duplicates, registered: registry ? models.length : 0 };\n }\n}\n","/**\n * Provider factory: builds adapter instances from configuration (§5, §7).\n * Custom and local gateways ride the OpenAI-compatible adapter unless a\n * dedicated one exists.\n */\nimport { OmniNodeError } from \"../errors/index.js\";\nimport type { AuditSink } from \"../audit/index.js\";\nimport type { IChatProvider, ProviderConfig, ProviderType } from \"../types/provider.js\";\nimport { OmniHilbrasProvider } from \"./omnihilbras/index.js\";\nimport { OpenAICompatibleProvider } from \"./openai-compatible/index.js\";\n\n/** Provider types served by the OpenAI-compatible adapter. */\nexport const OPENAI_COMPATIBLE_TYPES: readonly ProviderType[] = [\n \"openai-compatible\",\n \"openrouter\",\n \"local\",\n \"custom\",\n];\n\nexport interface CreateProviderOptions {\n /** Correlates provider errors in the audit log (§18). */\n audit?: AuditSink;\n env?: Record<string, string | undefined>;\n}\n\nexport function createProvider(config: ProviderConfig, options: CreateProviderOptions = {}): IChatProvider {\n const shared = {\n ...(options.env !== undefined ? { env: options.env } : {}),\n ...(options.audit !== undefined ? { audit: options.audit } : {}),\n };\n if (config.type === \"omnihilbras\") {\n return new OmniHilbrasProvider(config, undefined, options.env, options.audit);\n }\n if (OPENAI_COMPATIBLE_TYPES.includes(config.type)) {\n return new OpenAICompatibleProvider(config, undefined, options.env, options.audit);\n }\n void shared;\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Provider type \"${config.type}\" has no adapter yet.`);\n}\n","/**\n * Normalized model registry (§8): aggregates models discovered from all\n * configured providers under \"provider:model\" keys.\n */\nimport type { ModelCapabilities, ModelInfo } from \"../types/model.js\";\nimport type { IProvider } from \"../types/provider.js\";\n\nexport interface ModelFilter {\n provider?: string;\n capability?: keyof ModelCapabilities;\n}\n\nexport interface DiscoveryResult {\n provider: string;\n models: ModelInfo[];\n error?: Error;\n}\n\nexport function registryKey(provider: string, id: string): string {\n return `${provider}:${id}`;\n}\n\nexport class ModelRegistry {\n private readonly models = new Map<string, ModelInfo>();\n\n register(model: ModelInfo): void {\n this.models.set(registryKey(model.provider, model.id), model);\n }\n\n get(provider: string, id: string): ModelInfo | undefined {\n return this.models.get(registryKey(provider, id));\n }\n\n list(filter: ModelFilter = {}): ModelInfo[] {\n return [...this.models.values()]\n .filter((model) => (filter.provider ? model.provider === filter.provider : true))\n .filter((model) =>\n filter.capability ? model.capabilities?.[filter.capability] === true : true,\n )\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id));\n }\n\n /** Availability validation (§27 Phase 1): present in the registry and not retired. */\n isAvailable(provider: string, id: string): boolean {\n const model = this.get(provider, id);\n return model !== undefined && (model.status ?? \"available\") === \"available\";\n }\n\n /** Discover models from one provider and register them. */\n async discoverFrom(provider: IProvider): Promise<ModelInfo[]> {\n const discovered = await provider.listModels();\n for (const model of discovered) this.register(model);\n return discovered;\n }\n\n /** Discover from many providers; a failing provider does not abort the rest. */\n async discoverAll(providers: IProvider[]): Promise<DiscoveryResult[]> {\n return Promise.all(\n providers.map(async (provider) => {\n try {\n return {\n provider: provider.config.name,\n models: await this.discoverFrom(provider),\n };\n } catch (error) {\n return {\n provider: provider.config.name,\n models: [],\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n }\n}\n","/**\n * Process adapter (§9): runs CLI agents as child processes and communicates\n * over stdin/stdout, managing the process lifecycle, working directory,\n * environment, exit codes, logs and timeouts.\n *\n * Three input modes (§9, §21):\n * - \"stdin\": the composed task text is written to the agent's stdin.\n * - \"arg\": the composed task text is appended as the last command argument.\n * - \"protocol\": NodeToAgentMessage envelopes as JSON lines on stdin; the\n * agent answers with AgentToNodeMessage JSON lines (REPORT,\n * COMPLETION, ERROR, ...) whose structured payloads are parsed\n * into reports.\n */\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { AgentError } from \"../../errors/index.js\";\nimport { PROTOCOL_V2, ProtocolSession, type QuestionResponder } from \"../../agent-protocol/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\nimport type {\n AgentConfig,\n AgentInfo,\n AgentTaskInput,\n AgentTaskOutput,\n IAgent,\n} from \"../../types/agent.js\";\nimport type { Report } from \"../../types/report.js\";\nimport { validateWorkingDirectory } from \"../cwd.js\";\nimport { buildChildEnv } from \"../env.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\n/** Per-stream byte budget before output is truncated and the agent killed. */\nexport const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\nexport function composeTaskText(input: AgentTaskInput): string {\n const sections: string[] = [`# Objective\\n${input.objective}`];\n if (input.role) {\n const lines = [\"# Role\", `${input.role.name} (${input.role.id})`];\n if (input.role.responsibilities.length > 0) {\n lines.push(\"\", \"Responsibilities:\", ...input.role.responsibilities.map((r) => `- ${r}`));\n }\n if (input.role.expectedOutputs.length > 0) {\n lines.push(\"\", \"Expected outputs:\", ...input.role.expectedOutputs.map((o) => `- ${o}`));\n }\n sections.push(lines.join(\"\\n\"));\n }\n if (input.context) sections.push(`# Context\\n${input.context}`);\n if (input.instruction) sections.push(`# Instruction\\n${input.instruction}`);\n return sections.join(\"\\n\\n\");\n}\n\nfunction buildProtocolMessages(input: AgentTaskInput, agentName: string): string[] {\n // Protocol v2 envelopes with full correlation (roadmap §7.2, §7.4).\n const session = new ProtocolSession({\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n });\n return session.taskMessages(\n input.objective,\n input.role,\n input.context,\n input.instruction,\n );\n}\n\nexport class ProcessAgent implements IAgent {\n readonly config: AgentConfig;\n readonly info: AgentInfo;\n private readonly log: Logger;\n private readonly running = new Map<string, ChildProcess>();\n\n constructor(config: AgentConfig, log: Logger = logger) {\n if (!config.command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${config.name}\" has no command configured.`);\n }\n this.config = config;\n this.log = log.child({ agent: config.name });\n this.info = {\n name: config.name,\n integration: \"process\",\n command: config.command,\n cwd: config.cwd,\n status: \"ready\",\n capabilities: [config.inputMode ?? \"stdin\"],\n };\n }\n\n async run(input: AgentTaskInput): Promise<AgentTaskOutput> {\n const command = this.config.command;\n if (!command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${this.config.name}\" has no command configured.`);\n }\n const mode = this.config.inputMode ?? \"stdin\";\n const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n return new Promise<AgentTaskOutput>((resolve, reject) => {\n // Validate the working directory BEFORE spawning (roadmap §8): never\n // silently fall back to the OmniNode cwd.\n let cwd: string | undefined;\n try {\n cwd = validateWorkingDirectory(this.config.cwd, {\n allowExternal: this.config.allowExternalCwd,\n })?.cwd;\n } catch (error) {\n // Invalid working directory — fail before spawning anything.\n reject(error);\n return;\n }\n\n const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n ...(cwd !== undefined ? { cwd } : {}),\n env: buildChildEnv(this.config),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // Own process group so the whole tree can be terminated together\n // (roadmap §8: no orphaned children).\n ...(process.platform === \"win32\" ? {} : { detached: true }),\n },\n );\n this.running.set(input.taskId, child);\n GLOBAL_RUNNING.add(child);\n installSignalForwarding();\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let outputLimitExceeded = false;\n let settled = false;\n const maxOutputBytes = this.config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process tree.`);\n killTree(child, \"SIGTERM\");\n setTimeout(() => killTree(child, \"SIGKILL\"), KILL_GRACE_MS).unref();\n }, timeoutMs);\n\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n this.running.delete(input.taskId);\n GLOBAL_RUNNING.delete(child);\n finish();\n };\n\n // Output protection (roadmap §8): runaway/binary output is truncated at\n // a byte budget, and a flooding agent is killed rather than allowed to\n // exhaust memory.\n const collect = (into: \"stdout\" | \"stderr\", chunk: Buffer): void => {\n if (outputLimitExceeded) return;\n const text = sanitizeChunk(chunk);\n if (into === \"stdout\") {\n if (stdout.length + text.length > maxOutputBytes) {\n stdout = (stdout + text).slice(0, maxOutputBytes);\n outputLimitExceeded = true;\n this.log.warn(`Agent \"${this.config.name}\" exceeded the ${maxOutputBytes} byte output limit — killing it.`);\n killTree(child, \"SIGKILL\");\n return;\n }\n stdout += text;\n } else {\n if (stderr.length + text.length > maxOutputBytes) {\n stderr = (stderr + text).slice(0, maxOutputBytes);\n return;\n }\n stderr += text;\n }\n };\n child.stdout?.on(\"data\", (chunk: Buffer) => collect(\"stdout\", chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => collect(\"stderr\", chunk));\n\n // Agents that exit without reading stdin raise EPIPE on write — that is\n // not an agent failure, so the stream error is ignored.\n child.stdin?.on(\"error\", () => {});\n if (mode !== \"arg\") {\n const payload =\n mode === \"protocol\"\n ? buildProtocolMessages(input, this.config.name).join(\"\\n\") + \"\\n\"\n : composeTaskText(input) + \"\\n\";\n child.stdin?.write(payload);\n child.stdin?.end();\n }\n\n child.on(\"error\", (error) => {\n settle(() => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${this.config.name}\": command \"${command}\" was not found. Is it installed and on PATH?`,\n { cause: error },\n ),\n );\n return;\n }\n reject(\n new AgentError(\"AGENT_FAILED\", `Agent \"${this.config.name}\" failed to start: ${error.message}.`, {\n cause: error,\n }),\n );\n });\n });\n\n child.on(\"close\", (code, signal) => {\n settle(() => {\n if (timedOut) {\n reject(\n new AgentError(\n \"AGENT_TIMEOUT\",\n `Agent \"${this.config.name}\" timed out after ${timeoutMs}ms and was killed.`,\n {\n details: {\n operation: \"agent.run\",\n agent: this.config.name,\n durationMs: timeoutMs,\n // The process was started and may have performed side\n // effects before being killed — the outcome is unknown,\n // not failed (roadmap §6.3).\n dispatched: true,\n stdout: stdout.slice(0, 4000),\n stderr: stderr.slice(0, 2000),\n },\n },\n ),\n );\n return;\n }\n\n const logs = stderr.trim().length > 0 ? stderr.split(\"\\n\") : undefined;\n if (mode === \"protocol\") {\n // interpretProtocolRun can reject (e.g. protocol violations); throwing\n // inside this event callback would escape the promise entirely.\n try {\n resolve(\n interpretProtocolRun({\n input,\n agentName: this.config.name,\n stdout,\n exitCode: code,\n logs,\n }),\n );\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n const trimmed = stdout.trim();\n resolve({\n taskId: input.taskId,\n status: code === 0 && !outputLimitExceeded ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n ...(outputLimitExceeded\n ? { error: `Agent exceeded the ${maxOutputBytes} byte output limit and was terminated.` }\n : code === 0\n ? {}\n : { error: describeExit(code, signal) }),\n });\n });\n });\n });\n }\n\n /** Ask the agent to stop current work (SIGTERM). */\n async cancel(taskId: string): Promise<void> {\n const child = this.running.get(taskId);\n if (child) killTree(child, \"SIGTERM\");\n }\n\n runningTaskIds(): string[] {\n return [...this.running.keys()];\n }\n}\n\ninterface ProtocolRunInput {\n input: AgentTaskInput;\n agentName: string;\n stdout: string;\n exitCode: number | null;\n logs?: string[];\n responder?: QuestionResponder;\n}\n\nfunction interpretProtocolRun({\n input,\n agentName,\n stdout,\n exitCode,\n logs,\n responder,\n}: ProtocolRunInput): AgentTaskOutput {\n const session = new ProtocolSession(\n {\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n },\n { ...(responder !== undefined ? { responder } : {}) },\n );\n\n // The stream was drained line-by-line already; re-decode deterministically.\n for (const result of session.decoder.push(stdout)) {\n // handled synchronously below via handle(); questions are resolved eagerly\n session.handle(result);\n }\n for (const result of session.decoder.flush()) {\n session.handle(result);\n }\n\n const reports = session.reports\n .flatMap((payload) => (Array.isArray(payload) ? payload : [payload]))\n .map((payload, index) => normalizeReport(payload, input.taskId, agentName, index))\n .filter((report): report is NonNullable<typeof report> => report !== undefined);\n\n const trimmed = stdout.trim();\n const protocolBlock = {\n protocol: session.descriptor?.protocol ?? PROTOCOL_V2,\n legacy: !session.sawV2 && session.descriptor === undefined,\n ...(session.descriptor !== undefined ? { descriptor: session.descriptor } : {}),\n questions: session.questions,\n violations: session.violations.map((v) => `${v.code}: ${v.message}`),\n };\n\n if (session.errorMessage !== undefined) {\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: session.errorMessage,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n };\n }\n\n if (session.descriptor === undefined && session.violations.length > 0 && session.reports.length === 0 && session.completionSummary === undefined) {\n // Nothing usable parsed: protocol violation rather than silent success.\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: `agent produced no valid protocol messages: ${protocolBlock.violations.join(\"; \")}`,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n };\n }\n\n const completed = exitCode === 0 && session.completionSummary !== undefined;\n return {\n taskId: input.taskId,\n status: completed || exitCode === 0 ? (completed ? \"completed\" : \"completed\") : \"failed\",\n summary: session.completionSummary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n ...(exitCode !== 0 ? { error: `Process exited with code ${exitCode ?? \"unknown\"}` } : {}),\n };\n}\n\n/**\n * Every live agent process, so Ctrl-C / SIGTERM on OmniNode reaches the whole\n * tree instead of orphaning children (roadmap §8, signal handling).\n */\nconst GLOBAL_RUNNING = new Set<ChildProcess>();\nlet signalForwardingInstalled = false;\n\nfunction installSignalForwarding(): void {\n if (signalForwardingInstalled) return;\n signalForwardingInstalled = true;\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n for (const child of GLOBAL_RUNNING) {\n killTree(child, \"SIGTERM\");\n }\n });\n }\n}\n\n/** Kills a child and, on POSIX, its whole process group (roadmap §8 tree cleanup). */\nexport function killTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // Group already gone — fall through to direct kill.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // Process already exited.\n }\n}\n\n/** Human-readable exit reason, including signal terminations. */\nexport function describeExit(code: number | null, signal: NodeJS.Signals | null): string {\n if (signal !== null) {\n return signal === \"SIGKILL\"\n ? \"Process was killed (SIGKILL) — usually an external kill or OOM.\"\n : `Process terminated by signal ${signal}.`;\n }\n if (code === null) return \"Process terminated without an exit code.\";\n return `Process exited with code ${code}.`;\n}\n\n/**\n * Decodes a stdout/stderr chunk safely: invalid UTF-8 becomes replacement\n * characters and NUL bytes are stripped, so binary noise cannot poison the\n * protocol decoder or the terminal (roadmap §8, encoding hardening).\n */\nexport function sanitizeChunk(chunk: Buffer): string {\n return [...chunk.toString(\"utf8\")].filter((char) => char.charCodeAt(0) !== 0).join(\"\");\n}\n\n/** Normalizes a loose REPORT payload into a strict Report; drops malformed entries. */\nfunction normalizeReport(\n payload: unknown,\n taskId: string,\n agentName: string,\n index: number,\n): Report | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const raw = payload as Record<string, unknown>;\n if (typeof raw.summary !== \"string\") return undefined;\n return {\n id: typeof raw.id === \"string\" ? raw.id : `${taskId}-report-${index}`,\n taskId: typeof raw.taskId === \"string\" ? raw.taskId : taskId,\n agent: typeof raw.agent === \"string\" ? raw.agent : agentName,\n summary: raw.summary,\n findings: Array.isArray(raw.findings) ? (raw.findings as Report[\"findings\"]) : [],\n recommendations: Array.isArray(raw.recommendations) ? (raw.recommendations as string[]) : [],\n createdAt: typeof raw.createdAt === \"string\" ? raw.createdAt : new Date().toISOString(),\n };\n}\n\nfunction firstLine(text: string, maxLength = 200): string {\n const line = text.split(\"\\n\", 1)[0] ?? text;\n return line.length > maxLength ? `${line.slice(0, maxLength)}…` : line;\n}\n","/**\n * OmniNode Agent Protocol v2 — versioning (roadmap §7.1).\n *\n * Protocol identifiers are namespaced strings so an agent can negotiate the\n * dialect it speaks: `omninode-agent-protocol/2`.\n */\nexport const PROTOCOL_V2 = \"omninode-agent-protocol/2\";\n\n/** Versions this build accepts. v1 is the unversioned dialect shipped with OmniNode 1.x. */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n \"omninode-agent-protocol/1\",\n PROTOCOL_V2,\n];\n\nexport const MAX_MESSAGE_BYTES = 1_048_576; // 1 MiB per message line\n\nexport function isSupportedProtocol(protocol: string): boolean {\n return SUPPORTED_PROTOCOL_VERSIONS.includes(protocol);\n}","/**\n * OmniNode Agent Protocol v2 — message model (roadmap §7.2–§7.4, §7.7).\n *\n * Every message is a JSON line carrying a `ProtocolEnvelope`. All ids are\n * optional for inbound tolerance but OmniNode always emits them, so every\n * message is traceable to agent / task / pipeline / execution / request.\n */\nimport type { Report } from \"../types/report.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\n\n/** Messages OmniNode sends to an agent. */\nexport type ProtocolNodeToAgentType =\n | \"TASK\"\n | \"HELLO_ACK\"\n | \"CONTEXT\"\n | \"INSTRUCTION\"\n | \"RESPONSE\"\n | \"CANCEL\";\n\n/** Messages an agent sends to OmniNode. */\nexport type ProtocolAgentToNodeType =\n | \"HELLO\"\n | \"TASK_REQUEST\"\n | \"TASK_ACCEPTED\"\n | \"TASK_STARTED\"\n | \"STATUS\"\n | \"QUESTION\"\n | \"REPORT\"\n | \"ARTIFACT\"\n | \"COMPLETION\"\n | \"ERROR\"\n | \"CANCELLED\";\n\nexport type ProtocolMessageType = ProtocolNodeToAgentType | ProtocolAgentToNodeType;\n\nexport interface ProtocolEnvelope<T extends ProtocolMessageType = ProtocolMessageType> {\n /** `omninode-agent-protocol/2`. Inbound messages without it are treated as v1. */\n protocol: string;\n /** Unique id of this message. */\n messageId: string;\n /** Id of the request/thread this message belongs to. */\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n /** Execution identity (roadmap §6.5) — ties the message to one attempt. */\n executionId?: string;\n timestamp: string;\n type: T;\n payload: unknown;\n metadata?: Record<string, unknown>;\n}\n\n/** Standard artifact kinds (roadmap §7.7). */\nexport type ArtifactKind =\n | \"file\"\n | \"patch\"\n | \"report\"\n | \"log\"\n | \"screenshot\"\n | \"document\"\n | \"data\";\n\nexport interface ArtifactPayload {\n kind: ArtifactKind;\n /** Path, URL or logical name. */\n ref: string;\n description?: string;\n mediaType?: string;\n bytes?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface QuestionPayload {\n /** Question id to answer. */\n questionId: string;\n question: string;\n /** What kind of answer is expected (free text, file path, options…). */\n expected?: \"text\" | \"path\" | \"choice\";\n options?: string[];\n}\n\nexport interface TaskPayload {\n taskId: string;\n objective: string;\n}\n\nexport interface ReportPayload {\n report: Report | Report[];\n}\n\n/** A question an agent asked during a run, with the answer OmniNode gave (if any). */\nexport interface AskedQuestion {\n questionId: string;\n question: string;\n answer?: string;\n}\n\nexport function newMessageId(prefix = \"msg\"): string {\n const random = Math.random().toString(36).slice(2, 10);\n return `${prefix}-${Date.now().toString(36)}-${random}`;\n}\n\n/** Builds a v2 envelope with ids and timestamp filled in. */\nexport function envelope<T extends ProtocolMessageType>(\n type: T,\n payload: unknown,\n ids: {\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n executionId?: string;\n metadata?: Record<string, unknown>;\n } = {},\n): ProtocolEnvelope<T> {\n return {\n protocol: PROTOCOL_V2,\n messageId: newMessageId(),\n ...(ids.requestId !== undefined ? { requestId: ids.requestId } : {}),\n ...(ids.taskId !== undefined ? { taskId: ids.taskId } : {}),\n ...(ids.agentId !== undefined ? { agentId: ids.agentId } : {}),\n ...(ids.pipelineId !== undefined ? { pipelineId: ids.pipelineId } : {}),\n ...(ids.executionId !== undefined ? { executionId: ids.executionId } : {}),\n timestamp: new Date().toISOString(),\n type,\n payload,\n ...(ids.metadata !== undefined ? { metadata: ids.metadata } : {}),\n };\n}","/**\n * OmniNode Agent Protocol v2 — codec and validation (roadmap §7.5).\n *\n * Decoding NEVER throws: every failure is returned as a typed\n * `ProtocolViolation` with a machine-readable code, so a misbehaving agent\n * can never crash OmniNode.\n */\nimport {\n MAX_MESSAGE_BYTES,\n PROTOCOL_V2,\n isSupportedProtocol,\n} from \"./version.js\";\nimport type { ProtocolEnvelope, ProtocolMessageType } from \"./types.js\";\n\nexport type ProtocolViolationCode =\n | \"INVALID_JSON\"\n | \"NOT_AN_OBJECT\"\n | \"UNKNOWN_TYPE\"\n | \"MISSING_FIELD\"\n | \"UNSUPPORTED_VERSION\"\n | \"OVERSIZED\"\n | \"INVALID_PAYLOAD\";\n\nexport interface ProtocolViolation {\n code: ProtocolViolationCode;\n message: string;\n /** Raw line (truncated) for diagnostics. */\n sample?: string;\n}\n\nexport type DecodeResult =\n | { ok: true; envelope: ProtocolEnvelope; legacy: boolean }\n | { ok: false; error: ProtocolViolation };\n\nconst KNOWN_TYPES = new Set<string>([\n // node → agent\n \"TASK\", \"HELLO_ACK\", \"CONTEXT\", \"INSTRUCTION\", \"RESPONSE\", \"CANCEL\",\n // agent → node\n \"HELLO\", \"TASK_REQUEST\", \"TASK_ACCEPTED\", \"TASK_STARTED\", \"STATUS\",\n \"QUESTION\", \"REPORT\", \"ARTIFACT\", \"COMPLETION\", \"ERROR\", \"CANCELLED\",\n]);\n\nconst PAYLOAD_REQUIRED_TYPES = new Set<string>([\"TASK\", \"REPORT\", \"COMPLETION\", \"ERROR\", \"QUESTION\", \"ARTIFACT\", \"HELLO\"]);\n\n/** Validates one decoded JSON value as a protocol envelope. */\nexport function validateEnvelope(value: unknown, line?: string): DecodeResult {\n const sample = line?.slice(0, 200);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { ok: false, error: { code: \"NOT_AN_OBJECT\", message: \"message must be a JSON object\", ...(sample ? { sample } : {}) } };\n }\n const raw = value as Record<string, unknown>;\n\n // Version negotiation: absent protocol = v1 (OmniNode 1.x agents), else must be supported.\n const protocol = raw.protocol;\n if (protocol === undefined) {\n // legacy v1: requires a bare {type, payload} shape\n const type = raw.type;\n if (typeof type !== \"string\" || !KNOWN_TYPES.has(type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(type)}`, ...(sample ? { sample } : {}) } };\n }\n return {\n ok: true,\n legacy: true,\n envelope: {\n protocol: \"omninode-agent-protocol/1\",\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"legacy\",\n timestamp: new Date().toISOString(),\n type: type as ProtocolMessageType,\n payload: raw.payload,\n },\n };\n }\n if (typeof protocol !== \"string\" || !isSupportedProtocol(protocol)) {\n return {\n ok: false,\n error: { code: \"UNSUPPORTED_VERSION\", message: `unsupported protocol \"${String(protocol)}\"`, ...(sample ? { sample } : {}) },\n };\n }\n\n if (raw.type === undefined) {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"message is missing 'type'\", ...(sample ? { sample } : {}) } };\n }\n if (typeof raw.type !== \"string\" || !KNOWN_TYPES.has(raw.type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(raw.type)}`, ...(sample ? { sample } : {}) } };\n }\n if (raw.timestamp !== undefined && typeof raw.timestamp !== \"string\") {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"'timestamp' must be a string\", ...(sample ? { sample } : {}) } };\n }\n if (PAYLOAD_REQUIRED_TYPES.has(raw.type) && (raw.payload === undefined || raw.payload === null)) {\n return { ok: false, error: { code: \"INVALID_PAYLOAD\", message: `${raw.type} requires a payload`, ...(sample ? { sample } : {}) } };\n }\n\n return {\n ok: true,\n legacy: protocol !== PROTOCOL_V2,\n envelope: {\n protocol,\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"unknown\",\n ...(typeof raw.requestId === \"string\" ? { requestId: raw.requestId } : {}),\n ...(typeof raw.taskId === \"string\" ? { taskId: raw.taskId } : {}),\n ...(typeof raw.agentId === \"string\" ? { agentId: raw.agentId } : {}),\n ...(typeof raw.pipelineId === \"string\" ? { pipelineId: raw.pipelineId } : {}),\n ...(typeof raw.executionId === \"string\" ? { executionId: raw.executionId } : {}),\n timestamp: typeof raw.timestamp === \"string\" ? raw.timestamp : new Date().toISOString(),\n type: raw.type as ProtocolMessageType,\n payload: raw.payload,\n ...(raw.metadata !== null && typeof raw.metadata === \"object\" ? { metadata: raw.metadata as Record<string, unknown> } : {}),\n },\n };\n}\n\n/** Decodes one protocol line (no trailing newline). */\nexport function decodeMessage(line: string, maxBytes = MAX_MESSAGE_BYTES): DecodeResult {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n return { ok: false, error: { code: \"INVALID_JSON\", message: \"empty line\" } };\n }\n if (trimmed.length > maxBytes) {\n return {\n ok: false,\n error: { code: \"OVERSIZED\", message: `message of ${trimmed.length} bytes exceeds the ${maxBytes} byte limit`, sample: trimmed.slice(0, 200) },\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(trimmed);\n } catch (error) {\n return {\n ok: false,\n error: { code: \"INVALID_JSON\", message: error instanceof Error ? error.message : \"invalid JSON\", sample: trimmed.slice(0, 200) },\n };\n }\n return validateEnvelope(value, trimmed);\n}\n\n/** Serializes an envelope to a single JSON line. */\nexport function encodeMessage(envelope: ProtocolEnvelope, maxBytes = MAX_MESSAGE_BYTES): string {\n const line = JSON.stringify(envelope);\n if (line.length > maxBytes) {\n throw new Error(`outbound protocol message of ${line.length} bytes exceeds the ${maxBytes} byte limit`);\n }\n return line;\n}\n\n/**\n * Streaming line decoder for agent stdout. Feed chunks; receive decoded\n * envelopes and violations in order. Survives garbage: a bad line yields a\n * violation and the stream continues.\n */\nexport class ProtocolDecoder {\n private buffer = \"\";\n private readonly maxBytes: number;\n\n constructor(maxBytes = MAX_MESSAGE_BYTES) {\n this.maxBytes = maxBytes;\n }\n\n push(chunk: string): DecodeResult[] {\n this.buffer += chunk;\n const results: DecodeResult[] = [];\n let index = this.buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = this.buffer.slice(0, index);\n this.buffer = this.buffer.slice(index + 1);\n if (line.trim().length > 0) results.push(decodeMessage(line, this.maxBytes));\n index = this.buffer.indexOf(\"\\n\");\n }\n // Guard against an agent emitting an endless line with no newline.\n if (this.buffer.length > this.maxBytes) {\n results.push({\n ok: false,\n error: { code: \"OVERSIZED\", message: `line exceeded ${this.maxBytes} bytes without a newline`, sample: this.buffer.slice(0, 200) },\n });\n this.buffer = \"\";\n }\n return results;\n }\n\n /** Flush any trailing line when the process exits. */\n flush(): DecodeResult[] {\n if (this.buffer.trim().length === 0) {\n this.buffer = \"\";\n return [];\n }\n const result = decodeMessage(this.buffer, this.maxBytes);\n this.buffer = \"\";\n return [result];\n }\n}","/**\n * OmniNode Agent Protocol v2 — handshake (roadmap §7.1).\n *\n * An agent announces itself with HELLO; OmniNode replies with HELLO_ACK.\n * Handshakes are optional for v1-style agents (no HELLO = legacy dialect).\n */\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type ProtocolEnvelope } from \"./types.js\";\n\nexport interface AgentDescriptor {\n /** Protocol the agent speaks. */\n protocol: string;\n name: string;\n version?: string;\n capabilities: string[];\n /** Message types the agent can emit. */\n supports: string[];\n}\n\nexport type HelloResult =\n | { ok: true; descriptor: AgentDescriptor }\n | { ok: false; reason: string };\n\nexport function parseHello(envelopeValue: ProtocolEnvelope): HelloResult {\n if (envelopeValue.type !== \"HELLO\") {\n return { ok: false, reason: `expected HELLO, received ${envelopeValue.type}` };\n }\n const payload = envelopeValue.payload;\n if (payload === null || typeof payload !== \"object\") {\n return { ok: false, reason: \"HELLO payload must be an object\" };\n }\n const p = payload as Record<string, unknown>;\n if (typeof p.name !== \"string\" || p.name.length === 0) {\n return { ok: false, reason: \"HELLO payload is missing 'name'\" };\n }\n return {\n ok: true,\n descriptor: {\n protocol: envelopeValue.protocol,\n name: p.name,\n ...(typeof p.version === \"string\" ? { version: p.version } : {}),\n capabilities: Array.isArray(p.capabilities) ? p.capabilities.filter((c): c is string => typeof c === \"string\") : [],\n supports: Array.isArray(p.supports) ? p.supports.filter((s): s is string => typeof s === \"string\") : [],\n },\n };\n}\n\nexport function buildHello(descriptor: Omit<AgentDescriptor, \"protocol\">): ProtocolEnvelope<\"HELLO\"> {\n return envelope(\"HELLO\", descriptor, { agentId: descriptor.name });\n}\n\nexport function buildHelloAck(descriptor: AgentDescriptor): ProtocolEnvelope<\"HELLO_ACK\"> {\n return envelope(\"HELLO_ACK\", {\n ok: true,\n protocol: PROTOCOL_V2,\n agent: descriptor.name,\n ...(descriptor.version !== undefined ? { agentVersion: descriptor.version } : {}),\n supportedProtocols: [PROTOCOL_V2],\n }, { agentId: descriptor.name });\n}\n","/**\n * OmniNode Agent Protocol v2 — session (roadmap §7.6).\n *\n * A session drives a protocol-mode agent: it emits v2 envelopes with\n * correlation ids, tolerates legacy (unversioned) replies, answers agent\n * questions through a responder callback, and collects reports, artifacts\n * and the completion — never throwing on malformed input.\n */\nimport { decodeMessage, encodeMessage, ProtocolDecoder, type DecodeResult, type ProtocolViolation } from \"./codec.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type AskedQuestion, type ProtocolEnvelope } from \"./types.js\";\nimport { parseHello, buildHelloAck, type AgentDescriptor } from \"./handshake.js\";\nimport { ProtocolError } from \"../errors/index.js\";\n\nexport interface SessionIds {\n requestId: string;\n taskId: string;\n agentId: string;\n pipelineId?: string;\n executionId?: string;\n}\n\nexport interface QuestionResponder {\n (question: { questionId: string; question: string; expected?: string }): Promise<string> | string;\n}\n\nexport class ProtocolSession {\n readonly decoder: ProtocolDecoder;\n private readonly ids: SessionIds;\n private readonly responder: QuestionResponder | undefined;\n readonly violations: ProtocolViolation[] = [];\n readonly questions: AskedQuestion[] = [];\n readonly artifacts: ProtocolEnvelope[\"payload\"][] = [];\n reports: ProtocolEnvelope[\"payload\"][] = [];\n descriptor?: AgentDescriptor;\n completionSummary?: string;\n errorMessage?: string;\n\n constructor(ids: SessionIds, options: { responder?: QuestionResponder; maxBytes?: number } = {}) {\n this.ids = ids;\n this.responder = options.responder;\n this.decoder = new ProtocolDecoder(options.maxBytes);\n }\n\n /** The v2 messages OmniNode sends to open a task (written to the agent's stdin). */\n taskMessages(objective: string, role?: unknown, context?: string, instruction?: string): string[] {\n const ids = this.ids;\n const messages: ProtocolEnvelope[] = [envelope(\"TASK\", { taskId: ids.taskId, objective }, ids)];\n if (role !== undefined) messages.push(envelope(\"CONTEXT\", { role }, ids));\n if (context !== undefined && context.length > 0) messages.push(envelope(\"CONTEXT\", { body: context }, ids));\n if (instruction !== undefined && instruction.length > 0) messages.push(envelope(\"INSTRUCTION\", { text: instruction }, ids));\n return messages.map((m) => encodeMessage(m));\n }\n\n helloAck(descriptor: AgentDescriptor): string {\n return encodeMessage(buildHelloAck(descriptor));\n }\n\n /** Consumes decoded stdout, answering questions as they arrive. */\n async handle(decoded: DecodeResult): Promise<void> {\n if (!decoded.ok) {\n // Agent misbehavior is recorded, never fatal (§7.5).\n this.violations.push(decoded.error);\n return;\n }\n const message = decoded.envelope;\n if (message.protocol === PROTOCOL_V2) this.sawV2 = true;\n if (message.type === \"HELLO\") {\n const hello = parseHello(message);\n if (hello.ok) this.descriptor = hello.descriptor;\n else this.violations.push({ code: \"INVALID_PAYLOAD\", message: `bad HELLO: ${hello.reason}` });\n return;\n }\n if (message.type === \"QUESTION\") {\n await this.answerQuestion(message);\n return;\n }\n if (message.type === \"REPORT\") {\n this.reports.push(message.payload);\n return;\n }\n if (message.type === \"ARTIFACT\") {\n this.artifacts.push(message.payload);\n return;\n }\n if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n this.completionSummary = typeof payload?.summary === \"string\" ? payload.summary : \"\";\n return;\n }\n if (message.type === \"ERROR\") {\n const payload = message.payload as { message?: unknown; code?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"agent reported an error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n this.errorMessage = `Agent error${code}: ${detail}`;\n return;\n }\n if (message.type === \"TASK_ACCEPTED\" || message.type === \"TASK_STARTED\" || message.type === \"STATUS\") {\n // Lifecycle acknowledgements: observed, no action needed by the core.\n return;\n }\n this.violations.push({\n code: \"UNKNOWN_TYPE\",\n message: `unexpected message type ${message.type} from agent`,\n });\n }\n\n private async answerQuestion(message: ProtocolEnvelope): Promise<void> {\n const payload = (message.payload ?? {}) as { questionId?: unknown; question?: unknown; expected?: unknown };\n const questionId = typeof payload.questionId === \"string\" ? payload.questionId : message.messageId;\n const question = typeof payload.question === \"string\" ? payload.question : \"\";\n const expected = typeof payload.expected === \"string\" ? payload.expected : \"text\";\n\n let answer: string | undefined;\n if (this.responder) {\n try {\n answer = await this.responder({ questionId, question, expected });\n } catch (error) {\n this.violations.push({\n code: \"INVALID_PAYLOAD\",\n message: `question responder failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n this.questions.push({ questionId, question, ...(answer !== undefined ? { answer } : {}) });\n // Answer on stdout via the write callback supplied by the caller.\n this.pendingAnswers.push(\n encodeMessage(\n envelope(\"RESPONSE\", { questionId, ...(answer !== undefined ? { body: answer } : {}) }, {\n ...this.ids,\n requestId: message.requestId ?? this.ids.requestId,\n }),\n ),\n );\n }\n\n readonly pendingAnswers: string[] = [];\n /** True once any inbound message carried the v2 protocol field. */\n sawV2 = false;\n}\n\nexport async function decodeStream(session: ProtocolSession, chunk: string): Promise<string[]> {\n const decoded = session.decoder.push(chunk);\n for (const result of decoded) {\n await session.handle(result);\n }\n return session.pendingAnswers.splice(0);\n}\n\nexport function requireCompletion(session: ProtocolSession): void {\n if (session.errorMessage !== undefined) {\n throw new ProtocolError(session.errorMessage);\n }\n}\n\nexport { decodeMessage };","/**\n * Working-directory validation for agent processes (roadmap §8): existence,\n * directory-ness, access, path normalization and project boundaries.\n */\nimport { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { AgentError } from \"../errors/index.js\";\n\nexport interface CwdValidation {\n /** Normalized absolute path. */\n cwd: string;\n /** True when the directory sits outside the project root (project boundary). */\n outsideProject: boolean;\n}\n\nexport function validateWorkingDirectory(\n cwd: string | undefined,\n options: { projectRoot?: string; allowExternal?: boolean } = {},\n): CwdValidation | undefined {\n if (!cwd) return undefined;\n\n const normalized = isAbsolute(cwd) ? resolve(cwd) : resolve(process.cwd(), cwd);\n let stats;\n try {\n stats = statSync(normalized);\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" does not exist or is not accessible.`,\n { cause: error, details: { cwd: normalized } },\n );\n }\n if (!stats.isDirectory()) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Working directory \"${normalized}\" is not a directory.`, {\n details: { cwd: normalized },\n });\n }\n // Access check: attempt to list it.\n try {\n statSync(resolve(normalized, \".\"));\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is not accessible.`,\n { cause: error },\n );\n }\n\n const projectRoot = resolve(options.projectRoot ?? process.cwd());\n const rel = relative(projectRoot, normalized);\n const outsideProject = rel.startsWith(\"..\") || isAbsolute(rel);\n if (outsideProject && options.allowExternal !== true) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is outside the project root \"${projectRoot}\". ` +\n `Set allow_external_cwd: true on the agent to permit this.`,\n { details: { cwd: normalized, projectRoot } },\n );\n }\n return { cwd: normalized, outsideProject };\n}","/**\n * Agent environment policies (roadmap §8, Environment Isolation).\n *\n * Four explicit policies, so operators decide exactly what an agent can see:\n * - `inherit` (default, backwards compatible): the full parent environment\n * - `allowlist`: only the allow-listed variables (+ PATH/HOME)\n * - `denylist`: the parent environment minus the deny-listed variables\n * - `explicit`: nothing from the parent; only PATH/HOME and `env`\n *\n * The v1 boolean `inherit_env: false` is still honored and maps to `explicit`.\n */\nimport type { AgentConfig } from \"../types/agent.js\";\n\nexport type EnvPolicy = \"inherit\" | \"allowlist\" | \"denylist\" | \"explicit\";\n\n/** Variables always provided so shells and runtimes keep working. */\nconst BASELINE_KEYS = [\"PATH\", \"HOME\"] as const;\n\nexport function resolveEnvPolicy(config: Partial<AgentConfig>): EnvPolicy {\n if (config.envPolicy !== undefined) return config.envPolicy;\n if (config.inheritEnv === false) return \"explicit\"; // v1 compatibility\n return \"inherit\";\n}\n\nexport function buildChildEnv(config: AgentConfig): NodeJS.ProcessEnv {\n const configured = config.env ?? {};\n const policy = resolveEnvPolicy(config);\n\n if (policy === \"inherit\") {\n return { ...process.env, ...configured };\n }\n\n const base: NodeJS.ProcessEnv = {};\n for (const key of BASELINE_KEYS) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n\n switch (policy) {\n case \"explicit\":\n return { ...base, ...configured };\n case \"allowlist\": {\n const allowed: NodeJS.ProcessEnv = { ...base };\n for (const key of config.envAllowlist ?? []) {\n const value = process.env[key];\n if (value !== undefined) allowed[key] = value;\n }\n return { ...allowed, ...configured };\n }\n case \"denylist\": {\n const denied = new Set((config.envDenylist ?? []).map((k) => k.toUpperCase()));\n const filtered: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (denied.has(key.toUpperCase())) continue;\n filtered[key] = value;\n }\n return { ...filtered, ...configured };\n }\n }\n}","/**\n * Agent adapter registry (roadmap §8, Native Adapters).\n *\n * New integration styles (native/API-level agents) plug in here without\n * changing OmniNode core: register an `IAgentAdapter` and `createAgent`\n * consults the registry before falling back to the process adapter.\n */\nimport { AgentError } from \"../errors/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\n\nexport interface IAgentAdapter {\n /** Integration type this adapter serves, e.g. \"native\" or \"process\". */\n readonly integration: string;\n create(config: AgentConfig): IAgent;\n}\n\nexport class AgentAdapterRegistry {\n private readonly adapters = new Map<string, IAgentAdapter>();\n\n register(adapter: IAgentAdapter): void {\n this.adapters.set(adapter.integration, adapter);\n }\n\n get(integration: string): IAgentAdapter | undefined {\n return this.adapters.get(integration);\n }\n\n list(): IAgentAdapter[] {\n return [...this.adapters.values()];\n }\n\n create(config: AgentConfig): IAgent {\n const adapter = this.get(config.integration);\n if (!adapter) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `No agent adapter registered for integration \"${config.integration}\". ` +\n `Registered: ${[...this.adapters.keys()].join(\", \") || \"(none)\"}.`,\n );\n }\n return adapter.create(config);\n }\n}\n\n/** Process-level adapter — the built-in CLI integration. */\nexport class ProcessAgentAdapter implements IAgentAdapter {\n readonly integration = \"process\";\n\n constructor(private readonly factory: (config: AgentConfig) => IAgent) {}\n\n create(config: AgentConfig): IAgent {\n return this.factory(config);\n }\n}","/** Agent registry (§10): the set of agents connected to OmniNode. */\nimport type { IAgent } from \"../types/agent.js\";\n\nexport class AgentRegistry {\n private readonly agents = new Map<string, IAgent>();\n\n register(agent: IAgent): void {\n this.agents.set(agent.info.name, agent);\n }\n\n get(name: string): IAgent | undefined {\n return this.agents.get(name);\n }\n\n list(): IAgent[] {\n return [...this.agents.values()].sort((a, b) => a.info.name.localeCompare(b.info.name));\n }\n}\n","/**\n * Agent factory (§9–§10): builds adapter instances from configuration.\n * \"cli\" agent configs are mapped to the process integration by the loader.\n */\nimport type { AppConfig } from \"../config/index.js\";\nimport { OmniNodeError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\nimport { ProcessAgent } from \"./process/index.js\";\nimport { AgentRegistry } from \"./registry.js\";\nimport { AgentAdapterRegistry, ProcessAgentAdapter } from \"./adapters.js\";\n\n/**\n * Registry consulted first so native/API-level integrations plug in without\n * touching core (roadmap §8, Native Adapters).\n */\nexport const defaultAgentAdapters = new AgentAdapterRegistry();\ndefaultAgentAdapters.register(new ProcessAgentAdapter((config) => new ProcessAgent(config)));\n\nexport function createAgent(config: AgentConfig, adapters: AgentAdapterRegistry = defaultAgentAdapters): IAgent {\n const registered = adapters.get(config.integration);\n if (registered) return registered.create(config);\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `No native adapter is registered for \"${config.name}\". Register an IAgentAdapter ` +\n `(createAgent(config, adapters)) or use input over stdin/stdout (type \"cli\").`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\n\nexport { AgentAdapterRegistry } from \"./adapters.js\";\nexport type { IAgentAdapter } from \"./adapters.js\";\n\n/** Builds an agent registry from the project configuration, skipping agents that fail to construct. */\nexport function buildAgentRegistry(config: AppConfig, log: Logger = logger): AgentRegistry {\n const registry = new AgentRegistry();\n for (const agentConfig of config.project.agents) {\n try {\n registry.register(createAgent(agentConfig));\n } catch (error) {\n log.warn(\n `Skipping agent \"${agentConfig.name}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return registry;\n}\n","/** Role registry (§11): the set of roles available for task assignment. */\nimport type { AppConfig } from \"../config/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\n\nexport class RoleRegistry {\n private readonly roles = new Map<string, RoleDefinition>();\n\n register(role: RoleDefinition): void {\n this.roles.set(role.id, role);\n }\n\n registerAll(roles: RoleDefinition[]): void {\n for (const role of roles) this.register(role);\n }\n\n get(id: string): RoleDefinition | undefined {\n return this.roles.get(id);\n }\n\n list(): RoleDefinition[] {\n return [...this.roles.values()].sort((a, b) => a.id.localeCompare(b.id));\n }\n}\n\n/** Builds a role registry from the project configuration. */\nexport function buildRoleRegistry(config: AppConfig): RoleRegistry {\n const registry = new RoleRegistry();\n registry.registerAll(config.project.roles);\n return registry;\n}\n","/**\n * Shared JSON file persistence (v2 Phase 12 — Persistence Layer).\n *\n * Guarantees:\n * - **Atomic writes**: temp file → fsync → rename → directory fsync, so a\n * crash never leaves a half-written store.\n * - **Corruption detection**: unparseable files are *quarantined* (renamed,\n * never deleted) and the store continues empty.\n * - **Schema versioning**: documents carry `schemaVersion`; v1 documents are\n * migrated on read, future versions are refused rather than misread.\n */\nimport { open, mkdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\n/** Current on-disk schema version. */\nexport const SCHEMA_VERSION = 2;\n\nexport interface JsonDocument<T> {\n schemaVersion?: number;\n items: T[];\n}\n\nexport type DocumentState =\n | { status: \"missing\" }\n | { status: \"empty\" }\n | { status: \"v1-legacy\" }\n | { status: \"current\"; schemaVersion: number; count: number }\n | { status: \"future\"; schemaVersion: number }\n | { status: \"corrupt\"; detail: string };\n\nexport interface JsonFileStoreOptions {\n directory?: string;\n fileName: string;\n /** Schema version to write (defaults to the current version). */\n schemaVersion?: number;\n /** Power-loss durability: \"rename\" (default) or \"fsync\" (slower). */\n durability?: Durability;\n /** Called when a persisted file is corrupt (after quarantine). */\n onCorrupt?: (path: string, error: unknown) => void;\n /** Disable file moves (used by dry runs / tests that inspect in place). */\n quarantine?: boolean;\n}\n\nexport type Durability = \"rename\" | \"fsync\";\n\n/**\n * Writes a file atomically: temp → rename. The rename guarantees readers\n * never observe a torn file. With `durability: \"fsync\"` the data and the\n * directory entry are also flushed, which additionally survives power loss —\n * at a significant per-write cost, so it is opt-in.\n */\nexport async function writeFileAtomic(\n target: string,\n contents: string,\n durability: Durability = \"rename\",\n): Promise<void> {\n const tmp = `${target}.tmp`;\n await mkdir(dirname(target), { recursive: true });\n\n if (durability === \"fsync\") {\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n } else {\n await writeFile(tmp, contents, \"utf8\");\n }\n\n await rename(tmp, target);\n\n if (durability === \"fsync\") {\n try {\n const dir = await open(dirname(target), \"r\");\n try {\n await dir.sync();\n } finally {\n await dir.close();\n }\n } catch {\n // Directory fsync is unsupported on some platforms — the rename is still atomic.\n }\n }\n}\n\n/** Reads and classifies a persisted document without modifying it. */\nexport async function inspectDocument(path: string): Promise<DocumentState> {\n let raw: string;\n try {\n await stat(path);\n } catch {\n return { status: \"missing\" };\n }\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n return { status: \"corrupt\", detail: `unreadable: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (raw.trim().length === 0) return { status: \"empty\" };\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return { status: \"corrupt\", detail: error instanceof Error ? error.message : \"invalid JSON\" };\n }\n if (Array.isArray(parsed)) return { status: \"v1-legacy\" }; // v1 stored bare arrays\n if (parsed === null || typeof parsed !== \"object\") return { status: \"corrupt\", detail: \"not an object\" };\n const doc = parsed as JsonDocument<unknown>;\n if (!Array.isArray(doc.items)) return { status: \"corrupt\", detail: \"missing items array\" };\n const version = typeof doc.schemaVersion === \"number\" ? doc.schemaVersion : 1;\n if (version > SCHEMA_VERSION) return { status: \"future\", schemaVersion: version };\n if (version < SCHEMA_VERSION) return { status: \"v1-legacy\" };\n return { status: \"current\", schemaVersion: version, count: doc.items.length };\n}\n\n/** Reads a document, migrating v1 shapes and quarantining corruption. */\nexport async function readDocument<T>(\n path: string,\n onCorrupt?: (path: string, error: unknown) => void,\n quarantine = true,\n): Promise<T[]> {\n const state = await inspectDocument(path);\n if (state.status === \"missing\" || state.status === \"empty\") return [];\n if (state.status === \"future\") {\n const error = new Error(\n `${path} was written by a newer OmniNode (schema v${state.schemaVersion} > v${SCHEMA_VERSION})`,\n );\n onCorrupt?.(path, error);\n return [];\n }\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n onCorrupt?.(path, error);\n return [];\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as T[]; // v1 legacy: bare array\n return (parsed as JsonDocument<T>).items ?? [];\n } catch (error) {\n // Preserve the damaged file for inspection instead of overwriting it.\n if (quarantine) {\n const quarantinePath = `${path}.corrupt-${Date.now()}`;\n try {\n await rename(path, quarantinePath);\n logger.child({ component: \"persistence\" }).warn(\n `Quarantined unreadable store file ${path} → ${quarantinePath}`,\n );\n } catch {\n // Quarantine is best effort.\n }\n }\n onCorrupt?.(path, error);\n return [];\n }\n}\n\nexport class JsonFileStore<T> {\n private readonly filePath: string;\n private readonly schemaVersion: number;\n private readonly durability: Durability;\n private readonly onCorrupt?: (path: string, error: unknown) => void;\n private readonly quarantine: boolean;\n private readonly log: Logger;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(options: JsonFileStoreOptions) {\n this.filePath = `${options.directory ?? `${process.cwd()}/.omninode`}/${options.fileName}`;\n this.schemaVersion = options.schemaVersion ?? SCHEMA_VERSION;\n this.durability = options.durability ?? \"rename\";\n this.onCorrupt = options.onCorrupt;\n this.quarantine = options.quarantine ?? true;\n this.log = logger.child({ component: \"persistence\", file: options.fileName });\n }\n\n get path(): string {\n return this.filePath;\n }\n\n /** All items, or [] when missing/migrated-from-v1/corrupt. */\n protected async readAll(): Promise<T[]> {\n return readDocument<T>(this.filePath, this.onCorrupt, this.quarantine);\n }\n\n protected async writeAll(items: T[]): Promise<void> {\n const document: JsonDocument<T> = { schemaVersion: this.schemaVersion, items };\n await writeFileAtomic(this.filePath, `${JSON.stringify(document, null, 2)}\\n`, this.durability);\n }\n\n /** Serializes an async operation against this file. */\n protected synchronized<R>(operation: () => Promise<R>): Promise<R> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /** Read-modify-write helper: applies `mutate` to the current items. */\n protected async mutate<R>(mutate: (items: T[]) => Promise<[T[], R]> | [T[], R]): Promise<R> {\n return this.synchronized(async () => {\n const items = await this.readAll();\n const [next, result] = await mutate(items);\n await this.writeAll(next);\n return result;\n });\n }\n}\n","/**\n * Task persistence (§4.1 — execution state). The store is replaceable\n * (§2 — Modular); the default implementation is a local JSON file so\n * OmniNode stays local-first (§25).\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Task, TaskStatus } from \"../types/task.js\";\n\nexport interface TaskStoreFilter {\n status?: TaskStatus;\n project?: string;\n}\n\nexport interface TaskStore {\n save(task: Task): Promise<void>;\n get(id: string): Promise<Task | undefined>;\n list(filter?: TaskStoreFilter): Promise<Task[]>;\n}\n\nexport class FileTaskStore extends JsonFileStore<Task> implements TaskStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"tasks.json\" });\n }\n\n save(task: Task): Promise<void> {\n return this.mutate((tasks) => {\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n return [tasks, undefined];\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n const tasks = await this.readAll();\n return tasks.find((t) => t.id === id);\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n const tasks = await this.readAll();\n return tasks\n .filter((task) => (filter.status ? task.status === filter.status : true))\n .filter((task) => (filter.project ? task.project === filter.project : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/**\n * Task engine (§13, §27 Phase 4): owns the task lifecycle — create, queue,\n * run, cancel — validates role/agent assignment against the registries and\n * persists every transition through the task store.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { AgentError, TaskError } from \"../errors/index.js\";\nimport type { AuditAction, AuditSink } from \"../audit/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type {\n ExecutionRecord,\n Task,\n TaskContext,\n TaskResult,\n TaskStatus,\n} from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\n/**\n * Strict state machine (roadmap §6.2). Invalid transitions are rejected —\n * engines never mutate state directly.\n *\n * created ──▶ queued ──▶ running ──┬─▶ completed\n * │ │ │ ├─▶ failed\n * │ │ │ ├─▶ timed_out (no side effects possible)\n * └───────────┴─────────┴────────┼─▶ unknown (outcome unprovable — e.g. killed after dispatch)\n * ├─▶ cancelled\n * └─▶ partially_completed (fan-out where some units succeeded)\n */\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"timed_out\", \"unknown\", \"cancelled\", \"partially_completed\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n // failed → running is the only re-entry: bounded automatic retry (§6.4).\n failed: [\"running\"],\n timed_out: [],\n cancelled: [],\n unknown: [],\n partially_completed: [],\n};\n\n/**\n * Error codes safe to retry automatically: a transient agent crash before any\n * report was produced. Timeouts/unknown outcomes are NEVER auto-retried\n * because the agent may already have performed side effects (roadmap §6.4).\n */\nconst RETRYABLE_ERROR_CODES: readonly string[] = [\"AGENT_FAILED\"];\nconst EXECUTION_HISTORY_LIMIT = 10;\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n pipelineId?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\n}\n\nexport interface RunTaskOptions {\n /** Total attempts (1 = no automatic retry). Retries apply to retryable errors only. */\n maxAttempts?: number;\n /** Linear backoff base in ms: waits backoffMs × attempt between attempts. */\n retryBackoffMs?: number;\n}\n\nexport interface TaskEngineOptions {\n agents: AgentRegistry;\n roles: RoleRegistry;\n store: TaskStore;\n /** When present, tasks gather relevant memory before running and record outcomes after (§20). */\n memory?: MemoryService;\n /** When present, task lifecycle transitions are appended to the audit log (§24). */\n audit?: AuditSink;\n log?: Logger;\n}\n\nexport class TaskEngine {\n private readonly log: Logger;\n\n constructor(private readonly options: TaskEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"tasks\" });\n }\n\n get store(): TaskStore {\n return this.options.store;\n }\n\n async create(input: CreateTaskInput): Promise<Task> {\n if (!input.objective || input.objective.trim().length === 0) {\n throw new TaskError(\"TASK_INVALID\", \"Task objective must not be empty.\");\n }\n if (input.role && !this.options.roles.get(input.role)) {\n throw new TaskError(\"TASK_INVALID\", \n `Role \"${input.role}\" is not defined. Add it under project.roles in omninode.yaml.`,\n );\n }\n if (input.agent && !this.options.agents.get(input.agent)) {\n throw new TaskError(\"TASK_INVALID\", \n `Agent \"${input.agent}\" is not registered. Add it with \\`omninode agent add\\`.`,\n );\n }\n\n const now = new Date().toISOString();\n const task: Task = {\n id: generateTaskId(),\n objective: input.objective.trim(),\n status: \"created\",\n attempt: 0,\n createdAt: now,\n updatedAt: now,\n ...(input.project !== undefined ? { project: input.project } : {}),\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n ...(input.agent !== undefined ? { agent: input.agent } : {}),\n ...(input.context !== undefined ? { context: input.context } : {}),\n };\n await this.options.store.save(task);\n this.log.info(`Created task ${task.id}.`);\n await this.audit(\"task.created\", task, { objective: task.objective });\n return task;\n }\n\n async queue(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n return this.transition(task, \"queued\");\n }\n\n /** Runs the task through its assigned agent and records the result.\n * `maxAttempts` enables bounded automatic retries of *retryable* errors\n * with linear backoff; unknown/timed_out outcomes are never auto-retried. */\n async run(id: string, options: RunTaskOptions = {}): Promise<Task> {\n const task = await this.mustGet(id);\n if (task.status !== \"created\" && task.status !== \"queued\") {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be run.`);\n }\n if (!task.agent) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} has no agent assigned. Re-create it with --agent.`);\n }\n const agent = this.options.agents.get(task.agent);\n if (!agent) {\n throw new TaskError(\"TASK_INVALID\", `Agent \"${task.agent}\" is not registered anymore.`);\n }\n const role = task.role ? this.options.roles.get(task.role) : undefined;\n\n this.log.info(`Running task ${task.id} on agent \"${task.agent}\".`);\n\n // §20: relevant memory is gathered before the agent receives context.\n let background = task.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: task.objective,\n ...(task.role ? { role: task.role } : {}),\n ...(task.project ? { project: task.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n const maxAttempts = Math.max(1, options.maxAttempts ?? 1);\n const backoffMs = options.retryBackoffMs ?? 0;\n\n let current = task;\n for (let i = 0; i < maxAttempts; i += 1) {\n // Attempt numbers are cumulative for the task (roadmap §6.5).\n const attempt = current.attempt + 1;\n const executionId = `exec-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n const startedAt = new Date().toISOString();\n current = await this.transition(current, \"running\", { attempt });\n\n await this.options.audit?.record({\n at: startedAt,\n action: \"agent.started\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt },\n });\n\n let output;\n let thrown: unknown;\n try {\n output = await agent.run({\n taskId: current.id,\n objective: current.objective,\n executionId,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n thrown = error;\n }\n\n const finishedAt = new Date().toISOString();\n await this.options.audit?.record({\n at: finishedAt,\n action: \"agent.completed\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt, outcome: thrown !== undefined || output === undefined ? \"threw\" : \"returned\" },\n });\n if (thrown !== undefined || output === undefined) {\n const outcome = classifyThrown(thrown);\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n const retryable =\n outcome === \"failed\" &&\n RETRYABLE_ERROR_CODES.includes(errorCode(thrown)) &&\n i < maxAttempts - 1;\n current = await this.transition(current, outcome, {\n attempt,\n lastError: message,\n execution: {\n executionId,\n attempt,\n startedAt,\n finishedAt,\n outcome,\n error: message,\n },\n });\n this.log.warn(`Task ${current.id} attempt ${attempt} → ${outcome}: ${message}`);\n if (retryable) {\n if (backoffMs > 0) await sleep(backoffMs * attempt);\n continue;\n }\n if (this.options.memory) await this.options.memory.recordTaskOutcome(current);\n return current;\n }\n\n // The task may have been cancelled while the agent was finishing —\n // respect the terminal state instead of forcing a completed transition.\n const currentState = await this.options.store.get(current.id);\n if (currentState?.status === \"cancelled\") {\n current = currentState;\n break;\n }\n\n const result: TaskResult = {\n ...(output.summary !== undefined ? { summary: output.summary } : {}),\n ...(output.reports !== undefined && output.reports.length > 0 ? { reports: output.reports } : {}),\n // Keep the verbatim output (bounded) for report extraction and audit.\n ...(output.rawOutput !== undefined && output.rawOutput.length > 0\n ? { rawOutput: output.rawOutput.slice(0, 10_000) }\n : {}),\n ...(output.error !== undefined ? { error: output.error } : {}),\n finishedAt,\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n current = await this.transition(current, finalStatus, {\n attempt,\n result,\n execution: { executionId, attempt, startedAt, finishedAt, outcome: finalStatus },\n });\n this.log.info(`Task ${current.id} finished: ${finalStatus}.`);\n break;\n }\n\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(current);\n }\n return current;\n }\n\n async cancel(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n if (!ALLOWED_TRANSITIONS[task.status].includes(\"cancelled\")) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be cancelled.`);\n }\n if (task.agent) {\n const agent = this.options.agents.get(task.agent);\n await agent?.cancel?.(task.id);\n }\n return this.transition(task, \"cancelled\");\n }\n\n /** Error recovery: reset a failed/cancelled/unknown/timed_out task so it can run again. */\n async retry(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n const retryableStates: TaskStatus[] = [\"failed\", \"cancelled\", \"unknown\", \"timed_out\"];\n if (!retryableStates.includes(task.status)) {\n throw new TaskError(\n \"TASK_INVALID\",\n `Only failed, timed out, unknown or cancelled tasks can be retried — task ${id} is \"${task.status}\".`,\n );\n }\n const { result: _discarded, ...rest } = task;\n const reset: Task = {\n ...rest,\n status: \"created\",\n updatedAt: new Date().toISOString(),\n };\n await this.options.store.save(reset);\n await this.audit(\"task.retry\", reset, { from: task.status });\n this.log.info(`Task ${id} reset for retry.`);\n return reset;\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.options.store.get(id);\n }\n\n async list(filter?: TaskStoreFilter): Promise<Task[]> {\n return this.options.store.list(filter);\n }\n\n private async mustGet(id: string): Promise<Task> {\n const task = await this.options.store.get(id);\n if (!task) {\n throw new TaskError(\"TASK_NOT_FOUND\", `Task \"${id}\" does not exist in this project's task store.`);\n }\n return task;\n }\n\n private async transition(\n task: Task,\n to: TaskStatus,\n extra: { result?: TaskResult; attempt?: number; lastError?: string; execution?: ExecutionRecord } = {},\n ): Promise<Task> {\n const allowed = ALLOWED_TRANSITIONS[task.status] ?? [];\n if (!allowed.includes(to)) {\n throw new TaskError(\"TASK_INVALID\", `Task ${task.id} cannot move from \"${task.status}\" to \"${to}\".`);\n }\n const executions = extra.execution\n ? [...(task.executions ?? []), extra.execution].slice(-EXECUTION_HISTORY_LIMIT)\n : task.executions;\n const updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.attempt !== undefined ? { attempt: extra.attempt } : {}),\n ...(extra.lastError !== undefined ? { lastError: extra.lastError } : {}),\n ...(executions !== undefined ? { executions } : {}),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n await this.audit(`task.${to === \"queued\" ? \"queued\" : to}` as AuditAction, updated, {\n from: task.status,\n });\n return updated;\n }\n\n private async audit(\n action: AuditAction,\n task: Task,\n detail?: Record<string, unknown>,\n executionId?: string,\n ): Promise<void> {\n // Correlation (§18): every event carries task/pipeline/agent/execution ids.\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action,\n id: task.id,\n taskId: task.id,\n ...(task.project !== undefined ? { project: task.project } : {}),\n ...(task.pipelineId !== undefined ? { pipelineId: task.pipelineId } : {}),\n ...(task.agent !== undefined ? { agentId: task.agent } : {}),\n ...(executionId !== undefined ? { executionId } : {}),\n ...(detail !== undefined ? { detail } : {}),\n });\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nfunction errorCode(error: unknown): string {\n return (error as { code?: string } | undefined)?.code ?? \"\";\n}\n\n/**\n * Classifies a thrown adapter error into a terminal state.\n *\n * §6.3: a timeout is NOT assumed to be a failure. If the operation was\n * dispatched, the remote side may have completed it, so the outcome is\n * `unknown`. Only a timeout provably raised *before* dispatch becomes\n * `timed_out`.\n */\nfunction classifyThrown(error: unknown): \"failed\" | \"timed_out\" | \"unknown\" {\n if (error instanceof AgentError && error.code === \"AGENT_TIMEOUT\") {\n const dispatched = (error.details as { dispatched?: unknown } | undefined)?.dispatched;\n return dispatched === false ? \"timed_out\" : \"unknown\";\n }\n return \"failed\";\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Audit logging (§24): append-only JSONL record of lifecycle events\n * (task/pipeline transitions) in the project's .omninode directory. Useful\n * for compliance reviews and debugging multi-agent runs.\n */\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport type AuditAction =\n | \"task.created\"\n | \"task.queued\"\n | \"task.running\"\n | \"task.completed\"\n | \"task.failed\"\n | \"task.cancelled\"\n | \"task.retry\"\n | \"pipeline.run.started\"\n | \"pipeline.run.finished\"\n | \"pipeline.run.failed\"\n | \"pipeline.run.cancelled\"\n | \"plan.generated\"\n | \"agent.started\"\n | \"agent.completed\"\n | \"provider.error\"\n | \"memory.context.gathered\"\n | \"memory.outcome.recorded\";\n\n/**\n * Every event carries correlation ids so a failed execution can be traced\n * across task → execution → pipeline run → agent → provider (roadmap §18).\n */\nexport interface AuditEvent {\n at: string;\n action: AuditAction;\n project?: string;\n /** Primary subject: task id, pipeline run id, plan id… */\n id?: string;\n taskId?: string;\n pipelineId?: string;\n executionId?: string;\n agentId?: string;\n providerId?: string;\n actor?: string;\n detail?: Record<string, unknown>;\n}\n\nexport interface AuditSink {\n record(event: AuditEvent): Promise<void>;\n}\n\n/** Append-only JSONL sink. Failures are logged, never propagated. */\nexport class FileAuditLog implements AuditSink {\n private readonly filePath: string;\n private readonly log: Logger;\n\n constructor(directory = `${process.cwd()}/.omninode`, log: Logger = logger) {\n this.filePath = `${directory}/audit.jsonl`;\n this.log = log.child({ component: \"audit\" });\n }\n\n async record(event: AuditEvent): Promise<void> {\n try {\n await mkdir(dirname(this.filePath), { recursive: true });\n // Append-only: a crash can tear the last line, which `recent()` skips.\n // fsync-per-event would make every execution wait on the disk.\n await appendFile(this.filePath, `${JSON.stringify(event)}\\n`, \"utf8\");\n } catch (error) {\n this.log.warn(\n `Audit write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Recent events, oldest first; used by the CLI. */\n async recent(limit = 20): Promise<AuditEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf8\");\n } catch {\n return [];\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as AuditEvent;\n } catch {\n return undefined;\n }\n })\n .filter((event): event is AuditEvent => event !== undefined);\n return events.slice(-limit);\n }\n}","/**\n * Shared memory-contract helpers (roadmap §12). Adapters implement\n * `retrieve` / `store`; these helpers supply the defaults for `search`,\n * `metadata` and the v1 `query` / `write` aliases, so the contract is\n * defined once.\n */\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\n/** Free-text search defaults to a relevance retrieve. */\nexport function defaultSearch(\n provider: Pick<IMemoryProvider, \"retrieve\">,\n text: string,\n options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {},\n): Promise<MemoryEntry[]> {\n return provider.retrieve({\n text,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n}\n\nexport function defaultMetadata(\n name: string,\n options: {\n capabilities?: MemoryProviderMetadata[\"capabilities\"];\n relevanceRanking?: boolean;\n backend?: Record<string, unknown>;\n } = {},\n): MemoryProviderMetadata {\n return {\n name,\n capabilities: options.capabilities ?? [\"retrieve\", \"store\", \"search\"],\n relevanceRanking: options.relevanceRanking ?? false,\n ...(options.backend !== undefined ? { backend: options.backend } : {}),\n };\n}","/**\n * Local file-based memory provider: the default implementation so persistent\n * memory works out of the box, locally (§25), with no external service.\n * Relevance is scored by keyword overlap and tag matches — deterministic and\n * dependency-free.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"this\", \"that\", \"from\", \"into\", \"was\", \"were\",\n \"have\", \"has\", \"had\", \"are\", \"but\", \"not\", \"you\", \"his\", \"her\", \"its\",\n \"their\", \"them\", \"then\", \"than\", \"when\", \"what\", \"which\", \"will\", \"would\",\n \"been\", \"were\", \"also\", \"because\", \"about\", \"after\", \"before\",\n]);\n\nexport function keywords(text: string): Set<string> {\n return new Set(\n (text ?? \"\")\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 4 && !STOPWORDS.has(t)),\n );\n}\n\nfunction relevanceScore(queryKeywords: Set<string>, entry: MemoryEntry): number {\n if (queryKeywords.size === 0) return 0;\n const entryKeywords = keywords(`${entry.content} ${entry.key}`);\n let overlap = 0;\n for (const keyword of queryKeywords) {\n if (entryKeywords.has(keyword)) overlap += 1;\n }\n let tagMatches = 0;\n for (const tag of entry.tags ?? []) {\n if (queryKeywords.has(tag.toLowerCase())) tagMatches += 1;\n }\n return overlap * 2 + tagMatches * 1.5;\n}\n\nexport class LocalMemoryProvider extends JsonFileStore<MemoryEntry> implements IMemoryProvider {\n readonly name = \"local\";\n\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"memory.json\" });\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"json-file\", deterministicScoring: true },\n });\n }\n\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(this, text, options);\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const entries = await this.readAll();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : true))\n .filter((entry) => (query.category ? entry.category === query.category : true))\n .filter((entry) =>\n query.tags && query.tags.length > 0\n ? query.tags.every((tag) => (entry.tags ?? []).includes(tag))\n : true,\n );\n\n if (!query.text || query.text.trim().length === 0) {\n return filtered\n .sort((a, b) => (b.updatedAt ?? b.createdAt ?? \"\").localeCompare(a.updatedAt ?? a.createdAt ?? \"\"))\n .slice(0, query.limit ?? 10);\n }\n\n const queryKeywords = keywords(query.text);\n return filtered\n .map((entry) => ({ entry, score: relevanceScore(queryKeywords, entry) }))\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, query.limit ?? 10)\n .map(({ entry }) => entry);\n }\n\n store(entry: MemoryEntry): Promise<void> {\n return this.mutate((entries) => {\n const index = entries.findIndex((e) => e.key === entry.key);\n const stamped: MemoryEntry = {\n ...entry,\n createdAt: entry.createdAt ?? new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n if (index >= 0) entries[index] = stamped;\n else entries.push(stamped);\n return [entries, undefined];\n });\n }\n\n async count(): Promise<number> {\n return (await this.readAll()).length;\n }\n}\n","/**\n * Remembera memory provider (§19): the preferred Hilbras memory integration,\n * reached over HTTP. Remembera is strictly optional — the core also runs with\n * the local memory provider or none at all (§2).\n *\n * API convention assumed by this adapter (adjust here if the real API differs):\n * write: POST {baseUrl}/api/memory body: MemoryEntry JSON → 2xx\n * query: POST {baseUrl}/api/memory/query body: MemoryQuery JSON → { entries: MemoryEntry[] }\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { resolveApiKey } from \"../providers/auth.js\";\nimport { requestJson } from \"../providers/http.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\n\nexport interface RememberaConfig {\n baseUrl: string;\n apiKeyEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nexport class RememberaMemoryProvider implements IMemoryProvider {\n readonly name = \"remembera\";\n private readonly baseUrl: string;\n private readonly apiKeyEnvVar?: string;\n private readonly env: Record<string, string | undefined>;\n private readonly log: Logger;\n\n constructor(config: RememberaConfig, log: Logger = logger) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.apiKeyEnvVar = config.apiKeyEnvVar;\n this.env = config.env ?? process.env;\n this.log = log.child({ component: \"remembera\" });\n }\n\n private get authenticationConfigured(): boolean {\n return this.apiKeyEnvVar === undefined || Boolean(this.env[this.apiKeyEnvVar]);\n }\n\n private headers(): Record<string, string> {\n const key = this.apiKeyEnvVar\n ? resolveApiKey({ name: \"remembera\", apiKeyEnvVar: this.apiKeyEnvVar }, this.env)\n : undefined;\n return key ? { authorization: `Bearer ${key}` } : {};\n }\n\n /** Search delegates to the gateway's relevance query. */\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(\n this,\n text,\n {\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n },\n );\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"http\", baseUrl: this.baseUrl, authenticated: this.authenticationConfigured },\n });\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const { status, body } = await this.request(`${this.baseUrl}/api/memory/query`, query);\n if (status !== 200) {\n throw new MemoryError(`Remembera query returned HTTP ${status}.`);\n }\n const entries = (body as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new MemoryError(\"Remembera query response had no entries array.\");\n }\n return entries.map((entry) => this.toEntry(entry)).filter((entry): entry is MemoryEntry => entry !== undefined);\n }\n\n async store(entry: MemoryEntry): Promise<void> {\n const { status } = await this.request(`${this.baseUrl}/api/memory`, entry);\n if (status !== 200 && status !== 201) {\n throw new MemoryError(`Remembera write returned HTTP ${status}.`);\n }\n }\n\n private async request(url: string, body: unknown): Promise<{ status: number; body: unknown }> {\n // Resolved outside the try so auth failures propagate as-is.\n const headers = this.headers();\n try {\n return await requestJson(url, {\n method: \"POST\",\n headers,\n body,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MemoryError(`Remembera request to ${url} failed: ${message}`, { cause: error });\n }\n }\n\n private toEntry(raw: unknown): MemoryEntry | undefined {\n if (raw === null || typeof raw !== \"object\") {\n this.log.warn(\"Skipping malformed Remembera memory entry.\");\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n if (typeof entry.key !== \"string\" || typeof entry.content !== \"string\") {\n this.log.warn(\"Skipping Remembera memory entry without key/content.\");\n return undefined;\n }\n const scope = entry.scope;\n return {\n key: entry.key,\n content: entry.content,\n scope:\n scope === \"project\" || scope === \"role\" || scope === \"task\" || scope === \"knowledge\"\n ? scope\n : \"knowledge\",\n ...(Array.isArray(entry.tags) ? { tags: entry.tags.filter((t): t is string => typeof t === \"string\") } : {}),\n ...(typeof entry.category === \"string\"\n ? { category: entry.category as MemoryEntry[\"category\"] }\n : {}),\n ...(typeof entry.createdAt === \"string\" ? { createdAt: entry.createdAt } : {}),\n ...(typeof entry.updatedAt === \"string\" ? { updatedAt: entry.updatedAt } : {}),\n };\n }\n}\n","/** Memory provider factory: memory is optional; local is the default. */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { IMemoryProvider } from \"../types/memory.js\";\nimport { LocalMemoryProvider } from \"./local.js\";\nimport { RememberaMemoryProvider } from \"./remembera.js\";\n\nexport type MemoryProviderConfig = NonNullable<AppConfig[\"project\"][\"memory\"]>;\n\nexport function createMemoryProvider(config?: MemoryProviderConfig): IMemoryProvider {\n if (!config || config.provider === \"local\") {\n return new LocalMemoryProvider();\n }\n if (config.provider === \"remembera\") {\n if (!config.baseUrl) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Memory provider \"remembera\" needs a base_url in omninode.yaml.`,\n );\n }\n return new RememberaMemoryProvider({\n baseUrl: config.baseUrl,\n apiKeyEnvVar: config.apiKeyEnvVar,\n });\n }\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Unknown memory provider \"${config.provider}\". Available: local, remembera.`,\n );\n}\n","/**\n * Memory service + context manager (§12, Context Retrieval):\n *\n * Task → context query → relevant memory → context → agent/planner\n *\n * Retrieval is task-oriented and budgeted — OmniNode never loads all memory\n * into a prompt. Failures are best-effort by default; when memory is marked\n * `required`, they become fatal instead (§12, Failure Handling).\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry } from \"../types/memory.js\";\nimport type { Task } from \"../types/task.js\";\n\nexport interface MemoryContextQuery {\n objective: string;\n role?: string;\n project?: string;\n /** Maximum entries to consider (relevance-ranked by the provider). */\n limit?: number;\n}\n\nexport interface MemoryTaskContext {\n /** Prompt-ready context text (\"\" when nothing relevant was found). */\n text: string;\n entries: MemoryEntry[];\n /** True when the character budget cut the context short. */\n truncated: boolean;\n}\n\nconst DEFAULT_ENTRY_LIMIT = 8;\nexport const MAX_CONTEXT_CHARS = 4_000;\n\nexport interface MemoryServiceOptions {\n /** When true, backend failures propagate instead of being logged. */\n required?: boolean;\n maxContextChars?: number;\n}\n\nexport class MemoryService {\n private readonly log: Logger;\n private readonly required: boolean;\n private readonly maxContextChars: number;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n options: MemoryServiceOptions = {},\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n this.required = options.required ?? false;\n this.maxContextChars = options.maxContextChars ?? MAX_CONTEXT_CHARS;\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n get isRequired(): boolean {\n return this.required;\n }\n\n /** Structured, budgeted context for a task (§12 — avoid loading all memory). */\n async contextFor(query: MemoryContextQuery): Promise<MemoryTaskContext> {\n let entries: MemoryEntry[];\n try {\n entries = await this.provider.retrieve({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: query.limit ?? DEFAULT_ENTRY_LIMIT,\n });\n } catch (error) {\n return this.handleFailure(\"retrieve\", error, { text: \"\", entries: [], truncated: false });\n }\n return this.format(entries);\n }\n\n /** Prompt-ready context text (v1 convenience wrapper). */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n return (await this.contextFor(query)).text;\n }\n\n /** Records a finished task's outcome — task history plus \"known problems\" (§12). */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.store({\n key: `task:${task.id}`,\n scope: \"task\",\n category: \"tasks\",\n content: `Objective: ${task.objective}\\nStatus: ${task.status}\\nOutcome: ${outcome}`,\n tags: [\"task\", ...(task.agent ? [task.agent] : []), ...(task.role ? [task.role] : [])],\n createdAt: task.createdAt,\n });\n const significant = (task.result?.reports ?? []).flatMap((report) =>\n report.findings\n .filter((finding) => finding.severity === \"high\" || finding.severity === \"critical\")\n .map((finding) => ({ report, finding })),\n );\n for (const { report, finding } of significant) {\n await this.provider.store({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n category: \"problems\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.handleFailure(\"store\", error, undefined);\n }\n }\n\n private format(entries: MemoryEntry[]): MemoryTaskContext {\n if (entries.length === 0) return { text: \"\", entries, truncated: false };\n const byScope = new Map<string, MemoryEntry[]>();\n for (const entry of entries) {\n byScope.set(entry.scope, [...(byScope.get(entry.scope) ?? []), entry]);\n }\n const parts: string[] = [];\n for (const scope of [\"project\", \"task\", \"role\", \"knowledge\"]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries\n .map((entry) => {\n const category = entry.category ? `[${entry.category}] ` : \"\";\n return `- ${category}${entry.content}`;\n })\n .join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n let text = parts.join(\"\\n\\n\");\n const truncated = text.length > this.maxContextChars;\n if (truncated) text = `${text.slice(0, this.maxContextChars - 1)}…`;\n return { text, entries, truncated };\n }\n\n /**\n * Failure policy (§12): continue unless memory is explicitly required.\n */\n private handleFailure(operation: string, error: unknown, fallback?: MemoryTaskContext): MemoryTaskContext {\n const message = error instanceof Error ? error.message : String(error);\n if (this.required) {\n throw new MemoryError(\n `Memory is marked required, but ${operation} failed: ${message}`,\n { cause: error },\n );\n }\n this.log.warn(`Memory ${operation} failed (continuing without memory): ${message}`);\n return fallback ?? { text: \"\", entries: [], truncated: false };\n }\n}","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { TaskEngine } from \"./engine.js\";\nimport { FileTaskStore } from \"./store.js\";\n\nexport function createTaskEngine(config: AppConfig, log: Logger = logger, directory?: string): TaskEngine {\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n return new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(directory),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n}\n","/**\n * Pipeline engine (§14, §15, §27 Phase 5): validates pipeline definitions,\n * schedules steps over their dependency DAG (implicit sequential chain by\n * default, parallel where the DAG allows), fans research steps out to several\n * agents, hands combined context to plan steps (via a chat model) and to the\n * final execution agent. Every task runs through the TaskEngine, so tasks,\n * results and reports are persisted normally.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport { PipelineError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { createProvider } from \"../providers/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type {\n IPipelineExecutor,\n PipelineDefinition,\n PipelineRun,\n PipelineRunOptions,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatFn } from \"../types/chat.js\";\n// Re-exported for v1 compatibility: ChatFn now lives in the neutral types layer.\nexport type { ChatFn };\nimport type { Plan } from \"../types/plan.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/index.js\";\nimport { aggregateReports } from \"../reports/aggregate.js\";\nimport type { AuditSink } from \"../audit/index.js\";\nimport type { IPlanner } from \"../planner/index.js\";\nimport type { PlanStore } from \"../planner/store.js\";\nimport { HeuristicPlanner } from \"../planner/heuristic.js\";\nimport { ModelPlanner } from \"../planner/model.js\";\nimport type { TaskEngine } from \"../tasks/index.js\";\nimport type { PipelineRunStore } from \"./store.js\";\n\nexport interface PipelineEngineOptions {\n tasks: TaskEngine;\n agents: AgentRegistry;\n roles: RoleRegistry;\n providers: AppConfig[\"project\"][\"providers\"];\n store: PipelineRunStore;\n chat?: ChatFn;\n /** Default planner used by plan steps without their own model (§18). */\n planner?: IPlanner;\n /** When present, plans produced by plan steps are persisted. */\n plans?: PlanStore;\n /** When present, pipeline lifecycle events are appended to the audit log (§24). */\n audit?: AuditSink;\n /** When present, finished runs have their reports collected, stored and combined (§16–§17). */\n reports?: ReportService;\n log?: Logger;\n}\n\nexport interface RunPipelineOptions {\n objective?: string;\n onStep?: (stepRun: PipelineStepRun) => void;\n}\n\ninterface StepOutcome {\n status: \"completed\" | \"failed\" | \"partial\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n /** Execution ids of created tasks, for correlation (§6.5). */\n executionIds?: string[];\n /** Step attempt that produced this outcome (1 = first try). */\n attempt?: number;\n planId?: string;\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n runId?: string;\n /** Definition id (correlates events with the pipeline, not just the run). */\n pipelineDefId?: string;\n taskId?: string;\n role?: RoleDefinition;\n combinedContext: string;\n reports: Report[];\n pipelineRunId?: string;\n}\n\nexport class PipelineEngine implements IPipelineExecutor {\n private readonly log: Logger;\n /** Runs executing in THIS process — cancellation can terminate them directly. */\n private readonly activeRuns = new Map<\n string,\n { taskIds: Set<string>; cancelTasks: () => Promise<void> }\n >();\n\n constructor(private readonly options: PipelineEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"pipelines\" });\n }\n\n get store(): PipelineRunStore {\n return this.options.store;\n }\n\n /**\n * Saves the run while preserving fields that may be set by another process\n * (e.g. a cancellation request) — an in-memory snapshot must never clobber\n * externally requested cancellation (§9.2).\n */\n private async persist(run: PipelineRun): Promise<void> {\n const current = await this.options.store.get(run.id);\n await this.options.store.save({\n ...run,\n ...(current?.cancellationRequested === true\n ? { cancellationRequested: true, cancellationRequestedAt: current.cancellationRequestedAt }\n : {}),\n });\n }\n\n /** Structural + semantic validation (§27 Phase 5 — pipeline parser). */\n validate(def: PipelineDefinition): void {\n const ids = new Set<string>();\n for (const step of def.steps) {\n if (ids.has(step.id)) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Duplicate step id \"${step.id}\".`);\n }\n ids.add(step.id);\n }\n for (const step of def.steps) {\n for (const dep of step.dependsOn ?? []) {\n if (!ids.has(dep)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" depends on unknown step \"${dep}\".`,\n );\n }\n }\n if ((step.kind === \"research\") && (step.agents ?? []).length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Research step \"${step.id}\" needs at least one agent.`,\n );\n }\n if ((step.kind === \"execute\" || step.kind === \"custom\") && !step.agent) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Step \"${step.id}\" (${step.kind}) needs an agent.`);\n }\n }\n this.assertAcyclic(def);\n }\n\n private assertAcyclic(def: PipelineDefinition): void {\n const deps = this.effectiveDependencies(def);\n const remaining = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n for (const [id, list] of deps) {\n remaining.set(id, list.length);\n for (const d of list) {\n dependents.set(d, [...(dependents.get(d) ?? []), id]);\n }\n }\n const queue = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) === 0);\n let processed = 0;\n while (queue.length > 0) {\n const id = queue.shift()!;\n processed += 1;\n for (const next of dependents.get(id) ?? []) {\n const left = (remaining.get(next) ?? 0) - 1;\n remaining.set(next, left);\n if (left === 0) queue.push(next);\n }\n }\n if (processed < deps.size) {\n const stuck = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) > 0);\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" has a dependency cycle involving: ${stuck.join(\", \")}.`,\n );\n }\n }\n\n /**\n * Steps run sequentially in definition order unless they declare explicit\n * dependencies, which enable parallel branches.\n */\n private effectiveDependencies(def: PipelineDefinition): Map<string, string[]> {\n const deps = new Map<string, string[]>();\n def.steps.forEach((step, index) => {\n const explicit = step.dependsOn ?? [];\n deps.set(\n step.id,\n explicit.length > 0 ? explicit : index > 0 ? [def.steps[index - 1]!.id] : [],\n );\n });\n return deps;\n }\n\n async run(def: PipelineDefinition, options: PipelineRunOptions = {}): Promise<PipelineRun> {\n this.validate(def);\n\n const objective = (options.objective ?? def.objective ?? \"\").trim();\n if (objective.length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" needs an objective — pass one or set it in the definition.`,\n );\n }\n const role = def.role ? this.options.roles.get(def.role) : undefined;\n if (def.role && !role) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Role \"${def.role}\" (pipeline \"${def.id}\") is not defined in project.roles.`,\n );\n }\n // Agents referenced by steps must be registered, and plan-step models\n // must resolve to a configured provider — both before anything runs (§9.5).\n for (const step of def.steps) {\n for (const name of [...(step.agents ?? []), ...(step.agent ? [step.agent] : [])]) {\n if (!this.options.agents.get(name)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" references unregistered agent \"${name}\".`,\n );\n }\n }\n if (step.model) {\n const separator = step.model.indexOf(\":\");\n if (separator <= 0 || separator === step.model.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" has an invalid model reference \"${step.model}\" — use \"provider:model-id\".`,\n );\n }\n const providerName = step.model.slice(0, separator);\n if (!this.options.providers.some((p) => p.name === providerName)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" uses model \"${step.model}\" but provider \"${providerName}\" is not configured.`,\n );\n }\n }\n }\n\n const now = new Date().toISOString();\n const run: PipelineRun = {\n id: `run-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n pipelineId: def.id,\n attempt: 1,\n objective,\n status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n const liveTaskIds = new Set<string>();\n this.activeRuns.set(run.id, {\n taskIds: liveTaskIds,\n cancelTasks: async () => {\n for (const taskId of liveTaskIds) {\n await this.options.tasks.cancel(taskId).catch(() => undefined);\n }\n },\n });\n this.log.info(`Running pipeline ${def.id} as ${run.id} (attempt ${run.attempt}).`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"pipeline.run.started\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, objective },\n });\n\n const deps = this.effectiveDependencies(def);\n const outcomes = new Map<string, StepOutcome>();\n const pending = new Set(def.steps.map((s) => s.id));\n const contextParts: string[] = [];\n const allReports: Report[] = [];\n let cancelled = false;\n\n while (pending.size > 0) {\n // §9.2 cancellation check point: stop scheduling, terminate what runs.\n const persisted = await this.options.store.get(run.id);\n if (persisted?.cancellationRequested === true) {\n cancelled = true;\n run.cancellationRequested = true;\n run.cancellationRequestedAt = persisted.cancellationRequestedAt;\n await this.activeRuns.get(run.id)?.cancelTasks();\n for (const step of def.steps.filter((s) => pending.has(s.id))) {\n const stepRun: PipelineStepRun = { stepId: step.id, status: \"cancelled\" };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n }\n pending.clear();\n break;\n }\n\n const ready = def.steps.filter(\n (step) => pending.has(step.id) && (deps.get(step.id) ?? []).every((d) => outcomes.has(d)),\n );\n if (ready.length === 0) {\n // Cycle — already rejected by validate(), but never hang.\n throw new PipelineError(\"PIPELINE_FAILED\", `Pipeline \"${def.id}\" scheduling stalled.`);\n }\n\n const settled = await Promise.all(\n ready.map(async (step): Promise<StepOutcome> => {\n if (!this.shouldRun(step, deps.get(step.id) ?? [], outcomes)) {\n return { status: \"skipped\", summary: \"\", taskIds: [], reports: [] };\n }\n const ctx: StepContext = {\n objective,\n ...(role ? { role } : {}),\n combinedContext: contextParts.join(\"\\n\\n\"),\n reports: [...allReports],\n pipelineRunId: run.id,\n runId: run.id,\n pipelineDefId: def.id,\n taskId: run.id,\n };\n return this.executeStep(step, ctx);\n }),\n );\n\n ready.forEach((step, index) => {\n const outcome = settled[index]!;\n outcomes.set(step.id, outcome);\n pending.delete(step.id);\n allReports.push(...outcome.reports);\n if (outcome.status !== \"skipped\" && outcome.summary.length > 0) {\n const contribution = outcome.contextContribution ?? outcome.summary;\n contextParts.push(`## Step \"${step.id}\" (${step.kind})\\n${contribution}`);\n }\n const stepRun: PipelineStepRun = {\n stepId: step.id,\n attempt: outcome.attempt ?? 1,\n ...(outcome.executionIds && outcome.executionIds.length > 0\n ? { executionIds: outcome.executionIds }\n : {}),\n status:\n outcome.status === \"skipped\"\n ? \"cancelled\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : outcome.status === \"partial\"\n ? \"partially_completed\"\n : \"completed\",\n ...(outcome.taskIds.length > 0 ? { taskIds: outcome.taskIds } : {}),\n ...(outcome.planId !== undefined ? { planId: outcome.planId } : {}),\n ...(outcome.error !== undefined ? { error: outcome.error } : {}),\n };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n });\n run.reports = [...allReports];\n await this.persist(run);\n }\n\n const allOutcomes = [...outcomes.values()];\n const failed = !cancelled && allOutcomes.some((o) => o.status === \"failed\");\n const partial = !cancelled && !failed && allOutcomes.some((o) => o.status === \"partial\");\n const finalStatus: PipelineRunStatus = cancelled\n ? \"cancelled\"\n : failed\n ? \"failed\"\n : partial\n ? \"partial\"\n : \"completed\";\n const planId = [...outcomes.values()].find((o) => o.planId !== undefined)?.planId;\n\n // §28 — Result: the outcome of the last completed step with tasks.\n let resultSummary: string | undefined;\n for (let i = def.steps.length - 1; i >= 0; i -= 1) {\n const step = def.steps[i]!;\n const outcome = outcomes.get(step.id);\n if (outcome?.status !== \"completed\" || outcome.taskIds.length === 0) continue;\n const stepTasks = (\n await Promise.all(outcome.taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const summaries = stepTasks\n .map((task) => task.result?.summary)\n .filter((summary): summary is string => summary !== undefined);\n if (summaries.length > 0) resultSummary = summaries.join(\"\\n\");\n break;\n }\n\n // Report system (§16–§17): collect, store and combine reports from the\n // analysis tasks (research/analyze) — execution output is a result, not a report.\n let combinedReportId: string | undefined;\n if (this.options.reports) {\n const taskIds = def.steps\n .filter((step) => step.kind === \"research\" || step.kind === \"analyze\")\n .flatMap((step) => outcomes.get(step.id)?.taskIds ?? []);\n const tasks = (\n await Promise.all(taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const collected = await this.options.reports.collectFromTasks(tasks);\n await this.options.reports.saveReports(collected);\n const combined = await this.options.reports.generateCombined(collected, {\n objective,\n pipelineRunId: run.id,\n taskIds,\n });\n combinedReportId = combined?.id;\n if (collected.length > 0) {\n run.reports = collected;\n }\n }\n\n const finishedAt = new Date().toISOString();\n this.activeRuns.delete(run.id);\n const finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt,\n attempts: [...(run.attempts ?? []), { attempt: run.attempt, startedAt: run.startedAt ?? finishedAt, finishedAt, status: finalStatus }],\n ...(run.reports !== undefined && run.reports.length > 0 ? { reports: run.reports } : {}),\n ...(combinedReportId !== undefined ? { combinedReportId } : {}),\n ...(planId !== undefined ? { planId } : {}),\n ...(resultSummary !== undefined ? { resultSummary } : {}),\n };\n await this.persist(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: cancelled ? \"pipeline.run.cancelled\" : finalStatus === \"failed\" ? \"pipeline.run.failed\" : \"pipeline.run.finished\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, status: finalStatus },\n });\n return finished;\n }\n\n /** First-class cancellation (§9.2): requests cancellation and terminates\n * tasks that are running in this process immediately. */\n async cancel(runId: string): Promise<void> {\n const run = await this.options.store.get(runId);\n if (!run) {\n throw new PipelineError(\"PIPELINE_NOT_FOUND\", `Pipeline run \"${runId}\" does not exist.`);\n }\n await this.options.store.save({\n ...run,\n cancellationRequested: true,\n cancellationRequestedAt: new Date().toISOString(),\n });\n const active = this.activeRuns.get(runId);\n if (active) {\n await active.cancelTasks();\n }\n }\n\n async get(runId: string): Promise<PipelineRun | undefined> {\n return this.options.store.get(runId);\n }\n\n async listRuns(filter?: { pipelineId?: string }): Promise<PipelineRun[]> {\n return this.options.store.list(filter);\n }\n\n private shouldRun(\n step: PipelineStep,\n deps: string[],\n outcomes: Map<string, StepOutcome>,\n ): boolean {\n const condition = step.condition ?? \"on-success\";\n const depStatuses = deps.map((d) => outcomes.get(d)?.status);\n const anyFailed = depStatuses.includes(\"failed\");\n // A partial dependency carries real output, so it does not block.\n const anySkipped = depStatuses.includes(\"skipped\");\n if (condition === \"always\") return true;\n if (condition === \"on-failure\") return anyFailed;\n return !anyFailed && !anySkipped;\n }\n\n private async executeStep(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const retries = step.retries ?? 0;\n let last: StepOutcome | undefined;\n for (let attempt = 0; attempt <= retries; attempt += 1) {\n if (attempt > 0) {\n this.log.warn(`Step \"${step.id}\" failed — retry ${attempt}/${retries}.`);\n }\n last = await this.executeStepOnce(step, ctx);\n if (last.status !== \"failed\") return { ...last, attempt: attempt + 1 };\n }\n return { ...last!, attempt: retries + 1 };\n }\n\n /** Registers tasks created for a step as live, so cancellation can terminate them (§9.2). */\n private trackLiveTasks(runId: string | undefined, taskIds: string[]): void {\n if (!runId) return;\n const active = this.activeRuns.get(runId);\n if (!active) return;\n for (const id of taskIds) active.taskIds.add(id);\n }\n\n private async executeStepOnce(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n switch (step.kind) {\n case \"research\":\n return this.runFanOut(step, ctx);\n case \"collect\":\n return { status: \"completed\", summary: \"(collect: outputs gathered from previous steps)\", taskIds: [], reports: [] };\n case \"analyze\":\n if (!step.agent) {\n return { status: \"completed\", summary: \"(analyze: pass-through, no agent assigned)\", taskIds: [], reports: [] };\n }\n return this.runSingle(step, ctx, step.agent);\n case \"plan\":\n return this.runPlan(step, ctx);\n case \"execute\":\n case \"custom\":\n return this.runSingle(step, ctx, step.agent!);\n }\n }\n\n /** Research fan-out: one task per agent, in parallel (§15). */\n private async runFanOut(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const agentNames = step.agents ?? [];\n const created = await Promise.all(\n agentNames.map((name) =>\n this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: name,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0\n ? { context: { background: ctx.combinedContext } }\n : {}),\n }),\n ),\n );\n this.trackLiveTasks(ctx.runId, created.map((t) => t.id));\n const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n const executionIds = results.map((r) => r.executions?.at(-1)?.executionId).filter((id): id is string => id !== undefined);\n\n const completedTasks = results.filter((r) => r.status === \"completed\");\n const failedTasks = results.filter((r) => r.status !== \"completed\");\n const lines = results.map((result, index) => {\n const agentName = agentNames[index] ?? \"unknown\";\n const outcome = result.result?.summary ?? result.result?.error ?? \"(no output)\";\n return `- ${agentName}: ${outcome}`;\n });\n const reports = results.flatMap((r) => r.result?.reports ?? []);\n const summary = lines.join(\"\\n\");\n\n if (failedTasks.length > 0) {\n const firstError = failedTasks[0]?.result?.error ?? failedTasks[0]?.lastError ?? \"unknown outcome\";\n const states = failedTasks.map((r) => r.status).join(\", \");\n return {\n // Some agents succeeded → the step produced usable but incomplete\n // intelligence: partial, not failed (roadmap §9.3).\n status: completedTasks.length > 0 ? \"partial\" : \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) incomplete (${states}) — ${firstError}`,\n reports,\n };\n }\n return {\n status: \"completed\",\n summary,\n taskIds: created.map((t) => t.id),\n ...(executionIds.length > 0 ? { executionIds } : {}),\n reports,\n };\n }\n\n private async runSingle(\n step: PipelineStep,\n ctx: StepContext,\n agentName: string,\n ): Promise<StepOutcome> {\n const task = await this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: agentName,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: { background: ctx.combinedContext } } : {}),\n });\n this.trackLiveTasks(ctx.runId, [task.id]);\n const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n // Unknown/timed_out outcomes are not failures — the work may have\n // happened remotely; the step is incomplete, not broken.\n status: result.status === \"unknown\" || result.status === \"timed_out\" ? \"partial\" : \"failed\",\n summary: result.result?.summary ?? \"\",\n taskIds: [task.id],\n error: result.result?.error ?? `task ${task.id} did not complete`,\n reports: result.result?.reports ?? [],\n };\n }\n return {\n status: \"completed\",\n summary: result.result?.summary ?? \"(no output)\",\n taskIds: [task.id],\n reports: result.result?.reports ?? [],\n };\n }\n\n private async runPlan(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n // §15 Planner Input: task, reports, aggregated findings (consensus +\n // conflicts), context, role and step constraints.\n const aggregated = ctx.reports.length > 0 ? aggregateReports(ctx.reports) : undefined;\n const request = {\n objective: ctx.objective,\n reports: ctx.reports,\n ...(aggregated !== undefined ? { aggregated } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: ctx.combinedContext } : {}),\n ...(ctx.role ? { role: ctx.role } : {}),\n ...(step.constraints !== undefined && step.constraints.length > 0\n ? { constraints: step.constraints }\n : {}),\n ...(ctx.pipelineRunId !== undefined ? { pipelineRunId: ctx.pipelineRunId } : {}),\n };\n\n // Selection order: an explicit step model wins, then the configured\n // default planner, then a pass-through (nothing to plan with).\n let planner: IPlanner;\n if (step.model) {\n planner = new ModelPlanner({\n model: step.model,\n chat: this.getChat(),\n fallback: new HeuristicPlanner(),\n log: this.log,\n });\n } else if (this.options.planner) {\n planner = this.options.planner;\n } else {\n return {\n status: \"completed\",\n summary: \"(plan: no model or planner configured — skipped)\",\n taskIds: [],\n reports: [],\n };\n }\n\n let plan: Plan;\n try {\n plan = await planner.plan(request);\n } catch (error) {\n return {\n status: \"failed\",\n summary: \"\",\n taskIds: [],\n error: error instanceof Error ? error.message : String(error),\n reports: [],\n };\n }\n\n await this.options.plans?.save(plan);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"plan.generated\",\n id: plan.id,\n ...(ctx.pipelineDefId !== undefined ? { pipelineId: ctx.pipelineDefId } : {}),\n detail: {\n generatedBy: plan.generatedBy,\n steps: plan.steps.length,\n run: ctx.pipelineRunId,\n taskId: ctx.taskId,\n },\n });\n return {\n status: \"completed\",\n summary: plan.summary,\n contextContribution: formatPlan(plan),\n taskIds: [],\n planId: plan.id,\n reports: [],\n };\n }\n\n private getChat(): ChatFn {\n if (this.options.chat) return this.options.chat;\n throw new PipelineError(\n \"PIPELINE_FAILED\",\n \"No chat function available — configure a provider for plan steps.\",\n );\n }\n}\n\nfunction formatPlan(plan: Plan): string {\n const lines = [\n `# Implementation Plan (by ${plan.generatedBy})`,\n plan.summary,\n \"Steps:\",\n ...plan.steps.map((step) => {\n const targets = step.targets && step.targets.length > 0 ? ` [targets: ${step.targets.join(\", \")}]` : \"\";\n return `${step.order}. ${step.title}${targets}`;\n }),\n ];\n if (plan.risks && plan.risks.length > 0) {\n lines.push(\"Risks:\", ...plan.risks.map((risk) => `- ${risk}`));\n }\n return lines.join(\"\\n\");\n}\n\n/** Default chat function: resolves \"provider:model\" against the configured providers. */\nexport interface DefaultChatOptions {\n /** Correlates provider errors in the audit log (§18). */\n audit?: AuditSink;\n env?: Record<string, string | undefined>;\n}\n\nexport function createDefaultChatFn(\n providers: AppConfig[\"project\"][\"providers\"],\n options: DefaultChatOptions = {},\n): ChatFn {\n return async (modelRef, messages) => {\n const separator = modelRef.indexOf(\":\");\n if (separator <= 0 || separator === modelRef.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Invalid model reference \"${modelRef}\". Use \"provider:model-id\".`,\n );\n }\n const providerName = modelRef.slice(0, separator);\n const modelId = modelRef.slice(separator + 1);\n const providerConfig = providers.find((p) => p.name === providerName);\n if (!providerConfig) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Provider \"${providerName}\" (model \"${modelRef}\") is not configured.`,\n );\n }\n const provider = createProvider(providerConfig, {\n ...(options.audit !== undefined ? { audit: options.audit } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n });\n const response = await provider.chat({ model: modelId, messages });\n return response.content;\n };\n}\n","/**\n * Report aggregation (§17): normalizes formats, groups duplicate and similar\n * findings, preserves source attribution, and produces one CombinedReport.\n * Grouping uses deterministic token-set similarity so results are testable.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AggregatedFinding,\n AggregatedRecommendation,\n CombinedReport,\n Confidence,\n ConflictPosition,\n Finding,\n FindingSeverity,\n FindingSource,\n Report,\n ReportConflict,\n} from \"../types/report.js\";\nimport { normalizeEvidence } from \"./schema.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nexport interface AggregateOptions {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n /** Token-set Jaccard similarity above which findings are merged. */\n similarityThreshold?: number;\n}\n\nexport function aggregateReports(reports: Report[], options: AggregateOptions = {}): CombinedReport {\n const threshold = options.similarityThreshold ?? 0.7;\n\n const findingGroups: AggregatedFinding[] = [];\n const recommendationGroups: AggregatedRecommendation[] = [];\n\n for (const report of reports) {\n for (const finding of report.findings) {\n mergeFinding(findingGroups, finding, report, threshold);\n }\n for (const text of report.recommendations) {\n mergeRecommendation(recommendationGroups, text, report, threshold);\n }\n }\n\n const sources = [...new Set(reports.map((r) => r.agent))].sort();\n const totalRawFindings = reports.reduce((sum, r) => sum + r.findings.length, 0);\n const conflicts = detectConflicts(findingGroups);\n // Agreement = independently reported by 2+ agents with the same severity.\n const agreements = findingGroups.filter(\n (group) =>\n group.sources.length > 1 &&\n group.severity !== undefined &&\n new Set(Object.values(group.severityBySource ?? {})).size === 1,\n );\n const disputed = conflicts.length;\n const summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\n `${agreements.length} agreement(s), ${disputed} conflict(s), ` +\n `${recommendationGroups.length} recommendation group(s).`;\n\n return {\n id: `combined-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n title: options.objective !== undefined ? truncate(options.objective, 120) : \"Combined report\",\n ...(options.objective !== undefined ? { objective: options.objective } : {}),\n ...(options.pipelineRunId !== undefined ? { pipelineRunId: options.pipelineRunId } : {}),\n taskIds: options.taskIds ?? [],\n summary,\n findings: findingGroups.sort((a, b) => rank(b) - rank(a)),\n agreements,\n conflicts,\n recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\n metadata: {\n agents: sources.length,\n reports: reports.length,\n rawFindings: totalRawFindings,\n findingGroups: findingGroups.length,\n agreements: agreements.length,\n conflicts: conflicts.length,\n },\n };\n}\n\nfunction rankConfidence(confidence: Confidence | undefined): number {\n return confidence ? { low: 1, medium: 2, high: 3 }[confidence] : 0;\n}\n\n/**\n * Conflict detection (§14): agents disagreeing about the same finding is a\n * first-class result. Both positions are preserved — OmniNode never silently\n * chooses one.\n */\nexport function detectConflicts(groups: AggregatedFinding[]): ReportConflict[] {\n const conflicts: ReportConflict[] = [];\n for (const group of groups) {\n if (group.sources.length < 2) continue;\n\n const severities = new Set(Object.values(group.severityBySource ?? {}));\n if (severities.size > 1) {\n conflicts.push({\n type: \"severity\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note:\n `Agents disagree on severity (${[...severities].sort((a, b) => SEVERITY_RANK[a] - SEVERITY_RANK[b]).join(\", \")}); ` +\n `the highest severity is shown, every position is preserved.`,\n });\n }\n\n const recommendations = (group.recommendations ?? []).filter((r) => r.length > 0);\n if (recommendations.length > 1) {\n conflicts.push({\n type: \"recommendation\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note: `Agents proposed ${recommendations.length} different fixes; none was discarded.`,\n });\n }\n }\n return conflicts;\n}\n\nfunction position(\n source: FindingSource,\n group: AggregatedFinding,\n): ConflictPosition {\n return {\n agent: source.agent,\n reportId: source.reportId,\n ...(group.severityBySource?.[source.agent] !== undefined\n ? { severity: group.severityBySource[source.agent] }\n : {}),\n ...(group.confidenceBySource?.[source.agent] !== undefined\n ? { confidence: group.confidenceBySource[source.agent] }\n : {}),\n ...(group.recommendations?.[0] !== undefined ? { recommendation: group.recommendations[0] } : {}),\n };\n}\n\nfunction rank(finding: AggregatedFinding): number {\n return finding.severity ? SEVERITY_RANK[finding.severity] : -1;\n}\n\nfunction mergeFinding(groups: AggregatedFinding[], finding: Finding, report: Report, threshold: number): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.title, finding.title, threshold));\n if (group) {\n group.occurrences += 1;\n group.details.push(finding.detail);\n group.sources.push(source);\n group.evidence.push(...(normalizeEvidence(finding.evidence) ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\n }\n // Confidence preservation (§14): keep the strongest, and record per source.\n if (finding.confidence && rankConfidence(finding.confidence) > rankConfidence(group.confidence)) {\n group.confidence = finding.confidence;\n }\n if (finding.severity) {\n group.severityBySource = { ...group.severityBySource, [report.agent]: finding.severity };\n }\n if (finding.confidence) {\n group.confidenceBySource = { ...group.confidenceBySource, [report.agent]: finding.confidence };\n }\n if (finding.recommendation && !group.recommendations?.includes(finding.recommendation)) {\n group.recommendations = [...(group.recommendations ?? []), finding.recommendation];\n }\n return;\n }\n groups.push({\n title: finding.title,\n details: [finding.detail],\n sources: [source],\n occurrences: 1,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.confidence ? { confidence: finding.confidence } : {}),\n ...(finding.severity ? { severityBySource: { [report.agent]: finding.severity } } : {}),\n ...(finding.confidence ? { confidenceBySource: { [report.agent]: finding.confidence } } : {}),\n ...(finding.recommendation ? { recommendations: [finding.recommendation] } : {}),\n evidence: [...(normalizeEvidence(finding.evidence) ?? [])],\n });\n}\n\nfunction mergeRecommendation(\n groups: AggregatedRecommendation[],\n text: string,\n report: Report,\n threshold: number,\n): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.text, text, threshold));\n if (group) {\n group.occurrences += 1;\n group.sources.push(source);\n return;\n }\n groups.push({ text, sources: [source], occurrences: 1 });\n}\n\nexport function similar(a: string, b: string, threshold: number): boolean {\n const left = tokens(a);\n const right = tokens(b);\n if (left.size === 0 || right.size === 0) return false;\n let intersection = 0;\n for (const token of left) {\n if (right.has(token)) intersection += 1;\n }\n const union = left.size + right.size - intersection;\n return intersection / union >= threshold;\n}\n\nfunction tokens(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 3),\n );\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report validation and normalization (roadmap §13, Report Validation).\n *\n * Reports are machine-readable objects: they are schema-validated before they\n * can enter aggregation, and legacy string evidence / `detail` fields are\n * normalized into the v2 shape on the way in.\n */\nimport { z } from \"zod\";\nimport type { Confidence, Evidence, EvidenceInput, Finding, Report } from \"../types/report.js\";\n\nconst evidenceSchema = z.union([\n z.string().transform((excerpt): Evidence => ({ kind: \"observation\", excerpt })),\n z.object({\n kind: z.enum([\"file\", \"line\", \"url\", \"command\", \"observation\", \"artifact\"]),\n ref: z.string().optional(),\n line: z.number().int().optional(),\n excerpt: z.string().optional(),\n agent: z.string().optional(),\n }),\n]);\n\nconst findingSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n detail: z.string().default(\"\"),\n description: z.string().optional(),\n severity: z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]).optional(),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n severityBySource: z.record(z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"])).optional(),\n confidenceBySource: z.record(z.enum([\"low\", \"medium\", \"high\"])).optional(),\n recommendations: z.array(z.string()).optional(),\n evidence: z.array(evidenceSchema).optional(),\n location: z.string().optional(),\n tags: z.array(z.string()).optional(),\n source: z.object({ agent: z.string().optional(), reportId: z.string().optional(), pipelineRunId: z.string().optional() }).optional(),\n recommendation: z.string().optional(),\n});\n\nconst artifactSchema = z.object({\n kind: z.enum([\"file\", \"patch\", \"log\", \"screenshot\", \"document\", \"data\"]),\n ref: z.string().min(1),\n description: z.string().optional(),\n mediaType: z.string().optional(),\n bytes: z.number().int().optional(),\n});\n\nconst reportSchema = z.object({\n id: z.string().min(1),\n taskId: z.string().min(1),\n agent: z.string().min(1),\n agentId: z.string().optional(),\n pipelineRunId: z.string().optional(),\n model: z.string().optional(),\n summary: z.string(),\n findings: z.array(findingSchema),\n recommendations: z.array(z.string()),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n evidence: z.array(evidenceSchema).optional(),\n artifacts: z.array(artifactSchema).optional(),\n createdAt: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n});\n\nexport interface ReportValidationIssue {\n path: string;\n message: string;\n}\n\nexport type ReportValidationResult =\n | { valid: true; report: Report }\n | { valid: false; issues: ReportValidationIssue[]; reason: string };\n\n/** Validates (and normalizes) a report; malformed reports are rejected. */\nexport function validateReport(value: unknown): ReportValidationResult {\n const parsed = reportSchema.safeParse(value);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n }));\n return {\n valid: false,\n issues,\n reason: `report failed schema validation (${issues.length} issue(s))`,\n };\n }\n const report = parsed.data as Report;\n // Cross-field normalization: description mirrors detail, source carries provenance.\n report.findings = report.findings.map((finding) => ({\n ...finding,\n description: finding.description ?? finding.detail,\n ...(finding.source === undefined\n ? { source: { agent: report.agent, reportId: report.id, ...(report.pipelineRunId !== undefined ? { pipelineRunId: report.pipelineRunId } : {}) } }\n : {}),\n }));\n return { valid: true, report };\n}\n\n/** Normalizes evidence entries (strings or objects) to typed evidence. */\nexport function normalizeEvidence(input: EvidenceInput[] | undefined): Evidence[] | undefined {\n if (input === undefined) return undefined;\n return input.map((item) =>\n typeof item === \"string\" ? { kind: \"observation\" as const, excerpt: item } : item,\n );\n}\n\nexport function normalizeFinding(finding: Finding): Finding {\n return {\n ...finding,\n description: finding.description ?? finding.detail,\n evidence: normalizeEvidence(finding.evidence),\n };\n}\n\nexport type { Confidence };","/**\n * HeuristicPlanner: a deterministic, dependency-free planner that derives an\n * implementation plan from recommendations and significant findings.\n * Used as the no-model option and as the graceful fallback when a model's\n * output is rejected (§15).\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { Finding, FindingSeverity } from \"../types/report.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\ninterface ContributedFinding {\n finding: Finding;\n agent: string;\n}\n\nexport class HeuristicPlanner implements IPlanner {\n readonly name = \"heuristic\";\n\n async plan(request: PlanRequest): Promise<Plan> {\n const steps: PlanStep[] = [];\n\n // One step per distinct recommendation (deduped by text).\n const recommendations = dedupe(request.reports.flatMap((r) => r.recommendations));\n for (const text of recommendations) {\n steps.push({\n id: `step-${steps.length + 1}`,\n title: truncate(text, 120),\n order: steps.length + 1,\n ...(steps.length > 0 ? { dependsOn: [`step-${steps.length}`] } : {}),\n });\n }\n\n // Remediation steps for significant findings, most severe first. Aggregated\n // findings (with consensus/conflicts) take precedence when available.\n const contributed: ContributedFinding[] = request.aggregated\n ? request.aggregated.findings.map((finding) => ({\n finding: {\n id: `agg-${slug(finding.title)}`,\n title: finding.title,\n detail: finding.details[0] ?? finding.title,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.recommendations && finding.recommendations.length > 0\n ? { recommendation: finding.recommendations[0] }\n : {}),\n },\n agent: finding.sources.map((s) => s.agent).join(\"+\"),\n }))\n : request.reports.flatMap((report) =>\n report.findings.map((finding) => ({ finding, agent: report.agent })),\n );\n\n const significant = contributed\n .filter(({ finding }) =>\n finding.severity ? SEVERITY_RANK[finding.severity] >= SEVERITY_RANK.high : false,\n )\n .sort(\n (a, b) =>\n SEVERITY_RANK[b.finding.severity ?? \"info\"] - SEVERITY_RANK[a.finding.severity ?? \"info\"],\n );\n for (const { finding } of significant) {\n steps.push(remediationStep(finding, steps.length + 1));\n }\n\n if (steps.length === 0) {\n steps.push({\n id: \"step-1\",\n title: \"Gather additional information\",\n description:\n \"The research reports contained no actionable recommendations or significant findings. \" +\n \"Investigate the objective further before planning implementation work.\",\n order: 1,\n });\n }\n\n const risks = significant\n .filter(({ finding }) => finding.severity === \"critical\")\n .map(({ finding }) => `Critical finding unaddressed until its step completes: ${finding.title}`);\n const conflicts = request.aggregated?.conflicts ?? [];\n if (conflicts.length > 0) {\n risks.push(\n `${conflicts.length} unresolved agent disagreement(s): ${conflicts.map((c) => c.findingTitle).join(\"; \")}`,\n );\n }\n\n return {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: request.aggregated?.title ?? truncate(request.objective, 120),\n summary:\n `Derived from ${request.reports.length} report(s): ` +\n `${recommendations.length} recommendation step(s), ${significant.length} remediation step(s).`,\n steps,\n ...(risks.length > 0 ? { risks } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: \"heuristic\",\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n }\n}\n\nfunction remediationStep(finding: Finding, order: number): PlanStep {\n return {\n id: `step-${order}`,\n title: `Fix: ${truncate(finding.title, 100)}`,\n description: finding.detail,\n order,\n dependsOn: order > 1 ? [`step-${order - 1}`] : [],\n sourceFindings: [finding.id],\n ...(finding.recommendation ? { recommendation: finding.recommendation } : {}),\n };\n}\n\nfunction dedupe(texts: string[]): string[] {\n return [...new Set(texts.map((t) => t.trim()).filter((t) => t.length > 0))];\n}\n\nfunction slug(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\").slice(0, 40);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * ModelPlanner (§18): uses a chat model (\"provider:model-id\" through the chat\n * layer) to produce an implementation plan. The model is asked for JSON\n * matching the plan contract; unparseable output degrades gracefully to the\n * heuristic fallback rather than failing the pipeline.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { PlannerError } from \"../errors/index.js\";\nimport { planJsonSchema, validatePlan } from \"./schema.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { ChatFn, ChatMessage } from \"../types/chat.js\";\n\nimport { buildPlannerContext } from \"./context.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nexport interface ModelPlannerOptions {\n model: string;\n chat: ChatFn;\n /** Extra instruction appended to the system prompt. */\n instruction?: string;\n /** Used when the model output is unparseable (or the call fails, if tolerateErrors). */\n fallback?: IPlanner;\n log?: Logger;\n}\n\nexport class ModelPlanner implements IPlanner {\n readonly name = \"model\";\n private readonly log: Logger;\n\n constructor(private readonly options: ModelPlannerOptions) {\n this.log = (options.log ?? logger).child({ component: \"planner\", model: options.model });\n }\n\n async plan(request: PlanRequest): Promise<Plan> {\n const context = buildPlannerContext(request);\n const messages: ChatMessage[] = [\n {\n role: \"system\",\n content:\n \"You are the OmniNode planner. Given the objective and the combined research context, \" +\n \"produce a final analysis and a prioritized, actionable implementation plan. \" +\n \"Respond with JSON ONLY (no prose, no code fences) matching exactly this shape: \" +\n '{\"goal\": string, \"summary\": string, \"steps\": [{\"id\": string, \"title\": string, \"description\": string, ' +\n '\"order\": number, \"targets\": string[], \"acceptance_criteria\": string[], \"source_findings\": string[]}], ' +\n '\"risks\": string[], \"notes\": string[]}. ' +\n (this.options.instruction ?? \"\"),\n },\n { role: \"user\", content: context },\n ];\n\n let responseText: string;\n try {\n responseText = await this.options.chat(this.options.model, messages);\n } catch (error) {\n return this.degrade(request, `planner model call failed: ${describe(error)}`);\n }\n\n const parsed = parsePlanJson(responseText);\n if (!parsed.ok) {\n return this.degrade(request, `planner model output rejected: ${parsed.reason}`, parsed.issues);\n }\n\n const plan: Plan = {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: parsed.goal,\n summary: parsed.summary,\n steps: parsed.steps,\n ...(parsed.risks !== undefined ? { risks: parsed.risks } : {}),\n ...(parsed.notes !== undefined ? { notes: parsed.notes } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: `model:${this.options.model}`,\n model: this.options.model,\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n\n // §15 Validation: every generated plan passes schema validation.\n const validation = validatePlan(plan);\n if (!validation.valid) {\n return this.degrade(request, `generated plan rejected: ${validation.reason}`, validation.issues);\n }\n return validation.plan;\n }\n\n private async degrade(\n request: PlanRequest,\n reason: string,\n issues: Array<{ path: string; message: string }> = [],\n ): Promise<Plan> {\n if (this.options.fallback) {\n this.log.warn(`${reason} — using the heuristic fallback planner.`);\n return this.options.fallback.plan(request);\n }\n // Structured error: the caller sees exactly what was rejected (§15).\n throw new PlannerError(\"PLAN_INVALID\", `Planner failed: ${reason}.`, {\n details: { reason, issues },\n });\n }\n}\n\nexport type PlanJsonResult =\n | { ok: true; goal: string; summary: string; steps: PlanStep[]; risks?: string[]; notes?: string[] }\n | { ok: false; reason: string; issues: Array<{ path: string; message: string }> };\n\n/** Extracts and validates plan JSON from arbitrary model output (§15). */\nexport function parsePlanJson(text: string): PlanJsonResult {\n const unfenced = text.replace(/```(?:json)?/gi, \"\");\n const start = unfenced.indexOf(\"{\");\n const end = unfenced.lastIndexOf(\"}\");\n if (start < 0 || end <= start) {\n return { ok: false, reason: \"planner output contained no JSON object\", issues: [] };\n }\n let json: unknown;\n try {\n json = JSON.parse(unfenced.slice(start, end + 1));\n } catch (error) {\n return {\n ok: false,\n reason: `planner output was not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n issues: [],\n };\n }\n const parsed = planJsonSchema.safeParse(json);\n if (!parsed.success) {\n return {\n ok: false,\n reason: \"planner output did not match the plan schema\",\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n }\n const steps: PlanStep[] = parsed.data.steps\n .map((step, index) => ({\n id: step.id ?? `step-${index + 1}`,\n title: step.title,\n description: step.description,\n order: step.order ?? index + 1,\n targets: step.targets,\n acceptanceCriteria: step.acceptance_criteria,\n dependsOn: step.depends_on,\n sourceFindings: step.source_findings,\n }))\n .sort((a, b) => a.order - b.order);\n return {\n ok: true,\n goal: parsed.data.goal,\n summary: parsed.data.summary,\n steps,\n risks: parsed.data.risks,\n notes: parsed.data.notes,\n };\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Plan validation (roadmap §15, Validation): every generated plan passes\n * schema validation. Invalid plans are rejected with structured issues and\n * — where a fallback is configured — fall back to heuristic planning.\n */\nimport { z } from \"zod\";\nimport type { Plan } from \"../types/plan.js\";\n\nconst planStepSchema = z.object({\n id: z.string().min(1).optional(),\n title: z.string().min(1),\n description: z.string().optional(),\n order: z.number().int().optional(),\n targets: z.array(z.string()).optional(),\n acceptance_criteria: z.array(z.string()).optional(),\n depends_on: z.array(z.string()).optional(),\n source_findings: z.array(z.string()).optional(),\n});\n\nexport const planJsonSchema = z.object({\n goal: z.string().min(1),\n summary: z.string().min(1),\n steps: z.array(planStepSchema).min(1),\n risks: z.array(z.string()).optional(),\n notes: z.array(z.string()).optional(),\n});\n\nexport interface PlanValidationIssue {\n path: string;\n message: string;\n}\n\nexport type PlanValidationResult =\n | { valid: true; plan: Plan }\n | { valid: false; issues: PlanValidationIssue[]; reason: string };\n\n/** Validates a plan object (ids/order filled by the caller). */\nexport function validatePlan(plan: Plan): PlanValidationResult {\n const issues: PlanValidationIssue[] = [];\n const stepIds = new Set<string>();\n\n for (const [index, step] of plan.steps.entries()) {\n if (stepIds.has(step.id)) {\n issues.push({ path: `steps.${index}.id`, message: `duplicate step id \"${step.id}\"` });\n }\n stepIds.add(step.id);\n if (!step.title || step.title.trim().length === 0) {\n issues.push({ path: `steps.${index}.title`, message: \"title must not be empty\" });\n }\n for (const dep of step.dependsOn ?? []) {\n if (!stepIds.has(dep) && !plan.steps.some((s) => s.id === dep)) {\n issues.push({ path: `steps.${index}.dependsOn`, message: `unknown step dependency \"${dep}\"` });\n }\n }\n }\n\n if (plan.steps.length === 0) {\n issues.push({ path: \"steps\", message: \"a plan needs at least one step\" });\n }\n if (!plan.summary || plan.summary.trim().length === 0) {\n issues.push({ path: \"summary\", message: \"summary must not be empty\" });\n }\n\n return issues.length > 0\n ? { valid: false, issues, reason: `plan failed validation (${issues.length} issue(s))` }\n : { valid: true, plan };\n}\n\n/** Builds the parser input type for model-produced plan JSON. */\nexport type PlanJsonInput = z.input<typeof planJsonSchema>;\n","/**\n * Planner context builder (§15, Planner Input): assembles the original task,\n * project context, agent reports, aggregated findings, relevant memory and\n * constraints into one structured input, in that order.\n */\nimport type { PlanRequest } from \"./types.js\";\nimport type { Report } from \"../types/report.js\";\n\nexport function buildPlannerContext(request: PlanRequest): string {\n const parts: string[] = [`# Task\\n${request.objective}`];\n\n if (request.projectContext) {\n parts.push(`# Project context\\n${request.projectContext}`);\n }\n\n if (request.role) {\n const roleLines = [`# Role\\n${request.role.name} (${request.role.id})`];\n if (request.role.responsibilities.length > 0) {\n roleLines.push(\"Responsibilities:\", ...request.role.responsibilities.map((r) => `- ${r}`));\n }\n if (request.role.expectedOutputs.length > 0) {\n roleLines.push(\"Expected outputs:\", ...request.role.expectedOutputs.map((o) => `- ${o}`));\n }\n parts.push(roleLines.join(\"\\n\"));\n }\n\n if (request.reports.length > 0) {\n const agents = [...new Set(request.reports.map((r) => r.agent))].join(\", \");\n const findingLines = request.reports.flatMap((report: Report) =>\n report.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (source: ${report.agent}, finding: ${finding.id})` +\n (finding.detail ? ` — ${finding.detail}` : \"\"),\n ),\n );\n parts.push(\n `# Agent reports (${request.reports.length} by ${agents})\\n` +\n (findingLines.length > 0 ? findingLines.join(\"\\n\") : \"(no findings reported)\"),\n );\n\n const recommendationLines = request.reports.flatMap((report) =>\n report.recommendations.map((text) => `- ${text} (source: ${report.agent})`),\n );\n if (recommendationLines.length > 0) {\n parts.push(`# Recommendations\\n${recommendationLines.join(\"\\n\")}`);\n }\n }\n\n if (request.aggregated) {\n const aggregatedLines = [\n `- findings: ${request.aggregated.findings.length} (agreements: ${request.aggregated.agreements.length}, conflicts: ${request.aggregated.conflicts.length})`,\n ...request.aggregated.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences})`,\n ),\n // Conflicts stay visible to the planner — it must plan around disagreement.\n ...request.aggregated.conflicts.map(\n (conflict) => `- CONFLICT (${conflict.type}) on \"${conflict.findingTitle}\": ${conflict.note}`,\n ),\n ];\n parts.push(`# Aggregated findings\\n${aggregatedLines.join(\"\\n\")}`);\n }\n\n if (request.memory && request.memory.length > 0) {\n parts.push(\n `# Relevant memory\\n` +\n request.memory.map((entry) => `- [${entry.scope}] ${entry.content}`).join(\"\\n\"),\n );\n }\n\n if (request.constraints && request.constraints.length > 0) {\n parts.push(`# Constraints\\n${request.constraints.map((c) => `- ${c}`).join(\"\\n\")}`);\n }\n\n if (request.context) {\n parts.push(`# Research context\\n${request.context}`);\n }\n\n return parts.join(\"\\n\\n\");\n}\n","/**\n * Pipeline run persistence (§27 Phase 5 — pipeline state). Same\n * replaceable-store pattern as the task store, local-first JSON file.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { PipelineRun, PipelineRunStatus } from \"../types/pipeline.js\";\n\nexport interface PipelineRunFilter {\n pipelineId?: string;\n status?: PipelineRunStatus;\n}\n\nexport interface PipelineRunStore {\n save(run: PipelineRun): Promise<void>;\n get(id: string): Promise<PipelineRun | undefined>;\n list(filter?: PipelineRunFilter): Promise<PipelineRun[]>;\n}\n\nexport class FilePipelineRunStore extends JsonFileStore<PipelineRun> implements PipelineRunStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"pipelines.json\" });\n }\n\n save(run: PipelineRun): Promise<void> {\n return this.mutate((runs) => {\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n return [runs, undefined];\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return (await this.readAll()).find((r) => r.id === id);\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return (await this.readAll())\n .filter((run) => (filter.pipelineId ? run.pipelineId === filter.pipelineId : true))\n .filter((run) => (filter.status ? run.status === filter.status : true))\n .sort((a, b) => (a.startedAt ?? \"\").localeCompare(b.startedAt ?? \"\"));\n }\n}\n","/**\n * Plan persistence (§27 Phase 8 — planner result storage). Same\n * replaceable-store pattern as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Plan } from \"../types/plan.js\";\n\nexport interface PlanFilter {\n pipelineRunId?: string;\n taskId?: string;\n}\n\nexport interface PlanStore {\n save(plan: Plan): Promise<void>;\n get(id: string): Promise<Plan | undefined>;\n list(filter?: PlanFilter): Promise<Plan[]>;\n}\n\nexport class FilePlanStore extends JsonFileStore<Plan> implements PlanStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"plans.json\" });\n }\n\n save(plan: Plan): Promise<void> {\n return this.mutate((plans) => {\n const index = plans.findIndex((p) => p.id === plan.id);\n if (index >= 0) plans[index] = plan;\n else plans.push(plan);\n return [plans, undefined];\n });\n }\n\n async get(id: string): Promise<Plan | undefined> {\n return (await this.readAll()).find((p) => p.id === id);\n }\n\n async list(filter: PlanFilter = {}): Promise<Plan[]> {\n return (await this.readAll())\n .filter((plan) => (filter.pipelineRunId ? plan.pipelineRunId === filter.pipelineRunId : true))\n .filter((plan) => (filter.taskId ? plan.taskId === filter.taskId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/** Planner factory from project configuration (§18 — planner provider support). */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { ChatFn } from \"../types/chat.js\";\nimport { HeuristicPlanner } from \"./heuristic.js\";\nimport { ModelPlanner } from \"./model.js\";\nimport type { IPlanner } from \"./types.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport function buildPlanner(\n plannerConfig: AppConfig[\"project\"][\"planner\"],\n chat: ChatFn,\n log: Logger = logger,\n): IPlanner | undefined {\n if (!plannerConfig) return undefined;\n if (plannerConfig.kind === \"heuristic\") {\n return new HeuristicPlanner();\n }\n if (!plannerConfig.model) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n 'Planner kind \"model\" needs a model reference (\"provider:model-id\") in omninode.yaml.',\n );\n }\n return new ModelPlanner({\n model: plannerConfig.model,\n chat,\n ...(plannerConfig.instruction !== undefined ? { instruction: plannerConfig.instruction } : {}),\n fallback: new HeuristicPlanner(),\n log,\n });\n}\n","/**\n * Report normalization (§17): turns an agent's text output into a structured\n * Report by extracting findings, recommendations and evidence from\n * markdown-style sections. Deterministic heuristics; AI-assisted extraction\n * can layer on top later via the planner.\n */\nimport type { Finding, FindingSeverity, Report } from \"../types/report.js\";\n\nexport interface ExtractionMeta {\n taskId: string;\n agent: string;\n model?: string;\n}\n\nconst BULLET = /^(?:[-*•]|\\d+[.)])\\s+(.*)$/;\n\ninterface Section {\n heading: string;\n bullets: string[];\n}\n\nfunction parseSections(raw: string): Section[] {\n const sections: Section[] = [];\n let current: Section = { heading: \"\", bullets: [] };\n for (const line of raw.split(\"\\n\")) {\n const heading = /^(#{1,6})\\s+(.*)$/.exec(line.trim());\n if (heading) {\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n current = { heading: heading[2]?.toLowerCase() ?? \"\", bullets: [] };\n continue;\n }\n const bullet = BULLET.exec(line.trim());\n if (bullet && current.heading.length > 0) {\n current.bullets.push(bullet[1]?.trim() ?? \"\");\n }\n }\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n return sections;\n}\n\nfunction collectBullets(sections: Section[], patterns: RegExp[]): string[] {\n const matches = sections.filter((section) => patterns.some((p) => p.test(section.heading)));\n return matches.flatMap((section) => section.bullets).filter((b) => b.length > 0);\n}\n\nfunction guessSeverity(text: string): FindingSeverity | undefined {\n if (/critical|severe/i.test(text)) return \"critical\";\n if (/\\bhigh\\b|major/i.test(text)) return \"high\";\n if (/medium|moderate/i.test(text)) return \"medium\";\n if (/\\blow\\b|minor/i.test(text)) return \"low\";\n return undefined;\n}\n\nexport function extractReportFromText(raw: string, meta: ExtractionMeta): Report {\n const trimmed = raw.trim();\n const nonEmpty = trimmed\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n // Prefer a prose line over markdown headings/bullets for the summary.\n const proseLine =\n nonEmpty.find((line) => !line.startsWith(\"#\") && !BULLET.test(line)) ?? nonEmpty[0] ?? \"\";\n const cleaned = proseLine.replace(/^#{1,6}\\s+/, \"\").replace(BULLET, \"$1\");\n const summary = cleaned.length > 0 ? truncate(cleaned, 200) : \"(no output)\";\n\n const sections = parseSections(trimmed);\n const findingTexts = collectBullets(sections, [/finding/, /issue/, /problem/, /vulnerab/]);\n const recommendationTexts = collectBullets(sections, [/recommend/, /suggestion/, /next step/, /action/]);\n const evidenceTexts = collectBullets(sections, [/evidence/, /proof/, /log/]);\n\n const findings: Finding[] = findingTexts.map((text, index) => ({\n id: `${meta.taskId}-f-${index + 1}`,\n title: truncate(text, 120),\n detail: text,\n description: text,\n severity: guessSeverity(text),\n }));\n\n return {\n id: `${meta.taskId}-report`,\n taskId: meta.taskId,\n agent: meta.agent,\n ...(meta.model !== undefined ? { model: meta.model } : {}),\n summary,\n findings,\n recommendations: recommendationTexts.map((t) => truncate(t, 200)),\n ...(evidenceTexts.length > 0\n ? { evidence: evidenceTexts.map((excerpt) => ({ kind: \"observation\" as const, excerpt })) }\n : {}),\n metadata: evidenceTexts.length > 0 ? { evidenceCount: evidenceTexts.length } : undefined,\n createdAt: new Date().toISOString(),\n };\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report service (§16–§17): collects reports from finished tasks (structured\n * protocol reports when present, extraction from text otherwise), persists\n * them with source attribution and generates combined reports.\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Task } from \"../types/task.js\";\nimport type { Report, CombinedReport } from \"../types/report.js\";\nimport { aggregateReports, type AggregateOptions } from \"./aggregate.js\";\nimport { extractReportFromText } from \"./extract.js\";\nimport { validateReport } from \"./schema.js\";\nimport type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\n/** Serialized size budget for a single report (roadmap §17 — output limits). */\nexport const MAX_REPORT_BYTES = 256 * 1024;\n\nexport interface CollectionDiagnostics {\n collected: number;\n accepted: number;\n rejected: Array<{ key: string; reason: string; issues: string[] }>;\n}\n\nexport class ReportService {\n private readonly log: Logger;\n /** Rejected reports from the last collection (§13 — malformed never enters aggregation). */\n lastDiagnostics: CollectionDiagnostics = { collected: 0, accepted: 0, rejected: [] };\n\n constructor(\n private readonly store: ReportStore,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"reports\" });\n }\n\n get storeRef(): ReportStore {\n return this.store;\n }\n\n /** Normalizes finished tasks into reports (§17 — normalizer), validating each\n * one so malformed reports never reach aggregation (§13). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const candidates: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n candidates.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n candidates.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\n\n const reports: Report[] = [];\n const rejected: CollectionDiagnostics[\"rejected\"] = [];\n for (const candidate of candidates) {\n const size = Buffer.byteLength(JSON.stringify(candidate), \"utf8\");\n if (size > MAX_REPORT_BYTES) {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: `report exceeds the ${MAX_REPORT_BYTES} byte limit (${size} bytes)`,\n issues: [],\n });\n this.log.warn(`Rejected oversized report (${size} bytes).`);\n continue;\n }\n const result = validateReport(candidate);\n if (result.valid) {\n reports.push(result.report);\n } else {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: result.reason,\n issues: result.issues.map((issue) => `${issue.path}: ${issue.message}`),\n });\n this.log.warn(`Rejected malformed report: ${result.reason}`);\n }\n }\n this.lastDiagnostics = { collected: candidates.length, accepted: reports.length, rejected };\n return reports;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n if (reports.length === 0) return;\n await this.store.saveReports(reports);\n this.log.info(`Stored ${reports.length} report(s).`);\n }\n\n async generateCombined(reports: Report[], meta: CombinedMeta = {}): Promise<CombinedReport | undefined> {\n if (reports.length === 0) return undefined;\n const options: AggregateOptions = {\n ...(meta.objective !== undefined ? { objective: meta.objective } : {}),\n ...(meta.pipelineRunId !== undefined ? { pipelineRunId: meta.pipelineRunId } : {}),\n ...(meta.taskIds !== undefined ? { taskIds: meta.taskIds } : {}),\n };\n const combined = aggregateReports(reports, options);\n await this.store.saveCombined(combined);\n this.log.info(`Generated combined report ${combined.id}.`);\n return combined;\n }\n}\n","/**\n * Report persistence (§16 — report storage). Same replaceable-store and\n * serialized-write patterns as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { CombinedReport, Report } from \"../types/report.js\";\n\nexport interface ReportFilter {\n taskId?: string;\n agent?: string;\n}\n\nexport interface CombinedReportFilter {\n pipelineRunId?: string;\n}\n\nexport interface ReportStore {\n saveReports(reports: Report[]): Promise<void>;\n listReports(filter?: ReportFilter): Promise<Report[]>;\n saveCombined(combined: CombinedReport): Promise<void>;\n getCombined(id: string): Promise<CombinedReport | undefined>;\n listCombined(filter?: CombinedReportFilter): Promise<CombinedReport[]>;\n}\n\ntype StoreEntry = { kind: \"report\"; report: Report } | { kind: \"combined\"; combined: CombinedReport };\n\nexport class FileReportStore extends JsonFileStore<StoreEntry> implements ReportStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"reports.json\" });\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n await this.mutate((entries) => {\n for (const report of reports) {\n const index = entries.findIndex((e) => e.kind === \"report\" && e.report.id === report.id);\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n return [entries, undefined];\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"report\"; report: Report } => e.kind === \"report\")\n .map((e) => e.report)\n .filter((report) => (filter.taskId ? report.taskId === filter.taskId : true))\n .filter((report) => (filter.agent ? report.agent === filter.agent : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n\n async saveCombined(combined: CombinedReport): Promise<void> {\n await this.mutate((entries) => {\n const index = entries.findIndex((e) => e.kind === \"combined\" && e.combined.id === combined.id);\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n return [entries, undefined];\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n const found = (await this.readAll()).find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) => (filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","import type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildPlanner } from \"../planner/index.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { ReportService } from \"../reports/index.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { TaskEngine } from \"../tasks/index.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport { PipelineEngine, createDefaultChatFn } from \"./engine.js\";\nimport { FilePipelineRunStore } from \"./store.js\";\n\nexport function buildPipelineEngine(config: AppConfig, log: Logger = logger): PipelineEngine {\n const auditLog = new FileAuditLog();\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n const chat = createDefaultChatFn(config.project.providers, { audit: auditLog });\n const tasks = new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n return new PipelineEngine({\n tasks,\n agents,\n roles,\n providers: config.project.providers,\n store: new FilePipelineRunStore(),\n chat,\n ...(config.project.planner !== undefined\n ? { planner: buildPlanner(config.project.planner, chat, log) }\n : {}),\n plans: new FilePlanStore(),\n reports: new ReportService(new FileReportStore(), log),\n audit: new FileAuditLog(),\n log,\n });\n}\n","/**\n * Persistence layer (v2 Phase 12): one entry point to every local store,\n * the canonical storage interface names, and the migration path that upgrades\n * v1 data in place.\n */\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { LocalMemoryProvider } from \"../memory/local.js\";\nimport { FilePipelineRunStore } from \"../pipelines/store.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport {\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n type DocumentState,\n} from \"./json-file-store.js\";\nexport {\n JsonFileStore,\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n} from \"./json-file-store.js\";\nexport type { JsonDocument, DocumentState, JsonFileStoreOptions, Durability } from \"./json-file-store.js\";\n\n// Canonical storage interface names (roadmap §16). The v1 names above remain\n// the exported API; these aliases document the mapping.\nexport type { TaskStore, PipelineStore, ReportStore, PlanStore, MemoryStore, AuditStore } from \"./store-types.js\";\n\n/** Bundles every store for a single project directory. */\nexport class ProjectStores {\n readonly tasks: FileTaskStore;\n readonly pipelineRuns: FilePipelineRunStore;\n readonly reports: FileReportStore;\n readonly plans: FilePlanStore;\n readonly memory: LocalMemoryProvider;\n readonly audit: FileAuditLog;\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.tasks = new FileTaskStore(directory);\n this.pipelineRuns = new FilePipelineRunStore(directory);\n this.reports = new FileReportStore(directory);\n this.plans = new FilePlanStore(directory);\n this.memory = new LocalMemoryProvider(directory);\n this.audit = new FileAuditLog(directory);\n }\n}\n\nexport interface MigrationReport {\n file: string;\n state: DocumentState[\"status\"];\n before?: number;\n after?: number;\n migrated: boolean;\n note?: string;\n}\n\n/** Every persisted store file OmniNode manages in a project. */\nexport const STORE_FILES = [\n \"tasks.json\",\n \"pipelines.json\",\n \"reports.json\",\n \"plans.json\",\n \"memory.json\",\n] as const;\n\n/**\n * Migration (roadmap §16): inspects every store file, reports its schema\n * state, and — unless `checkOnly` — rewrites v1 documents at the current\n * schema version. Idempotent and safe: unknown/future versions are reported,\n * never rewritten.\n */\nexport async function migrateProjectStores(\n directory = `${process.cwd()}/.omninode`,\n options: { checkOnly?: boolean } = {},\n): Promise<MigrationReport[]> {\n const reports: MigrationReport[] = [];\n for (const file of STORE_FILES) {\n const path = `${directory}/${file}`;\n const state = await inspectDocument(path);\n if (state.status === \"missing\") {\n reports.push({ file, state: state.status, migrated: false });\n continue;\n }\n if (state.status === \"current\") {\n reports.push({ file, state: state.status, before: state.count, after: state.count, migrated: false });\n continue;\n }\n if (state.status === \"future\") {\n reports.push({\n file,\n state: state.status,\n migrated: false,\n note: `written by a newer OmniNode (schema v${state.schemaVersion}); not touched`,\n });\n continue;\n }\n if (state.status === \"corrupt\") {\n reports.push({ file, state: state.status, migrated: false, note: state.detail });\n continue;\n }\n // v1-legacy or empty: rewrite at the current schema version.\n const items = await readDocument<unknown>(path, undefined, false);\n if (!options.checkOnly) {\n await writeFileAtomic(path, `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, items }, null, 2)}\\n`);\n }\n const beforeCount = items.length;\n reports.push({\n file,\n state: state.status,\n before: beforeCount,\n after: items.length,\n migrated: !options.checkOnly,\n ...(options.checkOnly ? { note: \"would migrate\" } : {}),\n });\n }\n return reports;\n}\n","export const OMNINODE_VERSION = \"2.0.0-alpha.14\";\n"],"mappings":";AAyBO,IAAM,yBAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACGO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EAET,YAAY,MAAyB,SAAiB,UAAgC,CAAC,GAAG;AACxF,UAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AACvC,SAAK,OAAO,WAAW;AACvB,SAAK,OAAO;AACZ,SAAK,UAAU,QAAQ;AAAA,EACzB;AACF;AAEO,IAAM,cAAN,cAA0B,cAAc;AAAA,EAC7C,YACE,MACA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,gBAAN,cAA4B,cAAc;AAAA,EAC/C,YACE,MAKA,SACA,UAAgC,CAAC,GACjC;AACA,UAAM,MAAM,SAAS,OAAO;AAAA,EAC9B;AACF;AAEO,IAAM,aAAN,cAAyB,cAAc;AAA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readFile","dirname","mkdir","dirname","readFile","randomBytes","randomBytes","z","randomBytes","randomBytes","SEVERITY_RANK","truncate","randomBytes","z","randomBytes","randomBytes","truncate"]}
|