@posthog/agent 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +221 -219
  3. package/dist/adapters/claude/conversion/tool-use-to-acp.d.ts +21 -0
  4. package/dist/adapters/claude/conversion/tool-use-to-acp.js +547 -0
  5. package/dist/adapters/claude/conversion/tool-use-to-acp.js.map +1 -0
  6. package/dist/adapters/claude/permissions/permission-options.d.ts +13 -0
  7. package/dist/adapters/claude/permissions/permission-options.js +117 -0
  8. package/dist/adapters/claude/permissions/permission-options.js.map +1 -0
  9. package/dist/adapters/claude/questions/utils.d.ts +132 -0
  10. package/dist/adapters/claude/questions/utils.js +63 -0
  11. package/dist/adapters/claude/questions/utils.js.map +1 -0
  12. package/dist/adapters/claude/tools.d.ts +18 -0
  13. package/dist/adapters/claude/tools.js +95 -0
  14. package/dist/adapters/claude/tools.js.map +1 -0
  15. package/dist/agent-DBQY1BfC.d.ts +123 -0
  16. package/dist/agent.d.ts +5 -0
  17. package/dist/agent.js +3656 -0
  18. package/dist/agent.js.map +1 -0
  19. package/dist/claude-cli/cli.js +3695 -2746
  20. package/dist/claude-cli/vendor/ripgrep/COPYING +3 -0
  21. package/dist/claude-cli/vendor/ripgrep/arm64-darwin/rg +0 -0
  22. package/dist/claude-cli/vendor/ripgrep/arm64-darwin/ripgrep.node +0 -0
  23. package/dist/claude-cli/vendor/ripgrep/arm64-linux/rg +0 -0
  24. package/dist/claude-cli/vendor/ripgrep/arm64-linux/ripgrep.node +0 -0
  25. package/dist/claude-cli/vendor/ripgrep/x64-darwin/rg +0 -0
  26. package/dist/claude-cli/vendor/ripgrep/x64-darwin/ripgrep.node +0 -0
  27. package/dist/claude-cli/vendor/ripgrep/x64-linux/rg +0 -0
  28. package/dist/claude-cli/vendor/ripgrep/x64-linux/ripgrep.node +0 -0
  29. package/dist/claude-cli/vendor/ripgrep/x64-win32/rg.exe +0 -0
  30. package/dist/claude-cli/vendor/ripgrep/x64-win32/ripgrep.node +0 -0
  31. package/dist/gateway-models.d.ts +24 -0
  32. package/dist/gateway-models.js +93 -0
  33. package/dist/gateway-models.js.map +1 -0
  34. package/dist/index.d.ts +170 -1157
  35. package/dist/index.js +3252 -5074
  36. package/dist/index.js.map +1 -1
  37. package/dist/logger-DDBiMOOD.d.ts +24 -0
  38. package/dist/posthog-api.d.ts +40 -0
  39. package/dist/posthog-api.js +175 -0
  40. package/dist/posthog-api.js.map +1 -0
  41. package/dist/server/agent-server.d.ts +41 -0
  42. package/dist/server/agent-server.js +4451 -0
  43. package/dist/server/agent-server.js.map +1 -0
  44. package/dist/server/bin.d.ts +1 -0
  45. package/dist/server/bin.js +4507 -0
  46. package/dist/server/bin.js.map +1 -0
  47. package/dist/types.d.ts +129 -0
  48. package/dist/types.js +1 -0
  49. package/dist/types.js.map +1 -0
  50. package/package.json +66 -14
  51. package/src/acp-extensions.ts +98 -16
  52. package/src/adapters/acp-connection.ts +494 -0
  53. package/src/adapters/base-acp-agent.ts +150 -0
  54. package/src/adapters/claude/claude-agent.ts +596 -0
  55. package/src/adapters/claude/conversion/acp-to-sdk.ts +102 -0
  56. package/src/adapters/claude/conversion/sdk-to-acp.ts +571 -0
  57. package/src/adapters/claude/conversion/tool-use-to-acp.ts +618 -0
  58. package/src/adapters/claude/hooks.ts +64 -0
  59. package/src/adapters/claude/mcp/tool-metadata.ts +102 -0
  60. package/src/adapters/claude/permissions/permission-handlers.ts +433 -0
  61. package/src/adapters/claude/permissions/permission-options.ts +103 -0
  62. package/src/adapters/claude/plan/utils.ts +56 -0
  63. package/src/adapters/claude/questions/utils.ts +92 -0
  64. package/src/adapters/claude/session/commands.ts +38 -0
  65. package/src/adapters/claude/session/mcp-config.ts +37 -0
  66. package/src/adapters/claude/session/models.ts +12 -0
  67. package/src/adapters/claude/session/options.ts +236 -0
  68. package/src/adapters/claude/tool-meta.ts +143 -0
  69. package/src/adapters/claude/tools.ts +53 -688
  70. package/src/adapters/claude/types.ts +61 -0
  71. package/src/adapters/codex/spawn.ts +130 -0
  72. package/src/agent.ts +96 -587
  73. package/src/execution-mode.ts +43 -0
  74. package/src/gateway-models.ts +135 -0
  75. package/src/index.ts +79 -0
  76. package/src/otel-log-writer.test.ts +105 -0
  77. package/src/otel-log-writer.ts +94 -0
  78. package/src/posthog-api.ts +75 -235
  79. package/src/resume.ts +115 -0
  80. package/src/sagas/apply-snapshot-saga.test.ts +690 -0
  81. package/src/sagas/apply-snapshot-saga.ts +88 -0
  82. package/src/sagas/capture-tree-saga.test.ts +892 -0
  83. package/src/sagas/capture-tree-saga.ts +141 -0
  84. package/src/sagas/resume-saga.test.ts +558 -0
  85. package/src/sagas/resume-saga.ts +332 -0
  86. package/src/sagas/test-fixtures.ts +250 -0
  87. package/src/server/agent-server.test.ts +220 -0
  88. package/src/server/agent-server.ts +748 -0
  89. package/src/server/bin.ts +88 -0
  90. package/src/server/jwt.ts +65 -0
  91. package/src/server/schemas.ts +47 -0
  92. package/src/server/types.ts +13 -0
  93. package/src/server/utils/retry.test.ts +122 -0
  94. package/src/server/utils/retry.ts +61 -0
  95. package/src/server/utils/sse-parser.test.ts +93 -0
  96. package/src/server/utils/sse-parser.ts +46 -0
  97. package/src/session-log-writer.test.ts +140 -0
  98. package/src/session-log-writer.ts +137 -0
  99. package/src/test/assertions.ts +114 -0
  100. package/src/test/controllers/sse-controller.ts +107 -0
  101. package/src/test/fixtures/api.ts +111 -0
  102. package/src/test/fixtures/config.ts +33 -0
  103. package/src/test/fixtures/notifications.ts +92 -0
  104. package/src/test/mocks/claude-sdk.ts +251 -0
  105. package/src/test/mocks/msw-handlers.ts +48 -0
  106. package/src/test/setup.ts +114 -0
  107. package/src/test/wait.ts +41 -0
  108. package/src/tree-tracker.ts +173 -0
  109. package/src/types.ts +54 -137
  110. package/src/utils/acp-content.ts +58 -0
  111. package/src/utils/async-mutex.test.ts +104 -0
  112. package/src/utils/async-mutex.ts +31 -0
  113. package/src/utils/common.ts +15 -0
  114. package/src/utils/gateway.ts +9 -6
  115. package/src/utils/logger.ts +0 -30
  116. package/src/utils/streams.ts +220 -0
  117. package/CLAUDE.md +0 -331
  118. package/src/adapters/claude/claude.ts +0 -1947
  119. package/src/adapters/claude/mcp-server.ts +0 -810
  120. package/src/adapters/claude/utils.ts +0 -267
  121. package/src/adapters/connection.ts +0 -95
  122. package/src/file-manager.ts +0 -273
  123. package/src/git-manager.ts +0 -577
  124. package/src/schemas.ts +0 -241
  125. package/src/session-store.ts +0 -259
  126. package/src/task-manager.ts +0 -163
  127. package/src/todo-manager.ts +0 -180
  128. package/src/tools/registry.ts +0 -134
  129. package/src/tools/types.ts +0 -133
  130. package/src/utils/tapped-stream.ts +0 -60
  131. package/src/worktree-manager.ts +0 -974
package/dist/index.d.ts CHANGED
@@ -1,7 +1,13 @@
1
- import { AgentSideConnection } from '@agentclientprotocol/sdk';
2
- export { SessionNotification } from '@agentclientprotocol/sdk';
3
- import { CanUseTool } from '@anthropic-ai/claude-agent-sdk';
4
- import { z } from 'zod';
1
+ export { A as AcpConnection, a as AcpConnectionConfig, b as Agent, c as AgentAdapter, C as CodexProcessOptions, I as InProcessAcpConnection, O as OtelLogConfig, d as OtelLogWriter, S as SessionContext, e as SessionLogWriter, f as SessionLogWriterOptions, g as createAcpConnection } from './agent-DBQY1BfC.js';
2
+ import { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
3
+ import { L as Logger } from './logger-DDBiMOOD.js';
4
+ export { a as LoggerConfig } from './logger-DDBiMOOD.js';
5
+ export { ArrayModelInfo, BLOCKED_MODELS, DEFAULT_GATEWAY_MODEL, FetchGatewayModelsOptions, GatewayModel, fetchArrayModels, fetchGatewayModels, formatGatewayModelName, getProviderName, isAnthropicModel } from './gateway-models.js';
6
+ import { PostHogAPIClient } from './posthog-api.js';
7
+ export { getLlmGatewayUrl } from './posthog-api.js';
8
+ import { ContentBlock } from '@agentclientprotocol/sdk';
9
+ import { TreeSnapshotEvent, DeviceInfo, TreeSnapshot } from './types.js';
10
+ export { AgentConfig, AgentMode, FileChange, FileStatus, LogLevel, OnLogCallback, OtelTransportConfig, StoredEntry, StoredNotification, Task, TaskRun } from './types.js';
5
11
 
6
12
  /**
7
13
  * PostHog-specific ACP extensions.
@@ -10,6 +16,10 @@ import { z } from 'zod';
10
16
  * - Custom notification methods are prefixed with `_posthog/`
11
17
  * - Custom data can be attached via `_meta` fields
12
18
  *
19
+ * Note: When using `extNotification()` from the ACP SDK, it automatically
20
+ * adds an extra underscore prefix (e.g., `_posthog/tree_snapshot` becomes
21
+ * `__posthog/tree_snapshot` in the log). Code that reads logs should handle both.
22
+ *
13
23
  * See: https://agentclientprotocol.com/docs/extensibility
14
24
  */
15
25
  /**
@@ -17,18 +27,36 @@ import { z } from 'zod';
17
27
  * Used with AgentSideConnection.extNotification() or Client.extNotification()
18
28
  */
19
29
  declare const POSTHOG_NOTIFICATIONS: {
20
- /** Git branch was created */
30
+ /** Git branch was created for a task */
21
31
  readonly BRANCH_CREATED: "_posthog/branch_created";
22
- /** Task run has started */
32
+ /** Task run has started execution */
23
33
  readonly RUN_STARTED: "_posthog/run_started";
24
- /** Task has completed */
34
+ /** Task has completed (success or failure) */
25
35
  readonly TASK_COMPLETE: "_posthog/task_complete";
26
36
  /** Error occurred during task execution */
27
37
  readonly ERROR: "_posthog/error";
28
- /** Console/log output */
38
+ /** Console/log output from the agent */
29
39
  readonly CONSOLE: "_posthog/console";
30
- /** SDK session ID notification (for resumption) */
40
+ /** Maps taskRunId to agent's sessionId and adapter type (for resumption) */
31
41
  readonly SDK_SESSION: "_posthog/sdk_session";
42
+ /** Tree state snapshot captured (git tree hash + file archive) */
43
+ readonly TREE_SNAPSHOT: "_posthog/tree_snapshot";
44
+ /** Agent mode changed (interactive/background) */
45
+ readonly MODE_CHANGE: "_posthog/mode_change";
46
+ /** Request to resume a session from previous state */
47
+ readonly SESSION_RESUME: "_posthog/session/resume";
48
+ /** User message sent from client to agent */
49
+ readonly USER_MESSAGE: "_posthog/user_message";
50
+ /** Request to cancel current operation */
51
+ readonly CANCEL: "_posthog/cancel";
52
+ /** Request to close the session */
53
+ readonly CLOSE: "_posthog/close";
54
+ /** Agent status update (thinking, working, etc.) */
55
+ readonly STATUS: "_posthog/status";
56
+ /** Task-level notification (progress, milestones) */
57
+ readonly TASK_NOTIFICATION: "_posthog/task_notification";
58
+ /** Marks a boundary for log compaction */
59
+ readonly COMPACT_BOUNDARY: "_posthog/compact_boundary";
32
60
  };
33
61
  type PostHogNotificationType = (typeof POSTHOG_NOTIFICATIONS)[keyof typeof POSTHOG_NOTIFICATIONS];
34
62
  interface BranchCreatedPayload {
@@ -39,9 +67,6 @@ interface RunStartedPayload {
39
67
  runId: string;
40
68
  taskId?: string;
41
69
  }
42
- /**
43
- * Payload for task complete notification
44
- */
45
70
  interface TaskCompletePayload {
46
71
  sessionId: string;
47
72
  taskId: string;
@@ -51,1196 +76,184 @@ interface ErrorNotificationPayload {
51
76
  message: string;
52
77
  error?: unknown;
53
78
  }
54
- /**
55
- * Console output for a session
56
- */
57
79
  interface ConsoleNotificationPayload {
58
80
  sessionId: string;
59
81
  level: "debug" | "info" | "warn" | "error";
60
82
  message: string;
61
83
  }
62
- /**
63
- * Maps a session ID to a SDKs session ID
64
- */
65
84
  interface SdkSessionPayload {
85
+ taskRunId: string;
66
86
  sessionId: string;
67
- sdkSessionId: string;
68
- }
69
- type PostHogNotificationPayload = BranchCreatedPayload | RunStartedPayload | TaskCompletePayload | ErrorNotificationPayload | ConsoleNotificationPayload | SdkSessionPayload;
70
-
71
- /**
72
- * Stored custom notification following ACP extensibility model.
73
- * Custom notifications use underscore-prefixed methods (e.g., `_posthog/phase_start`).
74
- * See: https://agentclientprotocol.com/docs/extensibility
75
- */
76
- interface StoredNotification {
77
- type: "notification";
78
- /** When this notification was stored */
87
+ adapter: "claude" | "codex";
88
+ }
89
+ interface TreeSnapshotPayload {
90
+ treeHash: string;
91
+ baseCommit: string | null;
92
+ archiveUrl?: string;
93
+ changes: Array<{
94
+ path: string;
95
+ status: "A" | "M" | "D";
96
+ }>;
79
97
  timestamp: string;
80
- /** JSON-RPC 2.0 notification (no id field = notification, not request) */
81
- notification: {
82
- jsonrpc: "2.0";
83
- method: string;
84
- params?: Record<string, unknown>;
85
- };
86
- }
87
- /**
88
- * Type alias for stored log entries.
89
- */
90
- type StoredEntry = StoredNotification;
91
- interface Task {
92
- id: string;
93
- task_number?: number;
94
- slug?: string;
95
- title: string;
96
- description: string;
97
- origin_product: "error_tracking" | "eval_clusters" | "user_created" | "support_queue" | "session_summaries";
98
- github_integration?: number | null;
99
- repository: string;
100
- json_schema?: Record<string, unknown> | null;
101
- created_at: string;
102
- updated_at: string;
103
- created_by?: {
104
- id: number;
105
- uuid: string;
106
- distinct_id: string;
107
- first_name: string;
108
- email: string;
98
+ interrupted?: boolean;
99
+ device?: {
100
+ type: "local" | "cloud";
101
+ name?: string;
109
102
  };
110
- latest_run?: TaskRun;
111
103
  }
112
- type ArtifactType = "plan" | "context" | "reference" | "output" | "artifact";
113
- interface TaskRunArtifact {
114
- name: string;
115
- type: ArtifactType;
116
- size?: number;
117
- content_type?: string;
118
- storage_path?: string;
119
- uploaded_at?: string;
104
+ interface ModeChangePayload {
105
+ mode: "interactive" | "background";
106
+ previous_mode: "interactive" | "background";
120
107
  }
121
- type TaskRunStatus = "not_started" | "queued" | "in_progress" | "completed" | "failed" | "cancelled";
122
- type TaskRunEnvironment = "local" | "cloud";
123
- interface TaskRun {
124
- id: string;
125
- task: string;
126
- team: number;
127
- branch: string | null;
128
- stage: string | null;
129
- environment: TaskRunEnvironment;
130
- status: TaskRunStatus;
131
- log_url: string;
132
- error_message: string | null;
133
- output: Record<string, unknown> | null;
134
- state: Record<string, unknown>;
135
- artifacts?: TaskRunArtifact[];
136
- created_at: string;
137
- updated_at: string;
138
- completed_at: string | null;
139
- }
140
- interface SupportingFile {
141
- name: string;
142
- content: string;
143
- type: ArtifactType;
144
- created_at: string;
108
+ interface SessionResumePayload {
109
+ sessionId: string;
110
+ fromSnapshot?: string;
145
111
  }
146
- interface TaskArtifactUploadPayload {
147
- name: string;
148
- type: ArtifactType;
112
+ interface UserMessagePayload {
149
113
  content: string;
150
- content_type?: string;
151
- }
152
- declare enum PermissionMode {
153
- PLAN = "plan",
154
- DEFAULT = "default",
155
- ACCEPT_EDITS = "acceptEdits",
156
- BYPASS = "bypassPermissions"
157
- }
158
- interface TaskExecutionOptions {
159
- repositoryPath?: string;
160
- permissionMode?: PermissionMode;
161
- isCloudMode?: boolean;
162
- createPR?: boolean;
163
- autoProgress?: boolean;
164
- queryOverrides?: Record<string, unknown>;
165
- canUseTool?: CanUseTool;
166
- skipGitBranch?: boolean;
167
- framework?: "claude";
168
- task?: Task;
169
- isReconnect?: boolean;
170
114
  }
171
- interface ExecutionResult {
172
- results: any[];
173
- }
174
- type McpServerConfig = {
175
- type?: "stdio";
176
- command: string;
177
- args?: string[];
178
- env?: Record<string, string>;
179
- } | {
180
- type: "sse";
181
- url: string;
182
- headers?: Record<string, string>;
183
- } | {
184
- type: "http";
185
- url: string;
186
- headers?: Record<string, string>;
187
- } | {
188
- type: "sdk";
189
- name: string;
190
- instance?: any;
191
- };
192
- type LogLevel$1 = "debug" | "info" | "warn" | "error";
193
- type OnLogCallback = (level: LogLevel$1, scope: string, message: string, data?: unknown) => void;
194
- interface AgentConfig {
195
- workingDirectory?: string;
196
- posthogApiUrl?: string;
197
- getPosthogApiKey?: () => string;
198
- posthogProjectId?: number;
199
- posthogMcpUrl?: string;
200
- mcpServers?: Record<string, McpServerConfig>;
201
- debug?: boolean;
202
- onLog?: OnLogCallback;
203
- canUseTool?: CanUseTool;
204
- }
205
- interface PostHogAPIConfig {
206
- apiUrl: string;
207
- getApiKey: () => string;
208
- projectId: number;
209
- }
210
- type ResourceType = "error" | "experiment" | "insight" | "feature_flag" | "generic";
211
- interface PostHogResource {
212
- type: ResourceType;
213
- id: string;
214
- url: string;
215
- title?: string;
216
- content: string;
217
- metadata?: Record<string, any>;
115
+ interface StatusPayload {
116
+ sessionId: string;
117
+ status: string;
118
+ message?: string;
218
119
  }
219
- interface UrlMention {
220
- url: string;
221
- type: ResourceType;
222
- id?: string;
223
- label?: string;
120
+ interface TaskNotificationPayload {
121
+ sessionId: string;
122
+ type: string;
123
+ message?: string;
124
+ data?: Record<string, unknown>;
224
125
  }
225
- interface WorktreeInfo {
226
- worktreePath: string;
227
- worktreeName: string;
228
- branchName: string;
229
- baseBranch: string;
230
- createdAt: string;
126
+ interface CompactBoundaryPayload {
127
+ sessionId: string;
128
+ timestamp: string;
231
129
  }
130
+ type PostHogNotificationPayload = BranchCreatedPayload | RunStartedPayload | TaskCompletePayload | ErrorNotificationPayload | ConsoleNotificationPayload | SdkSessionPayload | TreeSnapshotPayload | ModeChangePayload | SessionResumePayload | UserMessagePayload | StatusPayload | TaskNotificationPayload | CompactBoundaryPayload;
232
131
 
233
- type TaskRunUpdate = Partial<Pick<TaskRun, "status" | "branch" | "stage" | "error_message" | "output" | "state">>;
234
- type TaskCreatePayload = Pick<Task, "description"> & Partial<Pick<Task, "title" | "repository" | "origin_product">>;
235
- declare class PostHogAPIClient {
236
- private config;
237
- constructor(config: PostHogAPIConfig);
238
- private get baseUrl();
239
- private get headers();
240
- private apiRequest;
241
- getTeamId(): number;
242
- getBaseUrl(): string;
243
- getApiKey(): string;
244
- getLlmGatewayUrl(): string;
245
- fetchTask(taskId: string): Promise<Task>;
246
- listTasks(filters?: {
247
- repository?: string;
248
- organization?: string;
249
- origin_product?: string;
250
- }): Promise<Task[]>;
251
- updateTask(taskId: string, updates: Partial<Task>): Promise<Task>;
252
- createTask(payload: TaskCreatePayload): Promise<Task>;
253
- listTaskRuns(taskId: string): Promise<TaskRun[]>;
254
- getTaskRun(taskId: string, runId: string): Promise<TaskRun>;
255
- createTaskRun(taskId: string, payload?: Partial<Omit<TaskRun, "id" | "task" | "team" | "created_at" | "updated_at" | "completed_at" | "artifacts">>): Promise<TaskRun>;
256
- updateTaskRun(taskId: string, runId: string, payload: TaskRunUpdate): Promise<TaskRun>;
257
- setTaskRunOutput(taskId: string, runId: string, output: Record<string, unknown>): Promise<TaskRun>;
258
- appendTaskRunLog(taskId: string, runId: string, entries: StoredEntry[]): Promise<TaskRun>;
259
- uploadTaskArtifacts(taskId: string, runId: string, artifacts: TaskArtifactUploadPayload[]): Promise<TaskRunArtifact[]>;
260
- /**
261
- * Fetch logs from S3 using presigned URL from TaskRun
262
- * @param taskRun - The task run containing the log_url
263
- * @returns Array of stored entries, or empty array if no logs available
264
- */
265
- fetchTaskRunLogs(taskRun: TaskRun): Promise<StoredEntry[]>;
266
- /**
267
- * Fetch error details from PostHog error tracking
268
- */
269
- fetchErrorDetails(errorId: string, projectId?: string): Promise<PostHogResource>;
270
- /**
271
- * Generic resource fetcher by URL or ID
272
- */
273
- fetchResourceByUrl(urlMention: UrlMention): Promise<PostHogResource>;
274
- /**
275
- * Format error data for agent consumption
276
- */
277
- private formatErrorContent;
278
- }
132
+ declare function fetchMcpToolMetadata(mcpServers: Record<string, McpServerConfig>, logger?: Logger): Promise<void>;
133
+ declare function isMcpToolReadOnly(toolName: string): boolean;
279
134
 
280
135
  /**
281
- * Simple logger utility with configurable debug mode and external log forwarding
136
+ * Resume - Restore agent state from persisted log
137
+ *
138
+ * Handles resuming a task from any point:
139
+ * - Fetches log via the PostHog API
140
+ * - Finds latest tree_snapshot event
141
+ * - Rebuilds conversation from log events
142
+ * - Restores working tree from snapshot
143
+ *
144
+ * Uses Saga pattern for atomic operations with clear success/failure tracking.
145
+ *
146
+ * The log is the single source of truth for:
147
+ * - Conversation history (user_message, agent_message_chunk, tool_call, tool_result)
148
+ * - Working tree state (tree_snapshot events)
149
+ * - Session metadata (device info, mode changes)
282
150
  */
283
- declare enum LogLevel {
284
- ERROR = 0,
285
- WARN = 1,
286
- INFO = 2,
287
- DEBUG = 3
288
- }
289
- interface LoggerConfig {
290
- debug?: boolean;
291
- prefix?: string;
292
- scope?: string;
293
- onLog?: OnLogCallback;
294
- }
295
- declare class Logger {
296
- private debugEnabled;
297
- private prefix;
298
- private scope;
299
- private onLog?;
300
- constructor(config?: LoggerConfig);
301
- setDebug(enabled: boolean): void;
302
- setOnLog(onLog: OnLogCallback | undefined): void;
303
- private formatMessage;
304
- private emitLog;
305
- error(message: string, error?: Error | unknown): void;
306
- warn(message: string, data?: unknown): void;
307
- info(message: string, data?: unknown): void;
308
- debug(message: string, data?: unknown): void;
309
- log(level: LogLevel$1, message: string, data?: unknown, scope?: string): void;
310
- /**
311
- * Create a child logger with additional prefix and scope
312
- */
313
- child(childPrefix: string): Logger;
314
- }
315
151
 
316
- interface SessionPersistenceConfig {
152
+ interface ResumeState {
153
+ conversation: ConversationTurn[];
154
+ latestSnapshot: TreeSnapshotEvent | null;
155
+ /** Whether the tree snapshot was successfully applied (files restored) */
156
+ snapshotApplied: boolean;
157
+ interrupted: boolean;
158
+ lastDevice?: DeviceInfo;
159
+ logEntryCount: number;
160
+ }
161
+ interface ConversationTurn {
162
+ role: "user" | "assistant";
163
+ content: ContentBlock[];
164
+ toolCalls?: ToolCallInfo[];
165
+ }
166
+ interface ToolCallInfo {
167
+ toolCallId: string;
168
+ toolName: string;
169
+ input: unknown;
170
+ result?: unknown;
171
+ }
172
+ interface ResumeConfig {
317
173
  taskId: string;
318
174
  runId: string;
319
- logUrl: string;
320
- sdkSessionId?: string;
321
- }
322
- declare class SessionStore {
323
- private posthogAPI?;
324
- private pendingEntries;
325
- private flushTimeouts;
326
- private configs;
327
- private logger;
328
- constructor(posthogAPI?: PostHogAPIClient, logger?: Logger);
329
- /** Register a session for persistence */
330
- register(sessionId: string, config: SessionPersistenceConfig): void;
331
- /** Unregister and flush pending */
332
- unregister(sessionId: string): Promise<void>;
333
- /** Check if a session is registered for persistence */
334
- isRegistered(sessionId: string): boolean;
335
- /**
336
- * Append a raw JSON-RPC line for persistence.
337
- * Parses and wraps as StoredNotification for the API.
338
- */
339
- appendRawLine(sessionId: string, line: string): void;
340
- /** Load raw JSON-RPC messages from S3 */
341
- load(logUrl: string): Promise<StoredNotification[]>;
342
- /**
343
- * Poll S3 for new entries since last check.
344
- * Used for interrupt handling in cloud mode.
345
- */
346
- pollForNewEntries(sessionId: string, lastKnownCount: number): Promise<StoredNotification[]>;
347
- /** Force flush pending entries */
348
- flush(sessionId: string): Promise<void>;
349
- private scheduleFlush;
350
- /** Get the persistence config for a session */
351
- getConfig(sessionId: string): SessionPersistenceConfig | undefined;
352
- /**
353
- * Start a session for persistence.
354
- * Loads the task run and updates status to "in_progress".
355
- */
356
- start(sessionId: string, taskId: string, runId: string): Promise<TaskRun | undefined>;
357
- /**
358
- * Mark a session as completed.
359
- */
360
- complete(sessionId: string): Promise<void>;
361
- /**
362
- * Mark a session as failed.
363
- */
364
- fail(sessionId: string, error: Error | string): Promise<void>;
365
- /**
366
- * Update the task run associated with a session.
367
- */
368
- updateTaskRun(sessionId: string, update: TaskRunUpdate): Promise<TaskRun | undefined>;
175
+ repositoryPath: string;
176
+ apiClient: PostHogAPIClient;
177
+ logger?: Logger;
369
178
  }
370
-
371
- type StreamPair = {
372
- readable: globalThis.ReadableStream<Uint8Array>;
373
- writable: globalThis.WritableStream<Uint8Array>;
374
- };
375
-
376
179
  /**
377
- * Shared ACP connection factory.
180
+ * Resume a task from its persisted log.
181
+ * Returns the rebuilt state for the agent to continue from.
378
182
  *
379
- * Creates ACP connections for the Claude Code agent.
183
+ * Uses Saga pattern internally for atomic operations.
184
+ * Note: snapshotApplied field indicates if files were actually restored -
185
+ * even if latestSnapshot is non-null, files may not have been restored if
186
+ * the snapshot had no archive URL or download/extraction failed.
380
187
  */
188
+ declare function resumeFromLog(config: ResumeConfig): Promise<ResumeState>;
189
+ /**
190
+ * Convert resumed conversation back to API format for continuation.
191
+ */
192
+ declare function conversationToPromptHistory(conversation: ConversationTurn[]): Array<{
193
+ role: "user" | "assistant";
194
+ content: ContentBlock[];
195
+ }>;
381
196
 
382
- type AgentFramework = "claude";
383
- type AcpConnectionConfig = {
384
- framework?: AgentFramework;
385
- sessionStore?: SessionStore;
386
- sessionId?: string;
387
- taskId?: string;
388
- };
389
- type InProcessAcpConnection = {
390
- agentConnection: AgentSideConnection;
391
- clientStreams: StreamPair;
392
- };
393
197
  /**
394
- * Creates an ACP connection with the specified agent framework.
198
+ * TreeTracker - Git tree-based state capture for cloud/local sync
395
199
  *
396
- * @param config - Configuration including framework selection
397
- * @returns Connection with agent and client streams
200
+ * Captures the entire working state as a git tree hash + archive:
201
+ * - Atomic state snapshots (no partial syncs)
202
+ * - Efficient delta detection using git's diffing
203
+ * - Simpler resume logic (restore tree, continue)
204
+ *
205
+ * Uses Saga pattern for atomic operations with automatic rollback on failure.
206
+ * Uses a temporary git index to avoid modifying the user's staging area.
398
207
  */
399
- declare function createAcpConnection(config?: AcpConnectionConfig): InProcessAcpConnection;
400
208
 
401
- declare class Agent {
402
- private workingDirectory;
403
- private taskManager;
404
- private posthogAPI?;
405
- private fileManager;
406
- private gitManager;
209
+ interface TreeTrackerConfig {
210
+ repositoryPath: string;
211
+ taskId: string;
212
+ runId: string;
213
+ apiClient?: PostHogAPIClient;
214
+ logger?: Logger;
215
+ }
216
+ declare class TreeTracker {
217
+ private repositoryPath;
218
+ private taskId;
219
+ private runId;
220
+ private apiClient?;
407
221
  private logger;
408
- private acpConnection?;
409
- private mcpServers?;
410
- private canUseTool?;
411
- private currentRunId?;
412
- private sessionStore?;
413
- debug: boolean;
414
- constructor(config: AgentConfig);
415
- /**
416
- * Enable or disable debug logging
417
- */
418
- setDebug(enabled: boolean): void;
222
+ private lastTreeHash;
223
+ constructor(config: TreeTrackerConfig);
419
224
  /**
420
- * Configure LLM gateway environment variables for Claude Code CLI.
225
+ * Capture current working tree state as a snapshot.
226
+ * Uses a temporary index to avoid modifying user's staging area.
227
+ * Uses Saga pattern for atomic operation with automatic cleanup on failure.
421
228
  */
422
- private _configureLlmGateway;
229
+ captureTree(options?: {
230
+ interrupted?: boolean;
231
+ }): Promise<TreeSnapshot | null>;
423
232
  /**
424
- * @deprecated Use runTaskV2() for local execution or runTaskCloud() for cloud execution.
425
- * This method used the old workflow system which has been removed.
233
+ * Download and apply a tree snapshot.
234
+ * Uses Saga pattern for atomic operation with rollback on failure.
426
235
  */
427
- runTask(_taskId: string, _taskRunId: string, _options?: TaskExecutionOptions): Promise<void>;
236
+ applyTreeSnapshot(snapshot: TreeSnapshot): Promise<void>;
428
237
  /**
429
- * Creates an in-process ACP connection for client communication.
430
- * Sets up git branch for the task, configures LLM gateway.
431
- * The client handles all prompting/querying via the returned streams.
432
- *
433
- * @returns InProcessAcpConnection with clientStreams for the client to use
238
+ * Get the last captured tree hash.
434
239
  */
435
- runTaskV2(taskId: string, taskRunId: string, options?: TaskExecutionOptions): Promise<InProcessAcpConnection>;
436
- fetchTask(taskId: string): Promise<Task>;
437
- getPostHogClient(): PostHogAPIClient | undefined;
240
+ getLastTreeHash(): string | null;
438
241
  /**
439
- * Send a notification to a cloud task run's S3 log.
440
- * The cloud runner will pick up new notifications via interrupt polling.
242
+ * Set the last tree hash (used when resuming).
441
243
  */
442
- sendNotification(taskId: string, runId: string, notification: StoredNotification): Promise<void>;
443
- getTaskFiles(taskId: string): Promise<any[]>;
444
- createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string, customBody?: string): Promise<string>;
445
- attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void>;
446
- updateTaskBranch(taskId: string, branchName: string): Promise<void>;
447
- cancelTask(taskId: string): void;
448
- getTaskExecutionStatus(taskId: string): string | null;
449
- private prepareTaskBranch;
450
- private ensureOpenAIGatewayEnv;
451
- private ensureGeminiGatewayEnv;
452
- runTaskCloud(taskId: string, taskRunId: string, options?: TaskExecutionOptions): Promise<void>;
453
- }
454
-
455
- declare const TokenEventSchema: z.ZodObject<{
456
- ts: z.ZodNumber;
457
- } & {
458
- type: z.ZodLiteral<"token">;
459
- content: z.ZodString;
460
- contentType: z.ZodOptional<z.ZodEnum<["text", "thinking", "tool_input"]>>;
461
- }, "strip", z.ZodTypeAny, {
462
- type: "token";
463
- content: string;
464
- ts: number;
465
- contentType?: "text" | "thinking" | "tool_input" | undefined;
466
- }, {
467
- type: "token";
468
- content: string;
469
- ts: number;
470
- contentType?: "text" | "thinking" | "tool_input" | undefined;
471
- }>;
472
- declare const StatusEventSchema: z.ZodObject<{
473
- ts: z.ZodNumber;
474
- } & {
475
- type: z.ZodLiteral<"status">;
476
- phase: z.ZodString;
477
- kind: z.ZodOptional<z.ZodString>;
478
- branch: z.ZodOptional<z.ZodString>;
479
- prUrl: z.ZodOptional<z.ZodString>;
480
- taskId: z.ZodOptional<z.ZodString>;
481
- messageId: z.ZodOptional<z.ZodString>;
482
- model: z.ZodOptional<z.ZodString>;
483
- }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
484
- ts: z.ZodNumber;
485
- } & {
486
- type: z.ZodLiteral<"status">;
487
- phase: z.ZodString;
488
- kind: z.ZodOptional<z.ZodString>;
489
- branch: z.ZodOptional<z.ZodString>;
490
- prUrl: z.ZodOptional<z.ZodString>;
491
- taskId: z.ZodOptional<z.ZodString>;
492
- messageId: z.ZodOptional<z.ZodString>;
493
- model: z.ZodOptional<z.ZodString>;
494
- }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
495
- ts: z.ZodNumber;
496
- } & {
497
- type: z.ZodLiteral<"status">;
498
- phase: z.ZodString;
499
- kind: z.ZodOptional<z.ZodString>;
500
- branch: z.ZodOptional<z.ZodString>;
501
- prUrl: z.ZodOptional<z.ZodString>;
502
- taskId: z.ZodOptional<z.ZodString>;
503
- messageId: z.ZodOptional<z.ZodString>;
504
- model: z.ZodOptional<z.ZodString>;
505
- }, z.ZodTypeAny, "passthrough">>;
506
- declare const ConsoleEventSchema: z.ZodObject<{
507
- ts: z.ZodNumber;
508
- } & {
509
- type: z.ZodLiteral<"console">;
510
- level: z.ZodEnum<["debug", "info", "warn", "error"]>;
511
- message: z.ZodString;
512
- }, "strip", z.ZodTypeAny, {
513
- type: "console";
514
- message: string;
515
- ts: number;
516
- level: "debug" | "info" | "warn" | "error";
517
- }, {
518
- type: "console";
519
- message: string;
520
- ts: number;
521
- level: "debug" | "info" | "warn" | "error";
522
- }>;
523
- declare const ErrorEventSchema: z.ZodObject<{
524
- ts: z.ZodNumber;
525
- } & {
526
- type: z.ZodLiteral<"error">;
527
- message: z.ZodString;
528
- error: z.ZodOptional<z.ZodUnknown>;
529
- errorType: z.ZodOptional<z.ZodString>;
530
- context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
531
- sdkError: z.ZodOptional<z.ZodUnknown>;
532
- }, "strip", z.ZodTypeAny, {
533
- type: "error";
534
- message: string;
535
- ts: number;
536
- error?: unknown;
537
- context?: Record<string, unknown> | undefined;
538
- errorType?: string | undefined;
539
- sdkError?: unknown;
540
- }, {
541
- type: "error";
542
- message: string;
543
- ts: number;
544
- error?: unknown;
545
- context?: Record<string, unknown> | undefined;
546
- errorType?: string | undefined;
547
- sdkError?: unknown;
548
- }>;
549
- declare const AgentEventSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
550
- ts: z.ZodNumber;
551
- } & {
552
- type: z.ZodLiteral<"token">;
553
- content: z.ZodString;
554
- contentType: z.ZodOptional<z.ZodEnum<["text", "thinking", "tool_input"]>>;
555
- }, "strip", z.ZodTypeAny, {
556
- type: "token";
557
- content: string;
558
- ts: number;
559
- contentType?: "text" | "thinking" | "tool_input" | undefined;
560
- }, {
561
- type: "token";
562
- content: string;
563
- ts: number;
564
- contentType?: "text" | "thinking" | "tool_input" | undefined;
565
- }>, z.ZodObject<{
566
- ts: z.ZodNumber;
567
- } & {
568
- type: z.ZodLiteral<"content_block_start">;
569
- index: z.ZodNumber;
570
- contentType: z.ZodEnum<["text", "tool_use", "thinking"]>;
571
- toolName: z.ZodOptional<z.ZodString>;
572
- toolId: z.ZodOptional<z.ZodString>;
573
- }, "strip", z.ZodTypeAny, {
574
- type: "content_block_start";
575
- ts: number;
576
- contentType: "text" | "tool_use" | "thinking";
577
- index: number;
578
- toolName?: string | undefined;
579
- toolId?: string | undefined;
580
- }, {
581
- type: "content_block_start";
582
- ts: number;
583
- contentType: "text" | "tool_use" | "thinking";
584
- index: number;
585
- toolName?: string | undefined;
586
- toolId?: string | undefined;
587
- }>, z.ZodObject<{
588
- ts: z.ZodNumber;
589
- } & {
590
- type: z.ZodLiteral<"content_block_stop">;
591
- index: z.ZodNumber;
592
- }, "strip", z.ZodTypeAny, {
593
- type: "content_block_stop";
594
- ts: number;
595
- index: number;
596
- }, {
597
- type: "content_block_stop";
598
- ts: number;
599
- index: number;
600
- }>, z.ZodObject<{
601
- ts: z.ZodNumber;
602
- } & {
603
- type: z.ZodLiteral<"tool_call">;
604
- toolName: z.ZodString;
605
- callId: z.ZodString;
606
- args: z.ZodRecord<z.ZodString, z.ZodUnknown>;
607
- parentToolUseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
608
- tool: z.ZodOptional<z.ZodUnknown>;
609
- category: z.ZodOptional<z.ZodUnknown>;
610
- }, "strip", z.ZodTypeAny, {
611
- type: "tool_call";
612
- args: Record<string, unknown>;
613
- toolName: string;
614
- ts: number;
615
- callId: string;
616
- parentToolUseId?: string | null | undefined;
617
- tool?: unknown;
618
- category?: unknown;
619
- }, {
620
- type: "tool_call";
621
- args: Record<string, unknown>;
622
- toolName: string;
623
- ts: number;
624
- callId: string;
625
- parentToolUseId?: string | null | undefined;
626
- tool?: unknown;
627
- category?: unknown;
628
- }>, z.ZodObject<{
629
- ts: z.ZodNumber;
630
- } & {
631
- type: z.ZodLiteral<"tool_result">;
632
- toolName: z.ZodString;
633
- callId: z.ZodString;
634
- result: z.ZodUnknown;
635
- isError: z.ZodOptional<z.ZodBoolean>;
636
- parentToolUseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
637
- tool: z.ZodOptional<z.ZodUnknown>;
638
- category: z.ZodOptional<z.ZodUnknown>;
639
- }, "strip", z.ZodTypeAny, {
640
- type: "tool_result";
641
- toolName: string;
642
- ts: number;
643
- callId: string;
644
- isError?: boolean | undefined;
645
- result?: unknown;
646
- parentToolUseId?: string | null | undefined;
647
- tool?: unknown;
648
- category?: unknown;
649
- }, {
650
- type: "tool_result";
651
- toolName: string;
652
- ts: number;
653
- callId: string;
654
- isError?: boolean | undefined;
655
- result?: unknown;
656
- parentToolUseId?: string | null | undefined;
657
- tool?: unknown;
658
- category?: unknown;
659
- }>, z.ZodObject<{
660
- ts: z.ZodNumber;
661
- } & {
662
- type: z.ZodLiteral<"message_start">;
663
- messageId: z.ZodOptional<z.ZodString>;
664
- model: z.ZodOptional<z.ZodString>;
665
- }, "strip", z.ZodTypeAny, {
666
- type: "message_start";
667
- ts: number;
668
- messageId?: string | undefined;
669
- model?: string | undefined;
670
- }, {
671
- type: "message_start";
672
- ts: number;
673
- messageId?: string | undefined;
674
- model?: string | undefined;
675
- }>, z.ZodObject<{
676
- ts: z.ZodNumber;
677
- } & {
678
- type: z.ZodLiteral<"message_delta">;
679
- stopReason: z.ZodOptional<z.ZodString>;
680
- stopSequence: z.ZodOptional<z.ZodString>;
681
- usage: z.ZodOptional<z.ZodObject<{
682
- outputTokens: z.ZodNumber;
683
- }, "strip", z.ZodTypeAny, {
684
- outputTokens: number;
685
- }, {
686
- outputTokens: number;
687
- }>>;
688
- }, "strip", z.ZodTypeAny, {
689
- type: "message_delta";
690
- ts: number;
691
- stopReason?: string | undefined;
692
- stopSequence?: string | undefined;
693
- usage?: {
694
- outputTokens: number;
695
- } | undefined;
696
- }, {
697
- type: "message_delta";
698
- ts: number;
699
- stopReason?: string | undefined;
700
- stopSequence?: string | undefined;
701
- usage?: {
702
- outputTokens: number;
703
- } | undefined;
704
- }>, z.ZodObject<{
705
- ts: z.ZodNumber;
706
- } & {
707
- type: z.ZodLiteral<"message_stop">;
708
- }, "strip", z.ZodTypeAny, {
709
- type: "message_stop";
710
- ts: number;
711
- }, {
712
- type: "message_stop";
713
- ts: number;
714
- }>, z.ZodObject<{
715
- ts: z.ZodNumber;
716
- } & {
717
- type: z.ZodLiteral<"user_message">;
718
- content: z.ZodString;
719
- isSynthetic: z.ZodOptional<z.ZodBoolean>;
720
- }, "strip", z.ZodTypeAny, {
721
- type: "user_message";
722
- content: string;
723
- ts: number;
724
- isSynthetic?: boolean | undefined;
725
- }, {
726
- type: "user_message";
727
- content: string;
728
- ts: number;
729
- isSynthetic?: boolean | undefined;
730
- }>, z.ZodObject<{
731
- ts: z.ZodNumber;
732
- } & {
733
- type: z.ZodLiteral<"status">;
734
- phase: z.ZodString;
735
- kind: z.ZodOptional<z.ZodString>;
736
- branch: z.ZodOptional<z.ZodString>;
737
- prUrl: z.ZodOptional<z.ZodString>;
738
- taskId: z.ZodOptional<z.ZodString>;
739
- messageId: z.ZodOptional<z.ZodString>;
740
- model: z.ZodOptional<z.ZodString>;
741
- }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
742
- ts: z.ZodNumber;
743
- } & {
744
- type: z.ZodLiteral<"status">;
745
- phase: z.ZodString;
746
- kind: z.ZodOptional<z.ZodString>;
747
- branch: z.ZodOptional<z.ZodString>;
748
- prUrl: z.ZodOptional<z.ZodString>;
749
- taskId: z.ZodOptional<z.ZodString>;
750
- messageId: z.ZodOptional<z.ZodString>;
751
- model: z.ZodOptional<z.ZodString>;
752
- }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
753
- ts: z.ZodNumber;
754
- } & {
755
- type: z.ZodLiteral<"status">;
756
- phase: z.ZodString;
757
- kind: z.ZodOptional<z.ZodString>;
758
- branch: z.ZodOptional<z.ZodString>;
759
- prUrl: z.ZodOptional<z.ZodString>;
760
- taskId: z.ZodOptional<z.ZodString>;
761
- messageId: z.ZodOptional<z.ZodString>;
762
- model: z.ZodOptional<z.ZodString>;
763
- }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{
764
- ts: z.ZodNumber;
765
- } & {
766
- type: z.ZodLiteral<"init">;
767
- model: z.ZodString;
768
- tools: z.ZodArray<z.ZodString, "many">;
769
- permissionMode: z.ZodString;
770
- cwd: z.ZodString;
771
- apiKeySource: z.ZodString;
772
- agents: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
773
- slashCommands: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
774
- outputStyle: z.ZodOptional<z.ZodString>;
775
- mcpServers: z.ZodOptional<z.ZodArray<z.ZodObject<{
776
- name: z.ZodString;
777
- status: z.ZodString;
778
- }, "strip", z.ZodTypeAny, {
779
- status: string;
780
- name: string;
781
- }, {
782
- status: string;
783
- name: string;
784
- }>, "many">>;
785
- }, "strip", z.ZodTypeAny, {
786
- type: "init";
787
- tools: string[];
788
- ts: number;
789
- model: string;
790
- permissionMode: string;
791
- cwd: string;
792
- apiKeySource: string;
793
- agents?: string[] | undefined;
794
- slashCommands?: string[] | undefined;
795
- outputStyle?: string | undefined;
796
- mcpServers?: {
797
- status: string;
798
- name: string;
799
- }[] | undefined;
800
- }, {
801
- type: "init";
802
- tools: string[];
803
- ts: number;
804
- model: string;
805
- permissionMode: string;
806
- cwd: string;
807
- apiKeySource: string;
808
- agents?: string[] | undefined;
809
- slashCommands?: string[] | undefined;
810
- outputStyle?: string | undefined;
811
- mcpServers?: {
812
- status: string;
813
- name: string;
814
- }[] | undefined;
815
- }>, z.ZodObject<{
816
- ts: z.ZodNumber;
817
- } & {
818
- type: z.ZodLiteral<"console">;
819
- level: z.ZodEnum<["debug", "info", "warn", "error"]>;
820
- message: z.ZodString;
821
- }, "strip", z.ZodTypeAny, {
822
- type: "console";
823
- message: string;
824
- ts: number;
825
- level: "debug" | "info" | "warn" | "error";
826
- }, {
827
- type: "console";
828
- message: string;
829
- ts: number;
830
- level: "debug" | "info" | "warn" | "error";
831
- }>, z.ZodObject<{
832
- ts: z.ZodNumber;
833
- } & {
834
- type: z.ZodLiteral<"compact_boundary">;
835
- trigger: z.ZodEnum<["manual", "auto"]>;
836
- preTokens: z.ZodNumber;
837
- }, "strip", z.ZodTypeAny, {
838
- type: "compact_boundary";
839
- ts: number;
840
- trigger: "manual" | "auto";
841
- preTokens: number;
842
- }, {
843
- type: "compact_boundary";
844
- ts: number;
845
- trigger: "manual" | "auto";
846
- preTokens: number;
847
- }>, z.ZodObject<{
848
- ts: z.ZodNumber;
849
- } & {
850
- type: z.ZodLiteral<"done">;
851
- result: z.ZodOptional<z.ZodString>;
852
- durationMs: z.ZodOptional<z.ZodNumber>;
853
- durationApiMs: z.ZodOptional<z.ZodNumber>;
854
- numTurns: z.ZodOptional<z.ZodNumber>;
855
- totalCostUsd: z.ZodOptional<z.ZodNumber>;
856
- usage: z.ZodOptional<z.ZodUnknown>;
857
- modelUsage: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
858
- inputTokens: z.ZodNumber;
859
- outputTokens: z.ZodNumber;
860
- cacheReadInputTokens: z.ZodNumber;
861
- cacheCreationInputTokens: z.ZodNumber;
862
- webSearchRequests: z.ZodNumber;
863
- costUSD: z.ZodNumber;
864
- contextWindow: z.ZodNumber;
865
- }, "strip", z.ZodTypeAny, {
866
- outputTokens: number;
867
- inputTokens: number;
868
- cacheReadInputTokens: number;
869
- cacheCreationInputTokens: number;
870
- webSearchRequests: number;
871
- costUSD: number;
872
- contextWindow: number;
873
- }, {
874
- outputTokens: number;
875
- inputTokens: number;
876
- cacheReadInputTokens: number;
877
- cacheCreationInputTokens: number;
878
- webSearchRequests: number;
879
- costUSD: number;
880
- contextWindow: number;
881
- }>>>;
882
- permissionDenials: z.ZodOptional<z.ZodArray<z.ZodObject<{
883
- tool_name: z.ZodString;
884
- tool_use_id: z.ZodString;
885
- tool_input: z.ZodRecord<z.ZodString, z.ZodUnknown>;
886
- }, "strip", z.ZodTypeAny, {
887
- tool_use_id: string;
888
- tool_input: Record<string, unknown>;
889
- tool_name: string;
890
- }, {
891
- tool_use_id: string;
892
- tool_input: Record<string, unknown>;
893
- tool_name: string;
894
- }>, "many">>;
895
- }, "strip", z.ZodTypeAny, {
896
- type: "done";
897
- ts: number;
898
- result?: string | undefined;
899
- usage?: unknown;
900
- durationMs?: number | undefined;
901
- durationApiMs?: number | undefined;
902
- numTurns?: number | undefined;
903
- totalCostUsd?: number | undefined;
904
- modelUsage?: Record<string, {
905
- outputTokens: number;
906
- inputTokens: number;
907
- cacheReadInputTokens: number;
908
- cacheCreationInputTokens: number;
909
- webSearchRequests: number;
910
- costUSD: number;
911
- contextWindow: number;
912
- }> | undefined;
913
- permissionDenials?: {
914
- tool_use_id: string;
915
- tool_input: Record<string, unknown>;
916
- tool_name: string;
917
- }[] | undefined;
918
- }, {
919
- type: "done";
920
- ts: number;
921
- result?: string | undefined;
922
- usage?: unknown;
923
- durationMs?: number | undefined;
924
- durationApiMs?: number | undefined;
925
- numTurns?: number | undefined;
926
- totalCostUsd?: number | undefined;
927
- modelUsage?: Record<string, {
928
- outputTokens: number;
929
- inputTokens: number;
930
- cacheReadInputTokens: number;
931
- cacheCreationInputTokens: number;
932
- webSearchRequests: number;
933
- costUSD: number;
934
- contextWindow: number;
935
- }> | undefined;
936
- permissionDenials?: {
937
- tool_use_id: string;
938
- tool_input: Record<string, unknown>;
939
- tool_name: string;
940
- }[] | undefined;
941
- }>, z.ZodObject<{
942
- ts: z.ZodNumber;
943
- } & {
944
- type: z.ZodLiteral<"error">;
945
- message: z.ZodString;
946
- error: z.ZodOptional<z.ZodUnknown>;
947
- errorType: z.ZodOptional<z.ZodString>;
948
- context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
949
- sdkError: z.ZodOptional<z.ZodUnknown>;
950
- }, "strip", z.ZodTypeAny, {
951
- type: "error";
952
- message: string;
953
- ts: number;
954
- error?: unknown;
955
- context?: Record<string, unknown> | undefined;
956
- errorType?: string | undefined;
957
- sdkError?: unknown;
958
- }, {
959
- type: "error";
960
- message: string;
961
- ts: number;
962
- error?: unknown;
963
- context?: Record<string, unknown> | undefined;
964
- errorType?: string | undefined;
965
- sdkError?: unknown;
966
- }>, z.ZodObject<{
967
- ts: z.ZodNumber;
968
- } & {
969
- type: z.ZodLiteral<"metric">;
970
- key: z.ZodString;
971
- value: z.ZodNumber;
972
- unit: z.ZodOptional<z.ZodString>;
973
- }, "strip", z.ZodTypeAny, {
974
- key: string;
975
- value: number;
976
- type: "metric";
977
- ts: number;
978
- unit?: string | undefined;
979
- }, {
980
- key: string;
981
- value: number;
982
- type: "metric";
983
- ts: number;
984
- unit?: string | undefined;
985
- }>, z.ZodObject<{
986
- ts: z.ZodNumber;
987
- } & {
988
- type: z.ZodLiteral<"artifact">;
989
- kind: z.ZodString;
990
- content: z.ZodUnknown;
991
- }, "strip", z.ZodTypeAny, {
992
- type: "artifact";
993
- kind: string;
994
- ts: number;
995
- content?: unknown;
996
- }, {
997
- type: "artifact";
998
- kind: string;
999
- ts: number;
1000
- content?: unknown;
1001
- }>, z.ZodObject<{
1002
- ts: z.ZodNumber;
1003
- } & {
1004
- type: z.ZodLiteral<"raw_sdk_event">;
1005
- sdkMessage: z.ZodUnknown;
1006
- }, "strip", z.ZodTypeAny, {
1007
- type: "raw_sdk_event";
1008
- ts: number;
1009
- sdkMessage?: unknown;
1010
- }, {
1011
- type: "raw_sdk_event";
1012
- ts: number;
1013
- sdkMessage?: unknown;
1014
- }>]>;
1015
- type TokenEvent = z.infer<typeof TokenEventSchema>;
1016
- type StatusEvent = z.infer<typeof StatusEventSchema>;
1017
- type ConsoleEvent = z.infer<typeof ConsoleEventSchema>;
1018
- type ErrorEvent = z.infer<typeof ErrorEventSchema>;
1019
- type AgentEvent = z.infer<typeof AgentEventSchema>;
1020
- /**
1021
- * Parse and validate an AgentEvent from unknown input.
1022
- * Returns the parsed event if valid, or null if invalid.
1023
- */
1024
- declare function parseAgentEvent(input: unknown): AgentEvent | null;
1025
- /**
1026
- * Parse and validate multiple AgentEvents from an array of unknown inputs.
1027
- * Invalid entries are discarded.
1028
- */
1029
- declare function parseAgentEvents(inputs: unknown[]): AgentEvent[];
1030
-
1031
- interface TaskFile {
1032
- name: string;
1033
- content: string;
1034
- type: "plan" | "context" | "reference" | "output" | "artifact";
1035
- }
1036
- interface LocalArtifact {
1037
- name: string;
1038
- content: string;
1039
- type: TaskFile["type"];
1040
- contentType: string;
1041
- size: number;
244
+ setLastTreeHash(hash: string | null): void;
1042
245
  }
1043
- declare class PostHogFileManager {
1044
- private repositoryPath;
1045
- private logger;
1046
- constructor(repositoryPath: string, logger?: Logger);
1047
- private getTaskDirectory;
1048
- private getTaskFilePath;
1049
- ensureTaskDirectory(taskId: string): Promise<void>;
1050
- writeTaskFile(taskId: string, file: TaskFile): Promise<void>;
1051
- readTaskFile(taskId: string, fileName: string): Promise<string | null>;
1052
- listTaskFiles(taskId: string): Promise<string[]>;
1053
- deleteTaskFile(taskId: string, fileName: string): Promise<void>;
1054
- taskDirectoryExists(taskId: string): Promise<boolean>;
1055
- cleanupTaskDirectory(taskId: string): Promise<void>;
1056
- writePlan(taskId: string, plan: string): Promise<void>;
1057
- readPlan(taskId: string): Promise<string | null>;
1058
- writeContext(taskId: string, context: string): Promise<void>;
1059
- readContext(taskId: string): Promise<string | null>;
1060
- writeRequirements(taskId: string, requirements: string): Promise<void>;
1061
- readRequirements(taskId: string): Promise<string | null>;
1062
- writeTodos(taskId: string, data: unknown): Promise<void>;
1063
- readTodos(taskId: string): Promise<unknown | null>;
1064
- getTaskFiles(taskId: string): Promise<SupportingFile[]>;
1065
- collectTaskArtifacts(taskId: string): Promise<LocalArtifact[]>;
1066
- private resolveFileType;
1067
- private inferContentType;
1068
- }
1069
-
1070
- interface TodoItem {
1071
- content: string;
1072
- status: "pending" | "in_progress" | "completed";
1073
- activeForm: string;
1074
- }
1075
- interface TodoList {
1076
- items: TodoItem[];
1077
- metadata: {
1078
- total: number;
1079
- pending: number;
1080
- in_progress: number;
1081
- completed: number;
1082
- last_updated: string;
1083
- };
1084
- }
1085
- declare class TodoManager {
1086
- private fileManager;
1087
- private logger;
1088
- constructor(fileManager: PostHogFileManager, logger?: Logger);
1089
- readTodos(taskId: string): Promise<TodoList | null>;
1090
- writeTodos(taskId: string, todos: TodoList): Promise<void>;
1091
- parseTodoWriteInput(toolInput: Record<string, unknown>): TodoList;
1092
- private calculateMetadata;
1093
- getTodoContext(taskId: string): Promise<string>;
1094
- checkAndPersistFromMessage(message: Record<string, unknown>, taskId: string): Promise<TodoList | null>;
1095
- }
1096
-
1097
246
  /**
1098
- * Tool category classification for grouping related tools.
1099
- * Makes it easier for UIs to filter and display tools by function.
247
+ * Check if a commit is available on any remote branch.
248
+ * Used to validate that cloud can fetch the base commit during handoff.
1100
249
  */
1101
- type ToolCategory = "filesystem" | "shell" | "web" | "assistant" | "search" | "unknown";
250
+ declare function isCommitOnRemote(commit: string, cwd: string): Promise<boolean>;
1102
251
  /**
1103
- * Base tool interface representing a tool that can be called by the agent.
1104
- * Each tool has a name, category, and human-readable description.
1105
- */
1106
- interface Tool {
1107
- name: string;
1108
- category: ToolCategory;
1109
- description: string;
1110
- }
1111
- interface ReadTool extends Tool {
1112
- name: "Read";
1113
- category: "filesystem";
1114
- }
1115
- interface WriteTool extends Tool {
1116
- name: "Write";
1117
- category: "filesystem";
1118
- }
1119
- interface EditTool extends Tool {
1120
- name: "Edit";
1121
- category: "filesystem";
1122
- }
1123
- interface GlobTool extends Tool {
1124
- name: "Glob";
1125
- category: "filesystem";
1126
- }
1127
- interface NotebookEditTool extends Tool {
1128
- name: "NotebookEdit";
1129
- category: "filesystem";
1130
- }
1131
- interface BashTool extends Tool {
1132
- name: "Bash";
1133
- category: "shell";
1134
- }
1135
- interface BashOutputTool extends Tool {
1136
- name: "BashOutput";
1137
- category: "shell";
1138
- }
1139
- interface KillShellTool extends Tool {
1140
- name: "KillShell";
1141
- category: "shell";
1142
- }
1143
- interface WebFetchTool extends Tool {
1144
- name: "WebFetch";
1145
- category: "web";
1146
- }
1147
- interface WebSearchTool extends Tool {
1148
- name: "WebSearch";
1149
- category: "web";
1150
- }
1151
- interface GrepTool extends Tool {
1152
- name: "Grep";
1153
- category: "search";
1154
- }
1155
- interface TaskTool extends Tool {
1156
- name: "Task";
1157
- category: "assistant";
1158
- }
1159
- interface TodoWriteTool extends Tool {
1160
- name: "TodoWrite";
1161
- category: "assistant";
1162
- }
1163
- interface ExitPlanModeTool extends Tool {
1164
- name: "ExitPlanMode";
1165
- category: "assistant";
1166
- }
1167
- interface AskUserQuestionTool extends Tool {
1168
- name: "AskUserQuestion";
1169
- category: "assistant";
1170
- }
1171
- interface SlashCommandTool extends Tool {
1172
- name: "SlashCommand";
1173
- category: "assistant";
1174
- }
1175
- /**
1176
- * Union type of all known tool types.
1177
- * Useful for discriminated unions and type narrowing.
1178
- */
1179
- type KnownTool = ReadTool | WriteTool | EditTool | GlobTool | NotebookEditTool | BashTool | BashOutputTool | KillShellTool | WebFetchTool | WebSearchTool | GrepTool | TaskTool | TodoWriteTool | ExitPlanModeTool | AskUserQuestionTool | SlashCommandTool;
1180
-
1181
- /**
1182
- * Tool registry for looking up tool definitions by name.
1183
- * Provides metadata about tools for UI consumption.
252
+ * Validate that a snapshot can be handed off to cloud execution.
253
+ * Cloud needs to be able to fetch the baseCommit from a remote.
254
+ *
255
+ * @throws Error if the snapshot cannot be restored on cloud
1184
256
  */
1185
- declare class ToolRegistry {
1186
- /**
1187
- * Get tool definition by name.
1188
- * Returns undefined if tool is not recognized.
1189
- */
1190
- get(name: string): Tool | undefined;
1191
- /**
1192
- * Get all registered tools.
1193
- */
1194
- getAll(): Tool[];
1195
- /**
1196
- * Check if a tool name is registered.
1197
- */
1198
- has(name: string): boolean;
1199
- /**
1200
- * Get all tools in a specific category.
1201
- */
1202
- getByCategory(category: string): Tool[];
1203
- }
1204
-
1205
- declare function getLlmGatewayUrl(posthogHost: string): string;
1206
-
1207
- interface WorktreeConfig {
1208
- mainRepoPath: string;
1209
- worktreeBasePath?: string;
1210
- logger?: Logger;
1211
- }
1212
- declare class WorktreeManager {
1213
- private mainRepoPath;
1214
- private worktreeBasePath;
1215
- private repoName;
1216
- private logger;
1217
- constructor(config: WorktreeConfig);
1218
- private usesExternalPath;
1219
- private runGitCommand;
1220
- private randomElement;
1221
- generateWorktreeName(): string;
1222
- private getWorktreeFolderPath;
1223
- private getWorktreePath;
1224
- worktreeExists(name: string): Promise<boolean>;
1225
- ensureArrayDirIgnored(): Promise<void>;
1226
- private generateUniqueWorktreeName;
1227
- private getDefaultBranch;
1228
- createWorktree(options?: {
1229
- baseBranch?: string;
1230
- }): Promise<WorktreeInfo>;
1231
- deleteWorktree(worktreePath: string): Promise<void>;
1232
- getWorktreeInfo(worktreePath: string): Promise<WorktreeInfo | null>;
1233
- listWorktrees(): Promise<WorktreeInfo[]>;
1234
- private parseWorktreeList;
1235
- isWorktree(repoPath: string): Promise<boolean>;
1236
- getMainRepoPathFromWorktree(worktreePath: string): Promise<string | null>;
1237
- cleanupOrphanedWorktrees(associatedWorktreePaths: string[]): Promise<{
1238
- deleted: string[];
1239
- errors: Array<{
1240
- path: string;
1241
- error: string;
1242
- }>;
1243
- }>;
1244
- }
257
+ declare function validateForCloudHandoff(snapshot: TreeSnapshot, repositoryPath: string): Promise<void>;
1245
258
 
1246
- export { type AcpConnectionConfig, Agent, type AgentConfig, type AgentEvent, type AgentFramework, type AskUserQuestionTool, type BashOutputTool, type BashTool, type BranchCreatedPayload, type ConsoleEvent, type ConsoleNotificationPayload, type EditTool, type ErrorEvent, type ErrorNotificationPayload, type ExecutionResult, type ExitPlanModeTool, type GlobTool, type GrepTool, type InProcessAcpConnection, type KillShellTool, type KnownTool, LogLevel, type LogLevel$1 as LogLevelType, Logger, type LoggerConfig, type McpServerConfig, type NotebookEditTool, type OnLogCallback, POSTHOG_NOTIFICATIONS, PermissionMode, type PostHogNotificationPayload, type PostHogNotificationType, type ReadTool, type RunStartedPayload, type SdkSessionPayload, type SessionPersistenceConfig, SessionStore, type SlashCommandTool, type StatusEvent, type StoredEntry, type StoredNotification, type SupportingFile, type Task, type TaskCompletePayload, type TaskRun, type TaskTool, type TodoItem, type TodoList, TodoManager, type TodoWriteTool, type TokenEvent, type Tool, type ToolCategory, ToolRegistry, type WebFetchTool, type WebSearchTool, type WorktreeConfig, type WorktreeInfo, WorktreeManager, type WriteTool, createAcpConnection, getLlmGatewayUrl, parseAgentEvent, parseAgentEvents };
259
+ export { type BranchCreatedPayload, type CompactBoundaryPayload, type ConsoleNotificationPayload, type ConversationTurn, DeviceInfo, type ErrorNotificationPayload, Logger, type ModeChangePayload, POSTHOG_NOTIFICATIONS, PostHogAPIClient, type PostHogNotificationPayload, type PostHogNotificationType, type ResumeConfig, type ResumeState, type RunStartedPayload, type SdkSessionPayload, type SessionResumePayload, type StatusPayload, type TaskCompletePayload, type TaskNotificationPayload, type ToolCallInfo, TreeSnapshot, TreeSnapshotEvent, type TreeSnapshotPayload, TreeTracker, type TreeTrackerConfig, type UserMessagePayload, conversationToPromptHistory, fetchMcpToolMetadata, isCommitOnRemote, isMcpToolReadOnly, resumeFromLog, validateForCloudHandoff };