@posthog/agent 2.1.148 → 2.1.152
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/adapters/claude/conversion/tool-use-to-acp.d.ts +2 -0
- package/dist/adapters/claude/conversion/tool-use-to-acp.js +10 -3
- package/dist/adapters/claude/conversion/tool-use-to-acp.js.map +1 -1
- package/dist/agent.js +111 -14
- package/dist/agent.js.map +1 -1
- package/dist/posthog-api.js +1 -1
- package/dist/posthog-api.js.map +1 -1
- package/dist/server/agent-server.d.ts +1 -0
- package/dist/server/agent-server.js +150 -21
- package/dist/server/agent-server.js.map +1 -1
- package/dist/server/bin.cjs +162 -33
- package/dist/server/bin.cjs.map +1 -1
- package/package.json +1 -1
- package/src/adapters/claude/conversion/sdk-to-acp.ts +66 -0
- package/src/adapters/claude/conversion/tool-use-to-acp.ts +33 -5
- package/src/adapters/claude/session/options.ts +9 -0
- package/src/adapters/codex/spawn.ts +1 -1
- package/src/agent.ts +9 -1
- package/src/sagas/apply-snapshot-saga.ts +2 -0
- package/src/sagas/capture-tree-saga.ts +2 -0
- package/src/sagas/resume-saga.ts +2 -0
- package/src/server/agent-server.ts +60 -5
- package/src/session-log-writer.ts +39 -4
package/package.json
CHANGED
|
@@ -192,6 +192,7 @@ function handleToolUseChunk(
|
|
|
192
192
|
const toolInfo = toolInfoFromToolUse(chunk, {
|
|
193
193
|
supportsTerminalOutput: ctx.supportsTerminalOutput,
|
|
194
194
|
toolUseId: chunk.id,
|
|
195
|
+
cachedFileContent: ctx.fileContentCache,
|
|
195
196
|
});
|
|
196
197
|
|
|
197
198
|
const meta: Record<string, unknown> = {
|
|
@@ -221,6 +222,66 @@ function handleToolUseChunk(
|
|
|
221
222
|
};
|
|
222
223
|
}
|
|
223
224
|
|
|
225
|
+
function extractTextFromContent(content: unknown): string | null {
|
|
226
|
+
if (Array.isArray(content)) {
|
|
227
|
+
const parts: string[] = [];
|
|
228
|
+
for (const item of content) {
|
|
229
|
+
if (
|
|
230
|
+
typeof item === "object" &&
|
|
231
|
+
item !== null &&
|
|
232
|
+
"text" in item &&
|
|
233
|
+
typeof (item as Record<string, unknown>).text === "string"
|
|
234
|
+
) {
|
|
235
|
+
parts.push((item as { text: string }).text);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return parts.length > 0 ? parts.join("") : null;
|
|
239
|
+
}
|
|
240
|
+
if (typeof content === "string") {
|
|
241
|
+
return content;
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function stripCatLineNumbers(text: string): string {
|
|
247
|
+
return text.replace(/^ *\d+[\t→]/gm, "");
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function updateFileContentCache(
|
|
251
|
+
toolUse: { name: string; input: unknown },
|
|
252
|
+
chunk: { content?: unknown },
|
|
253
|
+
ctx: ChunkHandlerContext,
|
|
254
|
+
): void {
|
|
255
|
+
const input = toolUse.input as Record<string, unknown> | undefined;
|
|
256
|
+
const filePath = input?.file_path ? String(input.file_path) : undefined;
|
|
257
|
+
if (!filePath) return;
|
|
258
|
+
|
|
259
|
+
if (toolUse.name === "Read" && !input?.limit && !input?.offset) {
|
|
260
|
+
const fileText = extractTextFromContent(chunk.content);
|
|
261
|
+
if (fileText !== null) {
|
|
262
|
+
ctx.fileContentCache[filePath] = stripCatLineNumbers(fileText);
|
|
263
|
+
}
|
|
264
|
+
} else if (toolUse.name === "Write") {
|
|
265
|
+
const content = input?.content;
|
|
266
|
+
if (typeof content === "string") {
|
|
267
|
+
ctx.fileContentCache[filePath] = content;
|
|
268
|
+
}
|
|
269
|
+
} else if (toolUse.name === "Edit") {
|
|
270
|
+
const oldString = input?.old_string;
|
|
271
|
+
const newString = input?.new_string;
|
|
272
|
+
if (
|
|
273
|
+
typeof oldString === "string" &&
|
|
274
|
+
typeof newString === "string" &&
|
|
275
|
+
filePath in ctx.fileContentCache
|
|
276
|
+
) {
|
|
277
|
+
const current = ctx.fileContentCache[filePath];
|
|
278
|
+
ctx.fileContentCache[filePath] = input?.replace_all
|
|
279
|
+
? current.replaceAll(oldString, newString)
|
|
280
|
+
: current.replace(oldString, newString);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
224
285
|
function handleToolResultChunk(
|
|
225
286
|
chunk: AnthropicContentChunk & {
|
|
226
287
|
tool_use_id: string;
|
|
@@ -241,12 +302,17 @@ function handleToolResultChunk(
|
|
|
241
302
|
return [];
|
|
242
303
|
}
|
|
243
304
|
|
|
305
|
+
if (!chunk.is_error) {
|
|
306
|
+
updateFileContentCache(toolUse, chunk, ctx);
|
|
307
|
+
}
|
|
308
|
+
|
|
244
309
|
const { _meta: resultMeta, ...toolUpdate } = toolUpdateFromToolResult(
|
|
245
310
|
chunk as Parameters<typeof toolUpdateFromToolResult>[0],
|
|
246
311
|
toolUse,
|
|
247
312
|
{
|
|
248
313
|
supportsTerminalOutput: ctx.supportsTerminalOutput,
|
|
249
314
|
toolUseId: chunk.tool_use_id,
|
|
315
|
+
cachedFileContent: ctx.fileContentCache,
|
|
250
316
|
},
|
|
251
317
|
);
|
|
252
318
|
|
|
@@ -34,7 +34,11 @@ type ToolInfo = Pick<ToolCall, "title" | "kind" | "content" | "locations">;
|
|
|
34
34
|
|
|
35
35
|
export function toolInfoFromToolUse(
|
|
36
36
|
toolUse: Pick<ToolUseBlock, "name" | "input">,
|
|
37
|
-
options?: {
|
|
37
|
+
options?: {
|
|
38
|
+
supportsTerminalOutput?: boolean;
|
|
39
|
+
toolUseId?: string;
|
|
40
|
+
cachedFileContent?: Record<string, string>;
|
|
41
|
+
},
|
|
38
42
|
): ToolInfo {
|
|
39
43
|
const name = toolUse.name;
|
|
40
44
|
const input = toolUse.input as Record<string, unknown> | undefined;
|
|
@@ -144,8 +148,24 @@ export function toolInfoFromToolUse(
|
|
|
144
148
|
|
|
145
149
|
case "Edit": {
|
|
146
150
|
const path = input?.file_path ? String(input.file_path) : undefined;
|
|
147
|
-
|
|
148
|
-
|
|
151
|
+
let oldText: string | null = input?.old_string
|
|
152
|
+
? String(input.old_string)
|
|
153
|
+
: null;
|
|
154
|
+
let newText: string = input?.new_string ? String(input.new_string) : "";
|
|
155
|
+
|
|
156
|
+
// If we have cached file content, show a full-file diff
|
|
157
|
+
if (
|
|
158
|
+
path &&
|
|
159
|
+
options?.cachedFileContent &&
|
|
160
|
+
path in options.cachedFileContent
|
|
161
|
+
) {
|
|
162
|
+
const oldContent = options.cachedFileContent[path];
|
|
163
|
+
const newContent = input?.replace_all
|
|
164
|
+
? oldContent.replaceAll(oldText ?? "", newText)
|
|
165
|
+
: oldContent.replace(oldText ?? "", newText);
|
|
166
|
+
oldText = oldContent;
|
|
167
|
+
newText = newContent;
|
|
168
|
+
}
|
|
149
169
|
|
|
150
170
|
return {
|
|
151
171
|
title: path ? `Edit \`${path}\`` : "Edit",
|
|
@@ -170,8 +190,12 @@ export function toolInfoFromToolUse(
|
|
|
170
190
|
const filePath = input?.file_path ? String(input.file_path) : undefined;
|
|
171
191
|
const contentStr = input?.content ? String(input.content) : undefined;
|
|
172
192
|
if (filePath) {
|
|
193
|
+
const oldContent =
|
|
194
|
+
options?.cachedFileContent && filePath in options.cachedFileContent
|
|
195
|
+
? options.cachedFileContent[filePath]
|
|
196
|
+
: null;
|
|
173
197
|
contentResult = toolContent()
|
|
174
|
-
.diff(filePath,
|
|
198
|
+
.diff(filePath, oldContent, contentStr ?? "")
|
|
175
199
|
.build();
|
|
176
200
|
} else if (contentStr) {
|
|
177
201
|
contentResult = toolContent().text(contentStr).build();
|
|
@@ -453,7 +477,11 @@ export function toolUpdateFromToolResult(
|
|
|
453
477
|
| BetaRequestMCPToolResultBlockParam
|
|
454
478
|
| BetaToolSearchToolResultBlockParam,
|
|
455
479
|
toolUse: Pick<ToolUseBlock, "name" | "input"> | undefined,
|
|
456
|
-
options?: {
|
|
480
|
+
options?: {
|
|
481
|
+
supportsTerminalOutput?: boolean;
|
|
482
|
+
toolUseId?: string;
|
|
483
|
+
cachedFileContent?: Record<string, string>;
|
|
484
|
+
},
|
|
457
485
|
): Pick<ToolCallUpdate, "title" | "content" | "locations" | "_meta"> {
|
|
458
486
|
if (
|
|
459
487
|
"is_error" in toolResult &&
|
|
@@ -140,6 +140,7 @@ function buildSpawnWrapper(
|
|
|
140
140
|
sessionId: string,
|
|
141
141
|
onProcessSpawned: (info: ProcessSpawnedInfo) => void,
|
|
142
142
|
onProcessExited?: (pid: number) => void,
|
|
143
|
+
logger?: Logger,
|
|
143
144
|
): (options: SpawnOptions) => SpawnedProcess {
|
|
144
145
|
return (spawnOpts: SpawnOptions): SpawnedProcess => {
|
|
145
146
|
const child = spawn(spawnOpts.command, spawnOpts.args, {
|
|
@@ -156,6 +157,13 @@ function buildSpawnWrapper(
|
|
|
156
157
|
});
|
|
157
158
|
}
|
|
158
159
|
|
|
160
|
+
child.stderr?.on("data", (data: Buffer) => {
|
|
161
|
+
const msg = data.toString().trim();
|
|
162
|
+
if (msg && logger) {
|
|
163
|
+
logger.debug(`[claude-code:${child.pid}] stderr: ${msg}`);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
159
167
|
if (onProcessExited) {
|
|
160
168
|
child.on("exit", () => {
|
|
161
169
|
if (child.pid) {
|
|
@@ -256,6 +264,7 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
|
|
|
256
264
|
params.sessionId,
|
|
257
265
|
params.onProcessSpawned,
|
|
258
266
|
params.onProcessExited,
|
|
267
|
+
params.logger,
|
|
259
268
|
),
|
|
260
269
|
}),
|
|
261
270
|
};
|
|
@@ -101,7 +101,7 @@ export function spawnCodexProcess(options: CodexProcessOptions): CodexProcess {
|
|
|
101
101
|
});
|
|
102
102
|
|
|
103
103
|
child.stderr?.on("data", (data: Buffer) => {
|
|
104
|
-
logger.
|
|
104
|
+
logger.warn("codex-acp stderr:", data.toString());
|
|
105
105
|
});
|
|
106
106
|
|
|
107
107
|
child.on("error", (err) => {
|
package/src/agent.ts
CHANGED
|
@@ -36,6 +36,12 @@ export class Agent {
|
|
|
36
36
|
logger: this.logger.child("SessionLogWriter"),
|
|
37
37
|
localCachePath: config.localCachePath,
|
|
38
38
|
});
|
|
39
|
+
|
|
40
|
+
if (config.localCachePath) {
|
|
41
|
+
SessionLogWriter.cleanupOldSessions(config.localCachePath).catch(
|
|
42
|
+
() => {},
|
|
43
|
+
);
|
|
44
|
+
}
|
|
39
45
|
}
|
|
40
46
|
}
|
|
41
47
|
|
|
@@ -69,7 +75,9 @@ export class Agent {
|
|
|
69
75
|
options: TaskExecutionOptions = {},
|
|
70
76
|
): Promise<InProcessAcpConnection> {
|
|
71
77
|
const gatewayConfig = this._configureLlmGateway(options.adapter);
|
|
72
|
-
this.logger.info("Configured LLM gateway",
|
|
78
|
+
this.logger.info("Configured LLM gateway", {
|
|
79
|
+
adapter: options.adapter,
|
|
80
|
+
});
|
|
73
81
|
this.taskRunId = taskRunId;
|
|
74
82
|
|
|
75
83
|
let allowedModelIds: Set<string> | undefined;
|
|
@@ -21,6 +21,8 @@ export interface CaptureTreeOutput {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export class CaptureTreeSaga extends Saga<CaptureTreeInput, CaptureTreeOutput> {
|
|
24
|
+
readonly sagaName = "CaptureTreeSaga";
|
|
25
|
+
|
|
24
26
|
protected async execute(input: CaptureTreeInput): Promise<CaptureTreeOutput> {
|
|
25
27
|
const {
|
|
26
28
|
repositoryPath,
|
package/src/sagas/resume-saga.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface ResumeOutput {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
export class ResumeSaga extends Saga<ResumeInput, ResumeOutput> {
|
|
44
|
+
readonly sagaName = "ResumeSaga";
|
|
45
|
+
|
|
44
46
|
protected async execute(input: ResumeInput): Promise<ResumeOutput> {
|
|
45
47
|
const { taskId, runId, repositoryPath, apiClient } = input;
|
|
46
48
|
const logger =
|
|
@@ -17,6 +17,7 @@ import { TreeTracker } from "../tree-tracker.js";
|
|
|
17
17
|
import type {
|
|
18
18
|
AgentMode,
|
|
19
19
|
DeviceInfo,
|
|
20
|
+
LogLevel,
|
|
20
21
|
TaskRun,
|
|
21
22
|
TreeSnapshotEvent,
|
|
22
23
|
} from "../types.js";
|
|
@@ -155,6 +156,35 @@ export class AgentServer {
|
|
|
155
156
|
private questionRelayedToSlack = false;
|
|
156
157
|
private detectedPrUrl: string | null = null;
|
|
157
158
|
|
|
159
|
+
private emitConsoleLog = (
|
|
160
|
+
level: LogLevel,
|
|
161
|
+
_scope: string,
|
|
162
|
+
message: string,
|
|
163
|
+
data?: unknown,
|
|
164
|
+
): void => {
|
|
165
|
+
if (!this.session) return;
|
|
166
|
+
|
|
167
|
+
const formatted =
|
|
168
|
+
data !== undefined ? `${message} ${JSON.stringify(data)}` : message;
|
|
169
|
+
|
|
170
|
+
const notification = {
|
|
171
|
+
jsonrpc: "2.0",
|
|
172
|
+
method: POSTHOG_NOTIFICATIONS.CONSOLE,
|
|
173
|
+
params: { level, message: formatted },
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
this.broadcastEvent({
|
|
177
|
+
type: "notification",
|
|
178
|
+
timestamp: new Date().toISOString(),
|
|
179
|
+
notification,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
this.session.logWriter.appendRawLine(
|
|
183
|
+
this.session.payload.run_id,
|
|
184
|
+
JSON.stringify(notification),
|
|
185
|
+
);
|
|
186
|
+
};
|
|
187
|
+
|
|
158
188
|
constructor(config: AgentServerConfig) {
|
|
159
189
|
this.config = config;
|
|
160
190
|
this.logger = new Logger({ debug: true, prefix: "[AgentServer]" });
|
|
@@ -590,6 +620,17 @@ export class AgentServer {
|
|
|
590
620
|
logWriter,
|
|
591
621
|
};
|
|
592
622
|
|
|
623
|
+
this.logger = new Logger({
|
|
624
|
+
debug: true,
|
|
625
|
+
prefix: "[AgentServer]",
|
|
626
|
+
onLog: (level, scope, message, data) => {
|
|
627
|
+
// Preserve console output (onLog suppresses default console.*)
|
|
628
|
+
const _formatted =
|
|
629
|
+
data !== undefined ? `${message} ${JSON.stringify(data)}` : message;
|
|
630
|
+
this.emitConsoleLog(level, scope, message, data);
|
|
631
|
+
},
|
|
632
|
+
});
|
|
633
|
+
|
|
593
634
|
this.logger.info("Session initialized successfully");
|
|
594
635
|
|
|
595
636
|
// Signal in_progress so the UI can start polling for updates
|
|
@@ -1103,15 +1144,29 @@ Important:
|
|
|
1103
1144
|
...snapshot,
|
|
1104
1145
|
device: this.session.deviceInfo,
|
|
1105
1146
|
};
|
|
1147
|
+
|
|
1148
|
+
const notification = {
|
|
1149
|
+
jsonrpc: "2.0" as const,
|
|
1150
|
+
method: POSTHOG_NOTIFICATIONS.TREE_SNAPSHOT,
|
|
1151
|
+
params: snapshotWithDevice,
|
|
1152
|
+
};
|
|
1153
|
+
|
|
1106
1154
|
this.broadcastEvent({
|
|
1107
1155
|
type: "notification",
|
|
1108
1156
|
timestamp: new Date().toISOString(),
|
|
1109
|
-
notification
|
|
1110
|
-
jsonrpc: "2.0",
|
|
1111
|
-
method: POSTHOG_NOTIFICATIONS.TREE_SNAPSHOT,
|
|
1112
|
-
params: snapshotWithDevice,
|
|
1113
|
-
},
|
|
1157
|
+
notification,
|
|
1114
1158
|
});
|
|
1159
|
+
|
|
1160
|
+
// Persist to log writer so cloud runs have tree snapshots
|
|
1161
|
+
const { archiveUrl: _, ...paramsWithoutArchive } = snapshotWithDevice;
|
|
1162
|
+
const logNotification = {
|
|
1163
|
+
...notification,
|
|
1164
|
+
params: paramsWithoutArchive,
|
|
1165
|
+
};
|
|
1166
|
+
this.session.logWriter.appendRawLine(
|
|
1167
|
+
this.session.payload.run_id,
|
|
1168
|
+
JSON.stringify(logNotification),
|
|
1169
|
+
);
|
|
1115
1170
|
}
|
|
1116
1171
|
} catch (error) {
|
|
1117
1172
|
this.logger.error("Failed to capture tree state", error);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import fsp from "node:fs/promises";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import type { SessionContext } from "./otel-log-writer.js";
|
|
4
5
|
import type { PostHogAPIClient } from "./posthog-api.js";
|
|
@@ -30,6 +31,7 @@ export class SessionLogWriter {
|
|
|
30
31
|
private static readonly FLUSH_MAX_INTERVAL_MS = 5000;
|
|
31
32
|
private static readonly MAX_FLUSH_RETRIES = 10;
|
|
32
33
|
private static readonly MAX_RETRY_DELAY_MS = 30_000;
|
|
34
|
+
private static readonly SESSIONS_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
33
35
|
|
|
34
36
|
private posthogAPI?: PostHogAPIClient;
|
|
35
37
|
private pendingEntries: Map<string, StoredNotification[]> = new Map();
|
|
@@ -196,10 +198,16 @@ export class SessionLogWriter {
|
|
|
196
198
|
);
|
|
197
199
|
this.retryCounts.set(sessionId, 0);
|
|
198
200
|
} else {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
201
|
+
if (retryCount === 1) {
|
|
202
|
+
this.logger.warn(
|
|
203
|
+
`Failed to persist session logs, will retry (up to ${SessionLogWriter.MAX_FLUSH_RETRIES} attempts)`,
|
|
204
|
+
{
|
|
205
|
+
taskId: session.context.taskId,
|
|
206
|
+
runId: session.context.runId,
|
|
207
|
+
error: error instanceof Error ? error.message : String(error),
|
|
208
|
+
},
|
|
209
|
+
);
|
|
210
|
+
}
|
|
203
211
|
const currentPending = this.pendingEntries.get(sessionId) ?? [];
|
|
204
212
|
this.pendingEntries.set(sessionId, [...pending, ...currentPending]);
|
|
205
213
|
this.scheduleFlush(sessionId);
|
|
@@ -344,4 +352,31 @@ export class SessionLogWriter {
|
|
|
344
352
|
});
|
|
345
353
|
}
|
|
346
354
|
}
|
|
355
|
+
|
|
356
|
+
static async cleanupOldSessions(localCachePath: string): Promise<number> {
|
|
357
|
+
const sessionsDir = path.join(localCachePath, "sessions");
|
|
358
|
+
let deleted = 0;
|
|
359
|
+
try {
|
|
360
|
+
const entries = await fsp.readdir(sessionsDir);
|
|
361
|
+
const now = Date.now();
|
|
362
|
+
for (const entry of entries) {
|
|
363
|
+
const entryPath = path.join(sessionsDir, entry);
|
|
364
|
+
try {
|
|
365
|
+
const stats = await fsp.stat(entryPath);
|
|
366
|
+
if (
|
|
367
|
+
stats.isDirectory() &&
|
|
368
|
+
now - stats.birthtimeMs > SessionLogWriter.SESSIONS_MAX_AGE_MS
|
|
369
|
+
) {
|
|
370
|
+
await fsp.rm(entryPath, { recursive: true, force: true });
|
|
371
|
+
deleted++;
|
|
372
|
+
}
|
|
373
|
+
} catch {
|
|
374
|
+
// Skip entries we can't stat
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
} catch {
|
|
378
|
+
// Sessions dir may not exist yet
|
|
379
|
+
}
|
|
380
|
+
return deleted;
|
|
381
|
+
}
|
|
347
382
|
}
|