# praecise-harness The framework for AI agents. A folder is an app. > Praecise names two things that work at different levels. **This is > praecise-harness**: it runs agents — models, escalation, grounding, memory, > resumable workflows. [praecise-engine](https://github.com/Praecise/praecise-engine) > is the acceleration layer underneath a model: speculative decoding, batching, > backend tuning. One makes an agent work; the other makes a model faster, and > neither needs the other to be useful. The `@praecise` npm scope is shared on > purpose — it is the family, not either product. > This package was previously published as `praecise`. That package name is > deprecated: install `@praecise/harness`. The command is still `praecise`. You describe what an agent is for, what it knows, and what it may act through. Everything underneath — which model to use, when to escalate to a stronger one, how to ground an answer in your files, how to remember a conversation, how to resume a workflow that stopped for a human — is derived and handled for you. ``` my-app/ ├─ agents/support.ts ├─ functions/refund.ts ├─ memory/faq.md └─ .env ``` ```ts // agents/support.ts import { agent } from "@praecise/harness"; export default agent({ role: "Customer support for Acme.", tools: ["refund"], }); ``` ```sh npx @praecise/harness dev ``` ``` → http://localhost:3000/support chat UI · REST · MCP endpoint ``` --- # Install Node 22 or newer. ```sh npm i @praecise/harness ``` Or start a new app from scratch: ```sh npx @praecise/harness init my-app cd my-app npm install ``` Put one key in `.env` and you are running: ```sh PRAECISE_API_KEY=... ``` That runs the app on Praecise Cloud, which decides what each rung of the ladder runs on. There is nothing to choose and no model id to keep current. `PRAECISE_GATEWAY_URL` sends that key to another address, where the cloud is reached somewhere other than its public one. To run on your own endpoints instead, describe them in `praecise.config.ts` and put their keys in `.env`: ```ts export default defineConfig({ models: { house: { url: "https://models.internal", credential: "HOUSE_KEY", speaks: "chat", fast: "…", balanced: "…", best: "…", room: 200_000, }, }, }); ``` The first endpoint whose credential is present is the one that runs, and a declared endpoint always beats the cloud. Naming a single model is fine — every rung then runs on it. The framework knows no endpoint but Praecise Cloud by name: a base URL and a model id belong to the app that chose them. `room` is how much context that endpoint has, in tokens. Everything carried into a request — the instructions, what was recalled, the conversation so far, and what a tool handed back — is a share of it, so an endpoint with room to spare uses it. Leave it out and a modest figure is assumed, which costs you nothing except some of the conversation you could have carried. An endpoint with needs of its own says so in the same three lines rather than in a patched copy of the framework: ```ts house: { url: "https://models.internal", credential: "HOUSE_KEY", credentialHeader: "x-house-key", headers: { "x-region": "eu" }, body: { chat_template_kwargs: { enable_thinking: false } }, }, ``` `credentialHeader` is for an endpoint that refuses `Authorization: Bearer` and wants its own key header; the credential still comes from `credential`, so nothing in your app has to read the secret in order to place it. `headers` are sent with every request and applied last, so one of them beats anything else the wire would send. `body` is for fields the endpoint's runtime names and the protocol does not — merged underneath the request, so what was actually asked for wins and `model` and the conversation can never be replaced from a config file. An endpoint that serves one request at a time refuses everything queued behind the one in flight, and crossing to a dearer model on that is paying more precisely because the cheap one was busy. `limits: { retries: 4, retryDelay: 2000 }` says how many times to ask the same endpoint again and how long to wait before the first of them; the wait doubles, with jitter, and the defaults are 2 and 200 ms. An endpoint that says how long to wait (`retry-after`) is waited on for that long, up to thirty seconds. Every request runs under a clock. A streamed answer is watched between frames (`PRAECISE_WIRE_IDLE_MS`, 45000 by default) and a buffered one as a whole (`PRAECISE_WIRE_TOTAL_MS`, 240000 by default); an endpoint that goes silent is crossed to the next model. Four more fields describe what an endpoint can do, and all are optional: ```ts house: { url: "https://models.internal", credential: "HOUSE_KEY", speaks: "responses", thinking: "effort", levels: ["low", "medium", "high", "xhigh"], output: 32_000, embeds: "…", cache: false, }, ``` `levels` are the words the endpoint takes for depth, shallowest first; the default is `low`, `medium`, `high`, and an endpoint with a level above `high` names it here. `output` is the most tokens one reply may take. `embeds` is the model the endpoint turns text into vectors with (see [Stores](#stores)). `cache: false` stops the `messages` wire marking the instructions and the conversation for the endpoint to keep between requests, for a gateway that refuses the marker. An endpoint that says what it charges has its answers priced. `prices` is per million tokens, per rung, in a currency the endpoint names: ```ts house: { url: "https://models.internal", credential: "HOUSE_KEY", fast: "…", best: "…", prices: { currency: "USD", fast: { input: 1, output: 5 }, best: { input: 5, output: 25, cachedRead: 0.5, cacheWrite: 6 }, }, }, ``` `answer.usage.cost` is then the cost by currency (`{ USD: 0.0095 }`), and a span carries it as `praecise.usage.cost` and `praecise.usage.cost.currency`. Where only some of the models that answered declared a price, `usage.unpricedTokens` says how many tokens the figure leaves out. The framework ships no price list: an endpoint with no `prices` is not priced at all. --- # The folder Nothing here is required except the one folder you actually use. ``` agents/ one file per agent workflows/ one file per workflow memory/ .md and .txt every agent can answer from functions/ your own code, callable by an agent tools/ MCP services the app may act through skills/ how to do a kind of work, read when it applies evals/ what a right answer looks like, checked on demand stores/ somewhere to keep things guard.ts which tool calls the app actually makes hooks.ts what happens after a tool runs and before an agent stops praecise.config.ts .env ``` A file's name is its name: `agents/support.ts` is the agent `support`, served at `/support`. Nothing to register, no imports between files, no config to keep in sync. TypeScript works with no setup. `praecise dev`, `run`, `list`, `mcp` and `package` compile the app before loading it, into `.praecise/build`, using the `typescript` in your own project — so the version you chose is the version your code is built with, and praecise itself stays dependency-free. Only what changed is rebuilt. It is a transpile, not a type check: types are erased and nothing is verified, which is why it takes milliseconds and why a type error never stops a dev server. Checking types is `npm run typecheck` (`tsc --noEmit`), in your editor and in CI, where a type error should stop something. Nothing is built for a JavaScript app, or on a runtime that reads TypeScript natively. --- # As an SDK, without a folder The folder is the default and not the only way in. The same app can be a value you import: ```ts import { createApp, agent, fn, guard } from "@praecise/harness"; const app = await createApp({ name: "acme", config: { models: { /* ... */ } }, agents: { support: agent({ role: "Help.", description: "Answers questions.", tools: ["lookup"] }), }, functions: { lookup: fn({ description: "Look up an order.", input: { id: "the order id" }, effect: "read", run: ({ id }) => ({ id, status: "delivered" }), }), }, guard: guard((attempt) => (attempt.effect === "write" ? "read-only today" : undefined)), }); await app.ask("support", "where is order 12?"); ``` The record key is the name, which is the rule the folder already uses: `agents/support.ts` and `{ agents: { support } }` are the same agent by the same name. Reach for this when the folder cannot be one: - **You are shipping agents in a package.** A library cannot ship a folder — it can ship one to copy, which stops receiving fixes the moment it is copied. It can export an app, or a piece of one. - **There is no filesystem to scan.** An edge worker, a bundled binary, a browser. The loader needs `readdir` and dynamic `import` of arbitrary paths; a bundler needs to see imports statically. Those requirements are opposed, and this side satisfies the second. - **The app is assembled, not written.** Generated from a spec, composed per tenant, built from parts. Both doors produce the same project and run the same checks. An agent with no role, memory pointing at a store that does not exist, a workflow with a cycle — each is refused the same way in the same words, because two front doors with two standards is a framework where a bug report cannot be reproduced. `defineApp` returns the project without starting it, so you can inspect `warnings` and `faults` first. `createApp` refuses to start a faulted app rather than serving one that is missing the agent the next request names. ## Changing agents while the app runs A running app can take a new agent, a new version of one, or lose one: ```ts await app.add(agent({ name: "billing", role: "Answer billing questions." })); await app.replace(agent({ name: "support", role: "Customer support for Acme.", tools: ["lookup"] })); await app.remove("billing"); ``` The agent is checked and planned as it would be at load. Requests already under way finish on the plan they started with; the next request for that name gets the new one. MCP clients are not sent a list-changed notification. ## Testing without a model `@praecise/harness/testing` is a model that says what a test tells it to: ```ts import { createApp } from "@praecise/harness"; import { scriptedModel } from "@praecise/harness/testing"; const model = scriptedModel([ { tool: { name: "lookup", args: { order: "9" } } }, "It shipped.", ]); const app = await createApp({ config: { models: model.models }, agents, functions }); const answer = await app.ask("support", "where is order 9?"); model.requests; // every request the app made, in order ``` Each entry is one reply: text, a tool call, or a function of the request. `scriptedEndpoint` does the same one level down, as a `fetch` that answers with the bodies it is given, and `systemText` reads the instructions out of a request. --- # As a library to build on A third shape, for a package whose job is to *be* built on. Export a piece of an app and let the application compose it: ```ts // in your library export const observability = { agents: { auditor: agent({ role: "Audit.", description: "Audits things." }) }, functions: { measure: fn({ /* ... */ }) }, }; // in the application import { mergeApps, createApp } from "@praecise/harness"; import { observability } from "@acme/observability"; const app = await createApp(mergeApps(observability, myOwnApp)); ``` Later definitions win, because the merge order is the caller's statement of precedence — an application overriding a library's agent is the point. Collisions are **reported** in `collisions` rather than applied silently: two packages that both export `support` produce an app where one of them is simply gone, and nobody notices until the wrong one answers. Two guards is not a guard, so that is reported too. --- # Agents ```ts import { agent } from "@praecise/harness"; export default agent({ role: "Customer support for Acme. Warm, brief, never guesses.", knows: ["memory/policies.md"], tools: ["refund"], rules: ["Never promise a refund date.", "Escalate anything about a chargeback."], greeting: "Hi — what can I help with?", }); ``` Every field but `role` is optional. `memory/**` is already included for every agent, so `knows` is for narrowing, or for pulling in something from elsewhere. When the documents do not fit in the agent's instructions, none of them are dropped. The instructions carry an outline of every document — its name, its size and its headings — along with the documents that still fit whole, and the agent gets one `read_knowledge` tool to read a document, or a single section of it by heading. The tool offers only the names that exist, and an unknown name or heading is answered with the ones that do. A folder that fits is composed as it always was and gets no tool. If the outline itself cannot fit, the documents it leaves out are named in the app's problems. Ask for structured data instead of prose: ```ts export default agent({ role: "Sort an incoming support message.", quality: "fast", memory: false, returns: { category: "one of: refund, shipping, account, other", urgency: "low, normal, or high", summary: "one sentence", }, }); ``` `returns` takes three forms. Fields and hints, as above, constrain the structure and leave each value as text. A JSON Schema object asks for typed data. A [Standard Schema](https://standardschema.dev) validator, which is what most validation libraries hand over, also types `answer.data`: ```ts const triage = agent({ role: "Sort an incoming support message.", returns: Ticket, // any Standard Schema validator read: (ticket) => (ticket.urgency === "high" && !ticket.summary ? "A high-urgency ticket needs a summary." : undefined), }); const answer = await app.ask(triage, "My order never arrived."); answer.data.category; // typed by the schema ``` A JSON Schema or a Standard Schema is sent to the endpoint for constrained decoding where it has that, and the answer is checked against it either way. `read` is a check of your own on the result: say nothing to accept it, or a sentence to refuse it. An answer that fails either is asked for again with more depth, then from a stronger model, and after the strongest the request ends in a `ShapeError` carrying `issues` and the `text` that failed. The JSON Schema keywords that are checked are listed in `CHECKED_KEYWORDS`; a schema that uses one that is not (`UNCHECKED_KEYWORDS`: `$ref`, `allOf`, `pattern`, `format` and others) is reported in the app's problems. `quality` is `"fast" | "balanced" | "best"` and is the only dial. It is not a model name — it says how much room there is to work in, not which model answers. ## Which model answers That is decided per request, before anything is spent, from the size of the request and what has to be read to answer it. An easy question goes to the cheap model and costs one call. A large one goes straight to a stronger model, because starting cheap and climbing would mean paying twice and making the second model read everything again from cold. When a request lands near the edge of what a model handles, that model is asked the same question more than once, at the same time, and the answers are compared against each other. A model that knows the answer gives it twice; a model that is guessing does not guess the same way twice. Only then does the agent climb. Nothing asks a model how sure it is. A model asked that will say it is sure, and an answer wrapped in a report on itself is worse than the answer. The framework keeps a record of what it chose and what came of it, under `.praecise/routing/`. The fact worth having is the one it would otherwise never learn: whether a stronger model, once asked, said anything different. An agent whose climbs keep landing on the same answer stops climbing so readily. None of that is configuration. It is what `quality` means. ## Bounding one request A caller can narrow the ladder for a single request, never widen it: ```ts // economise: this request may not reach the strongest rung await app.ask("support", question, { ceiling: "balanced" }); // the cheap answer was rejected: re-ask without starting on that model again await app.ask("support", question, { floor: "balanced" }); ``` `ceiling` is the most expensive rung the request may reach. It trims the agent's declared ladder rather than picking one rung, so the router still escalates below it. `floor` is the cheapest rung it may start on. Lifting a ceiling does not move a request up, because the router still enters cheapest-first; a floor is how a caller that already rejected the cheap model's answer says not to ask it again. Both can only remove rungs the agent declared, never add one, so neither can reach a model its author did not put on that agent. With both set the floor is clamped to the ceiling: a floor above the ceiling gets the ceiling, never an empty ladder. A caller can narrow what the agent may use the same way: ```ts await app.ask("desk", question, { allow: { tools: ["lookup"], knows: ["pricing"] }, maxCalls: 12, }); ``` `allow.tools` lists what the agent may still call and `allow.knows` what stays in its instructions. Both only take away. Anything else the agent was given is not offered and is refused if it is called anyway, through tool search, through code mode, or by an agent this one asks, which is held to the same lists. A name the agent does not have is an error. A live session is not narrowed. `maxCalls` is the most model calls the request may make, counting tool turns, samples, climbs, summaries and the calls of any agent asked on the way. Reaching it ends the request with `CallLimitReached`. `limits.calls` in the config is the default for requests that do not say. ## Who a request is for ```ts await app.ask("support", question, { caller: { person: "u_1", plan: "pro" }, context: { tenant }, }); ``` `caller` is who the request is for, as the app vouches for them, and `context` is anything else the app wants to travel with it. Both reach the guard and the authority on every tool call (`attempt.caller`, `attempt.context`), the second argument of every function called, the meter, and any agent this one asks, in the background or not. Neither is sent to a model, a trace or a recording. `startWorkflow`, `resumeWorkflow` and `callTool` take the same two. ## Sending more than text A question can carry anything that has a media type: a picture, a recording, a film, a PDF, a sensor log, a robot's joint state, a table, a scene. ```ts await app.ask("support", "What does this invoice say is due?", { attachments: [{ mime: "application/pdf", url: "https://files.example.com/invoice.pdf" }], }); ``` An attachment is a media type and either the bytes (`data`, base64) or a `url` the endpoint can fetch. Over HTTP it is `attachments` on the request body, up to ten, and a `url` must be `https:` or `data:`. An attachment belongs to the request it came with: a named conversation keeps what was said, not what was shown. What the model is shown follows one rule, the same on every wire: 1. **The endpoint reads it.** Images and PDFs on `messages` and `responses`; images on `chat`; images, audio, video and PDFs on `contents` and `interactions`. A `chat` server that takes audio or video says so with `takes: ["image", "audio", "video"]` on the endpoint. These are sent as they are, in the shape the wire has for them. 2. **A reader renders it.** Data no model reads is shown as a faithful rendering, placed after the question: | Media type | What the model is shown | | --- | --- | | `application/senml+json` (RFC 8428 sensor measurements) | each channel as a series: count, span, min, max, mean, deviation, and 24 evenly spaced values | | JSON tensors in the Open Inference Protocol form (`{ name, shape, datatype, data }`): robot state, action chunks, latents | each tensor's name, shape, type, range and first values | | `text/csv`, `text/tab-separated-values` | columns with their statistics, and the first and last rows; a short table whole | | `model/gltf+json` | what the scene contains, counted and named | | `text/*`, JSON, XML, YAML | the text, cut to fit | 3. **Neither.** It is left out, and `answer.notes` says which attachment and why. The data is never rewritten: a tool or a store handed the same attachment gets every sample. Teach the framework another kind of data with a reader: ```ts import { registerReader } from "@praecise/harness"; registerReader("a robot log", "application/vnd.mcap", (attachment) => summarise(attachment)); ``` A function returns something other than text with `attach`, and an MCP tool that returns an image, audio or a file has it handed to the model the same way rather than spelled out as base64: ```ts import { attach, fn } from "@praecise/harness"; export default fn({ description: "Take a picture with the front camera.", effect: "read", run: async () => attach("Frame 12.", { mime: "image/jpeg", data: await frame() }), }); ``` What a model makes that is not text (an image from `contents` or `interactions`, speech from `chat`) comes back on `answer.attachments`. Asking an endpoint for it is the endpoint's own field, set through `body` in `models`. **A film an endpoint cannot watch** is taken apart by a decoder the app registers. One ships, over an `ffmpeg` binary the app points to: ```ts import { ffmpegDecoder, registerDecoder } from "@praecise/harness"; registerDecoder("ffmpeg", "video/", ffmpegDecoder({ bin: "/usr/bin/ffmpeg", every: 2, frames: 16 })); ``` The stills are sent as images. The sound is sent as audio where the endpoint takes it, transcribed by the cheapest rung that does where it does not, and otherwise left out with a note. **A large attachment is uploaded once.** Past a size, an attachment is sent through the endpoint's files API and named from then on instead of being sent inside every request: past 5 MB on `messages`, 20 MB on `responses`, `contents` and `interactions`, and not at all on `chat` unless the endpoint says `uploads: true`. `uploads: { over, keep }` sets the size in bytes and how long the endpoint is asked to hold the file; `uploads: false` turns it off. What was uploaded is remembered for the life of the process. An upload that fails is sent inside the request, with a note. **Large media can be kept by address.** `app.blobs` holds bytes under the SHA-256 of what they are, on disk under `.praecise/blobs` unless the app brings a store: ```ts import { detach, sweepBlobs } from "@praecise/harness"; const light = await detach(app.blobs, attachment); // { mime, blob: "sha256:…" } await sweepBlobs(app.blobs, live); // remove what `live` does not name ``` An attachment carried as `blob` costs its address wherever it is written down, and its bytes are put back before a model or a reader is shown it. Bytes are hashed again when read. Nothing is removed until `sweepBlobs` is run, and a sweep leaves anything kept within the last day (`olderThan`, in milliseconds), because a blob is written before the row that names it; `dryRun: true` reports what would go without removing it. An HTTP caller cannot send a `blob`. **More formats, as a plugin.** `@praecise/harness/formats` adds readers for robotics, scene and array data: ```ts import { defineConfig } from "@praecise/harness"; import { formats } from "@praecise/harness/formats"; export default defineConfig({ plugins: [formats()] }); ``` It reads MCAP, ROS 1 bags, LeRobot dataset metadata, Parquet footers, Arrow IPC schemas, PCD and PLY point clouds, Gaussian splats (PLY and `.splat`), USD (`.usda` in full; `.usdc` and `.usdz` described) and `.npy`/`.npz` arrays, and identifies a ROS 2 `.db3` bag. Each rendering ends by saying what was not read. `formats({ only })` and `formats({ except })` choose among them, and `registerFormats()` registers them without a plugin. MCAP chunks compressed with zstd need Node 22.15 or newer. ## Work that takes a while An agent may go to its tools sixteen times in one request before it has to answer; `turns` on the agent changes that. What keeps long work inside the endpoint's context is not the count: - A tool result too long to hand over is kept whole for the length of the request. The agent sees the start and the end of it and a name, and reads the rest with `read_result`, by line or by search. - When the record of the work passes half the endpoint's `room`, older tool results are replaced by a line saying they were cleared and can be asked for again. The calls themselves stay. - If that is not enough, the model is asked once for notes on the earlier work, and those notes replace it. The question itself is never rewritten. Each of these is reported in `answer.notes`. Calls in one turn that only read (`effect: "read"`) run together; anything else runs in the order the model asked. ## Many questions at once `askMany` hands many questions for one agent to the endpoint's batch API: ```ts const results = await app.askMany("triage", messages); for (const { answer, error } of results) { // one entry per question, in the order asked } ``` Each entry is an answer or the error that question ended in. An agent's tools run between batches. Batching ships for the `messages`, `responses`, `chat` and `contents` shapes; on `interactions`, or on an endpoint that says `batch: false`, the requests are sent one at a time. `poll`, `within`, `linger`, `signal` and `onBatch` are the options, and `registerBatch` teaches the framework the batch API of a shape of your own. ## A live session A conversation over one connection, for voice and anything else that is not a request and a reply. The endpoint says where sessions run: ```ts house: { url: "https://models.example", credential: "HOUSE_KEY", speaks: "responses", realtime: { model: "…" } }, ``` ```ts const session = await app.open("desk", { output: "audio" }); session.send({ text: "Where is order 4021?" }); for await (const event of session) { if (event.kind === "audio") play(event.data); if (event.kind === "turn" && event.state === "ended") break; } await session.close(); ``` `send` takes `text`, `audio` or `attachments`; `interrupt()` stops the agent speaking. Events are `text`, `audio`, `transcript`, `speech`, `turn`, `tool`, `tool result`, `refused`, `usage`, `note`, `error` and `closed`. The agent's tools are called through the same guard and authority as in a request. Sessions run over WebSocket. Protocols ship for the `responses`, `chat`, `contents` and `interactions` shapes, not for `messages`; `registerSession` adds one. A session has no failover: a connection that drops is closed, not reopened on another endpoint. A named conversation's history, recall and selves are not carried into a session, and images are the only media that can be sent beside audio and text. ## One agent asking another Name an agent in another agent's `tools` and it becomes a tool: ```ts // agents/lead.ts export default agent({ role: "Answer questions about an account.", tools: ["researcher", "refund"], }); ``` The agent asked starts from its own role and tools and sees nothing of the conversation that led to it, so the task it is given has to stand on its own. Only its answer comes back; the results it read along the way never enter the asking agent's context. Its tokens are counted in the asking request's `usage`, the call goes through `guard.ts` like any other, and what it read marks the answer `tainted` the same way. A request may go three agents deep (`limits.depth`); past that the model is told why not. A name in `tools` is a function if `functions/` has it, a service if `tools/` has it, and an agent otherwise. With `background: true` the asking agent may start another agent and carry on: ```ts export default agent({ role: "Answer questions about an account.", tools: ["researcher"], background: true, }); ``` Calling `researcher` with `background: true` returns a handle at once. The agent then has `check_agent`, `steer_agent`, `cancel_agent` and `collect_agent` to see how the other is getting on, tell it something more, stop it, and take its answer. Four may be working at once in one request, and any still working when the request answers are stopped. ## Advice from a stronger model ```ts export default agent({ role: "Triage incoming tickets.", quality: "best", tools: ["lookup"], advisor: true, }); ``` With `advisor: true` the agent gets a `consult` tool. Calling it sends the agent's instructions and the work so far to the strongest model on its ladder, which says what it would do next in at most about two thousand tokens and does none of the work. The cheaper model carries on. It is not offered while the strongest model is itself answering. ## An agent that remembers who it is An agent starts every request from its role, its rules and its tools. A **self** is what persists around it: an identity, what it has learned, what it has been reading, and what came of its earlier work. An agent declares the self it is, and the harness does the rest on every request, however the agent is reached: ```ts export default agent({ role: "Find the pieces in the catalogue that carry an idea.", tools: ["search-products"], self: "design", }); ``` Before the request, the self's context is read and placed after everything stable in the system prompt, as the self's own notes. After it, what was asked and answered is recorded against a ticket, so that what comes of the answer later reaches exactly what the self drew on. Where selves live is the app's choice, in `praecise.config.ts`: ```ts export default defineConfig({ selves: { url: "https://selves.example.com", credential: "SELVES_KEY" }, }); ``` `url` may also come from `SELVES_URL`. The provider speaks a small protocol: | | | |---|---| | `POST {url}/selves/{handle}/context` | `{surface, task, interactive}` → `{preamble, ticket, lessons}` | | `POST {url}/tickets/{ticket}/work` | `{brief}` | | `POST {url}/tickets/{ticket}/outcome` | `{signal: -1..1, label, detail?, by?}` | | `PUT {url}/selves/{handle}` | create a self from the agent's `template`, with `adminCredential` (default `SELVES_ADMIN_KEY`) | Or bring your own provider in code: `App.load({ selves: myProvider })` with anything that implements `SelfProvider`. **A self per person.** A handle with `{person}` is a self for each person the app serves, created from a template the first time they ask: ```ts self: { handle: "coach-{person}", template: { name: "Coach", charter: { purpose: "Remember what works for this person." } }, }, ``` The person is the one the caller names (`caller.person` in `ask`, `person` on the HTTP body, `_meta["com.praecise/person"]` on an MCP `tools/call`), vouched for by whoever holds the app's token. A caller can name where it is asking in the same way (`surface`, or `_meta["com.praecise/surface"]`), which picks the self's persona for that surface. It is reduced to a digest before it becomes part of a handle. **Rating an answer.** Every answer from a self carries `answer.self`: the handle, what it drew on, and a ticket. Set `SELVES_TICKET_SECRET` (or `ticketCredential`) and the ticket is bound to the person it was issued to, which makes it safe to send to their browser. A rating comes back through `app.rate(ticket, verdict, person)` or `POST /api/selves/outcome`, optionally with a `check`: something the app measured about what came of the answer (`{ name, passed, failures }`). A rating is credit; a failed check is what a self learns from; a ticket issued to somebody else reads exactly like one that has expired. The ticket also arrives early, as a `self` progress event, and in `_meta["com.praecise/self"]` on an MCP result. **One memory.** A self already remembers, so an agent that is a self cannot also declare `memory`: two records of the same life would disagree. **What a self is sent.** After an answer, the provider is sent what was asked, what was answered and which tools were used. An agent and an app each have a say over that: ```ts self: { handle: "coach-{person}", record: (work) => ({ ...work, answer: redact(work.answer) }), }, ``` `record` returns what is sent instead; returning nothing sends nothing. The app's `beforeRecord` hook in `hooks.ts` is asked after it, with what it left, and answers the same way. One that throws sends nothing. **Memory, not a dependency.** If the provider cannot be reached, the agent answers as it would have without its self and says so in a note. `selves: { required: true }` makes that an error instead. --- # Workflows Steps run in order. Any `{{name}}` is replaced before the step runs, and can reference an input or an earlier step. ```ts import { workflow } from "@praecise/harness"; export default workflow({ input: { message: "the customer's message" }, steps: [ { id: "sorted", ask: "{{message}}", agent: "triage" }, { id: "reply", when: "{{sorted.category}}", is: { refund: [ { id: "draft", ask: "Draft a refund reply: {{message}}", agent: "support" }, { id: "approved", approve: "Send this?\n\n{{reply.draft}}" }, ], }, otherwise: [{ id: "draft", ask: "Reply to: {{message}}", agent: "support" }], }, ], }); ``` Eight kinds of step: | | | |---|---| | `ask` | delegate to an agent | | `use` | call a service, e.g. `use: "ledger.create_invoice"` | | `approve` | stop and wait for a human | | `wait` | stop and wait for an event from outside | | `each` | run steps once per item, optionally in parallel | | `when` | branch on a value | | `repeat` | run steps until a check holds, with a required `max` | | `plan` | let a model lay out the remaining work, then run it as a graph | An `approve` step writes the run to disk and returns. It survives a restart, and resuming replays the recorded outputs rather than re-running the steps before it — the model is not called twice for work already done. A `wait` step stops the same way, for an event instead of a person: ```ts { id: "paid", wait: "com.acme.payment.received", subject: "{{order}}", timeout: 86400, onTimeout: "continue" } ``` `wait` is the CloudEvent `type` awaited. `source` and `subject` narrow it, which is how a run waits for its own event and not the next one of that type. The event that matches continues the run, once, and is the step's output: `type`, `source`, `id`, `subject`, `time`, `data` and `timedOut`. It arrives through `app.signal(event)`, `app.deliver(workflow, event)`, `app.publish(event)` or the [event routes](#events). An event that arrives while nothing waits for it is not kept. `timeout` is in seconds; running out fails the run, or with `onTimeout: "continue"` carries on with `{ timedOut: true }`. A timeout fires only while a process holds the app, or when `app.expire()` is called: nothing wakes a run whose app is not running. A run waits for one event at a time. A string that is *only* a reference keeps its type, so `with: "{{draft}}"` hands a tool an object rather than `[object Object]`. Any step may carry `after: ["id", ...]`. One `after` anywhere turns the list into a graph: steps run as soon as what they wait for is done, so independent work goes in parallel instead of in the order it happened to be written. Without any `after`, the steps run in order, which is what a short workflow wants. Two things about `after` that are easy to read the wrong way, because both are about where a step SITS rather than what it says: A step inside `each`, `when` or `repeat` may wait for a step outside it, and usually means to. If the block it sits in already waits for that step, the dependency is satisfied before the block begins — naming it again is redundant rather than wrong, and nothing is lost. What is reported is the other case: a wait on something nobody waits for, where the two really could run in either order. A `repeat` condition may name the steps inside its own body. `until: "{{panel.passed}}"` over a body containing `panel` is the ordinary way to write "go round again until the panel agrees", and it works because the condition is evaluated after the body has run. `max` is required on `repeat` because an unbounded loop is a bug, so there is no way to write one. And a `plan` is produced once rather than on every step — deciding what to do next is itself a model call, and paying for it repeatedly is what makes agentic loops expensive. The plan is recorded as a version rather than overwritten, so a resume runs the graph that was agreed rather than inventing a fresh one. --- # When a run stops badly A workflow that waits for a human is the easy case. The hard cases are a process that died and a decision that turned out to be wrong, and they need different answers. ```ts import { resumeRun, recoverRun, forkRun } from "@praecise/harness"; // a human answered the gate — the decision is the argument, not a flag await resumeRun(runId, { approved: true, approver: "ada", channel: "cli" }, spec, deps); // the process driving the run died; re-drive it from the journal await recoverRun(runId, spec, deps); // ask what would have happened if an earlier step had decided differently await forkRun(runId, spec, deps, { after: "sorted", patch: { sorted: { category: "refund" } } }); ``` **`resumeRun`** answers a gate. It refuses a run still marked `running`, because something may still be driving it. **`recoverRun`** exists for exactly that refusal. A crash leaves a `running` status behind with nobody driving, and the journal is the only way back. Calling it asserts the driver is dead — the store records state, not processes, so that assertion is yours to make. Completed steps are replayed from the journal and never re-executed. A step interrupted **mid-side-effect** is the case neither can resolve alone. It is marked inflight, and recovery refuses to repeat it: nothing in the journal can prove the effect did not already happen, and a charge issued twice is worse than a run that stopped. Resolve it and clear the entry, or retry under the same idempotency key. **`forkRun`** is for the counterfactual. It copies the journal up to a point and nothing past it, so the original stays readable exactly as it happened, beside the one that might have. `patch` is what makes it worth having: edit an earlier step's output and watch what follows change — asking what the run would have done if the classifier had said `refund`, without pretending it did. Every patched value is recorded as patched. **Stopping a run** is `app.cancelWorkflow(runId, { reason, by })`, or `POST /api/runs//cancel`. A run in flight is interrupted where it stands and one waiting at a gate or for an event is ended there; either is recorded as `cancelled`. A function hears it as `signal` in its second argument, and `startWorkflow(name, input, { signal })` ties a run to a signal of the caller's. A `passes` check that is running a command is not interrupted, and a run streamed over AG-UI reports its cancellation as `RUN_ERROR`. There is no CLI command for it. **A ceiling in money.** `limits: { spend: { amount: 2, currency: "USD" } }` in the config stops a run that has spent that much, counted from the `prices` its endpoints declared. A run that reaches a model with no declared price, or one priced in another currency, is stopped and told why instead of being counted as free. --- # Tools Anything that speaks MCP goes in `tools/`, one file per service: ```ts // tools/ledger.ts import { tool } from "@praecise/harness"; export default tool({ url: "https://ledger.example.com/mcp", credential: "LEDGER_TOKEN", }); ``` Then `tools: ["ledger"]` on any agent, and `LEDGER_TOKEN` in `.env`. Leave `credential` off and it reads `LEDGER_API_KEY`, after the filename. There is no built-in list of known services. A hard-coded endpoint is someone else's URL to change and someone else's product to retire; four lines in your own repo say plainly what your app talks to. A service that is listed but unconfigured does not break the app — the dashboard says which key is missing and the agent runs without it. ## A local program, or an ordinary API A large share of published MCP servers are programs you launch rather than URLs you call, and most APIs worth reaching have an OpenAPI description and no MCP server at all. Both are services here: ```ts // tools/files.ts — a program, spawned without a shell export default tool({ command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."] }); // tools/stripe.ts — an ordinary HTTP API, described export default tool({ openapi: "https://api.example.com/openapi.json", credential: "ACME_KEY" }); ``` An OpenAPI document becomes one tool per operation, with the parameters flattened into the single object a model produces and each value's location remembered — so the model does not have to know which of its arguments are a path segment, a query string, a header, or the body. ## Code mode An agent with many tools, or one that chains calls, does better writing a program than making calls one by one. Turn on `code` and the agent gets a single `code` tool instead of one per operation: its services appear as a typed API in the tool's description, the model writes a short program against it, and only the program's result comes back into context. ```ts // agents/analyst.ts export default agent({ role: "Answers questions that need several systems at once.", tools: ["crm", "billing", "acme"], code: true, }); ``` The program runs in a [Praecise Silo](https://praecise.com/silo): a microVM with no network, whose only way out is the agent's services. Each HTTP service is bound into it; the silo's host makes each call with the credential from `.env`, so the key never enters the program's world. An MCP server becomes `tools..(args)`; an OpenAPI service becomes `tools..request({ method, path, query, body })`, with its document in `spec.` for the program to search — a large API never has to fit in the prompt. A service launched as a local program cannot be bound and stays an ordinary tool beside `code`. `code: true` reaches the silo service named by `code: { silo }`, else by `PRAECISE_SILO`, else its local socket: a `unix:` path on the same machine, or an `https://` address reached with the agent token in `PRAECISE_SILO_TOKEN`. `code: { language: "python" }` asks for Python (`"javascript"` also works); the default is TypeScript. One silo is kept per agent for its term, `ttl` seconds (default 1800), and replaced when it expires. `code: { allow: { acme: ["GET /things/*"], crm: ["find_contact"] } }` narrows what the program may call, by service: tool names for an MCP server, `"METHOD /path"` patterns for an OpenAPI service. The silo refuses anything else before it leaves the host and logs every call, allowed or not. ## More tools than fit in a list Every tool an agent is shown is read on every request. When an agent's services publish more than a dozen tools and their definitions pass a tenth of the endpoint's `room`, they are not listed. The agent gets `find_tools`, which answers a description of a job with the best-matching tools and their arguments, and `use_tool`, which calls one by name. A call made through `use_tool` is checked by `guard.ts` and recorded as a call to the tool it names. Your own functions are always listed. ## Servers that want a token you do not have yet A hosted MCP server is usually an OAuth 2.1 protected resource, and answering its challenge needs a browser, a callback, and somewhere to keep tokens — three things a framework should not decide for you. praecise implements the protocol and leaves those to you: it recognises the challenge, hands it to your `authorize` callback, and retries the request once with whatever you return. `OAuthClient` covers the flow itself, including the parts that exist because of an attack rather than a feature — the `resource` parameter on both requests so a token minted for one server cannot be spent at another, byte-exact issuer validation, PKCE, and registrations that are never presented to a server that did not mint them. Where the authorization server supports Client ID Metadata Documents, set `clientMetadataUrl` to the HTTPS address of a document your app hosts and that address is used as the client id, with no registration request. `clientMetadataDocument()` builds the document. Without the option, or on a server that does not support it, the client registers dynamically as before. Two grants need nobody at a keyboard, and a service names one in its file: ```ts // tools/ledger.ts export default tool({ url: "https://ledger.example.com/mcp", oauth: { grant: "client_credentials", issuer: "https://auth.example.com", clientId: "acme-app", secret: "LEDGER_CLIENT_SECRET", }, }); ``` `client_credentials` is the app acting as itself, with a secret or a private key (`key`) it signs an assertion with. `grant: "id-jag"` is enterprise-managed authorization: the identity provider at `idp` is asked, on the strength of the ID token named by `assertion`, for a grant the server's authorization server exchanges for a token. `secret`, `key` and `assertion` are names of environment variables, never the values. `issuer` is required, and the grant is made there or not at all. A service declared this way has one identity; an app that serves many people calls `exchangeIdentity` and `redeemGrant` on `OAuthClient` for each of them. The `id-jag` grant follows a specification that is still a draft. ## What an MCP server may ask of the app **Something from a person, mid-call.** A server may ask for a value (a form) or send the person to a page (a URL). The app answers through `mcp.elicit`: ```ts const app = await App.load({ root, mcp: { elicit: { form: async ({ service, message, schema }) => ({ action: "accept", content: await askPerson(message, schema) }), url: async ({ service, url, host }) => ({ action: "decline" }), }, }, }); ``` Each mode is declared to a server only when its handler is there, so a server never asks for what nothing can answer. The URL is handed to the app and never fetched. A call may be asked for more input eight times running. **To be told when its tools change.** `watch: true` on a service keeps a `subscriptions/listen` stream open and lists the server's tools again when it says they changed. **To offer its skills.** `skills: true` on a service, or a list of `skill://` addresses, offers agents the skills that server serves, read through a `read_service_skill` tool. Each file is checked against the server's manifest by SHA-256, marked with where it came from, and treated as that service's output. Nothing in a skill is executed. **To show a view.** A tool may bring an interactive page with its result (an MCP App). With `mcp: { apps: true }` the page is read from the service and handed on as `answer.ui`, and as an `ACTIVITY_SNAPSHOT` over AG-UI, for a front end to render in a sandbox of its own. What the page asks for (`tools/call`, `resources/read`, `ping`) is forwarded to `POST /api/ui/` and goes through `guard.ts` with `via: "ui"`. The frame, its sandbox and the messages into it are the front end's. MCP roots, sampling and logging are not offered: the revision of the protocol spoken here deprecates all three. ## A screen as a tool `computer` turns a screen into a function an agent can call, and `browserScreen` is the screen that ships, a Chromium the app points to: ```ts // functions/browser.ts import { browserScreen, computer } from "@praecise/harness"; export default computer(await browserScreen({ executable: "/usr/bin/chromium", url: "https://example.com" })); ``` The agent takes screenshots and clicks, double-clicks, moves, drags, scrolls, types, presses keys, waits and zooms. The function is `effect: "write"` and its output is untrusted, so the guard sees every action and what is read from a page taints what follows. An endpoint that has a computer tool of its own names its type as `computer` on the endpoint, and on the `messages` shape the tool is sent as that; everywhere else it is sent as an ordinary function. Any other screen is an object that implements `Screen`. `computer(screen, options)` takes the tool's `name` (`computer` by default), an `about` sentence on what the screen is, `screenshotAfter: true` to return a screenshot with every action that can change the screen (off by default, after `settleMs`, 400 by default), and `maxWait`, the longest one wait may be in seconds (30 by default). --- # Stores ```ts // stores/history.ts import { store } from "@praecise/harness"; export default store({ of: "sql" }); ``` That is a working store. It keeps a file under `.praecise/` and needs nothing installed. Give it a `url`, or a `credential` naming the environment variable that holds one, when it should live somewhere else — a `postgres://` url moves it to a server, and nothing above changes. The built-in backend's text search rides on the FTS5 module of Node's bundled SQLite. Whether that module is present is a property of how your Node was BUILT, not of its version number — the Node 22 this was last checked against has it, and a build without it raises `no such module: fts5` while everything else about the store keeps working. If search matters, check rather than assume: ```sh node -e 'new (require("node:sqlite").DatabaseSync)(":memory:").exec("CREATE VIRTUAL TABLE t USING fts5(x)")' ``` Four verbs work on every store, whichever family you declared: ```ts const history = await app.store("history"); await history.remember({ text: "customer asked about order 4021", scope: "acme" }); await history.recall("order 4021", { scope: "acme" }); // relevant, recent counting for more await history.search("4021"); // contains these terms, whatever its age await history.history({ limit: 50 }); // newest first await history.forget({ scope: "acme" }); // and how many went ``` `recall` and `search` are different questions. `search` is a lookup and does not care how old something is. `recall` is a judgement, and a judgement decays — something said this morning is more likely to be what you meant than the same sentence from a year ago. None of the four composes a query, which is the point: an agent asking to recall something has no string to compose badly. Your own SQL is a separate door: ```ts await history.query("SELECT total FROM invoices WHERE account = ?", ["acme"]); ``` A store declared `of: "vector"` compares vectors you supply, and falls back to text when you do not: ```ts await history.remember({ text: "…", vector: embedding }); await history.recall(embedding, { limit: 5 }); ``` Embeddings are supplied rather than derived, unless an endpoint says what it embeds with. Name an `embeds` model on an endpoint in `models` and an agent that remembers into a vector store has each exchange embedded as it is kept and is recalled by meaning. If the embedding cannot be had, recall falls back to text. `App.load({ embedder })` takes your own function instead. Asked with both, a store answers both ways and joins the two orders by reciprocal rank: ```ts await history.recall({ text: "order 4021", vector: embedding }, { scope: "acme" }); ``` An agent that remembers into a vector store is recalled this way. A reranker scores what was found a second time, reading the question and each candidate together: name a `reranks` model on an endpoint (sent to `{url}/rerank`), or pass `App.load({ reranker: async (query, documents) => scores })`. `{ rerank: false }` leaves it out of one question. ## Typed records A store may say what a record in it looks like, with any Standard Schema validator: ```ts // stores/tickets.ts export default store({ of: "document", schema: Ticket }); ``` Everything `remember` is given is checked first. A batch with anything wrong in it is refused whole, with a `SchemaError` whose `issues` name each row, path and message, and what is kept is what the validator returned. `RecordOf` is the record's type. It is a check on the way in and nothing more; values, facts and series are not checked against it. ## Values, facts and series Text to recall is one shape of data. A store also keeps three others, on every backend, with nothing more to declare or install: ```ts const kept = await app.store("history"); // a value under a name, in a namespace, with an optional lifetime in seconds await kept.values.put(["users", "ada"], "theme", { dark: true }, { ttl: 3600 }); await kept.values.get(["users", "ada"], "theme"); await kept.values.list(["users", "ada"]); await kept.values.delete(["users", "ada"], "theme"); // how two things are related, and when that was true const id = await kept.facts.relate("ada", "works_at", "acme", { validFrom, source: "hr-export", confidence: 0.9 }); await kept.facts.unrelate(id, { at }); // closed, never deleted await kept.facts.facts({ subject: "ada", asOf }); // what was true then await kept.facts.neighbors("ada", { direction: "both", depth: 2 }); // readings in order of time await kept.series.append("boiler/temp", [{ at, value: 61.5, tags: { unit: "Cel" } }]); await kept.series.range("boiler/temp", { from, to, bucket: 60_000, aggregate: "mean" }); await kept.series.last("boiler/temp"); ``` A value is replaced when written again. A fact said twice is one fact, and one that stops being true keeps its place in the record: `asOf` answers with what was true at a moment, and `asOf: "ever"` with everything that was ever believed. A reading sent twice for the same moment is one reading. None of the three turns up when an agent recalls something, because each is kept under a scope of its own. They are verbs over the operations every backend already implements, so a driver you bring has all of them once it passes `conform`. What that costs is stated: on a backend that offers nothing more, a walk over facts and an aggregate over a series read the rows involved and work the answer out in this process. That is the right trade for what an agent keeps and the wrong one for a warehouse, which is what `query()` is for. A backend may do some of it itself, and says which in `capabilities.faster`: `walk`, `buckets`, `ids`, `validity`. The file and Postgres backends walk facts with a recursive query and aggregate a series in the database, Postgres using `time_bucket` where TimescaleDB is found. On PostgreSQL 18 ids are made by the server (`uuidv7()`), and where `btree_gist` is installed a fact's validity is held under a key that refuses overlap, so `facts.relate` throws on a fact that overlaps one already there. `conform` holds each of these to the answer worked out in this process. A `postgres://` url takes two settings of its own. `sslmode` is `disable`, `prefer` (the default), `require` or `verify-full`, which also checks the certificate. `max_protocol_version` is `3.0` (the default), `3.2` or `latest`: 3.2 arrived with PostgreSQL 18, is asked for only when the url says so, and a server that does not speak it answers with the version it does, which the connection then uses. The version a connection settled on is in the store's `capabilities.detail`. There is no ORM, and that is a decision rather than a gap. A layer mapping tables to classes buys type safety for code a person writes; an agent's access to data is safe because of the role its connection holds and because every value is bound, not because of a type. For a table of your own, `query()` takes the SQL. ## Which families are served `of` takes five families. What ships serves four of them, and it serves them through one shape: a table of text, json metadata, a time, and an optional vector. | | | |---|---| | `sql` | served — it is a table, and `query` is its own SQL | | `document` | served — metadata is `jsonb` on a server, JSON on a file | | `timeseries` | served — ordered and ranged by time, and partitioned by it where TimescaleDB is installed | | `vector` | served — ordered by pgvector or sqlite-vec where those are installed, compared in this process where they are not | | `graph` | **not served as an engine** — relationships are kept and walked through `facts` on any store; a graph database is a backend you bring | A family the backend cannot honour is refused when the store is opened, and the refusal names what is served and what to do instead. It used to be accepted: `of: "graph"` against a `postgres://` url got the same table of text as everything else, and nothing anywhere said so. `of` is still declarative where a driver *can* honour it — nothing changes about the four verbs — but it is no longer a word that only reaches a prompt. Which path a store is actually on is a question with an answer: ```ts const kept = await app.store("history"); kept.capabilities.vectorSearch; // "index" — the database orders them // "scan" — every vector is read and compared here kept.capabilities.detail; // why that one, and what would change it ``` A fallback that is a hundred times slower and completely invisible is the kind of thing that gets discovered as a latency graph a year later, so it is not invisible. ## What an extension costs the person installing it Nothing here requires one, and each is worth a different amount of trouble. | | | |---|---| | **pgvector** | `CREATE EXTENSION vector` — one statement, no restart, no config edit. A `vector` store then keeps embeddings in a real `vector(n)` column with an HNSW index, and `ORDER BY … <=> …` happens in the database. Declare `dimensions`; a column with no width cannot be indexed. | | **TimescaleDB** | `shared_preload_libraries = 'timescaledb'` in `postgresql.conf`, then **a restart** — the one extension here that costs downtime. A `timeseries` store is then a hypertable in weekly chunks. Only `create_hypertable` is used, which is in the Apache-2.0 subset; compression, continuous aggregates, retention policies and the job scheduler are the source-available half and are deliberately not touched. | | **sqlite-vec** | Build or download the extension, then name the file in `PRAECISE_SQLITE_EXTENSION`. Off unless that variable is set: loading one runs somebody else's machine code inside the process holding your data, which is a decision for whoever is deploying, not for a framework guessing from a url. | | **Apache AGE** | `CREATE EXTENSION age`, then `LOAD 'age'` and a `search_path` in **every session**. Nothing here uses it, and a graph store is refused rather than pretended at. | An existing table is never migrated underneath you. A Postgres store that already keeps its vectors as `bytea` goes on comparing them here even once the extension is installed, and says so in `detail` — reading a column that no longer holds your vectors would not be faster, it would be empty. All of it is reachable through `query()` right now, whether or not anything above knows the extension exists: ```ts await kept.query("SELECT id FROM praecise_items ORDER BY vector <=> $1 LIMIT 5", [asked]); await kept.query(`SELECT time_bucket('1 day', to_timestamp(at / 1000)) AS day, count(*) FROM praecise_items GROUP BY day ORDER BY day DESC`); await kept.query("SELECT * FROM cypher('g', $$ MATCH (a)-[:KNOWS]->(b) RETURN b $$) AS (b agtype)"); ``` That door is the author's, not the agent's, and it is open before any of this is. ## What an agent remembers `memory: true` gives an agent four things, and they are kept apart on purpose: | | What it is | Who writes it | How the agent meets it | | --- | --- | --- | --- | | The record | Every exchange: what was asked, what was answered | The runtime | A few that share words with the question are shown beside it; the rest it searches | | Working notes | What the agent chose to write down while it worked | The agent, with `write_note` | It searches them | | Subject pages | One page per thing it keeps coming back to, gathered from the record and the notes | The reflect pass | It searches and reads them | | What it carries | A short list of facts and procedures | A person, by accepting a proposal | Placed in front of it on every request | Only the last row changes what an agent is told, and only a person changes it. The other three are things the agent looks through with `search_memory` and `read_memory`, and they are labelled with where they came from: its own and unconfirmed, from a person, or from outside the app. An exchange is kept as `external` when anything the app does not trust was read while answering, and whatever is later drawn from it is held to that. Words are found in whatever script the text is written in, so recall works the same for text that is not in Latin letters. An agent can remember into a store instead of into files, and then all four of those are in the store: the record and the notes as rows its index searches, the pages and what it carries as documents beside them. Nothing of its memory is on the machine's disk, so several machines serving one app against one database have one memory. ```ts export default agent({ role: "Answers customer questions about orders.", memory: { store: "history" }, }); ``` Each agent is its own scope, so one store holds every agent's memory without any of them seeing another's. `store: "history"` in `praecise.config.ts` makes that the store for every agent that asks for memory without naming one. A store an agent remembers into holds records of the framework's own shape, so it is declared without a `schema`; one with a schema is refused at load. ## Reading the record back ```sh praecise memory support # what it carries, and any proposal waiting praecise memory support --reflect # read the record: propose changes, file what is new onto pages praecise memory support --accept # adopt what was proposed, or `--accept 0,2` for those positions praecise memory support --reject # discard the proposal; the record is untouched praecise memory support --retire # stop carrying one entry praecise memory support --record # the exchanges it kept, with their ids praecise memory support --notes # the working notes it wrote praecise memory support --pages # its subject pages; `--page ` shows one praecise memory support --redact --note "sent in error" ``` `--reflect` asks a model to read the record and the working notes against what the agent carries now. It proposes facts and procedures to start carrying, each naming the exchanges or notes it was drawn from, and it proposes closing or replacing a carried entry where the record shows it has changed. Nothing it proposes takes effect until `--accept`. What is carried accumulates: an entry adopted last month is still carried after the exchanges it came from have aged out of the record. A replaced or retired entry is closed with the time, not deleted. Where a proposed entry would replace a carried one, the one from the source of higher authority stands, and between equals the later one; that is compared as values and never asked of a model. An agent carries at most 48 entries, because every one is read on every request. The same pass files what is new in the record onto subject pages. Each page is written by a request of its own that is shown that page and the entries filed on it, and a page changed by someone else in the meantime is left as it is. Pages need nobody's agreement because they are only ever found and read. The pass takes the agent's memory to itself while it runs: a second one for the same agent, from this process or from another machine on the same store, is refused (`AlreadyReflecting`) until the first is done. To have the record read back on a schedule while the app is served: ```ts export default agent({ role: "Answers customer questions about orders.", memory: { reflect: { cron: "0 3 * * *" } }, }); ``` `praecise dev` and `serve()` start that schedule. An app made with `App.load` or `createApp` and served some other way starts it with one call, `app.tend()`. Where several processes serve one app each may call it: a tick is read back once. `--redact` takes one exchange or working note back: the record still shows that something happened and when, with the note where the words were (`taken back` when none is given), and the agent does not answer from it again. From code these are `app.reflect`, `app.pending`, `app.accept`, `app.reject`, `app.retire`, `app.learned`, `app.carried`, `app.recorded`, `app.jotted`, `app.jot`, `app.filed`, `app.page`, `app.redact` and `app.clearMemory`. ## What memory is worth ```sh praecise eval support --memory ``` runs one suite twice. First as always: every case asked as though nothing had been asked before. Then with a memory that starts empty, the cases asked in the order they are written, each able to use what the ones before it left. It reports both and the difference. The second run keeps its memory under a name of its own and removes it afterwards, so the agent's real memory is neither read nor written. A suite measures this only where its cases build on one another. From code: `app.evaluateMemory(suite)`. ## Bringing a backend Four backends ship: a file, a Postgres server spoken to over its own wire protocol, Redis or Valkey spoken to the same way, and one that keeps nothing past the process — `url: "memory:"`, for an example or a test that should leave nothing behind. None costs a dependency. ```ts // stores/cache.ts export default store({ of: "vector", url: "redis://cache:6379/0?prefix=app", dimensions: 1024 }); ``` A `redis://`, `rediss://`, `valkey://` or `valkeys://` url is spoken to in RESP3, falling back to RESP2; `rediss` and `valkeys` are the same over TLS. The path is the database number, and `?prefix=` is what every key starts with (`praecise` by default). Vector sets, time series and JSON are used where the server has them. There is no text index, so `search` reads a scope and compares; `sql` and `graph` are not served; and `query()` takes a command, not SQL. Anything else is a `Driver` your app hands over, matched to a store by the scheme of its url. A driver's connection keeps, lists, matches, drops and redacts rows, and `add`s one only if nothing is kept under its id, which the backend has to decide in one step: locks, leases and document revisions are made from it. ```ts const app = await App.load({ drivers: [myDriver] }); ``` A driver implements named operations — keep these, list that window, match these terms, drop this scope — not a SQL string. Everything above it is written once and every backend gets it, and there is no query language between a model and your data for either of them to get wrong. Four that are worth the afternoon, one per family this does not serve well or at all. Each speaks HTTP, so a driver is a `fetch` and the six operations above it: | | | |---|---| | **Qdrant** for `vector` | Apache-2.0. Named vectors, payload filters and a filtered search that stays exact — which is the thing an approximate index gives up when a window narrows. | | **Neo4j Community** for `graph` | Its Query API is plain HTTP: `POST /db/neo4j/query/v2`, Cypher in the body, Basic auth. The server is GPLv3; speaking HTTP to a server creates no obligation for the thing doing the speaking, which is what makes this reachable without a licence conversation. | | **CouchDB** for `document` | Apache-2.0, and HTTP is its native interface rather than a gateway to it. Mango selectors do the narrowing. | | **ClickHouse** for `timeseries` | Apache-2.0. Where a hypertable stops being enough and the question turns into an aggregate over a billion rows. | None of them is a dependency here, and none of them is endorsed by anything but the fit. `conform` grades whichever you write exactly as harshly as the ones that ship. Most of what a store promises is not in the type. A redacted row keeps its place and its timestamp; clearing what it said also clears the vector it could still be found by; a negative limit means the whole window; handing a row back does not hand over the row itself. A driver can satisfy the compiler completely and get every one of those wrong, and nothing would say so until an agent recalled something that was meant to have been taken back. So ask it: ```ts import { conform, conformanceReport } from "@praecise/harness"; console.log(conformanceReport(await conform(myDriver, { url: "…" }))); ``` It answers with a line per promise, says which it did not check and why, and does not grade your backend any more gently than the ones that ship. --- # Reading documents into a store `praecise ingest` turns a folder of documents into rows an agent can answer from: ```sh praecise ingest ./docs --store catalogue praecise ingest ./docs --store catalogue --fields "price: the amount in pounds, sku: the product code" ``` PDF, Word, Excel, PowerPoint, CSV, images and source all convert. Text is split at the document's own paragraph boundaries rather than on a fixed window, because a half-sentence retrieved alone is worse than a miss — the model completes it from imagination instead of noticing it is partial. `--fields` is opt-in and costs a model call per chunk. It turns text you can search into records you can query, and it refuses rather than guessing: an extraction that does not parse, or that leaves out a declared field, is kept as text with the reason recorded. A row with prose where a price should be is worse than a row with no price. Ids are derived from the source path and the chunk's content, so running it twice does not double the catalogue and changing one paragraph replaces only that chunk. Point `ask: { store, type }` at the same store and `/ask` answers from it — the business's real data, live, rather than a copy. --- # Skills A skill is how to do a kind of work, written once and read only when it applies. It is a folder in the open [Agent Skills](https://agentskills.io/specification) format: ``` skills/ └─ refunds/ ├─ SKILL.md └─ references/policy.md ``` ```md --- name: refunds description: How to decide and issue a refund. Use when a customer asks for money back. --- 1. Look the order up before anything else. 2. … ``` Each agent's instructions list every skill's name and description. The body is read through a `read_skill` tool when the agent decides the skill applies, and the other files in the folder the same way, by path. `skills: ["refunds"]` on an agent narrows what it sees; `skills: false` gives it none. `allowed-tools` is read and not enforced. These are different from the [skills an agent works out for itself](#what-an-agent-remembers): those are proposed from its traces and wait for a person to accept them. ## Skills and plugins from a registry A registry is an index anyone can host, in the Agent Skills discovery format (`/.well-known/agent-skills/index.json`). An app lists the ones it reads: ```ts export default defineConfig({ registries: ["https://skills.example"] }); ``` ```sh praecise search refunds # look through the registries for skills and plugins praecise add refunds --show # fetch and print a skill without installing it praecise add refunds # install it ``` A skill is fetched over `https`, checked against the digest the index gives, and written to `skills//` with nothing marked executable. A plugin is not fetched: it is recorded in `praecise.plugins.json` and the command to install it is printed. `--kind skill` or `--kind plugin` says which, where a registry lists both under one name. Nothing is read from a registry unless one of the two commands is run, and there is no default registry. An app serves its own skills to MCP clients as well: `skills/list`, `skills/get` and `skill:///` resources. A skill whose front matter says `metadata: { access: internal }` is not served. --- # Evals An eval says what a right answer looks like, so a change to a role, a tool or a model can be checked rather than hoped about: ```ts // evals/support.ts import { evaluation } from "@praecise/harness"; export default evaluation({ agent: "support", trials: 3, cases: [ { name: "refund over the limit is not promised", input: "I want a refund of 900 for order 4021.", expect: [ { calls: "lookup" }, { avoids: "refund" }, { judge: "Says a person has to approve it, and does not promise a date." }, ], }, ], }); ``` ```sh praecise eval # every suite; exits 1 if a case misses its bar praecise eval support --trials 5 --json ``` A suite names an `agent` or a `workflow`. Graders are `contains`, `excludes`, `matches`, `equals` and `fields` (over `returns` data), `calls`, `avoids`, `judge` (a rubric graded by a model, which may answer "unknown"), `reference` (the answer says what a recorded one did), and `check` (your own function). A case may set `budget: { tokens, spend }`. Each case is run `trials` times and the report gives `pass@k` (at least one trial passed) and `pass^k` (every trial passed); `bar: "any"` accepts the first, and the default `"all"` requires the second. Trials do not share a conversation or memory. The same run is `app.evaluate(suite?, { trials })`. ## Cases from what really happened With `record: true` in the config, what each agent was asked, what its tools returned and what it answered is kept under `.praecise/recordings`, with credentials redacted. `capture` turns those into a suite: ```sh praecise capture support --last 50 # an agent's recorded exchanges praecise capture handle --name nightly # a workflow's runs, written as evals/nightly.ts ``` A captured agent case is replayed: a tool the agent calls is answered from the recording and never run, so the same input meets the same world every time, and a call the recording does not hold is answered with an error. The case's grader is `{ reference: "judge" }`, which compares a structured result field for field and asks a model whether two texts say the same thing; `--exact` writes `{ reference: "exact" }`, which fails any difference. A workflow's cases are captured and compared the same way, but its steps run for real. Replay needs the built-in runtime. `app.capture(name, { last, mode })` is the same from code, and `App.load({ recorder })` takes the record somewhere else. ## Scoring live answers A suite can score a sample of an agent's live answers with its graders: ```ts export default evaluation({ agent: "support", cases: [], online: { sample: 0.1, expect: [{ judge: "Does not promise a refund date." }], threshold: 0.8 }, }); ``` Scoring starts after the answer has been returned and can neither delay nor fail the request. The score is the share of the graders that passed. It goes to the app's `tracer` as a span named `evaluate ` in the answer's own trace, carrying a `gen_ai.evaluation.result` event, and below `threshold` it goes to `notify` as `com.praecise.eval.below`. One answer is scored at a time, and scores waiting beyond thirty-two are dropped. `app.settled()` waits for recording and scoring already begun; `app.close()` does too. --- # Events A workflow can be started, or continued, by something that happened elsewhere. **Pushed.** `POST /api/events/` takes a [CloudEvent](https://cloudevents.io) — structured (`application/cloudevents+json`), a batch of up to a hundred (`application/cloudevents-batch+json`), or binary (`ce-id`, `ce-source`, `ce-type`, `ce-specversion` headers with the data as the body): ```sh curl -X POST "$URL/api/events/paid" -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/cloudevents+json" \ -d '{"specversion":"1.0","id":"evt-1","source":"/billing","type":"invoice.paid","data":{"invoice":4021}}' ``` The run is named from the event's `source` and `id`, so an event delivered twice, as anything that retries will do, finds the run the first delivery started. The workflow receives the event's `data` as `event`, with `type`, `subject` and `time` beside it. `app.deliver(workflow, event)` is the same from code. A run of that workflow stopped at a `wait` step the event matches is continued instead, and only when none is waiting is a run started. **Published.** A workflow says which event types start it, and anything in the app can publish one: ```ts // workflows/fulfil.ts export default workflow({ on: "com.acme.order.placed", steps: [{ id: "pack", ask: "Pack order {{event.order}}", agent: "warehouse" }], }); ``` ```ts // functions/checkout.ts export default fn({ input: { order: "the order id" }, run: async ({ order }, { publish }) => { await publish?.("com.acme.order.placed", { order }); }, }); ``` `app.publish(event)` and `POST /api/events` do the same with a CloudEvent. Every workflow that declared the type starts a run, and every run waiting for the event continues. An event published twice with the same `source` and `id` starts nothing new, and a step that is retried publishes the same event. The bus is in this process: types match exactly, with no patterns; a chain of runs publishing to each other is refused past sixteen deep; and what a publisher read as untrusted does not mark the runs it starts. **Pulled.** `app.follow(source, workflow, { signal })` starts a run for every event a `Source` yields and stores the cursor of the last one handled, so it continues where it stopped after a restart. **On time.** A clock is a source: ```ts import { clock } from "@praecise/harness"; await app.follow(clock("nightly", { cron: "0 2 * * *", zone: "Europe/Lisbon" }), "report", { signal }); await app.follow(clock("poll", { every: 300 }), "sync", { signal }); ``` `cron` is five fields, read in `zone` (UTC unless said); `every` is in seconds. The run receives `scheduled` and `missed`. `catchUp` says what happens to ticks that fell due while nothing was running: `"latest"` (the default) runs the most recent and counts the rest in `missed`, `"all"` runs each, `"none"` runs none. There is no seconds field and no macros such as `@daily`, and nothing follows a clock unless the app calls `follow`. `cronNext(expression, after, zone)` is the arithmetic on its own. **Told.** A run outlives whoever started it, so an app can say what its runs do to somebody who is not holding a connection open: ```ts const app = await App.load({ root, notify: { url: "https://ops.example.com/hooks/praecise", secret: process.env.HOOK_SECRET }, }); ``` Each run reports `com.praecise.run.started`, `.waiting` (stopped at a gate, with the step and what is being asked), `.done`, `.failed` and `.cancelled` as CloudEvents, once per change, except that two processes holding the same run may each report its cancellation. The event names the run and its status and never carries what the run produced. A `{ url, secret }` target receives a signed webhook in the [Standard Webhooks](https://www.standardwebhooks.com) form (`webhook-id`, `webhook-timestamp`, `webhook-signature`), retried with backoff; `verifyWebhook(secret, headers, body)` checks one on the receiving side. `notify` may be a function instead. Delivery happens behind the run and cannot fail it; one that does not arrive is listed in `app.problems`. `app.onRunChange(listener)` hears the same changes in this process. **Described.** `GET /asyncapi.json` is the events the app receives and sends, as an AsyncAPI 3.1.0 document: the types its workflows start on and wait for, and the notifications above. `asyncApi(app)` builds it. --- # Work that outlives a connection Three callers can start work here and come back for it later: | Caller | How | | --- | --- | | An MCP client that declares the Tasks extension | Calling a workflow returns a task at once (`resultType: "task"`). The client polls `tasks/get`, or names the task in `subscriptions/listen` and is sent `notifications/tasks` as it changes. `tasks/cancel` stops the run. A run waiting at an approval gate is `input_required`, and is never approved over MCP. `tasks/get`, `tasks/update` and `tasks/cancel` require the `Mcp-Name` header. A client that does not declare the extension gets the blocking call it always got. | | An A2A peer | `SendMessage` returns a task; `GetTask`, `SubscribeToTask` and `ListTasks` follow it, and `CancelTask` stops the run. A 1.0 peer may register a webhook to be told instead (below). | | Anything that speaks HTTP | `POST /api/workflows/`, then the run's own record, or the events above. `POST /api/runs//cancel` stops it. | As a client, a tool call that comes back as an MCP task is followed to its end, by notification where the server sends them and by polling where it does not, and returned as the result it would have been. It is cancelled if the request is. --- # Plugins A plugin is a package that extends an app from `praecise.config.ts`: ```ts import { defineConfig } from "@praecise/harness"; import { billing } from "@acme/praecise-billing"; export default defineConfig({ plugins: [billing] }); ``` ```ts // in @acme/praecise-billing export const billing = { name: "billing", app: { agents: { invoices: agent({ /* ... */ }) }, functions: { refund: fn({ /* ... */ }) } }, drivers: [ledgerDriver], setup: () => registerReader("a ledger export", "application/vnd.acme.ledger", read), commands: { reconcile: { describe: "Reconcile the ledger.", run: () => 0 } }, }; ``` `app` is a piece of an app: agents, workflows, tools, functions, prompts, resources, stores, evals and skills, keyed by name as a folder keys them by file. It is merged under the app's own folder, so where both define a name the app's is used and the collision is reported in the app's warnings. `drivers` are storage backends. `setup` runs once before the app is planned, and is where a plugin registers a request shape (`registerWire`) or a reader. `hooks` are asked after the app's own `hooks.ts`, in the order the plugins are listed. `blobs` is where the app's blobs are kept in place of a folder on disk. `commands` run as `praecise `. Everything a plugin brings is checked by the rules the folder is checked by. ## An environment An environment is a plugin that equips agents for one platform or toolchain: the skills for working on it, the tools that reach it, an agent that knows it, and a command that says what the machine is missing. It is not a separate kind of thing, so nothing has to be learned to write one. ```ts // in @acme/praecise-android import { agent, skillsIn, tool, type Plugin } from "@praecise/harness"; export const android: Plugin = { name: "android", app: { skills: skillsIn(new URL("./skills", import.meta.url)), tools: { gradle: tool({ command: ["gradle-mcp"] }) }, agents: { android: agent({ description: "Builds, tests and releases the Android app.", role: "You build, test and release the Android app.", tools: ["gradle"] }), }, }, commands: { doctor: { describe: "Say what this machine is missing.", run: check } }, }; ``` `skillsIn` reads a folder of skills, one directory per skill with a `SKILL.md` and whatever sits beside it, the way an app's own `skills/` is read. The skills stay files, so the folder a package ships is one any other reader of the Agent Skills format can use as well, and there is one copy of each skill. A `SKILL.md` whose front matter cannot be read stops the package loading, with the file named. An app takes an environment with one line, `plugins: [android]`, and can narrow what an agent of its own sees with `skills: [...]` and `tools: [...]`. A skill or agent the app wrote under the same name is the one used. Environments are kept in their own repository, [praecise-harness-environments](https://github.com/Praecise/praecise-harness-environments), one folder each, with the rules for writing one. The first is for Apple development: building, testing, signing and releasing apps with Xcode. --- # Running it ```sh praecise dev # dashboard, chat, REST, MCP, traces — reloads on save praecise run support "where is order 4021?" praecise run handle message="I want a refund" praecise list praecise doctor # everything wrong with this app, in one pass praecise eval # run the evals; non-zero if a case misses its bar praecise capture support # turn recorded exchanges, or a workflow's runs, into eval cases praecise search refunds # look through the app's registries for skills and plugins praecise add refunds # add a piece to the app, or a skill or plugin from a registry praecise acp --agent support # serve an agent over stdio, for an editor praecise ingest ./docs --store catalogue ``` `doctor` is the first thing to run when something is not working. It reports what will stop the app, then what merely degrades it, then what is only worth knowing, and exits non-zero only on the first kind — so CI can gate on it. `run` also reads stdin, and takes `--json`. The rest of the commands, and the options that are not tied to one section of this page: ```sh praecise init my-app --template support # start from a template; --template alone lists them praecise memory support # what an agent carries, and what is proposed (see below) praecise mcp # serve the app on stdin and stdout, for an MCP client praecise package ./dist # write a package someone else can run praecise dev --port 4000 # the port, when it is not the config's or 3000 praecise eval --bail # stop at the first case that misses its bar ``` | | | |---|---| | `--dir ` | the project directory, for every command; the default is the working directory | | `--force` | with `init`, `add` and `capture`: overwrite files that already exist | | `--template ` | with `init`: `assistant`, `support`, `research` or `plan` | | `--provider ` | with `dev`, `run` and `eval`: put one endpoint from `models` first, whatever the order they are declared in | | `--json` | with `run`, `list`, `eval` and the Praecise Cloud commands: output a program can read | | `--hosted` | with `package`: package for a server others reach, where a caller is not trusted because a person launched it and anything `gated` stays hidden until the caller proves itself | | `--agent ` | with `acp`, the agent to serve; with `ingest --fields`, the agent that does the extracting | | `--scope ` | with `ingest`: the scope the rows are written under | `praecise check` is `doctor` and `praecise ls` is `list`. `praecise help` prints the usage. Colour is left out when output is not a terminal or `NO_COLOR` is set. Each command reads `.env` from the project directory before loading the app. `praecise --version` prints the version from 0.6.1; in 0.6.0 and earlier, use `praecise -v`. While `dev` is up: | | | |---|---| | `GET /` | dashboard | | `GET /` | chat UI | | `GET /w/` | run form and history | | `POST /api/agents/` | `{ input, thread?, attachments? }` | | `POST /api/workflows/` | the workflow's inputs | | `POST /api/functions/` | a function's inputs; answered as `{ result }`, through the guard | | `GET /api/runs` | the runs the app has kept | | `GET /api/runs//events` | one run, followed as a stream of its events | | `GET /api/threads`, `GET /api/threads/`, `DELETE /api/threads/` | conversations: listed (`?agent=` narrows), read, and forgotten | | `GET /api/resources/` | what a resource reads, in its own media type | | `GET /api/traces`, `DELETE /api/traces` | the spans behind `/traces` as JSON, and clearing them | | `POST /api/events/` | a CloudEvent; continues the run waiting for it, or starts one, once | | `POST /api/events` | a CloudEvent, published to every workflow that declared its type | | `POST /api/runs/` | `{ approved, approver?, signature?, note? }` | | `POST /api/runs//cancel` | stop a run; it is recorded as `cancelled` | | `POST /api/ui/` | what an MCP App's view asks of the service that brought it | | `POST /v1/responses` | an agent through the Responses API; `model` is the agent's name | | `POST /mcp` | every agent and workflow, as MCP tools | | `POST /a2a` | the same app as an agent a peer delegates to (A2A 1.0, and 0.3 for a caller that speaks it) | | `POST /a2a/message:send`, `POST /a2a/message:stream` | the same over A2A's HTTP+JSON binding | | `GET /a2a/tasks`, `GET /a2a/tasks/` | a peer's tasks, and one of them | | `POST /a2a/tasks/:cancel`, `POST /a2a/tasks/:subscribe` | stop a task, or follow it as a stream | | `/a2a/tasks//pushNotificationConfigs` | where a peer is told what a task does | | `GET /asyncapi.json` | the events this app receives and sends, as AsyncAPI | | `GET /.well-known/agent-card.json` | what a peer needs to know first | | `GET /ask`, `POST /ask` | a natural-language question, answered from this app's own store | | `GET /llms.txt` | a map of this app, for a model that arrived knowing nothing | | `GET /ai.json`, `GET /.well-known/ai-plugin.json` | the same, as JSON-LD | | `GET /robots.txt` | allows the front page, `llms.txt` and the server card, and disallows the routes that cost a model call | | `GET /traces` | what the last few requests actually did | | `GET /mcp/server-card` | what an MCP client needs before it connects | | `GET /.well-known/ai-catalog.json` | everything this origin offers, from one address | | `GET /.well-known/http-message-signatures-directory` | the public half of the key outbound requests are signed with; served only when `botAuth` is set | | `GET /health` | the app's name, what it contains by name, and its problems | A function that declares `http: "POST /webhook"` is also served at that method and path, with the same token and origin checks as `/api`: the body (or the query, for a `GET`) is its input and what it returns is the response. That MCP line means anything that speaks it — a chat app, an IDE, another agent — can use this app without knowing it is one. The rest is the same idea for the other kinds of caller: a peer agent (A2A), a person's front end (AG-UI, below), a client written against the Responses API, an editor (the Agent Client Protocol), and a machine that arrived at the URL knowing nothing (`llms.txt`). ## A peer agent Beside JSON-RPC at `/a2a`, the same methods are served in A2A's HTTP+JSON binding under the same address, as the routes above; there are no tenant-prefixed paths. gRPC is not offered and is not listed on the card. **Push notifications.** A peer speaking 1.0 may register a webhook for a task (`CreateTaskPushNotificationConfig`, and `Get`, `List` and `Delete` beside it, or `taskPushNotificationConfig` on the message that starts the task). Each change is posted to it as `application/a2a+json`. The address must be `https` and not a private or loopback one unless its host is allowed: ```ts await serve({ root, a2a: { push: { allowHosts: ["hooks.internal.example"] } } }); ``` A peer speaking 0.3 is refused push, and registrations are not kept across a restart. **Signed cards.** With `botAuth` set, the agent card is signed (JWS over the card's canonical JSON form). Before believing a peer's card: ```ts import { fetchAgentCard } from "@praecise/harness"; const { card } = await fetchAgentCard("https://peer.example", { keys, unsigned: "refuse" }); ``` `keys` is a key set already held for that agent, and `trust` names origins whose key sets are believed; the card's own origin is always among them. A card that is unsigned or cannot be verified is returned marked `unverified`, or refused with `unsigned: "refuse"`. `verifyAgentCard` checks a card already in hand. ## An interface the agent describes When a request says which A2UI catalogs its renderer can draw (`a2uiRendererCapabilities`), the agent gets a `show_surface` tool. What it sends is checked as an A2UI 1.0 envelope and returned beside the answer: over A2A as a data part of type `application/a2ui+json`, over AG-UI as an `ACTIVITY_SNAPSHOT`, and over HTTP as `a2ui` on the response. What the person does on the surface comes back as `a2ui` input on the next request. Component contents are not checked against a catalog, and there is no renderer here: that is the front end's. ## In an editor ```sh praecise acp --agent support ``` serves one agent over stdin and stdout in the Agent Client Protocol, for an editor that launches it. A prompt streams the agent's words and tool calls; a call the authority wants a person for is put to the editor as a permission request; and where the editor offers to read files or run a terminal, those are lent to the agent as tools for that session. The editor is given five minutes to answer a request (`AcpOptions.requestTimeoutMs`). Sessions can be created, loaded and cancelled. MCP servers an editor names when it creates a session are not connected, and plans, modes, listing sessions, authentication and audio are not offered. ## As a Responses endpoint `POST /v1/responses` answers in the shape of the Responses API, so a client written against that API can call an agent by putting its name in `model`: ```sh curl "$URL/v1/responses" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"model":"support","input":"where is order 4021?"}' ``` `input` is a string or a list of items, `stream: true` streams the events, and `previous_response_id` continues the conversation. A client's own function tools are offered to the agent: a call comes back as a `function_call` item and the client answers with `function_call_output`, within two minutes unless `serve({ responses: { toolWaitMs } })` says otherwise. Errors use the API's envelope. Refused by name, not ignored: `background`, a structured `text.format`, `tool_choice` other than `auto` or `none`, item references, file inputs, image URLs, the WebSocket transport and `/compact`. ## Streaming Any agent endpoint streams when you ask for `text/event-stream`. praecise's own event shape is the default; `?protocol=ag-ui` switches to AG-UI, which anything built to render agents already understands, and `?stream=` narrows what you get: ```sh curl -N -H "Accept: text/event-stream" \ "$URL/api/agents/support?protocol=ag-ui&stream=messages,tools" \ -d '{"input":"where is order 4021?"}' ``` `messages` is the agent's words, `tools` what it reached for, `updates` how the answer was routed, `custom` your own notes, `values` lifecycle only. They combine. A workflow streams too: `POST /api/workflows/?protocol=ag-ui` with `Accept: text/event-stream`. A run that stops at an approval gate ends its stream with `RUN_FINISHED` carrying an interrupt, and is continued by a request whose `resume` answers it, under the same rules as `POST /api/runs/`. ## Seeing what happened `praecise dev` collects OpenTelemetry GenAI spans in memory and renders them at `/traces` — a timeline per request, with how long each call took, tokens in and out, which model, and which failed. In production you pass your own `tracer` and the spans go to whatever you already run; praecise adds no OpenTelemetry dependency, because the convention is in the data and the transport is yours. Every `/api/*` route, `/mcp`, `/a2a`, `/v1/responses`, `/traces` and a function's own `http` route needs the bearer token the server prints on startup. Pass it as `Authorization: Bearer `. The discovery documents (`llms.txt`, `ai.json`, the agent card, `asyncapi.json`) and `/ask` answer without it and show a caller who has not presented it only what is open; the server card, the AI catalog, `robots.txt` and `/health` are the same for everyone. --- # Config Optional. A project needs none. ```ts // praecise.config.ts import { defineConfig } from "@praecise/harness"; export default defineConfig({ name: "Acme Support", quality: "balanced", port: 3000, }); ``` Every field is optional: | | | |---|---| | `name`, `version`, `description` | What the app is called (the folder's name by default), the version it publishes itself as (`0.1.0` by default), and one line on what it is for. | | `quality` | The default for every agent that does not set its own. | | `preference` | `"cost"`, `"balanced"` (the default) or `"quality"`: what to favour when cost and quality pull apart. Under `"quality"` the ladder is not climbed: the strongest rung answers at full depth and nothing is checked. | | `explore` | The share of routing decisions sent somewhere the estimate would not have sent them, so the routing record can be read back. Off by default; `EXPLORATION` (2%) is the value to use, and anything above 5% is clamped. Ignored under `preference: "cost"` and `"quality"`. | | `port` | The dev server's port. 3000 by default. | | `models` | The endpoints, in the order they are preferred (see [Install](#install)). | | `limits` | `depth`, `concurrency` (4 steps at once), `timeout` (600 seconds a step), `budget` (tokens a run may spend), `calls`, `spend`, `retries` and `retryDelay`. | | `store` | The store an agent remembers into when it asks for one without naming it. | | `stateDir` | Where runs, conversations, memory, recordings and the rest of the app's state are kept. `.praecise` by default. | | `strict` | Refuse where the framework would otherwise be friendly. An app with no model endpoint answers with a placeholder so that a new folder does something; with `strict: true`, or `PRAECISE_STRICT` set in the environment where the config says nothing, it refuses. An app whose configured endpoints cannot be reached refuses either way. | | `record` | Keep each exchange for [`praecise capture`](#cases-from-what-really-happened). | | `registries` | The indexes [`praecise search` and `praecise add`](#skills-and-plugins-from-a-registry) read. | | `plugins` | [Plugins](#plugins). | | `ask` | What `/ask` may spend and where it reads: `quality`, `mode` (`list`, `summarize`, `generate`), `agent`, `limit`, `store`, `type`. Left out, `/ask` retrieves and ranks without reaching a model. | | `ingest` | How files become text for `praecise ingest`: `using` is `native`, `model`, `mcp` or `cloud`, beside the `url` and `credential` of the service that does it. | | `selves` | Where [selves](#an-agent-that-remembers-who-it-is) live. | --- # Handing it to someone else An app is finished when someone else can run it. `praecise package` writes a directory that installs and starts like anything else on npm: praecise package ./dist cd dist && npm install && npx my-app What comes out is your own files, a launcher, and `mcp.json` — the tool surface, written down. Nothing is bundled or compiled, because the folder already is the app. Keeping the surface in a file means a rename shows up as a diff someone can review rather than as a break a caller discovers at run time. It also comes out importable, for a caller that would rather write code than read a list of tools: ```ts import app from "my-app"; const answer = await app.support({ input: "where is order 4021?" }); ``` That is the same app under the same rules — `api.d.ts` is a line per tool where `mcp.json` is a schema per tool, which matters when the reader is a model paying for every one of them. The same folder also runs in place. `praecise mcp` serves it on stdin and stdout for a client that launches it as a subprocess, and `praecise dev` serves it over HTTP for a browser and for anything already speaking the protocol. --- # Deploying to Praecise Cloud These commands are in 0.6.0 and later. The same command deploys a project on [Praecise Cloud](https://praecise.cloud), shows what is live, and goes back to an earlier release: ```sh praecise login # paste a token; it is checked, then kept for next time praecise deploy --wait # deploy the project and stay until it is live praecise releases # the releases that are kept, and which one is live praecise rollback # serve the previous release again praecise rollback 20261108-080000 praecise status # one project, or every project the token can see praecise logs -n 100 praecise whoami # who the token is, and what it may do ``` `deploy` asks Praecise Cloud to build and release the project from the source it is set up with; it does not upload this folder. Without `--wait` it returns as soon as the deploy has started. With it, the build log is printed as it grows and the command exits 0 when the release is live, 1 when it is not. `rollback` answers once the earlier release is serving and healthy, which can take a few minutes. The releases it can go back to are the ones `releases` lists. `logs` prints 200 lines unless `-n` (or `--lines`) says otherwise, from 1 to 2000. `--dir` names the folder `praecise.json` is read from. **The token.** Create one on the Account page of the console (), where you choose what it may do (read, deploy, roll back), which project it is for, and when it stops working. `praecise login` keeps it in `~/.config/praecise/cloud.json` (under `XDG_CONFIG_HOME` where that is set), readable only by you. On a build machine, set `PRAECISE_CLOUD_TOKEN` instead and skip `login`. The token is never printed. **The project.** A command takes it from the first of these that is there: the name on the command line (`praecise deploy shop`), `--project shop`, `PRAECISE_PROJECT`, or a `praecise.json` in the folder: ```json { "project": "shop" } ``` `rollback` takes the release on the command line, so name its project one of the other three ways. **In a script.** Every command takes `--json` and prints what the service answered, a refusal included, as `{ "error": "...", "code": "..." }`. The exit code says which kind of outcome it was: | | | |---|---| | `0` | done | | `1` | the deploy or rollback failed, or the service could not be reached | | `2` | the command, or what it asked for, was not valid | | `3` | not signed in, or the token may not do that | | `4` | no such project, release or deploy | | `5` | a deploy is already running for the project | `deploy` and `rollback` send a key with the request, so a request that is sent twice does the work once. To make a re-run of the same step safe as well, name the key yourself: `praecise deploy --wait --key build-4021`. | | | |---|---| | `PRAECISE_CLOUD_TOKEN` | the token, instead of the one `login` kept | | `PRAECISE_PROJECT` | the project, when it is not named on the command line | | `PRAECISE_CLOUD_URL` | the address of the service, when it is not `https://console.praecise.cloud` | An agent can do the same without the command line: the service speaks MCP at `https://console.praecise.cloud/mcp`, with the same token as the bearer. --- # Bring your own, or bring one key The framework is open source and complete on its own. Point it at your own model endpoints, your own database, your own object storage, and it runs entirely on things you operate — the only cost is that you describe each one and hold its credentials. Praecise Cloud is the managed side of the same app. One key, and the models behind the ladder, the database, and object storage are all provisioned for you and reachable through the same code you already wrote. Nothing in the app changes; the config gets shorter. --- # Underneath The runtime is part of the package and has no dependencies of its own — nothing to install alongside it, nothing to configure. It takes each question to the cheapest model that can answer it and climbs only when that one is not confident enough, which is why `quality` is the only dial you are given. --- # What you are trusting A framework does not get to assume where it will run, so here is what this one assumes and what it does not. **The dev server authenticates.** It mints a token on startup and prints it; every `/api/*` and `/mcp` request needs it. It binds loopback by default, and it **refuses to start** on an address the network can see unless you have configured authentication — a refusal rather than a warning, because that misconfiguration is the one that turns every other risk into a remote one. Mutating requests are checked against an origin allowlist and a `Host` allowlist, and must be `application/json`, so a page you happen to be visiting cannot drive it and a rebound DNS name cannot read it. **Approvals are attributed; they are non-repudiable only if you make them so.** With no signer wired, an approval records who claimed it and is marked `unsigned` — the framework will not synthesise a signature, because a fake one is a lie the audit trail carries forever. Wire `approvals.sign` and `approvals.verify` and the picture changes: a signature that does not verify is refused rather than stored, and a quorum counts the **subjects your verifier proved**, never the names a caller typed. A gate that requires two people refuses to start without a verifier, rather than accepting one person twice. **Agents are not sandboxed from the control plane.** `guard.ts` is the boundary for what a tool may do, and it sees which channel a call arrived on. A `plan` step gives a model no tools unless you name them. **Everything is persisted in plaintext unless you seal it.** Prompts, inputs, outputs and conversations go to `/.praecise/`, owner-only (`0700`/`0600`), with no retention policy. Three things can be sealed at rest, each with a cipher of your own: workflow runs (`runCipher`), conversations (`threads`) and what agents remember into files (`memory`): ```ts const app = await App.load({ root, runCipher: cipher, threads: cipher, memory: cipher }); ``` `threads` also takes a backend in place of a cipher (`Conversations`), to keep conversations somewhere else altogether. Memory is kept somewhere else by naming a store, on the agent or as the app's `store`. Still plain: the routing record, recordings, the ingest cache and source cursors. Credentials quoted by an exception are redacted before anything is written. If you process personal data, this directory is your record and `app.redact()` is your erasure mechanism. **Limits are enforced, not declared.** A budget counts planning and judging, not just the obvious calls; concurrency is bounded across the whole run rather than per step, so nesting cannot multiply it; and every model call has a timeout. **The app has the last word on spending.** A `meter` is asked before every model call the runtime makes: each rung tried, each sample, a climb, a summary, advice, a transcription, and the calls of an agent asked on the way. ```ts const app = await App.load({ root, meter: { reserve: (call) => (spent(call.caller) > allowance ? "This account has used its allowance." : undefined), settle: (call, usage) => record(call.caller, usage), }, }); ``` `reserve` is handed the agent, the rung, the caller, the context and an estimate. A sentence back refuses the call and ends the request with `MeterRefused`; a refusal is never answered by climbing to another model. `settle` is told what the call took. Live sessions and embeddings are not metered, and a permission classifier is only when it is passed the same meter. --- # Acting under someone else's rules An agent that pays, signs or moves anything usually answers to rules the app does not write: a mandate, a policy service, a signed delegation. Five seams carry that, all off until passed to `App.load`: ```ts const app = await App.load({ root, authority, // check(attempt) -> { allow } | { refuse } | { stepUp, digest } journal: { sink, signer }, // every acting step sealed, chained, signed, delivered payer, // a 402 paid once per step, status before pay botAuth, // every outbound request signed (Web Bot Auth), key directory served sandbox, // snapshot per step, restore before recovery runCipher, // runs sealed at rest }); ``` A function says what it does as an `action`, computed from the arguments it was actually given, and whether its output can be trusted: ```ts export default fn({ input: { to: "who", amount: "how much" }, effect: "write", action: ({ to, amount }) => ({ operation: "pay", counterparty: String(to), amount: String(amount) }), run: async ({ to, amount }, { fetch = globalThis.fetch }) => (await fetch(`https://pay.example/${to}?amount=${amount}`)).json(), }); ``` The authority is asked after `guard.ts` on every path: the model's tool loop, workflow steps, HTTP, MCP and the CLI. A refusal goes back to the model as the tool's result. A `stepUp` on a workflow step pauses the run at `:approve`; the approval must be signed over a claim that includes the action's `digest`, and the step is asked again with the verified approver attached. Once untrusted output (a fetched page, an inbox) has been read, every later action in that conversation or run is marked `tainted`, so the authority can insist on a person for anything the text might have put there. An authority can be a policy in prose, read against each call by a model: ```ts import { permissionClassifier } from "@praecise/harness"; const authority = permissionClassifier({ policy: "Refunds up to 100 are fine. Anything that sends email needs a person.", models: config.models, rung: "fast", }); ``` It answers allow, deny or ask, and ask becomes a `stepUp`. It is shown what the person said and the calls the agent has made (`attempt.recent`), never what a tool returned or what the model wrote, so text the agent merely read cannot argue its own case. Identical calls are answered from memory (the last 500 decisions, or `remember`). A classifier that cannot be reached, whose answer cannot be read, or that has not decided within `timeoutMs` (20 seconds by default) does not allow the call. `allowReads: true` lets calls that declare `effect: "read"` through without asking, `endpoint` names which of `models` decides, and `onDecision` is told every decision. In a conversation, a `stepUp` can be answered mid-turn: `approve` on an ask is handed the call and its digest, puts the question to a person, and returns the approval once `app.approvalOf(asking, decision)` has verified it. The authority is then asked again with the approval attached. --- # Deciding what leaves the building Anything published can say who may reach it and what calling it does: ```ts export default agent({ role: "Review the ledger and flag anything unusual.", description: "Audits transactions for a named account.", access: "gated", // open (default) · gated · internal effect: "read", // read · write (default) · destructive }); ``` `internal` is the useful one. The agent still exists and your other agents still use it, it simply never leaves — it is absent from the published list and cannot be called even by a caller who knows the name, because refusing is not the same as admitting it is there. This is worth doing for a reason beyond privacy. A caller shown twenty tools starts acting where it should have declined, so the smallest honest surface is also the most accurate one. `effect` feeds the same judgement: it tells a caller what a call would cost before it makes it, and an undeclared tool is assumed to change something. Both `mcp` and `package` will narrow further on request, and packaging says so when the surface has grown past what a caller can weigh: ```sh praecise mcp --groups workflows # one part of the app, not all of it praecise package ./dist --read-only # only what changes nothing ``` The same two narrow the dev server: `POST /mcp?groups=workflows&read`. An agent can also say what a catalogue should show about it: ```ts export default agent({ role: "Review the ledger and flag anything unusual.", description: "Audits transactions for a named account.", meta: { version: "2.1.0", tags: ["finance", "ledger"], languages: ["en", "pt-BR"], examples: ["Review account 4021 for March."] }, }); ``` `meta` is read by every surface that lists the agent: its skill on the A2A agent card (where `tags` replace the group it is published in, and `inputModes` and `outputModes` are stated), its MCP tool's `_meta["com.praecise/meta"]`, `llms.txt` and the JSON-LD. It is never shown to a model. Nothing published can be undescribed. `praecise package` refuses an app whose tools say only their own name back, because a caller reads the description and nothing else before deciding — describe it, or mark it `internal` if it was never meant to leave. ## Deciding call by call `access` and `effect` settle what an agent may reach for. What it may do with a particular call is a different question, and a `guard.ts` at the root answers it: ```ts import { guard } from "@praecise/harness"; export default guard(({ tool, args }) => { if (tool === "refund" && Number(args.amount) > 500) { return "A refund over 500 needs a person to approve it."; } }); ``` Say nothing and the call goes ahead. Say a sentence and it does not — and the sentence goes back to the model as that tool's own result. That last part is the point. A model told a refund needs approval can say so to the customer and offer to raise it; a model handed an exception can only stop, and the run ends somewhere nobody chose. So write the reason for the model to read, because it will read it. A guard that throws is treated as a refusal too, for the same reason: the app was asked and did not manage to say yes. A refusal is not counted against the model that asked for it. It says nothing about whether that model was good enough — a stronger one would have been refused in the same place. ## After a tool, and before stopping A guard speaks before a call. `hooks.ts` at the root speaks at the moments after: ```ts import { hooks } from "@praecise/harness"; export default hooks({ afterTool: ({ tool, result }) => (tool === "lookup" ? { result: withoutCardNumbers(result) } : undefined), beforeStop: ({ transcript }) => (ranTheTests(transcript) ? undefined : "Run the tests before answering."), beforeCompact: () => ({ keep: true }), }); ``` Each answers as a guard does: say nothing and what was going to happen happens. `afterTool` sees every result before the model does, and may replace it (`{ result }`) or withhold it with a sentence the model reads instead (`{ reject }`). `beforeStop` is asked when an agent answers instead of calling a tool; a sentence back sends it to work again with that as the reason, three times in one conversation and no more. `beforeCompact` is asked before earlier work is replaced by a summary: `{ keep: true }` forbids the summary and `{ summary }` supplies one. `beforeRecord` decides [what a self is sent](#an-agent-that-remembers-who-it-is). --- # What the API covers Every name exported from `@praecise/harness` is listed in [API.md](API.md), grouped by the task it belongs to. From 1.0 that list is what semantic versioning covers. The framework's own moving parts — the project loader, the planner, the provider wire formats, the packager, the CLI entry point — live at `@praecise/harness/internal`, which is deliberately **not** covered: names there may change or disappear in any release, patch releases included. Nothing was deleted to draw that line; it moved, so that needing one of those names never means forking the framework. Changes to either surface are recorded in [CHANGELOG.md](CHANGELOG.md). [CAPABILITIES.md](CAPABILITIES.md) lists everything the framework does and what it deliberately does not, each as `built` or `declined` with the reason, the seam a new capability goes in through, and what the tests do not cover. --- # The public API Everything exported from `@praecise/harness` is listed here. From 1.0 onwards this list is what semantic versioning covers: a name on this page will not be removed, and its shape will not change incompatibly, without a major release. Anything **not** on this page is not part of the promise, even if you can reach it. In particular: > **`@praecise/harness/internal` is unstable and unversioned.** Every name behind that > subpath may change, be renamed, or disappear in any release, including a patch > release. There is no deprecation period. It exists so that needing one of the > framework's own moving parts does not force you to fork the framework — not as > a second API. If something you genuinely need is only reachable there, please > open an issue; that is a gap in the surface below. Deep imports (`@praecise/harness/dist/...`) are not reachable at all. The package's `exports` map has exactly five entries: `.`, `./internal`, `./formats`, `./testing`, and `./package.json`. `@praecise/harness/formats` and `@praecise/harness/testing` are public and are listed [below](#praeciseharnessformats). --- ## Authoring — writing the app A folder of these calls *is* the app. This is the only part most apps ever use. | Name | What it is | | --- | --- | | `agent` | Declare an agent: a role, what it knows, what it may act through. | | `workflow` | Declare a sequence or graph of steps, with a declared outcome. | | `tool` | Declare an external service the app may call. | | `fn` | Declare a local function an agent may call. `http: "POST /webhook"` also serves it at that method and path on the dev server. | | `prompt` | Declare a named, parameterised prompt. | | `resource` | Declare a readable resource addressed by URI. | | `store` | Declare a backing store (`sql`, `vector`, `document`, `timeseries`; `graph` needs a brought backend — see [Storage](#storage-and-extending-it)). | | `guard` | Declare a check that runs before a call and may refuse it. | | `hooks` | Declare what happens after a tool runs, before an agent stops, before a transcript is summarised, and before a self is sent its record (`hooks.ts`). | | `middleware` | Wrap every call the app makes. | | `knowledge` | Declare a document the app knows, in code rather than in `memory/`. | | `blueprint` | Declare a set of files that scaffolds a whole app. | | `template` | Declare a set of files that scaffolds one part of one. | | `evaluation` | Declare an eval suite: an agent or workflow, cases, and what a right answer looks like. | | `defineConfig` | The contents of `praecise.config.ts`. | | `QUALITIES` | The ladder rungs, in order: `fast`, `balanced`, `best`. Frozen. | **Narrowing a step.** A `Step` is a union; these tell you which arm you have. `isAsk` · `isUse` · `isApprove` · `isWait` · `isPlan` · `isEach` · `isRepeat` · `isWhen` Each asks whether the step carries that discriminant as its OWN key with a value that is not `undefined` — so `{ ask: cond ? "x" : undefined, use: "svc.fallback" }` is a `use`, and a key inherited from a prototype does not classify anything. `STEP_KINDS` is the same eight names in the order the runner dispatches them, and `kindsOf(step)` returns the ones a step carries. A step carrying more than one is refused when the workflow loads: nothing can tell which was meant, and guessing is how a nested body came to be validated, reported, and never run. **Types.** One `*Spec` per kind (what the call returns) and one `*Input` per kind (what you pass it): `AgentSpec`/`AgentInput` · `WorkflowSpec`/`WorkflowInput` · `ToolSpec`/`ToolInput` · `FunctionSpec`/`FunctionInput` · `PromptSpec`/`PromptInput` · `ResourceSpec`/`ResourceInput` · `StoreSpec`/`StoreInput` · `GuardSpec`/`GuardInput` · `MiddlewareSpec`/`MiddlewareInput` · `KnowledgeSpec`/`KnowledgeInput` · `BlueprintSpec`/`BlueprintInput` · `TemplateSpec`/`TemplateInput` · `EvaluationSpec`/`EvaluationInput` · `HooksSpec`/`HooksInput` An authored skill (`skills//SKILL.md`) has no call of its own; in a code-defined app it is `AuthoredSkillInput`, and loaded it is `AuthoredSkill`. Supporting types: | Type | What it describes | | --- | --- | | `Published` | What every published thing declares: `access`, `effect`, `group`. | | `Access` | Who may reach it: `"open"`, `"gated"`, `"internal"`. | | `Effect` | What calling it does: `"read"`, `"write"`, `"destructive"`. | | `Step` | The step union, and its arms `AskStep`, `UseStep`, `ApproveStep`, `WaitStep`, `EachStep`, `WhenStep`, `RepeatStep`, `PlanStep`. A `WaitStep` stops a run until a CloudEvent of the `wait` type arrives, narrowed by `source` and `subject`, with a `timeout` in seconds and `onTimeout: "fail" \| "continue"`. | | `Check` | What a `repeat` runs until, and what a workflow's `outcome` asserts. | | `Ref` | A reference into the run's scope, written as text. | | `Returns` | A declared output shape: field names to plain-English hints, a JSON Schema object, or a Standard Schema validator. `DataOf` is what `answer.data` is for one. | | `Quality` | One rung of the ladder. | | `Limits` | Ceilings a run inherits: `depth`, `concurrency`, `timeout`, `budget`, `calls` (model calls one request may make), `spend` (a `Money` one run may spend, counted from declared `prices`), and how patient to be with an endpoint that is merely busy — `retries` (default 2) and `retryDelay` (default 200 ms, doubling with jitter). | | `Money`, `Prices`, `Rates` | An amount in a named currency; what an endpoint charges per rung (`prices` on a model endpoint); and what a million tokens cost on one model (`input`, `output`, `cachedRead`, `cacheWrite`, `reasoning`). | | `AgentMeta` | `meta` on an agent: `version`, `tags`, `languages`, `inputModes`, `outputModes`, `examples`, and anything else, for the surfaces that list the agent. | | `FunctionRunOptions`, `Publish` | The second argument of a function's `run`: `idempotencyKey`, `run`, `step`, `fetch`, `approvals`, `signal`, `publish` (a `Publish`, which puts an event on the app's bus), `transcript`, `caller` and `context`. | | `ToolOutcome`, `Stopping`, `Compacting`, `AfterTool`, `BeforeCompact` | What each hook is handed, and what `afterTool` and `beforeCompact` may answer. | | `OnlineEval`, `RecordedRun`, `RecordedTool` | `online` on an eval suite (`sample`, `expect`, `threshold`), and the recorded run a captured case carries (`answer`, `data`, `tools`). | | `ServiceOAuth` | `oauth` on a service: the `client_credentials` or `id-jag` grant its token is obtained with. | | `RecordOf`, `RecordInputOf`, `TypedStoreSpec` | The record a store's `schema` describes, what it accepts on the way in, and a store declared with one. | | `Recent` | One entry of `Attempt.recent`: something the person said, or a call the agent made. | | `MemorySpec` | How an agent remembers: `store` (all of its memory goes there; `AppConfig.store` is the default), `recall`, and `reflect` (a schedule on which its record is read back, started by `praecise dev`, `serve()` or `app.tend()`). | | `App.reflect`, `App.tend`, `App.pending`, `App.accept`, `App.reject`, `App.retire`, `App.learned`, `App.carried`, `App.recorded`, `App.jotted`, `App.jot`, `App.filed`, `App.page`, `App.redact`, `App.clearMemory`, `App.evaluateMemory` | An agent's memory from code: read its record back, decide on what is proposed, see and change what is kept, and measure what memory is worth on a suite. `Reflection`, `MemoryGain`, `AlreadyReflecting`. | | `AppConfig` | The `praecise.config.ts` shape: `name`, `version`, `description`, `quality`, `preference`, `explore`, `port`, `models`, `limits`, `store`, `stateDir`, `strict` (or `PRAECISE_STRICT` in the environment where the config says nothing), `record`, `registries`, `plugins`, `ask`, `ingest`, `selves`. | | `Provider`, `ModelProvider` | An endpoint the app may call: `url`, `credential`, and three fields for an endpoint with needs of its own — `credentialHeader` (the header the credential goes in, where a bearer is refused), `headers` (sent with every request, and applied last), and `body` (fields merged into the request that the protocol does not name; what the request itself asks for always wins). | | `Call`, `Reply`, `Attempt` | What middleware and guards are handed. | | `FileContents` | One file a blueprint or template writes. | | `StoreKind` | Which kind of store a `store()` declares. | | `StepKind` | One of `STEP_KINDS`. | | `Preference` | `preference` in the config: `"cost"`, `"balanced"` (default) or `"quality"` — what the deployment values when cost and quality pull apart. Under `"quality"` the strongest rung answers and nothing is checked. | | `EvalCase`, `Grader`, `GraderKind`, `GRADER_KINDS` | One case of an eval (`name`, `input`, `expect`, `budget` in tokens or money, `recorded`), the graders it may expect (`contains`, `excludes`, `matches`, `equals`, `fields`, `calls`, `avoids`, `judge`, `reference`, `check`), and their names. | | `CodeModeSpec` | `code` on an agent: `silo`, `language` (`typescript`, `javascript`, `python`), `ttl` (seconds, default 1800) and `allow`. See [Code mode](#code-mode). | ## Running — loading a folder and driving it | Name | What it does | | --- | --- | | `App` | Load a folder into a running app. `App.load({ root })`. | | `AppOptions` | What `App.load` accepts: root, env, fetch, drivers, telemetry sink, `prefer` (one endpoint from `models` put first, whatever order they are declared in), `askConcurrency` (how many asks may be in flight at once, 8 by default), `maxInput` (the longest input one ask may carry, 200,000 characters by default), and the seams listed on this page — `embedder`, `reranker`, `blobs`, `approvals`, `authority`, `journal`, `payer`, `botAuth`, `notify`, `runCipher`, `threads`, `memory`, `sandbox`, `tracer`, `recorder`, `selves`, `mcp`, `meter`, `WebSocket`. | | `startRun` | Start a workflow run. | | `resumeRun` | Resume one that stopped at a human approval gate. | | `cancelRun` | Stop a run and record it as `cancelled`. `App.cancelWorkflow(id, { reason, by })` is the same over a loaded app. | | `signalRun`, `timeoutRun`, `awaits` | Continue a run stopped at a `wait` step with the event it awaited, end a wait that ran out of time, and say whether a run is waiting for a given event. `App.signal(event)` and `App.expire()` are the same over a loaded app. | | `subscriptionsOf` | The CloudEvent types a workflow's `on` names. `App.publish(event)` starts a run of every workflow that declared the type and continues every run waiting for it. | | `clock`, `cronNext` | A `Source` that ticks every so many seconds or by a five-field cron expression in a time zone, for `App.follow`; and the next time an expression falls due. Types: `ClockOptions`, `Schedule`, `Tick`. | | `recoverRun` | Re-drive a run that was interrupted, refusing where exactly-once cannot be proven. | | `RunStore` | Where runs are persisted, and how they are listed and loaded. | | `serve` | Bring up the dev server: chat UI, REST, and an MCP endpoint. | | `serveStdio` | Serve the app over MCP on stdio, for an editor or another agent. | | `followRun` | Async-iterate a run's events, from the start and then as they arrive. | | `provenanceOf` | Build the graph of what a run derived from what. | | `createApp` | An app described in code (`AppDefinition`) rather than a folder, ready to run. Refuses a faulted definition. | | `defineApp` | The same definition checked into a `Project` without starting it, so `warnings` and `faults` can be read first. | | `mergeApps` | Compose definitions; later ones win, and every collision is reported in `collisions`. | | `cloudEvent`, `readCloudEvents`, `CLOUDEVENTS_JSON`, `CLOUDEVENTS_BATCH` | Mint a CloudEvents 1.0 event; read the events an HTTP request carries (structured, batched or binary), or a sentence saying why it carries none; and the two media types. `App.deliver(workflow, event)` continues the run of that workflow waiting for the event, or starts one, once per `source` + `id`. | | `App.replace`, `App.add`, `App.remove` | Replace an agent of a running app, add one, or remove one by name. Requests under way finish on the plan they started with. | | `App.askMany` | Many questions for one agent through the endpoint's batch API; a `Batched` (`{ answer }` or `{ error }`) per question, in order. | | `App.open` | Open a live session with an agent (`OpenOptions`), returning a `Session`. | | `App.capture`, `App.settled` | Eval cases from an agent's recordings or a workflow's runs; and a promise for the recording and scoring already begun. | | `App.approvalOf` | Verify a person's decision on a `StepUp`, for `AskOptions.approve` to return. | | `App.onRunChange` | Hear each `RunTransition` in this process; returns the function that stops listening. | | `App.blobs`, `App.threads` | The app's `BlobStore` and its conversations. | | `runEvaluation`, `runEvaluations` | Run one eval suite, or several, against anything that can ask an agent and run a workflow. `App.evaluate(suite?, options)` is the same over a loaded app. | | `evaluationFaults` | What is wrong with an eval suite as written. | | `renderReport` | An `EvalReport` as the table `praecise eval` prints. | | `Recordings`, `casesFromRecordings`, `casesFromRuns`, `renderCapturedSuite` | Exchanges kept as they occurred (`record: true` in the config, or `AppOptions.recorder`), eval cases made from them or from a workflow's runs, and a suite file written from those cases. Types: `Recorder`, `Recording`, `ReferenceMode`. | | `recordingTape`, `replayTape`, `redacted` | A `ToolTape` that writes a request's tool calls down, one that answers them from a recording, and a recording with credentials taken out. | | `scoreAnswer`, `evaluationSpan`, `EVALUATION_EVENT` | Score one live answer with a suite's `online` graders (`OnlineScore`), the span that carries the score, and the name of its event, `gen_ai.evaluation.result`. | | `EVAL_EVENT_TYPES`, `evalEvent`, `EvalNotice` | The notification sent when a live score falls below its threshold (`com.praecise.eval.below`), as a CloudEvent. | | `DISCOVERY_SCHEMA`, `WELL_KNOWN_SKILLS`, `indexUrlOf`, `parseIndex`, `searchEntries` | Reading a registry: the discovery schema followed, the well-known path of an index, the index URL for a registry as configured, an index parsed into `RegistryEntry` rows, and a search over them. | | `skillsIn` | Read a folder of skills (one directory per skill, a `SKILL.md` and the text files beside it) into the record `Plugin.app.skills` and `defineApp` take. | | `fetchSkill`, `installSkill`, `installCommand`, `recordPlugin`, `readRecordedPlugins`, `readRegistries`, `PLUGINS_FILE` | Installing from a registry: fetch a skill and check its digest (`FetchedSkill`), write it to `skills//`, the install command for a plugin, record a plugin in `praecise.plugins.json` (`RecordedPlugin`), and read that file and the configured registries. | | `unpackArchive`, `safeRelativePath` | Unpack a skill archive within limits (`ArchiveFile`, `ArchiveLimits`), and refuse a path that would leave the folder it is written to. | Types: `Run`, `RunStatus`, `RunEvent`, `PlanVersion`, `Outcome`, `ProvGraph`, `WorkflowDeps`, `GenAiSpan`, `ProvisionRequest`, `ProvisionResult`, `ApprovalClaim`, `ApprovalDecision`, `VerifyResult`, `DevServer`, `ServeOptions`, `StdioServer`, `StdioOptions`, `Project`, `Doc`, `AgentPlan`, `LocalTool`, `ResolvedService`, `Rung`, `AppDefinition`, `Approvals` (the shape of `AppOptions.approvals`: the signer and verifier for gates), `EvalOptions`, `EvalReport`, `SuiteReport`, `CaseReport`, `TrialReport`, `EvalTarget`, `EvalJudge`, `CloudEvent`, `Plugin` (what `plugins` in the config takes: `name`, `commands`, `app`, `hooks`, `drivers`, `blobs`, `setup`; `CliPlugin` is its earlier name), `ToolContext` (what a `LocalTool`'s `run` is handed besides its arguments: the transcript so far and the request's signal), `AwaitedEvent` (what a run stopped at a `wait` step is waiting for). `RunStatus` includes `cancelled`. `Span` carries `events` (`SpanEvent`). An `AgentPlan` also carries `delegates` (other agents named in `tools`), `turns` and `advisor`. A `Rung` carries `levels`, `output` and `cache` where the provider declared them. `Project` and `Doc` are what `App.project` is. `AgentPlan` is what an agent was compiled into — the composed instructions, the rungs to try, the tools it may call — and is what a custom `WorkflowDeps.planFor` must return. `ApprovalClaim` is exactly what an approval signature covers; implement `WorkflowDeps.sign`/`verify` against it. With no signer, nothing is synthesised — the ledger records the approval as unsigned rather than inventing a signature. ## Acting under rules — actions, authority, payments, journal What an app needs when its agents act for someone under rules it does not write itself. Every piece is optional and off until passed to `App.load`. | Name | What it does | | --- | --- | | `Action` | A side effect in checkable terms: operation, counterparty, amount, asset, network, model, detail; `tainted` is set by the runtime. A function declares one with `action(args)`. | | `Trust` | `"trusted"` or `"untrusted"` on a function (`trust`) or a service (`ToolSpec.trust`, default untrusted). Reading untrusted output taints every later action in that conversation or run. | | `Authority`, `Verdict` | `AppOptions.authority`: `check(attempt)` answers a `Verdict` — `allow`, `refuse` or `stepUp` with a digest. Asked after the guard on every path to a tool. | | `StepUpRequired` | What a direct call throws on `stepUp`. A workflow `use` step turns it into a gate named `:approve` whose signed `ApprovalClaim` carries the `digest`; the call is asked again with the verified approval (subject, digest, signature) in `Attempt.approvals`, and a local function receives the same list as `opts.approvals` (`FunctionRunOptions`, each a `VerifiedApproval`) to present onward. In a conversation it is a refusal the model reads. | | `Journal`, `Signer`, `JournalSink` | `AppOptions.journal`: every finished `ask` and `use` step is sealed as a `JournalEntry` (input and output digests, action, approvals, payments, evidence, sandbox snapshot), hash-chained, signed when a signer is given, recorded on the run, then delivered to the sink, which may return an anchor. A sink failure fails the run; recovery re-delivers. | | `verifyJournal` | Check sealed entries: numbering, chain, hashes, and signatures when given a verifier. | | `seal`, `SealedEntry` | Hash a `JournalEntry` and sign the hash when there is a signer. | | `canonicalJson`, `digestOf` | JSON with keys sorted at every depth, and the digest over it, so equal values hash equally. | | `Payer`, `payingFetch`, `withPaymentKey` | `AppOptions.payer`: a 402 met by the app's fetch is paid under a key derived from the step's idempotency key, asking `status(key, required)` first so a retried step reuses a settled payment, presented the way that server asked for it. Local functions receive the app's fetch as `opts.fetch`. Types: `PaymentRequired`, `Paid`, `PaymentStatus`, `PaymentRecord`. | | `Sandbox` | `AppOptions.sandbox`: `snapshot` after each journalled step (named on the entry), `restore` of the latest before `recoverRun` drives a crashed run. | | `RunCipher` | `AppOptions.runCipher`: run files sealed at rest; plaintext files are refused rather than read. | | `StateCipher`, `isCipher` | The same two operations, for `AppOptions.threads` and `AppOptions.memory`: conversations, and what agents remember into files, sealed at rest. | | `Conversations`, `Threads`, `Folder` | Where conversations are kept: the interface a backend implements (`load`, `append`, `list`, `forget`), the app's own, and the one that keeps them as files. Types: `Thread`, `ThreadSummary`, `Turn`. | | `permissionClassifier` | An `Authority` that reads a policy written in prose against each call by asking a model: allow, deny, or ask a person. Refuses when it cannot decide. Types: `ClassifierOptions`, `Classified`, `Decision`. | | `Meter`, `MeterRefused`, `CallLimitReached`, `estimateOf` | `AppOptions.meter`: `reserve(call)` is asked before every model call and refuses with a sentence; `settle(call, usage)` is told what it took. `MeterRefused` is what a refused request ends in, `CallLimitReached` what one past `maxCalls` ends in. Types: `MeteredCall`, `MeteredUsage`, `CallPurpose`. | | `AskCaller` | Who a request is for: `person`, and anything else the app adds. Carried with `context` to the guard, the authority, functions and the meter, and to no model. | | `StepUp` | What `AskOptions.approve` is asked: the call the authority allows only with approval, and its `digest`. | | `outboundFault`, `privateAddress` | Whether an address a caller supplied is one this process should request: `https`, and not private or loopback unless its host is allowed (`OutboundOptions`). | | `postWithRetries` | The retrying POST webhooks are delivered with. | | `Source`, `SourceEvent`, `App.follow` | Durable triggers: one run per event, the cursor stored after each (`CursorFile` keeps it between runs of the process), a re-delivered event finding the run it already started (`runIdFor`). | | `CliPlugin` | `plugins` in the config: commands reached as `praecise `. | | `ChatResponse.evidence` | A wire may return proof of what it ran; it is collected on `Answer.evidence` and carried into the journal. A wire that requires it refuses a reply without it. | ## The harness — models, memory, and adapters | Name | What it is | | --- | --- | | `BuiltinHarness` | The harness that ships with the framework. | | `resolveHarness` | Pick a harness from config and credentials. | | `Harness` | The interface a harness satisfies. Implement it to replace ours. | | `ChatAdapter` | `(request: ChatRequest) => Promise` — one provider. | | `ProviderError` | What an adapter throws when a provider refuses or fails. Throwing this rather than a bare `Error` is what lets the ladder tell a retryable failure from a fatal one. | | `Episode`, `Jotting`, `Page`, `PageSummary`, `Note`, `Candidate`, `ProposedNote`, `Retirement`, `Accepted`, `Filed` | What an agent keeps and carries, as `App` hands it back: an exchange, a working note, a subject page, a carried fact or procedure, a proposal and its parts, and what accepting or filing came to. | | `Origin`, `authorityOf` | Where something kept came from (`user`, `tool`, `agent`, `external`), and the authority of something drawn from several sources: the lowest of them. | | `Ledger` | The record of routing decisions, and what they cost. Every row carries the `propensity` of the choice it records; without that the log answers "was this escalation worth it" and nothing else. | | `route`, `difficultyOf` | Where a request starts and how hard it looked. Difficulty counts the conversation, the choice of tools, and how much has to be read — not the length of the question. | | `riskOf` | How likely a request is to be got WRONG, which is a different axis from how hard it is. Question length lives here: it predicts failure after difficulty is controlled for, so it widens the margin at which an answer is checked instead of moving which model answers. | | `verifyMarginFor` | How much band-headroom is close enough to be worth checking: `VERIFY_MARGIN` at rest, widening with risk and stakes. | | `ladderFrom` | The depths to ask one rung for, in order, before crossing to another model. At most three, because that is how many an endpoint can tell apart. | | `attach` | Return something other than text from a function: `attach(result, ...attachments)`. | | `registerReader`, `knownReaders` | Teach the framework to show a kind of data to a model, by media type, and list the readers registered. A `Reader` is handed the attachment and its text, and returns what the model should read. Later registrations are asked first. | | `embedderFor` | The `Embedder` for the first reachable endpoint in `models` that names an `embeds` model, or nothing. `AppOptions.embedder` takes your own. | | `rerankerFor` | The `Reranker` for the first reachable endpoint that names a `reranks` model, or nothing. `AppOptions.reranker` takes your own. | | `registerDecoder`, `knownDecoders`, `show` | Teach the framework to take apart media an endpoint cannot be sent (a `Decoder` answers a `Decoded`: stills and sound), list the decoders registered, and work out what a model is shown for a set of attachments (`Showing`). | | `ffmpegDecoder` | The decoder that ships, for video, over an `ffmpeg` binary the app names. Types: `FfmpegOptions`, `FfmpegRun`. | | `Uploads`, `registerUploader`, `knownUploaders`, `send`, `bearer` | The cache that uploads a large attachment once through an endpoint's files API, the registry of how each shape stores a file (`Uploader`), and the transport an uploader is written over. Types: `Endpoint`, `UploadSetting`, `Uploaded`, `Uploading`, `UploadsOptions`. | | `Batcher`, `Seat`, `registerBatch`, `knownBatches`, `requestOf`, `replyOf` | What hands many requests to an endpoint's batch API, the registry of how each shape takes a batch (`BatchDriver`), and the request and reply of one item. Types: `Asking`, `Batch`, `Batched`, `BatchItem`, `BatchOptions`, `BatchResult`. | | `LiveSession`, `registerSession`, `knownSessions`, `sessionFor`, `realtimeSession`, `liveSession` | A live session as `App.open` returns it, the registry of session protocols by name (`SessionOpener`), and the two that ship. `connect`, `Events`, `frameText` and `socketBase` are what an opener is written over. Types: `Session`, `SessionEvent`, `SessionInput`, `SessionAudio`, `SessionRequest`, `SessionFaculties`, `OpenOptions`, `WireSession`, `Line`, `Socket`, `SocketConstructor`. | | `amountOf`, `priceFor` | Arithmetic over the prices an endpoint declared: what some usage cost, and the price of one model. Types: `Cost`, `Price`. | | `composeHooks`, `SENT_BACK` | Several sets of hooks as one, and how many times `beforeStop` may send an agent back in one conversation. | | `computer`, `computerTool`, `browserScreen` | A screen as a function an agent calls, the tool underneath it, and the screen that ships: a browser. Types: `Screen`, `BrowserScreen`, `BrowserScreenOptions`, `ComputerOptions`, `Button`, `ScreenPoint`, `ScreenRegion`, `NativeTool`. | | `ToolTape` | `AskOptions.tape`: hears a request's tool calls, or answers them in place of the tools. | | `EXPLORATION` | The share of routing decisions worth randomising (2%) so the record can be read back. Set it as `explore` in `praecise.config.ts`; off unless you do. | Types: `ChatRequest`, `ChatResponse`, `Message`, `ToolCall`, `ToolSchema`, `Answer`, `AskOptions`, `Progress`, `Usage`, `Routing`, `Episode`, `Attachment`, `Stop`, `Embedder`, `Delegate`, `Kind`, `Reader`, `UiView`. An `Attachment` may carry `fileId` (the name an endpoint gave bytes uploaded to it) and `blob` (where the bytes are kept in the app's blob store). `Usage` reports `cost`, by currency, where the endpoints that answered declared `prices`, and `unpricedTokens` where some did not. `Answer` is generic in its `data`, and carries `ui` (the `UiView`s tools brought with their results). A `ModelProvider` may also declare `reranks`, `uploads`, `batch`, `realtime`, `computer` and `prices`. A `Message` of any role may carry `attachments`: what was sent with a question, or what a tool returned with its result. `ChatResponse.attachments` and `Answer.attachments` are what a model made that is not text. A model endpoint's `takes` says which of `image`, `audio`, `video`, `document` it can be sent. `McpCallOptions.media` is where an MCP tool result's images, audio and files are handed over. `Usage` reports `cacheWriteTokens` and `reasoningTokens` where an endpoint reported them. `ChatResponse.stop` is why a reply ended in one vocabulary on every wire (`end`, `tools`, `length`, `refusal`, `filter`, `paused`, `error`); `finishReason` keeps the endpoint's own word. `ChatResponse.replay` and `Message.replay` carry what an endpoint wants handed back with tool results (its reasoning), opaque to everything but the wire that wrote it. `ChatRequest` gains `levels`, `stable` (how much of the start of `system` is the same on every request) and `cache`. `ProviderError.retryAfter` is how long the endpoint asked to be left alone, in milliseconds. **`AskOptions`**, what `App.ask(agent, input, options)` and `Harness.ask` take: | Field | What it does | | --- | --- | | `task` | What the request is about when the input carries more than the question (grounding, retrieved passages). A self looks up its memory by it and records it as the work. Defaults to the input. | | `history` | Prior turns, oldest first, when the caller keeps its own. | | `thread` | The conversation this belongs to; naming one reads back what was said and adds what is said now. | | `signal` | Cancels the request. | | `onProgress` | Called with each `Progress` event as the work happens, which also lets the answer arrive in fragments where it can. | | `ceiling` | The most expensive rung (`Quality`) this request may reach. It trims the agent's declared ladder and never raises it, so the router still escalates below it. Where it would leave nothing, the cheapest declared rung is kept. | | `floor` | The cheapest rung this request may start on: for re-asking after a cheap answer was rejected, so that model is not asked again. It can only remove rungs the agent declared, never add one, and is clamped to the ceiling: a floor above the ceiling gets the ceiling, never an empty ladder. Where it would remove every remaining rung, the dearest one left is kept. | | `trace` | The trace this request is already part of, so its spans join it. | | `tainted` | Start the request already tainted: something untrusted was read before it began. | | `caller`, `surface`, `background` | Who the request is for (`caller.person`), where it comes from, and whether nobody is waiting on it. Read by selves. `caller` is an `AskCaller` and may carry anything else the app wants its guard, authority, functions and meter to see. | | `context` | Whatever else the app sends with the request. Never read by the framework, shown to a model, or written to a trace or a recording; handed on with `caller`. | | `allow` | `{ tools?, knows? }`: narrow what the agent may call and what stays in its instructions, for this request. It only takes away, and a name the agent does not have is an error. | | `maxCalls` | The most model calls the request may make, counting every one. Reaching it ends the request with `CallLimitReached`. Defaults to `limits.calls`. | | `steer` | Called before each step the agent takes; what it returns is put to the agent as further turns of the caller's. | | `tools` | `LocalTool`s that exist for this request only, beside the agent's own. | | `approve` | Asked when the authority says a call needs a person's approval; answers with a `VerifiedApproval` or the sentence the model should read. | | `tape` | A `ToolTape` that hears, or answers, this request's tool calls. | | `attachments` | Images and documents sent with the question: `{ mime, data? , url?, name? }`. They belong to this request and are not kept with a named conversation. | | `depth` | How many agents deep the request already is. Set by the runtime when one agent asks another. | **Provider wires.** An endpoint's `speaks` names a request shape, and each shape is a `ChatAdapter`: | Name | What it is | | --- | --- | | `chatWire`, `messagesWire`, `contentsWire`, `responsesWire`, `interactionsWire` | The shapes that ship. | | `adapterFor` | The adapter registered for a shape. | | `registerWire`, `knownWires` | Teach the framework a new shape (replacing a built-in is refused), and list what is registered. | A `chat` endpoint that ignores `stream: true` and answers with one buffered JSON completion is read as such: the stream is parsed only when the response is `text/event-stream`, and a streaming caller then receives the whole text at once. **Clocks on every wire.** A streamed answer is watched between frames — the clock starts again at every frame, so a long answer arriving steadily is never cut off (`PRAECISE_WIRE_IDLE_MS`, default 45000). One that arrives in one piece is watched as a whole (`PRAECISE_WIRE_TOTAL_MS`, default 240000). A timeout arrives as a `ProviderError` with status `0`, so the ladder crosses to the next model rather than asking the silent endpoint again, and a caller's own `signal` still cancels. On the `chat` wire a stream that stops after some text has arrived keeps that text, with `finishReason: "timeout"` and the reason in `notes`. ### Selves | Name | What it is | | --- | --- | | `self` on `agent()` | The self an agent is: a handle, or `{ handle, surface?, template?, record? }`; `{person}` in a handle makes a self per person. `record` decides what the self is sent after an answer. | | `selves` in `defineConfig` | Where selves live: `url`, `credential`, `adminCredential`, `ticketCredential`, `surface`, `required`, `timeoutMs`. | | `selvesOverHttp` | The provider for the HTTP self protocol. | | `SelfProvider` | The interface a provider satisfies: `context`, `record`, `outcome`. Pass one as `selves` in `AppOptions`. | | `signTicket`, `openTicket` | Bind a ticket to a person, and check that binding. | | `App.rate` | A verdict on an answer a self gave, with the ticket the answer carried, and optionally a mechanical `check`. | Types: `SelfDeclaration`, `SelfTemplate`, `SelfContext`, `SelfVerdict`, `SelfCheck`, `AnswerSelf`, `HttpSelvesOptions`, `RecordSelf`, `SelfWork`, `SelfRecording`. `AskOptions` gains `caller`, `surface` and `background`; `Answer` gains `self`; `Progress` gains `self`. `PROTOCOL_VERSION` is the MCP protocol revision this framework speaks. ### Services: MCP, OpenAPI and code mode | Name | What it is | | --- | --- | | `McpClient`, `mcpRequest`, `mcpHeaders` | A client for an MCP server, and the builders for a conforming request. | | `collectResources` | Read the resources an agent's services were told to attach, rendered as knowledge. | | `Unauthorized` | Thrown when a server will not answer without a token; it carries the challenge the OAuth flow starts from. | | `ApiClient` | An OpenAPI-described HTTP API presented with the same shape as an MCP client. | | `ToolSource` | What the harness needs from a service, whichever protocol it speaks. | | `operationsFrom`, `toolsFrom`, `requestFor`, `callOperation` | Read a document into operations, turn them into tool schemas, build the request for one (to inspect or approve before it leaves), and call it. | | `operationName`, `baseUrlOf`, `resolveRefs` | A stable tool name for an operation, a document's base URL (OpenAPI 3 and Swagger 2), and local `$ref` resolution. Remote refs are not fetched. | | `McpHost`, `Elicit`, `clientCapabilities` | `AppOptions.mcp`: `elicit.form` and `elicit.url` answer a server that asks a person for something mid-call, and `apps` says a front end renders the views tools bring. `clientCapabilities` is what is declared to a server as a result. Types: `FormElicitation`, `UrlElicitation`, `ElicitResult`, `ElicitedValue`. | | `InputRequired`, `elicitedFault` | What a call ends in when a server asks for input nothing can give, and what is wrong with an answer to a form. | | `McpSubscription`, `McpSubscriptionFilter`, `McpNotification` | A `subscriptions/listen` stream: what `watch: true` on a service holds open, and how a task's changes arrive. | | `collectSkills`, `serviceSkillTool`, `READ_SERVICE_SKILL` | The skills a service serves (`skills` on a service), and the `read_service_skill` tool an agent reads them with. Types: `McpSkill`, `McpSkillFile`, `OfferedSkill`. | | `uiOf`, `UI_MIME`, `McpToolUi`, `McpToolResult` | The interactive view a tool declares, the media type of its page (`text/html;profile=mcp-app`), and a tool result as a service returned it. | | `SKILLS_EXTENSION`, `UI_EXTENSION`, `CLIENT_CREDENTIALS_EXTENSION`, `ENTERPRISE_AUTH_EXTENSION` | The names of the MCP extensions spoken. | Types: `McpResource`, `McpResourceContents`, `McpPrompt`, `McpPromptResult`, `McpProgress`, `McpRequestOptions`, `McpCallOptions`, `McpCompletion`, `Operation`, `Where`, `CollectOptions`. #### Code mode `code: true` (or a `CodeModeSpec`) on an agent replaces its per-operation tools with one `code` tool. The agent's HTTP services are described to the model as a typed API — an MCP server as `tools..(args)`, an OpenAPI service as `tools..request({ method, path, query, body })` with its document in `spec.` — and the program runs in a Praecise Silo with the services bound in and their credentials kept outside it. A service launched as a local program stays an ordinary tool. | Name | What it is | | --- | --- | | `CODE_TOOL` | The name of that tool: `"code"`. | | `SiloExecutor` | The `code` tool's runner: one silo per agent, created on first use, kept for its `ttl`, created again once it expires. | | `bindingsFor` | Which services can be bound into a silo, and how (`Binding`). | | `typesFor`, `tsType` | The declarations the model reads, one namespace per bound service, and a TypeScript type for a JSON Schema. | | `codeTool` | The `code` tool's schema, with those declarations in its description. | `allow` narrows what a program may call, per service: tool names for an MCP server, `"METHOD /path"` patterns (with `*`) for an OpenAPI service. A service not named may be called for anything it offers. The silo enforces the rules and logs every call. The silo is addressed by `silo`, else `PRAECISE_SILO`, else its local socket; an `https://` address is reached with the token in `PRAECISE_SILO_TOKEN`. ## Storage, and extending it Using a store: | Name | What it does | | --- | --- | | `Stores` | Every store the app declared, opened on demand. | | `openStore` | Open one store from a URL. | | `Kept` | A store's write side, as handed to app code. | Writing a new backend: | Name | What it does | | --- | --- | | `memoryDriver` | The in-process driver. Useful as the reference implementation. | | `sqliteDriver` | The SQLite driver. Loads `node:sqlite` lazily, on first use. | | `postgresDriver` | The Postgres driver. | | `redisDriver`, `Resp`, `RespError`, `respOptionsFrom` | The Redis and Valkey driver (`redis://`, `rediss://`, `valkey://`, `valkeys://`), and the RESP client it is written over, reusable by a driver that speaks it. Types: `RespOptions`, `RespReply`. | | `fuse` | Several orders of the same rows made one by reciprocal rank, which is how `recall` joins what the words found to what the vector found. | | `SchemaError` | What `remember` throws when a store with a `schema` is given a record outside it; `issues` (`SchemaIssue`) name each row, path and message. | | `diskBlobs`, `memoryBlobs`, `detach`, `inline`, `sweepBlobs`, `addressOf`, `isBlobAddress`, `blobsIn` | Blobs: a `BlobStore` on disk or in memory, an attachment's bytes moved into one and put back, the sweep that removes what nothing names (`SweepOptions`, `Swept`), the address of some bytes (`sha256:` and the digest), the test for one, and every address a value mentions. Types: `BlobStore`, `BlobInfo`. | | `Values`, `Facts`, `Series` | What `store.values`, `store.facts` and `store.series` are: a value under a name with an optional lifetime, and `claim`, which keeps one only if the name is free (`Connection.add`, the one verb a driver must decide in a single step); how two things are related and when that was true, with a walk of up to three steps; and readings in order of time, with windows and aggregates. Each is written over a `Connection`'s existing operations, so every backend has all three. | | `conform` | Run the conformance suite against a driver you wrote. | | `conformanceReport` | The same, rendered for a human. | | `Wire` | The Postgres wire framing, reusable by a driver that speaks it. | | `wireOptionsFrom` | Turn a connection URL into wire options, including `sslmode` (`disable`, `prefer`, `require`, `verify-full`) and `max_protocol_version` (`3.0`, `3.2`, `latest`). | Types: `Driver`, `Store`, `Connection`, `ConnectOptions`, `Capabilities`, `Item`, `Keep`, `Found`, `Query`, `Window`, `Ranked`, `ResultSet`, `Promised`, `Conformance`, `StoresOptions`, `WireOptions`, `WireResult`, `Held`, `Asked`, `RecallQuery`, `Reranker`, `Meta`, `Extras`, `Faster`, `Walk`, `WalkStep`, `Bucket`, `Buckets`, `Entry`, `Namespace`, `Fact`, `FactOptions`, `FactQuery`, `Neighbour`, `Point`, `RangeOptions`, `Aggregate`. `Store.recall` takes text, a vector, or both (`Asked`), and `RecallQuery.rerank` set false leaves the store's reranker out of one question. `Capabilities.faster` lists what a backend does itself instead of leaving it to this process: `walk`, `buckets`, `ids`, `validity`. A driver only has to implement the capabilities it actually has; `conform` checks what it claims, not a fixed list. ### Which family a store actually gets `of` declares one of five families. What ships serves four — `sql`, `document`, `timeseries` and `vector` — over one table of text, json, a time and an optional vector. `graph` is not served by anything here and is **refused when the store is opened**, naming what is served. That refusal is the honest half of a declaration that used to be accepted and then quietly ignored. `Capabilities` carries three fields for reading the choice back: | Name | What it says | | --- | --- | | `serves` | The families this backend will answer for. Absent means the driver makes no claim, and a driver that makes none is held to none — a backend written before this existed is not refused for having no opinion. | | `vectorSearch` | `"index"` where the database orders by distance, `"scan"` where every vector is read and compared in this process. `vectors` still means *can it hold them*; this is what asking costs. | | `detail` | What was settled at connect, phrased as the thing to do about it. | `ConnectOptions` carries two more: `of`, so a driver can shape itself to what it is holding, and `extension`, a native extension path an operator named. The SQLite driver reads the second from `PRAECISE_SQLITE_EXTENSION` and loads nothing without it. ### Extensions, and what each costs | Extension | To install | What it buys | | --- | --- | --- | | pgvector | `CREATE EXTENSION vector` — one statement, no restart | A real `vector(n)` column, an HNSW index, and `<=>` doing the ordering. Needs `dimensions`. | | TimescaleDB | `shared_preload_libraries` plus **a restart** | A `timeseries` store becomes a hypertable in weekly chunks. Only `create_hypertable` is used — the Apache-2.0 subset. Compression, continuous aggregates, retention and the job scheduler are source-available and are not touched. | | sqlite-vec | A build on disk, named in `PRAECISE_SQLITE_EXTENSION` | vec0 answers nearest-vector queries over an unnarrowed window. Never loaded unless asked for. | | Apache AGE | `CREATE EXTENSION age`, plus `LOAD 'age'` and a `search_path` per session | Nothing here uses it. Reachable through `query()`. | Whatever is installed is reachable through `Store.query()` regardless — the author's door, not the agent's. An existing table is never migrated underneath an adopter: a `bytea` vector column keeps the in-process comparison and says so in `detail`. ## Dialect and latent transport Two halves of one idea: the framework ships the **mechanism**, and each app declares its own **vocabulary** on top. A vocabulary is a property of your domain, so hard-coding one here would make every app speak the same language whether or not it meant the same things. **The codec.** A versioned, field-typed wire format built from a table of message specs. | Name | What it is | | --- | --- | | `defineDialect` | Build a dialect from a version string and a table of message specs. | | `str`, `num`, `bool`, `list`, `fixed2` | Field codecs. `fixed2` fixes a number to two decimal places, so a value round-trips identically. | | `Dialect`, `MessageSpec`, `Field`, `FieldCodec` | The types involved. | **The transport.** An intermediate representation passed between steps without being rendered back to text. | Name | What it is | | --- | --- | | `latent` | Wrap a vector as a payload, with its source and dimensions. | | `isLatent` | Type guard for one. | | `latentRef` | Name a payload without carrying it. | | `createRefs` | A ref table, so a payload travels once and is referred to after. | | `latentChannel` | Move payloads between steps. | | `probe` | Read a named scalar off a payload. | | `LatentPayload`, `LatentRef`, `LatentChannel`, `Refs`, `Probe` | The types involved. | `probe` is not optional decoration. An opaque vector nobody can measure is not something to put in a pipeline; probes are what keep latent traffic auditable after the fact. ## Observability There is no telemetry dependency and no exporter. The framework produces the standard shape and the app wires the sink. **`AppOptions.tracer`** takes `(span: Span) => void` and is the one to use. `Span` is an OpenTelemetry span: `traceId`, `spanId`, `parentSpanId`, `startTime`, `endTime`, `status`, and attributes in the GenAI semantic convention (`gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `error.type`). Model calls and tool calls are instrumented, a call that threw still produces a span, and trace context crosses into MCP as `traceparent` so a tool server's work joins the same trace. **`AppOptions.emit` and `WorkflowDeps.emit`** take `(span: GenAiSpan) => void` and predate the above. `GenAiSpan` is a flat event — `operation`, `name`, `step`, `durationMs`, `at` — describing what a WORKFLOW did (`plan`, `invoke_agent`, `invoke_workflow`, `execute_tool`). It carries no trace ids, so nothing emitted through it can be joined to anything else. Both are live and they are bridged: when a `tracer` is wired, workflow events reach it as conformant spans keyed on the run, so a workflow and the model calls its steps made appear as one trace rather than two unrelated records of the same work. Prefer `tracer` in new code; `emit` remains for anything already using it. - `Tracer` is the type of `AppOptions.tracer`, and `GenAiOperation` the operations a span can name (`chat`, `execute_tool`, `embeddings`). `traced(...)` times one call and hands the span over, including when the call throws. - `TraceContext` is where in a trace a call sits; `traceparentOf` and `parseTraceparent` write and read a W3C `traceparent` header, `traceMeta` gives the `_meta` keys MCP reserves for it, and `newTraceId`/`newSpanId` mint ids. - `TraceLog` is a bounded in-memory collector — what `praecise dev` installs to render `/traces`. `laneOf(span, trace)` places a span in its trace's timeline; `Trace` is one trace assembled from its spans. - `COST_ATTRIBUTE` and `COST_CURRENCY_ATTRIBUTE` are the span attributes a priced call carries: `praecise.usage.cost` and `praecise.usage.cost.currency`. - `Ledger` records routing decisions and spend. - `provenanceOf(run)` answers what a run derived from what. - `followRun(runs, id, signal)` streams `RunEvent`s live. - `forkRun(id, spec, deps, { after, patch, by })` branches a run from a past step, optionally editing an earlier output. The original is untouched and every patch is recorded as a `patched` event naming who made it. --- ## Protocols Everything an app publishes is reachable four ways, from one declaration. - **MCP `2026-07-28`** — `handleMcp(app, message, caller)` serves it and `toolsOf(app, caller)` lists the tools that caller may see; `McpClient` consumes it. Stateless: every request carries its own version, capabilities and identity in `_meta`. `mcpRequest(method, params)` and `mcpHeaders(...)` build a conforming request, which is worth using rather than assembling by hand. - **A2A 1.0** — `agentCard(app, caller, baseUrl)` and `handleA2A(app, message, caller, tasks)`. `TaskStore` holds what `SendMessage` created so `GetTask` can find it. `streamsA2A(message)` says whether a request is one of the two that answer as a stream (`SendStreamingMessage`, `SubscribeToTask`), and `streamA2A(...)` yields its events. `A2A_VERSION` is the revision spoken (`"1.0"`, the form the header and the card use) and `AGENT_CARD_PATH` where the card is served. A caller that sends `A2A-Version: 0.3`, or uses a 0.3 method name, is answered in the 0.3 shapes. `restA2A(...)` serves the HTTP+JSON binding under the same address (`A2ARestRequest`, `A2ARestAnswer`), and `tasksOf` is the task store an app's A2A endpoint uses, made on first use. `A2AOptions.push` (`ServeOptions.a2a`) says which hosts a push notification may be sent to (`PushConfig`). Types: `Task`, `TaskState`, `TaskStatus`, `A2AMessage`, `Part`, `A2AVersion`, `TaskEvent`. - **Signed agent cards** — `signAgentCard`, `cardSignerFor`, `cardPayload` and `jcs` sign a card over its canonical JSON form; `verifyAgentCard(card, jwks)` checks one and `fetchAgentCard(address, { keys, trust, unsigned })` fetches a peer's and says whether it verified. Types: `AgentCardSignature`, `CardSigner`, `CardVerification`, `FetchAgentCardOptions`, `FetchedAgentCard`. - **MCP Tasks** — the server answers a workflow call from a client that declares `io.modelcontextprotocol/tasks` with a task, serves `tasks/get` and `tasks/cancel` (which stops the run), and sends `notifications/tasks` to a client that names the task in `subscriptions/listen`; `McpClient.call` follows a task it is handed to its end. `McpStream` is what a streamed MCP answer is. - **Skills over MCP** — `listSkills`, `getSkill`, `readSkillDirectory`, `readSkillFile` and `renderSkillFile` serve the app's authored skills (`skills/list`, `skills/get`, `skill://` resources). Type: `ServedSkill`. - **MCP Apps** — `ui` on a function, agent or workflow names a `ui://` resource to show beside its result; `handleView(...)` answers what a view asks of the service that brought it, which is what `POST /api/ui/` serves. `MCP_APPS_ACTIVITY` is the AG-UI activity type a view is sent as. - **A2UI 1.0** — `surfaceTool` (`SURFACE_TOOL`, `show_surface`) is the tool an agent sends a surface with; `validateA2ui` and `validateA2uiEvents` check an envelope and a renderer's events (`A2uiFault`); `rendererCatalogs` reads the catalogs a turn's renderer named; `a2uiTurn` reads what a turn carried from a renderer and `eventsText` puts its events into words for the agent. `A2UI_VERSION`, `A2UI_MEDIA_TYPE`, `A2UI_EXTENSION_URI` and `A2UI_ACTIVITY` are the constants. Types: `A2uiMessage`, `A2uiComponent`, `A2uiEvent`, `A2uiFunctionCall`, `A2uiFunctionResponse`. - **Agent Client Protocol** — `serveAcp({ app, agent })` serves one agent over stdio for an editor; `ACP_PROTOCOL_VERSION` is the version spoken. Types: `AcpOptions`, `AcpServer`. - **Responses API** — `handleResponses(...)` answers `POST /v1/responses` (`RESPONSES_PATH`), where `model` names an agent, and `responsesFrame` writes one stream event. Types: `ResponsesOptions`, `ResponsesAnswer`, `ResponsesError`, `ResponseResource`, `ResponseItem`, `ResponseEvent`. - **AsyncAPI** — `asyncApi(app, caller, baseUrl)` describes the events the app receives and sends, served at `ASYNCAPI_PATH` (`ASYNCAPI_VERSION`). - **Catalogue listings** — `listingOf` works out what a published capability says about itself (`Listing`) from an agent's `meta`, and `META_KEY` is the `_meta` key it is carried under on an MCP tool. - **Discovery** — `mcpServerCard(...)` at `MCP_SERVER_CARD_PATH` and `aiCatalog(...)` at `AI_CATALOG_PATH` (`AI_CATALOG_VERSION` marks the catalog's shape as provisional: the standard it follows is a draft). - **Web Bot Auth** — `signingFetch(fetch, signer)` signs every request per RFC 9421 with the `web-bot-auth` tag (`WEB_BOT_AUTH_TAG`); `keyDirectory(keys)` is the body served at `KEY_DIRECTORY_PATH` (`KEY_DIRECTORY_TYPE`); `verifySignature(request, jwks)` checks one; `thumbprint(jwk)` and `signatureBase(...)` are the pieces. `AppOptions.botAuth` applies it to the app's outbound requests. Types: `BotSigner`, `Ed25519PublicJwk`, `SignatureParams`, `SignedRequest`, `Verification`. - **Run notifications and webhooks** — `AppOptions.notify` (`Notify`) is told what runs do as CloudEvents (`RUN_EVENT_TYPES`, `runEvent`, `RunNotice`, `RunEventType`, `RunTransition`). `signWebhook`, `verifyWebhook` and `deliverWebhook` implement Standard Webhooks (`WebhookTarget`, `WebhookDelivery`, `DeliverWebhookOptions`). - **AG-UI interrupts** — `interruptOf`, `answerInterrupts`, `followWork`, `AguiInterrupt`, `AguiResume`: a workflow stream that stops at a gate ends with an interrupt outcome and is resumed through the existing approval path. - **AG-UI** — `AguiStream` translates praecise's `Progress` events into AG-UI's, keeping message boundaries. `modesFrom(...)` reads a `?stream=` selector, `modeOf(event)` says which `StreamMode` an event belongs to, `ALL_MODES` lists them, and `sseFrame(event)` writes one `AguiEvent` (of an `AguiType`) as an SSE frame. - **OAuth 2.1** — `OAuthClient` for servers that are protected resources, plus `parseChallenge`, `canonicalResource`, `metadataUrls`, `stepUpScopes`, `challengeFor` (the S256 PKCE challenge), `randomString`, and `expiryOf`/`expired` for deciding when to refresh. `OAuthOptions.clientMetadataUrl` names a Client ID Metadata Document to use as the client id where the authorization server supports one, and `clientMetadataDocument(...)` builds that document. `authorizerFor` turns a `MachineGrant` (client credentials, or an identity assertion exchanged at an identity provider) into a function that finds a token, and `clientAssertion` signs the assertion a key-holding client presents. Types: `OAuthOptions`, `Challenge`, `Tokens`, `ClientRegistration`, `MachineGrant`, `PendingAuthorization`, `DiscoveryResult`, `ProtectedResourceMetadata`, `AuthorizationServerMetadata`, `ClientMetadataDocument`. `llmsTxt(app, caller, baseUrl)` (served at `LLMS_TXT_PATH`), `jsonLd(...)`, `jsonLdScript(...)` (the same, ready for a page's ``) and `robotsTxt(...)` are the discovery documents; `ask(app, request, caller, policy)` answers a natural-language question from the app's own store, and `compact(results, budget)` is the layer between a database and a prompt — supersede, deduplicate, fit, and reorder for where a model actually reads. Around them: `fromStore` reads store rows as schema.org objects, `rank` and `termsOf` rank what the app publishes against a question, `edgeFirst` puts the best matches where a model reads, and `qualityFor` and `modeFor` cap what was asked for at what the `AskPolicy` allows. Types: `AskAnswer`, `AskMode`, `AskPolicy`, `AskResult`, `Compacted`. --- ## Ingestion `ingestInto(dir, store, options)` reads a folder of documents into a store. `chunk(text, size, overlap)` splits at the document's own paragraph boundaries, `chunkId(source, text)` derives a stable id so re-running does not duplicate, and `readFields(said, fields)` reads a model's extraction or refuses it, from the prompt `extractionPrompt(text, fields)` builds. `ingestible(dir)` lists the files the pipeline can read. `canConvert`, `isTextFormat` and `ingestFile` (with `Converted` and `Converter`) are the conversion layer underneath. Types: `IngestPipelineOptions`, `IngestReport`. --- ## Structured results A declared `returns` is fields and hints, a JSON Schema, or a Standard Schema validator. - `returnsKind(returns)` says which (`ReturnsKind`); `isJsonSchema` and `isStandardSchema` are the tests. - `validateJson(schema, value)` checks a value against a JSON Schema and answers with what is wrong. `CHECKED_KEYWORDS` are the keywords it checks, `UNCHECKED_KEYWORDS` the ones it does not, and `uncheckedIn(schema)` the unchecked ones a schema uses. - `ShapeError` is what a request ends in when the strongest model's answer is still outside the shape; it carries `issues` and the `text`. - Types: `StandardSchemaV1`, `StandardResult`, `StandardIssue`, `StandardOutput`, `DataOf`. --- ## `@praecise/harness/formats` Readers for robotics, scene and array data, as a plugin. Public, and covered by the same promise as the root. | Name | What it is | | --- | --- | | `formats` | The plugin: `plugins: [formats()]`. `formats({ only })` and `formats({ except })` choose among the formats (`FormatsOptions`). | | `registerFormats` | Register the same readers without a plugin. | | `describeAttachment` | The rendering of one attachment, or nothing where no format here reads it. | | `formatNames`, `FormatName` | The names `only` and `except` take. | | `mcap`, `rosbag`, `rosbag2`, `lerobot`, `parquet`, `arrow`, `pcd`, `ply`, `splat`, `splatPly`, `usd`, `npy` | Each format on its own (`Format`). | ## `@praecise/harness/testing` A model that says what a test tells it to. Public, and covered by the same promise as the root. | Name | What it is | | --- | --- | | `scriptedModel` | A model endpoint that answers from a list of replies. `models` goes in the config, `requests` is every request the app made, `push` adds replies, and `remaining` counts what is left. Types: `ScriptedModel`, `ScriptedModelOptions`, `Scripted`, `ScriptedReply`, `ScriptedCall`, `ScriptedRequest`. | | `scriptedEndpoint` | The same one level down: a `fetch` that answers with the bodies it is given. Types: `ScriptedEndpoint`, `EndpointReply`. | | `systemText` | The instructions of a request, as text. | --- ## `@praecise/harness/internal` Unstable. Unversioned. May change or vanish in any release, patch releases included. Documented here only so you know what it holds and why you should not reach for it: - **Loading** — `loadProject`, `resolveKnows`, `findCycle`, `Importer`, `LoadOptions` - **Ingest** — `converterFor`, `ConvertRequest`, `IngestOptions`, `ConverterOptions` - **Compiling** — `planProject`, `planAgent`, `planWorkflowAgent`, `schemaFor`, `PlanOptions` - **Harness internals** — `stateDirFor`, `stream`, `trim` - **Store internals** — `urlFor`, `asObjects` - **Workflow internals** — `checkSteps`, `provisioner`, `runCommand`, `splitCommand`, `Manifest`, `ProvisionerDeps` - **Server internals** — `callPublished`, `promptsOf`, `resourcesOf`, `groupsOf`, `noticesOf`, `openChannel`, `Caller`, `McpTool`, `Channel` - **Packaging** — `buildPackage`, `manifestFor`, `apiModule`, `apiTypes`, `faultsIn`, `hintsIn`, `PackageManifest`, `PackageOptions`, `PackageResult`, `Describable` - **CLI** — `cli`. The supported way to run this is the `praecise` binary. `adapterFor`, `chatWire`, `contentsWire`, `messagesWire`, `handleMcp`, `toolsOf`, `canConvert`, `ingestFile`, `Converted` and `Converter` are also reachable here, and are public: they are exported from the root and documented above. --- # Capabilities Everything the framework does, where it lives, and what it deliberately does not do. Each row is either `built` or `declined`; a declined row gives the reason. When a provider changes a request shape or a protocol publishes a revision, the row that names it is the row to re-check. ## How anything is added A capability goes in through a seam that already exists. If there is no seam for it, the seam is the thing to build first. | Seam | What goes through it | | --- | --- | | `ChatAdapter` + `registerWire` | A request shape. One file per shape; shared transport in `wire/http.ts`. | | `registerSession`, `registerUploader`, `registerBatch` | A live-session protocol, a files API and a batch API, each beside the wire it belongs to. | | `LocalTool` | Anything a model can call: your functions, and every tool the runtime itself contributes (`harness/faculties.ts`). The loop has no branch per capability. | | `Attachment` + `registerReader` + `registerDecoder` | Anything sent or returned that is not text. The endpoint reads it, a reader renders it, a decoder takes it apart, or a note says it was left out. | | `Harness` | The whole runtime. Replace it, or stand a test double in for it. | | `Driver` + `conform` | A storage backend. Values, facts and series are verbs over a driver's existing operations, so a new backend has them without implementing them; a driver may declare faster paths, each held to the same answer. | | `Embedder`, `Reranker`, `BlobStore` | Text to vectors, a second opinion on what was found, and where large bytes are kept. | | `Source`, `CloudEvent`, `notify` | Events in (pulled and pushed) and out. | | `guard`, `Authority`, `hooks`, `meter`, `middleware` | A check before a call, policy, the moments after a tool call and before stopping or summarising, a say before every model call, and a wrap around a request. | | `Plugin` | A package's piece of an app: agents, functions, tools, skills, drivers, blobs, hooks, commands, and a `setup` for registering wires and readers. | | `SelfProvider`, `payer`, `botAuth`, `sandbox`, `tracer`, `Screen` | Identity and memory of a self, payment, request signing, isolation, telemetry, and a screen for computer use. | | Folder kinds (`agents/`, `workflows/`, `functions/`, `tools/`, `stores/`, `memory/`, `skills/`, `evals/`) | What an app is made of. The same kinds are accepted in code by `createApp` and from a plugin. | The framework ships no model ids, no base URLs and no prices. Provider coverage means every shape a provider speaks is spoken correctly, not that a provider is named. ## 1. Model providers and wires | # | Capability | Status | Where | | --- | --- | --- | --- | | 1.1 | Five request shapes: `chat`, `messages`, `responses`, `contents`, `interactions`; more by `registerWire` | built | `harness/wire/` | | 1.2 | Per-endpoint credential header, extra headers, extra body fields | built | `define.ts` `Provider` | | 1.3 | Constrained decoding from a schema on every wire that has it | built | each wire | | 1.4 | No sampling parameters sent to endpoints that reject them | built | each wire | | 1.5 | Idle and total clocks on every wire, composed with the caller's signal | built | `wire/http.ts` | | 1.6 | `retry-after` honoured; spend-limit 429s not retried | built | `wire/http.ts`, `builtin.ts` | | 1.7 | Reasoning handed back across tool turns: thinking blocks, encrypted reasoning items, `reasoning_content`/`reasoning`, thought steps, thought signatures | built | each wire, `Message.replay` | | 1.8 | One vocabulary for why a reply ended; refusal and filter recognised on every wire; truncation reported | built | `stopOf`, `ChatResponse.stop` | | 1.9 | Prompt caching where the endpoint must be told: stable system prefix and conversation breakpoint | built | `wire/messages.ts`, `ChatRequest.stable` | | 1.10 | Cache reads and writes counted as input on every wire; cache-write and reasoning tokens reported | built | `Usage` | | 1.11 | Depth words above `high` (`xhigh`, `max`), declared per endpoint | built | `ModelProvider.levels` | | 1.12 | Output room declared per endpoint; thinking requests not starved by a small default | built | `ModelProvider.output` | | 1.13 | Embeddings and reranking endpoints | built | `harness/embed.ts`, `harness/rerank.ts`, `ModelProvider.embeds` / `reranks` | | 1.14 | Live sessions over a WebSocket: text and audio in and out, tool calls through the guard, interruption. Openers for the realtime protocol of `responses`/`chat` and the live protocol of `contents`/`interactions` | built | `wire/session.ts`, `wire/realtime.ts`, `wire/live.ts`, `App.open`. One endpoint per session, no failover or reconnect; no WebRTC; no opener for `messages`, which publishes no such protocol. | | 1.15 | Large attachments uploaded once through the endpoint's files API and named after | built | `wire/files.ts`, `ModelProvider.uploads`. The cache is per process. | | 1.16 | Batch APIs: many questions handed over together, tools run between batches | built | `wire/batch.ts`, `App.askMany`. No driver for `interactions`, whose batch API does not take it. | | 1.17 | Server-side tools (provider web search, code execution), provider-hosted MCP connectors | declined | The app's tools go through `guard.ts` and the authority; a tool that runs on the provider's side does not. Reachable through `body` on an endpoint for an app that wants one. | | 1.18 | Server-held conversations (`previous_response_id`, `thread`, `previous_interaction_id`) | declined | The framework keeps the transcript it replays (`store: false` is sent on purpose); a second copy on the provider is retention nobody asked for. | | 1.19 | Provider-side context editing and compaction | declined | Done in the runtime (tool-result clearing and compaction, in the agent loop) so it works the same on every wire. | ## 2. Modalities and data types | # | Capability | Status | Where | | --- | --- | --- | --- | | 2.1 | One content model: an attachment is a media type and bytes, a URL, an uploaded file's name or a blob address, on a question and on a tool result | built | `Attachment`, `Message.attachments` | | 2.2 | Images and PDFs on every wire | built | each wire | | 2.3 | Audio and video where the shape has a place: `contents`, `interactions`, and `chat` when the endpoint's `takes` says so | built | `ModelProvider.takes`, `harness/modality.ts` | | 2.4 | Explicit degradation: what an endpoint cannot be sent is rendered or named in `answer.notes`, never dropped silently | built | `present`, `show` | | 2.5 | Time series and sensor data: SenML (RFC 8428) rendered per channel with statistics and a downsample | built | reader in `modality.ts` | | 2.6 | Robot state, action chunks, latents: tensors in the Open Inference Protocol JSON form | built | reader in `modality.ts` | | 2.7 | Tables (CSV, TSV), scenes (glTF), text, JSON, XML, YAML | built | readers in `modality.ts` | | 2.8 | Media in tool results on every wire: `attach()` from a function; MCP image, audio, embedded resource, resource link | built | `runTool`, `mediaIn`, each wire | | 2.9 | Media out: images and audio a model returns, on `answer.attachments` | built | `contents`, `interactions`, `chat` | | 2.10 | New kinds of data by registration, from an app or a plugin | built | `registerReader` | | 2.11 | Documents into a store: PDF, Word, Excel, PowerPoint, CSV, images, source | built | `src/ingest/` | | 2.12 | Dense latent payloads between steps, with probes | built | `transport.ts` | | 2.13 | Recordings, tables, point clouds and scenes described to a model: MCAP, ROS 1 bags, LeRobot dataset metadata, Parquet, Arrow IPC, PCD, PLY, Gaussian splats, USD, NumPy | built | `@praecise/harness/formats`, a plugin that is off until listed. Structure, sizes, time range, topics or columns and a bounded sample; every rendering ends by naming what it did not read. | | 2.14 | Video an endpoint cannot take, taken apart into stills and a transcript | built | `registerDecoder`, `ffmpegDecoder` over a binary the app names. With no decoder registered the video is named in a note. | | 2.15 | Forecasting, vision-language-action and world models as callable models | declined as wires | They take and return tensors and media, not conversations. They are tools (an MCP service or a function) whose inputs and outputs are attachments; tensors read as attachments and media in tool results are what makes that work. | | 2.16 | A dialect codec: an app's own compact message notation with a lossless expansion; a mismatched version, an unknown tag or a duplicate tag is refused on decode | built | `codec.ts` `defineDialect`. The vocabulary is the app's; none ships. | ## 3. The agent loop | # | Capability | Status | Where | | --- | --- | --- | --- | | 3.1 | Tool loop with guard and authority on every call, refusal returned to the model as the result | built | `builtin.ts` | | 3.2 | Turn limit per agent (default 16); model-call limit per request | built | `AgentSpec.turns`, `AskOptions.maxCalls`, `Limits.calls` | | 3.3 | Tool-result clearing when the transcript passes half the room, keeping the calls | built | `harness/context.ts` | | 3.4 | Compaction: the model writes notes on the earlier work; the question is never rewritten | built | `harness/context.ts` | | 3.5 | Long results kept whole and read by line or search | built | `Shelf`, `read_result` | | 3.6 | Read-only calls in one turn run together | built | `builtin.ts` | | 3.7 | Tool search: `find_tools` / `use_tool` when a list is too long; the guard sees the real tool | built | `harness/faculties.ts` | | 3.8 | Code mode: one `code` tool over the agent's services, run in a microVM | built | `harness/codemode.ts` | | 3.9 | Knowledge that overflows is outlined and read through a tool | built | `compile/outline.ts` | | 3.10 | Authored skills (SKILL.md) with progressive disclosure | built | `project/skills.ts`, `compile/skills.ts` | | 3.11 | Structured output: `returns` as fields and hints, a JSON Schema or a Standard Schema; the answer is checked, and one that fails sends the router up a rung | built | `schema.ts`, `AgentSpec.returns`, `AgentSpec.read`, `ShapeError` | | 3.12 | Streaming that never takes back what it showed | built | `Progress` | | 3.13 | Cancellation reaches tools as well as models | built | `runTool` | | 3.14 | Hooks after a tool call (rewrite or withhold), before stopping (send back, bounded), before compaction (forbid or supply), and before a self is told (shorten or drop) | built | `harness/hooks.ts`, `hooks.ts` in a project, `Plugin.hooks` | | 3.15 | A request carries who it is for and an app-defined context to the guard, the authority, functions and the meter, and never to a model | built | `AskOptions.caller`, `AskOptions.context`, `Attempt` | | 3.16 | A request narrows an agent's tools and knowledge, and can only remove | built | `AskOptions.allow` | | 3.17 | A request lends an agent tools of its own, and answers an approval mid-turn | built | `AskOptions.tools`, `AskOptions.approve` | | 3.18 | Computer use: an action vocabulary over a `Screen`, screenshots as tool-result images, a browser driver over the DevTools Protocol, the endpoint's own tool type where it declares one | built | `harness/computer.ts`, `harness/browser.ts`, `ModelProvider.computer` | | 3.19 | Built-in file and shell tools | declined | An app's tools are MCP services, functions or code mode. A framework that ships a shell ships a default nobody audited. | ## 4. Orchestration and long-running work | # | Capability | Status | Where | | --- | --- | --- | --- | | 4.1 | Workflows: sequence, graph (`after`), `each`, `when`, `repeat`, `plan`, `approve`, `wait` | built | `workflow/run.ts` | | 4.2 | Durable runs: journal, resume at a gate, recover after a crash, fork with a patch, idempotency keys | built | `workflow/` | | 4.3 | Signed approvals with quorum | built | `workflow/verify.ts` | | 4.4 | Sub-agents with isolated context, as tools; bounded depth; usage and taint carried up | built | `delegateTool`, `AgentPlan.delegates` | | 4.5 | Background sub-agents: started without waiting, checked, steered, cancelled, collected | built | `Crew`, `AgentSpec.background`, `AskOptions.steer` | | 4.6 | Work that outlives a connection, over MCP: the Tasks extension, server and client, with pushed task state | built | `server/mcp-tasks.ts`, `harness/mcp.ts` | | 4.7 | Work that outlives a connection, over A2A: tasks, streaming, subscription, push notifications | built | `server/a2a.ts` | | 4.8 | Cancelling a run that is under way: the call in flight is aborted and the run ends as `cancelled` | built | `App.cancelWorkflow`, `POST /api/runs//cancel`, MCP `tasks/cancel`, A2A `CancelTask` | | 4.9 | A workflow step that waits for an outside event, continued once, with a timeout | built | `WaitStep`, `App.signal`. The timeout fires while a process holds the app; exactly-once holds within one process. | | 4.10 | Scheduled runs: a clock is a source, by interval or cron expression, with a stated catch-up rule | built | `schedule.ts` `clock` | | 4.11 | One agent replaced, added or removed in a running app; requests under way finish on the plan they started with | built | `App.replace`, `App.add`, `App.remove` | ## 5. Events | # | Capability | Status | Where | | --- | --- | --- | --- | | 5.1 | Pulled: a `Source` with a stored cursor, at-least-once, one run per event | built | `sources.ts`, `App.follow` | | 5.2 | Pushed: CloudEvents 1.0 over HTTP (structured, batched, binary), one run per `source` + `id` | built | `events.ts`, `POST /api/events/`, `App.deliver` | | 5.3 | Told: run lifecycle as CloudEvents to a function or a signed webhook (Standard Webhooks), retried, never failing the run | built | `notify.ts`, `webhooks.ts` | | 5.4 | Run and answer streams over SSE; AG-UI | built | `server/events.ts`, `server/agui.ts` | | 5.5 | A bus inside the app: a workflow subscribes to event types, a function or step publishes, a retried step republishes the same event | built | `WorkflowSpec.on`, `App.publish`, `POST /api/events`. In process, exact types only. | | 5.6 | An AsyncAPI description of what the app receives and sends | built | `server/asyncapi.ts`, `GET /asyncapi.json` | ## 6. The model ladder and deciding | # | Capability | Status | Where | | --- | --- | --- | --- | | 6.1 | Per-request routing from the shape of the request; cost/balanced/quality preference | built | `harness/routing.ts` | | 6.2 | Self-consistency check near the edge of a rung; depth before another model | built | `builtin.ts` | | 6.3 | Ladder across endpoints; transient failure retried in place, dead endpoint crossed | built | `compile/models.ts`, `builtin.ts` | | 6.4 | Per-request `ceiling` and `floor` | built | `AskOptions` | | 6.5 | Routing ledger with propensities and optional exploration | built | `Ledger` | | 6.6 | Advisor: the strongest rung consulted while a cheaper one works | built | `consultTool`, `AgentSpec.advisor` | | 6.7 | Budgets counted across planning and judging; concurrency bounded per run | built | `Limits` | | 6.8 | Cost in money from prices the endpoint declares; a spending cap on a run; nothing priced that was not declared | built | `harness/cost.ts`, `ModelProvider.prices`, `Limits.spend` | | 6.9 | A meter asked before every model call the runtime makes, and told what each took | built | `harness/meter.ts`, `AppOptions.meter`. Live sessions and embeddings are not metered. | | 6.10 | An app with no model endpoint answers with a placeholder, or refuses under `strict`; one whose configured endpoints cannot be reached always refuses | built | `AppConfig.strict`, `PRAECISE_STRICT`, `harness/index.ts` | | 6.11 | A ceiling on asks in flight at once, and on the length of one input | built | `AppOptions.askConcurrency`, `AppOptions.maxInput` | ## 7. Memory and data There is no ORM, and that is a decision. What makes an agent's data access safe is the role its connection holds and bound parameters, not a type mapping. The framework offers verbs (namespaced key-value, relationships with the time they were true, time series, text and vector recall) and SQL, or the backend's own commands, as the door an author opens on purpose. | # | Capability | Status | Where | | --- | --- | --- | --- | | 7.1 | Text: `remember`, `recall` (relevance decayed by recency), `search`, `history`, `forget`, `redact` | built | `stores/store.ts` | | 7.2 | Vectors: pgvector HNSW, sqlite-vec or Redis vector sets where installed, compared in process where not, and said which | built | `stores/` | | 7.3 | Recall by words and by meaning at once, fused by rank, with an optional reranker | built | `fuse`, `Reranker` | | 7.4 | SQL as the author's own door, bound parameters only | built | `Store.query`, `stores/wire.ts` | | 7.5 | Key-value: namespaced `put`/`get`/`delete`/`list` with a lifetime, and `claim`, which keeps a value only if the name is free and tells exactly one of several callers yes | built | `stores/models.ts` `Values`, `Connection.add` | | 7.6 | Relationships: bi-temporal facts, closed never deleted, `asOf`, a walk to three steps | built | `stores/models.ts` `Facts` | | 7.7 | Time series: `append`, `range` with windows and aggregates, `last` | built | `stores/models.ts` `Series` | | 7.8 | Walks and series buckets answered by the database where it can: recursive SQL, grouped aggregates, `time_bucket` where TimescaleDB is present | built | `stores/paths.ts`, `Capabilities.faster` | | 7.9 | Typed records: a Standard Schema on a store, checked on the way in, typed on the way out | built | `StoreSpec.schema`, `SchemaError` | | 7.10 | Blobs: bytes kept once under their SHA-256, on disk by default, carried by address from a row or an attachment; swept only when asked | built | `blobs.ts`, `App.blobs`, `Plugin.blobs` | | 7.11 | Conversations by name; a record of exchanges; working notes the agent writes; subject pages, one writer each; facts and procedures carried only once a person accepts them; selves | built | `harness/threads.ts`, `memory.ts`, `recollect.ts`, `pages.ts`, `consolidate.ts`, `shelf.ts`, `selves.ts` | | 7.12 | Conversations and memory sealed at rest with a cipher; conversations kept in a backend the app supplies; all of an agent's memory (record, working notes, pages, what it carries) kept in a declared store, by the agent's choice or the app's default, on every backend | built | `AppOptions.threads`, `AppOptions.memory`, `MemorySpec.store`, `AppConfig.store`, `harness/keeping.ts`, `harness/shelf.ts` | | 7.13 | Backends: memory, a file (SQLite), PostgreSQL over its own wire client, Redis and Valkey over their own; anything else a `Driver`, graded by `conform` | built | `stores/` | | 7.14 | PostgreSQL 18: `uuidv7()` ids, a `WITHOUT OVERLAPS` key on a fact's validity where `btree_gist` is installed, protocol 3.2 on request | built | `stores/postgres.ts`, `stores/wire.ts`. Detected; older servers fall back and say so. | | 7.15 | A graph engine as a store family (`of: "graph"`) | declined | Refused rather than pretended at. Relationships are bi-temporal facts on any store; a graph query language is a backend an app brings. | | 7.16 | Memory tools for the agent: search and read what it has kept, write a working note. What it is told on every request still changes only when a person accepts a proposal. | built | `harness/recollect.ts` | | 7.17 | Reading the record back, by hand or on a schedule: proposes changes to what is carried, checks what is carried against the record, files what is new onto pages | built | `App.reflect`, `App.tend`, `MemorySpec.reflect` | | 7.18 | Where everything kept came from (`user`, `tool`, `agent`, `external`), set by the runtime, carried through every derivation at the lowest of its sources, and deciding which of two entries stands | built | `harness/memory.ts`, `settle` | | 7.19 | Recall by words in any script | built | `termsOf` | | 7.20 | Documents with revisions for pages and what is carried: a write names the revision it read and is refused if the document moved on, between processes and between machines; one reading of a record at a time per agent, by lease | built | `harness/shelf.ts`, `AlreadyReflecting` | ## 8. Safety | # | Capability | Status | Where | | --- | --- | --- | --- | | 8.1 | `guard.ts`, `authority`, `access`/`effect` on everything published | built | `define.ts`, `authority.ts` | | 8.2 | Taint: untrusted output marks every later action; carried across a delegated agent | built | `Answer.tainted`, `builtin.ts` | | 8.3 | Credentials outside the sandbox in code mode; allow rules enforced by the silo | built | `harness/codemode.ts` | | 8.4 | Sealed, hash-chained, optionally signed journal | built | `journal.ts` | | 8.5 | Dev server: token, loopback default, origin and host allowlists | built | `server/` | | 8.6 | Attachment and resource-link URLs limited to `https:` and `data:`; webhook addresses refused when they resolve into a private network | built | `attachmentsIn`, `mediaIn`, `outbound.ts` | | 8.7 | Outbound requests signed so a server can tell which agent is calling (Web Bot Auth, RFC 9421) | built | `botauth.ts`, `AppOptions.botAuth` | | 8.8 | A gate is never approved by a peer's message (MCP task update, A2A message) | built | `server/mcp-tasks.ts`, `server/a2a.ts` | | 8.9 | A permission classifier: an authority that puts each tool call to a model against the app's policy, and fails closed | built | `classifier.ts` `permissionClassifier` | ## 9. Evals and observability | # | Capability | Status | Where | | --- | --- | --- | --- | | 9.1 | OpenTelemetry GenAI spans, trace context in and out | built | `harness/trace.ts` | | 9.2 | Attribute names per the current registry (`cache_read`, `cache_write`, `reasoning`) | built | `builtin.ts` | | 9.3 | Eval suites with code and model graders, repeated trials, `pass@k`/`pass^k`, CI exit code | built | `src/eval/`, `praecise eval` | | 9.4 | Provenance graph of a run | built | `workflow/provenance.ts` | | 9.5 | Eval cases captured from recorded exchanges and replayed against the tool results they met | built | `eval/replay.ts`, `praecise capture`. A workflow case is compared to its recorded result; its steps run again. | | 9.6 | A sample of live answers scored after they are returned, reported on the trace and through `notify` | built | `eval/online.ts`, `EvaluationSpec.online` | | 9.7 | A scripted model for an app's own tests, with no network | built | `@praecise/harness/testing` | | 9.8 | Spans collected in memory by the dev server and shown as a timeline per request | built | `server/traces.ts`, `GET /traces`, `GET /api/traces` | | 9.9 | A check of the app that says what will stop it, what degrades it and what is worth knowing, with an exit code | built | `praecise doctor` | | 9.10 | One suite run without memory and with it, cases in order on a memory that starts empty and is removed afterwards, and the difference | built | `App.evaluateMemory`, `praecise eval --memory` | ## 10. Protocols Versions are the latest published as of 2026-11-13. | # | Protocol | Version | Status | Where | | --- | --- | --- | --- | --- | | 10.1 | MCP, client and server: stateless, `server/discover`, `Mcp-Method`/`Mcp-Name`, `resultType`, `ttlMs`/`cacheScope` | 2026-07-28 | built | `harness/mcp.ts`, `server/mcp.ts` | | 10.2 | MCP Tasks extension, with task state pushed over `subscriptions/listen` | 2026-07-28 | built | `server/mcp-tasks.ts`, `harness/mcp.ts` | | 10.3 | MCP OAuth: PKCE, resource indicators, issuer validation, step-up; Client ID Metadata Documents with dynamic registration as fallback; client credentials; enterprise-managed authorization (identity assertion grant) | 2026-07-28 extensions | built | `harness/oauth.ts`. The identity assertion grant follows an IETF draft and serves one identity per service. | | 10.4 | MCP elicitation, form and URL, answered by a handler the app supplies | 2026-07-28 | built | `AppOptions.mcp.elicit` | | 10.5 | MCP tool lists re-read when a server says they changed | 2026-07-28 | built | `ToolSpec.watch` | | 10.6 | Skills over MCP: an app serves its `skills/`, and reads a server's against its manifest | beta | built | `server/mcp-skills.ts`, `harness/mcp-skills.ts` | | 10.7 | MCP Apps: a tool declares a view; as a host, views reach the front end and their calls go through the guard | 2026-01-26 | built | `server/mcp-apps.ts`. The sandboxed frame and the messages into it are the front end's. | | 10.8 | MCP Server Card; AI Catalog | card beta, catalog draft | built | `server/discovery.ts`. The catalog's shape is provisional. | | 10.9 | MCP roots, sampling and logging | deprecated in 2026-07-28 | declined | Not declared, so a conforming server does not ask. | | 10.10 | MCP servers on earlier revisions | | declined | Stated in `harness/mcp.ts`. | | 10.11 | A2A: JSON-RPC and HTTP+JSON bindings, streaming, `ListTasks`, input-required at a gate, push notifications, signed agent cards and their verification; 0.3 callers answered in 0.3 | 1.0.1 | built | `server/a2a.ts`, `server/a2a-card.ts` | | 10.12 | A2A over gRPC | 1.0.1 | declined | Needs a second listener with TLS and a protobuf codec for the whole message set. Not listed on the card, so no client dials it. | | 10.13 | AG-UI event names and fields; one terminal event per run; interrupts and resume for workflows | 1.0 | built | `server/agui.ts` | | 10.14 | A2UI: an agent answers with an interface, validated and carried over A2A and AG-UI; what the person does comes back as input | 1.0 | built | `server/a2ui.ts`. No renderer; drawing is the front end's. | | 10.15 | Agent Client Protocol: an agent served to an editor over stdin and stdout | protocol 1 | built | `server/acp.ts`, `praecise acp` | | 10.16 | A Responses-compatible ingress: any Responses client calls an agent | 2026-04-24 | built | `server/responses.ts`, `POST /v1/responses` | | 10.17 | CloudEvents; Standard Webhooks; AsyncAPI | 1.0.2; 1.0; 3.1.0 | built | `events.ts`, `webhooks.ts`, `server/asyncapi.ts` | | 10.18 | Web Bot Auth | draft-01 | built | `botauth.ts` | | 10.19 | Agent Skills (SKILL.md), and the skills discovery index | index 0.2.0 | built | `project/skills.ts`, `registry/` | | 10.20 | Payment on 402 through a `payer`, idempotent per step | x402 v2 | built | `payments.ts` | | 10.21 | `llms.txt`, `ai.json`, agent card discovery, with an agent's own catalogue metadata | | built | `server/discovery.ts`, `AgentSpec.meta` | | 10.22 | OpenTelemetry GenAI conventions | Development | built | `harness/trace.ts` | | 10.23 | A natural-language `/ask` endpoint in NLWeb's shape: `query` and a `mode` of `list`, `summarize` or `generate`, answered from the app's own knowledge and stores, a named store's rows as schema.org objects | | built | `server/ask.ts`, `AppConfig.ask`. Without `ask` in the config no model is reached. | | 10.24 | Published prompts and resources served over MCP beside the tools | 2026-07-28 | built | `server/mcp.ts`, `prompt`, `resource` | ## 11. Extending an app | # | Capability | Status | Where | | --- | --- | --- | --- | | 11.1 | Tools: MCP services over HTTP and stdio, OpenAPI documents, local functions, code mode | built | `tools/`, `functions/` | | 11.2 | Composing apps in code: `mergeApps`, collisions reported | built | `sdk.ts` | | 11.3 | Plugins from the config: a piece of an app, drivers, blobs, hooks, a `setup`, commands | built | `project/plugins.ts` | | 11.3a | Skills from a plugin, read from a folder the package ships (`skillsIn`), so a plugin can be a whole environment for one platform | built | `project/plugins.ts`, `project/skills.ts`. Environments are kept in `praecise-environments`. | | 11.4 | Packaging an app as an installable, importable package with its tool surface written down | built | `src/package/` | | 11.5 | Skills and plugins found in an index anyone can host, checked against a digest, never run | built | `registry/`, `praecise search`, `praecise add`. No index is built in. | | 11.6 | A new app from a template, and a piece added to one: a function, tool, store, workflow, guard, or a blueprint the app wrote | built | `praecise init --template`, `praecise add`, `cli/templates.ts`, `cli/pieces.ts` | | 11.7 | A TypeScript app transpiled on load with the project's own `typescript`; types are erased, not checked | built | `project/typescript.ts` | | 11.8 | A function served at an HTTP route of its own, under the token and origin checks of `/api` | built | `FunctionSpec.http`, `server/index.ts` | | 11.9 | Deploying to Praecise Cloud from the command line: deploy, releases, rollback, status, logs | built | `cli/cloud.ts` | ## What tests do not cover - No request has been sent from the test suite to a live model endpoint, a live session, a files API or a batch API: those are covered by tests against the shapes in the providers' documentation. `scripts/verify-wires.mjs` makes one real call per wire and is run by hand before a release. - Redis and Valkey, and the PostgreSQL 18 paths, are tested against scripted servers. The PostgreSQL tests that need a server run where one is reachable. - Computer use is tested against a scripted DevTools endpoint, the video decoder against a scripted `ffmpeg`, and the protocol servers (A2A, MCP, Agent Client Protocol, Responses) against their published schemas, not against other implementations. - The MCP server card's endpoint field, the AI catalog's shape and the A2UI encoding over AG-UI follow documents that are still drafts or leave the detail open. --- # Changelog All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) from 1.0.0 onwards. Before 1.0.0, the shape of the public API was still being settled; that is what the entries before 1.0.0 are. ## Unreleased ## 1.1.0 - 2026-11-22 ### Added - A plugin may bring skills (`app.skills`), checked as a `SKILL.md` is and merged under the app's own, so a plugin can be a whole environment for one platform: its skills, tools, an agent and a command. - `skillsIn(folder)` reads a folder of skills, with the text files beside each, into the shape a plugin or `defineApp` takes. ## 1.0.0 - 2026-11-22 Memory is rebuilt, the store drivers gain one verb, and nothing written by an earlier version is read or migrated. Apps that kept agent memory start with none. ### Changed - **Memory is four things, kept apart.** An agent with `memory` has a record of exchanges, working notes it writes itself, subject pages, and a short list it carries. Only the last is placed in front of it, and only a person changes it. - **All of an agent's memory is in one place.** In files under `/memory//`, or, for an agent that names a store, in that store: the record and notes as rows, the pages and what it carries as documents. Nothing is split between a database and a machine's disk. - **`AppConfig.store` is honoured.** It is the store for every agent that asks for memory without naming one. It was declared and never read. - **A store an agent remembers into is declared without a `schema`.** One with a schema is refused at load. - **What an agent carries accumulates.** Accepting a proposal adds to what is carried instead of replacing it. A replaced or retired entry is closed with the time, not deleted, and which of two entries stands is decided by authority and then time. `App.accept` answers with `{ kept, closed, refused }`. An agent carries at most 48 entries. - **Facts and procedures are one list behind one gate.** A procedure is a carried entry of `kind: "procedure"`, proposed and accepted like a fact. - **`App.propose` is `App.reflect`, and `praecise memory --propose` is `--reflect`.** It also checks what is carried against the record and files what is new onto subject pages. One reading at a time per agent: a second is refused with `AlreadyReflecting`. - **A driver's `Connection` has `add`.** It keeps a row only if nothing is kept under its id, decided by the backend in one step. Every shipped driver implements it and `conform` checks it; a driver of your own must add it. - Development dependencies are at their latest releases: TypeScript 7.0, Vitest 5.1, oxlint 1.94, `@types/node` 26.6. ### Removed - **A memory backend of the app's own.** `AppOptions.memory` takes a cipher and nothing else; memory is kept elsewhere by naming a store, and a backend the framework does not ship is a `Driver`. `Recollection`, `Memory` and `StoredMemory` are no longer exported. - `SkillBook`, `usableProcedures`, `renderSkills`, `settle` and their types. - `MemorySpec.write`, which was never read. ### Added - **Memory tools.** An agent with memory is given `search_memory`, `read_memory` and `write_note`, and is told what its memory is for. What it writes is searched, never placed in front of it. - **Subject pages.** One page per subject, one writer per page: a write names the revision it read and is refused if the page has moved on, between processes and between machines (`App.filed`, `App.page`). - **The record read back on a schedule.** `memory: { reflect: { cron } }`, started by `praecise dev`, `serve()` or `app.tend()`. Where several processes serve one app, a tick is read back once. - **Origin is set by the runtime.** An exchange or note written after anything untrusted was read is kept as `external`, and reading external memory marks the request as tainted. - **Recall in any script.** Words are found the way each script separates them. - **`store.values.claim`.** Keeps a value only if the name is free; of several callers at once, one is told yes. - **`praecise eval --memory`** and `App.evaluateMemory`: one suite without memory and with it, and the difference. - `App.retire`, `App.carried`, `App.jot`, `App.jotted`, `App.clearMemory`. ### Fixed - A memory file that could not be read as what was written is refused and left as it is; it was read as empty and overwritten by the next write. - Two writers to one memory file, in one process or in two, both keep what they wrote. ### Also in this release - **Reasoning is handed back with tool results on every wire.** Signed thinking blocks on `messages`, output items with encrypted reasoning on `responses`, `reasoning_content` or `reasoning` on `chat`, and thought steps on `interactions` are returned to the endpoint unchanged on the next turn of a tool loop (`ChatResponse.replay`, `Message.replay`). They never leave the rung they came from. - **Prompt caching on the `messages` wire.** The part of the instructions that is the same on every request, and the end of a tool loop's transcript, are marked for the endpoint to keep. `cache: false` on an endpoint turns it off. `Usage.cacheWriteTokens` reports what was kept. - **Attachments.** `AskOptions.attachments`, and `attachments` on `POST /api/agents/`, send images and documents with a question on all five wires. - **One rule for anything sent that is not text.** An attachment the endpoint reads is sent as it is: audio and video on `contents` and `interactions`, and on `chat` where the endpoint's `takes` says so. Data no model reads is rendered by a reader chosen by media type: SenML sensor measurements, Open Inference Protocol tensors, CSV and TSV tables, glTF scenes, text and JSON. Anything else is left out with a note. `registerReader` adds a reader. - **Tool results carry media.** A function returns `attach(result, ...attachments)`, and an MCP tool's image, audio, embedded file or `https:` resource link is handed to the model on every wire. Before, such a block was written into the transcript as base64. - **`answer.attachments`.** Images and audio a model returns on `contents`, `interactions` and `chat` come back with the answer. - **Values, facts and series on every store.** `store.values` keeps a value under a name in a namespace, with an optional lifetime. `store.facts` records how two things are related, with the time it was true and the time it was recorded, closes a fact rather than deleting it, and walks relationships up to three steps. `store.series` keeps readings in order of time and answers a span as points or as windowed aggregates. All three are written over the operations a driver already implements, so a brought backend has them too. - **Events over HTTP.** `POST /api/events/` and `app.deliver()` start a run for a CloudEvent, once per `source` and `id`. - **Plugins bring more than commands.** A plugin in `plugins` may carry `app` (a piece of an app, merged under the app's own folder), `drivers`, and `setup`. `commands` is now optional. The type is `Plugin`; `CliPlugin` remains as its alias. - **Depth words, output room and embeddings are the endpoint's to declare.** `levels`, `output` and `embeds` on a model endpoint. - **Longer work in one request.** `turns` on an agent (default 16, was a fixed 6). Old tool results are cleared, and then the earlier work is summarised, when the transcript passes half the endpoint's `room`. A result too long for the transcript is kept whole and read with `read_result`. Calls in one turn that only read run together. - **An agent can ask another agent.** An agent named in `tools` is a tool: it runs with its own context and only its answer comes back. Bounded by `limits.depth` (default 3). - **`advisor: true`.** A `consult` tool asks the strongest model on the agent's ladder for advice while a cheaper one does the work. - **Tool search.** More than a dozen service tools whose definitions pass a tenth of the endpoint's `room` are found with `find_tools` and called with `use_tool` instead of being listed. - **Authored skills.** `skills//SKILL.md` in the Agent Skills format, listed in an agent's instructions and read through `read_skill`. `skills` on an agent narrows or disables them. - **Evals.** `evals/`, `evaluation()`, `app.evaluate()` and `praecise eval`, with `pass@k` and `pass^k` over repeated trials and an exit code for CI. - **Recall by meaning.** An agent that remembers into a vector store has each exchange embedded when an endpoint names an `embeds` model or the app passes an `embedder`, and falls back to text when the embedding cannot be had. - **MCP Tasks.** A workflow called by an MCP client that declares the Tasks extension returns a task; `tasks/get` and `tasks/cancel` follow it. As a client, a tool call that returns a task is followed to its end. - **Run notifications.** `notify` in `App.load` is told when a run starts, waits at a gate, finishes or fails, as CloudEvents, to a function or as a signed webhook (Standard Webhooks). `signWebhook`, `verifyWebhook`, `deliverWebhook`. - **Web Bot Auth.** `botAuth` in `App.load` signs every outbound request (RFC 9421, Ed25519) and serves the key directory. `signingFetch`, `verifySignature`. - **MCP server card and AI catalog.** `GET /mcp/server-card` and `GET /.well-known/ai-catalog.json`. The catalog's shape is provisional. - **AG-UI interrupts.** A workflow streamed with `?protocol=ag-ui` ends at an approval gate with an interrupt and is continued with `resume`. - **A2A 1.0.** The `/a2a` endpoint speaks 1.0 method names, card and error shapes, streams `SendStreamingMessage` and `SubscribeToTask` over SSE, paginates `ListTasks`, and reports a run waiting at an approval gate as `TASK_STATE_INPUT_REQUIRED`. A caller that speaks 0.3 is answered in 0.3. - **Client ID Metadata Documents.** `OAuthClient` takes `clientMetadataUrl` and uses it as the client id where the authorization server supports it; `clientMetadataDocument()` builds the document. - **Eval cases from recordings.** `record: true` in the config keeps each exchange under `.praecise/recordings`, with credentials redacted, and `praecise capture ` (`app.capture()`) writes a suite from them or from a workflow's runs. An agent case replays its tool calls from the recording (`AskOptions.tape`); a call the recording does not hold is an error. The new `reference` grader compares an answer with the recorded one, by a judge or exactly. A workflow's steps run for real. - **Online evals.** `online: { sample, expect, threshold }` on a suite scores a sample of an agent's live answers after they are returned. The score goes to the `tracer` as a `gen_ai.evaluation.result` event and, below the threshold, to `notify` as `com.praecise.eval.below`. `app.settled()` waits for it. - **Registries.** `registries` in the config lists Agent Skills discovery indexes. `praecise search` looks through them and `praecise add ` installs a skill, digest checked, into `skills//`, or records a plugin in `praecise.plugins.json` with the command that installs it. There is no default registry. - **Cancelling a run.** `app.cancelWorkflow()`, `POST /api/runs//cancel` and `cancelRun` stop a run and record it as `cancelled`, reported as `com.praecise.run.cancelled`. A function hears it as `signal` in its second argument, and `startWorkflow` takes a `signal`. - **`wait` steps.** A workflow step that stops until a CloudEvent of a given type, `source` and `subject` arrives, with `timeout` and `onTimeout`. `app.signal()` continues the runs waiting for an event and `app.expire()` times out the ones whose time is up. A timeout fires only while a process holds the app. - **Clocks.** `clock(name, { cron, zone })` or `{ every }` is a source for `app.follow`, with `catchUp` for ticks that fell due while nothing ran. `cronNext` is the arithmetic. - **An event bus, and AsyncAPI.** `on` on a workflow names the event types that start it. `app.publish()`, `publish` in a function's second argument and `POST /api/events` put an event on the bus, once per `source` and `id`. The bus is in-process and matches exact types. `GET /asyncapi.json` describes the events an app receives and sends (AsyncAPI 3.1.0). - **A video decoder.** `registerDecoder` takes apart media an endpoint cannot be sent, and `ffmpegDecoder` does it for video over an `ffmpeg` binary the app names: stills as images, and the sound as audio or as a transcript. - **Uploads.** An attachment past a size is uploaded once through the endpoint's files API and named after (`Attachment.fileId`). `uploads` on an endpoint sets the size or turns it off; it is on by default for `messages`, `responses`, `contents` and `interactions`. `registerUploader` covers another shape. - **Batches.** `app.askMany(agent, questions)` hands many questions to the endpoint's batch API on `messages`, `responses`, `chat` and `contents`, and answers in order with an answer or an error each. `batch: false` on an endpoint sends them one at a time. `registerBatch` covers another shape. - **Live sessions.** `app.open(agent)` opens a conversation over one WebSocket where the endpoint declares `realtime`, with text, audio and the agent's tools through the same guard. Protocols ship for the `responses`, `chat`, `contents` and `interactions` shapes; `registerSession` adds one. A session has no failover. - **Cost in money.** `prices` on an endpoint, per million tokens per rung, gives `usage.cost` by currency, `usage.unpricedTokens`, and the span attributes `praecise.usage.cost` and `praecise.usage.cost.currency`. `limits.spend` caps a run and stops one that reaches an unpriced model. An eval case's `budget` takes `spend`. - **Hooks.** `hooks.ts` at the root, and `hooks` on a plugin: `afterTool` rewrites or withholds a result, `beforeStop` sends an agent back to work up to three times, `beforeCompact` forbids or supplies a summary, and `beforeRecord` decides what a self is sent. - **Background agents.** `background: true` on an agent lets it start the agents in its `tools` without waiting, and check, steer, cancel and collect them. Four may run at once in a request. `AskOptions.steer` says more to a request under way. - **A permission classifier.** `permissionClassifier({ policy, models })` is an authority that reads a policy in prose against each call by asking a model. It sees what the person said and the calls made (`Attempt.recent`), never a tool's output, and refuses when it cannot decide. - **Computer use.** `computer(screen)` is a screen as a function, and `browserScreen()` is a browser to use as one. `computer` on an endpoint names its own computer tool, used on the `messages` wire. - **`@praecise/harness/formats`.** A plugin of readers for MCAP, ROS 1 bags, LeRobot metadata, Parquet footers, Arrow IPC schemas, PCD, PLY, Gaussian splats, USD and `.npy`/`.npz`; a ROS 2 `.db3` bag is identified. - **Typed records.** `schema` on a store takes any Standard Schema validator. `remember` refuses a batch with anything outside it (`SchemaError`), and `RecordOf` is the record's type. - **Blobs.** `app.blobs` keeps bytes under their SHA-256. `detach` moves an attachment's bytes there (`Attachment.blob`), they are put back before a model is shown it, and `sweepBlobs` removes what nothing names. `blobs` in `App.load` or on a plugin replaces the folder on disk. - **A reranker.** `reranks` on an endpoint, or `reranker` in `App.load`, scores what a store recalled a second time; `{ rerank: false }` leaves it out of one question. - **Faster paths in the SQL backends.** Fact walks and series aggregates run in the database on SQLite and Postgres, with `time_bucket` where TimescaleDB is found, and PostgreSQL 18 makes ids with `uuidv7()`. `capabilities.faster` says which a backend does, and `conform` holds each to the in-process answer. - **PostgreSQL protocol 3.2, on request.** `max_protocol_version=3.2` (or `latest`) on a `postgres://` url asks for it; the default stays 3.0, and a server older than 18 settles on 3.0. `capabilities.detail` names the version a connection settled on. - **A Redis and Valkey driver.** `redis://`, `rediss://`, `valkey://` and `valkeys://` urls open a store over RESP3, falling back to RESP2, using vector sets, time series and JSON where the server has them. There is no text index, and `query()` takes a command. - **`CAPABILITIES.md`.** Every capability is listed as `built` or `declined` with its reason, beside the seams a new one goes in through and what the tests do not cover. - **MCP elicitation.** `mcp.elicit` in `App.load` answers a server that asks a person for a value (`form`) or sends them to a page (`url`). Each mode is declared only when its handler is there. - **MCP subscriptions and task notifications.** `watch: true` on a service lists its tools again when the server says they changed. A task is followed through `notifications/tasks` where the server sends them, and the server sends them for its own tasks. `app.onRunChange()` hears run changes in process. - **Skills over MCP.** An app's authored skills are served as `skills/list`, `skills/get` and `skill://` resources, and `skills` on a service offers that server's skills to agents through `read_service_skill`, checked against the server's manifest. - **Machine grants.** `oauth` on a service gets its token by `client_credentials` or by `id-jag`, with nobody at a keyboard. - **MCP Apps.** `ui` on a function, agent or workflow names a `ui://` resource to show beside its result. As a host, `mcp: { apps: true }` hands a tool's view on as `answer.ui` and over AG-UI, and `POST /api/ui/` serves what the view asks for, through the guard. - **A2A push notifications, signed cards and HTTP+JSON.** A 1.0 peer may register a webhook for a task. The agent card is signed when `botAuth` is set, and `fetchAgentCard` and `verifyAgentCard` check a peer's. The HTTP+JSON binding is served under `/a2a`. gRPC is not offered. - **A2UI 1.0.** When a turn names the catalogs its renderer draws, the agent gets a `show_surface` tool, and the surface is returned over A2A, AG-UI and HTTP. No renderer is included. - **Agent Client Protocol.** `praecise acp` (`serveAcp`) serves an agent to an editor over stdio. - **A Responses endpoint.** `POST /v1/responses` answers in the shape of the Responses API, with `model` naming an agent. - **`caller` and `context`.** `AskOptions.caller` carries anything the app adds beside `person`, and `AskOptions.context` anything else. Both reach the guard and authority (`Attempt.caller`, `Attempt.context`), functions, the meter and delegated agents, and no model. `startWorkflow`, `resumeWorkflow` and `callTool` take both. - **`allow`.** `AskOptions.allow` narrows the tools and knowledge an agent has for one request. - **A meter, and a call limit.** `meter` in `App.load` is asked before every model call and may refuse it (`MeterRefused`). `AskOptions.maxCalls` and `limits.calls` bound the model calls of one request (`CallLimitReached`). - **Typed `returns`.** `returns` takes a JSON Schema or a Standard Schema as well as fields and hints, and `read` on an agent is a check of the app's own. An answer outside either is asked for again, then from a stronger model, then ends in `ShapeError`. `app.ask(agent, …)` with the agent itself types `answer.data`. - **`@praecise/harness/testing`.** `scriptedModel`, `scriptedEndpoint` and `systemText`, for testing an app without a model. - **Agent `meta`.** `meta` on an agent is read by the A2A card, the MCP tool's `_meta["com.praecise/meta"]`, `llms.txt` and the JSON-LD. - **A say over what a self is sent.** `self.record` on an agent and the `beforeRecord` hook rewrite or withhold it. - **Sealed conversations and memory.** `threads` and `memory` in `App.load` take a cipher, or a backend of the app's own. - **Replacing agents in a running app.** `app.replace()`, `app.add()` and `app.remove()`. - **Requests may lend tools and answer approvals.** `AskOptions.tools` adds tools for one request, and `AskOptions.approve` with `app.approvalOf()` answers a `stepUp` mid-turn. ### Changed - **MCP `tasks/cancel` and A2A `CancelTask` stop the run.** Before, they stopped the task being reported and the run carried on. - **`app.deliver()` and `POST /api/events/` continue a waiting run first.** A run of the workflow stopped at a `wait` step the event matches is continued; a run is started only when none is waiting. - **A function called from a tool loop receives a second argument**, as one called from a workflow step does: `signal`, `publish`, `transcript`, `caller` and `context`. - **`StoredMemory.recall` asks by text and by vector** and joins the two orders by reciprocal rank. - **`GetExtendedAgentCard` is answered with -32004** (unsupported operation). - **`Mcp-Name` is required on `tasks/get`, `tasks/update` and `tasks/cancel`.** - **`createApp` names agents from their keys**, as it does workflows. - **An A2A skill's tags are the group it is published in**, or the agent's `meta.tags` where it has any. - **On PostgreSQL 18 with `btree_gist`, an overlapping fact is refused.** `facts.relate` throws where the new fact's validity overlaps one already recorded. - **A suite with `online` and no cases is valid.** - **`app.close()` waits** for recordings and scores already begun. - **An attachment weighs 1,500 tokens** in the transcript, and a tool result that is cleared loses its attachments with it. - **`resources/read` carries `ttlMs` and `cacheScope`.** - **`capture`, `search` and `acp` are built-in command names.** A plugin command of one of those names is no longer reached. - **Every wire runs under a clock**, not only `chat`: `PRAECISE_WIRE_IDLE_MS` between frames of a stream and `PRAECISE_WIRE_TOTAL_MS` on a buffered reply. - **Why a reply ended is one vocabulary** (`ChatResponse.stop`). A refusal or a content filter on any wire now crosses to the next model; before, only a reply whose native reason was the word `refusal` did. A reply that ran out of room is reported in `answer.notes`. - **`retry-after` is honoured**, up to thirty seconds, and a 429 that is about a spend limit is not retried. - **On the `messages` wire, `inputTokens` includes what was read from and written to the cache**, as it does on every other wire. A request that hit the cache reports a larger `inputTokens` than it did before, with the same bill. - **A `messages` request that may think is given 16,384 tokens** for the thought and the answer when the endpoint declares no `output`. It was 4,096. - **One tool result may take 8% of the endpoint's `room`** in the transcript, down from 20%, because the whole result is now kept and readable. - **AG-UI events use the standard's names and fields** (`RUN_STARTED`, `TEXT_MESSAGE_CONTENT`, `TOOL_CALL_RESULT` with `messageId` and `content`, `ACTIVITY_SNAPSHOT`). A failed run ends in `RUN_ERROR` alone, and a refused tool call is an activity, not an error that ends the run. - **`eval` is a built-in command name.** A plugin command named `eval` is no longer reached. - **Paths in load errors and knowledge names use forward slashes on Windows.** ### Fixed - Replacing a run file retries the rename, which failed with `EPERM` on Windows while another reader held the file. - A span's cached-token attribute is `gen_ai.usage.cache_read.input_tokens`, the name in the convention. It was `gen_ai.usage.cached_tokens`. - `OAuthClient` checks that a registration belongs to the issuer it is presented to when completing a flow and when refreshing, not only when beginning one. ## 0.6.1 - 2026-11-10 ### Fixed - **`praecise --version` prints the version.** It printed the usage text; only `-v` gave the version. ## 0.6.0 - 2026-11-10 ### Added - **Praecise Cloud from the command line.** `praecise login`, `deploy`, `releases`, `rollback`, `status`, `logs` and `whoami` deploy a project on Praecise Cloud, show what is live, and go back to an earlier release. The token comes from `praecise login` (kept in `~/.config/praecise/cloud.json`, readable only by its owner) or from `PRAECISE_CLOUD_TOKEN`; the project from the command line, `PRAECISE_PROJECT`, or `praecise.json` in the folder. `deploy --wait` follows the deploy to its end and prints its log. Every command takes `--json`, and exits 0 when done, 1 when a deploy or rollback failed, 2 for a command that was not valid, 3 when not signed in or not allowed, 4 when there is no such project or release, and 5 when a deploy is already running. They use the runtime's own `fetch` and add no dependency. ### Changed - **Seven command names are now built in.** A plugin command named `login`, `deploy`, `releases`, `rollback`, `status`, `logs` or `whoami` is no longer reached, because the built-in command answers first. Give such a plugin command another name. ## 0.5.0 - 2026-10-27 The first release published since 0.3.2. Versions 0.4.0 and 0.4.1 were tagged in the repository but never published, so everything they contained is listed here. ### Added - **A floor for one request.** `AskOptions.floor` is the cheapest rung a request may start on, the mirror of `ceiling`. It exists for re-asking after a cheap answer was rejected: lifting a ceiling does not move a request up, because the router still enters cheapest-first, so the same small model was asked again. A floor can only remove rungs the agent declared, never add one, and with both set it is clamped to the ceiling: a floor above the ceiling gets the ceiling, never an empty ladder. - **Code mode.** `code: true` on an agent replaces its per-operation tools with a single `code` tool. The agent's HTTP services are described to the model as a typed API (MCP tools as functions, OpenAPI services as `request()` with the document available as `spec` to search), and the model's program runs in a Praecise Silo with the services bound in and their credentials kept outside it. Services launched as local programs remain ordinary tools. Exported for use outside agents: `CODE_TOOL`, `SiloExecutor`, `bindingsFor`, `typesFor`, `codeTool`, `tsType`, and the types `CodeModeSpec` and `Binding`. - **Code mode allow rules.** `code: { allow: { : [...] } }` narrows what a program may call: tool names for MCP servers, `"METHOD /path"` patterns for OpenAPI services. The silo enforces them and logs every call. - **Actions and an authority.** A function can declare the `action` a call takes, computed from its validated arguments, and an app can pass an `authority` that is asked after the guard on every path to a tool. It allows, refuses with a reason, or asks for a person: on a workflow step that becomes a gate whose signed claim binds the action's `digest` (`ApprovalClaim.digest`), and the call is asked again with the verified approver in `Attempt.approvals`. Each verified approval carries its signature (`VerifiedApproval`), and a local function receives the same list as `opts.approvals`, so an action can present the approval to whoever checks it next. - **Integrity labels.** Functions and services carry `trust`; services default to untrusted. Once untrusted output has been read, every later action in the same conversation or run is marked `tainted` (`Answer.tainted`, `Run.tainted`). - **A sealed journal.** `journal: { sink, signer }` seals every finished `ask` and `use` step as a hash-chained, optionally signed entry recorded on the run before it is delivered; `verifyJournal` checks a chain. Wires may return `evidence`, collected on `Answer.evidence` and carried into the journal. - **Payments on 402.** `payer` pays a 402 met by the app's fetch under a key derived from the step's idempotency key, checking `status(key, required)` first so a retried step reuses a settled payment, presented in the form the server asked for. Local functions receive the app's fetch as `opts.fetch`. - **Sandbox snapshots, sealed runs, durable sources, CLI plugins.** `sandbox` snapshots after each journalled step and restores before recovery; `runCipher` seals run files at rest; `App.follow(source, workflow)` starts one run per event and resumes after the stored cursor; config `plugins` add `praecise `. - A local function called by a workflow `use` step receives the calling `run` and `step` in its options, to key what it records. - The package ships a `NOTICE` file, and the copyright holder is Praecise LTD. ### Fixed - A workflow `use` step's idempotency key is SHA-256 over the workflow, the run, the step and the step's arguments. It was a 32-bit hash of the run, step and arguments, so two runs could present the same key and a deduplicating tool would skip the second one's effect. - A workflow defined in code (`createApp`, `defineApp`) is named by its key, as a folder names one by its file. It was left unnamed, so its runs were recorded under `workflow` and could not be resumed or recovered by name. - **Endpoints that ignore `stream: true`.** The `chat` wire parses a stream only when the response is `text/event-stream`. An endpoint that answered with one buffered completion was read as a stream with no frames, which returned an empty answer with zero usage; it is now read as the completion it is, and a streaming caller receives its whole text at once. - `praecise init` wrote a `package.json` depending on `@praecise/harness@^0.3.0`, which on a 0.x version never installs anything newer than 0.3, and `praecise -v` printed `0.3.0`. Both now come from the package's own version. ## 0.3.2 ### Added **What a request is about, when the input carries more than the question.** An app that grounds a request sends the grounding as the input, because that is what the model reads — and a self was then looking up its memory by the wrapper and recording the wrapper as the work. `AskOptions.task` says what was actually asked, over HTTP as `task` and over MCP as `_meta["com.praecise/task"]`. It defaults to the input, so nothing changes for an app that sends only a question. ## 0.3.1 ### Fixed **A request to the `chat` shape now has a clock on it.** It passed only the caller's signal, so an endpoint that accepted the connection and then stopped writing held the request until something else gave up — and on an endpoint that serves one request at a time, held the slot with it. A streamed answer is now watched between frames, with the clock starting again at every frame so that a long answer arriving steadily is never cut off for being long (`PRAECISE_WIRE_IDLE_MS`, default 45000). One that arrives in one piece is watched as a whole (`PRAECISE_WIRE_TOTAL_MS`, default 240000). A timeout arrives as a `ProviderError` with status `0` — the shape a dead endpoint already produced — so the ladder crosses to the next model rather than asking the silent one again. The caller's own signal is composed with the clock, never replaced, so cancelling still cancels and is not reported as a provider failure. **Text that arrived is no longer thrown away with the stream that carried it.** A stream that died after some of the answer had been sent lost the answer too, which had already been shown to whoever asked and already been paid for. What comes back now is the partial text, with `finishReason: "timeout"` and the reason in `ChatResponse.notes`. A stream that said nothing at all is still a rung that failed. **`reasoning_effort` is sent only to an endpoint that declared it takes effort.** It went to every endpoint asked for any depth at all, and `planModels` asks for depth on the balanced and best rungs whatever the provider said — so an endpoint that takes depth as a token budget, or takes none, was sent a field it rejects outright. `thinking: "effort"` is now the whole of what turns it on; anything else, including saying nothing, leaves it off. **Every request to the `chat` shape now carries a completion ceiling.** The `messages` shape has always defaulted one and this shape sent none, so a reply decoded without bound. It defaults to 4096 the same way. A request that asks for depth is also floored at 512: the budget covers the reasoning and the reply out of one pool, and one too small to hold both is spent entirely on the first and returns an empty answer that still bills. ### Added **`Provider.credentialHeader`, `Provider.headers` and `Provider.body`.** Three lines in a config for an endpoint with needs of its own, in place of three patches to a fork. `credentialHeader` names the header the credential is sent in, for an endpoint that reads a bearer as an anonymous caller and refuses it — the credential still comes from `credential`, so nothing in the app has to handle the secret. `headers` are sent with every request and applied last, so one of them wins over anything the wire would otherwise send. `body` is merged into the request beneath what the wire built, for the fields a runtime names and the protocol does not; what the request asks for wins, and `model` and the conversation are never replaceable from a config. **`Limits.retries` and `Limits.retryDelay`.** How many times a rung that failed for a passing reason is asked again, and how long to wait before the first of them. The previous fixed values — 2 and 200 ms, doubling with jitter — are the defaults. Worth raising where one endpoint serves one request at a time: it refuses everything queued behind the one in flight, and crossing to another model on that is paying more precisely because the cheap one was busy. ## 0.3.0 ### Renamed **The package is now `@praecise/harness`; the command is still `praecise`.** Install with `npm i @praecise/harness` and import from `"@praecise/harness"` (and `"@praecise/harness/internal"`). The package was previously published as `praecise`; that package name is deprecated and receives no further releases. `praecise init` writes a `package.json` that depends on `@praecise/harness`, and `praecise package` writes a launcher and module that import it. Everything an existing app is written against keeps its name: the `praecise.config.ts` config file, the `.praecise/` state directory, the `com.praecise/*` `_meta` keys, every environment variable (`PRAECISE_API_KEY`, `SELVES_URL` and the rest) and the `praecise-person` header. ### Added **Selves.** An agent can declare the self it is (`self: "design"`) and the harness reads that self's context before every request and records the work after it, through a self provider configured as `selves` in `praecise.config.ts` or passed as `AppOptions.selves`. `{person}` in a handle gives each person their own self, created from a template on first use. Answers carry `answer.self` with a ticket, bound to the person when `SELVES_TICKET_SECRET` is set, and ratings come back through `App.rate` or `POST /api/selves/outcome`. The self travels on every surface: `ask`, `watch` (a `self` progress event), HTTP, AG-UI, and MCP (`_meta["com.praecise/self"]`, with the person in `_meta["com.praecise/person"]`). An agent that is a self keeps no second memory: `self` and `memory` together are a fault. `selvesOverHttp` speaks the HTTP self protocol. A caller can name the surface it asks from (`surface` over HTTP, `_meta["com.praecise/surface"]` on an MCP `tools/call`), so a self answers in that surface's persona wherever the agent is reached. A verdict on a self's answer can carry a `check`, something the app measured about what came of it, through `App.rate`, `POST /api/selves/outcome` and the HTTP self protocol. **Protocols.** The current MCP revision, `2026-07-28`, on both the client and the server, with no dual-era fallback — it is a stateless protocol, so the `initialize` handshake, session header, standalone GET stream, `ping`, `logging/setLevel` and SSE resumability are gone, and every request carries its own version, capabilities and identity. A2A 1.0 publishes the app as an agent a peer can delegate to, with an agent card at `/.well-known/agent-card.json`. AG-UI streams to whoever is watching: `?protocol=ag-ui` on any agent endpoint, with `?stream=` selecting `messages`, `tools`, `updates`, `custom` or `values`. **OAuth 2.1** for MCP servers that are protected resources, with the parts that exist because of an attack rather than a feature: resource indicators (RFC 8707) on both the authorization and token request, byte-exact issuer validation (RFC 9207), PKCE, and registrations keyed by issuer so one is never presented to a server that did not mint it. **OpenAPI descriptions become tools.** `tool({ openapi })` is a third kind of service alongside `url` and `command`; operations are flattened into the single object a model produces, and the location of each value is remembered rather than guessed at call time. **An SDK door.** `createApp` takes an app as a value rather than reading a folder, for shipping agents in a package, running where there is no filesystem to scan, or assembling an app from parts. `mergeApps` composes definitions and reports collisions instead of letting one silently disappear. Both doors build the same project and run the same checks. **A TypeScript build step.** Every `.ts` file is compiled into `.praecise/build` before anything is imported, using the compiler in your own project, so a TypeScript app runs on a Node that cannot read TypeScript. One broken file costs you that file rather than the whole app. **Discovery, for machines.** `/llms.txt`, JSON-LD at `/ai.json`, a `robots.txt` inverted for an app where there is little to index and much that costs a model call, and `/ask` — an NLWeb-shaped endpoint that answers a natural-language question from the app's own store, at a rung the operator caps. **An ingestion pipeline.** `praecise ingest --store ` reads PDFs, Word, Excel, PowerPoint, CSV, images and source into a store; `--fields` asks a model to pull named values out of each chunk. Idempotent on content, so running it twice does not double the catalogue. **Tracing, forking, and a page to look at them.** OpenTelemetry GenAI spans, with no OpenTelemetry dependency — the convention is in the data and the transport is yours. Trace context crosses into MCP via `traceparent`. `forkRun` branches a run from a past step, optionally patching an earlier output, recording who did it. `praecise dev` serves `/traces`, a timeline of what the last few requests did. **`praecise doctor`** says everything wrong with an app in one pass, ranked by whether it stops the app running, and exits non-zero only on the blocking kind. ### Changed - `fn`, `workflow` and `prompt` infer from what they declare. `run`'s arguments come from `input`, `after` only accepts step ids that exist, and a prompt's `{{placeholders}}` must name declared fields. Each of these was previously a silent runtime failure: an undeclared field arrived as `undefined`, a mistyped `after` produced a step that was never ready, and a mistyped placeholder interpolated to nothing and sent the model a sentence with a hole in it. - `AskOptions.ceiling` caps how expensive a request may get, trimming an agent's ladder so escalation still works below it. ### Fixed - `App.load` crashed with a raw `TypeError` when an agent had no `role` — the loader recorded the fault and then the planner destroyed the report describing it. - `clientFor` and `collectTools` both tested for an API key alone, making stdio MCP servers unreachable by construction. - The interactions wire computed a warning about silently-dropped sampling parameters and put it on a type nobody holds. - `praecise init` wrote a `.ts` app that the runtime could not load. - Store errors, resource reads, and protocol refusals now carry `cause` or a named error rather than a flattened string. ### Changed - **Breaking (shape of the public API), ahead of 1.0.** The package root now exports the public API and nothing else. It previously exported 98 values and 122 types, most of which were the framework's own moving parts — a planner, a loader, provider wire formats, MCP request handlers, the packager, the CLI entry point. Tagging 1.0 would have semver-locked every one of them, which would either be a promise the project could not keep or a freeze on its own insides. Nothing was deleted. 38 values and 16 types moved to the new `@praecise/harness/internal` subpath (see *Added*), so every current import keeps working after a one-line change to the specifier, and nobody has to fork the framework to reach something they genuinely need. Moved to `@praecise/harness/internal`: `findCycle`, `loadProject`, `resolveKnows`, `canConvert`, `ingestFile`, `converterFor`, `planAgent`, `planProject`, `planWorkflowAgent`, `schemaFor`, `adapterFor`, `chatWire`, `contentsWire`, `messagesWire`, `stateDirFor`, `stream`, `trim`, `asObjects`, `urlFor`, `checkSteps`, `provisioner`, `runCommand`, `splitCommand`, `openChannel`, `callPublished`, `groupsOf`, `handleMcp`, `noticesOf`, `promptsOf`, `resourcesOf`, `toolsOf`, `apiModule`, `apiTypes`, `faultsIn`, `hintsIn`, `buildPackage`, `manifestFor`, `cli`; and the types `Importer`, `LoadOptions`, `Converted`, `Converter`, `ConvertRequest`, `IngestOptions`, `PlanOptions`, `Manifest`, `ProvisionerDeps`, `Channel`, `Caller`, `McpTool`, `Describable`, `PackageManifest`, `PackageOptions`, `PackageResult`. The authoring surface, the running surface, the harness contract, the store and driver surface, and the dialect codec and latent transport are all unchanged and stay at the root. - The `api.js` module generated by `buildPackage` now imports `callPublished` from `@praecise/harness/internal` rather than from the root. It is regenerated on every build, so it tracks whichever version of praecise built it. ### Added - **`@praecise/harness/internal`**, a second entry point holding everything demoted above. It is explicitly **not covered by semantic versioning**: names there may change, be renamed, or disappear in any release, patch releases included, with no deprecation period. It exists so that necessity does not force a fork, not as a second API. - **`API.md`**, the written-down public API, grouped by task — authoring, running, the harness, storage and driver extension, dialect and latent transport, observability — with one line per name and a plain statement of what `@praecise/harness/internal` does and does not promise. - **`CHANGELOG.md`** (this file). - Types that exported types already referred to but which could not be imported. `AgentSpec.access` is an `Access`, `WorkflowSpec.outcome` is a `Check`, and every published spec extends `Published`, yet none of the three were exported; their sibling `Effect` was, which is what makes it an oversight rather than a decision. Now exported: `Access`, `Check`, `Published`. - `ProviderError`. The documented `ChatAdapter` contract says an adapter should throw it, and an adapter author outside this repository could not reach it. - `ApprovalClaim` and `ApprovalDecision`, for the same reason: `WorkflowDeps` asks for `sign(claim: ApprovalClaim)` and `verify`, and neither type was importable. - `Wire` and `wireOptionsFrom`, with their types `WireOptions`, `WireResult` and `Held`. They were exported from the stores barrel but omitted from the root, so a driver author could not reuse the Postgres wire framing. - `Project` and `Doc` are now documented as public rather than incidental: they are the type of `App.project`. - `LocalTool` and `ResolvedService` join `AgentPlan` and `Rung` at the root, so an `AgentPlan` — which a custom `WorkflowDeps.planFor` has to return — can be written down without unnameable fields.