@posthog/agent 1.14.0 → 1.15.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/README.md +110 -0
- package/dist/src/agent.d.ts +3 -1
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +7 -0
- package/dist/src/agent.js.map +1 -1
- package/dist/src/agents/execution.d.ts +1 -1
- package/dist/src/agents/execution.d.ts.map +1 -1
- package/dist/src/agents/execution.js +0 -1
- package/dist/src/agents/execution.js.map +1 -1
- package/dist/src/agents/planning.d.ts +1 -1
- package/dist/src/agents/planning.d.ts.map +1 -1
- package/dist/src/agents/planning.js +1 -1
- package/dist/src/agents/planning.js.map +1 -1
- package/dist/src/agents/research.d.ts +1 -1
- package/dist/src/agents/research.js +1 -1
- package/dist/src/agents/research.js.map +1 -1
- package/dist/src/types.d.ts +4 -1
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/dist/src/workflow/steps/build.d.ts.map +1 -1
- package/dist/src/workflow/steps/build.js +22 -0
- package/dist/src/workflow/steps/build.js.map +1 -1
- package/dist/src/workflow/steps/plan.d.ts.map +1 -1
- package/dist/src/workflow/steps/plan.js +13 -0
- package/dist/src/workflow/steps/plan.js.map +1 -1
- package/dist/src/workflow/steps/research.d.ts.map +1 -1
- package/dist/src/workflow/steps/research.js +12 -0
- package/dist/src/workflow/steps/research.js.map +1 -1
- package/package.json +1 -1
- package/src/agent.ts +10 -2
- package/src/agents/execution.ts +0 -1
- package/src/agents/planning.ts +1 -1
- package/src/agents/research.ts +1 -1
- package/src/types.ts +12 -0
- package/src/workflow/steps/build.ts +23 -0
- package/src/workflow/steps/plan.ts +13 -0
- package/src/workflow/steps/research.ts +12 -0
package/README.md
CHANGED
|
@@ -145,3 +145,113 @@ await agent.runTask(task, {
|
|
|
145
145
|
}
|
|
146
146
|
});
|
|
147
147
|
```
|
|
148
|
+
|
|
149
|
+
## Fine-Grained Permissions
|
|
150
|
+
|
|
151
|
+
For advanced control over agent actions, you can provide a `canUseTool` callback that intercepts every tool use during the **build phase** (for task execution) or **direct run calls**. This allows you to implement custom approval flows, logging, or restrictions.
|
|
152
|
+
|
|
153
|
+
See the [Claude Agent SDK Permissions docs](https://docs.claude.com/en/api/agent-sdk/permissions) for more details.
|
|
154
|
+
|
|
155
|
+
### Per-Agent Configuration
|
|
156
|
+
|
|
157
|
+
Apply the same permission hook to all task executions and direct runs:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { Agent } from '@posthog/agent';
|
|
161
|
+
import type { PermissionResult } from '@posthog/agent';
|
|
162
|
+
|
|
163
|
+
const agent = new Agent({
|
|
164
|
+
workingDirectory: "/path/to/repo",
|
|
165
|
+
posthogApiUrl: "https://app.posthog.com",
|
|
166
|
+
posthogApiKey: process.env.POSTHOG_API_KEY,
|
|
167
|
+
canUseTool: async (toolName, input, { signal, suggestions }) => {
|
|
168
|
+
// Block destructive commands
|
|
169
|
+
if (toolName === 'Bash' && input.command?.includes('rm -rf')) {
|
|
170
|
+
return {
|
|
171
|
+
behavior: 'deny',
|
|
172
|
+
message: 'Destructive rm -rf commands are not allowed',
|
|
173
|
+
interrupt: true
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Allow everything else
|
|
178
|
+
return {
|
|
179
|
+
behavior: 'allow',
|
|
180
|
+
updatedInput: input
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Per-Task Configuration
|
|
187
|
+
|
|
188
|
+
Override permissions for specific tasks (only applied during build phase):
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
await agent.runTask(task, {
|
|
192
|
+
repositoryPath: "/path/to/repo",
|
|
193
|
+
permissionMode: PermissionMode.DEFAULT,
|
|
194
|
+
canUseTool: async (toolName, input, { signal, suggestions }) => {
|
|
195
|
+
// Custom approval UI
|
|
196
|
+
const approved = await showApprovalDialog({
|
|
197
|
+
tool: toolName,
|
|
198
|
+
input: input,
|
|
199
|
+
suggestions: suggestions // Permission updates for "always allow"
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
if (approved.action === 'allow') {
|
|
203
|
+
return {
|
|
204
|
+
behavior: 'allow',
|
|
205
|
+
updatedInput: approved.modifiedInput || input,
|
|
206
|
+
updatedPermissions: approved.rememberChoice ? suggestions : undefined
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
behavior: 'deny',
|
|
212
|
+
message: approved.reason || 'User denied permission',
|
|
213
|
+
interrupt: !approved.continueWithGuidance
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Direct Run Example
|
|
220
|
+
|
|
221
|
+
For one-off queries with custom permissions:
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
const result = await agent.run("Fix the authentication bug", {
|
|
225
|
+
repositoryPath: "/path/to/repo",
|
|
226
|
+
permissionMode: PermissionMode.DEFAULT,
|
|
227
|
+
canUseTool: async (toolName, input, { signal }) => {
|
|
228
|
+
console.log(`Agent wants to use ${toolName}:`, input);
|
|
229
|
+
|
|
230
|
+
// Simple approval logic
|
|
231
|
+
if (toolName === 'Write' || toolName === 'Edit') {
|
|
232
|
+
const allowedFiles = ['src/', 'tests/'];
|
|
233
|
+
const filePath = input.file_path || input.path;
|
|
234
|
+
const isAllowed = allowedFiles.some(prefix => filePath?.startsWith(prefix));
|
|
235
|
+
|
|
236
|
+
if (!isAllowed) {
|
|
237
|
+
return {
|
|
238
|
+
behavior: 'deny',
|
|
239
|
+
message: `Can only modify files in: ${allowedFiles.join(', ')}`
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return { behavior: 'allow', updatedInput: input };
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### Available Tool Names
|
|
250
|
+
|
|
251
|
+
The `canUseTool` callback receives one of these tool names:
|
|
252
|
+
- **Read-only**: `Read`, `Glob`, `Grep`, `WebFetch`, `WebSearch`, `ListMcpResources`, `ReadMcpResource`
|
|
253
|
+
- **Modifications**: `Write`, `Edit`, `NotebookEdit`
|
|
254
|
+
- **Execution**: `Bash`, `BashOutput`, `KillBash`, `Task`
|
|
255
|
+
- **Planning**: `ExitPlanMode`, `TodoWrite`
|
|
256
|
+
|
|
257
|
+
**Note**: Research and planning phases have fixed, read-only tool sets. The `canUseTool` hook only applies to the build phase and direct run calls.
|
package/dist/src/agent.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Task, ExecutionResult, AgentConfig } from './types.js';
|
|
1
|
+
import type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';
|
|
2
2
|
import { PostHogAPIClient } from './posthog-api.js';
|
|
3
3
|
import { type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';
|
|
4
4
|
export declare class Agent {
|
|
@@ -15,6 +15,7 @@ export declare class Agent {
|
|
|
15
15
|
private promptBuilder;
|
|
16
16
|
private extractor?;
|
|
17
17
|
private mcpServers?;
|
|
18
|
+
private canUseTool?;
|
|
18
19
|
debug: boolean;
|
|
19
20
|
constructor(config?: AgentConfig);
|
|
20
21
|
/**
|
|
@@ -30,6 +31,7 @@ export declare class Agent {
|
|
|
30
31
|
repositoryPath?: string;
|
|
31
32
|
permissionMode?: import('./types.js').PermissionMode;
|
|
32
33
|
queryOverrides?: Record<string, any>;
|
|
34
|
+
canUseTool?: CanUseTool;
|
|
33
35
|
}): Promise<ExecutionResult>;
|
|
34
36
|
fetchTask(taskId: string): Promise<Task>;
|
|
35
37
|
getPostHogClient(): PostHogAPIClient | undefined;
|
package/dist/src/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent.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,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAO9D,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,kBAAkB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAOxF,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAO9F,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuBlH,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB1F,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAczE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAUhC,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;YAUvC,iBAAiB;IAqB/B,OAAO,CAAC,sBAAsB;YAiBhB,iBAAiB;IAsC/B,OAAO,CAAC,SAAS;CAapB;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/src/agent.js
CHANGED
|
@@ -26,10 +26,12 @@ class Agent {
|
|
|
26
26
|
promptBuilder;
|
|
27
27
|
extractor;
|
|
28
28
|
mcpServers;
|
|
29
|
+
canUseTool;
|
|
29
30
|
debug;
|
|
30
31
|
constructor(config = {}) {
|
|
31
32
|
this.workingDirectory = config.workingDirectory || process.cwd();
|
|
32
33
|
this.onEvent = config.onEvent;
|
|
34
|
+
this.canUseTool = config.canUseTool;
|
|
33
35
|
this.debug = config.debug || false;
|
|
34
36
|
// Build default PostHog MCP server configuration
|
|
35
37
|
const posthogMcpUrl = config.posthogMcpUrl
|
|
@@ -162,6 +164,11 @@ class Agent {
|
|
|
162
164
|
settingSources: ["local"],
|
|
163
165
|
mcpServers: this.mcpServers,
|
|
164
166
|
};
|
|
167
|
+
// Add canUseTool hook if provided (options take precedence over instance config)
|
|
168
|
+
const canUseTool = options.canUseTool || this.canUseTool;
|
|
169
|
+
if (canUseTool) {
|
|
170
|
+
baseOptions.canUseTool = canUseTool;
|
|
171
|
+
}
|
|
165
172
|
const response = query({
|
|
166
173
|
prompt,
|
|
167
174
|
options: { ...baseOptions, ...(options.queryOverrides || {}) },
|
package/dist/src/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, AgentConfig } from './types.js';\nimport { TaskManager } from './task-manager.js';\nimport { PostHogAPIClient } from './posthog-api.js';\nimport { PostHogFileManager } from './file-manager.js';\nimport { GitManager } from './git-manager.js';\nimport { TemplateManager } from './template-manager.js';\nimport { ClaudeAdapter } from './adapters/claude/claude-adapter.js';\nimport type { ProviderAdapter } from './adapters/types.js';\nimport { Logger } from './utils/logger.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.js';\nimport { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';\nimport { TASK_WORKFLOW } from './workflow/config.js';\nimport type { WorkflowRuntime } from './workflow/types.js';\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private extractor?: StructuredExtractor;\n private mcpServers?: Record<string, any>;\n public debug: boolean;\n\n constructor(config: AgentConfig = {}) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl = config.posthogMcpUrl\n || process.env.POSTHOG_MCP_URL\n || 'https://mcp.posthog.com/mcp';\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers['Authorization'] = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: 'http' as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n }\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers\n };\n this.logger = new Logger({ debug: this.debug, prefix: '[PostHog Agent]' });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child('FileManager')\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child('GitManager')\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child('PromptBuilder')\n });\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug('Configured LLM gateway', { gatewayUrl });\n } catch (error) {\n this.logger.error('Failed to configure LLM gateway', error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(taskOrId: Task | string, options: import('./types.js').TaskExecutionOptions = {}): Promise<void> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info('Starting adaptive task execution', { taskId: task.id, taskSlug, isCloudMode });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });\n this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n extractor: this.extractor,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n if (isCloudMode) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n await this.progressReporter.complete();\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any> } = {}): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n for await (const message of response) {\n this.logger.debug('Received message in direct run', message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\n }\n results.push(message);\n }\n \n return { results };\n }\n \n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug('Fetching task from PostHog', { taskId });\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n \n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n }\n return this.posthogAPI.listTasks(filters);\n }\n \n // File system operations for task artifacts\n async writeTaskFile(taskId: string, fileName: string, content: string, type: 'plan' | 'context' | 'reference' | 'output' = 'reference'): Promise<void> {\n this.logger.debug('Writing task file', { taskId, fileName, type, contentLength: content.length });\n await this.fileManager.writeTaskFile(taskId, { name: fileName, content, type });\n }\n \n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug('Reading task file', { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n \n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug('Getting task files', { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug('Found task files', { taskId, fileCount: files.length });\n return files;\n }\n \n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info('Writing plan', { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n \n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug('Reading plan', { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info('Creating planning branch', { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug('Planning branch created', { taskId, branchName });\n // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\n return branchName;\n }\n \n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info('Committing plan', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug('Plan committed', { taskId, commitHash });\n return commitHash;\n }\n \n async createImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n this.logger.info('Creating implementation branch', { taskId, fromBranch: planningBranchName });\n const branchName = await this.gitManager.createTaskImplementationBranch(taskId, planningBranchName);\n this.logger.debug('Implementation branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n this.logger.info('Committing implementation', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(taskId, taskTitle, planSummary);\n this.logger.debug('Implementation committed', { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody\n );\n\n this.logger.info('Pull request created', { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void> {\n this.logger.info('Attaching PR to task run', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl }\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, updates);\n this.logger.debug('PR attached to task run', { taskId, runId: this.progressReporter.runId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task run branch', { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot update branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, { branch: branchName });\n this.logger.debug('Task run branch updated', { taskId, runId: this.progressReporter.runId, branchName });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager['executionStates']) {\n if (execution.taskId === taskId && execution.status === 'running') {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager['executionStates'].values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n this.logger.info('Creating task branch', { taskSlug });\n const branchName = `posthog/task-${taskSlug}`;\n await this.gitManager.createOrSwitchToBranch(branchName);\n this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));\n\n await this.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n } else {\n this.logger.info('Switching to existing task branch', { branch: existingBranch });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n }\n\n private async ensurePullRequest(task: Task, stepResults: Record<string, any>): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info('PR already exists, skipping creation', { taskId: task.id, prUrl: existingPr });\n return;\n }\n\n const buildResult = stepResults['build'];\n if (!buildResult?.commitCreated) {\n this.logger.warn('Build step did not produce a commit; skipping PR creation', { taskId: task.id });\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\n );\n\n this.emitEvent(this.adapter.createStatusEvent('pr_created', { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info('PR attached to task successfully', { taskId: task.id, prUrl });\n } catch (error) {\n this.logger.warn('Could not attach PR to task', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== 'token') {\n // Log all events except tokens (too verbose)\n this.logger.debug('Emitting event', { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === 'function') {\n persistPromise.catch((error: Error) =>\n this.logger.debug('Failed to persist agent event', { message: error.message })\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport { PermissionMode } from './types.js';\nexport type { Task, SupportingFile, ExecutionResult, AgentConfig } from './types.js';\n"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,IAAA,gBAAgB;AAChB,IAAA,OAAO;AACP,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,eAAe;AACf,IAAA,OAAO;AACP,IAAA,MAAM;AACN,IAAA,gBAAgB;AAChB,IAAA,aAAa;AACb,IAAA,SAAS;AACT,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,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C,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC5C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAChE,aAAA,CAAC;QACN;IACJ;AAEQ,IAAA,SAAS,CAAC,KAAU,EAAA;QACxB,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;;YAEtC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QAC3E;QACA,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC;QAC/D,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE;YAC7D,cAAc,CAAC,KAAK,CAAC,CAAC,KAAY,KAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';\nimport { TaskManager } from './task-manager.js';\nimport { PostHogAPIClient } from './posthog-api.js';\nimport { PostHogFileManager } from './file-manager.js';\nimport { GitManager } from './git-manager.js';\nimport { TemplateManager } from './template-manager.js';\nimport { ClaudeAdapter } from './adapters/claude/claude-adapter.js';\nimport type { ProviderAdapter } from './adapters/types.js';\nimport { Logger } from './utils/logger.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.js';\nimport { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';\nimport { TASK_WORKFLOW } from './workflow/config.js';\nimport type { WorkflowRuntime } from './workflow/types.js';\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private extractor?: StructuredExtractor;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n public debug: boolean;\n\n constructor(config: AgentConfig = {}) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl = config.posthogMcpUrl\n || process.env.POSTHOG_MCP_URL\n || 'https://mcp.posthog.com/mcp';\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers['Authorization'] = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: 'http' as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n }\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers\n };\n this.logger = new Logger({ debug: this.debug, prefix: '[PostHog Agent]' });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child('FileManager')\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child('GitManager')\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child('PromptBuilder')\n });\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug('Configured LLM gateway', { gatewayUrl });\n } catch (error) {\n this.logger.error('Failed to configure LLM gateway', error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(taskOrId: Task | string, options: import('./types.js').TaskExecutionOptions = {}): Promise<void> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info('Starting adaptive task execution', { taskId: task.id, taskSlug, isCloudMode });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });\n this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n extractor: this.extractor,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n if (isCloudMode) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n await this.progressReporter.complete();\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any>; canUseTool?: CanUseTool } = {}): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n // Add canUseTool hook if provided (options take precedence over instance config)\n const canUseTool = options.canUseTool || this.canUseTool;\n if (canUseTool) {\n baseOptions.canUseTool = canUseTool;\n }\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n for await (const message of response) {\n this.logger.debug('Received message in direct run', message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\n }\n results.push(message);\n }\n \n return { results };\n }\n \n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug('Fetching task from PostHog', { taskId });\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n \n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n }\n return this.posthogAPI.listTasks(filters);\n }\n \n // File system operations for task artifacts\n async writeTaskFile(taskId: string, fileName: string, content: string, type: 'plan' | 'context' | 'reference' | 'output' = 'reference'): Promise<void> {\n this.logger.debug('Writing task file', { taskId, fileName, type, contentLength: content.length });\n await this.fileManager.writeTaskFile(taskId, { name: fileName, content, type });\n }\n \n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug('Reading task file', { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n \n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug('Getting task files', { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug('Found task files', { taskId, fileCount: files.length });\n return files;\n }\n \n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info('Writing plan', { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n \n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug('Reading plan', { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info('Creating planning branch', { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug('Planning branch created', { taskId, branchName });\n // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\n return branchName;\n }\n \n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info('Committing plan', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug('Plan committed', { taskId, commitHash });\n return commitHash;\n }\n \n async createImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n this.logger.info('Creating implementation branch', { taskId, fromBranch: planningBranchName });\n const branchName = await this.gitManager.createTaskImplementationBranch(taskId, planningBranchName);\n this.logger.debug('Implementation branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n this.logger.info('Committing implementation', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(taskId, taskTitle, planSummary);\n this.logger.debug('Implementation committed', { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody\n );\n\n this.logger.info('Pull request created', { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void> {\n this.logger.info('Attaching PR to task run', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl }\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, updates);\n this.logger.debug('PR attached to task run', { taskId, runId: this.progressReporter.runId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task run branch', { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot update branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, { branch: branchName });\n this.logger.debug('Task run branch updated', { taskId, runId: this.progressReporter.runId, branchName });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager['executionStates']) {\n if (execution.taskId === taskId && execution.status === 'running') {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager['executionStates'].values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n this.logger.info('Creating task branch', { taskSlug });\n const branchName = `posthog/task-${taskSlug}`;\n await this.gitManager.createOrSwitchToBranch(branchName);\n this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));\n\n await this.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n } else {\n this.logger.info('Switching to existing task branch', { branch: existingBranch });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n }\n\n private async ensurePullRequest(task: Task, stepResults: Record<string, any>): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info('PR already exists, skipping creation', { taskId: task.id, prUrl: existingPr });\n return;\n }\n\n const buildResult = stepResults['build'];\n if (!buildResult?.commitCreated) {\n this.logger.warn('Build step did not produce a commit; skipping PR creation', { taskId: task.id });\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\n );\n\n this.emitEvent(this.adapter.createStatusEvent('pr_created', { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info('PR attached to task successfully', { taskId: task.id, prUrl });\n } catch (error) {\n this.logger.warn('Could not attach PR to task', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== 'token') {\n // Log all events except tokens (too verbose)\n this.logger.debug('Emitting event', { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === 'function') {\n persistPromise.catch((error: Error) =>\n this.logger.debug('Failed to persist agent event', { message: error.message })\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport { PermissionMode } from './types.js';\nexport type { Task, SupportingFile, ExecutionResult, AgentConfig } from './types.js';\n"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,IAAA,gBAAgB;AAChB,IAAA,OAAO;AACP,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,eAAe;AACf,IAAA,OAAO;AACP,IAAA,MAAM;AACN,IAAA,gBAAgB;AAChB,IAAA,aAAa;AACb,IAAA,SAAS;AACT,IAAA,UAAU;AACV,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,SAAsB,EAAE,EAAA;QAChC,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;AAC7B,QAAA,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU;QACnC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK;;AAGlC,QAAA,MAAM,aAAa,GAAG,MAAM,CAAC;eACtB,OAAO,CAAC,GAAG,CAAC;AACZ,eAAA,6BAA6B;;QAGpC,MAAM,OAAO,GAA2B,EAAE;AAC1C,QAAA,IAAI,MAAM,CAAC,aAAa,EAAE;YACtB,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,CAAC,aAAa,CAAA,CAAE;QAC/D;AAEA,QAAA,MAAM,iBAAiB,GAAG;AACtB,YAAA,OAAO,EAAE;AACL,gBAAA,IAAI,EAAE,MAAe;AACrB,gBAAA,GAAG,EAAE,aAAa;gBAClB,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC1D;SACJ;;QAGD,IAAI,CAAC,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AAC,KAAY,KAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const EXECUTION_SYSTEM_PROMPT = "<role>\nPostHog AI Execution Agent \u2014 autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies \u2014 only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n
|
|
1
|
+
export declare const EXECUTION_SYSTEM_PROMPT = "<role>\nPostHog AI Execution Agent \u2014 autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies \u2014 only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format>";
|
|
2
2
|
//# sourceMappingURL=execution.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../../src/agents/execution.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,
|
|
1
|
+
{"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../../src/agents/execution.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,o7CAoCnB,CAAC"}
|
|
@@ -30,7 +30,6 @@ Before completing the task, verify:
|
|
|
30
30
|
- Captured meaningful events with PostHog SDK where appropriate
|
|
31
31
|
- Wrapped new logic in PostHog feature flags where appropriate
|
|
32
32
|
- Updated documentation, README, or type hints as needed
|
|
33
|
-
- No build artifacts or dependencies are being committed
|
|
34
33
|
</checklist>
|
|
35
34
|
|
|
36
35
|
<output_format>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<role>\nPostHog AI Execution Agent — autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies — only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n
|
|
1
|
+
{"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<role>\nPostHog AI Execution Agent — autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies — only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format>`;"],"names":[],"mappings":"AAAO,MAAM,uBAAuB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const PLANNING_SYSTEM_PROMPT = "<role>\nPostHog AI Planning Agent \u2014 analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications
|
|
1
|
+
export declare const PLANNING_SYSTEM_PROMPT = "<role>\nPostHog AI Planning Agent \u2014 analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or edits\n- Output ONLY the plan markdown \u2014 no preamble, no acknowledgment, no meta-commentary\n</constraints>\n\n<objective>\nCreate a detailed, actionable implementation plan that an execution agent can follow to complete the task successfully.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Break down task requirements and identify technical constraints\n4. Define step-by-step implementation approach\n5. Specify files to modify/create with exact paths\n6. Identify testing requirements and potential risks\n</process>\n\n<output_format>\nOutput the plan DIRECTLY as markdown with NO preamble text. Do NOT say \"I'll create a plan\" or \"Here's the plan\" \u2014 just output the plan content.\n\nRequired sections (follow the template provided in the task prompt):\n- Summary: Brief overview of approach\n- Files to Create/Modify: Specific paths and purposes\n- Implementation Steps: Ordered list of actions\n- Testing Strategy: How to verify it works\n- Considerations: Dependencies, risks, edge cases\n</output_format>\n\n<examples>\n<bad_example>\n\"Sure! I'll create a detailed implementation plan for you to add authentication. Here's what we'll do...\"\nReason: No preamble \u2014 output the plan directly\n</bad_example>\n\n<good_example>\n\"# Implementation Plan\n\n## Summary\nAdd JWT-based authentication to API endpoints using existing middleware pattern...\n\n## Files to Modify\n- src/middleware/auth.ts: Add JWT verification\n...\"\nReason: Direct plan output with no meta-commentary\n</good_example>\n</examples>\n\n<context_integration>\nIf research findings, context files, or reference materials are provided:\n- Incorporate research findings into your analysis\n- Follow patterns and approaches identified in research\n- Build upon or refine any existing planning work\n- Reference specific files and components mentioned in context\n</context_integration>";
|
|
2
2
|
//# sourceMappingURL=planning.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planning.d.ts","sourceRoot":"","sources":["../../../src/agents/planning.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB
|
|
1
|
+
{"version":3,"file":"planning.d.ts","sourceRoot":"","sources":["../../../src/agents/planning.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB,2qEA2DZ,CAAC"}
|
|
@@ -4,7 +4,7 @@ PostHog AI Planning Agent — analyze codebases and create actionable implementa
|
|
|
4
4
|
|
|
5
5
|
<constraints>
|
|
6
6
|
- Read-only: analyze files, search code, explore structure
|
|
7
|
-
- No modifications
|
|
7
|
+
- No modifications or edits
|
|
8
8
|
- Output ONLY the plan markdown — no preamble, no acknowledgment, no meta-commentary
|
|
9
9
|
</constraints>
|
|
10
10
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planning.js","sources":["../../../src/agents/planning.ts"],"sourcesContent":["export const PLANNING_SYSTEM_PROMPT = `<role>\nPostHog AI Planning Agent — analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications
|
|
1
|
+
{"version":3,"file":"planning.js","sources":["../../../src/agents/planning.ts"],"sourcesContent":["export const PLANNING_SYSTEM_PROMPT = `<role>\nPostHog AI Planning Agent — analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or edits\n- Output ONLY the plan markdown — no preamble, no acknowledgment, no meta-commentary\n</constraints>\n\n<objective>\nCreate a detailed, actionable implementation plan that an execution agent can follow to complete the task successfully.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Break down task requirements and identify technical constraints\n4. Define step-by-step implementation approach\n5. Specify files to modify/create with exact paths\n6. Identify testing requirements and potential risks\n</process>\n\n<output_format>\nOutput the plan DIRECTLY as markdown with NO preamble text. Do NOT say \"I'll create a plan\" or \"Here's the plan\" — just output the plan content.\n\nRequired sections (follow the template provided in the task prompt):\n- Summary: Brief overview of approach\n- Files to Create/Modify: Specific paths and purposes\n- Implementation Steps: Ordered list of actions\n- Testing Strategy: How to verify it works\n- Considerations: Dependencies, risks, edge cases\n</output_format>\n\n<examples>\n<bad_example>\n\"Sure! I'll create a detailed implementation plan for you to add authentication. Here's what we'll do...\"\nReason: No preamble — output the plan directly\n</bad_example>\n\n<good_example>\n\"# Implementation Plan\n\n## Summary\nAdd JWT-based authentication to API endpoints using existing middleware pattern...\n\n## Files to Modify\n- src/middleware/auth.ts: Add JWT verification\n...\"\nReason: Direct plan output with no meta-commentary\n</good_example>\n</examples>\n\n<context_integration>\nIf research findings, context files, or reference materials are provided:\n- Incorporate research findings into your analysis\n- Follow patterns and approaches identified in research\n- Build upon or refine any existing planning work\n- Reference specific files and components mentioned in context\n</context_integration>`;"],"names":[],"mappings":"AAAO,MAAM,sBAAsB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const RESEARCH_SYSTEM_PROMPT = "<role>\nPostHog AI Research Agent \u2014 analyze codebases to understand implementation context and identify areas of focus for development tasks.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n</constraints>\n\n<objective>\nYour PRIMARY goal is to understand the codebase thoroughly and provide context for the planning phase.\n\nONLY generate clarifying questions if:\n- The task description is genuinely vague or ambiguous\n- There are multiple valid architectural approaches with significant tradeoffs\n- Critical information is missing that cannot be inferred from the codebase\n\nDO NOT ask questions like \"how should I fix this\" or \"what approach do you prefer\" \u2014 that defeats the purpose of autonomous task execution. The user has already specified what they want done.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Locate similar implementations or related code\n4. Identify the key areas of the codebase that will be affected\n5. Document your findings to provide context for planning\n6. ONLY if genuinely needed: generate 2-3 specific clarification questions\n</process>\n\n<output_format>\nOutput ONLY the markdown artifact with no preamble:\n\n```markdown\n# Research Findings\n\n## Codebase Analysis\n[Brief summary of relevant code structure, patterns, and files]\n\n## Key Areas of Focus\n[List specific files/components that need modification]\n\n## Implementation Context\n[Important patterns, dependencies, or constraints found in the code]\n\n## Clarifying Questions\n[ONLY include this section if it will increase the quality of the plan]\n\n## Question 1: [Specific architectural decision]\n**Options:**\n- a) [Concrete option with file references]\n- b) [Alternative with file references]\n- c) Something else (please specify)\n```\n\nFormat requirements:\n- Use \"## Question N:\" for question headers (h2)\n- Follow with \"**Options:**\" on its own line\n- Start options with \"- a)\", \"- b)\", \"- c)\"\n- Always include \"c) Something else (please specify)\"\n- Max
|
|
1
|
+
export declare const RESEARCH_SYSTEM_PROMPT = "<role>\nPostHog AI Research Agent \u2014 analyze codebases to understand implementation context and identify areas of focus for development tasks.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n</constraints>\n\n<objective>\nYour PRIMARY goal is to understand the codebase thoroughly and provide context for the planning phase.\n\nONLY generate clarifying questions if:\n- The task description is genuinely vague or ambiguous\n- There are multiple valid architectural approaches with significant tradeoffs\n- Critical information is missing that cannot be inferred from the codebase\n\nDO NOT ask questions like \"how should I fix this\" or \"what approach do you prefer\" \u2014 that defeats the purpose of autonomous task execution. The user has already specified what they want done.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Locate similar implementations or related code\n4. Identify the key areas of the codebase that will be affected\n5. Document your findings to provide context for planning\n6. ONLY if genuinely needed: generate 2-3 specific clarification questions\n</process>\n\n<output_format>\nOutput ONLY the markdown artifact with no preamble:\n\n```markdown\n# Research Findings\n\n## Codebase Analysis\n[Brief summary of relevant code structure, patterns, and files]\n\n## Key Areas of Focus\n[List specific files/components that need modification]\n\n## Implementation Context\n[Important patterns, dependencies, or constraints found in the code]\n\n## Clarifying Questions\n[ONLY include this section if it will increase the quality of the plan]\n\n## Question 1: [Specific architectural decision]\n**Options:**\n- a) [Concrete option with file references]\n- b) [Alternative with file references]\n- c) Something else (please specify)\n```\n\nFormat requirements:\n- Use \"## Question N:\" for question headers (h2)\n- Follow with \"**Options:**\" on its own line\n- Start options with \"- a)\", \"- b)\", \"- c)\"\n- Always include \"c) Something else (please specify)\"\n- Max 4 questions total\n</output_format>\n\n<examples>\n<good_example>\nTask: \"Fix authentication bug in login flow\"\nOutput: Research findings showing auth flow files, patterns used, NO questions needed\n</good_example>\n\n<bad_example>\nTask: \"Fix authentication bug\"\nOutput: \"How should I fix the authentication? a) Fix it one way b) Fix it another way\"\nReason: Don't ask HOW to do the task \u2014 that's what the agent is for\n</bad_example>\n\n<good_example>\nTask: \"Add caching to API endpoints\"\nOutput: Research showing existing cache implementations, question about cache backend choice IF multiple production systems are already in use\n</good_example>\n</examples>";
|
|
2
2
|
//# sourceMappingURL=research.d.ts.map
|
|
@@ -57,7 +57,7 @@ Format requirements:
|
|
|
57
57
|
- Follow with "**Options:**" on its own line
|
|
58
58
|
- Start options with "- a)", "- b)", "- c)"
|
|
59
59
|
- Always include "c) Something else (please specify)"
|
|
60
|
-
- Max
|
|
60
|
+
- Max 4 questions total
|
|
61
61
|
</output_format>
|
|
62
62
|
|
|
63
63
|
<examples>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"research.js","sources":["../../../src/agents/research.ts"],"sourcesContent":["export const RESEARCH_SYSTEM_PROMPT = `<role>\nPostHog AI Research Agent — analyze codebases to understand implementation context and identify areas of focus for development tasks.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n</constraints>\n\n<objective>\nYour PRIMARY goal is to understand the codebase thoroughly and provide context for the planning phase.\n\nONLY generate clarifying questions if:\n- The task description is genuinely vague or ambiguous\n- There are multiple valid architectural approaches with significant tradeoffs\n- Critical information is missing that cannot be inferred from the codebase\n\nDO NOT ask questions like \"how should I fix this\" or \"what approach do you prefer\" — that defeats the purpose of autonomous task execution. The user has already specified what they want done.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Locate similar implementations or related code\n4. Identify the key areas of the codebase that will be affected\n5. Document your findings to provide context for planning\n6. ONLY if genuinely needed: generate 2-3 specific clarification questions\n</process>\n\n<output_format>\nOutput ONLY the markdown artifact with no preamble:\n\n\\`\\`\\`markdown\n# Research Findings\n\n## Codebase Analysis\n[Brief summary of relevant code structure, patterns, and files]\n\n## Key Areas of Focus\n[List specific files/components that need modification]\n\n## Implementation Context\n[Important patterns, dependencies, or constraints found in the code]\n\n## Clarifying Questions\n[ONLY include this section if it will increase the quality of the plan]\n\n## Question 1: [Specific architectural decision]\n**Options:**\n- a) [Concrete option with file references]\n- b) [Alternative with file references]\n- c) Something else (please specify)\n\\`\\`\\`\n\nFormat requirements:\n- Use \"## Question N:\" for question headers (h2)\n- Follow with \"**Options:**\" on its own line\n- Start options with \"- a)\", \"- b)\", \"- c)\"\n- Always include \"c) Something else (please specify)\"\n- Max
|
|
1
|
+
{"version":3,"file":"research.js","sources":["../../../src/agents/research.ts"],"sourcesContent":["export const RESEARCH_SYSTEM_PROMPT = `<role>\nPostHog AI Research Agent — analyze codebases to understand implementation context and identify areas of focus for development tasks.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n</constraints>\n\n<objective>\nYour PRIMARY goal is to understand the codebase thoroughly and provide context for the planning phase.\n\nONLY generate clarifying questions if:\n- The task description is genuinely vague or ambiguous\n- There are multiple valid architectural approaches with significant tradeoffs\n- Critical information is missing that cannot be inferred from the codebase\n\nDO NOT ask questions like \"how should I fix this\" or \"what approach do you prefer\" — that defeats the purpose of autonomous task execution. The user has already specified what they want done.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Locate similar implementations or related code\n4. Identify the key areas of the codebase that will be affected\n5. Document your findings to provide context for planning\n6. ONLY if genuinely needed: generate 2-3 specific clarification questions\n</process>\n\n<output_format>\nOutput ONLY the markdown artifact with no preamble:\n\n\\`\\`\\`markdown\n# Research Findings\n\n## Codebase Analysis\n[Brief summary of relevant code structure, patterns, and files]\n\n## Key Areas of Focus\n[List specific files/components that need modification]\n\n## Implementation Context\n[Important patterns, dependencies, or constraints found in the code]\n\n## Clarifying Questions\n[ONLY include this section if it will increase the quality of the plan]\n\n## Question 1: [Specific architectural decision]\n**Options:**\n- a) [Concrete option with file references]\n- b) [Alternative with file references]\n- c) Something else (please specify)\n\\`\\`\\`\n\nFormat requirements:\n- Use \"## Question N:\" for question headers (h2)\n- Follow with \"**Options:**\" on its own line\n- Start options with \"- a)\", \"- b)\", \"- c)\"\n- Always include \"c) Something else (please specify)\"\n- Max 4 questions total\n</output_format>\n\n<examples>\n<good_example>\nTask: \"Fix authentication bug in login flow\"\nOutput: Research findings showing auth flow files, patterns used, NO questions needed\n</good_example>\n\n<bad_example>\nTask: \"Fix authentication bug\"\nOutput: \"How should I fix the authentication? a) Fix it one way b) Fix it another way\"\nReason: Don't ask HOW to do the task — that's what the agent is for\n</bad_example>\n\n<good_example>\nTask: \"Add caching to API endpoints\"\nOutput: Research showing existing cache implementations, question about cache backend choice IF multiple production systems are already in use\n</good_example>\n</examples>`;\n\n"],"names":[],"mappings":"AAAO,MAAM,sBAAsB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { CanUseTool, PermissionResult } from '@anthropic-ai/claude-agent-sdk/sdkTypes.js';
|
|
2
|
+
export type { CanUseTool, PermissionResult };
|
|
1
3
|
export interface Task {
|
|
2
4
|
id: string;
|
|
3
5
|
title: string;
|
|
@@ -56,6 +58,7 @@ export interface TaskExecutionOptions {
|
|
|
56
58
|
isCloudMode?: boolean;
|
|
57
59
|
autoProgress?: boolean;
|
|
58
60
|
queryOverrides?: Record<string, any>;
|
|
61
|
+
canUseTool?: CanUseTool;
|
|
59
62
|
}
|
|
60
63
|
interface BaseEvent {
|
|
61
64
|
ts: number;
|
|
@@ -233,6 +236,7 @@ export interface AgentConfig {
|
|
|
233
236
|
posthogMcpUrl?: string;
|
|
234
237
|
mcpServers?: Record<string, McpServerConfig>;
|
|
235
238
|
debug?: boolean;
|
|
239
|
+
canUseTool?: CanUseTool;
|
|
236
240
|
}
|
|
237
241
|
export interface PostHogAPIConfig {
|
|
238
242
|
apiUrl: string;
|
|
@@ -253,5 +257,4 @@ export interface UrlMention {
|
|
|
253
257
|
id?: string;
|
|
254
258
|
label?: string;
|
|
255
259
|
}
|
|
256
|
-
export {};
|
|
257
260
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/src/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,4CAA4C,CAAC;AAC/F,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,CAAC;AAG7C,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,gBAAgB,GAAG,eAAe,GAAG,cAAc,GAAG,eAAe,GAAG,mBAAmB,CAAC;IAC5G,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IAInB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,a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AAG,YAAY,GAAG,SAAS,GAAG,cAAc,GAAG,SAAS,CAAC;AAE3F,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAED,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
|
package/dist/src/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/types.ts"],"sourcesContent":["// PostHog Task model (matches Array's OpenAPI schema)\nexport interface Task {\n id: string;\n title: string;\n description: string;\n origin_product: 'error_tracking' | 'eval_clusters' | 'user_created' | 'support_queue' | 'session_summaries';\n position?: number;\n github_integration?: number | null;\n repository_config?: unknown; // JSONField\n repository_list: string;\n primary_repository: string;\n created_at: string;\n updated_at: string;\n\n // DEPRECATED: These fields have been moved to TaskRun\n // Use task.latest_run instead\n current_stage?: string | null;\n github_branch?: string | null;\n github_pr_url?: string | null;\n latest_run?: TaskRun;\n}\n\n// Log entry structure for TaskRun.log\nexport interface LogEntry {\n type: string; // e.g., \"info\", \"warning\", \"error\", \"success\", \"debug\"\n message: string;\n [key: string]: unknown; // Allow additional fields\n}\n\n// TaskRun model - represents individual execution runs of tasks\nexport interface TaskRun {\n id: string;\n task: string; // Task ID\n team: number;\n branch: string | null;\n status: 'started' | 'in_progress' | 'completed' | 'failed';\n log: LogEntry[]; // Array of log entry objects\n error_message: string | null;\n output: Record<string, unknown> | null; // Structured output (PR URL, commit SHA, etc.)\n state: Record<string, unknown>; // Intermediate run state (defaults to {}, never null)\n created_at: string;\n updated_at: string;\n completed_at: string | null;\n}\n\nexport interface SupportingFile {\n name: string;\n content: string;\n type: 'plan' | 'context' | 'reference' | 'output';\n created_at: string;\n}\n\nexport enum PermissionMode {\n PLAN = \"plan\",\n DEFAULT = \"default\",\n ACCEPT_EDITS = \"acceptEdits\",\n BYPASS = \"bypassPermissions\"\n}\n\nexport interface ExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n}\n\nexport interface TaskExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n isCloudMode?: boolean; // Determines local vs cloud behavior (local pauses after each phase)\n autoProgress?: boolean;\n queryOverrides?: Record<string, any>;\n}\n\n// Base event with timestamp\ninterface BaseEvent {\n ts: number;\n}\n\n// Streaming content events\nexport interface TokenEvent extends BaseEvent {\n type: 'token';\n content: string;\n contentType?: 'text' | 'thinking' | 'tool_input';\n}\n\nexport interface ContentBlockStartEvent extends BaseEvent {\n type: 'content_block_start';\n index: number;\n contentType: 'text' | 'tool_use' | 'thinking';\n toolName?: string;\n toolId?: string;\n}\n\nexport interface ContentBlockStopEvent extends BaseEvent {\n type: 'content_block_stop';\n index: number;\n}\n\n// Tool events\nexport interface ToolCallEvent extends BaseEvent {\n type: 'tool_call';\n toolName: string;\n callId: string;\n args: Record<string, any>;\n parentToolUseId?: string | null; // For nested tool calls (subagents)\n // Tool metadata (enriched by adapter for UI consumption)\n tool?: import('./tools/types.js').Tool;\n category?: import('./tools/types.js').ToolCategory;\n}\n\nexport interface ToolResultEvent extends BaseEvent {\n type: 'tool_result';\n toolName: string;\n callId: string;\n result: any;\n isError?: boolean; // Whether the tool execution failed\n parentToolUseId?: string | null; // For nested tool calls (subagents)\n // Tool metadata (enriched by adapter for UI consumption)\n tool?: import('./tools/types.js').Tool;\n category?: import('./tools/types.js').ToolCategory;\n}\n\n// Message lifecycle events\nexport interface MessageStartEvent extends BaseEvent {\n type: 'message_start';\n messageId?: string;\n model?: string;\n}\n\nexport interface MessageDeltaEvent extends BaseEvent {\n type: 'message_delta';\n stopReason?: string;\n stopSequence?: string;\n usage?: {\n outputTokens: number;\n };\n}\n\nexport interface MessageStopEvent extends BaseEvent {\n type: 'message_stop';\n}\n\n// User message events\nexport interface UserMessageEvent extends BaseEvent {\n type: 'user_message';\n content: string;\n isSynthetic?: boolean;\n}\n\n// System events\nexport interface StatusEvent extends BaseEvent {\n type: 'status';\n phase: string;\n // Common optional fields (varies by phase):\n kind?: string; // Kind of status (plan, implementation)\n branch?: string; // Git branch name\n prUrl?: string; // Pull request URL\n taskId?: string; // Task identifier\n messageId?: string; // Claude message ID\n model?: string; // Model name\n [key: string]: any; // Allow additional fields\n}\n\nexport interface InitEvent extends BaseEvent {\n type: 'init';\n model: string;\n tools: string[];\n permissionMode: string;\n cwd: string;\n apiKeySource: string;\n agents?: string[];\n slashCommands?: string[];\n outputStyle?: string;\n mcpServers?: Array<{ name: string; status: string }>;\n}\n\nexport interface CompactBoundaryEvent extends BaseEvent {\n type: 'compact_boundary';\n trigger: 'manual' | 'auto';\n preTokens: number;\n}\n\n// Result events\nexport interface DoneEvent extends BaseEvent {\n type: 'done';\n result?: string; // Final summary text from Claude\n durationMs?: number;\n durationApiMs?: number; // API-only duration (excluding local processing)\n numTurns?: number;\n totalCostUsd?: number;\n usage?: any;\n modelUsage?: { // Per-model usage breakdown\n [modelName: string]: {\n inputTokens: number;\n outputTokens: number;\n cacheReadInputTokens: number;\n cacheCreationInputTokens: number;\n webSearchRequests: number;\n costUSD: number;\n contextWindow: number;\n };\n };\n permissionDenials?: Array<{ // Tools that were denied by permissions\n tool_name: string;\n tool_use_id: string;\n tool_input: Record<string, unknown>;\n }>;\n}\n\nexport interface ErrorEvent extends BaseEvent {\n type: 'error';\n message: string;\n error?: any;\n errorType?: string;\n context?: Record<string, any>; // Partial error context for debugging\n sdkError?: any; // Original SDK error object\n}\n\n// Metric and artifact events (general purpose, not tool-specific)\nexport interface MetricEvent extends BaseEvent {\n type: 'metric';\n key: string;\n value: number;\n unit?: string;\n}\n\nexport interface ArtifactEvent extends BaseEvent {\n type: 'artifact';\n kind: string;\n content: any;\n}\n\nexport interface RawSDKEvent extends BaseEvent {\n type: 'raw_sdk_event';\n sdkMessage: any; // Full SDK message for debugging\n}\n\nexport type AgentEvent =\n | TokenEvent\n | ContentBlockStartEvent\n | ContentBlockStopEvent\n | ToolCallEvent\n | ToolResultEvent\n | MessageStartEvent\n | MessageDeltaEvent\n | MessageStopEvent\n | UserMessageEvent\n | StatusEvent\n | InitEvent\n | CompactBoundaryEvent\n | DoneEvent\n | ErrorEvent\n | MetricEvent\n | ArtifactEvent\n | RawSDKEvent;\n\nexport interface ExecutionResult {\n results: any[];\n}\n\nexport interface PlanResult {\n plan: string;\n}\n\nexport interface TaskExecutionResult {\n task: Task;\n plan?: string;\n executionResult?: ExecutionResult;\n}\n\n// MCP Server configuration types (re-exported from Claude SDK for convenience)\nexport type McpServerConfig = {\n type?: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n} | {\n type: 'sse';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'http';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'sdk';\n name: string;\n instance?: any; // McpServer instance\n};\n\nexport interface AgentConfig {\n workingDirectory?: string;\n onEvent?: (event: AgentEvent) => void;\n\n // PostHog API configuration\n posthogApiUrl?: string;\n posthogApiKey?: string;\n\n // PostHog MCP configuration\n posthogMcpUrl?: string;\n\n // MCP Server configuration\n // Additional MCP servers (PostHog MCP is always included by default)\n // You can override the PostHog MCP config by providing mcpServers.posthog\n mcpServers?: Record<string, McpServerConfig>;\n\n // Logging configuration\n debug?: boolean;\n}\n\nexport interface PostHogAPIConfig {\n apiUrl: string;\n apiKey: string;\n}\n\n// URL mention types\nexport type ResourceType = 'error' | 'experiment' | 'insight' | 'feature_flag' | 'generic';\n\nexport interface PostHogResource {\n type: ResourceType;\n id: string;\n url: string;\n title?: string;\n content: string;\n metadata?: Record<string, any>;\n}\n\nexport interface UrlMention {\n url: string;\n type: ResourceType;\n id?: string;\n label?: string;\n}"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/types.ts"],"sourcesContent":["\n// import and export to keep a single type file\nimport type { CanUseTool, PermissionResult } from '@anthropic-ai/claude-agent-sdk/sdkTypes.js';\nexport type { CanUseTool, PermissionResult };\n\n// PostHog Task model (matches Array's OpenAPI schema)\nexport interface Task {\n id: string;\n title: string;\n description: string;\n origin_product: 'error_tracking' | 'eval_clusters' | 'user_created' | 'support_queue' | 'session_summaries';\n position?: number;\n github_integration?: number | null;\n repository_config?: unknown; // JSONField\n repository_list: string;\n primary_repository: string;\n created_at: string;\n updated_at: string;\n\n // DEPRECATED: These fields have been moved to TaskRun\n // Use task.latest_run instead\n current_stage?: string | null;\n github_branch?: string | null;\n github_pr_url?: string | null;\n latest_run?: TaskRun;\n}\n\n// Log entry structure for TaskRun.log\nexport interface LogEntry {\n type: string; // e.g., \"info\", \"warning\", \"error\", \"success\", \"debug\"\n message: string;\n [key: string]: unknown; // Allow additional fields\n}\n\n// TaskRun model - represents individual execution runs of tasks\nexport interface TaskRun {\n id: string;\n task: string; // Task ID\n team: number;\n branch: string | null;\n status: 'started' | 'in_progress' | 'completed' | 'failed';\n log: LogEntry[]; // Array of log entry objects\n error_message: string | null;\n output: Record<string, unknown> | null; // Structured output (PR URL, commit SHA, etc.)\n state: Record<string, unknown>; // Intermediate run state (defaults to {}, never null)\n created_at: string;\n updated_at: string;\n completed_at: string | null;\n}\n\nexport interface SupportingFile {\n name: string;\n content: string;\n type: 'plan' | 'context' | 'reference' | 'output';\n created_at: string;\n}\n\nexport enum PermissionMode {\n PLAN = \"plan\",\n DEFAULT = \"default\",\n ACCEPT_EDITS = \"acceptEdits\",\n BYPASS = \"bypassPermissions\"\n}\n\nexport interface ExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n}\n\nexport interface TaskExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n isCloudMode?: boolean; // Determines local vs cloud behavior (local pauses after each phase)\n autoProgress?: boolean;\n queryOverrides?: Record<string, any>;\n // Fine-grained permission control (only applied to build phase)\n // See: https://docs.claude.com/en/api/agent-sdk/permissions\n canUseTool?: CanUseTool;\n}\n\n// Base event with timestamp\ninterface BaseEvent {\n ts: number;\n}\n\n// Streaming content events\nexport interface TokenEvent extends BaseEvent {\n type: 'token';\n content: string;\n contentType?: 'text' | 'thinking' | 'tool_input';\n}\n\nexport interface ContentBlockStartEvent extends BaseEvent {\n type: 'content_block_start';\n index: number;\n contentType: 'text' | 'tool_use' | 'thinking';\n toolName?: string;\n toolId?: string;\n}\n\nexport interface ContentBlockStopEvent extends BaseEvent {\n type: 'content_block_stop';\n index: number;\n}\n\n// Tool events\nexport interface ToolCallEvent extends BaseEvent {\n type: 'tool_call';\n toolName: string;\n callId: string;\n args: Record<string, any>;\n parentToolUseId?: string | null; // For nested tool calls (subagents)\n // Tool metadata (enriched by adapter for UI consumption)\n tool?: import('./tools/types.js').Tool;\n category?: import('./tools/types.js').ToolCategory;\n}\n\nexport interface ToolResultEvent extends BaseEvent {\n type: 'tool_result';\n toolName: string;\n callId: string;\n result: any;\n isError?: boolean; // Whether the tool execution failed\n parentToolUseId?: string | null; // For nested tool calls (subagents)\n // Tool metadata (enriched by adapter for UI consumption)\n tool?: import('./tools/types.js').Tool;\n category?: import('./tools/types.js').ToolCategory;\n}\n\n// Message lifecycle events\nexport interface MessageStartEvent extends BaseEvent {\n type: 'message_start';\n messageId?: string;\n model?: string;\n}\n\nexport interface MessageDeltaEvent extends BaseEvent {\n type: 'message_delta';\n stopReason?: string;\n stopSequence?: string;\n usage?: {\n outputTokens: number;\n };\n}\n\nexport interface MessageStopEvent extends BaseEvent {\n type: 'message_stop';\n}\n\n// User message events\nexport interface UserMessageEvent extends BaseEvent {\n type: 'user_message';\n content: string;\n isSynthetic?: boolean;\n}\n\n// System events\nexport interface StatusEvent extends BaseEvent {\n type: 'status';\n phase: string;\n // Common optional fields (varies by phase):\n kind?: string; // Kind of status (plan, implementation)\n branch?: string; // Git branch name\n prUrl?: string; // Pull request URL\n taskId?: string; // Task identifier\n messageId?: string; // Claude message ID\n model?: string; // Model name\n [key: string]: any; // Allow additional fields\n}\n\nexport interface InitEvent extends BaseEvent {\n type: 'init';\n model: string;\n tools: string[];\n permissionMode: string;\n cwd: string;\n apiKeySource: string;\n agents?: string[];\n slashCommands?: string[];\n outputStyle?: string;\n mcpServers?: Array<{ name: string; status: string }>;\n}\n\nexport interface CompactBoundaryEvent extends BaseEvent {\n type: 'compact_boundary';\n trigger: 'manual' | 'auto';\n preTokens: number;\n}\n\n// Result events\nexport interface DoneEvent extends BaseEvent {\n type: 'done';\n result?: string; // Final summary text from Claude\n durationMs?: number;\n durationApiMs?: number; // API-only duration (excluding local processing)\n numTurns?: number;\n totalCostUsd?: number;\n usage?: any;\n modelUsage?: { // Per-model usage breakdown\n [modelName: string]: {\n inputTokens: number;\n outputTokens: number;\n cacheReadInputTokens: number;\n cacheCreationInputTokens: number;\n webSearchRequests: number;\n costUSD: number;\n contextWindow: number;\n };\n };\n permissionDenials?: Array<{ // Tools that were denied by permissions\n tool_name: string;\n tool_use_id: string;\n tool_input: Record<string, unknown>;\n }>;\n}\n\nexport interface ErrorEvent extends BaseEvent {\n type: 'error';\n message: string;\n error?: any;\n errorType?: string;\n context?: Record<string, any>; // Partial error context for debugging\n sdkError?: any; // Original SDK error object\n}\n\n// Metric and artifact events (general purpose, not tool-specific)\nexport interface MetricEvent extends BaseEvent {\n type: 'metric';\n key: string;\n value: number;\n unit?: string;\n}\n\nexport interface ArtifactEvent extends BaseEvent {\n type: 'artifact';\n kind: string;\n content: any;\n}\n\nexport interface RawSDKEvent extends BaseEvent {\n type: 'raw_sdk_event';\n sdkMessage: any; // Full SDK message for debugging\n}\n\nexport type AgentEvent =\n | TokenEvent\n | ContentBlockStartEvent\n | ContentBlockStopEvent\n | ToolCallEvent\n | ToolResultEvent\n | MessageStartEvent\n | MessageDeltaEvent\n | MessageStopEvent\n | UserMessageEvent\n | StatusEvent\n | InitEvent\n | CompactBoundaryEvent\n | DoneEvent\n | ErrorEvent\n | MetricEvent\n | ArtifactEvent\n | RawSDKEvent;\n\nexport interface ExecutionResult {\n results: any[];\n}\n\nexport interface PlanResult {\n plan: string;\n}\n\nexport interface TaskExecutionResult {\n task: Task;\n plan?: string;\n executionResult?: ExecutionResult;\n}\n\n// MCP Server configuration types (re-exported from Claude SDK for convenience)\nexport type McpServerConfig = {\n type?: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n} | {\n type: 'sse';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'http';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'sdk';\n name: string;\n instance?: any; // McpServer instance\n};\n\nexport interface AgentConfig {\n workingDirectory?: string;\n onEvent?: (event: AgentEvent) => void;\n\n // PostHog API configuration\n posthogApiUrl?: string;\n posthogApiKey?: string;\n\n // PostHog MCP configuration\n posthogMcpUrl?: string;\n\n // MCP Server configuration\n // Additional MCP servers (PostHog MCP is always included by default)\n // You can override the PostHog MCP config by providing mcpServers.posthog\n mcpServers?: Record<string, McpServerConfig>;\n\n // Logging configuration\n debug?: boolean;\n\n // Fine-grained permission control for direct run() calls\n // See: https://docs.claude.com/en/api/agent-sdk/permissions\n canUseTool?: CanUseTool;\n}\n\nexport interface PostHogAPIConfig {\n apiUrl: string;\n apiKey: string;\n}\n\n// URL mention types\nexport type ResourceType = 'error' | 'experiment' | 'insight' | 'feature_flag' | 'generic';\n\nexport interface PostHogResource {\n type: ResourceType;\n id: string;\n url: string;\n title?: string;\n content: string;\n metadata?: Record<string, any>;\n}\n\nexport interface UrlMention {\n url: string;\n type: ResourceType;\n id?: string;\n label?: string;\n}"],"names":[],"mappings":"IAyDY;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,cAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,cAAA,CAAA,cAAA,CAAA,GAAA,aAA4B;AAC5B,IAAA,cAAA,CAAA,QAAA,CAAA,GAAA,mBAA4B;AAC9B,CAAC,EALW,cAAc,KAAd,cAAc,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,SAAS,EAAE,
|
|
1
|
+
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,SAAS,EAAE,kBAuGvB,CAAC"}
|
|
@@ -29,7 +29,29 @@ const buildStep = async ({ step, context }) => {
|
|
|
29
29
|
permissionMode: configuredPermissionMode,
|
|
30
30
|
settingSources: ['local'],
|
|
31
31
|
mcpServers,
|
|
32
|
+
// Allow all tools for build phase - full read/write access needed for implementation
|
|
33
|
+
allowedTools: [
|
|
34
|
+
'Task',
|
|
35
|
+
'Bash',
|
|
36
|
+
'BashOutput',
|
|
37
|
+
'KillBash',
|
|
38
|
+
'Edit',
|
|
39
|
+
'Read',
|
|
40
|
+
'Write',
|
|
41
|
+
'Glob',
|
|
42
|
+
'Grep',
|
|
43
|
+
'NotebookEdit',
|
|
44
|
+
'WebFetch',
|
|
45
|
+
'WebSearch',
|
|
46
|
+
'ListMcpResources',
|
|
47
|
+
'ReadMcpResource',
|
|
48
|
+
'TodoWrite',
|
|
49
|
+
],
|
|
32
50
|
};
|
|
51
|
+
// Add fine-grained permission hook if provided
|
|
52
|
+
if (options.canUseTool) {
|
|
53
|
+
baseOptions.canUseTool = options.canUseTool;
|
|
54
|
+
}
|
|
33
55
|
const response = query({
|
|
34
56
|
prompt: fullPrompt,
|
|
35
57
|
options: { ...baseOptions, ...(options.queryOverrides || {}) },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n }\n\n const hasChanges = await gitManager.hasChanges();\n context.stepResults[step.id] = { commitCreated: false };\n if (!hasChanges) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n }\n\n await gitManager.addFiles(['.']);\n const commitCreated = await finalizeStepGitActions(context, step, {\n commitMessage: `Implementation for ${task.title}`,\n });\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No commit created during build step', { taskId: task.id });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;;AAMO,MAAM,SAAS,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACrE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,OAAO,EACP,MAAM,EACN,aAAa,EACb,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC;AAE5C,IAAA,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU;IACjC,MAAM,QAAQ,GACV,SAAS,EAAE,MAAM,IAAI,OAAO,SAAS,CAAC,MAAM,KAAK;AAC7C,UAAG,SAAS,CAAC,MAAc,CAAC;UAC1B,IAAI;IAEd,IAAI,QAAQ,EAAE;AACV,QAAA,UAAU,CAAC,IAAI,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC/E,QAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;IAChC;AAEA,IAAA,UAAU,CAAC,IAAI,CAAC,sBAAsB,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC5D,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,aAAa,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAEvE,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,oBAAoB,CAAC,IAAI,EAAE,GAAG,CAAC;AAC3E,IAAA,MAAM,UAAU,GAAG,CAAA,EAAG,uBAAuB,CAAA,IAAA,EAAO,eAAe,EAAE;AAErE,IAAA,MAAM,wBAAwB,GAC1B,OAAO,CAAC,cAAc;AACtB,SAAC,OAAO,IAAI,CAAC,cAAc,KAAK;cACzB,IAAI,CAAC;AACR,cAAE,IAAI,CAAC,cAAc,CAAC;QAC1B,cAAc,CAAC,YAAY;AAE/B,IAAA,MAAM,WAAW,GAAwB;QACrC,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,GAAG;AACH,QAAA,cAAc,EAAE,wBAAwB;QACxC,cAAc,EAAE,CAAC,OAAO,CAAC;QACzB,UAAU;
|
|
1
|
+
{"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n // Allow all tools for build phase - full read/write access needed for implementation\n allowedTools: [\n 'Task',\n 'Bash',\n 'BashOutput',\n 'KillBash',\n 'Edit',\n 'Read',\n 'Write',\n 'Glob',\n 'Grep',\n 'NotebookEdit',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n ],\n };\n\n // Add fine-grained permission hook if provided\n if (options.canUseTool) {\n baseOptions.canUseTool = options.canUseTool;\n }\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n }\n\n const hasChanges = await gitManager.hasChanges();\n context.stepResults[step.id] = { commitCreated: false };\n if (!hasChanges) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n }\n\n await gitManager.addFiles(['.']);\n const commitCreated = await finalizeStepGitActions(context, step, {\n commitMessage: `Implementation for ${task.title}`,\n });\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No commit created during build step', { taskId: task.id });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;;AAMO,MAAM,SAAS,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACrE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,OAAO,EACP,MAAM,EACN,aAAa,EACb,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,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pD,KAAA,CAAC;IACF,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,aAAa,EAAE;IAEhD,IAAI,CAAC,aAAa,EAAE;AAChB,QAAA,UAAU,CAAC,IAAI,CAAC,qCAAqC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC/E;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/plan.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,QAAQ,EAAE,
|
|
1
|
+
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/plan.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,QAAQ,EAAE,kBAuHtB,CAAC"}
|
|
@@ -46,6 +46,19 @@ const planStep = async ({ step, context }) => {
|
|
|
46
46
|
permissionMode: 'plan',
|
|
47
47
|
settingSources: ['local'],
|
|
48
48
|
mcpServers,
|
|
49
|
+
// Allow research tools: read-only operations, web search, MCP resources, and ExitPlanMode
|
|
50
|
+
allowedTools: [
|
|
51
|
+
'Read',
|
|
52
|
+
'Glob',
|
|
53
|
+
'Grep',
|
|
54
|
+
'WebFetch',
|
|
55
|
+
'WebSearch',
|
|
56
|
+
'ListMcpResources',
|
|
57
|
+
'ReadMcpResource',
|
|
58
|
+
'ExitPlanMode',
|
|
59
|
+
'TodoWrite',
|
|
60
|
+
'BashOutput',
|
|
61
|
+
],
|
|
49
62
|
};
|
|
50
63
|
const response = query({
|
|
51
64
|
prompt: fullPrompt,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","sources":["../../../../src/workflow/steps/plan.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { PLANNING_SYSTEM_PROMPT } from '../../agents/planning.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const planStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('PlanStep');\n\n const existingPlan = await fileManager.readPlan(task.id);\n if (existingPlan) {\n stepLogger.info('Plan already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n const questionsData = await fileManager.readQuestions(task.id);\n if (!questionsData || !questionsData.answered) {\n stepLogger.info('Waiting for answered research questions', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research_questions' }));\n return { status: 'skipped', halt: true };\n }\n\n stepLogger.info('Starting planning phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'planning' }));\n\n const researchContent = await fileManager.readResearch(task.id);\n let researchContext = '';\n if (researchContent) {\n researchContext += `## Research Analysis\\n\\n${researchContent}\\n\\n`;\n }\n\n researchContext += `## Implementation Decisions\\n\\n`;\n for (const question of questionsData.questions) {\n const answer = questionsData.answers?.find(\n (a: any) => a.questionId === question.id\n );\n\n researchContext += `### ${question.question}\\n\\n`;\n if (answer) {\n researchContext += `**Selected:** ${answer.selectedOption}\\n`;\n if (answer.customInput) {\n researchContext += `**Details:** ${answer.customInput}\\n`;\n }\n } else {\n researchContext += `**Selected:** Not answered\\n`;\n }\n researchContext += `\\n`;\n }\n\n const planningPrompt = await promptBuilder.buildPlanningPrompt(task, cwd);\n const fullPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${planningPrompt}\\n\\n${researchContext}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n let planContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n if (message.type === 'assistant' && message.message?.content) {\n for (const c of message.message.content) {\n if (c.type === 'text' && c.text) {\n planContent += `${c.text}\\n`;\n }\n }\n }\n }\n\n if (planContent.trim()) {\n await fileManager.writePlan(task.id, planContent.trim());\n stepLogger.info('Plan completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Planning phase for ${task.title}`,\n });\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed', halt: true };\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAKO,MAAM,QAAQ,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACpE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,WAAW,EACX,OAAO,EACP,MAAM,EACN,WAAW,EACX,UAAU,EACV,aAAa,EACb,OAAO,EACP,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;IAE3C,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IACxD,IAAI,YAAY,EAAE;AACd,QAAA,UAAU,CAAC,IAAI,CAAC,oCAAoC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC1E,QAAA,OAAO,EAAE,M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AAc,IAAI;AAC7D,YAAA,IAAI,MAAM,CAAC,WAAW,EAAE;AACpB,gBAAA,eAAe,IAAI,CAAA,aAAA,EAAgB,MAAM,CAAC,WAAW,IAAI;YAC7D;QACJ;aAAO;YACH,eAAe,IAAI,8BAA8B;QACrD;QACA,eAAe,IAAI,IAAI;IAC3B;IAEA,MAAM,cAAc,GAAG,MAAM,aAAa,CAAC,mBAAmB,CAAC,IAAI,EAAE,GAAG,CAAC;IACzE,MAAM,UAAU,GAAG,CAAA,EAAG,sBAAsB,OAAO,cAAc,CAAA,IAAA,EAAO,eAAe,CAAA,CAAE;AAEzF,IAAA,MAAM,WAAW,GAAwB;QACrC,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,GAAG;AACH,QAAA,cAAc,EAAE,MAAM;QACtB,cAAc,EAAE,CAAC,OAAO,CAAC;QACzB,UAAU;
|
|
1
|
+
{"version":3,"file":"plan.js","sources":["../../../../src/workflow/steps/plan.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { PLANNING_SYSTEM_PROMPT } from '../../agents/planning.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const planStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('PlanStep');\n\n const existingPlan = await fileManager.readPlan(task.id);\n if (existingPlan) {\n stepLogger.info('Plan already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n const questionsData = await fileManager.readQuestions(task.id);\n if (!questionsData || !questionsData.answered) {\n stepLogger.info('Waiting for answered research questions', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research_questions' }));\n return { status: 'skipped', halt: true };\n }\n\n stepLogger.info('Starting planning phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'planning' }));\n\n const researchContent = await fileManager.readResearch(task.id);\n let researchContext = '';\n if (researchContent) {\n researchContext += `## Research Analysis\\n\\n${researchContent}\\n\\n`;\n }\n\n researchContext += `## Implementation Decisions\\n\\n`;\n for (const question of questionsData.questions) {\n const answer = questionsData.answers?.find(\n (a: any) => a.questionId === question.id\n );\n\n researchContext += `### ${question.question}\\n\\n`;\n if (answer) {\n researchContext += `**Selected:** ${answer.selectedOption}\\n`;\n if (answer.customInput) {\n researchContext += `**Details:** ${answer.customInput}\\n`;\n }\n } else {\n researchContext += `**Selected:** Not answered\\n`;\n }\n researchContext += `\\n`;\n }\n\n const planningPrompt = await promptBuilder.buildPlanningPrompt(task, cwd);\n const fullPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${planningPrompt}\\n\\n${researchContext}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n // Allow research tools: read-only operations, web search, MCP resources, and ExitPlanMode\n allowedTools: [\n 'Read',\n 'Glob',\n 'Grep',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'ExitPlanMode',\n 'TodoWrite',\n 'BashOutput',\n ],\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n let planContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n if (message.type === 'assistant' && message.message?.content) {\n for (const c of message.message.content) {\n if (c.type === 'text' && c.text) {\n planContent += `${c.text}\\n`;\n }\n }\n }\n }\n\n if (planContent.trim()) {\n await fileManager.writePlan(task.id, planContent.trim());\n stepLogger.info('Plan completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Planning phase for ${task.title}`,\n });\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed', halt: true };\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAKO,MAAM,QAAQ,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACpE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,WAAW,EACX,OAAO,EACP,MAAM,EACN,WAAW,EACX,UAAU,EACV,aAAa,EACb,OAAO,EACP,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;IAE3C,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IACxD,IAAI,YAAY,EAAE;AACd,QAAA,UAAU,CAAC,IAAI,CAAC,oCAAoC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC1E,QAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;IAChC;IAEA,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;IAC9D,IAAI,CAAC,aAAa,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE;AAC3C,QAAA,UAAU,CAAC,IAAI,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC/E,QAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC,CAAC;QACvF,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE;IAC5C;AAEA,IAAA,UAAU,CAAC,IAAI,CAAC,yBAAyB,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC/D,IAAA,SAAS,CAAC,OAAO,C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,aAAa,EAAE,CAAA,mBAAA,EAAsB,IAAI,CAAC,KAAK,CAAA,CAAE;AACpD,KAAA,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE;AACd,QAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;QAC7E,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE;IAC9C;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;AAC7E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"research.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/research.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"research.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/research.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,YAAY,EAAE,kBAiK1B,CAAC"}
|
|
@@ -20,6 +20,18 @@ const researchStep = async ({ step, context }) => {
|
|
|
20
20
|
permissionMode: 'plan',
|
|
21
21
|
settingSources: ['local'],
|
|
22
22
|
mcpServers,
|
|
23
|
+
// Allow research tools: read-only operations, web search, and MCP resources
|
|
24
|
+
allowedTools: [
|
|
25
|
+
'Read',
|
|
26
|
+
'Glob',
|
|
27
|
+
'Grep',
|
|
28
|
+
'WebFetch',
|
|
29
|
+
'WebSearch',
|
|
30
|
+
'ListMcpResources',
|
|
31
|
+
'ReadMcpResource',
|
|
32
|
+
'TodoWrite',
|
|
33
|
+
'BashOutput',
|
|
34
|
+
],
|
|
23
35
|
};
|
|
24
36
|
const response = query({
|
|
25
37
|
prompt: fullPrompt,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"research.js","sources":["../../../../src/workflow/steps/research.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { RESEARCH_SYSTEM_PROMPT } from '../../agents/research.js';\nimport type { ExtractedQuestionWithAnswer } from '../../structured-extraction.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const researchStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n extractor,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('ResearchStep');\n\n const existingResearch = await fileManager.readResearch(task.id);\n if (existingResearch) {\n stepLogger.info('Research already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting research phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'research' }));\n\n const researchPrompt = await promptBuilder.buildResearchPrompt(task, cwd);\n const fullPrompt = `${RESEARCH_SYSTEM_PROMPT}\\n\\n${researchPrompt}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n let researchContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n if (message.type === 'assistant' && message.message?.content) {\n for (const c of message.message.content) {\n if (c.type === 'text' && c.text) {\n researchContent += `${c.text}\\n`;\n }\n }\n }\n }\n\n if (researchContent.trim()) {\n await fileManager.writeResearch(task.id, researchContent.trim());\n stepLogger.info('Research completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Research phase for ${task.title}`,\n });\n\n if (extractor && researchContent.trim()) {\n try {\n stepLogger.info('Extracting questions from research.md', { taskId: task.id });\n const parsedQuestions = await extractor.extractQuestions(researchContent);\n\n await fileManager.writeQuestions(task.id, {\n questions: parsedQuestions,\n answered: false,\n answers: null,\n });\n\n emitEvent({\n type: 'artifact',\n ts: Date.now(),\n kind: 'research_questions',\n content: parsedQuestions,\n });\n\n stepLogger.info('Questions extracted successfully', {\n taskId: task.id,\n count: parsedQuestions.length,\n });\n } catch (error) {\n stepLogger.error('Failed to extract questions', {\n taskId: task.id,\n error: error instanceof Error ? error.message : String(error),\n });\n emitEvent({\n type: 'error',\n ts: Date.now(),\n message: `Failed to extract questions: ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n } else if (!extractor) {\n stepLogger.warn(\n 'Question extractor not available, skipping question extraction. Ensure LLM gateway is configured.'\n );\n emitEvent({\n type: 'status',\n ts: Date.now(),\n phase: 'extraction_skipped',\n message: 'Question extraction skipped - extractor not configured',\n });\n }\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research' }));\n return { status: 'completed', halt: true };\n }\n\n const questionsData = await fileManager.readQuestions(task.id);\n if (questionsData && !questionsData.answered && extractor && researchContent.trim()) {\n const researchQuestions = await extractor.extractQuestionsWithAnswers(researchContent);\n const answers = (researchQuestions as ExtractedQuestionWithAnswer[]).map((qa) => ({\n questionId: qa.id,\n selectedOption: qa.recommendedAnswer,\n customInput: qa.justification,\n }));\n\n await fileManager.writeQuestions(task.id, {\n questions: researchQuestions.map((qa) => ({\n id: qa.id,\n question: qa.question,\n options: qa.options,\n })),\n answered: true,\n answers,\n });\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Answer research questions for ${task.title}`,\n });\n stepLogger.info('Auto-answered research questions', { taskId: task.id });\n }\n\n emitEvent(adapter.createStatusEvent('phase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,EAAE,IAAI,EAAE;AACxC,YAAA,aAAa,EAAE,CAAA,8BAAA,EAAiC,IAAI,CAAC,KAAK,CAAA,CAAE;AAC/D,SAAA,CAAC;AACF,QAAA,UAAU,CAAC,IAAI,CAAC,kCAAkC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC5E;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;AAC7E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
|
|
1
|
+
{"version":3,"file":"research.js","sources":["../../../../src/workflow/steps/research.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { RESEARCH_SYSTEM_PROMPT } from '../../agents/research.js';\nimport type { ExtractedQuestionWithAnswer } from '../../structured-extraction.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const researchStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n extractor,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('ResearchStep');\n\n const existingResearch = await fileManager.readResearch(task.id);\n if (existingResearch) {\n stepLogger.info('Research already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting research phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'research' }));\n\n const researchPrompt = await promptBuilder.buildResearchPrompt(task, cwd);\n const fullPrompt = `${RESEARCH_SYSTEM_PROMPT}\\n\\n${researchPrompt}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n // Allow research tools: read-only operations, web search, and MCP resources\n allowedTools: [\n 'Read',\n 'Glob',\n 'Grep',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n 'BashOutput',\n ],\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n let researchContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n if (message.type === 'assistant' && message.message?.content) {\n for (const c of message.message.content) {\n if (c.type === 'text' && c.text) {\n researchContent += `${c.text}\\n`;\n }\n }\n }\n }\n\n if (researchContent.trim()) {\n await fileManager.writeResearch(task.id, researchContent.trim());\n stepLogger.info('Research completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Research phase for ${task.title}`,\n });\n\n if (extractor && researchContent.trim()) {\n try {\n stepLogger.info('Extracting questions from research.md', { taskId: task.id });\n const parsedQuestions = await extractor.extractQuestions(researchContent);\n\n await fileManager.writeQuestions(task.id, {\n questions: parsedQuestions,\n answered: false,\n answers: null,\n });\n\n emitEvent({\n type: 'artifact',\n ts: Date.now(),\n kind: 'research_questions',\n content: parsedQuestions,\n });\n\n stepLogger.info('Questions extracted successfully', {\n taskId: task.id,\n count: parsedQuestions.length,\n });\n } catch (error) {\n stepLogger.error('Failed to extract questions', {\n taskId: task.id,\n error: error instanceof Error ? error.message : String(error),\n });\n emitEvent({\n type: 'error',\n ts: Date.now(),\n message: `Failed to extract questions: ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n } else if (!extractor) {\n stepLogger.warn(\n 'Question extractor not available, skipping question extraction. Ensure LLM gateway is configured.'\n );\n emitEvent({\n type: 'status',\n ts: Date.now(),\n phase: 'extraction_skipped',\n message: 'Question extraction skipped - extractor not configured',\n });\n }\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research' }));\n return { status: 'completed', halt: true };\n }\n\n const questionsData = await fileManager.readQuestions(task.id);\n if (questionsData && !questionsData.answered && extractor && researchContent.trim()) {\n const researchQuestions = await extractor.extractQuestionsWithAnswers(researchContent);\n const answers = (researchQuestions as ExtractedQuestionWithAnswer[]).map((qa) => ({\n questionId: qa.id,\n selectedOption: qa.recommendedAnswer,\n customInput: qa.justification,\n }));\n\n await fileManager.writeQuestions(task.id, {\n questions: researchQuestions.map((qa) => ({\n id: qa.id,\n question: qa.question,\n options: qa.options,\n })),\n answered: true,\n answers,\n });\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Answer research questions for ${task.title}`,\n });\n stepLogger.info('Auto-answered research questions', { taskId: task.id });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAMO,MAAM,YAAY,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACxE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,WAAW,EACX,OAAO,EACP,MAAM,EACN,WAAW,EACX,UAAU,EACV,aAAa,EACb,OAAO,EACP,UAAU,EACV,SAAS,EACT,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC;IAE/C,MAAM,gBAAgB,GAAG,MAAM,WAAW,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;IAChE,IAAI,gBAAgB,EAAE;AAClB,QAAA,UAAU,CAAC,IAAI,CAAC,wCAAwC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC9E,QAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;IAChC;AAEA,IAAA,UAAU,CAAC,IAAI,CAAC,yBAAyB,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC/D,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,aAAa,EAAE,EAAE,KAA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O,GAAI,iBAAmD,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM;YAC9E,UAAU,EAAE,EAAE,CAAC,EAAE;YACjB,cAAc,EAAE,EAAE,CAAC,iBAAiB;YACpC,WAAW,EAAE,EAAE,CAAC,aAAa;AAChC,SAAA,CAAC,CAAC;AAEH,QAAA,MAAM,WAAW,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,EAAE;YACtC,SAAS,EAAE,iBAAiB,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM;gBACtC,EAAE,EAAE,EAAE,CAAC,EAAE;gBACT,QAAQ,EAAE,EAAE,CAAC,QAAQ;gBACrB,OAAO,EAAE,EAAE,CAAC,OAAO;AACtB,aAAA,CAAC,CAAC;AACH,YAAA,QAAQ,EAAE,IAAI;YACd,OAAO;AACV,SAAA,CAAC;AAEF,QAAA,MAAM,UAAU,CAAC,kBAAkB,EAAE;AACrC,QAAA,MAAM,sBAAsB,CAAC,OAAO,EAAE,IAAI,EAAE;AACxC,YAAA,aAAa,EAAE,CAAA,8BAAA,EAAiC,IAAI,CAAC,KAAK,CAAA,CAAE;AAC/D,SAAA,CAAC;AACF,QAAA,UAAU,CAAC,IAAI,CAAC,kCAAkC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC5E;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;AAC7E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
|
package/package.json
CHANGED
package/src/agent.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
-
import type { Task, ExecutionResult, AgentConfig } from './types.js';
|
|
2
|
+
import type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';
|
|
3
3
|
import { TaskManager } from './task-manager.js';
|
|
4
4
|
import { PostHogAPIClient } from './posthog-api.js';
|
|
5
5
|
import { PostHogFileManager } from './file-manager.js';
|
|
@@ -28,11 +28,13 @@ export class Agent {
|
|
|
28
28
|
private promptBuilder: PromptBuilder;
|
|
29
29
|
private extractor?: StructuredExtractor;
|
|
30
30
|
private mcpServers?: Record<string, any>;
|
|
31
|
+
private canUseTool?: CanUseTool;
|
|
31
32
|
public debug: boolean;
|
|
32
33
|
|
|
33
34
|
constructor(config: AgentConfig = {}) {
|
|
34
35
|
this.workingDirectory = config.workingDirectory || process.cwd();
|
|
35
36
|
this.onEvent = config.onEvent;
|
|
37
|
+
this.canUseTool = config.canUseTool;
|
|
36
38
|
this.debug = config.debug || false;
|
|
37
39
|
|
|
38
40
|
// Build default PostHog MCP server configuration
|
|
@@ -181,7 +183,7 @@ export class Agent {
|
|
|
181
183
|
}
|
|
182
184
|
|
|
183
185
|
// Direct prompt execution - still supported for low-level usage
|
|
184
|
-
async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any
|
|
186
|
+
async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any>; canUseTool?: CanUseTool } = {}): Promise<ExecutionResult> {
|
|
185
187
|
await this._configureLlmGateway();
|
|
186
188
|
const baseOptions: Record<string, any> = {
|
|
187
189
|
model: "claude-sonnet-4-5-20250929",
|
|
@@ -191,6 +193,12 @@ export class Agent {
|
|
|
191
193
|
mcpServers: this.mcpServers,
|
|
192
194
|
};
|
|
193
195
|
|
|
196
|
+
// Add canUseTool hook if provided (options take precedence over instance config)
|
|
197
|
+
const canUseTool = options.canUseTool || this.canUseTool;
|
|
198
|
+
if (canUseTool) {
|
|
199
|
+
baseOptions.canUseTool = canUseTool;
|
|
200
|
+
}
|
|
201
|
+
|
|
194
202
|
const response = query({
|
|
195
203
|
prompt,
|
|
196
204
|
options: { ...baseOptions, ...(options.queryOverrides || {}) },
|
package/src/agents/execution.ts
CHANGED
|
@@ -30,7 +30,6 @@ Before completing the task, verify:
|
|
|
30
30
|
- Captured meaningful events with PostHog SDK where appropriate
|
|
31
31
|
- Wrapped new logic in PostHog feature flags where appropriate
|
|
32
32
|
- Updated documentation, README, or type hints as needed
|
|
33
|
-
- No build artifacts or dependencies are being committed
|
|
34
33
|
</checklist>
|
|
35
34
|
|
|
36
35
|
<output_format>
|
package/src/agents/planning.ts
CHANGED
|
@@ -4,7 +4,7 @@ PostHog AI Planning Agent — analyze codebases and create actionable implementa
|
|
|
4
4
|
|
|
5
5
|
<constraints>
|
|
6
6
|
- Read-only: analyze files, search code, explore structure
|
|
7
|
-
- No modifications
|
|
7
|
+
- No modifications or edits
|
|
8
8
|
- Output ONLY the plan markdown — no preamble, no acknowledgment, no meta-commentary
|
|
9
9
|
</constraints>
|
|
10
10
|
|
package/src/agents/research.ts
CHANGED
|
@@ -57,7 +57,7 @@ Format requirements:
|
|
|
57
57
|
- Follow with "**Options:**" on its own line
|
|
58
58
|
- Start options with "- a)", "- b)", "- c)"
|
|
59
59
|
- Always include "c) Something else (please specify)"
|
|
60
|
-
- Max
|
|
60
|
+
- Max 4 questions total
|
|
61
61
|
</output_format>
|
|
62
62
|
|
|
63
63
|
<examples>
|
package/src/types.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
|
|
2
|
+
// import and export to keep a single type file
|
|
3
|
+
import type { CanUseTool, PermissionResult } from '@anthropic-ai/claude-agent-sdk/sdkTypes.js';
|
|
4
|
+
export type { CanUseTool, PermissionResult };
|
|
5
|
+
|
|
1
6
|
// PostHog Task model (matches Array's OpenAPI schema)
|
|
2
7
|
export interface Task {
|
|
3
8
|
id: string;
|
|
@@ -68,6 +73,9 @@ export interface TaskExecutionOptions {
|
|
|
68
73
|
isCloudMode?: boolean; // Determines local vs cloud behavior (local pauses after each phase)
|
|
69
74
|
autoProgress?: boolean;
|
|
70
75
|
queryOverrides?: Record<string, any>;
|
|
76
|
+
// Fine-grained permission control (only applied to build phase)
|
|
77
|
+
// See: https://docs.claude.com/en/api/agent-sdk/permissions
|
|
78
|
+
canUseTool?: CanUseTool;
|
|
71
79
|
}
|
|
72
80
|
|
|
73
81
|
// Base event with timestamp
|
|
@@ -305,6 +313,10 @@ export interface AgentConfig {
|
|
|
305
313
|
|
|
306
314
|
// Logging configuration
|
|
307
315
|
debug?: boolean;
|
|
316
|
+
|
|
317
|
+
// Fine-grained permission control for direct run() calls
|
|
318
|
+
// See: https://docs.claude.com/en/api/agent-sdk/permissions
|
|
319
|
+
canUseTool?: CanUseTool;
|
|
308
320
|
}
|
|
309
321
|
|
|
310
322
|
export interface PostHogAPIConfig {
|
|
@@ -49,8 +49,31 @@ export const buildStep: WorkflowStepRunner = async ({ step, context }) => {
|
|
|
49
49
|
permissionMode: configuredPermissionMode,
|
|
50
50
|
settingSources: ['local'],
|
|
51
51
|
mcpServers,
|
|
52
|
+
// Allow all tools for build phase - full read/write access needed for implementation
|
|
53
|
+
allowedTools: [
|
|
54
|
+
'Task',
|
|
55
|
+
'Bash',
|
|
56
|
+
'BashOutput',
|
|
57
|
+
'KillBash',
|
|
58
|
+
'Edit',
|
|
59
|
+
'Read',
|
|
60
|
+
'Write',
|
|
61
|
+
'Glob',
|
|
62
|
+
'Grep',
|
|
63
|
+
'NotebookEdit',
|
|
64
|
+
'WebFetch',
|
|
65
|
+
'WebSearch',
|
|
66
|
+
'ListMcpResources',
|
|
67
|
+
'ReadMcpResource',
|
|
68
|
+
'TodoWrite',
|
|
69
|
+
],
|
|
52
70
|
};
|
|
53
71
|
|
|
72
|
+
// Add fine-grained permission hook if provided
|
|
73
|
+
if (options.canUseTool) {
|
|
74
|
+
baseOptions.canUseTool = options.canUseTool;
|
|
75
|
+
}
|
|
76
|
+
|
|
54
77
|
const response = query({
|
|
55
78
|
prompt: fullPrompt,
|
|
56
79
|
options: { ...baseOptions, ...(options.queryOverrides || {}) },
|
|
@@ -69,6 +69,19 @@ export const planStep: WorkflowStepRunner = async ({ step, context }) => {
|
|
|
69
69
|
permissionMode: 'plan',
|
|
70
70
|
settingSources: ['local'],
|
|
71
71
|
mcpServers,
|
|
72
|
+
// Allow research tools: read-only operations, web search, MCP resources, and ExitPlanMode
|
|
73
|
+
allowedTools: [
|
|
74
|
+
'Read',
|
|
75
|
+
'Glob',
|
|
76
|
+
'Grep',
|
|
77
|
+
'WebFetch',
|
|
78
|
+
'WebSearch',
|
|
79
|
+
'ListMcpResources',
|
|
80
|
+
'ReadMcpResource',
|
|
81
|
+
'ExitPlanMode',
|
|
82
|
+
'TodoWrite',
|
|
83
|
+
'BashOutput',
|
|
84
|
+
],
|
|
72
85
|
};
|
|
73
86
|
|
|
74
87
|
const response = query({
|
|
@@ -40,6 +40,18 @@ export const researchStep: WorkflowStepRunner = async ({ step, context }) => {
|
|
|
40
40
|
permissionMode: 'plan',
|
|
41
41
|
settingSources: ['local'],
|
|
42
42
|
mcpServers,
|
|
43
|
+
// Allow research tools: read-only operations, web search, and MCP resources
|
|
44
|
+
allowedTools: [
|
|
45
|
+
'Read',
|
|
46
|
+
'Glob',
|
|
47
|
+
'Grep',
|
|
48
|
+
'WebFetch',
|
|
49
|
+
'WebSearch',
|
|
50
|
+
'ListMcpResources',
|
|
51
|
+
'ReadMcpResource',
|
|
52
|
+
'TodoWrite',
|
|
53
|
+
'BashOutput',
|
|
54
|
+
],
|
|
43
55
|
};
|
|
44
56
|
|
|
45
57
|
const response = query({
|