@wrongstack/core 0.1.9 → 0.2.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 (69) hide show
  1. package/dist/agent-bridge-DmBiCipY.d.ts +33 -0
  2. package/dist/compactor-DSl2FK7a.d.ts +17 -0
  3. package/dist/config-DXrqb41m.d.ts +193 -0
  4. package/dist/{provider-txgB0Oq9.d.ts → context-u0bryklF.d.ts} +540 -472
  5. package/dist/coordination/index.d.ts +892 -0
  6. package/dist/coordination/index.js +2869 -0
  7. package/dist/coordination/index.js.map +1 -0
  8. package/dist/defaults/index.d.ts +34 -2309
  9. package/dist/defaults/index.js +5610 -4608
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/events-B6Q03pTu.d.ts +290 -0
  12. package/dist/execution/index.d.ts +260 -0
  13. package/dist/execution/index.js +1625 -0
  14. package/dist/execution/index.js.map +1 -0
  15. package/dist/index.d.ts +81 -11
  16. package/dist/index.js +7727 -6174
  17. package/dist/index.js.map +1 -1
  18. package/dist/infrastructure/index.d.ts +10 -0
  19. package/dist/infrastructure/index.js +575 -0
  20. package/dist/infrastructure/index.js.map +1 -0
  21. package/dist/input-reader-E-ffP2ee.d.ts +12 -0
  22. package/dist/kernel/index.d.ts +15 -4
  23. package/dist/kernel/index.js.map +1 -1
  24. package/dist/logger-BH6AE0W9.d.ts +24 -0
  25. package/dist/logger-BMQgxvdy.d.ts +12 -0
  26. package/dist/mcp-servers-BA1Ofmfj.d.ts +100 -0
  27. package/dist/memory-CEXuo7sz.d.ts +16 -0
  28. package/dist/mode-CV077NjV.d.ts +27 -0
  29. package/dist/models/index.d.ts +60 -0
  30. package/dist/models/index.js +621 -0
  31. package/dist/models/index.js.map +1 -0
  32. package/dist/models-registry-DqzwpBQy.d.ts +46 -0
  33. package/dist/models-registry-Y2xbog0E.d.ts +95 -0
  34. package/dist/multi-agent-BDfkxL5C.d.ts +351 -0
  35. package/dist/observability/index.d.ts +353 -0
  36. package/dist/observability/index.js +691 -0
  37. package/dist/observability/index.js.map +1 -0
  38. package/dist/observability-BhnVLBLS.d.ts +67 -0
  39. package/dist/path-resolver-CPRj4bFY.d.ts +10 -0
  40. package/dist/path-resolver-Crkt8wTQ.d.ts +54 -0
  41. package/dist/plugin-CoYYZKdn.d.ts +447 -0
  42. package/dist/renderer-0A2ZEtca.d.ts +158 -0
  43. package/dist/sdd/index.d.ts +206 -0
  44. package/dist/sdd/index.js +864 -0
  45. package/dist/sdd/index.js.map +1 -0
  46. package/dist/secret-scrubber-3TLUkiCV.d.ts +31 -0
  47. package/dist/secret-scrubber-CwYliRWd.d.ts +54 -0
  48. package/dist/secret-vault-DoISxaKO.d.ts +19 -0
  49. package/dist/security/index.d.ts +46 -0
  50. package/dist/security/index.js +536 -0
  51. package/dist/security/index.js.map +1 -0
  52. package/dist/selector-BRqzvugb.d.ts +51 -0
  53. package/dist/session-reader-C3x96CDR.d.ts +150 -0
  54. package/dist/skill-Bx8jxznf.d.ts +72 -0
  55. package/dist/storage/index.d.ts +540 -0
  56. package/dist/storage/index.js +1802 -0
  57. package/dist/storage/index.js.map +1 -0
  58. package/dist/{system-prompt-vAB0F54-.d.ts → system-prompt-CG9jU5-5.d.ts} +9 -1
  59. package/dist/task-graph-BITvWt4t.d.ts +160 -0
  60. package/dist/tool-executor-CYdZdtno.d.ts +97 -0
  61. package/dist/types/index.d.ts +26 -4
  62. package/dist/types/index.js +1787 -4
  63. package/dist/types/index.js.map +1 -1
  64. package/dist/utils/index.d.ts +49 -2
  65. package/dist/utils/index.js +100 -2
  66. package/dist/utils/index.js.map +1 -1
  67. package/package.json +34 -2
  68. package/dist/mode-Pjt5vMS6.d.ts +0 -815
  69. package/dist/session-reader-9sOTgmeC.d.ts +0 -1087
@@ -1,2309 +1,34 @@
1
- import { g as Logger, f as LogLevel, P as PathResolver, r as ModelsRegistry, O as EventBus, z as ResolvedModel, j as MemoryStore, i as MemoryScope, S as SecretScrubber, t as PermissionPolicy, I as InputReader, s as PermissionDecision, B as RetryPolicy, E as ErrorHandler, a as Compactor, R as RecoveryDecision, H as SkillLoader, J as SkillManifest, G as SkillEntry, b as Config, c as ConfigLoader, d as ConfigStore, C as CompactReport, a0 as MiddlewareHandler, p as ModelsDevPayload, A as ResolvedProvider, W as WireFamily, n as ModeStore, l as ModeConfig, k as Mode, M as MCPServerConfig } from '../mode-Pjt5vMS6.js';
2
- import { u as TokenCounter, U as Usage, C as CacheStats, p as SessionStore, o as SessionMetadata, r as SessionWriter, l as ResumedSession, S as SessionData, q as SessionSummary, c as ContentBlock, v as Tool, a0 as Context, i as ProviderError, h as Provider, M as Message, F as ToolUseBlock, B as ToolResultBlock, n as SessionEvent } from '../provider-txgB0Oq9.js';
3
- import { h as AttachmentStore, A as AddAttachmentInput, g as AttachmentRef, d as Attachment, S as SecretVault, x as MultiAgentCoordinator, w as MultiAgentConfig, a9 as SubagentRunner, a5 as SubagentConfig, X as SpawnResult, al as TaskSpec, B as BridgeMessage, a as AgentBridge, l as CoordinatorStatus, aj as TaskResult, aC as Agent, aE as AgentInput, j as BridgeTransport, b as AgentBridgeConfig, o as DoneCondition, aM as RunResult, a4 as Specification, Y as SpecAnalysis, a3 as SpecValidationResult, af as TaskGraph, ag as TaskNode, ae as TaskFilter, ak as TaskSort, ai as TaskProgress, an as TaskType, ah as TaskPriority, at as ToolExecutorOptions, au as ToolExecutorStrategy, ao as ToolBatchResult, O as SessionReader, n as DefaultSessionReaderOptions, N as SessionQuery, T as SessionSummaryLite, R as SessionSearchQuery, Q as SessionSearchHit, L as SessionExportOptions, u as MetricsSink, s as MetricLabels, v as MetricsSnapshot, q as HealthRegistry, H as HealthCheck, c as AggregateHealth, aw as Tracer, W as Span } from '../session-reader-9sOTgmeC.js';
4
- export { aG as BudgetExceededError, aH as BudgetKind, aI as BudgetLimits, aJ as BudgetUsage, aN as SubagentBudget } from '../session-reader-9sOTgmeC.js';
5
- import { a as WstackPaths } from '../wstack-paths-BGu2INTm.js';
6
- import { EventEmitter } from 'node:events';
7
-
8
- interface DefaultLoggerOptions {
9
- level?: LogLevel;
10
- file?: string;
11
- pretty?: boolean;
12
- bindings?: Record<string, unknown>;
13
- }
14
- declare class DefaultLogger implements Logger {
15
- level: LogLevel;
16
- private readonly file?;
17
- private readonly bindings;
18
- private readonly pretty;
19
- constructor(opts?: DefaultLoggerOptions);
20
- error(msg: string, ctx?: unknown): void;
21
- warn(msg: string, ctx?: unknown): void;
22
- info(msg: string, ctx?: unknown): void;
23
- debug(msg: string, ctx?: unknown): void;
24
- trace(msg: string, ctx?: unknown): void;
25
- child(bindings: Record<string, unknown>): Logger;
26
- private log;
27
- }
28
-
29
- declare class DefaultPathResolver implements PathResolver {
30
- readonly projectRoot: string;
31
- readonly cwd: string;
32
- constructor(cwd?: string);
33
- detectProjectRoot(start: string): string;
34
- resolve(input: string): string;
35
- isInsideRoot(absPath: string): boolean;
36
- ensureInsideRoot(absPath: string): string;
37
- }
38
-
39
- /**
40
- * Token counter that derives pricing from the ModelsRegistry instead of a
41
- * hardcoded table. If a model is unknown to the registry (or the registry is
42
- * unavailable) the counter still tracks token totals but reports zero cost.
43
- */
44
- declare class DefaultTokenCounter implements TokenCounter {
45
- private input;
46
- private output;
47
- private cacheRead;
48
- private cacheWrite;
49
- private costInput;
50
- private costOutput;
51
- private readonly registry?;
52
- private readonly providerId?;
53
- private readonly events?;
54
- private priceCache;
55
- constructor(opts?: {
56
- registry?: ModelsRegistry;
57
- providerId?: string;
58
- events?: EventBus;
59
- });
60
- account(usage: Usage, model?: string): void;
61
- /** Synchronous variant for code paths that have already resolved the model. */
62
- accountWithModel(usage: Usage, resolved: ResolvedModel): void;
63
- total(): Usage;
64
- estimateCost(): {
65
- input: number;
66
- output: number;
67
- total: number;
68
- currency: 'USD';
69
- };
70
- cacheStats(): CacheStats;
71
- /** Invalidate cached prices so the next account() call fetches fresh data. */
72
- invalidateCache(): void;
73
- reset(): void;
74
- private applyPrice;
75
- }
76
-
77
- interface SessionStoreOptions {
78
- dir: string;
79
- /** Optional EventBus for emitting session diagnostics. */
80
- events?: EventBus;
81
- }
82
- declare class DefaultSessionStore implements SessionStore {
83
- private readonly dir;
84
- private readonly events?;
85
- constructor(opts: SessionStoreOptions);
86
- create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter>;
87
- resume(id: string): Promise<ResumedSession>;
88
- load(id: string): Promise<SessionData>;
89
- list(limit?: number): Promise<SessionSummary[]>;
90
- private summaryFor;
91
- delete(id: string): Promise<void>;
92
- private summarize;
93
- private metaFromEvents;
94
- private replay;
95
- }
96
-
97
- /**
98
- * The persisted form of a single queued user message. The TUI's
99
- * in-memory QueueItem has a render id; that's pure UI bookkeeping, so
100
- * we drop it when serializing — fresh ids are assigned on rehydrate.
101
- */
102
- interface PersistedQueueItem {
103
- displayText: string;
104
- blocks: ContentBlock[];
105
- }
106
- /**
107
- * Side-file storage for a session's pending input queue. Lives at
108
- * `<sessionDir>/queue.json` next to the attachment spool. Reads are
109
- * tolerant (missing/malformed file → empty array); writes are atomic
110
- * (tmp + rename) so a crash mid-write can never leave a partial file
111
- * the next launch would choke on.
112
- *
113
- * The contract is "snapshot replacement": every mutation hands the
114
- * full queue and we rewrite the file. The queue is small (rarely more
115
- * than a handful of messages), so this is cheaper than delta logging
116
- * and avoids the replay complexity.
117
- */
118
- declare class QueueStore {
119
- private readonly file;
120
- constructor(opts: {
121
- dir: string;
122
- });
123
- write(items: PersistedQueueItem[]): Promise<void>;
124
- read(): Promise<PersistedQueueItem[]>;
125
- clear(): Promise<void>;
126
- }
127
-
128
- interface AttachmentStoreOptions {
129
- /**
130
- * Directory for spooling payloads larger than `spoolThresholdBytes`.
131
- * When omitted, all payloads stay in memory.
132
- */
133
- spoolDir?: string;
134
- spoolThresholdBytes?: number;
135
- }
136
- /**
137
- * In-memory attachment store with optional disk spool. Placeholder syntax
138
- * is `[<kind> #<seq>]` where kind is `pasted` / `image` / `file`. Unknown
139
- * placeholders are passed through as-is so users can write that literal
140
- * text without losing it.
141
- */
142
- declare class DefaultAttachmentStore implements AttachmentStore {
143
- private readonly items;
144
- private readonly refs;
145
- private nextSeq;
146
- private readonly spoolDir;
147
- private readonly spoolThreshold;
148
- constructor(opts?: AttachmentStoreOptions);
149
- add(input: AddAttachmentInput): Promise<AttachmentRef>;
150
- get(id: string): Promise<Attachment | undefined>;
151
- list(): AttachmentRef[];
152
- expand(text: string): Promise<ContentBlock[]>;
153
- clear(): Promise<void>;
154
- private toBlock;
155
- }
156
-
157
- interface MemoryStoreOptions {
158
- paths: WstackPaths;
159
- }
160
- /**
161
- * Three scopes:
162
- * project-agents → <project>/.wrongstack/AGENTS.md (committed)
163
- * project-memory → ~/.wrongstack/projects/<hash>/memory.md (per-project agent notes)
164
- * user-memory → ~/.wrongstack/memory.md (global personal memory)
165
- */
166
- declare class DefaultMemoryStore implements MemoryStore {
167
- private readonly files;
168
- /**
169
- * Per-scope serialization queue. `remember` / `forget` / `consolidate` /
170
- * `clear` are read-modify-write against a single file; without a lock,
171
- * two concurrent calls on the same scope can read the same baseline and
172
- * the later write silently drops the earlier entry. We chain each
173
- * mutation onto the prior promise for the same scope so they run in
174
- * issue order. Different scopes still proceed in parallel.
175
- */
176
- private readonly writeChain;
177
- constructor(opts: MemoryStoreOptions);
178
- private runSerialized;
179
- readAll(): Promise<string>;
180
- read(scope: MemoryScope): Promise<string>;
181
- remember(text: string, scope?: MemoryScope): Promise<void>;
182
- forget(query: string, scope?: MemoryScope): Promise<number>;
183
- private forgetUnsafe;
184
- consolidate(scope: MemoryScope): Promise<void>;
185
- private consolidateUnsafe;
186
- clear(scope?: MemoryScope): Promise<void>;
187
- }
188
-
189
- declare class DefaultSecretScrubber implements SecretScrubber {
190
- scrub(text: string): string;
191
- private scrubOne;
192
- scrubObject<T>(obj: T): T;
193
- }
194
-
195
- interface SecretVaultOptions {
196
- /** Absolute path to the key file. Created with mode 0o600 if missing. */
197
- keyFile: string;
198
- }
199
- /**
200
- * Default vault: AES-256-GCM with a key stored at `keyFile` (mode 0o600).
201
- * The key is loaded lazily on first encrypt/decrypt; if it does not exist,
202
- * a fresh one is generated. Decryption of plaintext values is a no-op so
203
- * legacy configs continue to work.
204
- */
205
- declare class DefaultSecretVault implements SecretVault {
206
- private readonly keyFile;
207
- private key?;
208
- constructor(opts: SecretVaultOptions);
209
- isEncrypted(value: string): boolean;
210
- encrypt(plaintext: string): string;
211
- decrypt(value: string): string;
212
- private loadOrCreateKey;
213
- }
214
- /**
215
- * Walk a Config-shaped object and decrypt any apiKey-like fields in place,
216
- * returning a new object. Used by the config loader so the rest of the
217
- * system never has to know about the wire format.
218
- */
219
- declare function decryptConfigSecrets<T>(cfg: T, vault: SecretVault): T;
220
- declare function encryptConfigSecrets<T>(cfg: T, vault: SecretVault): T;
221
- /**
222
- * Re-write `~/.wrongstack/config.json` (or any path) with all secret-bearing
223
- * fields encrypted. Used by the `wstack auth` subcommand.
224
- */
225
- declare function rewriteConfigEncrypted(configPath: string, vault: SecretVault, patch?: Record<string, unknown>): Promise<void>;
226
- /**
227
- * Scan a config file on disk for plaintext secret-bearing fields and
228
- * rewrite the file with them encrypted in place. Returns a count of how
229
- * many fields were migrated. Idempotent — calling on a fully-encrypted
230
- * file is a no-op and writes nothing. Used by the CLI on every boot so
231
- * users who had plaintext keys before the vault landed are upgraded
232
- * transparently.
233
- */
234
- declare function migratePlaintextSecrets(configPath: string, vault: SecretVault): Promise<{
235
- migrated: number;
236
- file: string;
237
- }>;
238
-
239
- interface PermissionPolicyOptions {
240
- trustFile: string;
241
- yolo?: boolean;
242
- promptDelegate?: (tool: Tool, input: unknown, suggestedPattern: string) => Promise<'yes' | 'no' | 'always' | 'deny'>;
243
- inputReader?: InputReader;
244
- }
245
- declare class DefaultPermissionPolicy implements PermissionPolicy {
246
- private policy;
247
- private loaded;
248
- private readonly trustFile;
249
- private readonly yolo;
250
- private readonly promptDelegate?;
251
- constructor(opts: PermissionPolicyOptions);
252
- reload(): Promise<void>;
253
- evaluate(tool: Tool, input: unknown, _ctx: Context): Promise<PermissionDecision>;
254
- trust(rule: {
255
- tool: string;
256
- pattern: string;
257
- }): Promise<void>;
258
- private subjectFor;
259
- private findNamespaceEntry;
260
- }
261
-
262
- declare class DefaultRetryPolicy implements RetryPolicy {
263
- private static readonly NETWORK_ERR_RE;
264
- shouldRetry(err: Error | ProviderError, attempt: number): boolean;
265
- maxAttempts(err: Error | ProviderError): number;
266
- delayMs(attempt: number): number;
267
- }
268
-
269
- /**
270
- * Tiered error recovery strategies.
271
- * Each strategy is attempted in order until one returns a decision.
272
- */
273
- interface RecoveryStrategy {
274
- /** Human-readable label for logs. */
275
- label: string;
276
- /** Optional compactor for context_overflow recovery. */
277
- compactor?: Compactor;
278
- /** Returns an explicit recovery decision, or null to fall through. */
279
- attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;
280
- }
281
- declare class DefaultErrorHandler implements ErrorHandler {
282
- private readonly strategies;
283
- constructor(strategies?: RecoveryStrategy[]);
284
- classify(err: unknown): {
285
- kind: 'rate_limit' | 'overloaded' | 'server' | 'client' | 'network' | 'abort' | 'context_overflow' | 'unknown';
286
- retryable: boolean;
287
- };
288
- recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null>;
289
- }
290
-
291
- interface SkillLoaderOptions {
292
- paths: WstackPaths;
293
- bundledDir?: string;
294
- }
295
- /**
296
- * Discovery order (later layers shadow earlier ones at boot, but we walk
297
- * highest priority first and skip names already seen):
298
- * 1. Project-committed: <project>/.wrongstack/skills/
299
- * 2. User-global: ~/.wrongstack/skills/
300
- * 3. Bundled with build: packages/core/skills/
301
- */
302
- declare class DefaultSkillLoader implements SkillLoader {
303
- private readonly dirs;
304
- private cache?;
305
- constructor(opts: SkillLoaderOptions);
306
- list(): Promise<SkillManifest[]>;
307
- find(name: string): Promise<SkillManifest | undefined>;
308
- manifestText(): Promise<string>;
309
- listEntries(): Promise<SkillEntry[]>;
310
- readBody(name: string): Promise<string>;
311
- }
312
-
313
- /**
314
- * A single config source. Higher priority wins in merges.
315
- * Sources are applied in priority order (lowest first), so a source
316
- * with priority=10 overrides one with priority=1.
317
- */
318
- interface ConfigSource {
319
- /** Unique name for debugging and error messages. */
320
- name: string;
321
- /** Lower numbers merge first, higher numbers override lower. Default: 50. */
322
- priority?: number;
323
- /**
324
- * Read the raw config patch. Return an empty object if unavailable.
325
- * Errors are surfaced but do not abort loading — the source is skipped.
326
- */
327
- read(): Promise<Partial<Config>>;
328
- }
329
- interface ConfigLoaderOptions {
330
- paths: WstackPaths;
331
- strict?: boolean;
332
- vault?: SecretVault;
333
- /** Extra sources merged after the built-in layers. */
334
- sources?: ConfigSource[];
335
- }
336
- declare class DefaultConfigLoader implements ConfigLoader {
337
- private readonly paths;
338
- private readonly strict;
339
- private readonly vault;
340
- private readonly extraSources;
341
- constructor(opts: ConfigLoaderOptions);
342
- load(opts?: {
343
- cliFlags?: Partial<Config>;
344
- cwd?: string;
345
- }): Promise<Config>;
346
- private readJson;
347
- private validateBehavior;
348
- private validateIdentity;
349
- }
350
-
351
- /**
352
- * Reference implementation of `ConfigStore`. Stores a single frozen Config
353
- * and notifies watchers synchronously on every update. Updates use a deep
354
- * clone so callers can mutate their `partial` argument freely without
355
- * tainting state.
356
- *
357
- * For the CLI: instantiate once at boot, pass the store (not the Config)
358
- * to subsystems that care about runtime changes (provider switching,
359
- * extension reload).
360
- */
361
- declare class DefaultConfigStore implements ConfigStore {
362
- private current;
363
- private watchers;
364
- constructor(initial: Config);
365
- get(): Readonly<Config>;
366
- getSection<K extends keyof Config>(key: K): Readonly<Config[K]>;
367
- getExtension(pluginName: string): Readonly<Record<string, unknown>>;
368
- update(partial: Partial<Config>): Readonly<Config>;
369
- watch(cb: (next: Readonly<Config>, prev: Readonly<Config>) => void): () => void;
370
- }
371
-
372
- /**
373
- * L2-D: Config version migration framework. Pure functions, decoupled
374
- * from disk/CLI — caller passes a parsed JSON object and gets back the
375
- * up-to-date `Config` shape (or a structured error explaining why
376
- * migration failed).
377
- *
378
- * Migrations are registered as `{ from, to, migrate }` triples and run
379
- * sequentially. Each migration is independently testable. Adding a new
380
- * version means appending one migration; existing user configs are
381
- * upgraded in place at load time.
382
- */
383
- interface MigrationContext {
384
- /**
385
- * Original on-disk version of the input. Migrations may use this to
386
- * decide between in-place patches and rewrites.
387
- */
388
- fromVersion: number;
389
- /**
390
- * Set when the migration writes back to disk. Callers persist the
391
- * migrated config when this is true so the user doesn't see the same
392
- * migration banner on every boot.
393
- */
394
- shouldPersist: boolean;
395
- }
396
- interface ConfigMigration {
397
- /** Version of the input this migration accepts. */
398
- from: number;
399
- /** Version of the output it produces. */
400
- to: number;
401
- /** Pure transform — no I/O. */
402
- migrate(input: Record<string, unknown>, ctx: MigrationContext): Record<string, unknown>;
403
- /** Optional human-readable description for migration logs / banners. */
404
- describe?: string;
405
- }
406
- interface MigrationResult {
407
- /** Final config (still typed as `unknown`-keyed — caller validates). */
408
- config: Record<string, unknown>;
409
- /** Ordered list of `from→to` versions that ran. */
410
- applied: string[];
411
- /** True when at least one migration produced changes worth persisting. */
412
- shouldPersist: boolean;
413
- }
414
- declare class ConfigMigrationError extends Error {
415
- readonly fromVersion: number;
416
- readonly targetVersion: number;
417
- readonly missingStep: number | null;
418
- constructor(opts: {
419
- message: string;
420
- fromVersion: number;
421
- targetVersion: number;
422
- missingStep: number | null;
423
- });
424
- }
425
- /**
426
- * Run registered migrations until the input reaches `targetVersion`.
427
- *
428
- * Resolution rules:
429
- * 1. If `input.version === targetVersion`, no migrations run; `shouldPersist`
430
- * is false.
431
- * 2. Otherwise walk the migration chain from `input.version` upward,
432
- * picking the migration whose `from` matches the current version.
433
- * 3. Stop when `current.version === targetVersion`.
434
- * 4. If no migration matches at some point, throw `ConfigMigrationError`
435
- * with the missing step recorded for diagnostics.
436
- *
437
- * Migrations may be downward (e.g. for staged rollouts), but `targetVersion`
438
- * must be reachable strictly via the registered chain — there's no implicit
439
- * "skip" or transitive resolution.
440
- */
441
- declare function runConfigMigrations(input: Record<string, unknown>, targetVersion: number, migrations: readonly ConfigMigration[]): MigrationResult;
442
- /**
443
- * Default empty migration registry. Real migrations are appended as new
444
- * Config versions are introduced. Example (when v2 lands):
445
- *
446
- * export const CONFIG_MIGRATIONS: readonly ConfigMigration[] = [
447
- * {
448
- * from: 1, to: 2, describe: 'rename `apiKey` → `auth.apiKey`',
449
- * migrate(cfg) {
450
- * const apiKey = cfg.apiKey;
451
- * delete cfg.apiKey;
452
- * return { ...cfg, auth: { ...(cfg.auth ?? {}), apiKey } };
453
- * },
454
- * },
455
- * ];
456
- */
457
- declare const DEFAULT_CONFIG_MIGRATIONS: readonly ConfigMigration[];
458
-
459
- interface CompactorOptions {
460
- preserveK?: number;
461
- eliseThreshold?: number;
462
- estimator?: (text: string) => number;
463
- }
464
- declare class HybridCompactor implements Compactor {
465
- private readonly preserveK;
466
- private readonly eliseThreshold;
467
- private readonly estimator;
468
- constructor(opts?: CompactorOptions);
469
- compact(ctx: Context, opts?: {
470
- aggressive?: boolean;
471
- }): Promise<CompactReport>;
472
- private eliseOldToolResults;
473
- private collapseAncientTurns;
474
- private estimateMessages;
475
- }
476
-
477
- /**
478
- * Options for IntelligentCompactor.
479
- */
480
- interface IntelligentCompactorOptions {
481
- /** Provider to use for LLM-assisted summarization. Required. */
482
- provider: Provider;
483
- /** Fraction of maxContext that triggers a warning (default 0.6). */
484
- warnThreshold?: number;
485
- /** Fraction of maxContext that triggers soft compaction (default 0.75). */
486
- softThreshold?: number;
487
- /** Fraction of maxContext that triggers hard compaction (default 0.9). */
488
- hardThreshold?: number;
489
- /** Max context window in tokens (used only for threshold fraction math). */
490
- maxContext?: number;
491
- /** How many recent (user+assistant) pairs to always preserve (default 4). */
492
- preserveK?: number;
493
- /** Token threshold below which tool results are not elided (default 500). */
494
- eliseThreshold?: number;
495
- /** System prompt for the summarizer sub-LLM. */
496
- summarizerPrompt?: string;
497
- /**
498
- * Model ID to use for summarization. When not set, the same model as the
499
- * agent is used (which risks cascading failure on context overflow). Set to
500
- * a fast/cheap model like `claude-3-5-haiku-20240620` for resilience.
501
- */
502
- summarizerModel?: string;
503
- }
504
- /**
505
- * IntelligentCompactor uses an LLM to:
506
- * - Analyze message importance and preserve critical context
507
- * - Generate semantic summaries for old message ranges
508
- * - Make intelligent decisions about what to compact
509
- *
510
- * It extends HybridCompactor's elision logic with LLM-assisted summarization.
511
- */
512
- declare class IntelligentCompactor implements Compactor {
513
- private readonly provider;
514
- private readonly warnThreshold;
515
- private readonly softThreshold;
516
- private readonly hardThreshold;
517
- private readonly maxContext;
518
- private readonly preserveK;
519
- private readonly eliseThreshold;
520
- private readonly summarizerPrompt;
521
- private readonly summarizerModel?;
522
- constructor(opts: IntelligentCompactorOptions);
523
- compact(ctx: Context, opts?: {
524
- aggressive?: boolean;
525
- }): Promise<CompactReport>;
526
- private summarizeAncientTurns;
527
- private findSafeBoundary;
528
- private findExchangeStart;
529
- private callSummarizer;
530
- private messagesToText;
531
- private lightweightCompact;
532
- private eliseOldToolResults;
533
- private hasTextContent;
534
- private estimateTokens;
535
- }
536
-
537
- /**
538
- * Result of LLM-driven message importance analysis.
539
- * The selector marks each message range with an importance tier,
540
- * and optionally provides a natural-language summary for collapsed ranges.
541
- */
542
- interface SelectorResult {
543
- /**
544
- * Ordered list of kept message ranges. Each entry describes a
545
- * message range that should be preserved verbatim in the context.
546
- */
547
- kept: Array<{
548
- from: number;
549
- to: number;
550
- importance: 'critical' | 'high' | 'medium';
551
- }>;
552
- /**
553
- * Collapsed ranges — either replaced by the compactor or omitted.
554
- * Each entry may carry a summary text produced by the LLM.
555
- */
556
- collapsed: Array<{
557
- from: number;
558
- to: number;
559
- summary?: string;
560
- }>;
561
- /**
562
- * Raw reasoning from the selector LLM (for debugging / audit).
563
- */
564
- reasoning: string;
565
- }
566
- /**
567
- * Message selector that uses an LLM to decide which message ranges
568
- * to keep vs collapse/summarize. The selector runs as a separate API
569
- * call before compaction, making it more surgical than fixed-window
570
- * or rules-based approaches.
571
- */
572
- interface MessageSelector {
573
- /**
574
- * Analyze `messages` and return a structured plan for what to keep
575
- * vs collapse. May modify the messages array in-place if needed,
576
- * or return a plan that the caller (Compactor) executes.
577
- *
578
- * @param messages Current message history (may be modified in-place)
579
- * @param maxToKeep Token budget — selector should aim to keep total
580
- * retained message content under this threshold
581
- */
582
- select(messages: Message[], maxToKeep: number): Promise<SelectorResult>;
583
- }
584
-
585
- /**
586
- * Options for SelectiveCompactor — the most configurable compactor.
587
- */
588
- interface SelectiveCompactorOptions {
589
- /** Provider for LLM calls (selector + summarizer). Required. */
590
- provider: Provider;
591
- /** Selector for LLM-driven importance analysis. */
592
- selector?: MessageSelector;
593
- /** Fraction of maxContext that triggers a warning (default 0.6). */
594
- warnThreshold?: number;
595
- /** Fraction of maxContext that triggers soft compaction (default 0.75). */
596
- softThreshold?: number;
597
- /** Fraction of maxContext that triggers hard compaction (default 0.9). */
598
- hardThreshold?: number;
599
- /** Max context window in tokens (used for threshold fraction math). */
600
- maxContext?: number;
601
- /** How many recent (user+assistant) pairs to always preserve (default 4). */
602
- preserveK?: number;
603
- /** Token threshold below which tool results are not elided (default 500). */
604
- eliseThreshold?: number;
605
- /** Model for selector LLM calls (default: same as provider default). */
606
- selectorModel?: string;
607
- /** Summarizer model for collapsed ranges (default: same as selectorModel). */
608
- summarizerModel?: string;
609
- /** Prompt for the summarizer sub-LLM. */
610
- summarizerPrompt?: string;
611
- }
612
- /**
613
- * SelectiveCompactor uses an LLM-driven MessageSelector to make
614
- * surgical decisions about which message ranges to keep vs collapse.
615
- *
616
- * Compared to HybridCompactor / IntelligentCompactor:
617
- * - HybridCompactor: rule-based (preserveK + elision), no LLM calls
618
- * - IntelligentCompactor: LLM summarization but no structured selection
619
- * - SelectiveCompactor: full LLM-driven selection + optional summarization
620
- */
621
- declare class SelectiveCompactor implements Compactor {
622
- private readonly provider;
623
- private readonly selector;
624
- private readonly warnThreshold;
625
- private readonly softThreshold;
626
- private readonly hardThreshold;
627
- private readonly maxContext;
628
- private readonly preserveK;
629
- private readonly eliseThreshold;
630
- private readonly summarizerModel;
631
- private readonly summarizerPrompt;
632
- constructor(opts: SelectiveCompactorOptions);
633
- compact(ctx: Context, opts?: {
634
- aggressive?: boolean;
635
- }): Promise<CompactReport>;
636
- /**
637
- * Run the LLM selector to decide what to keep vs collapse.
638
- * Returns the token savings achieved.
639
- */
640
- private runSelector;
641
- /**
642
- * Execute a SelectorResult plan: collapse/remove ranges and
643
- * insert summaries where the selector provided them.
644
- */
645
- private executePlan;
646
- private summarizeRange;
647
- private messagePreview;
648
- /**
649
- * Fallback when selector fails: aggressively trim from the oldest end
650
- * until we hit targetBudget.
651
- */
652
- private aggressiveRecencyTrim;
653
- private computeTargetBudget;
654
- private eliseOldToolResults;
655
- private hasTextContent;
656
- private estimateTokens;
657
- private roughTokenEstimate;
658
- }
659
-
660
- interface LLMSelectorOptions {
661
- /** Provider used for the selector LLM call. Required. */
662
- provider: Provider;
663
- /** Model for the selector. Defaults to the provider's default model. */
664
- model?: string;
665
- /**
666
- * Maximum tokens to keep in context (target budget).
667
- * Selector will aim to keep total content below this.
668
- */
669
- maxContextTokens?: number;
670
- /**
671
- * Prompt instructing the selector how to behave.
672
- * Should guide the LLM on importance tiers and output format.
673
- */
674
- systemPrompt?: string;
675
- }
676
- /**
677
- * LLM-powered message selector. Calls a sub-LLM to analyze the
678
- * message history and produce a keep/collapse plan — more surgical
679
- * than fixed-window rules.
680
- */
681
- declare class LLMSelector implements MessageSelector {
682
- private readonly provider;
683
- private readonly model;
684
- private readonly maxContextTokens;
685
- private readonly systemPrompt;
686
- constructor(opts: LLMSelectorOptions);
687
- select(messages: Message[], maxToKeep: number): Promise<SelectorResult>;
688
- private fallbackSelect;
689
- private parseSelectorOutput;
690
- }
691
-
692
- type CompactionFailureMode = 'throw' | 'throw_on_hard' | 'continue';
693
- interface AutoCompactionOptions {
694
- aggressiveOn?: 'hard' | 'soft' | 'warn';
695
- events?: EventBus;
696
- failureMode?: CompactionFailureMode;
697
- }
698
- /**
699
- * Pipeline middleware that monitors context token load and automatically
700
- * triggers compaction when the warn/soft/hard thresholds are crossed.
701
- * Runs before the next agent iteration.
702
- */
703
- declare class AutoCompactionMiddleware {
704
- readonly name = "AutoCompaction";
705
- private readonly compactor;
706
- private readonly warnThreshold;
707
- private readonly softThreshold;
708
- private readonly hardThreshold;
709
- private readonly maxContext;
710
- private readonly estimator;
711
- private readonly aggressiveOn;
712
- private readonly events?;
713
- private readonly failureMode;
714
- /**
715
- * @param compactor Compactor to use for compaction.
716
- * @param maxContext Provider's max context window in tokens.
717
- * @param estimator Token estimation function.
718
- * @param thresholds Threshold fractions (0-1) of maxContext.
719
- * @param opts Optional behavior. By default, failures at the
720
- * hard threshold throw AGENT_CONTEXT_OVERFLOW so
721
- * the agent does not continue into a likely
722
- * provider context overflow. Warn/soft failures
723
- * still emit compaction.failed and continue.
724
- */
725
- constructor(compactor: Compactor, maxContext: number, estimator: (ctx: Context) => number, thresholds: {
726
- warn: number;
727
- soft: number;
728
- hard: number;
729
- }, optsOrAggressiveOn?: AutoCompactionOptions | 'hard' | 'soft' | 'warn', events?: EventBus);
730
- handler(): MiddlewareHandler<Context>;
731
- private compact;
732
- }
733
-
734
- interface DefaultModelsRegistryOptions {
735
- cacheFile: string;
736
- url?: string;
737
- ttlSeconds?: number;
738
- fetchImpl?: typeof fetch;
739
- /** Pre-seeded payload — useful for offline scenarios and tests. */
740
- seed?: ModelsDevPayload;
741
- /**
742
- * Maximum age in seconds for stale cache fallback when network fails.
743
- * Defaults to 7 days. Set to `Infinity` for full offline resilience
744
- * (risk: deprecated models, wrong pricing). Set to `0` to disable
745
- * stale fallback entirely.
746
- */
747
- maxStaleAgeSeconds?: number;
748
- }
749
- declare function classifyFamily(npm: string | undefined): WireFamily;
750
- declare class DefaultModelsRegistry implements ModelsRegistry {
751
- private payload?;
752
- private fetchedAt?;
753
- private readonly cacheFile;
754
- private readonly url;
755
- private readonly ttlMs;
756
- private readonly fetchImpl;
757
- private readonly seed?;
758
- private readonly maxStaleAgeMs;
759
- constructor(opts: DefaultModelsRegistryOptions);
760
- load(opts?: {
761
- force?: boolean;
762
- }): Promise<ModelsDevPayload>;
763
- refresh(): Promise<ModelsDevPayload>;
764
- listProviders(): Promise<ResolvedProvider[]>;
765
- getProvider(id: string): Promise<ResolvedProvider | undefined>;
766
- getModel(providerId: string, modelId: string): Promise<ResolvedModel | undefined>;
767
- suggestModel(providerId: string): Promise<string | undefined>;
768
- ageSeconds(): Promise<number>;
769
- private resolveProvider;
770
- private isFresh;
771
- private isWithinMaxStaleAge;
772
- private readCache;
773
- /** Used by `wstack models refresh` to expose where the cache lives. */
774
- cacheLocation(): string;
775
- }
776
-
777
- declare class DefaultModeStore implements ModeStore {
778
- private activeModeId;
779
- private modes;
780
- private configDir;
781
- constructor(config: ModeConfig);
782
- getActiveMode(): Promise<Mode | null>;
783
- setActiveMode(modeId: string | null): Promise<void>;
784
- listModes(): Promise<Mode[]>;
785
- getMode(modeId: string): Promise<Mode | null>;
786
- addMode(mode: Mode): Promise<void>;
787
- removeMode(modeId: string): Promise<void>;
788
- private loadActiveMode;
789
- private saveActiveMode;
790
- }
791
- interface ModeLoaderOptions {
792
- projectModesDir?: string;
793
- userModesDir?: string;
794
- }
795
- declare function loadProjectModes(modesDir: string): Promise<Mode[]>;
796
- declare function loadUserModes(modesDir: string): Promise<Mode[]>;
797
-
798
- interface MultiAgentCoordinatorOptions {
799
- /**
800
- * Callback that executes a task on behalf of a subagent. Required for
801
- * `assign()` to actually run anything — without it, tasks queue forever.
802
- * The coordinator provides per-subagent isolation (own budget, own signal,
803
- * own bridge) and enforces timeout + concurrency.
804
- */
805
- runner?: SubagentRunner;
806
- }
807
- declare class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {
808
- readonly coordinatorId: string;
809
- readonly config: MultiAgentConfig;
810
- private readonly runner?;
811
- private readonly subagents;
812
- private pendingTasks;
813
- private completedResults;
814
- private totalIterations;
815
- private inFlight;
816
- constructor(config: MultiAgentConfig, options?: MultiAgentCoordinatorOptions);
817
- spawn(subagent: SubagentConfig): Promise<SpawnResult>;
818
- assign(task: TaskSpec): Promise<void>;
819
- delegate(to: string, msg: BridgeMessage): Promise<void>;
820
- /**
821
- * Wire up the communication bridge for a subagent. Call after spawn() once
822
- * the caller has created the bidirectional connection.
823
- */
824
- setSubagentBridge(subagentId: string, bridge: AgentBridge): void;
825
- stop(subagentId: string): Promise<void>;
826
- stopAll(): Promise<void>;
827
- getStatus(): CoordinatorStatus;
828
- /** Expose snapshot of completed results — useful for callers awaiting all done. */
829
- results(): readonly TaskResult[];
830
- /**
831
- * Manual completion — for callers that drive subagents without a runner
832
- * (e.g. external orchestrators). When a runner is configured the coordinator
833
- * calls this itself.
834
- */
835
- completeTask(result: TaskResult): void;
836
- private tryDispatchNext;
837
- private canDispatch;
838
- private findIdleSubagent;
839
- private runDispatched;
840
- private executeWithTimeout;
841
- private recordCompletion;
842
- private isDone;
843
- }
844
-
845
- /**
846
- * Caller-supplied factory that builds an isolated `Agent` for a subagent.
847
- * The factory MUST construct a fresh `Context` per call — sharing context
848
- * between subagents defeats isolation. Each Agent should also use either
849
- * its own `EventBus` or a forwarded view, so per-subagent metrics can be
850
- * attributed correctly.
851
- */
852
- type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;
853
- interface AgentFactoryResult {
854
- agent: Agent;
855
- /** Event bus the factory wired to this agent — required for budget hookup. */
856
- events: EventBus;
857
- }
858
- interface AgentRunnerOptions {
859
- factory: AgentFactory;
860
- /**
861
- * Format a TaskSpec into the user input the agent will receive. Defaults
862
- * to `task.description ?? ''`. Override when subagents expect structured
863
- * input (e.g. JSON contracts, role-prefixed prompts).
864
- */
865
- formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;
866
- }
867
- /**
868
- * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring
869
- * the coordinator's budget and abort signal. This is the production adapter —
870
- * the coordinator's `runner` option in CLI/TUI assemblies points here.
871
- *
872
- * Lifecycle per task:
873
- * 1. factory(config) → fresh Agent + EventBus.
874
- * 2. Subscribe to events to feed the budget (tool calls, token usage).
875
- * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.
876
- * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.
877
- * 5. Unsubscribe and let the factory's resources be GC'd.
878
- *
879
- * The budget is checked synchronously from event handlers — a runaway agent
880
- * that crosses its tool-call limit triggers `BudgetExceededError`, which the
881
- * coordinator surfaces as `status: 'failed'` on the task result.
882
- */
883
- declare function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner;
884
-
885
- /**
886
- * Single fleet-wide event with subagent attribution. Whatever a child
887
- * agent emits on its own EventBus gets re-published here, prefixed with
888
- * `subagentId` so a single subscriber can multiplex across the fleet.
889
- *
890
- * The director uses `FleetBus.filter('tool.executed', …)` to see every
891
- * tool call across the fleet; the TUI uses
892
- * `FleetBus.subscribe(id, handler)` to render a per-subagent panel.
893
- */
894
- interface FleetEvent {
895
- subagentId: string;
896
- taskId?: string;
897
- ts: number;
898
- type: string;
899
- payload: unknown;
900
- }
901
- type FleetHandler = (event: FleetEvent) => void;
902
- /**
903
- * Fan-in for per-subagent EventBuses. Each subagent's bus is plugged in
904
- * via `attach()`; the FleetBus re-emits every event with subagent
905
- * attribution. Detachment is automatic via the returned disposer — call
906
- * it when a subagent terminates so we don't leak listeners.
907
- *
908
- * The bus exposes two subscription modes: by `subagentId` (everything
909
- * from one child) and by `type` (one event-type across the fleet). They
910
- * compose — if you need a per-subagent + per-type slice, subscribe by
911
- * type and filter on `event.subagentId` in your handler.
912
- */
913
- declare class FleetBus {
914
- private readonly byId;
915
- private readonly byType;
916
- private readonly any;
917
- /**
918
- * Hook a subagent's EventBus into the fleet. EventBus is strongly
919
- * typed and doesn't expose an `onAny` hook, so we subscribe to the
920
- * canonical set of event types a subagent emits during a run. New
921
- * event types added to the kernel must be added here too — but the
922
- * cost is a tiny single line per type, and the explicit list keeps
923
- * the wire format clear.
924
- *
925
- * Returns a disposer that detaches every subscription; call on
926
- * subagent teardown so the listeners don't outlive the run.
927
- */
928
- attach(subagentId: string, bus: EventBus, taskId?: string): () => void;
929
- /** Subscribe to every event from one subagent. */
930
- subscribe(subagentId: string, handler: FleetHandler): () => void;
931
- /** Subscribe to one event type across all subagents. */
932
- filter(type: string, handler: FleetHandler): () => void;
933
- /** Subscribe to literally everything. The fleet roll-up uses this. */
934
- onAny(handler: FleetHandler): () => void;
935
- emit(event: FleetEvent): void;
936
- }
937
- /**
938
- * Roll-up of token usage + cost across an entire director run. The
939
- * director's `fleet_status` tool returns this so the model can reason
940
- * about budget in its next turn ("the researcher already burned $0.40,
941
- * lean on summaries for the next task").
942
- */
943
- interface FleetUsage {
944
- total: {
945
- input: number;
946
- output: number;
947
- cacheRead: number;
948
- cacheWrite: number;
949
- cost: number;
950
- };
951
- perSubagent: Record<string, SubagentUsageSnapshot>;
952
- }
953
- interface SubagentUsageSnapshot {
954
- subagentId: string;
955
- provider?: string;
956
- model?: string;
957
- input: number;
958
- output: number;
959
- cacheRead: number;
960
- cacheWrite: number;
961
- cost: number;
962
- toolCalls: number;
963
- iterations: number;
964
- startedAt: number;
965
- lastEventAt: number;
966
- }
967
- /**
968
- * Aggregates provider.response + tool.executed events from the FleetBus
969
- * into a live `FleetUsage` snapshot. Costs are computed by the caller
970
- * via a `priceLookup(subagentId)` so we don't bake provider-pricing
971
- * coupling into core; the CLI/tests supply a function that resolves
972
- * each subagent's per-token rates from the models registry.
973
- */
974
- declare class FleetUsageAggregator {
975
- private readonly bus;
976
- private readonly priceLookup?;
977
- private readonly metaLookup?;
978
- private readonly perSubagent;
979
- private readonly total;
980
- constructor(bus: FleetBus, priceLookup?: ((subagentId: string) => {
981
- input?: number;
982
- output?: number;
983
- cacheRead?: number;
984
- cacheWrite?: number;
985
- } | undefined) | undefined, metaLookup?: ((subagentId: string) => {
986
- provider?: string;
987
- model?: string;
988
- } | undefined) | undefined);
989
- /** Live snapshot — safe to call from a tool's execute() body. */
990
- snapshot(): FleetUsage;
991
- private ensure;
992
- private onProviderResponse;
993
- private onToolExecuted;
994
- private onIterationStarted;
995
- }
996
-
997
- /**
998
- * In-memory pub/sub transport for agent-to-agent messaging.
999
- * Subscribers register by agentId and receive messages via callback.
1000
- */
1001
- declare class InMemoryBridgeTransport implements BridgeTransport {
1002
- private readonly subs;
1003
- send(msg: BridgeMessage, to: string): Promise<void>;
1004
- subscribe(agentId: string, handler: (msg: BridgeMessage) => void): () => void;
1005
- close(agentId: string): Promise<void>;
1006
- }
1007
-
1008
- declare class InMemoryAgentBridge implements AgentBridge {
1009
- readonly agentId: string;
1010
- readonly coordinatorId: string;
1011
- private readonly transport;
1012
- private readonly subscriptions;
1013
- private pendingRequests;
1014
- private stopped;
1015
- private timeoutMs;
1016
- constructor(config: AgentBridgeConfig, transport: BridgeTransport);
1017
- send(msg: BridgeMessage): Promise<void>;
1018
- broadcast(msg: BridgeMessage): Promise<void>;
1019
- subscribe(handler: (msg: BridgeMessage) => void | Promise<void>): () => void;
1020
- request<T>(msg: BridgeMessage, timeoutMs?: number): Promise<BridgeMessage<T>>;
1021
- stop(): Promise<void>;
1022
- }
1023
- declare function createMessage<T = unknown>(type: BridgeMessage['type'], from: string, payload: T, to?: string): BridgeMessage<T>;
1024
-
1025
- /**
1026
- * Director — high-level orchestrator that owns a `MultiAgentCoordinator`,
1027
- * a `FleetBus`, and a `FleetUsageAggregator`. Exposes a small imperative
1028
- * API (`spawn`, `assign`, `awaitTasks`, `terminate`, `status`, `usage`)
1029
- * that's easy to test, and a `tools()` factory that wraps the same API
1030
- * as agent-callable `Tool`s so an LLM can drive the orchestration.
1031
- *
1032
- * This class is intentionally *not* an `Agent`. It's a coordinator +
1033
- * observability surface. To make it LLM-driven, construct an Agent
1034
- * with `director.tools()` registered. That keeps the construction
1035
- * symmetric with how other agents are built and avoids smuggling a
1036
- * heavy LLM dependency into core just for the director path.
1037
- */
1038
- interface DirectorOptions {
1039
- config: MultiAgentConfig;
1040
- runner?: SubagentRunner;
1041
- /**
1042
- * When set, the director writes a `fleet.json` manifest to this path
1043
- * recording every spawned subagent (id, provider, model, role, task
1044
- * ids). Used by `wstack replay <runId>` to rehydrate a fleet. Pass an
1045
- * absolute file path — the directory must already exist (the
1046
- * director-session factory creates it when used together).
1047
- */
1048
- manifestPath?: string;
1049
- /**
1050
- * Optional roster used by `leaderSystemPrompt()` to render a roles
1051
- * summary into the leader's preamble. Same shape as the roster passed
1052
- * to `tools()` — typically the same value.
1053
- */
1054
- roster?: Record<string, SubagentConfig>;
1055
- /**
1056
- * Override the built-in fleet preamble (see `DEFAULT_DIRECTOR_PREAMBLE`).
1057
- * Pass an empty string to suppress the preamble entirely.
1058
- */
1059
- directorPreamble?: string;
1060
- /**
1061
- * Override the built-in subagent baseline (see
1062
- * `DEFAULT_SUBAGENT_BASELINE`). Pass an empty string to suppress.
1063
- */
1064
- subagentBaseline?: string;
1065
- /**
1066
- * Absolute path to a directory the fleet can use as a shared scratchpad
1067
- * (read + write by every subagent). When set, the director creates it on
1068
- * construction and `subagentSystemPrompt()` automatically injects a
1069
- * "Shared notes" block telling subagents where to drop their findings.
1070
- * This is the cheap fleet-coordination channel — agents don't need each
1071
- * other's transcripts, just each other's conclusions.
1072
- *
1073
- * Convention: under a fleet run rooted at `<sessionsRoot>/<runId>/`,
1074
- * pass `<sessionsRoot>/<runId>/shared/` here.
1075
- */
1076
- sharedScratchpadPath?: string;
1077
- /**
1078
- * Maximum number of spawns this director can perform across its
1079
- * lifetime. Default: unlimited. Acts as a hard fleet-wide cost cap —
1080
- * a runaway leader that keeps spawning workers gets cut off cleanly
1081
- * instead of burning provider tokens until the user kills the
1082
- * process. The N+1-th spawn call rejects with a `DirectorBudgetError`.
1083
- */
1084
- maxSpawns?: number;
1085
- /**
1086
- * Maximum nesting depth for spawns. The director constructed by the
1087
- * user is at depth `spawnDepth` (default 0); any subagent that itself
1088
- * acts as a director would construct its own `Director` with
1089
- * `spawnDepth: parent.spawnDepth + 1`. When `spawnDepth >= maxSpawnDepth`,
1090
- * `spawn()` rejects. Default: 2 (root director can spawn workers; a
1091
- * worker that becomes a sub-director cannot itself spawn further).
1092
- * This stops infinite recursive director chains from a hostile or
1093
- * confused prompt.
1094
- */
1095
- maxSpawnDepth?: number;
1096
- /**
1097
- * Current spawn-chain depth for this director instance. Defaults to 0.
1098
- * A nested director should pass `parent.spawnDepth + 1`. Together with
1099
- * `maxSpawnDepth` this bounds the chain.
1100
- */
1101
- spawnDepth?: number;
1102
- }
1103
- /**
1104
- * Thrown by `Director.spawn()` when a configured spawn cap (`maxSpawns`,
1105
- * `maxSpawnDepth`) is hit. Distinct error class so callers — including
1106
- * the `spawn_subagent` tool surface — can recognize the budget case and
1107
- * report it cleanly instead of treating it like an unexpected failure.
1108
- */
1109
- declare class DirectorBudgetError extends Error {
1110
- readonly kind: 'max_spawns' | 'max_spawn_depth';
1111
- readonly limit: number;
1112
- readonly observed: number;
1113
- constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number);
1114
- }
1115
- declare class Director {
1116
- readonly id: string;
1117
- readonly fleet: FleetBus;
1118
- readonly usage: FleetUsageAggregator;
1119
- /**
1120
- * Director-side bridge endpoint. Subagents are wired to the same
1121
- * in-memory transport so the director can `ask()` them synchronously
1122
- * and they can `send()` progress back. Exposed so external code (e.g.
1123
- * the TUI) can subscribe to inbound messages.
1124
- */
1125
- readonly bridge: InMemoryAgentBridge;
1126
- private readonly transport;
1127
- private readonly coordinator;
1128
- /** Resolves with the matching `TaskResult` the first time the
1129
- * coordinator emits `task.completed` for a given task id. Each entry
1130
- * is created lazily on first poll/await and cleared once consumed. */
1131
- private readonly taskWaiters;
1132
- /** Cache of completed results in case the consumer asks AFTER the
1133
- * coordinator already fired the event — `awaitTasks(['t-1'])` after
1134
- * t-1 finished should resolve immediately, not hang. */
1135
- private readonly completed;
1136
- /** Per-subagent provider/model metadata, captured at spawn time so the
1137
- * FleetUsageAggregator's metaLookup can surface readable rows. */
1138
- private readonly subagentMeta;
1139
- private readonly priceLookups;
1140
- /** Bridge endpoints we created per subagent (so we can `stop()` them
1141
- * on shutdown and free transport subscriptions). */
1142
- private readonly subagentBridges;
1143
- /** Tracks per-spawn config + assigned task ids for manifest writing. */
1144
- private readonly manifestEntries;
1145
- private readonly manifestPath?;
1146
- private readonly roster?;
1147
- private readonly directorPreamble;
1148
- private readonly subagentBaseline;
1149
- /** Absolute path to the fleet's shared scratchpad directory, or null
1150
- * when none was configured. Exposed as a readonly getter for callers
1151
- * that need to surface the path to the user (e.g. the CLI logging
1152
- * the location after `--director` boots). */
1153
- readonly sharedScratchpadPath: string | null;
1154
- /** Spawn cap (lifetime total). Infinity means unlimited. */
1155
- readonly maxSpawns: number;
1156
- /** Nesting cap. The N-th director in a chain has `spawnDepth = N-1`. */
1157
- readonly maxSpawnDepth: number;
1158
- /** This director's position in a director chain. Root director = 0. */
1159
- readonly spawnDepth: number;
1160
- /** Live spawn counter for `maxSpawns` enforcement. */
1161
- private spawnCount;
1162
- constructor(opts: DirectorOptions);
1163
- /**
1164
- * Spawn a subagent. Identical to the coordinator's `spawn()` but
1165
- * captures provider/model metadata for the usage aggregator and
1166
- * lets the FleetBus attach to the runner's EventBus when the task
1167
- * actually runs (see `attachSubagentBus`).
1168
- *
1169
- * Caller-supplied `priceLookup` is optional but recommended — without
1170
- * it the `cost` column in `usage.snapshot()` stays at 0.
1171
- */
1172
- spawn(config: SubagentConfig, priceLookup?: {
1173
- input?: number;
1174
- output?: number;
1175
- cacheRead?: number;
1176
- cacheWrite?: number;
1177
- }): Promise<string>;
1178
- /**
1179
- * Synchronously ask a subagent something via the bridge. Sends a
1180
- * `task` message addressed to the subagent and awaits a matching
1181
- * reply (matched by message id). Subagent runners that handle these
1182
- * requests subscribe to `ctx.bridge` and reply with a message whose
1183
- * `id` equals the incoming request's id (see `InMemoryAgentBridge`'s
1184
- * `request<T>` implementation).
1185
- *
1186
- * Returns the response payload directly (the bridge wrapper is
1187
- * unwrapped for ergonomics). Times out after `timeoutMs` (default
1188
- * matches the bridge's own default of 30s) — surface those rejections
1189
- * to the caller as actionable errors instead of letting tools hang.
1190
- */
1191
- ask<T = unknown>(subagentId: string, payload: unknown, timeoutMs?: number): Promise<T>;
1192
- /**
1193
- * Read completed task results and format them as a structured text
1194
- * block the director's LLM can paste into its own context. The
1195
- * Director keeps every completed `TaskResult` in `completed` so this
1196
- * is a pure read — no bridge round-trip, cheap to call.
1197
- *
1198
- * The returned string is intentionally markdown-flavored: headers per
1199
- * subagent, a one-line meta row (iter / tools / ms), and the task's
1200
- * result text. Pass `style: 'json'` for a programmatic shape instead
1201
- * (useful when the director model is doing structured-output work).
1202
- */
1203
- rollUp(taskIds: string[], style?: 'markdown' | 'json'): string;
1204
- /**
1205
- * Write the fleet manifest to `manifestPath`. Returns the path written
1206
- * or null when no path was configured. Captures every spawn + its
1207
- * assigned tasks — paired with per-subagent JSONLs, this is enough to
1208
- * replay an entire director run.
1209
- */
1210
- writeManifest(): Promise<string | null>;
1211
- /**
1212
- * Tear down the director: stop every subagent, close every bridge
1213
- * endpoint, and (when configured) write the final manifest. Idempotent
1214
- * — calling shutdown twice is a no-op on the second invocation.
1215
- */
1216
- shutdown(): Promise<void>;
1217
- /**
1218
- * Hand a task to the coordinator. Returns the assigned task id so
1219
- * callers can wait on it via `awaitTasks([id])`. The coordinator's
1220
- * concurrency limit applies — the task may queue before running.
1221
- */
1222
- assign(task: TaskSpec): Promise<string>;
1223
- /**
1224
- * Block until every task id resolves. Returns results in the same
1225
- * order as the input. If any task hasn't completed by the time this
1226
- * is called, the promise hangs until it does — pair with a timeout
1227
- * at the caller if that's a concern. Resolves immediately for ids
1228
- * whose results were already cached.
1229
- */
1230
- awaitTasks(taskIds: string[]): Promise<TaskResult[]>;
1231
- terminate(subagentId: string): Promise<void>;
1232
- terminateAll(): Promise<void>;
1233
- status(): CoordinatorStatus;
1234
- /**
1235
- * Subscribe to coordinator events. Currently only `task.completed` is
1236
- * exposed (the others are internal lifecycle). Returns an unsubscribe
1237
- * function. External callers (e.g. the CLI's `MultiAgentHost`) use this
1238
- * to drive their own pending/results tracking without poking the
1239
- * coordinator directly.
1240
- */
1241
- on(event: 'task.completed', handler: (payload: {
1242
- task: TaskSpec;
1243
- result: TaskResult;
1244
- }) => void): () => void;
1245
- /**
1246
- * Snapshot of every task that has resolved (success, failed, timeout,
1247
- * stopped) since the director started. Returned in completion order
1248
- * via the internal map's iteration order. Used by `/fleet status` to
1249
- * paint the completed table without reaching into private state.
1250
- */
1251
- completedResults(): TaskResult[];
1252
- snapshot(): FleetUsage;
1253
- /**
1254
- * Compose the leader/director-agent system prompt: fleet preamble +
1255
- * (optional) roster summary + user base prompt. Pass the result to your
1256
- * leader Agent's `ctx.systemPrompt` when constructing it.
1257
- *
1258
- * `basePrompt` defaults to `config.leaderSystemPrompt` so callers can
1259
- * use the no-arg form when the multi-agent config already carries it.
1260
- */
1261
- leaderSystemPrompt(basePrompt?: string): string;
1262
- /**
1263
- * Compose a subagent's system prompt for a given `SubagentConfig`:
1264
- * baseline + role + task + per-spawn override. Returned by value — does
1265
- * not mutate the config. Factories (the user-supplied `AgentFactory`)
1266
- * should call this when building each subagent's Agent so the bridge
1267
- * contract, role context, and override are all surfaced.
1268
- *
1269
- * When `taskBrief` is omitted the Task section is dropped. Pass the
1270
- * actual task description here to reinforce it in the system prompt
1271
- * (the runner already passes it as user input — duplicating in the
1272
- * system prompt is optional but improves anchoring on small models).
1273
- */
1274
- subagentSystemPrompt(config: SubagentConfig, taskBrief?: string): string;
1275
- /**
1276
- * Build the tool set the LLM-driven director uses to orchestrate.
1277
- * Returns an array of `Tool` definitions; register these on the
1278
- * director's `Agent` to expose `spawn_subagent`, `assign_task`, etc.
1279
- * Each tool's `execute()` delegates straight to the matching method
1280
- * above.
1281
- *
1282
- * Tools all carry `permission: 'auto'` — the *user* has already
1283
- * approved running the director when they kicked off the run, so
1284
- * gating individual orchestration calls behind a confirm prompt
1285
- * would just be noise. The actual subagent tools they spawn are
1286
- * still permission-checked normally.
1287
- */
1288
- tools(roster?: Record<string, SubagentConfig>): Tool[];
1289
- }
1290
-
1291
- /**
1292
- * Per-subagent session factory.
1293
- *
1294
- * Director runs produce many parallel transcripts — one per spawned
1295
- * subagent — and we want them all rooted under the same director-run
1296
- * directory so a future `wstack replay <runId>` can rehydrate the whole
1297
- * fleet from a single tree.
1298
- *
1299
- * The factory builds (or accepts) a `SessionStore` whose `dir` points at
1300
- * `<sessionsRoot>/<directorRunId>/`, and returns a small `create()`
1301
- * function that the orchestration layer calls per-spawn. Each call
1302
- * yields a fresh `SessionWriter` whose JSONL file lives in that
1303
- * directory, named by either the caller-supplied `subagentId` (preferred,
1304
- * so the file name is human-readable) or a derived id.
1305
- *
1306
- * **Why a thin factory instead of plumbing options through every spawn
1307
- * site?** Because the director is the only caller that needs this
1308
- * isolation pattern, and shoving `sessionStore` options into
1309
- * `SubagentConfig` would leak storage details into a config shape that
1310
- * agents and the coordinator have no business knowing about.
1311
- */
1312
- interface DirectorSessionFactoryOptions {
1313
- /**
1314
- * Either a parent directory where `<directorRunId>/` will be created,
1315
- * or a pre-built `SessionStore` whose `dir` already points at the
1316
- * director run directory. Tests pass an in-memory store for isolation;
1317
- * production code passes the path under `~/.wrongstack/sessions/`.
1318
- */
1319
- store?: SessionStore;
1320
- sessionsRoot?: string;
1321
- /**
1322
- * Director run id — namespaces all subagent JSONLs under one folder.
1323
- * Defaults to a timestamped id; supplied explicitly when resuming a
1324
- * prior fleet manifest.
1325
- */
1326
- directorRunId?: string;
1327
- }
1328
- interface DirectorSessionFactory {
1329
- /** Absolute directory where this director run's transcripts live. */
1330
- readonly dir: string;
1331
- /** The director run id used to namespace the directory. */
1332
- readonly directorRunId: string;
1333
- /**
1334
- * Create a fresh `SessionWriter` for the named subagent. Each
1335
- * subagent gets its own JSONL file. The writer's `id` matches the
1336
- * supplied `subagentId` so disk paths line up with in-memory ids.
1337
- */
1338
- createSubagentSession(args: {
1339
- subagentId: string;
1340
- provider?: string;
1341
- model?: string;
1342
- title?: string;
1343
- }): Promise<SessionWriter>;
1344
- }
1345
- /**
1346
- * Build a `DirectorSessionFactory`. Pass either a pre-configured
1347
- * `SessionStore` (tests) or a `sessionsRoot` path (production). When
1348
- * neither is supplied the factory throws — there's no sane default for
1349
- * "where do these JSONLs live".
1350
- */
1351
- declare function makeDirectorSessionFactory(opts: DirectorSessionFactoryOptions): DirectorSessionFactory;
1352
-
1353
- /**
1354
- * System-prompt composition helpers for the Director ecosystem.
1355
- *
1356
- * Two callers need composed prompts:
1357
- *
1358
- * 1. The **leader** (the director's own Agent) — needs a preamble that
1359
- * explains the fleet protocol: when to spawn, when to await, how to
1360
- * roll up, and the eight orchestration tools it owns.
1361
- *
1362
- * 2. Each **subagent** — needs a baseline that explains it has a parent
1363
- * it can call via the bridge, a role-specific block, the task brief,
1364
- * and finally any per-spawn `systemPromptOverride` from `SubagentConfig`.
1365
- *
1366
- * Both composers are pure functions: feed them parts, they return a string.
1367
- * No I/O, no side effects, no implicit defaults beyond the ones exported
1368
- * here. Callers (CLI multi-agent factory, Director itself) decide which
1369
- * parts to fill in — that keeps the composition seam visible and testable.
1370
- */
1371
- /**
1372
- * Default fleet-protocol preamble injected at the **front** of the
1373
- * director-agent's system prompt. Kept deliberately short — long preambles
1374
- * crowd out the user's leader prompt and the LLM stops attending. The tool
1375
- * descriptions live on the tool definitions themselves; this preamble only
1376
- * teaches *when* to reach for them.
1377
- */
1378
- declare const DEFAULT_DIRECTOR_PREAMBLE = "You are the Director of a multi-agent fleet. You orchestrate worker\nsubagents by spawning them, assigning tasks, awaiting completions, and\nrolling up their outputs into your next decision.\n\nCore fleet tools available to you:\n - spawn_subagent \u2014 create a worker with a chosen provider / model / role\n - assign_task \u2014 hand a piece of work to a specific subagent\n - await_tasks \u2014 block until named task ids complete (parallel-safe)\n - ask_subagent \u2014 synchronously query a running subagent via the bridge\n - roll_up \u2014 aggregate finished tasks into a markdown/json summary\n - terminate_subagent \u2014 abort a stuck worker (use sparingly)\n - fleet_status \u2014 snapshot of all subagents and pending tasks\n - fleet_usage \u2014 token + cost breakdown per subagent and total\n\nWorking rules:\n 1. Decompose first. Before spawning, decide which sub-tasks are\n independent and can run in parallel. Sequential work doesn't need a\n subagent \u2014 do it yourself.\n 2. Match worker to job. Cheap/fast model for triage, capable model for\n synthesis. Different providers per sibling is allowed and encouraged.\n 3. Always pair an assign with an await. Don't fire-and-forget; you owe\n the user a single coherent answer at the end.\n 4. Roll up before deciding. After await_tasks resolves, call roll_up so\n the results are folded back into your context in a compact form.\n 5. Budget is real. Check fleet_usage periodically. If a subagent is\n thrashing, terminate it rather than letting cost climb silently.\n 6. Never claim a subagent's work as your own without verifying it. If a\n result looks wrong, ask_subagent for clarification before passing it\n to the user.";
1379
- /**
1380
- * Default baseline prepended to every subagent's system prompt. Tells the
1381
- * subagent its place in the hierarchy and the bridge contract — without
1382
- * this, a subagent has no way to know it *can* ask the parent for
1383
- * clarification, and it will hallucinate answers when context is missing.
1384
- *
1385
- * Bridge contract: subagents may `send` progress and `request` answers, but
1386
- * MAY NOT exfiltrate the parent's full system prompt or tools list. The
1387
- * baseline reinforces this in plain text — the actual enforcement is at
1388
- * the bridge transport layer.
1389
- */
1390
- declare const DEFAULT_SUBAGENT_BASELINE = "You are a subagent operating under a Director. You were spawned to handle\na specific slice of a larger plan \u2014 do that slice well and report back.\n\nBridge contract:\n - You have a parent (the Director). You may call `request` on the\n parent bridge to ask a clarifying question. Use this sparingly; the\n parent is also working.\n - You MAY NOT request the parent's system prompt, tool list, or other\n subagents' context. Those are not yours to read.\n - Your final task output is what the Director sees. Be concise,\n structured, and self-contained \u2014 assume the Director will paste your\n output into its own context.";
1391
- /** Parts the leader-prompt composer accepts. All optional. */
1392
- interface DirectorPromptParts {
1393
- /** The user's existing leader system prompt — typically what was passed
1394
- * via `MultiAgentConfig.leaderSystemPrompt`. */
1395
- basePrompt?: string;
1396
- /** Override the built-in fleet preamble. Pass empty string to suppress. */
1397
- directorPreamble?: string;
1398
- /** Optional roster summary block — a short list of pre-configured roles
1399
- * the director can spawn (e.g. "researcher, coder, reviewer"). Helps
1400
- * small models discover the available shapes without scanning tools. */
1401
- rosterSummary?: string;
1402
- }
1403
- /**
1404
- * Compose the leader/director's system prompt. Order:
1405
- * 1. Director preamble (fleet protocol)
1406
- * 2. Roster summary (optional, when provided)
1407
- * 3. User base prompt (the per-project leader prompt)
1408
- *
1409
- * Sections are separated by a blank line. Empty parts are skipped so the
1410
- * output never contains stray blank-line runs.
1411
- */
1412
- declare function composeDirectorPrompt(parts?: DirectorPromptParts): string;
1413
- /** Parts the subagent-prompt composer accepts. Layered from generic to
1414
- * specific; later layers override earlier ones when they conflict. */
1415
- interface SubagentPromptParts {
1416
- /** Base persona/identity for *every* subagent. Defaults to the bridge
1417
- * contract baseline. Pass empty string to suppress. */
1418
- baseline?: string;
1419
- /** Role-specific block, e.g. "You are a code reviewer. Focus on…". */
1420
- role?: string;
1421
- /** Task brief — usually the same string the runner passes as user input,
1422
- * but exposed here in case the factory wants it duplicated in the
1423
- * system prompt for reinforcement. */
1424
- task?: string;
1425
- /**
1426
- * Absolute path to a shared scratchpad directory the whole fleet can
1427
- * read/write. When set, the composer adds a "Shared notes" block that
1428
- * tells the subagent where to drop findings and where to look for
1429
- * sibling output. This is the cheap fleet-coordination channel —
1430
- * agents don't need each other's transcripts, just each other's
1431
- * conclusions. Falls between `task` and `override` so the override
1432
- * can still narrow or replace it.
1433
- */
1434
- sharedScratchpad?: string;
1435
- /** Final per-spawn override from `SubagentConfig.systemPromptOverride`.
1436
- * Added last so it wins on conflict — that's by design: the spawn site
1437
- * knows the most about what this specific subagent should do. */
1438
- override?: string;
1439
- }
1440
- /**
1441
- * Compose a subagent's system prompt. Order:
1442
- * 1. Baseline (bridge contract)
1443
- * 2. Role
1444
- * 3. Task brief
1445
- * 4. Per-spawn override
1446
- *
1447
- * Same blank-line-separated joining as the director composer.
1448
- *
1449
- * Layering rationale: the baseline never needs to change between
1450
- * subagents; the role is the "what kind of worker is this"; the task is
1451
- * the "what should you do *now*"; the override is the spawn-site escape
1452
- * hatch ("…and respond only in JSON"). Putting override last means it
1453
- * never gets squashed by something earlier in the chain.
1454
- */
1455
- declare function composeSubagentPrompt(parts?: SubagentPromptParts): string;
1456
- /**
1457
- * Render a short bullet list summarising a roster — useful for stuffing
1458
- * into `composeDirectorPrompt({ rosterSummary })` so the director model
1459
- * can see available roles without scanning tool descriptions.
1460
- *
1461
- * Each entry: `- <role-id>: <name>[ (provider/model)] — <prompt-headline>`
1462
- * The prompt headline is the first non-empty line of `config.prompt`,
1463
- * truncated to 80 chars. Skipped entirely when the role has no prompt.
1464
- */
1465
- declare function rosterSummaryFromConfigs(roster: Record<string, {
1466
- name: string;
1467
- provider?: string;
1468
- model?: string;
1469
- prompt?: string;
1470
- role?: string;
1471
- }>): string;
1472
-
1473
- /**
1474
- * Pre-built subagent role configurations for the WrongStack fleet.
1475
- * These can be passed to `MultiAgentHost.spawn()` or used as templates
1476
- * for the director's roster.
1477
- */
1478
-
1479
- /**
1480
- * Audit Log Agent — analyzes session logs, event streams, and traces.
1481
- * Use for: post-mortems, trend analysis, operational insights.
1482
- */
1483
- declare const AUDIT_LOG_AGENT: SubagentConfig;
1484
- /**
1485
- * Bug Hunter Agent — systematic bug and code smell detection.
1486
- * Use for: pre-refactoring health checks, code review, regression prevention.
1487
- */
1488
- declare const BUG_HUNTER_AGENT: SubagentConfig;
1489
- /**
1490
- * Refactor Planner Agent — structured refactoring planning.
1491
- * Use for: large rewrites, technical debt reduction, architecture improvements.
1492
- */
1493
- declare const REFACTOR_PLANNER_AGENT: SubagentConfig;
1494
- /**
1495
- * Security Scanner Agent — vulnerability and secret detection.
1496
- * Use for: CI checks, pre-release audits, dependency vulnerability scanning.
1497
- */
1498
- declare const SECURITY_SCANNER_AGENT: SubagentConfig;
1499
- /** All pre-built agents in a map for easy lookup by role. */
1500
- declare const FLEET_ROSTER: Record<string, SubagentConfig>;
1501
- /** Quick-access list for spawning all at once. */
1502
- declare const ALL_FLEET_AGENTS: SubagentConfig[];
1503
-
1504
- type AutonomousResult = RunResult & {
1505
- toolCalls: number;
1506
- reason?: string;
1507
- };
1508
- interface DoneCheckResult {
1509
- done: boolean;
1510
- reason?: string;
1511
- iterations: number;
1512
- toolCalls: number;
1513
- }
1514
- declare class DoneConditionChecker {
1515
- private readonly condition;
1516
- private readonly compiledRegex;
1517
- constructor(condition: DoneCondition);
1518
- check(state: {
1519
- iterations: number;
1520
- toolCalls: number;
1521
- lastOutput?: string;
1522
- }): DoneCheckResult;
1523
- }
1524
- interface AutonomousRunnerOptions {
1525
- agent: Agent;
1526
- context: Context;
1527
- doneCondition: DoneCondition;
1528
- iterationTimeoutMs?: number;
1529
- onIteration?: (state: {
1530
- iteration: number;
1531
- toolCalls: number;
1532
- }) => void;
1533
- onDone?: (result: AutonomousResult) => void;
1534
- }
1535
- declare class AutonomousRunner {
1536
- private readonly opts;
1537
- private iterations;
1538
- private toolCalls;
1539
- private lastOutput?;
1540
- private stopped;
1541
- private readonly doneChecker;
1542
- constructor(opts: AutonomousRunnerOptions);
1543
- run(): Promise<AutonomousResult>;
1544
- private runLoop;
1545
- stop(): void;
1546
- }
1547
-
1548
- declare class SpecParser {
1549
- parse(content: string): Specification;
1550
- private extractTitle;
1551
- private extractVersion;
1552
- private extractOverview;
1553
- private extractSections;
1554
- private extractRequirements;
1555
- private parseRequirementLine;
1556
- private mapSectionType;
1557
- analyze(spec: Specification): SpecAnalysis;
1558
- validate(spec: Specification): SpecValidationResult;
1559
- }
1560
-
1561
- interface TaskStore {
1562
- saveGraph(graph: TaskGraph): Promise<void>;
1563
- loadGraph(id: string): Promise<TaskGraph | null>;
1564
- listGraphs(): Promise<{
1565
- id: string;
1566
- title: string;
1567
- updatedAt: number;
1568
- }[]>;
1569
- deleteGraph(id: string): Promise<void>;
1570
- }
1571
- interface TaskTrackerOptions {
1572
- store: TaskStore;
1573
- /**
1574
- * Called when an in-the-background persistence (`saveGraph`) rejects.
1575
- * The synchronous TaskTracker methods (addNode/addEdge/updateNodeStatus)
1576
- * fire-and-forget their writes; without this, a failing store silently
1577
- * loses graph mutations. Defaults to a console.warn.
1578
- */
1579
- onPersistError?: (err: unknown) => void;
1580
- }
1581
- interface TaskTransition {
1582
- from: TaskNode['status'];
1583
- to: TaskNode['status'];
1584
- timestamp: number;
1585
- reason?: string;
1586
- }
1587
- declare class TaskTracker {
1588
- private readonly opts;
1589
- private graph;
1590
- private transitions;
1591
- constructor(opts: TaskTrackerOptions);
1592
- createGraph(specId: string, title: string): Promise<TaskGraph>;
1593
- loadGraph(id: string): Promise<TaskGraph | null>;
1594
- addNode(node: Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'>): TaskNode;
1595
- addEdge(from: string, to: string, type?: TaskGraph['edges'][0]['type']): void;
1596
- updateNodeStatus(id: string, status: TaskNode['status'], reason?: string): void;
1597
- getNode(id: string): TaskNode | undefined;
1598
- getAllNodes(filter?: TaskFilter, sort?: TaskSort): TaskNode[];
1599
- getChildren(parentId: string): TaskNode[];
1600
- getDependents(taskId: string): string[];
1601
- getBlockers(taskId: string): string[];
1602
- canStart(taskId: string): boolean;
1603
- getProgress(): TaskProgress;
1604
- getTransitions(taskId?: string): TaskTransition[];
1605
- private unblockDependents;
1606
- private checkAndBlockIfNeeded;
1607
- /**
1608
- * Fire-and-forget persistence with attached error handler.
1609
- * Synchronous mutators (addNode/addEdge/updateNodeStatus) use this to
1610
- * avoid forcing an async cascade through every caller; if the store
1611
- * rejects, the configured `onPersistError` is invoked so failures are
1612
- * surfaced instead of swallowed by an unhandled promise rejection.
1613
- */
1614
- private persist;
1615
- }
1616
-
1617
- interface TaskGeneratorOptions {
1618
- taskTracker: TaskTracker;
1619
- }
1620
- interface GeneratedTask {
1621
- specRequirementId?: string;
1622
- title: string;
1623
- description: string;
1624
- type: TaskType;
1625
- priority: TaskPriority;
1626
- estimateHours?: number;
1627
- tags?: string[];
1628
- }
1629
- declare class TaskGenerator {
1630
- private readonly opts;
1631
- constructor(opts: TaskGeneratorOptions);
1632
- generateFromSpec(spec: Specification): Promise<TaskGraph>;
1633
- private createTaskFromRequirement;
1634
- private createTaskFromEndpoint;
1635
- private buildDescription;
1636
- private mapRequirementType;
1637
- private estimateHours;
1638
- private estimateForEndpoint;
1639
- generateSubtasks(parentTaskId: string, spec: Specification): Promise<void>;
1640
- }
1641
- declare class DefaultTaskStore implements TaskStore {
1642
- private graphs;
1643
- saveGraph(graph: TaskGraph): Promise<void>;
1644
- loadGraph(id: string): Promise<TaskGraph | null>;
1645
- listGraphs(): Promise<{
1646
- id: string;
1647
- title: string;
1648
- updatedAt: number;
1649
- }[]>;
1650
- deleteGraph(id: string): Promise<void>;
1651
- private cloneGraph;
1652
- }
1653
-
1654
- /**
1655
- * Extended event map used internally by TaskFlow and multi-agent components.
1656
- * These events are emitted on the injected EventBus and are a subset of
1657
- * the full EventMap — they do not require a separate registration.
1658
- */
1659
- interface TaskFlowEventMap {
1660
- 'phase.change': {
1661
- from: TaskFlowPhase;
1662
- to: TaskFlowPhase;
1663
- };
1664
- 'task.started': {
1665
- taskId: string;
1666
- };
1667
- 'task.completed': {
1668
- taskId: string;
1669
- result?: unknown;
1670
- };
1671
- 'task.failed': {
1672
- taskId: string;
1673
- error: string;
1674
- };
1675
- 'task.review': {
1676
- taskId: string;
1677
- };
1678
- 'spec.analyzed': {
1679
- analysis: SpecAnalysis;
1680
- };
1681
- 'progress': {
1682
- percent: number;
1683
- message: string;
1684
- };
1685
- 'done': {
1686
- graph: TaskGraph;
1687
- };
1688
- 'error': {
1689
- phase: TaskFlowPhase;
1690
- error: Error;
1691
- };
1692
- }
1693
- type TaskFlowPhase = 'idle' | 'parsing' | 'analyzing' | 'generating' | 'executing' | 'reviewing' | 'completing' | 'done' | 'failed';
1694
- type TaskFlowEventName = keyof TaskFlowEventMap;
1695
- interface TaskFlowOptions {
1696
- tracker: TaskTracker;
1697
- events: EventBus;
1698
- doneCondition?: DoneCondition;
1699
- maxConcurrent?: number;
1700
- }
1701
- interface TaskFlowExecutionContext {
1702
- executeTask: (task: TaskNode) => Promise<unknown>;
1703
- onTaskComplete?: (task: TaskNode, result: unknown) => void;
1704
- onTaskFail?: (task: TaskNode, error: Error) => void;
1705
- }
1706
- declare class TaskFlow {
1707
- private readonly opts;
1708
- private phase;
1709
- private spec;
1710
- private graph;
1711
- private stopped;
1712
- constructor(opts: TaskFlowOptions);
1713
- private emit;
1714
- fromSpec(specContent: string): Promise<TaskGraph>;
1715
- execute(ctx: TaskFlowExecutionContext): Promise<TaskGraph>;
1716
- reviewTask(taskId: string, approved: boolean, comment?: string): Promise<void>;
1717
- stop(): void;
1718
- getPhase(): TaskFlowPhase;
1719
- getGraph(): TaskGraph | null;
1720
- getSpec(): Specification | null;
1721
- private setPhase;
1722
- private getExecutableTasks;
1723
- private executeSingleTask;
1724
- private checkDoneCondition;
1725
- private emitProgress;
1726
- }
1727
- interface SpecDrivenDevOptions {
1728
- workingDirectory: string;
1729
- events: EventBus;
1730
- doneCondition?: DoneCondition;
1731
- }
1732
- declare class SpecDrivenDev {
1733
- private store;
1734
- private tracker;
1735
- private readonly events;
1736
- private flows;
1737
- constructor(opts: SpecDrivenDevOptions);
1738
- createFlow(specContent: string, options?: Partial<TaskFlowOptions>): Promise<TaskFlow>;
1739
- getTracker(): TaskTracker;
1740
- getFlow(graphId: string): TaskFlow | undefined;
1741
- listFlows(): {
1742
- id: string;
1743
- title: string;
1744
- phase: TaskFlowPhase;
1745
- }[];
1746
- }
1747
-
1748
- /**
1749
- * Per-project lockfile used for crash detection. The CLI writes one of
1750
- * these alongside the session JSONLs (`<projectSessions>/active.json`)
1751
- * when an interactive run starts, and deletes it on clean exit. If we
1752
- * find one on the next launch whose owning PID is dead (or whose host
1753
- * doesn't match), we know the previous run was killed mid-flight and
1754
- * the session it was writing to is a recovery candidate.
1755
- *
1756
- * The lockfile is intentionally per-project (already isolated by
1757
- * `wpaths.projectSessions`), so two TUIs in two different repos do not
1758
- * fight each other.
1759
- */
1760
- interface RecoveryLockOptions {
1761
- /** Directory the lockfile lives in. Usually `wpaths.projectSessions`. */
1762
- dir: string;
1763
- /** This process's PID. Default: `process.pid`. */
1764
- pid?: number;
1765
- /** Hostname recorded for the lock. Default: `os.hostname()`. */
1766
- hostname?: string;
1767
- /** Locks older than this are considered orphaned (disk wiped, etc.). Default 24h. */
1768
- maxAgeMs?: number;
1769
- /** Used to check whether the abandoned session was actually closed cleanly. */
1770
- sessionStore?: SessionStore;
1771
- /**
1772
- * Override the PID-liveness probe. Default: `process.kill(pid, 0)` —
1773
- * succeeds (or throws EPERM) when the PID is alive, throws ESRCH when
1774
- * it is gone. Tests inject a deterministic stub.
1775
- */
1776
- isPidAlive?: (pid: number) => boolean;
1777
- }
1778
- interface AbandonedSession {
1779
- sessionId: string;
1780
- pid: number;
1781
- startedAt: string;
1782
- /** Lockfile age in ms at the time of the check. */
1783
- ageMs: number;
1784
- /** Number of messages already on disk for this session. */
1785
- messageCount: number;
1786
- }
1787
- declare class RecoveryLock {
1788
- private readonly file;
1789
- private readonly pid;
1790
- private readonly hostname;
1791
- private readonly maxAgeMs;
1792
- private readonly sessionStore?;
1793
- private readonly probe;
1794
- constructor(opts: RecoveryLockOptions);
1795
- /**
1796
- * Examine the lockfile and decide whether it represents an abandoned
1797
- * session. Returns `null` if the file is missing, points to a live
1798
- * instance, references a clean-closed session, is too old, or is
1799
- * malformed. Otherwise returns enough detail to prompt the user.
1800
- *
1801
- * Important: this is a read-only check. We never delete an active
1802
- * lock from here — if another wstack instance is alive, the caller
1803
- * should bail or run with a fresh session instead.
1804
- */
1805
- checkAbandoned(): Promise<AbandonedSession | null>;
1806
- /**
1807
- * Claim the lock for the given session. Overwrites any existing lock
1808
- * — the caller should have already handled abandonment (via
1809
- * `checkAbandoned`) before calling this.
1810
- */
1811
- write(sessionId: string): Promise<void>;
1812
- /**
1813
- * Release the lock. Idempotent — silently succeeds if the file is
1814
- * already gone (e.g. someone else cleared it, or the directory was
1815
- * wiped).
1816
- */
1817
- clear(): Promise<void>;
1818
- private readLock;
1819
- }
1820
-
1821
- declare class ToolExecutor {
1822
- private readonly registry;
1823
- private readonly opts;
1824
- private readonly serializer;
1825
- private readonly iterationTimeoutMs;
1826
- constructor(registry: {
1827
- get(name: string): Tool | undefined;
1828
- list(): Tool[];
1829
- }, opts: ToolExecutorOptions);
1830
- /**
1831
- * Execute a batch of tool uses using the configured strategy.
1832
- * Returns the execution results and the remaining output budget.
1833
- */
1834
- executeBatch(toolUses: ToolUseBlock[], ctx: Context, strategy: ToolExecutorStrategy): Promise<ToolBatchResult>;
1835
- /**
1836
- * Execute a single tool with timeout, permission check, and output capping.
1837
- * Emits `tool.started` via the injected EventBus (if any) right before
1838
- * invoking the tool — closes the observability gap between "model decided
1839
- * to call a tool" and "tool.executed".
1840
- */
1841
- executeTool(tool: Tool, use: ToolUseBlock, ctx: Context, budget: number): Promise<ToolResultBlock>;
1842
- private runWithTimeout;
1843
- private runStreamedTool;
1844
- private unknownToolResult;
1845
- private deniedResult;
1846
- private decrementBudget;
1847
- /**
1848
- * Compute the suggestedPattern string for a tool+input pair.
1849
- * Matches the logic in DefaultPermissionPolicy so the TUI shows the
1850
- * same subject that the trust file would use.
1851
- */
1852
- private subjectFor;
1853
- }
1854
-
1855
- /**
1856
- * L2-A: read-only view over a `SessionStore` with query, replay, search,
1857
- * and export helpers. Implemented on top of the public `SessionStore`
1858
- * surface so any concrete store can be inspected without re-implementation.
1859
- *
1860
- * The heavy operations re-parse the JSONL stream on every call — fine for
1861
- * /resume and one-off analytics. Wrap with a memoizing decorator if needed.
1862
- */
1863
- declare class DefaultSessionReader implements SessionReader {
1864
- private readonly store;
1865
- constructor(opts: DefaultSessionReaderOptions);
1866
- query(q?: SessionQuery): Promise<SessionSummaryLite[]>;
1867
- replay(sessionId: string): AsyncIterable<SessionEvent>;
1868
- search(q: SessionSearchQuery, sessionId?: string): Promise<SessionSearchHit[]>;
1869
- export(sessionId: string, opts: SessionExportOptions): Promise<string>;
1870
- metadata(sessionId: string): Promise<SessionMetadata>;
1871
- }
1872
-
1873
- /**
1874
- * In-memory metrics sink. Suitable for embedded use, tests, and /metrics
1875
- * scrape over HTTP. For production push-based pipelines, write an adapter
1876
- * that implements MetricsSink and forwards to OTLP/StatsD/Prometheus.
1877
- */
1878
- declare class InMemoryMetricsSink implements MetricsSink {
1879
- private counters;
1880
- private gauges;
1881
- private histograms;
1882
- counter(name: string, value?: number, labels?: MetricLabels): void;
1883
- gauge(name: string, value: number, labels?: MetricLabels): void;
1884
- histogram(name: string, value: number, labels?: MetricLabels): void;
1885
- snapshot(): MetricsSnapshot;
1886
- reset(): void;
1887
- private getOrCreate;
1888
- }
1889
- /** Cheap noop sink — drop-in default when observability is not configured. */
1890
- declare class NoopMetricsSink implements MetricsSink {
1891
- counter(): void;
1892
- gauge(): void;
1893
- histogram(): void;
1894
- snapshot(): MetricsSnapshot;
1895
- reset(): void;
1896
- }
1897
-
1898
- /**
1899
- * Aggregates registered health checks. Worst status wins — one unhealthy check
1900
- * makes the whole system unhealthy. Use timeouts so a slow probe can't stall
1901
- * the response.
1902
- */
1903
- declare class DefaultHealthRegistry implements HealthRegistry {
1904
- private checks;
1905
- private readonly timeoutMs;
1906
- constructor(opts?: {
1907
- timeoutMs?: number;
1908
- });
1909
- register(check: HealthCheck): void;
1910
- unregister(name: string): void;
1911
- run(): Promise<AggregateHealth>;
1912
- private runOne;
1913
- }
1914
-
1915
- /**
1916
- * Default tracer is a noop — zero overhead when observability is not wired up.
1917
- * Replace at runtime with an OpenTelemetry-backed Tracer to enable real spans.
1918
- */
1919
- declare class NoopTracer implements Tracer {
1920
- startSpan(): Span;
1921
- }
1922
-
1923
- /**
1924
- * Lightweight OTel adapter. Doesn't pull in `@opentelemetry/api` directly —
1925
- * the user passes their already-initialized OTel Tracer through, and this
1926
- * wrapper translates our minimal Span surface onto theirs.
1927
- *
1928
- * Usage:
1929
- * import { trace } from '@opentelemetry/api';
1930
- * const tracer = trace.getTracer('wrongstack', '1.0');
1931
- * const wrappedTracer = new OTelTracer(tracer);
1932
- * // pass `wrappedTracer` as Agent.tracer / ToolExecutor.tracer.
1933
- *
1934
- * The shape of the upstream Tracer is intentionally typed loosely so we
1935
- * don't need a build-time dependency. Anything OTel-compatible works,
1936
- * including OpenInference, Tempo, etc.
1937
- */
1938
-
1939
- interface OTelLikeSpan {
1940
- setAttribute(key: string, value: string | number | boolean): unknown;
1941
- recordException(err: {
1942
- message: string;
1943
- stack?: string;
1944
- name?: string;
1945
- }): unknown;
1946
- setStatus?(status: {
1947
- code: number;
1948
- message?: string;
1949
- }): unknown;
1950
- end(): unknown;
1951
- }
1952
- interface OTelLikeTracer {
1953
- startSpan(name: string, options?: {
1954
- attributes?: Record<string, string | number | boolean>;
1955
- }): OTelLikeSpan;
1956
- }
1957
- declare class OTelTracer implements Tracer {
1958
- private readonly upstream;
1959
- constructor(upstream: OTelLikeTracer);
1960
- startSpan(name: string, attrs?: Record<string, string | number | boolean>): Span;
1961
- }
1962
-
1963
- /**
1964
- * Subscribes a MetricsSink to the EventBus. Returns an unsubscribe function
1965
- * that detaches all listeners. This is the single integration point between
1966
- * the agent's event stream and the observability layer — no metric calls
1967
- * leak into core call sites.
1968
- */
1969
- declare function wireMetricsToEvents(events: EventBus, sink: MetricsSink): () => void;
1970
-
1971
- /**
1972
- * Render a `MetricsSnapshot` as Prometheus text-format bytes. The output
1973
- * always ends with a trailing newline (Prometheus requires it).
1974
- */
1975
- declare function renderPrometheus(snapshot: MetricsSnapshot): string;
1976
- /** MIME type Prometheus servers must respond with on /metrics. */
1977
- declare const PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
1978
- interface MetricsServerOptions {
1979
- port: number;
1980
- /** Bind address. Defaults to 127.0.0.1 so we don't accidentally expose metrics publicly. */
1981
- host?: string;
1982
- sink: MetricsSink;
1983
- /** Path to serve on. Defaults to /metrics. */
1984
- path?: string;
1985
- /**
1986
- * V2-C: optional health registry. When provided, the server also responds
1987
- * on `/healthz` (configurable via `healthPath`) with a JSON aggregate of
1988
- * every registered health check. K8s probes expect a single HTTP server
1989
- * exposing both `/metrics` and `/healthz`, so we mount them on the same
1990
- * port rather than opening a sibling listener.
1991
- */
1992
- healthRegistry?: HealthRegistry;
1993
- /** Path to serve health JSON on. Defaults to /healthz. */
1994
- healthPath?: string;
1995
- }
1996
- interface MetricsServerHandle {
1997
- port: number;
1998
- url: string;
1999
- close(): Promise<void>;
2000
- }
2001
- /**
2002
- * Start an HTTP server that exposes a Prometheus scrape endpoint.
2003
- * Uses node:http directly to avoid pulling a framework into the core graph.
2004
- *
2005
- * Why bind to 127.0.0.1 by default: telemetry endpoints inside an agent
2006
- * process can leak prompt content via metric labels (tool name, error
2007
- * message, etc.). The default keeps that on the loopback interface;
2008
- * operators who want network scraping opt in explicitly with host: '0.0.0.0'.
2009
- */
2010
- declare function startMetricsServer(opts: MetricsServerOptions): Promise<MetricsServerHandle>;
2011
-
2012
- /**
2013
- * V2-A: OTLP/JSON metrics push exporter.
2014
- *
2015
- * Periodically POSTs `MetricsSink.snapshot()` to an OTLP HTTP receiver
2016
- * (the OpenTelemetry Collector, vendor agents like Honeycomb, Datadog,
2017
- * Grafana Cloud, etc.). The wire format is OTLP/JSON v1.0 — covered by
2018
- * the spec at github.com/open-telemetry/opentelemetry-proto.
2019
- *
2020
- * Why no `@opentelemetry/*` dep: the core graph is intentionally
2021
- * dependency-free. The JSON shape is well-defined and stable; bringing
2022
- * in the official SDK would add ~3MB and pin us to its release cadence.
2023
- * Operators who need the OTLP gRPC transport or vendor-specific quirks
2024
- * can wrap an `@opentelemetry/exporter-metrics-otlp-grpc` in a custom
2025
- * `MetricsSink` instead — the seam exists.
2026
- */
2027
- interface OtlpMetricsExporterOptions {
2028
- /** Source of metric data. The exporter reads `snapshot()` per interval. */
2029
- sink: MetricsSink;
2030
- /**
2031
- * OTLP HTTP endpoint base URL. Path `/v1/metrics` is appended unless
2032
- * the URL already ends with `/v1/metrics` (idempotent).
2033
- * Example: `http://otel-collector:4318` or `https://otlp.example.com`.
2034
- */
2035
- endpoint: string;
2036
- /** Push interval in milliseconds. Defaults to 30s (Prometheus default). */
2037
- intervalMs?: number;
2038
- /** Optional bearer token / API key (sent as `Authorization`). */
2039
- authorization?: string;
2040
- /** Extra request headers (vendor-specific keys go here). */
2041
- headers?: Record<string, string>;
2042
- /** Resource attributes attached to every export. Defaults: `service.name=wrongstack`. */
2043
- resourceAttributes?: Record<string, string>;
2044
- /** Instrumentation scope. Default: `wrongstack`. */
2045
- scopeName?: string;
2046
- /** Per-request timeout. Defaults to 10s. */
2047
- timeoutMs?: number;
2048
- /** Override fetch (for tests). Defaults to global `fetch`. */
2049
- fetchImpl?: typeof globalThis.fetch;
2050
- /** Called when a push fails. Defaults to silent (telemetry must never crash the host). */
2051
- onError?: (err: unknown) => void;
2052
- }
2053
- interface OtlpMetricsExporterHandle {
2054
- /** Push immediately (in addition to the scheduled interval). */
2055
- flush(): Promise<void>;
2056
- /** Stop the timer, attempt a final flush, then resolve. */
2057
- stop(): Promise<void>;
2058
- }
2059
- interface OtlpAttribute$1 {
2060
- key: string;
2061
- value: {
2062
- stringValue: string;
2063
- };
2064
- }
2065
- interface OtlpDataPoint {
2066
- attributes: OtlpAttribute$1[];
2067
- timeUnixNano: string;
2068
- asDouble?: number;
2069
- asInt?: string;
2070
- count?: string;
2071
- sum?: number;
2072
- quantileValues?: {
2073
- quantile: number;
2074
- value: number;
2075
- }[];
2076
- }
2077
- interface OtlpMetric {
2078
- name: string;
2079
- description?: string;
2080
- unit?: string;
2081
- sum?: {
2082
- dataPoints: OtlpDataPoint[];
2083
- aggregationTemporality: 2;
2084
- isMonotonic: true;
2085
- };
2086
- gauge?: {
2087
- dataPoints: OtlpDataPoint[];
2088
- };
2089
- summary?: {
2090
- dataPoints: OtlpDataPoint[];
2091
- };
2092
- }
2093
- interface OtlpExportRequest {
2094
- resourceMetrics: {
2095
- resource: {
2096
- attributes: OtlpAttribute$1[];
2097
- };
2098
- scopeMetrics: {
2099
- scope: {
2100
- name: string;
2101
- version?: string;
2102
- };
2103
- metrics: OtlpMetric[];
2104
- }[];
2105
- }[];
2106
- }
2107
- /**
2108
- * Build the OTLP/JSON export body from a sink snapshot. Exported for tests
2109
- * and for callers that want to ship via their own transport.
2110
- */
2111
- declare function buildOtlpMetricsRequest(sink: MetricsSink, opts?: {
2112
- resourceAttributes?: Record<string, string>;
2113
- scopeName?: string;
2114
- }): OtlpExportRequest;
2115
- /**
2116
- * Start pushing metrics to an OTLP HTTP receiver. Returns a handle with
2117
- * `flush()` and `stop()`.
2118
- */
2119
- declare function startOtlpMetricsExporter(opts: OtlpMetricsExporterOptions): OtlpMetricsExporterHandle;
2120
-
2121
- type SpanAttrValue = string | number | boolean;
2122
- interface RecordedSpan {
2123
- traceId: string;
2124
- spanId: string;
2125
- name: string;
2126
- startTimeUnixNano: bigint;
2127
- endTimeUnixNano?: bigint;
2128
- attributes: Record<string, SpanAttrValue>;
2129
- status: {
2130
- code: number;
2131
- message?: string;
2132
- };
2133
- }
2134
- interface OtlpTraceExporterOptions {
2135
- /** OTLP HTTP endpoint base URL. `/v1/traces` is appended unless already present. */
2136
- endpoint: string;
2137
- /** Push interval in milliseconds. Defaults to 5s (traces are bursty). */
2138
- intervalMs?: number;
2139
- /** Hard cap on buffered spans. When exceeded, oldest are dropped. Defaults to 2048. */
2140
- maxBufferedSpans?: number;
2141
- /** Authorization header. */
2142
- authorization?: string;
2143
- /** Extra request headers. */
2144
- headers?: Record<string, string>;
2145
- /** Resource attributes. Defaults to `service.name=wrongstack`. */
2146
- resourceAttributes?: Record<string, string>;
2147
- /** Instrumentation scope name. Default `wrongstack`. */
2148
- scopeName?: string;
2149
- /** Per-request timeout in ms. Default 10s. */
2150
- timeoutMs?: number;
2151
- /** Override fetch (for tests). */
2152
- fetchImpl?: typeof globalThis.fetch;
2153
- /** Called on push failure. Defaults to silent. */
2154
- onError?: (err: unknown) => void;
2155
- }
2156
- interface OtlpTraceExporterHandle {
2157
- /** The Tracer to install on Agent / ToolExecutor. */
2158
- readonly tracer: Tracer;
2159
- /** Push buffered spans immediately. */
2160
- flush(): Promise<void>;
2161
- /** Stop the timer, push remaining spans, resolve. */
2162
- stop(): Promise<void>;
2163
- /** Test helper: snapshot of spans currently in the buffer (not yet pushed). */
2164
- readonly buffered: () => readonly RecordedSpan[];
2165
- }
2166
- interface OtlpAttribute {
2167
- key: string;
2168
- value: {
2169
- stringValue: string;
2170
- } | {
2171
- boolValue: boolean;
2172
- } | {
2173
- doubleValue: number;
2174
- } | {
2175
- intValue: string;
2176
- };
2177
- }
2178
- interface OtlpSpan {
2179
- traceId: string;
2180
- spanId: string;
2181
- name: string;
2182
- kind: 1;
2183
- startTimeUnixNano: string;
2184
- endTimeUnixNano: string;
2185
- attributes: OtlpAttribute[];
2186
- status: {
2187
- code: number;
2188
- message?: string;
2189
- };
2190
- }
2191
- interface OtlpTracesRequest {
2192
- resourceSpans: {
2193
- resource: {
2194
- attributes: OtlpAttribute[];
2195
- };
2196
- scopeSpans: {
2197
- scope: {
2198
- name: string;
2199
- };
2200
- spans: OtlpSpan[];
2201
- }[];
2202
- }[];
2203
- }
2204
- declare function buildOtlpTracesRequest(spans: readonly RecordedSpan[], opts?: {
2205
- resourceAttributes?: Record<string, string>;
2206
- scopeName?: string;
2207
- }): OtlpTracesRequest;
2208
- /**
2209
- * Start the OTLP trace exporter. Returns a `Tracer` to install on the
2210
- * runtime (`Agent.run` etc.) and `flush()`/`stop()` controls.
2211
- */
2212
- declare function startOtlpTraceExporter(opts: OtlpTraceExporterOptions): OtlpTraceExporterHandle;
2213
-
2214
- type ContextManagerAction = 'check' | 'summary' | 'prune' | 'add_note' | 'compact';
2215
- interface ContextManagerInput {
2216
- action: ContextManagerAction;
2217
- /** 0-based message indices for prune/summary (inclusive). */
2218
- from?: number;
2219
- to?: number;
2220
- /** Text for add_note / summary actions. For summary, this is the LLM-provided summary text. */
2221
- text?: string;
2222
- /** Inject after which index (for add_note). Defaults to prepend (0). */
2223
- afterIndex?: number;
2224
- }
2225
- interface ContextManagerResult {
2226
- action: ContextManagerAction;
2227
- beforeTokens: number;
2228
- afterTokens?: number;
2229
- removedCount?: number;
2230
- messageCount: number;
2231
- summary?: string;
2232
- notes?: string;
2233
- }
2234
- /**
2235
- * Options for creating a context manager tool.
2236
- * `compactor` is required for the "compact" action; without it the action returns an error.
2237
- */
2238
- interface ContextManagerToolOptions {
2239
- compactor?: Compactor;
2240
- /**
2241
- * Optional sub-LLM summarizer. When provided, the "summary" action calls this
2242
- * to produce real summaries of message ranges instead of placeholder text.
2243
- * (signature matches Provider.complete — return the summary text in result.content[0].text)
2244
- */
2245
- summarizer?: (messages: Message[]) => Promise<string>;
2246
- }
2247
- declare function createContextManagerTool(opts?: ContextManagerToolOptions): Tool<ContextManagerInput, ContextManagerResult>;
2248
- /** Pre-built instance with no compactor — compact action will return an error. */
2249
- declare const contextManagerTool: Tool<ContextManagerInput, ContextManagerResult>;
2250
-
2251
- /**
2252
- * Built-in MCP server presets available to all WrongStack users out of the box.
2253
- * These servers must be explicitly enabled in config (disabled by default).
2254
- *
2255
- * To enable: set `mcpServers: { serverName: { enabled: true } }` in your config.
2256
- *
2257
- * Some servers require environment variables or additional config — see notes below.
2258
- *
2259
- * Transport types:
2260
- * stdio — spawns a local npm package binary via child_process
2261
- * sse — HTTP SSE endpoint (client POSTs requests)
2262
- * streamable-http — session-based HTTP with NDJSON responses
2263
- */
2264
- /** Filesystem access: read, write, list, search, tree. Good for exploring projects. */
2265
- declare const filesystemServer: () => MCPServerConfig;
2266
- /** GitHub API: issues, PRs, repos, search, file operations. Requires GITHUB_PERSONAL_ACCESS_TOKEN. */
2267
- declare const githubServer: () => MCPServerConfig;
2268
- /**
2269
- * Context7 — codebase-aware documentation and Q&A using context from your code.
2270
- * Live documentation for any library, grounded in your actual versions.
2271
- */
2272
- declare const context7Server: () => MCPServerConfig;
2273
- /**
2274
- * Brave Search — web search via Brave Browser's API.
2275
- * Requires BRAVE_SEARCH_API_KEY. Free tier: 2,000 queries/month.
2276
- * Sign up at https://api.search.brave.com/
2277
- */
2278
- declare const braveSearchServer: () => MCPServerConfig;
2279
- /**
2280
- * Block (Block, Inc.) — Postgres database access via SQL.
2281
- * Useful for running queries against a connected database during development.
2282
- */
2283
- declare const blockServer: () => MCPServerConfig;
2284
- /**
2285
- * EverArt — AI image generation via various providers.
2286
- * Requires EVERART_API_KEY.
2287
- */
2288
- declare const everArtServer: () => MCPServerConfig;
2289
- /**
2290
- * Slack — messaging, channels, search.
2291
- * Requires SLACK_BOT_TOKEN and either SLACK_TEAM_ID or SLACK_USER_TOKEN.
2292
- */
2293
- declare const slackServer: () => MCPServerConfig;
2294
- /**
2295
- * AWS knowledge base — EC2, S3, Lambda, IAM, CloudFormation, cost management.
2296
- * Requires AWS access key + secret in environment.
2297
- */
2298
- declare const awsServer: () => MCPServerConfig;
2299
- /**
2300
- * Google Maps — directions, distance matrix, geocoding, places.
2301
- * Requires GOOGLE_MAPS_API_KEY.
2302
- */
2303
- declare const googleMapsServer: () => MCPServerConfig;
2304
- /** Sentinel — security vulnerability scanning (sentinel-labs). */
2305
- declare const sentinelServer: () => MCPServerConfig;
2306
- /** Everything bundled — full set of built-in servers. Useful for `wstack mcp add --all`. */
2307
- declare const allServers: () => Record<string, MCPServerConfig>;
2308
-
2309
- export { ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, type AbandonedSession, type AgentFactory, type AgentFactoryResult, type AgentRunnerOptions, type AttachmentStoreOptions, AutoCompactionMiddleware, AutonomousRunner, type AutonomousRunnerOptions, BUG_HUNTER_AGENT, type CompactorOptions, type ConfigLoaderOptions, type ConfigMigration, ConfigMigrationError, type ConfigSource, type ContextManagerAction, type ContextManagerInput, type ContextManagerResult, type ContextManagerToolOptions, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, type DefaultLoggerOptions, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, type DefaultModelsRegistryOptions, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, DefaultTokenCounter, Director, DirectorBudgetError, type DirectorPromptParts, type DirectorSessionFactory, type DirectorSessionFactoryOptions, type DoneCheckResult, DoneConditionChecker, FLEET_ROSTER, FleetBus, type FleetEvent, type FleetHandler, type FleetUsage, FleetUsageAggregator, type GeneratedTask, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, type IntelligentCompactorOptions, LLMSelector, type LLMSelectorOptions, type MemoryStoreOptions, type MetricsServerHandle, type MetricsServerOptions, type MigrationContext, type MigrationResult, type ModeLoaderOptions, type MultiAgentCoordinatorOptions, NoopMetricsSink, NoopTracer, OTelTracer, type OtlpMetricsExporterHandle, type OtlpMetricsExporterOptions, type OtlpTraceExporterHandle, type OtlpTraceExporterOptions, PROMETHEUS_CONTENT_TYPE, type PermissionPolicyOptions, type PersistedQueueItem, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, type RecoveryLockOptions, SECURITY_SCANNER_AGENT, type SecretVaultOptions, SelectiveCompactor, type SelectiveCompactorOptions, type SessionStoreOptions, type SkillLoaderOptions, SpecDrivenDev, type SpecDrivenDevOptions, SpecParser, type SubagentPromptParts, type SubagentUsageSnapshot, TaskFlow, type TaskFlowEventMap, type TaskFlowEventName, type TaskFlowExecutionContext, type TaskFlowOptions, type TaskFlowPhase, TaskGenerator, type TaskGeneratorOptions, type TaskStore, TaskTracker, type TaskTrackerOptions, type TaskTransition, ToolExecutor, allServers, awsServer, blockServer, braveSearchServer, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createContextManagerTool, createMessage, decryptConfigSecrets, encryptConfigSecrets, everArtServer, filesystemServer, githubServer, googleMapsServer, loadProjectModes, loadUserModes, makeAgentSubagentRunner, makeDirectorSessionFactory, migratePlaintextSecrets, renderPrometheus, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, sentinelServer, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, wireMetricsToEvents };
1
+ export { D as DefaultLogger, a as DefaultLoggerOptions } from '../logger-BH6AE0W9.js';
2
+ export { AbandonedSession, AttachmentStoreOptions, ConfigLoaderOptions, ConfigMigration, ConfigMigrationError, ConfigSource, DEFAULT_CONFIG_MIGRATIONS, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultMemoryStore, DefaultSessionStore, DirectorStateCheckpoint, DirectorStateSnapshot, DirectorSubagentState, DirectorTaskState, MemoryStoreOptions, MigrationContext, MigrationResult, PersistedQueueItem, PlanFile, PlanItem, QueueStore, RecoveryLock, RecoveryLockOptions, SessionAnalyzer, SessionStoreOptions, TodosCheckpointFile, addPlanItem, attachPlanCheckpoint, attachTodosCheckpoint, clearPlan, emptyPlan, formatPlan, loadDirectorState, loadPlan, loadTodosCheckpoint, removePlanItem, runConfigMigrations, savePlan, saveTodosCheckpoint, setPlanItemStatus } from '../storage/index.js';
3
+ export { D as DefaultSessionReader } from '../session-reader-C3x96CDR.js';
4
+ export { D as DefaultSecretScrubber, a as DefaultSecretVault, S as SecretVaultOptions, d as decryptConfigSecrets, e as encryptConfigSecrets, m as migratePlaintextSecrets, r as rewriteConfigEncrypted } from '../secret-scrubber-CwYliRWd.js';
5
+ export { AutoApprovePermissionPolicy, DefaultPermissionPolicy, PermissionPolicyOptions } from '../security/index.js';
6
+ export { C as CompactorOptions, D as DefaultErrorHandler, a as DefaultRetryPolicy, H as HybridCompactor, T as ToolExecutor } from '../tool-executor-CYdZdtno.js';
7
+ export { AutoCompactionMiddleware, AutonomousRunner, AutonomousRunnerOptions, DefaultSkillLoader, DoneCheckResult, DoneConditionChecker, IntelligentCompactor, IntelligentCompactorOptions, SelectiveCompactor, SelectiveCompactorOptions, SkillLoaderOptions } from '../execution/index.js';
8
+ export { ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AgentFactory, AgentFactoryResult, AgentRunnerOptions, BUG_HUNTER_AGENT, CreateDelegateToolOptions, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DefaultMultiAgentCoordinator, DelegateHost, Director, DirectorBudgetError, DirectorPromptParts, DirectorSessionFactory, DirectorSessionFactoryOptions, FLEET_ROSTER, FleetBus, FleetEvent, FleetHandler, FleetUsage, FleetUsageAggregator, MultiAgentCoordinatorOptions, REFACTOR_PLANNER_AGENT, SECURITY_SCANNER_AGENT, SubagentPromptParts, SubagentUsageSnapshot, composeDirectorPrompt, composeSubagentPrompt, createDelegateTool, makeAgentSubagentRunner, makeDirectorSessionFactory, rosterSummaryFromConfigs } from '../coordination/index.js';
9
+ export { B as BudgetExceededError, a as BudgetKind, b as BudgetLimits, c as BudgetUsage, S as SubagentBudget } from '../multi-agent-BDfkxL5C.js';
10
+ export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-DmBiCipY.js';
11
+ export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-DqzwpBQy.js';
12
+ export { DefaultModeStore, LLMSelector, LLMSelectorOptions, ModeLoaderOptions, loadProjectModes, loadUserModes } from '../models/index.js';
13
+ export { DefaultTaskStore, GeneratedTask, SpecDrivenDev, SpecDrivenDevOptions, SpecParser, TaskFlow, TaskFlowEventMap, TaskFlowEventName, TaskFlowExecutionContext, TaskFlowOptions, TaskFlowPhase, TaskGenerator, TaskGeneratorOptions, TaskStore, TaskTracker, TaskTrackerOptions, TaskTransition } from '../sdd/index.js';
14
+ 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';
15
+ 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, s as sentinelServer, o as slackServer } from '../mcp-servers-BA1Ofmfj.js';
16
+ import '../logger-BMQgxvdy.js';
17
+ import '../events-B6Q03pTu.js';
18
+ import '../context-u0bryklF.js';
19
+ import '../memory-CEXuo7sz.js';
20
+ import '../wstack-paths-BGu2INTm.js';
21
+ import '../config-DXrqb41m.js';
22
+ import '../models-registry-Y2xbog0E.js';
23
+ import '../secret-vault-DoISxaKO.js';
24
+ import '../secret-scrubber-3TLUkiCV.js';
25
+ import '../input-reader-E-ffP2ee.js';
26
+ import '../compactor-DSl2FK7a.js';
27
+ import '../skill-Bx8jxznf.js';
28
+ import '../plugin-CoYYZKdn.js';
29
+ import '../observability-BhnVLBLS.js';
30
+ import '../renderer-0A2ZEtca.js';
31
+ import '../selector-BRqzvugb.js';
32
+ import 'node:events';
33
+ import '../mode-CV077NjV.js';
34
+ import '../task-graph-BITvWt4t.js';