host
The host is the first argument of a module’s default export. A module uses it to read from Pi Pocket and to report to it. To add to the app, a module uses web, the second argument.
The host does not change when a module reloads. It changes only when the server restarts. Thus a module that uses a member newer than the running server must check that the member is there. Using the host tells you how.
The types are Host and the types that it uses, in types/pocket.d.ts. Types for your editor tells you how to import them.
Running version
Section titled “Running version”pocketVersion
Section titled “pocketVersion”readonly pocketVersion: string;The running server’s package version, including a pre-release suffix when present. It is read at server startup, not from files that an update replaced later. It is not the extension API level (web.api). Check that this member exists on older servers. A version-monitor extension can compare this value with a release obtained by its own server code, then show a notice; this member does not fetch updates or restart the server.
Folders
Section titled “Folders”dataDir
Section titled “dataDir”readonly dataDir: string;Pi Pocket’s data folder. It is ~/.pi-pocket, unless PI_POCKET_DIR or the --data option gives another folder. The drop-in folder is extensions/ in it.
agentDir
Section titled “agentDir”readonly agentDir: string;Pi’s own folder, usually ~/.pi/agent. Pi keeps its sign-ins, models, settings, skills, and prompt templates there.
cwdOf(conversationId: ConversationId): string;The conversation’s current working folder, or its canonical workspace URI for a remote session. It reads the current agent state, so a module must not cache it across folder changes.
Skills
Section titled “Skills”skillPaths
Section titled “skillPaths”skillPaths(): string[];The extra skill folders that Pi’s settings give.
skills
Section titled “skills”skills(cwd: string): Skill[];Pi’s skills for a session that works in the folder cwd. The list has the skills from all the places where Pi looks.
Models
Section titled “Models”resolveModel
Section titled “resolveModel”resolveModel(spec: string): ModelRef;Finds a model from provider/modelId, or from a model id alone. The model must be signed in, and its sign-in must work. When there is no such model, it throws an error. The error names no other models: the choice of model is the person’s.
modelInfo
Section titled “modelInfo”modelInfo(spec: string): { model: ModelRef; name: string; thinkingLevels: ModelThinkingLevel[]; contextWindow?: number; cost?: { input: number; output: number };} | undefined;Local metadata for one exact provider/modelId, including a known model without configured auth. Since 0.20.0 it can also give contextWindow (tokens) and cost (dollars per million input and output tokens); cost is left out when the catalog has no price (an unknown or free model), and contextWindow can be 0 when unknown, so check for both. A bare id or unknown pair returns undefined. It does not contact a provider, report sign-in details, or list models. Use it to describe the source model or a model already chosen by the owner. It does not authorize its use; starts still check the current model policy and availability.
subagentModels
Section titled “subagentModels”subagentModels(): readonly string[];The models that the owner lets subagents use, as provider/modelId. While the list is empty (the default), a subagent runs on the model of its own session. Once it has models, subagents and linked sessions run only on those: the model of the session when it is listed and none is named; when it is not listed, the caller must name a listed model. The owner sets it in Menu → Providers → Subagent models.
modelProblem
Section titled “modelProblem”modelProblem(ref: ModelRef, fresh?: boolean): Promise<string | undefined>;Why Pi cannot use a model now, in words that Pi can tell a person. For example, Pi Pocket does not know the model, its provider is not signed in, or its sign-in expired. It is undefined when Pi can use the model. With fresh: true, it asks the provider about the sign-in again first.
classifierModel
Section titled “classifierModel”classifierModel(): string | undefined;The classifier model the owner chose in Menu → Providers, as provider/modelId, or undefined when none is chosen. Pi Pocket names no classifier model on its own: a module that has no model of its own, and finds none here, does nothing.
classify
Section titled “classify”classify(request: ClassifyRequest): Promise<Record<string, ClassifierAnswer>>;One classifier-model call: typed questions about JSON state, answered by the model that request.model names, or by the owner’s chosen classifier (classifierModel) when it names none. Classifier models are a class of their own (TypeSafe’s Jev, Cloudflare’s Clef, OpenAI’s GPT-6 Luna): they do not chat, and they answer a choice, a score, or yes/no. The call runs through Pi’s model runtime and uses the owner’s stored provider sign-ins and keys, exactly as a session’s own model calls do. It never wakes a session. What you put in state and images goes to that provider: say so in your module’s settings, so the owner knows what leaves the machine.
modelisprovider/modelIdof a classifier model; the id may hold more slashes. A bare id works when it names one classifier only. A chat model is refused with an error. Leave it out to use the owner’s choice. Find the ids with Pi’s model listing, such asmodels.getAvailableOfType("classifier")in a codemode script.stateis what the model judges.questionsmaps ids to questions, in pi-ai’sClassifierQuestionshapes:{ type: "choice", instructions, criteria: { label: meaning } },{ type: "score", instructions, criteria: [lowest, …, highest] }, or{ type: "bool", instructions, criteria: { true: meaning, false: meaning } }. At least one question.- It resolves to the answers by question id, in pi-ai’s
ClassifierAnswershapes:{ type: "choice", choice, probabilities, confidence },{ type: "score", score, confidence }, or{ type: "bool", probability }. - It throws when no classifier model is named and the owner chose none (“No classifier model is chosen: pick one in Providers”), when no such classifier exists, when the spec names a chat model, when its provider has no stored sign-in or key, or when the call fails. Nothing is sent without the owner’s stored key, and the owner can see the cost with the provider as any other model call.
A module that runs on a server older than 0.31.0 checks typeof host.classify === "function" first and works without it.
ClassifyRequest
Section titled “ClassifyRequest”model: the classifier model,provider/modelId, asclassifyabove takes it. Optional: left out, the owner’s choice is used.state: what the model judges, one JSON object.images: images judged together withstate. Only classifier models whose input accepts images answer them.questions: what it answers, by question id, with the shapes of pi-ai’sClassifierQuestion.
registerModelProvider
Section titled “registerModelProvider”registerModelProvider(provider: string, config: ProviderConfig): () => void;Registers a model provider with Pi’s model runtime, as a Pi extension does. config is Pi’s own ProviderConfig: the provider’s name, base URL, API key, API, headers, and models or refreshModels function. When Pi refuses the config, the call throws and changes nothing. Open tabs get the provider’s models once Pi refreshed it locally.
The return value removes the provider again. Give it to web.onDispose, or the provider stays after the module is edited or turned off:
web.onDispose(host.registerModelProvider("example", config));The last registration of a name wins: Pi uses its config alone, not merged with the one before. Its removal puts back the registration before it, from another module or from an older version that is still in force. A removal of a registration that is not the last one changes nothing in Pi. So a version that a reload replaces can call its removal safely, and a new version that fails to load leaves the old version’s provider in place.
A name can be a built-in provider’s, or one in Pi’s models.json. The registration then changes that provider until its removal, and the API key the owner stored for it still applies. With another baseUrl, the owner’s stored key goes to that address. Say so when you ask the owner to turn the module on.
Two things to know about how Pi refreshes models.
First, registration refreshes models locally only. A provider whose catalog comes from refreshModels alone shows no models until a network refresh, as with the app’s Refresh models action. To look right away, ship a fallback list: a small static models with the provider’s most common models. The network pass replaces it.
Second, every refresh, even a local one, calls refreshModels. When allowNetwork is false, return the models you have: stored?.models ?? [], or another fallback list. Returning [] empties the provider in Pi until the next network pass, because an empty list still counts as the provider’s answer.
shapeModelRequests
Section titled “shapeModelRequests”shapeModelRequests( shape: (payload: unknown, model: Model<Api>) => unknown | undefined,): () => void;Shapes the request that every model call sends. shape gets the payload Pi built and the model, and returns a replacement payload (or a promise of one), or undefined to keep it. A shaper that throws is logged and skipped. It runs after Pi and the caller shaped the request, closest to the wire. The return value stops the shaping. Only the modules that the owner turned on shape requests.
A shaper can change what a provider bills or how it answers, and its effect lasts until it is removed. Say so when you ask the owner to turn the module on.
thinkingLevels
Section titled “thinkingLevels”readonly thinkingLevels: readonly ModelThinkingLevel[];The thinking levels, lowest first. They have the names that models and sessions use.
People and limits
Section titled “People and limits”registerWorkspaceProvider
Section titled “registerWorkspaceProvider”registerWorkspaceProvider(scheme: string, provider: WorkspaceProvider): () => void;Registers the execution environment for a URI scheme such as ssh. resolveCwd returns the canonical address. It must keep the same scheme. Pi Pocket stores that address and refuses to use the local machine when no provider is active. The returned disposer removes only its own registration. See Execution environments for workspaces.
WorkspaceProvider has env(cwd: string): ExecutionEnv and resolveCwd(cwd: string, signal?: AbortSignal): Promise<string>. env returns promptly. It receives the canonical workspace address. resolveCwd can check and canonicalize the address. signal is optional: in 0.28, session creation and settings do not pass one yet.
requesterOf
Section titled “requesterOf”requesterOf(conversationId: ConversationId): string | undefined;The id of the person that Pi works for in a session now. This is the person whose message started Pi’s current work.
roleOf
Section titled “roleOf”roleOf(personId: string): Role | undefined;The role of a person by id: "owner", "guest", or "viewer". It is undefined for an id that is not a person here. It reads the role that core uses, so a module does not keep its own copy. Use it with requesterOf to know if Pi works for the owner. It can change in a minor release. Check that it is there first: host.roleOf?.(id).
heldBack
Section titled “heldBack”heldBack(conversationId: ConversationId): string | undefined;Why Pi cannot start work in a session now when nobody asked for it, for example to read a subagent’s report. The reason is a spend limit: the session’s limit, or the limit of the person who pays there. It is undefined when Pi can start.
onLimitsChanged
Section titled “onLimitsChanged”onLimitsChanged(listener: () => void): () => void;Calls listener each time the owner changes a spend limit. It returns a function: call it to stop.
Events
Section titled “Events”on<E extends AppEventName>(event: E, listener: (data: AppEvents[E]) => unknown): () => void;Calls listener each time something happens in the app: a session is made, renamed, or archived, a person sends Pi a message, or Pi starts or stops working. Each event comes after the change is stored. A listener runs after the work that caused it, never in its way: one that throws or rejects is logged, and the other listeners still run. Each one gets its own frozen copy of the data. It returns how to stop: pass that to web.onDispose. PiP’s conversation is its person’s alone, and sends no events. An unknown event name throws. See AppEvents.
web.onDispose( host.on("run.ended", ({ conversationId, session, outcome, failure }) => { if (conversationId === session && outcome === "failed") { log.push({ session, failure }); } }),);Approval observations
Section titled “Approval observations”pendingApprovals
Section titled “pendingApprovals”readonly pendingApprovals: PendingApprovals;Read-only snapshots and events for tool approvals and questions that wait for a person. This is the public observation API; the mutable approval service remains internal. It never approves, denies, or answers a question. Check that this member exists on older servers.
Each call names a top-level source session. It acts for the person Pi works for there, as linkedSessions does. An unknown session, a PiP, a source with no known requester, or a requester who no longer sees the source is refused. The snapshot includes only waits that the requester and everyone who can see the source can see. This prevents a tool from copying a private session’s status into a shared transcript. Subagents use their parent session’s audience. PiP waits are never exposed.
Snapshots and events are frozen copies. Arguments, commands, paths, free-text reasons, question titles and fields, answer values, and the answering person’s name are withheld. tool and summary describe only the kind of action; an unknown tool name becomes tool. This deliberately withholds all argument text, not just text that looks like a secret.
pendingApprovals.list
Section titled “pendingApprovals.list”list(source: ConversationId): readonly PendingApproval[];The currently pending, visible waits, including waits in other visible sessions. Resolved waits are not kept as history. Subscribe first, then list, and reconcile by id. Re-list after a reload, reconnect, audience change, or restart. On a restart the durable guard hook reconstructs pending waits as runs resume; the snapshot can be empty until that happens. The same guard wait keeps its id and original createdAt. An old wait made before this API gets a time on its first replay with this version. Questions from host.ask keep their existing interrupted-call behavior: a retried question can have a new id.
pendingApprovals.on
Section titled “pendingApprovals.on”on<E extends keyof ApprovalEvents>( source: ConversationId, event: E, listener: (approval: ApprovalEvents[E]) => unknown,): () => void;Listen to created or resolved, and pass the returned disposer to web.onDispose. The subscription binds to the source’s current requester. Core checks that person’s current access and the source’s whole current audience again before each delivery. Removing access stops delivery; it does not synthesize a resolved event. Reconcile a snapshot when access changes.
Listeners run after the change and do not block an approval. A throwing or rejecting listener is logged without its error text; other listeners still run. Events are live notifications, not a durable queue. A restarted server can emit created again for the same pending id; subscribers must handle duplicates. A stop or server shutdown cancels an in-memory wait, but a restart can reconstruct that same guard wait. Use resolved with cancelled as the end of this wait, not as a denial.
PendingApproval
Section titled “PendingApproval”interface PendingApproval { readonly id: string; readonly conversationId: ConversationId; readonly session: ConversationId; readonly createdAt: number; readonly tool: "bash" | "write" | "edit" | "ask" | "tool"; readonly summary: string; readonly state: "pending";}id: the approval’s stable id, also used by its card in the app. It grants no permission to answer it.conversationId: the conversation that waits, which can belong to a subagent.session: the top-level session that contains it. A browser module can usepocket.openConversation(Number(approval.session))to open the session for a person.createdAt: Unix time in milliseconds.tool,summary: the kind of action, with all arguments redacted.state: alwayspendingin a snapshot orcreatedevent.
ResolvedApproval
Section titled “ResolvedApproval”interface ResolvedApproval extends Omit<PendingApproval, "state"> { readonly state: "resolved"; readonly outcome: "allowed" | "denied" | "cancelled" | "superseded";}The same metadata, with state: "resolved" and an outcome. allowed and denied record the person’s decision (submitted and declined for a question). cancelled means the waiting context ended without a decision; superseded means another request replaced this id. No answer values or person’s name are included.
ApprovalEvents
Section titled “ApprovalEvents”interface ApprovalEvents { readonly created: PendingApproval; readonly resolved: ResolvedApproval;}What each pendingApprovals.on listener receives. These events are source-scoped, not global host.on events.
Asking people, hiding values, and the browser
Section titled “Asking people, hiding values, and the browser”These came in 0.22.0, and are experimental. People’s values and the browser tells how to use them together.
ask(request: AskRequest, context: Context): Promise<AskAnswer>;Asks the person Pi works for, on a card in the session, as an approval asks. The card shows the request’s title, its text, a field for each of its fields (a hidden one for a secret), and a button. Only the original requester can send it, while they can still steer. Anyone who can steer can decline it. A replay without its original requester is declined instead of asking someone else. It notifies that person, as an approval does.
What they type comes back in the answer’s values, and nowhere else: not to Pi, into the transcript, or to the other people in the session. A plain Allow, such as from a notification, is refused: each field must be filled in. Do not keep the values in a memo or a document, where a restart would find them. Without a memo, a call that a restart cut off comes back as interrupted, and asks again when Pi tries again. See AskRequest and AskAnswer.
hide(value: HiddenValue): () => void;Hides a value from what Pi and people read, until the returned function is called. Each one becomes [label]:
- in the output of commands as it streams: bash’s live output and its result, a
!command’s card, and a check’s output. A value split across two chunks is held back until it can be told apart, so up to its length less one character comes later than the rest; - in every tool’s result (what the model reads, what programs read, and its details, keys too), before it is stored;
- in people’s messages to Pi, the files a message brings along, and an edit sent again: a value pasted there is replaced before the message is stored, sent to the model, or made the session’s title. A
!command that holds one is refused, since it runs as stored.
With conversationId, it is hidden in that session and its subagents. A guess that matches shows as [label], so hide only a value that cannot be guessed, never a short code.
It does not reach a file that a command writes (such as bash’s spill file for long output), entries from before the value was hidden, or a value that a command changed (encoded, reversed). Hide each form that you expect, such as its base64, as a value of its own. It keeps values out of transcripts by accident: it is not a boundary against a command that leaks a value on purpose. Pass the returned function to web.onDispose. See HiddenValue.
commandEnv
Section titled “commandEnv”commandEnv(provider: CommandEnvProvider): () => void;Adds environment variables to the commands that run in sessions: Pi’s bash, people’s ! commands, and Done when’s checks. Before each command, each provider gets the command, its folder, and its session, and gives variables to add, or nothing. A later provider’s variable wins over an earlier one’s. A provider that throws, or takes more than 5 seconds, adds nothing, and the server’s log says why; the command still runs. Use it to put a value into $NAME for the commands that name it, so the value does not go through Pi. Hide the value with hide too. Pass the returned function to web.onDispose. See CommandEnvProvider.
browser
Section titled “browser”browser( conversationId: ConversationId, options?: { open?: boolean },): Promise<BrowserPageHandle | undefined>;A session’s browser page: the one that Pi’s browser tool and the people in the session use. With open: true, it opens the page when it is not open. It is undefined while the Browser module is off, and without open, when no page is open. See BrowserPageHandle.
Turn notes
Section titled “Turn notes”annotateTurns
Section titled “annotateTurns”annotateTurns(name: string, annotate: TurnAnnotator): () => void;Adds a note for the model right after a person’s message, as a separate entry of the transcript. annotate gets the Turn and returns the note’s text, or undefined for none. Pi Pocket stores the note in the same commit as the message, and never computes it again. The model reads Note from extension <name>: and a line break before the text. Only a message placed at once gets notes: Pi does not work in the session, and nothing is queued. A queued message, an Interrupt, a scheduled message, and PiP’s own conversation get none. The annotators of all modules have 2 seconds together; one that is late, throws, or returns more than 4,000 characters adds nothing, and the session shows a warning. name is 1 to 60 letters, digits, ., _, :, or -, and the transcript shows it with each note. Pass the returned function to web.onDispose. See Turn notes.
Notices and text
Section titled “Notices and text”notice
Section titled “notice”notice(level: NoticeLevel, message: string, conversationId?: ConversationId): void;Reports something to the server’s log and to the app. level is "info", "warning", or "error". With conversationId, only the tabs of that session show the notice. Pi Pocket 0.13.1 added conversationId.
readonly text: SafeText;Makes text from other places safe for Pi to read: from a web page, an issue, or a file that a person did not write. In the same place, tell Pi that the text is data.
text.quoted
Section titled “text.quoted”quoted(text: string, max?: number): string;Gives the text as one line in quotes that the text cannot close. It removes invisible characters and tags, and it cuts the line to max characters. Limits gives the default max.
text.defang
Section titled “text.defang”defang(text: string): string;Keeps the lines of the text, but leaves no closing tag in it. Use it for text that you put between tags of your own.
Public web pages
Section titled “Public web pages”fetchPublic
Section titled “fetchPublic”fetchPublic(url: string | URL, init?: PublicFetchInit): Promise<Response>;Fetches an address that came from outside (from Pi, a page, or a person) as fetch does, but filters non-public ranges and this machine’s interface addresses. Use it for each address that the module did not write itself: a tool that reads a page that Pi names, a crawl, or a link from a search result.
- It takes only
httpandhttpsaddresses, with no user or password in them. - It refuses an IP address that is not public: loopback, private, link-local, shared (
100.64.0.0/10), multicast, and the ranges set apart for documentation and later use. In IPv6, only global unicast addresses (2000::/3) are public, less the ranges set apart in it. An IPv4-mapped IPv6 address is checked as its IPv4 address. - It also refuses every IPv4 and IPv6 address on this machine’s network interfaces, including public ones. It reads the interface list fresh for each address check. Equivalent IPv6 spellings and IPv4-mapped addresses receive the same check.
- It resolves a name when it connects, and refuses the name when any of its addresses is in a non-public range or on a local interface. The connection goes only to an address that it checked. So a name that resolves to a public address first and to a private one later (DNS rebinding) cannot reach the private one.
- It checks each redirect the same way. A 303, and a
POSTthat a 301 or 302 sends on, become aGET. A redirect to another origin drops theAuthorization,Cookie, andProxy-Authorizationheaders. - It stops at a size, a time, and a number of redirects (limits). Give
initother values. - It uses its own connections, not the HTTP proxy in Pi’s settings: a proxy resolves names itself, out of the check’s reach. Behind a proxy that is the only way out, it cannot connect.
The filter does not inspect routes. It cannot detect a public address that routes back into the network through NAT reflection or internally routed public ranges. Network controls must restrict those paths when needed.
A refusal throws an Error with a code:
"POCKET_NOT_PUBLIC": the URL is not allowed, or a literal, DNS answer, or redirect address is in a non-public range or on a local interface."POCKET_TOO_LARGE": the body is larger thanmaxBytes. An uncompressed response whoseContent-Lengthis larger is refused at once. Otherwise the error comes when you read the body, as it is decoded."POCKET_REDIRECTS": more redirects thanmaxRedirects, or a redirect withredirect: "error".
Other failures, such as a name that does not resolve, reject as fetch does. The response’s url is the address of the last redirect, and redirected says whether it followed one.
The text of a page is text from outside: give it to Pi through text (Text from other places). examples/read-page.ts is a tool that uses both.
PublicFetchInit
Section titled “PublicFetchInit”interface PublicFetchInit { method?: string; headers?: Record<string, string> | [string, string][] | Headers; body?: string | Uint8Array; signal?: AbortSignal; redirect?: "follow" | "manual" | "error"; maxRedirects?: number; maxBytes?: number; timeoutMs?: number;}What fetchPublic takes besides the address.
method,headers, andsignal: as forfetch.methodisGETby default.body: a string or bytes, which a 307 or 308 redirect sends again.redirect:"follow"(the default) follows redirects and checks each address."manual"gives the redirect response."error"throws on a redirect.maxRedirects: the redirects to follow at most.maxBytes: the size of the body at most, after it is decoded.timeoutMs: the time for the whole request at most, the body included.
Ordinary sessions
Section titled “Ordinary sessions”sessions
Section titled “sessions”readonly sessions: Sessions;Lets an extension start an ordinary session, the same kind a person gets from New session. Starting an ordinary session tells you who it acts for, what it checks, and what the new session is.
The call acts as the person that Pi works for in source, and that person’s checks apply. Give it a key that stays the same when the call runs again. A second call with the same key returns the session the first call made, and sends its message once. It acts for the person of the first call, and it does not check the model, the folder, or the spend limit again. A key of linkedSessions.start never finds a session of this API.
sessions.start
Section titled “sessions.start”start( source: ConversationId, request: { title?: string; cwd?: string; model?: string; thinking?: string; message?: string }, key: string,): Promise<{ session: ConversationId }>;Makes a top-level session and, when message is given, sends that text as its first message. It returns the new session’s id.
- The new session works in
cwdwhen supplied, otherwise the server’s default folder.cwdmust name an existing folder and uses the normal folder-picker path rules. A missing folder is refused before a session is made. modelisprovider/modelId. It must be a model known here whose provider can be used now. Without it, the session starts on the model a new session would get. The owner’s list of models for subagents does not apply.thinkingis any level. Pi Pocket lowers it to the highest level the model has, or uses the model’s lowest when it has none that low. Without it, the session keeps the thinking level it started with.- The new session has no
linkedFrom. It is its own row in the session list, and it can start linked sessions of its own. - A source past its spend limit, a person invited to one session, and a PiP source are refused, and nothing is made.
- A blank
messageis refused, and nothing is made. Amessageis also refused when the session gets no model: nomodeland no default model.
Outside data
Section titled “Outside data”readonly inbox?: InboxApi;Gives data from outside the app (a chat message, a feed’s item, a service’s event) to a session that exists, or to PiP, as a message from one person. Webhooks use the same path. It is undefined on a server older than 0.29.0: check host.inbox?.deliver first. Delivering outside data tells how to use it.
inbox.deliver
Section titled “inbox.deliver”deliver(target: ConversationId, delivery: InboxDelivery): Promise<{ sent: boolean }>;Sends one message to target, as [via <via>]. Pi reads the person’s instructions first, then whether the sender is trusted, then the payload between <tag> tags, then a line that says the payload is data.
by: the id of the person Pi works for on it. The person must be able to see and steer the session, and not be a viewer.payload: the text that came. Core makes it safe between the tags (no closing tag survives) and cuts it to 8,000 characters.key: delivers once. A second delivery with the same key sends nothing and returns{ sent: false }, also after a restart. Use the source’s own id for the event.tagandattributes: the fence’s tag (defaultoutside-data) and up to 8 attributes, each made one line without quotes.sender: who sent it. The name and the id go in the fence’s tag, asfromandfrom-id, because they came from outside. Outside the fence, one line says only whether the owner marked the id as trusted (trusted: true). This is guidance to the model, not a boundary: an id can be spoofed on some services.limit: a cap of messages in an hour for onebucket, kept in memory. A restart resets it. The cap is 600 at most.
It throws an error with a status: 400 for a delivery that cannot be right, 410 when the session is gone or its person cannot see it, 503 when PiP is off, 429 when the bucket’s limit is reached, and 409 when the session does not take messages now. Try again later after a 409 or a 503, with the same key.
Linked sessions
Section titled “Linked sessions”linkedSessions
Section titled “linkedSessions”readonly linkedSessions: LinkedSessions;Lets a tool start sessions from the session that it runs in, send messages between them, and stop or archive one, as Agent Teams does. A team or orchestration extension uses the same calls. A linked session is an ordinary session. Starting and messaging sessions tells you how they work, what they cannot do, and how to call them.
Each call acts as the person that Pi works for in source, and that person’s checks apply. Give each call a key that stays the same when the call runs again, such as ${api.taskId}:${api.callId}. A second call with the same key does nothing again: it returns what the first call returned.
linkedSessions.start
Section titled “linkedSessions.start”start( source: ConversationId, request: { title?: string; message: string; model?: string; thinking?: string; cwd?: string }, key: string,): Promise<{ session: ConversationId; address: string; answers?: boolean }>;Makes a session linked to source and sends it message as its first message. It returns the new session’s id, and the address that source uses for it. answers (since 0.29.0) says whether its final answer comes back to source by itself: it is false when source turned its answers off with linkedSessions.reports. An older Pi Pocket does not return it.
- The new session works in
cwdwhen supplied, otherwise the folder ofsource.cwdmust name an existing folder and uses the normal folder-picker path rules. A blankcwdcounts as nocwd. A relativecwdresolves against the folder of the server process, not the folder of the source.cwdis since 0.19.0: an older Pi Pocket ignores it and uses the folder ofsource, so a gallery entry that needs it setsminPocketto0.19.0. It gets a copy of the agent settings ofsource, but not its history. - Without
title, the title is the first line ofmessage. modelisprovider/modelId. While the owner’s list of models for subagents is empty, it must be the model ofsource. Once the list has models, it must be one of them. Without it, the session uses the model ofsourcewhen the list is empty or has it. Otherwisestartis refused with an error that names the allowed models.thinkingcan be any level, also one above the level ofsource. Without it, the session uses the level ofsource. Pi Pocket lowers it to the highest level that the model has, or uses the lowest level of the model when it has none that low.- When Pi cannot use the model now,
startmakes nothing and throws an error.
linkedSessions.send
Section titled “linkedSessions.send”send( source: ConversationId, request: { to: string; message: string; steer?: boolean }, key: string,): Promise<{ answers?: boolean }>;Sends message to the linked session at the address to. The session gets it at its next pause (since 0.28.0; before, only with steer: true). With steer: false, it waits for the session’s run to end. send returns when the session takes the message, not when it answers, with { answers } (since 0.28.0): whether the session’s final answer comes back to the source by itself, which it does only when the source started it. An older Pi Pocket does not return it.
The session that gets the message reads it between tags. Words before it say that the agent of another session wrote it, and that it is a request, not a person’s order. They also give the address to write to, and say that its final answer goes back by itself when its run ends (linked-sessions.md).
linkedSessions.stop
Section titled “linkedSessions.stop”stop( source: ConversationId, request: { to: string }, key: string,): Promise<{ busy: boolean }>;Stops the run of the linked session at the address to, and withdraws what waits in its queue. When the session is idle, it has no run to stop, and the call only withdraws what waits in its queue. busy is true when it was working. It needs the same access as send, and it reaches only a session of this team. An older Pi Pocket has no stop: check for it, and set minPocket to 0.28.0 when you need it.
linkedSessions.archive
Section titled “linkedSessions.archive”archive( source: ConversationId, request: { to: string; archived?: boolean }, key: string,): Promise<{ archived: boolean; repeating: number }>;Archives the linked session at the address to. With archived: false, it brings the session back. Without archived, it archives. archived in the result says whether the session is archived now. repeating is how many of its repeating schedules keep running: an archive does not stop them. It needs the same access as send. An older Pi Pocket has no archive.
linkedSessions.reports
Section titled “linkedSessions.reports”reports( source: ConversationId, request: { take: boolean }, key: string,): Promise<{ take: boolean }>;Sets whether source, as a lead, takes the final answers of the sessions it started when their runs end. By default it takes them. With take: false, no run end of a session it started reaches it: old ones, new ones, archived ones, from any start path. send from source then returns answers: false, and its message asks the target to send the answer. With take: true, the answers come back. take in the result says the state now. The switch is stored on the session source. It needs the same access as archive, but on source itself: the turn, no plan mode, and room under the spend limit. A repeat with the same key changes nothing again and returns the first result, even with other arguments. A take that is not a boolean throws a TypeError, and nothing is stored. An older Pi Pocket has no reports: check for it.
linkedSessions.list
Section titled “linkedSessions.list”list(source: ConversationId): Promise<LinkedSession[]>;The sessions linked to source, at any distance, that the person Pi works for can see. Each has an address of the source session’s own, so no session id goes into its transcript.
LinkedSession
Section titled “LinkedSession”interface LinkedSession { address: string; title?: string; cwd?: string; busy?: boolean; archived?: boolean; failed?: string;}A linked session, as list gives it.
address: the address that the asking session uses for it. It is never the session’s id.title,cwd(its folder),busy(Pi works in it now),archived, andfailed: these are there only when all the people who see the asking session see this session too.failed(since 0.28.0): why its last run gave up, the same short line the session list shows. It is there only while that failure stands. A later run clears it, and a run that was stopped leaves none.
Types for events
Section titled “Types for events”AppEvents
Section titled “AppEvents”interface AppEvents { "session.created": { conversationId: number; cwd: string; createdBy?: string; forkedFrom?: number; linkedFrom?: number; }; "session.renamed": { conversationId: number; title: string }; "session.archived": { conversationId: number; archived: boolean }; "session.removed": { conversationId: number }; "message.sent": { conversationId: number; by: string; submissionId: string; text: string; via?: string; }; "run.started": { conversationId: number; session: number }; "run.ended": { conversationId: number; session: number; outcome: "done" | "failed" | "aborted"; failure?: string; };}What each event’s listener gets.
session.created: a session in the list was made, by a person, a fork (forkedFrom), a linked start (linkedFrom), or a resend.createdByis a person’s id. Subagents are not sessions in the list, and send none.session.renamed,session.archived: its new title, or whether it is archived now.session.removed(since 0.30.0): the owner removed an archived session from the app (Session cleanup). Its id is not shown again: drop what your module keeps for it.message.sent: a person’s message to Pi, a steer or a queued one too.byis their id.textis the words as stored, with values that extensions hide already hidden and attachments left out.vianames what sent it for them, such as PiP or a schedule.run.started,run.ended: Pi started or stopped working in a conversation.conversationIdis that conversation, a session’s or a subagent’s;sessionis the session it belongs to. Since 0.28.0,run.endedalso says how the run stopped:outcomeisdonewhen it finished,failedwhen it gave up, orabortedwhen it was stopped.failureis why it gave up, the same short line the session list shows, and only whenoutcomeisfailed. A session’s failure stands until a later run starts.
AppEventName
Section titled “AppEventName”type AppEventName = keyof AppEvents;The name of an event: "session.created", "session.renamed", "session.archived", "session.removed", "message.sent", "run.started", or "run.ended".
Types for asking, hiding, and the browser
Section titled “Types for asking, hiding, and the browser”AskRequest
Section titled “AskRequest”interface AskRequest { readonly conversationId: ConversationId; readonly id: string; readonly taskId: TaskId; readonly callId?: string; readonly title: string; readonly text?: string; readonly fields?: readonly AskField[]; readonly submit?: string;}id: unique while the card waits, and the same when the call asks again, such as${api.taskId}:${api.callId}. A new ask with the id of one that waits replaces it, and the one before is declined.taskId,callId: the call that asks, so the card and its answer show with it.title: one line, up to 120 characters.text: up to 2000.fields: up to 6. None makes a question that the button alone answers, such as “Solve the CAPTCHA in the browser, then tap Done”.submit: the button’s words, up to 30 characters. “Send” by default, “Done” with no fields.
AskField
Section titled “AskField”interface AskField { name: string; label: string; header?: string; choices?: AskChoice[]; multiple?: boolean; other?: boolean; secret?: boolean; placeholder?: string; autocomplete?: string;}
interface AskChoice { label: string; description?: string;}name: the value’s key in the answer: letters, digits, and_, up to 40, starting with a letter. Each field’s is its own.label: what the card says above the field, one line of up to 80 characters. A field withchoiceshas its question here, up to 300.header: a short tag over the field, such as “Database”, up to 12 characters.choices: 2 to 4 answers to pick, shown as buttons, with different labels. A choice’slabelis one line of up to 60 characters, and itsdescription, under it, of up to 160. The field’s value is the label chosen.multiple: withchoices, the person can choose one or more. The value is their labels, one per line, in the order ofchoices.other: withchoices, the person can type an answer of their own instead, and the value is what they typed. Itsplaceholderis the words of that field while it is empty.- A value that is not one of the choices (and with no
other) is refused, with an error that names the field, never the value. secret: a hidden input, as for a password. Not for a field withchoices.autocomplete: a hint for the browser and the phone’s keyboard, such asusername,current-password, orone-time-code. Not for a field withchoices.
AskAnswer
Section titled “AskAnswer”type AskAnswer = | { readonly answered: true; readonly by: string; readonly values: Readonly<Record<string, string>>; } | { readonly answered: false; readonly by: string };What the person did. by is the name of who answered or declined. Each value is 1 to 4096 characters.
HiddenValue
Section titled “HiddenValue”interface HiddenValue { value: string; label: string; conversationId?: number;}value: 4 to 4096 characters. A shorter one would turn up in ordinary output by chance. 2000 values at most are hidden at once.label: what shows in its place, as[label], such as[secret GITHUB_TOKEN]: 1 to 60 letters, digits, spaces, and_ . : -.conversationId: only in this session. Without it, in every session.
CommandRun
Section titled “CommandRun”interface CommandRun { readonly conversationId: number; readonly command: string | readonly string[]; readonly cwd: string;}A command about to run: its session, the command as the shell gets it (or a program and its arguments), and its folder.
CommandEnvProvider
Section titled “CommandEnvProvider”type CommandEnvProvider = ( run: CommandRun,) => Record<string, string> | undefined | Promise<Record<string, string> | undefined>;Gives the variables to add to one command. A name is letters, digits, and _, not starting with a digit; a value has no NUL. A variable that breaks these is left out. The variables of all providers for one command are 256 KB at most.
interface Turn { readonly conversationId: number; readonly by: string; readonly via?: string; readonly text: string; readonly at: number; readonly previousActivityAt?: number; readonly signal: AbortSignal;}One person’s message, before Pi answers it: its session, the person’s id, what sent it for them (via, when it is not their own typing), their words as stored (hidden values hidden, attachments left out), and when it came. previousActivityAt is the newest time of a message, an answer, or a tool result among the session’s last 32 entries, also from before a reset. It is undefined when there is none. signal aborts when the time for annotators ends.
TurnAnnotator
Section titled “TurnAnnotator”type TurnAnnotator = (turn: Turn) => string | undefined | Promise<string | undefined>;Gives the text of a note for one turn, at most 4,000 characters, or undefined for no note. Pi Pocket trims the text; an empty text is no note.
BrowserTarget
Section titled “BrowserTarget”interface BrowserTarget { readonly ref?: string; readonly selector?: string; readonly label?: string; readonly x?: number; readonly y?: number;}What to act on: a ref from the last snapshot (e12), a CSS selector, the visible text or label of an element, or a point in CSS pixels of the viewport.
BrowserControl
Section titled “BrowserControl”interface BrowserControl { ref: string; role: string; name: string; kind: string; disabled: boolean; inView: boolean; value?: string; placeholder?: string; checked?: boolean; options?: string[]; href?: string;}One control of a snapshot, as data, up to 500 of them.
role:button,link,textbox,checkbox,combobox, and so on, orclickablefor an element that only looks clickable.kind: an input’s type (text,password,email, and so on),textarea,select, or the element’s tag.value: a field’s or a select’s value. A password field’s is••••when it holds one, and never its value.options: a select’s options, up to 50.href: a link’s address.
BrowserPageHandle
Section titled “BrowserPageHandle”interface BrowserPageHandle { readonly url: string; readonly title: string; snapshot(): Promise<{ text: string; controls: BrowserControl[]; truncated: boolean; scroll: { y: number; viewport: number; height: number }; }>; inspect( target: BrowserTarget, ): Promise<{ label: string; kind: string; editable: boolean; password: boolean }>; navigate(url: string): Promise<void>; click(target: BrowserTarget): Promise<{ label: string; navigated: boolean }>; type(target: BrowserTarget, text: string, options?: { submit?: boolean }): Promise<string>; fill(target: BrowserTarget, value: string): Promise<string>; select(target: BrowserTarget, value: string): Promise<string>; press(key: string): Promise<void>; scroll(target?: BrowserTarget, dy?: number): Promise<string>; waitFor(options: { text?: string; selector?: string; timeoutMs?: number }): Promise<boolean>;}The page, with what Pi’s browser tool does, but no script to run in it.
snapshot: the page as Pi reads it (text), and its controls as data. Refs last until the next snapshot, Pi’s too.inspect: what a target is, scrolled into view: its description, itskind, and whether it is a field (editable) or a password field.fill: puts a person’s value into a field (not a select), replacing what it holds. The target is a ref, a selector, or a label, not a point. It throws and fills nothing when something covers the field, or when the focus does not reach it. The value is not in what it returns, and the snapshot shows a password field’s as••••. Pi can still read a field’s value with itsevaluate: hide the value withhidetoo.inspectwith a point (x,y) says what is at that point, without scrolling or acting on it.type,click,select,press,scroll,waitFor,navigate: as thebrowsertool’s actions.navigatetakes an http(s) address, host:port, or a file path.- What they return:
type,select, andscrollgive the description of what they acted on;clickgives it with whether the page went elsewhere (navigated);waitForgives whether what it waited for showed;navigateandpressgive nothing.
Internal members
Section titled “Internal members”The host has more members, for Pi Pocket’s built-in modules only. They are not in the types file, and they can change in any release without notice. Do not use them in a drop-in. API stability tells you what this means.
approvals: the mutable approval service, for the guard and app only. For public, read-only snapshots and events, usependingApprovals.guard: Lancet Guard.schedules: scheduled messages, for the schedule tool.schedules.limitsholds the limits in force (perSession,chars,repeatMinutes,aheadDays); the schedules module copies the owner’s settings into it, so a module should read it and not change it. A server from before 0.24.0 has nolimits.background: commands Pi runs in the background, for the background tool:start,read,stop,list, andlimits(running, which the background module copies from the owner’s setting). A server from before 0.24.0 has none.goals: Done when, for the goals module.browsers: the built-in browser, for the browser tool.memory: the lessons that Pi keeps across sessions, for the memory tool.watches: the pull request watches of sessions, for thewatch_prtool.repoWatches: the task of repository watches, for the triggers module.pip: what the tools of PiP, the owner’s assistant, do.pipCompaction: PiP’s own summaries when its context is compacted.gallery: the extension gallery, for its own routes.sessionCleanup(since 0.30.0): archived sessions’ plans, worktrees cleaned up, and sessions removed from the app, for the Session cleanup module.toolNames: the names of the tools that the modules that are on give now (built-in and drop-in), for codemode’s Only mode.stopToolCall,waitsForLimit,alertOwner(since 0.29.0): for the stall watches of Subagents and Agent Teams. They stop one running call, say whether a run waits for a provider’s limit, and tell the owner (a notice and a push).linkedSessions.activity,linkedSessions.stopCall,linkedSessions.onLedRun(since 0.29.0): for the stall watch of Agent Teams. They give the led sessions at work, stop a stuck call of a led session, and call back when a led session starts a run.updates: updates of Pi Pocket itself, for the Updates module’s routes. Its status says how the copy was installed (installKind:git,npm-global,npm-local,npx, orunknown) and what stands in the way of an update from the app.
These pages describe Pi Pocket 0.31.3. Your copy has the pages of its own version in its docs/ folder.