qlogicagent 0.5.0 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +402 -402
  2. package/dist/agent.js +18 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/contracts.js +1 -0
  5. package/dist/index.js +22 -0
  6. package/dist/orchestration.js +125 -0
  7. package/dist/types/agent/agent.d.ts +43 -0
  8. package/dist/types/agent/constants.d.ts +47 -0
  9. package/dist/types/agent/tool-loop.d.ts +96 -0
  10. package/dist/types/agent/types.d.ts +250 -0
  11. package/dist/types/cli/main.d.ts +11 -0
  12. package/dist/types/cli/stdio-server.d.ts +56 -0
  13. package/dist/types/cli/tool-bootstrap.d.ts +21 -0
  14. package/dist/types/config/config.d.ts +17 -0
  15. package/dist/types/contracts/hooks.d.ts +175 -0
  16. package/dist/types/contracts/index.d.ts +10 -0
  17. package/dist/types/contracts/planner.d.ts +35 -0
  18. package/dist/types/contracts/skill-candidate.d.ts +63 -0
  19. package/dist/types/contracts/todo.d.ts +14 -0
  20. package/dist/types/index.d.ts +13 -0
  21. package/dist/types/llm/builtin-providers.d.ts +10 -0
  22. package/dist/types/llm/debug-transport.d.ts +12 -0
  23. package/dist/types/llm/index.d.ts +16 -0
  24. package/dist/types/llm/llm-client.d.ts +43 -0
  25. package/dist/types/llm/model-catalog.d.ts +53 -0
  26. package/dist/types/llm/provider-def.d.ts +59 -0
  27. package/dist/types/llm/provider-registry.d.ts +54 -0
  28. package/dist/types/llm/transport.d.ts +62 -0
  29. package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
  30. package/dist/types/llm/transports/openai-chat.d.ts +36 -0
  31. package/dist/types/orchestration/agent-registry.d.ts +46 -0
  32. package/dist/types/orchestration/context-collapse.d.ts +58 -0
  33. package/dist/types/orchestration/context-compression.d.ts +301 -0
  34. package/dist/types/orchestration/conversation-repair.d.ts +61 -0
  35. package/dist/types/orchestration/curator-scheduler.d.ts +119 -0
  36. package/dist/types/orchestration/error-classification.d.ts +12 -0
  37. package/dist/types/orchestration/failover-classification.d.ts +8 -0
  38. package/dist/types/orchestration/failover-error.d.ts +33 -0
  39. package/dist/types/orchestration/fork-subagent.d.ts +100 -0
  40. package/dist/types/orchestration/index.d.ts +113 -0
  41. package/dist/types/orchestration/memory-provider.d.ts +14 -0
  42. package/dist/types/orchestration/reactive-compact.d.ts +73 -0
  43. package/dist/types/orchestration/retry-loop.d.ts +69 -0
  44. package/dist/types/orchestration/skill-candidate.d.ts +52 -0
  45. package/dist/types/orchestration/skill-consolidation.d.ts +123 -0
  46. package/dist/types/orchestration/skill-improvement.d.ts +59 -0
  47. package/dist/types/orchestration/skill-similarity.d.ts +98 -0
  48. package/dist/types/orchestration/task-types.d.ts +142 -0
  49. package/dist/types/orchestration/team-orchestration.d.ts +195 -0
  50. package/dist/types/orchestration/team-tool-loop-wiring.d.ts +92 -0
  51. package/dist/types/orchestration/tool-choice-policy.d.ts +54 -0
  52. package/dist/types/orchestration/tool-loop-state.d.ts +50 -0
  53. package/dist/types/orchestration/tool-schema.d.ts +39 -0
  54. package/dist/types/orchestration/turn-loop-guard.d.ts +86 -0
  55. package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
  56. package/dist/types/runtime/execution/forked-agent.d.ts +111 -0
  57. package/dist/types/runtime/execution/index.d.ts +6 -0
  58. package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
  59. package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
  60. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
  61. package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
  62. package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
  63. package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
  64. package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
  65. package/dist/types/runtime/hooks/index.d.ts +3 -0
  66. package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
  67. package/dist/types/runtime/index.d.ts +5 -0
  68. package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
  69. package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
  70. package/dist/types/runtime/infra/index.d.ts +6 -0
  71. package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
  72. package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
  73. package/dist/types/runtime/infra/token-budget.d.ts +92 -0
  74. package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
  75. package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
  76. package/dist/types/runtime/prompt/index.d.ts +3 -0
  77. package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
  78. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
  79. package/dist/types/runtime/session/index.d.ts +2 -0
  80. package/dist/types/runtime/session/session-memory.d.ts +91 -0
  81. package/dist/types/runtime/session/session-persistence.d.ts +94 -0
  82. package/dist/types/runtime/session/session-state.d.ts +117 -0
  83. package/dist/types/skills/index.d.ts +125 -0
  84. package/dist/types/skills/mcp/index.d.ts +3 -0
  85. package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
  86. package/dist/types/skills/mcp/mcp-manager.d.ts +84 -0
  87. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
  88. package/dist/types/skills/memory-extractor.d.ts +64 -0
  89. package/dist/types/skills/memory-query-tool.d.ts +43 -0
  90. package/dist/types/skills/memory-store.d.ts +66 -0
  91. package/dist/types/skills/memory-tool.d.ts +67 -0
  92. package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
  93. package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
  94. package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
  95. package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
  96. package/dist/types/skills/permissions/index.d.ts +12 -0
  97. package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
  98. package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
  99. package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
  100. package/dist/types/skills/permissions/types.d.ts +113 -0
  101. package/dist/types/skills/plugins/index.d.ts +2 -0
  102. package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
  103. package/dist/types/skills/plugins/plugin-loader.d.ts +45 -0
  104. package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
  105. package/dist/types/skills/portable-tool.d.ts +71 -0
  106. package/dist/types/skills/qmemory-adapter.d.ts +42 -0
  107. package/dist/types/skills/skill-frontmatter.d.ts +19 -0
  108. package/dist/types/skills/skill-guard.d.ts +23 -0
  109. package/dist/types/skills/skill-loader.d.ts +16 -0
  110. package/dist/types/skills/skill-source.d.ts +119 -0
  111. package/dist/types/skills/skill-types.d.ts +199 -0
  112. package/dist/types/skills/think-tool.d.ts +16 -0
  113. package/dist/types/skills/todo-tool.d.ts +63 -0
  114. package/dist/types/skills/tool-registry.d.ts +29 -0
  115. package/dist/types/skills/tools/agent-tool.d.ts +91 -0
  116. package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
  117. package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
  118. package/dist/types/skills/tools/brief-tool.d.ts +74 -0
  119. package/dist/types/skills/tools/browser-tool.d.ts +114 -0
  120. package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
  121. package/dist/types/skills/tools/config-tool.d.ts +63 -0
  122. package/dist/types/skills/tools/cron-tool.d.ts +116 -0
  123. package/dist/types/skills/tools/edit-tool.d.ts +43 -0
  124. package/dist/types/skills/tools/exec-tool.d.ts +97 -0
  125. package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
  126. package/dist/types/skills/tools/instructions-tool.d.ts +103 -0
  127. package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
  128. package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
  129. package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
  130. package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
  131. package/dist/types/skills/tools/memory-tool.d.ts +74 -0
  132. package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
  133. package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
  134. package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
  135. package/dist/types/skills/tools/notify-tool.d.ts +53 -0
  136. package/dist/types/skills/tools/patch-tool.d.ts +45 -0
  137. package/dist/types/skills/tools/pdf-tool.d.ts +66 -0
  138. package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
  139. package/dist/types/skills/tools/read-tool.d.ts +51 -0
  140. package/dist/types/skills/tools/repl-tool.d.ts +70 -0
  141. package/dist/types/skills/tools/search-tool.d.ts +112 -0
  142. package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
  143. package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
  144. package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
  145. package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
  146. package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
  147. package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
  148. package/dist/types/skills/tools/shell/index.d.ts +17 -0
  149. package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
  150. package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
  151. package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
  152. package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
  153. package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
  154. package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
  155. package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
  156. package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
  157. package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
  158. package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
  159. package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
  160. package/dist/types/skills/tools/task-tool.d.ts +104 -0
  161. package/dist/types/skills/tools/team-tool.d.ts +89 -0
  162. package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
  163. package/dist/types/skills/tools/tts-tool.d.ts +38 -0
  164. package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
  165. package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
  166. package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
  167. package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
  168. package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
  169. package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
  170. package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
  171. package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
  172. package/dist/types/skills/tools/write-tool.d.ts +45 -0
  173. package/package.json +4 -2
@@ -0,0 +1,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/context-compression.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,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,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
+ * - .openclaw/settings.json → permission hot-reload
14
+ * - INSTRUCTIONS.md / .openclaw/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,6 @@
1
+ export { getBudgetContinuationMessage } from "./token-budget.js";
2
+ export { type SecureStorage, saveApiKey, loadApiKey } from "./secure-storage.js";
3
+ export { createFileWatcher, FileWatcher } from "./file-watcher.js";
4
+ export { TaskStore } from "./task-runtime.js";
5
+ export { createWorktreeBackend } from "./worktree-backend.js";
6
+ export { registerCleanup, runCleanupFunctions } from "./cleanup-registry.js";
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Secure Storage — CC secureStorage parity.
3
+ *
4
+ * Platform-aware credential persistence abstraction:
5
+ * - Interface: get/set/delete with typed data
6
+ * - Implementation: file-based JSON with 0o600 permissions (CC plainTextStorage parity)
7
+ * - macOS Keychain / Windows Credential Manager can be added as plugins
8
+ *
9
+ * Storage layout:
10
+ * ~/.openclaw/.credentials.json — API keys, OAuth tokens
11
+ *
12
+ * Reference: claude-code-haha/src/utils/secureStorage/
13
+ */
14
+ export interface SecureStorageData {
15
+ /** Primary API key (user-set) */
16
+ apiKey?: string;
17
+ /** OAuth tokens (if using OAuth flow) */
18
+ oauth?: {
19
+ accessToken: string;
20
+ refreshToken: string;
21
+ expiresAt: number;
22
+ };
23
+ /** Arbitrary key-value pairs for extensibility */
24
+ [key: string]: unknown;
25
+ }
26
+ /**
27
+ * CC SecureStorage interface parity.
28
+ *
29
+ * Implementations may use OS keychain, encrypted file, or plain-text file.
30
+ * Callers should not assume any specific storage backend.
31
+ */
32
+ export interface SecureStorage {
33
+ readonly name: string;
34
+ get(): Promise<SecureStorageData | null>;
35
+ set(data: SecureStorageData): Promise<{
36
+ success: boolean;
37
+ warning?: string;
38
+ }>;
39
+ delete(): Promise<boolean>;
40
+ }
41
+ /**
42
+ * File-based secure storage with restrictive permissions.
43
+ *
44
+ * On Unix: file created with 0o600 (owner-only read/write).
45
+ * On Windows: ACLs are not set (relies on user profile permissions).
46
+ *
47
+ * This matches CC's plainTextStorage.ts behavior — it's the default
48
+ * on Linux/Windows, and the fallback on macOS.
49
+ */
50
+ export declare class FileSecureStorage implements SecureStorage {
51
+ readonly name = "file";
52
+ get(): Promise<SecureStorageData | null>;
53
+ set(data: SecureStorageData): Promise<{
54
+ success: boolean;
55
+ warning?: string;
56
+ }>;
57
+ delete(): Promise<boolean>;
58
+ }
59
+ /**
60
+ * Get the platform-appropriate secure storage instance.
61
+ *
62
+ * Currently returns FileSecureStorage on all platforms.
63
+ * macOS Keychain integration can be added by checking platform
64
+ * and returning a KeychainSecureStorage wrapper.
65
+ */
66
+ export declare function getSecureStorage(): SecureStorage;
67
+ /**
68
+ * Save an API key to secure storage.
69
+ */
70
+ export declare function saveApiKey(apiKey: string): Promise<{
71
+ success: boolean;
72
+ warning?: string;
73
+ }>;
74
+ /**
75
+ * Load the stored API key (returns null if none saved).
76
+ */
77
+ export declare function loadApiKey(): Promise<string | null>;
78
+ /**
79
+ * Delete the stored API key.
80
+ */
81
+ export declare function deleteApiKey(): Promise<boolean>;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Task Runtime — CC framework.ts parity.
3
+ *
4
+ * Manages task lifecycle: creation, state updates, completion, cleanup.
5
+ * All task types (local_bash, local_agent, dream, etc.) use this framework.
6
+ *
7
+ * CC equivalent: src/utils/task/framework.ts + src/Task.ts
8
+ *
9
+ * Architecture note: CC uses React-style setAppState(prev => next). We use
10
+ * a simple Map-based store since we're in a subprocess (no React).
11
+ */
12
+ import type { TaskState, TaskType, TaskLifecycle, PermissionRole, IsolationMode, LocalAgentTaskState, LocalBashTaskState } from "../../orchestration/task-types.js";
13
+ import type { HookRegistry } from "../../contracts/hooks.js";
14
+ /** Polling interval for running tasks (ms) */
15
+ export declare const POLL_INTERVAL_MS = 1000;
16
+ /** Display duration for killed tasks before eviction (ms) */
17
+ export declare const STOPPED_DISPLAY_MS = 3000;
18
+ /** Grace period for terminal tasks before eviction (ms) */
19
+ export declare const PANEL_GRACE_MS = 30000;
20
+ export declare function generateTaskId(type: TaskType): string;
21
+ /**
22
+ * In-memory task store — replaces CC's AppState.tasks.
23
+ *
24
+ * Thread-safe for single-process use. All mutations go through
25
+ * updateTaskState / registerTask for consistency.
26
+ */
27
+ export declare class TaskStore {
28
+ private tasks;
29
+ private listeners;
30
+ private hooks;
31
+ private sessionId;
32
+ /** Attach a hook registry to fire task.created / task.completed hooks. */
33
+ setHooks(hooks: HookRegistry, sessionId: string): void;
34
+ /**
35
+ * Register a listener for task state changes.
36
+ * @returns Unregister function
37
+ */
38
+ onTaskChange(listener: (taskId: string, task: TaskState | null) => void): () => void;
39
+ private notify;
40
+ /**
41
+ * Register a new task.
42
+ */
43
+ registerTask(task: TaskState): void;
44
+ /**
45
+ * Update a task's state via an updater function.
46
+ * CC equivalent: updateTaskState()
47
+ */
48
+ updateTask<T extends TaskState>(taskId: string, updater: (task: T) => T): void;
49
+ /**
50
+ * Get a task by ID.
51
+ */
52
+ getTask(taskId: string): TaskState | undefined;
53
+ /**
54
+ * Get all running tasks.
55
+ */
56
+ getRunningTasks(): TaskState[];
57
+ /**
58
+ * Get all tasks.
59
+ */
60
+ getAllTasks(): TaskState[];
61
+ /**
62
+ * Evict a terminal task from the store.
63
+ */
64
+ evictTask(taskId: string): void;
65
+ /**
66
+ * Evict all terminal tasks that have passed their grace period.
67
+ */
68
+ evictStaleTasks(graceMs?: number): void;
69
+ }
70
+ export declare function isTerminalLifecycle(lifecycle: TaskLifecycle): boolean;
71
+ /**
72
+ * Transition a task to a terminal state.
73
+ */
74
+ export declare function completeTask(store: TaskStore, taskId: string): void;
75
+ export declare function failTask(store: TaskStore, taskId: string, error?: string): void;
76
+ export declare function cancelTask(store: TaskStore, taskId: string): void;
77
+ /**
78
+ * Create and register a local agent task.
79
+ */
80
+ export declare function createLocalAgentTask(store: TaskStore, opts: {
81
+ agentName: string;
82
+ systemPrompt: string;
83
+ allowedTools?: string[];
84
+ parentTaskId?: string;
85
+ tokenBudget?: number;
86
+ maxTurns?: number;
87
+ permissionRole?: PermissionRole;
88
+ isolation?: IsolationMode;
89
+ worktreeBranch?: string;
90
+ }): LocalAgentTaskState;
91
+ /**
92
+ * Create and register a local bash task.
93
+ */
94
+ export declare function createLocalBashTask(store: TaskStore, opts: {
95
+ command: string;
96
+ cwd: string;
97
+ parentTaskId?: string;
98
+ label?: string;
99
+ }): LocalBashTaskState;
100
+ /**
101
+ * Build a task notification message in CC's XML format.
102
+ * This is injected into the conversation as context for the model.
103
+ */
104
+ export declare function buildTaskNotification(task: TaskState, summary: string): string;
105
+ /**
106
+ * Get the global task store singleton.
107
+ */
108
+ export declare function getTaskStore(): TaskStore;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Sub-agent Token Budget Enforcer — CC-aligned budget limits.
3
+ *
4
+ * Prevents sub-agents from consuming infinite tokens by:
5
+ * 1. Per-task token budget (from TaskStateBase.tokenBudget)
6
+ * 2. Session-level aggregate budget (all tasks combined)
7
+ * 3. Budget continuation messages (CC tokenBudget.ts pattern)
8
+ * 4. Graceful degradation (warn → force-stop, never hard-crash)
9
+ *
10
+ * CC reference: utils/tokenBudget.ts, main.tsx --max-budget-usd / --task-budget
11
+ *
12
+ * Key difference from CC: We track prompt + completion tokens (not USD).
13
+ * CC has no explicit per-sub-agent budget; they rely on session-level maxBudgetUsd.
14
+ * We add per-task enforcement to prevent a single sub-agent from exhausting the budget.
15
+ */
16
+ import type { TokenUsage } from "../../agent/types.js";
17
+ export interface BudgetConfig {
18
+ /** Per-task token budget (prompt + completion). 0 = unlimited. */
19
+ taskBudgetTokens: number;
20
+ /** Session-level token budget across all tasks. 0 = unlimited. */
21
+ sessionBudgetTokens: number;
22
+ /** Warning threshold as percentage (0-100). Default: 80. */
23
+ warningThresholdPct: number;
24
+ }
25
+ export interface TaskBudgetState {
26
+ taskId: string;
27
+ /** Token budget for this task. 0 = unlimited. */
28
+ budgetTokens: number;
29
+ /** Accumulated token usage for this task. */
30
+ usage: TokenUsage;
31
+ /** Whether a warning has been issued for this task. */
32
+ warned: boolean;
33
+ /** Whether this task has been force-stopped due to budget. */
34
+ stopped: boolean;
35
+ }
36
+ export interface SessionBudgetState {
37
+ /** Session-level budget. 0 = unlimited. */
38
+ budgetTokens: number;
39
+ /** Aggregate usage across ALL tasks in this session. */
40
+ totalUsage: TokenUsage;
41
+ /** Per-task states keyed by taskId. */
42
+ tasks: Map<string, TaskBudgetState>;
43
+ }
44
+ export type BudgetCheckResult = {
45
+ status: "ok";
46
+ } | {
47
+ status: "warning";
48
+ message: string;
49
+ usagePct: number;
50
+ } | {
51
+ status: "exceeded";
52
+ message: string;
53
+ usagePct: number;
54
+ };
55
+ /**
56
+ * Parse a token budget from user text input.
57
+ * CC reference: parseTokenBudget()
58
+ *
59
+ * Supports:
60
+ * - Shorthand start: "+500k", "+1.5m"
61
+ * - Shorthand end: "keep working +1m."
62
+ * - Verbose: "use 500k tokens", "spend 1.5M tokens"
63
+ */
64
+ export declare function parseTokenBudget(text: string): number | null;
65
+ /**
66
+ * Generate a budget continuation message (CC getBudgetContinuationMessage pattern).
67
+ * Appended to the assistant context when approaching budget limits.
68
+ */
69
+ export declare function getBudgetContinuationMessage(usagePct: number, currentTokens: number, budgetTokens: number): string;
70
+ export declare function createSessionBudgetState(config?: Partial<BudgetConfig>): SessionBudgetState;
71
+ export declare function registerTaskBudget(session: SessionBudgetState, taskId: string, budgetTokens: number): TaskBudgetState;
72
+ /**
73
+ * Record token usage for a task and aggregate into session.
74
+ */
75
+ export declare function recordTaskUsage(session: SessionBudgetState, taskId: string, usage: TokenUsage): void;
76
+ /**
77
+ * Check whether a task is within its token budget.
78
+ */
79
+ export declare function checkTaskBudget(session: SessionBudgetState, taskId: string, config?: Partial<BudgetConfig>): BudgetCheckResult;
80
+ /**
81
+ * Get a summary of all task budgets in a session.
82
+ */
83
+ export declare function getSessionBudgetSummary(session: SessionBudgetState): {
84
+ sessionUsed: number;
85
+ sessionBudget: number;
86
+ tasks: Array<{
87
+ taskId: string;
88
+ used: number;
89
+ budget: number;
90
+ stopped: boolean;
91
+ }>;
92
+ };