@devries-cameron20 / t3code-1 / commits / 947916887c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(pi): import terminal Pi sessions during setup (#27515)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: GPT 6.1 Sol <codex@openai.com>

Wout Stiens committed Oct 30, 2026 at 17:10 UTC 947916887cce53e5f4b4aa77725315fa6c382635
8 files changed +393 -87
apps/server/src/project/AgentSessionImporter.test.ts
+31 -17
@@ -1,5 +1,6 @@
1 import { expect, it } from "@effect/vitest";
2 import {
3 + type AgentSessionSource,
4 EventId,
5 ProjectId,
6 ProviderDriverKind,
@@ -50,7 +51,7 @@ const persistence = Layer.mergeAll(
51 function candidate(
52 modelSelection: typeof CODEX_MODEL_SELECTION,
53 providerSessionId: string,
53 - provider: "codex" | "claudeAgent" = "codex",
54 + provider: AgentSessionSource = "codex",
55 ) {
56 const providerInstanceId = modelSelection.instanceId;
57 return {
@@ -82,6 +83,12 @@ function candidate(
83 } satisfies AgentSessionScanner.AgentSessionRecentThread;
84 }
85
86 +const PI_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("pi"), model: "default" };
87 +
88 +// Pi threads are owned by their session file path, not the session UUID.
89 +const nativeId = ({ source }: ReturnType<typeof candidate>) =>
90 + source.provider === "pi" ? source.filePath : source.providerSessionId;
91 +
92 function importId(source: ReturnType<typeof candidate>) {
93 return ThreadId.make(
94 `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`,
@@ -95,19 +102,17 @@ const seedOwner = Effect.fn(function* (
102 const sink = yield* EventSink.EventSinkV2;
103 const ids = yield* IdAllocator.IdAllocatorV2;
104 const { providerInstanceId, providerSessionId, provider } = source.source;
105 + const nativeThreadId = nativeId(source);
106 const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`);
107 const driver = ProviderDriverKind.make(provider);
108 const providerThread: OrchestrationV2ProviderThread = {
101 - id: ids.derive.providerThread({
102 - driver,
103 - nativeThreadId: providerSessionId,
104 - }),
109 + id: ids.derive.providerThread({ driver, nativeThreadId }),
110 driver,
111 providerInstanceId,
112 providerSessionId: null,
113 appThreadId: threadId,
114 ownerNodeId: null,
110 - nativeThreadRef: { driver, nativeId: providerSessionId, strength: "strong" },
115 + nativeThreadRef: { driver, nativeId: nativeThreadId, strength: "strong" },
116 nativeConversationHeadRef: null,
117 status: "idle",
118 firstRunOrdinal: 1,
@@ -252,10 +257,12 @@ it.effect(
257 "claudeAgent",
258 );
259 const deleted = candidate(CODEX_MODEL_SELECTION, "deleted");
260 + const ownedPi = candidate(PI_MODEL_SELECTION, "owned-pi", "pi");
261 const owners = [
262 yield* seedOwner(active),
263 yield* seedOwner(archived, "archived"),
264 yield* seedOwner(deleted, "deleted"),
265 + yield* seedOwner(ownedPi),
266 ];
267 const before = yield* Effect.forEach(owners, (id) =>
268 projections.getThreadRecords(id, ["providerThreads"]),
@@ -266,10 +273,19 @@ it.effect(
273 "claudeAgent",
274 );
275 const unowned = candidate(CODEX_MODEL_SELECTION, "unowned");
269 - const importer = yield* makeImporter([active, archived, deleted, otherInstance, unowned]);
276 + const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi");
277 + const importer = yield* makeImporter([
278 + active,
279 + archived,
280 + deleted,
281 + ownedPi,
282 + otherInstance,
283 + unowned,
284 + unownedPi,
285 + ]);
286
271 - expect(yield* importer.run).toEqual({ importedCount: 2, skippedCount: 0 });
272 - for (const source of [active, archived, deleted]) {
287 + expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 });
288 + for (const source of [active, archived, deleted, ownedPi]) {
289 const threadId = importId(source);
290 expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
291 expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]);
@@ -286,8 +302,8 @@ it.effect(
302 "event" in stored ? [stored.event.threadId] : [],
303 ),
304 ),
289 - ).toEqual(new Set([importId(otherInstance), importId(unowned)]));
290 - for (const source of [otherInstance, unowned]) {
305 + ).toEqual(new Set([importId(otherInstance), importId(unowned), importId(unownedPi)]));
306 + for (const source of [otherInstance, unowned, unownedPi]) {
307 const threadId = importId(source);
308 const records = yield* projections.getThreadRecords(threadId, [
309 "messages",
@@ -296,15 +312,13 @@ it.effect(
312 expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]);
313 expect(records.thread.historyOrigin).toBe("v1_import");
314 expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
299 - expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(
300 - source.source.providerSessionId,
301 - );
315 + expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source));
316 expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
317 providerInstanceId: source.source.providerInstanceId,
318 resumeCursor:
305 - source.source.provider === "codex"
306 - ? { threadId: source.source.providerSessionId }
307 - : { threadId, resume: source.source.providerSessionId },
319 + source.source.provider === "claudeAgent"
320 + ? { threadId, resume: source.source.providerSessionId }
321 + : { threadId: nativeId(source) },
322 runtimePayload: { importedTranscripts: [source.source] },
323 });
324 }
apps/server/src/project/AgentSessionImporter.ts
+8 -5
@@ -250,6 +250,9 @@ const make = Effect.gen(function* () {
250 });
251 }
252 const driver = ProviderDriverKind.make(thread.source);
253 + // Pi resumes by session file path; its session UUID only names the thread.
254 + const nativeThreadId =
255 + thread.source === "pi" ? source.filePath : thread.providerSessionId;
256 const persistRuntime = runtimes.upsert(
257 {
258 threadId,
@@ -260,9 +263,9 @@ const make = Effect.gen(function* () {
263 status: "stopped",
264 lastSeenAt: thread.updatedAt,
265 resumeCursor:
263 - thread.source === "codex"
264 - ? { threadId: thread.providerSessionId }
265 - : { threadId, resume: thread.providerSessionId },
266 + thread.source === "claudeAgent"
267 + ? { threadId, resume: thread.providerSessionId }
268 + : { threadId: nativeThreadId },
269 runtimePayload: { cwd: project.workspaceRoot },
270 },
271 { onConflict: "ignore" },
@@ -288,7 +291,7 @@ const make = Effect.gen(function* () {
291 const providerThreadId = idAllocator.derive.providerThread({
292 driver,
293 providerInstanceId: thread.providerInstanceId,
291 - nativeThreadId: thread.providerSessionId,
294 + nativeThreadId,
295 });
296 const createdAt = dateTime(thread.createdAt);
297 const updatedAt = dateTime(thread.updatedAt);
@@ -337,7 +340,7 @@ const make = Effect.gen(function* () {
340 ownerNodeId: null,
341 nativeThreadRef: {
342 driver,
340 - nativeId: thread.providerSessionId,
343 + nativeId: nativeThreadId,
344 strength: "strong",
345 },
346 nativeConversationHeadRef: null,
apps/server/src/project/AgentSessionScanner.test.ts
+138 -5
@@ -46,6 +46,7 @@ const layerProjectStore = (importedWorkspaceRoots: ReadonlyArray<string>) =>
46 interface ScannerTestInput {
47 readonly claudeHomePath: string;
48 readonly codexHomePath: string;
49 + readonly piAgentDir?: string;
50 readonly importedWorkspaceRoots?: ReadonlyArray<string>;
51 readonly configBaseDir?: string;
52 readonly providerInstances?: ContractServerSettings["providerInstances"];
@@ -65,6 +66,20 @@ const layerScannerTest = (input: ScannerTestInput) =>
66 driver: ProviderDriverKind.make("codex"),
67 config: { homePath: input.codexHomePath },
68 },
69 + // Keeps the default Pi instance off the developer's real ~/.pi.
70 + [ProviderInstanceId.make("pi")]: {
71 + driver: ProviderDriverKind.make("pi"),
72 + enabled: true,
73 + environment: [
74 + {
75 + name: "PI_CODING_AGENT_DIR",
76 + value: input.piAgentDir ?? `${input.claudeHomePath}/pi-agent`,
77 + sensitive: false,
78 + },
79 + { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false },
80 + ],
81 + config: {},
82 + },
83 ...input.providerInstances,
84 },
85 }),
@@ -561,9 +576,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
576 const codexHomePath = yield* makeTempDir("t3code-codex-legacy-");
577 const claudeEnvironmentHome = yield* makeTempDir("t3code-claude-env-");
578 const codexEnvironmentHome = yield* makeTempDir("t3code-codex-env-");
579 + const piAgentDir = yield* makeTempDir("t3code-pi-agent-");
580 + const piSessionDir = yield* makeTempDir("t3code-pi-sessions-");
581 const claudeWorkspace = yield* makeTempDir("t3code-workspace-claude-");
582 const codexWorkspace = yield* makeTempDir("t3code-workspace-codex-");
566 -
583 + const piWorkspace = yield* makeTempDir("t3code-workspace-pi-");
584 + const piFlatWorkspace = yield* makeTempDir("t3code-workspace-pi-flat-");
585 +
586 + // Pi nests sessions per cwd by default and keeps a custom session directory flat.
587 + for (const [filePath, cwd, mtime] of [
588 + [
589 + path.join(piAgentDir, "sessions", "--slug--", "2026-01-03_pi.jsonl"),
590 + piWorkspace,
591 + "2026-01-03T00:00:00.000Z",
592 + ],
593 + [
594 + path.join(piSessionDir, "2026-01-04_pi-flat.jsonl"),
595 + piFlatWorkspace,
596 + "2026-01-04T00:00:00.000Z",
597 + ],
598 + ] as const) {
599 + yield* writeTranscript({
600 + filePath,
601 + contents: `${encodeTranscriptRecord({ type: "session", version: 3, id: "pi", cwd })}\n`,
602 + mtimeMs: Date.parse(mtime),
603 + });
604 + }
605 yield* writeTranscript({
606 filePath: path.join(claudeEnvironmentHome, "projects", "-actual", "session.jsonl"),
607 contents: claudeSessionLine(claudeWorkspace),
@@ -598,12 +636,31 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
636 environment: [{ name: "CODEX_HOME", value: codexEnvironmentHome, sensitive: false }],
637 config: {},
638 },
639 + [ProviderInstanceId.make("pi")]: {
640 + driver: ProviderDriverKind.make("pi"),
641 + enabled: true,
642 + environment: [
643 + { name: "PI_CODING_AGENT_DIR", value: piAgentDir, sensitive: false },
644 + { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false },
645 + ],
646 + config: {},
647 + },
648 + [ProviderInstanceId.make("pi-flat")]: {
649 + driver: ProviderDriverKind.make("pi"),
650 + enabled: true,
651 + environment: [
652 + { name: "PI_CODING_AGENT_SESSION_DIR", value: piSessionDir, sensitive: false },
653 + ],
654 + config: {},
655 + },
656 },
657 });
658
604 - expect(result.candidates.map((candidate) => candidate.path)).toEqual([
605 - codexWorkspace,
606 - claudeWorkspace,
659 + expect(result.candidates.map((candidate) => [candidate.path, candidate.sources])).toEqual([
660 + [piFlatWorkspace, ["pi"]],
661 + [piWorkspace, ["pi"]],
662 + [codexWorkspace, ["codex"]],
663 + [claudeWorkspace, ["claudeAgent"]],
664 ]);
665 }),
666 );
@@ -983,13 +1040,14 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
1040 });
1041
1042 describe("recentThreads", () => {
986 - it.effect("imports recent Claude and Codex sessions for the selected project only", () =>
1043 + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () =>
1044 Effect.gen(function* () {
1045 const path = yield* Path.Path;
1046 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1047 yield* TestClock.setTime(nowMs);
1048 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1049 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1050 + const piAgentDir = yield* makeTempDir("t3code-pi-agent-");
1051 const workspace = yield* makeTempDir("t3code-workspace-");
1052 const otherWorkspace = yield* makeTempDir("t3code-workspace-other-");
1053
@@ -1053,21 +1111,96 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
1111 ].join("\n"),
1112 mtimeMs: nowMs - 60 * 60 * 1000,
1113 });
1114 + const piMessage = (
1115 + id: string,
1116 + parentId: string | null,
1117 + message: { readonly role: string; readonly content: unknown },
1118 + ) =>
1119 + encodeTranscriptRecord({
1120 + type: "message",
1121 + id,
1122 + parentId,
1123 + timestamp: "2026-08-24T11:00:00.000Z",
1124 + message,
1125 + });
1126 + // The user rewound to the first prompt; the abandoned branch stays in the file.
1127 + yield* writeTranscript({
1128 + filePath: path.join(piAgentDir, "sessions", "--selected--", "2026-08-24_pi.jsonl"),
1129 + contents: [
1130 + encodeTranscriptRecord({
1131 + type: "session",
1132 + version: 3,
1133 + id: "pi-recent",
1134 + cwd: workspace,
1135 + }),
1136 + piMessage("a1", null, { role: "user", content: "Plan the change" }),
1137 + piMessage("a2", "a1", {
1138 + role: "assistant",
1139 + content: [{ type: "text", text: "Abandoned answer" }],
1140 + }),
1141 + piMessage("a3", "a2", { role: "user", content: "Abandoned follow-up" }),
1142 + piMessage("b1", "a1", {
1143 + role: "assistant",
1144 + content: [
1145 + { type: "thinking", thinking: "Hidden reasoning" },
1146 + { type: "toolCall", id: "call-1", name: "bash", arguments: {} },
1147 + ],
1148 + }),
1149 + piMessage("bn", "b1", { role: "toolResult", content: null }),
1150 + piMessage("b2", "bn", {
1151 + role: "toolResult",
1152 + content: [{ type: "text", text: "Tool output" }],
1153 + }),
1154 + piMessage("b3", "b2", {
1155 + role: "assistant",
1156 + content: [{ type: "text", text: "Active answer" }],
1157 + }),
1158 + encodeTranscriptRecord({
1159 + type: "session_info",
1160 + id: "b4",
1161 + parentId: "b3",
1162 + name: "Pi refactor",
1163 + }),
1164 + ].join("\n"),
1165 + mtimeMs: nowMs - 30 * 60 * 1000,
1166 + });
1167 + // Version 1 sessions predate the entry tree.
1168 + yield* writeTranscript({
1169 + filePath: path.join(piAgentDir, "sessions", "--selected--", "2025-01-01_pi-v1.jsonl"),
1170 + contents: [
1171 + encodeTranscriptRecord({ type: "session", id: "pi-v1", cwd: workspace }),
1172 + encodeTranscriptRecord({
1173 + type: "message",
1174 + message: { role: "user", content: "Legacy prompt" },
1175 + }),
1176 + encodeTranscriptRecord({
1177 + type: "message",
1178 + message: { role: "assistant", content: [{ type: "text", text: "Legacy answer" }] },
1179 + }),
1180 + ].join("\n"),
1181 + mtimeMs: nowMs - 2 * 24 * 60 * 60 * 1000,
1182 + });
1183
1184 const threads = yield* runRecentThreads({
1185 claudeHomePath,
1186 codexHomePath,
1187 + piAgentDir,
1188 workspaceRoot: workspace,
1189 });
1190
1191 expect(threads.map((thread) => thread.providerSessionId)).toEqual([
1192 + "pi-recent",
1193 "codex-recent",
1194 "claude-recent",
1195 + "pi-v1",
1196 ]);
1197 expect(threads.map((thread) => thread.messages.map((message) => message.text))).toEqual([
1198 + ["Plan the change", "Active answer"],
1199 ["Review this code", "Looks good"],
1200 ["Fix the project", "Done"],
1201 + ["Legacy prompt", "Legacy answer"],
1202 ]);
1203 + expect(threads[0]).toMatchObject({ source: "pi", title: "Pi refactor" });
1204 }),
1205 );
1206
apps/server/src/project/AgentSessionScanner.ts
+170 -21
@@ -32,7 +32,9 @@ import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server
32 import * as ServerConfig from "../config.ts";
33 import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
34 import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
35 +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
36 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
37 +import { resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage";
38 import * as ServerSettings from "../serverSettings.ts";
39 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
40 import {
@@ -78,6 +80,10 @@ const CodexTurnMetadata = Schema.Struct({
80
81 const TranscriptRecord = Schema.Struct({
82 type: Schema.optional(Schema.String),
83 + // Pi entries form a tree through id/parentId; session_info entries carry its name.
84 + id: Schema.optional(Schema.String),
85 + parentId: Schema.optional(Schema.NullOr(Schema.String)),
86 + name: Schema.optional(Schema.String),
87 timestamp: Schema.optional(Schema.String),
88 cwd: Schema.optional(Schema.String),
89 sessionId: Schema.optional(Schema.String),
@@ -106,6 +112,13 @@ const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
112 const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
113 const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord));
114 const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord);
115 +const decodePiEntryLinks = Schema.decodeUnknownOption(
116 + Schema.Struct({
117 + type: TranscriptRecord.fields.type,
118 + id: TranscriptRecord.fields.id,
119 + parentId: TranscriptRecord.fields.parentId,
120 + }),
121 +);
122 const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord);
123 const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata);
124
@@ -287,6 +300,39 @@ function deriveTitle(source: AgentSessionSource, text: string): string | undefin
300 return request.trim().split("\n")[0]?.slice(0, 100).trim() || undefined;
301 }
302
303 +// Pi keeps abandoned branches in the file; its active branch runs from the last entry to the root.
304 +function activePiBranch(
305 + records: ReadonlyArray<DecodedTranscriptRecord>,
306 +): ReadonlyArray<DecodedTranscriptRecord> {
307 + const entries = records.filter((record) => record.type !== "session");
308 + const leaf = entries.at(-1);
309 + // Version 1 sessions predate the tree and are linear.
310 + if (leaf?.id === undefined) return entries;
311 + const byId = new Map(
312 + entries.flatMap((entry) => (entry.id === undefined ? [] : [[entry.id, entry] as const])),
313 + );
314 + const branch: Array<DecodedTranscriptRecord> = [];
315 + for (
316 + let entry: DecodedTranscriptRecord | undefined = leaf;
317 + entry !== undefined && branch.length < entries.length;
318 + entry = entry.parentId ? byId.get(entry.parentId) : undefined
319 + ) {
320 + branch.push(entry);
321 + }
322 + return branch.toReversed();
323 +}
324 +
325 +function isPiConversationRecord(
326 + record: DecodedTranscriptRecord,
327 +): record is DecodedTranscriptRecord & {
328 + readonly message: typeof TranscriptMessage.Type & { readonly role: "user" | "assistant" };
329 +} {
330 + return (
331 + record.type === "message" &&
332 + (record.message?.role === "user" || record.message?.role === "assistant")
333 + );
334 +}
335 +
336 export function parseAgentSessionTranscript(
337 input: AgentSessionTranscriptMetadata & {
338 readonly contents: string;
@@ -311,8 +357,16 @@ function parseAgentSessionRecords(
357 // Claude filenames are session IDs. Codex rollout filenames include extra
358 // timestamp text, so only transcript metadata can provide a resumable ID.
359 let providerSessionId =
314 - input.source === "codex" ? "" : (claudeFields.sessionId ?? input.fallbackSessionId);
315 - const title = claudeFields.title ?? null;
360 + input.source === "codex"
361 + ? ""
362 + : input.source === "pi"
363 + ? records.find((record) => record.type === "session")?.id?.trim() || input.fallbackSessionId
364 + : (claudeFields.sessionId ?? input.fallbackSessionId);
365 + // Pi titles a session by its latest session_info on any branch; an empty name clears it.
366 + const title =
367 + input.source === "pi"
368 + ? records.findLast((record) => record.type === "session_info")?.name?.trim() || null
369 + : (claudeFields.title ?? null);
370 let model = claudeFields.model ?? null;
371 let derivedTitle: string | undefined;
372 let hasCodexSessionId = false;
@@ -403,8 +457,20 @@ function parseAgentSessionRecords(
457 };
458
459 let recordIndex = -1;
406 - for (const record of records) {
460 + for (const record of input.source === "pi" ? activePiBranch(records) : records) {
461 recordIndex += 1;
462 + if (input.source === "pi") {
463 + if (!isPiConversationRecord(record)) continue;
464 + const text = extractText(record.message.content);
465 + if (text.length === 0) continue;
466 + retainMessage({
467 + role: record.message.role,
468 + text,
469 + createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
470 + codexResponseUser: false,
471 + });
472 + continue;
473 + }
474 if (input.source === "claudeAgent") {
475 if (isHiddenClaudeRecord(record)) continue;
476 if (record.type !== "user" && record.type !== "assistant") continue;
@@ -507,6 +573,8 @@ function shouldRetainDecodedRecord(
573 source: AgentSessionSource,
574 record: DecodedTranscriptRecord,
575 ): boolean {
576 + // Any Pi entry can be a link on the active branch.
577 + if (source === "pi") return true;
578 if (source === "claudeAgent") {
579 if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) {
580 return false;
@@ -843,15 +911,29 @@ export const make = Effect.gen(function* () {
911 reader.write(decoder.decode());
912 recordCount += 1;
913 if (recordCount > recordLimit) return false;
846 - const decoded = decodeTranscriptValue(reader.finish());
847 - if (Option.isSome(decoded)) {
914 + const value = reader.finish();
915 + const decoded = decodeTranscriptValue(value);
916 + if (Option.isNone(decoded) && source === "pi") {
917 + // Pi accepts messages this schema rejects, such as null content; keep their tree links.
918 + records.push(...Option.toArray(decodePiEntryLinks(value)));
919 + } else if (Option.isSome(decoded)) {
920 if (Option.isNone(cwd)) cwd = Option.fromNullOr(extractDecodedCwd(decoded.value));
921 if (source === "claudeAgent") {
922 claudeFields = foldClaudeFields(claudeFields, decoded.value);
923 }
924 if (shouldRetainDecodedRecord(source, decoded.value)) {
853 - records.push(decoded.value);
854 - historyBytes += recordBytes;
925 + if (
926 + source === "pi" &&
927 + decoded.value.type === "message" &&
928 + !isPiConversationRecord(decoded.value)
929 + ) {
930 + // Tool output can dwarf the conversation; keep only the tree links.
931 + const { message: _message, ...links } = decoded.value;
932 + records.push(links);
933 + } else {
934 + records.push(decoded.value);
935 + historyBytes += recordBytes;
936 + }
937 }
938 }
939 recordBytes = 0;
@@ -1030,6 +1112,59 @@ export const make = Effect.gen(function* () {
1112 },
1113 );
1114
1115 + // Pi nests sessions in one directory per cwd, but a custom session directory holds them flat.
1116 + const discoverPiTranscripts = Effect.fn("AgentSessionScanner.discoverPiTranscripts")(function* (
1117 + sessionsDir: string,
1118 + providerInstanceId: ProviderInstanceId,
1119 + operationBudget: number,
1120 + ) {
1121 + let operationsRemaining = operationBudget;
1122 + let truncated = false;
1123 + const readDirectory = (directory: string) => {
1124 + if (operationsRemaining <= 0) {
1125 + truncated = true;
1126 + return Effect.succeed<ReadonlyArray<string>>([]);
1127 + }
1128 + operationsRemaining -= 1;
1129 + return listDirectory(directory);
1130 + };
1131 + const transcripts: Array<TranscriptCandidate> = [];
1132 + for (const entry of yield* readDirectory(sessionsDir)) {
1133 + if (operationsRemaining <= 0) {
1134 + truncated = true;
1135 + break;
1136 + }
1137 + const entryPath = path.join(sessionsDir, entry);
1138 + const filePaths = entry.endsWith(".jsonl")
1139 + ? [entryPath]
1140 + : (yield* readDirectory(entryPath))
1141 + .filter((nested) => nested.endsWith(".jsonl"))
1142 + .map((nested) => path.join(entryPath, nested));
1143 +
1144 + for (const filePath of filePaths) {
1145 + if (operationsRemaining <= 0) {
1146 + truncated = true;
1147 + break;
1148 + }
1149 + operationsRemaining -= 1;
1150 + const stats = yield* statOption(filePath);
1151 + if (
1152 + Option.isSome(stats) &&
1153 + stats.value.type === "File" &&
1154 + Option.isSome(stats.value.mtime)
1155 + ) {
1156 + transcripts.push({
1157 + filePath,
1158 + mtimeMs: stats.value.mtime.value.getTime(),
1159 + providerInstanceId,
1160 + size: Number(stats.value.size),
1161 + });
1162 + }
1163 + }
1164 + }
1165 + return { transcripts, truncated };
1166 + });
1167 +
1168 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
1169 source: AgentSessionSource,
1170 transcripts: ReadonlyArray<TranscriptCandidate>,
@@ -1081,7 +1216,7 @@ export const make = Effect.gen(function* () {
1216 const raw: Array<RawCandidate> = [];
1217 let truncated = false;
1218
1084 - for (const source of ["claudeAgent", "codex"] as const) {
1219 + for (const source of ["claudeAgent", "codex", "pi"] as const) {
1220 const instances: Array<{
1221 readonly instanceId: ProviderInstanceId;
1222 readonly config: ProviderInstanceConfig;
@@ -1111,26 +1246,36 @@ export const make = Effect.gen(function* () {
1246 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
1247 const seenHomes = new Set<string>();
1248 for (const { instanceId, config: instance } of instances) {
1114 - const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
1115 - const configuredHome = instance.environment?.findLast(
1116 - (variable) => variable.name === homeVariable,
1117 - )?.value;
1118 - const environmentHome =
1119 - typeof configuredHome === "string" ? configuredHome : hostEnvironment[homeVariable];
1249 + const environmentHome = (name: "CLAUDE_CONFIG_DIR" | "CODEX_HOME") => {
1250 + const configured = instance.environment?.findLast(
1251 + (variable) => variable.name === name,
1252 + )?.value;
1253 + return typeof configured === "string" ? configured : hostEnvironment[name];
1254 + };
1255
1256 let homePath: string;
1122 - if (source === "claudeAgent") {
1257 + if (source === "pi") {
1258 + const environment = yield* mergeProviderInstanceEnvironment(
1259 + instance.environment,
1260 + hostEnvironment,
1261 + ).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir));
1262 + homePath = resolvePiSessionsDir(environment, homeDir, path);
1263 + } else if (source === "claudeAgent") {
1264 const config = decodeClaudeSettings(instance.config ?? {});
1265 if (Option.isNone(config)) continue;
1125 - homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome);
1266 + homePath = resolveClaudeConfigDir(
1267 + config.value.homePath,
1268 + environmentHome("CLAUDE_CONFIG_DIR"),
1269 + );
1270 } else {
1271 const config = decodeCodexSettings(instance.config ?? {});
1272 if (Option.isNone(config)) continue;
1273 + const codexHome = environmentHome("CODEX_HOME");
1274 const codexSettings =
1275 config.value.homePath.trim().length === 0 &&
1276 config.value.shadowHomePath.trim().length === 0 &&
1132 - environmentHome?.trim()
1133 - ? { ...config.value, homePath: environmentHome }
1277 + codexHome?.trim()
1278 + ? { ...config.value, homePath: codexHome }
1279 : config.value;
1280 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
1281 Effect.provideService(Path.Path, path),
@@ -1155,9 +1300,13 @@ export const make = Effect.gen(function* () {
1300 truncated = true;
1301 continue;
1302 }
1158 - const discovered = yield* source === "claudeAgent"
1159 - ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget)
1160 - : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget);
1303 + const discover =
1304 + source === "claudeAgent"
1305 + ? discoverClaudeTranscripts
1306 + : source === "codex"
1307 + ? discoverCodexTranscripts
1308 + : discoverPiTranscripts;
1309 + const discovered = yield* discover(home.homePath, home.providerInstanceId, operationBudget);
1310 truncated ||= discovered.truncated;
1311 transcriptCandidates.push(...discovered.transcripts);
1312 }
apps/web/src/components/onboarding/WelcomeWizard.tsx
+22 -24
@@ -15,6 +15,7 @@ import {
15 squashAtomCommandFailure,
16 } from "@t3tools/client-runtime/state/runtime";
17 import {
18 + AgentSessionSource,
19 AuthTerminalOperateScope,
20 CommandId,
21 defaultInstanceIdForDriver,
@@ -1715,41 +1716,38 @@ function ImportCandidateRow({
1716 );
1717 }
1718
1719 +const IMPORT_SOURCE_NAMES: Record<AgentSessionSource, string> = {
1720 + claudeAgent: "Claude Code",
1721 + codex: "Codex",
1722 + pi: "Pi",
1723 +};
1724 +
1725 function ImportRowMeta({
1726 sources,
1727 threadCount,
1728 lastActiveAt,
1729 }: {
1723 - readonly sources: ReadonlyArray<"claudeAgent" | "codex"> | null;
1730 + readonly sources: ReadonlyArray<AgentSessionSource> | null;
1731 readonly threadCount: number;
1732 readonly lastActiveAt: string | null;
1733 }) {
1734 const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt);
1735 const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value;
1736 return (
1730 - <span className="ml-auto grid shrink-0 grid-cols-[1rem_1rem_2.5rem_2.25rem] items-center gap-x-1 text-xs text-muted-foreground tabular-nums">
1731 - <span className="flex size-4 items-center justify-center">
1732 - {sources?.includes("claudeAgent") ? (
1733 - <span role="img" aria-label="Claude Code">
1734 - <ProviderInstanceIcon
1735 - driverKind={ProviderDriverKind.make("claudeAgent")}
1736 - displayName="Claude Code"
1737 - iconClassName="size-3"
1738 - />
1739 - </span>
1740 - ) : null}
1741 - </span>
1742 - <span className="flex size-4 items-center justify-center">
1743 - {sources?.includes("codex") ? (
1744 - <span role="img" aria-label="Codex">
1745 - <ProviderInstanceIcon
1746 - driverKind={ProviderDriverKind.make("codex")}
1747 - displayName="Codex"
1748 - iconClassName="size-3"
1749 - />
1750 - </span>
1751 - ) : null}
1752 - </span>
1737 + <span className="ml-auto grid shrink-0 grid-cols-[1rem_1rem_1rem_2.5rem_2.25rem] items-center gap-x-1 text-xs text-muted-foreground tabular-nums">
1738 + {AgentSessionSource.literals.map((source) => (
1739 + <span key={source} className="flex size-4 items-center justify-center">
1740 + {sources?.includes(source) ? (
1741 + <span role="img" aria-label={IMPORT_SOURCE_NAMES[source]}>
1742 + <ProviderInstanceIcon
1743 + driverKind={ProviderDriverKind.make(source)}
1744 + displayName={IMPORT_SOURCE_NAMES[source]}
1745 + iconClassName="size-3"
1746 + />
1747 + </span>
1748 + ) : null}
1749 + </span>
1750 + ))}
1751 <span className="text-right">{threadCount}</span>
1752 <span className="text-right whitespace-nowrap">{age}</span>
1753 </span>
docs/user/welcome-wizard.md
+7 -3
@@ -59,7 +59,7 @@ terminal metadata while the terminal process can use them.
59
60 ## Import your projects
61
62 -T3 Code finds directories that Claude Code or Codex has used. Git repositories
62 +T3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories
63 are listed first, newest activity on top. When the remote is on GitHub, the
64 group shows the repository as `owner/name`. Clones with the same remote share
65 one group. Directories that are not git repositories sit under "Other folders".
@@ -74,8 +74,12 @@ offered.
74 A large or malformed history can reach the scan limit. T3 Code keeps the
75 projects it found and warns when projects or conversations may be missing.
76
77 -Imported projects include Codex and Claude conversations active within the last
78 -30 days. You can continue those conversations in T3 Code.
77 +Imported projects include Claude, Codex and Pi conversations active within the last
78 +30 days. You can continue those conversations in T3 Code. Pi is off by default:
79 +enable it in Settings, then open `/welcome` to import its sessions. Pi sessions
80 +are read from each enabled Pi provider's session directory, which follows
81 +`PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A
82 +Pi conversation imports its active branch, the one Pi reopens.
83
84 Conversation import is best effort. T3 Code keeps the first user prompt and the
85 newest remaining visible user and assistant messages, with 200 messages total.
packages/contracts/src/agentSessions.ts
+1 -1
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
2 import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts";
3 import { ProviderInstanceId } from "./providerInstance.ts";
4
5 -export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex"]);
5 +export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi"]);
6 export type AgentSessionSource = typeof AgentSessionSource.Type;
7
8 export const AgentSessionImportSource = Schema.Struct({
packages/provider-pi/src/server/usage.ts
+16 -11
@@ -131,16 +131,21 @@ export const piUsageReader: ProviderUsageReader<PiSettings, Path.Path> = {
131 directories: Effect.fn("piUsageReader.directories")(function* ({ environment }) {
132 const path = yield* Path.Path;
133 const home = yield* HostProcess.HomeDirectory;
134 - const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim();
135 - if (sessionDir) return [{ dir: path.resolve(expandHomePath(sessionDir, home)) }];
136 - const agentDir = environment.PI_CODING_AGENT_DIR?.trim();
137 - return [
138 - {
139 - dir: path.resolve(
140 - agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"),
141 - "sessions",
142 - ),
143 - },
144 - ];
134 + return [{ dir: resolvePiSessionsDir(environment, home, path) }];
135 }),
136 };
137 +
138 +/** Where Pi stores session JSONL files for a provider environment, matching Pi's own lookup. */
139 +export function resolvePiSessionsDir(
140 + environment: NodeJS.ProcessEnv,
141 + home: string,
142 + path: Path.Path,
143 +): string {
144 + const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim();
145 + if (sessionDir) return path.resolve(expandHomePath(sessionDir, home));
146 + const agentDir = environment.PI_CODING_AGENT_DIR?.trim();
147 + return path.resolve(
148 + agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"),
149 + "sessions",
150 + );
151 +}