@hilbras/omninode 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/index.ts","../src/logger/index.ts","../src/config/schema.ts","../src/config/loader.ts","../src/config/default.ts","../src/providers/auth.ts","../src/providers/http.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/agents/registry.ts","../src/agents/factory.ts","../src/roles/index.ts","../src/tasks/store.ts","../src/tasks/engine.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/pipelines/store.ts","../src/reports/aggregate.ts","../src/reports/extract.ts","../src/reports/service.ts","../src/reports/store.ts","../src/pipelines/engine-factory.ts","../src/version.ts"],"sourcesContent":["/** 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 | \"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 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 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 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 })\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 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 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 })\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 ProjectConfigYaml = z.infer<typeof projectConfigSchema>;\nexport type AppConfigYaml = z.infer<typeof appConfigSchema>;\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 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 memory?: {\n provider: string;\n baseUrl?: string;\n apiKeyEnvVar?: string;\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 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.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 },\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 })),\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 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 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 */\nimport { ProviderError } from \"../errors/index.js\";\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 let response: Response;\n try {\n 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 } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new ProviderError(\"PROVIDER_UNAVAILABLE\", `Request to ${url} failed: ${reason}.`, {\n cause: error,\n });\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch (error) {\n throw new ProviderError(\"PROVIDER_UNAVAILABLE\", `Response from ${url} was not valid JSON.`, {\n cause: error,\n details: { status: response.status },\n });\n }\n\n return { status: response.status, body: parsed };\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\";\nimport type { ChatRequest, ChatResponse } from \"../../types/chat.js\";\nimport type { ModelInfo } from \"../../types/model.js\";\nimport type { IChatProvider, ProviderConfig, ProviderStatus } from \"../../types/provider.js\";\nimport { authHeaders } from \"../auth.js\";\nimport { requestJson } from \"../http.js\";\n\ninterface OpenAIModelEntry {\n id?: unknown;\n owned_by?: unknown;\n created?: 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 private readonly log: Logger;\n\n constructor(config: ProviderConfig, log: Logger = logger) {\n this.config = { ...config, baseUrl: normalizeBaseUrl(config.baseUrl) };\n this.log = log.child({ provider: config.name });\n }\n\n async listModels(): Promise<ModelInfo[]> {\n const { status, body } = await requestJson(`${this.config.baseUrl}/models`, {\n headers: authHeaders(this.config),\n });\n if (status === 401 || status === 403) {\n throw authFailed(this.config, status);\n }\n if (status !== 200) {\n throw unavailable(this.config, `Model discovery returned HTTP ${status}.`, status);\n }\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({\n provider: this.config.name,\n id: entry.id,\n displayName: entry.id,\n status: \"available\",\n metadata: {\n ...(typeof entry.owned_by === \"string\" ? { ownedBy: entry.owned_by } : {}),\n ...(typeof entry.created === \"number\" ? { createdAt: entry.created } : {}),\n },\n });\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 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 const { status, body } = await requestJson(`${this.config.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: authHeaders(this.config),\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\n if (status === 401 || status === 403) throw authFailed(this.config, status);\n if (status === 404) {\n throw new ProviderError(\n \"MODEL_NOT_FOUND\",\n `Model \"${request.model}\" or the chat endpoint was not found on provider \"${this.config.name}\" (HTTP 404).`,\n { details: { status } },\n );\n }\n if (status !== 200) {\n throw unavailable(this.config, `Chat completion returned HTTP ${status}.`, status);\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\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 authFailed(config: ProviderConfig, status: number): ProviderError {\n const envHint = config.apiKeyEnvVar\n ? ` Check that $${config.apiKeyEnvVar} is set and valid.`\n : \" The provider requires authentication; configure api_key_env_var for it.\";\n return new ProviderError(\n \"PROVIDER_AUTH_FAILED\",\n `Authentication with provider \"${config.name}\" failed (HTTP ${status}).${envHint}`,\n { details: { status } },\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 /**\n * Run the full connect flow. Throws on authentication or transport failure\n * (use healthCheck() for a non-throwing probe).\n */\n async connect(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, ProtocolError } from \"../../errors/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 { EnvelopeMeta, NodeToAgentMessage } from \"../../types/protocol.js\";\nimport type { Report } from \"../../types/report.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\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 const meta: EnvelopeMeta = {\n taskId: input.taskId,\n agent: agentName,\n timestamp: new Date().toISOString(),\n };\n const messages: NodeToAgentMessage[] = [\n { type: \"TASK\", payload: { taskId: input.taskId, objective: input.objective } },\n ];\n if (input.role) messages.push({ type: \"ROLE\", payload: input.role });\n if (input.context) messages.push({ type: \"CONTEXT\", payload: { body: input.context } });\n if (input.instruction) messages.push({ type: \"INSTRUCTION\", payload: { text: input.instruction } });\n return messages.map((message) => JSON.stringify({ meta, message }));\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 const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n cwd: this.config.cwd,\n env: { ...process.env, ...this.config.env },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n );\n this.running.set(input.taskId, child);\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process.`);\n child.kill(\"SIGTERM\");\n setTimeout(() => child.kill(\"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 finish();\n };\n\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\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 { details: { taskId: input.taskId, stdout: stdout.slice(0, 4000), stderr: stderr.slice(0, 2000) } },\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 ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n error:\n code === 0\n ? undefined\n : `Process exited with code ${code ?? \"unknown\"}${signal ? ` (signal: ${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) child.kill(\"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}\n\nfunction interpretProtocolRun({ input, agentName, stdout, exitCode, logs }: ProtocolRunInput): AgentTaskOutput {\n const reports: Report[] = [];\n let summary: string | undefined;\n let error: string | undefined;\n let sawProtocolMessage = false;\n\n for (const line of stdout.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n const message = parseAgentMessage(trimmed);\n if (!message) continue;\n sawProtocolMessage = true;\n\n if (message.type === \"REPORT\") {\n const report = normalizeReport(message.payload, input.taskId, agentName, reports.length);\n if (report) reports.push(report);\n } else if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n if (typeof payload?.summary === \"string\") summary = payload.summary;\n } else if (message.type === \"ERROR\") {\n const payload = message.payload as { code?: unknown; message?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"unknown error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n error = `Agent error${code}: ${detail}`;\n }\n // STATUS / QUESTION / ARTIFACT are informational in v0.4 (§21 backlog).\n }\n\n if (!sawProtocolMessage && exitCode === 0) {\n throw new ProtocolError(\n `Agent \"${agentName}\" produced no protocol messages on stdout (input mode \"protocol\").`,\n { details: { taskId: input.taskId, stdout: stdout.slice(0, 2000) } },\n );\n }\n\n const trimmed = stdout.trim();\n return {\n taskId: input.taskId,\n status: error !== undefined || exitCode !== 0 ? \"failed\" : \"completed\",\n summary: summary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n reports: reports.length > 0 ? reports : undefined,\n error:\n error ??\n (exitCode !== 0 ? `Process exited with code ${exitCode ?? \"unknown\"}` : undefined),\n };\n}\n\n/** Accepts both bare `{ type, payload }` and enveloped `{ meta, message }` lines. */\nfunction parseAgentMessage(line: string): { type: string; payload: unknown } | undefined {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n if (typeof parsed.type === \"string\") {\n return { type: parsed.type, payload: parsed.payload };\n }\n const inner = parsed.message as Record<string, unknown> | undefined;\n if (inner && typeof inner.type === \"string\") {\n return { type: inner.type, payload: inner.payload };\n }\n } catch {\n // Non-JSON chatter is tolerated; protocol compliance is judged overall.\n }\n return undefined;\n}\n\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","/** 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\";\n\nexport function createAgent(config: AgentConfig): IAgent {\n if (config.integration === \"process\") {\n return new ProcessAgent(config);\n }\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `Native agent adapters are planned for a later phase. Use input over stdin/stdout (type \"cli\") for \"${config.name}\" for now.`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\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 * 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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements TaskStore {\n private readonly filePath: string;\n /**\n * Read-modify-write operations are serialized: parallel pipeline tasks\n * would otherwise race on the JSON file (last writer wins).\n */\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/tasks.json`;\n }\n\n async save(task: Task): Promise<void> {\n return this.synchronized(async () => {\n const tasks = await this.load();\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n await this.write(tasks);\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.synchronized(async () => {\n const tasks = await this.load();\n return tasks.find((t) => t.id === id);\n });\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n return this.synchronized(async () => {\n const tasks = await this.load();\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 private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<Task[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as Task[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(tasks: Task[]): Promise<void> {\n // Write to a temp file and rename for an atomic-enough local save.\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(tasks, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 { TaskError } from \"../errors/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type { Task, TaskContext, TaskResult, TaskStatus } from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"cancelled\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n failed: [],\n cancelled: [],\n};\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\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 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 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 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 async run(id: string): 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 const running = await this.transition(task, \"running\");\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 = running.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: running.objective,\n ...(running.role ? { role: running.role } : {}),\n ...(running.project ? { project: running.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n let output;\n try {\n output = await agent.run({\n taskId: running.id,\n objective: running.objective,\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.log.error(`Task ${task.id} failed: ${message}`);\n return this.transition(running, \"failed\", {\n result: { error: message, finishedAt: new Date().toISOString() },\n });\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: new Date().toISOString(),\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n const finished = await this.transition(running, finalStatus, { result });\n this.log.info(`Task ${task.id} finished: ${finalStatus}.`);\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(finished);\n }\n return finished;\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 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 } = {},\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 updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n return updated;\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { IMemoryProvider, MemoryEntry, MemoryQuery } 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 implements IMemoryProvider {\n readonly name = \"local\";\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/memory.json`;\n }\n\n async query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : 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\n async write(entry: MemoryEntry): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\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 await this.saveAll(entries);\n });\n }\n\n async count(): Promise<number> {\n return (await this.load()).length;\n }\n\n private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<MemoryEntry[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as MemoryEntry[]) : [];\n } catch {\n return [];\n }\n }\n\n private async saveAll(entries: MemoryEntry[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(entries, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 { IMemoryProvider, MemoryEntry, MemoryQuery } from \"../types/memory.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 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 async query(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 write(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.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 (§19–§20): gathers relevant memory before a task runs and\n * records outcomes afterwards — the Task → memory → relevant context →\n * agents → reports → memory loop. Memory failures are best-effort: they log\n * a warning and never fail a task, because memory is an enhancement, not a\n * dependency (§2).\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry, MemoryScope } 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}\n\nconst MAX_CONTEXT_CHARS = 4_000;\n\nexport class MemoryService {\n private readonly log: Logger;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n /** Relevant context for a task objective; empty string when nothing matches. */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n try {\n const entries = await this.provider.query({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: 8,\n });\n if (entries.length === 0) return \"\";\n const byScope = new Map<MemoryScope, 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\"] as MemoryScope[]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries.map((entry) => `- ${entry.content}`).join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n const context = parts.join(\"\\n\\n\");\n return context.length > MAX_CONTEXT_CHARS ? `${context.slice(0, MAX_CONTEXT_CHARS)}…` : context;\n } catch (error) {\n this.log.warn(\n `Memory query failed (continuing without memory): ${error instanceof Error ? error.message : String(error)}`,\n );\n return \"\";\n }\n }\n\n /** Records a finished task's outcome — best-effort. */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.write({\n key: `task:${task.id}`,\n scope: \"task\",\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 // Significant findings become project-level \"known problems\" (§19).\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.write({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.log.warn(\n `Memory write failed (continuing): ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n}\n","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/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 ? { memory: new MemoryService(createMemoryProvider(config.project.memory), log) }\n : {}),\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 PipelineDefinition,\n PipelineRun,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatMessage } from \"../types/chat.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/index.js\";\nimport type { TaskEngine } from \"../tasks/index.js\";\nimport type { PipelineRunStore } from \"./store.js\";\n\nexport type ChatFn = (modelRef: string, messages: ChatMessage[]) => Promise<string>;\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 /** 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\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n role?: RoleDefinition;\n combinedContext: string;\n}\n\nexport class PipelineEngine {\n private readonly log: Logger;\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 /** 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: RunPipelineOptions = {}): 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 before anything runs.\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 }\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 status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n this.log.info(`Running pipeline ${def.id} as ${run.id}.`);\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\n while (pending.size > 0) {\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 };\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 status:\n outcome.status === \"skipped\" ? \"cancelled\" : outcome.status === \"failed\" ? \"failed\" : \"completed\",\n ...(outcome.taskIds.length > 0 ? { taskIds: outcome.taskIds } : {}),\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.options.store.save(run);\n }\n\n const failed = [...outcomes.values()].some((o) => o.status === \"failed\");\n const finalStatus: PipelineRunStatus = failed ? \"failed\" : \"completed\";\n\n // Report system (§16–§17): collect, store and combine reports from all tasks.\n let combinedReportId: string | undefined;\n if (this.options.reports) {\n const taskIds = [...outcomes.values()].flatMap((o) => o.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 finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt: new Date().toISOString(),\n ...(run.reports !== undefined && run.reports.length > 0 ? { reports: run.reports } : {}),\n ...(combinedReportId !== undefined ? { combinedReportId } : {}),\n };\n await this.options.store.save(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n return finished;\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 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;\n }\n return last!;\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 const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n\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 ?? \"unknown error\";\n return {\n status: \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) failed — ${firstError}`,\n reports,\n };\n }\n return { status: \"completed\", summary, taskIds: created.map((t) => t.id), reports };\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 const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n status: \"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 if (!step.model) {\n // The full planner layer is Phase 8; a plan step without a model passes through.\n return { status: \"completed\", summary: \"(plan: no model configured — skipped)\", taskIds: [], reports: [] };\n }\n const messages: ChatMessage[] = [\n {\n role: \"system\",\n content:\n \"You are a planning assistant inside OmniNode. Given the objective and the combined \" +\n \"research context, produce a prioritized, actionable plan.\",\n },\n {\n role: \"user\",\n content: `# Objective\\n${ctx.objective}\\n\\n${ctx.combinedContext}\\n\\nProduce the final plan.`,\n },\n ];\n try {\n const planText = await this.getChat()(step.model, messages);\n return {\n status: \"completed\",\n summary: planText.split(\"\\n\", 1)[0] ?? planText,\n contextContribution: planText,\n taskIds: [],\n reports: [],\n };\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\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\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 * Pipeline run persistence (§27 Phase 5 — pipeline state). Same\n * replaceable-store pattern as the task store, local-first JSON file.\n */\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements PipelineRunStore {\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/pipelines.json`;\n }\n\n async save(run: PipelineRun): Promise<void> {\n return this.synchronized(async () => {\n const runs = await this.load();\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n await this.write(runs);\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return this.synchronized(async () => {\n const runs = await this.load();\n return runs.find((r) => r.id === id);\n });\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return this.synchronized(async () => {\n const runs = await this.load();\n return runs\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 private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<PipelineRun[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as PipelineRun[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(runs: PipelineRun[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(runs, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 Finding,\n FindingSeverity,\n FindingSource,\n Report,\n} from \"../types/report.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 summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\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 recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\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(...(finding.evidence ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\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 evidence: [...(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 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 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 metadata: evidenceTexts.length > 0 ? { evidence: evidenceTexts } : 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 type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\nexport class ReportService {\n private readonly log: Logger;\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). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const reports: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n reports.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n reports.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements ReportStore {\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/reports.json`;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\n for (const report of reports) {\n const index = entries.findIndex(\n (e) => e.kind === \"report\" && e.report.id === report.id,\n );\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n await this.write(entries);\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n return entries\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\n async saveCombined(combined: CombinedReport): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const index = entries.findIndex(\n (e) => e.kind === \"combined\" && e.combined.id === combined.id,\n );\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n await this.write(entries);\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const found = entries.find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n });\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n return entries\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) =>\n filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true,\n )\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n });\n }\n\n private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<StoreEntry[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as StoreEntry[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(entries: StoreEntry[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(entries, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\n }\n}\n","/** Assembles a PipelineEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/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 { 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 tasks = new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(),\n ...(config.project.memory !== undefined\n ? { memory: new MemoryService(createMemoryProvider(config.project.memory), log) }\n : {}),\n log,\n });\n return new PipelineEngine({\n tasks,\n agents,\n roles,\n providers: config.project.providers,\n store: new FilePipelineRunStore(),\n chat: createDefaultChatFn(config.project.providers),\n reports: new ReportService(new FileReportStore(), log),\n log,\n });\n}\n","export const OMNINODE_VERSION = \"0.8.0\";\n"],"mappings":";AA8BO,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,UAAg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WAAU,KAAK,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,CAAC;AAAA,GAAM,MAAM;AACpE,UAAMD,QAAO,KAAK,KAAK,QAAQ;AAAA,EACjC;AACF;;;AC5GO,SAAS,oBAAoB,QAAmB,MAAc,QAAwB;AAC3F,QAAM,SAAS,mBAAmB,QAAQ,GAAG;AAC7C,QAAM,QAAQ,kBAAkB,MAAM;AACtC,QAAM,QAAQ,IAAI,WAAW;AAAA,IAC3B;AAAA,IACA;AAAA,IACA,OAAO,IAAI,cAAc;AAAA,IACzB,GAAI,OAAO,QAAQ,WAAW,SAC1B,EAAE,QAAQ,IAAI,cAAc,qBAAqB,OAAO,QAAQ,MAAM,GAAG,GAAG,EAAE,IAC9E,CAAC;AAAA,IACL;AAAA,EACF,CAAC;AACD,SAAO,IAAI,eAAe;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,OAAO,QAAQ;AAAA,IAC1B,OAAO,IAAI,qBAAqB;AAAA,IAChC,MAAM,oBAAoB,OAAO,QAAQ,SAAS;AAAA,IAClD,SAAS,IAAI,cAAc,IAAI,gBAAgB,GAAG,GAAG;AAAA,IACrD;AAAA,EACF,CAAC;AACH;;;ACnCO,IAAM,mBAAmB;","names":["DEFAULT_TIMEOUT_MS","trimmed","mkdir","readFile","rename","writeFile","dirname","randomBytes","randomBytes","mkdir","readFile","rename","writeFile","dirname","randomBytes","truncate","mkdir","readFile","rename","writeFile","dirname"]}
1
+ {"version":3,"sources":["../src/errors/index.ts","../src/logger/index.ts","../src/config/schema.ts","../src/config/loader.ts","../src/config/default.ts","../src/providers/auth.ts","../src/providers/http.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/agents/registry.ts","../src/agents/factory.ts","../src/roles/index.ts","../src/tasks/store.ts","../src/tasks/engine.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/planner/heuristic.ts","../src/planner/model.ts","../src/planner/context.ts","../src/pipelines/store.ts","../src/planner/store.ts","../src/planner/factory.ts","../src/reports/aggregate.ts","../src/reports/extract.ts","../src/reports/service.ts","../src/reports/store.ts","../src/pipelines/engine-factory.ts","../src/version.ts"],"sourcesContent":["/** 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 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 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 })\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 })\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 * 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 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 };\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 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 },\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 })),\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 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 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 */\nimport { ProviderError } from \"../errors/index.js\";\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 let response: Response;\n try {\n 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 } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new ProviderError(\"PROVIDER_UNAVAILABLE\", `Request to ${url} failed: ${reason}.`, {\n cause: error,\n });\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch (error) {\n throw new ProviderError(\"PROVIDER_UNAVAILABLE\", `Response from ${url} was not valid JSON.`, {\n cause: error,\n details: { status: response.status },\n });\n }\n\n return { status: response.status, body: parsed };\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\";\nimport type { ChatRequest, ChatResponse } from \"../../types/chat.js\";\nimport type { ModelInfo } from \"../../types/model.js\";\nimport type { IChatProvider, ProviderConfig, ProviderStatus } from \"../../types/provider.js\";\nimport { authHeaders } from \"../auth.js\";\nimport { requestJson } from \"../http.js\";\n\ninterface OpenAIModelEntry {\n id?: unknown;\n owned_by?: unknown;\n created?: 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 private readonly log: Logger;\n\n constructor(config: ProviderConfig, log: Logger = logger) {\n this.config = { ...config, baseUrl: normalizeBaseUrl(config.baseUrl) };\n this.log = log.child({ provider: config.name });\n }\n\n async listModels(): Promise<ModelInfo[]> {\n const { status, body } = await requestJson(`${this.config.baseUrl}/models`, {\n headers: authHeaders(this.config),\n });\n if (status === 401 || status === 403) {\n throw authFailed(this.config, status);\n }\n if (status !== 200) {\n throw unavailable(this.config, `Model discovery returned HTTP ${status}.`, status);\n }\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({\n provider: this.config.name,\n id: entry.id,\n displayName: entry.id,\n status: \"available\",\n metadata: {\n ...(typeof entry.owned_by === \"string\" ? { ownedBy: entry.owned_by } : {}),\n ...(typeof entry.created === \"number\" ? { createdAt: entry.created } : {}),\n },\n });\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 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 const { status, body } = await requestJson(`${this.config.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: authHeaders(this.config),\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\n if (status === 401 || status === 403) throw authFailed(this.config, status);\n if (status === 404) {\n throw new ProviderError(\n \"MODEL_NOT_FOUND\",\n `Model \"${request.model}\" or the chat endpoint was not found on provider \"${this.config.name}\" (HTTP 404).`,\n { details: { status } },\n );\n }\n if (status !== 200) {\n throw unavailable(this.config, `Chat completion returned HTTP ${status}.`, status);\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\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 authFailed(config: ProviderConfig, status: number): ProviderError {\n const envHint = config.apiKeyEnvVar\n ? ` Check that $${config.apiKeyEnvVar} is set and valid.`\n : \" The provider requires authentication; configure api_key_env_var for it.\";\n return new ProviderError(\n \"PROVIDER_AUTH_FAILED\",\n `Authentication with provider \"${config.name}\" failed (HTTP ${status}).${envHint}`,\n { details: { status } },\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 /**\n * Run the full connect flow. Throws on authentication or transport failure\n * (use healthCheck() for a non-throwing probe).\n */\n async connect(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, ProtocolError } from \"../../errors/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 { EnvelopeMeta, NodeToAgentMessage } from \"../../types/protocol.js\";\nimport type { Report } from \"../../types/report.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\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 const meta: EnvelopeMeta = {\n taskId: input.taskId,\n agent: agentName,\n timestamp: new Date().toISOString(),\n };\n const messages: NodeToAgentMessage[] = [\n { type: \"TASK\", payload: { taskId: input.taskId, objective: input.objective } },\n ];\n if (input.role) messages.push({ type: \"ROLE\", payload: input.role });\n if (input.context) messages.push({ type: \"CONTEXT\", payload: { body: input.context } });\n if (input.instruction) messages.push({ type: \"INSTRUCTION\", payload: { text: input.instruction } });\n return messages.map((message) => JSON.stringify({ meta, message }));\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 const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n cwd: this.config.cwd,\n env: { ...process.env, ...this.config.env },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n );\n this.running.set(input.taskId, child);\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process.`);\n child.kill(\"SIGTERM\");\n setTimeout(() => child.kill(\"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 finish();\n };\n\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\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 { details: { taskId: input.taskId, stdout: stdout.slice(0, 4000), stderr: stderr.slice(0, 2000) } },\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 ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n error:\n code === 0\n ? undefined\n : `Process exited with code ${code ?? \"unknown\"}${signal ? ` (signal: ${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) child.kill(\"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}\n\nfunction interpretProtocolRun({ input, agentName, stdout, exitCode, logs }: ProtocolRunInput): AgentTaskOutput {\n const reports: Report[] = [];\n let summary: string | undefined;\n let error: string | undefined;\n let sawProtocolMessage = false;\n\n for (const line of stdout.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n const message = parseAgentMessage(trimmed);\n if (!message) continue;\n sawProtocolMessage = true;\n\n if (message.type === \"REPORT\") {\n const report = normalizeReport(message.payload, input.taskId, agentName, reports.length);\n if (report) reports.push(report);\n } else if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n if (typeof payload?.summary === \"string\") summary = payload.summary;\n } else if (message.type === \"ERROR\") {\n const payload = message.payload as { code?: unknown; message?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"unknown error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n error = `Agent error${code}: ${detail}`;\n }\n // STATUS / QUESTION / ARTIFACT are informational in v0.4 (§21 backlog).\n }\n\n if (!sawProtocolMessage && exitCode === 0) {\n throw new ProtocolError(\n `Agent \"${agentName}\" produced no protocol messages on stdout (input mode \"protocol\").`,\n { details: { taskId: input.taskId, stdout: stdout.slice(0, 2000) } },\n );\n }\n\n const trimmed = stdout.trim();\n return {\n taskId: input.taskId,\n status: error !== undefined || exitCode !== 0 ? \"failed\" : \"completed\",\n summary: summary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n reports: reports.length > 0 ? reports : undefined,\n error:\n error ??\n (exitCode !== 0 ? `Process exited with code ${exitCode ?? \"unknown\"}` : undefined),\n };\n}\n\n/** Accepts both bare `{ type, payload }` and enveloped `{ meta, message }` lines. */\nfunction parseAgentMessage(line: string): { type: string; payload: unknown } | undefined {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n if (typeof parsed.type === \"string\") {\n return { type: parsed.type, payload: parsed.payload };\n }\n const inner = parsed.message as Record<string, unknown> | undefined;\n if (inner && typeof inner.type === \"string\") {\n return { type: inner.type, payload: inner.payload };\n }\n } catch {\n // Non-JSON chatter is tolerated; protocol compliance is judged overall.\n }\n return undefined;\n}\n\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","/** 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\";\n\nexport function createAgent(config: AgentConfig): IAgent {\n if (config.integration === \"process\") {\n return new ProcessAgent(config);\n }\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `Native agent adapters are planned for a later phase. Use input over stdin/stdout (type \"cli\") for \"${config.name}\" for now.`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\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 * 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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements TaskStore {\n private readonly filePath: string;\n /**\n * Read-modify-write operations are serialized: parallel pipeline tasks\n * would otherwise race on the JSON file (last writer wins).\n */\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/tasks.json`;\n }\n\n async save(task: Task): Promise<void> {\n return this.synchronized(async () => {\n const tasks = await this.load();\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n await this.write(tasks);\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.synchronized(async () => {\n const tasks = await this.load();\n return tasks.find((t) => t.id === id);\n });\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n return this.synchronized(async () => {\n const tasks = await this.load();\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 private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<Task[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as Task[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(tasks: Task[]): Promise<void> {\n // Write to a temp file and rename for an atomic-enough local save.\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(tasks, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 { TaskError } from \"../errors/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type { Task, TaskContext, TaskResult, TaskStatus } from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"cancelled\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n failed: [],\n cancelled: [],\n};\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\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 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 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 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 async run(id: string): 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 const running = await this.transition(task, \"running\");\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 = running.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: running.objective,\n ...(running.role ? { role: running.role } : {}),\n ...(running.project ? { project: running.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n let output;\n try {\n output = await agent.run({\n taskId: running.id,\n objective: running.objective,\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.log.error(`Task ${task.id} failed: ${message}`);\n return this.transition(running, \"failed\", {\n result: { error: message, finishedAt: new Date().toISOString() },\n });\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: new Date().toISOString(),\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n const finished = await this.transition(running, finalStatus, { result });\n this.log.info(`Task ${task.id} finished: ${finalStatus}.`);\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(finished);\n }\n return finished;\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 (§27 Phase 9): reset a failed/cancelled task so it can run again. */\n async retry(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n if (task.status !== \"failed\" && task.status !== \"cancelled\") {\n throw new TaskError(\n \"TASK_INVALID\",\n `Only failed 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 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 } = {},\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 updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n return updated;\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { IMemoryProvider, MemoryEntry, MemoryQuery } 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 implements IMemoryProvider {\n readonly name = \"local\";\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/memory.json`;\n }\n\n async query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : 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\n async write(entry: MemoryEntry): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\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 await this.saveAll(entries);\n });\n }\n\n async count(): Promise<number> {\n return (await this.load()).length;\n }\n\n private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<MemoryEntry[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as MemoryEntry[]) : [];\n } catch {\n return [];\n }\n }\n\n private async saveAll(entries: MemoryEntry[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(entries, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 { IMemoryProvider, MemoryEntry, MemoryQuery } from \"../types/memory.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 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 async query(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 write(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.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 (§19–§20): gathers relevant memory before a task runs and\n * records outcomes afterwards — the Task → memory → relevant context →\n * agents → reports → memory loop. Memory failures are best-effort: they log\n * a warning and never fail a task, because memory is an enhancement, not a\n * dependency (§2).\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry, MemoryScope } 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}\n\nconst MAX_CONTEXT_CHARS = 4_000;\n\nexport class MemoryService {\n private readonly log: Logger;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n /** Relevant context for a task objective; empty string when nothing matches. */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n try {\n const entries = await this.provider.query({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: 8,\n });\n if (entries.length === 0) return \"\";\n const byScope = new Map<MemoryScope, 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\"] as MemoryScope[]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries.map((entry) => `- ${entry.content}`).join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n const context = parts.join(\"\\n\\n\");\n return context.length > MAX_CONTEXT_CHARS ? `${context.slice(0, MAX_CONTEXT_CHARS)}…` : context;\n } catch (error) {\n this.log.warn(\n `Memory query failed (continuing without memory): ${error instanceof Error ? error.message : String(error)}`,\n );\n return \"\";\n }\n }\n\n /** Records a finished task's outcome — best-effort. */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.write({\n key: `task:${task.id}`,\n scope: \"task\",\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 // Significant findings become project-level \"known problems\" (§19).\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.write({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.log.warn(\n `Memory write failed (continuing): ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n}\n","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/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 ? { memory: new MemoryService(createMemoryProvider(config.project.memory), log) }\n : {}),\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 PipelineDefinition,\n PipelineRun,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatMessage } from \"../types/chat.js\";\nimport type { Plan } from \"../types/plan.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/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 type ChatFn = (modelRef: string, messages: ChatMessage[]) => Promise<string>;\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, 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\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n planId?: string;\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n role?: RoleDefinition;\n combinedContext: string;\n reports: Report[];\n pipelineRunId?: string;\n}\n\nexport class PipelineEngine {\n private readonly log: Logger;\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 /** 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: RunPipelineOptions = {}): 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 before anything runs.\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 }\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 objective,\n status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n this.log.info(`Running pipeline ${def.id} as ${run.id}.`);\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\n while (pending.size > 0) {\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 };\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 status:\n outcome.status === \"skipped\" ? \"cancelled\" : outcome.status === \"failed\" ? \"failed\" : \"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.options.store.save(run);\n }\n\n const failed = [...outcomes.values()].some((o) => o.status === \"failed\");\n const finalStatus: PipelineRunStatus = failed ? \"failed\" : \"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 finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt: new Date().toISOString(),\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.options.store.save(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n return finished;\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 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;\n }\n return last!;\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 const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n\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 ?? \"unknown error\";\n return {\n status: \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) failed — ${firstError}`,\n reports,\n };\n }\n return { status: \"completed\", summary, taskIds: created.map((t) => t.id), reports };\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 const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n status: \"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 const request = {\n objective: ctx.objective,\n reports: ctx.reports,\n ...(ctx.combinedContext.length > 0 ? { context: ctx.combinedContext } : {}),\n ...(ctx.role ? { role: ctx.role } : {}),\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 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 * HeuristicPlanner: a deterministic, dependency-free planner that derives an\n * implementation plan directly from recommendations and significant findings.\n * Used as the no-model option and as the graceful fallback when a model's\n * output can't be parsed.\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\nexport class HeuristicPlanner implements IPlanner {\n readonly name = \"heuristic\";\n\n async plan(request: PlanRequest): Promise<Plan> {\n const steps: PlanStep[] = [];\n const findings = request.reports.flatMap((report) =>\n report.findings.map((finding) => ({ finding, agent: report.agent })),\n );\n\n // One step per distinct recommendation (deduped by text).\n const recommendations = dedupe(request.reports.flatMap((r) => r.recommendations));\n for (const [index, text] of recommendations.entries()) {\n steps.push({\n id: `step-${steps.length + 1}`,\n title: truncate(text, 120),\n order: steps.length + 1,\n ...(index > 0 ? { dependsOn: [`step-${steps.length}`] } : {}),\n });\n }\n\n // Remediation steps for significant findings, most severe first.\n const significant = findings\n .filter(({ finding }) => (finding.severity ? SEVERITY_RANK[finding.severity] >= SEVERITY_RANK.high : false))\n .sort((a, b) => SEVERITY_RANK[b.finding.severity ?? \"info\"] - SEVERITY_RANK[a.finding.severity ?? \"info\"]);\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\n return {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\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 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 };\n}\n\nfunction dedupe(texts: string[]): string[] {\n return [...new Set(texts.map((t) => t.trim()).filter((t) => t.length > 0))];\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 { z } from \"zod\";\nimport { PlannerError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { ChatMessage } from \"../types/chat.js\";\nimport type { ChatFn } from \"../pipelines/index.js\";\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\nconst planStepJsonSchema = z\n .object({\n id: z.string().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 .strict();\n\nconst planJsonSchema = z\n .object({\n summary: z.string().min(1),\n steps: z.array(planStepJsonSchema).min(1),\n risks: z.array(z.string()).optional(),\n notes: z.array(z.string()).optional(),\n })\n .strict();\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 '{\"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) {\n return this.degrade(request, \"planner model output was not valid plan JSON\");\n }\n\n const plan: Plan = {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n summary: parsed.summary,\n steps: parsed.steps,\n ...(parsed.risks !== undefined ? { risks: parsed.risks } : {}),\n ...(parsed.notes !== undefined ? { notes: parsed.notes } : {}),\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 return plan;\n }\n\n private async degrade(request: PlanRequest, reason: string): 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 throw new PlannerError(\"PLANNER_FAILED\", `Planner failed: ${reason}.`);\n }\n}\n\n/** Extracts and validates the plan JSON from arbitrary model output. */\nexport function parsePlanJson(\n text: string,\n): { summary: string; steps: PlanStep[]; risks?: string[]; notes?: string[] } | undefined {\n const unfenced = text.replace(/```(?:json)?/gi, \"\");\n const start = unfenced.indexOf(\"{\");\n const end = unfenced.lastIndexOf(\"}\");\n if (start < 0 || end <= start) return undefined;\n try {\n const json: unknown = JSON.parse(unfenced.slice(start, end + 1));\n const parsed = planJsonSchema.safeParse(json);\n if (!parsed.success) return undefined;\n\n const steps: PlanStep[] = parsed.data.steps.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 return {\n summary: parsed.data.summary,\n steps: steps.sort((a, b) => a.order - b.order),\n risks: parsed.data.risks,\n notes: parsed.data.notes,\n };\n } catch {\n return undefined;\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Planner context builder (§18): assembles everything the planner needs —\n * the objective, the combined findings from the AI reports (with source\n * attribution), relevant memory and the role definition — into one\n * structured text.\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[] = [`# Objective\\n${request.objective}`];\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 `# Findings (${request.reports.length} report(s) 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 const summaryLines = request.reports.map((report) => `- [${report.agent}] ${report.summary}`);\n parts.push(`# Report summaries\\n${summaryLines.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.context && request.context.length > 0) {\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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements PipelineRunStore {\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/pipelines.json`;\n }\n\n async save(run: PipelineRun): Promise<void> {\n return this.synchronized(async () => {\n const runs = await this.load();\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n await this.write(runs);\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return this.synchronized(async () => {\n const runs = await this.load();\n return runs.find((r) => r.id === id);\n });\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return this.synchronized(async () => {\n const runs = await this.load();\n return runs\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 private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<PipelineRun[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as PipelineRun[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(runs: PipelineRun[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(runs, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\n }\n}\n","/**\n * Plan persistence (§27 Phase 8 — planner result storage). Same\n * replaceable-store pattern as the other local stores.\n */\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements PlanStore {\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/plans.json`;\n }\n\n async save(plan: Plan): Promise<void> {\n return this.synchronized(async () => {\n const plans = await this.load();\n const index = plans.findIndex((p) => p.id === plan.id);\n if (index >= 0) plans[index] = plan;\n else plans.push(plan);\n await this.write(plans);\n });\n }\n\n async get(id: string): Promise<Plan | undefined> {\n return this.synchronized(async () => {\n const plans = await this.load();\n return plans.find((p) => p.id === id);\n });\n }\n\n async list(filter: PlanFilter = {}): Promise<Plan[]> {\n return this.synchronized(async () => {\n const plans = await this.load();\n return plans\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\n private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<Plan[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as Plan[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(plans: Plan[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(plans, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\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 \"../pipelines/index.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 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 Finding,\n FindingSeverity,\n FindingSource,\n Report,\n} from \"../types/report.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 summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\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 recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\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(...(finding.evidence ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\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 evidence: [...(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 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 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 metadata: evidenceTexts.length > 0 ? { evidence: evidenceTexts } : 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 type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\nexport class ReportService {\n private readonly log: Logger;\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). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const reports: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n reports.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n reports.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\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 { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\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 implements ReportStore {\n private readonly filePath: string;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.filePath = `${directory}/reports.json`;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\n for (const report of reports) {\n const index = entries.findIndex(\n (e) => e.kind === \"report\" && e.report.id === report.id,\n );\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n await this.write(entries);\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n return entries\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\n async saveCombined(combined: CombinedReport): Promise<void> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const index = entries.findIndex(\n (e) => e.kind === \"combined\" && e.combined.id === combined.id,\n );\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n await this.write(entries);\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n return this.synchronized(async () => {\n const entries = await this.load();\n const found = entries.find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n });\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return this.synchronized(async () => {\n const entries = await this.load();\n return entries\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) =>\n filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true,\n )\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n });\n }\n\n private synchronized<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n private async load(): Promise<StoreEntry[]> {\n try {\n const raw = await readFile(this.filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as StoreEntry[]) : [];\n } catch {\n return [];\n }\n }\n\n private async write(entries: StoreEntry[]): Promise<void> {\n const tmp = `${this.filePath}.tmp`;\n await mkdir(dirname(this.filePath), { recursive: true });\n await writeFile(tmp, `${JSON.stringify(entries, null, 2)}\\n`, \"utf8\");\n await rename(tmp, this.filePath);\n }\n}\n","import type { AppConfig } from \"../config/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 ? { memory: new MemoryService(createMemoryProvider(config.project.memory), log) }\n : {}),\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 log,\n });\n}\n","export const OMNINODE_VERSION = \"0.10.0\";\n"],"mappings":";AAgCO,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,YAA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ACH;;;ACzCO,IAAM,mBAAmB;","names":["DEFAULT_TIMEOUT_MS","trimmed","mkdir","readFile","rename","writeFile","dirname","randomBytes","randomBytes","randomBytes","z","z","randomBytes","randomBytes","mkdir","readFile","rename","writeFile","dirname","mkdir","readFile","rename","writeFile","dirname","randomBytes","SEVERITY_RANK","truncate","truncate","mkdir","readFile","rename","writeFile","dirname"]}