qlogicagent 0.5.0 → 0.5.3

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 (173) hide show
  1. package/README.md +402 -402
  2. package/dist/agent.js +18 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/contracts.js +1 -0
  5. package/dist/index.js +22 -0
  6. package/dist/orchestration.js +125 -0
  7. package/dist/types/agent/agent.d.ts +43 -0
  8. package/dist/types/agent/constants.d.ts +47 -0
  9. package/dist/types/agent/tool-loop.d.ts +96 -0
  10. package/dist/types/agent/types.d.ts +250 -0
  11. package/dist/types/cli/main.d.ts +11 -0
  12. package/dist/types/cli/stdio-server.d.ts +56 -0
  13. package/dist/types/cli/tool-bootstrap.d.ts +21 -0
  14. package/dist/types/config/config.d.ts +17 -0
  15. package/dist/types/contracts/hooks.d.ts +175 -0
  16. package/dist/types/contracts/index.d.ts +10 -0
  17. package/dist/types/contracts/planner.d.ts +35 -0
  18. package/dist/types/contracts/skill-candidate.d.ts +63 -0
  19. package/dist/types/contracts/todo.d.ts +14 -0
  20. package/dist/types/index.d.ts +13 -0
  21. package/dist/types/llm/builtin-providers.d.ts +10 -0
  22. package/dist/types/llm/debug-transport.d.ts +12 -0
  23. package/dist/types/llm/index.d.ts +16 -0
  24. package/dist/types/llm/llm-client.d.ts +43 -0
  25. package/dist/types/llm/model-catalog.d.ts +53 -0
  26. package/dist/types/llm/provider-def.d.ts +59 -0
  27. package/dist/types/llm/provider-registry.d.ts +54 -0
  28. package/dist/types/llm/transport.d.ts +62 -0
  29. package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
  30. package/dist/types/llm/transports/openai-chat.d.ts +36 -0
  31. package/dist/types/orchestration/agent-registry.d.ts +46 -0
  32. package/dist/types/orchestration/context-collapse.d.ts +58 -0
  33. package/dist/types/orchestration/context-compression.d.ts +301 -0
  34. package/dist/types/orchestration/conversation-repair.d.ts +61 -0
  35. package/dist/types/orchestration/curator-scheduler.d.ts +119 -0
  36. package/dist/types/orchestration/error-classification.d.ts +12 -0
  37. package/dist/types/orchestration/failover-classification.d.ts +8 -0
  38. package/dist/types/orchestration/failover-error.d.ts +33 -0
  39. package/dist/types/orchestration/fork-subagent.d.ts +100 -0
  40. package/dist/types/orchestration/index.d.ts +113 -0
  41. package/dist/types/orchestration/memory-provider.d.ts +14 -0
  42. package/dist/types/orchestration/reactive-compact.d.ts +73 -0
  43. package/dist/types/orchestration/retry-loop.d.ts +69 -0
  44. package/dist/types/orchestration/skill-candidate.d.ts +52 -0
  45. package/dist/types/orchestration/skill-consolidation.d.ts +123 -0
  46. package/dist/types/orchestration/skill-improvement.d.ts +59 -0
  47. package/dist/types/orchestration/skill-similarity.d.ts +98 -0
  48. package/dist/types/orchestration/task-types.d.ts +142 -0
  49. package/dist/types/orchestration/team-orchestration.d.ts +195 -0
  50. package/dist/types/orchestration/team-tool-loop-wiring.d.ts +92 -0
  51. package/dist/types/orchestration/tool-choice-policy.d.ts +54 -0
  52. package/dist/types/orchestration/tool-loop-state.d.ts +50 -0
  53. package/dist/types/orchestration/tool-schema.d.ts +39 -0
  54. package/dist/types/orchestration/turn-loop-guard.d.ts +86 -0
  55. package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
  56. package/dist/types/runtime/execution/forked-agent.d.ts +111 -0
  57. package/dist/types/runtime/execution/index.d.ts +6 -0
  58. package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
  59. package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
  60. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
  61. package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
  62. package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
  63. package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
  64. package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
  65. package/dist/types/runtime/hooks/index.d.ts +3 -0
  66. package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
  67. package/dist/types/runtime/index.d.ts +5 -0
  68. package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
  69. package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
  70. package/dist/types/runtime/infra/index.d.ts +6 -0
  71. package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
  72. package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
  73. package/dist/types/runtime/infra/token-budget.d.ts +92 -0
  74. package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
  75. package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
  76. package/dist/types/runtime/prompt/index.d.ts +3 -0
  77. package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
  78. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
  79. package/dist/types/runtime/session/index.d.ts +2 -0
  80. package/dist/types/runtime/session/session-memory.d.ts +91 -0
  81. package/dist/types/runtime/session/session-persistence.d.ts +94 -0
  82. package/dist/types/runtime/session/session-state.d.ts +117 -0
  83. package/dist/types/skills/index.d.ts +125 -0
  84. package/dist/types/skills/mcp/index.d.ts +3 -0
  85. package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
  86. package/dist/types/skills/mcp/mcp-manager.d.ts +84 -0
  87. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
  88. package/dist/types/skills/memory-extractor.d.ts +64 -0
  89. package/dist/types/skills/memory-query-tool.d.ts +43 -0
  90. package/dist/types/skills/memory-store.d.ts +66 -0
  91. package/dist/types/skills/memory-tool.d.ts +67 -0
  92. package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
  93. package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
  94. package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
  95. package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
  96. package/dist/types/skills/permissions/index.d.ts +12 -0
  97. package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
  98. package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
  99. package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
  100. package/dist/types/skills/permissions/types.d.ts +113 -0
  101. package/dist/types/skills/plugins/index.d.ts +2 -0
  102. package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
  103. package/dist/types/skills/plugins/plugin-loader.d.ts +45 -0
  104. package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
  105. package/dist/types/skills/portable-tool.d.ts +71 -0
  106. package/dist/types/skills/qmemory-adapter.d.ts +42 -0
  107. package/dist/types/skills/skill-frontmatter.d.ts +19 -0
  108. package/dist/types/skills/skill-guard.d.ts +23 -0
  109. package/dist/types/skills/skill-loader.d.ts +16 -0
  110. package/dist/types/skills/skill-source.d.ts +119 -0
  111. package/dist/types/skills/skill-types.d.ts +199 -0
  112. package/dist/types/skills/think-tool.d.ts +16 -0
  113. package/dist/types/skills/todo-tool.d.ts +63 -0
  114. package/dist/types/skills/tool-registry.d.ts +29 -0
  115. package/dist/types/skills/tools/agent-tool.d.ts +91 -0
  116. package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
  117. package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
  118. package/dist/types/skills/tools/brief-tool.d.ts +74 -0
  119. package/dist/types/skills/tools/browser-tool.d.ts +114 -0
  120. package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
  121. package/dist/types/skills/tools/config-tool.d.ts +63 -0
  122. package/dist/types/skills/tools/cron-tool.d.ts +116 -0
  123. package/dist/types/skills/tools/edit-tool.d.ts +43 -0
  124. package/dist/types/skills/tools/exec-tool.d.ts +97 -0
  125. package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
  126. package/dist/types/skills/tools/instructions-tool.d.ts +103 -0
  127. package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
  128. package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
  129. package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
  130. package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
  131. package/dist/types/skills/tools/memory-tool.d.ts +74 -0
  132. package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
  133. package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
  134. package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
  135. package/dist/types/skills/tools/notify-tool.d.ts +53 -0
  136. package/dist/types/skills/tools/patch-tool.d.ts +45 -0
  137. package/dist/types/skills/tools/pdf-tool.d.ts +66 -0
  138. package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
  139. package/dist/types/skills/tools/read-tool.d.ts +51 -0
  140. package/dist/types/skills/tools/repl-tool.d.ts +70 -0
  141. package/dist/types/skills/tools/search-tool.d.ts +112 -0
  142. package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
  143. package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
  144. package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
  145. package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
  146. package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
  147. package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
  148. package/dist/types/skills/tools/shell/index.d.ts +17 -0
  149. package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
  150. package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
  151. package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
  152. package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
  153. package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
  154. package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
  155. package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
  156. package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
  157. package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
  158. package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
  159. package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
  160. package/dist/types/skills/tools/task-tool.d.ts +104 -0
  161. package/dist/types/skills/tools/team-tool.d.ts +89 -0
  162. package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
  163. package/dist/types/skills/tools/tts-tool.d.ts +38 -0
  164. package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
  165. package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
  166. package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
  167. package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
  168. package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
  169. package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
  170. package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
  171. package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
  172. package/dist/types/skills/tools/write-tool.d.ts +45 -0
  173. package/package.json +4 -2
@@ -0,0 +1,301 @@
1
+ export interface CompressibleMessage {
2
+ role: string;
3
+ content?: string | unknown;
4
+ tool_call_id?: string;
5
+ tool_calls?: unknown;
6
+ name?: string;
7
+ }
8
+ export interface CompressionResult {
9
+ messages: CompressibleMessage[];
10
+ droppedCount: number;
11
+ strategy: string;
12
+ /** Phase 4: optional metrics from the compression pass */
13
+ metrics?: CompressionMetrics;
14
+ }
15
+ export interface CompressionMetrics {
16
+ tokensBefore: number;
17
+ tokensAfter: number;
18
+ compressionRatio: number;
19
+ /** ms elapsed for this strategy pass */
20
+ latencyMs: number;
21
+ /** Whether an LLM call was made during this pass */
22
+ usedLlm: boolean;
23
+ /** Whether prompt cache was invalidated by compression */
24
+ cacheInvalidated?: boolean;
25
+ }
26
+ export interface CompressionStrategy {
27
+ compress(messages: CompressibleMessage[], budget: number): CompressionResult;
28
+ }
29
+ /**
30
+ * Async compression strategy — required for LLM-based summarization.
31
+ * Falls back to sync `compress` when the caller doesn't support async.
32
+ */
33
+ export interface AsyncCompressionStrategy extends CompressionStrategy {
34
+ compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
35
+ }
36
+ export declare function isAsyncCompressionStrategy(s: CompressionStrategy): s is AsyncCompressionStrategy;
37
+ /** Caller-provided LLM summarization function (wired by Hub). */
38
+ export type SummarizeFn = (messages: CompressibleMessage[], instruction: string) => Promise<string>;
39
+ export declare class SlidingWindowStrategy implements CompressionStrategy {
40
+ private estimateTokens;
41
+ constructor(estimateTokens: (msg: CompressibleMessage) => number);
42
+ compress(messages: CompressibleMessage[], budget: number): CompressionResult;
43
+ }
44
+ export declare class SummarizeOldStrategy implements CompressionStrategy {
45
+ private recentCount;
46
+ private summarize;
47
+ constructor(recentCount: number, summarize: (messages: CompressibleMessage[]) => string);
48
+ compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
49
+ }
50
+ export declare class ToolResultTrimStrategy implements CompressionStrategy {
51
+ private maxToolResultChars;
52
+ constructor(maxToolResultChars?: number);
53
+ compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
54
+ }
55
+ export declare function composeStrategies(...strategies: CompressionStrategy[]): CompressionStrategy;
56
+ /**
57
+ * Compose strategies with async support — if any strategy is async,
58
+ * the pipeline becomes async.
59
+ */
60
+ export declare function composeAsyncStrategies(...strategies: CompressionStrategy[]): AsyncCompressionStrategy;
61
+ /**
62
+ * Build the structured 9-section summary instruction for the LLM.
63
+ * Based on Claude Code's Full Compact mode, adapted for Hub.
64
+ */
65
+ export declare function buildStructuredSummaryPrompt(messagesToSummarize: CompressibleMessage[], opts?: {
66
+ taskContext?: string;
67
+ }): string;
68
+ export interface HeadTailProtectionConfig {
69
+ /** Number of initial user-assistant exchanges to protect (default: 1) */
70
+ protectedHeadExchanges: number;
71
+ /** Number of recent messages to always keep (default: 8 = ~4 exchanges) */
72
+ protectedTailMessages: number;
73
+ /** The summarization callback */
74
+ summarize: SummarizeFn;
75
+ /** Optional token estimator */
76
+ estimateTokens?: (msg: CompressibleMessage) => number;
77
+ /** Optional extra context for the summary prompt */
78
+ taskContext?: string;
79
+ }
80
+ /**
81
+ * Phase 2.2: Head/Tail protected summarization.
82
+ *
83
+ * Protects: system messages + first exchange + last N messages.
84
+ * Compresses: middle section via LLM summarization.
85
+ */
86
+ export declare class HeadTailProtectedStrategy implements AsyncCompressionStrategy {
87
+ private config;
88
+ constructor(config: HeadTailProtectionConfig);
89
+ compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
90
+ compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
91
+ }
92
+ export interface IncrementalCompactConfig {
93
+ /** Messages newer than this count are never summarized (default: 12) */
94
+ preserveRecentCount: number;
95
+ /** Summarization callback */
96
+ summarize: SummarizeFn;
97
+ /** Token estimator */
98
+ estimateTokens?: (msg: CompressibleMessage) => number;
99
+ }
100
+ /**
101
+ * Phase 2.3: Incremental (partial) compaction.
102
+ *
103
+ * Only summarizes the oldest messages beyond the preserve window.
104
+ * Avoids repeatedly re-summarizing already-compressed content.
105
+ * If a previous summary marker exists, only new old messages are compressed.
106
+ */
107
+ export declare class IncrementalCompactStrategy implements AsyncCompressionStrategy {
108
+ private config;
109
+ constructor(config: IncrementalCompactConfig);
110
+ compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
111
+ compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
112
+ }
113
+ export interface CacheAwareCompressionConfig {
114
+ /** The inner strategy to delegate to */
115
+ inner: CompressionStrategy;
116
+ /** Token estimator */
117
+ estimateTokens?: (msg: CompressibleMessage) => number;
118
+ /**
119
+ * Callback: notify when prompt cache was invalidated by compression.
120
+ * Hub uses this to set pendingPostCompaction and track cache miss rate.
121
+ */
122
+ onCacheInvalidated?: (info: {
123
+ droppedCount: number;
124
+ strategy: string;
125
+ }) => void;
126
+ }
127
+ /**
128
+ * Phase 3: Cache-aware wrapper.
129
+ *
130
+ * Wraps any strategy and tracks whether compression invalidated the
131
+ * provider prompt cache. System prompt prefix stability is preserved
132
+ * by never modifying system[0] (the original system prompt).
133
+ */
134
+ export declare class CacheAwareCompressionStrategy implements AsyncCompressionStrategy {
135
+ private config;
136
+ constructor(config: CacheAwareCompressionConfig);
137
+ compress(messages: CompressibleMessage[], budget: number): CompressionResult;
138
+ compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
139
+ }
140
+ export interface AdaptiveBudgetConfig {
141
+ /** Model context window size in tokens */
142
+ modelContextWindow: number;
143
+ /** Target usage ratio (0.0–1.0, default 0.75) — trigger compaction at this fraction */
144
+ targetUsageRatio: number;
145
+ /** Minimum guaranteed budget in tokens */
146
+ minBudget: number;
147
+ /** Maximum budget (usually = modelContextWindow) */
148
+ maxBudget: number;
149
+ }
150
+ export declare const DEFAULT_ADAPTIVE_BUDGET_CONFIG: AdaptiveBudgetConfig;
151
+ /**
152
+ * Compute the adaptive token budget for a given model + message history.
153
+ *
154
+ * Adjusts based on model context window, and uses the target ratio
155
+ * so compression triggers before hitting the hard limit.
156
+ */
157
+ export declare function computeAdaptiveBudget(config?: Partial<AdaptiveBudgetConfig>): number;
158
+ /**
159
+ * Decide which compression tier to use based on current token count vs budget.
160
+ */
161
+ export type CompressionTier = "none" | "trim-only" | "sliding-window" | "llm-summarize";
162
+ export declare function selectCompressionTier(currentTokens: number, budget: number): CompressionTier;
163
+ export interface CompressionEvent {
164
+ timestamp: number;
165
+ strategy: string;
166
+ tokensBefore: number;
167
+ tokensAfter: number;
168
+ droppedCount: number;
169
+ latencyMs: number;
170
+ usedLlm: boolean;
171
+ cacheInvalidated: boolean;
172
+ tier: CompressionTier;
173
+ }
174
+ export interface CompressionMetricsSnapshot {
175
+ totalCompressions: number;
176
+ totalLlmCalls: number;
177
+ totalCacheInvalidations: number;
178
+ averageCompressionRatio: number;
179
+ averageLatencyMs: number;
180
+ totalTokensSaved: number;
181
+ recentEvents: CompressionEvent[];
182
+ }
183
+ export declare class CompressionMetricsCollector {
184
+ private events;
185
+ private maxEvents;
186
+ constructor(maxEvents?: number);
187
+ record(event: CompressionEvent): void;
188
+ snapshot(): CompressionMetricsSnapshot;
189
+ reset(): void;
190
+ }
191
+ /**
192
+ * A pluggable context engine. Only one can be active at a time.
193
+ * The default engine uses the 4-layer compression funnel.
194
+ */
195
+ export interface ContextEngine {
196
+ /** Unique engine identifier */
197
+ readonly id: string;
198
+ /** Human-readable label */
199
+ readonly label: string;
200
+ /** Compress messages for a turn */
201
+ compressAsync(messages: CompressibleMessage[], budget: number, context?: {
202
+ model?: string;
203
+ sessionId?: string;
204
+ }): Promise<CompressionResult>;
205
+ }
206
+ /**
207
+ * Registry for context engines. Enforces single-active constraint.
208
+ */
209
+ export declare class ContextEngineRegistry {
210
+ private engines;
211
+ private activeId;
212
+ register(engine: ContextEngine): void;
213
+ activate(id: string): boolean;
214
+ getActive(): ContextEngine | undefined;
215
+ listEngines(): Array<{
216
+ id: string;
217
+ label: string;
218
+ active: boolean;
219
+ }>;
220
+ }
221
+ /**
222
+ * MicroCompact — selective clearing of old compactable tool results.
223
+ *
224
+ * CC parity: microCompact.ts
225
+ *
226
+ * For tool result messages from COMPACTABLE_TOOLS, if the message is
227
+ * "old enough" (not in the most recent N messages), replace its content
228
+ * with a compact "[result cleared]" marker. This preserves the tool call
229
+ * structure (so the LLM knows what was called) but reclaims token budget.
230
+ *
231
+ * This is a lighter alternative to full summarization — it runs BEFORE
232
+ * LLM summarization as a first-pass reduction.
233
+ */
234
+ export declare class MicroCompactStrategy implements CompressionStrategy {
235
+ /** Number of recent messages to preserve (don't clear) */
236
+ private preserveRecentCount;
237
+ /** Token estimator */
238
+ private estimateTokens;
239
+ constructor(
240
+ /** Number of recent messages to preserve (don't clear) */
241
+ preserveRecentCount?: number,
242
+ /** Token estimator */
243
+ estimateTokens?: (msg: CompressibleMessage) => number);
244
+ compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
245
+ }
246
+ /**
247
+ * After compaction, the most recently read/edited files may have been
248
+ * dropped from the conversation. CC re-injects up to N file contents
249
+ * to ensure the agent doesn't lose awareness of files it was working with.
250
+ *
251
+ * CC parity: compact.ts postCompactFileStateRecovery
252
+ */
253
+ export interface PostCompactRecoveryConfig {
254
+ /** Maximum number of files to re-inject (default 5) */
255
+ maxFiles: number;
256
+ /** Maximum total tokens for re-injected files (default 50000) */
257
+ maxTokenBudget: number;
258
+ /** Function to read a file from disk (injected by caller) */
259
+ readFile: (path: string) => Promise<string | null>;
260
+ /** Token estimator */
261
+ estimateTokens?: (text: string) => number;
262
+ }
263
+ /**
264
+ * Extract file paths that were recently read/edited from the conversation.
265
+ * Looks at tool calls and results for file path arguments.
266
+ */
267
+ export declare function extractRecentFilePaths(messages: CompressibleMessage[]): string[];
268
+ /**
269
+ * Re-inject recently-used file contents after compaction.
270
+ *
271
+ * Call this AFTER compression but BEFORE sending to the LLM.
272
+ * Appends file content as system messages at the end of the
273
+ * system message block.
274
+ */
275
+ export declare function postCompactFileRecovery(compressedMessages: CompressibleMessage[], originalMessages: CompressibleMessage[], config: PostCompactRecoveryConfig): Promise<CompressibleMessage[]>;
276
+ /**
277
+ * Snip Compact — permanently remove specific messages by identifier.
278
+ *
279
+ * CC parity: services/compact/snipCompact.ts
280
+ *
281
+ * Unlike sliding window or summarization, snip removes messages by
282
+ * their unique id (tool_call_id, or index-based). This is used for:
283
+ * - Removing old tool results that are known to be stale
284
+ * - Dropping large image/media messages after they've been processed
285
+ * - Clearing tombstoned messages from the transcript
286
+ *
287
+ * Snip runs BEFORE microcompact and autocompact — both may fire
288
+ * after snip if the result is still over threshold.
289
+ */
290
+ export interface SnipResult {
291
+ messages: CompressibleMessage[];
292
+ tokensFreed: number;
293
+ removedCount: number;
294
+ /** Optional boundary message to yield (marks snip point in transcript). */
295
+ boundaryMessage?: CompressibleMessage;
296
+ }
297
+ /**
298
+ * Remove messages whose tool_call_id or name matches the removedIds set.
299
+ * If no removedIds are pending, this is a no-op.
300
+ */
301
+ export declare function snipCompactIfNeeded(messages: CompressibleMessage[], removedIds: Set<string>, estimateTokens?: (msg: CompressibleMessage) => number): SnipResult;
@@ -0,0 +1,61 @@
1
+ export interface OpenAiToolCall {
2
+ id: string;
3
+ type: "function";
4
+ function: {
5
+ name: string;
6
+ arguments: string;
7
+ };
8
+ }
9
+ export interface OpenAiChatToolCallRef {
10
+ id?: string;
11
+ function?: {
12
+ name?: string;
13
+ arguments?: string;
14
+ };
15
+ name?: string;
16
+ [key: string]: unknown;
17
+ }
18
+ export interface OpenAiChatMessageLike {
19
+ role: string;
20
+ content?: unknown;
21
+ tool_calls?: OpenAiChatToolCallRef[];
22
+ tool_call_id?: string;
23
+ [key: string]: unknown;
24
+ }
25
+ export interface OpenAiResponsesItemLike {
26
+ type: string;
27
+ id?: string;
28
+ call_id?: string;
29
+ role?: string;
30
+ content?: unknown;
31
+ status?: string;
32
+ [key: string]: unknown;
33
+ }
34
+ export interface ConversationRepairOptions {
35
+ stopReason?: string;
36
+ placeholderToolResult?: string;
37
+ placeholderFunctionCallOutput?: string;
38
+ forcedStopReasons?: readonly string[];
39
+ }
40
+ type ContentPart = {
41
+ type: string;
42
+ text?: string;
43
+ [key: string]: unknown;
44
+ };
45
+ export type { ContentPart };
46
+ export declare function sanitizeOpenAiChatMessages<T extends OpenAiChatMessageLike>(messages: readonly T[]): T[];
47
+ export declare function ensureAssistantReasoningContent<T extends Record<string, unknown>>(messages: readonly T[], defaultValue?: string): T[];
48
+ export declare function stripForcedStopAssistantToolMetadata<T extends OpenAiChatMessageLike>(messages: readonly T[], options?: ConversationRepairOptions): T[];
49
+ export declare function injectDanglingToolCallPlaceholders<T extends OpenAiChatMessageLike>(messages: readonly T[], options?: ConversationRepairOptions): T[];
50
+ export declare function repairOpenAiChatConversation<T extends OpenAiChatMessageLike>(messages: readonly T[], options?: ConversationRepairOptions): T[];
51
+ export declare function downgradeOpenAiFunctionCallReasoningPairs<T extends {
52
+ role?: unknown;
53
+ content?: unknown;
54
+ toolCallId?: unknown;
55
+ toolUseId?: unknown;
56
+ }>(messages: readonly T[]): T[];
57
+ export declare function downgradeOpenAiReasoningBlocks<T extends {
58
+ role?: unknown;
59
+ content?: unknown;
60
+ }>(messages: readonly T[]): T[];
61
+ export declare function repairOpenAiResponsesItems<T extends OpenAiResponsesItemLike>(items: readonly T[], options?: ConversationRepairOptions): T[];
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Curator scheduler — pure strategy for autonomous skill library
3
+ * maintenance. Decides WHEN to run the curator review cycle and
4
+ * computes automatic lifecycle transitions (active → stale → archived).
5
+ *
6
+ * No I/O — all functions are pure; the caller supplies timestamps and
7
+ * skill records, and receives transition instructions back.
8
+ */
9
+ /** Policy knobs for the curator scheduler. */
10
+ export interface CuratorSchedulePolicy {
11
+ /** Minimum idle seconds before curator may trigger (default: 7200 = 2 h). */
12
+ minIdleSeconds: number;
13
+ /** Minimum interval between curator runs in seconds (default: 604800 = 7 days). */
14
+ intervalSeconds: number;
15
+ /** Days without activity before marking a skill stale (default: 30). */
16
+ staleAfterDays: number;
17
+ /** Days without activity before archiving a stale skill (default: 90). */
18
+ archiveAfterDays: number;
19
+ /** Maximum skills to process in one LLM review pass (default: 50). */
20
+ maxReviewBatchSize: number;
21
+ }
22
+ export declare const DEFAULT_CURATOR_SCHEDULE_POLICY: CuratorSchedulePolicy;
23
+ /** Persistent curator state (stored by the host runtime). */
24
+ export interface CuratorState {
25
+ /** ISO-8601 timestamp of last curator run. */
26
+ lastRunAt: string | null;
27
+ /** Duration of last run in seconds. */
28
+ lastRunDurationSeconds: number;
29
+ /** Human-readable summary of last run. */
30
+ lastRunSummary: string;
31
+ /** Whether curator is paused by the user. */
32
+ paused: boolean;
33
+ /** Cumulative run count. */
34
+ runCount: number;
35
+ }
36
+ export declare const INITIAL_CURATOR_STATE: CuratorState;
37
+ /** Lifecycle state of an agent-created skill. */
38
+ export type CuratorSkillLifecycleState = "active" | "stale" | "archived";
39
+ /** Minimal skill activity record consumed by the scheduler. */
40
+ export interface CuratorSkillRecord {
41
+ /** Skill name / identifier. */
42
+ name: string;
43
+ /** Whether this skill was agent-created (only these are curated). */
44
+ agentCreated: boolean;
45
+ /** Current lifecycle state. */
46
+ state: CuratorSkillLifecycleState;
47
+ /** Whether the user pinned this skill (immune to auto-transitions). */
48
+ pinned: boolean;
49
+ /** ISO-8601 timestamp of last activity. */
50
+ lastActivityAt: string | null;
51
+ /** Cumulative use count. */
52
+ useCount: number;
53
+ /** ISO-8601 timestamp of creation. */
54
+ createdAt: string;
55
+ }
56
+ /** Input for the gate check. */
57
+ export interface CuratorGateInput {
58
+ /** Current ISO-8601 timestamp. */
59
+ now: string;
60
+ /** Seconds the session has been idle. */
61
+ idleSeconds: number;
62
+ /** Current curator state. */
63
+ state: CuratorState;
64
+ /** Whether the feature is enabled at all. */
65
+ enabled: boolean;
66
+ /** Policy overrides. */
67
+ policy?: Partial<CuratorSchedulePolicy>;
68
+ }
69
+ /** Result of the gate check: should the curator run? */
70
+ export interface CuratorGateResult {
71
+ shouldRun: boolean;
72
+ reason: string;
73
+ }
74
+ /**
75
+ * Determine whether the curator should run now.
76
+ *
77
+ * All gates must pass:
78
+ * 1. Feature enabled
79
+ * 2. Not paused
80
+ * 3. Session idle ≥ minIdleSeconds
81
+ * 4. Time since last run ≥ intervalSeconds
82
+ */
83
+ export declare function shouldRunCurator(input: CuratorGateInput): CuratorGateResult;
84
+ /** A single lifecycle transition computed by the scheduler. */
85
+ export interface CuratorLifecycleTransition {
86
+ skillName: string;
87
+ from: CuratorSkillLifecycleState;
88
+ to: CuratorSkillLifecycleState;
89
+ reason: string;
90
+ }
91
+ /** Summary of all auto-transitions in one pass. */
92
+ export interface CuratorAutoTransitionResult {
93
+ checked: number;
94
+ transitions: CuratorLifecycleTransition[];
95
+ markedStale: number;
96
+ archived: number;
97
+ reactivated: number;
98
+ }
99
+ /**
100
+ * Compute automatic lifecycle transitions for agent-created skills.
101
+ *
102
+ * Pure function — no I/O, no mutations. The caller applies the
103
+ * returned transitions to its skill storage.
104
+ *
105
+ * Rules:
106
+ * - Pinned skills are never transitioned.
107
+ * - Non-agent-created skills are skipped.
108
+ * - active → stale: no activity for staleAfterDays.
109
+ * - stale → archived: no activity for archiveAfterDays.
110
+ * - stale/archived → active: if useCount increased (reactivation).
111
+ */
112
+ export declare function computeLifecycleTransitions(skills: readonly CuratorSkillRecord[], now: string, policy?: Partial<CuratorSchedulePolicy>): CuratorAutoTransitionResult;
113
+ /**
114
+ * Select skills that should be reviewed by the LLM curator.
115
+ *
116
+ * Only non-pinned, agent-created skills in active or stale state
117
+ * are eligible for review. Returns at most maxReviewBatchSize names.
118
+ */
119
+ export declare function selectReviewCandidates(skills: readonly CuratorSkillRecord[], policy?: Partial<CuratorSchedulePolicy>): string[];
@@ -0,0 +1,12 @@
1
+ import type { FailoverReason } from "./failover-classification.js";
2
+ export type ErrorCategory = "RETRYABLE_TRANSIENT" | "RETRYABLE_DEGRADED" | "NON_RETRYABLE_AUTH" | "NON_RETRYABLE_CONTENT" | "NON_RETRYABLE_QUOTA" | "TOOL_EXECUTION_FAILED";
3
+ export interface RetryStrategy {
4
+ retryable: boolean;
5
+ maxRetries: number;
6
+ baseDelayMs: number;
7
+ backoffMultiplier: number;
8
+ switchProvider: boolean;
9
+ }
10
+ export declare function classifyError(status: number | undefined, message?: string): ErrorCategory;
11
+ export declare function classifyErrorFromReason(reason: FailoverReason): ErrorCategory;
12
+ export declare function getRetryStrategy(category: ErrorCategory): RetryStrategy;
@@ -0,0 +1,8 @@
1
+ export type FailoverReason = "auth" | "auth_permanent" | "format" | "rate_limit" | "overloaded" | "billing" | "timeout" | "model_not_found" | "session_expired" | "unknown";
2
+ export declare function isTimeoutErrorMessage(raw: string): boolean;
3
+ export declare function isCloudflareOrHtmlErrorPage(raw: string): boolean;
4
+ export declare function isTransientHttpError(raw: string): boolean;
5
+ export declare function classifyFailoverReasonFromHttpStatus(status: number | undefined, message?: string): FailoverReason | null;
6
+ export declare function isModelNotFoundErrorMessage(raw: string): boolean;
7
+ export declare function classifyFailoverReason(raw: string): FailoverReason | null;
8
+ export declare function isFailoverErrorMessage(raw: string): boolean;
@@ -0,0 +1,33 @@
1
+ import { type FailoverReason } from "./failover-classification.js";
2
+ export declare class FailoverError extends Error {
3
+ readonly reason: FailoverReason;
4
+ readonly provider?: string;
5
+ readonly model?: string;
6
+ readonly profileId?: string;
7
+ readonly status?: number;
8
+ readonly code?: string;
9
+ constructor(message: string, params: {
10
+ reason: FailoverReason;
11
+ provider?: string;
12
+ model?: string;
13
+ profileId?: string;
14
+ status?: number;
15
+ code?: string;
16
+ cause?: unknown;
17
+ });
18
+ }
19
+ export declare function isFailoverError(err: unknown): err is FailoverError;
20
+ export declare function resolveFailoverStatus(reason: FailoverReason): number | undefined;
21
+ export declare function isTimeoutError(err: unknown): boolean;
22
+ export declare function resolveFailoverReasonFromError(err: unknown): FailoverReason | null;
23
+ export declare function describeFailoverError(err: unknown): {
24
+ message: string;
25
+ reason?: FailoverReason;
26
+ status?: number;
27
+ code?: string;
28
+ };
29
+ export declare function coerceToFailoverError(err: unknown, context?: {
30
+ provider?: string;
31
+ model?: string;
32
+ profileId?: string;
33
+ }): FailoverError | null;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Fork Sub-Agent — CC-aligned fork mechanism for spawning child agents.
3
+ *
4
+ * Core design principles (aligned with Claude Code):
5
+ * 1. Child agent shares parent's message prefix (prompt cache hit)
6
+ * 2. Fork uses placeholder results to ensure byte-identical prefix across children
7
+ * 3. Child has independent tool context (doesn't pollute parent state)
8
+ * 4. Results flow back via AsyncGenerator (streaming backflow)
9
+ * 5. Depth control via in-memory counter (not DB-based)
10
+ */
11
+ import type { AgentDefinition } from "./agent-registry.js";
12
+ /** Sentinel tag injected into fork children to prevent recursive forking. */
13
+ export declare const FORK_SENTINEL_TAG = "<fork-child-context>";
14
+ /** Placeholder text used for all tool_results in shared prefix (ensures byte-identical prefix). */
15
+ export declare const FORK_PLACEHOLDER_RESULT = "Fork started \u2014 processing in background";
16
+ /** Maximum fork depth for in-memory agents (more permissive than DB sidechain). */
17
+ export declare const MAX_FORK_DEPTH = 4;
18
+ /** Maximum fork depth for DB-backed sidechains (more conservative). */
19
+ export declare const MAX_SIDECHAIN_DB_DEPTH = 2;
20
+ export interface ForkContext {
21
+ /** Parent's full message history (becomes shared prefix for cache). */
22
+ parentMessages: unknown[];
23
+ /** Parent's rendered system prompt (byte-exact for cache hit). */
24
+ systemPrompt: string;
25
+ /** Parent's full tool pool (useExactTools=true pattern). */
26
+ parentTools: string[];
27
+ /** Current fork depth (0 = root). */
28
+ depth: number;
29
+ /** Abort signal from parent. */
30
+ abortSignal?: AbortSignal;
31
+ /** Parent's agent ID for lineage tracking. */
32
+ parentAgentId: string;
33
+ }
34
+ export interface ForkChildConfig {
35
+ /** The agent definition to run. */
36
+ agent: AgentDefinition;
37
+ /** Task-specific prompt for this child (the unique part after shared prefix). */
38
+ taskPrompt: string;
39
+ /** Optional override for max turns. */
40
+ maxTurns?: number;
41
+ /** Whether to run in background (async). */
42
+ isAsync?: boolean;
43
+ }
44
+ export interface ForkChildMessage {
45
+ role: "assistant" | "user" | "system";
46
+ content: unknown;
47
+ toolCalls?: unknown[];
48
+ }
49
+ export interface ForkResult {
50
+ /** Whether the fork completed successfully. */
51
+ ok: boolean;
52
+ /** Child's final output text (summary). */
53
+ output: string;
54
+ /** Messages produced by the child (for result backflow). */
55
+ messages: ForkChildMessage[];
56
+ /** Total tokens consumed by the child. */
57
+ tokensUsed: number;
58
+ /** Whether the child hit its turn limit. */
59
+ maxTurnsReached: boolean;
60
+ /** Child's agent ID. */
61
+ childAgentId: string;
62
+ }
63
+ /**
64
+ * Check if current context is inside a fork child (prevents recursive forking).
65
+ */
66
+ export declare function isInForkChild(messages: unknown[]): boolean;
67
+ /**
68
+ * Check if fork depth allows spawning another child.
69
+ */
70
+ export declare function canForkAtDepth(currentDepth: number, mode?: "in-memory" | "db-sidechain"): boolean;
71
+ /**
72
+ * Build forked messages that ensure byte-identical prefix across all fork children.
73
+ *
74
+ * Strategy (aligned with CC's buildForkedMessages):
75
+ * 1. Keep full parent message history (all tool_use blocks, thinking, text)
76
+ * 2. Replace all pending tool_results with FORK_PLACEHOLDER_RESULT
77
+ * 3. Append a single user message with the child-specific directive
78
+ * → All children share the same prefix up to the directive → maximum cache hits.
79
+ */
80
+ export declare function buildForkedMessages(context: ForkContext, childConfig: ForkChildConfig): unknown[];
81
+ /**
82
+ * Build placeholder tool results for the shared prefix.
83
+ * When parent has pending tool_calls, replace them all with identical placeholder text
84
+ * so all fork children produce byte-identical API request prefix.
85
+ */
86
+ export declare function buildForkPlaceholderResults(pendingToolCallIds: string[]): Array<{
87
+ role: "tool";
88
+ tool_call_id: string;
89
+ content: string;
90
+ }>;
91
+ /**
92
+ * Resolve the effective tool set for a fork child.
93
+ * CC pattern: useExactTools=true → child gets parent's full tool pool,
94
+ * then filtered by agent definition.
95
+ */
96
+ export declare function resolveForkChildTools(parentTools: string[], agent: AgentDefinition): string[];
97
+ /**
98
+ * Generate a unique agent ID for a fork child.
99
+ */
100
+ export declare function generateForkChildAgentId(parentAgentId: string, agentName: string, depth: number): string;