qlogicagent 2.24.9 → 2.24.11

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 (34) hide show
  1. package/README.md +4 -0
  2. package/dist/agent.js +7 -11
  3. package/dist/cli.js +7 -7
  4. package/dist/embedded.js +11 -0
  5. package/dist/index.js +150 -163
  6. package/dist/orchestration.js +10 -16
  7. package/dist/skills/builtin/web-research/SKILL.md +8 -5
  8. package/dist/types/agent/tool-loop/compression-pipeline.d.ts +5 -11
  9. package/dist/types/agent/tool-loop/stream-error-recovery.d.ts +2 -7
  10. package/dist/types/agent/tool-loop.d.ts +3 -12
  11. package/dist/types/agent/types.d.ts +2 -7
  12. package/dist/types/cli/core-tools/fork-system-prompt.d.ts +13 -21
  13. package/dist/types/cli/handlers/turn-handler.d.ts +2 -2
  14. package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +1 -1
  15. package/dist/types/embedded/contracts.d.ts +244 -0
  16. package/dist/types/embedded/default-runtime-ports.d.ts +3 -0
  17. package/dist/types/embedded/embedded-tool-executor.d.ts +9 -0
  18. package/dist/types/embedded/index.d.ts +3 -0
  19. package/dist/types/orchestration/error-handling/retry-loop.d.ts +0 -9
  20. package/dist/types/orchestration/index.d.ts +2 -4
  21. package/dist/types/protocol/wire/acp-protocol.d.ts +6 -3
  22. package/dist/types/protocol/wire/index.d.ts +2 -2
  23. package/dist/types/protocol/wire/notification-payloads.d.ts +7 -0
  24. package/dist/types/runtime/config/tunable-defaults.d.ts +0 -3
  25. package/dist/types/runtime/context/context-compression-strategies.d.ts +0 -108
  26. package/dist/types/runtime/execution/tool-result-storage.d.ts +0 -11
  27. package/dist/types/runtime/hooks/context-compression.d.ts +9 -12
  28. package/dist/types/runtime/infra/file-watcher.d.ts +1 -3
  29. package/dist/types/runtime/ports/agent-runtime-ports.d.ts +0 -13
  30. package/dist/types/runtime/ports/model-transport-contracts.d.ts +15 -0
  31. package/dist/types/runtime/prompt/instruction-loader.d.ts +13 -13
  32. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +9 -11
  33. package/package.json +10 -2
  34. package/dist/types/orchestration/context/context-collapse.d.ts +0 -58
@@ -0,0 +1,244 @@
1
+ export interface AgentLogger {
2
+ info(message: string): void;
3
+ info(context: Record<string, unknown>, message: string): void;
4
+ warn(message: string): void;
5
+ warn(context: Record<string, unknown>, message: string): void;
6
+ error(message: string): void;
7
+ error(context: Record<string, unknown>, message: string): void;
8
+ debug(message: string): void;
9
+ debug(context: Record<string, unknown>, message: string): void;
10
+ }
11
+ export interface ToolCallMessage {
12
+ id: string;
13
+ type: "function";
14
+ function: {
15
+ name: string;
16
+ arguments: string;
17
+ };
18
+ }
19
+ export interface ChatMessage {
20
+ role: "system" | "user" | "assistant" | "tool";
21
+ content: string | null;
22
+ tool_calls?: ToolCallMessage[];
23
+ tool_call_id?: string;
24
+ name?: string;
25
+ is_error?: boolean;
26
+ reasoning_content?: string;
27
+ thinkingBlocks?: Array<{
28
+ thinking: string;
29
+ signature: string;
30
+ }>;
31
+ }
32
+ export interface ToolDefinition {
33
+ type: "function";
34
+ function: {
35
+ name: string;
36
+ description: string;
37
+ parameters?: Record<string, unknown>;
38
+ };
39
+ }
40
+ export interface LLMRequest {
41
+ model: string;
42
+ messages: ChatMessage[];
43
+ tools?: ToolDefinition[];
44
+ toolChoice?: "auto" | "none" | "required" | {
45
+ type: "function";
46
+ name: string;
47
+ };
48
+ temperature?: number;
49
+ maxTokens?: number;
50
+ reasoning?: {
51
+ effort: "minimal" | "low" | "medium" | "high" | "xhigh";
52
+ includeEncryptedReasoning?: boolean;
53
+ };
54
+ maxToolCalls?: number;
55
+ streamRequired?: boolean;
56
+ promptCacheKey?: string;
57
+ promptCacheRetention?: "in_memory" | "24h";
58
+ serviceTier?: "auto" | "default" | "flex" | "priority";
59
+ parallelToolCalls?: boolean;
60
+ textVerbosity?: "low" | "medium" | "high";
61
+ }
62
+ export type LLMChunk = {
63
+ type: "delta";
64
+ text: string;
65
+ } | {
66
+ type: "tool_call_delta";
67
+ index: number;
68
+ id?: string;
69
+ name?: string;
70
+ arguments: string;
71
+ } | {
72
+ type: "reasoning_delta";
73
+ text: string;
74
+ } | {
75
+ type: "reasoning_block_complete";
76
+ thinking: string;
77
+ signature: string;
78
+ } | {
79
+ type: "usage";
80
+ totalPromptTokens?: number;
81
+ promptTokens: number;
82
+ completionTokens: number;
83
+ reasoningTokens?: number;
84
+ cacheReadTokens?: number;
85
+ cacheCreationTokens?: number;
86
+ } | {
87
+ type: "response_id";
88
+ id: string;
89
+ } | {
90
+ type: "annotations";
91
+ annotations: Array<{
92
+ type: string;
93
+ url?: string;
94
+ title?: string;
95
+ [key: string]: unknown;
96
+ }>;
97
+ } | {
98
+ type: "error";
99
+ message: string;
100
+ } | {
101
+ type: "done";
102
+ finishReason: string;
103
+ };
104
+ export interface LLMTransport {
105
+ stream(request: LLMRequest, apiKey: string, signal?: AbortSignal): AsyncGenerator<LLMChunk>;
106
+ }
107
+ export interface ToolInvoker {
108
+ invoke(turnId: string, name: string, args: string, signal?: AbortSignal): Promise<{
109
+ result: string;
110
+ error?: string;
111
+ toolReferences?: string[];
112
+ imageUrls?: string[];
113
+ details?: Record<string, unknown>;
114
+ }>;
115
+ }
116
+ export interface TurnConfig {
117
+ model?: string;
118
+ maxRounds?: number;
119
+ temperature?: number;
120
+ contextWindowTokens?: number;
121
+ maxOutputTokens?: number;
122
+ modelMaxOutputTokens?: number;
123
+ maxTurns?: number;
124
+ maxToolCalls?: number;
125
+ maxConcurrentTools?: number;
126
+ parallelToolCalls?: boolean;
127
+ streamRequired?: boolean;
128
+ toolChoice?: "auto" | "none" | "required";
129
+ }
130
+ export interface TurnRequest {
131
+ turnId: string;
132
+ sessionId: string;
133
+ messages: ChatMessage[];
134
+ availableTools?: ToolDefinition[];
135
+ tools: ToolDefinition[];
136
+ systemPrompt?: string;
137
+ config?: TurnConfig;
138
+ }
139
+ export interface TokenUsage {
140
+ inputTokens?: number;
141
+ outputTokens?: number;
142
+ reasoningTokens?: number;
143
+ cacheRead?: number;
144
+ cacheWrite?: number;
145
+ }
146
+ export type TurnEvent = {
147
+ type: "start";
148
+ turnId: string;
149
+ effectiveMaxRounds?: number;
150
+ effectiveMaxToolCalls?: number;
151
+ } | {
152
+ type: "delta";
153
+ turnId: string;
154
+ text: string;
155
+ } | {
156
+ type: "tool_call";
157
+ turnId: string;
158
+ callId: string;
159
+ name: string;
160
+ displayName?: string;
161
+ arguments: string;
162
+ inputSummary?: string;
163
+ } | {
164
+ type: "tool_result";
165
+ turnId: string;
166
+ callId: string;
167
+ name: string;
168
+ ok: boolean;
169
+ error?: string;
170
+ outputPreview?: string;
171
+ durationMs?: number;
172
+ details?: Record<string, unknown>;
173
+ } | {
174
+ type: "tool_blocked";
175
+ turnId: string;
176
+ callId: string;
177
+ name: string;
178
+ reason: string;
179
+ } | {
180
+ type: "recovery";
181
+ turnId: string;
182
+ action: string;
183
+ detail?: string;
184
+ } | {
185
+ type: "text_rollback";
186
+ turnId: string;
187
+ keepLength: number;
188
+ reason: string;
189
+ } | {
190
+ type: "reasoning_delta";
191
+ turnId: string;
192
+ text: string;
193
+ } | {
194
+ type: "annotations";
195
+ turnId: string;
196
+ annotations: Array<{
197
+ type: string;
198
+ url?: string;
199
+ title?: string;
200
+ [key: string]: unknown;
201
+ }>;
202
+ } | {
203
+ type: "tool_use_summary";
204
+ turnId: string;
205
+ ledgerSchemaVersion: 5;
206
+ toolCalls: Array<Record<string, unknown>>;
207
+ availableToolNames: string[];
208
+ enabledToolNames: string[];
209
+ toolCallNames: string[];
210
+ blockedToolCalls: Array<{
211
+ name: string;
212
+ reason: string;
213
+ }>;
214
+ } | {
215
+ type: "end";
216
+ turnId: string;
217
+ content: string;
218
+ turnStatus?: "completed" | "stopped";
219
+ taskOutcome?: "unverified";
220
+ usage?: TokenUsage;
221
+ model?: string;
222
+ provider?: string;
223
+ recoveryTrace?: Record<string, number>;
224
+ } | {
225
+ type: "error";
226
+ turnId: string;
227
+ error: string;
228
+ code?: string;
229
+ usage?: TokenUsage;
230
+ };
231
+ export interface EmbeddedRuntimeOptions {
232
+ maxToolResultChars?: number;
233
+ }
234
+ export interface EmbeddedAgent {
235
+ run(request: TurnRequest, signal?: AbortSignal): AsyncGenerator<TurnEvent>;
236
+ }
237
+ export interface CreateEmbeddedAgentOptions {
238
+ llmTransport: LLMTransport;
239
+ toolInvoker: ToolInvoker;
240
+ apiKey?: string;
241
+ logger?: AgentLogger;
242
+ maxRounds?: number;
243
+ runtime?: EmbeddedRuntimeOptions;
244
+ }
@@ -0,0 +1,3 @@
1
+ import type { AgentRuntimePorts } from "../runtime/ports/agent-runtime-ports.js";
2
+ import type { EmbeddedRuntimeOptions } from "./contracts.js";
3
+ export declare function createEmbeddedRuntimePorts(options?: EmbeddedRuntimeOptions): AgentRuntimePorts;
@@ -0,0 +1,9 @@
1
+ import { type OpenAiToolCall } from "../runtime/ports/tool-call-contracts.js";
2
+ import type { StreamingToolExecutorPort, StreamingToolExecutorPortConfig, ToolExecutionResultPort } from "../runtime/ports/agent-runtime-ports.js";
3
+ export declare class EmbeddedToolExecutor implements StreamingToolExecutorPort {
4
+ private readonly config;
5
+ private readonly calls;
6
+ constructor(config: StreamingToolExecutorPortConfig);
7
+ addTool(call: OpenAiToolCall): void;
8
+ getRemainingResults(): AsyncIterable<ToolExecutionResultPort>;
9
+ }
@@ -0,0 +1,3 @@
1
+ import type { CreateEmbeddedAgentOptions, EmbeddedAgent } from "./contracts.js";
2
+ export declare function createEmbeddedAgent(options: CreateEmbeddedAgentOptions): EmbeddedAgent;
3
+ export type { AgentLogger, ChatMessage, CreateEmbeddedAgentOptions, EmbeddedAgent, EmbeddedRuntimeOptions, LLMChunk, LLMRequest, LLMTransport, ToolDefinition, ToolInvoker, TurnConfig, TurnEvent, TurnRequest, } from "./contracts.js";
@@ -27,15 +27,6 @@ export declare const DEFAULT_PERSISTENT_RETRY_CONFIG: PersistentRetryConfig;
27
27
  * CC parity: CLAUDE_CODE_UNATTENDED_RETRY
28
28
  */
29
29
  export declare function isPersistentRetryEnabled(): boolean;
30
- /**
31
- * Error class for triggering model fallback after repeated 529s.
32
- * CC parity: FallbackTriggeredError
33
- */
34
- export declare class FallbackTriggeredError extends Error {
35
- readonly originalModel: string;
36
- readonly fallbackModel: string;
37
- constructor(originalModel: string, fallbackModel: string);
38
- }
39
30
  /**
40
31
  * Error class for when retries are exhausted and cannot continue.
41
32
  * CC parity: CannotRetryError
@@ -1,12 +1,10 @@
1
1
  export { buildAssistantToolCallMessage, buildToolResultMessage, type FunctionToolDefinition, } from "./tool-loop/tool-schema.js";
2
2
  export { classifyError, isRetryableCategory, type ErrorCategory, } from "./error-handling/error-classification.js";
3
- export { composeStrategies, composeAsyncStrategies, SlidingWindowStrategy, SummarizeOldStrategy, ToolResultTrimStrategy, HeadTailProtectedStrategy, IncrementalCompactStrategy, CacheAwareCompressionStrategy, CompressionMetricsCollector, ContextEngineRegistry, MicroCompactStrategy, postCompactFileRecovery, type PostCompactRecoveryConfig, buildStructuredSummaryPrompt, CONTEXT_CAPSULE_MARKER, parseContextCapsule, redactCompressionSecrets, computeAdaptiveBudget, isAsyncCompressionStrategy, selectCompressionTier, DEFAULT_ADAPTIVE_BUDGET_CONFIG, type AdaptiveBudgetConfig, type AsyncCompressionStrategy, type CacheAwareCompressionConfig, type CompressibleMessage, type CompressionEvent, type ContextCapsule, type ContextCompactionReceipt, type CompressionMetrics, type CompressionMetricsSnapshot, type CompressionResult, type CompressionStrategy, type CompressionTier, type ContextEngine, type HeadTailProtectionConfig, type IncrementalCompactConfig, type SummarizeFn, } from "../runtime/context/context-compression-strategies.js";
4
- export { snipCompactIfNeeded, type SnipResult, } from "../runtime/context/context-compression-strategies.js";
5
- export { applyCollapsesIfNeeded as applyContextCollapsesIfNeeded, recoverFromOverflow as recoverContextCollapseFromOverflow, createCollapseStore, type CollapseStore, type CollapseStage, } from "./context/context-collapse.js";
3
+ export { SlidingWindowStrategy, SummarizeOldStrategy, ToolResultTrimStrategy, HeadTailProtectedStrategy, CacheAwareCompressionStrategy, CompressionMetricsCollector, ContextEngineRegistry, buildStructuredSummaryPrompt, CONTEXT_CAPSULE_MARKER, parseContextCapsule, redactCompressionSecrets, computeAdaptiveBudget, isAsyncCompressionStrategy, selectCompressionTier, DEFAULT_ADAPTIVE_BUDGET_CONFIG, type AdaptiveBudgetConfig, type AsyncCompressionStrategy, type CacheAwareCompressionConfig, type CompressibleMessage, type CompressionEvent, type ContextCapsule, type ContextCompactionReceipt, type CompressionMetrics, type CompressionMetricsSnapshot, type CompressionResult, type CompressionStrategy, type CompressionTier, type ContextEngine, type HeadTailProtectionConfig, type SummarizeFn, } from "../runtime/context/context-compression-strategies.js";
6
4
  export { applyToolChoicePolicy, type ApplyToolChoicePolicyInput, type ApplyToolChoicePolicyResult, } from "./tool-loop/tool-choice-policy.js";
7
5
  export { repairOpenAiChatConversation, type ConversationRepairOptions, type OpenAiChatMessageLike, type OpenAiToolCall, } from "./tool-loop/conversation-repair.js";
8
6
  export { advanceToolLoopState, recoverToolLoopStateFromChatConversation, recoverToolLoopStateFromResponsesItems, settleToolLoopState, type RepairToolLoopStateResult, type ToolLoopRepairAction, type ToolLoopState, } from "./tool-loop/tool-loop-state.js";
9
- export { isForegroundSource, isTransientCapacityError, computeRetryBackoff, isPersistentRetryEnabled, FallbackTriggeredError, type PersistentRetryConfig, } from "./error-handling/retry-loop.js";
7
+ export { isForegroundSource, isTransientCapacityError, computeRetryBackoff, isPersistentRetryEnabled, type PersistentRetryConfig, } from "./error-handling/retry-loop.js";
10
8
  export { canForkAtDepth, buildForkedMessages, buildForkPlaceholderResults, FORK_PLACEHOLDER_RESULT, FORK_SENTINEL_TAG, generateForkChildAgentId, isInForkChild, MAX_FORK_DEPTH, resolveForkChildTools, type ForkChildConfig, type ForkChildMessage, type ForkContext, type ForkResult, } from "./subagent/fork-subagent.js";
11
9
  export { getBuiltInAgent, getBuiltInAgents, isBuiltInAgent, resolveAgentToolSet, type AgentDefinition, } from "./subagent/agent-registry.js";
12
10
  export { createTaskState, type IsolationMode, type PermissionRole, type TaskType, type TaskLifecycle, type TaskState, type TaskStateBase, type LocalBashTaskState, type LocalAgentTaskState, type RemoteAgentTaskState, } from "./subagent/task-types.js";
@@ -215,12 +215,15 @@ export interface AcpFsWriteTextFileResult {
215
215
  bytesWritten: number;
216
216
  }
217
217
  export interface AcpUsage {
218
+ totalTokens: number;
218
219
  inputTokens: number;
219
220
  outputTokens: number;
220
- cacheReadTokens?: number;
221
- cacheWriteTokens?: number;
222
- totalCost?: number;
221
+ thoughtTokens?: number;
222
+ cachedReadTokens?: number;
223
+ cachedWriteTokens?: number;
224
+ _meta?: Record<string, unknown>;
223
225
  }
226
+ export declare const ACP_AUTHORITATIVE_USAGE_META_KEY = "xiaozhiclaw/authoritativeUsage";
224
227
  export type AcpStopReason = "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled";
225
228
  export interface AcpJsonRpcRequest {
226
229
  jsonrpc: "2.0";
@@ -1,6 +1,6 @@
1
1
  export { type ChatMessage, type ChatMessageRole, type ContextAnchor, type ContextAnchorCategory, type ContextEnvelope, type LocalizedToolText, type SemanticToolCapability, type ThinkingBlock, type ToolCapabilityCategory, type ToolCallMessage, type ToolDefinition, type ToolIdentity, } from "./chat-types.js";
2
- export { type MediaResultType, type NotificationMethod, type NotificationMethodMap, type TurnDeltaNotification, type TurnEndNotification, type TurnMediaResultNotification, type TurnReasoningDeltaNotification, type TurnToolBlockedNotification, type TurnToolCallNotification, type TurnToolResultNotification, type WireTokenUsage, } from "./notification-payloads.js";
3
- export { ACP_METHODS, ACP_PROTOCOL_VERSION, isAcpJsonRpcNotification, isAcpJsonRpcRequest, isAcpJsonRpcResponse, parseAcpMessage, type AcpAgentCapabilities, type AcpConfigOptionDescriptor, type AcpContentBlock, type AcpFsReadTextFileParams, type AcpFsReadTextFileResult, type AcpFsWriteTextFileParams, type AcpFsWriteTextFileResult, type AcpHostCapabilities, type AcpInitializeParams, type AcpInitializeResult, type AcpJsonRpcError, type AcpJsonRpcMessage, type AcpJsonRpcNotification, type AcpJsonRpcRequest, type AcpJsonRpcResponse, type AcpMode, type AcpPermissionOption, type AcpPermissionRequestParams, ACP_PERMISSION_PRESENTATION_META_KEY, type AcpPermissionPresentationMetaV1, type AcpPermissionRequestResult, type AcpSessionCancelParams, type AcpSessionCloseParams, type AcpSessionMeta, type AcpSessionLoadParams, type AcpSessionModeState, type AcpSessionNewParams, type AcpSessionNewResult, type AcpSessionPromptParams, type AcpSessionPromptResult, type AcpSessionSetConfigParams, type AcpSessionSetConfigResult, type AcpStandardMethod, type AcpStopReason, type AcpUsage, } from "./acp-protocol.js";
2
+ export { type MediaResultType, type NotificationMethod, type NotificationMethodMap, type TurnDeltaNotification, type TurnEndNotification, type TurnMediaResultNotification, type TurnReasoningDeltaNotification, type TurnToolBlockedNotification, type TurnToolCallNotification, type TurnToolResultNotification, type WireAuthoritativeUsage, type WireTokenUsage, } from "./notification-payloads.js";
3
+ export { ACP_METHODS, ACP_PROTOCOL_VERSION, isAcpJsonRpcNotification, isAcpJsonRpcRequest, isAcpJsonRpcResponse, parseAcpMessage, type AcpAgentCapabilities, type AcpConfigOptionDescriptor, type AcpContentBlock, type AcpFsReadTextFileParams, type AcpFsReadTextFileResult, type AcpFsWriteTextFileParams, type AcpFsWriteTextFileResult, type AcpHostCapabilities, type AcpInitializeParams, type AcpInitializeResult, type AcpJsonRpcError, type AcpJsonRpcMessage, type AcpJsonRpcNotification, type AcpJsonRpcRequest, type AcpJsonRpcResponse, type AcpMode, type AcpPermissionOption, type AcpPermissionRequestParams, ACP_PERMISSION_PRESENTATION_META_KEY, type AcpPermissionPresentationMetaV1, type AcpPermissionRequestResult, type AcpSessionCancelParams, type AcpSessionCloseParams, type AcpSessionMeta, type AcpSessionLoadParams, type AcpSessionModeState, type AcpSessionNewParams, type AcpSessionNewResult, type AcpSessionPromptParams, type AcpSessionPromptResult, ACP_AUTHORITATIVE_USAGE_META_KEY, type AcpSessionSetConfigParams, type AcpSessionSetConfigResult, type AcpStandardMethod, type AcpStopReason, type AcpUsage, } from "./acp-protocol.js";
4
4
  export { type ApprovalRequiredToolContract, type ModelSelectionReason, type PendingPromptContract, type RuntimeCapabilitySummaryContract, type RuntimeSessionContract, type SessionIdentityContract, } from "./session.js";
5
5
  export { CAPABILITY_MANIFEST_DIFF_SECTIONS, cloneCapabilityManifestSnapshot, createCapabilityManifestDiffPayload, deriveCapabilityToolNamespaces, deriveCapabilityWorkspaceIds, mergeCapabilityManifestSnapshot, type CapabilityManifestApprovalMode, type CapabilityManifestApprovalPolicyContract, type CapabilityManifestDiffSection, type CapabilityMcpManifestContract, type CapabilityManifestSnapshotContract, type HostCapabilitySnapshotContract, type CapabilityPluginManifestContract, type RuntimeCapabilityViewContract, type RuntimeToolEligibilityContract, type CapabilitySkillManifestContract, type CapabilityToolManifestContract, type CapabilityWorkspaceSummaryContract, type ToolEligibilityResolvedSource, type ToolEligibilityReasonCode, type ToolEligibilityStatus, } from "./capability-manifest.js";
6
6
  export { WEB_ACTION_SCOPE_VALUES, WEB_APPROVAL_DEFAULT_VALUES, WEB_CAPABILITY_FAMILY_VALUES, WEB_CAPABILITY_ID_VALUES, WEB_DEGRADATION_TARGET_VALUES, WEB_ESCALATION_REASON_VALUES, WEB_EXECUTION_MODE_VALUES, WEB_POLICY_RISK_CLASS_VALUES, WEB_RETRY_POLICY_VALUES, WEB_STATEFULNESS_VALUES, WEB_TASK_MODE_VALUES, type WebActionScope, type WebApprovalDefault, type WebCapabilityDescriptorContract, type WebCapabilityFamily, type WebCapabilityId, type WebDegradationTarget, type WebEscalationReason, type WebExecutionMode, type WebPolicyRiskClass, type WebRetryPolicy, type WebStatefulness, type WebTaskMode, type ToolRiskLevel, } from "./web-capability.js";
@@ -1,10 +1,17 @@
1
1
  /** Token accounting returned by an Agent turn. */
2
+ export interface WireAuthoritativeUsage {
3
+ source: string;
4
+ currency: string;
5
+ cost: string;
6
+ requestIds: string[];
7
+ }
2
8
  export interface WireTokenUsage {
3
9
  inputTokens: number;
4
10
  outputTokens: number;
5
11
  reasoningTokens?: number;
6
12
  cacheRead?: number;
7
13
  cacheWrite?: number;
14
+ authoritative?: WireAuthoritativeUsage;
8
15
  }
9
16
  /** Internal events that have a direct standard ACP projection. */
10
17
  export interface TurnDeltaNotification {
@@ -37,8 +37,6 @@ export declare const MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000;
37
37
  export declare const TOOL_RESULT_PREVIEW_BYTES = 2000;
38
38
  /** Heartbeat interval during persistent retry waits (ms). */
39
39
  export declare const HEARTBEAT_INTERVAL_MS = 30000;
40
- /** Max 529 errors before fallback model switch. */
41
- export declare const MAX_529_RETRIES = 3;
42
40
  /** Max consecutive API error retries before aborting. */
43
41
  export declare const MAX_API_RETRIES = 2;
44
42
  /** Max backoff interval for persistent retry (ms). */
@@ -107,7 +105,6 @@ export interface TunableDefaults {
107
105
  maxToolResultsPerMessageChars: number;
108
106
  toolResultPreviewBytes: number;
109
107
  heartbeatIntervalMs: number;
110
- max529Retries: number;
111
108
  maxApiRetries: number;
112
109
  persistentRetryMaxBackoffMs: number;
113
110
  persistentRetryResetCapMs: number;
@@ -82,12 +82,6 @@ export declare class ToolResultTrimStrategy implements CompressionStrategy {
82
82
  constructor(maxToolResultChars?: number);
83
83
  compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
84
84
  }
85
- export declare function composeStrategies(...strategies: CompressionStrategy[]): CompressionStrategy;
86
- /**
87
- * Compose strategies with async support — if any strategy is async,
88
- * the pipeline becomes async.
89
- */
90
- export declare function composeAsyncStrategies(...strategies: CompressionStrategy[]): AsyncCompressionStrategy;
91
85
  /**
92
86
  * Build the structured 9-section summary instruction for the LLM.
93
87
  * Based on Claude Code's Full Compact mode, adapted for Hub.
@@ -119,27 +113,6 @@ export declare class HeadTailProtectedStrategy implements AsyncCompressionStrate
119
113
  compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
120
114
  compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
121
115
  }
122
- export interface IncrementalCompactConfig {
123
- /** Messages newer than this count are never summarized (default: 12) */
124
- preserveRecentCount: number;
125
- /** Summarization callback */
126
- summarize: SummarizeFn;
127
- /** Token estimator */
128
- estimateTokens?: (msg: CompressibleMessage) => number;
129
- }
130
- /**
131
- * Phase 2.3: Incremental (partial) compaction.
132
- *
133
- * Only summarizes the oldest messages beyond the preserve window.
134
- * Avoids repeatedly re-summarizing already-compressed content.
135
- * If a previous summary marker exists, only new old messages are compressed.
136
- */
137
- export declare class IncrementalCompactStrategy implements AsyncCompressionStrategy {
138
- private config;
139
- constructor(config: IncrementalCompactConfig);
140
- compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
141
- compressAsync(messages: CompressibleMessage[], budget: number): Promise<CompressionResult>;
142
- }
143
116
  export interface CacheAwareCompressionConfig {
144
117
  /** The inner strategy to delegate to */
145
118
  inner: CompressionStrategy;
@@ -248,84 +221,3 @@ export declare class ContextEngineRegistry {
248
221
  active: boolean;
249
222
  }>;
250
223
  }
251
- /**
252
- * MicroCompact — selective clearing of old compactable tool results.
253
- *
254
- * CC parity: microCompact.ts
255
- *
256
- * For tool result messages from COMPACTABLE_TOOLS, if the message is
257
- * "old enough" (not in the most recent N messages), replace its content
258
- * with a compact "[result cleared]" marker. This preserves the tool call
259
- * structure (so the LLM knows what was called) but reclaims token budget.
260
- *
261
- * This is a lighter alternative to full summarization — it runs BEFORE
262
- * LLM summarization as a first-pass reduction.
263
- */
264
- export declare class MicroCompactStrategy implements CompressionStrategy {
265
- /** Number of recent messages to preserve (don't clear) */
266
- private preserveRecentCount;
267
- /** Token estimator */
268
- private estimateTokens;
269
- constructor(
270
- /** Number of recent messages to preserve (don't clear) */
271
- preserveRecentCount?: number,
272
- /** Token estimator */
273
- estimateTokens?: (msg: CompressibleMessage) => number);
274
- compress(messages: CompressibleMessage[], _budget: number): CompressionResult;
275
- }
276
- /**
277
- * After compaction, the most recently read/edited files may have been
278
- * dropped from the conversation. CC re-injects up to N file contents
279
- * to ensure the agent doesn't lose awareness of files it was working with.
280
- *
281
- * CC parity: compact.ts postCompactFileStateRecovery
282
- */
283
- export interface PostCompactRecoveryConfig {
284
- /** Maximum number of files to re-inject (default 5) */
285
- maxFiles: number;
286
- /** Maximum total tokens for re-injected files (default 50000) */
287
- maxTokenBudget: number;
288
- /** Function to read a file from disk (injected by caller) */
289
- readFile: (path: string) => Promise<string | null>;
290
- /** Token estimator */
291
- estimateTokens?: (text: string) => number;
292
- }
293
- /**
294
- * Extract file paths that were recently read/edited from the conversation.
295
- * Looks at tool calls and results for file path arguments.
296
- */
297
- export declare function extractRecentFilePaths(messages: CompressibleMessage[]): string[];
298
- /**
299
- * Re-inject recently-used file contents after compaction.
300
- *
301
- * Call this AFTER compression but BEFORE sending to the LLM.
302
- * Appends file content as system messages at the end of the
303
- * system message block.
304
- */
305
- export declare function postCompactFileRecovery(compressedMessages: CompressibleMessage[], originalMessages: CompressibleMessage[], config: PostCompactRecoveryConfig): Promise<CompressibleMessage[]>;
306
- /**
307
- * Snip Compact — permanently remove specific messages by identifier.
308
- *
309
- * CC parity: services/compact/snipCompact.ts
310
- *
311
- * Unlike sliding window or summarization, snip removes messages by
312
- * their unique id (tool_call_id, or index-based). This is used for:
313
- * - Removing old tool results that are known to be stale
314
- * - Dropping large image/media messages after they've been processed
315
- * - Clearing tombstoned messages from the transcript
316
- *
317
- * Snip runs BEFORE microcompact and autocompact — both may fire
318
- * after snip if the result is still over threshold.
319
- */
320
- export interface SnipResult {
321
- messages: CompressibleMessage[];
322
- tokensFreed: number;
323
- removedCount: number;
324
- /** Optional boundary message to yield (marks snip point in transcript). */
325
- boundaryMessage?: CompressibleMessage;
326
- }
327
- /**
328
- * Remove messages whose tool_call_id or name matches the removedIds set.
329
- * If no removedIds are pending, this is a no-op.
330
- */
331
- export declare function snipCompactIfNeeded(messages: CompressibleMessage[], removedIds: Set<string>, estimateTokens?: (msg: CompressibleMessage) => number): SnipResult;
@@ -20,8 +20,6 @@ export declare const TOOL_RESULTS_SUBDIR = "tool-results";
20
20
  /** XML tag wrapping persisted output previews (CC PERSISTED_OUTPUT_TAG) */
21
21
  export declare const PERSISTED_OUTPUT_TAG = "<persisted-output>";
22
22
  export declare const PERSISTED_OUTPUT_CLOSING_TAG = "</persisted-output>";
23
- /** Marker injected by microcompact when clearing old tool results (CC parity) */
24
- export declare const TOOL_RESULT_CLEARED_MESSAGE = "[Old tool result content cleared]";
25
23
  /**
26
24
  * Per-conversation-thread state for the aggregate tool result budget.
27
25
  * State must be stable to preserve prompt cache:
@@ -68,15 +66,6 @@ export declare function toolResultContextPolicy(details: Record<string, unknown>
68
66
  export declare function toolResultContextBudget(policy: ToolResultContextPolicy): ToolResultContextBudget;
69
67
  export declare function requiredContextBudgetViolation(state: ContentReplacementState | undefined, details: Record<string, unknown> | undefined, contentSize: number): string | undefined;
70
68
  export declare function registerToolResultContext(state: ContentReplacementState | undefined, toolCallId: string, details: Record<string, unknown> | undefined, contentSize?: number, _invocationArgs?: Record<string, unknown>): void;
71
- /**
72
- * Re-apply required Host instruction context after generic compression stages.
73
- * Existing tool messages are restored in place; if a whole tool exchange was removed,
74
- * a system capsule is inserted so wire-level tool-call pairing stays valid.
75
- */
76
- export declare function restoreRequiredContextMessages(messagesBefore: MessageLike[], messagesAfter: MessageLike[], state: ContentReplacementState): {
77
- messages: MessageLike[];
78
- recoveredCount: number;
79
- };
80
69
  /**
81
70
  * Where oversized tool output is spilled to disk.
82
71
  *
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Single-pass context compaction for the Agent turn loop.
3
+ * The active tier chooses exactly one transform; model selection remains in
4
+ * the Host-projected registry and is never guessed by this module.
5
+ */
1
6
  import { ContextEngineRegistry, type CompressibleMessage, type CompressionResult, type CompressionStrategy, type AsyncCompressionStrategy, type SummarizeFn } from "../context/context-compression-strategies.js";
2
7
  import type { HookRegistry } from "./hook-registry.js";
3
8
  import type { RuntimeLogger } from "./hook-registry.js";
@@ -23,23 +28,15 @@ export declare function createSummarizeFn(log: RuntimeLogger, opts?: {
23
28
  apiKey?: string;
24
29
  model?: string;
25
30
  }): SummarizeFn;
26
- /** Phase 1: sync-only pipeline (ToolResultTrim + MicroCompact + SlidingWindow) */
31
+ /** Synchronous fallback: one deterministic sliding-window transform. */
27
32
  export declare function createSyncPipeline(): CompressionStrategy;
28
- /** Phase 2+3: async pipeline with LLM summarization + cache awareness */
33
+ /** One protected summarization transform with cache accounting. */
29
34
  export declare function createAsyncPipeline(summarize: SummarizeFn, opts?: {
30
35
  onCacheInvalidated?: (info: {
31
36
  droppedCount: number;
32
37
  strategy: string;
33
38
  }) => void;
34
39
  }): AsyncCompressionStrategy;
35
- /** Phase 2.3: incremental compaction pipeline (for partial compact) */
36
- export declare function createIncrementalPipeline(summarize: SummarizeFn, opts?: {
37
- preserveRecentCount?: number;
38
- onCacheInvalidated?: (info: {
39
- droppedCount: number;
40
- strategy: string;
41
- }) => void;
42
- }): AsyncCompressionStrategy;
43
40
  export interface CompressOptions {
44
41
  budget?: number;
45
42
  model?: string;
@@ -48,9 +45,9 @@ export interface CompressOptions {
48
45
  summarize?: SummarizeFn;
49
46
  sessionId?: string;
50
47
  }
51
- /** Synchronous compression (Phase 1 only). */
48
+ /** Synchronous one-pass compression. */
52
49
  export declare function compressMessages(messages: CompressibleMessage[], opts?: CompressOptions): CompressionResult;
53
- /** Async compression (Phase 2+) supports LLM summarization. */
50
+ /** Async one-pass compression; the selected tier may use LLM summarization. */
54
51
  export declare function compressMessagesAsync(messages: CompressibleMessage[], opts: CompressOptions & {
55
52
  summarize: SummarizeFn;
56
53
  }): Promise<CompressionResult>;
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * Watched paths:
13
13
  * - .qlogicagent/settings.json → permission hot-reload
14
- * - INSTRUCTIONS.md / .qlogicagent/INSTRUCTIONS.md → instruction re-load
14
+ * - INSTRUCTIONS.md / .qlogicagent/INSTRUCTIONS.md → file.changed notification
15
15
  * - configurable additional patterns
16
16
  *
17
17
  * Reference: claude-code file-watcher usage throughout lifecycle
@@ -26,8 +26,6 @@ export interface FileWatcherDeps {
26
26
  hooks: HookRegistry;
27
27
  /** Logger */
28
28
  log?: (msg: string) => void;
29
- /** Callback to reset instruction cache when instructions change (injected, decoupled from prompt/) */
30
- onInstructionCacheReset?: () => void;
31
29
  }
32
30
  export type ChangeType = "created" | "modified" | "deleted";
33
31
  export interface FileChangeEvent {
@@ -56,18 +56,6 @@ export interface ToolLoopRuntimePorts {
56
56
  newlyReplacedCount: number;
57
57
  newlyPersistedBytes?: number;
58
58
  }>;
59
- restoreRequiredContextMessages?(messagesBefore: Array<{
60
- role: string;
61
- content?: string | unknown;
62
- tool_call_id?: string;
63
- }>, messagesAfter: Array<{
64
- role: string;
65
- content?: string | unknown;
66
- tool_call_id?: string;
67
- }>, state: unknown): {
68
- messages: unknown[];
69
- recoveredCount: number;
70
- };
71
59
  getActiveContextCompressionEngine(): ContextCompressionEnginePort | null;
72
60
  compressMessages(messages: RuntimeCompressibleMessage[], options: {
73
61
  budget: number;
@@ -83,5 +71,4 @@ export interface ToolLoopRuntimePorts {
83
71
  }
84
72
  export interface AgentRuntimePorts {
85
73
  toolLoop: ToolLoopRuntimePorts;
86
- resolveModelForPurpose(purpose: "smallModel" | string): string | null;
87
74
  }
@@ -82,6 +82,21 @@ export type LLMChunk = {
82
82
  reasoningTokens?: number;
83
83
  cacheReadTokens?: number;
84
84
  cacheCreationTokens?: number;
85
+ authoritative?: {
86
+ schemaVersion: number;
87
+ source: string;
88
+ requestId: string;
89
+ currency: string;
90
+ cost: string;
91
+ tokens: {
92
+ promptTokens: number;
93
+ completionTokens: number;
94
+ totalTokens: number;
95
+ reasoningTokens: number;
96
+ cacheReadTokens: number;
97
+ cacheCreationTokens: number;
98
+ };
99
+ };
85
100
  } | {
86
101
  type: "response_id";
87
102
  id: string;