-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcontrol.ts
More file actions
1751 lines (1540 loc) · 53.4 KB
/
control.ts
File metadata and controls
1751 lines (1540 loc) · 53.4 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
/**
* Session Control Extension
*
* Enables inter-session communication via Unix domain sockets. When enabled with
* the `--session-control` flag, each pi session creates a control socket at
* `~/.pi/session-control/<session-id>.sock` that accepts JSON-RPC commands.
*
* Features:
* - Send messages to other running pi sessions (steer or follow-up mode)
* via tool (`send_to_session`) or startup CLI flags (`--control-session`, `--send-session-message`)
* - Retrieve the last assistant message from a session
* - Get AI-generated summaries of session activity
* - Clear/rewind sessions to their initial state
* - Subscribe to turn_end events for async coordination
*
* Once loaded the extension registers a `send_to_session` tool that allows the AI to
* communicate with other pi sessions programmatically.
*
* Usage:
* pi --session-control
*
* One-shot startup send:
* pi -p --session-control --control-session <session-name|session-id> --send-session-message <text>
* [--send-session-mode steer|follow_up] [--send-session-wait turn_end|message_processed]
* [--send-session-include-sender-info]
* (startup send is one-way by default; use --send-session-wait turn_end to capture response on stdout)
*
* Environment:
* Sets PI_SESSION_ID when enabled, allowing child processes to discover
* the current session.
*
* RPC Protocol:
* Commands are newline-delimited JSON objects with a `type` field:
* - { type: "send", message: "...", mode?: "steer"|"follow_up" }
* - { type: "get_message" }
* - { type: "get_summary" }
* - { type: "clear", summarize?: boolean }
* - { type: "abort" }
* - { type: "subscribe", event: "turn_end" }
*
* Responses are JSON objects with { type: "response", command, success, data?, error? }
* Events are JSON objects with { type: "event", event, data?, subscriptionId? }
*/
import type {
ExtensionAPI,
ExtensionContext,
TurnEndEvent,
MessageRenderer,
ModelRegistry,
} from "@mariozechner/pi-coding-agent";
import { getMarkdownTheme } from "@mariozechner/pi-coding-agent";
import { complete, type Model, type Api, type UserMessage, type TextContent } from "@mariozechner/pi-ai";
import { StringEnum } from "@mariozechner/pi-ai";
import { Box, Container, Markdown, Spacer, Text } from "@mariozechner/pi-tui";
import { Type } from "@sinclair/typebox";
import { promises as fs } from "node:fs";
import * as net from "node:net";
import * as os from "node:os";
import * as path from "node:path";
const CONTROL_FLAG = "session-control";
const CONTROL_TARGET_FLAG = "control-session";
const CONTROL_SEND_MESSAGE_FLAG = "send-session-message";
const CONTROL_SEND_MODE_FLAG = "send-session-mode";
const CONTROL_SEND_WAIT_FLAG = "send-session-wait";
const CONTROL_SEND_INCLUDE_SENDER_FLAG = "send-session-include-sender-info";
const CONTROL_DIR = path.join(os.homedir(), ".pi", "session-control");
const SOCKET_SUFFIX = ".sock";
const SESSION_MESSAGE_TYPE = "session-message";
const SENDER_INFO_PATTERN = /<sender_info>[\s\S]*?<\/sender_info>/g;
// ============================================================================
// RPC Types
// ============================================================================
interface RpcResponse {
type: "response";
command: string;
success: boolean;
error?: string;
data?: unknown;
id?: string;
}
interface RpcEvent {
type: "event";
event: string;
data?: unknown;
subscriptionId?: string;
}
// Unified command structure
interface RpcSendCommand {
type: "send";
message: string;
mode?: "steer" | "follow_up";
id?: string;
}
interface RpcGetMessageCommand {
type: "get_message";
id?: string;
}
interface RpcGetSummaryCommand {
type: "get_summary";
id?: string;
}
interface RpcClearCommand {
type: "clear";
summarize?: boolean;
id?: string;
}
interface RpcAbortCommand {
type: "abort";
id?: string;
}
interface RpcSubscribeCommand {
type: "subscribe";
event: "turn_end";
id?: string;
}
type RpcCommand =
| RpcSendCommand
| RpcGetMessageCommand
| RpcGetSummaryCommand
| RpcClearCommand
| RpcAbortCommand
| RpcSubscribeCommand;
// ============================================================================
// Subscription Management
// ============================================================================
interface TurnEndSubscription {
socket: net.Socket;
subscriptionId: string;
}
interface SocketState {
server: net.Server | null;
socketPath: string | null;
context: ExtensionContext | null;
alias: string | null;
aliasTimer: ReturnType<typeof setInterval> | null;
turnEndSubscriptions: TurnEndSubscription[];
}
// ============================================================================
// Summarization
// ============================================================================
const CODEX_MODEL_ID = "gpt-5.1-codex-mini";
const HAIKU_MODEL_ID = "claude-haiku-4-5";
const SUMMARIZATION_SYSTEM_PROMPT = `You are a conversation summarizer. Create concise, accurate summaries that preserve key information, decisions, and outcomes.`;
const TURN_SUMMARY_PROMPT = `Summarize what happened in this conversation since the last user prompt. Focus on:
- What was accomplished
- Any decisions made
- Files that were read, modified, or created
- Any errors or issues encountered
- Current state/next steps
Be concise but comprehensive. Preserve exact file paths, function names, and error messages.`;
async function selectSummarizationModel(
currentModel: Model<Api> | undefined,
modelRegistry: ModelRegistry,
): Promise<Model<Api> | undefined> {
const codexModel = modelRegistry.find("openai-codex", CODEX_MODEL_ID);
if (codexModel) {
const auth = await modelRegistry.getApiKeyAndHeaders(codexModel);
if (auth.ok) return codexModel;
}
const haikuModel = modelRegistry.find("anthropic", HAIKU_MODEL_ID);
if (haikuModel) {
const auth = await modelRegistry.getApiKeyAndHeaders(haikuModel);
if (auth.ok) return haikuModel;
}
return currentModel;
}
// ============================================================================
// Utilities
// ============================================================================
const STATUS_KEY = "session-control";
function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
return typeof error === "object" && error !== null && "code" in error;
}
function getSocketPath(sessionId: string): string {
return path.join(CONTROL_DIR, `${sessionId}${SOCKET_SUFFIX}`);
}
function isSafeSessionId(sessionId: string): boolean {
return !sessionId.includes("/") && !sessionId.includes("\\") && !sessionId.includes("..") && sessionId.length > 0;
}
function isSafeAlias(alias: string): boolean {
return !alias.includes("/") && !alias.includes("\\") && !alias.includes("..") && alias.length > 0;
}
function getAliasPath(alias: string): string {
return path.join(CONTROL_DIR, `${alias}.alias`);
}
function getSessionAlias(ctx: ExtensionContext): string | null {
const sessionName = ctx.sessionManager.getSessionName();
const alias = sessionName ? sessionName.trim() : "";
if (!alias || !isSafeAlias(alias)) return null;
return alias;
}
async function ensureControlDir(): Promise<void> {
await fs.mkdir(CONTROL_DIR, { recursive: true });
}
async function removeSocket(socketPath: string | null): Promise<void> {
if (!socketPath) return;
try {
await fs.unlink(socketPath);
} catch (error) {
if (isErrnoException(error) && error.code !== "ENOENT") {
throw error;
}
}
}
// TODO: add GC for stale sockets/aliases older than 7 days.
async function removeAliasesForSocket(socketPath: string | null): Promise<void> {
if (!socketPath) return;
try {
const entries = await fs.readdir(CONTROL_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isSymbolicLink()) continue;
const aliasPath = path.join(CONTROL_DIR, entry.name);
let target: string;
try {
target = await fs.readlink(aliasPath);
} catch {
continue;
}
const resolvedTarget = path.resolve(CONTROL_DIR, target);
if (resolvedTarget === socketPath) {
await fs.unlink(aliasPath);
}
}
} catch (error) {
if (isErrnoException(error) && error.code === "ENOENT") return;
throw error;
}
}
async function createAliasSymlink(sessionId: string, alias: string): Promise<void> {
if (!alias || !isSafeAlias(alias)) return;
const aliasPath = getAliasPath(alias);
const target = `${sessionId}${SOCKET_SUFFIX}`;
try {
await fs.unlink(aliasPath);
} catch (error) {
if (isErrnoException(error) && error.code !== "ENOENT") {
throw error;
}
}
try {
await fs.symlink(target, aliasPath);
} catch (error) {
if (isErrnoException(error) && error.code !== "EEXIST") {
throw error;
}
}
}
async function resolveSessionIdFromAlias(alias: string): Promise<string | null> {
if (!alias || !isSafeAlias(alias)) return null;
const aliasPath = getAliasPath(alias);
try {
const target = await fs.readlink(aliasPath);
const resolvedTarget = path.resolve(CONTROL_DIR, target);
const base = path.basename(resolvedTarget);
if (!base.endsWith(SOCKET_SUFFIX)) return null;
const sessionId = base.slice(0, -SOCKET_SUFFIX.length);
return isSafeSessionId(sessionId) ? sessionId : null;
} catch (error) {
if (isErrnoException(error) && error.code === "ENOENT") return null;
return null;
}
}
async function getAliasMap(): Promise<Map<string, string[]>> {
const aliasMap = new Map<string, string[]>();
const entries = await fs.readdir(CONTROL_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isSymbolicLink()) continue;
if (!entry.name.endsWith(".alias")) continue;
const aliasPath = path.join(CONTROL_DIR, entry.name);
let target: string;
try {
target = await fs.readlink(aliasPath);
} catch {
continue;
}
const resolvedTarget = path.resolve(CONTROL_DIR, target);
const aliases = aliasMap.get(resolvedTarget);
const aliasName = entry.name.slice(0, -".alias".length);
if (aliases) {
aliases.push(aliasName);
} else {
aliasMap.set(resolvedTarget, [aliasName]);
}
}
return aliasMap;
}
async function isSocketAlive(socketPath: string): Promise<boolean> {
return await new Promise((resolve) => {
const socket = net.createConnection(socketPath);
const timeout = setTimeout(() => {
socket.destroy();
resolve(false);
}, 300);
const cleanup = (alive: boolean) => {
clearTimeout(timeout);
socket.removeAllListeners();
resolve(alive);
};
socket.once("connect", () => {
socket.end();
cleanup(true);
});
socket.once("error", () => {
cleanup(false);
});
});
}
type LiveSessionInfo = {
sessionId: string;
name?: string;
aliases: string[];
socketPath: string;
};
async function getLiveSessions(): Promise<LiveSessionInfo[]> {
await ensureControlDir();
const entries = await fs.readdir(CONTROL_DIR, { withFileTypes: true });
const aliasMap = await getAliasMap();
const sessions: LiveSessionInfo[] = [];
for (const entry of entries) {
if (!entry.name.endsWith(SOCKET_SUFFIX)) continue;
const socketPath = path.join(CONTROL_DIR, entry.name);
const alive = await isSocketAlive(socketPath);
if (!alive) continue;
const sessionId = entry.name.slice(0, -SOCKET_SUFFIX.length);
if (!isSafeSessionId(sessionId)) continue;
const aliases = aliasMap.get(socketPath) ?? [];
const name = aliases[0];
sessions.push({ sessionId, name, aliases, socketPath });
}
sessions.sort((a, b) => (a.name ?? a.sessionId).localeCompare(b.name ?? b.sessionId));
return sessions;
}
async function syncAlias(state: SocketState, ctx: ExtensionContext): Promise<void> {
if (!state.server || !state.socketPath) return;
const alias = getSessionAlias(ctx);
if (alias && alias !== state.alias) {
await removeAliasesForSocket(state.socketPath);
await createAliasSymlink(ctx.sessionManager.getSessionId(), alias);
state.alias = alias;
return;
}
if (!alias && state.alias) {
await removeAliasesForSocket(state.socketPath);
state.alias = null;
}
}
function writeResponse(socket: net.Socket, response: RpcResponse): void {
try {
socket.write(`${JSON.stringify(response)}\n`);
} catch {
// Socket may be closed
}
}
function writeEvent(socket: net.Socket, event: RpcEvent): void {
try {
socket.write(`${JSON.stringify(event)}\n`);
} catch {
// Socket may be closed
}
}
function parseCommand(line: string): { command?: RpcCommand; error?: string } {
try {
const parsed = JSON.parse(line) as RpcCommand;
if (!parsed || typeof parsed !== "object") {
return { error: "Invalid command" };
}
if (typeof parsed.type !== "string") {
return { error: "Missing command type" };
}
return { command: parsed };
} catch (error) {
return { error: error instanceof Error ? error.message : "Failed to parse command" };
}
}
// ============================================================================
// Message Extraction
// ============================================================================
interface ExtractedMessage {
role: "user" | "assistant";
content: string;
timestamp: number;
}
function getLastAssistantMessage(ctx: ExtensionContext): ExtractedMessage | undefined {
const branch = ctx.sessionManager.getBranch();
for (let i = branch.length - 1; i >= 0; i--) {
const entry = branch[i];
if (entry.type === "message") {
const msg = entry.message;
if ("role" in msg && msg.role === "assistant") {
const textParts = msg.content
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text);
if (textParts.length > 0) {
return {
role: "assistant",
content: textParts.join("\n"),
timestamp: msg.timestamp,
};
}
}
}
}
return undefined;
}
function getMessagesSinceLastPrompt(ctx: ExtensionContext): ExtractedMessage[] {
const branch = ctx.sessionManager.getBranch();
const messages: ExtractedMessage[] = [];
let lastUserIndex = -1;
for (let i = branch.length - 1; i >= 0; i--) {
const entry = branch[i];
if (entry.type === "message" && "role" in entry.message && entry.message.role === "user") {
lastUserIndex = i;
break;
}
}
if (lastUserIndex === -1) return [];
for (let i = lastUserIndex; i < branch.length; i++) {
const entry = branch[i];
if (entry.type === "message") {
const msg = entry.message;
if ("role" in msg && (msg.role === "user" || msg.role === "assistant")) {
const textParts = msg.content
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text);
if (textParts.length > 0) {
messages.push({
role: msg.role,
content: textParts.join("\n"),
timestamp: msg.timestamp,
});
}
}
}
}
return messages;
}
function getFirstEntryId(ctx: ExtensionContext): string | undefined {
const entries = ctx.sessionManager.getEntries();
if (entries.length === 0) return undefined;
const root = entries.find((e) => e.parentId === null);
return root?.id ?? entries[0]?.id;
}
function extractTextContent(content: string | Array<TextContent | { type: string }>): string {
if (typeof content === "string") return content;
return content
.filter((c): c is TextContent => c.type === "text")
.map((c) => c.text)
.join("\n");
}
function stripSenderInfo(text: string): string {
return text.replace(SENDER_INFO_PATTERN, "").trim();
}
interface SenderInfo {
sessionId?: string;
sessionName?: string;
}
function parseSenderInfo(text: string): SenderInfo | null {
const match = text.match(/<sender_info>([\s\S]*?)<\/sender_info>/);
if (!match) return null;
const raw = match[1].trim();
if (!raw) return null;
if (raw.startsWith("{")) {
try {
const parsed = JSON.parse(raw) as { sessionId?: unknown; sessionName?: unknown };
const sessionId = typeof parsed.sessionId === "string" ? parsed.sessionId.trim() : "";
const sessionName = typeof parsed.sessionName === "string" ? parsed.sessionName.trim() : "";
if (sessionId || sessionName) {
return {
sessionId: sessionId || undefined,
sessionName: sessionName || undefined,
};
}
} catch {
// Ignore JSON parse errors, fall back to legacy parsing.
}
}
const legacyIdMatch = raw.match(/session\s+([a-f0-9-]{6,})/i);
if (legacyIdMatch) {
return { sessionId: legacyIdMatch[1] };
}
return null;
}
function formatSenderInfo(info: SenderInfo | null): string | null {
if (!info) return null;
const { sessionName, sessionId } = info;
if (sessionName && sessionId) return `${sessionName} (${sessionId})`;
if (sessionName) return sessionName;
if (sessionId) return sessionId;
return null;
}
const renderSessionMessage: MessageRenderer = (message, { expanded }, theme) => {
const rawContent = extractTextContent(message.content);
const senderInfo = parseSenderInfo(rawContent);
let text = stripSenderInfo(rawContent);
if (!text) text = "(no content)";
if (!expanded) {
const lines = text.split("\n");
if (lines.length > 5) {
text = `${lines.slice(0, 5).join("\n")}\n...`;
}
}
const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
const labelBase = theme.fg("customMessageLabel", `\x1b[1m[${message.customType}]\x1b[22m`);
const senderText = formatSenderInfo(senderInfo);
const label = senderText ? `${labelBase} ${theme.fg("dim", `from ${senderText}`)}` : labelBase;
box.addChild(new Text(label, 0, 0));
box.addChild(new Spacer(1));
box.addChild(
new Markdown(text, 0, 0, getMarkdownTheme(), {
color: (value: string) => theme.fg("customMessageText", value),
}),
);
return box;
};
// ============================================================================
// Command Handlers
// ============================================================================
async function handleCommand(
pi: ExtensionAPI,
state: SocketState,
command: RpcCommand,
socket: net.Socket,
): Promise<void> {
const id = "id" in command && typeof command.id === "string" ? command.id : undefined;
const respond = (success: boolean, commandName: string, data?: unknown, error?: string) => {
if (state.context) {
void syncAlias(state, state.context);
}
writeResponse(socket, { type: "response", command: commandName, success, data, error, id });
};
const ctx = state.context;
if (!ctx) {
respond(false, command.type, undefined, "Session not ready");
return;
}
void syncAlias(state, ctx);
// Abort
if (command.type === "abort") {
ctx.abort();
respond(true, "abort");
return;
}
// Subscribe to turn_end
if (command.type === "subscribe") {
if (command.event === "turn_end") {
const subscriptionId = id ?? `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
state.turnEndSubscriptions.push({ socket, subscriptionId });
const cleanup = () => {
const idx = state.turnEndSubscriptions.findIndex((s) => s.subscriptionId === subscriptionId);
if (idx !== -1) state.turnEndSubscriptions.splice(idx, 1);
};
socket.once("close", cleanup);
socket.once("error", cleanup);
respond(true, "subscribe", { subscriptionId, event: "turn_end" });
return;
}
respond(false, "subscribe", undefined, `Unknown event type: ${command.event}`);
return;
}
// Get last message
if (command.type === "get_message") {
const message = getLastAssistantMessage(ctx);
if (!message) {
respond(true, "get_message", { message: null });
return;
}
respond(true, "get_message", { message });
return;
}
// Get summary
if (command.type === "get_summary") {
const messages = getMessagesSinceLastPrompt(ctx);
if (messages.length === 0) {
respond(false, "get_summary", undefined, "No messages to summarize");
return;
}
const model = await selectSummarizationModel(ctx.model, ctx.modelRegistry);
if (!model) {
respond(false, "get_summary", undefined, "No model available for summarization");
return;
}
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
if (!auth.ok) {
respond(false, "get_summary", undefined, auth.error);
return;
}
try {
const conversationText = messages
.map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
.join("\n\n");
const userMessage: UserMessage = {
role: "user",
content: [{ type: "text", text: `<conversation>\n${conversationText}\n</conversation>\n\n${TURN_SUMMARY_PROMPT}` }],
timestamp: Date.now(),
};
const response = await complete(
model,
{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: [userMessage] },
{ apiKey: auth.apiKey, headers: auth.headers },
);
if (response.stopReason === "aborted" || response.stopReason === "error") {
respond(false, "get_summary", undefined, "Summarization failed");
return;
}
const summary = response.content
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text)
.join("\n");
respond(true, "get_summary", { summary, model: model.id });
} catch (error) {
respond(false, "get_summary", undefined, error instanceof Error ? error.message : "Summarization failed");
}
return;
}
// Clear session
if (command.type === "clear") {
if (!ctx.isIdle()) {
respond(false, "clear", undefined, "Session is busy - wait for turn to complete");
return;
}
const firstEntryId = getFirstEntryId(ctx);
if (!firstEntryId) {
respond(false, "clear", undefined, "No entries in session");
return;
}
const currentLeafId = ctx.sessionManager.getLeafId();
if (currentLeafId === firstEntryId) {
respond(true, "clear", { cleared: true, alreadyAtRoot: true });
return;
}
if (command.summarize) {
// Summarization requires navigateTree which we don't have direct access to
// Return an error for now - the caller should clear without summarize
// or use a different approach
respond(false, "clear", undefined, "Clear with summarization not supported via RPC - use summarize=false");
return;
}
// Access internal session manager to rewind (type assertion to access non-readonly methods)
try {
const sessionManager = ctx.sessionManager as unknown as { rewindTo(id: string): void };
sessionManager.rewindTo(firstEntryId);
respond(true, "clear", { cleared: true, targetId: firstEntryId });
} catch (error) {
respond(false, "clear", undefined, error instanceof Error ? error.message : "Clear failed");
}
return;
}
// Send message
if (command.type === "send") {
const message = command.message;
if (typeof message !== "string" || message.trim().length === 0) {
respond(false, "send", undefined, "Missing message");
return;
}
const mode = command.mode ?? "steer";
const isIdle = ctx.isIdle();
const customMessage = {
customType: SESSION_MESSAGE_TYPE,
content: message,
display: true,
};
if (isIdle) {
pi.sendMessage(customMessage, { triggerTurn: true });
} else {
pi.sendMessage(customMessage, {
triggerTurn: true,
deliverAs: mode === "follow_up" ? "followUp" : "steer",
});
}
respond(true, "send", { delivered: true, mode: isIdle ? "direct" : mode });
return;
}
respond(false, command.type, undefined, `Unsupported command: ${command.type}`);
}
// ============================================================================
// Server Management
// ============================================================================
async function createServer(pi: ExtensionAPI, state: SocketState, socketPath: string): Promise<net.Server> {
const server = net.createServer((socket) => {
socket.setEncoding("utf8");
let buffer = "";
socket.on("data", (chunk) => {
buffer += chunk;
let newlineIndex = buffer.indexOf("\n");
while (newlineIndex !== -1) {
const line = buffer.slice(0, newlineIndex).trim();
buffer = buffer.slice(newlineIndex + 1);
newlineIndex = buffer.indexOf("\n");
if (!line) continue;
const parsed = parseCommand(line);
if (parsed.error) {
if (state.context) {
void syncAlias(state, state.context);
}
writeResponse(socket, {
type: "response",
command: "parse",
success: false,
error: `Failed to parse command: ${parsed.error}`,
});
continue;
}
handleCommand(pi, state, parsed.command!, socket);
}
});
});
// Wait for server to start listening, with error handling
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, () => {
server.removeListener("error", reject);
resolve();
});
});
return server;
}
interface RpcClientOptions {
timeout?: number;
waitForEvent?: "turn_end";
}
async function sendRpcCommand(
socketPath: string,
command: RpcCommand,
options: RpcClientOptions = {},
): Promise<{ response: RpcResponse; event?: { message?: ExtractedMessage; turnIndex?: number } }> {
const { timeout = 5000, waitForEvent } = options;
return new Promise((resolve, reject) => {
const socket = net.createConnection(socketPath);
socket.setEncoding("utf8");
const timeoutHandle = setTimeout(() => {
socket.destroy(new Error("timeout"));
}, timeout);
let buffer = "";
let response: RpcResponse | null = null;
const cleanup = () => {
clearTimeout(timeoutHandle);
socket.removeAllListeners();
};
socket.on("connect", () => {
socket.write(`${JSON.stringify(command)}\n`);
// If waiting for turn_end, also subscribe
if (waitForEvent === "turn_end") {
const subscribeCmd: RpcSubscribeCommand = { type: "subscribe", event: "turn_end" };
socket.write(`${JSON.stringify(subscribeCmd)}\n`);
}
});
socket.on("data", (chunk) => {
buffer += chunk;
let newlineIndex = buffer.indexOf("\n");
while (newlineIndex !== -1) {
const line = buffer.slice(0, newlineIndex).trim();
buffer = buffer.slice(newlineIndex + 1);
newlineIndex = buffer.indexOf("\n");
if (!line) continue;
try {
const msg = JSON.parse(line);
// Handle response
if (msg.type === "response") {
if (msg.command === command.type) {
response = msg;
// If not waiting for event, we're done
if (!waitForEvent) {
cleanup();
socket.end();
resolve({ response });
return;
}
}
// Ignore subscribe response
continue;
}
// Handle turn_end event
if (msg.type === "event" && msg.event === "turn_end" && waitForEvent === "turn_end") {
cleanup();
socket.end();
if (!response) {
reject(new Error("Received event before response"));
return;
}
resolve({ response, event: msg.data || {} });
return;
}
} catch {
// Ignore parse errors, keep waiting
}
}
});
socket.on("error", (error) => {
cleanup();
reject(error);
});
});
}
async function startControlServer(pi: ExtensionAPI, state: SocketState, ctx: ExtensionContext): Promise<void> {
await ensureControlDir();
const sessionId = ctx.sessionManager.getSessionId();
const socketPath = getSocketPath(sessionId);
if (state.socketPath === socketPath && state.server) {
state.context = ctx;
await syncAlias(state, ctx);
return;
}
await stopControlServer(state);
await removeSocket(socketPath);
state.context = ctx;
state.socketPath = socketPath;
state.server = await createServer(pi, state, socketPath);
state.alias = null;
await syncAlias(state, ctx);
}
async function stopControlServer(state: SocketState): Promise<void> {
if (!state.server) {
await removeAliasesForSocket(state.socketPath);
await removeSocket(state.socketPath);
state.socketPath = null;
state.alias = null;
return;
}
const socketPath = state.socketPath;
state.socketPath = null;
state.turnEndSubscriptions = [];
await new Promise<void>((resolve) => state.server?.close(() => resolve()));
state.server = null;
await removeAliasesForSocket(socketPath);
await removeSocket(socketPath);
state.alias = null;
}
function updateStatus(ctx: ExtensionContext | null, enabled: boolean): void {
if (!ctx?.hasUI) return;
if (!enabled) {
ctx.ui.setStatus(STATUS_KEY, undefined);
return;
}
const sessionId = ctx.sessionManager.getSessionId();
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme.fg("dim", `session ${sessionId}`));
}
function updateSessionEnv(ctx: ExtensionContext | null, enabled: boolean): void {
if (!enabled) {
delete process.env.PI_SESSION_ID;
return;
}
if (!ctx) return;
process.env.PI_SESSION_ID = ctx.sessionManager.getSessionId();
}
// Extension factories run before extension flag values are hydrated into runtime.flagValues,
// so we inspect argv directly when deciding whether to register tools at load time.
function wasBooleanFlagPassed(flagName: string): boolean {
const flag = `--${flagName}`;
return process.argv.slice(2).includes(flag);
}
function shouldRegisterControlTools(pi: ExtensionAPI): boolean {
return pi.getFlag(CONTROL_FLAG) === true || wasBooleanFlagPassed(CONTROL_FLAG);
}
// ============================================================================
// Extension Export
// ============================================================================
export default function (pi: ExtensionAPI) {
pi.registerFlag(CONTROL_FLAG, {
description: "Enable per-session control socket under ~/.pi/session-control",
type: "boolean",
});
pi.registerFlag(CONTROL_TARGET_FLAG, {
description: "Target session name or session id for startup control send",
type: "string",
});
pi.registerFlag(CONTROL_SEND_MESSAGE_FLAG, {
description: "Message to send to --control-session at startup",
type: "string",
});
pi.registerFlag(CONTROL_SEND_MODE_FLAG, {
description: "Startup send mode: steer or follow_up",
type: "string",