pi-studio 0.11.8 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -62,6 +62,8 @@ import {
62
62
  buildStudioReplDeadPaneCloseArgs,
63
63
  isStudioGnuplotSession,
64
64
  isStudioReplReadyLine,
65
+ parseStudioReplPaneCwd,
66
+ STUDIO_REPL_PANE_CWD_FORMAT,
65
67
  STUDIO_REPL_PANE_FORMAT,
66
68
  STUDIO_REPL_SESSION_NAME,
67
69
  studioReplSessionTarget,
@@ -92,14 +94,23 @@ import {
92
94
  REPL_ACTIVITY_RUN_START_BUDGET,
93
95
  buildReplActivityReport,
94
96
  confirmReplActivityDelivered,
97
+ createPiReplRecordActivityLink,
95
98
  createReplActivityState,
96
99
  holdReplActivityCommit,
100
+ isPiReplSessionName,
97
101
  listReplRecordEntries,
98
102
  readReplRecordInert,
99
103
  recordActivityMode,
100
104
  replEntryVersion,
101
105
  resetReplActivityState,
102
106
  } from "./shared/studio-repl-activity.js";
107
+ import {
108
+ createStudioReplFileRoutes,
109
+ openStudioReplFileRoute,
110
+ resolveStudioReplFiles,
111
+ STUDIO_REPL_FILE_ENTRIES,
112
+ studioReplSessionRunBounds,
113
+ } from "./shared/studio-repl-files.js";
103
114
  import {
104
115
  createReplSubmissionDisplay,
105
116
  normalizeReplSubmissionEchoMode,
@@ -8246,6 +8257,19 @@ function respondStudioDirectoryGrantRequiredJson(res: ServerResponse, error: Stu
8246
8257
  });
8247
8258
  }
8248
8259
 
8260
+ // An inline Content-Disposition for any file name: an ASCII fallback, and the name itself as
8261
+ // UTF-8 (RFC 6266), since Node refuses a header with characters such as Δ or 測 (Sol, Astra, c116).
8262
+ function studioInlineContentDisposition(name: string, fallback: string): string {
8263
+ const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/[;"\\]/g, "_").trim() || fallback;
8264
+ let encoded = "";
8265
+ try {
8266
+ encoded = encodeURIComponent(name).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
8267
+ } catch {
8268
+ // A name that isn't well-formed Unicode keeps only its fallback.
8269
+ }
8270
+ return encoded && encoded !== ascii ? `inline; filename="${ascii}"; filename*=UTF-8''${encoded}` : `inline; filename="${ascii}"`;
8271
+ }
8272
+
8249
8273
  function respondPdfFile(req: IncomingMessage, res: ServerResponse, filePath: string): void {
8250
8274
  const method = (req.method ?? "GET").toUpperCase();
8251
8275
  if (method !== "GET" && method !== "HEAD") {
@@ -8263,7 +8287,7 @@ function respondPdfFile(req: IncomingMessage, res: ServerResponse, filePath: str
8263
8287
  ].map((value) => Number(value).toString(16)).join("-")}"`;
8264
8288
  const commonHeaders = {
8265
8289
  "Content-Type": "application/pdf",
8266
- "Content-Disposition": `inline; filename="${basename(filePath).replace(/["\\]/g, "") || "document.pdf"}"`,
8290
+ "Content-Disposition": studioInlineContentDisposition(basename(filePath), "document.pdf"),
8267
8291
  "Referrer-Policy": "no-referrer",
8268
8292
  "Cache-Control": "no-store",
8269
8293
  "X-Content-Type-Options": "nosniff",
@@ -8299,6 +8323,24 @@ function respondHtmlPreviewResourceJson(req: IncomingMessage, res: ServerRespons
8299
8323
  });
8300
8324
  }
8301
8325
 
8326
+ // An image a REPL record entry names, as itself, for the pane's thumbnail and the image viewer.
8327
+ // Opened on its own, an SVG can't run scripts or load other files: the page is sandboxed.
8328
+ function respondStudioReplFileImage(req: IncomingMessage, res: ServerResponse, filePath: string, mimeType: string): void {
8329
+ const method = (req.method ?? "GET").toUpperCase();
8330
+ if (method !== "GET" && method !== "HEAD") { res.setHeader("Allow", "GET, HEAD"); respondText(res, 405, "Use GET or HEAD."); return; }
8331
+ const image = method === "HEAD" ? undefined : readFileSync(filePath);
8332
+ res.writeHead(200, {
8333
+ "Content-Type": mimeType,
8334
+ "Content-Length": String(image ? image.length : statSync(filePath).size),
8335
+ "Cache-Control": "no-store",
8336
+ "X-Content-Type-Options": "nosniff",
8337
+ "Referrer-Policy": "no-referrer",
8338
+ "Cross-Origin-Resource-Policy": "same-origin",
8339
+ "Content-Security-Policy": "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'",
8340
+ });
8341
+ res.end(image);
8342
+ }
8343
+
8302
8344
  function respondStudioReadOnlyImage(req: IncomingMessage, res: ServerResponse, filePath: string, mimeType: string): void {
8303
8345
  const method = (req.method ?? "GET").toUpperCase();
8304
8346
  if (method !== "GET" && method !== "HEAD") { res.setHeader("Allow", "GET, HEAD"); respondText(res, 405, "Use GET or HEAD."); return; }
@@ -12756,6 +12798,11 @@ function recordStudioReplJournalEntry(
12756
12798
  }
12757
12799
 
12758
12800
  function getStudioReplJournalEntries(sessionName: string | null | undefined): StudioReplJournalEntry[] {
12801
+ return readStudioReplJournal(sessionName).entries;
12802
+ }
12803
+
12804
+ /** A session's record entries, or every session's, with the sessions they were read from. */
12805
+ function readStudioReplJournal(sessionName: string | null | undefined): { entries: StudioReplJournalEntry[]; sessions: StudioReplSessionInfo[] } {
12759
12806
  const normalizedSessionName = String(sessionName || "").trim();
12760
12807
  const sessions = normalizedSessionName
12761
12808
  ? [inspectStudioReplSession(normalizedSessionName)].filter((session): session is StudioReplSessionInfo => Boolean(session))
@@ -12788,10 +12835,60 @@ function getStudioReplJournalEntries(sessionName: string | null | undefined): St
12788
12835
  const entries = (normalizedSessionName
12789
12836
  ? studioReplJournalEntries.filter((entry) => entry.sessionName === normalizedSessionName)
12790
12837
  : studioReplJournalEntries).filter((entry) => !refused.has(entry.sessionName));
12791
- return entries.slice(-STUDIO_REPL_JOURNAL_MAX_ENTRIES).map((entry) => ({
12792
- ...entry,
12793
- sharedSynced: !studioReplUnsyncedJournalEntryIds.has(entry.id) && entry.sharedSynced === true,
12794
- }));
12838
+ return {
12839
+ entries: entries.slice(-STUDIO_REPL_JOURNAL_MAX_ENTRIES).map((entry) => ({
12840
+ ...entry,
12841
+ sharedSynced: !studioReplUnsyncedJournalEntryIds.has(entry.id) && entry.sharedSynced === true,
12842
+ })),
12843
+ sessions,
12844
+ };
12845
+ }
12846
+
12847
+ type StudioReplFileRoutes = ReturnType<typeof createStudioReplFileRoutes>;
12848
+
12849
+ // A pane's current directory, asked of tmux by pane ID (studio-repl-tmux.js says why not in the listing).
12850
+ function readStudioReplPaneCwd(paneId: string): string | undefined {
12851
+ if (!/^%\d+$/.test(paneId)) return undefined;
12852
+ const result = runStudioTmux(["display-message", "-p", "-t", paneId, STUDIO_REPL_PANE_CWD_FORMAT], { timeout: 3_000 });
12853
+ return result.ok ? parseStudioReplPaneCwd(result.stdout) || undefined : undefined;
12854
+ }
12855
+
12856
+ /**
12857
+ * Entries for the page, each of a session's latest STUDIO_REPL_FILE_ENTRIES with the image and
12858
+ * PDF files it names (studio-repl-files.js): `{ id, written, image, v }`, `id` naming its route
12859
+ * and `v` the file's version. A relative path resolves against the session's first pane's
12860
+ * current directory, asked of tmux once a session and only when an entry needs it.
12861
+ */
12862
+ function attachStudioReplEntryFiles(entries: StudioReplJournalEntry[], sessions: StudioReplSessionInfo[], routes: StudioReplFileRoutes | undefined) {
12863
+ if (!routes) return entries;
12864
+ const panes = new Map(sessions.map((session) => [session.sessionName, session.target]));
12865
+ const cwds = new Map<string, string | undefined>();
12866
+ const cwdOf = (sessionName: string) => () => {
12867
+ if (!cwds.has(sessionName)) {
12868
+ const paneId = panes.get(sessionName);
12869
+ cwds.set(sessionName, paneId ? readStudioReplPaneCwd(paneId) : undefined);
12870
+ }
12871
+ return cwds.get(sessionName);
12872
+ };
12873
+ // Each entry's own turn in its session, so a file the next one wrote isn't this one's.
12874
+ const bounds = studioReplSessionRunBounds(entries);
12875
+ const looked = new Set<string>();
12876
+ const counts = new Map<string, number>();
12877
+ for (let index = entries.length - 1; index >= 0; index--) {
12878
+ const sessionName = entries[index].sessionName;
12879
+ const count = counts.get(sessionName) ?? 0;
12880
+ if (count >= STUDIO_REPL_FILE_ENTRIES) continue;
12881
+ counts.set(sessionName, count + 1);
12882
+ looked.add(entries[index].id);
12883
+ }
12884
+ return entries.map((entry) => {
12885
+ if (!looked.has(entry.id)) return entry;
12886
+ const files = resolveStudioReplFiles(entry, cwdOf(entry.sessionName), { bounds: bounds.get(entry.id) });
12887
+ return files.length ? {
12888
+ ...entry,
12889
+ files: files.map((file) => ({ id: routes.add(file), written: file.written, image: file.contentType !== "application/pdf", v: file.version })),
12890
+ } : entry;
12891
+ });
12795
12892
  }
12796
12893
 
12797
12894
  function updateStudioReplJournalEntryOutput(
@@ -14096,6 +14193,19 @@ ${cssVarsBlock}
14096
14193
 
14097
14194
  export default function (pi: ExtensionAPI) {
14098
14195
  let serverState: StudioServerState | null = null;
14196
+ // Routes for the files the REPL pane shows, made anew for each server's token.
14197
+ let studioReplFiles: { token: string; routes: StudioReplFileRoutes } | null = null;
14198
+ const getStudioReplFileRoutes = (): StudioReplFileRoutes | undefined => {
14199
+ const token = serverState?.token;
14200
+ if (!token) return undefined;
14201
+ if (studioReplFiles?.token !== token) studioReplFiles = { token, routes: createStudioReplFileRoutes(token) };
14202
+ return studioReplFiles.routes;
14203
+ };
14204
+ // Record entries as the page gets them, with the files they name.
14205
+ const getStudioReplPageEntries = (sessionName: string | null | undefined): StudioReplJournalEntry[] => {
14206
+ const { entries, sessions } = readStudioReplJournal(sessionName);
14207
+ return attachStudioReplEntryFiles(entries, sessions, getStudioReplFileRoutes());
14208
+ };
14099
14209
  const studioWorkspaceStateStore = createStudioWorkspaceStateStore();
14100
14210
  // Hosting-capable unless the env flags turned hosting off; single editor mode doesn't use it.
14101
14211
  const studioBufferStateStore = createStudioBufferServerStore({ legacyState: (id: string) => studioWorkspaceStateStore.get(id),
@@ -14170,38 +14280,60 @@ export default function (pi: ExtensionAPI) {
14170
14280
  percent: null,
14171
14281
  };
14172
14282
  // The selected REPL session, the count of explicit actions and `shown`.
14173
- const studioReplSelection = createReplSelection<StudioReplSessionInfo>();
14283
+ // pi-repl's view of its own sessions, when it's loaded too and reports (studio-repl-activity.js,
14284
+ // D5): told what Studio's pane shows whenever that changes.
14285
+ const piReplActivity = createPiReplRecordActivityLink(pi.events);
14286
+ const studioReplSelection = createReplSelection<StudioReplSessionInfo>({ onChange: (session) => piReplActivity.pane(session?.sessionName ?? null) });
14174
14287
  // What Studio's agent has been told of its REPL sessions' records (PANE-AWARENESS-DESIGN.md,
14175
14288
  // draft 3, after D5 of the shared design for people's sends). Read when Studio loads.
14176
14289
  const replActivityMode = recordActivityMode();
14177
14290
  const replActivity = createReplActivityState();
14178
14291
  // The session showing in Studio's REPL pane, where the person's Quick sends go, and those
14179
14292
  // this conversation has sent to or named.
14180
- const replActivitySessionNames = (): string[] => [...new Set(
14181
- [studioReplSelection.session?.sessionName, ...replActivity.used].filter((name): name is string => Boolean(name)),
14293
+ // While pi-repl reports, its own sessions are its to report.
14294
+ const replActivitySessionNames = (leaveToPiRepl = false): string[] => [...new Set(
14295
+ [studioReplSelection.session?.sessionName, ...replActivity.used].filter((name): name is string => Boolean(name) && !(leaveToPiRepl && isPiReplSessionName(name))),
14182
14296
  )];
14297
+ // A session this conversation sent to or named, for Studio's reports and pi-repl's.
14298
+ const useReplActivitySession = (sessionName: string) => {
14299
+ replActivity.used.add(sessionName);
14300
+ piReplActivity.used(sessionName);
14301
+ };
14183
14302
  // The report a tool result carries, held until its text is seen in what the model is given.
14184
14303
  // The agent's own send isn't reported back to it, but is marked as told in the version its
14185
- // result shows, once that result's text (`own.text`) is seen too.
14186
- const prepareReplActivityForResult = async (toolCallId: string, own?: { sessionName: string; id: string; text: string }, budget = REPL_ACTIVITY_RESULT_BUDGET): Promise<string> => {
14304
+ // result shows, once that result's text (`own.text`) is seen too. While pi-repl reports, its
14305
+ // report of its own sessions comes first, in the room Studio's report of the rest leaves.
14306
+ const prepareReplActivityForResult = async (toolCallId: string, ownSend?: { sessionName: string; id: string; text: string; status: string }, budget = REPL_ACTIVITY_RESULT_BUDGET): Promise<string> => {
14187
14307
  if (replActivityMode === "off") return "";
14308
+ const leaveToPiRepl = piReplActivity.reports();
14309
+ const toPiRepl = Boolean(ownSend && leaveToPiRepl && isPiReplSessionName(ownSend.sessionName));
14310
+ const own = toPiRepl ? undefined : ownSend;
14311
+ let studioReport = "";
14188
14312
  try {
14189
- const names = replActivitySessionNames();
14190
- if (!names.length) return "";
14191
- const observations = await observeStudioReplActivity(names);
14192
- const observedOwn = own ? observations.find((observed) => observed.ok && observed.sessionName === own.sessionName) : undefined;
14193
- const ownEntry = observedOwn?.ok ? observedOwn.record.entries.find((entry) => entry.id === own?.id) : undefined;
14194
- const report = buildReplActivityReport(replActivity, observations, {
14195
- budget,
14196
- exclude: new Set(own ? [own.id] : []),
14197
- own: own && ownEntry ? [{ sessionName: own.sessionName, id: own.id, version: replEntryVersion(ownEntry), text: own.text }] : [],
14198
- });
14199
- holdReplActivityCommit(replActivity, `tool:${toolCallId}`, report.commit);
14200
- return report.text;
14313
+ const names = replActivitySessionNames(leaveToPiRepl);
14314
+ if (names.length) {
14315
+ const observations = await observeStudioReplActivity(names);
14316
+ const observedOwn = own ? observations.find((observed) => observed.ok && observed.sessionName === own.sessionName) : undefined;
14317
+ const ownEntry = observedOwn?.ok ? observedOwn.record.entries.find((entry) => entry.id === own?.id) : undefined;
14318
+ const report = buildReplActivityReport(replActivity, observations, {
14319
+ budget,
14320
+ exclude: new Set(own ? [own.id] : []),
14321
+ own: own && ownEntry ? [{ sessionName: own.sessionName, id: own.id, version: replEntryVersion(ownEntry), text: own.text }] : [],
14322
+ });
14323
+ holdReplActivityCommit(replActivity, `tool:${toolCallId}`, report.commit);
14324
+ studioReport = report.text;
14325
+ }
14201
14326
  } catch {
14202
14327
  // The tool's own result stands without it.
14203
- return "";
14204
14328
  }
14329
+ const piReplReport = leaveToPiRepl
14330
+ ? await piReplActivity.report({
14331
+ budget: budget - (studioReport ? studioReport.length + 2 : 0),
14332
+ cwd: process.cwd(),
14333
+ own: toPiRepl && ownSend ? { sessionName: ownSend.sessionName, id: ownSend.id, text: ownSend.text, shown: [ownSend.status] } : undefined,
14334
+ })
14335
+ : "";
14336
+ return [piReplReport, studioReport].filter(Boolean).join("\n\n");
14205
14337
  };
14206
14338
  const REPL_ACTIVITY_GUIDELINES = replActivityMode === "off" ? [] : [
14207
14339
  "Studio tells you about new entries in its REPL sessions' shared records (the user's sends and notes, other agents', pi-repl's)"
@@ -14323,7 +14455,7 @@ export default function (pi: ExtensionAPI) {
14323
14455
  parameters: STUDIO_REPL_STATUS_TOOL_PARAMS,
14324
14456
  async execute(toolCallId, params) {
14325
14457
  const selected = selectStudioReplSessionForTool({ sessionName: params.sessionName, target: params.target });
14326
- if (params.sessionName && selected.session?.sessionName === params.sessionName) replActivity.used.add(params.sessionName);
14458
+ if (params.sessionName && selected.session?.sessionName === params.sessionName) useReplActivitySession(params.sessionName);
14327
14459
  const recordEntries = selected.session ? getStudioReplJournalEntries(selected.session.sessionName) : [];
14328
14460
  const lines = [
14329
14461
  `Active Studio REPL: ${studioReplSelection.session?.sessionName || "none"}`,
@@ -14423,7 +14555,7 @@ export default function (pi: ExtensionAPI) {
14423
14555
  // The agent's send is an explicit choice when admitted, before it waits for the
14424
14556
  // session's lease; only a ticket still current lets its result select (Sol, Astra).
14425
14557
  const ticket = studioReplSelection.choose({ session: selected.session });
14426
- replActivity.used.add(selected.session.sessionName);
14558
+ useReplActivitySession(selected.session.sessionName);
14427
14559
  // Every exit after admission tells the pages Studio's selection: the result when
14428
14560
  // it selects, otherwise a repl_state, so a failure can't leave them behind (Sol).
14429
14561
  let published = false;
@@ -14570,7 +14702,7 @@ export default function (pi: ExtensionAPI) {
14570
14702
  sharedSynced: journalEntry.sharedSynced === true,
14571
14703
  completed,
14572
14704
  timedOut: Boolean(sent.controlFiles?.doneFile && !completed),
14573
- journalEntries: getStudioReplJournalEntries(selected.session.sessionName),
14705
+ journalEntries: getStudioReplPageEntries(selected.session.sessionName),
14574
14706
  select,
14575
14707
  ...(select ? {
14576
14708
  session: currentSession,
@@ -14582,7 +14714,7 @@ export default function (pi: ExtensionAPI) {
14582
14714
  } : {}),
14583
14715
  });
14584
14716
  // What else the session's record holds that the agent hasn't been told, before its own result.
14585
- const activity = await prepareReplActivityForResult(toolCallId, { sessionName: currentSession.sessionName, id: journalEntry.id, text });
14717
+ const activity = await prepareReplActivityForResult(toolCallId, { sessionName: currentSession.sessionName, id: journalEntry.id, text, status: journalEntry.status });
14586
14718
  return {
14587
14719
  content: [{ type: "text", text: activity ? `${activity}\n\n${text}` : text }],
14588
14720
  details: {
@@ -15448,7 +15580,7 @@ export default function (pi: ExtensionAPI) {
15448
15580
  activeSessionName: active?.sessionName ?? null,
15449
15581
  activeRuntime: studioReplSelection.runtime,
15450
15582
  shown: studioReplSelection.shown,
15451
- journalEntries: getStudioReplJournalEntries(active?.sessionName ?? null),
15583
+ journalEntries: getStudioReplPageEntries(active?.sessionName ?? null),
15452
15584
  recordActivity: replActivityMode,
15453
15585
  // What the page sends as when it hasn't chosen a name.
15454
15586
  personName: person.name,
@@ -15484,7 +15616,7 @@ export default function (pi: ExtensionAPI) {
15484
15616
  shown: studioReplSelection.shown,
15485
15617
  transcript: captured.transcript,
15486
15618
  capturedAt: Date.now(),
15487
- journalEntries: getStudioReplJournalEntries(captured.session.sessionName),
15619
+ journalEntries: getStudioReplPageEntries(captured.session.sessionName),
15488
15620
  ...extra,
15489
15621
  });
15490
15622
  };
@@ -15499,13 +15631,13 @@ export default function (pi: ExtensionAPI) {
15499
15631
  session: captured.session,
15500
15632
  transcript: captured.transcript,
15501
15633
  capturedAt: Date.now(),
15502
- journalEntries: getStudioReplJournalEntries(captured.session.sessionName),
15634
+ journalEntries: getStudioReplPageEntries(captured.session.sessionName),
15503
15635
  } : {
15504
15636
  type: "repl_capture",
15505
15637
  observation: true,
15506
15638
  sessionName,
15507
15639
  captureError: captured.message,
15508
- journalEntries: getStudioReplJournalEntries(sessionName),
15640
+ journalEntries: getStudioReplPageEntries(sessionName),
15509
15641
  });
15510
15642
  };
15511
15643
 
@@ -15521,7 +15653,7 @@ export default function (pi: ExtensionAPI) {
15521
15653
  sendReplSelectionToClient(client, extra);
15522
15654
  return;
15523
15655
  }
15524
- sendReplStateToClient(client, { journalEntries: getStudioReplJournalEntries(sessionName), ...extra });
15656
+ sendReplStateToClient(client, { journalEntries: getStudioReplPageEntries(sessionName), ...extra });
15525
15657
  };
15526
15658
 
15527
15659
  const emitDebugEvent = (event: string, details?: Record<string, unknown>) => {
@@ -17787,7 +17919,7 @@ export default function (pi: ExtensionAPI) {
17787
17919
  requestId: msg.requestId,
17788
17920
  sessionName: msg.sessionName,
17789
17921
  message: sent.message,
17790
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
17922
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17791
17923
  });
17792
17924
  const timeoutMs = STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS;
17793
17925
  let completed = false;
@@ -17874,7 +18006,7 @@ export default function (pi: ExtensionAPI) {
17874
18006
  type: "repl_journal_ack",
17875
18007
  requestId: msg.requestId,
17876
18008
  sessionName: msg.sessionName,
17877
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
18009
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17878
18010
  });
17879
18011
  } catch (error) {
17880
18012
  sendToClient(client, { type: "error", requestId: msg.requestId, message: error instanceof Error ? error.message : String(error) });
@@ -17904,7 +18036,7 @@ export default function (pi: ExtensionAPI) {
17904
18036
  type: "repl_journal_ack",
17905
18037
  requestId: msg.requestId,
17906
18038
  sessionName: msg.sessionName,
17907
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
18039
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17908
18040
  });
17909
18041
  } catch (error) {
17910
18042
  sendToClient(client, { type: "error", requestId: msg.requestId, message: error instanceof Error ? error.message : String(error) });
@@ -19930,6 +20062,27 @@ export default function (pi: ExtensionAPI) {
19930
20062
  return;
19931
20063
  }
19932
20064
 
20065
+ // A file a REPL record entry names, by the route the page was given for it.
20066
+ if (requestUrl.pathname === "/repl-file") {
20067
+ const token = requestUrl.searchParams.get("token") ?? "";
20068
+ if (token !== serverState.token) {
20069
+ respondText(res, 403, "Invalid or expired studio token. Re-run /studio.");
20070
+ return;
20071
+ }
20072
+ const opened = openStudioReplFileRoute(getStudioReplFileRoutes()?.get(requestUrl.searchParams.get("id") ?? ""));
20073
+ if (!opened.ok) {
20074
+ respondText(res, opened.status, opened.message);
20075
+ return;
20076
+ }
20077
+ try {
20078
+ if (opened.contentType === "application/pdf") respondPdfFile(req, res, opened.filePath);
20079
+ else respondStudioReplFileImage(req, res, opened.filePath, opened.contentType);
20080
+ } catch {
20081
+ if (!res.headersSent) respondText(res, 404, "Studio couldn't read this file.");
20082
+ }
20083
+ return;
20084
+ }
20085
+
19933
20086
  if (requestUrl.pathname === "/pdf-resource") {
19934
20087
  const token = requestUrl.searchParams.get("token") ?? "";
19935
20088
  if (token !== serverState.token) {
@@ -20940,7 +21093,7 @@ export default function (pi: ExtensionAPI) {
20940
21093
  pi.on("before_agent_start", async () => {
20941
21094
  if (replActivityMode !== "on") return undefined;
20942
21095
  try {
20943
- const names = replActivitySessionNames();
21096
+ const names = replActivitySessionNames(piReplActivity.reports());
20944
21097
  if (!names.length) return undefined;
20945
21098
  const report = buildReplActivityReport(replActivity, await observeStudioReplActivity(names), { budget: REPL_ACTIVITY_RUN_START_BUDGET });
20946
21099
  if (!report.text) return undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-studio",
3
- "version": "0.11.8",
3
+ "version": "0.11.10",
4
4
  "description": "Two-pane browser workspace for pi with prompt/response editing, annotations, critiques, active quiz, prompt/response history, live previews, and tmux-backed REPL/literate REPL workflows",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -63,6 +63,86 @@ const PERSON_CHANNELS = [
63
63
  { prefix: /^studio:(?:send|note):/, origin: "pi-studio", channel: "Pi Studio" },
64
64
  ];
65
65
 
66
+ /*
67
+ * pi-repl's view of its own sessions, when it's loaded in the same Pi (D5 of the shared design,
68
+ * agreed with pi-repl's session on 3 Nov; REPL_SESSION_RECORD_PROTOCOL.md, "One view per agent").
69
+ * Studio asks on Pi's event bus whether pi-repl is there, at each run's start and each REPL tool
70
+ * result. If it answers with protocol 2 or later, Studio leaves the `pi-repl-*` sessions to it:
71
+ * it tells pi-repl what Studio's pane shows and which of them Studio's agent used, and each of
72
+ * Studio's REPL results carries pi-repl's report of them, the agent's own send aside. Without
73
+ * that answer (no pi-repl, or 0.12.0's protocol 1, which can't report into Studio's results),
74
+ * Studio tells it nothing and tells its agent of every session itself, as before.
75
+ */
76
+ export const PI_REPL_RECORD_ACTIVITY_CHANNEL = "pi-repl:record-activity:v1";
77
+ // The first protocol whose pi-repl reports into Studio's results.
78
+ export const PI_REPL_REPORT_PROTOCOL = 2;
79
+ // How long a result waits for pi-repl's report; pi-repl gives its own reads 2 seconds.
80
+ export const PI_REPL_REPORT_DEADLINE_MS = 3_000;
81
+ // The sessions pi-repl's view takes: its own tools' sessions, as pi-repl names them.
82
+ export const PI_REPL_SESSION_NAME = /^pi-repl-[a-z0-9][a-z0-9-]{0,80}$/;
83
+
84
+ /** Whether pi-repl, when it reports, keeps this session's view. */
85
+ export function isPiReplSessionName(name) {
86
+ return typeof name === "string" && PI_REPL_SESSION_NAME.test(name);
87
+ }
88
+
89
+ /**
90
+ * Studio's side of the channel, on Pi's event bus (`pi.events`). pi-repl answers a probe at once,
91
+ * while the emit runs, and a report when it has read the records. A missing or failing bus is no
92
+ * answer.
93
+ */
94
+ export function createPiReplRecordActivityLink(events, { deadlineMs = PI_REPL_REPORT_DEADLINE_MS } = {}) {
95
+ let paneTold;
96
+ const emit = (message) => {
97
+ try {
98
+ events?.emit?.(PI_REPL_RECORD_ACTIVITY_CHANNEL, message);
99
+ return true;
100
+ } catch {
101
+ // Studio goes on as if pi-repl weren't there.
102
+ return false;
103
+ }
104
+ };
105
+ const reports = () => {
106
+ let protocol = 0;
107
+ emit({ kind: "probe", reply: (answer) => { protocol = Number(answer?.protocol) || 0; } });
108
+ return protocol >= PI_REPL_REPORT_PROTOCOL;
109
+ };
110
+ return {
111
+ /** Whether pi-repl answers now with a protocol that reports into Studio's results. */
112
+ reports,
113
+ /** A `pi-repl-*` session Studio's agent sent to or named. */
114
+ used(sessionName) {
115
+ if (isPiReplSessionName(sessionName) && reports()) emit({ kind: "used", sessionName });
116
+ },
117
+ /** The session Studio's pane shows, told when it changes: null for none, or one that isn't pi-repl's. */
118
+ pane(sessionName) {
119
+ const name = isPiReplSessionName(sessionName) ? sessionName : null;
120
+ if (name === paneTold || !reports()) return;
121
+ paneTold = name;
122
+ emit({ kind: "pane", sessionName: name });
123
+ },
124
+ /**
125
+ * pi-repl's report for one of Studio's results, within `budget`: of the sessions Studio's
126
+ * agent used and its pane, what the agent hasn't been told, its own send (`own`) aside.
127
+ * pi-repl holds it until its text is seen in what the model is given. Empty when there is
128
+ * nothing to tell or no reply in time; a late one is dropped, so its entries come round again.
129
+ * @param {{ budget: number, cwd?: string, own?: { sessionName: string, id: string, text: string, shown: string[] } }} request
130
+ * @returns {Promise<string>}
131
+ */
132
+ report({ budget, cwd, own }) {
133
+ return new Promise((resolve) => {
134
+ const timer = setTimeout(() => resolve(""), deadlineMs);
135
+ const reply = (text) => {
136
+ clearTimeout(timer);
137
+ resolve(typeof text === "string" ? text : "");
138
+ };
139
+ const ownSend = own && isPiReplSessionName(own.sessionName) ? { sessionName: own.sessionName, id: own.id, text: own.text, shown: [...own.shown] } : undefined;
140
+ if (!emit({ kind: "report", budget, ...(cwd ? { cwd } : {}), ...(ownSend ? { own: ownSend } : {}), reply })) reply("");
141
+ });
142
+ },
143
+ };
144
+ }
145
+
66
146
  /**
67
147
  * Who sent an entry and how, as D5 reads the record (P3): an agent's label; a person's name
68
148
  * under a person's request-ID prefix on its matching origin; otherwise "User", "via Pi Studio"