Method reference
This page lists the methods of the @pstdio/sdk HTTP client and what the other SDK entry points export.
Import a declared @pstdio/sdk subpath. The package has no root entry point.
The SDK overview lists all entries and their dependency requirements.
For page limits, canonical fields, project scope and 0.44 aliases, see client conventions.
HTTP client
import { createClient, PstdioApiError } from "@pstdio/sdk/client";
const client = createClient();
const projects = await client.projects.query();
createClient(options?: ClientOptions) accepts baseUrl, token, and fetch.
Outside the browser, it reads PSTDIO_API_URL and PSTDIO_API_TOKEN when those
options are omitted. The fallback URL is http://127.0.0.1:19840.
createRequest(options: ClientOptions) returns the low-level request function.
HTTP failures throw PstdioApiError, which exposes message and status.
Transport failures throw PstdioConnectionError, with the original error in cause.
Cancelled requests keep the abort reason. Hosts can report connection loss once
in their status bar while keeping loaded views visible. Sync reconnects after
a closed stream or missed heartbeats and calls onConnected when ready again.
See the request types for request
headers, cancellation, and other options.
The client exposes these groups. Each link contains the current method signatures and request and response types. Methods marked with an asterisk (*) are not in the current stable release; † marks later unreleased additions. See Release availability.
| Group | Methods | Contract |
|---|---|---|
account |
login*, loginStatus*, cancelLogin*, projectsCatalog†, projectLocalRemoval†, removeLocalProject†, downloadCloudProject†, deleteCloudProject†, projectDeletionStatus†, projectSyncStatus*, retryProjectSync†, retryProjectSyncSource†, status*, logout*, devices*, renameDevice*, removeDevice*, syncProject*, stopProjectSync*, resolveReturnedChanges*, sendDeviceCommand† |
AccountClient, device login |
assets |
begin*, get*, cancel*, upload*, read* |
AssetsClient, asset guide |
resources |
addAnchors, removeAnchors, queryAnchors*, queryRelated†, deprecated listAnchors |
ResourceAnchorsClient, related resources |
views |
query*, queryBoards*, queryOrphaned*, board, deprecated boards/list/orphaned, get, create, update, delete, reorder, setDefault |
BoardViewsClient |
projects |
query*, deprecated list, get, create, attachInitialWorkspace, retrySetup, update, delete, bindEnvironment*, folder†, chooseFolder†, open†, recoveryPoints†, restore†, folderSources‡, folderRecovery‡, captureFolder‡, downloadFolder‡, restoreFolder‡, cancelFolderRecovery‡ |
ProjectClient |
filesystem |
drives*, list, createDirectory |
FilesystemClient |
workspaces |
getCapacity, updateCapacity, query*, queryProviders*, deprecated listProviders/list, getByShorthand, create, rename, resolveEntry, listFiles, createDirectory, createFile, readFile, writeFile, moveEntry, deleteEntry, diffFiles*, diffFile*, diffSummary*, watchDiff, watchFiles, removeWorktree, delete |
WorkspaceClient |
sessions |
query*, iterate*, deprecated list, get, uploadAttachment, deleteAttachment, create, rename, fork†, archive, delete*, followUp, steer†, approve, getConversation, getHarnessCommands, getDraftHarnessCommands, invokeHarnessOperation, getQueuedMessages, getQueuedFollowUps, updateQueuedFollowUp, combineQueuedFollowUps, steerQueuedFollowUp, removeQueuedFollowUp*, moveQueuedFollowUp*, resolveSessionId, updateStatus, stream, connectStream, retainResources† |
SessionClient, queued requests |
skills |
query*, deprecated list, get |
SkillClient |
agents |
query*, queryModels*, authentication†, authenticate†, getParamDefaults*, setParamDefaults*, deprecated info/models |
AgentClient |
extensions |
install, diagnostics, metadata*, contributions*, marketplaceContributions*, setEnabled*, setAutomationEnabled*, reload*, uninstall*, createNotification*, uploadCommandFile*, enableInstalled, listAppearance, listCommands, listProject, upgradeProject, listConnections, configureConnection, checkConnection, deleteConnection, execute, streamCommand*, deprecated stream, dispatchEvent |
ExtensionClient |
automation |
issueToken, listTokens, revokeToken, createRun, getRun, listRunEvents, cancelRun |
AutomationClient |
notifications |
query*, setStatus*, setStatusByKey*, count, get, update, deprecated list/create/markRead/dismiss/markDone/snooze/resolveByDedupeKey |
NotificationsClient |
settings |
get, update |
SettingsClient |
linkIcons |
get* |
LinkIconsClient |
sync |
start |
SyncClient |
textEditing |
connect† |
Public text transport |
nativeDocuments |
open†, submit†, snapshot†, watch†, presence†, close† |
Native document client |
runtime |
ready*, environment*, resolveTarget*, claimBrowserSession*, createBrowserLogin |
RuntimeClient |
client.textEditing.connect({ projectId, scope }) opens an authenticated text
connection under the declared agent or placement scope. Source references and
selected-source grants use the same host admission checks as extension webviews.
Call connection.guest() and pass its host to createTextEditingClient from
@pstdio/sdk/extensions to obtain public text sessions. A session owns local Yjs
edits, drafts, durability fences and recovery; flush() waits for local durability,
and project() also waits for the source file or domain projection.
Close with guest.close() so every registered session can finish its drafts and
flush before teardown. A refused close leaves recovery available. The connection’s
disconnect() is terminal transport cleanup, not a substitute for that ordinary
close barrier. These APIs are unreleased additions.
client.agents.authentication(agentId, { projectId, model }) reads native account
readiness for the selected model provider. client.agents.authenticate(agentId, input, options) runs a cancellable account flow over the authenticated WebSocket;
onPrompt receives browser links and messages, and onRequest answers provider
choices and masked credential fields. Replies do not enter conversation history or
command events. See harness sign-in.
client.filesystem.drives() returns { drives }, with each drive’s name and root
path on the Windows runtime host. Other platforms return an empty array.
client.nativeDocuments.open({ projectId, target }) opens a durable local editor
room for a declared Markdown source. submit saves binary text updates before
acknowledging them. snapshot reads the current text history. watch streams text
and transient participants until its abort signal ends. presence updates the
connection’s selection; close releases its room. These methods use the normal
local host credentials. Relay credentials stay in the host. Native extension
editors use this connection automatically after declaring documentSource.
extensions.install installs a catalog extension or an uploaded folder into a project,
the same path pst extensions add uses. extensions.diagnostics returns the checks
behind pst extensions check. extensions.streamCommand runs a command and streams its
chunks and final outcome; it replaces extensions.stream. runtime.environment returns the runtime’s stable environment ID, and
projects.bindEnvironment binds a known project ID to a folder in that environment,
as pst projects environment and pst projects bind do.
See the client guide for sessions, file attachments,
connections, and remote automation examples. Board views describes the views group.
Release availability
The table follows the source on main. @pstdio/sdk 0.43.1, the current stable
release, has every method above except the ones marked with * or †. Those include all
of client.assets, the bounded query methods, sessions.iterate, and
extensions.streamCommand. On 0.43.1, use the methods marked deprecated here, such
as projects.list and extensions.stream; they are not deprecated in that release.
The methods marked with an asterisk are in 0.44.0-nightly builds and ship in the release after 0.43.x. Each one
needs both the newer SDK and a Prompt Studio app from that release. Installing a
newer @pstdio/sdk does not add the API routes to an older app. See
App, SDK, and extension API versions.
The methods marked †, client.sessions.steer, client.sessions.retainResources, client.projects.folder and client.projects.chooseFolder, are unreleased additions after 0.44.0 and need both the newer SDK and host. See live input for steering.
client.account.login(managerOrigin?) starts Google sign-in through the host’s configured account service. With no argument, the host uses PSTDIO_ACCOUNT_MANAGER_ORIGIN or the hosted default https://base.prompt.studio/accounts. An explicit HTTPS address overrides both.
Unreleased Cloud project copy APIs are exposed on client.account.
projectsCatalog()returns Cloud membership, device presence, allowed actions, and outstanding deletion receipts. An offline device reports the most recent membership it knows.projectLocalRemoval(id)reports upload certainty and the owned resources removal can clean up.removeLocalProject(id, { discardUnsynced: true })explicitly acknowledges that unsynced work may be lost. The default is false. A recheck that needs acknowledgement throwsLocalRemovalConflictErrorwith a freshpreflight. An incomplete cleanup can be retried with the same project ID.downloadCloudProject(id)explicitly requests to restore a Cloud only copy and returns its presence. UseprojectSyncStatus(id)after the host recovers the project to follow the download and wait for offline readiness.deleteCloudProject(id, { confirm: true })starts or resumes retirement. Read the same operation withprojectDeletionStatus(id)even when the project has no downloaded copy. Onlystate: "completed"means cleanup finished. After a lost reply, read the receipt or repeat the confirmed request when the connection returns.
When showing a destructive confirmation, pass the returned account as expectedAccount in the mutation body. The host rejects a confirmation if the active Cloud account has changed.
stopProjectSync(id) is Make local and preserves the later merge path. Permanent Cloud deletion retires that identity while preserving downloaded device copies as local projects.
Unreleased: pass deviceId to client.sessions.create(projectId, input) or client.workspaces.create(input) to run creation on your selected online Cloud device. Session follow-ups, approvals and cancellation use the session’s owning device automatically. A session never moves. client.account.sendDeviceCommand(projectId, deviceId, command, signal?) exposes the typed actions directly and returns { status, body } from the target. Commands and replies are encrypted and signed, large payloads cross in ordered chunks, and each command needs a fresh one-use authorization from the target. Offline actions fail immediately; nothing is queued for reconnect. A lost reply does not prove that an accepted action failed.
Attachment bytes are submitted with their session action. The complete remote action must fit within 64 MiB after JSON and base64 encoding, across the prompt and all files together; the normal per-file upload limit remains 25 MiB. Oversized actions fail before transfer or target execution. For example, two 25 MiB files exceed the combined encoded limit.
The methods marked ‡ are unreleased and need both the newer SDK and host. They restore a cloud project’s folder from a copy another of your devices captured; see pst projects folder. restoreFolder(projectId, { deviceId, sourceId, path }) and downloadFolder start an operation and return its progress; read it with folderRecovery(projectId) or the folder field of client.account.projectSyncStatus(projectId). Errors carry a code such as destination_exists, destination_created, destination_too_long, name_collision, unsafe_entry, integrity, not_downloaded or keys_unavailable.
client.projects.open(projectId) prepares a managed local folder and restores downloaded artifact files. client.projects.folder(projectId) and client.projects.chooseFolder(projectId, input) read the folder location or attach a chosen checkout before automatic setup; see Get your cloud projects on a new computer.
client.sessions.retainResources(sessionId) keeps a conversation’s native resources while a client has it open, including after its run finishes. It returns a connection with close(). Close it when the tab closes; the host then keeps the session ready for 30 minutes after the last client’s interest or active work ends. The connection shares the session stream, restores interest after disconnect, and does not load history or start a run. Idle providers release their resources without deleting the conversation.
client.sessions.fork(sessionId, { messageId }) copies history through the selected agent reply, inclusive. Omit the options to copy the whole settled conversation. It returns an independent conversation in the same workspace. It preserves the history, agent, model, and parameters without starting a turn. It requires a harness with native fork support. A selected reply can be forked while later work runs or waits in the source queue; copying the whole conversation requires no pending work. This needs the SDK and host additions on main.
client.sessions.imports provides preview(input), start(input), get(id), pause(id), resume(id), and errors(id, { offset, limit }). Inputs contain sourcePath, optional storagePath, and a projectMap from source IDs to existing destination project IDs. Paths belong to the API host. Preview leaves live data unchanged; start/resume return a durable background job with preparation/indexing progress and import counters. Errors are paged with nextOffset.
The REST paths are POST /v1/session-imports/preview, POST /v1/session-imports, GET /v1/session-imports/{id}, POST /v1/session-imports/{id}/pause, POST /v1/session-imports/{id}/resume, and GET /v1/session-imports/{id}/errors. This restores exported historical conversations without starting an agent or adopting the original native conversation. See CLI import behavior for supported formats, project mapping, duplicate identity, checkpoints, failure recovery, and resource limits.
Planner commands
Tickets, statuses, and tags belong to the Planner extension. Use its commands
through client.extensions.execute, or use the pst tickets CLI aliases.
The installed extension must be enabled in the project.
const response = await client.extensions.execute("pstdio.pstdio-planner.command.list-tickets", {
projectId,
params: { status: "In Progress" },
});
if (response.outcome.status === "success") {
console.log(response.outcome.value);
}
Use client.extensions.listCommands(projectId) to discover command IDs. IDs include
the publisher, extension name, contribution kind, and local ID. Do not construct
them from the package name alone.
Extension authoring
@pstdio/sdk/extensions exports contribution helpers, typed references, command
and renderer contexts, storage contracts, and the webview client. It also exports
EXTENSION_API_VERSION, the extension API version of that SDK build.
engines.pstdio declares caret ranges that include the host’s API version.
See API versioning.
Use the composition cookbook for definePage,
shared placement items, resource identity, navigation, controls, qualifyRef,
and typed GuestHost.call capabilities. The
React entry provides
useCommandQuery and useCommandMutation for webviews.
The shared finite-query API provides createScopedQueryClient, query.subscribe,
getSnapshot, invalidate, read and refreshObserved. An explicit read()
retains required work through settlement. refreshObserved() invalidates and awaits
only observed optional work; its caller does not keep a closed presentation alive.
Use the state and lifetime guide
for identity, scope, cancellation and released-dependency requirements.
Other entries
Use ctx.storage.records for durable grouped writes, observed
revisions, and conflict resolution. Keep exact operation IDs for storage retries;
do not rerun commands with external effects. ctx.storage.records and
ctx.storage.assets ship in the release after 0.43.x; see
storage availability.
@pstdio/sdk/apiexports HTTP request and response types.@pstdio/sdk/resourcesexports product resource types.@pstdio/sdk/promptsexportsrenderPrompt(template, data)for Mustache rendering.@pstdio/sdk/hooksis deprecated in 0.44. Use typed hooks from@pstdio/sdk/extensions; external clients useclient.sessions.followUp(sessionId, input). The old hook contexts, payload mirror and singular session facade remain through 0.44.@pstdio/sdk/dataexports draft layout, frontmatter, and ID/name resolution helpers. See data exports.@pstdio/sdk/testingexports command contexts and in-memory storage, file, and resource adapters for extension tests. See testing exports.
Live input
client.sessions.steer(id, { expectedRunStartedAt, prompt, attachments }) sends new input only to the captured active run. Read its identity from getQueuedFollowUps(id) before uploading files. Each attachment is { fileId }. Optional summaryFromSessionId, summaryFormat (brief or detailed), and summaryRole (assistant or all) can supply a source summary with or without a prompt. Live input keeps the current execution settings.
The result is accepted, rejected, or uncertain, as for queued steering below. Inactive, unsupported, blocked, or changed runs reject without starting or queuing another turn. Uncertain delivery retains held evidence and attachments. Do not retry automatically, including after a failed HTTP request whose delivery outcome is unknown.
Queued requests
client.sessions.getQueuedFollowUps(id) returns each request’s queue position, revision, prompt, model, complete parameters, and attachment references. It also reports the current run identity and steering availability.
updateQueuedFollowUp(id, position, { prompt, expectedRevision, model, params, attachments }) saves a complete request without sending input. Optional fields keep their saved values; null model selects the provider default, null parameters reset defaults, and an empty attachment list removes references. A stale revision fails without modifying another request.
combineQueuedFollowUps(id, targetPosition, { sourcePosition, sourceRevision, targetRevision }) combines two saved requests with matching settings. Text follows their queue order and attachments are deduplicated.
steerQueuedFollowUp(id, position, { expectedRevision, expectedRunStartedAt }) sends one saved request into supported active work. Inspect status: accepted includes a delivery ID; rejected includes a reason and message; uncertain includes a delivery ID and message. Never automatically retry uncertain delivery. Unsupported harnesses return a typed rejection.
client.workspaces.watchDiff(workspaceId, { projectId, signal, onReady, onChange })
observes local file/Git diff changes on the client’s existing shared event transport.
onReady establishes the baseline boundary; onChange is an invalidation hint for
finite diff reads. Aborting signal releases the logical subscription without
opening or closing unrelated resources’ connections.
client.workspaces.watchFiles(workspaceId, { projectId, signal, onReady, onChange })
observes local file changes, including non-Git project folders. It uses the same shared client
stream. Keep the observation only while presenting files, reconcile the finite listing on
onReady, refresh it on onChange, and abort when the presentation leaves. Hints do not
replace document contents or save edits. The host shares watches between observers and
checks the workspace’s project, readiness and file-access capability.
Resource Activity (API 0.4.2)
client.activity and ctx.activity use the complete owning resource identity. Owners opt in through the resource kind’s activity declaration; sessions have no Activity. These additions require a host and SDK providing API 0.4.2. See resource Activity for permissions, persistence and CLI examples.
| Methods | Result |
|---|---|
client.activity.capabilities(resource), ctx.activity.capabilities(resource) |
Read the resource’s supported capabilities and discussion permission; null means no Activity. |
client.activity.query({ resource, cursor, limit }), ctx.activity.query(...) |
Read a bounded page with stable IDs, the next cursor and unresolved root-discussion count. |
client.activity.get(resource, id), ctx.activity.get(resource, id) |
Read one entry on that exact resource. |
client.activity.publish(resource, entry), ctx.activity.publish(resource, entry) |
Publish a retry-keyed comment, owner-authored change or immutable revision-bound outcome. The HTTP client accepts optional { sourceSessionId } as a third argument. |
client.activity.resolve(resource, id, resolved), ctx.activity.resolve(resource, id, resolved) |
Resolve or reopen a root discussion. |
client.activity.attach(resource, file), ctx.activity.attach(resource, file) |
Store verified bytes and receive an attachment ID to include in an entry. |
client.activity.readAttachment(resource, id), ctx.activity.readAttachment(resource, id) |
Read attachment metadata and bytes after resource-scoped authorization. |
client.activity.handoff(resource, id, options), ctx.activity.handoff(resource, id, options) |
After explicit confirmation, start or recover the targeted comment’s single linked session on its original device. |
client.activity.watch(resource, { signal, onChange, onReady }) |
Observe invalidations on the client’s shared transport; aborting closes this logical subscription. |
ctx.activity.importEntry(resource, historical) |
Owner-only import that preserves the original author, creation time, source reference and exact outcome revision. |
Existing ctx.activity.record remains available for audit events. Outcomes never carry approval across revisions. Publish a new outcome for corrections; do not duplicate canonical evidence in Reports.
Updated at: 2026-11-12