Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion docs/content/docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,17 @@ Your own actions and lifecycle hooks get Pi Durable's `Harness` as `c.pi`. In `o

<CodeSnippet file="examples/docs/pi/cost.ts" title="server.ts" />

### Tools and hooks with the Actor's context

Define tools in `tools` and hooks in `hooks`, keyed by name, the way you define actions. Each gets the Actor's context as `c` first, so a tool can read the agent's key, use its database and `c.pi`, and call other Actors:

<CodeSnippet file="examples/docs/pi/actor-tools.ts" title="server.ts" />

- A tool's `execute(c, args, api, context)` takes the rest of Pi Durable's `defineTool` fields, such as `replay`. The key in `tools` is its name, and `args` are typed from `parameters`.
- Every Pi Durable hook works, with `c` first, such as `beforeTool(c, call, api, context)` and `onYield(c, answer, api, context)`.
- `c` has no connection. Tools and hooks run in the background, also after a wake and in conversations a tool creates.
- They are installed as the extension `rivet-pi-actor`, which conversations that use the default extensions get. You can still pass a `registry` for other extensions.

### Keep app state in a document

A <a href="https://github.com/earendil-works/pi/blob/main/packages/durable/README.md#your-own-state" target="_blank" rel="noopener noreferrer">document</a> is typed state saved with the conversation. Change it inside `c.pi.commit`, and read it with `c.pi.snapshot`:
Expand Down Expand Up @@ -665,7 +676,9 @@ The `pi()` function accepts every [`actor()`](/actors/docs/actor-configuration)

| Option | Description |
| --- | --- |
| `registry` | Required. Your tools and tasks, from `createRegistry()`. See [Bundle Tools and Hooks into Extensions](/guides/pi-extensions). |
| `tools` | Tools that get the Actor's context. See [Tools and hooks with the Actor's context](#tools-and-hooks-with-the-actors-context). |
| `hooks` | Pi Durable hooks that get the Actor's context. |
| `registry` | Extensions with your tools, sections, and tasks, from `createRegistry()`. See [Bundle Tools and Hooks into Extensions](/guides/pi-extensions). |
| `model` | Starting model of new conversations, as `provider/modelId`. |
| `scopedModels` | Models a client may switch to. |
| `apiKeys` | API keys by provider. See [Keys in code](#keys-in-code). |
Expand Down
58 changes: 58 additions & 0 deletions examples/docs/pi/actor-tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { num, obj, str } from "@earendil-works/pi-schema";
import { pi } from "@rivet-dev/pi";
import { actor, setup } from "rivetkit";
import { db } from "rivetkit/db";

// Another actor the agent's tool calls.
const payments = actor({
db: db({
onMigrate: async (db) => {
await db.execute("CREATE TABLE IF NOT EXISTS refunds (order_id TEXT NOT NULL, amount REAL NOT NULL)");
},
}),
actions: {
refund: async (c, orderId: string, amount: number) => {
await c.db.execute("INSERT INTO refunds (order_id, amount) VALUES (?, ?)", orderId, amount);
},
},
});

// The agent's own table, in its database next to Pi Durable's.
const FREEZES = "CREATE TABLE IF NOT EXISTS refund_freezes (frozen_at INTEGER NOT NULL)";

// One agent per customer, keyed by their email.
const support = pi({
model: "anthropic/claude-opus-5-5",
onWake: async (c) => {
await c.db.execute(FREEZES);
},
tools: {
refund: {
description: "Refund an order, in dollars.",
parameters: obj({ orderId: str(), amount: num() }),
// `c` is the agent's context: its key, database, vars, and other actors.
execute: async (c, args) => {
const [email] = c.key;
await c.client<typeof registry>().payments.getOrCreate([email]).refund(args.orderId, args.amount);
return { output: [{ type: "text", text: `Refunded $${args.amount} for ${args.orderId}.` }] };
},
},
},
hooks: {
// Hooks get the agent's context first too.
beforeTool: async (c, call) => {
if (call.name !== "refund") return undefined;
const freezes = await c.db.execute("SELECT 1 FROM refund_freezes LIMIT 1");
return freezes.length > 0 ? { block: "Refunds are frozen for this customer." } : undefined;
},
},
actions: {
freezeRefunds: async (c) => {
await c.db.execute("INSERT INTO refund_freezes (frozen_at) VALUES (?)", Date.now());
},
},
});

export const registry = setup({ use: { support, payments } });

registry.start();
6 changes: 3 additions & 3 deletions packages/pi/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import { assertModelAllowed } from "./models.js";
import type { PiContext } from "./runtime.js";
import {
documentsByKind,
type PiOptions,
piRuntime,
type ResolvedPiOptions,
resumeDueSleeps,
type Waiting,
withHarness,
Expand Down Expand Up @@ -117,7 +117,7 @@ export type PiActions = ReturnType<typeof createPiActions>;
* the same names. Ids replace objects, and conversation methods take the
* conversation id first. `prompt` is the one convenience action.
*/
export function createPiActions(options: PiOptions) {
export function createPiActions(options: ResolvedPiOptions) {
const documents = documentsByKind(options);
const run = <T>(
c: PiContext,
Expand Down Expand Up @@ -546,7 +546,7 @@ async function requireTask(
* is rejected.
*/
function resolveAgentChange(
options: PiOptions,
options: ResolvedPiOptions,
change: PiAgentChange,
): AgentChange {
const snapshot = options.registry.snapshot();
Expand Down
128 changes: 128 additions & 0 deletions packages/pi/src/actor-tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import type { Context, JsonValue } from "@earendil-works/chord";
import { createContextKey } from "@earendil-works/chord/context";
import {
type AnyTask,
type CompactionHooks,
CompactionTask,
defineExtension,
type Extension,
type GenerationHooks,
GenerationTask,
type HookRegistration,
type ToolExecutionApi,
type ToolExecutionResult,
type ToolHooks,
type ToolRegistration,
ToolTask,
} from "@earendil-works/pi-durable";
import type { PiContext } from "./runtime.js";

/** The extension that holds the app's `tools` and `hooks`. Conversations that use the default selection get it. */
export const ACTOR_EXTENSION = "rivet-pi-actor";

/**
* The actor's context, carried by the context the harness opens with. Pi
* derives the context of every task from it, so a tool or hook finds the
* actor it runs in, also after a wake and in conversations a tool creates.
*/
export const PI_ACTOR_CONTEXT = createContextKey<PiContext>(
"@rivet-dev/pi/actor-context",
);

/** The arguments a tool with parameter schema `TParameters` gets. */
type ToolArgs<TParameters extends object> = Parameters<
ToolRegistration<TParameters>["execute"]
>[0];

/**
* A tool defined like an action: Pi Durable's `ToolRegistration` without
* `name`, which is its key in `tools`, and with the actor's context as the
* first argument of `execute`. `args` are typed from `parameters`.
*/
export type PiTool<
TContext,
TParameters extends object = any,
TDetails extends JsonValue = JsonValue,
> = Omit<ToolRegistration<TParameters, TDetails>, "name" | "execute"> & {
execute(
c: TContext,
args: ToolArgs<TParameters>,
api: ToolExecutionApi<TDetails>,
context: Context,
): ToolExecutionResult<TDetails> | Promise<ToolExecutionResult<TDetails>>;
};

type AllHooks = GenerationHooks & ToolHooks & CompactionHooks;

/** Pi Durable's hooks, each with the actor's context as its first argument, such as `beforeTool(c, call, api, context)`. */
export type PiHooks<TContext> = {
[K in keyof AllHooks]?: (
c: TContext,
...args: Parameters<AllHooks[K]>
) => ReturnType<AllHooks[K]>;
};

/** The task each hook belongs to. Hook names are unique across Pi Durable's built-in tasks. */
const HOOK_TASKS: Record<keyof AllHooks, AnyTask> = {
beforeRequest: GenerationTask,
beforeProviderRequest: GenerationTask,
afterResponse: GenerationTask,
onYield: GenerationTask,
afterTools: GenerationTask,
afterRun: GenerationTask,
beforeTool: ToolTask,
afterTool: ToolTask,
beforeCompact: CompactionTask,
};

/** The extension that runs the app's `tools` and `hooks` with the actor's context, or none when there are neither. */
export function actorExtension(
tools: Record<string, PiTool<PiContext>> = {},
hooks: PiHooks<PiContext> = {},
): Extension | undefined {
const toolNames = Object.keys(tools);
const hookNames = Object.keys(hooks) as (keyof AllHooks)[];
if (toolNames.length === 0 && hookNames.length === 0) return undefined;

// By task name, as `hook()` registers them.
const handlers = new Map<string, Record<string, unknown>>();
for (const name of hookNames) {
const handler = hooks[name] as
| ((c: PiContext, ...args: unknown[]) => unknown)
| undefined;
if (!handler) continue;
const task = HOOK_TASKS[name]?.definition.name;
if (!task) throw new Error(`pi() hooks: ${name} is not a Pi Durable hook`);
const forTask = handlers.get(task) ?? {};
// Every hook takes the context last.
forTask[name] = (...args: unknown[]) =>
handler(actorOf(args.at(-1) as Context), ...args);
handlers.set(task, forTask);
}

return defineExtension({
name: ACTOR_EXTENSION,
tools: toolNames.map((name) => {
const { execute, ...tool } = tools[name] as PiTool<PiContext>;
return {
...tool,
name,
execute: async (args, api, context) =>
execute(actorOf(context), args, api, context),
};
}),
hooks: [...handlers].map(
([task, forTask]): HookRegistration => ({ task, handlers: forTask }),
),
});
}

function actorOf(context: Context): PiContext {
const c = context.value(PI_ACTOR_CONTEXT);
if (!c) {
throw new Error(
"pi() tools and hooks run only in the harness of the pi() actor that defines them",
);
}
return c;
}
Loading
Loading