@wrongstack/core 0.306.4 → 0.307.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 (103) hide show
  1. package/dist/chronicle/index.js +957 -953
  2. package/dist/chronicle/metrics-ingest.d.ts +55 -0
  3. package/dist/chronicle/metrics-schema.d.ts +86 -0
  4. package/dist/chronicle/metrics-store.d.ts +5 -120
  5. package/dist/chronicle/project-server.js +1083 -1084
  6. package/dist/chronicle/sqlite-journal-quota.d.ts +39 -0
  7. package/dist/chronicle/sqlite-journal-schema.d.ts +25 -0
  8. package/dist/chronicle/sqlite-journal.d.ts +12 -177
  9. package/dist/coordination/agents/index.js +1738 -1690
  10. package/dist/coordination/agents/project-agent-capture.d.ts +48 -0
  11. package/dist/coordination/agents/project-agent-identity.d.ts +3 -129
  12. package/dist/coordination/agents/project-agent-roster.d.ts +17 -0
  13. package/dist/coordination/index.js +6011 -5894
  14. package/dist/coordination/mail-tools.d.ts +1 -1
  15. package/dist/coordination/mailbox-http-actor-query.d.ts +16 -0
  16. package/dist/coordination/mailbox-http-router.d.ts +0 -48
  17. package/dist/coordination/mailbox-http-sse.d.ts +12 -0
  18. package/dist/coordination/mailbox-message-types.d.ts +71 -0
  19. package/dist/coordination/mailbox-predicates.d.ts +13 -0
  20. package/dist/coordination/mailbox-project-server.js +1 -1
  21. package/dist/coordination/mailbox-session-sync.d.ts +8 -0
  22. package/dist/coordination/mailbox-types.d.ts +6 -793
  23. package/dist/core/agent-loop-context.d.ts +28 -0
  24. package/dist/core/agent-loop-detector.d.ts +25 -0
  25. package/dist/core/fallback-doctor.d.ts +72 -0
  26. package/dist/core/index.d.ts +1 -0
  27. package/dist/core/index.js +1159 -888
  28. package/dist/defaults/index.js +3579 -3545
  29. package/dist/execution/autonomy-brain-llm.d.ts +55 -0
  30. package/dist/execution/autonomy-brain.d.ts +3 -156
  31. package/dist/execution/compaction-budget.d.ts +38 -0
  32. package/dist/execution/compaction-core.d.ts +3 -170
  33. package/dist/execution/compaction-elision.d.ts +58 -0
  34. package/dist/execution/council-orchestrator-helpers.d.ts +39 -0
  35. package/dist/execution/council-orchestrator.d.ts +3 -42
  36. package/dist/execution/council-response-parser.d.ts +56 -0
  37. package/dist/execution/index.js +2415 -2443
  38. package/dist/execution/prompt-enhancer.js +11 -3
  39. package/dist/execution/tool-executor-guard.d.ts +18 -0
  40. package/dist/execution/tool-executor-runner.d.ts +12 -0
  41. package/dist/execution/tool-executor.d.ts +0 -75
  42. package/dist/goal/index.js +19 -6
  43. package/dist/hq/index.js +8 -2
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +7813 -7292
  46. package/dist/infrastructure/index.js +3 -1
  47. package/dist/kernel/events/agent-events.d.ts +2 -0
  48. package/dist/kernel/events/provider-events.d.ts +13 -0
  49. package/dist/plugin/index.js +2590 -2561
  50. package/dist/plugins/auto-review-config.d.ts +53 -0
  51. package/dist/plugins/auto-review-git.d.ts +19 -0
  52. package/dist/plugins/auto-review-plugin.d.ts +2 -140
  53. package/dist/plugins/review-finding-verification.d.ts +7 -0
  54. package/dist/prompts/index.d.ts +1 -0
  55. package/dist/prompts/prompt-journal.d.ts +94 -0
  56. package/dist/security/index.js +627 -652
  57. package/dist/security/permission-explain.d.ts +19 -0
  58. package/dist/security/permission-policy.d.ts +0 -101
  59. package/dist/security/yolo-risk.d.ts +5 -4
  60. package/dist/session-catalog/index.js +220 -212
  61. package/dist/session-catalog/project-server.js +227 -219
  62. package/dist/session-catalog/store-rebuild.d.ts +9 -0
  63. package/dist/session-catalog/store-schema.d.ts +48 -0
  64. package/dist/session-catalog/store.d.ts +0 -17
  65. package/dist/storage/director-state.d.ts +6 -0
  66. package/dist/storage/file-session-writer.d.ts +2 -58
  67. package/dist/storage/index.d.ts +2 -1
  68. package/dist/storage/index.js +2057 -1925
  69. package/dist/storage/orphan-lock-cleaner.d.ts +15 -0
  70. package/dist/storage/session-recovery.d.ts +9 -0
  71. package/dist/storage/session-store/rename-session.d.ts +16 -0
  72. package/dist/storage/session-store/resume-session.d.ts +26 -0
  73. package/dist/storage/session-store/session-store-clear.d.ts +11 -0
  74. package/dist/storage/session-store/session-store-index.d.ts +13 -0
  75. package/dist/storage/session-store.d.ts +1 -129
  76. package/dist/storage/session-summary-tracker.d.ts +39 -0
  77. package/dist/storage/session-write-buffer.d.ts +43 -0
  78. package/dist/storage/session-writer/session-writer-flush.d.ts +4 -0
  79. package/dist/storage/session-writer/session-writer-summary-tracker.d.ts +28 -0
  80. package/dist/tools/fallback-agent-model-assign-tool.d.ts +18 -0
  81. package/dist/tools/fallback-leader-model-set-tool.d.ts +18 -0
  82. package/dist/tools/fallback-manage-tools.d.ts +8 -45
  83. package/dist/tools/fallback-profile-manage-tool.d.ts +16 -0
  84. package/dist/tools/fallback-provider-key-set-tool.d.ts +17 -0
  85. package/dist/tools/fallback-provider-manage-tool.d.ts +26 -0
  86. package/dist/tools/index.js +5070 -5071
  87. package/dist/types/config/root.d.ts +7 -2
  88. package/dist/types/default-config.d.ts +1 -1
  89. package/dist/types/index.d.ts +54 -55
  90. package/dist/types/index.js +953 -932
  91. package/dist/types/runtime-capability-manifest.d.ts +5 -5
  92. package/dist/types/session-markers.d.ts +12 -0
  93. package/dist/types/session-markers.js +19 -0
  94. package/dist/worktree/worktree-manager.d.ts +1 -1
  95. package/instructions/coordination/subagent-baseline.md +2 -2
  96. package/instructions/llm/prompt-enhancer.md +2 -1
  97. package/instructions/sections/tool/common-patterns.md +21 -0
  98. package/instructions/sections/tool/delegation-compact.md +3 -1
  99. package/instructions/sections/tool/delegation-full.md +5 -1
  100. package/instructions/system-lite.md +28 -3
  101. package/instructions/system-pro.md +37 -8
  102. package/instructions/system.md +4 -2
  103. package/package.json +5 -5
@@ -0,0 +1,15 @@
1
+ export interface OrphanLockCleanResult {
2
+ cleanedGitLocks: string[];
3
+ cleanedWorktrees: string[];
4
+ errors: string[];
5
+ }
6
+ /**
7
+ * Sweeps stale WrongStack worktree lockfiles left after an ungraceful
8
+ * crash (SIGKILL, power outage, OOM). Does not touch Git's own
9
+ * `.git/index.lock` — age is not a liveness signal for that mutex.
10
+ */
11
+ export declare function cleanOrphanLocks(projectRoot: string, options?: {
12
+ isPidAlive?: (pid: number) => boolean;
13
+ maxLockAgeMs?: number;
14
+ }): Promise<OrphanLockCleanResult>;
15
+ //# sourceMappingURL=orphan-lock-cleaner.d.ts.map
@@ -42,6 +42,15 @@ export interface RecoveryPlan {
42
42
  /** Free-form context the agent was working on, if any. */
43
43
  context: string | null;
44
44
  }
45
+ export interface InterruptedToolDetail {
46
+ name: string;
47
+ argsSummary?: string | undefined;
48
+ ts?: string | undefined;
49
+ }
50
+ /**
51
+ * Extracts any unresolved tool calls from a recovery plan's pending events.
52
+ */
53
+ export declare function extractInterruptedTools(plan: RecoveryPlan): InterruptedToolDetail[];
45
54
  /**
46
55
  * Result of `SessionRecovery.recover(sessionId)`. Distinct from
47
56
  * `StaleSession`: a session is "stale" if its latest lifecycle
@@ -0,0 +1,16 @@
1
+ import type { EventBus } from '../../kernel/events.js';
2
+ import type { SecretScrubber } from '../../types/secret-scrubber.js';
3
+ import type { SessionSummary } from '../../types/session.js';
4
+ export interface RenameSessionParams {
5
+ id: string;
6
+ name: string;
7
+ manifest: string;
8
+ jsonlPath: string;
9
+ events?: EventBus | undefined;
10
+ secretScrubber: SecretScrubber;
11
+ readSummaryManifest: (id: string) => Promise<SessionSummary | null>;
12
+ summaryFor: (id: string) => Promise<SessionSummary>;
13
+ appendToIndexStrict: (summary: SessionSummary) => Promise<void>;
14
+ }
15
+ export declare function executeRenameSession(params: RenameSessionParams): Promise<SessionSummary>;
16
+ //# sourceMappingURL=rename-session.d.ts.map
@@ -0,0 +1,26 @@
1
+ import * as fsp from 'node:fs/promises';
2
+ import type { EventBus } from '../../kernel/events.js';
3
+ import type { SecretScrubber } from '../../types/secret-scrubber.js';
4
+ import type { ResumedSession, SessionData, SessionEvent, SessionSummary } from '../../types/session.js';
5
+ import type { SessionCheckpointCas } from '../session-checkpoint-cas.js';
6
+ export interface ResumeSessionParams {
7
+ id: string;
8
+ canonicalId: string;
9
+ file: string;
10
+ projectRoot?: string | undefined;
11
+ events?: EventBus | undefined;
12
+ secretScrubber: SecretScrubber;
13
+ checkpointCas?: SessionCheckpointCas | undefined;
14
+ onAppend?: ((event: SessionEvent) => void) | undefined;
15
+ onAppendBatch?: ((events: SessionEvent[]) => void) | undefined;
16
+ load: (id: string) => Promise<SessionData>;
17
+ readSummaryManifest: (id: string) => Promise<SessionSummary | null>;
18
+ searchEvents: (id: string, predicate: (event: SessionEvent, index: number, ts: string) => boolean) => Promise<Array<{
19
+ event: SessionEvent;
20
+ }>>;
21
+ persistCatalogSummary: (summary: SessionSummary) => Promise<void>;
22
+ logWarn: (msg: string, ctx?: Record<string, unknown>) => void;
23
+ }
24
+ export declare function executeResumeSession(params: ResumeSessionParams): Promise<ResumedSession>;
25
+ export declare function openSessionForAppend(file: string): Promise<fsp.FileHandle>;
26
+ //# sourceMappingURL=resume-session.d.ts.map
@@ -0,0 +1,11 @@
1
+ import type { SessionCatalogProjectClient } from '../../session-catalog/client.js';
2
+ export interface ClearSessionHistoryParams {
3
+ id: string;
4
+ canonical: string;
5
+ catalogClient?: SessionCatalogProjectClient | undefined;
6
+ maintenanceHolderId: string;
7
+ ensureShardDir: (id: string) => Promise<string>;
8
+ sessionPath: (id: string, ext: '.jsonl' | '.summary.json') => string;
9
+ }
10
+ export declare function executeClearSessionHistory(params: ClearSessionHistoryParams): Promise<void>;
11
+ //# sourceMappingURL=session-store-clear.d.ts.map
@@ -0,0 +1,13 @@
1
+ import type { SessionSummary } from '../../types/session.js';
2
+ import type { IndexCacheEntry } from './types.js';
3
+ export declare const COMPACT_EVERY = 30;
4
+ export declare function appendToIndexStrict(dir: string, indexFile: string, summary: SessionSummary, invalidateShard: (id: string) => Promise<void>, onAppended: () => {
5
+ shouldCompact: boolean;
6
+ }, compactInner: () => Promise<void>): Promise<void>;
7
+ export declare function writeTombstone(dir: string, indexFile: string, id: string, invalidateShard: (id: string) => Promise<void>, onTombstone: () => void): Promise<void>;
8
+ export declare function readIndexFile(indexFile: string, currentCache: IndexCacheEntry | null): Promise<{
9
+ summaries: readonly SessionSummary[];
10
+ cache: IndexCacheEntry | null;
11
+ }>;
12
+ export declare function compactIndexInner(indexFile: string, entries: readonly SessionSummary[]): Promise<void>;
13
+ //# sourceMappingURL=session-store-index.d.ts.map
@@ -11,108 +11,35 @@ export declare class DefaultSessionStore implements SessionStore {
11
11
  private readonly logger;
12
12
  private readonly onAppend?;
13
13
  private readonly onAppendBatch?;
14
- /** Present in built production output; source-only tests retain the local compatibility path. */
15
14
  private readonly catalogClient;
16
15
  private readonly maintenanceHolderId;
17
- /**
18
- * In-memory cache for load() results, keyed by session ID. The cache is
19
- * invalidated when the file's mtimeMs or size changes (indicating the
20
- * file was written to). This eliminates redundant full-file reads and
21
- * JSON parses when the same session is loaded multiple times within the
22
- * store's lifetime (e.g., webui session detail views, list() fallbacks).
23
- *
24
- * Max size is capped to prevent unbounded memory growth in long-running
25
- * processes. When the limit is reached, the oldest entry is evicted.
26
- */
27
16
  private readonly _loadCache;
28
17
  private readonly loadCache;
29
18
  private _indexCache;
30
19
  private readonly shardManifestCache;
31
20
  private static readonly LIST_SCAN_CONCURRENCY;
21
+ private indexAppendCount;
32
22
  constructor(opts: SessionStoreOptions);
33
- /**
34
- * Emit a structured warning. Uses the configured Logger when available;
35
- * falls back to console.warn(JSON) so warnings are never silently dropped.
36
- */
37
23
  private logWarn;
38
24
  private scrubSummaries;
39
- /**
40
- * Clear the load() cache. Useful for testing or when the caller knows
41
- * the file has changed externally (e.g., another process wrote to it).
42
- */
43
25
  clearLoadCache(sessionId?: string): void;
44
26
  dispose(): Promise<void>;
45
- /** Absolute path to the session index file. */
46
27
  private get indexFile();
47
- /** Join session ID to its absolute path within the store directory. */
48
28
  private sessionPath;
49
29
  private shardManifestPath;
50
30
  private shardKeyForSessionId;
51
31
  private invalidateShardManifestBySessionId;
52
- /**
53
- * Ensure the directory implied by the session ID exists. When the ID
54
- * contains a date prefix like `2026-06-06/...`, this creates the date
55
- * subdirectory so sessions group naturally by day.
56
- */
57
32
  private ensureShardDir;
58
33
  create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter>;
59
34
  fork(id: string, opts?: SessionForkOptions): Promise<ForkedSession>;
60
- /**
61
- * Implements {@link SessionForkHost.readRawEvents} — the parent stream a fork
62
- * inherits, unmodified.
63
- *
64
- * Deliberately NOT `load()`: that loader empties superseded snapshot payloads
65
- * in place and front-drops events past its retention budget, both of which
66
- * are correct for reconstructing a conversation and wrong for copying a
67
- * journal prefix into a child. Streaming with an accept-everything predicate
68
- * keeps the scrubbing contract (`searchEvents` scrubs each line the same way
69
- * `load()` does) without either transformation.
70
- */
71
35
  readRawEvents(id: string): Promise<SessionEvent[]>;
72
- /**
73
- * Capture the deterministic post-tool workspace identity through the store-owned CAS.
74
- */
75
36
  captureWorkspaceCheckpoint(sessionId: string, promptIndex: number): Promise<WorkspaceCheckpointRef | undefined>;
76
- /**
77
- * Materialize a store-owned checkpoint into an already isolated workspace.
78
- */
79
37
  materializeWorkspaceCheckpoint(checkpoint: WorkspaceCheckpointRef, targetRoot: string): Promise<import("../types/session.js").WorkspaceMaterializationResult>;
80
38
  resolveId(query: string): Promise<string>;
81
39
  resume(id: string): Promise<ResumedSession>;
82
40
  load(id: string): Promise<SessionData>;
83
- /**
84
- * Fast-path loader that skips message reconstruction and adjacency repair.
85
- *
86
- * Use this for callers that only need the raw event stream + session
87
- * metadata — e.g. session listers, analytics, audit, and the TUI's
88
- * "events only" views. It avoids the message array build and
89
- * repairToolUseAdjacency cost on large session files (a long agent
90
- * run can have 50k+ events; rebuilding messages is O(events) and
91
- * allocates per-block, so skipping it is a meaningful win).
92
- *
93
- * The returned data.messages is an empty array; data.toolCallEnds
94
- * is computed from the raw events. usage is the sum across all
95
- * llm_response events — same as full load().
96
- */
97
41
  loadEventsOnly(id: string): Promise<SessionData>;
98
42
  private loadInternal;
99
- /**
100
- * Streaming search over a session's JSONL. Walks the file once, parses
101
- * each event lazily, and yields only the events that match `predicate`.
102
- * Stops as soon as `opts.limit` matches are collected.
103
- *
104
- * Why this exists: `load()` parses the entire file into memory and
105
- * rebuilds `messages`/`toolCallEnds` for every caller. `search()` only
106
- * needs to know which events contain matching text — a per-line
107
- * predicate is enough. The full parse work (and the `_loadCache` poll)
108
- * is wasted in that case.
109
- *
110
- * Memory: O(hits) regardless of file size. Disk: one linear scan,
111
- * terminated at `limit` if the caller asked for one.
112
- *
113
- * Errors: missing file yields []. Corrupt lines are skipped (same
114
- * policy as `load()`). Aborting via `signal` rejects with `AbortError`.
115
- */
116
43
  searchEvents(id: string, predicate: (event: SessionEvent, eventIndex: number, ts: string) => boolean, opts?: {
117
44
  limit?: number | undefined;
118
45
  signal?: AbortSignal | undefined;
@@ -122,16 +49,6 @@ export declare class DefaultSessionStore implements SessionStore {
122
49
  ts: string;
123
50
  }>>;
124
51
  list(limit?: number): Promise<SessionSummary[]>;
125
- /**
126
- * List sessions matching filter criteria, using the cached index.
127
- * Filters are applied BEFORE sorting and slicing, so the caller gets
128
- * exactly `limit` matching sessions — not a slice of a larger fetch.
129
- *
130
- * This avoids the DefaultSessionReader pattern of fetching 1000 sessions
131
- * then linear-filtering: the index is already in memory (readIndex
132
- * caches it), and the filter runs over the cached array without any
133
- * additional disk I/O.
134
- */
135
52
  listFiltered(criteria: {
136
53
  since?: string | undefined;
137
54
  until?: string | undefined;
@@ -141,69 +58,24 @@ export declare class DefaultSessionStore implements SessionStore {
141
58
  titleContains?: string | undefined;
142
59
  limit?: number | undefined;
143
60
  }): Promise<SessionSummary[]>;
144
- private indexAppendCount;
145
- private static readonly COMPACT_EVERY;
146
- /** Append a session summary to the index, propagating persistence failures. */
147
61
  private appendToIndexStrict;
148
- /** Best-effort index append used by writer close. */
149
62
  private appendToIndex;
150
- /** Final summary boundary: daemon is authoritative when available. */
151
63
  private persistCatalogSummary;
152
- /** Append a tombstone entry for a deleted session. */
153
64
  private writeTombstone;
154
- /**
155
- * Compact the index: read all entries, drop tombstones, deduplicate
156
- * (keep latest per session), and rewrite atomically. Acquires the index
157
- * file lock so a concurrent append (this process or another wstack in the
158
- * same project) can't be overwritten by the rewrite.
159
- */
160
65
  private compactIndex;
161
- /**
162
- * Lock-free compaction body. The caller MUST already hold the index file
163
- * lock (via withFileLock(this.indexFile, ...)). Uses atomicWrite for the
164
- * rewrite so the temp file gets a random suffix (no collision between two
165
- * compactions) and the Windows transient-EPERM rename retry.
166
- */
167
66
  private compactIndexInner;
168
- /**
169
- * Read the index file and return deduplicated session summaries.
170
- * Entries with a matching tombstone are filtered out.
171
- * Returns empty array when the index doesn't exist or is corrupt.
172
- */
173
67
  private readIndex;
174
- /**
175
- * Rebuild the index from disk by scanning all sessions and writing a
176
- * fresh _index.jsonl. Useful after manual cleanup or index corruption.
177
- */
178
68
  rebuildIndex(): Promise<number>;
179
69
  private listFromDirectoryScan;
180
70
  private collectShardKeys;
181
71
  private readOrBuildShardManifest;
182
- /**
183
- * Shard manifests are invalidated by other store processes via atomic
184
- * delete/rebuild. Validate the in-memory projection against the persisted
185
- * file so one long-lived process cannot retain another process's stale view.
186
- */
187
72
  private freshShardManifestCacheEntry;
188
73
  private collectSessionFilesInShard;
189
74
  private collectSessionFiles;
190
- /** Recursively collect session IDs from date-shard subdirectories.
191
- * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_…").
192
- * Skips `.jsonl`/`.summary.json` root files, dot-files, and
193
- * sub-directories that belong to fleet/subagent sessions. */
194
75
  private collectSessionIds;
195
76
  private summaryFor;
196
77
  private readSummaryManifest;
197
78
  private summaryHeaderFor;
198
- /**
199
- * Delete a session and all associated files: JSONL, summary, plan/todos
200
- * sidecars, and the session directory (fleet.json, shared/, subagents/).
201
- *
202
- * Individual file deletions are best-effort (logged as structured warnings),
203
- * but a tombstone is always written so readIndex() filters this session out.
204
- * If the session directory itself can't be removed, the error is surfaced
205
- * to the caller so prune() can report it.
206
- */
207
79
  private deleteSession;
208
80
  isEmpty(id: string): Promise<boolean>;
209
81
  delete(id: string): Promise<void>;
@@ -0,0 +1,39 @@
1
+ import type { SessionEvent, SessionMetadata, SessionSummary } from '../types/session.js';
2
+ export interface SessionSummaryTrackerOptions {
3
+ id: string;
4
+ startedAt: string;
5
+ meta: Omit<SessionMetadata, 'startedAt'>;
6
+ resumed?: boolean | undefined;
7
+ initialSummary?: SessionSummary | undefined;
8
+ resolveName?: (() => Promise<Pick<SessionSummary, 'name'> | null>) | undefined;
9
+ }
10
+ export declare class SessionSummaryTracker {
11
+ private readonly id;
12
+ private readonly startedAt;
13
+ private readonly meta;
14
+ private readonly resumed;
15
+ private readonly resolveNameCb?;
16
+ private summary;
17
+ private tokenIn;
18
+ private tokenOut;
19
+ private baseTokenTotal;
20
+ private iterationCount;
21
+ private toolCallCount;
22
+ private toolErrorCount;
23
+ private toolBreakdown;
24
+ private fileChangeCount;
25
+ private compactionCount;
26
+ private messageCount;
27
+ private lastUserMessage;
28
+ private lastActivityAt;
29
+ private outcome;
30
+ private openToolUses;
31
+ constructor(opts: SessionSummaryTrackerOptions);
32
+ get currentSummary(): Readonly<SessionSummary>;
33
+ get pendingToolUses(): string[];
34
+ observe(event: SessionEvent): void;
35
+ recomputeFromDisk(filePath: string): Promise<void>;
36
+ finalize(): Promise<SessionSummary>;
37
+ reset(resetAt: string): void;
38
+ }
39
+ //# sourceMappingURL=session-summary-tracker.d.ts.map
@@ -0,0 +1,43 @@
1
+ import * as fsp from 'node:fs/promises';
2
+ import type { EventBus } from '../kernel/events.js';
3
+ import type { SessionEvent } from '../types/session.js';
4
+ export interface SessionWriteBufferOptions {
5
+ sessionId: string;
6
+ filePath: string;
7
+ getHandle: () => fsp.FileHandle;
8
+ setHandle: (handle: fsp.FileHandle) => void;
9
+ events?: EventBus | undefined;
10
+ getTraceId?: () => string | undefined;
11
+ }
12
+ export declare class SessionWriteBuffer {
13
+ private readonly opts;
14
+ private static readonly FLUSH_INTERVAL_MS;
15
+ private static readonly FLUSH_SIZE;
16
+ private static readonly WRITE_BUFFER_MAX_EVENTS;
17
+ private static readonly WRITE_BUFFER_MAX_BYTES;
18
+ private writeBuffer;
19
+ private writeBufferBytes;
20
+ private flushTimer;
21
+ private bufferOverflowCount;
22
+ private lastBufferOverflowWarnAt;
23
+ private appendFailCount;
24
+ private lastAppendWarnAt;
25
+ private writeChain;
26
+ private flushPromise;
27
+ constructor(opts: SessionWriteBufferOptions);
28
+ get isClosed(): boolean;
29
+ get length(): number;
30
+ private eventBytes;
31
+ push(event: SessionEvent): boolean;
32
+ enqueueWrite(data: string): Promise<void>;
33
+ scheduleFlush(isClosed?: boolean): void;
34
+ cancelTimer(): void;
35
+ flushBuffer(isClosed?: boolean): Promise<void>;
36
+ private flushBufferOnce;
37
+ drainWriteChain(): Promise<void>;
38
+ drainFlushPromise(): Promise<void>;
39
+ flushSync(): void;
40
+ clear(): void;
41
+ shouldFlushNow(): boolean;
42
+ }
43
+ //# sourceMappingURL=session-write-buffer.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { SessionEvent } from '../../types/session.js';
2
+ export declare function isClosedHandleError(err: unknown): boolean;
3
+ export declare function flushBufferSync(filePath: string, events: SessionEvent[]): void;
4
+ //# sourceMappingURL=session-writer-flush.d.ts.map
@@ -0,0 +1,28 @@
1
+ import type { SessionEvent, SessionMetadata, SessionSummary } from '../../types/session.js';
2
+ export declare class SessionWriterSummaryTracker {
3
+ readonly id: string;
4
+ readonly startedAt: string;
5
+ readonly meta: Omit<SessionMetadata, 'startedAt'>;
6
+ summary: SessionSummary;
7
+ tokenIn: number;
8
+ tokenOut: number;
9
+ baseTokenTotal: number;
10
+ iterationCount: number;
11
+ toolCallCount: number;
12
+ toolErrorCount: number;
13
+ toolBreakdown: Record<string, number>;
14
+ fileChangeCount: number;
15
+ compactionCount: number;
16
+ messageCount: number;
17
+ lastUserMessage: string | undefined;
18
+ lastActivityAt: string;
19
+ outcome: SessionSummary['outcome'];
20
+ openToolUses: Set<string>;
21
+ constructor(id: string, startedAt: string, meta: Omit<SessionMetadata, 'startedAt'>, resumed: boolean, initialSummary?: SessionSummary | undefined);
22
+ get pendingToolUses(): string[];
23
+ observe(event: SessionEvent): void;
24
+ recomputeFromDisk(filePath: string): Promise<void>;
25
+ finalize(endedAt: string): SessionSummary;
26
+ reset(resetAt: string): void;
27
+ }
28
+ //# sourceMappingURL=session-writer-summary-tracker.d.ts.map
@@ -0,0 +1,18 @@
1
+ import type { Tool } from '../types/tool.js';
2
+ import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
3
+ export declare const AGENT_MODEL_ASSIGN_TOOL_NAME = "agent_model_assign";
4
+ interface AgentModelAssignInput {
5
+ role: string;
6
+ provider?: string | undefined;
7
+ model?: string | undefined;
8
+ profile?: string | undefined;
9
+ clear?: boolean | undefined;
10
+ }
11
+ interface AgentModelAssignOutput {
12
+ status: 'ok' | 'error';
13
+ message: string;
14
+ role?: string;
15
+ }
16
+ export declare function createAgentModelAssignTool(opts: FallbackManageToolOptions): Tool<AgentModelAssignInput, AgentModelAssignOutput>;
17
+ export {};
18
+ //# sourceMappingURL=fallback-agent-model-assign-tool.d.ts.map
@@ -0,0 +1,18 @@
1
+ import type { Tool } from '../types/tool.js';
2
+ import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
3
+ export declare const LEADER_MODEL_SET_TOOL_NAME = "leader_model_set";
4
+ interface LeaderModelSetInput {
5
+ action: 'show' | 'set' | 'profile' | 'toggle';
6
+ provider?: string | undefined;
7
+ model?: string | undefined;
8
+ profile?: string | undefined;
9
+ toggle?: 'fallbackAuto' | 'favoriteModelsOnly' | undefined;
10
+ value?: boolean | undefined;
11
+ }
12
+ interface LeaderModelSetOutput {
13
+ status: 'ok' | 'error';
14
+ message: string;
15
+ }
16
+ export declare function createLeaderModelSetTool(opts: FallbackManageToolOptions): Tool<LeaderModelSetInput, LeaderModelSetOutput>;
17
+ export {};
18
+ //# sourceMappingURL=fallback-leader-model-set-tool.d.ts.map
@@ -2,56 +2,19 @@
2
2
  * LLM-accessible tools covering every provider/model/fallback configurable area
3
3
  * in the system: favorites, fallback chains & profiles, provider management,
4
4
  * API key handling, leader model, per-role model assignment, and system view.
5
- *
6
- * DESIGN: Every operation that accepts a provider/model reference validates
7
- * the entry against the user's `favoriteModels` list FIRST. This means all
8
- * fallback additions, profiles, and role assignments are restricted to
9
- * user-curated favorites — the LLM cannot add arbitrary unknown models.
10
- *
11
- * Exceptions:
12
- * - Removing entries (chain, profile, favorites) works on any existing entry.
13
- * - Listing/viewing works unconditionally.
14
- * - The active leader model itself is not restricted (it's already set).
15
- *
16
- * Tools (8 total):
17
- * favorite_manage — List, add, remove favorite models.
18
- * fallback_chain_manage — View, add, insert, remove, clear the active chain.
19
- * fallback_profile_manage — List, create/update, delete named profiles.
20
- * agent_model_assign — Assign model/profile to role/phase/* in the matrix.
21
- * provider_manage — List, add, configure, remove provider entries.
22
- * provider_key_set — Set API key via env var, direct key, or interactive prompt.
23
- * leader_model_set — View/set leader model, derive from profile, toggle settings.
24
- * system_config_view — Comprehensive view + validation doctor for full config.
25
- *
26
- * Usage from an agent:
27
- * ```
28
- * favorite_manage({ action: "list" })
29
- * favorite_manage({ action: "add", model: "anthropic/claude-sonnet-4" })
30
- * fallback_chain_manage({ action: "add", model: "anthropic/claude-haiku-3" })
31
- * fallback_profile_manage({ action: "set", name: "fast", chain: ["openai/gpt-4o-mini"] })
32
- * agent_model_assign({ role: "security-scanner", provider: "anthropic", model: "claude-haiku-3" })
33
- * provider_key_set({ provider: "openai", envVar: "OPENAI_API_KEY" })
34
- * leader_model_set({ action: "show" })
35
- * system_config_view({ section: "all" })
36
- * ```
37
5
  */
38
6
  import type { Tool } from '../types/tool.js';
7
+ import { FALLBACK_CHAIN_MANAGE_TOOL_NAME } from './fallback-chain-manage-tool.js';
8
+ import { FAVORITE_MANAGE_TOOL_NAME } from './fallback-favorite-manage-tool.js';
39
9
  import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
40
- export { FALLBACK_CHAIN_MANAGE_TOOL_NAME } from './fallback-chain-manage-tool.js';
41
- export declare const FALLBACK_PROFILE_MANAGE_TOOL_NAME = "fallback_profile_manage";
42
- export declare const AGENT_MODEL_ASSIGN_TOOL_NAME = "agent_model_assign";
43
- export { FAVORITE_MANAGE_TOOL_NAME } from './fallback-favorite-manage-tool.js';
10
+ import { FALLBACK_PROFILE_MANAGE_TOOL_NAME } from './fallback-profile-manage-tool.js';
11
+ import { AGENT_MODEL_ASSIGN_TOOL_NAME } from './fallback-agent-model-assign-tool.js';
12
+ import { PROVIDER_MANAGE_TOOL_NAME, validateProviderBaseUrl } from './fallback-provider-manage-tool.js';
13
+ import { PROVIDER_KEY_SET_TOOL_NAME } from './fallback-provider-key-set-tool.js';
14
+ import { LEADER_MODEL_SET_TOOL_NAME } from './fallback-leader-model-set-tool.js';
15
+ export { FALLBACK_CHAIN_MANAGE_TOOL_NAME, FALLBACK_PROFILE_MANAGE_TOOL_NAME, AGENT_MODEL_ASSIGN_TOOL_NAME, FAVORITE_MANAGE_TOOL_NAME, PROVIDER_MANAGE_TOOL_NAME, PROVIDER_KEY_SET_TOOL_NAME, LEADER_MODEL_SET_TOOL_NAME, validateProviderBaseUrl, };
44
16
  export * from './fallback-system-config-view-tool.js';
45
17
  export type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
46
- export declare const PROVIDER_MANAGE_TOOL_NAME = "provider_manage";
47
- /**
48
- * Reject provider base URLs that are malformed, non-HTTP, or carry embedded
49
- * credentials (WS-013). Private and loopback hosts stay allowed on purpose —
50
- * Ollama, LM Studio and omniroute are first-class local providers.
51
- */
52
- export declare function validateProviderBaseUrl(raw: string): string | null;
53
- export declare const PROVIDER_KEY_SET_TOOL_NAME = "provider_key_set";
54
- export declare const LEADER_MODEL_SET_TOOL_NAME = "leader_model_set";
55
18
  /**
56
19
  * Create all 8 provider/model/fallback management tools that LLMs can call.
57
20
  *
@@ -0,0 +1,16 @@
1
+ import type { Tool } from '../types/tool.js';
2
+ import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
3
+ export declare const FALLBACK_PROFILE_MANAGE_TOOL_NAME = "fallback_profile_manage";
4
+ interface FallbackProfileInput {
5
+ action: 'list' | 'set' | 'delete';
6
+ name?: string | undefined;
7
+ chain?: string[] | undefined;
8
+ }
9
+ interface FallbackProfileOutput {
10
+ status: 'ok' | 'error';
11
+ message: string;
12
+ profiles?: Record<string, string[]>;
13
+ }
14
+ export declare function createFallbackProfileManageTool(opts: FallbackManageToolOptions): Tool<FallbackProfileInput, FallbackProfileOutput>;
15
+ export {};
16
+ //# sourceMappingURL=fallback-profile-manage-tool.d.ts.map
@@ -0,0 +1,17 @@
1
+ import type { Tool } from '../types/tool.js';
2
+ import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
3
+ export declare const PROVIDER_KEY_SET_TOOL_NAME = "provider_key_set";
4
+ interface ProviderKeySetInput {
5
+ provider: string;
6
+ key?: string | undefined;
7
+ envVar?: string | undefined;
8
+ label?: string | undefined;
9
+ setActive?: boolean | undefined;
10
+ }
11
+ interface ProviderKeySetOutput {
12
+ status: 'ok' | 'error' | 'needs_key';
13
+ message: string;
14
+ }
15
+ export declare function createProviderKeySetTool(opts: FallbackManageToolOptions): Tool<ProviderKeySetInput, ProviderKeySetOutput>;
16
+ export {};
17
+ //# sourceMappingURL=fallback-provider-key-set-tool.d.ts.map
@@ -0,0 +1,26 @@
1
+ import type { Tool } from '../types/tool.js';
2
+ import type { FallbackManageToolOptions } from './fallback-manage-tool-options.js';
3
+ export declare const PROVIDER_MANAGE_TOOL_NAME = "provider_manage";
4
+ interface ProviderManageInput {
5
+ action: 'list' | 'add' | 'configure' | 'remove';
6
+ provider?: string | undefined;
7
+ type?: string | undefined;
8
+ models?: string[] | undefined;
9
+ baseUrl?: string | undefined;
10
+ family?: string | undefined;
11
+ envVars?: string[] | undefined;
12
+ autoDiscoverModels?: boolean | undefined;
13
+ apiKey?: string | undefined;
14
+ }
15
+ interface ProviderManageOutput {
16
+ status: 'ok' | 'error';
17
+ message: string;
18
+ providers?: string[];
19
+ }
20
+ export declare const CREDENTIAL_SELECTOR_FIELDS: readonly ['apiKey', 'apiKeys', 'activeKey', 'envVars'];
21
+ export declare function envVarsClaimedByOtherProviders(providers: Record<string, Record<string, unknown>>, exceptProvider: string): Map<string, string>;
22
+ export declare function rejectBorrowedEnvVars(providers: Record<string, Record<string, unknown>>, provider: string, requested: readonly unknown[] | undefined): string | null;
23
+ export declare function validateProviderBaseUrl(raw: string): string | null;
24
+ export declare function createProviderManageTool(opts: FallbackManageToolOptions): Tool<ProviderManageInput, ProviderManageOutput>;
25
+ export {};
26
+ //# sourceMappingURL=fallback-provider-manage-tool.d.ts.map