pi-pocket 0.28.0-beta.2 → 0.28.0-beta.3

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.
@@ -64,7 +64,16 @@ Use a template for a message that people send often. Use a skill for steps that
64
64
 
65
65
  People sign in to providers in Menu → **Providers**, and pick a model for each session with the model chip in the message box. Pi Pocket uses Pi's sign-ins (`~/.pi/agent/auth.json`) and Pi's list of models. To add a model or a provider that Pi does not know, add it to `models.json` as Pi's `models.md` says. A provider that needs code comes as a Pi Pocket drop-in that calls `host.registerModelProvider` ([host.md](extensions/reference/host.md#registermodelprovider)), not as a Pi extension: see [Pi's extensions and packages](#pis-extensions-and-packages).
66
66
 
67
- **A Claude subscription.** Sign in to Anthropic with it in Providers. Then turn on **Claude subscription billing** in Menu → Extensions → Installed → **Built in**, so that requests count against the plan. It is off by default. Without it, Anthropic can bill the requests as extra usage, and refuse them when that is used up. Anthropic can change how it counts requests at any time.
67
+ **A Claude subscription.** Sign in to Anthropic with it in Providers. Then turn on **Claude subscription billing** in Menu → Extensions → Installed → **Built in**, so that requests count against the plan. It is off by default, and it asks before it turns on. Without it, Anthropic can bill the requests as extra usage, and refuse them when that is used up.
68
+
69
+ > [!WARNING]
70
+ > **Using a Claude subscription in Pi Pocket is at your own risk.** Anthropic's terms and its help pages disagree on it:
71
+ >
72
+ > - Anthropic's [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) forbid accessing its services "through automated or non-human means, whether through a bot, script, or otherwise", except with an Anthropic API key or where Anthropic explicitly permits it.
73
+ > - Its help pages say that third-party apps can use your subscription limits. Yet its servers often bill such requests as extra usage.
74
+ > - Claude subscription billing makes Pi Pocket's requests look like Claude Code's.
75
+ >
76
+ > Anthropic can change how it counts these requests, refuse them, or act on an account it finds using them. An Anthropic API key, or a model from another provider, has none of these risks.
68
77
 
69
78
  Models are the person's choice, never Pi's:
70
79
 
@@ -29,7 +29,7 @@ Rules for every stream:
29
29
 
30
30
  A design needs images, fonts, data files, and more than one page. Today an artifact is one UTF-8 file.
31
31
 
32
- - The `artifact` and `artifact_inline` tools get `assets`: up to 200 entries of `{ name, path }` (copy a file from the session's machine, binary allowed) or `{ name, content }` (UTF-8 text). `name` is a relative path: segments of `[A-Za-z0-9._-]`, joined by `/`, no `.` or `..` segment, no leading `/`, up to 200 characters.
32
+ - The `artifact` tool (and `artifact_inline`, until 0.28.0, when `inline: true` replaced it) gets `assets`: up to 200 entries of `{ name, path }` (copy a file from the session's machine, binary allowed) or `{ name, content }` (UTF-8 text). `name` is a relative path: segments of `[A-Za-z0-9._-]`, joined by `/`, no `.` or `..` segment, no leading `/`, up to 200 characters.
33
33
  - A new version keeps the assets of the version before. `removeAssets: string[]` drops some. An entry with an existing name replaces it.
34
34
  - Limits: 5 MB for one asset, 20 MB for all the assets of one version, as constants beside `MAX_BYTES`.
35
35
  - Storage: assets are stored once for each content hash (sha256) in a new document kind, `pocket.artifact-asset`, keyed by the hash, with the bytes in base64. `ArtifactVersion` gets an optional `assets?: Record<string, { hash: string; size: number; type: string }>`. A replayed call must find what it wrote, as the body does.
@@ -64,6 +64,7 @@ The host's members do not change while modules reload. A new member comes only a
64
64
  - `presentEntry` (experimental, since 0.28.0), with `PresentEntry`: how an input this module sends shows in the transcript. The model still reads that message in full ([Adding to the app](../app.md)).
65
65
  - What a route handler gets (`WebRequest`: `method`, `params`, `query`, `body`, `user`, `signal`; since 0.16.0 also request-lifetime `snapshot`, `context`, `commit`), and what its answer does.
66
66
  - A conversation-bound request's `conversation` metadata and human `linkedSessions.start` / `list`, with their authenticated-actor, receipt, and admission checks (since 0.16.0).
67
+ - `ConversationWebRequest.conversationUsage`, with `UsageTotals` and `ConversationUsage` (experimental, since 0.28.0): read-only usage for a visible conversation and its visible descendants.
67
68
  - The route paths, the methods, the `access` values (`owner`, `steer`, `view`), and the `X-Pocket` header that every call to a route must have.
68
69
 
69
70
  ### 5. A command's `ctx` and result
@@ -165,7 +166,7 @@ Since 0.26.0, `pocket.pip` (`ask`) is experimental, with `PipApi` and `PipAskRes
165
166
 
166
167
  Since 0.27.0, `host.roleOf(personId)` is experimental, and so is the `scroll` field of `host.browser`'s `snapshot()`.
167
168
 
168
- Since 0.28.0, `web.presentEntry` and `pocket.entryPresentation` are experimental, with `PresentEntry`. A module names how an input it sends shows. The model still reads that message in full. Since then too, `pocket.messages` leaves out an input stored as a module's own kind: before, such an input was not a message in the transcript at all.
169
+ Since 0.28.0, `web.presentEntry` and `pocket.entryPresentation` are experimental, with `PresentEntry`; so is `ConversationWebRequest.conversationUsage`, with `UsageTotals` and `ConversationUsage`. A module names how an input it sends shows. The model still reads that message in full. Since then too, `pocket.messages` leaves out an input stored as a module's own kind: before, such an input was not a message in the transcript at all.
169
170
 
170
171
  Since 0.20.0, the session list's extension points are experimental: `pocket.sessionChips`, `sessionAction`, `sessionFilter`, and `sessionSearch`, `WebRequest.sessions`, and their types. So is `pocket.composerKey`, with `ComposerKeySpec` and `ComposerBox`, and so are `pocket.onConversation`, `messages`, and `reveal`, with `MessagesOptions`, `MessagePage`, and `MessageInfo`. So are `host.registerModelProvider`, and `host.fetchPublic` with `PublicFetchInit`.
171
172
 
@@ -88,3 +88,4 @@ Each member in the reference has its own Since line. These parts came together:
88
88
  | A person's role: `host.roleOf` (experimental) | 0.27.0 |
89
89
  | The page's scroll position: `scroll` in the `host.browser` snapshot (experimental) | 0.27.0 |
90
90
  | Answers to pick on an ask's card: `header`, `choices`, `multiple`, and `other` in `AskField` (experimental) | 0.27.0 |
91
+ | Read-only conversation and descendant usage: `ConversationWebRequest.conversationUsage` (experimental) | 0.28.0 |
@@ -7,7 +7,7 @@ The rules for the names that a module gives. These are the names of its file, ex
7
7
  To install an extension with the name of an installed extension replaces that extension. A tool with the name of another tool replaces it in all sessions. Thus Pi Pocket refuses a drop-in that would take a name that Pi Pocket keeps, or a name that another module has. Menu → Extensions says why.
8
8
 
9
9
  - **Extension names that Pi Pocket keeps:** `coding-tools`, and all names that start with `pocket-`, such as `pocket-core`, `pocket-prompt`, and `pocket-guard`. This is true also when that built-in module is off.
10
- - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact`, `artifact_inline`, `browser`, `subagent`, `team`, `schedule`, `background`, `codemode`, `tool_search`, `memory`, `ask`, and `ask_someone`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
10
+ - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact` (and `artifact_inline`, a name still kept: it was a tool until 0.28.0, and old sessions hold its calls), `browser`, `subagent`, `team`, `schedule`, `background`, `codemode`, `tool_search`, `memory`, `ask`, and `ask_someone`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
11
11
  - **Names that another module has:** the first module to install an extension or tool keeps its name.
12
12
 
13
13
  Give each extension and tool a name of your own, with a prefix: `example-clock`, `acme_lookup`. To change how a built-in tool works, do not replace it. Wrap it (`wrapTool` in Pi Durable's README), or check its calls with a hook.
@@ -307,6 +307,7 @@ interface ConversationWebRequest extends WebRequest {
307
307
  readonly thinkingLevel: ModelThinkingLevel;
308
308
  };
309
309
  readonly linkedSessions: HumanLinkedSessions;
310
+ conversationUsage(conversationId?: ConversationId): Promise<ConversationUsage>;
310
311
  }
311
312
  ```
312
313
 
@@ -314,6 +315,82 @@ Since 0.16.0 · Stable
314
315
 
315
316
  Authoritative source metadata, plus request-lifetime human linked-session capabilities. An omitted `model` means the source has none. Metadata is a snapshot, not a promise that settings cannot change. A start rejects a source model, thinking level, or folder changed while it waits.
316
317
 
318
+ ### `ConversationWebRequest.conversationUsage`
319
+
320
+ ```ts
321
+ conversationUsage(conversationId?: ConversationId): Promise<ConversationUsage>;
322
+ ```
323
+
324
+ Since 0.28.0 · Experimental
325
+
326
+ A server-side member of `ConversationWebRequest`, available only inside a `web.conversationRoute` handler. Without an id, it reads the bound source. An id can select another visible conversation, including a subagent. It returns committed usage only, with no entries, text, session ids, or write capability.
327
+
328
+ Use a GET conversation route with `access: "view"` for a status item:
329
+
330
+ ```typescript
331
+ web.conversationRoute(
332
+ "GET",
333
+ "usage/:source",
334
+ async (request) => {
335
+ if (typeof request.conversationUsage !== "function") {
336
+ throw web.error(503, "Usage needs Pi Pocket 0.28.0 and a server restart.");
337
+ }
338
+
339
+ return request.conversationUsage();
340
+ },
341
+ { conversation: "source", access: "view" },
342
+ );
343
+ ```
344
+
345
+ The route checks its source and the signed-in person before the handler runs. The member checks them again when called and before returning. A target id requires visibility too. Missing conversations and PiP conversations are refused. Descendant sums and counts include only conversations the person can still see. A retained callback fails after the handler returns or the browser disconnects. There is no actor override. Do not broadcast the result to other people or keep it in a shared document: their visibility can differ.
346
+
347
+ This addition does not change route access: people invited to one session still cannot use extension web routes. Viewers with access to all sessions can read through a GET route; no steering, turn, or spend check applies to this read. A gallery entry that needs this member sets `minPocket` to `0.28.0`.
348
+
349
+ Each call reads usage documents and scans stored entries. It also reads the in-memory conversation tree. Cost grows with the stored history, including tool output, of the selected conversation and its descendants, not just their active context. Poll sparingly, not on each streamed token. The result is not an atomic snapshot: work can commit between the ledger and history reads or between conversations.
350
+
351
+ ### `UsageTotals`
352
+
353
+ ```ts
354
+ interface UsageTotals {
355
+ readonly requests: number;
356
+ readonly input: number;
357
+ readonly cacheRead: number;
358
+ readonly cacheWrite: number;
359
+ readonly output: number;
360
+ readonly reasoning?: number;
361
+ readonly cost: number;
362
+ readonly lastPrompt: number;
363
+ }
364
+ ```
365
+
366
+ Since 0.28.0 · Experimental
367
+
368
+ - `requests`: the number of stored assistant responses owned by this conversation, including error or aborted responses. Pi's own retry after an error stores a response of its own, so it counts. Requests with no assistant entry, such as compaction attempts and cache-keeper warm requests, are not counted.
369
+ - `input`: reported uncached input tokens, summed across requests.
370
+ - `cacheRead`: reported input tokens read from a prompt cache.
371
+ - `cacheWrite`: reported input tokens written to a prompt cache, including any 1-hour subset. That subset is not added twice.
372
+ - `output`: reported output tokens, including any separately reported reasoning tokens.
373
+ - `reasoning`: the sum of separately reported reasoning tokens. It is absent when none were reported, and can be 0 when a provider reports 0. Do not add it to `output`.
374
+ - `cost`: estimated US dollars from core's usage ledger, not a provider invoice. It includes model and tool usage, as core's spend does.
375
+ - `lastPrompt`: `input + cacheRead + cacheWrite` of the newest stored assistant response that reports any of them, by entry id: a failed request with no usage leaves the one before. It is 0 without such a response. It measures the last request, not the next request's context after a reset or compaction.
376
+
377
+ Token and cost totals come from core's `pi.usage` ledger. They include compaction and auxiliary requests recorded there, even when those requests have no response entry. Tool-reported usage counts too. A fork starts its own ledger; inherited responses do not count toward `requests` or `lastPrompt`. Old responses still count after a compaction or reset. A number that a provider does not report contributes 0; reasoning stays absent until one provider reports it. A conversation with no usage returns zeros and no reasoning field. Results are independent copies; changing a result changes no stored data. A call reads only the entries that came since the last call for the same conversation, so a module can ask often.
378
+
379
+ ### `ConversationUsage`
380
+
381
+ ```ts
382
+ interface ConversationUsage {
383
+ readonly own: UsageTotals;
384
+ readonly children: UsageTotals & { readonly count: number };
385
+ }
386
+ ```
387
+
388
+ Since 0.28.0 · Experimental
389
+
390
+ `own` covers only the selected conversation. `children` sums every visible conversation it started, at any depth: subagents, linked sessions, and their descendants. It excludes the selected conversation, its ancestors, siblings, and forks. Archived descendants still count. Each conversation counts once, including one with no usage. `children.count` is their count, and `children.lastPrompt` is the sum of each descendant's `lastPrompt`, not the newest prompt across the family. No descendants gives zeros and count 0.
391
+
392
+ Requested by @Haichiu in #195.
393
+
317
394
  ### `HumanLinkedSessions`
318
395
 
319
396
  ```ts
package/docs/features.md CHANGED
@@ -63,7 +63,7 @@ The full tour. For setup, see the [README](../README.md).
63
63
  - **Roles and invites.** An invite can let someone **steer** or make them **view only** (they read, react, and chat, but cannot send to Pi, approve, or upload). It can cover **every session** or **only this session**, and lasts 15 minutes, an hour, a day, or a week (**Expires after**); either way it works once, and a restart keeps it. Changing what the sheet's invite grants, or how long it lasts, ends the one it showed; **New invite** makes another and leaves the one before working. Only the owner can make an owner invite (**Sign in as me (owner)**): it makes no one new, but signs the device in with the owner's token, so it has full control, works once, and always expires in 15 minutes; rotating the owner token (`--rotate-token`) signs out every device signed in that way, and ends owner invites not yet used. Menu → **People** lists everyone, who is online, and when the others were last here. The owner can change what each person may do or remove them. The session list shows who is in each session, and a dot marks new chat messages.
64
64
  - **Notifications.** Menu → **Notifications** turns on push notifications for a device: Pi finished, Pi needs approval, someone @mentioned you, or a chat message in a session you take part in. You only get them while you are not looking at that session. An approval can be denied from the notification, and allowed there when the whole call fits on one short line. The home-screen icon counts the sessions that need you. They need an https address: the Cloudflare Tunnel or Tailscale Serve, or another tunnel such as ngrok in front of **This device only** (`--access local`). On iPhone, add Pi Pocket to the home screen first. The server signs pushes with its own keys in `~/.pi-pocket/push.json`.
65
65
  - **Built-in browser.** Menu → **Browser** (or Alt+B, `/browser localhost:5173`, or the globe in the top bar while a page is open; on a phone, a dot on the places button by the message box says so) opens a real Chromium page that runs on the server: beside the conversation on wide screens, full screen on phones. Type an address (`localhost:5173`, `example.com`), or (the owner) tap a row under **Running on this machine** on the start screen; a green dot in the rounded address field marks an open page. Tap, drag to scroll, and type into the page (the keyboard button sends text from a phone). The size button switches between fitting the panel (the page follows the panel when it changes size), desktop, phone, and tablet sizes, and the console button shows the page's logs and errors, with a warning-colored error count. Pi's `browser` tool uses the same page: it opens addresses (dev servers, HTML files on the machine, any site), reads a snapshot of the page's text and controls, clicks, types, takes screenshots it can see, reads the console, and runs JavaScript in the page, while everyone in the session watches. Each session has one page, in a browser context of its own; links that open a new tab open there instead, and dialogs are accepted. Anyone in the session can watch; using the page takes steering rights (and the wheel, while take turns is on), the addresses people open show in the chat, and only the owner opens files from the address bar. The browser reaches what the server reaches, `localhost` and its network included, and Lancet Guard does not check it (see SECURITY.md). A restart closes the pages, and each opens again at its last address and size. Where the panel covers the conversation, Esc closes it, unless the page has the keys (then Alt+B does). In plan mode Pi may look at pages but not click, type, or run scripts in them. It needs Chromium, Chrome, Brave, or Edge on the server (or `PI_POCKET_BROWSER`); the owner can turn it off in Extensions, which closes the panel too.
66
- - **Artifacts.** The `artifact` tool publishes versioned HTML pages, Markdown documents (shown in the app's theme), or SVG images. Give it `content`, `edits` against the latest version, or a `path` to a UTF-8 text file on the server (up to 2 MB). A path can be absolute, start with `~/`, or be relative to the session's folder. The file is copied into a durable version, not linked: changing or deleting the source does not change the artifact. For a new artifact, `.html`, `.md`/`.markdown`, and `.svg` infer its type; a path update keeps the existing id's type. A page can carry a bundle of files (since 0.26.0). `assets` adds up to 200 entries, each `{ name, path }` (a file on the server, binary allowed, copied and not linked) or `{ name, content }` (UTF-8 text): images, fonts, stylesheets, scripts, data files, or more HTML pages. A name is a relative path of letters, digits, dots, underscores, and hyphens, up to 200 characters, with no `.` or `..` segment. A new version keeps the assets of the one before it; an entry with the same name replaces one, and `removeAssets` drops some. One asset is up to 5 MB, and one version's assets up to 20 MB. A relative URL in the page (`assets/logo.png`, `about.html`) loads from the bundle in the viewer, in an inline card after Run, in the artifact's own tab, and in a published link. Each file is sent with the sandbox's policy, `nosniff`, and a type from its extension (an unknown one is never HTML). Assets are stored once for each content hash. A private page reaches its assets through a signed address that lasts 12 hours, so a page left open longer loads new assets only after a reload. `group` (a lowercase slug) puts artifacts together as variations of one design, and `kind` (`page` or `deck`) says what a design is; Design uses both. Artifacts from before 0.26.0 work as they did. The `artifact_inline` tool is the same store for HTML only (`content` or `edits`, no path): its call shows as a card in the reply, between Pi's words, instead of a link (see Rich replies). Pi's guide says when to use which: the card for a small interactive piece that belongs to what it is explaining, the viewer for a whole page, a game, a Markdown document, or an SVG image. An id made by either tool takes versions from both, but `artifact_inline` refuses an id that is Markdown or SVG, and the `artifact` tool cannot change the type of an id that has had an inline version (a card names a version, and the page comes by the artifact's type): Pi uses a new id for that. Pi's guide mentions `artifact_inline` only in sessions that have the tool, and says that only a direct call shows a card. The Artifacts sheet lists every version in a rounded card grid; opening one shows the sandboxed viewer (or its own tab). The list does not run artifacts as previews. Artifacts cannot reach the app or its cookies. In the viewer, an HTML artifact can ask for two things, which Pi knows how to build: a **follow-up**, a message it puts in your message box (after your draft, starting with which artifact it is from, with any selection as JSON) for you to read and send, never sent by itself, and only after you tap the page (a real tap or key press in the page, up to 5 seconds before: the page cannot fake one, and `window.focus()` does not count; each tap serves one follow-up), at most every 2 seconds (the viewer then closes, so the box shows); and **saved state**, up to 16 KB of JSON that it saves for you alone, so its filters and inputs come back after a reload, a restart, or on another device. Saved state stays out of Pi's context, belongs to the artifact rather than a version, and starts empty in a fork; a page that changes the state's shape names a new schema, and the old state then reads as none. Only people who can write to Pi get a follow-up; a viewer gets a notice. HTML run from a reply (▶ Run) can offer a follow-up too, but keeps no state. Only the artifact's first page is heard: as it starts, it opens a private channel to the app (a script the server puts first in an HTML artifact's page when a frame asks for it, and in the frame page that runs a reply's HTML), and everything goes over that channel, so a page the frame goes on to cannot use it and an answer still on its way never reaches it. `schema` is a string (a number is refused, for a get and a set alike). The bridge is for HTML artifacts, not Markdown or SVG. Neither works in a published link or an artifact's own tab. A session keeps up to 300 saved values; a person removed from the app keeps theirs until the session goes. **Share** in the viewer publishes one artifact to anyone with the link (`/pub/<token>`), with no sign-in: the page is the artifact's own sandboxed one, so it still cannot reach the app, and its address is the whole of the access. A bundle's files are at `/pub/<token>/<name>`, checked on every request: ending or expiring the link closes every file, a link that follows the newest version follows its assets, and a pinned link keeps its own. A published page gets no bridge. A share either stays at the version it was made from or follows the artifact's newest, and either lasts until it is ended or closes after a day, a week, or a month; **End** closes it at once, and the address then answers nothing. Only people who steer and see every session publish or end one, or see its address, never viewers or someone invited to a single session. The sheet lists the session's links still in force, with the address to copy; it starts at the server's public address when a tunnel gives one, else at this browser's.
66
+ - **Artifacts.** The `artifact` tool publishes versioned HTML pages, Markdown documents (shown in the app's theme), or SVG images. Give it `content`, `edits` against the latest version, or a `path` to a UTF-8 text file on the server (up to 2 MB). A path can be absolute, start with `~/`, or be relative to the session's folder. The file is copied into a durable version, not linked: changing or deleting the source does not change the artifact. For a new artifact, `.html`, `.md`/`.markdown`, and `.svg` infer its type; a path update keeps the existing id's type. A page can carry a bundle of files (since 0.26.0). `assets` adds up to 200 entries, each `{ name, path }` (a file on the server, binary allowed, copied and not linked) or `{ name, content }` (UTF-8 text): images, fonts, stylesheets, scripts, data files, or more HTML pages. A name is a relative path of letters, digits, dots, underscores, and hyphens, up to 200 characters, with no `.` or `..` segment. A new version keeps the assets of the one before it; an entry with the same name replaces one, and `removeAssets` drops some. One asset is up to 5 MB, and one version's assets up to 20 MB. A relative URL in the page (`assets/logo.png`, `about.html`) loads from the bundle in the viewer, in an inline card after Run, in the artifact's own tab, and in a published link. Each file is sent with the sandbox's policy, `nosniff`, and a type from its extension (an unknown one is never HTML). Assets are stored once for each content hash. A private page reaches its assets through a signed address that lasts 12 hours, so a page left open longer loads new assets only after a reload. `group` (a lowercase slug) puts artifacts together as variations of one design, and `kind` (`page` or `deck`) says what a design is; Design uses both. Artifacts from before 0.26.0 work as they did. `inline: true` (since 0.28.0, one tool; before it a second tool, `artifact_inline`, sent almost the same schema again on every request) is the same store for HTML only (`content` or `edits`, no path, no `type` but `html`): the call shows as a card in the reply, between Pi's words, instead of a link (see Rich replies). Pi's guide says when to use which: the card for a small interactive piece that belongs to what it is explaining, the viewer for a whole page, a game, a Markdown document, or an SVG image. An id made by either tool takes versions from both, but an `inline: true` call refuses an id that is Markdown or SVG, and the `artifact` tool cannot change the type of an id that has had an inline version (a card names a version, and the page comes by the artifact's type): Pi uses a new id for that. Pi's guide mentions `inline` only in sessions whose `artifact` tool has it (PiP's has not), and says that only a direct call shows a card. Sessions from before 0.28.0 keep their `artifact_inline` calls and results as stored, and still show them as cards, also in forks; the model is shown those calls as `artifact` with `inline: true` in its requests, so it does not repeat a tool it is no longer offered. The Artifacts sheet lists every version in a rounded card grid; opening one shows the sandboxed viewer (or its own tab). The list does not run artifacts as previews. Artifacts cannot reach the app or its cookies. In the viewer, an HTML artifact can ask for two things, which Pi knows how to build: a **follow-up**, a message it puts in your message box (after your draft, starting with which artifact it is from, with any selection as JSON) for you to read and send, never sent by itself, and only after you tap the page (a real tap or key press in the page, up to 5 seconds before: the page cannot fake one, and `window.focus()` does not count; each tap serves one follow-up), at most every 2 seconds (the viewer then closes, so the box shows); and **saved state**, up to 16 KB of JSON that it saves for you alone, so its filters and inputs come back after a reload, a restart, or on another device. Saved state stays out of Pi's context, belongs to the artifact rather than a version, and starts empty in a fork; a page that changes the state's shape names a new schema, and the old state then reads as none. Only people who can write to Pi get a follow-up; a viewer gets a notice. HTML run from a reply (▶ Run) can offer a follow-up too, but keeps no state. Only the artifact's first page is heard: as it starts, it opens a private channel to the app (a script the server puts first in an HTML artifact's page when a frame asks for it, and in the frame page that runs a reply's HTML), and everything goes over that channel, so a page the frame goes on to cannot use it and an answer still on its way never reaches it. `schema` is a string (a number is refused, for a get and a set alike). The bridge is for HTML artifacts, not Markdown or SVG. Neither works in a published link or an artifact's own tab. A session keeps up to 300 saved values; a person removed from the app keeps theirs until the session goes. **Share** in the viewer publishes one artifact to anyone with the link (`/pub/<token>`), with no sign-in: the page is the artifact's own sandboxed one, so it still cannot reach the app, and its address is the whole of the access. A bundle's files are at `/pub/<token>/<name>`, checked on every request: ending or expiring the link closes every file, a link that follows the newest version follows its assets, and a pinned link keeps its own. A published page gets no bridge. A share either stays at the version it was made from or follows the artifact's newest, and either lasts until it is ended or closes after a day, a week, or a month; **End** closes it at once, and the address then answers nothing. Only people who steer and see every session publish or end one, or see its address, never viewers or someone invited to a single session. The sheet lists the session's links still in force, with the address to copy; it starts at the server's public address when a tunnel gives one, else at this browser's.
67
67
  - **All artifacts.** The rail's artifact button opens every artifact in every session you can see, grouped by session (archived sessions are left out), newest first. Each row shows its type, size, age, and the number of its current (latest) version, as `v3 / 3` of the versions it has (`v1` when it has one). A tap opens that version in its session. The launcher's **All artifacts** opens it too, which is the way on a phone. The list is `GET /api/artifacts`.
68
68
  - **Design.** On by default (Menu → **Extensions** turns it off). A canvas beside the chat for Pi's HTML designs: prototypes, screens, one-pagers, and slide decks. A design is an artifact, so versions, the sandbox, saved state, and share links work as they do for any artifact. Open it from the rail, the places, **Open in Design** in the artifact viewer, or `/design-open` (with an artifact's id to open that one). On a wide screen the panel sits beside the chat; on a phone it covers the chat, and the way back keeps the canvas as it was. Since 0.26.0.
69
69
  - **The canvas.** A picker of the session's HTML artifacts (newest first, variations together); the page in the artifact sandbox, at phone (390×844), tablet (820×1180), desktop (1280×800), or a custom size; fit or zoom, and a light, dark, or theme backdrop. A new design that Pi makes opens by itself, unless you are in a mode, have a draft, or it is a variation of the open design.
@@ -125,7 +125,7 @@ The full tour. For setup, see the [README](../README.md).
125
125
  - **Refresh models.** The owner can tap **Refresh models** in the menu (under App) or the Providers sheet (in the provider controls), 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.
126
126
  - **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. An image starts to be made ready for the model as soon as it uploads, so a send seldom waits for it. In a session's message box (not PiP's), attached files stay across a reload, as the draft does, and leave with your sign-out; while a message is on its way, the box dims and holds what it sends, and if the send fails, it is all there to send again.
127
127
  - **Code in your messages.** In a message you send, `` `code` `` and a fence of ` ``` ` lines show as code, the way Pi's replies show it, colored when the fence names a language (` ```js `). A span closes with as many backticks as opened it, a fence's lines stand on their own, and a stray or unclosed one stays text. Nothing else is formatted: `*`, `#`, lists, and spacing stay as typed, and @mentions outside code stay buttons. Only the display changes: Pi, exports, and ↑ get the message as written.
128
- - **Rich replies.** Code blocks in Pi's replies show their language and a Copy button, with syntax colors for the common languages (no dependencies, so it works offline), and a block of more than 40 lines folds until you ask for the rest. Some show more than code, with the code a tab away: an `html` block (or a reply that is a whole page) is previewed as a page, inline, with its scripts off and nothing loaded from anywhere; **▶ Run** runs its scripts in the artifacts' sandbox, where it can reach the internet but not the app; an `svg` block is drawn as an image (tap it for full screen); and a `diff` or `patch` block opens in the diff viewer. While Pi is still writing, they show as code. Write cards color the file they write, and the file viewer previews `.html` files the same way, with Run. **Cards in the reply.** An `artifact_inline` call shows as a card in the reply, as the `html` block above with the artifact's name and version in its bar, an **Open** button for the artifact viewer at that version, and the same Preview/Code and Run/Stop; a failed, denied, or stopped call shows as a step with its reason instead. The result records the version its call made, so each card keeps showing its own: an update by Pi adds a new card, and earlier cards, in this session and a fork, do not change. A card's page is read from the artifact's own address, so whoever can see the session sees the card, a viewer and someone invited to this session alone included, and each can Run it. Once run, its page gets what an artifact's does: a follow-up for the message box (a notice for a viewer) and saved state under the artifact's id, shared with the viewer. A preview grows to fit the page, up to 1200 px, and a running page up to 900 px, then scrolls inside. On a phone the bar takes two lines. A viewer already open on an older version stays on it and offers "latest is vN" after an update. Only a call Pi makes itself is a card: one made inside a codemode script is one of its nested calls, and in PiP's panel the call is a line among its steps.
128
+ - **Rich replies.** Code blocks in Pi's replies show their language and a Copy button, with syntax colors for the common languages (no dependencies, so it works offline), and a block of more than 40 lines folds until you ask for the rest. Some show more than code, with the code a tab away: an `html` block (or a reply that is a whole page) is previewed as a page, inline, with its scripts off and nothing loaded from anywhere; **▶ Run** runs its scripts in the artifacts' sandbox, where it can reach the internet but not the app; an `svg` block is drawn as an image (tap it for full screen); and a `diff` or `patch` block opens in the diff viewer. While Pi is still writing, they show as code. Write cards color the file they write, and the file viewer previews `.html` files the same way, with Run. **Cards in the reply.** An `artifact` call with `inline: true` (an `artifact_inline` call, in a session from before 0.28.0) shows as a card in the reply, as the `html` block above with the artifact's name and version in its bar, an **Open** button for the artifact viewer at that version, and the same Preview/Code and Run/Stop; a failed, denied, or stopped call shows as a step with its reason instead. The result records the version its call made, so each card keeps showing its own: an update by Pi adds a new card, and earlier cards, in this session and a fork, do not change. A card's page is read from the artifact's own address, so whoever can see the session sees the card, a viewer and someone invited to this session alone included, and each can Run it. Once run, its page gets what an artifact's does: a follow-up for the message box (a notice for a viewer) and saved state under the artifact's id, shared with the viewer. A preview grows to fit the page, up to 1200 px, and a running page up to 900 px, then scrolls inside. On a phone the bar takes two lines. A viewer already open on an older version stays on it and offers "latest is vN" after an update. Only a call Pi makes itself is a card: one made inside a codemode script is one of its nested calls, and in PiP's panel the call is a line among its steps.
129
129
  - **Images inline.** Attached images show as thumbnails (also in the composer before you send). When Pi writes `![description](path)` with a path on the server (absolute, `~/…`, or relative to the session's folder), the image shows in its reply. Images a tool returns and SVG artifacts show inline too; an image Pi reads with `read` (often one you just sent) shows only when its call is opened, so it is not on screen twice. Tap any image to see it full screen. Only real image files are shown: the server checks a file's bytes, not just its name.
130
130
  - **Launcher.** `npm start` asks how your devices should reach Pi Pocket: this device only, the local network, a Cloudflare Tunnel, Tailscale, or Tailscale Serve. It then shows the address and a QR code to sign in your phone, and keeps running with keys to restart the server or change access.
131
131
 
package/docs/map.md CHANGED
@@ -39,7 +39,7 @@ A module split into parts keeps its name for the part others import, with the re
39
39
  | `errors.ts`, `paths.ts` | `HttpError`, `describe`, and input checks; `~` paths |
40
40
  | `zip.ts` | `zip(entries)`: a ZIP32 archive in memory with CRC32, UTF-8 names, and deflate, with no dependency; Design's PPTX and HTML exports use it |
41
41
 
42
- `extension-request.ts` owns extension routes' request-lifetime document/context capabilities and fresh person/source authorization. `http/extension-routes.ts` binds named source parameters and supplies human linked-session capabilities. `linked-sessions.ts` keeps the short final-admission lease; its child context watches policy publications and checks current config when Durable enters admission. `models.ts` supplies exact local `host.modelInfo` metadata. `versions.ts` supplies `host.pocketVersion` and `hello.server.pocketVersion`, read by browser `pocket.pocketVersion`; `pocket.openConversation` delegates to normal `store.navigate`.
42
+ `extension-request.ts` owns extension routes' request-lifetime document/context capabilities and fresh person/source authorization. `conversation-usage.ts` reads core usage ledgers and response counters for a conversation route, with visible descendant sums and fresh access checks. `http/extension-routes.ts` binds named source parameters and supplies human linked-session capabilities. `linked-sessions.ts` keeps the short final-admission lease; its child context watches policy publications and checks current config when Durable enters admission. `models.ts` supplies exact local `host.modelInfo` metadata. `versions.ts` supplies `host.pocketVersion` and `hello.server.pocketVersion`, read by browser `pocket.pocketVersion`; `pocket.openConversation` delegates to normal `store.navigate`.
43
43
 
44
44
  ### People
45
45
 
@@ -191,7 +191,7 @@ Outside `src/`: `flake.nix` and `nix/` build Pi Pocket with Nix (`nix/package.ni
191
191
 
192
192
  ## Extensions: `src/server/extensions/`
193
193
 
194
- Each default-exports `(host: PocketHost, web: ExtensionWeb) => Extension | Extension[] | void` (`web` adds to the app: [extensions/app.md](extensions/app.md)) and is installed in this order: `prompt` (system prompt, with where Pi Pocket's docs are), `artifacts` (the `artifact` and `artifact_inline` tools: one store, `publish`, and bundles: `assets`, `removeAssets`, `group`, `kind`), `browser` (browser tool and its prompt section; through `host.browsers`), `subagents` (subagent tool and its tasks: anchors, reporters, and the courier that sends waiting reports to the parent together; a subagent runs on its session's model, or one the owner allowed, and the app rebuilds the module when that list changes), `agent-teams` (Agent Teams, off by default: the `team` tool and its prompt section, through `host.linkedSessions`; its browser module `agent-teams.js` describes the tool's calls with `pocket.toolCall`; it imports of Pi Pocket's only types and `model-facts.ts`, a pure helper that formats model facts), `schedules` (schedule tool and its four limits, as settings; installs the schedule task), `background` (the background tool and its one setting, through `host.background`; installs the watch task), `goals` (hook after each answer), `plan` (tool hook and prompt section), `anthropic-subscription` (Claude subscription billing), `guard` (tool hook that asks for approval), `codemode` (codemode tool; a script's calls go through the same hooks), `memory` (memory tool and the prompt section of lessons in force; through `host.memory`), `pip` (PiP's tools, prompt, and follow task, through `host.pip`; only PiP's conversation selects it, as `PocketApp`'s settings leave it out of every other conversation's), `triggers` (the PR and repository watch tasks and the `watch_pr` tool, through `host.watches` and `host.repoWatches`; webhooks need it on), `gallery` (the extension gallery's owner-only routes under `/api/x/gallery/`, through `host.gallery`, and its twice-daily look for revoked versions; it installs `pocket-gallery`, which tells the web app it is on), `session-tags` (Session tags, off by default: its `x.session-tags.tags` document, routes that check ids with `request.sessions()`, and its browser folder `session-tags/`, which uses the session list's extension points; it imports nothing of Pi Pocket's but types, as a drop-in would), `ask` (Ask: Pi's `ask` tool and its prompt section, questions with answers to pick on a card through `host.ask`; subagents do not get it, and plan mode lets it run), `ask-someone` (Ask someone, off by default: the `ask_someone` tool, which saves a draft question in its `x.ask-someone.questions` document; routes to edit, share, and end them; a public page (`web.publicPage`) for one answer through each link; and its browser folder `ask-someone/`; it imports nothing of Pi Pocket's but types), `updates` (Updates of Pi Pocket itself: owner-only routes under `/api/x/updates/`, through `host.updates`, its three settings (look, install by itself, beta updates), the look every 6 hours and the install by itself, and its browser folder `updates/`, the menu row, launcher action, and sheet, which says in words how the copy was installed and shows the hints that the server gives for a local or npx install), `design` (Design mode's workspace: its routes under `/api/x/design/` for comments, tweaks, "go back to this one", and the designs list, the `pocket.design-comments` document, the `/design-open` command, and the agent side from `../design/index.ts` (tools, prompt guide, export route); its browser folder `design/` is the canvas: only `index.js` (the store, the rail button, the launcher actions, the command, and a loading state), `paths.js`, and `state.js` (the workspace's one store) load at app start; `app.js` (the workspace, with `style.css`) loads when the panel first opens, and `docks.js`, `views.js`, and the System view (`system-ui.js`, with `system.css`) when first used; `unsaved.js` carries the System view's unsaved count and save; `workspace.js` is the picker, toolbar, and modes, `canvas.js` the frame and its bridge, `docks.js` the versions, comments, text edits, and tweaks, `system-view.js`, `system-sections.js`, `system-widgets.js`, `system-actions.js`, `system-data.js`, and `system-preview.js` the System view, `check.js` the Check tab, `picker.js` the design picker, `views.js` compare, the variations grid, the slide strip, and present mode, `data.js` what it asks of the server, `parts.js` small pieces, `style.css` the workspace's sheet, and `system.css` the System view's; `devices.js`, `tweaks.js`, `edits.js`, `messages.js`, `comments.js`, `system.js`, `color.js`, and `specimen.js` are pure helpers (`color.js`, with `color.d.ts`, is also the server's color math, through `../design/color.ts`); `system-routes.ts` and `system-api.ts` are the System view's routes (`system`, `system/check`, `system/docs`, `system/export`) and the engines they call; it imports the app's own `/store.js` and `/artifact-bridge.js`), and `tool-search` (the `tool_search` tool, and the list of tools that wait to be searched for: `browser`, `background`, `schedule`, `watch_pr`, `ask_someone`, and the design tools; it marks them deferred with `wrapTool`, and shows their prompt sections only once one of their tools is loaded, with `wrapSection` (the design guide's section with any of the three design tools); on a model whose provider takes tool changes in the messages it loads a tool into the list, and on any other it gives the tool's description in the search result and Pi calls it from a codemode script, so the list, and the prompt cache that starts with it, never change; turn it off and they are offered every time).
194
+ Each default-exports `(host: PocketHost, web: ExtensionWeb) => Extension | Extension[] | void` (`web` adds to the app: [extensions/app.md](extensions/app.md)) and is installed in this order: `prompt` (system prompt, with where Pi Pocket's docs are), `artifacts` (the `artifact` tool, with `inline: true` for a card in the reply: one store, `publish`, and bundles: `assets`, `removeAssets`, `group`, `kind`; `legacyInline` shows old `artifact_inline` calls to the model as `artifact` calls; `withoutInline` is PiP's), `browser` (browser tool and its prompt section; through `host.browsers`), `subagents` (subagent tool and its tasks: anchors, reporters, and the courier that sends waiting reports to the parent together; a subagent runs on its session's model, or one the owner allowed, and the app rebuilds the module when that list changes), `agent-teams` (Agent Teams, off by default: the `team` tool and its prompt section, through `host.linkedSessions`; its browser module `agent-teams.js` describes the tool's calls with `pocket.toolCall`; it imports of Pi Pocket's only types and `model-facts.ts`, a pure helper that formats model facts), `schedules` (schedule tool and its four limits, as settings; installs the schedule task), `background` (the background tool and its one setting, through `host.background`; installs the watch task), `goals` (hook after each answer), `plan` (tool hook and prompt section), `anthropic-subscription` (Claude subscription billing), `guard` (tool hook that asks for approval), `codemode` (codemode tool; a script's calls go through the same hooks), `memory` (memory tool and the prompt section of lessons in force; through `host.memory`), `pip` (PiP's tools, prompt, and follow task, through `host.pip`; only PiP's conversation selects it, as `PocketApp`'s settings leave it out of every other conversation's), `triggers` (the PR and repository watch tasks and the `watch_pr` tool, through `host.watches` and `host.repoWatches`; webhooks need it on), `gallery` (the extension gallery's owner-only routes under `/api/x/gallery/`, through `host.gallery`, and its twice-daily look for revoked versions; it installs `pocket-gallery`, which tells the web app it is on), `session-tags` (Session tags, off by default: its `x.session-tags.tags` document, routes that check ids with `request.sessions()`, and its browser folder `session-tags/`, which uses the session list's extension points; it imports nothing of Pi Pocket's but types, as a drop-in would), `ask` (Ask: Pi's `ask` tool and its prompt section, questions with answers to pick on a card through `host.ask`; subagents do not get it, and plan mode lets it run), `ask-someone` (Ask someone, off by default: the `ask_someone` tool, which saves a draft question in its `x.ask-someone.questions` document; routes to edit, share, and end them; a public page (`web.publicPage`) for one answer through each link; and its browser folder `ask-someone/`; it imports nothing of Pi Pocket's but types), `updates` (Updates of Pi Pocket itself: owner-only routes under `/api/x/updates/`, through `host.updates`, its three settings (look, install by itself, beta updates), the look every 6 hours and the install by itself, and its browser folder `updates/`, the menu row, launcher action, and sheet, which says in words how the copy was installed and shows the hints that the server gives for a local or npx install), `design` (Design mode's workspace: its routes under `/api/x/design/` for comments, tweaks, "go back to this one", and the designs list, the `pocket.design-comments` document, the `/design-open` command, and the agent side from `../design/index.ts` (tools, prompt guide, export route); its browser folder `design/` is the canvas: only `index.js` (the store, the rail button, the launcher actions, the command, and a loading state), `paths.js`, and `state.js` (the workspace's one store) load at app start; `app.js` (the workspace, with `style.css`) loads when the panel first opens, and `docks.js`, `views.js`, and the System view (`system-ui.js`, with `system.css`) when first used; `unsaved.js` carries the System view's unsaved count and save; `workspace.js` is the picker, toolbar, and modes, `canvas.js` the frame and its bridge, `docks.js` the versions, comments, text edits, and tweaks, `system-view.js`, `system-sections.js`, `system-widgets.js`, `system-actions.js`, `system-data.js`, and `system-preview.js` the System view, `check.js` the Check tab, `picker.js` the design picker, `views.js` compare, the variations grid, the slide strip, and present mode, `data.js` what it asks of the server, `parts.js` small pieces, `style.css` the workspace's sheet, and `system.css` the System view's; `devices.js`, `tweaks.js`, `edits.js`, `messages.js`, `comments.js`, `system.js`, `color.js`, and `specimen.js` are pure helpers (`color.js`, with `color.d.ts`, is also the server's color math, through `../design/color.ts`); `system-routes.ts` and `system-api.ts` are the System view's routes (`system`, `system/check`, `system/docs`, `system/export`) and the engines they call; it imports the app's own `/store.js` and `/artifact-bridge.js`), and `tool-search` (the `tool_search` tool, and the list of tools that wait to be searched for: `browser`, `background`, `schedule`, `watch_pr`, `ask_someone`, and the design tools; it marks them deferred with `wrapTool`, and shows their prompt sections only once one of their tools is loaded, with `wrapSection` (the design guide's section with any of the three design tools); on a model whose provider takes tool changes in the messages it loads a tool into the list, and on any other it gives the tool's description in the search result and Pi calls it from a codemode script, so the list, and the prompt cache that starts with it, never change; turn it off and they are offered every time).
195
195
 
196
196
  ## Web: `web/` (Preact and htm, no build)
197
197
 
@@ -205,7 +205,7 @@ Plain ES modules, loaded as they are. `store.js` holds the shared state, and not
205
205
  | `gestures.js` | Touch gestures, each following its own finger by its identifier, passive where they can be: sheets dragged down and the drawer dragged left to close (`useDragToClose`); on phones, swipes on the conversation (right back, left Files), in Files (right back), and up from the message box (the places); a swipe in from the left edge goes back in an iPhone's home screen app |
206
206
  | `app.js` | Layout (tiled windows, and the subagents board in the conversation's place), top bar (with what changed, from `diff.js`), notices, keyboard shortcuts, routing |
207
207
  | `transcript.js` | The conversation as turns: messages, Pi's replies with message times arranged in the reply slot, its thinking and tool calls folded into groups that open into a timeline, extensions' command cards, approvals, the live line (and Pi's thinking above it), breadcrumbs (and `linked-sessions.js`, the links between linked sessions); a message from a linked session shows without its routing words |
208
- | `turns.js` | How the transcript reads a conversation, without drawing it: answers split into runs of words and groups of calls, and each `artifact_inline` call as an `inline` item between them (`itemsOf`), a group in a line (`summarize`, with extensions' own tools as `extension-ui.js` gives them: `setCallSummary`), and what a call came to from what its tool printed. No imports, so Node tests it |
208
+ | `turns.js` | How the transcript reads a conversation, without drawing it: answers split into runs of words and groups of calls, and each inline call (`artifact` with `inline: true`, or an old `artifact_inline`: `isInlineCall`) as an `inline` item between them (`itemsOf`), a group in a line (`summarize`, with extensions' own tools as `extension-ui.js` gives them: `setCallSummary`), and what a call came to from what its tool printed. No imports, so Node tests it |
209
209
  | `calls.js` | A tool call in one line, for the transcript's timeline and peek tiles; extensions' own tools as `extension-ui.js` gives them (`setCallDescriber`) |
210
210
  | `slots.js` | Slots: the top bar's buttons, the status line's items, the places, the message box's left buttons, and the actions under answers as named items, the app's own (`defineItem`) and extensions' (`fromExtensions`), in one order: defaults, `before`/`after`, extensions' `pocket.arrange`, then the person's own choices (`prefs().layout`, Appearance → Layout) |
211
211
  | `composer.js` | Message box, chips, the queue, plan and goal bars, `@` file suggestions, `!` commands, ↑ and Ctrl+R history, long-paste placeholders, the mic (`voice.js`), a subagent's way back to its session, the status line under it (kept to one row) |
@@ -250,7 +250,7 @@ Plain ES modules, loaded as they are. `store.js` holds the shared state, and not
250
250
  | `files-panel.js` | The Files tile: whether it is open and on which tab, the folder's tree (folders read as they open), Go to file, the open file beside the tree, and the Changes tab |
251
251
  | `diff.js` | The diff viewer: one file's diff (unified or split, line numbers, colors, changed words, hidden lines on request), `DiffBlock` for tool calls and replies, and `DiffReview`, every change file by file with viewed marks |
252
252
  | `diff-parse.js` | Diffs as data, without the DOM: unified diffs and Pi's edit format as files, hunks, and lines; rows that pair changed lines by likeness; the words that changed |
253
- | `rich.js` | Code blocks in replies that show more than code (a page previewed, with Run; an SVG; a diff), given to `Markdown` at load (`setRichBlock`); `InlineArtifact`, the card of an `artifact_inline` call (the same block, named by the artifact and its version, with Open, fetching that version's page from `/a/…`); `HtmlPreview`, `Highlighted` |
253
+ | `rich.js` | Code blocks in replies that show more than code (a page previewed, with Run; an SVG; a diff), given to `Markdown` at load (`setRichBlock`); `InlineArtifact`, the card of an inline artifact call (the same block, named by the artifact and its version, with Open, fetching that version's page from `/a/…`); `HtmlPreview`, `Highlighted` |
254
254
  | `run-frame.js` | `RunFrame`: a reply's HTML (or an inline card's page, as its artifact) run on a tap, in the server's sandboxed `/a/frame` page, sized to fit it |
255
255
  | `highlight.js` | Syntax colors without dependencies: `highlightLines` gives escaped HTML with flat `hl-` spans per line, which `diff.js` marks changed words in |
256
256
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pi-pocket",
3
- "version": "0.28.0-beta.2",
3
+ "version": "0.28.0-beta.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pi-pocket",
9
- "version": "0.28.0-beta.2",
9
+ "version": "0.28.0-beta.3",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.4.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pocket",
3
- "version": "0.28.0-beta.2",
3
+ "version": "0.28.0-beta.3",
4
4
  "description": "A durable, multiplayer, mobile-first web app for Pi agents, built on Pi Durable",
5
5
  "keywords": [
6
6
  "pi",
@@ -0,0 +1,235 @@
1
+ /** Read-only usage for an extension route's source and its visible descendants. */
2
+ import { UsageDoc, type ConversationId, type Cursor } from "@earendil-works/pi-durable";
3
+ import type { PocketApp } from "./app.ts";
4
+ import type { ExtensionRequest } from "./extension-request.ts";
5
+ import { HttpError } from "./errors.ts";
6
+ import type { ConversationUsage, UsageTotals } from "./host.ts";
7
+
8
+ function emptyTotals(): UsageTotals {
9
+ return {
10
+ requests: 0,
11
+ input: 0,
12
+ cacheRead: 0,
13
+ cacheWrite: 0,
14
+ output: 0,
15
+ cost: 0,
16
+ lastPrompt: 0,
17
+ };
18
+ }
19
+
20
+ function add(sum: UsageTotals, value: UsageTotals): void {
21
+ for (const field of [
22
+ "requests",
23
+ "input",
24
+ "cacheRead",
25
+ "cacheWrite",
26
+ "output",
27
+ "cost",
28
+ "lastPrompt",
29
+ ] as const) {
30
+ sum[field] += value[field];
31
+ }
32
+
33
+ if (value.reasoning !== undefined) {
34
+ sum.reasoning = (sum.reasoning ?? 0) + value.reasoning;
35
+ }
36
+ }
37
+
38
+ /** A conversation's request count and newest prompt, kept until a newer entry comes, so a module can ask often. */
39
+ const counted = new Map<ConversationId, { newest: number; requests: number; lastPrompt: number }>();
40
+
41
+ /**
42
+ * The conversations that `source` started, at any depth: its subagents, which live in its session's own list, and the
43
+ * linked sessions it started, which are sessions of their own. Only the sessions the walk reaches are listed, so a
44
+ * server with many sessions and subagents does not pay for all of them.
45
+ */
46
+ function descendantsOf(app: PocketApp, source: ConversationId): Set<ConversationId> {
47
+ const linked = new Map<ConversationId, ConversationId[]>();
48
+
49
+ for (const [key, meta] of Object.entries(app.sessionCatalogue())) {
50
+ const from = meta.linkedFrom?.id as ConversationId | undefined;
51
+
52
+ if (from !== undefined) {
53
+ linked.set(from, [...(linked.get(from) ?? []), Number(key) as ConversationId]);
54
+ }
55
+ }
56
+
57
+ const agents = new Map<ConversationId, Map<ConversationId, ConversationId[]>>();
58
+
59
+ const agentsIn = (root: ConversationId) => {
60
+ let byParent = agents.get(root);
61
+
62
+ if (byParent === undefined) {
63
+ byParent = new Map();
64
+
65
+ for (const id of app.conversationsOf(root)) {
66
+ const parent = id === root ? undefined : app.parentOf(id);
67
+
68
+ if (parent !== undefined) {
69
+ byParent.set(parent, [...(byParent.get(parent) ?? []), id]);
70
+ }
71
+ }
72
+
73
+ agents.set(root, byParent);
74
+ }
75
+
76
+ return byParent;
77
+ };
78
+
79
+ const ids = new Set<ConversationId>([source]);
80
+
81
+ for (const id of ids) {
82
+ for (const child of [
83
+ ...(agentsIn(app.rootOf(id)).get(id) ?? []),
84
+ ...(linked.get(id) ?? []),
85
+ ]) {
86
+ ids.add(child);
87
+ }
88
+ }
89
+
90
+ return ids;
91
+ }
92
+
93
+ /**
94
+ * A conversation's model responses, and the prompt size of the newest one that sent a prompt (a failed request with no
95
+ * usage leaves the one before). Entries come newest first: those up to the newest one read last time are not read again.
96
+ */
97
+ async function requestsOf(
98
+ app: PocketApp,
99
+ id: ConversationId,
100
+ scope: ExtensionRequest,
101
+ check: () => unknown,
102
+ ): Promise<{ requests: number; lastPrompt: number }> {
103
+ const conversation = await app.harness.conversation(id, scope.context);
104
+
105
+ if (conversation === undefined) {
106
+ return { requests: 0, lastPrompt: 0 };
107
+ }
108
+
109
+ const kept = counted.get(id);
110
+ let requests = 0;
111
+ let lastPrompt: number | undefined;
112
+ let newest: number | undefined;
113
+ let cursor: Cursor | undefined;
114
+
115
+ scan: do {
116
+ check();
117
+
118
+ const page = await conversation.entries({}, 256, cursor, scope.context);
119
+
120
+ for (const entry of page.items) {
121
+ const at = Number(entry.id);
122
+
123
+ newest ??= at;
124
+
125
+ if (kept !== undefined && at <= kept.newest) {
126
+ requests += kept.requests;
127
+ lastPrompt ??= kept.lastPrompt;
128
+ break scan;
129
+ }
130
+
131
+ // Forks inherit entries, but their usage ledger starts empty.
132
+ if (entry.conversationId !== id || entry.kind !== "pi.assistant") {
133
+ continue;
134
+ }
135
+
136
+ for (const message of entry.model ?? []) {
137
+ if (message.role !== "assistant") {
138
+ continue;
139
+ }
140
+
141
+ requests++;
142
+
143
+ const used = message.usage;
144
+ const prompt =
145
+ (used?.input ?? 0) + (used?.cacheRead ?? 0) + (used?.cacheWrite ?? 0);
146
+
147
+ if (lastPrompt === undefined && prompt > 0) {
148
+ lastPrompt = prompt;
149
+ }
150
+ }
151
+ }
152
+
153
+ cursor = page.next;
154
+ } while (cursor !== undefined);
155
+
156
+ const result = { newest: newest ?? kept?.newest ?? 0, requests, lastPrompt: lastPrompt ?? 0 };
157
+
158
+ counted.set(id, result);
159
+
160
+ return { requests: result.requests, lastPrompt: result.lastPrompt };
161
+ }
162
+
163
+ export async function conversationUsage(
164
+ app: PocketApp,
165
+ source: ConversationId,
166
+ scope: ExtensionRequest,
167
+ ): Promise<ConversationUsage> {
168
+ const current = () => {
169
+ const user = scope.current();
170
+ const meta = app.sessionMeta(app.rootOf(source));
171
+
172
+ if (
173
+ !Number.isSafeInteger(source) ||
174
+ Number(source) < 1 ||
175
+ meta === undefined ||
176
+ meta.pip !== undefined
177
+ ) {
178
+ throw new HttpError(404, "No such usage conversation.");
179
+ }
180
+
181
+ app.requireSee(user, source);
182
+
183
+ return user;
184
+ };
185
+
186
+ current();
187
+
188
+ if ((await app.harness.conversation(source, scope.context)) === undefined) {
189
+ throw new HttpError(404, "No such usage conversation.");
190
+ }
191
+
192
+ const ids = descendantsOf(app, source);
193
+
194
+ const values = new Map<ConversationId, UsageTotals>();
195
+
196
+ for (const id of ids) {
197
+ if (!app.canSee(current(), id)) {
198
+ continue;
199
+ }
200
+
201
+ const totals = emptyTotals();
202
+ const usage = await app.harness.snapshot(UsageDoc, id, scope.context);
203
+
204
+ for (const bucket of [usage?.models ?? {}, usage?.tools ?? {}]) {
205
+ for (const used of Object.values(bucket)) {
206
+ for (const field of ["input", "cacheRead", "cacheWrite", "output"] as const) {
207
+ totals[field] += used[field] ?? 0;
208
+ }
209
+
210
+ totals.cost += used.cost?.total ?? 0;
211
+
212
+ if (used.reasoning !== undefined) {
213
+ totals.reasoning = (totals.reasoning ?? 0) + used.reasoning;
214
+ }
215
+ }
216
+ }
217
+
218
+ Object.assign(totals, await requestsOf(app, id, scope, current));
219
+ values.set(id, totals);
220
+ }
221
+
222
+ // Access can change while the document and entry reads wait.
223
+ const user = current();
224
+ const descendants = emptyTotals();
225
+ let count = 0;
226
+
227
+ for (const [id, totals] of values) {
228
+ if (id !== source && app.canSee(user, id)) {
229
+ add(descendants, totals);
230
+ count++;
231
+ }
232
+ }
233
+
234
+ return { own: values.get(source) ?? emptyTotals(), children: { ...descendants, count } };
235
+ }
@@ -1,8 +1,10 @@
1
1
  /**
2
- * Claude subscription billing: adds the header that makes Anthropic count Pi Pocket's requests against a Claude
3
- * subscription. Anthropic says third-party apps draw from subscription limits, but its classifier can bill them as
4
- * extra usage instead, and refuse them when that pool is empty. Anthropic may change how it classifies requests. While
5
- * this is off, requests go out as Pi builds them.
2
+ * Claude subscription billing: at your own risk, as Anthropic's terms and its help pages disagree on it, Anthropic counts
3
+ * Pi Pocket's requests against a Claude subscription. The terms forbid using Claude "through automated or non-human
4
+ * means" except with an API key or where Anthropic explicitly permits it; the help pages say third-party apps can use
5
+ * subscription limits, yet Anthropic's servers often bill such requests as extra usage, and refuse them when that pool is
6
+ * empty. This adds the header that Claude Code sends, so the requests look like Claude Code's. Anthropic may change how
7
+ * it classifies requests, or act on an account it finds doing this. While this is off, requests go out as Pi builds them.
6
8
  */
7
9
  import { isClaudeCodeRequest, shapeRequest } from "../anthropic-shape.ts";
8
10
  import type { ExtensionWeb, PocketHost } from "../host.ts";