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
2 changes: 1 addition & 1 deletion docs/content/docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ To read older entries, pass `before` to `conversation.entries(id, { maxEntryId:

## Your own actions and `c.pi`

Your own actions and lifecycle hooks get Pi Durable's `Harness` as `c.pi`. In `onSleep` and `onDestroy`, it's set only if Pi is already open. This action reports what the agent has spent on model calls:
Your own actions, lifecycle hooks, `run`, `onRequest`, `onWebSocket`, `onBeforeActionResponse`, and `onAnswer` get Pi Durable's `Harness` as `c.pi`. In `onSleep` and `onDestroy`, it's set only if Pi is already open. A `workflow()` body gets its own `ctx`, which has no `c.pi`. This action reports what the agent has spent on model calls:

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

Expand Down
130 changes: 130 additions & 0 deletions packages/pi/src/actor-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ import type {
ActionContext,
ActorConfigInput,
ActorDefinition,
BeforeActionResponseContext,
Conn,
ConnectContext,
DestroyContext,
DisconnectContext,
EventSchemaConfig,
QueueSchemaConfig,
RequestContext,
RunConfig,
RunContext,
SleepContext,
UniversalWebSocket,
WakeContext,
WebSocketContext,
} from "rivetkit";
import type { PiDatabaseProvider } from "./runtime.js";

Expand Down Expand Up @@ -71,6 +77,75 @@ export interface UserActions<
>;
}

/** The run handler, which gets `c.pi` through `TAccess`. */
type UserRunHandler<
TState,
TConnParams,
TConnState,
TVars,
TInput,
TEvents extends EventSchemaConfig,
TQueues extends QueueSchemaConfig,
TAccess,
> = (
c: RunContext<
TState,
TConnParams,
TConnState,
TVars,
TInput,
PiDatabaseProvider,
TEvents,
TQueues
> &
TAccess,
) => void | Promise<void>;

type UserRun<
TState,
TConnParams,
TConnState,
TVars,
TInput,
TEvents extends EventSchemaConfig,
TQueues extends QueueSchemaConfig,
TAccess,
> =
| UserRunHandler<
TState,
TConnParams,
TConnState,
TVars,
TInput,
TEvents,
TQueues,
TAccess
>
| (Omit<
RunConfig<
TState,
TConnParams,
TConnState,
TVars,
TInput,
PiDatabaseProvider,
TEvents,
TQueues
>,
"run"
> & {
run: UserRunHandler<
TState,
TConnParams,
TConnState,
TVars,
TInput,
TEvents,
TQueues,
TAccess
>;
});

/** Lifecycle hooks that get `c.pi` through `TAccess`. */
interface UserHooks<
TState,
Expand Down Expand Up @@ -167,6 +242,61 @@ interface UserHooks<
TQueues
>,
) => void | Promise<void>;
/** A function, or a `RunConfig` whose `run` gets `c.pi`. */
run?: UserRun<
TState,
TConnParams,
TConnState,
TVars,
TInput,
TEvents,
TQueues,
TAccess
>;
onBeforeActionResponse?: <Out>(
c: BeforeActionResponseContext<
TState,
TConnParams,
TConnState,
TVars,
TInput,
PiDatabaseProvider,
TEvents,
TQueues
> &
TAccess,
name: string,
args: unknown[],
output: Out,
) => Out | Promise<Out>;
onRequest?: (
c: RequestContext<
TState,
TConnParams,
TConnState,
TVars,
TInput,
PiDatabaseProvider,
TEvents,
TQueues
> &
TAccess,
request: Request,
) => Response | Promise<Response>;
onWebSocket?: (
c: WebSocketContext<
TState,
TConnParams,
TConnState,
TVars,
TInput,
PiDatabaseProvider,
TEvents,
TQueues
> &
TAccess,
websocket: UniversalWebSocket,
) => void | Promise<void>;
}

/**
Expand Down
62 changes: 50 additions & 12 deletions packages/pi/src/actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ import type {
UserActions,
UserActorConfig,
} from "./actor-types.js";
import type { PiAnswer } from "./answers.js";
import { withExtension } from "./registry.js";
import {
closeHarness,
createPiRuntime,
exposePi,
openOnWake,
PI_RUNTIME,
type PiContext,
Expand All @@ -36,7 +38,6 @@ import {
piStopping,
type ResolvedPiOptions,
withPiAccess,
withUnavailablePi,
} from "./runtime.js";
import { migratePiTables } from "./storage.js";
import {
Expand All @@ -60,10 +61,11 @@ const piEvents: PiEvents = {
};

/**
* `c.pi`: the actor's Pi Durable harness, in the app's own actions and hooks.
* `c.pi`: the actor's Pi Durable harness, in the app's own actions and hooks,
* `run`, `onRequest`, `onWebSocket`, `onBeforeActionResponse`, and `onAnswer`.
* Reading it throws when Pi Durable cannot open, such as after a rollback to
* an older schema. In `onSleep` and `onDestroy` it is set only when Pi Durable
* is already open in this actor generation.
* an older schema. In `onSleep` and `onDestroy` it is set only when Pi
* Durable is already open in this actor generation.
*/
export interface PiAccess {
readonly pi: Harness;
Expand Down Expand Up @@ -120,7 +122,7 @@ export type PiUserActions<
>;

/**
* The `c` of the app's Pi `tools` and `hooks`: the actor's
* The `c` of the app's Pi `tools`, `hooks`, and `onAnswer`: the actor's
* context with `c.pi`. They run in the background, with no connection.
*/
export type PiToolContext<
Expand All @@ -143,15 +145,25 @@ export type PiToolContext<
> &
PiAccess;

/** The Pi options with `tools` and `hooks` typed to get the actor's context. */
type PiConfigOptions<TContext, TTools> = Omit<PiOptions, "tools" | "hooks"> & {
/** The Pi options with `tools`, `hooks`, and `onAnswer` typed to get the actor's context. */
type PiConfigOptions<TContext, TTools> = Omit<
PiOptions,
"tools" | "hooks" | "onAnswer"
> & {
/**
* Tools defined like actions, by name. `execute(c, args, api, context)`
* gets the actor's context first, and `args` typed from `parameters`.
*/
tools?: { [K in keyof TTools]: PiTool<TContext, TTools[K] & object> };
/** Pi Durable's hooks with the actor's context first, such as `beforeTool(c, call, api, context)`. */
hooks?: PiHooks<TContext>;
/**
* Called with the actor's context for every final answer, such as to text
* it to the user. A run that resumes after a crash can call it again for
* the same answer if it didn't return. A throw goes to `onReport` and
* leaves the run as it is.
*/
onAnswer?: (c: TContext, answer: PiAnswer) => void | Promise<void>;
};

/** Ordinary actor config plus the Pi Durable options. The app's actions, lifecycle hooks, Pi tools, and Pi hooks get `c.pi`. */
Expand Down Expand Up @@ -280,6 +292,29 @@ export function pi<
withPiAccess(c, piOptions, () => hook(c, ...args), {
opensHarness,
}));
// `onWake` opens Pi Durable before `run` starts, so `run` only needs the
// getter. It is not a counted call: one that lasts for the whole generation
// would hold every sleep's drain until its deadline.
const exposingPi = (run: (c: PiContext) => unknown) => (c: PiContext) => {
exposePi(c);
return run(c);
};
// A workflow's run function carries its config on symbol keys, so the wrapper keeps them.
const withPiRun = (run: unknown) => {
if (typeof run === "function") {
const wrapped = exposingPi(run as (c: PiContext) => unknown);
for (const key of Object.getOwnPropertySymbols(run)) {
Object.defineProperty(
wrapped,
key,
Object.getOwnPropertyDescriptor(run, key) as PropertyDescriptor,
);
}
return wrapped;
}
const config = run as { run?: (c: PiContext) => unknown } | undefined;
return config?.run ? { ...config, run: exposingPi(config.run) } : run;
};
const userOnWake = actorConfig.onWake;
const userOnDisconnect = withPi(actorConfig.onDisconnect);

Expand Down Expand Up @@ -316,25 +351,28 @@ export function pi<
msg: "pi durable could not open on wake; actions will retry",
error,
});
return withUnavailablePi(c, error, () => userOnWake?.(c));
exposePi(c);
return userOnWake?.(c);
}
Object.defineProperty(c, "pi", { value: harness, configurable: true });
try {
await userOnWake?.(c);
} finally {
harness.resume();
}
},
run: withPiRun(actorConfig.run),
onBeforeActionResponse: withPi(actorConfig.onBeforeActionResponse),
onRequest: withPi(actorConfig.onRequest),
onWebSocket: withPi(actorConfig.onWebSocket),
onConnect: withPi(actorConfig.onConnect),
onDisconnect: async (c: PiContext, conn: { id: string }) => {
// Shutdown runs onDisconnect in the same window as onSleep and
// onDestroy, in no set order, and those close Pi Durable. So a
// disconnect during shutdown never uses Pi, and its watches end when
// the harness closes.
if (c.abortSignal.aborted || piRuntime(c).status !== "open") {
await withUnavailablePi(c, piStopping(), () =>
actorConfig.onDisconnect?.(c, conn),
);
exposePi(c, piStopping());
await actorConfig.onDisconnect?.(c, conn);
return;
}
try {
Expand Down
9 changes: 5 additions & 4 deletions packages/pi/src/answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
hook,
type RegistryReader,
} from "@earendil-works/pi-durable";
import type { PiAccess } from "./actor.js";
import { withExtension } from "./registry.js";
import type { PiContext } from "./runtime.js";

Expand All @@ -21,9 +22,9 @@ export interface PiAnswer {
message: AssistantMessage;
}

/** Called with the actor's context for every final answer. */
/** Called with the actor's context, which has `c.pi`, for every final answer. */
export type PiOnAnswer = (
c: PiContext,
c: PiContext & PiAccess,
answer: PiAnswer,
) => void | Promise<void>;

Expand All @@ -38,15 +39,15 @@ export const ANSWER_EXTENSION = "rivet-pi-on-answer";
*/
export function withAnswerHook(
options: { registry: RegistryReader; settings?: HarnessSettings },
c: PiContext,
c: PiContext & PiAccess,
onAnswer: PiOnAnswer,
report: (error: unknown) => void,
): { registry: RegistryReader; settings?: HarnessSettings } {
return withExtension(options, answerExtension(c, onAnswer, report));
}

function answerExtension(
c: PiContext,
c: PiContext & PiAccess,
onAnswer: PiOnAnswer,
report: (error: unknown) => void,
): Extension {
Expand Down
Loading
Loading