pi-studio 0.11.9 → 0.11.11
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/CHANGELOG.md +11 -0
- package/README.md +10 -2
- package/ROADMAP.md +3 -2
- package/index.ts +87 -25
- package/package.json +1 -1
- package/shared/studio-copy-url.js +23 -0
- package/shared/studio-repl-activity.js +80 -0
- package/shared/studio-repl-selection.js +10 -3
- package/shared/studio-url-file.js +88 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,17 @@ All notable changes to `pi-studio` are documented here.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.11.11] — 2026-11-04
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- `/studio --copy-url` copies the running Studio's URL, the one `/studio --status` prints, for a terminal too narrow to show it whole. It uses Pi's own clipboard: the system clipboard and, over SSH, your terminal's too (OSC 52), which works if the terminal allows it. Pi can't confirm the terminal took it, so paste to check. It copies only in Pi's terminal interface; in RPC mode the URL is in Studio's notifications.
|
|
11
|
+
- With `PI_STUDIO_URL_FILE` set to an absolute path, Studio writes the last URL it printed for its main view to that file, so a script, an editor or a container can open Studio without anyone copying the URL out of the terminal ([#7](https://github.com/omaclaren/pi-studio/issues/7)). The file is created readable only by you (on Windows, its folder's permissions apply) and replaced whole. When Studio stops, it tries to remove the file, if it still holds Studio's URL. `/studio --status` names it. Nothing is written unless the variable is set; give each Pi process a file of its own. A file Studio can't write, such as one in a missing folder, gives a warning, and Studio starts as usual.
|
|
12
|
+
|
|
13
|
+
## [0.11.10] — 2026-11-03
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
- With pi-repl 0.12.1 or later loaded in the same Pi, the agent is told of each REPL record entry once. pi-repl keeps track of what the agent has been told about its own `pi-repl-*` sessions, including the one Studio's REPL pane shows and those the agent used through Studio's REPL tools. Its reports come at the start of a run, as before, and now also in Studio's REPL tool results. Studio tells the agent about the rest. Before, both told it about the `pi-repl-*` sessions. Without pi-repl, or with pi-repl 0.12.0 or older, Studio tells it about every session, as before.
|
|
17
|
+
|
|
7
18
|
## [0.11.9] — 2026-11-03
|
|
8
19
|
|
|
9
20
|
### Added
|
package/README.md
CHANGED
|
@@ -16,7 +16,9 @@ Zen mode, in rose-pine-dawn:
|
|
|
16
16
|
|
|
17
17
|

|
|
18
18
|
|
|
19
|
-
Watch the [demo](https://github.com/omaclaren/pi-studio/releases/download/demo-
|
|
19
|
+
Watch the [demo](https://github.com/omaclaren/pi-studio/releases/download/demo-studio/pi-studio-demo.mp4) (68s, real time, no audio, automated typing). It shows a prompt and its rendered answer, a linked note and a PDF figure in the Document, and a selection brought into the Prompt for a follow-up.
|
|
20
|
+
|
|
21
|
+
The screenshots and both demos are also on the [project page](https://omaclaren.github.io/pi-studio/).
|
|
20
22
|
|
|
21
23
|
## Features
|
|
22
24
|
|
|
@@ -65,6 +67,7 @@ Or from GitHub, `pi install https://github.com/omaclaren/pi-studio`, or once wit
|
|
|
65
67
|
| `/studio --port <port>` | Use a fixed port |
|
|
66
68
|
| `/studio --listen-all` | Listen on all interfaces, for containers ([see below](#network-and-ssh)) |
|
|
67
69
|
| `/studio --status`, `--stop` | Show the server's status, or stop it |
|
|
70
|
+
| `/studio --copy-url` | Copy the running Studio's URL, for a terminal too narrow to show it whole. Over SSH, Pi also sends it to your terminal's clipboard (OSC 52), which works if the terminal allows it; set `PI_CLIPBOARD_OSC52=1` where Pi can't tell it's remote, as in some tmux sessions |
|
|
68
71
|
| `/studio-replace` | Replace the open Studio view. In dual editor mode, move it to a new tab here |
|
|
69
72
|
| `/studio-editor-only [file]` | Open an extra editor tab (single editor mode) |
|
|
70
73
|
| `/studio-current <file>` | Load a file into the open Studio tab (single editor mode) |
|
|
@@ -136,7 +139,9 @@ Icons in exported PDFs need Mermaid CLI 11.12+ (`npm install -g @mermaid-js/merm
|
|
|
136
139
|
|
|
137
140
|
### REPL
|
|
138
141
|
|
|
139
|
-
The REPL pane runs code in tmux sessions. It can start its own, and it shares a record of submissions and output with [pi-repl](https://github.com/omaclaren/pi-repl) when both use the same session. Pane echo sets how much submitted code goes into the raw tmux history, as in pi-repl: up to 20 lines with Summary, the default, up to 40 with Full, and none with Off. Your sends and notes are recorded under your name (**Sending as**, under Quick send). An image or PDF an entry's code saved while it ran, such as a plot, shows under it when the code or output names it. The agent is told of record entries it hasn't seen, such as your sends, other clients' sends and late output, when a run starts and with its REPL tools' results. The record format is in [`shared/REPL_SESSION_RECORD_PROTOCOL.md`](./shared/REPL_SESSION_RECORD_PROTOCOL.md).
|
|
142
|
+
The REPL pane runs code in tmux sessions. It can start its own, and it shares a record of submissions and output with [pi-repl](https://github.com/omaclaren/pi-repl) when both use the same session. Pane echo sets how much submitted code goes into the raw tmux history, as in pi-repl: up to 20 lines with Summary, the default, up to 40 with Full, and none with Off. Your sends and notes are recorded under your name (**Sending as**, under Quick send). An image or PDF an entry's code saved while it ran, such as a plot, shows under it when the code or output names it. The agent is told of record entries it hasn't seen, such as your sends, other clients' sends and late output, when a run starts and with its REPL tools' results. With pi-repl 0.12.1 or later loaded too, pi-repl tells it about its own `pi-repl-*` sessions, also in Studio's tool results, and Studio about the rest, so nothing is told twice. The record format is in [`shared/REPL_SESSION_RECORD_PROTOCOL.md`](./shared/REPL_SESSION_RECORD_PROTOCOL.md).
|
|
143
|
+
|
|
144
|
+
Watch a [short demo](https://github.com/omaclaren/pi-studio/releases/download/demo-repl/pi-studio-repl-demo.mp4) of Pi, Quick send and Claude Code, through [agent-repl](https://github.com/omaclaren/agent-repl), sharing one Python session (50s, real time, no audio, automated typing).
|
|
140
145
|
|
|
141
146
|
### Side questions
|
|
142
147
|
|
|
@@ -148,6 +153,8 @@ Studio listens on `127.0.0.1` only, and every URL carries a token. Over SSH, for
|
|
|
148
153
|
|
|
149
154
|
For a container, `/studio --no-browser --listen-all --port 4321` listens on all interfaces. Anyone with the full URL can control Studio, including running prompts and reading or writing files, and there's no TLS. Treat the URL like a password, never expose the port to the internet, and bind the host side to loopback (`-p 127.0.0.1:4321:4321`). Quarto previews use a second port, which must be forwarded too.
|
|
150
155
|
|
|
156
|
+
For a script, an editor or a container that opens Studio itself, set `PI_STUDIO_URL_FILE` to an absolute path when you start Pi. Studio writes the last URL it printed for its main view to that file, creating it readable only by you, and removes it when Studio stops; `/studio --status` writes it again and names the file. Studio replaces a file already at that path (though not a link or a folder), so use a file of its own, in a private folder that isn't synced, and give each Pi process its own path. The file holds the same credential as the printed URL. If Pi crashes, or Studio can't remove the file, it's left behind, but its token no longer works. On Windows, who can read it follows its folder's permissions.
|
|
157
|
+
|
|
151
158
|
### Environment variables
|
|
152
159
|
|
|
153
160
|
| Variable | Effect |
|
|
@@ -159,6 +166,7 @@ For a container, `/studio --no-browser --listen-all --port 4321` listens on all
|
|
|
159
166
|
| `PI_STUDIO_REPL_ECHO_MODE` | Default pane echo for `studio_repl_send`: `summary` (the default), `off` or `full` |
|
|
160
167
|
| `PI_REPL_USER_NAME` | The name your REPL sends and notes are recorded under, ahead of the name saved with pi-repl |
|
|
161
168
|
| `PI_REPL_RECORD_ACTIVITY` | Whether the agent is told of new REPL record entries: `on` (the default: at a run's start and in REPL tool results), `send` (in results only) or `off`; unset, it follows `PI_REPL_PANE_ACTIVITY` |
|
|
169
|
+
| `PI_STUDIO_URL_FILE` | An absolute path where Studio writes the last URL it printed for its main view, for a program to read ([see above](#network-and-ssh)); a file of its own for each Pi process |
|
|
162
170
|
| `PI_STUDIO_PANDOC_TIMEOUT_MS`, `PI_STUDIO_LATEX_TIMEOUT_MS`, `PI_STUDIO_MERMAID_TIMEOUT_MS` | Export time limits |
|
|
163
171
|
|
|
164
172
|
Installing pi-studio also adds `pi-studio-dark` and `pi-studio-light` to Pi's themes, without changing your current theme.
|
package/ROADMAP.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
This is the current planning source of truth for Studio work. `NEXT-STAGE.md` is historical; `TODO.md` tracks smaller backlog items that are not yet assigned to a release.
|
|
4
4
|
|
|
5
|
-
## Current status (
|
|
5
|
+
## Current status (4 Nov 2026)
|
|
6
6
|
|
|
7
|
-
`0.11.
|
|
7
|
+
`0.11.11` is the current release. Studio is in a feature freeze from `0.11.9`, for use in normal work. Before the freeze, `0.11.9` added the images and PDFs a REPL entry's code saved, shown under the entry, and a PDF header that fits on one line. Two changes were approved in the freeze. `0.11.10` works with pi-repl `0.12.1` so that, with both loaded, the agent is told each REPL record entry once. `0.11.11` gets Studio's URL out of a terminal too narrow to show it: `/studio --copy-url` copies it, and `PI_STUDIO_URL_FILE` keeps it in a file for programs ([#7](https://github.com/omaclaren/pi-studio/issues/7)). During the freeze, changes are limited to fixes for failures in normal use, lost data, effects on other people's processes or files, and security. [TODO.md](TODO.md) lists the known limits and what comes after the freeze.
|
|
8
8
|
|
|
9
9
|
`0.10.0` (14 Oct) made the buffer-first workspace the default, as **dual editor mode** (Prompt and Document), with **single editor mode** one switch away (footer button, `/studio --single`). It went through real course use as private alpha candidates 49–69. The `PI_STUDIO_*` flags described further down are development overrides only: when any is set it decides, and the mode switch is hidden.
|
|
10
10
|
|
|
@@ -13,6 +13,7 @@ The `0.11` releases brought the REPL pane up to pi-repl `0.11.7`: Ruby, Java, Oc
|
|
|
13
13
|
### Parity at the freeze
|
|
14
14
|
|
|
15
15
|
- **pi-repl `0.11.7` and agent-repl `0.5.0`.** Studio's copies of the shared record, names, protocol, control-file, display, C++, gnuplot and M-language helpers are byte-identical to pi-repl's, and agent-repl carries the same record, names and protocol files. Two helpers differ: pi-repl generalised `repl-session-stop.js` and `repl-gnuplot-processes.js` for LFortran. Studio doesn't run LFortran, and won't paste into pi-repl's LFortran session ("This session takes code only through pi-repl").
|
|
16
|
+
- **pi-repl `0.12.1`'s record-activity channel.** pi-repl `0.12.0` started telling its agent about other clients' record entries itself. With both loaded, Studio `0.11.10` leaves the `pi-repl-*` sessions to pi-repl over Pi's event bus (protocol 2), and puts pi-repl's report in its own REPL results. Studio still has its older copy of pi-repl's activity module and protocol document, which are re-vendored after the freeze.
|
|
16
17
|
- **pi-markdown-preview `0.26.2` and agent-markdown-preview `0.13.2`.** Their REPL page reads the same records with the same record-directory check. Both show the images and PDFs an entry's code saved, by the same rules: a file shows when the entry names it and it was written in that entry's turn. Studio has them from `0.11.9`; the preview packages' REPL page has its latest rules on an unreleased branch.
|
|
17
18
|
|
|
18
19
|
## Release approach
|
package/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentSession, AgentSessionEvent, AgentSessionRuntime, CreateAgentSessionRuntimeFactory, ExtensionAPI, ExtensionCommandContext, ExtensionContext, ResourceLoader, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { buildSessionContext, createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createExtensionRuntime, defineTool, getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { buildSessionContext, copyToClipboard, createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createExtensionRuntime, defineTool, getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { type ModelThinkingLevel, type ThinkingLevel } from "@earendil-works/pi-ai";
|
|
4
4
|
import { completeSimple } from "@earendil-works/pi-ai/compat";
|
|
5
5
|
import { Type } from "@sinclair/typebox";
|
|
@@ -94,8 +94,10 @@ import {
|
|
|
94
94
|
REPL_ACTIVITY_RUN_START_BUDGET,
|
|
95
95
|
buildReplActivityReport,
|
|
96
96
|
confirmReplActivityDelivered,
|
|
97
|
+
createPiReplRecordActivityLink,
|
|
97
98
|
createReplActivityState,
|
|
98
99
|
holdReplActivityCommit,
|
|
100
|
+
isPiReplSessionName,
|
|
99
101
|
listReplRecordEntries,
|
|
100
102
|
readReplRecordInert,
|
|
101
103
|
recordActivityMode,
|
|
@@ -131,6 +133,8 @@ import {
|
|
|
131
133
|
} from "./shared/studio-tab-launcher.js";
|
|
132
134
|
import { buildStudioHostingBootstrapState, createStudioBufferServerStore, STUDIO_BUFFER_REQUEST_MAX_BYTES } from "./shared/studio-buffer-server.js";
|
|
133
135
|
import { createStudioTurns, readStudioEditorMode, resolveStudioEditorFlags, writeStudioEditorMode } from "./shared/studio-editor-mode.js";
|
|
136
|
+
import { createStudioUrlFile, STUDIO_URL_FILE_ENV } from "./shared/studio-url-file.js";
|
|
137
|
+
import { copyStudioUrl } from "./shared/studio-copy-url.js";
|
|
134
138
|
import { canonicalStudioDocumentPath, studioDocumentPathsReferToSameFile } from "./shared/studio-document-paths.js";
|
|
135
139
|
import { resolveStudioHostingPage, studioHostingCommandError, studioHostingLocalLinkError } from "./shared/studio-document-entrypoints.js";
|
|
136
140
|
import { systemThemeLacksTrueColor } from "./shared/studio-system-theme.js";
|
|
@@ -14246,6 +14250,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
14246
14250
|
let lastHostedFullWorkspaceId: string | null = null;
|
|
14247
14251
|
const currentFullStudioUrl = (state: StudioServerState) => buildStudioUrl(state.port, state.token, "full", undefined, undefined,
|
|
14248
14252
|
STUDIO_DOCUMENT_HOSTING_ENABLED ? { hostedWorkspaceId: studioBufferStateStore.activeHostingWorkspaces("full")[0] || lastHostedFullWorkspaceId || undefined } : undefined);
|
|
14253
|
+
// Issue #7: with PI_STUDIO_URL_FILE set, that file holds the URL Studio last printed for its main
|
|
14254
|
+
// view, written as it's printed, and goes when Studio stops. In dual editor mode a URL without its
|
|
14255
|
+
// workspace doesn't open Studio, so none is written until there is one. A launch that waited for the
|
|
14256
|
+
// browser while Studio was stopped and started again writes nothing: its URL is the old server's (Astra, candidate 119).
|
|
14257
|
+
const studioUrlFile = createStudioUrlFile(process.env);
|
|
14258
|
+
const studioMainUrlReady = () => !STUDIO_DOCUMENT_HOSTING_ENABLED || Boolean(studioBufferStateStore.activeHostingWorkspaces("full")[0] || lastHostedFullWorkspaceId);
|
|
14259
|
+
const publishStudioUrlFile = (url: string, state: StudioServerState, ctx: ExtensionCommandContext | null): boolean => {
|
|
14260
|
+
if (!studioUrlFile || serverState !== state || !studioMainUrlReady()) return false;
|
|
14261
|
+
const result = studioUrlFile.publish(url);
|
|
14262
|
+
if (!result.ok) ctx?.ui.notify(`Studio couldn't write its URL to ${STUDIO_URL_FILE_ENV} (${result.path}): ${result.message}.`, "warning");
|
|
14263
|
+
return result.ok;
|
|
14264
|
+
};
|
|
14249
14265
|
let studioCwd = process.cwd();
|
|
14250
14266
|
let lastCommandCtx: ExtensionCommandContext | null = null;
|
|
14251
14267
|
let latestModelRequestCtx: StudioModelRequestContext | null = null;
|
|
@@ -14278,38 +14294,60 @@ export default function (pi: ExtensionAPI) {
|
|
|
14278
14294
|
percent: null,
|
|
14279
14295
|
};
|
|
14280
14296
|
// The selected REPL session, the count of explicit actions and `shown`.
|
|
14281
|
-
|
|
14297
|
+
// pi-repl's view of its own sessions, when it's loaded too and reports (studio-repl-activity.js,
|
|
14298
|
+
// D5): told what Studio's pane shows whenever that changes.
|
|
14299
|
+
const piReplActivity = createPiReplRecordActivityLink(pi.events);
|
|
14300
|
+
const studioReplSelection = createReplSelection<StudioReplSessionInfo>({ onChange: (session) => piReplActivity.pane(session?.sessionName ?? null) });
|
|
14282
14301
|
// What Studio's agent has been told of its REPL sessions' records (PANE-AWARENESS-DESIGN.md,
|
|
14283
14302
|
// draft 3, after D5 of the shared design for people's sends). Read when Studio loads.
|
|
14284
14303
|
const replActivityMode = recordActivityMode();
|
|
14285
14304
|
const replActivity = createReplActivityState();
|
|
14286
14305
|
// The session showing in Studio's REPL pane, where the person's Quick sends go, and those
|
|
14287
14306
|
// this conversation has sent to or named.
|
|
14288
|
-
|
|
14289
|
-
|
|
14307
|
+
// While pi-repl reports, its own sessions are its to report.
|
|
14308
|
+
const replActivitySessionNames = (leaveToPiRepl = false): string[] => [...new Set(
|
|
14309
|
+
[studioReplSelection.session?.sessionName, ...replActivity.used].filter((name): name is string => Boolean(name) && !(leaveToPiRepl && isPiReplSessionName(name))),
|
|
14290
14310
|
)];
|
|
14311
|
+
// A session this conversation sent to or named, for Studio's reports and pi-repl's.
|
|
14312
|
+
const useReplActivitySession = (sessionName: string) => {
|
|
14313
|
+
replActivity.used.add(sessionName);
|
|
14314
|
+
piReplActivity.used(sessionName);
|
|
14315
|
+
};
|
|
14291
14316
|
// The report a tool result carries, held until its text is seen in what the model is given.
|
|
14292
14317
|
// The agent's own send isn't reported back to it, but is marked as told in the version its
|
|
14293
|
-
// result shows, once that result's text (`own.text`) is seen too.
|
|
14294
|
-
|
|
14318
|
+
// result shows, once that result's text (`own.text`) is seen too. While pi-repl reports, its
|
|
14319
|
+
// report of its own sessions comes first, in the room Studio's report of the rest leaves.
|
|
14320
|
+
const prepareReplActivityForResult = async (toolCallId: string, ownSend?: { sessionName: string; id: string; text: string; status: string }, budget = REPL_ACTIVITY_RESULT_BUDGET): Promise<string> => {
|
|
14295
14321
|
if (replActivityMode === "off") return "";
|
|
14322
|
+
const leaveToPiRepl = piReplActivity.reports();
|
|
14323
|
+
const toPiRepl = Boolean(ownSend && leaveToPiRepl && isPiReplSessionName(ownSend.sessionName));
|
|
14324
|
+
const own = toPiRepl ? undefined : ownSend;
|
|
14325
|
+
let studioReport = "";
|
|
14296
14326
|
try {
|
|
14297
|
-
const names = replActivitySessionNames();
|
|
14298
|
-
if (
|
|
14299
|
-
|
|
14300
|
-
|
|
14301
|
-
|
|
14302
|
-
|
|
14303
|
-
|
|
14304
|
-
|
|
14305
|
-
|
|
14306
|
-
|
|
14307
|
-
|
|
14308
|
-
|
|
14327
|
+
const names = replActivitySessionNames(leaveToPiRepl);
|
|
14328
|
+
if (names.length) {
|
|
14329
|
+
const observations = await observeStudioReplActivity(names);
|
|
14330
|
+
const observedOwn = own ? observations.find((observed) => observed.ok && observed.sessionName === own.sessionName) : undefined;
|
|
14331
|
+
const ownEntry = observedOwn?.ok ? observedOwn.record.entries.find((entry) => entry.id === own?.id) : undefined;
|
|
14332
|
+
const report = buildReplActivityReport(replActivity, observations, {
|
|
14333
|
+
budget,
|
|
14334
|
+
exclude: new Set(own ? [own.id] : []),
|
|
14335
|
+
own: own && ownEntry ? [{ sessionName: own.sessionName, id: own.id, version: replEntryVersion(ownEntry), text: own.text }] : [],
|
|
14336
|
+
});
|
|
14337
|
+
holdReplActivityCommit(replActivity, `tool:${toolCallId}`, report.commit);
|
|
14338
|
+
studioReport = report.text;
|
|
14339
|
+
}
|
|
14309
14340
|
} catch {
|
|
14310
14341
|
// The tool's own result stands without it.
|
|
14311
|
-
return "";
|
|
14312
14342
|
}
|
|
14343
|
+
const piReplReport = leaveToPiRepl
|
|
14344
|
+
? await piReplActivity.report({
|
|
14345
|
+
budget: budget - (studioReport ? studioReport.length + 2 : 0),
|
|
14346
|
+
cwd: process.cwd(),
|
|
14347
|
+
own: toPiRepl && ownSend ? { sessionName: ownSend.sessionName, id: ownSend.id, text: ownSend.text, shown: [ownSend.status] } : undefined,
|
|
14348
|
+
})
|
|
14349
|
+
: "";
|
|
14350
|
+
return [piReplReport, studioReport].filter(Boolean).join("\n\n");
|
|
14313
14351
|
};
|
|
14314
14352
|
const REPL_ACTIVITY_GUIDELINES = replActivityMode === "off" ? [] : [
|
|
14315
14353
|
"Studio tells you about new entries in its REPL sessions' shared records (the user's sends and notes, other agents', pi-repl's)"
|
|
@@ -14431,7 +14469,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
14431
14469
|
parameters: STUDIO_REPL_STATUS_TOOL_PARAMS,
|
|
14432
14470
|
async execute(toolCallId, params) {
|
|
14433
14471
|
const selected = selectStudioReplSessionForTool({ sessionName: params.sessionName, target: params.target });
|
|
14434
|
-
if (params.sessionName && selected.session?.sessionName === params.sessionName)
|
|
14472
|
+
if (params.sessionName && selected.session?.sessionName === params.sessionName) useReplActivitySession(params.sessionName);
|
|
14435
14473
|
const recordEntries = selected.session ? getStudioReplJournalEntries(selected.session.sessionName) : [];
|
|
14436
14474
|
const lines = [
|
|
14437
14475
|
`Active Studio REPL: ${studioReplSelection.session?.sessionName || "none"}`,
|
|
@@ -14531,7 +14569,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
14531
14569
|
// The agent's send is an explicit choice when admitted, before it waits for the
|
|
14532
14570
|
// session's lease; only a ticket still current lets its result select (Sol, Astra).
|
|
14533
14571
|
const ticket = studioReplSelection.choose({ session: selected.session });
|
|
14534
|
-
|
|
14572
|
+
useReplActivitySession(selected.session.sessionName);
|
|
14535
14573
|
// Every exit after admission tells the pages Studio's selection: the result when
|
|
14536
14574
|
// it selects, otherwise a repl_state, so a failure can't leave them behind (Sol).
|
|
14537
14575
|
let published = false;
|
|
@@ -14690,7 +14728,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
14690
14728
|
} : {}),
|
|
14691
14729
|
});
|
|
14692
14730
|
// What else the session's record holds that the agent hasn't been told, before its own result.
|
|
14693
|
-
const activity = await prepareReplActivityForResult(toolCallId, { sessionName: currentSession.sessionName, id: journalEntry.id, text });
|
|
14731
|
+
const activity = await prepareReplActivityForResult(toolCallId, { sessionName: currentSession.sessionName, id: journalEntry.id, text, status: journalEntry.status });
|
|
14694
14732
|
return {
|
|
14695
14733
|
content: [{ type: "text", text: activity ? `${activity}\n\n${text}` : text }],
|
|
14696
14734
|
details: {
|
|
@@ -20478,7 +20516,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
20478
20516
|
const state = await startServerNow(port, listenAll, token);
|
|
20479
20517
|
if (state.token !== token) throw new Error("another Studio server started first");
|
|
20480
20518
|
lastCommandCtx?.ui.notify(`Studio switched to ${label}.`, "info");
|
|
20481
|
-
if (pendingEditorModeLanding)
|
|
20519
|
+
if (pendingEditorModeLanding) {
|
|
20520
|
+
const url = `http://${STUDIO_ADVERTISED_HOST}:${state.port}${pendingEditorModeLanding.path}`;
|
|
20521
|
+
publishStudioUrlFile(url, state, lastCommandCtx);
|
|
20522
|
+
lastCommandCtx?.ui.notify(`Studio URL: ${url}`, "info");
|
|
20523
|
+
}
|
|
20482
20524
|
return state;
|
|
20483
20525
|
} catch (error) {
|
|
20484
20526
|
lastCommandCtx?.ui.notify(`Studio is now in ${label}, but it couldn't restart${port ? ` on port ${port}` : ""}: ${error instanceof Error ? error.message : String(error)}. Run /studio to open it.`, "error");
|
|
@@ -20542,6 +20584,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
20542
20584
|
} catch (error) {
|
|
20543
20585
|
ctx.ui.notify(`Browser opening failed; the workspace is kept: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
20544
20586
|
} finally {
|
|
20587
|
+
publishStudioUrlFile(url, state, ctx);
|
|
20545
20588
|
ctx.ui.notify(`Studio URL: ${url}`, "info");
|
|
20546
20589
|
const hint = state.listenAll ? null : buildStudioSshTunnelHint(state.port, url)
|
|
20547
20590
|
?? (flags.noBrowser ? buildStudioForwardingHint(state.port, url, { prefix: "Browser auto-open was skipped because --no-browser was used." }) : null);
|
|
@@ -20577,6 +20620,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
20577
20620
|
|
|
20578
20621
|
const state = serverState;
|
|
20579
20622
|
serverState = null;
|
|
20623
|
+
const urlFile = studioUrlFile?.clear();
|
|
20624
|
+
if (urlFile && !urlFile.ok) lastCommandCtx?.ui.notify(`Studio couldn't remove its URL file (${urlFile.path}): ${urlFile.message}.`, "warning");
|
|
20580
20625
|
|
|
20581
20626
|
await new Promise<void>((resolve) => {
|
|
20582
20627
|
state.wsServer.close(() => resolve());
|
|
@@ -21069,7 +21114,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21069
21114
|
pi.on("before_agent_start", async () => {
|
|
21070
21115
|
if (replActivityMode !== "on") return undefined;
|
|
21071
21116
|
try {
|
|
21072
|
-
const names = replActivitySessionNames();
|
|
21117
|
+
const names = replActivitySessionNames(piReplActivity.reports());
|
|
21073
21118
|
if (!names.length) return undefined;
|
|
21074
21119
|
const report = buildReplActivityReport(replActivity, await observeStudioReplActivity(names), { budget: REPL_ACTIVITY_RUN_START_BUDGET });
|
|
21075
21120
|
if (!report.text) return undefined;
|
|
@@ -21527,7 +21572,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
21527
21572
|
) => {
|
|
21528
21573
|
if (hasConnectedFullStudioView() && serverState) {
|
|
21529
21574
|
ctx.ui.notify("The existing full Studio was kept. Use its opening controls, or /studio-replace to move it here if you can't find it.", "warning");
|
|
21530
|
-
|
|
21575
|
+
const kept = currentFullStudioUrl(serverState);
|
|
21576
|
+
publishStudioUrlFile(kept, serverState, ctx);
|
|
21577
|
+
ctx.ui.notify(`Studio URL: ${kept}`, "info");
|
|
21531
21578
|
return;
|
|
21532
21579
|
}
|
|
21533
21580
|
// Oliver, 14 Oct: plain /studio reopens the last workspace when its tab is gone, asking to
|
|
@@ -21543,6 +21590,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21543
21590
|
} catch (error) {
|
|
21544
21591
|
ctx.ui.notify(`Browser opening failed; the workspace is kept: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
21545
21592
|
} finally {
|
|
21593
|
+
publishStudioUrlFile(url, state, ctx);
|
|
21546
21594
|
ctx.ui.notify(`Studio URL: ${url}`, "info");
|
|
21547
21595
|
const hint = state.listenAll ? null : buildStudioSshTunnelHint(state.port, url)
|
|
21548
21596
|
?? (flags.noBrowser ? buildStudioForwardingHint(state.port, url, { prefix: "Browser auto-open was skipped because --no-browser was used." }) : null);
|
|
@@ -21590,6 +21638,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21590
21638
|
} catch (error) {
|
|
21591
21639
|
ctx.ui.notify(`Browser opening failed; the same workspace is retained: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
21592
21640
|
} finally {
|
|
21641
|
+
if (owner.mode === "full") publishStudioUrlFile(url, state, ctx);
|
|
21593
21642
|
ctx.ui.notify(`Studio URL: ${url}`, "info");
|
|
21594
21643
|
const hint = state.listenAll ? null : buildStudioSshTunnelHint(state.port, url)
|
|
21595
21644
|
?? (flags.noBrowser ? buildStudioForwardingHint(state.port, url, { prefix: "Browser auto-open was skipped because --no-browser was used." }) : null);
|
|
@@ -21725,6 +21774,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21725
21774
|
: "A full pi Studio view is already open for this session. Close it first, use /studio-replace for a fresh full Studio view, or use /studio-editor-only for a concurrent editor-only Studio view.", "warning");
|
|
21726
21775
|
if (serverState) {
|
|
21727
21776
|
const url = currentFullStudioUrl(serverState);
|
|
21777
|
+
publishStudioUrlFile(url, serverState, ctx);
|
|
21728
21778
|
ctx.ui.notify(`Studio URL: ${url}`, "info");
|
|
21729
21779
|
const tunnelHint = serverState.listenAll
|
|
21730
21780
|
? null
|
|
@@ -21822,6 +21872,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21822
21872
|
ctx.ui.notify(`Failed to open browser: ${message}`, "error");
|
|
21823
21873
|
}
|
|
21824
21874
|
} finally {
|
|
21875
|
+
if (launchMode === "full") publishStudioUrlFile(url, state, ctx);
|
|
21825
21876
|
ctx.ui.notify(`Studio URL: ${url}`, "info");
|
|
21826
21877
|
if (tunnelHint) ctx.ui.notify(tunnelHint, "info");
|
|
21827
21878
|
if (state.listenAll) ctx.ui.notify(buildStudioListenAllWarning(state.port, url), "warning");
|
|
@@ -21846,16 +21897,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
21846
21897
|
}
|
|
21847
21898
|
const counts = getStudioClientCounts();
|
|
21848
21899
|
const url = currentFullStudioUrl(serverState);
|
|
21900
|
+
const filed = publishStudioUrlFile(url, serverState, ctx);
|
|
21849
21901
|
ctx.ui.notify(
|
|
21850
21902
|
`Studio running at ${url} (listening on ${serverState.bindHost}:${serverState.port}; busy: ${isStudioBusy() ? "yes" : "no"}; full views: ${counts.full}; editor-only views: ${counts.editorOnly})`,
|
|
21851
21903
|
"info",
|
|
21852
21904
|
);
|
|
21905
|
+
if (filed && studioUrlFile) ctx.ui.notify(`Studio URL file: ${studioUrlFile.path}`, "info");
|
|
21853
21906
|
const sshTunnelHint = serverState.listenAll ? null : buildStudioSshTunnelHint(serverState.port, url);
|
|
21854
21907
|
if (sshTunnelHint) ctx.ui.notify(sshTunnelHint, "info");
|
|
21855
21908
|
if (serverState.listenAll) ctx.ui.notify(buildStudioListenAllWarning(serverState.port, url), "warning");
|
|
21856
21909
|
return;
|
|
21857
21910
|
}
|
|
21858
21911
|
|
|
21912
|
+
// The URL --status prints, on the clipboard: for a terminal too narrow to show it whole.
|
|
21913
|
+
if (trimmed === "copy-url" || trimmed === "--copy-url") {
|
|
21914
|
+
const state = serverState;
|
|
21915
|
+
const result = await copyStudioUrl({ mode: ctx.mode, running: Boolean(state), url: state && studioMainUrlReady() ? currentFullStudioUrl(state) : null, copy: copyToClipboard });
|
|
21916
|
+
ctx.ui.notify(result.message, result.ok ? "info" : "warning");
|
|
21917
|
+
return;
|
|
21918
|
+
}
|
|
21919
|
+
|
|
21859
21920
|
if (trimmed === "help" || trimmed === "--help" || trimmed === "-h") {
|
|
21860
21921
|
ctx.ui.notify(
|
|
21861
21922
|
"Usage: /studio [path|--blank|--last]\n"
|
|
@@ -21869,6 +21930,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
21869
21930
|
+ " /studio --listen-all Explicitly bind to 0.0.0.0 instead of localhost (security-sensitive)\n"
|
|
21870
21931
|
+ " /studio --open-remote Over SSH, open the remote browser anyway\n"
|
|
21871
21932
|
+ " /studio --status Show studio status\n"
|
|
21933
|
+
+ " /studio --copy-url Copy the running Studio's URL to the clipboard\n"
|
|
21872
21934
|
+ " /studio --stop Stop studio server\n"
|
|
21873
21935
|
+ " /studio --single Use single editor mode (one editor), and remember it\n"
|
|
21874
21936
|
+ " /studio --dual Use dual editor mode (Prompt and Document), the default\n"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-studio",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.11",
|
|
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",
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// /studio --copy-url: the main view's URL on the clipboard, for a terminal too narrow to show it
|
|
2
|
+
// whole. Pi's copyToClipboard writes the system clipboard and, over SSH, also the terminal's own
|
|
3
|
+
// (OSC 52) through standard output, which in RPC, JSON and print modes carries Pi's output: only
|
|
4
|
+
// Pi's terminal interface copies. A Pi that doesn't say its mode copies nothing either; ctx.mode
|
|
5
|
+
// predates the Pi features Studio needs (Astra, candidate 119). RPC clients get the URL in
|
|
6
|
+
// Studio's notifications.
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {{ mode?: string, running: boolean, url: string | null, copy: (text: string) => Promise<void> }} options
|
|
10
|
+
* @returns {Promise<{ ok: boolean, message: string }>}
|
|
11
|
+
*/
|
|
12
|
+
export async function copyStudioUrl({ mode, running, url, copy }) {
|
|
13
|
+
if (mode !== "tui") return { ok: false, message: "Copying the URL needs Pi's terminal interface. /studio --status prints it." };
|
|
14
|
+
if (!running) return { ok: false, message: "Studio isn't running. Run /studio first." };
|
|
15
|
+
if (!url) return { ok: false, message: "Studio has no main view yet. Run /studio first." };
|
|
16
|
+
try {
|
|
17
|
+
await copy(url);
|
|
18
|
+
return { ok: true, message: "Copied Studio's URL." };
|
|
19
|
+
} catch (error) {
|
|
20
|
+
const reason = String(error instanceof Error ? error.message : error).replace(/\.$/, "");
|
|
21
|
+
return { ok: false, message: `Couldn't copy Studio's URL: ${reason}. /studio --status prints it.` };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -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"
|
|
@@ -32,8 +32,13 @@ const sameSelection = (left, right) => (left.session || right.session
|
|
|
32
32
|
? sameReplSessionLifetime(left.session, right.session)
|
|
33
33
|
: left.runtime === right.runtime);
|
|
34
34
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/**
|
|
36
|
+
* `onChange`, when given, is called with the selected session (or null) whenever the selection
|
|
37
|
+
* changes, such as to tell pi-repl what Studio's pane shows (candidate 118).
|
|
38
|
+
* @template {ReplSessionLifetime} S
|
|
39
|
+
* @param {{ onChange?: (session: S | null) => void }} [options]
|
|
40
|
+
*/
|
|
41
|
+
export function createReplSelection({ onChange } = {}) {
|
|
37
42
|
/** @type {{ session?: S, runtime?: string | null }} */
|
|
38
43
|
let selected = { runtime: null };
|
|
39
44
|
let shown = 0;
|
|
@@ -44,8 +49,10 @@ export function createReplSelection() {
|
|
|
44
49
|
/** @param {{ session?: S | null, runtime?: string | null }} target */
|
|
45
50
|
const show = (target) => {
|
|
46
51
|
const next = toSelection(target);
|
|
47
|
-
|
|
52
|
+
const changed = !sameSelection(selected, next);
|
|
53
|
+
if (changed) shown += 1;
|
|
48
54
|
selected = next;
|
|
55
|
+
if (changed) onChange?.(selected.session ?? null);
|
|
49
56
|
};
|
|
50
57
|
|
|
51
58
|
return {
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Studio's URL in a file a program can read, for a script, an editor or a container that opens
|
|
2
|
+
// Studio without anyone copying the URL out of a terminal (issue #7). Opt-in: nothing is written
|
|
3
|
+
// unless PI_STUDIO_URL_FILE names a file, and it comes from Pi's own environment, so each Pi
|
|
4
|
+
// process can be given its own file. The file holds the same credential the terminal prints.
|
|
5
|
+
//
|
|
6
|
+
// Everything here is synchronous: in one process a write and a clear can't overlap, so a stop
|
|
7
|
+
// can't be overtaken by a write that was still on its way. Whether a write's URL is still the
|
|
8
|
+
// running server's is the caller's to check.
|
|
9
|
+
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
import * as nodeFs from "node:fs";
|
|
12
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
13
|
+
|
|
14
|
+
export const STUDIO_URL_FILE_ENV = "PI_STUDIO_URL_FILE";
|
|
15
|
+
|
|
16
|
+
/** @typedef {{ ok: true, path: string } | { ok: false, path: string, message: string }} StudioUrlFileResult */
|
|
17
|
+
|
|
18
|
+
const errorText = (error) => error && typeof error === "object" && typeof error.code === "string"
|
|
19
|
+
? ({ ENOENT: "its folder doesn't exist", EACCES: "permission denied", EPERM: "permission denied", EISDIR: "it's a folder", EROFS: "the file system is read-only" }[error.code] ?? error.code)
|
|
20
|
+
: String(error?.message ?? error);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The URL file this process writes, or null when PI_STUDIO_URL_FILE isn't set.
|
|
24
|
+
* publish(url) puts the URL there; clear() removes it if it still holds what this process wrote.
|
|
25
|
+
* Neither throws: each returns { ok, path, message? }. Removal is best effort: a crash, or a
|
|
26
|
+
* removal that fails, leaves the file, whose token stops working with its server.
|
|
27
|
+
* options.fs replaces file functions, for tests.
|
|
28
|
+
*/
|
|
29
|
+
export function createStudioUrlFile(env = process.env, options = {}) {
|
|
30
|
+
const path = env?.[STUDIO_URL_FILE_ENV];
|
|
31
|
+
if (typeof path !== "string" || path === "") return null;
|
|
32
|
+
const platform = options.platform ?? process.platform;
|
|
33
|
+
const fs = { ...nodeFs, ...options.fs };
|
|
34
|
+
// What this process last wrote, so it removes only its own URL.
|
|
35
|
+
let written = null;
|
|
36
|
+
/** @returns {StudioUrlFileResult} */
|
|
37
|
+
const fail = (message) => ({ ok: false, path, message });
|
|
38
|
+
/** @returns {StudioUrlFileResult} */
|
|
39
|
+
const done = () => ({ ok: true, path });
|
|
40
|
+
|
|
41
|
+
/** @param {string} url @returns {StudioUrlFileResult} */
|
|
42
|
+
const publish = (url) => {
|
|
43
|
+
if (!isAbsolute(path)) return fail("it isn't an absolute path");
|
|
44
|
+
if (typeof url !== "string" || !url || /[\u0000-\u001f\u007f]/.test(url)) return fail("the URL isn't one line of text");
|
|
45
|
+
try {
|
|
46
|
+
// A link, a folder or a device there isn't replaced.
|
|
47
|
+
if (!fs.lstatSync(path).isFile()) return fail("something other than a file is there");
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error?.code !== "ENOENT") return fail(errorText(error));
|
|
50
|
+
}
|
|
51
|
+
const text = `${url}\n`;
|
|
52
|
+
// Private from its first byte: a new file beside the target, opened only if it doesn't
|
|
53
|
+
// exist, then renamed over the target, so a reader sees the old URL or the new one.
|
|
54
|
+
let temporary = null, descriptor = null;
|
|
55
|
+
try {
|
|
56
|
+
temporary = join(dirname(path), `.${basename(path)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
57
|
+
descriptor = fs.openSync(temporary, "wx", 0o600);
|
|
58
|
+
if (platform !== "win32") fs.fchmodSync(descriptor, 0o600);
|
|
59
|
+
fs.writeFileSync(descriptor, text, "utf8");
|
|
60
|
+
fs.closeSync(descriptor);
|
|
61
|
+
descriptor = null;
|
|
62
|
+
fs.renameSync(temporary, path);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (descriptor !== null) { try { fs.closeSync(descriptor); } catch {} }
|
|
65
|
+
if (temporary !== null) { try { fs.unlinkSync(temporary); } catch {} }
|
|
66
|
+
return fail(errorText(error));
|
|
67
|
+
}
|
|
68
|
+
written = text;
|
|
69
|
+
return done();
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** @returns {StudioUrlFileResult} */
|
|
73
|
+
const clear = () => {
|
|
74
|
+
if (written === null) return done();
|
|
75
|
+
const mine = written;
|
|
76
|
+
written = null;
|
|
77
|
+
try {
|
|
78
|
+
// A path given to another process too may hold its URL now: leave it.
|
|
79
|
+
if (!fs.lstatSync(path).isFile() || fs.readFileSync(path, "utf8") !== mine) return done();
|
|
80
|
+
fs.unlinkSync(path);
|
|
81
|
+
return done();
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return error?.code === "ENOENT" ? done() : fail(errorText(error));
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return { path, publish, clear };
|
|
88
|
+
}
|