qlogicagent 0.5.2 → 0.6.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 (167) hide show
  1. package/README.md +403 -402
  2. package/dist/agent.js +18 -0
  3. package/dist/cli.js +384 -0
  4. package/dist/contracts.js +1 -0
  5. package/dist/index.js +383 -0
  6. package/dist/orchestration.js +34 -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-access.d.ts +30 -0
  10. package/dist/types/agent/tool-loop.d.ts +94 -0
  11. package/dist/types/agent/types.d.ts +238 -0
  12. package/dist/types/cli/main.d.ts +11 -0
  13. package/dist/types/cli/stdio-server.d.ts +78 -0
  14. package/dist/types/cli/tool-bootstrap.d.ts +40 -0
  15. package/dist/types/cli/transport.d.ts +40 -0
  16. package/dist/types/config/config.d.ts +17 -0
  17. package/dist/types/contracts/hooks.d.ts +175 -0
  18. package/dist/types/contracts/index.d.ts +9 -0
  19. package/dist/types/contracts/planner.d.ts +35 -0
  20. package/dist/types/contracts/todo.d.ts +23 -0
  21. package/dist/types/index.d.ts +16 -0
  22. package/dist/types/llm/builtin-providers.d.ts +10 -0
  23. package/dist/types/llm/debug-transport.d.ts +12 -0
  24. package/dist/types/llm/index.d.ts +16 -0
  25. package/dist/types/llm/llm-client.d.ts +43 -0
  26. package/dist/types/llm/model-catalog.d.ts +53 -0
  27. package/dist/types/llm/provider-def.d.ts +59 -0
  28. package/dist/types/llm/provider-registry.d.ts +54 -0
  29. package/dist/types/llm/transport.d.ts +62 -0
  30. package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
  31. package/dist/types/llm/transports/openai-chat.d.ts +36 -0
  32. package/dist/types/orchestration/context/context-collapse.d.ts +58 -0
  33. package/dist/types/orchestration/context/context-compression.d.ts +301 -0
  34. package/dist/types/orchestration/context/reactive-compact.d.ts +73 -0
  35. package/dist/types/orchestration/context/turn-loop-guard.d.ts +86 -0
  36. package/dist/types/orchestration/error-handling/error-classification.d.ts +12 -0
  37. package/dist/types/orchestration/error-handling/failover-classification.d.ts +8 -0
  38. package/dist/types/orchestration/error-handling/failover-error.d.ts +33 -0
  39. package/dist/types/orchestration/error-handling/retry-loop.d.ts +69 -0
  40. package/dist/types/orchestration/index.d.ts +15 -0
  41. package/dist/types/orchestration/skill-improvement.d.ts +59 -0
  42. package/dist/types/orchestration/subagent/agent-registry.d.ts +46 -0
  43. package/dist/types/orchestration/subagent/fork-subagent.d.ts +98 -0
  44. package/dist/types/orchestration/subagent/task-types.d.ts +142 -0
  45. package/dist/types/orchestration/tool-loop/conversation-repair.d.ts +61 -0
  46. package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +54 -0
  47. package/dist/types/orchestration/tool-loop/tool-loop-state.d.ts +50 -0
  48. package/dist/types/orchestration/tool-loop/tool-schema.d.ts +39 -0
  49. package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
  50. package/dist/types/runtime/execution/forked-agent.d.ts +109 -0
  51. package/dist/types/runtime/execution/index.d.ts +6 -0
  52. package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
  53. package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
  54. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
  55. package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
  56. package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
  57. package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
  58. package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
  59. package/dist/types/runtime/hooks/index.d.ts +3 -0
  60. package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
  61. package/dist/types/runtime/index.d.ts +5 -0
  62. package/dist/types/runtime/infra/agent-paths.d.ts +57 -0
  63. package/dist/types/runtime/infra/checkpoint-backend.d.ts +8 -0
  64. package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
  65. package/dist/types/runtime/infra/disk-storage.d.ts +36 -0
  66. package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
  67. package/dist/types/runtime/infra/index.d.ts +8 -0
  68. package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
  69. package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
  70. package/dist/types/runtime/infra/token-budget.d.ts +92 -0
  71. package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
  72. package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
  73. package/dist/types/runtime/prompt/index.d.ts +3 -0
  74. package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
  75. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
  76. package/dist/types/runtime/session/index.d.ts +2 -0
  77. package/dist/types/runtime/session/session-memory.d.ts +90 -0
  78. package/dist/types/runtime/session/session-persistence.d.ts +94 -0
  79. package/dist/types/runtime/session/session-state.d.ts +117 -0
  80. package/dist/types/skills/index.d.ts +119 -0
  81. package/dist/types/skills/mcp/index.d.ts +3 -0
  82. package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
  83. package/dist/types/skills/mcp/mcp-manager.d.ts +83 -0
  84. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
  85. package/dist/types/skills/memory/memory-extractor.d.ts +64 -0
  86. package/dist/types/skills/memory/memory-store.d.ts +86 -0
  87. package/dist/types/skills/memory/memory-tool.d.ts +87 -0
  88. package/dist/types/skills/memory/qmemory-adapter.d.ts +42 -0
  89. package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
  90. package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
  91. package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
  92. package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
  93. package/dist/types/skills/permissions/index.d.ts +12 -0
  94. package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
  95. package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
  96. package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
  97. package/dist/types/skills/permissions/types.d.ts +113 -0
  98. package/dist/types/skills/plugins/index.d.ts +2 -0
  99. package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
  100. package/dist/types/skills/plugins/plugin-loader.d.ts +42 -0
  101. package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
  102. package/dist/types/skills/portable-tool.d.ts +104 -0
  103. package/dist/types/skills/skill-system/skill-frontmatter.d.ts +19 -0
  104. package/dist/types/skills/skill-system/skill-guard.d.ts +23 -0
  105. package/dist/types/skills/skill-system/skill-loader.d.ts +16 -0
  106. package/dist/types/skills/skill-system/skill-source.d.ts +119 -0
  107. package/dist/types/skills/skill-system/skill-types.d.ts +199 -0
  108. package/dist/types/skills/think-tool.d.ts +16 -0
  109. package/dist/types/skills/todo-tool.d.ts +72 -0
  110. package/dist/types/skills/tools/agent-tool.d.ts +91 -0
  111. package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
  112. package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
  113. package/dist/types/skills/tools/brief-tool.d.ts +74 -0
  114. package/dist/types/skills/tools/browser-tool.d.ts +114 -0
  115. package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
  116. package/dist/types/skills/tools/config-tool.d.ts +63 -0
  117. package/dist/types/skills/tools/cron-tool.d.ts +116 -0
  118. package/dist/types/skills/tools/edit-tool.d.ts +43 -0
  119. package/dist/types/skills/tools/exec-tool.d.ts +97 -0
  120. package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
  121. package/dist/types/skills/tools/instructions-tool.d.ts +65 -0
  122. package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
  123. package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
  124. package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
  125. package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
  126. package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
  127. package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
  128. package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
  129. package/dist/types/skills/tools/notify-tool.d.ts +53 -0
  130. package/dist/types/skills/tools/patch-tool.d.ts +45 -0
  131. package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
  132. package/dist/types/skills/tools/read-tool.d.ts +51 -0
  133. package/dist/types/skills/tools/repl-tool.d.ts +70 -0
  134. package/dist/types/skills/tools/search-tool.d.ts +112 -0
  135. package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
  136. package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
  137. package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
  138. package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
  139. package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
  140. package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
  141. package/dist/types/skills/tools/shell/index.d.ts +17 -0
  142. package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
  143. package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
  144. package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
  145. package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
  146. package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
  147. package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
  148. package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
  149. package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
  150. package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
  151. package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
  152. package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
  153. package/dist/types/skills/tools/task-tool.d.ts +104 -0
  154. package/dist/types/skills/tools/team-tool.d.ts +89 -0
  155. package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
  156. package/dist/types/skills/tools/tts-tool.d.ts +38 -0
  157. package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
  158. package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
  159. package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
  160. package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
  161. package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
  162. package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
  163. package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
  164. package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
  165. package/dist/types/skills/tools/write-tool.d.ts +45 -0
  166. package/dist/types/skills/tools.d.ts +65 -0
  167. package/package.json +4 -3
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Streaming Tool Executor — CC StreamingToolExecutor parity.
3
+ *
4
+ * Executes tools as they stream in with concurrency control:
5
+ * - Concurrent-safe tools execute in parallel with other concurrent-safe tools
6
+ * - Non-concurrent tools execute alone (exclusive access)
7
+ * - Results are buffered and emitted in the order tools were received
8
+ * - Bash errors cascade to abort sibling tools
9
+ * - Progress messages are yielded immediately
10
+ *
11
+ * Reference: claude-code src/services/tools/StreamingToolExecutor.ts
12
+ */
13
+ import type { ToolInvoker, AgentLogger, HookRegistry } from "../../agent/types.js";
14
+ import { type OpenAiToolCall } from "../../orchestration/index.js";
15
+ export type ToolStatus = "queued" | "executing" | "completed" | "yielded";
16
+ export interface ToolExecutionResult {
17
+ callId: string;
18
+ toolName: string;
19
+ ok: boolean;
20
+ error?: string;
21
+ blocked?: boolean;
22
+ blockReason?: string;
23
+ message: unknown;
24
+ }
25
+ export interface StreamingToolExecutorConfig {
26
+ toolInvoker: ToolInvoker;
27
+ hooks?: HookRegistry;
28
+ sessionId: string;
29
+ turnId: string;
30
+ log: AgentLogger;
31
+ signal?: AbortSignal;
32
+ /** Tool names that are considered concurrency-safe */
33
+ concurrencySafeTools?: Set<string>;
34
+ /** Hard ceiling on simultaneous tool executions (0 = unlimited). CC parity. */
35
+ maxConcurrentTools?: number;
36
+ }
37
+ /**
38
+ * Executes tools with concurrency control and streaming progress.
39
+ *
40
+ * Usage:
41
+ * 1. Call addTool() for each tool call as they arrive from the LLM stream
42
+ * 2. Call getCompletedResults() to drain completed results (non-blocking)
43
+ * 3. Call getRemainingResults() to wait for all remaining tools
44
+ */
45
+ export declare class StreamingToolExecutor {
46
+ private tools;
47
+ private hasErrored;
48
+ private erroredToolDescription;
49
+ private discarded;
50
+ private siblingAbortController;
51
+ private progressResolve?;
52
+ private readonly config;
53
+ private readonly concurrencySafe;
54
+ constructor(config: StreamingToolExecutorConfig);
55
+ /**
56
+ * Discard all pending and in-progress tools.
57
+ * Queued tools won't start, and in-progress tools receive synthetic errors.
58
+ */
59
+ discard(): void;
60
+ /**
61
+ * Add a tool to the execution queue. Starts executing immediately if conditions allow.
62
+ */
63
+ addTool(toolCall: OpenAiToolCall): void;
64
+ /**
65
+ * Check if a tool can execute based on current concurrency state.
66
+ */
67
+ private canExecuteTool;
68
+ /**
69
+ * Process the queue, starting tools when concurrency conditions allow.
70
+ */
71
+ private processQueue;
72
+ /**
73
+ * Get abort reason for a tool.
74
+ */
75
+ private getAbortReason;
76
+ /**
77
+ * Get a human-readable description of a tool for error messages.
78
+ */
79
+ private getToolDescription;
80
+ /**
81
+ * Create a synthetic error result for an aborted tool.
82
+ */
83
+ private createSyntheticError;
84
+ /**
85
+ * Execute a single tool.
86
+ */
87
+ private executeTool;
88
+ /**
89
+ * Get completed results that haven't been yielded yet (non-blocking).
90
+ * Maintains order where necessary.
91
+ */
92
+ getCompletedResults(): Generator<ToolExecutionResult>;
93
+ /**
94
+ * Wait for remaining tools and yield results as they complete.
95
+ */
96
+ getRemainingResults(): AsyncGenerator<ToolExecutionResult>;
97
+ private hasCompletedResults;
98
+ private hasExecutingTools;
99
+ private hasUnfinishedTools;
100
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Tool eligibility resolver for CLI subprocess mode.
3
+ *
4
+ * Ported from src/core/runtime/tool-eligibility.ts, replacing Hub's
5
+ * StoredGatewayCapabilitySnapshot with CLI's ToolDefinition[] from agent.turn.
6
+ *
7
+ * Core decision logic preserved:
8
+ * - Policy blocked (explicit block list)
9
+ * - Approval required (meta.requiresApproval / meta.isDangerous)
10
+ * - Read-only / safe tools (meta.isReadOnly → skip approval even in strict)
11
+ * - All tools from Gateway manifest are considered enabled & reachable
12
+ * (Gateway only sends available tools)
13
+ *
14
+ * Zero imports from express/pg/ioredis/ws.
15
+ */
16
+ import type { ToolDefinition } from "../../agent/types.js";
17
+ /**
18
+ * Tool permission levels aligned with Claude Code's permission model:
19
+ *
20
+ * Level 1 — always-allow: isReadOnly tools (e.g. read_file, search)
21
+ * Level 2 — default-allow: normal tools with no risk markers
22
+ * Level 3 — notify: isDangerous tools → emit tool_blocked warning but allow
23
+ * Level 4 — ask: requiresApproval tools → hook can block, emit approval.requested
24
+ * Level 5 — never-allow: explicitly blocked by policy
25
+ */
26
+ export type PermissionLevel = 1 | 2 | 3 | 4 | 5;
27
+ export type ToolEligibilityStatus = "eligible" | "approval-required" | "blocked-by-policy" | "dangerous-notify";
28
+ export type ToolEligibilityReasonCode = "policy_blocked" | "approval_required" | "dangerous_tool" | "always_allowed";
29
+ export interface ToolEligibilityEntry {
30
+ toolName: string;
31
+ status: ToolEligibilityStatus;
32
+ permissionLevel: PermissionLevel;
33
+ approvalRequired: boolean;
34
+ reasonCodes: ToolEligibilityReasonCode[];
35
+ }
36
+ export interface ToolEligibilityContext {
37
+ /** Explicitly blocked tool names (e.g. from config or policy) */
38
+ blockedToolNames?: string[];
39
+ /** Dangerous tool name patterns (regex strings) for pattern-based detection */
40
+ dangerousPatterns?: string[];
41
+ }
42
+ export interface ToolEligibilityResult {
43
+ /** Tools eligible for execution (includes approval-required ones) */
44
+ eligibleTools: ToolDefinition[];
45
+ /** Tools blocked by policy (removed from LLM tool list) */
46
+ blockedTools: ToolEligibilityEntry[];
47
+ /** Tools needing approval before execution */
48
+ approvalRequiredTools: ToolEligibilityEntry[];
49
+ /** Full eligibility map by tool name */
50
+ eligibilityByName: Map<string, ToolEligibilityEntry>;
51
+ }
52
+ /**
53
+ * Resolve tool eligibility for a set of tools from agent.turn.
54
+ *
55
+ * Returns filtered tool lists and eligibility metadata.
56
+ * Blocked tools are removed from the eligible list (not sent to LLM).
57
+ * Approval-required tools remain in the list but flagged for hook interception.
58
+ */
59
+ export declare function resolveToolEligibility(tools: ToolDefinition[], context?: ToolEligibilityContext): ToolEligibilityResult;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Tool result storage — CC toolResultStorage.ts aligned.
3
+ *
4
+ * Two-layer mechanism to manage tool result sizes:
5
+ * Level 1 (per-tool): At execution time, results > DEFAULT_MAX_RESULT_SIZE_CHARS
6
+ * are persisted to disk and replaced with preview references.
7
+ * Level 2 (per-message budget): Before API call, aggregate tool results in
8
+ * each group (consecutive tool messages between assistant messages)
9
+ * are checked against MAX_TOOL_RESULTS_PER_MESSAGE_CHARS. The largest
10
+ * fresh results are persisted until under budget.
11
+ *
12
+ * ContentReplacementState tracks decisions across turns for prompt cache
13
+ * stability — once a tool result's fate is decided (replaced or not), the
14
+ * decision is frozen for the remainder of the conversation.
15
+ *
16
+ * CC reference: src/utils/toolResultStorage.ts
17
+ * Zero imports from express/pg/ioredis/ws.
18
+ */
19
+ export declare const TOOL_RESULTS_SUBDIR = "tool-results";
20
+ /** XML tag wrapping persisted output previews (CC PERSISTED_OUTPUT_TAG) */
21
+ export declare const PERSISTED_OUTPUT_TAG = "<persisted-output>";
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
+ /**
26
+ * Per-conversation-thread state for the aggregate tool result budget.
27
+ * State must be stable to preserve prompt cache:
28
+ * - seenIds: tool_call_ids that have passed through the budget check (replaced
29
+ * or not). Once seen, a result's fate is frozen for the conversation.
30
+ * - replacements: subset of seenIds that were persisted to disk and
31
+ * replaced with previews, mapped to the exact preview string.
32
+ * Re-application is a Map lookup — no file I/O, byte-identical.
33
+ *
34
+ * CC reference: ContentReplacementState
35
+ */
36
+ export type ContentReplacementState = {
37
+ seenIds: Set<string>;
38
+ replacements: Map<string, string>;
39
+ };
40
+ export type PersistedToolResult = {
41
+ filepath: string;
42
+ originalSize: number;
43
+ preview: string;
44
+ hasMore: boolean;
45
+ };
46
+ export declare function createContentReplacementState(): ContentReplacementState;
47
+ export declare function generatePreview(content: string, maxBytes: number): {
48
+ preview: string;
49
+ hasMore: boolean;
50
+ };
51
+ export declare function persistToolResult(content: string, toolCallId: string, sessionId: string): Promise<PersistedToolResult | null>;
52
+ /**
53
+ * Build a reference message for large tool results (CC buildLargeToolResultMessage parity).
54
+ */
55
+ export declare function buildLargeToolResultMessage(result: PersistedToolResult): string;
56
+ /**
57
+ * If content exceeds threshold, persist to disk and return a preview reference.
58
+ * Falls back to hard truncation if persistence fails.
59
+ * Called at tool execution time in streaming-tool-executor.ts.
60
+ */
61
+ export declare function maybePersistLargeToolResult(content: string, toolCallId: string, sessionId: string, threshold?: number): Promise<string>;
62
+ interface MessageLike {
63
+ role: string;
64
+ content?: string | unknown;
65
+ tool_call_id?: string;
66
+ }
67
+ /**
68
+ * Enforce per-message aggregate budget on tool results.
69
+ * CC enforceToolResultBudget parity.
70
+ *
71
+ * For each group of tool messages whose content together exceeds
72
+ * the per-message limit, the largest FRESH (never-before-seen) results
73
+ * are persisted to disk and replaced with previews.
74
+ *
75
+ * State is tracked by tool_call_id: once a result is seen, its fate is
76
+ * frozen. Previously-replaced results get the same replacement re-applied
77
+ * (no I/O, byte-identical). Previously-unreplaced results are never
78
+ * replaced later (would break prompt cache).
79
+ *
80
+ * @param state — MUTATED in place (seenIds and replacements updated)
81
+ * @returns messages with replacements applied + count of new replacements
82
+ */
83
+ export declare function enforceToolResultBudget(messages: MessageLike[], state: ContentReplacementState, sessionId: string, limit?: number): Promise<{
84
+ messages: MessageLike[];
85
+ newlyReplacedCount: number;
86
+ }>;
87
+ export {};
@@ -0,0 +1,61 @@
1
+ import { ContextEngineRegistry, type CompressibleMessage, type CompressionResult, type CompressionStrategy, type AsyncCompressionStrategy, type SummarizeFn } from "../../orchestration/index.js";
2
+ import type { HookRegistry } from "./hook-registry.js";
3
+ import type { RuntimeLogger } from "./hook-registry.js";
4
+ import type { LLMTransport } from "../../llm/transport.js";
5
+ /** Rough token estimate: ~4 chars per token for mixed CJK/English. */
6
+ export declare function estimateTokens(msg: CompressibleMessage): number;
7
+ /** Estimate total tokens for a message array. */
8
+ export declare function estimateTotalTokens(messages: CompressibleMessage[]): number;
9
+ export declare function getCompressionMetrics(): import("../../orchestration/index.js").CompressionMetricsSnapshot;
10
+ export declare function getContextEngineRegistry(): ContextEngineRegistry;
11
+ /**
12
+ * Create a summarization callback using an injected LLM transport.
13
+ * For CLI mode: uses the same transport that powers the agent loop.
14
+ * Falls back to non-LLM summary when transport/apiKey not available.
15
+ */
16
+ export declare function createSummarizeFn(log: RuntimeLogger, opts?: {
17
+ transport?: LLMTransport;
18
+ apiKey?: string;
19
+ model?: string;
20
+ }): SummarizeFn;
21
+ /** Phase 1: sync-only pipeline (ToolResultTrim + MicroCompact + SlidingWindow) */
22
+ export declare function createSyncPipeline(): CompressionStrategy;
23
+ /** Phase 2+3: async pipeline with LLM summarization + cache awareness */
24
+ export declare function createAsyncPipeline(summarize: SummarizeFn, opts?: {
25
+ onCacheInvalidated?: (info: {
26
+ droppedCount: number;
27
+ strategy: string;
28
+ }) => void;
29
+ }): AsyncCompressionStrategy;
30
+ /** Phase 2.3: incremental compaction pipeline (for partial compact) */
31
+ export declare function createIncrementalPipeline(summarize: SummarizeFn, opts?: {
32
+ preserveRecentCount?: number;
33
+ onCacheInvalidated?: (info: {
34
+ droppedCount: number;
35
+ strategy: string;
36
+ }) => void;
37
+ }): AsyncCompressionStrategy;
38
+ export interface CompressOptions {
39
+ budget?: number;
40
+ model?: string;
41
+ pipeline?: CompressionStrategy;
42
+ allowLlm?: boolean;
43
+ summarize?: SummarizeFn;
44
+ sessionId?: string;
45
+ }
46
+ /** Synchronous compression (Phase 1 only). */
47
+ export declare function compressMessages(messages: CompressibleMessage[], opts?: CompressOptions): CompressionResult;
48
+ /** Async compression (Phase 2+) — supports LLM summarization. */
49
+ export declare function compressMessagesAsync(messages: CompressibleMessage[], opts: CompressOptions & {
50
+ summarize: SummarizeFn;
51
+ }): Promise<CompressionResult>;
52
+ export declare function registerDefaultContextEngine(log: RuntimeLogger, opts?: {
53
+ transport?: LLMTransport;
54
+ apiKey?: string;
55
+ model?: string;
56
+ }): void;
57
+ export declare function registerContextCompressionHook(hooks: HookRegistry, log: RuntimeLogger, opts?: {
58
+ transport?: LLMTransport;
59
+ apiKey?: string;
60
+ model?: string;
61
+ }): void;
@@ -0,0 +1,12 @@
1
+ import type { HookPoint, HookContextMap, HookResult, HookHandler, HookRegistration, HookRegistry } from "../../contracts/hooks.js";
2
+ export type { HookPoint, HookContextMap, HookResult, HookHandler, HookRegistration, HookRegistry };
3
+ /** Minimal logger interface — compatible with both pino and AgentLogger. */
4
+ export interface RuntimeLogger {
5
+ info(msg: string): void;
6
+ info(obj: Record<string, unknown>, msg: string): void;
7
+ warn(msg: string): void;
8
+ warn(obj: Record<string, unknown>, msg: string): void;
9
+ debug(msg: string): void;
10
+ debug(obj: Record<string, unknown>, msg: string): void;
11
+ }
12
+ export declare function createHookRegistry(log: RuntimeLogger): HookRegistry;
@@ -0,0 +1,3 @@
1
+ export { createHookRegistry, type RuntimeLogger } from "./hook-registry.js";
2
+ export { registerMemoryHooks, createMemoryPrefetchState, type MemoryHooksDeps, type MemoryPrefetchState, MEMORY_PREFETCH_CONFIG, } from "./memory-hooks.js";
3
+ export { registerContextCompressionHook, compressMessages } from "./context-compression.js";
@@ -0,0 +1,49 @@
1
+ import type { HookRegistry } from "../../contracts/hooks.js";
2
+ import type { MemoryProvider } from "qlogicagent-runtime-contracts";
3
+ export declare const MEMORY_PREFETCH_CONFIG: {
4
+ /** Max bytes of memory content to inject per session (CC: 60KB) */
5
+ readonly MAX_SESSION_BYTES: number;
6
+ /** Max results per recall query */
7
+ readonly LIMIT_PER_RECALL: 10;
8
+ /** Max entries in surfaced-path LRU set */
9
+ readonly MAX_SURFACED_ENTRIES: 100;
10
+ };
11
+ export interface MemoryHooksDeps {
12
+ /** QMemory adapter (MemoryProvider with search/health). */
13
+ memoryProvider?: MemoryProvider;
14
+ /** User ID for memory lookups. */
15
+ userId: string;
16
+ /** Logger. */
17
+ log: {
18
+ debug(msg: string): void;
19
+ warn(msg: string): void;
20
+ };
21
+ }
22
+ /** Session-scoped state for dedup and byte budget (CC parity). */
23
+ export interface MemoryPrefetchState {
24
+ /** Paths already surfaced this session (CC readFileState LRU parity). */
25
+ surfacedPaths: Set<string>;
26
+ /** Total bytes injected this session. */
27
+ sessionBytes: number;
28
+ }
29
+ /**
30
+ * Create a fresh memory prefetch state (once per session).
31
+ */
32
+ export declare function createMemoryPrefetchState(): MemoryPrefetchState;
33
+ /**
34
+ * Register memory lifecycle hooks on the HookRegistry.
35
+ *
36
+ * Hook points wired:
37
+ * - memory.before_recall: prefetch context from qmemory (query-based)
38
+ * - memory.after_recall: log recall results
39
+ *
40
+ * CC parity additions:
41
+ * - LRU dedup via surfacedPaths (filterDuplicateMemoryAttachments)
42
+ * - Session byte limit (MAX_SESSION_BYTES = 60KB)
43
+ * - Async prefetch (non-blocking promise, abort-aware)
44
+ *
45
+ * Returns a cleanup function to unregister.
46
+ */
47
+ export declare function registerMemoryHooks(hooks: HookRegistry, deps: MemoryHooksDeps,
48
+ /** Shared state — pass the same object across hook re-registrations in a session. */
49
+ prefetchState?: MemoryPrefetchState): () => void;
@@ -0,0 +1,5 @@
1
+ export * from "./session/index.js";
2
+ export * from "./hooks/index.js";
3
+ export * from "./execution/index.js";
4
+ export * from "./prompt/index.js";
5
+ export * from "./infra/index.js";
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Agent Paths — Centralized dot-directory name and path helpers.
3
+ *
4
+ * All filesystem paths under `~/.qlogicagent/` (user-level) or
5
+ * `<project>/.qlogicagent/` (project-level) must go through these
6
+ * helpers so the dot-dir name is defined in exactly one place.
7
+ */
8
+ /** Dot-directory name used for both user-level and project-level storage. */
9
+ export declare const AGENT_DOT_DIR = ".qlogicagent";
10
+ /** `~/.qlogicagent/` */
11
+ export declare function getUserAgentHome(): string;
12
+ /** `~/.qlogicagent/sessions/` */
13
+ export declare function getUserSessionsRoot(): string;
14
+ /** `~/.qlogicagent/sessions/{sessionId}` */
15
+ export declare function getUserSessionDir(sessionId: string): string;
16
+ /** `~/.qlogicagent/.credentials.json` */
17
+ export declare function getUserCredentialsPath(): string;
18
+ /** `~/.qlogicagent/plugins/` */
19
+ export declare function getUserPluginsDir(): string;
20
+ /** `~/.qlogicagent/skills/` */
21
+ export declare function getUserSkillsDir(): string;
22
+ /** `~/.qlogicagent/settings.json` */
23
+ export declare function getUserSettingsPath(): string;
24
+ /** `~/.qlogicagent/cache/` */
25
+ export declare function getUserCacheDir(): string;
26
+ /** `~/.qlogicagent/debug-logs/` */
27
+ export declare function getUserDebugLogsDir(): string;
28
+ /** `~/.qlogicagent/checkpoints/` or `~/.qlogicagent/checkpoints/{sessionId}` */
29
+ export declare function getUserCheckpointsDir(sessionId?: string): string;
30
+ /** `~/.qlogicagent/plugin-cache/` */
31
+ export declare function getUserPluginCacheDir(): string;
32
+ /** `~/.qlogicagent/mcp.json` */
33
+ export declare function getUserMcpConfigPath(): string;
34
+ /** `~/.qlogicagent/marketplace.json` */
35
+ export declare function getUserMarketplaceConfigPath(): string;
36
+ /** `~/.qlogicagent/workflows/` */
37
+ export declare function getUserWorkflowsDir(): string;
38
+ /** `~/.qlogicagent/INSTRUCTIONS.md` */
39
+ export declare function getUserInstructionsPath(): string;
40
+ /** `~/.qlogicagent/rules/` */
41
+ export declare function getUserRulesDir(): string;
42
+ /** `<cwd>/.qlogicagent/` */
43
+ export declare function getProjectAgentDir(cwd?: string): string;
44
+ /** `<cwd>/.qlogicagent/workflows/` */
45
+ export declare function getProjectWorkflowsDir(cwd?: string): string;
46
+ /** `<cwd>/.qlogicagent/plugins/` */
47
+ export declare function getProjectPluginsDir(cwd?: string): string;
48
+ /** `<cwd>/.qlogicagent/skills/` */
49
+ export declare function getProjectSkillsDir(cwd?: string): string;
50
+ /** `<cwd>/.qlogicagent/settings.json` */
51
+ export declare function getProjectSettingsPath(cwd?: string): string;
52
+ /** `<cwd>/.qlogicagent/INSTRUCTIONS.md` */
53
+ export declare function getProjectInstructionsPath(cwd?: string): string;
54
+ /** `<cwd>/.qlogicagent/rules/` */
55
+ export declare function getProjectRulesDir(cwd?: string): string;
56
+ /** `<gitRoot>/.qlogicagent/hooks/` */
57
+ export declare function getGitRootHooksDir(gitRoot: string): string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Local Checkpoint Backend — git-based shadow repo implementation.
3
+ *
4
+ * Creates and manages checkpoint snapshots in `~/.qlogicagent/checkpoints/<sessionId>/`
5
+ * using a shadow git repository independent of the user's project .git.
6
+ */
7
+ import type { CheckpointToolDeps } from "../../skills/tools/checkpoint-tool.js";
8
+ export declare function createLocalCheckpointBackend(projectRoot: string, sessionId: string): CheckpointToolDeps;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Cleanup Registry — CC cleanupRegistry.ts parity.
3
+ *
4
+ * Global registry for cleanup functions that should run during graceful shutdown.
5
+ * Separate from stop handling to avoid circular dependencies.
6
+ *
7
+ * Reference: claude-code src/utils/cleanupRegistry.ts
8
+ */
9
+ /**
10
+ * Register a cleanup function to run during graceful shutdown.
11
+ * @param cleanupFn - Function to run during cleanup (can be sync or async)
12
+ * @returns Unregister function that removes the cleanup handler
13
+ */
14
+ export declare function registerCleanup(cleanupFn: () => Promise<void>): () => void;
15
+ /**
16
+ * Run all registered cleanup functions.
17
+ * Used internally by graceful shutdown path.
18
+ */
19
+ export declare function runCleanupFunctions(): Promise<void>;
20
+ /**
21
+ * Get count of registered cleanup handlers (for diagnostics).
22
+ */
23
+ export declare function getCleanupCount(): number;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Disk Storage Manager — unified atomic file I/O for agent self-managed storage.
3
+ *
4
+ * Provides:
5
+ * - Atomic write (tmp + rename) with dir auto-creation
6
+ * - JSON read/write helpers
7
+ * - MemoryStore disk persistence (auto-save on mutation)
8
+ */
9
+ /**
10
+ * Write data atomically: write to a temp file in the same directory,
11
+ * then rename over the target. This prevents partial/corrupted reads.
12
+ */
13
+ export declare function atomicWriteFile(filePath: string, data: string | Buffer): Promise<void>;
14
+ /**
15
+ * Read a JSON file. Returns `undefined` if the file does not exist.
16
+ */
17
+ export declare function readJsonFile<T = unknown>(filePath: string): Promise<T | undefined>;
18
+ /**
19
+ * Write a JSON file atomically.
20
+ */
21
+ export declare function writeJsonFile(filePath: string, data: unknown): Promise<void>;
22
+ /** Path to user-level memory file: `~/.qlogicagent/memory.json` */
23
+ export declare function getMemoryFilePath(): string;
24
+ export interface PersistedMemory {
25
+ memory: string;
26
+ user: string;
27
+ /** ISO 8601 timestamp of last save. */
28
+ savedAt: string;
29
+ }
30
+ /** Load persisted memory from disk. Returns undefined if no file exists. */
31
+ export declare function loadPersistedMemory(): Promise<PersistedMemory | undefined>;
32
+ /** Save memory to disk atomically. */
33
+ export declare function savePersistedMemory(data: {
34
+ memory: string;
35
+ user: string;
36
+ }): Promise<void>;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * File Watcher — CC filesystem change tracking parity.
3
+ *
4
+ * Fires hook events when files in the project change:
5
+ * - file.changed (created/modified/deleted)
6
+ * - cwd.changed (working directory switch)
7
+ *
8
+ * Uses Node.js fs.watch for project-level file monitoring.
9
+ * Does NOT use chokidar or other heavyweight watchers —
10
+ * this is a lightweight change-awareness system.
11
+ *
12
+ * Watched paths:
13
+ * - .qlogicagent/settings.json → permission hot-reload
14
+ * - INSTRUCTIONS.md / .qlogicagent/INSTRUCTIONS.md → instruction re-load
15
+ * - configurable additional patterns
16
+ *
17
+ * Reference: claude-code file-watcher usage throughout lifecycle
18
+ */
19
+ import type { HookRegistry } from "../../contracts/hooks.js";
20
+ export interface FileWatcherDeps {
21
+ /** Project root directory (base for relative paths) */
22
+ projectRoot: string;
23
+ /** Session ID for hook context */
24
+ sessionId: string;
25
+ /** Hook registry for file.changed / cwd.changed events */
26
+ hooks: HookRegistry;
27
+ /** Logger */
28
+ log?: (msg: string) => void;
29
+ /** Callback to reset instruction cache when instructions change (injected, decoupled from prompt/) */
30
+ onInstructionCacheReset?: () => void;
31
+ }
32
+ export type ChangeType = "created" | "modified" | "deleted";
33
+ export interface FileChangeEvent {
34
+ filePath: string;
35
+ changeType: ChangeType;
36
+ relativePath: string;
37
+ }
38
+ export declare class FileWatcher {
39
+ private watchers;
40
+ private deps;
41
+ private debounceTimers;
42
+ private _cwd;
43
+ constructor(deps: FileWatcherDeps);
44
+ get cwd(): string;
45
+ /**
46
+ * Start watching files.
47
+ * Watches each path in WATCHED_PATHS that exists on disk.
48
+ */
49
+ start(): Promise<void>;
50
+ /**
51
+ * Watch a single path. If it's a directory, watches recursively.
52
+ */
53
+ private watchPath;
54
+ /**
55
+ * Handle a file change event (debounced).
56
+ */
57
+ private handleChange;
58
+ /**
59
+ * Update the current working directory.
60
+ * Fires cwd.changed hook if the directory actually changed.
61
+ */
62
+ setCwd(newCwd: string): void;
63
+ /**
64
+ * Stop all watchers.
65
+ */
66
+ stop(): void;
67
+ }
68
+ /**
69
+ * Create and start a file watcher.
70
+ * Returns the watcher instance (call .stop() to clean up).
71
+ */
72
+ export declare function createFileWatcher(deps: FileWatcherDeps): Promise<FileWatcher>;
@@ -0,0 +1,8 @@
1
+ export { AGENT_DOT_DIR, getUserAgentHome, getUserSessionDir, getUserCredentialsPath, getUserPluginsDir, getUserSkillsDir, getUserSettingsPath, getUserCacheDir, getUserDebugLogsDir, getUserCheckpointsDir, getUserPluginCacheDir, getUserMcpConfigPath, getUserMarketplaceConfigPath, getUserWorkflowsDir, getUserInstructionsPath, getProjectAgentDir, getProjectWorkflowsDir, getProjectPluginsDir, getProjectSkillsDir, getProjectSettingsPath, getProjectInstructionsPath, getProjectRulesDir, getGitRootHooksDir, } from "./agent-paths.js";
2
+ export { getBudgetContinuationMessage } from "./token-budget.js";
3
+ export { type SecureStorage, saveApiKey, loadApiKey } from "./secure-storage.js";
4
+ export { createFileWatcher, FileWatcher } from "./file-watcher.js";
5
+ export { TaskStore } from "./task-runtime.js";
6
+ export { createWorktreeBackend } from "./worktree-backend.js";
7
+ export { registerCleanup, runCleanupFunctions } from "./cleanup-registry.js";
8
+ export { atomicWriteFile, readJsonFile, writeJsonFile, loadPersistedMemory, savePersistedMemory, getMemoryFilePath, type PersistedMemory, } from "./disk-storage.js";