-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathagent-server.ts
More file actions
3615 lines (3218 loc) · 119 KB
/
Copy pathagent-server.ts
File metadata and controls
3615 lines (3218 loc) · 119 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 { createHash } from "node:crypto";
import { access, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative } from "node:path";
import { pathToFileURL } from "node:url";
import type {
ContentBlock,
PromptResponse,
RequestPermissionRequest,
RequestPermissionResponse,
} from "@agentclientprotocol/sdk";
import {
ClientSideConnection,
ndJsonStream,
PROTOCOL_VERSION,
} from "@agentclientprotocol/sdk";
import { type ServerType, serve } from "@hono/node-server";
import { execGh } from "@posthog/git/gh";
import { getCurrentBranch } from "@posthog/git/queries";
import { unzipSync } from "fflate";
import { Hono } from "hono";
import { z } from "zod";
import packageJson from "../../package.json" with { type: "json" };
import { POSTHOG_METHODS, POSTHOG_NOTIFICATIONS } from "../acp-extensions";
import {
createAcpConnection,
type InProcessAcpConnection,
} from "../adapters/acp-connection";
import {
getSessionJsonlPath,
hydrateSessionJsonl,
} from "../adapters/claude/session/jsonl-hydration";
import type { GatewayEnv } from "../adapters/claude/session/options";
import {
type AgentErrorClassification,
classifyAgentError,
} from "../adapters/error-classification";
import {
SIGNED_COMMIT_QUALIFIED_TOOL_NAME,
SIGNED_MERGE_QUALIFIED_TOOL_NAME,
SIGNED_REWRITE_QUALIFIED_TOOL_NAME,
} from "../adapters/signed-commit-shared";
import type { PermissionMode } from "../execution-mode";
import { DEFAULT_CODEX_MODEL, fetchGatewayModels } from "../gateway-models";
import { HandoffCheckpointTracker } from "../handoff-checkpoint";
import { PostHogAPIClient } from "../posthog-api";
import { findPrUrl, wasCreatedRecently } from "../pr-url-detector";
import {
formatConversationForResume,
type ResumeState,
resumeFromLog,
} from "../resume";
import { SessionLogWriter } from "../session-log-writer";
import type {
AgentMode,
DeviceInfo,
GitCheckpointEvent,
HandoffLocalGitState,
LogLevel,
Task,
TaskRun,
TaskRunArtifact,
} from "../types";
import { resourceLink } from "../utils/acp-content";
import { AsyncMutex } from "../utils/async-mutex";
import {
buildGatewayPropertyHeaders,
resolveGatewayProduct,
resolveLlmGatewayUrl,
} from "../utils/gateway";
import { Logger } from "../utils/logger";
import { logAgentshRuntimeInfo } from "./agentsh-runtime";
import {
normalizeCloudPromptContent,
promptBlocksToText,
} from "./cloud-prompt";
import { TaskRunEventStreamSender } from "./event-stream-sender";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
import { resolveRtkSavings } from "./rtk-savings";
import {
handoffLocalGitStateSchema,
jsonRpcRequestSchema,
validateCommandParams,
} from "./schemas";
import type { AgentServerConfig } from "./types";
const agentErrorClassificationSchema = z.enum([
"upstream_stream_terminated",
"upstream_connection_error",
"upstream_timeout",
"upstream_provider_failure",
"agent_error",
]) satisfies z.ZodType<AgentErrorClassification>;
export const UPSTREAM_PROVIDER_FAILURE_MESSAGE =
"The upstream AI provider failed to process the request. Please retry the task in a few minutes.";
const upstreamProviderFailureClassifications =
new Set<AgentErrorClassification>([
"upstream_stream_terminated",
"upstream_connection_error",
"upstream_timeout",
"upstream_provider_failure",
]);
const errorWithClassificationSchema = z.object({
data: z.object({ classification: agentErrorClassificationSchema }),
});
type MessageCallback = (message: unknown) => void;
export const SSE_KEEPALIVE_INTERVAL_MS = 25_000;
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();
}
},
});
}
export function isTurnCompleteNotification(message: unknown): boolean {
return (
typeof message === "object" &&
message !== null &&
(message as { method?: unknown }).method ===
POSTHOG_NOTIFICATIONS.TURN_COMPLETE
);
}
interface SseController {
send: (data: unknown) => void;
close: () => void;
}
interface ActiveSession {
payload: JwtPayload;
acpSessionId: string;
acpConnection: InProcessAcpConnection;
clientConnection: ClientSideConnection;
sseController: SseController | null;
deviceInfo: DeviceInfo;
logWriter: SessionLogWriter;
/** Current permission mode, tracked for relay decisions */
permissionMode: PermissionMode;
/** Whether a desktop client has ever connected via SSE during this session */
hasDesktopConnected: boolean;
pendingHandoffGitState?: HandoffLocalGitState;
}
interface InstalledSkillBundle {
skillName: string;
skillDefinition: string;
contentSha256: string;
skillRoot: string;
}
interface BuiltPrompt {
prompt: ContentBlock[];
meta?: Record<string, unknown>;
}
function hiddenTextBlock(text: string): ContentBlock {
return {
type: "text",
text,
_meta: { ui: { hidden: true } },
} as ContentBlock;
}
interface LocalSkillPromptContext {
skillName: string;
context: string;
}
function getTaskRunStateString(
taskRun: TaskRun | null,
key: string,
): string | null {
const state = taskRun?.state;
if (!state || typeof state !== "object") {
return null;
}
const value = (state as Record<string, unknown>)[key];
return typeof value === "string" ? value : null;
}
// Prompt block we hand the agent when the user attached files but we could not
// load any of them into the session (missing from the run manifest, no storage
// path, etc.). Without this the caller falls back to the bare task description —
// e.g. "Attached files: pasted-text.txt" — which points the agent at files it
// was never given and makes it hunt the filesystem in vain. Be explicit instead.
function buildMissingAttachmentNotice(count: number): string {
const subject = count === 1 ? "A file" : `${count} files`;
const pronoun = count === 1 ? "it" : "they";
const noun = count === 1 ? "attachment" : "attachments";
return (
`${subject} the user attached to this message could not be loaded into the session, ` +
`so ${pronoun} are unavailable here. Do not guess at the contents. Tell the user the ` +
`${noun} didn't come through, and ask them to paste the text directly or send ${pronoun} again.`
);
}
export class AgentServer {
private config: AgentServerConfig;
private sessionReadyBootMs?: number;
private sessionInitMs?: number;
private barrierReleasedAtMs?: number;
private logger: Logger;
private server: ServerType | null = null;
private session: ActiveSession | null = null;
private app: Hono;
private posthogAPI: PostHogAPIClient;
private eventStreamSender: TaskRunEventStreamSender | null = null;
private rtkSavingsEmitted = false;
private questionRelayedToSlack = false;
private adapterEmittedTurnComplete = false;
private detectedPrUrl: string | null = null;
// Reset per session. `evaluatedPrUrls` dedupes per URL; `prAttributionChain` serializes
// attributions so the most recently created PR in a run wins.
private readonly evaluatedPrUrls = new Set<string>();
private prAttributionChain: Promise<void> = Promise.resolve();
private lastReportedBranch: string | null = null;
private resumeState: ResumeState | null = null;
private nativeResume: { sessionId: string; warm: boolean } | null = null;
private installedSkillBundles = new Set<string>();
private installedSkillBundleInfo = new Map<string, InstalledSkillBundle>();
private installingSkillBundles = new Map<string, Promise<void>>();
// 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 deliveredMessageIds = new Set<string>();
private pendingPermissions = new Map<
string,
{
resolve: (response: {
outcome: { outcome: "selected"; optionId: string };
_meta?: Record<string, unknown>;
}) => void;
toolCallId?: string;
}
>();
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}`,
});
if (config.eventIngestToken) {
this.eventStreamSender = new TaskRunEventStreamSender({
apiUrl: config.apiUrl,
eventIngestBaseUrl: config.eventIngestBaseUrl,
keepProxyStreamOpen: config.eventIngestKeepStreamOpen,
projectId: config.projectId,
taskId: config.taskId,
runId: config.runId,
token: config.eventIngestToken,
logger: this.logger.child("EventIngest"),
streamWindowMs: config.eventIngestStreamWindowMs,
});
}
this.app = this.createApp();
}
private getRuntimeAdapter(): "claude" | "codex" {
return this.config.runtimeAdapter ?? "claude";
}
private getEffectiveMode(payload: JwtPayload): AgentMode {
return payload.mode ?? this.config.mode;
}
private getSessionPermissionMode(): PermissionMode {
if (this.session?.permissionMode) {
return this.session.permissionMode;
}
return this.getRuntimeAdapter() === "codex" ? "auto" : "default";
}
private shouldRelayPermissionToClient(mode: PermissionMode): boolean {
return mode === "default" || mode === "auto" || mode === "read-only";
}
private createApp(): Hono {
const app = new Hono();
app.get("/health", (c) => {
return c.json({
status: "ok",
hasSession: !!this.session,
bootMs: this.sessionReadyBootMs,
sessionInitMs: this.sessionInitMs,
});
});
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,
);
}
let keepaliveInterval: ReturnType<typeof setInterval> | null = null;
const clearKeepalive = (): void => {
if (keepaliveInterval) {
clearInterval(keepaliveInterval);
keepaliveInterval = null;
}
};
const stream = new ReadableStream({
start: async (controller) => {
let sseController: SseController | null = null;
const encoder = new TextEncoder();
const detachCurrentSseController = (): void => {
if (sseController) {
this.detachSseController(sseController);
}
};
const enqueueSseFrame = (frame: string): void => {
try {
controller.enqueue(encoder.encode(frame));
} catch {
clearKeepalive();
detachCurrentSseController();
}
};
sseController = {
send: (data: unknown) => {
enqueueSseFrame(`data: ${JSON.stringify(data)}\n\n`);
},
close: () => {
try {
clearKeepalive();
controller.close();
} catch {
detachCurrentSseController();
}
},
};
keepaliveInterval = setInterval(() => {
enqueueSseFrame(": keepalive\n\n");
}, SSE_KEEPALIVE_INTERVAL_MS);
try {
if (
!this.session ||
this.session.payload.run_id !== payload.run_id
) {
await this.initializeSession(payload, sseController);
} else {
this.session.sseController = sseController;
this.session.hasDesktopConnected = true;
this.replayPendingEvents();
}
this.sendSseEvent(sseController, {
type: "connected",
run_id: payload.run_id,
});
} catch (error) {
clearKeepalive();
throw error;
}
},
cancel: () => {
clearKeepalive();
this.logger.debug("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.debug(
`HTTP server listening on port ${this.config.port}`,
{ bootMs: Math.round(process.uptime() * 1000) },
);
resolve();
},
);
});
await this.autoInitializeSession();
}
private async loadResumeState(
taskId: string,
resumeRunId: string,
currentRunId: string,
): Promise<void> {
this.logger.debug("Loading resume state", { resumeRunId, currentRunId });
try {
this.resumeState = await resumeFromLog({
taskId,
runId: resumeRunId,
repositoryPath: this.config.repositoryPath,
apiClient: this.posthogAPI,
logger: new Logger({ debug: true, prefix: "[Resume]" }),
});
this.logger.debug("Resume state loaded", {
conversationTurns: this.resumeState.conversation.length,
hasGitCheckpoint: !!this.resumeState.latestGitCheckpoint,
gitCheckpointBranch:
this.resumeState.latestGitCheckpoint?.branch ?? null,
logEntries: this.resumeState.logEntryCount,
});
} catch (error) {
this.logger.debug("Failed to load resume state, starting fresh", {
error,
});
this.resumeState = null;
}
}
private async prepareNativeResume(
payload: JwtPayload,
posthogAPI: PostHogAPIClient,
preTaskRun: TaskRun | null,
runtimeAdapter: "claude" | "codex",
cwd: string,
permissionMode: PermissionMode,
): Promise<{ sessionId: string; warm: boolean } | null> {
if (runtimeAdapter !== "claude") return null;
const resumeRunId = this.getResumeRunId(preTaskRun);
if (!resumeRunId) return null;
if (!this.resumeState) {
await this.loadResumeState(payload.task_id, resumeRunId, payload.run_id);
}
const priorSessionId = this.resumeState?.sessionId ?? null;
if (!priorSessionId) {
this.logger.debug("No prior session id; using summary resume fallback", {
resumeRunId,
});
return null;
}
let warm = false;
try {
await access(getSessionJsonlPath(priorSessionId, cwd));
warm = true;
} catch {
warm = false;
}
try {
const hasSession = await hydrateSessionJsonl({
sessionId: priorSessionId,
cwd,
taskId: payload.task_id,
runId: resumeRunId,
model: this.config.model,
permissionMode,
posthogAPI,
log: {
info: (msg, data) => this.logger.debug(msg, data),
warn: (msg, data) => this.logger.warn(msg, data),
},
});
if (!hasSession) {
this.logger.debug(
"No session JSONL to resume; using summary fallback",
{
resumeRunId,
priorSessionId,
},
);
return null;
}
} catch (error) {
this.logger.warn(
"Session JSONL hydration failed; using summary fallback",
{
priorSessionId,
error: error instanceof Error ? error.message : String(error),
},
);
return null;
}
this.logger.debug("Native resume prepared", { priorSessionId, warm });
return { sessionId: priorSessionId, warm };
}
async stop(): Promise<void> {
this.logger.debug("Stopping agent server...");
if (this.session) {
await this.cleanupSession({ completeEventStream: true });
} else {
await this.eventStreamSender?.stop();
}
if (this.server) {
this.server.close();
this.server = null;
}
this.logger.debug("Agent server stopped");
}
/**
* Mark the run failed after an unrecoverable crash (uncaught exception /
* unhandled rejection). Without this a hard death is silent: the run row
* stays non-terminal, the desktop client just sees the stream stop and shows
* a generic "Cloud stream disconnected", and the workflow only gives up after
* the multi-hour inactivity timeout. Best-effort and self-contained so it can
* run from a process-level handler with no session context.
*/
async reportFatalError(error: unknown): Promise<void> {
const errorMessage = error instanceof Error ? error.message : String(error);
this.logger.error("Fatal agent-server error; marking run failed", error);
try {
await this.posthogAPI.updateTaskRun(
this.config.taskId,
this.config.runId,
{
status: "failed",
error_message: `Agent server crashed: ${errorMessage}`,
},
);
} catch (updateError) {
this.logger.error(
"Failed to mark run failed after fatal error",
updateError,
);
}
try {
await this.eventStreamSender?.stop();
} catch (stopError) {
this.logger.error(
"Failed to flush event stream after fatal error",
stopError,
);
}
}
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": {
this.logger.debug("Received user_message command", {
hasContent:
typeof params.content === "string"
? params.content.trim().length > 0
: Array.isArray(params.content) && params.content.length > 0,
artifactCount: Array.isArray(params.artifacts)
? params.artifacts.length
: 0,
});
const builtPrompt = await this.buildPromptFromContentAndArtifacts({
content: params.content as string | ContentBlock[] | undefined,
artifacts: Array.isArray(params.artifacts)
? (params.artifacts as TaskRunArtifact[])
: [],
taskId: this.session.payload.task_id,
runId: this.session.payload.run_id,
});
const prompt = builtPrompt.prompt;
if (prompt.length === 0) {
throw new Error("User message cannot be empty");
}
const messageId =
typeof params.messageId === "string" && params.messageId
? params.messageId
: undefined;
if (messageId) {
if (this.deliveredMessageIds.has(messageId)) {
this.logger.info("Duplicate user_message delivery ignored", {
messageId,
});
return { stopReason: "duplicate_delivery", duplicate: true };
}
this.deliveredMessageIds.add(messageId);
if (this.deliveredMessageIds.size > 500) {
const oldest = this.deliveredMessageIds.values().next().value;
if (oldest !== undefined) {
this.deliveredMessageIds.delete(oldest);
}
}
}
this.logger.debug("Built user_message prompt", {
blockTypes: prompt.map((block) => block.type),
});
const promptPreview = promptBlocksToText(prompt);
this.logger.debug(
`Processing user message (detectedPrUrl=${this.detectedPrUrl ?? "none"}): ${promptPreview.substring(0, 100)}...`,
);
this.session.logWriter.resetTurnMessages(this.session.payload.run_id);
const promptMeta: Record<string, unknown> = {
...(builtPrompt.meta ?? {}),
...(this.detectedPrUrl
? {
prContext: this.buildDetectedPrContext(this.detectedPrUrl),
}
: {}),
};
let result: PromptResponse;
try {
result = await this.session.clientConnection.prompt({
sessionId: this.session.acpSessionId,
prompt,
...(Object.keys(promptMeta).length > 0
? { _meta: promptMeta }
: {}),
});
} catch (error) {
if (messageId) {
this.deliveredMessageIds.delete(messageId);
}
await this.session.logWriter.flushAll();
const { recoverable } = await this.handleTurnFailure(
this.session.payload,
"followup",
error,
);
if (!recoverable) {
throw error;
}
return { stopReason: "error_recoverable" };
}
this.logger.debug("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.debug("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.debug("Failed to extract assistant message from logs");
}
return {
stopReason: result.stopReason,
...(assistantMessage && { assistant_message: assistantMessage }),
};
}
case POSTHOG_NOTIFICATIONS.CANCEL:
case "cancel": {
this.logger.debug("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.debug("Close requested");
const localGitState = this.extractHandoffLocalGitState(params);
if (localGitState && this.session) {
this.session.pendingHandoffGitState = localGitState;
}
await this.cleanupSession();
return { closed: true };
}
case "posthog/set_config_option":
case "set_config_option": {
const configId = params.configId as string;
const value = params.value as string;
this.logger.debug("Set config option requested", { configId, value });
const result =
await this.session.clientConnection.setSessionConfigOption({
sessionId: this.session.acpSessionId,
configId,
value,
});
return {
configOptions: result.configOptions,
};
}
case POSTHOG_METHODS.REFRESH_SESSION:
case "posthog/refresh_session":
case "refresh_session": {
const mcpServers = Array.isArray(params.mcpServers)
? params.mcpServers
: [];
const refreshedCredentials = Array.isArray(params.refreshedCredentials)
? (params.refreshedCredentials as string[])
: [];
const authorship =
typeof params.authorship === "string" ? params.authorship : "";