The HTTP API at a glance

Every route under /api/v1, what it takes and what it returns.

15 min read

Open the browser’s network panel when you sign in or send a message. The paths you see there are the same ones a custom client calls. Use this reference to look up a request, its successful reply, and the errors specific to that operation.

The rules before the route

Discover the workspace sign-in mode
GET /ai/api/v1/access HTTP/1.1
Host: pipal.example

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Content-Length: 16

{"mode":"token"}
  1. Base path and API prefix

    For a build mounted at /ai/, put /ai before /api/v1/access. This request is public.

  2. Configured host

    The host checks the authority even for public reads. This example uses the hostname of an illustrative token-mode deployment.

  3. API caching rule

    The API middleware adds this header before the handler runs.

  4. Sign-in mode

    Use the token exchange when the host returns this mode. In passkey mode, the response also describes setup and recovery availability.

GET  HTTP/1.1
Host: 

HTTP/1.1 200 OK
Content-Type: application/json

Content-Length: 16

1 Base path and API prefix

For a build mounted at /ai/, put /ai before /api/v1/access. This request is public.

An illustrative token-mode exchange under /ai/. Notice where the mount goes and which header keeps the response out of caches.

API paths in the tables start after /api/v1. For a build at /ai/, /models means /ai/api/v1/models. The host check applies even outside the API. A request whose URL host, including the port, matches neither the configured origin’s host nor the local origin’s host gets 403. GET /healthz, or GET /ai/healthz at that base, is public and returns 200 with {ok:true}. With a web build, the same host serves the public client and its /chats/:id entry. A request for the bare non-root mount (such as GET /ai) gets a 308 redirect to the trailing slash, keeping the query string. app.ts

After the host check, the mounted /api/* middleware sets Cache-Control: no-store. Every method except GET and HEAD must carry an Origin equal to the host’s configured origin (scheme, host and any nondefault port, with no trailing slash), including on public sign-in requests. A missing or mismatched origin gives 403. Next, a protected request without a live session gives 401. The request body limit is 128 KiB, with 10 MiB for POST /api/v1/uploads and 8 MiB for paths beginning with /api/v1/extensions/, under the build’s base. Exceeding the applicable limit gives 413. app.ts config.ts

Body shapes below use ? for an optional field. Send Content-Type: application/json for a JSON body, including {}. The shared parser returns 415 for a different media type and 400 for invalid JSON or fields. JSON objects reject extra fields unless the schema explicitly allows them. Field limits that use boundedText() count UTF-16 code units, after trimming where specified. Unless a row says otherwise, success is 200 and JSON. Hono also dispatches HEAD to GET on the built-in GET routes and drops the body. Use the GET route’s session, inputs and status for HEAD. The rows call out two handlers that explicitly take a different path for HEAD. When a row lists no body, the handler needs none. Listed errors add to the common checks above. Host errors use {error}, with an optional code for runtime errors. Unknown or unmounted API paths give 404 after middleware, if the request has passed the session check. Unexpected exceptions give 500. Extension handlers supply their own responses. request.ts README.md app.ts

Access and sessions

Successful sign-in sets pipal_session, scoped to the API under the build’s base path. The cookie is HttpOnly and SameSite Strict. It is Secure when the configured origin uses HTTPS. The matching browser sessionA sign-in record in server memory that the browser refers to with a cookie. lives in server memory for up to 12 hours from sign-in. Issuing a 33rd live session evicts the oldest. Carry the pipal_passkey flow cookie from options to verification when using WebAuthn, the browser’s passkey interface. auth.ts app.ts passkeys.ts

Route and contract
GET /access
Session Public
Returns {mode:"token"} or {mode:"passkey",setup,recovery}. setup is true when no keys are enrolled. recovery is true while a recovery code is active.
POST /session
Session Public in token mode
Body {token}, string up to 256 code units
Returns {ok:true} and session cookie
Errors 401 wrong token
DELETE /session
Session Required in either mode
Returns {ok:true}, ends session and clears cookie. The session’s open event streams end.
app.ts passkeys.ts

These routes are mounted in passkey mode. Assertion and Registration both require base64url strings id and rawId of 1–4,096 characters, type:"public-key" and the object clientExtensionResults. Assertion response requires nonempty base64url clientDataJSON, authenticatorData and signature. Supply a base64url userHandle of 1–4,096 characters. The schema allows it to be absent, but verification returns 403 unless the handle matches the workspace. Registration response requires nonempty base64url clientDataJSON and attestationObject. The schemas allow additional fields at the top level and in response and clientExtensionResults. passkeys.ts

Route and contract
POST /session/passkey/options
Session Public
Body {}
Returns Authentication options and flow cookie
Errors 409 no enrolled key
POST /session/passkey/verify
Session Public
Body Assertion
Returns {ok:true} and session cookie
Errors 403 stale flow or refused assertion, 429 verification capacity
POST /session/passkey/enroll/options
Session Public
Body {code,name}
Returns Registration options and flow cookie
Errors 403 wrong, expired or already consumed code, 429 flow capacity
POST /session/passkey/enroll/verify
Session Public
Body Registration
Returns {ok:true} and session cookie
Errors 403 stale flow or refused registration, 409 duplicate key, 429 verification capacity
GET /passkeys
Session Required
Returns Array of {id,name}
POST /passkeys/change/options
Session Required
Body {name} to add, or {remove} with the key ID
Returns Authentication options and flow cookie
Errors 404 unknown key, 409 last key, 429 flow capacity
POST /passkeys/change/verify
Session Required
Body Assertion
Returns {signedOut} (boolean) for removal, or {options} with registration options and a new flow cookie for addition. Removal revokes sessions signed in with that key and clears the caller’s session cookie when it signs the caller out.
Errors 403 stale flow or refused assertion, 404 unknown target, 409 last key, 429 flow or verification capacity
POST /passkeys/add/verify
Session Required
Body Registration
Returns {ok:true}
Errors 403 stale flow or refused registration, 409 duplicate key, 429 verification capacity

A passkey name has 1–80 trimmed code units. The setup or recovery code has 43 characters from letters, digits, underscores and hyphens. The flow cookie lasts 120 seconds. Sign-in and enrollment routes are public only in passkey mode. Enrollment and key changes share 128 pending flow slots. Sign-in options carry their challenge in the signed flow cookie. At most eight WebAuthn verifications run at once. Successful enrollment consumes the code. Recovery enrollment also invalidates outstanding flows and revokes prior sessions. passkeys.ts passkey-store.ts

Authentication options are PublicKeyCredentialRequestOptionsJSON. Registration options are PublicKeyCredentialCreationOptionsJSON. The server asks for user verification in both and a discoverable credential in registration. The options timeout is 120,000 milliseconds. Setup and recovery codes expire after ten minutes. passkeys.ts passkey-store.ts Access.svelte

Models and profiles

Route and contract
GET /models
Session Required
Returns ModelInfo[]. IDs, display names, provider, reasoning and image support, and allowed thinking levels.
GET /profiles
Session Required
Returns ProfileInfo[]. IDs, names, model and optional thinking level. Workspace-capable profiles include defaultLocation and locations, one entry per enabled locationThe place a chat uses for project tools, either the Pipal host, an account reached over SSH, or a Docker project., even if its probe failed. They include defaultYolo:true when new workspace chats default to YOLO. Each location has id and may include projects, canCreateProjects:true or unavailable:true. Top-level workspace:true and any top-level project fields describe the default location when it is open.
app.ts contracts.ts index.ts

Workspace settings

The location IDs are local (This machine), ssh (SSH machine) and docker (Docker). Use a nonnegative safe integer for revision and distinct IDs in enabled. The default location must belong to that array. Send null for the default location when the array is empty. The boolean defaultYolo starts as false. Omitting it on a settings update preserves the saved preference. Resending the same locations and defaults with the current revision retries enabled locations that are closed. A failed probe leaves the saved selection and revision intact, but can update a location’s error. workspace-locations.ts app.ts

Route and contract
GET /settings/workspace
Session Required
Returns WorkspaceSettings, with revision, enabled, defaultLocation, defaultYolo and locations. Each location entry has id and optional account, host, directory, setup and error. The catalog can include disabled locations.
Errors 404 runtime has no workspace settings
PUT /settings/workspace
Session Required
Body {revision,enabled,defaultLocation,defaultYolo?}
Returns Updated WorkspaceSettings with the next revision
Errors 400 invalid selection or destination needs setup, 404 runtime has no workspace settings, 409 stale revision, 503 probe failed or runtime is shutting down
contracts.ts index.ts

Conversations

A Summary is ConversationSummary. It includes the ID, title, archive flag, profile, model, thinking level and creation time, plus project when set and the resolved location. Core’s workspaceStatus() adds workspaceUnavailable:true if the pinned location or project binding is unavailable, and yolo:true when the grant matches the current workspace. A Snapshot is ConversationSnapshot, which adds the recent transcript, context-window usage, current run fields, partial text, live tools and optional worker or search activity, error and history cursor. index.ts view.ts

Chat settings fields are title?, profile?, project?, location?, model?, thinkingLevel? and yolo?. The name fields title, profile, project and model must contain 1–160 code units when trimmed. The handler trims title, profile and model. Send project exactly as named. New project names must have 1–64 characters, start with an ASCII letter or digit, and use only ASCII letters, digits, spaces, hyphens and underscores, with no trailing space. thinkingLevel accepts null for Auto or a level offered by the selected model. yolo is a boolean. app.ts index.ts

On creation, location accepts a location ID or none. Omit it to use the current default for an eligible profile, or none if no location applies. Where a location can open named projects, omitting project selects pipal-scratch. Omit project for Docker or none. The location and any project are pinned at creation. Repeat their current values in a patch or leave them out. index.ts contracts.ts

Omit yolo on creation to follow the saved default when the chat has a workspace. Send yolo:false to require approval in this chat even if the default is on. A keyed creation remembers the default it first read, including while it opens a project directory. Retrying the same request after a preference change uses the original choice. index.ts

Route and contract
GET /conversations
Session Required
Returns Summary array for top-level chats, including archived ones
GET /conversations/awaiting-approval
Session Required
Returns Summary array for top-level chats with a waiting workspace decision, including requests owned by a specialist or worker
POST /conversations
Session Required
Input Chat settings and UUID requestId?
Returns 201 Snapshot. Identical retries with a request ID return the existing chat’s current view.
Errors 400 invalid settings, profile ineligible for the selected location, invalid project or YOLO without an available workspace, 409 location unavailable, workspace changed while opening the project, conflicting ID reuse or conflicting project directory (including a file or symlink in its place), 503 project could not be opened
GET /conversations/search
Session Required
Input q and boolean string archived? (default false)
Returns {results}, up to 50 summaries with snippet (string or null)
Errors 400 query outside 1–256 trimmed code units or bad archive filter, 503 shutting down
GET /conversations/:id
Session Required
Returns Snapshot
Errors 404 unknown chat
PATCH /conversations/:id
Session Required
Input Chat settings and boolean archived?, at least one field
Returns Snapshot. Archiving also pauses the chat’s active routines.
Errors 400 invalid profile, model or thinking level, or enabling YOLO without a current workspace, 404 unknown chat, 409 owned child, location or project change, or an active run blocking changes to profile, model, thinking level or YOLO
GET /conversations/:id/history
Session Required
Input Query before, a positive safe integer from the current snapshot or previous page
Returns {messages,before?}, older messages in chronological order. If there is another page, send back its before.
Errors 400 invalid cursor, 404 unknown chat
GET /conversations/:id/session-info
Session Required
Returns SessionInfo, with storage, message and tool counts, timing, tokens, cost, model breakdown, cache re-billing and optional specialist usage
Errors 404 unknown chat
app.ts index.ts routines.ts contracts.ts development-workspace.ts transcript-search.ts

Messages and runs

A receipt is {id,requestId}. The id is the saved submission ID as a string. Reuse the same requestId with the same text, ordered text files and ordered attachment IDs when delivery is uncertain. The model text, including text-file labels and separators, can use up to 32,768 UTF-16 code units. Supply nonblank model text or at least one upload ID. An attachment list accepts up to four distinct UUIDs with a 20 MiB total for originals. The 12 MiB preparation limit counts UTF-8 text bytes and base64 image lengths before filename labels are added. contracts.ts index.ts uploads.ts

Route and contract
POST /conversations/:id/messages
Session Required
Input {text,requestId,attachmentIds?,textFiles?}. Each text file is {name,text} with a nonempty name. Request IDs use 1–128 letters, digits, underscores or hyphens.
Returns 202 receipt
Errors 400 invalid input, unavailable model, images on a text-only model, or unreadable PDF or image during preparation, 404 unknown chat or upload, 409 busy, archived, owned child or conflicting ID reuse, 413 original or prepared batch limit, 429 concurrent run or attachment preparation limit, 503 shutting down
POST /conversations/:id/workspace-approvals/:task
Session Required
Input {allow,park}, boolean and nonnegative safe integer. Use approval.taskId and approval.park in the owning chat, including a specialist’s or worker’s ID when it owns the call.
Returns {ok:true} when the decision is delivered. The woken call still checks its workspace binding before running.
Errors 404 unknown chat or malformed task ID, 409 changed park or task no longer awaiting that decision
POST /conversations/:id/stop
Session Required
Input No body. Optional query runId from the running snapshot, a positive safe integer in decimal with no leading zero.
Returns 202 {ok:true}. A stale run ID has no effect. Omitting it stops the active run.
Errors 400 invalid run ID, 404 unknown chat, 409 owned child
POST /conversations/:id/resume
Session Required
Input {runId}, using the snapshot’s resumableRunId, a positive safe integer as a string of 1–16 decimal digits with no leading zero. An unarchived top-level chat can expose this field after an abort without a deadline marker (stopped, for example after Stop), a deadline abort (failed, time limit reached), a hard turn limit (failed, turn limit), or a successful reserved final reply after the tool budget runs out (idle).
Returns 202 receipt for the continuation, with requestId equal to resume: followed by the run ID. Retries return the same receipt.
Errors 400 invalid ID or unavailable model, 404 unknown chat, 409 stale or ineligible run ID, busy or archived chat, or owned child, 429 run capacity, 503 shutting down
app.ts index.ts view.ts turn-budget.ts

The event stream

The snapshot carries generation backoff in retry:{attempt,at,reason}. The attempt is the one that failed, counted from one, and at is the next try in Unix milliseconds. Each active summary in compactions has a task ID, trigger, blocking flag, attempt and optional retry schedule. lastCompactionFailure records the last summary failure until a summary succeeds. A settled model error adds failureReason. All these reasons are fixed categories defined in contracts.ts. contracts.ts view.ts

Route and contract
GET /conversations/:id/events
Session Required
Input No body. Optional delta=1 or compact=1
Returns text/event-stream with X-Accel-Buffering: no
Errors 404 unknown chat before streaming. A watch failure after headers can produce resync.
HEAD /conversations/:id/events
Session Required
Returns Stream headers, no body or watch
Errors 404 unknown chat

The first view arrives in a snapshot event containing {version:1,snapshot}. Later snapshot events replace it. Compact mode can send update with the same envelope and messages omitted. Keep the last full message window for those updates. Delta mode takes precedence. After the first snapshot, it sends a delta event with {version:1,revision,edits} only when the view has changed. Revisions start at one and increase per emitted delta on that connection. Edits are ["set",path,value], ["delete",path] or ["slice",path,start,end,tail]. A path is an array of keys or indexes. A slice keeps the half-open range from start to end and appends the string or array tail. Reopen the stream for a full snapshot after resync with {version:1}. Every 15 seconds the stream sends a ping with {} in delta mode or a heartbeat comment otherwise. Disconnect, session revocation or expiry, and host shutdown end the watch. See Live streams for the client’s application rules. app.ts contracts.ts

Uploads

Route and contract
POST /uploads
Session Required
Input Original PNG, JPEG, GIF, WebP or PDF bytes, matching Content-Type, and percent-encoded X-Filename (1–255 UTF-16 code units after decoding and trimming, with no slashes, backslashes or ASCII control characters)
Returns 201 {id,name,mimeType,size}, size in bytes
Errors 400 invalid name, unreadable image header, missing dimensions or more than 32 million pixels, 413 over 10 MiB, 415 unsupported type or signature mismatch
GET /uploads/:id
Session Required
Returns Original bytes with recorded media type, length and inline filename under a sandbox policy
Errors 404 malformed upload ID or missing upload metadata
HEAD /uploads/:id
Session Required
Returns Original headers with no body
Errors 404 malformed upload ID or missing upload metadata

The upload and the send are separate requests. Use the returned ID in attachmentIds to attach an existing upload to a message. Files in, artifacts out explains preparation. app.ts uploads.ts

Artifacts

Snapshots and history carry the artifact card as {id,conversationId,title,revises?,kind?}. A completed delegate result can carry the same references in delegation.artifacts. kind: "file" identifies a published project file, and its title is the filename. HTML cards omit kind. Use the card’s conversationId and id in the routes below. Lookup also accepts another conversation in the same delegation tree. contracts.ts view.ts web-artifacts.ts

Route and contract
GET /conversations/:id/artifacts/:artifactId/preview
Session Required
Input Sec-Fetch-Dest: iframe and Sec-Fetch-Site: same-origin
Returns Web artifact HTML under the preview sandbox policy, with same-origin framing
Errors 403 wrong fetch context, 404 unknown chat, malformed ID, missing or out-of-tree artifact, or a file artifact
GET /conversations/:id/artifacts/:artifactId/download
Session Required
Returns For a file artifact, the saved bytes as an application/octet-stream attachment with the original basename. For a web artifact, the HTML source as a text/plain attachment with a title-derived .html name. Both use a UTF-8 filename* and an ASCII filename fallback in Content-Disposition.
Errors 404 unknown chat, malformed ID, or missing or out-of-tree artifact
app.ts index.ts web-artifacts.ts

Routines

A Schedule is {kind:"once",localTime,timezone} or {kind:"cron",expression,timezone}. Use YYYY-MM-DDTHH:mm for a one-off, optionally adding seconds and up to three fractional second digits. The time must be unambiguous in the selected IANA timezone. For a repeating schedule, supply five numeric cron fields in minute, hour, day-of-month, month, day-of-week order. The limits are 32 code units for the local time and 128 each for the trimmed expression and timezone. A Definition is {name,prompt,schedule}. A Routine adds id, revision, state (active, paused or finished), nextRunAt (number or null) and lastRun (null or {scheduledAt,status,reason?,messageId?}). Last-run status is running, waiting, completed, stopped or failed. Times in these replies are Unix milliseconds. app.ts routine-schedule.ts contracts.ts

Route and contract
GET /routines
Session Required
Returns RoutineGroup[], grouped by top-level chat, including archived chats with routines
POST /routines/preview
Session Required
Body Schedule
Returns {nextRunAt}
Errors 400 invalid schedule or no future time
GET /conversations/:id/routines
Session Required
Returns Routine array, empty when the chat has no routines.
Errors 404 unknown chat
POST /conversations/:id/routines
Session Required
Body Definition and UUID id?
Returns 201 Routine. Same ID and definition return the existing routine.
Errors 400 invalid name or prompt, or a new routine with an invalid schedule or no future occurrence, 404 unknown chat, 409 conflicting ID, archived chat, owned child or 50-routine limit
PUT /conversations/:id/routines/:routine
Session Required
Body Definition and positive safe integer revision?
Returns Updated Routine
Errors 400 invalid name or prompt, or a changed schedule that is invalid or has no future occurrence, 404 unknown chat or routine, 409 owned child, archived chat when rescheduling an unpaused routine, or stale revision with code routine_revision_conflict
PATCH /conversations/:id/routines/:routine
Session Required
Body {paused}, boolean
Returns Updated Routine
Errors 400 resuming a repeating schedule whose next occurrence cannot be calculated, 404 unknown chat or routine, 409 owned child or resuming a paused routine in an archived chat or after its one-off time
DELETE /conversations/:id/routines/:routine
Session Required
Returns {ok:true}
Errors 404 unknown chat or routine, 409 owned child

Names accept 1–160 trimmed code units and prompts 1–32,768 code units with nonblank content. Include the revision you loaded on PUT when you need to detect a concurrent edit. app.ts routines.ts

Providers

These routes manage the OpenAI connection separately from workspace access. Provider status contains {enabled,connected,model}. A connected account can have an empty model string after a refresh finds no eligible model. The session that owns a sign-in attempt can also receive attempt:{id,status,url?,error?}. The attempt status is pending, ready or failed. Poll the status route for the authorization link or the eventual failure message. provider-login.ts models.ts

Route and contract
GET /providers/openai/status
Session Required
Returns Provider status
POST /providers/openai/login
Session Required
Body {}
Returns 202 Provider status
Errors 409 server-managed provider, session closing, disconnect or another session’s active sign-in
POST /providers/openai/login/:id/callback
Session Required
Body {callback}, complete redirect address at http://127.0.0.1:1455/auth/callback, 1–8,192 code units. The scheme can be omitted. Supply single code, client_id and matching state parameters.
Returns 202 Provider status
Errors 400 invalid callback, 404 attempt missing or owned by another session, 409 attempt not waiting for callback
DELETE /providers/openai/login/:id
Session Required
Returns {ok:true}
Errors 404 attempt missing or owned by another session
DELETE /providers/openai/connection
Session Required
Returns Provider status after removing the connection
Errors 409 server-managed provider or account change in progress, 500 credential removal failed
app.ts provider-login.ts chatgpt-callback.ts

Extensions

Route and contract
GET /extensions
Session Required
Returns Configured server extension names as a string array. When no enabled location is open, the response omits pipal.coding and pipal.bash. The array describes the host, independent of any chat’s grants. app.ts index.ts
Any /extensions/:name/*
Session Required
Body Defined by the extension handler
Returns Defined by the handler
Errors 404 no handler for this name, plus handler-specific errors

The host strips Cookie and Authorization before handing the request to the extension. The handler receives the request and the path below its mount. If the reply has no Content Security Policy, the host supplies a sandbox policy. app.ts app.test.ts

For the reasons behind the API’s access checks and stream format, see Decisions and trade-offs.

Recap

  • Prefix each API path with the build’s base and /api/v1. Send the configured origin on writes and a session cookie on protected routes.
  • A send returns a receipt. Read the snapshot or open the event stream for the answer and current run state.
  • For a failed operation, read the error body alongside its HTTP status.

In the source

Book contents

Search the book