forked from nicobailon/pi-intercom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1832 lines (1747 loc) · 71.1 KB
/
Copy pathindex.ts
File metadata and controls
1832 lines (1747 loc) · 71.1 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 { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
import { randomUUID } from "crypto";
import { Type } from "typebox";
import { Text } from "@mariozechner/pi-tui";
import { IntercomClient } from "./broker/client.ts";
import { spawnBrokerIfNeeded } from "./broker/spawn.ts";
import { SessionListOverlay } from "./ui/session-list.ts";
import { ComposeOverlay, type ComposeResult } from "./ui/compose.ts";
import { InlineMessageComponent } from "./ui/inline-message.ts";
import { loadConfig, type IntercomConfig } from "./config.ts";
import type { SessionInfo, Message, Attachment } from "./types.ts";
import { ReplyTracker } from "./reply-tracker.ts";
const SUBAGENT_CONTROL_INTERCOM_EVENT = "subagent:control-intercom";
const SUBAGENT_RESULT_INTERCOM_EVENT = "subagent:result-intercom";
const SUBAGENT_RESULT_INTERCOM_DELIVERY_EVENT = "subagent:result-intercom-delivery";
const INBOUND_FLUSH_DELAY_MS = 200;
const INBOUND_IDLE_RETRY_MS = 500;
const DEFAULT_UNNAMED_SESSION_ALIAS_PREFIX = "subagent-chat";
const SUBAGENT_ORCHESTRATOR_TARGET_ENV = "PI_SUBAGENT_ORCHESTRATOR_TARGET";
const SUBAGENT_RUN_ID_ENV = "PI_SUBAGENT_RUN_ID";
const SUBAGENT_CHILD_AGENT_ENV = "PI_SUBAGENT_CHILD_AGENT";
const SUBAGENT_CHILD_INDEX_ENV = "PI_SUBAGENT_CHILD_INDEX";
const SUBAGENT_INTERCOM_SESSION_NAME_ENV = "PI_SUBAGENT_INTERCOM_SESSION_NAME";
const PRESENCE_RENAME_POLL_MS = 2000;
interface ChildOrchestratorMetadata {
orchestratorTarget: string;
runId: string;
agent: string;
index: string;
sessionName?: string;
}
interface InboundMessageEntry {
from: SessionInfo;
message: Message;
replyCommand?: string;
bodyText: string;
}
type ContactSupervisorReason = "need_decision" | "progress_update" | "interview_request";
interface SupervisorInterviewQuestion extends Record<string, unknown> {
id: string;
type: "single" | "multi" | "text" | "image" | "info";
question: string;
options?: unknown[];
}
interface SupervisorInterviewRequest extends Record<string, unknown> {
title?: string;
description?: string;
questions: SupervisorInterviewQuestion[];
}
interface SupervisorInterviewReply {
responses: Array<{ id: string; value: unknown }>;
}
function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function toError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function formatAttachments(attachments: Attachment[]): string {
let text = "";
for (const att of attachments) {
if (att.language) {
text += `\n\n---\n📎 ${att.name}\n~~~${att.language}\n${att.content}\n~~~`;
} else {
text += `\n\n---\n📎 ${att.name}\n${att.content}`;
}
}
return text;
}
function readChildOrchestratorMetadata(): ChildOrchestratorMetadata | null {
const orchestratorTarget = process.env[SUBAGENT_ORCHESTRATOR_TARGET_ENV]?.trim();
const runId = process.env[SUBAGENT_RUN_ID_ENV]?.trim();
const agent = process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim();
const index = process.env[SUBAGENT_CHILD_INDEX_ENV]?.trim();
if (!orchestratorTarget || !runId || !agent || !index) {
return null;
}
const sessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();
return {
orchestratorTarget,
runId,
agent,
index,
...(sessionName ? { sessionName } : {}),
};
}
function formatChildOrchestratorMessage(kind: "ask" | "update" | "interview", metadata: ChildOrchestratorMetadata, message: string): string {
const heading = kind === "ask"
? "Subagent needs a supervisor decision."
: kind === "interview"
? "Subagent requests a structured supervisor interview."
: "Subagent progress update.";
return [
heading,
`Run: ${metadata.runId}`,
`Agent: ${metadata.agent}`,
`Child index: ${metadata.index}`,
metadata.sessionName ? `Child intercom target: ${metadata.sessionName}` : undefined,
"",
message,
].filter((line): line is string => line !== undefined).join("\n");
}
function validateSupervisorInterviewRequest(input: unknown): { ok: true; interview: SupervisorInterviewRequest } | { ok: false; error: string } {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return { ok: false, error: "interview must be an object with a questions array" };
}
const raw = input as Record<string, unknown>;
if (raw.title !== undefined && typeof raw.title !== "string") {
return { ok: false, error: "interview.title must be a string when provided" };
}
if (raw.description !== undefined && typeof raw.description !== "string") {
return { ok: false, error: "interview.description must be a string when provided" };
}
if (!Array.isArray(raw.questions) || raw.questions.length === 0) {
return { ok: false, error: "interview.questions must be a non-empty array" };
}
const validTypes = new Set(["single", "multi", "text", "image", "info"]);
const ids = new Set<string>();
const questions: SupervisorInterviewQuestion[] = [];
for (let index = 0; index < raw.questions.length; index++) {
const questionInput = raw.questions[index];
if (!questionInput || typeof questionInput !== "object" || Array.isArray(questionInput)) {
return { ok: false, error: `interview.questions[${index}] must be an object` };
}
const question = questionInput as Record<string, unknown>;
if (typeof question.id !== "string" || question.id.trim() === "") {
return { ok: false, error: `interview.questions[${index}].id must be a non-empty string` };
}
const id = question.id.trim();
if (ids.has(id)) {
return { ok: false, error: `interview question id must be unique: ${id}` };
}
ids.add(id);
if (typeof question.type !== "string" || !validTypes.has(question.type)) {
return { ok: false, error: `interview.questions[${index}].type must be one of: single, multi, text, image, info` };
}
if (typeof question.question !== "string" || question.question.trim() === "") {
return { ok: false, error: `interview.questions[${index}].question must be a non-empty string` };
}
if (question.context !== undefined && typeof question.context !== "string") {
return { ok: false, error: `interview.questions[${index}].context must be a string when provided` };
}
let options: unknown[] | undefined;
if (question.options !== undefined) {
if (!Array.isArray(question.options)) {
return { ok: false, error: `interview.questions[${index}].options must be an array when provided` };
}
options = [];
for (let optionIndex = 0; optionIndex < question.options.length; optionIndex++) {
const option = question.options[optionIndex];
if (typeof option === "string") {
const label = option.trim();
if (!label) {
return { ok: false, error: `interview.questions[${index}].options[${optionIndex}] must not be empty` };
}
options.push(label);
} else if (!option || typeof option !== "object" || Array.isArray(option) || typeof (option as { label?: unknown }).label !== "string" || (option as { label: string }).label.trim() === "") {
return { ok: false, error: `interview.questions[${index}].options[${optionIndex}] must be a non-empty string or an object with a non-empty label` };
} else {
options.push({ ...option, label: (option as { label: string }).label.trim() });
}
}
}
if ((question.type === "single" || question.type === "multi") && (!options || options.length === 0)) {
return { ok: false, error: `interview.questions[${index}].options must be a non-empty array for ${question.type} questions` };
}
if (question.type !== "single" && question.type !== "multi" && options) {
return { ok: false, error: `interview.questions[${index}].options is only valid for single and multi questions` };
}
questions.push({
...question,
id,
type: question.type as SupervisorInterviewQuestion["type"],
question: question.question.trim(),
...(options ? { options } : {}),
});
}
return {
ok: true,
interview: {
...raw,
...(typeof raw.title === "string" ? { title: raw.title.trim() } : {}),
...(typeof raw.description === "string" ? { description: raw.description.trim() } : {}),
questions,
},
};
}
function interviewOptionLabel(option: unknown): string {
return typeof option === "string" ? option : (option as { label: string }).label;
}
function interviewExampleValue(question: SupervisorInterviewQuestion): unknown {
if (question.type === "multi") {
return question.options?.slice(0, 2).map(interviewOptionLabel) ?? [];
}
if (question.type === "single") {
return question.options?.[0] !== undefined ? interviewOptionLabel(question.options[0]) : "option label";
}
if (question.type === "image") {
return "image/file reference or description";
}
return "answer text";
}
function formatSupervisorInterviewRequest(interview: SupervisorInterviewRequest, message?: string): string {
const lines: string[] = [];
const title = interview.title?.trim();
if (title) lines.push(`Interview: ${title}`);
const description = interview.description?.trim();
if (description) lines.push(description);
const note = message?.trim();
if (note) lines.push(`Child note: ${note}`);
if (lines.length > 0) lines.push("");
lines.push("Questions:");
interview.questions.forEach((question, index) => {
lines.push(`${index + 1}. [${question.id}] (${question.type}) ${question.question}`);
if (typeof question.context === "string" && question.context.trim()) {
lines.push(` Context: ${question.context.trim()}`);
}
if (question.options?.length) {
lines.push(" Options:");
for (const option of question.options) {
lines.push(` - ${interviewOptionLabel(option)}`);
}
}
});
const responseExample = {
responses: interview.questions
.filter((question) => question.type !== "info")
.map((question) => ({
id: question.id,
value: interviewExampleValue(question),
})),
};
lines.push(
"",
"Supervisor reply instructions:",
"Reply with plain JSON or a fenced ```json block using this stable shape. Use the question ids exactly. Info questions are context-only and do not need responses. For single questions, value is one option label. For multi questions, value is an array of option labels. For text/image questions, value is a string unless the question asks otherwise.",
"",
"```json",
JSON.stringify(responseExample, null, 2),
"```",
);
return lines.join("\n");
}
function validateSupervisorInterviewReply(value: unknown, interview: SupervisorInterviewRequest): SupervisorInterviewReply {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("reply JSON must be an object with a responses array");
}
const responsesInput = (value as Record<string, unknown>).responses;
if (!Array.isArray(responsesInput)) {
throw new Error("reply JSON must include a responses array");
}
const questionById = new Map(interview.questions
.filter((question) => question.type !== "info")
.map((question) => [question.id, question]));
const seenIds = new Set<string>();
const responses: SupervisorInterviewReply["responses"] = [];
for (let index = 0; index < responsesInput.length; index++) {
const response = responsesInput[index];
if (!response || typeof response !== "object" || Array.isArray(response)) {
throw new Error(`responses[${index}] must be an object`);
}
const raw = response as Record<string, unknown>;
if (typeof raw.id !== "string" || raw.id.trim() === "") {
throw new Error(`responses[${index}].id must be a non-empty string`);
}
const id = raw.id.trim();
const question = questionById.get(id);
if (!question) {
throw new Error(`responses[${index}].id must match a non-info interview question id`);
}
if (seenIds.has(id)) {
throw new Error(`responses[${index}].id is duplicated: ${id}`);
}
seenIds.add(id);
if (!Object.hasOwn(raw, "value")) {
throw new Error(`responses[${index}].value is required`);
}
const value = raw.value;
if (question.type === "single") {
if (typeof value !== "string") throw new Error(`responses[${index}].value must be a string for single questions`);
const optionLabels = new Set(question.options?.map(interviewOptionLabel));
if (!optionLabels.has(value.trim())) throw new Error(`responses[${index}].value must match one of the question options`);
responses.push({ id, value: value.trim() });
continue;
}
if (question.type === "multi") {
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
throw new Error(`responses[${index}].value must be an array of strings for multi questions`);
}
const optionLabels = new Set(question.options?.map(interviewOptionLabel));
const selected = value.map((item) => item.trim());
const invalid = selected.find((item) => !optionLabels.has(item));
if (invalid) throw new Error(`responses[${index}].value contains an option that is not in the question options: ${invalid}`);
responses.push({ id, value: selected });
continue;
}
if (typeof value !== "string") {
throw new Error(`responses[${index}].value must be a string for ${question.type} questions`);
}
responses.push({ id, value });
}
return { responses };
}
function parseStructuredSupervisorReply(text: string, interview: SupervisorInterviewRequest): { value?: SupervisorInterviewReply; error?: string } | undefined {
const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
const candidate = (fencedMatch?.[1] ?? text).trim();
if (!candidate.startsWith("{") && !candidate.startsWith("[")) {
return undefined;
}
try {
return { value: validateSupervisorInterviewReply(JSON.parse(candidate), interview) };
} catch (error) {
return { error: getErrorMessage(error) };
}
}
function duplicateSessionNames(sessions: SessionInfo[]): Set<string> {
return new Set(
sessions
.map(s => s.name?.toLowerCase())
.filter((name): name is string => Boolean(name))
.filter((name, index, names) => names.indexOf(name) !== index)
);
}
function shortSessionId(sessionId: string): string {
return sessionId.slice(0, 8);
}
function parseSubagentIntercomPayload(payload: unknown): { to: string; message: string; requestId?: string } | null {
if (typeof payload !== "object" || payload === null) {
return null;
}
const record = payload as Record<string, unknown>;
if (typeof record.to !== "string" || typeof record.message !== "string") {
return null;
}
const requestId = typeof record.requestId === "string" ? record.requestId : undefined;
return { to: record.to, message: record.message, ...(requestId ? { requestId } : {}) };
}
function resolveIntercomPresenceName(sessionName: string | undefined, sessionId: string): string {
const trimmedName = sessionName?.trim();
if (trimmedName) {
return trimmedName;
}
const normalizedSessionId = sessionId.startsWith("session-") ? sessionId.slice("session-".length) : sessionId;
return `${DEFAULT_UNNAMED_SESSION_ALIAS_PREFIX}-${normalizedSessionId.slice(0, 8)}`;
}
function buildPresenceIdentity(pi: ExtensionAPI, sessionId: string): { name: string } {
return {
name: resolveIntercomPresenceName(pi.getSessionName(), sessionId),
};
}
function formatSessionLabel(session: SessionInfo, duplicates: Set<string>): string {
if (!session.name) {
return session.id;
}
return duplicates.has(session.name.toLowerCase())
? `${session.name} (${shortSessionId(session.id)})`
: session.name;
}
function formatSessionListRow(session: SessionInfo, currentCwd: string, isSelf: boolean): string {
const name = session.name || "Unnamed session";
const tags = [isSelf ? "self" : session.cwd === currentCwd ? "same cwd" : undefined, session.status]
.filter((tag): tag is string => Boolean(tag));
const suffix = tags.length ? ` [${tags.join(", ")}]` : "";
return `• ${name} (${shortSessionId(session.id)}) — ${session.cwd} (${session.model})${suffix}`;
}
function previewText(value: unknown, maxLength = 72): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.replace(/\s+/g, " ").trim();
if (!normalized) {
return undefined;
}
return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 1)}…` : normalized;
}
function firstTextContent(result: { content?: Array<{ type: string; text?: string }> }): string {
return result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.replace(/\*\*/g, "") ?? "";
}
export default function piIntercomExtension(pi: ExtensionAPI) {
let client: IntercomClient | null = null;
const config: IntercomConfig = loadConfig();
let runtimeContext: ExtensionContext | null = null;
let currentSessionId: string | null = null;
let currentModel = "unknown";
let sessionStartedAt: number | null = null;
let reconnectTimer: NodeJS.Timeout | null = null;
let reconnectPromise: Promise<IntercomClient> | null = null;
let reconnectPromiseGeneration: number | null = null;
let startupConnectTimer: NodeJS.Timeout | null = null;
let reconnectAttempt = 0;
let shuttingDown = false;
let disposed = true;
let runtimeStarted = false;
let runtimeGeneration = 0;
let agentRunning = false;
// Tracks the last presence name we pushed to the broker. Compared against
// pi.getSessionName() on every status sync so we can detect renames that
// pi-coding-agent does not currently route through the extension runner.
// See note on syncPresenceStatus below.
let lastPushedName: string | undefined;
let presenceRenamePoller: NodeJS.Timeout | null = null;
const activeTools = new Map<string, string>();
const replyTracker = new ReplyTracker();
const pendingIdleMessages: InboundMessageEntry[] = [];
let inboundFlushTimer: NodeJS.Timeout | null = null;
let replyWaiter: {
from: string;
replyTo: string;
resolve: (message: Message) => void;
reject: (error: Error) => void;
} | null = null;
function waitForReply(from: string, replyTo: string, signal?: AbortSignal): Promise<Message> {
if (replyWaiter) {
return Promise.reject(new Error("Already waiting for a reply"));
}
if (signal?.aborted) {
return Promise.reject(new Error("Cancelled"));
}
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
rejectReplyWaiter(new Error(`No reply from "${from}" within 10 minutes`));
}, 10 * 60 * 1000);
const cleanup = () => {
clearTimeout(timeout);
signal?.removeEventListener("abort", onAbort);
if (replyWaiter?.replyTo === replyTo) {
replyWaiter = null;
}
};
const onAbort = () => {
cleanup();
reject(new Error("Cancelled"));
};
signal?.addEventListener("abort", onAbort, { once: true });
replyWaiter = {
from,
replyTo,
resolve: (message) => {
cleanup();
resolve(message);
},
reject: (error) => {
cleanup();
reject(error);
},
};
});
}
function rejectReplyWaiter(error: Error): void {
replyWaiter?.reject(error);
}
function clearReconnectTimer(): void {
if (!reconnectTimer) {
return;
}
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
function clearStartupConnectTimer(): void {
if (!startupConnectTimer) {
return;
}
clearTimeout(startupConnectTimer);
startupConnectTimer = null;
}
function clearInboundFlushTimer(): void {
if (!inboundFlushTimer) {
return;
}
clearTimeout(inboundFlushTimer);
inboundFlushTimer = null;
}
function getLiveContext(ctx: ExtensionContext | null = runtimeContext, generation = runtimeGeneration): ExtensionContext | null {
if (disposed || shuttingDown || generation !== runtimeGeneration || !ctx) {
return null;
}
try {
if (currentSessionId && ctx.sessionManager.getSessionId() !== currentSessionId) {
return null;
}
void ctx.hasUI;
return ctx;
} catch {
// A context that throws while reading session/UI state is no longer usable.
return null;
}
}
function notifyIfLive(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error", generation = runtimeGeneration): void {
const liveContext = getLiveContext(ctx, generation);
if (!liveContext?.hasUI) {
return;
}
try {
liveContext.ui.notify(message, level);
} catch {
// The UI can disappear during session shutdown/reload while async overlay work is settling.
}
}
function getReconnectDelayMs(): number {
const backoffMs = [1000, 2000, 5000, 10000, 30000];
return backoffMs[Math.min(reconnectAttempt, backoffMs.length - 1)]!;
}
function currentStatus(): string {
const activeToolName = activeTools.values().next().value;
const lifecycleStatus = activeToolName ? `tool:${activeToolName}` : agentRunning ? "thinking" : "idle";
return config.status ? `${lifecycleStatus} · ${config.status}` : lifecycleStatus;
}
function buildRegistration(): Omit<SessionInfo, "id"> {
const liveContext = getLiveContext();
if (!liveContext || !currentSessionId || sessionStartedAt === null) {
throw new Error("Intercom runtime not initialized");
}
const identity = buildPresenceIdentity(pi, currentSessionId);
return {
name: identity.name,
cwd: liveContext.cwd ?? process.cwd(),
model: currentModel,
pid: process.pid,
startedAt: sessionStartedAt,
lastActivity: Date.now(),
status: currentStatus(),
};
}
function syncPresenceIdentity(sessionId: string): void {
if (!client || !getLiveContext()) {
return;
}
const identity = buildPresenceIdentity(pi, sessionId);
client.updatePresence({ ...identity, status: currentStatus() });
lastPushedName = identity.name;
}
function syncPresenceStatus(): void {
if (!client || !currentSessionId || !getLiveContext()) {
return;
}
// pi-coding-agent's setSessionName only emits to internal listeners and
// never reaches the extension runner, so renames done through /name,
// /rename, or any other caller are invisible to us as a discrete event.
// To stay correct without forking pi-coding-agent, opportunistically
// detect that the resolved presence name has drifted from what we last
// pushed and upgrade this status-only sync to a full identity sync. Both
// the built-in /name (which calls AgentSession.setSessionName directly)
// and the public pi.setSessionName converge on the same internal method,
// so this drift check covers both rename paths.
const expectedName = resolveIntercomPresenceName(pi.getSessionName(), currentSessionId);
if (expectedName !== lastPushedName) {
syncPresenceIdentity(currentSessionId);
return;
}
client.updatePresence({ status: currentStatus() });
}
function pollPresenceRenameDrift(): void {
if (!client || !currentSessionId || !getLiveContext()) {
return;
}
const expectedName = resolveIntercomPresenceName(pi.getSessionName(), currentSessionId);
if (expectedName !== lastPushedName) {
syncPresenceIdentity(currentSessionId);
}
}
function startPresenceRenamePoller(): void {
if (presenceRenamePoller) {
return;
}
presenceRenamePoller = setInterval(pollPresenceRenameDrift, PRESENCE_RENAME_POLL_MS);
presenceRenamePoller.unref?.();
}
function stopPresenceRenamePoller(): void {
if (!presenceRenamePoller) {
return;
}
clearInterval(presenceRenamePoller);
presenceRenamePoller = null;
}
function currentSessionTargetMatches(to: string, resolvedTo?: string | null, activeClient?: IntercomClient): boolean {
const targets = new Set<string>();
const addTarget = (target: string | undefined | null) => {
const trimmed = target?.trim();
if (trimmed) targets.add(trimmed.toLowerCase());
};
addTarget(currentSessionId);
addTarget(activeClient?.sessionId);
addTarget(pi.getSessionName());
if (currentSessionId) addTarget(buildPresenceIdentity(pi, currentSessionId).name);
return Boolean(resolvedTo && activeClient?.sessionId && resolvedTo === activeClient.sessionId)
|| targets.has(to.trim().toLowerCase());
}
function sendIncomingMessage(entry: InboundMessageEntry, delivery: "trigger" | "followUp", generation = runtimeGeneration): void {
if (runtimeStarted && !getLiveContext(runtimeContext, generation)) {
return;
}
if (delivery !== "followUp") {
replyTracker.queueTurnContext({ from: entry.from, message: entry.message, receivedAt: Date.now() });
}
const senderDisplay = entry.from.name || entry.from.id.slice(0, 8);
const replyInstruction = entry.replyCommand ? `\n\nTo reply, use the intercom tool: ${entry.replyCommand}` : "";
pi.sendMessage(
{
customType: "intercom_message",
content: `**📨 From ${senderDisplay}** (${entry.from.cwd})${replyInstruction}\n\n${entry.bodyText}`,
display: true,
details: entry,
},
delivery === "trigger"
? { triggerTurn: true }
: { deliverAs: "followUp" }
);
}
function scheduleInboundFlush(delayMs = INBOUND_FLUSH_DELAY_MS): void {
if (!getLiveContext()) {
return;
}
const scheduledGeneration = runtimeGeneration;
clearInboundFlushTimer();
inboundFlushTimer = setTimeout(() => {
inboundFlushTimer = null;
flushIdleMessages(scheduledGeneration);
}, delayMs);
}
function flushIdleMessages(generation = runtimeGeneration): void {
if (pendingIdleMessages.length === 0) {
return;
}
const ctx = getLiveContext(runtimeContext, generation);
if (!ctx) {
return;
}
let isIdle: boolean;
try {
isIdle = ctx.isIdle();
} catch {
// Stale contexts are cleaned up by shutdown/reload; do not deliver queued messages through them.
return;
}
if (!isIdle) {
scheduleInboundFlush(INBOUND_IDLE_RETRY_MS);
return;
}
const entries = pendingIdleMessages.splice(0, pendingIdleMessages.length);
entries.forEach((entry, index) => {
sendIncomingMessage(entry, index === 0 ? "trigger" : "followUp");
});
}
function queueIdleMessage(entry: InboundMessageEntry): void {
pendingIdleMessages.push(entry);
scheduleInboundFlush();
}
function handleIncomingMessage(ctx: ExtensionContext, from: SessionInfo, message: Message): void {
const messageGeneration = runtimeGeneration;
const liveContext = getLiveContext(ctx, messageGeneration);
if (!liveContext) {
return;
}
if (replyWaiter) {
const senderTarget = from.name || from.id;
const fromMatches = senderTarget.toLowerCase() === replyWaiter.from.toLowerCase()
|| from.id === replyWaiter.from;
const replyMatches = message.replyTo === replyWaiter.replyTo;
if (fromMatches && replyMatches) {
replyWaiter.resolve(message);
return;
}
}
const attachmentText = message.content.attachments?.length
? formatAttachments(message.content.attachments)
: "";
const bodyText = `${message.content.text}${attachmentText}`;
const replyCommand = config.replyHint && message.expectsReply
? `intercom({ action: "reply", message: "..." })`
: undefined;
replyTracker.recordIncomingMessage(from, message);
const entry = { from, message, replyCommand, bodyText };
void (async () => {
const activeContext = getLiveContext(liveContext, messageGeneration);
if (!activeContext) {
return;
}
if (!activeContext.isIdle()) {
if (!activeContext.hasUI) {
const activeClient = client;
if (!message.replyTo && activeClient?.isConnected()) {
try {
const result = await activeClient.send(from.id, {
text: "This agent is running in non-interactive mode and cannot respond to intercom messages while it is working. It will continue its current task and exit when done.",
replyTo: message.id,
});
if (result.delivered && getLiveContext(liveContext, messageGeneration)) {
replyTracker.markReplied(message.id);
}
} catch {
// Best-effort reply; keep the busy non-interactive session running either way.
}
}
return;
}
queueIdleMessage(entry);
return;
}
if (getLiveContext(liveContext, messageGeneration)) {
sendIncomingMessage(entry, "trigger", messageGeneration);
}
})();
}
function attachClientHandlers(nextClient: IntercomClient): void {
nextClient.on("message", (from, message) => {
const liveContext = getLiveContext();
if (client !== nextClient || !liveContext) {
return;
}
handleIncomingMessage(liveContext, from, message);
});
nextClient.on("disconnected", (error: Error) => {
if (client !== nextClient) {
return;
}
rejectReplyWaiter(new Error(`Disconnected while waiting for reply: ${error.message}`, { cause: error }));
client = null;
if (!shuttingDown && !disposed) {
clearReconnectTimer();
scheduleReconnect();
}
});
nextClient.on("error", () => {
// Keep broker/socket noise out of the TUI. Reconnect logic runs from the disconnect path.
});
}
function scheduleReconnect(): void {
if (disposed || shuttingDown || reconnectTimer || reconnectPromise || !getLiveContext()) {
return;
}
const scheduledGeneration = runtimeGeneration;
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
if (scheduledGeneration !== runtimeGeneration || !getLiveContext()) {
return;
}
reconnectAttempt += 1;
void ensureConnected("background").catch(() => {
// ensureConnected("background") already queued the next retry.
});
}, getReconnectDelayMs());
}
async function ensureConnected(reason: "startup" | "background" | "tool" | "overlay"): Promise<IntercomClient> {
if (!config.enabled) {
throw new Error("Intercom disabled");
}
if (disposed || shuttingDown) {
throw new Error("Intercom shutting down");
}
if (client && client.isConnected()) {
return client;
}
const contextAtStart = getLiveContext();
const generationAtStart = runtimeGeneration;
if (!contextAtStart || !currentSessionId || sessionStartedAt === null) {
throw new Error("Intercom runtime not initialized");
}
clearReconnectTimer();
if (reconnectPromise && reconnectPromiseGeneration === generationAtStart) {
return reconnectPromise;
}
const nextReconnectPromise = (async () => {
const nextClient = new IntercomClient();
client = nextClient;
attachClientHandlers(nextClient);
try {
await spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs);
const registration = buildRegistration();
await nextClient.connect(registration);
if (!getLiveContext(contextAtStart, generationAtStart)) {
await nextClient.disconnect();
throw new Error("Intercom runtime no longer active");
}
client = nextClient;
// Seed the drift baseline so the very first post-connect status sync
// does not redundantly upgrade itself to a full identity sync.
lastPushedName = registration.name;
reconnectAttempt = 0;
startPresenceRenamePoller();
return nextClient;
} catch (error) {
if (client === nextClient) {
client = null;
}
if (reason === "background" && getLiveContext(contextAtStart, generationAtStart)) {
scheduleReconnect();
}
throw toError(error);
} finally {
if (reconnectPromise === nextReconnectPromise) {
reconnectPromise = null;
reconnectPromiseGeneration = null;
}
}
})();
reconnectPromise = nextReconnectPromise;
reconnectPromiseGeneration = generationAtStart;
return nextReconnectPromise;
}
async function resolveSessionTarget(activeClient: IntercomClient, nameOrId: string): Promise<string | null> {
const sessions = await activeClient.listSessions();
const byId = sessions.find(s => s.id === nameOrId);
if (byId) {
return byId.id;
}
const lowerName = nameOrId.toLowerCase();
const byName = sessions.filter(s => s.name?.toLowerCase() === lowerName);
if (byName.length > 1) {
throw new Error(`Multiple sessions named "${nameOrId}" are connected. Use the session ID instead.`);
}
return byName[0]?.id ?? null;
}
function deliverLocalSubagentRelayMessage(sender: "subagent-control" | "subagent-result", status: string, messageText: string): void {
const now = Date.now();
sendIncomingMessage({
from: {
id: sender,
name: sender,
cwd: runtimeContext?.cwd ?? process.cwd(),
model: sender,
pid: process.pid,
startedAt: now,
lastActivity: now,
status,
},
message: {
id: randomUUID(),
timestamp: now,
content: { text: messageText },
},
bodyText: messageText,
}, "trigger");
}
function recordSubagentDeliveryError(entryType: string, to: string, message: string, error: unknown): void {
pi.appendEntry(entryType, {
to,
message,
error: getErrorMessage(error),
timestamp: Date.now(),
});
}
function emitResultDelivery(requestId: string | undefined, delivered: boolean, error?: unknown): void {
if (!requestId) return;
pi.events.emit(SUBAGENT_RESULT_INTERCOM_DELIVERY_EVENT, {
requestId,
delivered,
...(error ? { error: getErrorMessage(error) } : {}),
});
}
function relaySubagentIntercomPayload(payload: unknown, options: {
sender: "subagent-control" | "subagent-result";
status: string;
errorEntryType: string;
acknowledge?: boolean;
}): void {
const parsed = parseSubagentIntercomPayload(payload);
if (!parsed) return;
const relayGeneration = runtimeGeneration;
void (async () => {
const relayStillLive = () => !runtimeStarted || Boolean(getLiveContext(runtimeContext, relayGeneration));
if (!relayStillLive()) {
return;
}
if (currentSessionTargetMatches(parsed.to)) {
deliverLocalSubagentRelayMessage(options.sender, options.status, parsed.message);
if (options.acknowledge) emitResultDelivery(parsed.requestId, true);
return;
}
let activeClient: IntercomClient;
let target: string;
try {
activeClient = await ensureConnected("background");
target = await resolveSessionTarget(activeClient, parsed.to) ?? parsed.to;
} catch (error) {
if (!relayStillLive()) return;
recordSubagentDeliveryError(options.errorEntryType, parsed.to, parsed.message, error);
if (options.acknowledge) emitResultDelivery(parsed.requestId, false, error);
return;
}
if (!relayStillLive()) {
return;
}
if (currentSessionTargetMatches(parsed.to, target, activeClient)) {
deliverLocalSubagentRelayMessage(options.sender, options.status, parsed.message);
if (options.acknowledge) emitResultDelivery(parsed.requestId, true);
return;
}
try {
const result = await activeClient.send(target, { text: parsed.message });
if (!relayStillLive()) return;
if (!result.delivered) {
const error = new Error(result.reason ?? "Session may not exist or has disconnected.");
recordSubagentDeliveryError(options.errorEntryType, parsed.to, parsed.message, error);
if (options.acknowledge) emitResultDelivery(parsed.requestId, false, error);
return;
}
if (options.acknowledge) emitResultDelivery(parsed.requestId, true);
} catch (error) {
if (!relayStillLive()) return;
recordSubagentDeliveryError(options.errorEntryType, parsed.to, parsed.message, error);
if (options.acknowledge) emitResultDelivery(parsed.requestId, false, error);
}
})();
}
pi.events.on(SUBAGENT_CONTROL_INTERCOM_EVENT, (payload) => {
relaySubagentIntercomPayload(payload, {
sender: "subagent-control",
status: "needs_attention",
errorEntryType: "intercom_control_error",
});
});
pi.events.on(SUBAGENT_RESULT_INTERCOM_EVENT, (payload) => {
relaySubagentIntercomPayload(payload, {
sender: "subagent-result",
status: "result",
errorEntryType: "intercom_result_error",
acknowledge: true,
});
});
pi.on("session_start", (_event, ctx) => {
if (!config.enabled) {
return;
}
shuttingDown = false;
disposed = false;
runtimeStarted = true;
runtimeGeneration += 1;
reconnectAttempt = 0;
clearReconnectTimer();
clearStartupConnectTimer();
runtimeContext = ctx;
currentSessionId = ctx.sessionManager.getSessionId();
currentModel = ctx.model?.id ?? "unknown";
sessionStartedAt = Date.now();
agentRunning = false;
activeTools.clear();
const startupGeneration = runtimeGeneration;
startupConnectTimer = setTimeout(() => {
startupConnectTimer = null;
if (!getLiveContext(ctx, startupGeneration)) {
return;
}
void ensureConnected("startup").catch(() => {
if (!getLiveContext(ctx, startupGeneration)) {
return;
}
client = null;
scheduleReconnect();
});
}, 0);
});
pi.on("session_shutdown", async () => {
shuttingDown = true;
disposed = true;
runtimeGeneration += 1;
clearStartupConnectTimer();
clearReconnectTimer();
stopPresenceRenamePoller();