-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathagent-server.ts
More file actions
1710 lines (1499 loc) · 50.7 KB
/
agent-server.ts
File metadata and controls
1710 lines (1499 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { ContentBlock } from "@agentclientprotocol/sdk";
import {
ClientSideConnection,
ndJsonStream,
PROTOCOL_VERSION,
} from "@agentclientprotocol/sdk";
import { type ServerType, serve } from "@hono/node-server";
import { getCurrentBranch } from "@posthog/git/queries";
import { Hono } from "hono";
import packageJson from "../../package.json" with { type: "json" };
import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";
import {
createAcpConnection,
type InProcessAcpConnection,
} from "../adapters/acp-connection";
import { selectRecentTurns } from "../adapters/claude/session/jsonl-hydration";
import { PostHogAPIClient } from "../posthog-api";
import {
type ConversationTurn,
type ResumeState,
resumeFromLog,
} from "../resume";
import { SessionLogWriter } from "../session-log-writer";
import { TreeTracker } from "../tree-tracker";
import type {
AgentMode,
DeviceInfo,
LogLevel,
TaskRun,
TreeSnapshotEvent,
} from "../types";
import { AsyncMutex } from "../utils/async-mutex";
import { getLlmGatewayUrl } from "../utils/gateway";
import { Logger } from "../utils/logger";
import {
deserializeCloudPrompt,
normalizeCloudPromptContent,
promptBlocksToText,
} from "./cloud-prompt";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
import { jsonRpcRequestSchema, validateCommandParams } from "./schemas";
import type { AgentServerConfig } from "./types";
type MessageCallback = (message: unknown) => void;
class NdJsonTap {
private decoder = new TextDecoder();
private buffer = "";
constructor(private onMessage: MessageCallback) {}
process(chunk: Uint8Array): void {
this.buffer += this.decoder.decode(chunk, { stream: true });
const lines = this.buffer.split("\n");
this.buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.trim()) continue;
try {
this.onMessage(JSON.parse(line));
} catch {
// Not valid JSON, skip
}
}
}
}
function createTappedReadableStream(
underlying: ReadableStream<Uint8Array>,
onMessage: MessageCallback,
logger?: Logger,
): ReadableStream<Uint8Array> {
const reader = underlying.getReader();
const tap = new NdJsonTap(onMessage);
return new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const { value, done } = await reader.read();
if (done) {
controller.close();
return;
}
tap.process(value);
controller.enqueue(value);
} catch (error) {
logger?.debug("Read failed, closing stream", error);
controller.close();
}
},
cancel() {
reader.releaseLock();
},
});
}
function createTappedWritableStream(
underlying: WritableStream<Uint8Array>,
onMessage: MessageCallback,
logger?: Logger,
): WritableStream<Uint8Array> {
const tap = new NdJsonTap(onMessage);
const mutex = new AsyncMutex();
return new WritableStream<Uint8Array>({
async write(chunk) {
tap.process(chunk);
await mutex.acquire();
try {
const writer = underlying.getWriter();
await writer.write(chunk);
writer.releaseLock();
} catch (error) {
logger?.debug("Write failed (stream may be closed)", error);
} finally {
mutex.release();
}
},
async close() {
await mutex.acquire();
try {
const writer = underlying.getWriter();
await writer.close();
writer.releaseLock();
} catch (error) {
logger?.debug("Close failed (stream may be closed)", error);
} finally {
mutex.release();
}
},
async abort(reason) {
await mutex.acquire();
try {
const writer = underlying.getWriter();
await writer.abort(reason);
writer.releaseLock();
} catch (error) {
logger?.debug("Abort failed (stream may be closed)", error);
} finally {
mutex.release();
}
},
});
}
interface SseController {
send: (data: unknown) => void;
close: () => void;
}
interface ActiveSession {
payload: JwtPayload;
acpSessionId: string;
acpConnection: InProcessAcpConnection;
clientConnection: ClientSideConnection;
treeTracker: TreeTracker | null;
sseController: SseController | null;
deviceInfo: DeviceInfo;
logWriter: SessionLogWriter;
}
export class AgentServer {
private config: AgentServerConfig;
private logger: Logger;
private server: ServerType | null = null;
private session: ActiveSession | null = null;
private app: Hono;
private posthogAPI: PostHogAPIClient;
private questionRelayedToSlack = false;
private detectedPrUrl: string | null = null;
private lastReportedBranch: string | null = null;
private resumeState: ResumeState | null = null;
// Guards against concurrent session initialization. autoInitializeSession() and
// the GET /events SSE handler can both call initializeSession() — the SSE connection
// often arrives while newSession() is still awaited (this.session is still null),
// causing a second session to be created and duplicate Slack messages to be sent.
private initializationPromise: Promise<void> | null = null;
private pendingEvents: Record<string, unknown>[] = [];
private detachSseController(controller: SseController): void {
if (this.session?.sseController === controller) {
this.session.sseController = null;
}
}
private emitConsoleLog = (
level: LogLevel,
_scope: string,
message: string,
data?: unknown,
): void => {
if (!this.session) return;
const formatted =
data !== undefined ? `${message} ${JSON.stringify(data)}` : message;
const notification = {
jsonrpc: "2.0",
method: POSTHOG_NOTIFICATIONS.CONSOLE,
params: { level, message: formatted },
};
this.broadcastEvent({
type: "notification",
timestamp: new Date().toISOString(),
notification,
});
this.session.logWriter.appendRawLine(
this.session.payload.run_id,
JSON.stringify(notification),
);
};
constructor(config: AgentServerConfig) {
this.config = config;
this.logger = new Logger({ debug: true, prefix: "[AgentServer]" });
this.posthogAPI = new PostHogAPIClient({
apiUrl: config.apiUrl,
projectId: config.projectId,
getApiKey: () => config.apiKey,
userAgent: `posthog/cloud.hog.dev; version: ${config.version ?? packageJson.version}`,
});
this.app = this.createApp();
}
private getEffectiveMode(payload: JwtPayload): AgentMode {
return payload.mode ?? this.config.mode;
}
private createApp(): Hono {
const app = new Hono();
app.get("/health", (c) => {
return c.json({ status: "ok", hasSession: !!this.session });
});
app.get("/events", async (c) => {
let payload: JwtPayload;
try {
payload = this.authenticateRequest(c.req.header.bind(c.req));
} catch (error) {
return c.json(
{
error:
error instanceof JwtValidationError
? error.message
: "Invalid token",
code:
error instanceof JwtValidationError
? error.code
: "invalid_token",
},
401,
);
}
const stream = new ReadableStream({
start: async (controller) => {
const sseController: SseController = {
send: (data: unknown) => {
try {
controller.enqueue(
new TextEncoder().encode(`data: ${JSON.stringify(data)}\n\n`),
);
} catch {
this.detachSseController(sseController);
}
},
close: () => {
try {
controller.close();
} catch {
this.detachSseController(sseController);
}
},
};
if (!this.session || this.session.payload.run_id !== payload.run_id) {
await this.initializeSession(payload, sseController);
} else {
this.session.sseController = sseController;
this.replayPendingEvents();
}
this.sendSseEvent(sseController, {
type: "connected",
run_id: payload.run_id,
});
},
cancel: () => {
this.logger.info("SSE connection closed");
if (this.session?.sseController) {
this.session.sseController = null;
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
});
app.post("/command", async (c) => {
let payload: JwtPayload;
try {
payload = this.authenticateRequest(c.req.header.bind(c.req));
} catch (error) {
return c.json(
{
error:
error instanceof JwtValidationError
? error.message
: "Invalid token",
},
401,
);
}
if (!this.session || this.session.payload.run_id !== payload.run_id) {
return c.json({ error: "No active session for this run" }, 400);
}
const rawBody = await c.req.json().catch(() => null);
const parseResult = jsonRpcRequestSchema.safeParse(rawBody);
if (!parseResult.success) {
return c.json({ error: "Invalid JSON-RPC request" }, 400);
}
const command = parseResult.data;
const paramsValidation = validateCommandParams(
command.method,
command.params ?? {},
);
if (!paramsValidation.success) {
return c.json(
{
jsonrpc: "2.0",
id: command.id,
error: {
code: -32602,
message: paramsValidation.error,
},
},
200,
);
}
try {
const result = await this.executeCommand(
command.method,
(command.params as Record<string, unknown>) || {},
);
return c.json({
jsonrpc: "2.0",
id: command.id,
result,
});
} catch (error) {
return c.json({
jsonrpc: "2.0",
id: command.id,
error: {
code: -32000,
message: error instanceof Error ? error.message : "Unknown error",
},
});
}
});
app.notFound((c) => {
return c.json({ error: "Not found" }, 404);
});
return app;
}
async start(): Promise<void> {
await new Promise<void>((resolve) => {
this.server = serve(
{
fetch: this.app.fetch,
port: this.config.port,
},
() => {
this.logger.info(`HTTP server listening on port ${this.config.port}`);
resolve();
},
);
});
await this.autoInitializeSession();
}
private async autoInitializeSession(): Promise<void> {
const { taskId, runId, mode, projectId } = this.config;
this.logger.info("Auto-initializing session", { taskId, runId, mode });
// Check if this is a resume from a previous run
const resumeRunId = process.env.POSTHOG_RESUME_RUN_ID;
if (resumeRunId) {
this.logger.info("Resuming from previous run", {
resumeRunId,
currentRunId: runId,
});
try {
this.resumeState = await resumeFromLog({
taskId,
runId: resumeRunId,
repositoryPath: this.config.repositoryPath,
apiClient: this.posthogAPI,
logger: new Logger({ debug: true, prefix: "[Resume]" }),
});
this.logger.info("Resume state loaded", {
conversationTurns: this.resumeState.conversation.length,
snapshotApplied: this.resumeState.snapshotApplied,
logEntries: this.resumeState.logEntryCount,
});
} catch (error) {
this.logger.warn("Failed to load resume state, starting fresh", {
error,
});
this.resumeState = null;
}
}
// Create a synthetic payload from config (no JWT needed for auto-init)
const payload: JwtPayload = {
task_id: taskId,
run_id: runId,
team_id: projectId,
user_id: 0, // System-initiated
distinct_id: "agent-server",
mode,
};
await this.initializeSession(payload, null);
}
async stop(): Promise<void> {
this.logger.info("Stopping agent server...");
if (this.session) {
await this.cleanupSession();
}
if (this.server) {
this.server.close();
this.server = null;
}
this.logger.info("Agent server stopped");
}
private authenticateRequest(
getHeader: (name: string) => string | undefined,
): JwtPayload {
// Always require JWT validation - never trust unverified headers
if (!this.config.jwtPublicKey) {
throw new JwtValidationError(
"Server not configured with JWT public key",
"server_error",
);
}
const authHeader = getHeader("authorization");
if (!authHeader?.startsWith("Bearer ")) {
throw new JwtValidationError(
"Missing authorization header",
"invalid_token",
);
}
const token = authHeader.slice(7);
return validateJwt(token, this.config.jwtPublicKey);
}
private async executeCommand(
method: string,
params: Record<string, unknown>,
): Promise<unknown> {
if (!this.session) {
throw new Error("No active session");
}
switch (method) {
case POSTHOG_NOTIFICATIONS.USER_MESSAGE:
case "user_message": {
const prompt = normalizeCloudPromptContent(
params.content as string | ContentBlock[],
);
const promptPreview = promptBlocksToText(prompt);
this.logger.info(
`Processing user message (detectedPrUrl=${this.detectedPrUrl ?? "none"}): ${promptPreview.substring(0, 100)}...`,
);
this.session.logWriter.resetTurnMessages(this.session.payload.run_id);
const result = await this.session.clientConnection.prompt({
sessionId: this.session.acpSessionId,
prompt,
...(this.detectedPrUrl && {
_meta: {
prContext:
`IMPORTANT — OVERRIDE PREVIOUS INSTRUCTIONS ABOUT CREATING BRANCHES/PRs.\n` +
`You already have an open pull request: ${this.detectedPrUrl}\n` +
`You MUST:\n` +
`1. Check out the existing PR branch with \`gh pr checkout ${this.detectedPrUrl}\`\n` +
`2. Make changes, commit, and push to that branch\n` +
`You MUST NOT create a new branch, close the existing PR, or create a new PR.`,
},
}),
});
this.logger.info("User message completed", {
stopReason: result.stopReason,
});
if (result.stopReason === "end_turn") {
void this.syncCloudBranchMetadata(this.session.payload);
}
this.broadcastTurnComplete(result.stopReason);
if (result.stopReason === "end_turn") {
// Relay the response to Slack. For follow-ups this is the primary
// delivery path — the HTTP caller only handles reactions.
this.relayAgentResponse(this.session.payload).catch((err) =>
this.logger.warn("Failed to relay follow-up response", err),
);
}
// Flush logs and include the assistant's response text so callers
// (e.g. Slack follow-up forwarding) can extract it without racing
// against async log persistence to object storage.
let assistantMessage: string | undefined;
try {
await this.session.logWriter.flush(this.session.payload.run_id, {
coalesce: true,
});
assistantMessage = this.session.logWriter.getFullAgentResponse(
this.session.payload.run_id,
);
} catch {
this.logger.warn("Failed to extract assistant message from logs");
}
return {
stopReason: result.stopReason,
...(assistantMessage && { assistant_message: assistantMessage }),
};
}
case POSTHOG_NOTIFICATIONS.CANCEL:
case "cancel": {
this.logger.info("Cancel requested", {
acpSessionId: this.session.acpSessionId,
});
await this.session.clientConnection.cancel({
sessionId: this.session.acpSessionId,
});
return { cancelled: true };
}
case POSTHOG_NOTIFICATIONS.CLOSE:
case "close": {
this.logger.info("Close requested");
await this.cleanupSession();
return { closed: true };
}
default:
throw new Error(`Unknown method: ${method}`);
}
}
private async initializeSession(
payload: JwtPayload,
sseController: SseController | null,
): Promise<void> {
// Race condition guard: autoInitializeSession() starts first, but while it awaits
// newSession() (which takes ~1-2s for MCP metadata fetch), the Temporal relay connects
// to GET /events. That handler sees this.session === null and calls initializeSession()
// again, creating a duplicate session that sends the same prompt twice — resulting in
// duplicate Slack messages. This lock ensures the second caller waits for the first
// initialization to finish and reuses the session.
if (this.initializationPromise) {
this.logger.info("Waiting for in-progress initialization", {
runId: payload.run_id,
});
await this.initializationPromise;
// After waiting, just attach the SSE controller if needed
if (this.session && sseController) {
this.session.sseController = sseController;
this.replayPendingEvents();
}
return;
}
this.initializationPromise = this._doInitializeSession(
payload,
sseController,
);
try {
await this.initializationPromise;
} finally {
this.initializationPromise = null;
}
}
private async _doInitializeSession(
payload: JwtPayload,
sseController: SseController | null,
): Promise<void> {
if (this.session) {
await this.cleanupSession();
}
this.logger.info("Initializing session", {
runId: payload.run_id,
taskId: payload.task_id,
});
const deviceInfo: DeviceInfo = {
type: "cloud",
name: process.env.HOSTNAME || "cloud-sandbox",
};
this.configureEnvironment();
const posthogAPI = new PostHogAPIClient({
apiUrl: this.config.apiUrl,
projectId: this.config.projectId,
getApiKey: () => this.config.apiKey,
userAgent: `posthog/cloud.hog.dev; version: ${this.config.version ?? packageJson.version}`,
});
const treeTracker = this.config.repositoryPath
? new TreeTracker({
repositoryPath: this.config.repositoryPath,
taskId: payload.task_id,
runId: payload.run_id,
apiClient: posthogAPI,
logger: new Logger({ debug: true, prefix: "[TreeTracker]" }),
})
: null;
const logWriter = new SessionLogWriter({
posthogAPI,
logger: new Logger({ debug: true, prefix: "[SessionLogWriter]" }),
});
const acpConnection = createAcpConnection({
taskRunId: payload.run_id,
taskId: payload.task_id,
deviceType: deviceInfo.type,
logWriter,
onStructuredOutput: async (output) => {
await this.posthogAPI.setTaskRunOutput(
payload.task_id,
payload.run_id,
{
output,
},
);
},
});
// Tap both streams to broadcast all ACP messages via SSE (mimics local transport)
const onAcpMessage = (message: unknown) => {
this.broadcastEvent({
type: "notification",
timestamp: new Date().toISOString(),
notification: message,
});
};
const tappedReadable = createTappedReadableStream(
acpConnection.clientStreams.readable as ReadableStream<Uint8Array>,
onAcpMessage,
this.logger,
);
const tappedWritable = createTappedWritableStream(
acpConnection.clientStreams.writable as WritableStream<Uint8Array>,
onAcpMessage,
this.logger,
);
const clientStream = ndJsonStream(tappedWritable, tappedReadable);
const clientConnection = new ClientSideConnection(
() => this.createCloudClient(payload),
clientStream,
);
await clientConnection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {},
});
const [preTaskRun, preTask] = await Promise.all([
this.posthogAPI
.getTaskRun(payload.task_id, payload.run_id)
.catch((err) => {
this.logger.warn("Failed to fetch task run for session context", {
taskId: payload.task_id,
runId: payload.run_id,
error: err,
});
return null;
}),
this.posthogAPI.getTask(payload.task_id).catch((err) => {
this.logger.warn("Failed to fetch task for session context", {
taskId: payload.task_id,
error: err,
});
return null;
}),
]);
const prUrl =
typeof (preTaskRun?.state as Record<string, unknown>)
?.slack_notified_pr_url === "string"
? ((preTaskRun?.state as Record<string, unknown>)
.slack_notified_pr_url as string)
: null;
if (prUrl) {
this.detectedPrUrl = prUrl;
}
const sessionResponse = await clientConnection.newSession({
cwd: this.config.repositoryPath ?? "/tmp/workspace",
mcpServers: this.config.mcpServers ?? [],
_meta: {
sessionId: payload.run_id,
taskRunId: payload.run_id,
systemPrompt: this.buildSessionSystemPrompt(prUrl),
allowedDomains: this.config.allowedDomains,
jsonSchema: preTask?.json_schema ?? null,
...(this.config.claudeCode?.plugins?.length && {
claudeCode: {
options: {
plugins: this.config.claudeCode.plugins,
},
},
}),
},
});
const acpSessionId = sessionResponse.sessionId;
this.logger.info("ACP session created", {
acpSessionId,
runId: payload.run_id,
});
this.session = {
payload,
acpSessionId,
acpConnection,
clientConnection,
treeTracker,
sseController,
deviceInfo,
logWriter,
};
this.logger = new Logger({
debug: true,
prefix: "[AgentServer]",
onLog: (level, scope, message, data) => {
// Preserve console output (onLog suppresses default console.*)
const _formatted =
data !== undefined ? `${message} ${JSON.stringify(data)}` : message;
this.emitConsoleLog(level, scope, message, data);
},
});
this.logger.info("Session initialized successfully");
this.logger.info(
`Agent version: ${this.config.version ?? packageJson.version}`,
);
// Signal in_progress so the UI can start polling for updates
this.posthogAPI
.updateTaskRun(payload.task_id, payload.run_id, {
status: "in_progress",
})
.catch((err) =>
this.logger.warn("Failed to set task run to in_progress", err),
);
await this.sendInitialTaskMessage(payload, preTaskRun);
}
private async sendInitialTaskMessage(
payload: JwtPayload,
prefetchedRun?: TaskRun | null,
): Promise<void> {
if (!this.session) return;
// Fetch TaskRun early — needed for both resume detection and initial prompt
let taskRun = prefetchedRun ?? null;
if (!taskRun) {
try {
taskRun = await this.posthogAPI.getTaskRun(
payload.task_id,
payload.run_id,
);
} catch (error) {
this.logger.warn("Failed to fetch task run", {
taskId: payload.task_id,
runId: payload.run_id,
error,
});
}
}
// Check for resume if not already loaded from env var in autoInitializeSession
if (!this.resumeState) {
const resumeRunId = this.getResumeRunId(taskRun);
if (resumeRunId) {
this.logger.info("Resuming from previous run (via TaskRun state)", {
resumeRunId,
currentRunId: payload.run_id,
});
try {
this.resumeState = await resumeFromLog({
taskId: payload.task_id,
runId: resumeRunId,
repositoryPath: this.config.repositoryPath,
apiClient: this.posthogAPI,
logger: new Logger({ debug: true, prefix: "[Resume]" }),
});
this.logger.info("Resume state loaded (via TaskRun state)", {
conversationTurns: this.resumeState.conversation.length,
snapshotApplied: this.resumeState.snapshotApplied,
logEntries: this.resumeState.logEntryCount,
});
} catch (error) {
this.logger.warn("Failed to load resume state, starting fresh", {
error,
});
this.resumeState = null;
}
}
}
// Resume flow: if we have resume state, format conversation history as context
if (this.resumeState && this.resumeState.conversation.length > 0) {
await this.sendResumeMessage(payload, taskRun);
return;
}
try {
const task = await this.posthogAPI.getTask(payload.task_id);
const initialPromptOverride = taskRun
? this.getInitialPromptOverride(taskRun)
: null;
const pendingUserPrompt = this.getPendingUserPrompt(taskRun);
let initialPrompt: ContentBlock[] = [];
if (pendingUserPrompt?.length) {
initialPrompt = pendingUserPrompt;
} else if (initialPromptOverride) {
initialPrompt = [{ type: "text", text: initialPromptOverride }];
} else if (task.description) {
initialPrompt = [{ type: "text", text: task.description }];
}
if (initialPrompt.length === 0) {
this.logger.warn("Task has no description, skipping initial message");
return;
}
this.logger.info("Sending initial task message", {
taskId: payload.task_id,
descriptionLength: promptBlocksToText(initialPrompt).length,
usedInitialPromptOverride: !!initialPromptOverride,
usedPendingUserMessage: !!pendingUserPrompt?.length,
});
this.session.logWriter.resetTurnMessages(payload.run_id);
const result = await this.session.clientConnection.prompt({
sessionId: this.session.acpSessionId,
prompt: initialPrompt,
});
this.logger.info("Initial task message completed", {
stopReason: result.stopReason,
});
if (result.stopReason === "end_turn") {
void this.syncCloudBranchMetadata(payload);
}
this.broadcastTurnComplete(result.stopReason);
if (result.stopReason === "end_turn") {
await this.relayAgentResponse(payload);
}
} catch (error) {
this.logger.error("Failed to send initial task message", error);
if (this.session) {
await this.session.logWriter.flushAll();
}
await this.signalTaskComplete(payload, "error");
}
}
private async sendResumeMessage(
payload: JwtPayload,
taskRun: TaskRun | null,
): Promise<void> {
if (!this.session || !this.resumeState) return;
try {
const conversationSummary = this.formatConversationForResume(
this.resumeState.conversation,
);
// Read the pending user prompt from TaskRun state (set by the workflow
// when the user sends a follow-up message that triggers a resume).
const pendingUserPrompt = this.getPendingUserPrompt(taskRun);
const sandboxContext = this.resumeState.snapshotApplied
? `The workspace environment (all files, packages, and code changes) has been fully restored from where you left off.`
: `The workspace files from the previous session were not restored (the file snapshot may have expired), so you are starting with a fresh environment. Your conversation history is fully preserved below.`;
let resumePromptBlocks: ContentBlock[];
if (pendingUserPrompt?.length) {
resumePromptBlocks = [
{
type: "text",
text:
`You are resuming a previous conversation. ${sandboxContext}\n\n` +
`Here is the conversation history from the previous session:\n\n` +
`${conversationSummary}\n\n` +
`The user has sent a new message:\n\n`,
},
...pendingUserPrompt,
{
type: "text",
text: "\n\nRespond to the user's new message above. You have full context from the previous session.",
},
];
} else {
resumePromptBlocks = [
{
type: "text",
text:
`You are resuming a previous conversation. ${sandboxContext}\n\n` +
`Here is the conversation history from the previous session:\n\n` +
`${conversationSummary}\n\n` +
`Continue from where you left off. The user is waiting for your response.`,
},
];
}
this.logger.info("Sending resume message", {
taskId: payload.task_id,
conversationTurns: this.resumeState.conversation.length,
promptLength: promptBlocksToText(resumePromptBlocks).length,
hasPendingUserMessage: !!pendingUserPrompt?.length,
snapshotApplied: this.resumeState.snapshotApplied,
});
// Clear resume state so it's not reused
this.resumeState = null;
this.session.logWriter.resetTurnMessages(payload.run_id);
const result = await this.session.clientConnection.prompt({
sessionId: this.session.acpSessionId,
prompt: resumePromptBlocks,
});
this.logger.info("Resume message completed", {
stopReason: result.stopReason,
});
if (result.stopReason === "end_turn") {
void this.syncCloudBranchMetadata(payload);
}
this.broadcastTurnComplete(result.stopReason);
if (result.stopReason === "end_turn") {