botinabox 2.9.0 → 2.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +2 -1
  2. package/dist/channels/discord/adapter.d.ts +32 -0
  3. package/dist/channels/discord/inbound.d.ts +25 -0
  4. package/dist/channels/discord/index.d.ts +8 -84
  5. package/dist/channels/discord/models.d.ts +8 -0
  6. package/dist/channels/discord/outbound.d.ts +14 -0
  7. package/dist/channels/slack/adapter.d.ts +33 -0
  8. package/dist/channels/slack/bolt-adapter.d.ts +31 -0
  9. package/dist/channels/slack/enrichers/enrich.d.ts +12 -0
  10. package/dist/channels/slack/enrichers/image-enricher.d.ts +10 -0
  11. package/dist/channels/slack/enrichers/index.d.ts +4 -0
  12. package/dist/channels/slack/enrichers/pdf-enricher.d.ts +8 -0
  13. package/dist/channels/slack/enrichers/types.d.ts +33 -0
  14. package/dist/channels/slack/inbound.d.ts +59 -0
  15. package/dist/channels/slack/index.d.ts +13 -252
  16. package/dist/channels/slack/index.js +6 -2
  17. package/dist/channels/slack/media-type.d.ts +14 -0
  18. package/dist/channels/slack/models.d.ts +9 -0
  19. package/dist/channels/slack/outbound.d.ts +12 -0
  20. package/dist/channels/slack/transcribe.d.ts +41 -0
  21. package/dist/channels/webhook/adapter.d.ts +23 -0
  22. package/dist/channels/webhook/hmac.d.ts +13 -0
  23. package/dist/channels/webhook/index.d.ts +7 -70
  24. package/dist/channels/webhook/models.d.ts +9 -0
  25. package/dist/channels/webhook/server.d.ts +20 -0
  26. package/dist/cli/templates/config.yml.d.ts +7 -0
  27. package/dist/cli/templates/env.d.ts +1 -0
  28. package/dist/cli/templates/index.ts.d.ts +2 -0
  29. package/dist/cli/templates/package.json.d.ts +5 -0
  30. package/dist/cli.d.ts +1 -3
  31. package/dist/connectors/google/calendar-connector.d.ts +40 -0
  32. package/dist/connectors/google/drive-connector.d.ts +43 -0
  33. package/dist/connectors/google/drive-read.d.ts +81 -0
  34. package/dist/connectors/google/gmail-connector.d.ts +42 -0
  35. package/dist/connectors/google/index.d.ts +10 -369
  36. package/dist/connectors/google/oauth.d.ts +48 -0
  37. package/dist/connectors/google/types.d.ts +110 -0
  38. package/dist/core/chat/auto-discovery.d.ts +16 -0
  39. package/dist/core/chat/channel-registry.d.ts +45 -0
  40. package/dist/core/chat/chat-pipeline-v2.d.ts +138 -0
  41. package/dist/core/chat/chat-pipeline.d.ts +116 -0
  42. package/dist/core/chat/chat-responder.d.ts +94 -0
  43. package/dist/core/chat/formatter.d.ts +11 -0
  44. package/dist/core/chat/index.d.ts +26 -0
  45. package/dist/core/chat/message-interpreter.d.ts +91 -0
  46. package/dist/core/chat/message-store.d.ts +71 -0
  47. package/dist/core/chat/notification-queue.d.ts +34 -0
  48. package/dist/core/chat/pipeline.d.ts +38 -0
  49. package/dist/core/chat/policies.d.ts +16 -0
  50. package/dist/core/chat/routing.d.ts +17 -0
  51. package/dist/core/chat/session-key.d.ts +30 -0
  52. package/dist/core/chat/session-manager.d.ts +17 -0
  53. package/dist/core/chat/text-chunker.d.ts +9 -0
  54. package/dist/core/chat/triage-router.d.ts +75 -0
  55. package/dist/core/chat/types.d.ts +5 -0
  56. package/dist/core/config/defaults.d.ts +2 -0
  57. package/dist/core/config/index.d.ts +6 -0
  58. package/dist/core/config/interpolate.d.ts +5 -0
  59. package/dist/core/config/loader.d.ts +24 -0
  60. package/dist/core/config/schema.d.ts +5 -0
  61. package/dist/core/data/context-builder.d.ts +27 -0
  62. package/dist/core/data/core-entity-contexts.d.ts +14 -0
  63. package/dist/core/data/core-migrations.d.ts +5 -0
  64. package/dist/core/data/core-schema.d.ts +6 -0
  65. package/dist/core/data/data-store.d.ts +67 -0
  66. package/dist/core/data/domain-entity-contexts.d.ts +35 -0
  67. package/dist/core/data/domain-schema.d.ts +36 -0
  68. package/dist/core/data/index.d.ts +8 -0
  69. package/dist/core/data/types.d.ts +111 -0
  70. package/dist/core/hooks/hook-bus.d.ts +24 -0
  71. package/dist/core/hooks/index.d.ts +2 -0
  72. package/dist/core/hooks/types.d.ts +19 -0
  73. package/dist/core/index.d.ts +4 -0
  74. package/dist/core/llm/auto-discovery.d.ts +11 -0
  75. package/dist/core/llm/cost-tracker.d.ts +6 -0
  76. package/dist/core/llm/default-llm-call.d.ts +35 -0
  77. package/dist/core/llm/index.d.ts +6 -0
  78. package/dist/core/llm/model-router.d.ts +25 -0
  79. package/dist/core/llm/provider-registry.d.ts +9 -0
  80. package/dist/core/llm/types.d.ts +2 -0
  81. package/dist/core/orchestrator/adapters/api-adapter.d.ts +34 -0
  82. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +62 -0
  83. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +35 -0
  84. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +4 -0
  85. package/dist/core/orchestrator/adapters/output-extractor.d.ts +11 -0
  86. package/dist/core/orchestrator/adapters/process-manager.d.ts +15 -0
  87. package/dist/core/orchestrator/adapters/tool-loop.d.ts +22 -0
  88. package/dist/core/orchestrator/agent-registry.d.ts +31 -0
  89. package/dist/core/orchestrator/budget-controller.d.ts +19 -0
  90. package/dist/core/orchestrator/chain-guard.d.ts +14 -0
  91. package/dist/core/orchestrator/circuit-breaker.d.ts +65 -0
  92. package/dist/core/orchestrator/claude-stream-parser.d.ts +31 -0
  93. package/dist/core/orchestrator/config-revisions.d.ts +6 -0
  94. package/dist/core/orchestrator/dependency-resolver.d.ts +20 -0
  95. package/dist/core/orchestrator/execution-engine.d.ts +99 -0
  96. package/dist/core/orchestrator/governance-gate.d.ts +110 -0
  97. package/dist/core/orchestrator/learning-pipeline.d.ts +112 -0
  98. package/dist/core/orchestrator/loop-detector.d.ts +51 -0
  99. package/dist/core/orchestrator/ndjson-logger.d.ts +6 -0
  100. package/dist/core/orchestrator/permission-relay.d.ts +72 -0
  101. package/dist/core/orchestrator/run-manager.d.ts +31 -0
  102. package/dist/core/orchestrator/scheduler.d.ts +74 -0
  103. package/dist/core/orchestrator/secret-store.d.ts +57 -0
  104. package/dist/core/orchestrator/session-manager.d.ts +13 -0
  105. package/dist/core/orchestrator/task-queue.d.ts +34 -0
  106. package/dist/core/orchestrator/template-interpolate.d.ts +5 -0
  107. package/dist/core/orchestrator/tools/file-ops.d.ts +12 -0
  108. package/dist/core/orchestrator/tools/index.d.ts +47 -0
  109. package/dist/core/orchestrator/tools/management.d.ts +12 -0
  110. package/dist/core/orchestrator/tools/messaging.d.ts +21 -0
  111. package/dist/core/orchestrator/tools/read-file.d.ts +5 -0
  112. package/dist/core/orchestrator/tools/resolve-agent.d.ts +9 -0
  113. package/dist/core/orchestrator/tools/roster.d.ts +16 -0
  114. package/dist/core/orchestrator/tools/send-file.d.ts +5 -0
  115. package/dist/core/orchestrator/tools/status.d.ts +20 -0
  116. package/dist/core/orchestrator/tools/task-ops.d.ts +13 -0
  117. package/dist/core/orchestrator/user-registry.d.ts +47 -0
  118. package/dist/core/orchestrator/wakeup-queue.d.ts +9 -0
  119. package/dist/core/orchestrator/workflow-engine.d.ts +47 -0
  120. package/dist/core/security/audit.d.ts +20 -0
  121. package/dist/core/security/column-validator.d.ts +20 -0
  122. package/dist/core/security/index.d.ts +5 -0
  123. package/dist/core/security/process-env.d.ts +13 -0
  124. package/dist/core/security/sanitizer.d.ts +11 -0
  125. package/dist/core/security/types.d.ts +11 -0
  126. package/dist/core/update/auto-update.d.ts +21 -0
  127. package/dist/core/update/backup-manager.d.ts +7 -0
  128. package/dist/core/update/index.d.ts +8 -0
  129. package/dist/core/update/migration-hooks.d.ts +11 -0
  130. package/dist/core/update/types.d.ts +11 -0
  131. package/dist/core/update/update-checker.d.ts +11 -0
  132. package/dist/core/update/update-manager.d.ts +25 -0
  133. package/dist/core/update/version-utils.d.ts +6 -0
  134. package/dist/index.d.ts +38 -2366
  135. package/dist/index.js +112 -5
  136. package/dist/providers/anthropic/index.d.ts +5 -20
  137. package/dist/providers/anthropic/models.d.ts +2 -0
  138. package/dist/providers/anthropic/provider.d.ts +13 -0
  139. package/dist/providers/anthropic/tool-converter.d.ts +10 -0
  140. package/dist/providers/ollama/index.d.ts +4 -22
  141. package/dist/providers/ollama/provider.d.ts +17 -0
  142. package/dist/providers/openai/index.d.ts +5 -20
  143. package/dist/providers/openai/models.d.ts +2 -0
  144. package/dist/providers/openai/provider.d.ts +13 -0
  145. package/dist/providers/openai/tool-converter.d.ts +10 -0
  146. package/dist/shared/constants.d.ts +50 -0
  147. package/dist/shared/index.d.ts +14 -0
  148. package/dist/shared/types/agent.d.ts +36 -0
  149. package/dist/shared/types/channel.d.ts +78 -0
  150. package/dist/shared/types/config.d.ts +160 -0
  151. package/dist/shared/types/connector.d.ts +77 -0
  152. package/dist/shared/types/execution.d.ts +29 -0
  153. package/dist/shared/types/provider.d.ts +87 -0
  154. package/dist/shared/types/task.d.ts +47 -0
  155. package/dist/shared/types/workflow.d.ts +39 -0
  156. package/dist/shared/utils.d.ts +6 -0
  157. package/dist/update-check.d.ts +5 -0
  158. package/package.json +2 -2
@@ -0,0 +1,9 @@
1
+ import type { LLMProvider, ModelInfo } from "./types.js";
2
+ export declare class ProviderRegistry {
3
+ private providers;
4
+ register(provider: LLMProvider): void;
5
+ unregister(id: string): void;
6
+ get(id: string): LLMProvider | undefined;
7
+ list(): LLMProvider[];
8
+ listModels(): ModelInfo[];
9
+ }
@@ -0,0 +1,2 @@
1
+ /** LLM module types — re-exports from @botinabox/shared */
2
+ export type { LLMProvider, ModelInfo, ResolvedModel, ChatParams, ChatResult, ChatMessage, ContentBlock, TokenUsage, ToolDefinition, ToolUse, } from "../../shared/index.js";
@@ -0,0 +1,34 @@
1
+ import type { ModelRouter } from '../../llm/model-router.js';
2
+ import type { ChatMessage, TokenUsage } from "../../../shared/index.js";
3
+ export declare class ApiExecutionAdapter {
4
+ private modelRouter;
5
+ readonly type = "api";
6
+ constructor(modelRouter: ModelRouter);
7
+ execute(ctx: {
8
+ agent: {
9
+ id: string;
10
+ model?: string;
11
+ adapter_config?: string;
12
+ };
13
+ task: {
14
+ description?: string;
15
+ context?: string;
16
+ };
17
+ sessionParams?: {
18
+ history?: ChatMessage[];
19
+ };
20
+ contextFiles?: string[];
21
+ abortSignal?: AbortSignal;
22
+ onLog?: (stream: 'stdout' | 'stderr', chunk: string) => void;
23
+ }): Promise<{
24
+ output: string;
25
+ exitCode: number;
26
+ usage: TokenUsage & {
27
+ provider: string;
28
+ model: string;
29
+ };
30
+ sessionParams: {
31
+ history: ChatMessage[];
32
+ };
33
+ }>;
34
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Inputs to the CLI argument builder. Kept as a separate type so the
3
+ * pure arg-construction function is unit-testable without spawning a process.
4
+ */
5
+ export interface CliArgBuildInput {
6
+ prompt: string;
7
+ skipPermissions?: boolean;
8
+ sessionId?: string;
9
+ settings?: string;
10
+ appendSystemPrompt?: string;
11
+ addDirs?: string[];
12
+ extraArgs?: string[];
13
+ }
14
+ /**
15
+ * Build the argv array passed to the `claude` binary.
16
+ *
17
+ * Order matters for the `claude` CLI: flags come first, then `--print` with
18
+ * the prompt as the final positional argument. This function exists so the
19
+ * argv shape can be asserted in tests without a real subprocess.
20
+ */
21
+ export declare function buildCliArgs(input: CliArgBuildInput): string[];
22
+ export declare class CliExecutionAdapter {
23
+ readonly type = "cli";
24
+ execute(ctx: {
25
+ agent: {
26
+ id: string;
27
+ cwd?: string;
28
+ adapter_config?: string;
29
+ skip_permissions?: boolean;
30
+ };
31
+ task: {
32
+ title: string;
33
+ description?: string;
34
+ context?: string;
35
+ };
36
+ /**
37
+ * Optional Claude Code session UUID. When provided, passed as `--session-id`
38
+ * so the same UUID on subsequent calls resumes the same conversation.
39
+ * Callers typically derive this deterministically from a stable conversation
40
+ * key (e.g. thread identifier) so multi-turn exchanges maintain history.
41
+ */
42
+ sessionId?: string;
43
+ /**
44
+ * Value for `--settings`. Accepts a JSON string or a path to a settings
45
+ * file. Use this to override settings like `autoMemoryDirectory` without
46
+ * mutating the caller's global config.
47
+ */
48
+ settings?: string;
49
+ /** Value for `--append-system-prompt`. */
50
+ appendSystemPrompt?: string;
51
+ /** Additional directories passed via `--add-dir`. */
52
+ addDirs?: string[];
53
+ /** Extra CLI flags appended before the positional prompt. */
54
+ extraArgs?: string[];
55
+ logPath?: string;
56
+ onLog?: (stream: string, chunk: string) => void;
57
+ abortSignal?: AbortSignal;
58
+ }): Promise<{
59
+ output: string;
60
+ exitCode: number;
61
+ }>;
62
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * DeterministicAdapter — executes scripts without LLM calls.
3
+ * Story 6.1
4
+ *
5
+ * For tasks that don't require reasoning: routing, validation,
6
+ * data fetching, file transforms. Runs a user-specified command
7
+ * (Python, Node, bash) as a subprocess with task context on stdin.
8
+ */
9
+ export interface DeterministicConfig {
10
+ command: string;
11
+ args?: string[];
12
+ env?: Record<string, string>;
13
+ timeoutMs?: number;
14
+ inputMode?: 'stdin' | 'arg';
15
+ }
16
+ export declare class DeterministicAdapter {
17
+ readonly type = "deterministic";
18
+ execute(ctx: {
19
+ agent: {
20
+ id: string;
21
+ cwd?: string;
22
+ adapter_config?: string;
23
+ };
24
+ task: {
25
+ title: string;
26
+ description?: string;
27
+ context?: string;
28
+ };
29
+ abortSignal?: AbortSignal;
30
+ onLog?: (stream: string, chunk: string) => void;
31
+ }): Promise<{
32
+ output: string;
33
+ exitCode: number;
34
+ }>;
35
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Filter the process environment to only allowed keys, then merge in extras.
3
+ */
4
+ export declare function filterEnv(allowed?: string[], extra?: Record<string, string>): Record<string, string>;
@@ -0,0 +1,11 @@
1
+ export declare const MAX_OUTPUT_BYTES: number;
2
+ /**
3
+ * Extract final output from NDJSON log content.
4
+ * Finds last line with {type:'result'} or {role:'assistant'}.
5
+ * Caps at 4MB.
6
+ */
7
+ export declare function extractOutput(ndjsonContent: string): string;
8
+ /**
9
+ * Read file and extract output.
10
+ */
11
+ export declare function extractOutputFromFile(logPath: string): string;
@@ -0,0 +1,15 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ export interface SpawnOpts {
3
+ cwd: string;
4
+ allowedEnvVars?: string[];
5
+ extraEnv?: Record<string, string>;
6
+ timeoutMs?: number;
7
+ }
8
+ /**
9
+ * Spawn a process with its own PGID (detached=true) and piped stdio.
10
+ */
11
+ export declare function spawnProcess(command: string, args: string[], opts: SpawnOpts): ChildProcess;
12
+ /**
13
+ * Kill an entire process group by negative PID.
14
+ */
15
+ export declare function killProcessGroup(pid: number, signal?: NodeJS.Signals): void;
@@ -0,0 +1,22 @@
1
+ import type { ChatMessage, ChatParams, ChatResult, ToolDefinition } from "../../../shared/index.js";
2
+ export interface ToolExecutor {
3
+ (toolName: string, toolInput: unknown): Promise<string>;
4
+ }
5
+ export declare function toolLoop(params: {
6
+ model: string;
7
+ messages: ChatMessage[];
8
+ systemPrompt?: string;
9
+ tools?: ToolDefinition[];
10
+ maxIterations?: number;
11
+ signal?: AbortSignal;
12
+ }, callLLM: (params: ChatParams) => Promise<ChatResult>, executeTool?: ToolExecutor): AsyncGenerator<{
13
+ type: 'text';
14
+ content: string;
15
+ } | {
16
+ type: 'tool_use';
17
+ name: string;
18
+ input: unknown;
19
+ } | {
20
+ type: 'done';
21
+ result: ChatResult;
22
+ }>;
@@ -0,0 +1,31 @@
1
+ import type { DataStore } from '../data/data-store.js';
2
+ import type { HookBus } from '../hooks/hook-bus.js';
3
+ export declare class AgentRegistry {
4
+ private db;
5
+ private hooks;
6
+ constructor(db: DataStore, hooks: HookBus);
7
+ register(agent: {
8
+ slug: string;
9
+ name: string;
10
+ adapter: string;
11
+ role?: string;
12
+ [key: string]: unknown;
13
+ }, opts?: {
14
+ actorAgentId?: string;
15
+ }): Promise<string>;
16
+ getById(id: string): Promise<Record<string, unknown> | undefined>;
17
+ getBySlug(slug: string): Promise<Record<string, unknown> | undefined>;
18
+ list(filter?: {
19
+ status?: string;
20
+ role?: string;
21
+ }): Promise<Record<string, unknown>[]>;
22
+ update(id: string, changes: Record<string, unknown>): Promise<void>;
23
+ setStatus(id: string, newStatus: string): Promise<void>;
24
+ terminate(id: string): Promise<void>;
25
+ seedFromConfig(agentConfigs: Array<{
26
+ slug: string;
27
+ name: string;
28
+ adapter: string;
29
+ [key: string]: unknown;
30
+ }>): Promise<void>;
31
+ }
@@ -0,0 +1,19 @@
1
+ import type { DataStore } from '../data/data-store.js';
2
+ import type { HookBus } from '../hooks/hook-bus.js';
3
+ export declare class BudgetController {
4
+ private db;
5
+ private hooks;
6
+ constructor(db: DataStore, hooks: HookBus);
7
+ checkBudget(agentId: string): Promise<{
8
+ allowed: boolean;
9
+ reason?: string;
10
+ currentSpendCents: number;
11
+ limitCents: number;
12
+ }>;
13
+ resetMonthlySpend(agentId: string): Promise<void>;
14
+ globalCheck(): Promise<{
15
+ allowed: boolean;
16
+ totalSpentCents: number;
17
+ limitCents: number;
18
+ }>;
19
+ }
@@ -0,0 +1,14 @@
1
+ export declare const MAX_CHAIN_DEPTH = 5;
2
+ /**
3
+ * Throws if depth exceeds the maximum allowed chain depth.
4
+ */
5
+ export declare function checkChainDepth(depth: number, max?: number): void;
6
+ /**
7
+ * Build chain origin metadata for a new child task.
8
+ * If parentTaskId is provided, sets chain_origin_id and increments depth.
9
+ * Otherwise returns depth=0 with no origin.
10
+ */
11
+ export declare function buildChainOrigin(parentTaskId?: string, parentOriginId?: string, parentDepth?: number): {
12
+ chain_origin_id?: string;
13
+ chain_depth: number;
14
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * CircuitBreaker — prevents runaway agent failures with automatic escalation.
3
+ * Story 6.2
4
+ *
5
+ * States:
6
+ * CLOSED → normal operation, failures counted
7
+ * OPEN → tripped, all executions blocked, escalated to human
8
+ * HALF_OPEN → probe mode, one execution allowed to test recovery
9
+ *
10
+ * Integrates with LoopDetector and RunManager via HookBus events.
11
+ */
12
+ import type { DataStore } from '../data/data-store.js';
13
+ import type { HookBus } from '../hooks/hook-bus.js';
14
+ export declare enum BreakerState {
15
+ CLOSED = "closed",
16
+ OPEN = "open",
17
+ HALF_OPEN = "half_open"
18
+ }
19
+ export interface CircuitBreakerConfig {
20
+ /** Failures before tripping. Default: 3 */
21
+ failureThreshold?: number;
22
+ /** Milliseconds to wait before half-open probe. Default: 300_000 (5 min) */
23
+ resetTimeoutMs?: number;
24
+ /** Log events to the database. Default: true */
25
+ persist?: boolean;
26
+ }
27
+ export declare class CircuitBreaker {
28
+ private db;
29
+ private hooks;
30
+ private readonly breakers;
31
+ private readonly failureThreshold;
32
+ private readonly resetTimeoutMs;
33
+ private readonly persist;
34
+ constructor(db: DataStore, hooks: HookBus, config?: CircuitBreakerConfig);
35
+ /**
36
+ * Check if an agent is allowed to execute.
37
+ * Returns true if execution is allowed, false if circuit is open.
38
+ */
39
+ canExecute(agentId: string): boolean;
40
+ /**
41
+ * Record a successful execution. Resets the breaker to CLOSED.
42
+ */
43
+ recordSuccess(agentId: string): Promise<void>;
44
+ /**
45
+ * Record a failed execution. Increments failure count and may trip breaker.
46
+ */
47
+ recordFailure(agentId: string, reason?: string): Promise<void>;
48
+ /**
49
+ * Trip the breaker to OPEN state and escalate to human.
50
+ */
51
+ trip(agentId: string, reason: string): Promise<void>;
52
+ /**
53
+ * Manually reset a breaker (e.g. after human review).
54
+ */
55
+ reset(agentId: string): Promise<void>;
56
+ /**
57
+ * Get the current state of a breaker.
58
+ */
59
+ getState(agentId: string): BreakerState;
60
+ /**
61
+ * Get failure count for an agent.
62
+ */
63
+ getFailureCount(agentId: string): number;
64
+ private logEvent;
65
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Parse Claude CLI NDJSON (stream-json) output into structured results.
3
+ * Used by the CLI execution adapter to extract session info, costs,
4
+ * token usage, and text output from Claude CLI subprocess output.
5
+ */
6
+ export interface ParsedStream {
7
+ sessionId: string | null;
8
+ model: string | null;
9
+ costUsd: number | null;
10
+ usage: UsageSummary | null;
11
+ summary: string;
12
+ isError: boolean;
13
+ errorMessage: string | null;
14
+ stopReason: string | null;
15
+ }
16
+ export interface UsageSummary {
17
+ inputTokens: number;
18
+ cachedInputTokens: number;
19
+ outputTokens: number;
20
+ }
21
+ /**
22
+ * Parse Claude CLI NDJSON output into a structured result.
23
+ * Handles init, assistant, and result event types.
24
+ */
25
+ export declare function parseClaudeStream(stdout: string): ParsedStream;
26
+ /** Check if the run stopped due to max turns. */
27
+ export declare function isMaxTurns(parsed: ParsedStream): boolean;
28
+ /** Check if Claude CLI requires login. */
29
+ export declare function isLoginRequired(stdout: string): boolean;
30
+ /** Rewrite local image paths to prevent CLI auto-embedding as vision content. */
31
+ export declare function deactivateLocalImagePaths(prompt: string): string;
@@ -0,0 +1,6 @@
1
+ import type { DataStore } from '../data/data-store.js';
2
+ /**
3
+ * Creates a config revision record with before/after snapshots.
4
+ * Note: uses config_revisions table with config_yaml storing JSON of {agentId, before, after}.
5
+ */
6
+ export declare function createConfigRevision(db: DataStore, agentId: string, before: Record<string, unknown>, after: Record<string, unknown>): Promise<void>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Dependency resolution utilities for workflow steps and task deps.
3
+ */
4
+ export interface StepRef {
5
+ id: string;
6
+ dependsOn?: string[];
7
+ }
8
+ /**
9
+ * DFS cycle detection — returns true if cycle exists.
10
+ */
11
+ export declare function detectCycle(steps: StepRef[]): boolean;
12
+ /**
13
+ * Returns step IDs in topological (execution) order.
14
+ * Throws if a cycle is detected.
15
+ */
16
+ export declare function topologicalSort(steps: StepRef[]): string[];
17
+ /**
18
+ * Returns true if all dependencies are satisfied (present in completedTaskIds).
19
+ */
20
+ export declare function areDependenciesMet(taskDepsJson: string | undefined, completedTaskIds: Set<string>): boolean;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * ExecutionEngine — generic task executor with pluggable tools and tool loop.
3
+ *
4
+ * Listens for task.created events, picks up tasks, runs them through an LLM
5
+ * with tools, and finishes the run with the result.
6
+ *
7
+ * Apps configure: model, tools, system prompt, max iterations.
8
+ * Framework handles: task pickup, locking, tool loop, cost tracking, result storage.
9
+ */
10
+ import type { DataStore } from '../data/data-store.js';
11
+ import type { HookBus } from '../hooks/hook-bus.js';
12
+ import type { RunManager } from './run-manager.js';
13
+ export interface ToolDefinition {
14
+ name: string;
15
+ description: string;
16
+ input_schema: Record<string, unknown>;
17
+ }
18
+ export type ToolHandler = (input: Record<string, unknown>, context: ToolContext) => Promise<string>;
19
+ export interface ToolContext {
20
+ taskId: string;
21
+ agentId: string;
22
+ hooks: HookBus;
23
+ db: DataStore;
24
+ /** Resolve a relative file path to an absolute path (environment-aware). */
25
+ resolveFilePath?: (path: string) => string;
26
+ }
27
+ export interface ContextFile {
28
+ /** Absolute path, used as the `path` attribute in the wrapped XML tag. */
29
+ path: string;
30
+ /** Raw file contents (UTF-8). The engine does not read the filesystem itself. */
31
+ content: string;
32
+ }
33
+ export interface ExecutionEngineConfig {
34
+ /** Anthropic client instance */
35
+ client: {
36
+ messages: {
37
+ create: (params: Record<string, unknown>) => Promise<{
38
+ content: Array<{
39
+ type: string;
40
+ text?: string;
41
+ id?: string;
42
+ name?: string;
43
+ input?: unknown;
44
+ }>;
45
+ stop_reason: string;
46
+ usage: {
47
+ input_tokens: number;
48
+ output_tokens: number;
49
+ };
50
+ }>;
51
+ };
52
+ };
53
+ /** Model to use. Default: claude-sonnet-4-20250514 */
54
+ model?: string;
55
+ /** Max tool loop iterations. Default: 5 */
56
+ maxIterations?: number;
57
+ /** Tools available to the agent */
58
+ tools?: Array<{
59
+ definition: ToolDefinition;
60
+ handler: ToolHandler;
61
+ }>;
62
+ /** Additional system prompt text (appended after system context) */
63
+ systemPromptSuffix?: string;
64
+ /** Include system context (users, files, etc). Default: true */
65
+ includeSystemContext?: boolean;
66
+ /** Resolve file paths from DB-relative to absolute (for cross-environment support). */
67
+ resolveFilePath?: (path: string) => string;
68
+ /**
69
+ * Optional per-dispatch context resolver. Called once per task pickup with
70
+ * the resolved agent and task rows. Returned files are wrapped in
71
+ * `<file path="...">...</file>` XML tags and inserted into the system
72
+ * prompt between the static `buildSystemContext` block and the tool
73
+ * listing. Intended for apps that want to inject per-agent or per-project
74
+ * rendered context (rules, playbooks, agent definitions) that is not
75
+ * already covered by `buildSystemContext`.
76
+ *
77
+ * The resolver owns all filesystem / database lookups — the engine does
78
+ * not touch the disk. If the resolver throws, the task fails loudly per
79
+ * Rule-16-style fail-loud semantics; there is no silent fallback.
80
+ */
81
+ resolveContextFiles?: (ctx: {
82
+ agent: Record<string, unknown>;
83
+ task: Record<string, unknown>;
84
+ }) => Promise<ContextFile[]> | ContextFile[];
85
+ }
86
+ /**
87
+ * Wrap a set of context files in `<file path="...">...</file>` XML tags,
88
+ * joined by blank lines. Returns an empty string if the input is empty so
89
+ * callers can safely concatenate the result into a larger prompt without
90
+ * needing a conditional. Pure function — no I/O — so it can be unit-tested
91
+ * without touching the filesystem or a model.
92
+ */
93
+ export declare function formatContextFilesBlock(files: ContextFile[]): string;
94
+ export declare function registerExecutionEngine(opts: {
95
+ db: DataStore;
96
+ hooks: HookBus;
97
+ runs: RunManager;
98
+ config: ExecutionEngineConfig;
99
+ }): Promise<void>;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * GovernanceGate — independent validation gates for agent output.
3
+ * Story 6.7
4
+ *
5
+ * Key principle: gates report to the HUMAN, not to each other
6
+ * or to a project manager agent. Structural independence prevents capture.
7
+ *
8
+ * Gate dimensions:
9
+ * QA — data correctness (schema, row counts, format)
10
+ * Quality — code quality (lint, coverage, patterns)
11
+ * Drift — architectural drift (unintended dependencies, scope creep)
12
+ */
13
+ import type { HookBus } from '../hooks/hook-bus.js';
14
+ export type GateVerdict = 'pass' | 'fail' | 'warn';
15
+ export interface GateResult {
16
+ gateId: string;
17
+ verdict: GateVerdict;
18
+ findings: GateFinding[];
19
+ checkedAt: string;
20
+ durationMs: number;
21
+ }
22
+ export interface GateFinding {
23
+ severity: 'info' | 'warning' | 'error' | 'critical';
24
+ message: string;
25
+ location?: string;
26
+ suggestion?: string;
27
+ }
28
+ export interface GateInput {
29
+ agentId: string;
30
+ taskId: string;
31
+ output: string;
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+ /**
35
+ * Base class for governance gates. Each gate checks a different dimension.
36
+ * Gates are structurally independent — they report to the human operator,
37
+ * not to each other or to any agent.
38
+ */
39
+ export declare abstract class GovernanceGate {
40
+ abstract readonly id: string;
41
+ abstract readonly name: string;
42
+ abstract readonly dimension: string;
43
+ /**
44
+ * Run the gate check on agent output.
45
+ * Must return a verdict and any findings.
46
+ */
47
+ abstract check(input: GateInput): Promise<GateResult>;
48
+ }
49
+ /**
50
+ * QA Gate — validates data correctness.
51
+ * Checks: schema conformance, row counts, format validation.
52
+ */
53
+ export declare class QAGate extends GovernanceGate {
54
+ private validators;
55
+ readonly id = "qa";
56
+ readonly name = "Quality Assurance";
57
+ readonly dimension = "data_correctness";
58
+ constructor(validators?: Array<{
59
+ name: string;
60
+ validate: (output: string, metadata?: Record<string, unknown>) => GateFinding[];
61
+ }>);
62
+ check(input: GateInput): Promise<GateResult>;
63
+ }
64
+ /**
65
+ * Quality Gate — validates code quality.
66
+ * Checks: lint results, test coverage, review patterns.
67
+ */
68
+ export declare class QualityGate extends GovernanceGate {
69
+ private checks;
70
+ readonly id = "quality";
71
+ readonly name = "Code Quality";
72
+ readonly dimension = "code_quality";
73
+ constructor(checks?: Array<{
74
+ name: string;
75
+ check: (output: string, metadata?: Record<string, unknown>) => Promise<GateFinding[]>;
76
+ }>);
77
+ check(input: GateInput): Promise<GateResult>;
78
+ }
79
+ /**
80
+ * Drift Gate — detects architectural drift.
81
+ * Checks: unintended dependencies, scope creep, pattern violations.
82
+ */
83
+ export declare class DriftGate extends GovernanceGate {
84
+ private rules;
85
+ readonly id = "drift";
86
+ readonly name = "Architectural Drift";
87
+ readonly dimension = "architecture";
88
+ constructor(rules?: Array<{
89
+ name: string;
90
+ detect: (output: string, metadata?: Record<string, unknown>) => GateFinding[];
91
+ }>);
92
+ check(input: GateInput): Promise<GateResult>;
93
+ }
94
+ /**
95
+ * GateRunner — orchestrates multiple independent gates on agent output.
96
+ * Each gate runs independently. Results are reported to the human, not to agents.
97
+ */
98
+ export declare class GateRunner {
99
+ private gates;
100
+ private hooks;
101
+ constructor(gates: GovernanceGate[], hooks: HookBus);
102
+ /**
103
+ * Run all gates on the given input.
104
+ * Gates run independently — one failure doesn't block others.
105
+ */
106
+ runAll(input: GateInput): Promise<{
107
+ passed: boolean;
108
+ results: GateResult[];
109
+ }>;
110
+ }