@rivet-dev/pi 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/actions.d.ts +188 -77
  2. package/dist/actions.d.ts.map +1 -1
  3. package/dist/actions.js +276 -101
  4. package/dist/actions.js.map +1 -1
  5. package/dist/actor-config.d.ts +1 -2
  6. package/dist/actor-config.d.ts.map +1 -1
  7. package/dist/actor-config.js +1 -2
  8. package/dist/actor-config.js.map +1 -1
  9. package/dist/actor-sqlite.d.ts.map +1 -0
  10. package/dist/actor-sqlite.js.map +1 -0
  11. package/dist/actor.d.ts +21 -17
  12. package/dist/actor.d.ts.map +1 -1
  13. package/dist/actor.js +62 -34
  14. package/dist/actor.js.map +1 -1
  15. package/dist/credentials.d.ts +3 -4
  16. package/dist/credentials.d.ts.map +1 -1
  17. package/dist/credentials.js +11 -39
  18. package/dist/credentials.js.map +1 -1
  19. package/dist/drain.d.ts +1 -1
  20. package/dist/drain.js +1 -1
  21. package/dist/durable.d.ts +24 -0
  22. package/dist/durable.d.ts.map +1 -0
  23. package/dist/durable.js +5 -0
  24. package/dist/durable.js.map +1 -0
  25. package/dist/errors.d.ts.map +1 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/index.d.ts +4 -3
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/models.d.ts +4 -35
  31. package/dist/models.d.ts.map +1 -1
  32. package/dist/models.js +0 -70
  33. package/dist/models.js.map +1 -1
  34. package/dist/runtime.d.ts +84 -81
  35. package/dist/runtime.d.ts.map +1 -1
  36. package/dist/runtime.js +394 -406
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/storage.d.ts +27 -45
  39. package/dist/storage.d.ts.map +1 -1
  40. package/dist/storage.js +28 -99
  41. package/dist/storage.js.map +1 -1
  42. package/dist/tracing.d.ts +4 -9
  43. package/dist/tracing.d.ts.map +1 -1
  44. package/dist/tracing.js +4 -40
  45. package/dist/tracing.js.map +1 -1
  46. package/dist/{durable/watches.d.ts → watches.d.ts} +1 -1
  47. package/dist/watches.d.ts.map +1 -0
  48. package/dist/{durable/watches.js → watches.js} +1 -1
  49. package/dist/watches.js.map +1 -0
  50. package/package.json +10 -18
  51. package/dist/durable/actions.d.ts +0 -192
  52. package/dist/durable/actions.d.ts.map +0 -1
  53. package/dist/durable/actions.js +0 -289
  54. package/dist/durable/actions.js.map +0 -1
  55. package/dist/durable/actor-sqlite.d.ts.map +0 -1
  56. package/dist/durable/actor-sqlite.js.map +0 -1
  57. package/dist/durable/actor.d.ts +0 -36
  58. package/dist/durable/actor.d.ts.map +0 -1
  59. package/dist/durable/actor.js +0 -107
  60. package/dist/durable/actor.js.map +0 -1
  61. package/dist/durable/env.d.ts +0 -13
  62. package/dist/durable/env.d.ts.map +0 -1
  63. package/dist/durable/env.js +0 -178
  64. package/dist/durable/env.js.map +0 -1
  65. package/dist/durable/errors.d.ts.map +0 -1
  66. package/dist/durable/errors.js.map +0 -1
  67. package/dist/durable/index.d.ts +0 -5
  68. package/dist/durable/index.d.ts.map +0 -1
  69. package/dist/durable/index.js +0 -2
  70. package/dist/durable/index.js.map +0 -1
  71. package/dist/durable/runtime.d.ts +0 -92
  72. package/dist/durable/runtime.d.ts.map +0 -1
  73. package/dist/durable/runtime.js +0 -435
  74. package/dist/durable/runtime.js.map +0 -1
  75. package/dist/durable/storage.d.ts +0 -31
  76. package/dist/durable/storage.d.ts.map +0 -1
  77. package/dist/durable/storage.js +0 -53
  78. package/dist/durable/storage.js.map +0 -1
  79. package/dist/durable/watches.d.ts.map +0 -1
  80. package/dist/durable/watches.js.map +0 -1
  81. package/dist/sandbox.d.ts +0 -27
  82. package/dist/sandbox.d.ts.map +0 -1
  83. package/dist/sandbox.js +0 -224
  84. package/dist/sandbox.js.map +0 -1
  85. /package/dist/{durable/actor-sqlite.d.ts → actor-sqlite.d.ts} +0 -0
  86. /package/dist/{durable/actor-sqlite.js → actor-sqlite.js} +0 -0
  87. /package/dist/{durable/errors.d.ts → errors.d.ts} +0 -0
  88. /package/dist/{durable/errors.js → errors.js} +0 -0
package/dist/runtime.js CHANGED
@@ -1,23 +1,25 @@
1
- import { isAbsolute } from "node:path";
2
- import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { AgentDoc, configure, Harness, } from "@earendil-works/pi-durable";
3
+ import { SqliteStorage } from "@earendil-works/pi-durable/storage/sqlite";
4
+ import { databaseEnv, sandboxEnv } from "@rivet-dev/sandbox-adapter/pi";
3
5
  import { UserError } from "rivetkit";
6
+ import { actorSqlite } from "./actor-sqlite.js";
4
7
  import { SourceCredentialStore } from "./credentials.js";
5
- import { createActorModelRuntime, emptyCredentialStore, openingModel, } from "./models.js";
6
- import { createSandboxBashOperations, createSandboxTools } from "./sandbox.js";
7
- import { appendPiEntry, createPiSession, loadPiInterruptedRun, loadPiSandbox, loadPiSession, migratePiSession, savePiIdle, savePiRunning, savePiSandbox, savePiSettings, toFileEntries, } from "./storage.js";
8
- function lazySandbox(c, provider) {
9
- const lazy = {
10
- current: undefined,
11
- connect: () => (lazy.current ??= connectSandbox(c, provider).catch((error) => {
12
- lazy.current = undefined;
13
- throw error;
14
- })),
15
- };
16
- return lazy;
17
- }
8
+ import { toClientError } from "./errors.js";
9
+ import { createActorModelRuntime, emptyCredentialStore, } from "./models.js";
10
+ import { loadPiSandbox, savePiSandbox } from "./storage.js";
11
+ import { createConnectionWatches, reattachWatches, stopAllWatches, } from "./watches.js";
12
+ /**
13
+ * One minute, as in Cloudflare's Pi harness. A retry or poll wait longer than
14
+ * this lets the actor sleep, and a scheduled wake reopens Pi Durable at the
15
+ * deadline.
16
+ */
17
+ const LONG_WAIT_MS = 60_000;
18
+ /** The internal action a scheduled wake calls. */
19
+ const WAKE_ACTION = "pi.wake";
18
20
  export const PI_RUNTIME = Symbol.for("@rivet-dev/pi/runtime");
19
21
  export function createPiRuntime() {
20
- return { writes: Promise.resolve(), closing: false };
22
+ return { closing: false, watches: createConnectionWatches() };
21
23
  }
22
24
  export function piRuntime(c) {
23
25
  const runtime = c.vars?.[PI_RUNTIME];
@@ -26,466 +28,460 @@ export function piRuntime(c) {
26
28
  }
27
29
  return runtime;
28
30
  }
29
- /** Returns the actor's Pi session, opening it from SQLite on first use. */
30
- export function ensurePiSession(c, options) {
31
+ /**
32
+ * Opens the harness on wake without resuming interrupted work, so the app's
33
+ * `onWake` runs first. The caller calls `harness.resume()` after it. The wake
34
+ * context becomes the context of all background work.
35
+ */
36
+ export async function openOnWake(c, options) {
37
+ piRuntime(c).actor = c;
38
+ return ensureHarness(c, options, { resume: false });
39
+ }
40
+ /** Returns the actor's Pi Durable harness, opening it from SQLite on first use. */
41
+ async function ensureHarness(c, options, open = { resume: true }) {
31
42
  const runtime = piRuntime(c);
32
- if (runtime.closing) {
33
- return Promise.reject(sessionClosed());
43
+ if (runtime.closing)
44
+ throw harnessClosed();
45
+ runtime.harness ??= openHarness(runtime.actor ?? c, runtime, options, open).catch((error) => {
46
+ runtime.harness = undefined;
47
+ throw toClientError(error);
48
+ });
49
+ return (await runtime.harness).harness;
50
+ }
51
+ /**
52
+ * Runs an action against the harness. A failed call that left Pi Durable
53
+ * unusable reopens it before the error reaches the client, so the next call
54
+ * works. Calls use `BACKGROUND_CONTEXT`, so a wait such as `prompt` lasts
55
+ * until the run settles or the action times out, including while a stopping
56
+ * actor drains the run. RivetKit's action signal also fires when the actor
57
+ * starts to stop, so it cannot cancel a wait.
58
+ */
59
+ export async function withHarness(c, options, run) {
60
+ const harness = await ensureHarness(c, options);
61
+ try {
62
+ return await run(harness, BACKGROUND_CONTEXT);
34
63
  }
35
- if (!runtime.ready) {
36
- runtime.ready = openPiSession(c, runtime, options).catch((error) => {
37
- runtime.ready = undefined;
38
- throw error;
39
- });
64
+ catch (error) {
65
+ const runtime = piRuntime(c);
66
+ await recoverHarness(runtime.actor ?? c, runtime, options);
67
+ throw toClientError(error);
40
68
  }
41
- return runtime.ready;
42
69
  }
43
70
  /**
44
- * Runs the app's own action or hook with `c.pi` set to the session, then
45
- * saves what it changed, such as the model, as the built-in actions do. Code
46
- * that never reads `c.pi` runs even when the session cannot open; reading
47
- * `c.pi` throws the open error. Shutdown hooks pass `opensSession: false`, so
48
- * they use a session that is already open and never create a session or a
49
- * sandbox only to close it.
71
+ * Runs one of the app's own actions or hooks with the harness on `c.pi`. A
72
+ * failure that left Pi Durable unusable reopens it. The error reaches the
73
+ * client as from a built-in action. Code that never reads `c.pi` runs even
74
+ * when Pi Durable is closed or cannot open; reading `c.pi` throws the cause.
75
+ * Shutdown hooks pass `opensHarness: false`, so they use a harness that is
76
+ * already open and never open and resume one only to close it.
50
77
  */
51
- export async function withPiSession(c, options, body, { opensSession = true } = {}) {
78
+ export async function withPiAccess(c, options, body, { opensHarness = true } = {}) {
52
79
  const runtime = piRuntime(c);
53
- // Hooks such as onDisconnect still run after the session closed; only using c.pi fails.
80
+ // Hooks such as onDisconnect still run after Pi Durable closed; only using c.pi fails.
54
81
  if (runtime.closing)
55
- return withUnavailablePi(c, sessionClosed(), body);
56
- if (!opensSession && !runtime.ready) {
57
- return withUnavailablePi(c, sessionNotOpen(), body);
82
+ return withUnavailablePi(c, harnessClosed(), body);
83
+ if (!opensHarness && !runtime.harness) {
84
+ return withUnavailablePi(c, harnessNotOpen(), body);
58
85
  }
59
- let handle;
86
+ let harness;
60
87
  try {
61
- handle = await ensurePiSession(c, options);
88
+ harness = await ensureHarness(c, options);
62
89
  }
63
90
  catch (error) {
64
91
  c.log.warn({
65
- msg: "pi session could not open; reading c.pi throws this error",
92
+ msg: "pi durable could not open; reading c.pi throws this error",
66
93
  error,
67
94
  });
68
95
  return withUnavailablePi(c, error, body);
69
96
  }
70
- Object.defineProperty(c, "pi", { value: handle.session, configurable: true });
71
- let result;
97
+ Object.defineProperty(c, "pi", { value: harness, configurable: true });
72
98
  try {
73
- result = await body();
99
+ return await body();
74
100
  }
75
101
  catch (error) {
76
- await persistPiState(c, handle).catch((writeError) => {
77
- c.log.error({
78
- msg: "pi state write failed after an app action error",
79
- error: writeError,
80
- });
81
- });
82
- throw error;
102
+ await recoverHarness(runtime.actor ?? c, runtime, options);
103
+ throw toClientError(error);
83
104
  }
84
- await persistPiState(c, handle);
85
- return result;
86
105
  }
87
- /** Runs `body` with a `c.pi` that throws `error` when read. */
88
- export function withUnavailablePi(c, error, body) {
89
- Object.defineProperty(c, "pi", {
90
- get: () => {
91
- throw error;
92
- },
93
- configurable: true,
94
- });
95
- return body();
106
+ function harnessNotOpen() {
107
+ return new UserError("Pi Durable is not open in this actor generation, so this shutdown hook cannot use c.pi.");
96
108
  }
97
- function sessionNotOpen() {
98
- return new UserError("The Pi session is not open in this actor generation, so this shutdown hook cannot use c.pi.");
109
+ function harnessClosed() {
110
+ return new UserError("Pi Durable is closed because the actor is stopping.");
99
111
  }
100
- function sessionClosed() {
101
- return new UserError("The Pi session is closed because the actor is stopping.");
112
+ async function openHarness(c, runtime, options, open = { resume: true }) {
113
+ const storage = await SqliteStorage.open(actorSqlite(c.db));
114
+ const now = options.now ?? Date.now;
115
+ const harness = await Harness.open(storage, {
116
+ models: options.models ?? (await createModels(c, options)),
117
+ registry: options.registry,
118
+ settings: options.settings,
119
+ env: options.env ??
120
+ (options.sandbox
121
+ ? sandboxEnvBuilder(c, runtime, options.sandbox)
122
+ : (target) => databaseEnv(c.db, {
123
+ id: `pi-files:${c.actorId}`,
124
+ cwd: target.cwd,
125
+ })),
126
+ conversationCreated: startingAgent(options),
127
+ now: options.now,
128
+ onReport: (error) => {
129
+ // A commit that failed after storage admitted it leaves Pi Durable
130
+ // unusable. Background work reports it here, with no action to catch it.
131
+ queueMicrotask(() => void recoverHarness(c, runtime, options));
132
+ options.onReport?.(error);
133
+ },
134
+ }, BACKGROUND_CONTEXT);
135
+ reportBlockedTasks(c, await harness.inspect(BACKGROUND_CONTEXT));
136
+ if (open.resume)
137
+ harness.resume();
138
+ const isBusy = async () => busyState(await harness.inspect(BACKGROUND_CONTEXT), now(), LONG_WAIT_MS)
139
+ .kind === "busy";
140
+ const stopBusyWatch = watchBusy(c, harness, now, LONG_WAIT_MS);
141
+ await reattachWatches(c, runtime.watches, harness, documentsByKind(options));
142
+ return { harness, stopBusyWatch, isBusy };
102
143
  }
103
- /** Pi's built-in tools, which all run on the actor host. */
104
- const PI_BUILT_IN_TOOLS = [
105
- "read",
106
- "bash",
107
- "powershell",
108
- "edit",
109
- "write",
110
- "grep",
111
- "find",
112
- "ls",
113
- ];
114
- async function openPiSession(c, runtime, options) {
115
- const { settings, sandbox: sandboxProvider, providers, apiKeys, model, scopedModels, credentials: credentialSource, ...sessionOptions } = options;
116
- const loaded = await loadPiSession(c.db);
117
- const stored = loaded && (await migratePiSession(c.db, loaded));
118
- const sandbox = sandboxProvider ? lazySandbox(c, sandboxProvider) : undefined;
119
- // A new session takes its working directory from the sandbox, so only its first open connects.
120
- const firstSandbox = sandbox && !stored ? (await sandbox.connect()).sandbox : undefined;
121
- const cwd = firstSandbox?.cwd ?? stored?.cwd ?? sessionOptions.cwd ?? process.cwd();
122
- if (!isAbsolute(cwd)) {
123
- throw new Error(`pi() cwd must be an absolute path, received ${cwd}`);
144
+ /** App documents by `kind`, for clients that name a document. */
145
+ export function documentsByKind(options) {
146
+ return new Map((options.documents ?? []).map((doc) => [doc.definition.kind, doc]));
147
+ }
148
+ /** Pi Durable refuses every call once a commit failed after storage admitted it. */
149
+ function isUsable(harness) {
150
+ try {
151
+ harness.subscribeClose(() => { })();
152
+ return true;
124
153
  }
125
- const connect = sandbox && (async () => (await sandbox.connect()).sandbox);
126
- const settingsManager = SettingsManager.inMemory(stored?.settings ?? settings ?? {});
127
- const sessionManager = stored
128
- ? SessionManager.inMemory(cwd, undefined, toFileEntries(stored))
129
- : SessionManager.inMemory(cwd);
130
- const credentials = credentialSource
131
- ? new SourceCredentialStore(credentialSource(c))
132
- : undefined;
133
- const modelRuntime = await createActorModelRuntime({ providers, apiKeys }, credentials ?? emptyCredentialStore);
134
- const resourceLoader = sessionOptions.resourceLoader ??
135
- (await isolatedResourceLoader(cwd, sessionOptions.agentDir, settingsManager));
136
- const { session, modelFallbackMessage } = await createAgentSession({
137
- ...sessionOptions,
138
- cwd,
139
- modelRuntime,
140
- model: openingModel({ model, scopedModels }, modelRuntime, sessionManager.buildSessionContext().model),
141
- settingsManager,
142
- sessionManager,
143
- resourceLoader,
144
- customTools: connect
145
- ? [
146
- ...(sessionOptions.customTools ?? []),
147
- ...createSandboxTools(cwd, connect),
148
- ]
149
- : sessionOptions.customTools,
150
- excludeTools: [
151
- ...new Set([
152
- ...(sessionOptions.excludeTools ?? []),
153
- ...(sandbox ? ["powershell"] : PI_BUILT_IN_TOOLS),
154
- ]),
155
- ],
156
- });
157
- if (modelFallbackMessage) {
158
- c.log.warn({ msg: "pi model fallback", detail: modelFallbackMessage });
154
+ catch {
155
+ return false;
159
156
  }
160
- const handle = {
161
- session,
162
- settingsManager,
163
- cwd,
164
- sandbox,
165
- bashOperations: connect
166
- ? createSandboxBashOperations(cwd, connect)
167
- : undefined,
168
- persistedSettings: JSON.stringify(settingsManager.getGlobalSettings()),
169
- persistedEntryCount: stored?.entries.length ?? 0,
170
- credentials,
171
- };
172
- if (!stored) {
173
- const header = sessionManager.getHeader();
174
- if (!header) {
175
- throw new Error("Pi did not create a session header");
176
- }
177
- await createPiSession(c.db, {
178
- header,
179
- cwd,
180
- settings: JSON.parse(handle.persistedSettings),
181
- });
157
+ }
158
+ /** Closes and reopens a harness that Pi Durable refuses to use. The reopened harness resumes from storage. */
159
+ async function recoverHarness(c, runtime, options) {
160
+ const current = runtime.harness;
161
+ if (!current || runtime.closing)
162
+ return;
163
+ let open;
164
+ try {
165
+ open = await current;
182
166
  }
183
- await flushPiEntries(c, runtime, handle);
184
- session.subscribe((event) => {
185
- broadcastSessionEvent(c, event);
186
- if (!isStreamingDelta(event)) {
187
- flushPiEntries(c, runtime, handle).catch((error) => {
188
- c.log.error({
189
- msg: "pi session entry write failed, retrying on the next flush",
190
- error,
191
- });
192
- });
193
- }
194
- // The run state tells the next wake whether a run was cut off.
195
- if (event.type === "agent_start" ||
196
- (event.type === "queue_update" && session.isStreaming)) {
197
- void writeInOrder(c, runtime, () => savePiRunning(c.db, queuedMessages(session)));
198
- }
199
- else if (event.type === "agent_settled") {
200
- void writeInOrder(c, runtime, () => savePiIdle(c.db));
201
- }
167
+ catch {
168
+ return;
169
+ }
170
+ if (runtime.harness !== current || runtime.closing || isUsable(open.harness))
171
+ return;
172
+ c.log.warn({
173
+ msg: "pi durable stopped after a failed commit, reopening it from storage",
202
174
  });
203
- c.log.info({
204
- msg: "pi session opened",
205
- sessionId: session.sessionId,
206
- restored: stored !== undefined,
207
- entryCount: sessionManager.getEntries().length,
208
- messageCount: session.messages.length,
175
+ const reopened = (async () => {
176
+ await closeOpenHarness(open, runtime.watches);
177
+ return openHarness(c, runtime, options);
178
+ })().catch((error) => {
179
+ if (runtime.harness === reopened)
180
+ runtime.harness = undefined;
181
+ c.log.error({
182
+ msg: "pi durable could not reopen after a failed commit",
183
+ error,
184
+ });
185
+ throw toClientError(error);
209
186
  });
210
- return handle;
187
+ runtime.harness = reopened;
188
+ await reopened.catch(() => { });
211
189
  }
212
- /**
213
- * Connects to the actor's sandbox, creating one when none is stored or the
214
- * provider reports the stored one no longer exists. A new sandbox id is saved
215
- * as soon as `create` returns, so a failure later in the start reuses it. Any
216
- * other connect failure is thrown, so a temporary outage never replaces a
217
- * sandbox. `pi()` and `piDurable()` both store the id in `pi_sandbox`.
218
- */
219
- export async function connectSandbox(c, provider) {
220
- const existing = await loadPiSandbox(c.db);
221
- if (existing && existing.provider !== provider.name) {
222
- throw new Error(`pi sandbox was created by provider ${existing.provider}, but the actor now uses ${provider.name}`);
223
- }
224
- if (existing) {
225
- const sandbox = await provider.connect(c, existing.id);
226
- if (sandbox)
227
- return { provider, id: existing.id, sandbox };
228
- c.log.warn({
229
- msg: "pi sandbox no longer exists, creating a new one; files from the previous sandbox are lost",
230
- provider: provider.name,
231
- sandboxId: existing.id,
232
- });
233
- }
234
- const id = await provider.create(c);
235
- await savePiSandbox(c.db, { provider: provider.name, id });
236
- const sandbox = await provider.connect(c, id);
237
- if (!sandbox) {
238
- throw new Error(`pi sandbox ${provider.name}/${id} was not found right after it was created`);
239
- }
240
- return { provider, id, sandbox };
190
+ async function closeOpenHarness(open, watches) {
191
+ open.stopBusyWatch();
192
+ await stopAllWatches(watches);
193
+ await open.harness.close(BACKGROUND_CONTEXT);
241
194
  }
242
- /**
243
- * Pi's resource discovery reads the actor host's filesystem and loads host
244
- * code as extensions. Extensions, skills, prompt templates, context files, and
245
- * themes stay off unless the developer passes a loader.
246
- */
247
- async function isolatedResourceLoader(cwd, agentDir, settingsManager) {
248
- const loader = new DefaultResourceLoader({
249
- cwd,
250
- agentDir: agentDir ?? getAgentDir(),
251
- settingsManager,
252
- noExtensions: true,
253
- noSkills: true,
254
- noPromptTemplates: true,
255
- noContextFiles: true,
256
- noThemes: true,
257
- });
258
- await loader.reload();
259
- return loader;
195
+ async function createModels(c, options) {
196
+ const credentials = options.credentials
197
+ ? new SourceCredentialStore(options.credentials(c))
198
+ : emptyCredentialStore;
199
+ return createActorModelRuntime({ providers: options.providers, apiKeys: options.apiKeys }, credentials);
260
200
  }
261
- /** Token and output deltas never append entries, so they skip the entry diff. */
262
- function isStreamingDelta(event) {
263
- return (event.type === "message_update" ||
264
- event.type === "tool_execution_update" ||
265
- event.type === "bash_execution_update");
201
+ /** Parses `provider/modelId`. */
202
+ export function parseModelRef(name) {
203
+ const slash = name.indexOf("/");
204
+ if (slash <= 0 || slash === name.length - 1) {
205
+ throw new Error(`pi() model must be provider/modelId, received ${name}`);
206
+ }
207
+ return { provider: name.slice(0, slash), modelId: name.slice(slash + 1) };
266
208
  }
267
209
  /**
268
- * Writes every entry Pi appended since the last successful write, in append
269
- * order. The count only advances after an insert succeeds, so a failed write
270
- * is retried by the next flush. Returns the write so actions can await it.
210
+ * `model` and `thinkingLevel` start every new conversation: root, created, and
211
+ * forked. A fork already has its parent's agent, so it keeps it. The app's own
212
+ * `conversationCreated` runs after this.
271
213
  */
272
- function flushPiEntries(c, runtime, handle) {
273
- const write = runtime.writes.then(async () => {
274
- const entries = handle.session.sessionManager.getEntries();
275
- while (handle.persistedEntryCount < entries.length) {
276
- await appendPiEntry(c.db, entries[handle.persistedEntryCount]);
277
- handle.persistedEntryCount += 1;
278
- }
279
- });
280
- runtime.writes = write.catch(() => { });
281
- return write;
282
- }
283
- /** Runs a SQLite write after the entry writes queued before it. */
284
- function writeInOrder(c, runtime, write) {
285
- const next = runtime.writes.then(write);
286
- runtime.writes = next.catch((error) => {
287
- c.log.error({ msg: "pi run state write failed", error });
288
- });
289
- return next;
290
- }
291
- function queuedMessages(session) {
292
- return {
293
- steering: [...session.getSteeringMessages()],
294
- followUp: [...session.getFollowUpMessages()],
214
+ function startingAgent(options) {
215
+ const model = options.model === undefined ? undefined : parseModelRef(options.model);
216
+ const thinkingLevel = options.thinkingLevel;
217
+ const created = options.conversationCreated;
218
+ if (model === undefined && thinkingLevel === undefined)
219
+ return created;
220
+ return async (tx, conversation) => {
221
+ const agent = await tx.doc(AgentDoc, conversation.id);
222
+ await configure(tx, conversation.id, {
223
+ model: agent.model === undefined ? model : undefined,
224
+ thinkingLevel: agent.thinkingLevel === undefined ? thinkingLevel : undefined,
225
+ });
226
+ await created?.(tx, conversation);
295
227
  };
296
228
  }
297
229
  /**
298
- * Continues the run that was active when the actor stopped, when Pi's own
299
- * `Agent.continue()` accepts the transcript: its last message is a user or a
300
- * tool result message. Otherwise the chat stays as Pi left it, as after an
301
- * abort. The run continues in the background and keeps the actor awake.
230
+ * Builds the sandbox env without connecting, so a model request or a custom
231
+ * tool call never creates a sandbox. The sandbox connects on the first file
232
+ * or shell operation. A provider that does not report its working directory
233
+ * connects first, because the env needs that directory.
302
234
  */
303
- export async function resumeInterruptedRun(c, options) {
304
- const queue = await loadPiInterruptedRun(c.db);
305
- if (!queue)
306
- return;
307
- const handle = await ensurePiSession(c, options);
308
- const lastRole = handle.session.messages.at(-1)?.role;
309
- if (lastRole !== "user" && lastRole !== "toolResult") {
310
- c.log.info({
311
- msg: "pi run stopped where Pi cannot continue it, leaving the chat as is",
312
- lastRole,
235
+ function sandboxEnvBuilder(c, runtime, provider) {
236
+ const connect = async () => {
237
+ runtime.sandbox ??= connectSandbox(c, provider).catch((error) => {
238
+ runtime.sandbox = undefined;
239
+ throw error;
240
+ });
241
+ return (await runtime.sandbox).sandbox;
242
+ };
243
+ return async (target) => {
244
+ const root = provider.cwd ?? (await connect()).cwd;
245
+ return sandboxEnv(`${provider.name}:${c.actorId}`, root, connect, target.cwd);
246
+ };
247
+ }
248
+ function reportBlockedTasks(c, inspection) {
249
+ for (const task of inspection.tasks) {
250
+ if (task.state.kind !== "blocked")
251
+ continue;
252
+ c.log.warn({
253
+ msg: "pi durable task is blocked and does not keep the actor awake; inspect it with harness.inspect",
254
+ taskId: task.record.id,
255
+ kind: task.record.kind,
256
+ reason: task.state.reason,
257
+ error: task.state.error,
313
258
  });
314
- await writeInOrder(c, piRuntime(c), () => savePiIdle(c.db));
315
- return;
316
259
  }
317
- c.log.info({
318
- msg: "resuming the pi run that was active when the actor stopped",
319
- lastRole,
320
- });
321
- const run = continueRun(handle.session, queue)
322
- .then(() => persistPiState(c, handle))
323
- .catch((error) => {
324
- c.log.error({ msg: "resumed pi run failed", error });
325
- });
326
- void c.keepAwake(run);
327
260
  }
328
261
  /**
329
- * Runs `AgentSession`'s own run loop from the stored transcript, so retry,
330
- * compaction, and queued messages work as in any run. The loop starts with
331
- * `agent.prompt`; for that one call it continues instead. `pi-coding-agent`
332
- * is pinned exactly, and the resume test fails if these methods change.
262
+ * Whether live work should keep the actor awake. Tasks that run or are ready
263
+ * to run do. A task in a retry or poll wait longer than `longWaitMs` does not;
264
+ * the actor sleeps and a scheduled wake reopens it at the deadline. Waiting
265
+ * and completing tasks depend on other tasks, which decide. Blocked tasks
266
+ * never run, so they never keep the actor awake.
333
267
  */
334
- async function continueRun(session, queue) {
335
- const internals = session;
336
- for (const text of queue.steering)
337
- await internals._queueSteer(text);
338
- for (const text of queue.followUp)
339
- await internals._queueFollowUp(text);
340
- const agent = session.agent;
341
- Object.defineProperty(agent, "prompt", {
342
- configurable: true,
343
- value: async () => {
344
- Reflect.deleteProperty(agent, "prompt");
345
- await agent.continue();
346
- },
347
- });
348
- try {
349
- await internals._runAgentPrompt([]);
350
- }
351
- finally {
352
- Reflect.deleteProperty(agent, "prompt");
353
- }
354
- }
355
- function broadcastSessionEvent(c, event) {
356
- try {
357
- c.broadcast("event", event);
358
- }
359
- catch (error) {
360
- if (isActorStoppingError(error))
361
- return;
362
- c.log.error({ msg: "failed to broadcast pi session event", error });
268
+ function busyState(inspection, now, longWaitMs) {
269
+ let until;
270
+ for (const task of inspection.tasks) {
271
+ switch (task.state.kind) {
272
+ case "running":
273
+ case "ready": {
274
+ const deadline = waitDeadline(task.record.state.checkpoint);
275
+ if (deadline === undefined || deadline - now <= longWaitMs)
276
+ return { kind: "busy" };
277
+ until = Math.min(until ?? deadline, deadline);
278
+ break;
279
+ }
280
+ case "waiting":
281
+ case "completing":
282
+ case "blocked":
283
+ break;
284
+ }
363
285
  }
286
+ return until === undefined ? { kind: "idle" } : { kind: "waiting", until };
364
287
  }
365
- function isActorStoppingError(error) {
366
- if (!error || typeof error !== "object")
367
- return false;
368
- const candidate = error;
369
- return candidate.group === "actor" && candidate.code === "stopping";
288
+ /** The deadline of a task checkpoint in Pi's retry or poll phase. */
289
+ function waitDeadline(checkpoint) {
290
+ if (typeof checkpoint !== "object" ||
291
+ checkpoint === null ||
292
+ Array.isArray(checkpoint))
293
+ return undefined;
294
+ if (checkpoint.phase === "retry" && typeof checkpoint.until === "number")
295
+ return checkpoint.until;
296
+ if (checkpoint.phase === "poll" && typeof checkpoint.pollAt === "number")
297
+ return checkpoint.pollAt;
298
+ return undefined;
370
299
  }
371
300
  /**
372
- * Queues entries appended since the last flush and writes Pi's mutable settings
373
- * when they changed. Called after every action and on shutdown.
301
+ * Keeps the actor awake while Pi Durable has live work, rechecking after
302
+ * every commit. Returns a function that stops watching.
374
303
  */
375
- export async function persistPiState(c, handle) {
376
- await flushPiEntries(c, piRuntime(c), handle);
377
- const settings = handle.settingsManager.getGlobalSettings();
378
- const encoded = JSON.stringify(settings);
379
- if (encoded === handle.persistedSettings)
380
- return;
381
- await savePiSettings(c.db, settings);
382
- handle.persistedSettings = encoded;
383
- }
384
- /**
385
- * Aborts the run in memory when RivetKit declares this actor generation lost.
386
- * The engine may already run the next generation, which resumes the run, so
387
- * the lost one must stop calling the model and running tools. A lost
388
- * generation skips `onSleep`, and its storage rejects writes, so nothing is
389
- * stored here. A normal stop fires the same signal and drains in `onSleep`.
390
- * Takes the wake context, whose signal is the actor's, not one action's.
391
- */
392
- export function stopRunWhenLost(c) {
393
- const runtime = piRuntime(c);
394
- c.abortSignal.addEventListener("abort", () => {
395
- if (!isLost(c))
304
+ function watchBusy(c, harness, now, longWaitMs) {
305
+ let release;
306
+ let scheduledWakeAt;
307
+ let checking = false;
308
+ let dirty = false;
309
+ let stopped = false;
310
+ const stayAwake = () => {
311
+ if (release)
396
312
  return;
397
- runtime.closing = true;
398
- const ready = runtime.ready;
399
- runtime.ready = undefined;
400
- void ready
401
- ?.then((handle) => handle.session.abort())
402
- .catch((error) => c.log.error({ msg: "pi could not abort the lost run", error }));
403
- c.log.warn({
404
- msg: "pi actor generation lost, aborting its run; the next generation resumes it",
405
- });
406
- }, { once: true });
407
- }
408
- /**
409
- * RivetKit releases that stop lost generations expose `isLost` on the actor
410
- * context. Older releases still run `onSleep` for a lost generation, so the
411
- * drain handles it there.
412
- */
413
- function isLost(c) {
414
- return c.isLost === true;
313
+ const { promise, resolve } = Promise.withResolvers();
314
+ release = resolve;
315
+ void c.keepAwake(promise);
316
+ };
317
+ const letGo = () => {
318
+ release?.();
319
+ release = undefined;
320
+ };
321
+ const check = async () => {
322
+ if (checking) {
323
+ dirty = true;
324
+ return;
325
+ }
326
+ checking = true;
327
+ try {
328
+ do {
329
+ dirty = false;
330
+ const busy = busyState(await harness.inspect(BACKGROUND_CONTEXT), now(), longWaitMs);
331
+ if (stopped)
332
+ return;
333
+ if (busy.kind === "waiting" && busy.until !== scheduledWakeAt) {
334
+ // The actor may sleep through a long wait only once its wake is written.
335
+ stayAwake();
336
+ try {
337
+ await c.schedule.at(busy.until, WAKE_ACTION);
338
+ scheduledWakeAt = busy.until;
339
+ }
340
+ catch (error) {
341
+ // Pi's own timer then ends the wait, and its commit checks again.
342
+ c.log.warn({
343
+ msg: "pi durable could not schedule its wake, so the actor stays awake through the wait",
344
+ error,
345
+ });
346
+ }
347
+ if (stopped)
348
+ return;
349
+ }
350
+ const canSleep = busy.kind === "idle" ||
351
+ (busy.kind === "waiting" && busy.until === scheduledWakeAt);
352
+ if (canSleep)
353
+ letGo();
354
+ else
355
+ stayAwake();
356
+ } while (dirty && !stopped);
357
+ }
358
+ catch (error) {
359
+ if (!stopped)
360
+ c.log.warn({ msg: "pi durable busy check failed", error });
361
+ }
362
+ finally {
363
+ checking = false;
364
+ }
365
+ };
366
+ // Commit listeners must not call Pi Durable, so the check runs after the listener returns.
367
+ const unsubscribe = harness.subscribeCommits(() => queueMicrotask(() => void check()));
368
+ const stop = () => {
369
+ stopped = true;
370
+ unsubscribe();
371
+ letGo();
372
+ };
373
+ // Keep-awake only blocks idle sleep. Once shutdown starts it would only delay it.
374
+ c.abortSignal.addEventListener("abort", stop, { once: true });
375
+ void check();
376
+ return () => {
377
+ c.abortSignal.removeEventListener("abort", stop);
378
+ stop();
379
+ };
415
380
  }
416
381
  /**
417
- * Waits until the session is idle, or until `drainUntil` passes. Idle sleep
418
- * never has a run, so this only waits on a forced stop, such as a deploy. The
419
- * deadline ends before RivetKit's, so closing still fits in the grace period.
420
- * Pi stores each message as it ends, and the next wake resumes the run.
382
+ * Waits until no run is active, or until `drainUntil` passes. Idle sleep
383
+ * never has live work, so this only waits on a forced stop, such as an upgrade.
384
+ * The deadline ends before RivetKit's, so closing still fits in the grace
385
+ * period. Pi's records are already stored, and the next wake resumes the work.
421
386
  */
422
- async function drain(c, session, drainUntil) {
423
- if (session.isIdle)
424
- return;
425
- let timer;
426
- const gracePeriodEnded = new Promise((resolve) => {
427
- timer = setTimeout(() => resolve(true), Math.max(0, drainUntil - Date.now()));
428
- });
387
+ async function drain(c, open, drainUntil) {
388
+ let changed = () => { };
389
+ let timedOut = false;
390
+ const unsubscribe = open.harness.subscribeCommits(() => changed());
391
+ const timer = setTimeout(() => {
392
+ timedOut = true;
393
+ changed();
394
+ }, Math.max(0, drainUntil - Date.now()));
429
395
  try {
430
- const idle = session.waitForIdle().then(() => false);
431
- if (await Promise.race([idle, gracePeriodEnded])) {
432
- c.log.warn({
433
- msg: "pi run still active at the end of the grace period; it resumes on wake when Pi can continue it",
396
+ while (!timedOut) {
397
+ // Armed before the check, so a commit during the check is not missed.
398
+ const next = new Promise((resolve) => {
399
+ changed = resolve;
434
400
  });
401
+ if (!(await open.isBusy()))
402
+ return;
403
+ await next;
435
404
  }
405
+ c.log.warn({
406
+ msg: "pi durable run still active at the end of the grace period; it resumes on wake",
407
+ });
436
408
  }
437
409
  finally {
438
410
  clearTimeout(timer);
411
+ unsubscribe();
439
412
  }
440
413
  }
441
414
  /**
442
- * Stops the Pi session for this actor generation. On sleep it first waits,
443
- * until `drainUntil`, for a run to finish. A run still active then is not
444
- * aborted: the transcript ends at the last message Pi stored, and the next
445
- * wake resumes it. On destroy it aborts the run at once, since nothing would
446
- * resume it. Then lets extensions shut down, flushes settings and entries,
447
- * and suspends the sandbox on sleep, or destroys it on destroy.
415
+ * Closes Pi Durable for this actor generation. On sleep it drains first. On
416
+ * destroy it stops running work at once. Records of interrupted work stay
417
+ * running, and the next open resumes them. Then suspends the sandbox on
418
+ * sleep, or destroys it on destroy.
448
419
  */
449
- export async function closePiSession(c, options, stop) {
420
+ export async function closeHarness(c, options, stop) {
450
421
  const runtime = piRuntime(c);
451
- const ready = runtime.ready;
452
422
  const errors = [];
453
- let handle;
423
+ let open;
454
424
  try {
455
- handle = await ready;
425
+ open = await runtime.harness;
456
426
  }
457
427
  catch { }
458
- if (handle) {
459
- const open = handle;
460
- await attempt(errors, () => stop.reason === "sleep"
461
- ? drain(c, open.session, stop.drainUntil)
462
- : open.session.abort());
428
+ // Destroy has no next generation to resume in, so it stops running work at once.
429
+ if (open && stop.reason === "sleep") {
430
+ await drain(c, open, stop.drainUntil).catch((error) => errors.push(error));
463
431
  }
464
432
  runtime.closing = true;
465
- runtime.ready = undefined;
466
- if (handle) {
467
- const open = handle;
468
- await attempt(errors, async () => {
469
- if (open.session.hasExtensionHandlers("session_shutdown")) {
470
- await open.session.extensionRunner.emit({
471
- type: "session_shutdown",
472
- reason: "quit",
473
- });
474
- }
475
- });
476
- await attempt(errors, () => persistPiState(c, open));
477
- open.session.dispose();
478
- c.log.info({ msg: "pi session closed", sessionId: open.session.sessionId });
433
+ runtime.harness = undefined;
434
+ if (open) {
435
+ await closeOpenHarness(open, runtime.watches).catch((error) => errors.push(error));
479
436
  }
480
437
  const provider = options.sandbox;
481
438
  if (provider) {
482
- await attempt(errors, () => closeSandbox(c, provider, handle?.sandbox?.current, stop));
439
+ await closeSandbox(c, provider, runtime.sandbox, stop).catch((error) => errors.push(error));
483
440
  }
484
441
  if (errors.length === 1)
485
442
  throw errors[0];
486
- if (errors.length > 1) {
487
- throw new AggregateError(errors, "pi session shutdown failed");
443
+ if (errors.length > 1)
444
+ throw new AggregateError(errors, "pi durable shutdown failed");
445
+ }
446
+ /** Runs `body` with a `c.pi` that throws `error` when read. */
447
+ export function withUnavailablePi(c, error, body) {
448
+ Object.defineProperty(c, "pi", {
449
+ get: () => {
450
+ throw error;
451
+ },
452
+ configurable: true,
453
+ });
454
+ return body();
455
+ }
456
+ /**
457
+ * Connects to the actor's sandbox, creating one when none is stored or the
458
+ * provider reports the stored one no longer exists. A new sandbox id is saved
459
+ * as soon as `create` returns, so a failure later in the start reuses it. Any
460
+ * other connect failure is thrown, so a temporary outage never replaces a
461
+ * sandbox.
462
+ */
463
+ export async function connectSandbox(c, provider) {
464
+ const existing = await loadPiSandbox(c.db);
465
+ if (existing && existing.provider !== provider.name) {
466
+ throw new Error(`pi sandbox was created by provider ${existing.provider}, but the actor now uses ${provider.name}`);
488
467
  }
468
+ if (existing) {
469
+ const sandbox = await provider.connect(c, existing.id);
470
+ if (sandbox)
471
+ return { provider, id: existing.id, sandbox };
472
+ c.log.warn({
473
+ msg: "pi sandbox no longer exists, creating a new one; files from the previous sandbox are lost",
474
+ provider: provider.name,
475
+ sandboxId: existing.id,
476
+ });
477
+ }
478
+ const id = await provider.create(c);
479
+ await savePiSandbox(c.db, { provider: provider.name, id });
480
+ const sandbox = await provider.connect(c, id);
481
+ if (!sandbox) {
482
+ throw new Error(`pi sandbox ${provider.name}/${id} was not found right after it was created`);
483
+ }
484
+ return { provider, id, sandbox };
489
485
  }
490
486
  /**
491
487
  * Suspends the sandbox this generation connected when the actor sleeps. On
@@ -507,12 +503,4 @@ export async function closeSandbox(c, provider, connection, stop) {
507
503
  if (id !== undefined)
508
504
  await provider.destroy(c, id);
509
505
  }
510
- async function attempt(errors, operation) {
511
- try {
512
- await operation();
513
- }
514
- catch (error) {
515
- errors.push(error);
516
- }
517
- }
518
506
  //# sourceMappingURL=runtime.js.map