@compilr-dev/cli 0.5.17 → 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.
- package/dist/.tsbuildinfo.app +1 -1
- package/dist/agent.d.ts +39 -111
- package/dist/agent.js +173 -390
- package/dist/compilr-diff-companion.vsix +0 -0
- package/package.json +2 -2
package/dist/agent.js
CHANGED
|
@@ -1,45 +1,55 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Agent Configuration
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* and
|
|
4
|
+
* Thin wrapper around createCompilrAgent() from @compilr-dev/sdk.
|
|
5
|
+
* Handles CLI-specific concerns: credential resolution, system prompt
|
|
6
|
+
* assembly, subagent callbacks, and token estimates.
|
|
7
7
|
*/
|
|
8
8
|
import { log } from './foundation/logger.js';
|
|
9
|
-
import {
|
|
9
|
+
import { createCompilrAgent, createTaskTool, defaultAgentTypes, TOOL_SETS, BUILTIN_GUARDRAILS, } from '@compilr-dev/sdk';
|
|
10
10
|
import { isAutoCompactEnabled, isDelegationEnabled, getSetting } from './settings/index.js';
|
|
11
11
|
import { getApiKey } from './utils/credentials.js';
|
|
12
|
-
import { createToolRegistry, createMinimalToolRegistry, getDirectTools, getMetaTools, initializeMetaTools, getToolIndexForSystemPrompt, getFilteredToolIndexForSystemPrompt, getToolStats, setMetaToolFilter, createToolFallback, getRegisteredMetaTools, } from './tools.js';
|
|
13
|
-
// TOOL_GROUPS no longer needed — profile resolution moved to SDK
|
|
14
|
-
import { setCapabilityManager } from './multi-agent/capability-loader.js';
|
|
15
12
|
import { getAgentRegistry } from './agents/registry.js';
|
|
16
13
|
import { SystemPromptBuilder } from './system-prompt/index.js';
|
|
17
|
-
import { getDefaultModelForTier
|
|
14
|
+
import { getDefaultModelForTier } from './models/index.js';
|
|
18
15
|
import { PROVIDER_METADATA } from './models/providers.js';
|
|
19
16
|
import { setStaticEstimates, estimateTokens, estimateJsonTokens, } from './utils/token-tracker.js';
|
|
20
17
|
import { createFileLockCheckHook, createFileLockAcquireHook } from './multi-agent/file-lock-hook.js';
|
|
21
18
|
import { getActiveProject } from './tools/project-db.js';
|
|
19
|
+
import { allDbTools, allFactoryTools } from './tools/db-tools.js';
|
|
22
20
|
/**
|
|
23
21
|
* Default permission rules for potentially dangerous operations
|
|
24
|
-
* Note: Tool names are lowercase (bash, write_file, edit, git_commit)
|
|
25
22
|
*/
|
|
26
23
|
const DEFAULT_PERMISSION_RULES = [
|
|
27
|
-
// File writes need approval each time (user can see diff before approving)
|
|
28
24
|
{ toolName: 'write_file', level: 'once', description: 'Write/create files' },
|
|
29
25
|
{ toolName: 'edit', level: 'once', description: 'Edit file contents' },
|
|
30
|
-
// Git operations that modify state
|
|
31
26
|
{ toolName: 'git_commit', level: 'once', description: 'Create git commit' },
|
|
32
27
|
{ toolName: 'git_branch', level: 'once', description: 'Create/delete git branches' },
|
|
33
|
-
// Shell commands need approval each time
|
|
34
28
|
{ toolName: 'bash', level: 'once', description: 'Execute shell command' },
|
|
35
|
-
// Project runners (can have side effects)
|
|
36
29
|
{ toolName: 'run_tests', level: 'once', description: 'Run test suite' },
|
|
37
30
|
{ toolName: 'run_lint', level: 'once', description: 'Run linter (may auto-fix)' },
|
|
38
|
-
// Note: backlog_write removed - use workitem_* tools which modify database
|
|
39
31
|
];
|
|
32
|
+
/** Delegation config for tool result auto-summarization */
|
|
33
|
+
const CLI_DELEGATION_CONFIG = {
|
|
34
|
+
enabled: true,
|
|
35
|
+
delegationThreshold: 8000,
|
|
36
|
+
summaryMaxTokens: 800,
|
|
37
|
+
resultTTL: 600_000,
|
|
38
|
+
maxStoredResults: 50,
|
|
39
|
+
strategy: 'auto',
|
|
40
|
+
toolOverrides: {
|
|
41
|
+
bash: { threshold: 12000 },
|
|
42
|
+
grep: { threshold: 4000 },
|
|
43
|
+
git_diff: { threshold: 6000 },
|
|
44
|
+
get_tool_info: { enabled: false },
|
|
45
|
+
list_tools: { enabled: false },
|
|
46
|
+
ask_user: { enabled: false },
|
|
47
|
+
ask_user_simple: { enabled: false },
|
|
48
|
+
todo_read: { enabled: false },
|
|
49
|
+
},
|
|
50
|
+
};
|
|
40
51
|
/**
|
|
41
52
|
* Get permission info for a tool by name.
|
|
42
|
-
* Returns undefined if the tool doesn't require special permission (always allowed).
|
|
43
53
|
*/
|
|
44
54
|
export function getToolPermissionInfo(toolName) {
|
|
45
55
|
const rule = DEFAULT_PERMISSION_RULES.find(r => r.toolName === toolName);
|
|
@@ -53,7 +63,6 @@ export function getToolPermissionInfo(toolName) {
|
|
|
53
63
|
}
|
|
54
64
|
/**
|
|
55
65
|
* Get information about built-in guardrails.
|
|
56
|
-
* Used for displaying guardrail info in /help or status overlays.
|
|
57
66
|
*/
|
|
58
67
|
export function getBuiltinGuardrailInfo() {
|
|
59
68
|
return BUILTIN_GUARDRAILS.map((g) => ({
|
|
@@ -66,21 +75,16 @@ export function getBuiltinGuardrailInfo() {
|
|
|
66
75
|
}
|
|
67
76
|
/**
|
|
68
77
|
* Merges built-in agent types with custom agents from registry.
|
|
69
|
-
* Custom agents get safe read-only tools by default.
|
|
70
78
|
*/
|
|
71
79
|
function getMergedAgentTypes() {
|
|
72
80
|
const registry = getAgentRegistry();
|
|
73
81
|
const customAgents = registry.getCustomAgents();
|
|
74
|
-
// Start with default agent types (library now has correct tool names)
|
|
75
82
|
const mergedTypes = { ...defaultAgentTypes };
|
|
76
|
-
// Add custom agents from registry
|
|
77
83
|
for (const agent of customAgents) {
|
|
78
84
|
mergedTypes[agent.name] = {
|
|
79
85
|
description: agent.description,
|
|
80
86
|
systemPrompt: agent.systemPrompt,
|
|
81
87
|
defaultModel: agent.model === 'inherit' ? undefined : agent.model,
|
|
82
|
-
// Safe read-only tools for custom agents (using library's TOOL_SETS)
|
|
83
|
-
// Type assertion needed because TOOL_SETS typing might not be exported correctly
|
|
84
88
|
allowedTools: Array.isArray(TOOL_SETS.READ_ONLY) ? [...(TOOL_SETS.READ_ONLY)] : [],
|
|
85
89
|
maxIterations: 10,
|
|
86
90
|
contextMode: 'inherit-summary',
|
|
@@ -88,189 +92,52 @@ function getMergedAgentTypes() {
|
|
|
88
92
|
}
|
|
89
93
|
return mergedTypes;
|
|
90
94
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
* Resolves CLI-specific concerns (credentials, settings) then delegates
|
|
94
|
-
* provider instantiation to the SDK's createProviderFromType().
|
|
95
|
-
*/
|
|
96
|
-
function createProvider(options) {
|
|
95
|
+
// ─── Provider Resolution (CLI-specific credentials) ─────────────────────────
|
|
96
|
+
function resolveProviderConfig(options) {
|
|
97
97
|
const providerType = options.provider ?? 'claude';
|
|
98
|
-
const quiet = options.quiet ?? false;
|
|
99
98
|
const meta = PROVIDER_METADATA[providerType];
|
|
100
|
-
// 1. Resolve API key from CLI credential store
|
|
101
99
|
const apiKey = meta.requiresKey ? getApiKey(meta.credentialKey) : undefined;
|
|
102
100
|
if (!apiKey && meta.requiresKey) {
|
|
103
101
|
throw new Error(`${meta.displayName} API key not found.\n` +
|
|
104
102
|
`Run /keys to set it, or: export ${meta.envVar}=...` +
|
|
105
103
|
(providerType === 'claude' ? '\nOr use --provider ollama for local models.' : ''));
|
|
106
104
|
}
|
|
107
|
-
// 2. Resolve model (from options or registry default for balanced tier)
|
|
108
105
|
const model = options.model ?? getDefaultModelForTier(providerType, 'balanced')?.id;
|
|
109
|
-
// 3. Resolve Ollama base URL from settings
|
|
110
106
|
const baseUrl = providerType === 'ollama'
|
|
111
107
|
? ((typeof getSetting('ollamaBaseUrl') === 'string'
|
|
112
108
|
? getSetting('ollamaBaseUrl')
|
|
113
|
-
: undefined) ??
|
|
114
|
-
process.env.OLLAMA_BASE_URL ??
|
|
115
|
-
'http://localhost:11434')
|
|
109
|
+
: undefined) ?? process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434')
|
|
116
110
|
: undefined;
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
console.log(` Ollama server: ${baseUrl ?? ''}`);
|
|
122
|
-
}
|
|
123
|
-
// 5. Delegate to SDK (with tiktoken-based token estimator for debug payload)
|
|
124
|
-
return createProviderFromType(providerType, {
|
|
125
|
-
model,
|
|
126
|
-
apiKey: apiKey ?? undefined,
|
|
127
|
-
baseUrl,
|
|
128
|
-
siteName: providerType === 'openrouter' ? 'compilr-cli' : undefined,
|
|
129
|
-
estimateTokens,
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
// =============================================================================
|
|
133
|
-
// Dynamic Capability Loading Helpers
|
|
134
|
-
// =============================================================================
|
|
135
|
-
/**
|
|
136
|
-
* Derive profile group IDs from a tool filter (array of tool names).
|
|
137
|
-
* A group is included if any of its tools are in the filter.
|
|
138
|
-
*/
|
|
139
|
-
// getProfileGroupsFromToolFilter → replaced by resolveProfileGroups from SDK
|
|
140
|
-
// autoDetectCapabilities → replaced by autoDetectCapabilities from SDK
|
|
141
|
-
// createCapabilityHook → replaced by createCapabilityHook + CapabilityContext from SDK
|
|
142
|
-
/**
|
|
143
|
-
* Creates an Agent instance configured with all tools.
|
|
144
|
-
*/
|
|
145
|
-
export function createAgent(options = {}) {
|
|
146
|
-
const provider = createProvider(options);
|
|
147
|
-
// Create context manager with model-specific limits
|
|
148
|
-
// Uses library defaults: compact at 50%, summarize at 90%, emergency at 95%
|
|
149
|
-
// Auto-compact can be disabled via settings (requires restart)
|
|
150
|
-
const autoCompact = isAutoCompactEnabled();
|
|
151
|
-
const contextManager = new ContextManager({
|
|
152
|
-
provider,
|
|
153
|
-
config: {
|
|
154
|
-
maxContextTokens: getModelContextWindow(options.model ?? '', options.provider),
|
|
155
|
-
// If auto-compact disabled, set threshold to 100% (never triggers)
|
|
156
|
-
compaction: autoCompact
|
|
157
|
-
? DEFAULT_CONTEXT_CONFIG.compaction
|
|
158
|
-
: {
|
|
159
|
-
...DEFAULT_CONTEXT_CONFIG.compaction,
|
|
160
|
-
triggerThreshold: 1.0, // Never auto-trigger
|
|
161
|
-
triggerInterval: Number.MAX_SAFE_INTEGER, // Never interval-trigger
|
|
162
|
-
},
|
|
163
|
-
},
|
|
164
|
-
});
|
|
165
|
-
// Create event handler for verbose mode
|
|
166
|
-
const onEvent = options.verbose
|
|
167
|
-
? (event) => {
|
|
168
|
-
if (event.type === 'tool_start') {
|
|
169
|
-
log.debug({ component: 'agent', tool: event.name }, 'Tool starting');
|
|
170
|
-
}
|
|
171
|
-
else if (event.type === 'tool_end') {
|
|
172
|
-
log.debug({ component: 'agent', tool: event.name }, 'Tool done');
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
: undefined;
|
|
176
|
-
// Build modular system prompt based on current context
|
|
177
|
-
// Note: Anchors are NOT added here - they're handled by library's AnchorManager
|
|
178
|
-
// which re-injects them on every LLM call (survives compaction)
|
|
179
|
-
// Initialize meta-tools if enabled (needed for tool index)
|
|
180
|
-
// includeWarmTools=true moves 11 warm tools into meta-registry (hot-tools mode)
|
|
181
|
-
const useMetaTools = options.enableMetaTools && !options.minimal;
|
|
182
|
-
if (useMetaTools) {
|
|
183
|
-
initializeMetaTools(true);
|
|
184
|
-
}
|
|
185
|
-
// ==========================================================================
|
|
186
|
-
// Dynamic Capability Loading
|
|
187
|
-
// When meta-tools are enabled, create a CapabilityManager to control which
|
|
188
|
-
// tools and prompt modules are active per-turn.
|
|
189
|
-
// ==========================================================================
|
|
190
|
-
let capabilityManager;
|
|
191
|
-
let capabilityContext;
|
|
192
|
-
let orphanToolNames = [];
|
|
193
|
-
if (useMetaTools) {
|
|
194
|
-
// Use SDK's profile resolver instead of local implementation
|
|
195
|
-
const profileGroups = options.toolFilter
|
|
196
|
-
? resolveProfileGroups(options.toolFilter)
|
|
197
|
-
: Object.keys(CAPABILITY_PACKS);
|
|
198
|
-
const upfrontGroupIds = resolveUpfrontGroups(profileGroups);
|
|
199
|
-
capabilityManager = new CapabilityManager({
|
|
200
|
-
profileGroups,
|
|
201
|
-
packs: CAPABILITY_PACKS,
|
|
202
|
-
upfrontGroups: upfrontGroupIds,
|
|
203
|
-
});
|
|
204
|
-
// Expose the capability manager for slash command handlers (Phase 3)
|
|
205
|
-
setCapabilityManager(capabilityManager);
|
|
206
|
-
// Compute orphan tools (meta-registry tools not in any capability pack)
|
|
207
|
-
const packedTools = new Set();
|
|
208
|
-
for (const pack of Object.values(CAPABILITY_PACKS)) {
|
|
209
|
-
for (const tool of pack.tools) {
|
|
210
|
-
packedTools.add(tool);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
const registered = getRegisteredMetaTools();
|
|
214
|
-
orphanToolNames = registered
|
|
215
|
-
.map((t) => t.definition.name)
|
|
216
|
-
.filter((name) => !packedTools.has(name));
|
|
217
|
-
// Create capability context (SDK) for filter sync + auto-load callback
|
|
218
|
-
capabilityContext = new CapabilityContext({
|
|
219
|
-
manager: capabilityManager,
|
|
220
|
-
orphanTools: orphanToolNames,
|
|
221
|
-
onFilterUpdate: (allowed) => { setMetaToolFilter(allowed); },
|
|
222
|
-
});
|
|
223
|
-
capabilityContext.syncFilter();
|
|
224
|
-
// Log stats (unless quiet mode)
|
|
225
|
-
if (!options.quiet) {
|
|
226
|
-
const stats = getToolStats();
|
|
227
|
-
const loadedPacks = capabilityManager.getLoadedPackIds();
|
|
228
|
-
const loadableCount = capabilityManager.getCatalog().length;
|
|
229
|
-
console.log(`[Meta-tools] Direct: ${String(stats.directTools)}, ` +
|
|
230
|
-
`Meta: ${String(stats.metaRegistryTools)}, ` +
|
|
231
|
-
`Est. savings: ~${String(stats.tokenSavings)} tokens`);
|
|
232
|
-
console.log(`[Capabilities] Upfront: ${String(loadedPacks.length)} packs, ` +
|
|
233
|
-
`Loadable: ${String(loadableCount)} packs`);
|
|
111
|
+
if (!options.quiet) {
|
|
112
|
+
log.info({ component: 'agent', provider: meta.displayName, model: model ?? 'default' }, 'Provider configured');
|
|
113
|
+
if (providerType === 'ollama' && baseUrl !== 'http://localhost:11434') {
|
|
114
|
+
log.info({ component: 'agent', baseUrl }, 'Ollama server');
|
|
234
115
|
}
|
|
235
116
|
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
let systemPrompt;
|
|
241
|
-
// Check if we should use minimal system prompt (for testing role identity)
|
|
117
|
+
return { provider: providerType, model, apiKey: apiKey ?? undefined, baseUrl };
|
|
118
|
+
}
|
|
119
|
+
// ─── System Prompt Assembly ─────────────────────────────────────────────────
|
|
120
|
+
function buildSystemPrompt(options) {
|
|
242
121
|
if (options.useMinimalSystemPrompt && options.systemPromptAddition) {
|
|
243
|
-
|
|
244
|
-
systemPrompt = options.systemPromptAddition;
|
|
122
|
+
return options.systemPromptAddition;
|
|
245
123
|
}
|
|
246
|
-
|
|
247
|
-
//
|
|
248
|
-
//
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const buildResult = promptBuilder.build();
|
|
264
|
-
systemPrompt = buildResult.prompt;
|
|
265
|
-
// Prepend role-specific system prompt (for team agents)
|
|
266
|
-
// The default identity module is already excluded via hasRoleIdentity flag
|
|
267
|
-
if (options.systemPromptAddition) {
|
|
268
|
-
// Extract role name from the role prompt (format: "# ROLE: ROLE_NAME")
|
|
269
|
-
const roleMatch = options.systemPromptAddition.match(/^#\s*ROLE:\s*(.+)$/m);
|
|
270
|
-
const roleName = roleMatch ? roleMatch[1].trim() : 'specialized team member';
|
|
271
|
-
// Put FULL role prompt at the END (recency effect is stronger than primacy)
|
|
272
|
-
// LLMs weight the end of context more heavily
|
|
273
|
-
const roleEnding = `
|
|
124
|
+
const promptBuilder = new SystemPromptBuilder({
|
|
125
|
+
enableMetaTools: false, // SDK handles capability-based prompt assembly
|
|
126
|
+
hasGit: undefined, // Auto-detect (SDK capability hook will override if needed)
|
|
127
|
+
projectName: options.projectName,
|
|
128
|
+
projectSlug: options.projectSlug,
|
|
129
|
+
projectId: options.projectId,
|
|
130
|
+
projectContext: options.projectContext,
|
|
131
|
+
guidedModeContext: options.guidedModeContext,
|
|
132
|
+
planModeContext: options.planModeContext,
|
|
133
|
+
hasRoleIdentity: !!options.systemPromptAddition,
|
|
134
|
+
});
|
|
135
|
+
let systemPrompt = promptBuilder.build().prompt;
|
|
136
|
+
// Wrap role identity at beginning AND end for team agents
|
|
137
|
+
if (options.systemPromptAddition) {
|
|
138
|
+
const roleMatch = options.systemPromptAddition.match(/^#\s*ROLE:\s*(.+)$/m);
|
|
139
|
+
const roleName = roleMatch ? roleMatch[1].trim() : 'specialized team member';
|
|
140
|
+
const roleEnding = `
|
|
274
141
|
|
|
275
142
|
---
|
|
276
143
|
|
|
@@ -279,113 +146,118 @@ export function createAgent(options = {}) {
|
|
|
279
146
|
${options.systemPromptAddition}
|
|
280
147
|
|
|
281
148
|
**CRITICAL**: When asked "what is your role?", "what are you?", or similar identity questions, your response should acknowledge your assigned role. For example: "In this team, I'm the ${roleName}" or "I'm operating as the ${roleName} in this session."`;
|
|
282
|
-
|
|
283
|
-
systemPrompt = options.systemPromptAddition + '\n\n' + systemPrompt + roleEnding;
|
|
284
|
-
}
|
|
149
|
+
systemPrompt = options.systemPromptAddition + '\n\n' + systemPrompt + roleEnding;
|
|
285
150
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
151
|
+
return systemPrompt;
|
|
152
|
+
}
|
|
153
|
+
// ─── Context Pressure Hook ──────────────────────────────────────────────────
|
|
154
|
+
function createContextPressureHook() {
|
|
155
|
+
return (ctx) => {
|
|
156
|
+
const msgCount = ctx.messages.length;
|
|
157
|
+
if (msgCount < 20)
|
|
158
|
+
return undefined;
|
|
159
|
+
let hint;
|
|
160
|
+
if (msgCount < 40) {
|
|
161
|
+
hint = `[Context: ~${String(msgCount)} messages] Consider task() for multi-file operations.`;
|
|
162
|
+
}
|
|
163
|
+
else if (msgCount < 60) {
|
|
164
|
+
hint = `[Context: ~${String(msgCount)} messages - HIGH] Prefer task() sub-agents for file reads and code search.`;
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
hint = `[Context: ~${String(msgCount)} messages - CRITICAL] Use task() for ALL exploration. Do not read files directly.`;
|
|
168
|
+
}
|
|
169
|
+
const messages = [...ctx.messages];
|
|
170
|
+
messages.splice(1, 0, { role: 'user', content: hint });
|
|
171
|
+
return { messages };
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
// ─── Main Factory ───────────────────────────────────────────────────────────
|
|
175
|
+
/**
|
|
176
|
+
* Creates an Agent instance configured with all tools.
|
|
177
|
+
*
|
|
178
|
+
* Delegates to createCompilrAgent() from @compilr-dev/sdk for:
|
|
179
|
+
* - Provider creation, context management, observation masking
|
|
180
|
+
* - Smart windowing, tool output guards
|
|
181
|
+
* - Capability loading (meta-tools, dynamic prompt assembly)
|
|
182
|
+
* - Permission handling, guardrails, delegation
|
|
183
|
+
*
|
|
184
|
+
* CLI adds on top:
|
|
185
|
+
* - Credential resolution from CLI keystore
|
|
186
|
+
* - System prompt with project context and role identity
|
|
187
|
+
* - Subagent callbacks for UI updates
|
|
188
|
+
* - Token estimate logging
|
|
189
|
+
*/
|
|
190
|
+
export function createAgent(options = {}) {
|
|
191
|
+
const { provider, model, apiKey } = resolveProviderConfig(options);
|
|
192
|
+
const systemPrompt = buildSystemPrompt(options);
|
|
193
|
+
// ── Create agent via SDK ──────────────────────────────────────────────────
|
|
194
|
+
const compilrAgent = createCompilrAgent({
|
|
289
195
|
provider,
|
|
196
|
+
model,
|
|
197
|
+
apiKey,
|
|
290
198
|
systemPrompt,
|
|
291
199
|
maxIterations: options.maxIterations ?? 50,
|
|
292
|
-
onEvent,
|
|
293
|
-
contextManager,
|
|
294
|
-
// Set tool timeout to 2 minutes (default is 30s which is too short for complex operations)
|
|
295
|
-
// Sub-agents inherit this timeout from the parent agent
|
|
296
200
|
toolTimeoutMs: 120000,
|
|
297
|
-
// Enable file tracking for context restoration hints
|
|
298
201
|
enableFileTracking: true,
|
|
299
|
-
|
|
202
|
+
logger: log,
|
|
203
|
+
// Permissions
|
|
300
204
|
permissions: options.onPermissionRequest
|
|
301
|
-
?
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
307
|
-
: undefined,
|
|
308
|
-
// Iteration limit handler - asks user if they want to continue
|
|
205
|
+
? options.onPermissionRequest
|
|
206
|
+
: 'auto',
|
|
207
|
+
permissionRules: DEFAULT_PERMISSION_RULES,
|
|
208
|
+
includeDefaultRules: true,
|
|
209
|
+
// Iteration limits
|
|
309
210
|
onIterationLimitReached: options.onIterationLimitReached,
|
|
310
|
-
//
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
? {
|
|
314
|
-
maxAnchors: 50,
|
|
315
|
-
maxTokens: 4000,
|
|
316
|
-
includeDefaults: true,
|
|
317
|
-
// Note: We manage persistence ourselves via project-anchors.ts
|
|
318
|
-
// Don't set persistPath - we load anchors manually below
|
|
319
|
-
}
|
|
211
|
+
// Pins / anchors
|
|
212
|
+
pins: options.enableAnchors
|
|
213
|
+
? { maxAnchors: 50, maxTokens: 4000, includeDefaults: true }
|
|
320
214
|
: undefined,
|
|
321
|
-
// Guardrails
|
|
322
|
-
// 15 built-in patterns: git destructive ops, rm -rf, DROP TABLE, secrets, etc.
|
|
215
|
+
// Guardrails
|
|
323
216
|
guardrails: options.enableGuardrails
|
|
324
|
-
? {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
217
|
+
? { includeDefaults: true }
|
|
218
|
+
: false,
|
|
219
|
+
// Delegation
|
|
220
|
+
delegation: isDelegationEnabled() ? CLI_DELEGATION_CONFIG : undefined,
|
|
221
|
+
// Context management
|
|
222
|
+
context: {
|
|
223
|
+
compactionThreshold: isAutoCompactEnabled() ? undefined : 1.0,
|
|
224
|
+
},
|
|
225
|
+
// Suggest tool
|
|
226
|
+
onSuggest: options.onSuggest,
|
|
227
|
+
// Verbose event handler
|
|
228
|
+
onEvent: options.verbose
|
|
229
|
+
? (event) => {
|
|
230
|
+
if (event.type === 'tool_start') {
|
|
231
|
+
log.debug({ component: 'agent', tool: event.name }, 'Tool starting');
|
|
232
|
+
}
|
|
233
|
+
else if (event.type === 'tool_end') {
|
|
234
|
+
log.debug({ component: 'agent', tool: event.name }, 'Tool done');
|
|
235
|
+
}
|
|
328
236
|
}
|
|
329
237
|
: undefined,
|
|
330
|
-
//
|
|
331
|
-
|
|
238
|
+
// Capability loading (replaces CLI's manual meta-tools wiring)
|
|
239
|
+
// Platform tools (DB, factory) + MCP tools are passed as additionalTools
|
|
240
|
+
capabilities: (options.enableMetaTools && !options.minimal && !options.noTools)
|
|
332
241
|
? {
|
|
333
242
|
enabled: true,
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
// Custom thresholds
|
|
341
|
-
bash: { threshold: 12000 },
|
|
342
|
-
grep: { threshold: 4000 },
|
|
343
|
-
git_diff: { threshold: 6000 },
|
|
344
|
-
// Never summarize — agent needs verbatim results
|
|
345
|
-
get_tool_info: { enabled: false },
|
|
346
|
-
list_tools: { enabled: false },
|
|
347
|
-
ask_user: { enabled: false },
|
|
348
|
-
ask_user_simple: { enabled: false },
|
|
349
|
-
todo_read: { enabled: false },
|
|
350
|
-
},
|
|
243
|
+
profile: options.toolFilter ?? 'full',
|
|
244
|
+
additionalTools: [
|
|
245
|
+
...allDbTools,
|
|
246
|
+
...allFactoryTools,
|
|
247
|
+
...(options.mcpTools ?? []),
|
|
248
|
+
],
|
|
351
249
|
}
|
|
352
|
-
:
|
|
353
|
-
|
|
250
|
+
: {
|
|
251
|
+
enabled: false,
|
|
252
|
+
additionalTools: [
|
|
253
|
+
...allDbTools,
|
|
254
|
+
...allFactoryTools,
|
|
255
|
+
...(options.mcpTools ?? []),
|
|
256
|
+
],
|
|
257
|
+
},
|
|
258
|
+
// CLI-specific hooks
|
|
354
259
|
hooks: {
|
|
355
|
-
beforeLLM: [
|
|
356
|
-
// Context pressure hook
|
|
357
|
-
(ctx) => {
|
|
358
|
-
const utilization = contextManager.getUtilization();
|
|
359
|
-
if (utilization < 0.3)
|
|
360
|
-
return undefined;
|
|
361
|
-
const pct = Math.round(utilization * 100);
|
|
362
|
-
let hint;
|
|
363
|
-
if (utilization < 0.6) {
|
|
364
|
-
hint = `[Context: ${String(pct)}%] Consider task() for multi-file operations.`;
|
|
365
|
-
}
|
|
366
|
-
else if (utilization < 0.8) {
|
|
367
|
-
hint = `[Context: ${String(pct)}% - HIGH] Prefer task() sub-agents for file reads and code search.`;
|
|
368
|
-
}
|
|
369
|
-
else {
|
|
370
|
-
hint = `[Context: ${String(pct)}% - CRITICAL] Use task() for ALL exploration. Do not read files directly.`;
|
|
371
|
-
}
|
|
372
|
-
const messages = [...ctx.messages];
|
|
373
|
-
messages.splice(1, 0, { role: 'user', content: hint });
|
|
374
|
-
return { messages };
|
|
375
|
-
},
|
|
376
|
-
// Capability-aware system prompt assembly (SDK hook with auto-detection)
|
|
377
|
-
...(capabilityContext && baseSystemPrompt
|
|
378
|
-
? [createCapabilityHook(capabilityContext, baseSystemPrompt, {
|
|
379
|
-
staticSections: [TOOL_USAGE_META_MODULE.content],
|
|
380
|
-
conditionalModules: [
|
|
381
|
-
{ content: GIT_SAFETY_MODULE.content, whenModuleActive: ['git-safety'] },
|
|
382
|
-
{ content: PLATFORM_TOOL_HINTS_MODULE.content, whenModuleActive: ['platform-tool-hints'] },
|
|
383
|
-
{ content: FACTORY_TOOL_HINTS_MODULE.content, whenModuleActive: ['factory-tool-hints'] },
|
|
384
|
-
],
|
|
385
|
-
getToolIndex: (allowedNames) => getFilteredToolIndexForSystemPrompt(allowedNames),
|
|
386
|
-
})]
|
|
387
|
-
: []),
|
|
388
|
-
],
|
|
260
|
+
beforeLLM: [createContextPressureHook()],
|
|
389
261
|
beforeTool: [createFileLockCheckHook(getActiveProject)],
|
|
390
262
|
afterTool: [
|
|
391
263
|
createFileLockAcquireHook(getActiveProject),
|
|
@@ -393,7 +265,8 @@ ${options.systemPromptAddition}
|
|
|
393
265
|
],
|
|
394
266
|
},
|
|
395
267
|
});
|
|
396
|
-
|
|
268
|
+
const agent = compilrAgent.unwrap();
|
|
269
|
+
// ── Load persisted anchors ────────────────────────────────────────────────
|
|
397
270
|
if (options.enableAnchors && options.persistedAnchors) {
|
|
398
271
|
for (const anchor of options.persistedAnchors) {
|
|
399
272
|
agent.addPin({
|
|
@@ -402,112 +275,44 @@ ${options.systemPromptAddition}
|
|
|
402
275
|
priority: anchor.priority,
|
|
403
276
|
scope: anchor.scope,
|
|
404
277
|
tags: anchor.tags,
|
|
405
|
-
// Note: projectId is for our tracking, not needed by library
|
|
406
278
|
});
|
|
407
279
|
}
|
|
408
280
|
}
|
|
409
|
-
// Register
|
|
410
|
-
if (!options.noTools) {
|
|
411
|
-
// When meta-tools is enabled, use direct tools + meta-tools instead of all tools
|
|
412
|
-
let tools;
|
|
413
|
-
if (options.minimal) {
|
|
414
|
-
tools = createMinimalToolRegistry();
|
|
415
|
-
}
|
|
416
|
-
else if (options.enableMetaTools) {
|
|
417
|
-
// Hot-tools mode: only hot tools + get_tool_info (for schema introspection)
|
|
418
|
-
// Warm tools + meta-registry tools are accessed transparently via fallback handler
|
|
419
|
-
tools = [...getDirectTools(true), ...getMetaTools()];
|
|
420
|
-
// Add load_capability tool when the agent has loadable packs
|
|
421
|
-
if (capabilityManager?.hasLoadablePacks()) {
|
|
422
|
-
tools.push(createLoadCapabilityTool(capabilityManager));
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
else {
|
|
426
|
-
// Legacy mode: all tools declared directly
|
|
427
|
-
// eslint-disable-next-line @typescript-eslint/no-deprecated -- Intentional for backward compatibility
|
|
428
|
-
tools = createToolRegistry();
|
|
429
|
-
}
|
|
430
|
-
// Apply tool filter if specified (filter direct tools)
|
|
431
|
-
if (options.toolFilter && options.toolFilter.length > 0) {
|
|
432
|
-
const allowedTools = new Set(options.toolFilter);
|
|
433
|
-
// get_tool_info and load_capability are always allowed
|
|
434
|
-
const alwaysAllowed = new Set(['get_tool_info', 'load_capability']);
|
|
435
|
-
tools = tools.filter((tool) => allowedTools.has(tool.definition.name) || alwaysAllowed.has(tool.definition.name));
|
|
436
|
-
// When capability loading is active, the BeforeLLM hook manages the meta-tool filter.
|
|
437
|
-
// Otherwise, set it to the full tool filter.
|
|
438
|
-
if (!capabilityManager) {
|
|
439
|
-
setMetaToolFilter(options.toolFilter);
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
else if (!capabilityManager) {
|
|
443
|
-
// No filter and no capability loading - clear any previous filter
|
|
444
|
-
setMetaToolFilter(null);
|
|
445
|
-
}
|
|
446
|
-
// Type assertion needed for tool registry compatibility
|
|
447
|
-
agent.registerTools(tools);
|
|
448
|
-
// Register MCP tools (from external MCP servers)
|
|
449
|
-
// These are registered as direct tools since their schemas are unknown at build time
|
|
450
|
-
if (options.mcpTools && options.mcpTools.length > 0) {
|
|
451
|
-
agent.registerTools(options.mcpTools);
|
|
452
|
-
}
|
|
453
|
-
// Set up transparent fallback to meta-registry
|
|
454
|
-
// When the agent calls a tool not in direct tools (e.g., workitem_add),
|
|
455
|
-
// the fallback handler checks the meta-registry and executes it.
|
|
456
|
-
if (options.enableMetaTools && !options.minimal) {
|
|
457
|
-
agent.getToolRegistry().setFallbackHandler(createToolFallback());
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
// Register Task tool for sub-agent spawning (only in full mode)
|
|
281
|
+
// ── Register subagent task tool (CLI-specific callbacks) ──────────────────
|
|
461
282
|
if (!options.minimal && !options.noTools) {
|
|
462
|
-
// Track active subagents to correlate spawn/complete/events
|
|
463
|
-
// Track active subagents by toolUseId for token counting
|
|
464
283
|
const activeSubagents = new Map();
|
|
465
|
-
// Provide a way for caller to clear tracking state between runs
|
|
466
284
|
if (options.onSubagentTrackingReady) {
|
|
467
|
-
options.onSubagentTrackingReady(() => {
|
|
468
|
-
activeSubagents.clear();
|
|
469
|
-
});
|
|
285
|
+
options.onSubagentTrackingReady(() => { activeSubagents.clear(); });
|
|
470
286
|
}
|
|
471
287
|
const taskTool = createTaskTool({
|
|
472
288
|
parentAgent: agent,
|
|
473
289
|
agentTypes: getMergedAgentTypes(),
|
|
474
290
|
enableEventStreaming: true,
|
|
475
|
-
defaultTimeout: 120000,
|
|
476
|
-
// Now uses toolUseId for direct correlation (no more FIFO matching!)
|
|
291
|
+
defaultTimeout: 120000,
|
|
477
292
|
onSpawn: (agentType, description, toolUseId) => {
|
|
478
293
|
if (options.verbose) {
|
|
479
294
|
log.debug({ component: 'agent', agentType, toolUseId }, 'Spawning sub-agent: %s', description);
|
|
480
295
|
}
|
|
481
|
-
// Immediately notify with toolUseId - no more queuing/matching!
|
|
482
296
|
if (toolUseId) {
|
|
483
297
|
activeSubagents.set(toolUseId, { agentType, tokenCount: 0 });
|
|
484
|
-
|
|
485
|
-
options.onSubagentStart(toolUseId, agentType, description);
|
|
486
|
-
}
|
|
298
|
+
options.onSubagentStart?.(toolUseId, agentType, description);
|
|
487
299
|
}
|
|
488
300
|
},
|
|
489
301
|
onComplete: (agentType, result, toolUseId) => {
|
|
490
302
|
if (options.verbose) {
|
|
491
303
|
log.debug({ component: 'agent', agentType, iterations: result.iterations }, 'Sub-agent completed');
|
|
492
304
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
options.onSubagentEnd(toolUseId, true, result.toolCalls);
|
|
305
|
+
if (toolUseId) {
|
|
306
|
+
options.onSubagentEnd?.(toolUseId, true, result.toolCalls);
|
|
496
307
|
activeSubagents.delete(toolUseId);
|
|
497
308
|
}
|
|
498
309
|
},
|
|
499
|
-
// Stream subagent events for live updates
|
|
500
310
|
onSubAgentEvent: (eventInfo) => {
|
|
501
311
|
const { toolUseId, event } = eventInfo;
|
|
502
|
-
// Handle tool events for live updates
|
|
503
312
|
if (event.type === 'tool_start' && toolUseId && event.name && options.onSubagentToolUse) {
|
|
504
|
-
// Extract tool name and input summary
|
|
505
|
-
const toolName = event.name;
|
|
506
|
-
let summary;
|
|
507
|
-
// Try to get a meaningful summary from input
|
|
508
313
|
const input = event.input;
|
|
314
|
+
let summary;
|
|
509
315
|
if (input) {
|
|
510
|
-
// Common patterns for tool input summaries
|
|
511
316
|
const path = input.path;
|
|
512
317
|
const pattern = input.pattern;
|
|
513
318
|
const command = input.command;
|
|
@@ -521,64 +326,42 @@ ${options.systemPromptAddition}
|
|
|
521
326
|
else if (typeof filePath === 'string')
|
|
522
327
|
summary = filePath;
|
|
523
328
|
}
|
|
524
|
-
options.onSubagentToolUse(toolUseId,
|
|
329
|
+
options.onSubagentToolUse(toolUseId, event.name, summary);
|
|
525
330
|
}
|
|
526
331
|
},
|
|
527
332
|
});
|
|
528
|
-
// Type assertion needed for task tool compatibility
|
|
529
333
|
agent.registerTool(taskTool);
|
|
530
|
-
//
|
|
531
|
-
const suggestTool = createSuggestTool({
|
|
532
|
-
onSuggest: options.onSuggest,
|
|
533
|
-
});
|
|
534
|
-
agent.registerTool(suggestTool);
|
|
334
|
+
// Note: suggest tool is already registered by createCompilrAgent via onSuggest config
|
|
535
335
|
}
|
|
536
|
-
//
|
|
537
|
-
// Calculate and store token estimates for debugging
|
|
538
|
-
// ==========================================================================
|
|
336
|
+
// ── Token estimate logging ────────────────────────────────────────────────
|
|
539
337
|
if (!options.quiet) {
|
|
540
|
-
|
|
338
|
+
const toolDefs = agent.getToolRegistry().getDefinitions();
|
|
541
339
|
let toolTokens = 0;
|
|
542
|
-
|
|
543
|
-
let toolsForEstimate = [];
|
|
544
|
-
if (!options.noTools) {
|
|
545
|
-
if (options.minimal) {
|
|
546
|
-
toolsForEstimate = createMinimalToolRegistry();
|
|
547
|
-
}
|
|
548
|
-
else if (options.enableMetaTools) {
|
|
549
|
-
toolsForEstimate = [...getDirectTools(true), ...getMetaTools()];
|
|
550
|
-
}
|
|
551
|
-
else {
|
|
552
|
-
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
553
|
-
toolsForEstimate = createToolRegistry();
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
for (const tool of toolsForEstimate) {
|
|
557
|
-
const def = tool.definition;
|
|
340
|
+
for (const def of toolDefs) {
|
|
558
341
|
toolTokens += estimateJsonTokens({
|
|
559
342
|
name: def.name,
|
|
560
343
|
description: def.description,
|
|
561
344
|
input_schema: def.inputSchema,
|
|
562
345
|
});
|
|
563
346
|
}
|
|
564
|
-
// Add task tool and suggest tool estimates (if registered)
|
|
565
|
-
if (!options.minimal && !options.noTools) {
|
|
566
|
-
// Task tool has a large description with all agent types
|
|
567
|
-
toolTokens += 700; // Approximate for task tool
|
|
568
|
-
toolTokens += 200; // Approximate for suggest tool
|
|
569
|
-
}
|
|
570
|
-
// Calculate estimates
|
|
571
347
|
const systemTokens = estimateTokens(systemPrompt);
|
|
572
348
|
const roleTokens = options.systemPromptAddition
|
|
573
|
-
? estimateTokens(options.systemPromptAddition) * 2
|
|
349
|
+
? estimateTokens(options.systemPromptAddition) * 2
|
|
574
350
|
: 0;
|
|
575
351
|
const contextTokens = estimateTokens(options.projectContext);
|
|
576
352
|
setStaticEstimates({
|
|
577
|
-
system: systemTokens - roleTokens,
|
|
353
|
+
system: systemTokens - roleTokens,
|
|
578
354
|
role: roleTokens,
|
|
579
355
|
tools: toolTokens,
|
|
580
356
|
context: contextTokens,
|
|
581
357
|
});
|
|
358
|
+
log.info({
|
|
359
|
+
component: 'agent',
|
|
360
|
+
toolCount: toolDefs.length,
|
|
361
|
+
systemTokens,
|
|
362
|
+
toolTokens,
|
|
363
|
+
contextTokens,
|
|
364
|
+
}, 'Agent created');
|
|
582
365
|
}
|
|
583
366
|
return agent;
|
|
584
367
|
}
|