返回源码地图

packages/coding-agent/src/modes/interactive/session-share.ts

v1.3.0 · 71023aec1546 · 03/15:auto/gist/radius真实分支,上传失败不回退与分享metadata

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { spawn, spawnSync } from "node:child_process";
2import * as crypto from "node:crypto";
3import * as fs from "node:fs";
4import * as os from "node:os";
5import * as path from "node:path";
6import { DEFAULT_RADIUS_GATEWAY } from "@earendil-works/pi-ai/providers/radius-config";
7import { type Container, type EditorComponent, hyperlink, type TUI } from "@earendil-works/pi-tui";
8import { getAuthCredential } from "../../cli/auth-command.ts";
9import { getShareViewerUrl } from "../../config.ts";
10import type { AgentSession } from "../../core/agent-session.ts";
11import { exportSessionToJsonl } from "../../core/session-export.ts";
12import { BorderedLoader } from "./components/bordered-loader.ts";
13import { theme } from "./theme/theme.ts";
14
15interface SessionShareContext {
16 session: AgentSession;
17 ui: TUI;
18 editorContainer: Container;
19 editor: EditorComponent;
20 showStatus: (message: string) => void;
21 showError: (message: string) => void;
22}
23
24/** Trailing `pi.share` entry carrying the system prompt and tool schemas for the session viewer. */
25export 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}
48
49/** Export the current branch with presentation metadata for Radius. */
50export function exportSessionForShare(filePath: string, session: AgentSession): void {
51 exportSessionToJsonl(session.sessionManager, filePath, (parentId, timestamp) =>
52 createShareTrailingEntries(session, parentId, timestamp),
53 );
54}
55
56/** Share the current session through Radius, falling back to a private gist. */
57export 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");
61
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 }
77
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 }
88
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 errors
101 }
102 }
103}
104
105async function tryShareViaRadius(tmpFile: string, context: SessionShareContext): Promise<boolean> {
106 const provider = context.session.modelRuntime.getProvider("radius");
107 if (!provider) return false;
108
109 const token = getAuthCredential(
110 await context.session.modelRuntime.getAuth("radius", { minOAuthValidityMs: 5 * 60_000 }),
111 );
112 if (!token) return false;
113
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 };
123
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}
165
166async 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();
172
173 let proc: ReturnType<typeof spawn> | null = null;
174 loader.onAbort = () => {
175 proc?.kill();
176 restoreEditor(loader, context);
177 context.showStatus("Share cancelled");
178 };
179
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 });
193
194 if (loader.signal.aborted) return;
195 restoreEditor(loader, context);
196
197 if (result.code !== 0) {
198 context.showError(`Failed to create gist: ${result.stderr?.trim() || "Unknown error"}`);
199 return;
200 }
201
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 }
208
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}
218
219function 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}