1
import { spawn, spawnSync } from "node:child_process";2
import * as crypto from "node:crypto";3
import * as fs from "node:fs";4
import * as os from "node:os";5
import * as path from "node:path";6
import { DEFAULT_RADIUS_GATEWAY } from "@earendil-works/pi-ai/providers/radius-config";7
import { type Container, type EditorComponent, hyperlink, type TUI } from "@earendil-works/pi-tui";8
import { getAuthCredential } from "../../cli/auth-command.ts";9
import { getShareViewerUrl } from "../../config.ts";10
import type { AgentSession } from "../../core/agent-session.ts";11
import { exportSessionToJsonl } from "../../core/session-export.ts";12
import { BorderedLoader } from "./components/bordered-loader.ts";13
import { theme } from "./theme/theme.ts";15
interface SessionShareContext {16
session: AgentSession;17
ui: TUI;18
editorContainer: Container;19
editor: EditorComponent;20
showStatus: (message: string) => void;21
showError: (message: string) => void;22
}24
/** Trailing `pi.share` entry carrying the system prompt and tool schemas for the session viewer. */25
export function createShareTrailingEntries(26
session: AgentSession,27
parentId: string | null,28
timestamp: string,29
): object[] {30
return [31
{32
type: "custom",33
customType: "pi.share",34
id: crypto.randomUUID().slice(0, 8),35
parentId,36
timestamp,37
data: {38
systemPrompt: session.state.systemPrompt,39
tools: session.state.tools.map((tool) => ({40
name: tool.name,41
description: tool.description,42
parameters: tool.parameters,43
})),44
},45
},46
];47
}49
/** Export the current branch with presentation metadata for Radius. */50
export function exportSessionForShare(filePath: string, session: AgentSession): void {51
exportSessionToJsonl(session.sessionManager, filePath, (parentId, timestamp) =>52
createShareTrailingEntries(session, parentId, timestamp),53
);54
}56
/** Share the current session through Radius, falling back to a private gist. */57
export async function shareSession(context: SessionShareContext): Promise<void> {58
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-share-"));59
const jsonlFile = path.join(tempDir, "session.jsonl");60
const htmlFile = path.join(tempDir, "session.html");62
try {63
try {64
exportSessionForShare(jsonlFile, context.session);65
} catch (error: unknown) {66
context.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);67
return;68
}69
const destination = context.session.settingsManager.getSessionShareDestination();70
if (destination !== "gist") {71
if (await tryShareViaRadius(jsonlFile, context)) return;72
if (destination === "radius") {73
context.showError("Radius authentication is not configured. Run '/login radius' first.");74
return;75
}76
}78
try {79
const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });80
if (authResult.status !== 0) {81
context.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");82
return;83
}84
} catch {85
context.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");86
return;87
}89
try {90
await context.session.exportToHtml(htmlFile, { themeName: theme.name });91
} catch (error: unknown) {92
context.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);93
return;94
}95
await shareViaGist(htmlFile, context);96
} finally {97
try {98
fs.rmSync(tempDir, { recursive: true, force: true });99
} catch {100
// Ignore cleanup errors101
}102
}103
}105
async function tryShareViaRadius(tmpFile: string, context: SessionShareContext): Promise<boolean> {106
const provider = context.session.modelRuntime.getProvider("radius");107
if (!provider) return false;109
const token = getAuthCredential(110
await context.session.modelRuntime.getAuth("radius", { minOAuthValidityMs: 5 * 60_000 }),111
);112
if (!token) return false;114
const loader = new BorderedLoader(context.ui, theme, "Uploading to Radius...");115
context.editorContainer.clear();116
context.editorContainer.addChild(loader);117
context.ui.setFocus(loader);118
context.ui.requestRender();119
loader.onAbort = () => {120
restoreEditor(loader, context);121
context.showStatus("Share cancelled");122
};124
try {125
const body = fs.readFileSync(tmpFile);126
const url = new URL("/v1/artifacts", DEFAULT_RADIUS_GATEWAY);127
url.searchParams.set("visibility", "organization");128
url.searchParams.set("title", "Pi session");129
const response = await fetch(url, {130
method: "POST",131
headers: {132
Authorization: `Bearer ${token}`,133
"Content-Type": "application/x-ndjson",134
"Content-Length": String(body.byteLength),135
},136
body,137
signal: loader.signal,138
});139
if (loader.signal.aborted) return true;140
const json = (await response.json().catch(() => null)) as {141
artifact?: { canonical_url: string };142
error?: string;143
} | null;144
if (loader.signal.aborted) return true;145
restoreEditor(loader, context);146
if (!response.ok || !json?.artifact) {147
context.showError(148
`Failed to upload Radius artifact: ${json?.error || response.statusText || response.status}`,149
);150
return true;151
}152
const shareUrl = json.artifact.canonical_url;153
context.showStatus(`Share URL: ${hyperlink(shareUrl, shareUrl)}`);154
return true;155
} catch (error: unknown) {156
if (!loader.signal.aborted) {157
restoreEditor(loader, context);158
context.showError(159
`Failed to upload Radius artifact: ${error instanceof Error ? error.message : "Unknown error"}`,160
);161
}162
return true;163
}164
}166
async function shareViaGist(tmpFile: string, context: SessionShareContext): Promise<void> {167
const loader = new BorderedLoader(context.ui, theme, "Creating gist...");168
context.editorContainer.clear();169
context.editorContainer.addChild(loader);170
context.ui.setFocus(loader);171
context.ui.requestRender();173
let proc: ReturnType<typeof spawn> | null = null;174
loader.onAbort = () => {175
proc?.kill();176
restoreEditor(loader, context);177
context.showStatus("Share cancelled");178
};180
try {181
const result = await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve) => {182
proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);183
let stdout = "";184
let stderr = "";185
proc.stdout?.on("data", (data) => {186
stdout += data.toString();187
});188
proc.stderr?.on("data", (data) => {189
stderr += data.toString();190
});191
proc.on("close", (code) => resolve({ stdout, stderr, code }));192
});194
if (loader.signal.aborted) return;195
restoreEditor(loader, context);197
if (result.code !== 0) {198
context.showError(`Failed to create gist: ${result.stderr?.trim() || "Unknown error"}`);199
return;200
}202
const gistUrl = result.stdout?.trim();203
const gistId = gistUrl?.split("/").pop();204
if (!gistId) {205
context.showError("Failed to parse gist ID from gh output");206
return;207
}209
const previewUrl = getShareViewerUrl(gistId);210
context.showStatus(`Share URL: ${hyperlink(previewUrl, previewUrl)}\nGist: ${hyperlink(gistUrl, gistUrl)}`);211
} catch (error: unknown) {212
if (!loader.signal.aborted) {213
restoreEditor(loader, context);214
context.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);215
}216
}217
}219
function restoreEditor(loader: BorderedLoader, context: SessionShareContext): void {220
loader.dispose();221
context.editorContainer.clear();222
context.editorContainer.addChild(context.editor);223
context.ui.setFocus(context.editor);224
}