@wrongstack/core 0.63.4 → 0.68.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.
Files changed (57) hide show
  1. package/dist/{agent-bridge-B5rxWrg3.d.ts → agent-bridge-D-j6OOBT.d.ts} +1 -1
  2. package/dist/agent-subagent-runner-DRZ9-NnR.d.ts +1042 -0
  3. package/dist/{compactor-0vjZ8KTk.d.ts → compactor-D_ExJajC.d.ts} +1 -1
  4. package/dist/{config-BdDuaZmB.d.ts → config--86aHSln.d.ts} +1 -1
  5. package/dist/{context-iFMEO2rN.d.ts → context-y87Jc5ei.d.ts} +3 -3
  6. package/dist/coordination/index.d.ts +12 -12
  7. package/dist/coordination/index.js +265 -275
  8. package/dist/coordination/index.js.map +1 -1
  9. package/dist/defaults/index.d.ts +22 -22
  10. package/dist/defaults/index.js +181 -180
  11. package/dist/defaults/index.js.map +1 -1
  12. package/dist/{events-k8CHjcrN.d.ts → events-CIplI98R.d.ts} +1 -1
  13. package/dist/execution/index.d.ts +16 -385
  14. package/dist/execution/index.js +124 -146
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/goal-store-C7jcumEh.d.ts +96 -0
  18. package/dist/{index-Bc6BiP5q.d.ts → index-DKUvyTvV.d.ts} +28 -442
  19. package/dist/{index-CWdW_CJt.d.ts → index-b5uhfTSl.d.ts} +8 -8
  20. package/dist/index.d.ts +34 -32
  21. package/dist/index.js +692 -750
  22. package/dist/index.js.map +1 -1
  23. package/dist/infrastructure/index.d.ts +6 -6
  24. package/dist/kernel/index.d.ts +9 -9
  25. package/dist/{mcp-servers-CwqQDMYy.d.ts → mcp-servers-DwoNBf6r.d.ts} +3 -3
  26. package/dist/models/index.d.ts +2 -2
  27. package/dist/{multi-agent-coordinator-CNUJYq7U.d.ts → multi-agent-coordinator-CWnH-CiX.d.ts} +10 -2
  28. package/dist/{null-fleet-bus-DRoJ0uOY.d.ts → null-fleet-bus-CuN0ObJr.d.ts} +24 -31
  29. package/dist/observability/index.d.ts +2 -2
  30. package/dist/parallel-eternal-engine-0UwotoSx.d.ts +483 -0
  31. package/dist/{path-resolver-C5sPVne8.d.ts → path-resolver-DVkEcIw8.d.ts} +2 -2
  32. package/dist/{permission-Ld-i5ugf.d.ts → permission-C1A5whY5.d.ts} +5 -1
  33. package/dist/{permission-policy-CL-mPufp.d.ts → permission-policy-B2dK-T5N.d.ts} +19 -5
  34. package/dist/{plan-templates-ThBHOjaM.d.ts → plan-templates-Bprrzhbu.d.ts} +4 -4
  35. package/dist/{provider-runner-DJQa211J.d.ts → provider-runner-mXvXGSIw.d.ts} +3 -3
  36. package/dist/{retry-policy-BfBScewS.d.ts → retry-policy-CG3qvH_e.d.ts} +1 -1
  37. package/dist/sdd/index.d.ts +8 -8
  38. package/dist/sdd/index.js +123 -146
  39. package/dist/sdd/index.js.map +1 -1
  40. package/dist/security/index.d.ts +3 -3
  41. package/dist/security/index.js +31 -22
  42. package/dist/security/index.js.map +1 -1
  43. package/dist/{selector-DxhW7ML3.d.ts → selector-RvBR_YRW.d.ts} +1 -1
  44. package/dist/session-event-bridge-CDHxcmQU.d.ts +93 -0
  45. package/dist/{session-reader-q2ThszgG.d.ts → session-reader-BIpwM60D.d.ts} +1 -1
  46. package/dist/storage/index.d.ts +7 -6
  47. package/dist/{system-prompt-7LHyBbIf.d.ts → system-prompt-b61lOd49.d.ts} +2 -2
  48. package/dist/types/index.d.ts +23 -14
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/index.d.ts +2 -2
  51. package/dist/utils/index.js.map +1 -1
  52. package/package.json +1 -1
  53. package/skills/multi-agent/SKILL.md +0 -2
  54. package/dist/agent-subagent-runner-Zc3f37Sg.d.ts +0 -182
  55. package/dist/goal-store-iHltMi5n.d.ts +0 -188
  56. package/dist/multi-agent-SASYOrWA.d.ts +0 -554
  57. package/dist/tool-executor-CIjpGaRA.d.ts +0 -111
@@ -1,10 +1,10 @@
1
1
  export { D as DefaultLogger, a as DefaultLoggerOptions } from '../logger-bOzkF5LL.js';
2
- export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-C5sPVne8.js';
3
- export { C as ContextManagerAction, a as ContextManagerInput, b as ContextManagerResult, c as ContextManagerToolOptions, d as allServers, e as awsServer, f as blockServer, g as braveSearchServer, h as context7Server, i as contextManagerTool, j as createContextManagerTool, k as everArtServer, l as filesystemServer, m as githubServer, n as googleMapsServer, o as miniMaxVisionServer, s as sentinelServer, p as slackServer, z as zaiVisionServer } from '../mcp-servers-CwqQDMYy.js';
2
+ export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-DVkEcIw8.js';
3
+ export { C as ContextManagerAction, a as ContextManagerInput, b as ContextManagerResult, c as ContextManagerToolOptions, d as allServers, e as awsServer, f as blockServer, g as braveSearchServer, h as context7Server, i as contextManagerTool, j as createContextManagerTool, k as everArtServer, l as filesystemServer, m as githubServer, n as googleMapsServer, o as miniMaxVisionServer, s as sentinelServer, p as slackServer, z as zaiVisionServer } from '../mcp-servers-DwoNBf6r.js';
4
4
  import '../logger-DDd5C--Z.js';
5
- import '../events-k8CHjcrN.js';
6
- import '../context-iFMEO2rN.js';
5
+ import '../events-CIplI98R.js';
6
+ import '../context-y87Jc5ei.js';
7
7
  import '../models-registry-BcYJDKLm.js';
8
8
  import '../path-resolver-CPRj4bFY.js';
9
- import '../compactor-0vjZ8KTk.js';
10
- import '../config-BdDuaZmB.js';
9
+ import '../compactor-D_ExJajC.js';
10
+ import '../config--86aHSln.js';
@@ -1,18 +1,18 @@
1
- export { B as BindOptions, C as Container, D as Decorator, F as Factory, M as Middleware, b as MiddlewareHandler, N as NextFn, P as Pipeline, d as PipelineOptions, T as Token } from '../system-prompt-7LHyBbIf.js';
2
- export { E as EventBus, i as EventLogger, j as EventMap, k as EventName, L as Listener, S as ScopedEventBus } from '../events-k8CHjcrN.js';
3
- export { R as RunController, b as RunControllerOptions, T as TOKENS } from '../index-CWdW_CJt.js';
4
- import '../config-BdDuaZmB.js';
1
+ export { B as BindOptions, C as Container, D as Decorator, F as Factory, M as Middleware, b as MiddlewareHandler, N as NextFn, P as Pipeline, d as PipelineOptions, T as Token } from '../system-prompt-b61lOd49.js';
2
+ export { E as EventBus, i as EventLogger, j as EventMap, k as EventName, L as Listener, S as ScopedEventBus } from '../events-CIplI98R.js';
3
+ export { R as RunController, b as RunControllerOptions, T as TOKENS } from '../index-b5uhfTSl.js';
4
+ import '../config--86aHSln.js';
5
5
  import '../models-registry-BcYJDKLm.js';
6
- import '../context-iFMEO2rN.js';
7
- import '../compactor-0vjZ8KTk.js';
8
- import '../retry-policy-BfBScewS.js';
6
+ import '../context-y87Jc5ei.js';
7
+ import '../compactor-D_ExJajC.js';
8
+ import '../retry-policy-CG3qvH_e.js';
9
9
  import '../input-reader-E-ffP2ee.js';
10
10
  import '../logger-DDd5C--Z.js';
11
11
  import '../memory-CEXuo7sz.js';
12
12
  import '../mode-CV077NjV.js';
13
13
  import '../path-resolver-CPRj4bFY.js';
14
- import '../permission-Ld-i5ugf.js';
15
- import '../provider-runner-DJQa211J.js';
14
+ import '../permission-C1A5whY5.js';
15
+ import '../provider-runner-mXvXGSIw.js';
16
16
  import '../observability-BhnVLBLS.js';
17
17
  import '../secret-scrubber-3MHDDAtm.js';
18
18
  import '../skill-CxuWrsKK.js';
@@ -1,6 +1,6 @@
1
- import { a as Compactor } from './compactor-0vjZ8KTk.js';
2
- import { M as Message, Q as Tool } from './context-iFMEO2rN.js';
3
- import { M as MCPServerConfig } from './config-BdDuaZmB.js';
1
+ import { a as Compactor } from './compactor-D_ExJajC.js';
2
+ import { M as Message, Q as Tool } from './context-y87Jc5ei.js';
3
+ import { M as MCPServerConfig } from './config--86aHSln.js';
4
4
 
5
5
  type ContextManagerAction = 'check' | 'summary' | 'prune' | 'add_note' | 'compact' | 'repair';
6
6
  interface ContextManagerInput {
@@ -1,7 +1,7 @@
1
1
  export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-Cuq1C8V9.js';
2
2
  import { c as ModeStore, a as ModeConfig, M as Mode } from '../mode-CV077NjV.js';
3
- import { m as Provider, M as Message } from '../context-iFMEO2rN.js';
4
- import { M as MessageSelector, S as SelectorResult } from '../selector-DxhW7ML3.js';
3
+ import { m as Provider, M as Message } from '../context-y87Jc5ei.js';
4
+ import { M as MessageSelector, S as SelectorResult } from '../selector-RvBR_YRW.js';
5
5
  import '../models-registry-BcYJDKLm.js';
6
6
 
7
7
  declare class DefaultModeStore implements ModeStore {
@@ -1,5 +1,4 @@
1
- import { n as SubagentConfig, l as MultiAgentCoordinator, M as MultiAgentConfig, t as SubagentRunner, S as SpawnResult, v as TaskSpec, B as BridgeMessage, A as AgentBridge, k as CoordinatorStatus, u as TaskResult } from './multi-agent-SASYOrWA.js';
2
- import { F as FleetBus } from './agent-subagent-runner-Zc3f37Sg.js';
1
+ import { L as SubagentConfig, v as MultiAgentCoordinator, u as MultiAgentConfig, U as SubagentRunner, F as FleetBus, J as SpawnResult, Y as TaskSpec, B as BridgeMessage, a as AgentBridge, o as CoordinatorStatus, X as TaskResult } from './agent-subagent-runner-DRZ9-NnR.js';
3
2
  import { EventEmitter } from 'node:events';
4
3
 
5
4
  /**
@@ -299,6 +298,15 @@ declare class DefaultMultiAgentCoordinator extends EventEmitter implements Multi
299
298
  * underflow guard on every task after the first.
300
299
  */
301
300
  private drainPendingAsAborted;
301
+ /**
302
+ * Emit a synthetic `stopped`/`aborted_by_parent` completion for a single
303
+ * PENDING task — one that was never counted in `inFlight`. This MUST bypass
304
+ * `recordCompletion`: that path does `inFlight--`, which for a pending task
305
+ * steals a decrement from a genuinely in-flight task and trips the underflow
306
+ * guard — suppressing that real task's `task.completed` and hanging its
307
+ * `awaitTasks()` caller. Pushes the result and fires the event directly.
308
+ */
309
+ private emitPendingAborted;
302
310
  private runDispatched;
303
311
  private executeWithTimeout;
304
312
  private recordCompletion;
@@ -1,12 +1,11 @@
1
- import { c as AgentPhase, b as AgentDefinition, d as DefaultMultiAgentCoordinator, f as DispatchClassifier } from './multi-agent-coordinator-CNUJYq7U.js';
2
- import { n as SubagentConfig, u as TaskResult, k as CoordinatorStatus, v as TaskSpec, M as MultiAgentConfig, t as SubagentRunner } from './multi-agent-SASYOrWA.js';
3
- import { B as SessionWriter, Q as Tool, y as SessionStore } from './context-iFMEO2rN.js';
4
- import { F as FleetBus, e as FleetUsage, f as FleetUsageAggregator } from './agent-subagent-runner-Zc3f37Sg.js';
1
+ import { c as AgentPhase, b as AgentDefinition, d as DefaultMultiAgentCoordinator, f as DispatchClassifier } from './multi-agent-coordinator-CWnH-CiX.js';
2
+ import { F as FleetBus, r as FleetUsage, L as SubagentConfig, s as FleetUsageAggregator, X as TaskResult, o as CoordinatorStatus, Y as TaskSpec, u as MultiAgentConfig, U as SubagentRunner } from './agent-subagent-runner-DRZ9-NnR.js';
3
+ import { B as SessionWriter, Q as Tool, y as SessionStore } from './context-y87Jc5ei.js';
5
4
  import { EventEmitter } from 'node:events';
6
- import { B as BrainArbiter, E as EventBus } from './events-k8CHjcrN.js';
5
+ import { B as BrainArbiter, E as EventBus } from './events-CIplI98R.js';
7
6
  import { a as DirectorStateSnapshot } from './director-state-BmYi3DGA.js';
8
- import { p as ModelMatrixEntry } from './config-BdDuaZmB.js';
9
- import { I as InMemoryAgentBridge } from './agent-bridge-B5rxWrg3.js';
7
+ import { p as ModelMatrixEntry } from './config--86aHSln.js';
8
+ import { I as InMemoryAgentBridge } from './agent-bridge-D-j6OOBT.js';
10
9
 
11
10
  /**
12
11
  * Agent catalog aggregator.
@@ -779,6 +778,23 @@ declare class LargeAnswerStore {
779
778
  clear(): void;
780
779
  }
781
780
 
781
+ /**
782
+ * Director-specific error types. Extracted to keep the Director class
783
+ * focused on orchestration logic.
784
+ */
785
+ declare class FleetSpawnBudgetError extends Error {
786
+ readonly kind: 'max_spawns' | 'max_spawn_depth';
787
+ readonly limit: number;
788
+ readonly observed: number;
789
+ constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number, message?: string);
790
+ }
791
+ declare class FleetCostCapError extends Error {
792
+ readonly kind: 'max_cost_usd';
793
+ readonly limit: number;
794
+ readonly observed: number;
795
+ constructor(limit: number, observed: number);
796
+ }
797
+
782
798
  /**
783
799
  * Director — high-level orchestrator that owns a `MultiAgentCoordinator`,
784
800
  * a `FleetBus`, and a `FleetUsageAggregator`. Exposes a small imperative
@@ -985,30 +1001,7 @@ interface DirectorOptions {
985
1001
  }
986
1002
  /** Either a static matrix or a live getter (re-read on every spawn). */
987
1003
  type ModelMatrixSource = Record<string, ModelMatrixEntry> | (() => Record<string, ModelMatrixEntry> | undefined);
988
- /**
989
- * Thrown by `Director.spawn()` when a configured spawn cap (`maxSpawns`,
990
- * `maxSpawnDepth`) is hit. Distinct error class so callers — including
991
- * the `spawn_subagent` tool surface — can recognize the budget case and
992
- * report it cleanly instead of treating it like an unexpected failure.
993
- */
994
- declare class FleetSpawnBudgetError extends Error {
995
- readonly kind: 'max_spawns' | 'max_spawn_depth';
996
- readonly limit: number;
997
- readonly observed: number;
998
- constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number, message?: string);
999
- }
1000
- /**
1001
- * Thrown by `Director.spawn()` when the fleet-wide cost cap is exceeded.
1002
- * Distinct from `FleetSpawnBudgetError` (spawn count/depth) — this is a
1003
- * dollar-denominated ceiling that tracks cumulative spend across all
1004
- * subagents in the fleet.
1005
- */
1006
- declare class FleetCostCapError extends Error {
1007
- readonly kind: 'max_cost_usd';
1008
- readonly limit: number;
1009
- readonly observed: number;
1010
- constructor(limit: number, observed: number);
1011
- }
1004
+
1012
1005
  declare class Director implements ICoordinator {
1013
1006
  /** Alias for the ICoordinator contract. `id` is retained for backward compatibility. */
1014
1007
  get coordinatorId(): string;
@@ -1,6 +1,6 @@
1
1
  import { e as MetricsSink, M as MetricLabels, f as MetricsSnapshot, b as HealthRegistry, H as HealthCheck, A as AggregateHealth, T as Tracer, S as Span } from '../observability-BhnVLBLS.js';
2
- import { E as EventBus } from '../events-k8CHjcrN.js';
3
- import '../context-iFMEO2rN.js';
2
+ import { E as EventBus } from '../events-CIplI98R.js';
3
+ import '../context-y87Jc5ei.js';
4
4
 
5
5
  /**
6
6
  * In-memory metrics sink. Suitable for embedded use, tests, and /metrics
@@ -0,0 +1,483 @@
1
+ import { d as Context, n as ProviderError, Q as Tool, _ as ToolUseBlock, Y as ToolResultBlock } from './context-y87Jc5ei.js';
2
+ import { a as Compactor, C as CompactReport } from './compactor-D_ExJajC.js';
3
+ import { R as RecoveryDecision, E as ErrorHandler, a as RetryPolicy } from './retry-policy-CG3qvH_e.js';
4
+ import { b as ModelsRegistry } from './models-registry-BcYJDKLm.js';
5
+ import { r as ToolExecutorOptions, s as ToolExecutorStrategy, T as ToolBatchResult } from './index-DKUvyTvV.js';
6
+ import { A as Agent, c as AgentFactory } from './agent-subagent-runner-DRZ9-NnR.js';
7
+ import { J as JournalEntry } from './goal-store-C7jcumEh.js';
8
+ import { f as DispatchClassifier, d as DefaultMultiAgentCoordinator } from './multi-agent-coordinator-CWnH-CiX.js';
9
+
10
+ interface CompactorOptions {
11
+ preserveK?: number;
12
+ eliseThreshold?: number;
13
+ estimator?: (text: string) => number;
14
+ }
15
+
16
+ declare class HybridCompactor implements Compactor {
17
+ private readonly preserveK;
18
+ private readonly eliseThreshold;
19
+ private readonly estimator;
20
+ constructor(opts?: CompactorOptions);
21
+ compact(ctx: Context, opts?: {
22
+ aggressive?: boolean;
23
+ }): Promise<CompactReport>;
24
+ /**
25
+ * Estimate the full API request token count: messages + systemPrompt + toolDefs.
26
+ * This is the accurate figure for context-window pressure monitoring.
27
+ */
28
+ private estimateFullRequest;
29
+ private eliseOldToolResults;
30
+ private collapseAncientTurns;
31
+ private estimateMessages;
32
+ }
33
+
34
+ /**
35
+ * Tiered error recovery strategies.
36
+ * Each strategy is attempted in order until one returns a decision.
37
+ */
38
+ interface RecoveryStrategy {
39
+ /** Human-readable label for logs. */
40
+ label: string;
41
+ /** Optional compactor for context_overflow recovery. */
42
+ compactor?: Compactor;
43
+ /** Returns an explicit recovery decision, or null to fall through. */
44
+ attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;
45
+ }
46
+ /**
47
+ * Builds the ordered list of recovery strategies used by DefaultErrorHandler.
48
+ * Exported so callers can customise or extend the strategy chain.
49
+ */
50
+ declare function buildRecoveryStrategies(opts?: {
51
+ compactor?: Compactor;
52
+ modelsRegistry?: ModelsRegistry;
53
+ }): RecoveryStrategy[];
54
+ declare const DEFAULT_RECOVERY_STRATEGIES: RecoveryStrategy[];
55
+ declare class DefaultErrorHandler implements ErrorHandler {
56
+ private readonly strategies;
57
+ constructor(strategies?: RecoveryStrategy[]);
58
+ classify(err: unknown): {
59
+ kind: 'rate_limit' | 'overloaded' | 'server' | 'client' | 'network' | 'abort' | 'context_overflow' | 'unknown';
60
+ retryable: boolean;
61
+ };
62
+ recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null>;
63
+ }
64
+
65
+ declare class DefaultRetryPolicy implements RetryPolicy {
66
+ shouldRetry(err: Error | ProviderError, attempt: number): boolean;
67
+ maxAttempts(err: Error | ProviderError): number;
68
+ delayMs(attempt: number): number;
69
+ }
70
+
71
+ declare class ToolExecutor {
72
+ private readonly registry;
73
+ private opts;
74
+ private readonly serializer;
75
+ private readonly iterationTimeoutMs;
76
+ constructor(registry: {
77
+ get(name: string): Tool | undefined;
78
+ list(): Tool[];
79
+ }, opts: ToolExecutorOptions);
80
+ /**
81
+ * Clear the interactive confirm awaiter so the executor returns
82
+ * `ToolConfirmPendingResult` instead of blocking on stdin. Used by
83
+ * the CLI to switch from inline prompts (REPL) to event-driven
84
+ * confirmation (TUI) at runtime.
85
+ */
86
+ clearConfirmAwaiter(): void;
87
+ /**
88
+ * Execute a batch of tool uses using the configured strategy.
89
+ * Returns the execution results and the remaining output budget.
90
+ */
91
+ executeBatch(toolUses: ToolUseBlock[], ctx: Context, strategy: ToolExecutorStrategy): Promise<ToolBatchResult>;
92
+ /**
93
+ * Execute a single tool with timeout, permission check, and output capping.
94
+ * Emits `tool.started` via the injected EventBus (if any) right before
95
+ * invoking the tool — closes the observability gap between "model decided
96
+ * to call a tool" and "tool.executed".
97
+ */
98
+ executeTool(tool: Tool, use: ToolUseBlock, ctx: Context, budget: number): Promise<ToolResultBlock>;
99
+ private runWithTimeout;
100
+ private runStreamedTool;
101
+ private unknownToolResult;
102
+ private malformedInputResult;
103
+ private deniedResult;
104
+ private blockedByHookResult;
105
+ private decrementBudget;
106
+ /**
107
+ * Compute the suggestedPattern string for a tool+input pair.
108
+ * Matches the logic in DefaultPermissionPolicy so the TUI shows the
109
+ * same subject that the trust file would use.
110
+ */
111
+ private subjectFor;
112
+ }
113
+
114
+ /**
115
+ * Sense-decide-execute-reflect loop on top of a long-running Goal.
116
+ *
117
+ * Each iteration:
118
+ * 1. Sense — read goal, pending todos, `git status --porcelain`.
119
+ * 2. Decide — pick a source (todo / git / brainstorm) and a task.
120
+ * 3. Execute — single agent.run with a directive prompt.
121
+ * 4. Reflect — append a journal entry, persist state to disk.
122
+ *
123
+ * The loop runs forever until `stop()` is called externally (REPL SIGINT
124
+ * handler, /autonomy stop). No internal time/cost cap by design — the
125
+ * user wants "sittin sene". Failures are logged and the loop continues
126
+ * with a different source on the next tick.
127
+ */
128
+ interface EternalAutonomyOptions {
129
+ agent: Agent;
130
+ projectRoot: string;
131
+ /**
132
+ * Per-iteration agent timeout. Defaults to 5 minutes. A single hung
133
+ * provider call should not freeze the whole eternal loop.
134
+ */
135
+ iterationTimeoutMs?: number;
136
+ /**
137
+ * Maximum number of internal agent.run iterations the engine grants per
138
+ * eternal-loop tick. The engine sets `autonomousContinue: true` so the
139
+ * agent can run multi-step tasks end-to-end within one tick instead of
140
+ * bouncing back to the engine after every single tool call. Default 500.
141
+ * Previous 50 was far too low — agents hit the limit and restart constantly.
142
+ */
143
+ iterationMaxAgentSteps?: number;
144
+ /**
145
+ * Minimum sleep between iterations. Defaults to 1 s — enough for
146
+ * SIGINT handlers to fire mid-loop without pegging a core when the
147
+ * provider is being rate-limited.
148
+ */
149
+ cycleGapMs?: number;
150
+ /**
151
+ * Maximum consecutive failures before the source rotation forces a
152
+ * brainstorm cycle. Default 3. Acts as a soft-recovery, not a stop.
153
+ */
154
+ failureBudget?: number;
155
+ /**
156
+ * Per-todo failed-attempt ceiling. When the engine picks the same todo
157
+ * and the iteration fails this many times in total, the todo is taken
158
+ * out of rotation (engine prefers other sources) until it changes
159
+ * status. Default 3. Prevents the loop from spinning forever on one
160
+ * stuck task.
161
+ */
162
+ todoMaxAttempts?: number;
163
+ /**
164
+ * Consecutive brainstorm-DONE responses required to consider the goal
165
+ * complete and stop the engine. When the LLM's brainstorm step keeps
166
+ * answering `DONE`, the engine treats that as "no more work" and, after
167
+ * this many in a row, marks the goal as completed instead of sleeping
168
+ * forever. Default 3.
169
+ */
170
+ brainstormDoneStopThreshold?: number;
171
+ /** Side-channel notifications (logging, UI updates). */
172
+ onIteration?: (entry: JournalEntry) => void;
173
+ onError?: (err: Error, iteration: number) => void;
174
+ /**
175
+ * Per-iteration phase notifications for live UI updates (TUI status bar,
176
+ * etc.). Fires at each major stage transition: idle → decide → execute →
177
+ * reflect → (sleep | paused | stopped). Fire-and-forget — the engine
178
+ * does not await the callback.
179
+ */
180
+ onStage?: (stage: IterationStage) => void;
181
+ /**
182
+ * Optional injected git status reader — production code uses git, tests
183
+ * stub this out so they don't shell out.
184
+ */
185
+ gitStatusReader?: () => Promise<string>;
186
+ /**
187
+ * Optional clock — tests stub for deterministic timestamps.
188
+ */
189
+ now?: () => Date;
190
+ /**
191
+ * Optional compactor. When provided, the engine runs compaction every
192
+ * `compactEveryNIterations` iterations to keep the agent's message
193
+ * history under control during multi-day eternal loops. Without
194
+ * compaction, an infinite loop will eventually overflow the provider's
195
+ * context window and start failing.
196
+ */
197
+ compactor?: Compactor;
198
+ /** How many iterations between compaction calls. Default 25. */
199
+ compactEveryNIterations?: number;
200
+ /**
201
+ * Aggressive compaction threshold. When ctx token usage exceeds this
202
+ * fraction of `maxContextTokens`, compaction runs in aggressive mode
203
+ * regardless of the iteration cadence. 0.85 by default.
204
+ */
205
+ aggressiveCompactRatio?: number;
206
+ /**
207
+ * Model's max context window in tokens. When set, the engine watches
208
+ * `currentRequestTokens()` against this and triggers aggressive compact
209
+ * before the next iteration would overflow. Omit to disable threshold
210
+ * checks (iteration cadence still applies).
211
+ */
212
+ maxContextTokens?: number;
213
+ /**
214
+ * Base delay (ms) for the first transient-error backoff. Subsequent
215
+ * transient failures double this, capped at `transientBackoffMaxMs`.
216
+ * Default 2_000.
217
+ *
218
+ * "Transient" means the underlying error is recoverable per
219
+ * `WrongStackError.recoverable` (ProviderError sets this for 429/529/5xx
220
+ * /network errors). Permanent errors (auth/invalid request) skip the
221
+ * backoff and count toward `failureBudget` like before — backing off
222
+ * on a permanent failure is wasted time.
223
+ */
224
+ transientBackoffBaseMs?: number;
225
+ /** Ceiling for the exponential backoff. Default 60_000 (60 s). */
226
+ transientBackoffMaxMs?: number;
227
+ /** Called when the eternal loop stops for any reason (manual stop, goal complete, etc.). */
228
+ onEternalStop?: () => void;
229
+ }
230
+ type EternalEngineState = 'idle' | 'running' | 'stopped';
231
+ /**
232
+ * Per-iteration phase emitted via `onStage` so UIs can render the
233
+ * engine's live location in the sense-decide-execute-reflect loop.
234
+ */
235
+ type IterationStage = {
236
+ phase: 'idle';
237
+ } | {
238
+ phase: 'decide';
239
+ reason: string;
240
+ } | {
241
+ phase: 'execute';
242
+ task: string;
243
+ } | {
244
+ phase: 'reflect';
245
+ status: 'success' | 'failure' | 'aborted' | 'skipped';
246
+ note?: string;
247
+ } | {
248
+ phase: 'sleep';
249
+ ms: number;
250
+ } | {
251
+ phase: 'paused';
252
+ } | {
253
+ phase: 'stopped';
254
+ } | {
255
+ phase: 'error';
256
+ message: string;
257
+ };
258
+ declare class EternalAutonomyEngine {
259
+ private readonly opts;
260
+ private state;
261
+ private stopRequested;
262
+ private consecutiveFailures;
263
+ private consecutiveBrainstormDone;
264
+ /**
265
+ * Count of consecutive transient (recoverable) provider failures. Drives
266
+ * the exponential backoff between iterations. Reset on the first
267
+ * successful iteration so a single bad afternoon doesn't permanently
268
+ * slow the loop down.
269
+ */
270
+ private consecutiveTransientRetries;
271
+ private currentCtrl;
272
+ private iterationsSinceCompact;
273
+ private readonly goalPath;
274
+ constructor(opts: EternalAutonomyOptions);
275
+ /** Current engine state — readable for UIs. */
276
+ get currentState(): EternalEngineState;
277
+ /** Synchronously request stop. Resolves once the running iteration aborts. */
278
+ stop(): void;
279
+ /**
280
+ * Mark the engine as 'running' on disk + reset stop state so a new
281
+ * batch of `runOneIteration()` calls can proceed. Called by the REPL
282
+ * when the user invokes `/autonomy eternal`. Idempotent.
283
+ */
284
+ prime(): Promise<void>;
285
+ /**
286
+ * Main loop. Returns when stop() is called or the goal file is removed.
287
+ * Does NOT throw — every iteration is wrapped to keep the loop alive.
288
+ */
289
+ run(): Promise<void>;
290
+ /**
291
+ * Execute a single sense-decide-execute-reflect cycle.
292
+ * Returns true on success, false on handled failure / no-op.
293
+ *
294
+ * Exposed publicly so the REPL can pace iterations from its main loop
295
+ * — running the engine and the REPL as a single sequential consumer of
296
+ * `agent.run()` avoids race conditions on the shared Context.
297
+ */
298
+ runOneIteration(): Promise<boolean>;
299
+ /**
300
+ * Run compaction when either trigger fires:
301
+ * - We've done >= compactEveryNIterations since the last compact.
302
+ * - Current request tokens exceed aggressiveCompactRatio * maxContext.
303
+ *
304
+ * The second check uses *aggressive* mode to free more headroom; the
305
+ * cadence check uses non-aggressive (cheaper).
306
+ */
307
+ private maybeCompact;
308
+ /**
309
+ * Hybrid idea source.
310
+ * 1. Pending todos on the agent's context.
311
+ * 2. Dirty git working tree → propose a "review and finish this" task.
312
+ * 3. Otherwise: brainstorm via the LLM against the goal.
313
+ *
314
+ * After failureBudget consecutive failures, force brainstorm so the
315
+ * engine doesn't loop on the same broken todo or stuck git state.
316
+ */
317
+ private decide;
318
+ private pickPendingTodo;
319
+ private pickGitTask;
320
+ private readGitStatus;
321
+ private brainstormTask;
322
+ private buildDirective;
323
+ /**
324
+ * Exponential backoff for transient provider errors. `2^N * base`
325
+ * capped at `transientBackoffMaxMs`. Zero base disables backoff.
326
+ * Public-private to keep `runOneIteration` readable; the value is
327
+ * recomputed each call from the current retry count, so callers
328
+ * don't have to track state.
329
+ */
330
+ private computeTransientBackoffMs;
331
+ /**
332
+ * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms
333
+ * so SIGINT / `/autonomy stop` can land in the middle of a long
334
+ * backoff instead of waiting up to a minute for the timer.
335
+ */
336
+ private sleepInterruptible;
337
+ private appendIterationEntry;
338
+ /**
339
+ * Persistent per-todo failure counter. Skipped silently when the goal
340
+ * file has been removed (graceful clear). Each non-success iteration
341
+ * against a todo source bumps the counter by 1; `pickPendingTodo` reads
342
+ * the counter to rotate past stuck todos once they cross `todoMaxAttempts`.
343
+ */
344
+ private bumpTodoAttempt;
345
+ /**
346
+ * Flip the mission to `completed` and journal it. Called from two
347
+ * paths: (a) `[GOAL_COMPLETE]` marker in a successful iteration's
348
+ * finalText, (b) `brainstorm` returning DONE consecutively past the
349
+ * configured threshold. Idempotent — re-entry is a no-op once the
350
+ * goal is already `completed`.
351
+ */
352
+ private markGoalCompleted;
353
+ /**
354
+ * Manually clear the goal — equivalent to `/goal clear` typed by the user.
355
+ * Sets goalState to `abandoned`, removes the goal file, and fires
356
+ * `onEternalStop` so the REPL returns to normal mode.
357
+ */
358
+ private clearGoalManually;
359
+ private appendFailure;
360
+ private persistEngineState;
361
+ }
362
+
363
+ type ParallelEngineState = 'idle' | 'running' | 'stopped';
364
+ type ParallelIterationStage = {
365
+ phase: 'idle';
366
+ } | {
367
+ phase: 'decompose';
368
+ } | {
369
+ phase: 'fanout';
370
+ slots: number;
371
+ } | {
372
+ phase: 'await';
373
+ taskIds: string[];
374
+ } | {
375
+ phase: 'aggregate';
376
+ successCount: number;
377
+ total: number;
378
+ goalComplete: boolean;
379
+ } | {
380
+ phase: 'sleep';
381
+ ms: number;
382
+ } | {
383
+ phase: 'stopped';
384
+ } | {
385
+ phase: 'error';
386
+ message: string;
387
+ };
388
+ interface ParallelEternalOptions {
389
+ /** The coordinating agent — NOT a subagent. Owns container/tools/providers. */
390
+ agent: Agent;
391
+ /** Project root (used for goal.json path). */
392
+ projectRoot: string;
393
+ /**
394
+ * Override the resolved goal.json path. Defaults to
395
+ * `goalFilePath(projectRoot)` (a hashed location under the home dir).
396
+ * Primarily for tests that want an isolated goal file under a temp dir.
397
+ */
398
+ goalPath?: string;
399
+ /**
400
+ * Number of parallel subagent slots per tick.
401
+ * Default: 4. Range 1–16; values >8 are for high-throughput machines.
402
+ */
403
+ parallelSlots?: number;
404
+ /** Per-subagent default timeout in ms. Default: 300_000 (5 min). */
405
+ iterationTimeoutMs?: number;
406
+ onIteration?: (entry: JournalEntry) => void;
407
+ onError?: (err: Error, iteration: number) => void;
408
+ /** Per-tick phase notifications for live UI/status updates. */
409
+ onStage?: (stage: ParallelIterationStage) => void;
410
+ gitStatusReader?: () => Promise<string>;
411
+ now?: () => Date;
412
+ compactor?: Compactor;
413
+ compactEveryNIterations?: number;
414
+ aggressiveCompactRatio?: number;
415
+ maxContextTokens?: number;
416
+ /** Override the default agent factory (uses main agent if not provided). */
417
+ subagentFactory?: AgentFactory;
418
+ /**
419
+ * Route each decomposed slot task to the best-fit catalog agent via the
420
+ * smart dispatcher (heuristic keyword scoring). When enabled (default), each
421
+ * slot spawns in-role — the role's budget tier applies and a persona line is
422
+ * injected into the task — instead of as a faceless generic worker. Set
423
+ * false to keep the legacy generic spawn.
424
+ */
425
+ dispatch?: boolean;
426
+ /**
427
+ * Optional LLM fallback for ambiguous tasks. Passed straight to
428
+ * `dispatchAgent`; when omitted, routing is pure heuristic (instant, no
429
+ * provider call — preferred for a continuously-ticking autonomous loop).
430
+ */
431
+ dispatchClassifier?: DispatchClassifier;
432
+ }
433
+ /**
434
+ * Sense → Decide → Fan-out (4–8 parallel agents) → Aggregate → Loop.
435
+ *
436
+ * Each tick:
437
+ * 1. Sense — load goal, todos, git status
438
+ * 2. Decide — decompose goal into N parallel sub-tasks
439
+ * 3. Fan-out — spawn N subagents simultaneously, await all
440
+ * 4. Aggregate — write journal, update todos, check [GOAL_COMPLETE]
441
+ * 5. Loop — continue until stop() or mission complete
442
+ *
443
+ * Uses DefaultMultiAgentCoordinator + AgentSubagentRunner for subagent lifecycle.
444
+ */
445
+ declare class ParallelEternalEngine {
446
+ private readonly opts;
447
+ private state;
448
+ private stopRequested;
449
+ private iterationsSinceCompact;
450
+ private iterations;
451
+ private consecutiveFailures;
452
+ private readonly goalPath;
453
+ private readonly slots;
454
+ private readonly timeoutMs;
455
+ private coordinator;
456
+ private agentFactory;
457
+ private readonly dispatchEnabled;
458
+ private readonly dispatchClassifier?;
459
+ constructor(opts: ParallelEternalOptions);
460
+ get currentState(): ParallelEngineState;
461
+ /**
462
+ * Get the underlying coordinator for stats/monitoring.
463
+ */
464
+ getCoordinator(): DefaultMultiAgentCoordinator | null;
465
+ stop(): void;
466
+ prime(): Promise<void>;
467
+ run(): Promise<void>;
468
+ /**
469
+ * Execute one tick: decompose → fan-out → aggregate → compact.
470
+ * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).
471
+ */
472
+ runOneIteration(): Promise<boolean>;
473
+ private fanOut;
474
+ private decomposeGoal;
475
+ private readGitStatus;
476
+ private brainstormSubtasks;
477
+ private maybeCompact;
478
+ private appendIterationEntry;
479
+ private appendFailure;
480
+ private persistState;
481
+ }
482
+
483
+ export { type CompactorOptions as C, DEFAULT_RECOVERY_STRATEGIES as D, EternalAutonomyEngine as E, HybridCompactor as H, type IterationStage as I, type ParallelEngineState as P, type RecoveryStrategy as R, ToolExecutor as T, DefaultErrorHandler as a, DefaultRetryPolicy as b, type EternalAutonomyOptions as c, type EternalEngineState as d, ParallelEternalEngine as e, type ParallelEternalOptions as f, type ParallelIterationStage as g, buildRecoveryStrategies as h };
@@ -1,6 +1,6 @@
1
- import { E as EventBus } from './events-k8CHjcrN.js';
1
+ import { E as EventBus } from './events-CIplI98R.js';
2
2
  import { b as ModelsRegistry, R as ResolvedModel } from './models-registry-BcYJDKLm.js';
3
- import { O as TokenCounter, $ as Usage, C as CacheStats } from './context-iFMEO2rN.js';
3
+ import { O as TokenCounter, $ as Usage, C as CacheStats } from './context-y87Jc5ei.js';
4
4
  import { P as PathResolver } from './path-resolver-CPRj4bFY.js';
5
5
 
6
6
  /**