The core runtime
Admission, limits and deadlines: the rules that keep runs orderly.
You press Send in a chat that looks idle. Somewhere else, a timer is about to end another reply, and another tab is approving a command. Core gives those changes a shared order. It also writes down when your new run must finish, so the clock can survive the process that set it.
In this chapter
- Locate the runtime’s boundary between Hono and Pi Durable
- Follow the checks that accept or refuse a fresh input
- Work out when a chat counts against capacity and when its turn or time budget runs out
- Read a settled status and understand what Resume response starts
The runtime takes ownership before opening the store
The server calls createRuntime() with settings and a callback that loads the host’s profiles and extensions. Core first takes an exclusive lock on owner.sqlite in the data directory. It holds that lock while it runs the callback and opens durable.sqlite through Pi Durable. A second process pointing at the same data directory fails before it can start scheduling there. index.ts store-lock.ts
The returned object gives Hono specific operations on chats. The same runtime can serve a list of profiles, accept an input, or watch a reply. The host can close it as a unit, and the closed promise reports when the harness closes or fails. index.ts main.ts
When you first press Send in a new chat, the browser asks Core to create the chat before it posts your message. In create(), Core uses the requested locationThe place a chat uses for project tools, either the Pipal host, an account reached over SSH, or a Docker project., or the owner’s default when the profile can use a workspace and no location was given. If a project folder needs to be opened, Core opens it outside the database transaction and checks the binding again before saving. The location and any project name go into pipal.chat, along with the scope for a named project or Docker workspace. To use a different location or project, start a new chat. App.svelte index.ts
Deep diveWhat the runtime exposes to the host
| Job | Runtime surface |
|---|---|
| Discover settings and manage the model account | models, profiles, chatgpt |
| Create or change a chat | create, configure |
| Find and read chats | list, get, search, history, watch, sessionInfo |
| Retrieve artifacts | webArtifact for HTML previews, downloadArtifact for HTML or published file downloads |
| Send, interrupt, or continue | submit, stop, resume |
| Schedule prompts | list, listAll, create, edit, setPaused, remove on routines |
| Handle approval | waitingForApproval, approveWorkspace |
| Read or change workspace locations | workspaceSettings, setWorkspaceSettings |
| Manage the lifecycle | close, closed |
openRuntime() checks the runtime limits, installs extensions and validates profile settings against the model registry before opening the harness. Closing clears deadline timers and waits for the admission queue, transcript searches and pending workspace settings changes before closing the harness. Cleanup then unsubscribes from location updates, closes the search index and model registry, and releases the lock. Durable by default covers what Pi Durable recovers. index.ts
The optional web features enter the runtime through separate paths. When pipal.public-web is enabled, the host callback supplies tools for Exa search and Jina Reader. Core installs pipal.web-search separately when enabled. Its generation hook can add hosted search to a compatible provider request when the chat’s profile grants it. main.ts hosted-search.ts
loadWorkspaceLocations() starts fresh installs with all locations off. With an existing durable.sqlite and no settings file, it can import the configured SSH or Docker grant. workspace-locations.ts
POST /api/v1/conversations returns 201. A new creation request without a requested or applicable default location uses none. A matching retry can reuse the saved chat or its reserved location. create() returns 400 if the profile cannot use the selected workspace and 409 for an unavailable location or a changed backend detected at save. A second save attempt that still needs the project opened returns 503. patch() returns 409 for a changed location or project. app.ts index.ts
Admission
- Hono app.ts
- Core index.ts
- Pi Durable
- SQLite store
New input
Hono → Core · submit()
Validate the input
Core checks the formatted message and the request ID before joining the queue. Invalid input or a reserved ID prefix gets 400.
Core → Core · Queue
Take a turn
In
exclusive(), a closing runtime returns 503. Otherwise Core looks up the chat, returns 404 if it cannot find it or 409 if it is task-owned, and then inspects Pi’s pending submissions.Core → Pi Durable · conv.commit()
Check the request ID first
Core looks for a prior submission. A matching retry returns its old receipt. Reusing the ID for different input returns 409.
Core → Core · Chat setup
Check whether this chat can take new work
An archived chat returns 409. If its saved model has left the configured catalog, Core returns 400.
Core → Core · Capacity
Check who is already running
A run in this chat returns 409. Then Core counts qualifying pending submissions against the host limit, which can return 429.
Core → Pi Durable · conv.admit()
Place the input with a reject-if-busy policy
Pi can still report the chat busy. On success Core refreshes instructions, extension grants and tool filters, adding the turn-budget hooks to older chats with a current profile. It keeps the saved turn cap and records a fresh deadline.
Pi Durable → SQLite · Commit
Make the placement and deadline durable
The entry, generation task, submission record, and deadline commit together.
Core → Core · arm()
Check the deadline and set its timer
Still in this pass of the queue, Core starts a submission wait and checks for expiry. Settlement cancels the timer.
Core → Hono · Receipt
Return the submission ID and request ID
The message route returns the receipt as the body of its 202 response.
Matching retry
Hono → Core · submit()
Validate the input
Core checks the formatted message and the request ID before joining the queue. Invalid input or a reserved ID prefix gets 400.
Core → Core · Queue
Take a turn
In
exclusive(), a closing runtime returns 503. Otherwise Core looks up the chat, returns 404 if it cannot find it or 409 if it is task-owned, and then inspects Pi’s pending submissions.Core → Pi Durable · conv.commit()
Check the request ID first
Core looks for a prior submission. A matching retry returns its old receipt. Reusing the ID for different input returns 409.
Pi Durable → Core · Prior submission
Use the record already on disk
The saved entry matches this input. Core skips the fresh admission checks and returns that submission’s ID with the request ID.
Core → Hono · Original receipt
Acknowledge the same input
No new generation task or deadline is created. Hono still sends 202.
Host at capacity
Hono → Core · submit()
Validate the input
Core checks the formatted message and the request ID before joining the queue. Invalid input or a reserved ID prefix gets 400.
Core → Core · Queue
Take a turn
In
exclusive(), a closing runtime returns 503. Otherwise Core looks up the chat, returns 404 if it cannot find it or 409 if it is task-owned, and then inspects Pi’s pending submissions.Core → Pi Durable · conv.commit()
Check the request ID first
Core looks for a prior submission. A matching retry returns its old receipt. Reusing the ID for different input returns 409.
Core → Core · Chat setup
Check whether this chat can take new work
An archived chat returns 409. If its saved model has left the configured catalog, Core returns 400.
Core → Core · Capacity
Check who is already running
A run in this chat returns 409. Then Core counts qualifying pending submissions against the host limit, which can return 429.
Core → Hono · 429
Reject the attempt
The fresh input has no receipt and the chat has no live run. The inspected list includes enough ownerless submissions that are not waiting for approval to reach the limit. The caller can try again later.
Hono → Core
Validate the input
Core checks the formatted message and the request ID before joining the queue. Invalid input or a reserved ID prefix gets 400.
Once Hono has checked the request’s shape, it calls submit(). Core checks the formatted text, including inline file names and contents, against its 32,768 UTF-16 code unit limit and checks the request ID, then gives the attempt its turn on a promise chain shared across conversations. That chain is the admission queueThe shared promise chain that orders admission passes, deadline checks, workspace approval decisions and interruptions when a workspace location is disabled.. It orders admission passes, deadline checks, workspace approval decisions and interruptions when a location is disabled. The Hono server follows the checks before this call. contracts.ts index.ts
Within a pass, Core looks for the request IDA value the client sends again when retrying the same input so the server can recognize it. before it checks whether the chat can accept fresh work. A matching submission gives Core the receipt to return. For fresh work, Core checks the chat’s archive flag and saved model, then checks for an existing run and counts pending submissions against the admission limit. A successful admissionPipal’s acceptance of an input in the commit that saves the message, its work, and its run deadline. commits the input and its deadline together. Follow one message shows how the browser uses the receipt. index.ts
Deep diveWhy the next attempt runs even when this one fails
let line: Promise<unknown> = Promise.resolve();function exclusive<T>(operation: () => Promise<T>) { const result = line.then(operation); line = result.catch(() => {}); return result;}The caller receives the original result, including its rejection. The next caller waits on the version that has caught the rejection. Within the pass, the pending-submission list comes from harness.inspect() before conv.commit(). The receipt check and the remaining admission checks run inside the commit. Pi requires conv.admit() to precede other table writes in that transaction. index.ts README.md
| In order | Refusal |
|---|---|
Validate formatted text and request ID before joining exclusive() |
400 for blank formatted text without upload IDs, formatted text over 32,768 UTF-16 code units, a request ID outside 1–128 code units, or a routine: or resume: prefix in a direct Core call. The HTTP schema already rejects colons. |
| Check shutdown, find the chat, reject owned children, then inspect pending submissions | 503 for shutdown, 404 for an invalid ID or a missing conversation or chat document, 409 for a task-owned conversation |
| Look up the receipt and compare the input | 409 for different input under the existing ID. A match returns the old receipt. |
| Check archive, resolve the configured model, check the live run, then check host capacity | 409 for archive, 400 for an unavailable model, 409 for a running chat, 429 for a full host |
| If necessary, prepare uploads outside this pass and go back through the queue | Preparation can fail before another pass. If the model’s image support changed, Core prepares again. |
Check prepared image content, then call conv.admit() |
400 if prepared content contains images and the model cannot accept them. Pi’s ConversationBusy maps to 409. |
After Pi places the input, savedChatChange() checks whether the saved instructions, extension grants or list of removed tools need updating for the chat’s current binding. Core then records the deadline. File preparation happens between passes, outside the queue and the transaction. The host’s preparer can return 404 for missing uploads, 429 when two preparations are already underway, 413 for size, or 400 for unsuitable or unreadable content. Files in, artifacts out follows what the second pass checks. Scheduled prompts use the shared admission transaction too. Routines explains how a timer dispatches one. index.ts uploads.ts
setWorkspaceSettings() saves changes on its own promise chain, so a slow connection probe leaves the admission queue free. After the save, it takes a turn through exclusive() to mark affected workers as stopping and abort the runs with pending workspace work at disabled locations, including independent worker runs there. Then it notifies the open watches. index.ts
The limits count different kinds of work
Start with an idle chat whose model asks for two tools in one response. That is one tool roundA model response that requests tools, together with the tool calls it requested., and Pi Durable counts it once toward the run’s saved cap. The count starts at zero for each new run and survives a restart mid-run. When Core applies a profile’s settings, it saves the lower of the applicable runtime cap and the profile’s max_turns. A profile that omits the key uses the runtime cap. index.ts README.md
Key under [runtime] |
Default | Config range | What it bounds |
|---|---|---|---|
max_concurrent_runs |
2 | 1–16 | Pending top-level submissions that count at admission. Also sets the size of a separate pool of worker slots. |
max_turns |
50 for top-level Developer chats, 20 for other top-level chats and foreground specialists | 1–100 | A configured value replaces both defaults. The profile can lower the cap. |
run_timeout_ms |
120,000 ms | 1,000–3,600,000 ms | Initial elapsed-time budget for a newly admitted chat input. |
worker_max_turns |
100 | 1–500 | Tool rounds per independent worker run, subject to the worker profile limit. |
worker_timeout_ms |
1,200,000 ms | 1,000–3,600,000 ms | Initial elapsed-time budget for a worker assignment. The worker budget does not set a finishing window. |
The cap is saved in pi.agent. A new Developer chat with the bundled profile and no runtime override gets 50. If an older Developer chat already saved 20, its next admitted input refreshes the turn-budget extension and still uses 20. Reapply its profile to calculate the cap from the current settings. Profiles and models shows what else that refresh changes. index.ts developer.md
Pipal warns the model when it has two tool rounds left before the final request, then again when it has one. With a cap of 3, two rounds can run tools before Pipal asks for a text answer. A cap of 1 still allows a round of tools. If the model uses it, Pi reaches the hard cap and records turn_limit after the tools finish. turn-budget.ts runtime.test.ts
The configuration file accepts integers in the ranges above. Direct Core callers have a wider guard: all five limits must be safe integers from 1 through 2,147,483,647. A profile’s optional max_turns must be a positive safe integer. index.ts profiles.ts
Capacity counts inspected pending submissions from conversations that have no owner and are not waiting for workspace approval. A specialist answering on behalf of another chat comes under its parent’s admission. A chat waiting for workspace approval uses no slot, so another conversation can start while you’re deciding. Independent workers have their own deadline and hold a slot in a separate pool until the assignment settles. Delegation follows the specialist, and Workers follows that separate budget. index.ts
Deep diveHow Pipal leaves room for a final answer
pipal.turn-budget subtracts the rounds used from Math.max(1, maxTurns - 1). At zero it saves the generation task ID in pipal.chat.closeoutRun, asks for final text using the saved results, and removes the tools from that request. It also sets tool_choice: 'none' for OpenAI and DeepSeek. If a provider still requests a tool, the tool hook blocks its execution and Pi can still reach the hard cap. turn-budget.ts runtime.test.ts
A saved deadline can move
- Timer
- Core index.ts
- SQLite store
- Pi Durable
Core → SQLite · Save deadline
Begin with a deadline on disk
Admission saves
deadline = now + 120,000ms inpipal.chatand records a 90-second finishing allowance. This example has prior work before the current model request and no approval or reserved time.Core → Timer · Set timer
Schedule the next check
Inside
arm(), Core starts a settlement wait and callsexpire(). The deadline is still ahead, so Core schedules a check.Timer → Core · Timer fires
Queue a check when 120 seconds elapse
The timer schedules an expiry check through
exclusive(). The check reads the current deadline and confirms the submission is still placed.Core → Pi Durable · streamingReply()
Look for an answer already arriving
The current live generation has nonempty text, and the unused finishing window still reaches into the future.
Core → SQLite · Spend grace
Give the answer until 210 seconds
Core adds 90 seconds to the saved deadline and clears the allowance.
Core → Timer · Rearm
Schedule a check at the extended deadline
Core arms a new timer for the time remaining until the extended deadline.
Timer → Core · Timer fires again
Check the submission again
The second check finds the submission still placed and due at or after 210 seconds. The finishing window has already been spent.
Core → SQLite · Mark time limit
Record why the run is ending
Core sets the
timeLimitmarker in the chat before aborting.Core → Pi Durable · conv.abort()
End the work
Pi aborts the run. A settled snapshot with an aborted run failure reports
failedwith “time limit reached.”
Core → SQLite
Begin with a deadline on disk
Admission saves deadline = now + 120,000 ms in pipal.chat and records a 90-second finishing allowance. This example has prior work before the current model request and no approval or reserved time.
Core records a run deadlineA timestamp saved with the chat that Pipal uses to decide when to end a run, with adjustments for approvals and reserved tool or worker time. as an absolute timestamp in epoch milliseconds in pipal.chat when it admits the input. Core stores the timestamp on disk and keeps the timer in memory. On each wake, Core checks whether the submission is still placed and whether the deadline has moved. If the effective deadline has moved later, Core sets another timer. index.ts
If the effective deadline is due while the run is waiting for a workspace decision, Core leaves it parked. When Core delivers your approval or denial, it adds the elapsed wait to the saved deadline and checks the clock again. The wait can include time when the host was down. An approved command can also spend time on its own clock, and a reply already showing text can get one finishing window. Approvals and YOLO follows the decision itself. index.ts
Deep diveHow the timer accounts for waits, commands, and restarts
expire() reads the current deadline in a commit and adds active command and worker wait reservations. A wait_worker call reserves 1–300 seconds, 300 by default. When it wakes, it credits elapsed time up to that cap, clears its reservation, and asks Core to check again. A due deadline stays parked for workspace approval, including in a foreground specialist or a worker the chat is waiting on. Delivering the decision checks again. streamingReply() looks for nonempty live text, including from a foreground specialist. Core spends the allowance if it would extend the effective deadline past now. It clears the allowance and rearms from the new deadline with a minimum delay of 1 ms. On expiry, Core saves the timeLimit marker in the chat and any affected specialists before calling conv.abort(). index.ts workers.ts
The command wrapper calls withWorkspaceToolTime(), which uses the runtime callback when one is installed. runOnToolTime() records startedAt and limitMs against the budget owner. While the command runs, expiry adds the full reservation. Core refuses to start the reserved operation if the saved deadline has already passed. When the operation ends and its context has not been aborted, finishToolTime() adds the elapsed command time up to the cap, clears the reservation, and Core queues another expiry check. This can bring the next check forward. The wrapper covers the bounded command execution inside the project tool. The reservation must be a safe integer between 1 and 3,600,000 ms. The shared bashDefinition for This machine, SSH machine and Docker accepts timeouts of 1–3,600 seconds, and both Bash implementations default to 60 seconds. index.ts project-tool-definitions.ts project-shell.ts development-workspace.ts
At startup, interruptLocations() also catches work at locations whose disable was saved before the old process could abort it. Core then settles saved tool reservations on pending submissions before arming submissions that own their budgets and explicitly resuming the harness. That includes independent workers. Foreground specialists share the parent’s timer. Pi can start scheduling as soon as Core waits on a pending submission. The initial recovery check compares the saved deadline with the current time, so host downtime normally uses up budget. It skips the finishing window. A later timer check can still grant it for live text. If the effective deadline has expired and no approval is pending, Core marks the time limit and aborts. index.ts README.md
The last outcome determines what you can resume
The browser’s conversation snapshotThe JSON view Pipal assembles for the browser from saved chat state, recent messages, and live work. gets its status from view.ts. Core looks at Pi’s live run and last failure, plus the time-limit marker it saved. That marker is why a timeout can display a failure even though Core and the Stop button both use an abort. view.ts
| Status | How snapshot() gets it |
|---|---|
running |
A live run exists. The snapshot includes its task ID. |
idle |
No live run, no error text, and no aborted failure. A successful answer on the reserved final request also settles here. |
stopped |
No live run, and the recorded failure is an abort without the time-limit marker. |
failed |
No live run and there is error text. An aborted failure with the time-limit marker gives error: "time limit reached". Pi’s hard cap gives error: "turn limit". Other reasons have underscores replaced by spaces. |
In a top-level, unarchived chat with no live run, resumableRunId can name a stopped or timed-out run, a hard turn_limit failure, or a successful reserved final answer. Other run failures leave this field absent. The browser says “This response reached its turn limit.” for either turn-budget outcome and offers Resume response. You can also send a follow-up yourself. view.ts App.svelte
Resume response sends {runId} to POST /api/v1/conversations/:id/resume. The server returns a submission receipt with 202. Core admits a new input with a fresh deadline and a fresh count against the chat’s saved cap. The continuation prompt points the model to the saved conversation and tool results. app.ts index.ts
Deep diveResume is a new admission with a stable receipt
resume() validates a positive, safe integer written as a decimal task ID and derives the request ID resume:<taskId>. Core first checks shutdown and finds the writable chat. Inside the commit an existing resume receipt returns immediately. Otherwise Core applies the usual fresh admission checks and compares the requested task ID with resumableTask(). A different or absent ID returns 409. The next fresh input clears the saved closeoutRun marker, and Pi clears runFailure when a new run starts. index.ts view.ts README.md
For an abort, Core checks the newest entry at or after the failed run’s first entry. If it is from the failed task and contains an aborted assistant message, Core includes up to 16,384 UTF-16 code units from the tail of that text. The new input has a pipal.resume transcript entry, which view.ts displays as Resume response. index.ts contracts.ts view.ts
Core can now tell the difference between work that is running, work that has stopped, and work that has failed. How does a browser that arrives halfway through get the current picture? Live streams follows that first snapshot and the changes that come after it.
Recap
- The runtime holds the store lock. Its admission queue orders short decisions across chats.
- Capacity is checked when Pipal accepts fresh work. Turn limits and deadlines govern work after admission.
- Pipal reserves room for a text answer. Resume response admits a new input after a reserved final answer, a hard turn limit, or an abort.
- A chat waiting for approval is excluded from the host limit. Can you send a fresh message to that same chat?
- Yes, because its slot is free
- Yes, the message waits behind the approval
- No, the chat still has a live run
Answer and explanation
No, the chat still has a live run
The per-chat busy check runs before the host capacity check. A paused run still occupies its chat.
- The deadline arrives while a normal timer check sees nonempty text in the live generation. The saved finishing window is unused and would still reach into the future. What can Core do?
- Add the saved finishing window once
- Restart the full run on every new chunk
- Switch the chat to idle without aborting
Answer and explanation
Add the saved finishing window once
Core can extend the deadline once for live visible text. The commit that extends it clears the allowance.
- A reply used its reserved final request and the first Resume response POST committed, but the tab missed the 202. What happens if it repeats the request with the same task ID?
- It starts another continuation
- It gets the first continuation’s receipt
- It resumes the interrupted task in place
Answer and explanation
It gets the first continuation’s receipt
The task ID derives the same resume request ID, and the runtime checks that receipt before considering fresh admission.
A chat waiting for approval is excluded from the host limit. Can you send a fresh message to that same chat?
The deadline arrives while a normal timer check sees nonempty text in the live generation. The saved finishing window is unused and would still reach into the future. What can Core do?
A reply used its reserved final request and the first Resume response POST committed, but the tab missed the 202. What happens if it repeats the request with the same task ID?