pi-pocket 0.27.0-beta.3 → 0.27.0-beta.5

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/docs/features.md CHANGED
@@ -15,6 +15,7 @@ The full tour. For setup, see the [README](../README.md).
15
15
  - **Keyboard.** Alt+1…9 jumps to a session (hold Alt to see the numbers), Alt+↑/↓ goes to the previous or next one, Alt+N starts a new one (where Ctrl/⌘+1…9 starts it in a favorite folder), Alt+B opens or closes the browser, Alt+E the Files tile, Alt+T turns Show thinking on or off, Alt+V starts or stops dictation, and `?` lists every shortcut. On a computer, a session opens with the caret in its message box, ready to type; on a touch screen it waits for a tap, so the keyboard does not cover the conversation, and on a Mac a session opened with Alt+1…9 or Alt+↑/↓ leaves the box alone, so the next Alt shortcut still works (Option types characters in a box).
16
16
  - **The conversation.** A column of turns, made for phones. Your messages are cards with the sender's avatar (the accent for yours, the sender's color for someone else's), who sent each and when; Pi's replies are plain prose at Appearance's text size, streamed as they come (lists keep a quiet marker column; code, tables, and rich blocks are rounded cards). The **Message time** item under completed replies shows the time, with the date for earlier days, and can be hidden or moved in Appearance → Layout. What Pi does between its words, its thinking and tool calls, folds into one line that says what it did and for how long ("Thought, searched, read 2 files, ran 1 command · 18s"), and opens, as a card, into a timeline: a line per call with a circle for how it went (✓ done, × failed or denied, ! waiting for an approval, a spinner while it runs, ⑂ for a subagent, ✦ for a thought) and what it came to (lines added and removed, lines read, matches, tests passed, an exit code, "needs approval"), and tapped, its input and output, with the diff viewer's diffs for edits (line numbers, syntax colors, and the words that changed) and bash's live output. The newest turn's groups are open and earlier ones closed, unless Appearance's **Keep activity folded** (off by default) keeps them on their line until you open one; a thought alone still follows Show thinking. An approval is a card at the end of its turn (the command, the reason, Deny and Allow; once answered, the call's line says who allowed or denied it), and while Pi works one line, a pulsing dot with the state in the accent (the warning color while it waits for an approval), says what it does (thinking, working, waiting for an approval, retrying) and for how long. With **Show thinking** on in Appearance (or Alt+T, or the launcher), the current thought shows above that line as it streams, and the thoughts in the conversation show their words once written (a thought alone in its group opens, and one on a timeline opens its step). A chevron before the line's dot folds the live thought away, and again brings it back. Alt+T shows a short on/off notice, even while Pi is idle. During tool calls the latest thought stays; a new response clears it until the model shares new thinking. Models that share none say so, rather than showing an old thought as current. A fold holds in that session, also over a reload, until you open it again; the setting is off until you turn it on, in each browser, and while it is off or folded the live thought is neither selected nor drawn. The reading area follows new words until you scroll up in it, and follows again for each new thought. While Pi works, **Steer**, **Queue**, or **Interrupt** beside the model chip says whether a message steers the run, waits for it to end, or stops the run at once (the tool call too, as Stop does, which also withdraws what waits in the queue) and is sent after; Interrupt goes back to Steer after one use, or when Pi stops before it was used, while Steer and Queue stay as chosen; queued messages can be withdrawn, and your own, tapped open, can go back into the message box to change (**Edit**: its words above what you were typing, on a line of their own, with its files), move to Queue or Steer until Pi reads it, or go now as an Interrupt (a second tap confirms; `CONFIRM_INTERRUPT` in `web/composer.js` turns that off): that stops the run and sends only that message, while every other queued message, from everyone, stays queued in its order with its sender and mode (a restart in between loses or repeats none), and so do subagents' reports; with take turns on, moving one to Steer or Interrupt waits for your turn at the wheel, as sending does; Stop (or Esc twice) stops the run. A run stopped in the middle of a tool call ends with a "Stopped." line under its card.
17
17
  - **Getting around on a phone, with one hand.** Back (the swipe, Android's back button, the browser's) goes back to where you were: it closes what opened last (a sheet, the menu's next sheet back to the menu, a file back to the Files tree, back to Changes when the file was opened from there, the Files tile or the Browser panel, the drawer) before it leaves the session, and leaving goes to the session before or to the list, scrolled and searched as you left it. A session opened straight away (a link, a notification) has the list under it, so back does not leave the app. What you use most is a thumb's reach from the bottom edge: the button beside the message box (or a swipe up from it) opens the places, a short sheet of big tiles (Files, Changes, Browser, Artifacts, Chat, Find, Branch, Peeks) with the session menu below them. On the conversation, swipe left for Files and right to go back; in Files, swipe right to go back. Each swipe shows a mark that lights when letting go will act. The top bar leads back to the list (counting other sessions that wait for an approval) and keeps only the buttons with something to say. Every control is a thumb's size on a touch screen (small ones, such as a code block's Copy or a reply's Pin, keep their look and take a wider tap); a tap anywhere on the message box, off its one line of text, still goes to the text; a quick second tap does not land on whatever just slid in under it; tables in replies scroll sideways instead of crushing their columns; a diff's header keeps the file's name on a line of its own on a phone; and the command a peek tile asks about opens its session when tapped. The Files tile and the browser slide in as screens of their own and slide away on back, a file slides in over the tree, and the browser's tools sit on their own row under the address. Drag a sheet down, or the drawer left, to close it. In an iPhone home screen app, which has no back gesture of its own, swipe in from the left edge to go back.
18
+ - **Reply to a passage.** Select words in one of Pi's replies, on a phone or a desktop, and a **Reply** button appears by the selection (below it on a touch screen, where the system's menu sits above). It puts the passage in a quote strip above the message box (tap × to drop it); the next message goes to Pi with the passage first as a Markdown quote (up to 1,500 characters), and shows in the conversation as a quote block above your words.
18
19
  - **Forks.** Tap Pi's reply → More → **Fork from here**: a new session with everything up to that reply, which then goes its own way. Tap one of your messages to **edit it and send it again**, or send any message again, to the same model or another one (a retry). Each makes a new session that forks just before the message; the original stays as it is. A fork gets its own chat (with the pins of what it inherited), a link back to where it came from, and optionally a git worktree of its own.
19
20
  - **A new context.** Menu → **New context** (or `/reset [note]`): Pi starts fresh and no longer sees the messages so far, while everyone still does. An optional handoff note carries over what matters.
20
21
  - **Instructions for Pi.** Menu → **Instructions for Pi** (or `/instructions …`): ground rules Pi gets with every message in this session, such as "use pnpm, not npm". Everyone in the session can see them.
@@ -68,7 +69,7 @@ The full tour. For setup, see the [README](../README.md).
68
69
  - **Tweaks.** A page can declare knobs (colors, sizes, choices, switches) and the Tweaks tab shows them as controls that change the page live. Values are each person's own, kept for each design. **Keep these** puts them in the message box so that Pi writes them into the design.
69
70
  - **Variations.** Artifacts of one group show as a grid of live thumbnails. **Use this one** puts a message about it in the message box.
70
71
  - **Export and share.** PNG, PDF, PPTX (decks), and an HTML zip, from the menu. The file is written in the session's `exports/` folder and the browser downloads it. **Share a link** is the artifact viewer's Share. There is no Canva export.
71
- - **What Pi does.** Its guide (a prompt section, only while the module is on) gives Pi a page skeleton and craft rules: one HTML artifact for each design, `data-pid` on meaningful elements, a tweaks manifest of 3 to 8 knobs bound to the system's tokens, assets for images and fonts, variations as a group of 2 to 4 artifacts, a link to `ds/tokens.css` when the project has a design system, and a check with `design_preview` before it replies. When the project has a system, the guide carries a summary of it (roles and components first) as untrusted project data. Its tools: `design_preview` renders a version in a private headless Chromium (never the browser people watch) at mobile and desktop sizes, or the sizes asked for, and returns screenshots and a short report (see **Checks**); its options are `checks` (on by default), `tweaks`, `colorScheme`, `page` (another page of the bundle), and `actions` (hover, click, or focus on a selector before the screenshot). `design_export` writes PNG, PDF, PPTX, or an HTML zip, by default as `exports/<id>-v<version>.<ext>`, and refuses a path outside the session's folder; it also takes `tweaks`, a custom `viewport`, and, for a deck's PNG, `slide` (a number, or `"all"` for a zip of every slide). A page's PDF is as wide as its viewport, and PPTX slide images have twice the pixels. `design_system` reads, scans, and changes the project's design system (see **The design system**). The private renderer serves the bundle on a loopback address under a random path and gives Chromium no sign-in; other requests go through `host.fetchPublic`, so a design reaches only public addresses. Renders run 2 at once, and more wait their turn; each has 90 seconds.
72
+ - **What Pi does.** Its guide (a prompt section, only while the module is on) gives Pi an order of work, after Claude Design's (since 0.27.0): one round of questions when the work is new or unclear, then a start from what exists (the design system, the code, the screens) rather than a mock from scratch, a first version early, iterations, a check, and a short reply. A screen that exists is redesigned from itself: Pi reads its code and data first, makes version 1 the screen as it is today (in its place in the app, compared with a screenshot of the real one when it can get one), and then changes it in new versions, within what the code supports; a change that needs new data or server work is marked in the design and named in the reply, and a different direction becomes a new artifact in the same group. The product's own type sizes, spacing, and density win over the guide's craft defaults. It also gives Pi a page skeleton and craft rules: one HTML artifact for each design, `data-pid` on meaningful elements, a tweaks manifest of 3 to 8 knobs bound to the system's tokens, assets for images and fonts, variations as a group of 2 to 4 artifacts, a link to `ds/tokens.css` when the project has a design system, and a check with `design_preview` before it replies. When the project has a system, the guide carries a summary of it (roles and components first) as untrusted project data. Its tools: `design_preview` renders a version in a private headless Chromium (never the browser people watch) at mobile and desktop sizes, or the sizes asked for, and returns screenshots and a short report (see **Checks**); its options are `checks` (on by default), `tweaks`, `colorScheme`, `page` (another page of the bundle), and `actions` (hover, click, or focus on a selector before the screenshot). `design_export` writes PNG, PDF, PPTX, or an HTML zip, by default as `exports/<id>-v<version>.<ext>`, and refuses a path outside the session's folder; it also takes `tweaks`, a custom `viewport`, and, for a deck's PNG, `slide` (a number, or `"all"` for a zip of every slide). A page's PDF is as wide as its viewport, and PPTX slide images have twice the pixels. `design_system` reads, scans, and changes the project's design system (see **The design system**). The private renderer serves the bundle on a loopback address under a random path and gives Chromium no sign-in; other requests go through `host.fetchPublic`, so a design reaches only public addresses. Renders run 2 at once, and more wait their turn; each has 90 seconds.
72
73
  - **The design system.** A project's design system lives in `.pi/design/` in the session's folder: `tokens.json` (W3C Design Tokens, DTCG: groups, `$value`, `$type`, references such as `{color.blue.500}`, tiers for primitives, semantic roles, and component tokens), `tokens.<mode>.json` for each other mode (dark, high contrast, a brand), `components/<slug>.html` (a component specimen with its states), and `guidelines.md`. Pi Pocket checks it (broken or circular references, raw values in semantic roles, declared contrast pairs in every mode) and builds `dist/`: `tokens.css` (`:root`, a `[data-theme]` block for each mode, and a `prefers-color-scheme` block), `tailwind.css` (a Tailwind v4 `@theme`, with utilities such as `bg-surface` and `text-primary`), `tokens.<mode>.resolved.json` (DTCG, one for each mode), `tokens.studio.json` (Tokens Studio), `tokens.resolved.json` (a compact summary), and `components.css`. A design that links `ds/tokens.css`, `ds/tailwind.css`, or `ds/components.css` gets the current files as assets when Pi publishes it, a snapshot kept with that version. Pi's `design_system` tool has the actions `scan` (a structured draft from the project's style files: colors in every CSS syntax, roles, the type, spacing, and radius scales, shadows, motion, and dark mode, from CSS variables, Tailwind, SCSS, theme objects, token files such as Tokens Studio, and WordPress `theme.json`), `init` (from a scan or given tokens; it refuses to replace a system unless asked), `set`, `validate`, `compile`, `component`, `guidelines`, and the 0.26 `read` and `write`. A project with only `.pi/design-system.md` (the 0.26 format) keeps working.
73
74
  - **The System view.** The first row of the design picker (or `/design-open system`, or the launcher's "Open the design system") shows the system: **Colors** (role cards with contrast badges first, a live sample card, and the palette as ramp strips in a folded group), **Type**, **Spacing**, **Radii**, **Shadows** (each with its value), **Motion** (durations and easings that play), **Components** (every state, in a frame that runs nothing and loads nothing), and **Guidelines**. A section's count is its role tokens; the palette and component tokens show their own counts inside it. Modes show one at a time or side by side, and a mode's value says whether it is its own or inherited from the default. People who steer change a color, a size, a time, a weight, a font, an easing, or a shadow's layers in place, or link a token to another; the open design shows each change live when it uses the system's variables. The editor lists every contrast pair of a color (an exempt pair shows as exempt, not as a failure). **Undo** and **Redo** step through the changes, **Discard** gives them up, and **Save** writes the files and the generated CSS with no run of Pi (it refuses a change that the checks refuse, or one made on a system that changed meanwhile). The menu publishes the documentation page as a design, exports the generated files as a zip, and adds or removes a mode. People who only view see everything and change nothing. **Focus mode** hides the conversation for wide work. On a phone, the canvas fits the screen's width, and until a size is chosen it takes the size of its panel. The Design module loads only a small shell at app start; the workspace and the System view load when first opened.
74
75
  - **Checks.** A design's **Check** tab, `design_preview`, and `npm run design:check` (for CI: `src/server/design/check-cli.ts` on an HTML file and a `.pi/design` folder; exit 1 on an error, 2 without Chromium) render the page on the server and judge only what the author's CSS sets, never the browser's defaults. They report values that are not the system's (colors, fonts, and sizes, each with the exact CSS edit and the nearest token of the matching role), contrast (WCAG 2.2 AA, judged only where the background is certain), non-text contrast of focus rings and icon buttons (3:1), tap targets (an error under 24 px, a warning under 44 px), sideways overflow, image alt text, heading order, a missing `lang`, form controls with no label (a placeholder is not a label), links, buttons, and widgets with no accessible name, no `main` landmark, fonts that did not load, a missing viewport tag, missing `data-pid`s, elements with no visible focus style, long motion with no `prefers-reduced-motion` rule, and author-set input text under 16 px on a phone. A check runs in any mode of the system. The tab follows the mode and size on the canvas, puts a pin on each element, and **Send to Pi** puts one message with every finding in the message box. **Fix N exact matches** rewrites literals that equal a token exactly to `var(--token)` and saves a new version with no run of Pi. On a phone, the tab starts as a bar with the counts, so the page keeps most of the screen.
@@ -112,9 +113,9 @@ The full tour. For setup, see the [README](../README.md).
112
113
  - **Drop-in extensions.** Put your own extension module (a `.ts` file that default-exports `(host, web) => Extension`, or a list, or nothing) in `~/.pi-pocket/extensions/`. It shows in the Extensions sheet, stays off until the owner turns it on, can import Pi Pocket's packages (Pi Durable, pi-ai, Pi's MCP client pi-mcp, and the rest) as the built-in modules do, and reloads when edited. One that would take the name of a built-in extension or tool, or of another drop-in's, is not loaded, and the sheet says why: installing it would replace that one.
113
114
  - **Extensions in the app.** A module can add to the app itself, without changes to Pi Pocket's code: routes on the server, commands for the message box, and a browser module with buttons on the rail, pages in the conversation's place (as the subagents board shows), panels beside the conversation (where the Browser and Files panels dock, with a button in the top bar and the places), items in the status line under the message box (with a short form a narrow line takes), sheets, rows in the menu, and launcher actions, which work without asking Pi. A dashboard of a provider's usage, the server's load, or a machine's power and temperature, say: the route asks the service with a key that stays on the server, and the page shows what it says, live with the module's events. It is the owner's alone unless the module opens it to people who can steer, or to everyone who sees every session; someone invited to one session never gets it. A module can also show **public pages** to anyone with one of its links, with no sign-in (`/l/<token>`, since 0.22.0): each link closes at its time (30 days at most) or after the answers it takes, the page runs in a sandbox with no script, so whoever opens it while signed in lends it nothing, and Extensions says which modules have them ([docs/extensions/public-pages.md](extensions/public-pages.md)). Turning the module off takes away what it added, its pages included; an edit swaps the routes, and an edit to the browser module's files has tabs load it again. One that fails tells the owner why in a notice and in the Extensions sheet, and the rest of the app goes on; a tab opened with `?noext=1` loads none of their browser parts (safe mode), to turn off one that breaks the app. [docs/extensions.md](extensions/app.md) says how, with an example: a page with the server's load, memory, and uptime.
114
115
  - **Extension workspace APIs (0.16.0).** A page can save its own durable catalog with request-lifetime document commits, or use a source-bound route to start linked sessions as the person who clicked Run. Current source access, turn, plan, spend, team, and model checks apply; explicit thinking choices are not silently lowered. Human history can open authorized sessions through `pocket.openConversation`. Extensions can read the running server's package version through `host.pocketVersion` or browser `pocket.pocketVersion`, without an updater or restart control; the extension API level remains 1.
115
- - **Extensions hub.** Menu → **Extensions** opens **Discover**, **Installed**, and **Updates** for the owner while the gallery is on. Wide screens show the list and selected entry side by side; phones show one at a time, with Back returning to the filtered list. **Installed** (also tap "guard" in the status line) lists Pi Pocket's extensions with their tools, the routes, commands, and browser module they add to the app, and any load error, in this browser too. The owner can turn Artifacts, Design, Browser, Subagents, Scheduled messages, Done when, Plan mode, Codemode, Memory, PiP, Triggers, Extension gallery, Pi Pocket updates, Agent Teams, Session tags, Lancet Guard, or a drop-in off and on, or reload one; the change applies to every session at once, stays after restarts (`disabledExtensions` and `enabledExtensions` in `~/.pi-pocket/config.json`), and everyone in a session sees who changed what. Turning Lancet Guard off first shows a warning card with **Keep it on** and **Turn off**; only **Turn off** applies the change. This leaves Pi's own setting (`~/.pi/lancet-guard.json`) alone. Under PiP, the owner picks when PiP compacts its context. The system prompt cannot be turned off.
116
+ - **Extensions hub.** Menu → **Extensions** opens **Discover**, **Installed**, and **Updates**, as tabs in the sheet's head, for the owner while the gallery is on. Wide screens show the list and the selected entry side by side; phones show one at a time, with Back returning to the filtered list. The list is in sections: **Extensions** as dense rows divided by hairlines (a small mark, the name and its maker, one line about it, and up to three facts of what it reaches or adds, such as `openrouter.ai`, `a key`, `sees turns`, or `2 tools`), and **Themes** as cards, each a tiny desktop drawn in the theme's own colors with its color dots (since 0.27.0). Filters narrow Discover to **Extensions** or **Themes**, and to those with **Tools for Pi**, a part **In the app**, or ones that **Change Pi** (hooks, prompt sections, wraps). **Installed** (also tap "guard" in the status line, which opens it with **Built in** unfolded) lists your **Extensions** (from the gallery and your own drop-ins) first, each with how it stands now: **On**, **Off**, **Did not load** (with the error under it), **Off in this tab** (its browser part failed here), **Edited since install**, or **Revoked**; then your **Themes** (from the gallery, and your own, marked **Yours**, which open Appearance); then the **Built in** modules, folded under one line that says how many are on, and unfolded by a search or a module that did not load. A module's row shows its tools, the routes, commands, and browser module it adds to the app, and any load error, in this browser too. The owner can turn Artifacts, Design, Browser, Subagents, Scheduled messages, Done when, Plan mode, Codemode, Memory, PiP, Triggers, Extension gallery, Pi Pocket updates, Agent Teams, Session tags, Lancet Guard, or a drop-in off and on, or reload one; the change applies to every session at once, stays after restarts (`disabledExtensions` and `enabledExtensions` in `~/.pi-pocket/config.json`), and everyone in a session sees who changed what. Turning Lancet Guard off first shows a warning card with **Keep it on** and **Turn off**; only **Turn off** applies the change. This leaves Pi's own setting (`~/.pi/lancet-guard.json`) alone. Under PiP, the owner picks when PiP compacts its context. The system prompt cannot be turned off.
116
117
  - **Extension settings.** A module can declare settings (on or off, text, a number, a choice, or a secret such as an API key); the owner changes them in Menu → Extensions under the module, with **Save settings**, and **Default** or **Clear** to put one back. A secret's value never leaves the server: the sheet shows only that it is set. Modules can also listen to what happens in the app (sessions made, renamed, and archived, messages, runs) and offer services to each other; Extensions says which ones offer a service. Since 0.22.0 ([docs/extensions/services-settings.md](extensions/services-settings.md)).
117
- - **Extension gallery.** Menu → Extensions → **Discover** (or **Find extensions** in the launcher) lists drop-ins other people wrote, from a reviewed index ([TannerMidd/pi-pocket-extensions](https://github.com/TannerMidd/pi-pocket-extensions) unless the owner picks another): search them by name, words, and tags; entries for a newer Pi Pocket are hidden. Each row has a quiet **Install**. An entry walks through three steps, each with its buttons: **Install** (it stays off), **Look it over** (**View source**, **Ask Pi to review**), and **Turn it on**, which asks once more, in place, before code runs; what it adds shows in plain words, with technical information folded below. In Installed, a tap on a row opens its settings and details, and turning a drop-in on asks in its row. An entry shows who wrote it, where its code is (a GitHub repository at a pinned commit), its files, and what it declares: its tools (and which only read), hooks, prompt sections, wraps, routes, and browser module, and who can reach them. **Install** downloads its files over https from that commit, checks each against the SHA-256 the index pins (one that differs installs nothing), and puts them in the extensions folder, off, as every drop-in starts. Before turning it on, read its whole source in the gallery, or **Ask Pi to review**: a new session in the extensions folder, in plan mode, where Pi audits what the code reads (`config.json`, sign-ins, other secrets), the addresses it calls, the processes it starts, what its browser module does, and whether it does what it declares. Updates are never automatic: the **Updates** tab lists available updates with a **Review update** button, and the review shows what changes, as a diff of every file and of what it declares, before you apply it. When the index revokes the version you have, the gallery and Extensions say why and offer to turn it off, and a notice says so while it is on. **Uninstall** removes its files (where each came from is kept in `<name>.gallery.json` beside it). **Share…** on one of your own drop-ins in Extensions checks that it stands on its own (its files named after it, importing only Pi Pocket's packages and its own files), drafts its index entry (the description from its doc comment, each file's SHA-256, what it declares while it is on), asks where its files are on GitHub (the repository and commit you put them in, tags, your GitHub name), and, once the entry would pass the index's checks, opens GitHub's page for a pull request to the index with the entry filled in; Pi Pocket itself makes no GitHub calls. [docs/extensions.md](extensions/publishing.md) says how to publish. The owner's alone; turned off in Extensions, it reads nothing. It lists themes too, with a **Theme** tag and filter: **Install** checks a theme's pinned files and its CSS before it goes into `themes/`, and puts it in Appearance's list without applying it; **Update** shows a diff; **Remove** moves it to `themes/.removed/`; **Share…** in Appearance drafts an entry for one of your own themes ([themes.md](extensions/themes.md#themes-in-the-gallery)).
118
+ - **Extension gallery.** Menu → Extensions → **Discover** (or **Find extensions** in the launcher) lists drop-ins other people wrote, from a reviewed index ([TannerMidd/pi-pocket-extensions](https://github.com/TannerMidd/pi-pocket-extensions) unless the owner picks another): search them by name, words, and tags; entries for a newer Pi Pocket are hidden. Each row has a quiet **Install**, which installs it turned off. An entry (since 0.27.0) says **What it can reach** in plain sentences, each marked with where it comes from: **In its code** (from the scan below: "Talks to openrouter.ai", "Uses your openrouter key, from Pi", "Runs git and gh", "Uses files in its data folder"), **Declared** (the hooks it sees with, such as "Sees tool calls, before they run", and changes to Pi's instructions or tools), and **Always** (it runs in the server with your rights, in every session, where Lancet Guard does not see its code), then what the scan found nothing for. The scan reads the code's text, so the code can reach more than it finds: the entry says so, and nothing claims an extension stays inside. When the installed files were edited since install, the entry and the question say that the summary is the pinned version's, not what runs. **What it adds** shows its tools and commands as code, and what it puts in the app; technical information is folded below. **Install and turn on** asks one question over the sheet: what it reaches, with **Cancel**, **Install turned off**, and **Install and turn on** (Cancel has the focus, Escape closes only the question, and the question stays until it is installed and on); **Install turned off** installs it without asking, and an installed one that is off has **Turn on**, which asks the same question. Before turning it on, read its source with **View source**, or install it off and **Ask Pi to review**. A theme's entry shows its picture in its own colors (dark and light side by side when it has both), what it changes from its files (its colors, a layout of its own, its fonts, its images), its palette with the values, and **Use it in this browser** and **Open Appearance** once installed. In **Updates**, a row says what an update adds to what the extension declares ("Declares more: sees tool results; 2 new tools", or "Declares nothing new") before its review; its code's changes are in the review's diff. In Installed, a tap on a row opens its settings and details, and turning a drop-in on asks in its row. An entry shows who wrote it, where its code is (a GitHub repository at a pinned commit), its files, and what it declares: its tools (and which only read), hooks, prompt sections, wraps, routes, and browser module, and who can reach them. **Install** downloads its files over https from that commit, checks each against the SHA-256 the index pins (one that differs installs nothing), and puts them in the extensions folder, off, as every drop-in starts. Before turning it on, read its whole source in the gallery, or **Ask Pi to review**: a new session in the extensions folder, in plan mode, where Pi audits what the code reads (`config.json`, sign-ins, other secrets), the addresses it calls, the processes it starts, what its browser module does, and whether it does what it declares. Updates are never automatic: the **Updates** tab lists available updates with a **Review update** button, and the review shows what changes, as a diff of every file and of what it declares, before you apply it. When the index revokes the version you have, the gallery and Extensions say why and offer to turn it off, and a notice says so while it is on. **Uninstall** removes its files (where each came from is kept in `<name>.gallery.json` beside it). **Share…** on one of your own drop-ins in Extensions checks that it stands on its own (its files named after it, importing only Pi Pocket's packages and its own files), drafts its index entry (the description from its doc comment, each file's SHA-256, what it declares while it is on), asks where its files are on GitHub (the repository and commit you put them in, tags, your GitHub name), and, once the entry would pass the index's checks, opens GitHub's page for a pull request to the index with the entry filled in; Pi Pocket itself makes no GitHub calls. [docs/extensions.md](extensions/publishing.md) says how to publish. The owner's alone; turned off in Extensions, it reads nothing. It lists themes too, with a **Theme** tag and filter: **Install** checks a theme's pinned files and its CSS before it goes into `themes/`, and puts it in Appearance's list without applying it; **Update** shows a diff; **Remove** moves it to `themes/.removed/`; **Share…** in Appearance drafts an entry for one of your own themes ([themes.md](extensions/themes.md#themes-in-the-gallery)). **What an entry reaches.** `GET /api/x/gallery/reach` (the owner's, like the other gallery routes) answers `{ entries: { [name]: … } }` for every entry of the index read now, each with the entry's `pin` so the app matches a result to the exact files it shows, so the app can show what each one can reach before it is installed. An extension gives `{ kind: "extension", commit, scanned: { network, keys, programs, files } }`: short words for the hosts its address literals name (`localhost`, standards' namespaces, `example.*`, and repository pages left out; `addresses it builds at run time` when it calls `fetch(`, `new WebSocket(`, or `http.request` with no host in its code), the keys it reads (`openrouter key from Pi`, an environment variable whose name has `KEY`, `TOKEN`, or `SECRET`, `Pi's auth.json`), the programs it starts (`programs it names at run time` when it imports `child_process` but names none), and the files it writes (`its data folder`, paths under `~/.pi/agent/`, or `your home folder`). The scan is by literal patterns on the code with its comments taken out: it tells what the code says, not what it does. A theme gives `{ kind: "theme", commit, palette: { colors, colorsLight } }` from its `colors.toml` and `colors-light.toml` (`null` for one it lacks). An entry that cannot be read (a download fails, or a file differs from the size or SHA-256 the index pins) gives `{ kind, commit, error }` and fails no other entry. Only the code files (`.ts`, `.js`, `.mjs`, `.cjs`) and the two palette files are read: from the installed copy when the entry is installed at the same commit and each file is as pinned, otherwise downloaded from the pinned commit with the checks every download has. Results are kept in `gallery/reach.json` in the data folder, by entry, commit, and pinned files, so the next answer downloads nothing for them; entries that fail are tried again, and three are read at a time.
118
119
  - **Updates.** Menu → **Update Pi Pocket** (or the launcher) shows the running version, the newest release with its notes, and **Update to … and restart**; a notice says once when a new version is out. The owner's alone. Under the version, the sheet shows the checkout's branch and commit, **installed with npm (global)**, **installed with npm (local)**, or **run with npx**. For npm installs, Pi Pocket asks the npm registry's `latest` tag for the newest published version 2 minutes after the server starts and every 6 hours after, and GitHub for that version's release notes (`PI_POCKET_UPDATES_REPO` names another repository). A git checkout asks GitHub for the newest release (or the repository's version tags, without notes) and downloads its commit into the checkout under a ref of its own, `refs/pocket-update/target`. An update from a git checkout needs a checkout that the server's user can write, run by the launcher (`npm start`), with no changes that are not committed and no commits the release lacks, and a Node.js the release runs on; the sheet says which of these stands in the way, and an ignored file of yours where the release has a file stops it too. It installs the release's packages beside the checkout first (`npm ci` in `.pocket-update/staging/`, only when the lock file names other packages), stops loading edited files, puts the packages in place, moves the branch forward to the release's commit (a detached checkout moves detached), and restarts. **A global npm install** updates from the app too, when the server's user can write the folder that holds the package and the launcher runs the server: Pi Pocket installs the exact published version into a staging folder beside the package, swaps it in place of the running copy, and restarts, with the copy before kept next to it. If the machine stops at the very moment of the swap, `pi-pocket` may not start: `npm install -g pi-pocket` puts it back. A **local** npm install (in a project's `node_modules`) and a copy **run with npx** do not update from the app: the sheet lists what stands in the way, with the server's hint of what to run instead (`npm install pi-pocket@latest` in the project, or `npx pi-pocket@latest`), and the update button stays off. The owner runs the command and restarts. Running work continues through a restart, but a tool call the restart cuts off comes back as interrupted, and the sheet says when Pi works. When the new version does not start, the launcher puts the files before back and starts that (a git checkout puts the commit and packages back; a global npm install swaps the kept copy back, with no network), and the sheet and a notice say what happened; after the next look the sheet offers that version again, for the owner to try again. A release whose notes have a `[!WARNING]` or `[!CAUTION]` alert needs a tick that you read it, and is not undone by itself, since it may change data one way; so does a release whose notes Pi Pocket could not read because GitHub did not answer (the registry or the tag gave the version, with no notes), since they may have such an alert: read them on GitHub. Under Menu → Extensions → Installed → **Pi Pocket updates**: **Look for new versions** (on), **Install new versions by themselves** (off), and **Beta updates** (off). **Beta updates** (since 0.27.0) also offers pre-releases, tagged `vX.Y.Z-beta.N` (GitHub releases marked as pre-release; npm's `beta` dist-tag): a git checkout takes the highest version among GitHub's non-draft releases (or the beta tags, when GitHub does not answer), and an npm install the newer of the `latest` and `beta` dist-tags. A beta is marked **Beta** in the sheet, the menu hint, and the notice, and its caution says that it may have bugs. With the setting off nothing changes: only stable releases are offered, a beta is never offered, and a running beta still gets the next stable release (`0.27.0` is newer than `0.27.0-beta.N`, and `0.27.0-beta.2` is newer than `0.27.0-beta.1`) but never an older one. Turning it off drops a beta found before. An install by itself also takes a beta, when both settings are on. A server from before 0.27.0 needs a restart (menu → Restart server) for the setting to work. An install by itself waits until no session has worked for 10 minutes, and again after its packages install; it never takes a release with a warning or without notes, or one that failed before (did not start, or did not install). A launcher started before this feature restarts but does not go back, and cannot update a global npm install at all (the sheet says so): quit Pi Pocket and start it again once.
119
120
  - **Refresh models.** The owner can tap **Refresh models** in the menu (under App) or the Providers sheet (above Models for subagents), or run **Refresh models** from the Ctrl/⌘+K launcher. The same controls work on phones. Refresh reloads `models.json` and Pi’s sign-ins, and asks configured providers for fresh catalogs. The menu's row says when it is refreshing, and a notice gives the added and removed model counts, without closing the menu; the Providers sheet also shows the errors for individual providers. All connected tabs receive the updated list. Healthy providers finish independently of slow ones; each provider has an eight-second limit. Running sessions keep their chosen models. A local model must be configured in `models.json` or registered by a Pocket-compatible extension: refresh does not load regular Pi CLI extensions or discover arbitrary local servers.
120
121
  - **Uploads.** In normal chat and PiP, attach files with the picker, paste files or images, or drop them into the message box. Files are saved on the server for the conversation you send to and their paths are given to the agent; supported images also go straight to models that accept them.
package/docs/map.md CHANGED
@@ -171,6 +171,7 @@ The agent's side of Design mode. `extensions/design.ts` installs it (see Extensi
171
171
  | `gallery/files.ts`, `gallery/fetch.ts` | An extension's files in the drop-in folder: names checked, never through a link, a version put in place all or none with an undo journal that `recover` replays before extensions load; reading from other sites, https only, within size and time limits |
172
172
  | `gallery/diff.ts`, `gallery/share.ts` | A file's change as a unified diff, for updates; whether a drop-in stands on its own, and the draft of its entry, for Share |
173
173
  | `gallery/themes.ts` | Themes from the gallery in the data folder's `themes/`: a version written to a hidden folder, checked with `readTheme`, then put in place in one rename; the `.gallery.json` provenance in each; recovery at the start |
174
+ | `gallery/reach.ts` | What an entry can reach, by literal patterns on its code with comments taken out (hosts, keys, programs, files), a theme's palettes, and the results kept in `gallery/reach.json`; behind `GET /api/x/gallery/reach` |
174
175
  | `lancet.ts` | Loads Lancet Guard from Pi's install, and downloads its model on request |
175
176
  | `omarchy.ts` | The Omarchy desktop's current theme and wallpaper, read-only, for Follow desktop (`/api/theme`) |
176
177
  | `themes.ts`, `themes/` | Theme folders (`app.themes`): the built-in ones in `web/themes/` and the owner's in the data folder's `themes/`, read and checked (`themes/format.ts`: `theme.json`, `colors.toml`, limits; `themes/css.ts`: CSS's tokens and the files it loads), each one's last good version, watching, Duplicate, Remove, Edit with Pi |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pocket",
3
- "version": "0.27.0-beta.3",
3
+ "version": "0.27.0-beta.5",
4
4
  "description": "A durable, multiplayer, mobile-first web app for Pi agents, built on Pi Durable",
5
5
  "keywords": [
6
6
  "pi",
@@ -38,9 +38,26 @@ addEventListener("pocket:tweak", (event) => {
38
38
  </body>
39
39
  </html>`;
40
40
 
41
- /** The part that is the same for every session. */
41
+ /**
42
+ * The part that is the same for every session. The order of work follows Claude Design's: ask once, start from what
43
+ * exists (a screen that exists is rebuilt as it is before it changes), show a first version early, iterate, check, and
44
+ * reply briefly. A change that the product's code cannot support is named before it is built, never drawn as if it were.
45
+ */
42
46
  const GUIDE = `Designs live in the Design canvas as HTML artifacts, shown beside the chat. People comment on them, tweak them, edit their text, and export them: build each one to be pointed at, changed, and handed to code.
43
47
 
48
+ Work in this order:
49
+ 1. Ask first when the work is new or unclear: one round of questions, all together, then build without asking again. Ask only what would change the design: the starting point (which screen, code, files, or screenshots), the audience and format, how close to the current design to stay, how many variations and on which axes, and what to make tweakable. Read what the person attached or pointed at before you ask. Skip the round for a small change or a follow-up.
50
+ 2. Start from what exists. Read the project's design system, its code, and its screens before you draw: mocking from scratch is the last resort. When there is nothing to start from and the person gave you nothing, ask for it rather than invent a look.
51
+ 3. Show a first version early, then iterate from feedback rather than polish in private.
52
+ 4. Check it (below), then reply in a few lines: caveats and next steps, not a list of what you made.
53
+
54
+ A screen that exists (a page, a sheet, a dialog, or a component of the project) is redesigned from itself:
55
+ - Find its code first: the component, its CSS, the data it shows and where that data comes from (routes, types, data files), and its states. Read the source; do not rely on memory.
56
+ - Version 1 is the screen as it is today, rebuilt from that code: the same layout, sizes, density, copy, and real data (from the project's data files or the running app), in its place in the app (a sheet over the app stays a sheet over the app). Compare it with a screenshot of the real screen when you can get one (the browser tool on the running app), fix what differs, and say that version 1 is today's screen.
57
+ - Then change it as new versions of that artifact, within what the code supports: the data it has and the features it has. A change that needs new data, a new field, or new server work is marked as such in the design and named in your reply, so that the person decides before anyone builds it. Do not add sections, features, or content that the person did not ask for: propose them.
58
+ - A different direction keeps the work so far: make it a new artifact in the same group, not a new version over the last one.
59
+ - Research feeds the design and never replaces it: deliver the screen, not notes or a storyboard about it.
60
+
44
61
  Make each design:
45
62
  - One self-contained HTML artifact, responsive and touch-friendly. It loads nothing from the network: images, fonts, and data files go in with the tools' assets (ask the person for their paths), and icons and illustrations are inline SVG or CSS.
46
63
  - Start from this skeleton and keep every part of it:
@@ -48,16 +65,16 @@ ${SKELETON}
48
65
  - Put data-pid on every part a person may point at: sections, cards, headings, buttons, images. Short, unique, kebab-case (hero-title).
49
66
  - Give each design a tweaks manifest, the JSON array above, of 3 to 8 useful knobs (40 at most), each { name, label?, type: "range" | "color" | "select" | "toggle" | "text", value, min?, max?, step?, unit?, options? }. A name that starts with -- sets that CSS custom property on :root, so read your styling (accent, radius, spacing, type scale) from those properties; any other name reaches the page as a pocket:tweak event on window, with detail { name, value }.
50
67
  - A deck is one artifact with kind: "deck" on the artifact tool, <meta name="pocket-kind" content="deck">, and its slides as <section class="slide">, each written at 1920×1080 (<meta name="pocket-slide-size" content="WxH"> changes that). The canvas shows one slide at a time and scales it: write no navigation script.
51
- - Variations of one design share one group (the tools' group): 2 to 4 artifacts, made in parallel, through subagents or codemode. A person picks one, and you carry it on.
68
+ - Variations of one design share one group (the tools' group): 2 to 4 artifacts, made in parallel, through subagents or codemode. Root them in the existing design, order them from by the book to bold, and make them differ in layout, hierarchy, or interaction, not only in color. Caption each in one line, and say which one you would pick. A person picks one, and you carry it on.
52
69
 
53
- Craft, so that a design looks made and not generated:
70
+ Craft, so that a design looks made and not generated. When the product has its own look, its values (type sizes, spacing, density, control heights, corners) win over these defaults:
54
71
  - Phone first: lay out 390 px, then widen at 700 and 1100 px. Nothing scrolls sideways.
55
72
  - Type: two families at most and one scale (12, 14, 16, 20, 28, 40). Body text is 16 px (14 px in dense tools) at line height 1.5; headings 1.1 to 1.3; lines under 70 characters.
56
73
  - Space on a 4 px grid (4, 8, 12, 16, 24, 32, 48, 64). The same relation gets the same gap. Group by proximity before you draw a line.
57
74
  - Color: one accent, one neutral ramp, status colors only for status. Text reaches 4.5:1 on its ground (3:1 for text from 24 px and for edges a person must find, such as a field's border). Never mark a state by color alone.
58
75
  - Every interactive element is a real button, a, label, or input with default, hover, focus-visible, active, and disabled looks, a visible focus ring, and a touch target of 44 px or more.
59
76
  - Show the states a screen has: empty, loading, error, long text, many items.
60
- - Write real copy and plausible data: names, numbers, dates, prices. No lorem ipsum, no "Feature 1", no "Title".
77
+ - Use real content: the product's own data and copy when it has them, otherwise plausible names, numbers, dates, and prices. No lorem ipsum, no "Feature 1", no "Title", no made-up statistics.
61
78
  - Motion is 150 to 400 ms, one property at a time, and off under prefers-reduced-motion. Give every image alt text, and keep headings in order.
62
79
 
63
80
  Check before you reply:
@@ -66,7 +83,7 @@ Check before you reply:
66
83
 
67
84
  Work with feedback and hand off:
68
85
  - Comments, text edits, and kept tweaks from the canvas reach you as a message, each with its target as JSON (pid, selector, text, html). Make the next version with the artifact tool's edits, and change only what the message names.
69
- - Hand off a design to code: design_export with format html into the project, then start a linked session with the team tool and give it the export path. design_export also writes png, pdf, and pptx (a deck); it takes tweaks to apply first, viewport (a preset or { width, height }) for a page, and slide (a number, or "all" for a zip of every slide) for a deck.`;
86
+ - Hand off a design to code: design_export with format html into the project, then start a linked session with the team tool and give it the export path, the source files of the screen that the design changes, and any new data or server work that the design needs. design_export also writes png, pdf, and pptx (a deck); it takes tweaks to apply first, viewport (a preset or { width, height }) for a page, and slide (a number, or "all" for a zip of every slide) for a deck.`;
70
87
 
71
88
  /**
72
89
  * A short design that uses a system, for a session whose project has one. The names are the flagship's: a test renders
@@ -101,7 +118,7 @@ main { display: grid; gap: var(--space-4); max-width: 420px; margin: 0 auto; }
101
118
  /** What to do in a project with no design system: the end of the section when nothing was found. */
102
119
  const WITHOUT = `${GUIDE}
103
120
 
104
- The project has no design system yet. When the person points at a codebase, make one in three calls: design_system action "scan" (a structured draft; nothing is saved), then action "init" with fromScan true and changes [{ token, value }] for every role the scan guessed or marks uncertain (it refuses to replace a system unless replace is true), then action "validate" and fix what it lists. With only brand files or a description, call "init" with tokens (a DTCG object) and, for dark, modes. Add components with action "component" and rules with "guidelines" only when the person asks. Until there is a system, choose one accent, one neutral ramp, and the scales above, and keep them as custom properties on :root.`;
121
+ The project has no design system yet. When the person points at a codebase, make one in three calls: design_system action "scan" (a structured draft; nothing is saved), then action "init" with fromScan true and changes [{ token, value }] for every role the scan guessed or marks uncertain (it refuses to replace a system unless replace is true), then action "validate" and fix what it lists. With only brand files or a description, call "init" with tokens (a DTCG object) and, for dark, modes. Add components with action "component" and rules with "guidelines" only when the person asks. Until there is a system, follow the look of the code or screens the design comes from; only when the person asks for a new look, choose one accent, one neutral ramp, and the scales above. Keep the values as custom properties on :root.`;
105
122
 
106
123
  /** How to use a system: said once, before the system's own text. */
107
124
  const USE = `The project has a design system, so a design is on-system or it is wrong:
@@ -69,6 +69,21 @@ export default function createGallery(host: PocketHost, web: ExtensionWeb) {
69
69
  "installed",
70
70
  handle(() => gallery.installed()),
71
71
  );
72
+ web.route(
73
+ "GET",
74
+ "reach",
75
+ handle(() => {
76
+ // A server from before this route: its next start has it.
77
+ if ((gallery as Partial<typeof gallery>).reach === undefined) {
78
+ throw web.error(
79
+ 503,
80
+ "Restart the server (menu → Restart server) to see what extensions reach",
81
+ );
82
+ }
83
+
84
+ return gallery.reach();
85
+ }),
86
+ );
72
87
  web.route(
73
88
  "GET",
74
89
  "source/:name",
@@ -0,0 +1,410 @@
1
+ /**
2
+ * What a gallery entry can reach, read off its code: the hosts it names, the keys it reads, the programs it starts, and
3
+ * the files it writes; for a theme, its palette. The scan is by literal patterns, on the code with its comments taken
4
+ * out, so it tells what the code says and not what it does: a host built at run time is only said to be built. The
5
+ * results are kept in the gallery's folder, by entry and pinned files, so the code is downloaded once.
6
+ */
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ import { parseColors } from "../omarchy.ts";
10
+ import { sha256 } from "./entry.ts";
11
+
12
+ /** What the scan found, as short words for people. */
13
+ export interface Scanned {
14
+ network: string[];
15
+ keys: string[];
16
+ programs: string[];
17
+ files: string[];
18
+ }
19
+
20
+ /** A theme's palettes, by `colors.toml`'s keys, or null where it has no such file. */
21
+ export interface Palette {
22
+ colors: Record<string, string> | null;
23
+ colorsLight: Record<string, string> | null;
24
+ }
25
+
26
+ /** What the reading of one entry gives: what it reaches, or why it could not be read. */
27
+ export type Reach =
28
+ | { kind: "extension"; commit: string; scanned: Scanned }
29
+ | { kind: "theme"; commit: string; palette: Palette }
30
+ | { kind: "extension" | "theme"; commit: string; error: string };
31
+
32
+ /** Raise it when the scan changes, so results kept from an older scan are made again. */
33
+ export const SCAN_VERSION = 1;
34
+
35
+ /** The files the scan reads: code that runs. Other files are not downloaded. */
36
+ export const SCAN_FILE = /\.(?:[cm]?[jt]s)$/i;
37
+ /** A theme's palette files, as they are named inside its folder. */
38
+ export const PALETTE_FILES = ["colors.toml", "colors-light.toml"];
39
+
40
+ const DYNAMIC_ADDRESS = "addresses it builds at run time";
41
+ const DYNAMIC_PROGRAM = "programs it names at run time";
42
+ const DATA_FOLDER = "its data folder";
43
+ const HOME_FOLDER = "your home folder";
44
+
45
+ // ─── Comments ──────────────────────────────────────────────────────────────────────
46
+
47
+ /** What can come before a `/` that starts a regular expression and not a division. */
48
+ const BEFORE_REGEX = /[(,=:[!&|?{};+\-*%<>~^]/;
49
+
50
+ /**
51
+ * The code without its comments. Strings and regular expressions are kept as they are, so a `//` in an address is not
52
+ * taken for a comment. Line breaks stay, so lines still count.
53
+ */
54
+ export function stripComments(code: string): string {
55
+ let out = "";
56
+ let at = 0;
57
+ let last = "";
58
+
59
+ while (at < code.length) {
60
+ const char = code[at]!;
61
+ const next = code[at + 1];
62
+
63
+ if (char === "/" && next === "/") {
64
+ while (at < code.length && code[at] !== "\n") {
65
+ at++;
66
+ }
67
+
68
+ continue;
69
+ }
70
+
71
+ if (char === "/" && next === "*") {
72
+ const end = code.indexOf("*/", at + 2);
73
+ const stop = end === -1 ? code.length : end + 2;
74
+
75
+ out += code.slice(at, stop).replace(/[^\n]/g, " ");
76
+ at = stop;
77
+ continue;
78
+ }
79
+
80
+ if (char === '"' || char === "'" || char === "`") {
81
+ let stop = at + 1;
82
+
83
+ while (stop < code.length && code[stop] !== char) {
84
+ if (code[stop] === "\\") {
85
+ stop++;
86
+ } else if (code[stop] === "\n" && char !== "`") {
87
+ break;
88
+ }
89
+
90
+ stop++;
91
+ }
92
+
93
+ out += code.slice(at, stop + 1);
94
+ at = stop + 1;
95
+ last = char;
96
+ continue;
97
+ }
98
+
99
+ if (char === "/" && (last === "" || BEFORE_REGEX.test(last))) {
100
+ let stop = at + 1;
101
+ let inClass = false;
102
+
103
+ while (stop < code.length && code[stop] !== "\n") {
104
+ if (code[stop] === "\\") {
105
+ stop++;
106
+ } else if (code[stop] === "[") {
107
+ inClass = true;
108
+ } else if (code[stop] === "]") {
109
+ inClass = false;
110
+ } else if (code[stop] === "/" && !inClass) {
111
+ break;
112
+ }
113
+
114
+ stop++;
115
+ }
116
+
117
+ if (code[stop] === "/") {
118
+ out += code.slice(at, stop + 1);
119
+ at = stop + 1;
120
+ last = "/";
121
+ continue;
122
+ }
123
+ }
124
+
125
+ out += char;
126
+ at++;
127
+
128
+ if (!/\s/.test(char)) {
129
+ last = char;
130
+ }
131
+ }
132
+
133
+ return out;
134
+ }
135
+
136
+ // ─── The scan ────────────────────────────────────────────────────────────────────
137
+
138
+ const URL_LITERAL = /\b(?:https?|wss?):\/\/([^\s"'`\\/?#:<>()[\]{}$]*)(?::\d+)?([^\s"'`\\]*)/gi;
139
+ const HOST = /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/;
140
+ /** Hosts that name no outside service: this machine, standards' namespaces, and examples. */
141
+ const QUIET_HOST =
142
+ /^(?:localhost|127\.[\d.]+|(?:[a-z0-9-]+\.)*(?:w3\.org|example\.com|example\.org|schema\.org|json-schema\.org))$/;
143
+ /** A repository's page on GitHub: `/<owner>/<repo>`, and the pages under it that people read. */
144
+ const REPO_PAGE =
145
+ /^\/[\w.-]+\/[\w.-]+(?:\/(?:tree|blob|issues|pull|pulls|releases|wiki|commit|commits|discussions|actions|tags)(?:\/.*)?)?\/?$/;
146
+ const CALLS_OUT =
147
+ /(?<![\w$])(?:fetch|fetchPublic)\s*\(|\bnew\s+WebSocket\s*\(|\bhttps?\.request\s*\(/;
148
+
149
+ function networkOf(code: string): string[] {
150
+ const hosts = new Set<string>();
151
+
152
+ for (const match of code.matchAll(URL_LITERAL)) {
153
+ const host = match[1]!.toLowerCase();
154
+ const path = match[2]!.replace(/[?#].*$/, "");
155
+
156
+ if (
157
+ !HOST.test(host) ||
158
+ QUIET_HOST.test(host) ||
159
+ ((host === "github.com" || host === "www.github.com") && REPO_PAGE.test(path))
160
+ ) {
161
+ continue;
162
+ }
163
+
164
+ hosts.add(host);
165
+ }
166
+
167
+ if (hosts.size === 0 && CALLS_OUT.test(code)) {
168
+ return [DYNAMIC_ADDRESS];
169
+ }
170
+
171
+ // A host that is another one with more after it ("github.com.helper", from a git config key) names no service.
172
+ return [...hosts]
173
+ .filter((host) => ![...hosts].some((other) => host.startsWith(`${other}.`)))
174
+ .sort();
175
+ }
176
+
177
+ const SECRET_NAME = /KEY|TOKEN|SECRET/i;
178
+ const PI_KEY_CALL =
179
+ /(?<![\w$])(?:getApiKey|getApiKeyForProvider|getAuth|apiKeyFor)\s*\(\s*(["'`])([\w.-]{1,60})\1/g;
180
+ const ENV_READ = /\benv(?:\??\.|\[\s*["'`])([A-Za-z_][A-Za-z0-9_]*)/g;
181
+ const ENV_DESTRUCTURE = /\{([^{}]*)\}\s*=\s*(?:process\.)?env\b/g;
182
+
183
+ function keysOf(code: string): string[] {
184
+ const keys = new Set<string>();
185
+
186
+ for (const match of code.matchAll(PI_KEY_CALL)) {
187
+ keys.add(`${match[2]} key from Pi`);
188
+ }
189
+
190
+ const names = new Set<string>();
191
+
192
+ for (const match of code.matchAll(ENV_READ)) {
193
+ names.add(match[1]!);
194
+ }
195
+
196
+ for (const match of code.matchAll(ENV_DESTRUCTURE)) {
197
+ for (const part of match[1]!.split(",")) {
198
+ const name = /^\s*([A-Za-z_][A-Za-z0-9_]*)/.exec(part)?.[1];
199
+
200
+ if (name !== undefined) {
201
+ names.add(name);
202
+ }
203
+ }
204
+ }
205
+
206
+ for (const name of [...names].sort()) {
207
+ // A name that ends in "_" is the start of one built at run time (`GIT_CONFIG_KEY_${n}`), not a key it reads.
208
+ if (SECRET_NAME.test(name) && !name.endsWith("_")) {
209
+ keys.add(`environment variable ${name}`);
210
+ }
211
+ }
212
+
213
+ if (/auth\.json/.test(code)) {
214
+ keys.add("Pi's auth.json");
215
+ }
216
+
217
+ return [...keys].sort();
218
+ }
219
+
220
+ /** A call that starts a program, with the literal that opens its arguments. */
221
+ const PROGRAM_CALL =
222
+ /(?<![\w$.])(?:(?:child_process|childProcess|cp)\.)?(spawn|spawnSync|execFile|execFileSync|exec|execSync)\s*\(\s*(["'`])((?:\\.|(?!\2)[^\\\n])*)\2/g;
223
+ const CHILD_PROCESS = /\bchild_process\b/;
224
+
225
+ function programsOf(code: string): string[] {
226
+ const programs = new Set<string>();
227
+
228
+ for (const match of code.matchAll(PROGRAM_CALL)) {
229
+ const literal = match[3]!.split("${")[0]!;
230
+ // A command line (`exec`) starts with its program; the others are given it alone.
231
+ const program = (
232
+ match[1]!.startsWith("exec") && !match[1]!.startsWith("execFile")
233
+ ? literal.trim().split(/\s+/)[0]
234
+ : literal.trim()
235
+ )?.slice(0, 80);
236
+
237
+ if (program !== undefined && program !== "") {
238
+ programs.add(program);
239
+ }
240
+ }
241
+
242
+ if (programs.size === 0 && CHILD_PROCESS.test(code)) {
243
+ return [DYNAMIC_PROGRAM];
244
+ }
245
+
246
+ return [...programs].sort();
247
+ }
248
+
249
+ const WRITES =
250
+ /(?<![\w$])(?:writeFile|writeFileSync|mkdir|mkdirSync|rm|rmSync|appendFile|appendFileSync)\s*\(/;
251
+ const AGENT_PATH = /(?:~\/|\$HOME\/|\$\{HOME\}\/)?\.pi\/agent((?:\/[A-Za-z0-9_.-]+)*)/g;
252
+ const AGENT_JOIN = /["'`]\.pi["'`]\s*,\s*["'`]agent["'`]/;
253
+
254
+ function filesOf(code: string): string[] {
255
+ const files: string[] = [];
256
+ const paths = new Set<string>();
257
+
258
+ if (WRITES.test(code)) {
259
+ files.push(DATA_FOLDER);
260
+ }
261
+
262
+ for (const match of code.matchAll(AGENT_PATH)) {
263
+ paths.add(`~/.pi/agent${match[1]}`);
264
+ }
265
+
266
+ if (AGENT_JOIN.test(code) || /\bagentDir\b/.test(code)) {
267
+ paths.add("~/.pi/agent");
268
+ }
269
+
270
+ files.push(...[...paths].sort());
271
+
272
+ if (paths.size === 0 && /(?<![\w$])homedir\s*\(/.test(code)) {
273
+ files.push(HOME_FOLDER);
274
+ }
275
+
276
+ return files;
277
+ }
278
+
279
+ /** What the code of these files says it can reach, as one program: each file has its comments taken out first. */
280
+ export function scanFiles(files: readonly { name: string; text: string }[]): Scanned {
281
+ return scanStripped(files.map((file) => stripComments(file.text)).join("\n"));
282
+ }
283
+
284
+ /** What one file's code says it can reach. */
285
+ export function scanCode(text: string): Scanned {
286
+ return scanStripped(stripComments(text));
287
+ }
288
+
289
+ function scanStripped(code: string): Scanned {
290
+ return {
291
+ network: networkOf(code),
292
+ keys: keysOf(code),
293
+ programs: programsOf(code),
294
+ files: filesOf(code),
295
+ };
296
+ }
297
+
298
+ // ─── Themes ──────────────────────────────────────────────────────────────────────
299
+
300
+ /** A palette file's colors, or null when there is no file or it holds none. */
301
+ function colorsOf(text: string | undefined): Record<string, string> | null {
302
+ if (text === undefined) {
303
+ return null;
304
+ }
305
+
306
+ const colors = parseColors(text);
307
+
308
+ return Object.keys(colors).length === 0 ? null : colors;
309
+ }
310
+
311
+ /** A theme's palettes from its two palette files' text. The light one is a light palette, as the theme list reads it. */
312
+ export function themePalette(colors: string | undefined, light: string | undefined): Palette {
313
+ const lightColors = colorsOf(light);
314
+
315
+ return {
316
+ colors: colorsOf(colors),
317
+ colorsLight: lightColors === null ? null : { ...lightColors, mode: "light" },
318
+ };
319
+ }
320
+
321
+ // ─── Keeping results ───────────────────────────────────────────────────────────────
322
+
323
+ /** What identifies a result: the entry, its commit, and its pinned files, so a changed pin is read again. */
324
+ export function reachKey(
325
+ kind: string,
326
+ name: string,
327
+ commit: string,
328
+ files: readonly { name: string; sha256: string }[],
329
+ ): string {
330
+ const pins = sha256(
331
+ new TextEncoder().encode(
332
+ `${SCAN_VERSION}\n${files.map((file) => `${file.name} ${file.sha256}`).join("\n")}`,
333
+ ),
334
+ );
335
+
336
+ return `${kind}:${name}@${commit}:${pins}`;
337
+ }
338
+
339
+ const CACHE_FILE = "reach.json";
340
+
341
+ /** The results kept in the gallery's folder, by `reachKey`. */
342
+ export async function loadReach(folder: string): Promise<Record<string, Reach>> {
343
+ try {
344
+ const saved = JSON.parse(await readFile(join(folder, CACHE_FILE), "utf8")) as {
345
+ format?: unknown;
346
+ results?: unknown;
347
+ };
348
+
349
+ if (
350
+ saved.format !== SCAN_VERSION ||
351
+ typeof saved.results !== "object" ||
352
+ saved.results === null ||
353
+ Array.isArray(saved.results)
354
+ ) {
355
+ return {};
356
+ }
357
+
358
+ return saved.results as Record<string, Reach>;
359
+ } catch {
360
+ return {};
361
+ }
362
+ }
363
+
364
+ export async function saveReach(folder: string, results: Record<string, Reach>): Promise<void> {
365
+ const path = join(folder, CACHE_FILE);
366
+
367
+ await mkdir(folder, { recursive: true });
368
+ await writeFile(`${path}.tmp`, `${JSON.stringify({ format: SCAN_VERSION, results })}\n`);
369
+ await rename(`${path}.tmp`, path);
370
+ }
371
+
372
+ /** Whether a kept result still tells about this entry: its kind and commit, and not an error. */
373
+ export function usable(value: unknown, kind: string, commit: string): value is Reach {
374
+ if (typeof value !== "object" || value === null) {
375
+ return false;
376
+ }
377
+
378
+ const reach = value as Record<string, unknown>;
379
+
380
+ return (
381
+ reach.kind === kind &&
382
+ reach.commit === commit &&
383
+ reach.error === undefined &&
384
+ (kind === "theme"
385
+ ? typeof reach.palette === "object" && reach.palette !== null
386
+ : typeof reach.scanned === "object" && reach.scanned !== null)
387
+ );
388
+ }
389
+
390
+ /** Run `work` on each item, `limit` at a time; the results are in the order of the items. */
391
+ export async function mapLimit<T, R>(
392
+ items: readonly T[],
393
+ limit: number,
394
+ work: (item: T) => Promise<R>,
395
+ ): Promise<R[]> {
396
+ const results: R[] = new Array(items.length);
397
+ let next = 0;
398
+
399
+ await Promise.all(
400
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
401
+ while (next < items.length) {
402
+ const at = next++;
403
+
404
+ results[at] = await work(items[at]!);
405
+ }
406
+ }),
407
+ );
408
+
409
+ return results;
410
+ }