@wrongstack/core 0.5.5 → 0.5.6

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.
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Director state checkpoint — written incrementally throughout a fleet
3
+ * run so a crashed director can be inspected (and eventually resumed)
4
+ * instead of leaving only a final `fleet.json` manifest after `shutdown()`.
5
+ *
6
+ * Schema is JSON-friendly and deliberately denormalized. Each mutation
7
+ * triggers an atomic-write of the whole file — small payloads (typically
8
+ * < 10 KB even with dozens of subagents) make this cheap.
9
+ */
10
+ interface DirectorSubagentState {
11
+ id: string;
12
+ name?: string;
13
+ role?: string;
14
+ provider?: string;
15
+ model?: string;
16
+ spawnedAt: string;
17
+ }
18
+ interface DirectorTaskState {
19
+ taskId: string;
20
+ subagentId?: string;
21
+ description?: string;
22
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'timeout';
23
+ assignedAt?: string;
24
+ completedAt?: string;
25
+ iterations?: number;
26
+ toolCalls?: number;
27
+ durationMs?: number;
28
+ error?: string;
29
+ }
30
+ interface DirectorStateSnapshot {
31
+ version: 1;
32
+ directorRunId: string;
33
+ updatedAt: string;
34
+ spawnCount: number;
35
+ maxSpawns?: number;
36
+ spawnDepth: number;
37
+ maxSpawnDepth: number;
38
+ directorBudget?: {
39
+ maxCostUsd?: number;
40
+ };
41
+ subagents: DirectorSubagentState[];
42
+ tasks: DirectorTaskState[];
43
+ /** Aggregated usage snapshot. Optional — populated by the Director on save when available. */
44
+ usage?: unknown;
45
+ }
46
+ declare function loadDirectorState(filePath: string): Promise<DirectorStateSnapshot | null>;
47
+ /**
48
+ * In-memory accumulator with atomic-write checkpoint. The Director keeps
49
+ * an instance, mutates it on every spawn/assign/complete/fail event, and
50
+ * the instance debounces writes so a burst of activity collapses into a
51
+ * single disk hit.
52
+ *
53
+ * Supports crash recovery: use `loadDirectorState()` to read an existing
54
+ * checkpoint, then call `DirectorStateCheckpoint.resume(snapshot)` to
55
+ * re-attach to a fleet mid-flight. The lock mechanism ensures no two
56
+ * directors can claim the same checkpoint.
57
+ */
58
+ declare class DirectorStateCheckpoint {
59
+ private snapshot;
60
+ private readonly filePath;
61
+ private readonly lockPath;
62
+ private timer;
63
+ private readonly debounceMs;
64
+ private writing;
65
+ private rewriteRequested;
66
+ constructor(filePath: string, init: {
67
+ directorRunId: string;
68
+ maxSpawns?: number;
69
+ spawnDepth: number;
70
+ maxSpawnDepth: number;
71
+ directorBudget?: {
72
+ maxCostUsd?: number;
73
+ };
74
+ }, debounceMs?: number);
75
+ /**
76
+ * Attempt to acquire the lock for this checkpoint. Call this before
77
+ * resuming a crashed director run. If it returns false, another
78
+ * director process is still running this fleet — do not resume.
79
+ */
80
+ acquireLock(): Promise<boolean>;
81
+ /**
82
+ * Release the lock on graceful shutdown. Call `flush()` first to ensure
83
+ * the final checkpoint state is on disk before removing the lock.
84
+ * Without this, the next resume will see a stale-lock and refuse.
85
+ */
86
+ releaseLock(): Promise<void>;
87
+ /**
88
+ * Resume from a snapshot previously loaded via `loadDirectorState()`.
89
+ * Use this when `--resume <runId>` is triggered — the snapshot has
90
+ * the full fleet state (subagents, tasks) from before the crash; the
91
+ * checkpoint continues from there.
92
+ */
93
+ resume(snapshot: DirectorStateSnapshot): void;
94
+ current(): DirectorStateSnapshot;
95
+ recordSpawn(sub: DirectorSubagentState, spawnCount: number): void;
96
+ recordTaskAssigned(task: DirectorTaskState): void;
97
+ recordTaskStatus(taskId: string, patch: Partial<DirectorTaskState> & {
98
+ status: DirectorTaskState['status'];
99
+ }): void;
100
+ setUsage(usage: unknown): void;
101
+ /** Force a synchronous flush — used by Director.shutdown(). */
102
+ flush(): Promise<void>;
103
+ private bumpUpdatedAt;
104
+ private schedule;
105
+ private persist;
106
+ }
107
+
108
+ export { DirectorStateCheckpoint as D, type DirectorStateSnapshot as a, type DirectorSubagentState as b, type DirectorTaskState as c, loadDirectorState as l };
@@ -1,3 +1,4 @@
1
+ import { a as DirectorStateSnapshot } from './director-state-BmYi3DGA.js';
1
2
  import { M as MultiAgentConfig, i as SubagentRunner, c as SubagentConfig, k as TaskSpec, j as TaskResult, a as CoordinatorStatus, b as MultiAgentCoordinator, S as SpawnResult, l as BridgeMessage, A as AgentBridge } from './multi-agent-Cv8wk47i.js';
2
3
  import { r as SessionWriter, v as Tool, p as SessionStore } from './context-CLZXPPYk.js';
3
4
  import { I as InMemoryAgentBridge } from './agent-bridge-B07AYFBk.js';
@@ -217,6 +218,51 @@ interface DirectorOptions {
217
218
  * writes (the manifest will then only be written on `shutdown()`).
218
219
  */
219
220
  manifestDebounceMs?: number;
221
+ /**
222
+ * Fleet-wide cost ceiling. When set, `spawn()` refuses any new subagent
223
+ * that would push the fleet's total cost above this limit. The cap
224
+ * is checked BEFORE the spawn is recorded — a refused spawn must not
225
+ * leak partial state into the manifest or fleet bus. Let in-flight
226
+ * tasks complete; refuse new spawns only. When `maxCostUsd` is absent
227
+ * or Infinity, no cost cap applies.
228
+ */
229
+ directorBudget?: {
230
+ /**
231
+ * Maximum total USD the fleet may spend across all subagents.
232
+ * Default: Infinity (no cap).
233
+ */
234
+ maxCostUsd?: number;
235
+ };
236
+ /**
237
+ * Maximum auto-extensions per subagent per budget kind before the
238
+ * director denies further extensions. A subagent hitting the same
239
+ * soft limit repeatedly (e.g. 3× budget.threshold_reached for
240
+ * tool_calls) is likely looping on a prompt/config issue, not
241
+ * making legitimate progress. Default: 2. Set to Infinity to
242
+ * disable the cap (use with caution — a misconfigured subagent
243
+ * could burn unlimited budget).
244
+ */
245
+ maxBudgetExtensions?: number;
246
+ /**
247
+ * Debounce window for state-checkpoint writes. Default: 250ms.
248
+ * Bursts of spawn/assign/complete events collapse into one disk
249
+ * hit. Higher values reduce write amplification on fast machines;
250
+ * lower values improve crash-recovery fidelity (less state lost
251
+ * on sudden process exit).
252
+ */
253
+ checkpointDebounceMs?: number;
254
+ /**
255
+ * Sessions root directory for per-subagent JSONL transcripts.
256
+ * When set, the director can read subagent transcripts directly for
257
+ * `fleet_session` tool — no bridge round-trip needed. Path convention:
258
+ * `<sessionsRoot>/<directorRunId>/<subagentId>.jsonl`.
259
+ */
260
+ sessionsRoot?: string;
261
+ /**
262
+ * Director run id — namespaced under `sessionsRoot` to locate per-subagent
263
+ * JSONLs. Defaults to the director's own `id` when omitted.
264
+ */
265
+ directorRunId?: string;
220
266
  }
221
267
  /**
222
268
  * Thrown by `Director.spawn()` when a configured spawn cap (`maxSpawns`,
@@ -230,6 +276,18 @@ declare class DirectorBudgetError extends Error {
230
276
  readonly observed: number;
231
277
  constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number);
232
278
  }
279
+ /**
280
+ * Thrown by `Director.spawn()` when the fleet-wide cost cap is exceeded.
281
+ * Distinct from `DirectorBudgetError` (spawn count/depth) — this is a
282
+ * dollar-denominated ceiling that tracks cumulative spend across all
283
+ * subagents in the fleet.
284
+ */
285
+ declare class DirectorCostCapError extends Error {
286
+ readonly kind: 'max_cost_usd';
287
+ readonly limit: number;
288
+ readonly observed: number;
289
+ constructor(limit: number, observed: number);
290
+ }
233
291
  declare class Director {
234
292
  readonly id: string;
235
293
  readonly fleet: FleetBus;
@@ -284,6 +342,14 @@ declare class Director {
284
342
  /** Debounce timer for periodic manifest writes. */
285
343
  private manifestTimer;
286
344
  private readonly manifestDebounceMs;
345
+ /** Fleet-wide cost cap. Infinity means no cap. */
346
+ private readonly maxCostUsd;
347
+ /** Max auto-extensions per subagent per budget kind before denying. */
348
+ private readonly maxBudgetExtensions;
349
+ /** Sessions root for direct subagent JSONL reads (fleet_session tool). */
350
+ private readonly sessionsRoot?;
351
+ /** Director run id for JSONL path resolution. */
352
+ private readonly directorRunId;
287
353
  /** Resolves task descriptions back from `assign()` so completion events
288
354
  * can also carry a human-readable title. */
289
355
  private readonly taskDescriptions;
@@ -404,6 +470,28 @@ declare class Director {
404
470
  * paint the completed table without reaching into private state.
405
471
  */
406
472
  completedResults(): TaskResult[];
473
+ /**
474
+ * Inject a previously-saved checkpoint snapshot. Call this right after
475
+ * constructing a Director during a `--resume` run so the in-memory state
476
+ * (subagents, tasks, waiters) reflects the pre-crash reality instead of
477
+ * starting from a blank slate. The director then resumes from there —
478
+ * completing any in-flight tasks and ignoring tasks that already reached
479
+ * a terminal state in the prior run.
480
+ */
481
+ setCheckpointState(snapshot: DirectorStateSnapshot): void;
482
+ /**
483
+ * Read a subagent's JSONL transcript directly from disk (no bridge
484
+ * round-trip needed). Returns the last assistant text, stop reason,
485
+ * tool-use count, and line count — or null if the file is unavailable.
486
+ * Requires `sessionsRoot` to be set on construction.
487
+ */
488
+ readSession(subagentId: string, tail?: number): Promise<{
489
+ lastAssistantText?: string;
490
+ lastStopReason?: string;
491
+ toolUsesObserved: number;
492
+ events: number;
493
+ path?: string;
494
+ } | null>;
407
495
  snapshot(): FleetUsage;
408
496
  /**
409
497
  * Look up provider/model metadata for a spawned subagent. Returns
@@ -453,6 +541,18 @@ declare class Director {
453
541
  * still permission-checked normally.
454
542
  */
455
543
  tools(roster?: Record<string, SubagentConfig>): Tool[];
544
+ /**
545
+ * Attempt to acquire the checkpoint lock. Must be called before
546
+ * resuming — if another director process is alive, this returns
547
+ * false and the caller should not proceed with the resume.
548
+ */
549
+ acquireCheckpointLock(): Promise<boolean>;
550
+ /**
551
+ * Resume from a prior checkpoint snapshot (loaded via
552
+ * `loadDirectorState()`). Re-attach to the fleet mid-flight so
553
+ * subsequent spawn/assign calls update the checkpoint normally.
554
+ */
555
+ resumeFromCheckpoint(snapshot: DirectorStateSnapshot): void;
456
556
  }
457
557
 
458
558
  /**
@@ -511,6 +611,13 @@ interface CreateDelegateToolOptions {
511
611
  * JSONLs at `<sessionsRoot>/<runId>/<subagentId>.jsonl`.
512
612
  */
513
613
  directorRunId?: string;
614
+ /**
615
+ * Buffer subtracted from the caller's `timeoutMs` before passing it
616
+ * to the subagent. Gives the host a window to detect a subagent that
617
+ * has gone silent and surface a partial result rather than a generic
618
+ * timeout. Default: 30_000 ms.
619
+ */
620
+ subagentTimeoutBufferMs?: number;
514
621
  }
515
622
  /**
516
623
  * `delegate` — the only multi-agent tool a regular (non-director) agent
@@ -896,4 +1003,4 @@ declare function applyRosterBudget(cfg: SubagentConfig): SubagentConfig;
896
1003
  /** Quick-access list for spawning all at once. */
897
1004
  declare const ALL_FLEET_AGENTS: SubagentConfig[];
898
1005
 
899
- export { ALL_FLEET_AGENTS as A, BUG_HUNTER_AGENT as B, type CreateDelegateToolOptions as C, DEFAULT_DIRECTOR_PREAMBLE as D, rosterSummaryFromConfigs as E, FLEET_ROSTER as F, type MultiAgentCoordinatorOptions as M, REFACTOR_PLANNER_AGENT as R, SECURITY_SCANNER_AGENT as S, AUDIT_LOG_AGENT as a, type AgentFactory as b, type AgentFactoryResult as c, type AgentRunnerOptions as d, DEFAULT_SUBAGENT_BASELINE as e, DefaultMultiAgentCoordinator as f, type DelegateHost as g, Director as h, DirectorBudgetError as i, type DirectorPromptParts as j, type DirectorSessionFactory as k, type DirectorSessionFactoryOptions as l, FLEET_ROSTER_BUDGETS as m, FleetBus as n, type FleetEvent as o, type FleetHandler as p, type FleetUsage as q, FleetUsageAggregator as r, type SubagentPromptParts as s, type SubagentUsageSnapshot as t, applyRosterBudget as u, composeDirectorPrompt as v, composeSubagentPrompt as w, createDelegateTool as x, makeAgentSubagentRunner as y, makeDirectorSessionFactory as z };
1006
+ export { ALL_FLEET_AGENTS as A, BUG_HUNTER_AGENT as B, type CreateDelegateToolOptions as C, DEFAULT_DIRECTOR_PREAMBLE as D, rosterSummaryFromConfigs as E, FLEET_ROSTER as F, DirectorCostCapError as G, type MultiAgentCoordinatorOptions as M, REFACTOR_PLANNER_AGENT as R, SECURITY_SCANNER_AGENT as S, AUDIT_LOG_AGENT as a, type AgentFactory as b, type AgentFactoryResult as c, type AgentRunnerOptions as d, DEFAULT_SUBAGENT_BASELINE as e, DefaultMultiAgentCoordinator as f, type DelegateHost as g, Director as h, DirectorBudgetError as i, type DirectorPromptParts as j, type DirectorSessionFactory as k, type DirectorSessionFactoryOptions as l, FLEET_ROSTER_BUDGETS as m, FleetBus as n, type FleetEvent as o, type FleetHandler as p, type FleetUsage as q, FleetUsageAggregator as r, type SubagentPromptParts as s, type SubagentUsageSnapshot as t, applyRosterBudget as u, composeDirectorPrompt as v, composeSubagentPrompt as w, createDelegateTool as x, makeAgentSubagentRunner as y, makeDirectorSessionFactory as z };
package/dist/index.d.ts CHANGED
@@ -33,11 +33,12 @@ export { C as CriticalPathResult, D as DEFAULT_SPEC_TEMPLATE, S as SpecAnalysis,
33
33
  export { A as AggregateHealth, H as HealthCheck, a as HealthCheckResult, b as HealthRegistry, c as HealthStatus, M as MetricLabels, d as MetricSeries, e as MetricsSink, f as MetricsSnapshot, S as Span, T as Tracer } from './observability-BhnVLBLS.js';
34
34
  export { AtomicWriteOptions, BuildChildEnvOptions, CompileFail, CompileResult, MessageRepairReport, MessageRepairResult, NewlineStyle, RequestTokenBreakdown, SafeParseResult, ToolOutputSerializerOptions, UnifiedDiffOptions, ValidationError, ValidationResult, atomicWrite, buildChildEnv, color, compileGlob, compileUserRegex, createToolOutputSerializer, detectNewlineStyle, ensureDir, estimateRequestTokens, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, formatTodosList, matchAny, matchGlob, normalizeToLf, repairToolUseAdjacency, safeParse, safeStringify, sanitizeJsonString, stripAnsi, toStyle, unifiedDiff, validateAgainstSchema } from './utils/index.js';
35
35
  export { a as WstackPathOptions, W as WstackPaths, p as projectHash, r as resolveWstackPaths } from './wstack-paths-86YPFktR.js';
36
- export { A as AbandonedSession, a as AttachmentStoreOptions, C as ConfigLoaderOptions, b as ConfigMigration, c as ConfigMigrationError, d as ConfigSource, D as DEFAULT_CONFIG_MIGRATIONS, e as DefaultAttachmentStore, f as DefaultConfigLoader, g as DefaultConfigStore, h as DefaultMemoryStore, i as DefaultSessionStore, j as DirectorStateCheckpoint, k as DirectorStateSnapshot, l as DirectorSubagentState, m as DirectorTaskState, M as MemoryStoreOptions, n as MigrationContext, o as MigrationResult, P as PersistedQueueItem, p as PlanFile, q as PlanItem, Q as QueueStore, R as RecoveryLock, r as RecoveryLockOptions, S as SessionAnalyzer, s as SessionStoreOptions, T as TodosCheckpointFile, t as addPlanItem, u as attachPlanCheckpoint, v as attachTodosCheckpoint, w as clearPlan, x as emptyPlan, y as formatPlan, z as loadDirectorState, B as loadPlan, E as loadTodosCheckpoint, F as removePlanItem, G as runConfigMigrations, H as savePlan, I as saveTodosCheckpoint, J as setPlanItemStatus } from './director-state-BUxlqkOa.js';
36
+ export { A as AbandonedSession, a as AttachmentStoreOptions, C as ConfigLoaderOptions, b as ConfigMigration, c as ConfigMigrationError, d as ConfigSource, D as DEFAULT_CONFIG_MIGRATIONS, e as DefaultAttachmentStore, f as DefaultConfigLoader, g as DefaultConfigStore, h as DefaultMemoryStore, i as DefaultSessionStore, M as MemoryStoreOptions, j as MigrationContext, k as MigrationResult, P as PersistedQueueItem, l as PlanFile, m as PlanItem, n as PlanTemplate, Q as QueueStore, R as RecoveryLock, o as RecoveryLockOptions, S as SessionAnalyzer, p as SessionStoreOptions, T as TodosCheckpointFile, q as addPlanItem, r as attachPlanCheckpoint, s as attachTodosCheckpoint, t as clearPlan, u as deriveTodosFromPlanItem, v as emptyPlan, w as formatPlan, x as formatPlanTemplates, y as getPlanTemplate, z as listPlanTemplates, B as loadPlan, E as loadTodosCheckpoint, F as removePlanItem, G as runConfigMigrations, H as savePlan, I as saveTodosCheckpoint, J as setPlanItemStatus } from './plan-templates-DaxTCPfk.js';
37
+ export { D as DirectorStateCheckpoint, a as DirectorStateSnapshot, b as DirectorSubagentState, c as DirectorTaskState, l as loadDirectorState } from './director-state-BmYi3DGA.js';
37
38
  export { AutoApprovePermissionPolicy, DefaultPermissionPolicy, PermissionPolicyOptions } from './security/index.js';
38
39
  export { AutoCompactionMiddleware, AutonomousRunner, AutonomousRunnerOptions, DefaultSkillLoader, DoneCheckResult, DoneConditionChecker, IntelligentCompactor, IntelligentCompactorOptions, SelectiveCompactor, SelectiveCompactorOptions, SkillLoaderOptions } from './execution/index.js';
39
40
  export { DefaultProviderRunner } from './defaults/index.js';
40
- export { A as ALL_FLEET_AGENTS, a as AUDIT_LOG_AGENT, b as AgentFactory, c as AgentFactoryResult, d as AgentRunnerOptions, B as BUG_HUNTER_AGENT, C as CreateDelegateToolOptions, D as DEFAULT_DIRECTOR_PREAMBLE, e as DEFAULT_SUBAGENT_BASELINE, f as DefaultMultiAgentCoordinator, g as DelegateHost, h as Director, i as DirectorBudgetError, j as DirectorPromptParts, k as DirectorSessionFactory, l as DirectorSessionFactoryOptions, F as FLEET_ROSTER, m as FLEET_ROSTER_BUDGETS, n as FleetBus, o as FleetEvent, p as FleetHandler, q as FleetUsage, r as FleetUsageAggregator, M as MultiAgentCoordinatorOptions, R as REFACTOR_PLANNER_AGENT, S as SECURITY_SCANNER_AGENT, s as SubagentPromptParts, t as SubagentUsageSnapshot, u as applyRosterBudget, v as composeDirectorPrompt, w as composeSubagentPrompt, x as createDelegateTool, y as makeAgentSubagentRunner, z as makeDirectorSessionFactory, E as rosterSummaryFromConfigs } from './index-De4R4rQ7.js';
41
+ export { A as ALL_FLEET_AGENTS, a as AUDIT_LOG_AGENT, b as AgentFactory, c as AgentFactoryResult, d as AgentRunnerOptions, B as BUG_HUNTER_AGENT, C as CreateDelegateToolOptions, D as DEFAULT_DIRECTOR_PREAMBLE, e as DEFAULT_SUBAGENT_BASELINE, f as DefaultMultiAgentCoordinator, g as DelegateHost, h as Director, i as DirectorBudgetError, j as DirectorPromptParts, k as DirectorSessionFactory, l as DirectorSessionFactoryOptions, F as FLEET_ROSTER, m as FLEET_ROSTER_BUDGETS, n as FleetBus, o as FleetEvent, p as FleetHandler, q as FleetUsage, r as FleetUsageAggregator, M as MultiAgentCoordinatorOptions, R as REFACTOR_PLANNER_AGENT, S as SECURITY_SCANNER_AGENT, s as SubagentPromptParts, t as SubagentUsageSnapshot, u as applyRosterBudget, v as composeDirectorPrompt, w as composeSubagentPrompt, x as createDelegateTool, y as makeAgentSubagentRunner, z as makeDirectorSessionFactory, E as rosterSummaryFromConfigs } from './index-BDnUCRvL.js';
41
42
  export { DefaultModeStore, LLMSelector, LLMSelectorOptions, ModeLoaderOptions, loadProjectModes, loadUserModes } from './models/index.js';
42
43
  export { AISpecBuilder, AISpecBuilderOptions, AISpecPhase, AISpecSession, AutoExecutor, AutoExecutorOptions, BottleneckTask, CollectedAnswer, CriticalPathAnalysis, DefaultTaskStore, ExecutionSummary, GeneratedTask, SPEC_TEMPLATES, SpecDiff, SpecDrivenDev, SpecDrivenDevOptions, SpecIndexEntry, SpecParser, SpecStore, SpecStoreOptions, SpecVersion, SpecVersioning, TaskExecutionContext, TaskExecutionResult, TaskFlow, TaskFlowEventMap, TaskFlowEventName, TaskFlowExecutionContext, TaskFlowOptions, TaskFlowPhase, TaskGenerator, TaskGeneratorOptions, TaskGraphIndexEntry, TaskGraphStore, TaskGraphStoreOptions, TaskStore, TaskTracker, TaskTrackerOptions, TaskTransition, analyzeCriticalPath, createAutoExecutor, getTemplate, listTemplates, renderProgress, renderSpecAnalysis, renderTaskGraph, renderTaskList, templateToMarkdown } from './sdd/index.js';
43
44
  export { DefaultHealthRegistry, InMemoryMetricsSink, MetricsServerHandle, MetricsServerOptions, NoopMetricsSink, NoopTracer, OTelTracer, OtlpMetricsExporterHandle, OtlpMetricsExporterOptions, OtlpTraceExporterHandle, OtlpTraceExporterOptions, PROMETHEUS_CONTENT_TYPE, buildOtlpMetricsRequest, buildOtlpTracesRequest, renderPrometheus, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, wireMetricsToEvents } from './observability/index.js';