@posthog/agent 1.25.0 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/_tslib.js +74 -0
- package/dist/_virtual/_tslib.js.map +1 -0
- package/dist/_virtual/index.js +2 -2
- package/dist/_virtual/index2.js +2 -2
- package/dist/_virtual/index8.js +2 -2
- package/dist/_virtual/index9.js +2 -2
- package/dist/node_modules/@agentclientprotocol/sdk/dist/acp.js +284 -3
- package/dist/node_modules/@agentclientprotocol/sdk/dist/acp.js.map +1 -1
- package/dist/node_modules/@agentclientprotocol/sdk/dist/schema.js +2 -1
- package/dist/node_modules/@agentclientprotocol/sdk/dist/schema.js.map +1 -1
- package/dist/node_modules/ajv/dist/ajv.js +1 -1
- package/dist/node_modules/ajv/dist/compile/codegen/index.js +1 -1
- package/dist/node_modules/ajv/dist/compile/validate/index.js +1 -1
- package/dist/node_modules/ajv/dist/vocabularies/discriminator/index.js +1 -1
- package/dist/node_modules/ajv-formats/dist/index.js +1 -1
- package/dist/package.json.js +1 -1
- package/dist/src/adapters/claude/claude.d.ts.map +1 -1
- package/dist/src/adapters/claude/claude.js +21 -5
- package/dist/src/adapters/claude/claude.js.map +1 -1
- package/dist/src/adapters/claude/mcp-server.js +105 -92
- package/dist/src/adapters/claude/mcp-server.js.map +1 -1
- package/dist/src/adapters/claude/tools.d.ts.map +1 -1
- package/dist/src/adapters/claude/tools.js +8 -1
- package/dist/src/adapters/claude/tools.js.map +1 -1
- package/dist/src/agent.d.ts +7 -1
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +151 -0
- package/dist/src/agent.js.map +1 -1
- package/dist/src/session-store.d.ts +7 -2
- package/dist/src/session-store.d.ts.map +1 -1
- package/dist/src/session-store.js +11 -0
- package/dist/src/session-store.js.map +1 -1
- package/dist/src/worktree-manager.d.ts.map +1 -1
- package/dist/src/worktree-manager.js +3 -5
- package/dist/src/worktree-manager.js.map +1 -1
- package/package.json +1 -1
- package/src/adapters/claude/claude.ts +21 -5
- package/src/adapters/claude/tools.ts +8 -1
- package/src/agent.ts +213 -1
- package/src/session-store.ts +18 -3
- package/src/worktree-manager.ts +4 -7
package/dist/src/agent.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type InProcessAcpConnection } from "./adapters/claude/claude.js";
|
|
2
2
|
import { PostHogAPIClient } from "./posthog-api.js";
|
|
3
|
-
import type { AgentConfig, Task } from "./types.js";
|
|
3
|
+
import type { AgentConfig, StoredNotification, Task, TaskExecutionOptions } from "./types.js";
|
|
4
4
|
export declare class Agent {
|
|
5
5
|
private workingDirectory;
|
|
6
6
|
private taskManager;
|
|
@@ -37,6 +37,11 @@ export declare class Agent {
|
|
|
37
37
|
runTaskV2(taskId: string, taskRunId: string, options?: import("./types.js").TaskExecutionOptions): Promise<InProcessAcpConnection>;
|
|
38
38
|
fetchTask(taskId: string): Promise<Task>;
|
|
39
39
|
getPostHogClient(): PostHogAPIClient | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Send a notification to a cloud task run's S3 log.
|
|
42
|
+
* The cloud runner will pick up new notifications via interrupt polling.
|
|
43
|
+
*/
|
|
44
|
+
sendNotification(taskId: string, runId: string, notification: StoredNotification): Promise<void>;
|
|
40
45
|
getTaskFiles(taskId: string): Promise<any[]>;
|
|
41
46
|
createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string, customBody?: string): Promise<string>;
|
|
42
47
|
attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void>;
|
|
@@ -45,6 +50,7 @@ export declare class Agent {
|
|
|
45
50
|
getTaskExecutionStatus(taskId: string): string | null;
|
|
46
51
|
private prepareTaskBranch;
|
|
47
52
|
private ensureOpenAIGatewayEnv;
|
|
53
|
+
runTaskCloud(taskId: string, taskRunId: string, options?: TaskExecutionOptions): Promise<void>;
|
|
48
54
|
private ensurePullRequest;
|
|
49
55
|
}
|
|
50
56
|
export type { AgentConfig, ExecutionResult, SupportingFile, Task, } from "./types.js";
|
package/dist/src/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent.ts"],"names":[],"mappings":"AAWA,OAAO,EAEL,KAAK,sBAAsB,EAC5B,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAKpD,OAAO,KAAK,EACV,WAAW,EAEX,kBAAkB,EAClB,IAAI,EACJ,oBAAoB,EACrB,MAAM,YAAY,CAAC;AAKpB,qBAAa,KAAK;IAChB,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,UAAU,CAAC,CAAmB;IACtC,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,aAAa,CAAC,CAAyB;IAC/C,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,UAAU,CAAC,CAAsB;IACzC,OAAO,CAAC,UAAU,CAAC,CAAa;IAChC,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,YAAY,CAAC,CAAe;IAC7B,KAAK,EAAE,OAAO,CAAC;gBAEV,MAAM,EAAE,WAAW;IAyE/B;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO;IAKzB;;OAEG;YACW,oBAAoB;IAiBlC,OAAO,CAAC,qBAAqB;IAUvB,OAAO,CACX,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,OAAO,YAAY,EAAE,oBAAyB,GACtD,OAAO,CAAC,IAAI,CAAC;IAyFhB;;;;;;OAMG;IACG,SAAS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E,MAAM,YAAY,CAAC"}
|
package/dist/src/agent.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ClientSideConnection } from '../node_modules/@agentclientprotocol/sdk/dist/acp.js';
|
|
1
2
|
import { POSTHOG_NOTIFICATIONS } from './acp-extensions.js';
|
|
2
3
|
import { createAcpConnection } from './adapters/claude/claude.js';
|
|
3
4
|
import { PostHogFileManager } from './file-manager.js';
|
|
@@ -10,6 +11,8 @@ import { TemplateManager } from './template-manager.js';
|
|
|
10
11
|
import { Logger } from './utils/logger.js';
|
|
11
12
|
import { TASK_WORKFLOW } from './workflow/config.js';
|
|
12
13
|
export { PermissionMode } from './types.js';
|
|
14
|
+
import { PROTOCOL_VERSION } from '../node_modules/@agentclientprotocol/sdk/dist/schema.js';
|
|
15
|
+
import { ndJsonStream } from '../node_modules/@agentclientprotocol/sdk/dist/stream.js';
|
|
13
16
|
|
|
14
17
|
class Agent {
|
|
15
18
|
workingDirectory;
|
|
@@ -248,6 +251,21 @@ class Agent {
|
|
|
248
251
|
getPostHogClient() {
|
|
249
252
|
return this.posthogAPI;
|
|
250
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Send a notification to a cloud task run's S3 log.
|
|
256
|
+
* The cloud runner will pick up new notifications via interrupt polling.
|
|
257
|
+
*/
|
|
258
|
+
async sendNotification(taskId, runId, notification) {
|
|
259
|
+
if (!this.posthogAPI) {
|
|
260
|
+
throw new Error("PostHog API not configured. Cannot send notification to cloud task.");
|
|
261
|
+
}
|
|
262
|
+
await this.posthogAPI.appendTaskRunLog(taskId, runId, [notification]);
|
|
263
|
+
this.logger.debug("Notification sent to cloud task", {
|
|
264
|
+
taskId,
|
|
265
|
+
runId,
|
|
266
|
+
method: notification.notification.method,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
251
269
|
async getTaskFiles(taskId) {
|
|
252
270
|
this.logger.debug("Getting task files", { taskId });
|
|
253
271
|
const files = await this.fileManager.getTaskFiles(taskId);
|
|
@@ -384,6 +402,139 @@ Generated by PostHog Agent`;
|
|
|
384
402
|
process.env.OPENAI_API_KEY = resolvedToken;
|
|
385
403
|
}
|
|
386
404
|
}
|
|
405
|
+
async runTaskCloud(taskId, taskRunId, options = {}) {
|
|
406
|
+
await this._configureLlmGateway();
|
|
407
|
+
const task = await this.fetchTask(taskId);
|
|
408
|
+
const cwd = options.repositoryPath || this.workingDirectory;
|
|
409
|
+
const taskSlug = task.slug || task.id;
|
|
410
|
+
this.currentRunId = taskRunId;
|
|
411
|
+
this.logger.info("Starting cloud task execution", {
|
|
412
|
+
taskId: task.id,
|
|
413
|
+
taskSlug,
|
|
414
|
+
taskRunId,
|
|
415
|
+
cwd,
|
|
416
|
+
});
|
|
417
|
+
if (!this.sessionStore) {
|
|
418
|
+
throw new Error("SessionStore required for cloud mode. Ensure PostHog API credentials are configured.");
|
|
419
|
+
}
|
|
420
|
+
// Start session in SessionStore (updates task run status to in_progress)
|
|
421
|
+
const taskRun = await this.sessionStore.start(taskRunId, taskId, taskRunId);
|
|
422
|
+
this.logger.debug("Session started", {
|
|
423
|
+
taskRunId,
|
|
424
|
+
logUrl: taskRun?.log_url,
|
|
425
|
+
});
|
|
426
|
+
// Create internal ACP connection with S3 persistence
|
|
427
|
+
const acpConnection = createAcpConnection({
|
|
428
|
+
sessionStore: this.sessionStore,
|
|
429
|
+
sessionId: taskRunId,
|
|
430
|
+
taskId: task.id,
|
|
431
|
+
});
|
|
432
|
+
// Create client connection using the client-side streams
|
|
433
|
+
const clientStream = ndJsonStream(acpConnection.clientStreams.writable, acpConnection.clientStreams.readable);
|
|
434
|
+
// Create auto-approving client for headless cloud mode
|
|
435
|
+
const cloudClient = {
|
|
436
|
+
async requestPermission(params) {
|
|
437
|
+
const allowOption = params.options.find((o) => o.kind === "allow_once" || o.kind === "allow_always");
|
|
438
|
+
return {
|
|
439
|
+
outcome: {
|
|
440
|
+
outcome: "selected",
|
|
441
|
+
optionId: allowOption?.optionId ?? params.options[0].optionId,
|
|
442
|
+
},
|
|
443
|
+
};
|
|
444
|
+
},
|
|
445
|
+
async sessionUpdate(_params) {
|
|
446
|
+
// Notifications are already being persisted to S3 via tapped streams
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
const clientConnection = new ClientSideConnection((_agent) => cloudClient, clientStream);
|
|
450
|
+
try {
|
|
451
|
+
// Initialize the connection
|
|
452
|
+
await clientConnection.initialize({
|
|
453
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
454
|
+
clientCapabilities: {},
|
|
455
|
+
});
|
|
456
|
+
// Create new session
|
|
457
|
+
await clientConnection.newSession({
|
|
458
|
+
cwd,
|
|
459
|
+
mcpServers: [],
|
|
460
|
+
_meta: { sessionId: taskRunId },
|
|
461
|
+
});
|
|
462
|
+
// Prepare git branch if not skipped
|
|
463
|
+
if (!options.skipGitBranch) {
|
|
464
|
+
const sendNotification = async (method, params) => {
|
|
465
|
+
this.logger.debug(`Notification: ${method}`, params);
|
|
466
|
+
await acpConnection.agentConnection.extNotification?.(method, params);
|
|
467
|
+
};
|
|
468
|
+
await this.prepareTaskBranch(taskSlug, true, sendNotification);
|
|
469
|
+
}
|
|
470
|
+
// Build initial prompt from task description
|
|
471
|
+
const initialPrompt = [
|
|
472
|
+
{
|
|
473
|
+
type: "text",
|
|
474
|
+
text: `# Task: ${task.title}\n\n${task.description}`,
|
|
475
|
+
},
|
|
476
|
+
];
|
|
477
|
+
// Track the last known log entry count for interrupt polling
|
|
478
|
+
let lastKnownEntryCount = 0;
|
|
479
|
+
let isPolling = true;
|
|
480
|
+
// Start interrupt polling in background
|
|
481
|
+
const pollForInterrupts = async () => {
|
|
482
|
+
while (isPolling) {
|
|
483
|
+
await new Promise((resolve) => setTimeout(resolve, 2000)); // Poll every 2 seconds
|
|
484
|
+
if (!isPolling)
|
|
485
|
+
break;
|
|
486
|
+
try {
|
|
487
|
+
const newEntries = await this.sessionStore.pollForNewEntries(taskRunId, lastKnownEntryCount);
|
|
488
|
+
for (const entry of newEntries) {
|
|
489
|
+
lastKnownEntryCount++;
|
|
490
|
+
// Look for user_message notifications
|
|
491
|
+
if (entry.notification?.method === "sessionUpdate" &&
|
|
492
|
+
entry.notification?.params?.sessionUpdate ===
|
|
493
|
+
"user_message") {
|
|
494
|
+
const content = entry.notification?.params?.content;
|
|
495
|
+
if (content) {
|
|
496
|
+
this.logger.info("Processing user interrupt", { content });
|
|
497
|
+
// Send as new prompt - will be processed after current prompt completes
|
|
498
|
+
await clientConnection.prompt({
|
|
499
|
+
sessionId: taskRunId,
|
|
500
|
+
prompt: Array.isArray(content) ? content : [content],
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
catch (err) {
|
|
507
|
+
this.logger.warn("Interrupt polling error", { error: err });
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
// Start polling in background (don't await)
|
|
512
|
+
const pollingPromise = pollForInterrupts();
|
|
513
|
+
// Send initial prompt and wait for completion
|
|
514
|
+
this.logger.info("Sending initial prompt to agent");
|
|
515
|
+
const result = await clientConnection.prompt({
|
|
516
|
+
sessionId: taskRunId,
|
|
517
|
+
prompt: initialPrompt,
|
|
518
|
+
});
|
|
519
|
+
// Stop interrupt polling
|
|
520
|
+
isPolling = false;
|
|
521
|
+
await pollingPromise;
|
|
522
|
+
this.logger.info("Task execution complete", {
|
|
523
|
+
taskId: task.id,
|
|
524
|
+
stopReason: result.stopReason,
|
|
525
|
+
});
|
|
526
|
+
await this.sessionStore.complete(taskRunId);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
530
|
+
this.logger.error("Cloud task execution failed", {
|
|
531
|
+
taskId: task.id,
|
|
532
|
+
error: errorMessage,
|
|
533
|
+
});
|
|
534
|
+
await this.sessionStore.fail(taskRunId, errorMessage);
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
387
538
|
async ensurePullRequest(task, stepResults, sendNotification) {
|
|
388
539
|
const latestRun = task.latest_run;
|
|
389
540
|
const existingPr = latestRun?.output && typeof latestRun.output === "object"
|
package/dist/src/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { POSTHOG_NOTIFICATIONS } from \"./acp-extensions.js\";\nimport {\n createAcpConnection,\n type InProcessAcpConnection,\n} from \"./adapters/claude/claude.js\";\nimport { PostHogFileManager } from \"./file-manager.js\";\nimport { GitManager } from \"./git-manager.js\";\nimport { PostHogAPIClient } from \"./posthog-api.js\";\nimport { PromptBuilder } from \"./prompt-builder.js\";\nimport { SessionStore } from \"./session-store.js\";\nimport { TaskManager } from \"./task-manager.js\";\nimport { TemplateManager } from \"./template-manager.js\";\nimport type { AgentConfig, CanUseTool, Task } from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\nimport { TASK_WORKFLOW } from \"./workflow/config.js\";\nimport type { SendNotification, WorkflowRuntime } from \"./workflow/types.js\";\n\nexport class Agent {\n private workingDirectory: string;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private logger: Logger;\n private acpConnection?: InProcessAcpConnection;\n private promptBuilder: PromptBuilder;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n private currentRunId?: string;\n private sessionStore?: SessionStore;\n public debug: boolean;\n\n constructor(config: AgentConfig) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl =\n 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({\n debug: this.debug,\n prefix: \"[PostHog Agent]\",\n onLog: config.onLog,\n });\n this.taskManager = new TaskManager();\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 });\n this.templateManager = new TemplateManager();\n\n if (\n config.posthogApiUrl &&\n config.posthogApiKey &&\n config.posthogProjectId\n ) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n projectId: config.posthogProjectId,\n });\n\n // Create SessionStore from the API client for ACP connection\n this.sessionStore = new SessionStore(\n this.posthogAPI,\n this.logger.child(\"SessionStore\"),\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 }\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 try {\n const gatewayUrl = this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n } catch (error) {\n this.logger.error(\"Failed to configure LLM gateway\", error);\n throw error;\n }\n }\n\n private getOrCreateConnection(): InProcessAcpConnection {\n if (!this.acpConnection) {\n this.acpConnection = createAcpConnection({\n sessionStore: this.sessionStore,\n });\n }\n return this.acpConnection;\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(\n taskId: string,\n taskRunId: string,\n options: import(\"./types.js\").TaskExecutionOptions = {},\n ): Promise<void> {\n // await this._configureLlmGateway();\n\n const task = await this.fetchTask(taskId);\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n // Use taskRunId as sessionId - they are the same identifier\n this.currentRunId = taskRunId;\n\n this.logger.info(\"Starting adaptive task execution\", {\n taskId: task.id,\n taskSlug,\n taskRunId,\n isCloudMode,\n });\n\n const connection = this.getOrCreateConnection();\n\n // Create sendNotification using ACP connection's extNotification\n const sendNotification: SendNotification = async (method, params) => {\n this.logger.debug(`Notification: ${method}`, params);\n await connection.agentConnection.extNotification?.(method, params);\n };\n\n await sendNotification(POSTHOG_NOTIFICATIONS.RUN_STARTED, {\n sessionId: taskRunId,\n runId: taskRunId,\n });\n\n await this.prepareTaskBranch(taskSlug, isCloudMode, sendNotification);\n\n let taskError: Error | undefined;\n try {\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n runId: taskRunId,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n connection: connection.agentConnection,\n sessionId: taskRunId,\n sendNotification,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\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 const shouldCreatePR = options.createPR ?? isCloudMode;\n if (shouldCreatePR) {\n await this.ensurePullRequest(\n task,\n workflowContext.stepResults,\n sendNotification,\n );\n }\n\n this.logger.info(\"Task execution complete\", { taskId: task.id });\n await sendNotification(POSTHOG_NOTIFICATIONS.TASK_COMPLETE, {\n sessionId: taskRunId,\n taskId: task.id,\n });\n } catch (error) {\n taskError = error instanceof Error ? error : new Error(String(error));\n this.logger.error(\"Task execution failed\", {\n taskId: task.id,\n error: taskError.message,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.ERROR, {\n sessionId: taskRunId,\n message: taskError.message,\n });\n throw taskError;\n }\n }\n\n /**\n * Creates an in-process ACP connection for client communication.\n * Sets up git branch for the task, configures LLM gateway.\n * The client handles all prompting/querying via the returned streams.\n *\n * @returns InProcessAcpConnection with clientStreams for the client to use\n */\n async runTaskV2(\n taskId: string,\n taskRunId: string,\n options: import(\"./types.js\").TaskExecutionOptions = {},\n ): Promise<InProcessAcpConnection> {\n await this._configureLlmGateway();\n\n const task = await this.fetchTask(taskId);\n const taskSlug = (task as any).slug || task.id;\n const isCloudMode = options.isCloudMode ?? false;\n const _cwd = options.repositoryPath || this.workingDirectory;\n\n // Use taskRunId as sessionId - they are the same identifier\n this.currentRunId = taskRunId;\n\n this.acpConnection = createAcpConnection({\n sessionStore: this.sessionStore,\n sessionId: taskRunId,\n taskId: task.id,\n });\n\n const sendNotification: SendNotification = async (method, params) => {\n this.logger.debug(`Notification: ${method}`, params);\n await this.acpConnection?.agentConnection.extNotification?.(\n method,\n params,\n );\n };\n\n await sendNotification(POSTHOG_NOTIFICATIONS.RUN_STARTED, {\n sessionId: taskRunId,\n runId: taskRunId,\n });\n\n if (!options.skipGitBranch) {\n try {\n await this.prepareTaskBranch(taskSlug, isCloudMode, sendNotification);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\"Failed to prepare task branch\", {\n error: errorMessage,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.ERROR, {\n sessionId: taskRunId,\n message: errorMessage,\n });\n throw error;\n }\n }\n\n return this.acpConnection;\n }\n\n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n if (!this.posthogAPI) {\n const error = new Error(\n \"PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.\",\n );\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 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 createPullRequest(\n taskId: string,\n branchName: string,\n taskTitle: string,\n taskDescription: string,\n customBody?: string,\n ): Promise<string> {\n this.logger.info(\"Creating pull request\", {\n taskId,\n branchName,\n taskTitle,\n });\n\n const defaultBody = `## 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 const prBody = customBody || defaultBody;\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(\n taskId: string,\n prUrl: string,\n branchName?: string,\n ): Promise<void> {\n this.logger.info(\"Attaching PR to task run\", { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.currentRunId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot attach PR to task.\",\n );\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.currentRunId, updates);\n this.logger.debug(\"PR attached to task run\", {\n taskId,\n runId: this.currentRunId,\n prUrl,\n });\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.currentRunId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot update branch.\",\n );\n this.logger.error(\"PostHog API not configured\", error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.currentRunId, {\n branch: branchName,\n });\n this.logger.debug(\"Task run branch updated\", {\n taskId,\n runId: this.currentRunId,\n branchName,\n });\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(\n taskSlug: string,\n isCloudMode: boolean,\n sendNotification: SendNotification,\n ): Promise<void> {\n if (await this.gitManager.hasChanges()) {\n throw new Error(\n \"Cannot start task with uncommitted changes. Please commit or stash your changes first.\",\n );\n }\n\n // If we're running in a worktree, we're already on the correct branch\n // (the worktree was created with its own branch). Skip branch creation.\n const isWorktree = await this.gitManager.isWorktree();\n if (isWorktree) {\n const currentBranch = await this.gitManager.getCurrentBranch();\n this.logger.info(\"Running in worktree, using existing branch\", {\n branch: currentBranch,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.BRANCH_CREATED, {\n branch: currentBranch,\n });\n return;\n }\n\n await this.gitManager.resetToDefaultBranchIfNeeded();\n\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n const branchName = await this.gitManager.createTaskBranch(taskSlug);\n await sendNotification(POSTHOG_NOTIFICATIONS.BRANCH_CREATED, {\n branch: branchName,\n });\n\n await this.gitManager.addAllPostHogFiles();\n\n // Only commit if there are changes or we're in cloud mode\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, {\n allowEmpty: true,\n });\n } else {\n // Check if there are any changes before committing\n const hasChanges = await this.gitManager.hasStagedChanges();\n if (hasChanges) {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n }\n } else {\n this.logger.info(\"Switching to existing task branch\", {\n branch: existingBranch,\n });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(gatewayUrl?: string, token?: string): void {\n const resolvedGatewayUrl = gatewayUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedGatewayUrl) {\n process.env.OPENAI_BASE_URL = resolvedGatewayUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n }\n\n private async ensurePullRequest(\n task: Task,\n stepResults: Record<string, any>,\n sendNotification: SendNotification,\n ): 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\", {\n taskId: task.id,\n prUrl: existingPr,\n });\n return;\n }\n\n const buildResult = stepResults.build;\n if (!buildResult?.commitCreated) {\n this.logger.warn(\n \"Build step did not produce a commit; skipping PR creation\",\n { taskId: task.id },\n );\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const finalizeResult = stepResults.finalize;\n const prBody = finalizeResult?.prBody;\n\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? \"\",\n prBody,\n );\n\n await sendNotification(POSTHOG_NOTIFICATIONS.PR_CREATED, { prUrl });\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info(\"PR attached to task successfully\", {\n taskId: task.id,\n prUrl,\n });\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\nexport type {\n AgentConfig,\n ExecutionResult,\n SupportingFile,\n Task,\n} from \"./types.js\";\nexport { PermissionMode } from \"./types.js\";\n"],"names":[],"mappings":";;;;;;;;;;;;;MAiBa,KAAK,CAA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AE,IAAI,CAAC,EAAE,EAAE,CACpB;YACD;QACF;QAEA,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,gBAAgB,EAAE;AAC3D,QAAA,MAAM,cAAc,GAAG,WAAW,CAAC,QAAQ;AAC3C,QAAA,MAAM,MAAM,GAAG,cAAc,EAAE,MAAM;QAErC,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,iBAAiB,CACxC,IAAI,CAAC,EAAE,EACP,UAAU,EACV,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,WAAW,IAAI,EAAE,EACtB,MAAM,CACP;QAED,MAAM,gBAAgB,CAAC,qBAAqB,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC;AAEnE,QAAA,IAAI;AACF,YAAA,MAAM,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,UAAU,CAAC;AAC9D,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE;gBACnD,MAAM,EAAE,IAAI,CAAC,EAAE;gBACf,KAAK;AACN,aAAA,CAAC;QACJ;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC9C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9D,aAAA,CAAC;QACJ;IACF;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import {\n type Client,\n ClientSideConnection,\n type ContentBlock,\n ndJsonStream,\n PROTOCOL_VERSION,\n type RequestPermissionRequest,\n type RequestPermissionResponse,\n type SessionNotification,\n} from \"@agentclientprotocol/sdk\";\nimport { POSTHOG_NOTIFICATIONS } from \"./acp-extensions.js\";\nimport {\n createAcpConnection,\n type InProcessAcpConnection,\n} from \"./adapters/claude/claude.js\";\nimport { PostHogFileManager } from \"./file-manager.js\";\nimport { GitManager } from \"./git-manager.js\";\nimport { PostHogAPIClient } from \"./posthog-api.js\";\nimport { PromptBuilder } from \"./prompt-builder.js\";\nimport { SessionStore } from \"./session-store.js\";\nimport { TaskManager } from \"./task-manager.js\";\nimport { TemplateManager } from \"./template-manager.js\";\nimport type {\n AgentConfig,\n CanUseTool,\n StoredNotification,\n Task,\n TaskExecutionOptions,\n} from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\nimport { TASK_WORKFLOW } from \"./workflow/config.js\";\nimport type { SendNotification, WorkflowRuntime } from \"./workflow/types.js\";\n\nexport class Agent {\n private workingDirectory: string;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private logger: Logger;\n private acpConnection?: InProcessAcpConnection;\n private promptBuilder: PromptBuilder;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n private currentRunId?: string;\n private sessionStore?: SessionStore;\n public debug: boolean;\n\n constructor(config: AgentConfig) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl =\n 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({\n debug: this.debug,\n prefix: \"[PostHog Agent]\",\n onLog: config.onLog,\n });\n this.taskManager = new TaskManager();\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 });\n this.templateManager = new TemplateManager();\n\n if (\n config.posthogApiUrl &&\n config.posthogApiKey &&\n config.posthogProjectId\n ) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n projectId: config.posthogProjectId,\n });\n\n // Create SessionStore from the API client for ACP connection\n this.sessionStore = new SessionStore(\n this.posthogAPI,\n this.logger.child(\"SessionStore\"),\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 }\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 try {\n const gatewayUrl = this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n } catch (error) {\n this.logger.error(\"Failed to configure LLM gateway\", error);\n throw error;\n }\n }\n\n private getOrCreateConnection(): InProcessAcpConnection {\n if (!this.acpConnection) {\n this.acpConnection = createAcpConnection({\n sessionStore: this.sessionStore,\n });\n }\n return this.acpConnection;\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(\n taskId: string,\n taskRunId: string,\n options: import(\"./types.js\").TaskExecutionOptions = {},\n ): Promise<void> {\n // await this._configureLlmGateway();\n\n const task = await this.fetchTask(taskId);\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n // Use taskRunId as sessionId - they are the same identifier\n this.currentRunId = taskRunId;\n\n this.logger.info(\"Starting adaptive task execution\", {\n taskId: task.id,\n taskSlug,\n taskRunId,\n isCloudMode,\n });\n\n const connection = this.getOrCreateConnection();\n\n // Create sendNotification using ACP connection's extNotification\n const sendNotification: SendNotification = async (method, params) => {\n this.logger.debug(`Notification: ${method}`, params);\n await connection.agentConnection.extNotification?.(method, params);\n };\n\n await sendNotification(POSTHOG_NOTIFICATIONS.RUN_STARTED, {\n sessionId: taskRunId,\n runId: taskRunId,\n });\n\n await this.prepareTaskBranch(taskSlug, isCloudMode, sendNotification);\n\n let taskError: Error | undefined;\n try {\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n runId: taskRunId,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n connection: connection.agentConnection,\n sessionId: taskRunId,\n sendNotification,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\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 const shouldCreatePR = options.createPR ?? isCloudMode;\n if (shouldCreatePR) {\n await this.ensurePullRequest(\n task,\n workflowContext.stepResults,\n sendNotification,\n );\n }\n\n this.logger.info(\"Task execution complete\", { taskId: task.id });\n await sendNotification(POSTHOG_NOTIFICATIONS.TASK_COMPLETE, {\n sessionId: taskRunId,\n taskId: task.id,\n });\n } catch (error) {\n taskError = error instanceof Error ? error : new Error(String(error));\n this.logger.error(\"Task execution failed\", {\n taskId: task.id,\n error: taskError.message,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.ERROR, {\n sessionId: taskRunId,\n message: taskError.message,\n });\n throw taskError;\n }\n }\n\n /**\n * Creates an in-process ACP connection for client communication.\n * Sets up git branch for the task, configures LLM gateway.\n * The client handles all prompting/querying via the returned streams.\n *\n * @returns InProcessAcpConnection with clientStreams for the client to use\n */\n async runTaskV2(\n taskId: string,\n taskRunId: string,\n options: import(\"./types.js\").TaskExecutionOptions = {},\n ): Promise<InProcessAcpConnection> {\n await this._configureLlmGateway();\n\n const task = await this.fetchTask(taskId);\n const taskSlug = (task as any).slug || task.id;\n const isCloudMode = options.isCloudMode ?? false;\n const _cwd = options.repositoryPath || this.workingDirectory;\n\n // Use taskRunId as sessionId - they are the same identifier\n this.currentRunId = taskRunId;\n\n this.acpConnection = createAcpConnection({\n sessionStore: this.sessionStore,\n sessionId: taskRunId,\n taskId: task.id,\n });\n\n const sendNotification: SendNotification = async (method, params) => {\n this.logger.debug(`Notification: ${method}`, params);\n await this.acpConnection?.agentConnection.extNotification?.(\n method,\n params,\n );\n };\n\n await sendNotification(POSTHOG_NOTIFICATIONS.RUN_STARTED, {\n sessionId: taskRunId,\n runId: taskRunId,\n });\n\n if (!options.skipGitBranch) {\n try {\n await this.prepareTaskBranch(taskSlug, isCloudMode, sendNotification);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\"Failed to prepare task branch\", {\n error: errorMessage,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.ERROR, {\n sessionId: taskRunId,\n message: errorMessage,\n });\n throw error;\n }\n }\n\n return this.acpConnection;\n }\n\n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n if (!this.posthogAPI) {\n const error = new Error(\n \"PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.\",\n );\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 /**\n * Send a notification to a cloud task run's S3 log.\n * The cloud runner will pick up new notifications via interrupt polling.\n */\n async sendNotification(\n taskId: string,\n runId: string,\n notification: StoredNotification,\n ): Promise<void> {\n if (!this.posthogAPI) {\n throw new Error(\n \"PostHog API not configured. Cannot send notification to cloud task.\",\n );\n }\n\n await this.posthogAPI.appendTaskRunLog(taskId, runId, [notification]);\n this.logger.debug(\"Notification sent to cloud task\", {\n taskId,\n runId,\n method: notification.notification.method,\n });\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 createPullRequest(\n taskId: string,\n branchName: string,\n taskTitle: string,\n taskDescription: string,\n customBody?: string,\n ): Promise<string> {\n this.logger.info(\"Creating pull request\", {\n taskId,\n branchName,\n taskTitle,\n });\n\n const defaultBody = `## 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 const prBody = customBody || defaultBody;\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(\n taskId: string,\n prUrl: string,\n branchName?: string,\n ): Promise<void> {\n this.logger.info(\"Attaching PR to task run\", { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.currentRunId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot attach PR to task.\",\n );\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.currentRunId, updates);\n this.logger.debug(\"PR attached to task run\", {\n taskId,\n runId: this.currentRunId,\n prUrl,\n });\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.currentRunId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot update branch.\",\n );\n this.logger.error(\"PostHog API not configured\", error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.currentRunId, {\n branch: branchName,\n });\n this.logger.debug(\"Task run branch updated\", {\n taskId,\n runId: this.currentRunId,\n branchName,\n });\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(\n taskSlug: string,\n isCloudMode: boolean,\n sendNotification: SendNotification,\n ): Promise<void> {\n if (await this.gitManager.hasChanges()) {\n throw new Error(\n \"Cannot start task with uncommitted changes. Please commit or stash your changes first.\",\n );\n }\n\n // If we're running in a worktree, we're already on the correct branch\n // (the worktree was created with its own branch). Skip branch creation.\n const isWorktree = await this.gitManager.isWorktree();\n if (isWorktree) {\n const currentBranch = await this.gitManager.getCurrentBranch();\n this.logger.info(\"Running in worktree, using existing branch\", {\n branch: currentBranch,\n });\n await sendNotification(POSTHOG_NOTIFICATIONS.BRANCH_CREATED, {\n branch: currentBranch,\n });\n return;\n }\n\n await this.gitManager.resetToDefaultBranchIfNeeded();\n\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n const branchName = await this.gitManager.createTaskBranch(taskSlug);\n await sendNotification(POSTHOG_NOTIFICATIONS.BRANCH_CREATED, {\n branch: branchName,\n });\n\n await this.gitManager.addAllPostHogFiles();\n\n // Only commit if there are changes or we're in cloud mode\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, {\n allowEmpty: true,\n });\n } else {\n // Check if there are any changes before committing\n const hasChanges = await this.gitManager.hasStagedChanges();\n if (hasChanges) {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n }\n } else {\n this.logger.info(\"Switching to existing task branch\", {\n branch: existingBranch,\n });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(gatewayUrl?: string, token?: string): void {\n const resolvedGatewayUrl = gatewayUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedGatewayUrl) {\n process.env.OPENAI_BASE_URL = resolvedGatewayUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n }\n\n async runTaskCloud(\n taskId: string,\n taskRunId: string,\n options: TaskExecutionOptions = {},\n ): Promise<void> {\n await this._configureLlmGateway();\n\n const task = await this.fetchTask(taskId);\n const cwd = options.repositoryPath || this.workingDirectory;\n const taskSlug = (task as any).slug || task.id;\n\n this.currentRunId = taskRunId;\n\n this.logger.info(\"Starting cloud task execution\", {\n taskId: task.id,\n taskSlug,\n taskRunId,\n cwd,\n });\n\n if (!this.sessionStore) {\n throw new Error(\n \"SessionStore required for cloud mode. Ensure PostHog API credentials are configured.\",\n );\n }\n\n // Start session in SessionStore (updates task run status to in_progress)\n const taskRun = await this.sessionStore.start(taskRunId, taskId, taskRunId);\n this.logger.debug(\"Session started\", {\n taskRunId,\n logUrl: taskRun?.log_url,\n });\n\n // Create internal ACP connection with S3 persistence\n const acpConnection = createAcpConnection({\n sessionStore: this.sessionStore,\n sessionId: taskRunId,\n taskId: task.id,\n });\n\n // Create client connection using the client-side streams\n const clientStream = ndJsonStream(\n acpConnection.clientStreams.writable as WritableStream<Uint8Array>,\n acpConnection.clientStreams.readable as ReadableStream<Uint8Array>,\n );\n\n // Create auto-approving client for headless cloud mode\n const cloudClient: Client = {\n async requestPermission(params) {\n const allowOption = params.options.find(\n (o) => o.kind === \"allow_once\" || o.kind === \"allow_always\",\n );\n return {\n outcome: {\n outcome: \"selected\",\n optionId: allowOption?.optionId ?? params.options[0].optionId,\n },\n };\n },\n async sessionUpdate(_params) {\n // Notifications are already being persisted to S3 via tapped streams\n },\n };\n\n const clientConnection = new ClientSideConnection(\n (_agent) => cloudClient,\n clientStream,\n );\n\n try {\n // Initialize the connection\n await clientConnection.initialize({\n protocolVersion: PROTOCOL_VERSION,\n clientCapabilities: {},\n });\n\n // Create new session\n await clientConnection.newSession({\n cwd,\n mcpServers: [],\n _meta: { sessionId: taskRunId },\n });\n\n // Prepare git branch if not skipped\n if (!options.skipGitBranch) {\n const sendNotification: SendNotification = async (method, params) => {\n this.logger.debug(`Notification: ${method}`, params);\n await acpConnection.agentConnection.extNotification?.(method, params);\n };\n await this.prepareTaskBranch(taskSlug, true, sendNotification);\n }\n\n // Build initial prompt from task description\n const initialPrompt: ContentBlock[] = [\n {\n type: \"text\",\n text: `# Task: ${task.title}\\n\\n${task.description}`,\n },\n ];\n\n // Track the last known log entry count for interrupt polling\n let lastKnownEntryCount = 0;\n let isPolling = true;\n\n // Start interrupt polling in background\n const pollForInterrupts = async () => {\n while (isPolling) {\n await new Promise((resolve) => setTimeout(resolve, 2000)); // Poll every 2 seconds\n if (!isPolling) break;\n\n try {\n const newEntries = await this.sessionStore!.pollForNewEntries(\n taskRunId,\n lastKnownEntryCount,\n );\n\n for (const entry of newEntries) {\n lastKnownEntryCount++;\n // Look for user_message notifications\n if (\n entry.notification?.method === \"sessionUpdate\" &&\n (entry.notification?.params as any)?.sessionUpdate ===\n \"user_message\"\n ) {\n const content = (entry.notification?.params as any)?.content;\n if (content) {\n this.logger.info(\"Processing user interrupt\", { content });\n // Send as new prompt - will be processed after current prompt completes\n await clientConnection.prompt({\n sessionId: taskRunId,\n prompt: Array.isArray(content) ? content : [content],\n });\n }\n }\n }\n } catch (err) {\n this.logger.warn(\"Interrupt polling error\", { error: err });\n }\n }\n };\n\n // Start polling in background (don't await)\n const pollingPromise = pollForInterrupts();\n\n // Send initial prompt and wait for completion\n this.logger.info(\"Sending initial prompt to agent\");\n const result = await clientConnection.prompt({\n sessionId: taskRunId,\n prompt: initialPrompt,\n });\n\n // Stop interrupt polling\n isPolling = false;\n await pollingPromise;\n\n this.logger.info(\"Task execution complete\", {\n taskId: task.id,\n stopReason: result.stopReason,\n });\n\n await this.sessionStore.complete(taskRunId);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\"Cloud task execution failed\", {\n taskId: task.id,\n error: errorMessage,\n });\n await this.sessionStore.fail(taskRunId, errorMessage);\n throw error;\n }\n }\n\n private async ensurePullRequest(\n task: Task,\n stepResults: Record<string, any>,\n sendNotification: SendNotification,\n ): 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\", {\n taskId: task.id,\n prUrl: existingPr,\n });\n return;\n }\n\n const buildResult = stepResults.build;\n if (!buildResult?.commitCreated) {\n this.logger.warn(\n \"Build step did not produce a commit; skipping PR creation\",\n { taskId: task.id },\n );\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const finalizeResult = stepResults.finalize;\n const prBody = finalizeResult?.prBody;\n\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? \"\",\n prBody,\n );\n\n await sendNotification(POSTHOG_NOTIFICATIONS.PR_CREATED, { prUrl });\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info(\"PR attached to task successfully\", {\n taskId: task.id,\n prUrl,\n });\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\nexport type {\n AgentConfig,\n ExecutionResult,\n SupportingFile,\n Task,\n} from \"./types.js\";\nexport { PermissionMode } from \"./types.js\";\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;MAiCa,KAAK,CAAA;AACR,IAAA,gBAAgB;AAChB,IAAA,WAAW;AACX,IAAA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A,IAAI,CAAC,WAAW,EAAE,aAAa,EAAE;AAC/B,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,2DAA2D,EAC3D,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CACpB;YACD;QACF;QAEA,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,gBAAgB,EAAE;AAC3D,QAAA,MAAM,cAAc,GAAG,WAAW,CAAC,QAAQ;AAC3C,QAAA,MAAM,MAAM,GAAG,cAAc,EAAE,MAAM;QAErC,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,iBAAiB,CACxC,IAAI,CAAC,EAAE,EACP,UAAU,EACV,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,WAAW,IAAI,EAAE,EACtB,MAAM,CACP;QAED,MAAM,gBAAgB,CAAC,qBAAqB,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC;AAEnE,QAAA,IAAI;AACF,YAAA,MAAM,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,UAAU,CAAC;AAC9D,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE;gBACnD,MAAM,EAAE,IAAI,CAAC,EAAE;gBACf,KAAK;AACN,aAAA,CAAC;QACJ;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC9C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9D,aAAA,CAAC;QACJ;IACF;AACD;;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PostHogAPIClient, TaskRunUpdate } from "./posthog-api.js";
|
|
2
|
-
import type { TaskRun } from "./types.js";
|
|
2
|
+
import type { StoredNotification, TaskRun } from "./types.js";
|
|
3
3
|
import { Logger } from "./utils/logger.js";
|
|
4
4
|
export interface SessionPersistenceConfig {
|
|
5
5
|
taskId: string;
|
|
@@ -26,7 +26,12 @@ export declare class SessionStore {
|
|
|
26
26
|
*/
|
|
27
27
|
appendRawLine(sessionId: string, line: string): void;
|
|
28
28
|
/** Load raw JSON-RPC messages from S3 */
|
|
29
|
-
load(logUrl: string): Promise<
|
|
29
|
+
load(logUrl: string): Promise<StoredNotification[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Poll S3 for new entries since last check.
|
|
32
|
+
* Used for interrupt handling in cloud mode.
|
|
33
|
+
*/
|
|
34
|
+
pollForNewEntries(sessionId: string, lastKnownCount: number): Promise<StoredNotification[]>;
|
|
30
35
|
/** Force flush pending entries */
|
|
31
36
|
flush(sessionId: string): Promise<void>;
|
|
32
37
|
private scheduleFlush;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-store.d.ts","sourceRoot":"","sources":["../../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"session-store.d.ts","sourceRoot":"","sources":["../../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,qBAAa,YAAY;IACvB,OAAO,CAAC,UAAU,CAAC,CAAmB;IACtC,OAAO,CAAC,cAAc,CAAgD;IACtE,OAAO,CAAC,aAAa,CAA0C;IAC/D,OAAO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,EAAE,aAAa,GACpB,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC;CAyBhC"}
|
|
@@ -92,6 +92,17 @@ class SessionStore {
|
|
|
92
92
|
})
|
|
93
93
|
.filter((entry) => entry !== null);
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Poll S3 for new entries since last check.
|
|
97
|
+
* Used for interrupt handling in cloud mode.
|
|
98
|
+
*/
|
|
99
|
+
async pollForNewEntries(sessionId, lastKnownCount) {
|
|
100
|
+
const config = this.configs.get(sessionId);
|
|
101
|
+
if (!config?.logUrl)
|
|
102
|
+
return [];
|
|
103
|
+
const entries = await this.load(config.logUrl);
|
|
104
|
+
return entries.slice(lastKnownCount);
|
|
105
|
+
}
|
|
95
106
|
/** Force flush pending entries */
|
|
96
107
|
async flush(sessionId) {
|
|
97
108
|
const config = this.configs.get(sessionId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-store.js","sources":["../../src/session-store.ts"],"sourcesContent":["import type { PostHogAPIClient, TaskRunUpdate } from \"./posthog-api.js\";\nimport type { StoredNotification, TaskRun } from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\n\nexport interface SessionPersistenceConfig {\n taskId: string;\n runId: string;\n logUrl: string;\n sdkSessionId?: string;\n}\n\nexport class SessionStore {\n private posthogAPI?: PostHogAPIClient;\n private pendingEntries: Map<string, StoredNotification[]> = new Map();\n private flushTimeouts: Map<string, NodeJS.Timeout> = new Map();\n private configs: Map<string, SessionPersistenceConfig> = new Map();\n private logger: Logger;\n\n constructor(posthogAPI?: PostHogAPIClient, logger?: Logger) {\n this.posthogAPI = posthogAPI;\n this.logger =\n logger ?? new Logger({ debug: false, prefix: \"[SessionStore]\" });\n\n // Flush all pending on process exit\n const flushAllAndExit = async () => {\n const flushPromises: Promise<void>[] = [];\n for (const sessionId of this.configs.keys()) {\n flushPromises.push(this.flush(sessionId));\n }\n await Promise.all(flushPromises);\n process.exit(0);\n };\n\n process.on(\"beforeExit\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n process.on(\"SIGINT\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n process.on(\"SIGTERM\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n }\n\n /** Register a session for persistence */\n register(sessionId: string, config: SessionPersistenceConfig): void {\n this.configs.set(sessionId, config);\n }\n\n /** Unregister and flush pending */\n async unregister(sessionId: string): Promise<void> {\n await this.flush(sessionId);\n this.configs.delete(sessionId);\n }\n\n /** Check if a session is registered for persistence */\n isRegistered(sessionId: string): boolean {\n return this.configs.has(sessionId);\n }\n\n /**\n * Append a raw JSON-RPC line for persistence.\n * Parses and wraps as StoredNotification for the API.\n */\n appendRawLine(sessionId: string, line: string): void {\n const config = this.configs.get(sessionId);\n if (!config) {\n return;\n }\n\n try {\n const message = JSON.parse(line);\n const entry: StoredNotification = {\n type: \"notification\",\n timestamp: new Date().toISOString(),\n notification: message,\n };\n\n const pending = this.pendingEntries.get(sessionId) ?? [];\n pending.push(entry);\n this.pendingEntries.set(sessionId, pending);\n\n this.scheduleFlush(sessionId);\n } catch {\n this.logger.warn(\"Failed to parse raw line for persistence\", {\n sessionId,\n lineLength: line.length,\n });\n }\n }\n\n /** Load raw JSON-RPC messages from S3 */\n async load(logUrl: string): Promise<unknown[]> {\n const response = await fetch(logUrl);\n\n if (!response.ok) {\n return [];\n }\n\n const content = await response.text();\n if (!content.trim()) return [];\n\n return content\n .trim()\n .split(\"\\n\")\n .map((line) => {\n try {\n return JSON.parse(line);\n } catch {\n return null;\n }\n })\n .filter((entry): entry is unknown => entry !== null);\n }\n\n /** Force flush pending entries */\n async flush(sessionId: string): Promise<void> {\n const config = this.configs.get(sessionId);\n const pending = this.pendingEntries.get(sessionId);\n\n if (!config || !pending?.length) return;\n\n this.pendingEntries.delete(sessionId);\n const timeout = this.flushTimeouts.get(sessionId);\n if (timeout) {\n clearTimeout(timeout);\n this.flushTimeouts.delete(sessionId);\n }\n\n if (!this.posthogAPI) {\n this.logger.debug(\"No PostHog API configured, skipping flush\");\n return;\n }\n\n try {\n await this.posthogAPI.appendTaskRunLog(\n config.taskId,\n config.runId,\n pending,\n );\n } catch (error) {\n this.logger.error(\"Failed to persist session logs:\", error);\n }\n }\n\n private scheduleFlush(sessionId: string): void {\n const existing = this.flushTimeouts.get(sessionId);\n if (existing) clearTimeout(existing);\n const timeout = setTimeout(() => this.flush(sessionId), 500);\n this.flushTimeouts.set(sessionId, timeout);\n }\n\n /** Get the persistence config for a session */\n getConfig(sessionId: string): SessionPersistenceConfig | undefined {\n return this.configs.get(sessionId);\n }\n\n /**\n * Start a session for persistence.\n * Loads the task run and updates status to \"in_progress\".\n */\n async start(\n sessionId: string,\n taskId: string,\n runId: string,\n ): Promise<TaskRun | undefined> {\n if (!this.posthogAPI) {\n this.logger.debug(\n \"No PostHog API configured, registering session without persistence\",\n );\n this.register(sessionId, {\n taskId,\n runId,\n logUrl: \"\",\n });\n return undefined;\n }\n\n const taskRun = await this.posthogAPI.getTaskRun(taskId, runId);\n\n this.register(sessionId, {\n taskId,\n runId,\n logUrl: taskRun.log_url,\n });\n\n await this.updateTaskRun(sessionId, { status: \"in_progress\" });\n\n return taskRun;\n }\n\n /**\n * Mark a session as completed.\n */\n async complete(sessionId: string): Promise<void> {\n await this.flush(sessionId);\n await this.updateTaskRun(sessionId, { status: \"completed\" });\n }\n\n /**\n * Mark a session as failed.\n */\n async fail(sessionId: string, error: Error | string): Promise<void> {\n await this.flush(sessionId);\n const message = typeof error === \"string\" ? error : error.message;\n await this.updateTaskRun(sessionId, {\n status: \"failed\",\n error_message: message,\n });\n this.logger.error(\"Session failed\", { sessionId, error: message });\n }\n\n /**\n * Update the task run associated with a session.\n */\n async updateTaskRun(\n sessionId: string,\n update: TaskRunUpdate,\n ): Promise<TaskRun | undefined> {\n const config = this.configs.get(sessionId);\n if (!config) {\n this.logger.error(\n `Cannot update task run: session ${sessionId} not registered`,\n );\n return undefined;\n }\n\n if (!this.posthogAPI) {\n this.logger.debug(\"No PostHog API configured, skipping task run update\");\n return undefined;\n }\n\n try {\n return await this.posthogAPI.updateTaskRun(\n config.taskId,\n config.runId,\n update,\n );\n } catch (error) {\n this.logger.error(\"Failed to update task run:\", error);\n return undefined;\n }\n }\n}\n"],"names":[],"mappings":";;MAWa,YAAY,CAAA;AACf,IAAA,UAAU;AACV,IAAA,cAAc,GAAsC,IAAI,GAAG,EAAE;AAC7D,IAAA,aAAa,GAAgC,IAAI,GAAG,EAAE;AACtD,IAAA,OAAO,GAA0C,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IAEd,WAAA,CAAY,UAA6B,EAAE,MAAe,EAAA;AACxD,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;AAC5B,QAAA,IAAI,CAAC,MAAM;AACT,YAAA,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;;AAGlE,QAAA,MAAM,eAAe,GAAG,YAAW;YACjC,MAAM,aAAa,GAAoB,EAAE;YACzC,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE;gBAC3C,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAC3C;AACA,YAAA,MAAM,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAChC,YAAA,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AACjB,QAAA,CAAC;AAED,QAAA,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,MAAK;YAC5B,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC;AACvE,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAK;YACxB,eA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GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;QAC1C,IAAI,CAAC,MAAM,EAAE;YACX,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,CAAA,gCAAA,EAAmC,SAAS,CAAA,eAAA,CAAiB,CAC9D;AACD,YAAA,OAAO,SAAS;QAClB;AAEA,QAAA,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;AACpB,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qDAAqD,CAAC;AACxE,YAAA,OAAO,SAAS;QAClB;AAEA,QAAA,IAAI;AACF,YAAA,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CACxC,MAAM,CAAC,MAAM,EACb,MAAM,CAAC,KAAK,EACZ,MAAM,CACP;QACH;QAAE,OAAO,KAAK,EAAE;YACd,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC;AACtD,YAAA,OAAO,SAAS;QAClB;IACF;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"session-store.js","sources":["../../src/session-store.ts"],"sourcesContent":["import type { PostHogAPIClient, TaskRunUpdate } from \"./posthog-api.js\";\nimport type { StoredNotification, TaskRun } from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\n\nexport interface SessionPersistenceConfig {\n taskId: string;\n runId: string;\n logUrl: string;\n sdkSessionId?: string;\n}\n\nexport class SessionStore {\n private posthogAPI?: PostHogAPIClient;\n private pendingEntries: Map<string, StoredNotification[]> = new Map();\n private flushTimeouts: Map<string, NodeJS.Timeout> = new Map();\n private configs: Map<string, SessionPersistenceConfig> = new Map();\n private logger: Logger;\n\n constructor(posthogAPI?: PostHogAPIClient, logger?: Logger) {\n this.posthogAPI = posthogAPI;\n this.logger =\n logger ?? new Logger({ debug: false, prefix: \"[SessionStore]\" });\n\n // Flush all pending on process exit\n const flushAllAndExit = async () => {\n const flushPromises: Promise<void>[] = [];\n for (const sessionId of this.configs.keys()) {\n flushPromises.push(this.flush(sessionId));\n }\n await Promise.all(flushPromises);\n process.exit(0);\n };\n\n process.on(\"beforeExit\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n process.on(\"SIGINT\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n process.on(\"SIGTERM\", () => {\n flushAllAndExit().catch((e) => this.logger.error(\"Flush failed:\", e));\n });\n }\n\n /** Register a session for persistence */\n register(sessionId: string, config: SessionPersistenceConfig): void {\n this.configs.set(sessionId, config);\n }\n\n /** Unregister and flush pending */\n async unregister(sessionId: string): Promise<void> {\n await this.flush(sessionId);\n this.configs.delete(sessionId);\n }\n\n /** Check if a session is registered for persistence */\n isRegistered(sessionId: string): boolean {\n return this.configs.has(sessionId);\n }\n\n /**\n * Append a raw JSON-RPC line for persistence.\n * Parses and wraps as StoredNotification for the API.\n */\n appendRawLine(sessionId: string, line: string): void {\n const config = this.configs.get(sessionId);\n if (!config) {\n return;\n }\n\n try {\n const message = JSON.parse(line);\n const entry: StoredNotification = {\n type: \"notification\",\n timestamp: new Date().toISOString(),\n notification: message,\n };\n\n const pending = this.pendingEntries.get(sessionId) ?? [];\n pending.push(entry);\n this.pendingEntries.set(sessionId, pending);\n\n this.scheduleFlush(sessionId);\n } catch {\n this.logger.warn(\"Failed to parse raw line for persistence\", {\n sessionId,\n lineLength: line.length,\n });\n }\n }\n\n /** Load raw JSON-RPC messages from S3 */\n async load(logUrl: string): Promise<StoredNotification[]> {\n const response = await fetch(logUrl);\n\n if (!response.ok) {\n return [];\n }\n\n const content = await response.text();\n if (!content.trim()) return [];\n\n return content\n .trim()\n .split(\"\\n\")\n .map((line) => {\n try {\n return JSON.parse(line) as StoredNotification;\n } catch {\n return null;\n }\n })\n .filter((entry): entry is StoredNotification => entry !== null);\n }\n\n /**\n * Poll S3 for new entries since last check.\n * Used for interrupt handling in cloud mode.\n */\n async pollForNewEntries(\n sessionId: string,\n lastKnownCount: number,\n ): Promise<StoredNotification[]> {\n const config = this.configs.get(sessionId);\n if (!config?.logUrl) return [];\n\n const entries = await this.load(config.logUrl);\n return entries.slice(lastKnownCount);\n }\n\n /** Force flush pending entries */\n async flush(sessionId: string): Promise<void> {\n const config = this.configs.get(sessionId);\n const pending = this.pendingEntries.get(sessionId);\n\n if (!config || !pending?.length) return;\n\n this.pendingEntries.delete(sessionId);\n const timeout = this.flushTimeouts.get(sessionId);\n if (timeout) {\n clearTimeout(timeout);\n this.flushTimeouts.delete(sessionId);\n }\n\n if (!this.posthogAPI) {\n this.logger.debug(\"No PostHog API configured, skipping flush\");\n return;\n }\n\n try {\n await this.posthogAPI.appendTaskRunLog(\n config.taskId,\n config.runId,\n pending,\n );\n } catch (error) {\n this.logger.error(\"Failed to persist session logs:\", error);\n }\n }\n\n private scheduleFlush(sessionId: string): void {\n const existing = this.flushTimeouts.get(sessionId);\n if (existing) clearTimeout(existing);\n const timeout = setTimeout(() => this.flush(sessionId), 500);\n this.flushTimeouts.set(sessionId, timeout);\n }\n\n /** Get the persistence config for a session */\n getConfig(sessionId: string): SessionPersistenceConfig | undefined {\n return this.configs.get(sessionId);\n }\n\n /**\n * Start a session for persistence.\n * Loads the task run and updates status to \"in_progress\".\n */\n async start(\n sessionId: string,\n taskId: string,\n runId: string,\n ): Promise<TaskRun | undefined> {\n if (!this.posthogAPI) {\n this.logger.debug(\n \"No PostHog API configured, registering session without persistence\",\n );\n this.register(sessionId, {\n taskId,\n runId,\n logUrl: \"\",\n });\n return undefined;\n }\n\n const taskRun = await this.posthogAPI.getTaskRun(taskId, runId);\n\n this.register(sessionId, {\n taskId,\n runId,\n logUrl: taskRun.log_url,\n });\n\n await this.updateTaskRun(sessionId, { status: \"in_progress\" });\n\n return taskRun;\n }\n\n /**\n * Mark a session as completed.\n */\n async complete(sessionId: string): Promise<void> {\n await this.flush(sessionId);\n await this.updateTaskRun(sessionId, { status: \"completed\" });\n }\n\n /**\n * Mark a session as failed.\n */\n async fail(sessionId: string, error: Error | string): Promise<void> {\n await this.flush(sessionId);\n const message = typeof error === \"string\" ? error : error.message;\n await this.updateTaskRun(sessionId, {\n status: \"failed\",\n error_message: message,\n });\n this.logger.error(\"Session failed\", { sessionId, error: message });\n }\n\n /**\n * Update the task run associated with a session.\n */\n async updateTaskRun(\n sessionId: string,\n update: TaskRunUpdate,\n ): Promise<TaskRun | undefined> {\n const config = this.configs.get(sessionId);\n if (!config) {\n this.logger.error(\n `Cannot update task run: session ${sessionId} not registered`,\n );\n return undefined;\n }\n\n if (!this.posthogAPI) {\n this.logger.debug(\"No PostHog API configured, skipping task run update\");\n return undefined;\n }\n\n try {\n return await this.posthogAPI.updateTaskRun(\n config.taskId,\n config.runId,\n update,\n );\n } catch (error) {\n this.logger.error(\"Failed to update task run:\", error);\n return undefined;\n }\n }\n}\n"],"names":[],"mappings":";;MAWa,YAAY,CAAA;AACf,IAAA,UAAU;AACV,IAAA,cAAc,GAAsC,IAAI,GAAG,EAAE;AAC7D,IAAA,aAAa,GAAgC,IAAI,GAAG,EAAE;AACtD,IAAA,OAAO,GAA0C,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IAEd,WAAA,CAAY,UAA6B,EAAE,MAAe,EAAA;AACxD,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;AAC5B,QAAA,IAAI,CAAC,MAAM;AACT,YAAA,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;;AAGlE,QAAA,MAAM,eAAe,GAAG,YAAW;YACjC,MAAM,aAAa,GAAoB,EAAE;YACzC,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE;gBAC3C,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAC3C;AACA,YAAA,MAAM,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAChC,YAAA,OAAO,CAAC,IAAI,CAAC,CA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AO,SAAS;QAClB;IACF;AACD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worktree-manager.d.ts","sourceRoot":"","sources":["../../src/worktree-manager.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAK3C,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAgeD,qBAAa,eAAe;IAC1B,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,gBAAgB,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,MAAM,CAAS;gBAEX,MAAM,EAAE,cAAc;IASlC,OAAO,CAAC,gBAAgB;YAIV,aAAa;IAW3B,OAAO,CAAC,aAAa;IAIrB,oBAAoB,IAAI,MAAM;IAO9B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,eAAe;IAIjB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU9C,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC;YA+B9B,0BAA0B;YAkB1B,gBAAgB;IAwBxB,cAAc,IAAI,OAAO,CAAC,YAAY,CAAC;IAyDvC,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAsCnD,eAAe,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAcnE,aAAa,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAU9C,OAAO,CAAC,iBAAiB;
|
|
1
|
+
{"version":3,"file":"worktree-manager.d.ts","sourceRoot":"","sources":["../../src/worktree-manager.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YA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K,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAChD,CAAC;CA+CH"}
|
|
@@ -610,7 +610,7 @@ class WorktreeManager {
|
|
|
610
610
|
// Generate unique worktree name
|
|
611
611
|
const worktreeName = await this.generateUniqueWorktreeName();
|
|
612
612
|
const worktreePath = this.getWorktreePath(worktreeName);
|
|
613
|
-
const branchName = `
|
|
613
|
+
const branchName = `array/${worktreeName}`;
|
|
614
614
|
const baseBranch = await this.getDefaultBranch();
|
|
615
615
|
this.logger.info("Creating worktree", {
|
|
616
616
|
worktreeName,
|
|
@@ -716,10 +716,8 @@ class WorktreeManager {
|
|
|
716
716
|
// 1. Are in our worktree folder (external or in-repo)
|
|
717
717
|
// 2. Have a posthog/ branch prefix (our naming convention)
|
|
718
718
|
const isInWorktreeFolder = worktreePath?.startsWith(worktreeFolderPath);
|
|
719
|
-
const
|
|
720
|
-
if (worktreePath &&
|
|
721
|
-
branchName &&
|
|
722
|
-
(isInWorktreeFolder || isPosthogBranch)) {
|
|
719
|
+
const isArrayBranch = branchName?.startsWith("array/") || branchName?.startsWith("posthog/");
|
|
720
|
+
if (worktreePath && branchName && (isInWorktreeFolder || isArrayBranch)) {
|
|
723
721
|
const worktreeName = path.basename(worktreePath);
|
|
724
722
|
worktrees.push({
|
|
725
723
|
worktreePath,
|