qlogicagent 0.5.2 → 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 +3 -2
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Dream Sub-agent — CC autoDream parity.
3
+ *
4
+ * Memory consolidation runs as a restricted sub-agent:
5
+ * - Read-only tool access (bash: ls/grep/cat/find/stat/wc/head/tail)
6
+ * - File writes restricted to memory directory
7
+ * - 4-phase system prompt: Orient → Gather → Consolidate → Prune
8
+ * - Trigger gates: time (24h) + session count (5)
9
+ * - PID-based consolidation lock
10
+ *
11
+ * Reference: claude-code src/services/autoDream/
12
+ */
13
+ import type { DreamTaskState, DreamTurn } from "../../orchestration/task-types.js";
14
+ import type { ToolDefinition, ToolInvoker, AgentLogger, HookRegistry } from "../../agent/types.js";
15
+ import type { LLMTransport } from "../../llm/transport.js";
16
+ export interface DreamTriggerConfig {
17
+ /** Minimum hours since last consolidation. Default: 24. */
18
+ minHours: number;
19
+ /** Minimum sessions since last consolidation. Default: 5. */
20
+ minSessions: number;
21
+ /** Scan throttle interval (ms). Default: 600_000 (10 min). */
22
+ scanIntervalMs: number;
23
+ /** Force run, ignoring gates. */
24
+ force?: boolean;
25
+ }
26
+ export interface DreamContext {
27
+ /** Root directory where memory files live. */
28
+ memoryRoot: string;
29
+ /** Directory containing session transcript JSONL files. */
30
+ transcriptDir: string;
31
+ /** Current agent session ID (excluded from session count). */
32
+ currentSessionId: string;
33
+ /** Callback to list session IDs touched since a timestamp. */
34
+ listSessionsSince: (sinceMs: number) => Promise<string[]>;
35
+ }
36
+ export interface DreamToolRestriction {
37
+ toolName: string;
38
+ input: Record<string, unknown>;
39
+ }
40
+ export type DreamToolVerdict = {
41
+ allowed: true;
42
+ } | {
43
+ allowed: false;
44
+ reason: string;
45
+ };
46
+ /** Result of a dream consolidation run. */
47
+ export interface DreamRunResult {
48
+ /** Whether dream ran successfully. */
49
+ ok: boolean;
50
+ /** Number of sessions reviewed. */
51
+ sessionsReviewed: number;
52
+ /** Memory files touched. */
53
+ filesTouched: string[];
54
+ /** Dream turns produced. */
55
+ turns: DreamTurn[];
56
+ /** Total duration (ms). */
57
+ durationMs: number;
58
+ /** Error message if failed. */
59
+ error?: string;
60
+ }
61
+ /**
62
+ * Check if a tool invocation is allowed during dream consolidation.
63
+ *
64
+ * Allowed:
65
+ * - read_file, grep, glob, search — unrestricted read-only tools
66
+ * - bash — only read-only commands (ls, grep, cat, find, stat, wc, head, tail)
67
+ * - file_edit, file_write — only within memoryRoot
68
+ * - Everything else — denied
69
+ */
70
+ export declare function canUseDreamTool(memoryRoot: string, restriction: DreamToolRestriction): DreamToolVerdict;
71
+ /**
72
+ * Build the 4-phase memory consolidation prompt.
73
+ *
74
+ * Adapted from CC's consolidationPrompt.ts with our project context.
75
+ */
76
+ export declare function buildConsolidationPrompt(memoryRoot: string, transcriptDir: string, sessionIds: string[], opts?: {
77
+ hasQMemory?: boolean;
78
+ }): string;
79
+ /**
80
+ * Check whether dream consolidation should run.
81
+ *
82
+ * Gate order (cheapest first):
83
+ * 1. Time gate — hours since lastConsolidatedAt >= minHours
84
+ * 2. Scan throttle — 10-minute interval to suppress redundant scans
85
+ * 3. Session gate — session count since lastConsolidatedAt >= minSessions
86
+ *
87
+ * @returns Session IDs to review, or null if gates failed.
88
+ */
89
+ export declare function shouldTriggerDream(ctx: DreamContext, config?: Partial<DreamTriggerConfig>): Promise<{
90
+ sessionIds: string[];
91
+ } | null>;
92
+ /**
93
+ * Attempt to acquire the consolidation lock.
94
+ *
95
+ * @returns Prior mtime (for rollback) or null if blocked.
96
+ */
97
+ export declare function tryAcquireConsolidationLock(memoryRoot: string): Promise<number | null>;
98
+ /**
99
+ * Rollback the lock mtime after a failed dream run.
100
+ */
101
+ export declare function rollbackConsolidationLock(memoryRoot: string, priorMtime: number): Promise<void>;
102
+ /**
103
+ * Update the lock file to record successful consolidation (mtime = now).
104
+ */
105
+ export declare function markConsolidationComplete(memoryRoot: string): Promise<void>;
106
+ /** Create initial DreamTaskState. */
107
+ export declare function createDreamTaskState(opts: {
108
+ sessionId: string;
109
+ sessionsReviewing: number;
110
+ priorLockMtime: number;
111
+ parentTaskId?: string;
112
+ }): DreamTaskState;
113
+ /** Add a turn to the dream state. */
114
+ export declare function addDreamTurn(state: DreamTaskState, turn: DreamTurn, touchedPaths: string[]): DreamTaskState;
115
+ /** Mark dream as completed. */
116
+ export declare function completeDreamState(state: DreamTaskState): DreamTaskState;
117
+ /** Mark dream as failed. */
118
+ export declare function failDreamState(state: DreamTaskState): DreamTaskState;
119
+ /**
120
+ * Full dream orchestration entry point.
121
+ *
122
+ * This coordinates the entire dream lifecycle:
123
+ * 1. Check trigger gates
124
+ * 2. Acquire consolidation lock
125
+ * 3. Build consolidation prompt
126
+ * 4. Return dream context for the caller to run through agent loop
127
+ *
128
+ * The caller (stdio-server) is responsible for:
129
+ * - Running the prompt through the agent's tool loop
130
+ * - Applying canUseDreamTool() restrictions via tool.before_invoke hook
131
+ * - Calling markConsolidationComplete() on success
132
+ * - Calling rollbackConsolidationLock() on failure
133
+ */
134
+ export declare function prepareDreamRun(ctx: DreamContext, config?: Partial<DreamTriggerConfig>): Promise<{
135
+ prompt: string;
136
+ taskState: DreamTaskState;
137
+ sessionIds: string[];
138
+ } | null>;
139
+ export interface DreamRunDeps {
140
+ /** Dream context (memoryRoot, transcriptDir, etc.) */
141
+ context: DreamContext;
142
+ /** Trigger configuration */
143
+ triggerConfig?: Partial<DreamTriggerConfig>;
144
+ /** LLM transport */
145
+ transport: LLMTransport;
146
+ /** Tool invoker */
147
+ toolInvoker: ToolInvoker;
148
+ /** Available tools (will be filtered by canUseDreamTool) */
149
+ tools: ToolDefinition[];
150
+ /** API key */
151
+ apiKey: string;
152
+ /** Model for dream */
153
+ model: string;
154
+ /** Logger */
155
+ log: AgentLogger;
156
+ /** Hook registry */
157
+ hooks?: HookRegistry;
158
+ /** Parent abort signal */
159
+ parentSignal?: AbortSignal;
160
+ /**
161
+ * QMemory adapter — when provided, Dream Agent acts as the "hippocampus":
162
+ * reads existing long-term memories, writes classified session insights,
163
+ * and submits feedback on outdated/contradicted memories.
164
+ */
165
+ qmemoryAdapter?: {
166
+ search(query: string, userId: string, options?: {
167
+ limit?: number;
168
+ }): Promise<Array<{
169
+ blockId: string;
170
+ text: string;
171
+ score: number;
172
+ }>>;
173
+ addText?(text: string, userId: string, options?: {
174
+ sessionId?: string;
175
+ source?: string;
176
+ }): Promise<{
177
+ memoriesAdded: number;
178
+ }>;
179
+ feedback?(memoryIds: string[], signal: string, sessionId?: string): Promise<void>;
180
+ };
181
+ /** User ID for QMemory operations. */
182
+ qmemoryUserId?: string;
183
+ }
184
+ /**
185
+ * Run a complete dream consolidation using an isolated forked agent.
186
+ *
187
+ * CC parity: This uses runForkedAgent() for true isolation instead of
188
+ * hook-based tool restriction on the shared agent loop. The dream runs
189
+ * in its own message history with its own AbortController.
190
+ *
191
+ * Full lifecycle:
192
+ * 1. Check trigger gates
193
+ * 2. Acquire consolidation lock
194
+ * 3. Build consolidation prompt
195
+ * 4. Fork sub-agent with restricted tools
196
+ * 5. Run to completion
197
+ * 6. Mark consolidation complete (or rollback on failure)
198
+ */
199
+ export declare function runDream(deps: DreamRunDeps): Promise<DreamRunResult>;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Forked Agent — CC forkedAgent.ts parity.
3
+ *
4
+ * Runs an isolated agent query loop with:
5
+ * - Independent AbortController (parent abort propagates)
6
+ * - Independent message history (no mutation of parent conversation)
7
+ * - Shared LLM config for prompt cache sharing
8
+ * - Tool restriction via canUseTool function
9
+ * - Usage tracking across all API calls
10
+ * - Optional transcript recording
11
+ *
12
+ * This is the execution engine for all sub-agent types:
13
+ * - Dream consolidation
14
+ * - Background memory extraction
15
+ * - Skill/command forking
16
+ * - AgentTool async agents
17
+ *
18
+ * Reference: claude-code src/utils/forkedAgent.ts
19
+ */
20
+ import type { AgentLogger, ChatMessage, ToolDefinition, ToolInvoker, TokenUsage, TurnEvent, HookRegistry } from "../../agent/types.js";
21
+ import type { LLMTransport } from "../../llm/transport.js";
22
+ import type { AgentProgress } from "./progress-tracker.js";
23
+ /**
24
+ * Tool permission check function — CC canUseTool parity.
25
+ *
26
+ * Returns allow/deny for each tool invocation.
27
+ * Used by dream agent (read-only bash + memory writes only),
28
+ * session memory (full read, no write), etc.
29
+ */
30
+ export type CanUseToolFn = (toolName: string, input: Record<string, unknown>) => {
31
+ allowed: true;
32
+ } | {
33
+ allowed: false;
34
+ reason: string;
35
+ };
36
+ /**
37
+ * Parameters for running a forked agent.
38
+ */
39
+ export interface ForkedAgentParams {
40
+ /** Initial messages for the forked query loop */
41
+ promptMessages: ChatMessage[];
42
+ /** System prompt for the forked agent */
43
+ systemPrompt?: string;
44
+ /** Available tools */
45
+ tools: ToolDefinition[];
46
+ /** Tool permission check (restricts tool access) */
47
+ canUseTool?: CanUseToolFn;
48
+ /** LLM transport for API calls */
49
+ transport: LLMTransport;
50
+ /** Tool invoker for tool execution */
51
+ toolInvoker: ToolInvoker;
52
+ /** API key */
53
+ apiKey: string;
54
+ /** Model name */
55
+ model: string;
56
+ /** Logger */
57
+ log: AgentLogger;
58
+ /** Hook registry (optional) */
59
+ hooks?: HookRegistry;
60
+ /** Label for analytics/debugging */
61
+ forkLabel: string;
62
+ /** Source identifier for tracking */
63
+ querySource?: string;
64
+ /** Optional cap on number of turns */
65
+ maxTurns?: number;
66
+ /** Optional cap on output tokens */
67
+ maxOutputTokens?: number;
68
+ /** Temperature override */
69
+ temperature?: number;
70
+ /** Parent AbortController (child will be created) */
71
+ parentSignal?: AbortSignal;
72
+ /** Callback invoked for each event as it arrives */
73
+ onEvent?: (event: TurnEvent) => void;
74
+ /** Callback for progress updates */
75
+ onProgress?: (progress: AgentProgress) => void;
76
+ /** Skip transcript recording */
77
+ skipTranscript?: boolean;
78
+ /** Token budget for this sub-agent. 0 or undefined = no limit. */
79
+ budgetTokens?: number;
80
+ /** Parent sidechain depth (propagated to child tool loop) */
81
+ parentDepth?: number;
82
+ /** Sidechain type for tool access policy (default "code-repair" = full) */
83
+ sidechainType?: import("../../orchestration/index.js").SidechainType;
84
+ }
85
+ /**
86
+ * Result of a forked agent run.
87
+ */
88
+ export interface ForkedAgentResult {
89
+ /** All events yielded during the query loop */
90
+ events: TurnEvent[];
91
+ /** Accumulated token usage across all API calls */
92
+ totalUsage: TokenUsage;
93
+ /** Progress tracker final state */
94
+ progress: AgentProgress;
95
+ /** Duration of the fork in ms */
96
+ durationMs: number;
97
+ /** Whether it completed successfully */
98
+ ok: boolean;
99
+ /** Error message if failed */
100
+ error?: string;
101
+ }
102
+ /**
103
+ * Run a forked agent query loop with full isolation.
104
+ *
105
+ * This function:
106
+ * 1. Creates an isolated context (own AbortController, message history)
107
+ * 2. Runs the agent loop with tool restrictions
108
+ * 3. Tracks usage across all API calls
109
+ * 4. Returns accumulated results
110
+ */
111
+ export declare function runForkedAgent(params: ForkedAgentParams): Promise<ForkedAgentResult>;
@@ -0,0 +1,6 @@
1
+ export { StreamingToolExecutor } from "./streaming-tool-executor.js";
2
+ export { createContentReplacementState, enforceToolResultBudget, maybePersistLargeToolResult, type ContentReplacementState, type PersistedToolResult, } from "./tool-result-storage.js";
3
+ export { resolveToolEligibility, type ToolEligibilityContext, type ToolEligibilityResult } from "./tool-eligibility.js";
4
+ export { runForkedAgent, type ForkedAgentParams, type CanUseToolFn } from "./forked-agent.js";
5
+ export { runDream, type DreamRunDeps } from "./dream-agent.js";
6
+ export { createProgressTracker, updateProgressFromUsage, recordToolUse, getProgressUpdate, type AgentProgress, } from "./progress-tracker.js";
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Progress Tracker — CC ProgressTracker / AgentProgress parity.
3
+ *
4
+ * Tracks tool use count, token consumption (input/output split),
5
+ * and recent tool activities for UI display.
6
+ *
7
+ * Reference: claude-code src/tasks/LocalAgentTask/LocalAgentTask.tsx
8
+ */
9
+ /**
10
+ * Describes a single tool use activity — for UI previews and progress display.
11
+ */
12
+ export interface ToolActivity {
13
+ toolName: string;
14
+ input: Record<string, unknown>;
15
+ /** Pre-computed activity description, e.g. "Reading src/foo.ts" */
16
+ activityDescription?: string;
17
+ /** True if this is a search operation (grep, glob, etc.) */
18
+ isSearch?: boolean;
19
+ /** True if this is a read operation (read_file, cat, etc.) */
20
+ isRead?: boolean;
21
+ }
22
+ /**
23
+ * UI-facing progress snapshot — sent to host via JSON-RPC notifications.
24
+ */
25
+ export interface AgentProgress {
26
+ toolUseCount: number;
27
+ tokenCount: number;
28
+ lastActivity?: ToolActivity;
29
+ recentActivities?: ToolActivity[];
30
+ summary?: string;
31
+ }
32
+ /**
33
+ * Internal mutable state for tracking progress across a query loop.
34
+ *
35
+ * Token tracking note:
36
+ * - input_tokens in the API is cumulative per turn (includes all previous context),
37
+ * so we keep the latest value.
38
+ * - output_tokens is per-turn, so we sum those.
39
+ */
40
+ export interface ProgressTracker {
41
+ toolUseCount: number;
42
+ latestInputTokens: number;
43
+ cumulativeOutputTokens: number;
44
+ recentActivities: ToolActivity[];
45
+ }
46
+ export declare function createProgressTracker(): ProgressTracker;
47
+ export declare function getTokenCountFromTracker(tracker: ProgressTracker): number;
48
+ /**
49
+ * Resolver function that returns a human-readable activity description
50
+ * for a given tool name and input.
51
+ */
52
+ export type ActivityDescriptionResolver = (toolName: string, input: Record<string, unknown>) => string | undefined;
53
+ /**
54
+ * Default activity description resolver — extracts meaningful preview
55
+ * from tool input for UI display.
56
+ */
57
+ export declare function defaultActivityDescription(toolName: string, input: Record<string, unknown>): string | undefined;
58
+ /**
59
+ * Update tracker from an assistant message's usage and tool calls.
60
+ *
61
+ * CC equivalent: updateProgressFromMessage()
62
+ */
63
+ export declare function updateProgressFromUsage(tracker: ProgressTracker, usage: {
64
+ input_tokens?: number;
65
+ output_tokens?: number;
66
+ cache_creation_input_tokens?: number;
67
+ cache_read_input_tokens?: number;
68
+ }): void;
69
+ /**
70
+ * Record a tool use in the tracker.
71
+ */
72
+ export declare function recordToolUse(tracker: ProgressTracker, toolName: string, input: Record<string, unknown>, resolver?: ActivityDescriptionResolver): void;
73
+ /**
74
+ * Get a UI-facing progress snapshot from the tracker.
75
+ *
76
+ * CC equivalent: getProgressUpdate()
77
+ */
78
+ export declare function getProgressUpdate(tracker: ProgressTracker): AgentProgress;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Remote Agent Runtime — cloud sandbox execution via HTTP relay.
3
+ *
4
+ * Enables the local agent to delegate tasks to a cloud-hosted sandbox
5
+ * (e.g., qlogicagent-hub GPU workers, CCR-style isolated environments).
6
+ *
7
+ * Protocol:
8
+ * 1. POST /agents/run → start remote execution, returns sessionId
9
+ * 2. GET /agents/:id → poll for status + streaming results
10
+ * 3. POST /agents/:id/abort → cancel remote execution
11
+ *
12
+ * Reference: CC cloudCode / remoteAgent patterns
13
+ */
14
+ import type { AgentLogger, TokenUsage } from "../../agent/types.js";
15
+ export interface RemoteAgentConfig {
16
+ /** Base URL of the remote execution endpoint (e.g., hub relay). */
17
+ baseUrl: string;
18
+ /** API key for authentication. */
19
+ apiKey: string;
20
+ /** Timeout for HTTP requests in ms (default: 30_000). */
21
+ timeoutMs?: number;
22
+ /** Polling interval in ms (default: 2_000). */
23
+ pollIntervalMs?: number;
24
+ /** Max polling duration in ms (default: 300_000 = 5 min). */
25
+ maxPollDurationMs?: number;
26
+ /** Logger. */
27
+ log: AgentLogger;
28
+ }
29
+ export interface RemoteAgentRequest {
30
+ /** Task prompt for the remote agent. */
31
+ prompt: string;
32
+ /** Model to use on the remote side. */
33
+ model?: string;
34
+ /** Max turns for the remote agent. */
35
+ maxTurns?: number;
36
+ /** Tool restrictions (allowlist). */
37
+ allowedTools?: string[];
38
+ /** Label for tracking. */
39
+ label?: string;
40
+ }
41
+ export interface RemoteAgentResult {
42
+ /** Remote session ID. */
43
+ sessionId: string;
44
+ /** Whether it completed successfully. */
45
+ ok: boolean;
46
+ /** Text output from the remote agent. */
47
+ output?: string;
48
+ /** Error message if failed. */
49
+ error?: string;
50
+ /** Token usage on the remote side. */
51
+ usage?: TokenUsage;
52
+ /** Duration in ms. */
53
+ durationMs: number;
54
+ }
55
+ /**
56
+ * Run a task on a remote agent endpoint.
57
+ *
58
+ * This is a polling-based implementation:
59
+ * 1. POST to start the remote execution
60
+ * 2. Poll GET until completion or timeout
61
+ * 3. Return the aggregated result
62
+ */
63
+ export declare function runRemoteAgent(config: RemoteAgentConfig, request: RemoteAgentRequest, signal?: AbortSignal): Promise<RemoteAgentResult>;
@@ -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;