pi-deltabox 0.1.5 → 0.1.6

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.
package/README.md CHANGED
@@ -190,6 +190,13 @@ reached.
190
190
  private modes, publication happens at commit.
191
191
  5. Set `"transport": "serve"` or `"cli"` only when native loading is not
192
192
  available. These transports preserve the durable on-disk protocol.
193
+ 6. If Pi is killed or crashes without stopping its session, the next start
194
+ **recovers** it instead of starting fresh: the session keeps its pending
195
+ changes and its open review, and a notice tells you to settle them with
196
+ `/sandbox-review`, then `/sandbox-commit` or `/sandbox-abort`. Nothing is
197
+ committed or reverted on your behalf. This needs a deltabox-lite addon with
198
+ session ownership (native transport). If a session start fails, the next
199
+ turn, tool call, or command retries it.
193
200
 
194
201
  ## Performance benchmark
195
202
 
package/dist/client.js CHANGED
@@ -79,6 +79,31 @@ export function sessionNotices(info) {
79
79
  }
80
80
  return notices;
81
81
  }
82
+ export function recoveryNotices(recovery, project) {
83
+ if (!recovery)
84
+ return [];
85
+ const notices = [];
86
+ const next = recovery.pendingChanges === 0
87
+ ? "It has no pending changes."
88
+ : recovery.reviewActive
89
+ ? `It has ${recovery.pendingChanges} pending change(s); use /sandbox-review, then /sandbox-commit or /sandbox-abort.`
90
+ : `It has ${recovery.pendingChanges} pending change(s); use /sandbox-diff to inspect them.`;
91
+ notices.push({
92
+ code: "recovered",
93
+ level: "warning",
94
+ message: `Deltabox recovered session ${recovery.sessionId}, left running by a previous run that ended without stopping it. ${next}`,
95
+ });
96
+ if (recovery.otherOrphans.length > 0) {
97
+ notices.push({
98
+ code: "orphans",
99
+ level: "warning",
100
+ message: `${recovery.otherOrphans.length} other orphaned deltabox session(s) remain: ` +
101
+ `${recovery.otherOrphans.join(", ")}. Stop one with ` +
102
+ `\`deltabox session stop <id> --project ${project}\`.`,
103
+ });
104
+ }
105
+ return notices;
106
+ }
82
107
  export class DeltaboxClient {
83
108
  project;
84
109
  proc = null;
@@ -87,6 +112,8 @@ export class DeltaboxClient {
87
112
  nextId = 1;
88
113
  sessionId = null;
89
114
  sessionInfo = null;
115
+ starting = null;
116
+ recovery = null;
90
117
  native = null;
91
118
  bin;
92
119
  transport;
@@ -306,14 +333,74 @@ export class DeltaboxClient {
306
333
  parse(output) {
307
334
  return JSON.parse(output.stdout.toString("utf8"));
308
335
  }
336
+ /**
337
+ * Starts the session, or returns it if already started. Concurrent callers
338
+ * share one attempt, and a failed attempt is not remembered: the next call
339
+ * tries again instead of repeating a stale error.
340
+ */
309
341
  async start() {
310
342
  if (this.sessionId && this.sessionInfo)
311
343
  return this.sessionInfo;
344
+ this.starting ??= this.startOnce().finally(() => {
345
+ this.starting = null;
346
+ });
347
+ return this.starting;
348
+ }
349
+ /** Notices about a session `start` adopted instead of starting fresh. */
350
+ recoveryNotices() {
351
+ return recoveryNotices(this.recovery, this.project);
352
+ }
353
+ /**
354
+ * Adopts the newest orphan matching this client's filesystem configuration,
355
+ * so a restarted host picks up where a killed one stopped. Returns null
356
+ * when there is none, or when the addon predates session ownership.
357
+ */
358
+ async adoptOrphan(native) {
359
+ if (!native.orphanedSessions || !native.adoptSession)
360
+ return null;
361
+ const durability = this.filesystem.durability === "strict" ? "strict" : "process-crash";
362
+ const orphans = await native.orphanedSessions();
363
+ const candidates = [];
364
+ for (const id of orphans) {
365
+ try {
366
+ const info = await native.sessionStatus(id);
367
+ if (info.requested_fs_mode === this.filesystem.mode && info.durability === durability) {
368
+ candidates.push(info);
369
+ }
370
+ }
371
+ catch {
372
+ // Unreadable orphans stay for the user to stop by hand.
373
+ }
374
+ }
375
+ candidates.sort((a, b) => b.started_at_ms - a.started_at_ms);
376
+ for (const candidate of candidates) {
377
+ let info;
378
+ try {
379
+ info = await native.adoptSession(candidate.session_id);
380
+ }
381
+ catch {
382
+ continue; // another host adopted it first
383
+ }
384
+ // A run killed mid-turn leaves its review open; keeping it lets the
385
+ // user settle the recovered work with the usual review commands.
386
+ const review = await native.reviewStatus(info.session_id).catch(() => null);
387
+ this.recovery = {
388
+ sessionId: info.session_id,
389
+ pendingChanges: info.pending_changes,
390
+ reviewActive: review !== null,
391
+ otherOrphans: orphans.filter((id) => id !== info.session_id),
392
+ };
393
+ return info;
394
+ }
395
+ return null;
396
+ }
397
+ async startOnce() {
312
398
  const mode = this.filesystem.mode === "auto" ? null : this.filesystem.mode;
313
399
  const policy = this.policy ? resolve(this.project, this.policy) : null;
314
400
  let info;
315
401
  if (this.transport === "native") {
316
- info = await this.nativeRequired().startSession(policy ?? undefined, this.filesystem.durability, this.filesystem.groupCommitMs ?? undefined);
402
+ const native = this.nativeRequired();
403
+ info = (await this.adoptOrphan(native)) ?? await native.startSession(policy ?? undefined, this.filesystem.durability, this.filesystem.groupCommitMs ?? undefined);
317
404
  }
318
405
  else if (this.transport === "serve") {
319
406
  const info = (await this.request("session.start", {
package/dist/commands.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { renderDiff } from "./format.js";
2
- export function registerCommands(pi, getClient, getConfig, setMode) {
2
+ export function registerCommands(pi,
3
+ /** Resolves the started client; `ctx` receives any start notices. */
4
+ getClient, getConfig, setMode) {
3
5
  pi.registerCommand("sandbox-status", {
4
6
  description: "Show deltabox-lite session status and pending change count",
5
7
  handler: async (_args, ctx) => {
6
- const client = getClient();
8
+ const client = await getClient(ctx);
7
9
  try {
8
10
  const status = await client.status();
9
11
  ctx.ui.notify([
@@ -27,7 +29,7 @@ export function registerCommands(pi, getClient, getConfig, setMode) {
27
29
  pi.registerCommand("sandbox-review", {
28
30
  description: "Show the pending diff",
29
31
  handler: async (_args, ctx) => {
30
- const client = getClient();
32
+ const client = await getClient(ctx);
31
33
  try {
32
34
  const diff = await client.reviewDiff();
33
35
  const text = renderDiff(diff);
@@ -41,7 +43,7 @@ export function registerCommands(pi, getClient, getConfig, setMode) {
41
43
  pi.registerCommand("sandbox-commit", {
42
44
  description: "Commit pending changes to the real project",
43
45
  handler: async (_args, ctx) => {
44
- const client = getClient();
46
+ const client = await getClient(ctx);
45
47
  try {
46
48
  const result = await client.reviewCommit();
47
49
  ctx.ui.notify(`Committed ${result.applied} change(s) (${result.checkpoint_id.slice(0, 8)})`, "info");
@@ -54,7 +56,7 @@ export function registerCommands(pi, getClient, getConfig, setMode) {
54
56
  pi.registerCommand("sandbox-abort", {
55
57
  description: "Abort pending changes back to the head checkpoint",
56
58
  handler: async (_args, ctx) => {
57
- const client = getClient();
59
+ const client = await getClient(ctx);
58
60
  try {
59
61
  const result = await client.reviewAbort();
60
62
  ctx.ui.notify(`Aborted, restored ${result.restored} change(s)`, "info");
@@ -68,7 +70,7 @@ export function registerCommands(pi, getClient, getConfig, setMode) {
68
70
  description: "Keep pending changes and preserve the current rollback point",
69
71
  handler: async (_args, ctx) => {
70
72
  try {
71
- const active = await getClient().reviewSkip();
73
+ const active = await (await getClient(ctx)).reviewSkip();
72
74
  ctx.ui.notify(`Kept changes pending from ${active.checkpoint_id.slice(0, 8)}`, "info");
73
75
  }
74
76
  catch (error) {
@@ -79,7 +81,7 @@ export function registerCommands(pi, getClient, getConfig, setMode) {
79
81
  pi.registerCommand("sandbox-diff", {
80
82
  description: "Show the diff between two checkpoints (or base and head)",
81
83
  handler: async (args, ctx) => {
82
- const client = getClient();
84
+ const client = await getClient(ctx);
83
85
  const parts = String(args ?? "")
84
86
  .trim()
85
87
  .split(/\s+/)
package/dist/extension.js CHANGED
@@ -27,6 +27,33 @@ export function registerExtension(pi, dependencies = defaultDependencies) {
27
27
  }
28
28
  return client;
29
29
  };
30
+ // The client whose start notices were shown; each client announces once.
31
+ let announced = null;
32
+ /**
33
+ * The started client. A failed start is not sticky: the client is dropped,
34
+ * and the next tool call, command, or turn builds a fresh one and retries.
35
+ */
36
+ const ensureClient = async (ctx) => {
37
+ const current = getClient();
38
+ let info;
39
+ try {
40
+ info = await current.start();
41
+ }
42
+ catch (error) {
43
+ if (client === current) {
44
+ current.dispose();
45
+ client = null;
46
+ }
47
+ throw error;
48
+ }
49
+ if (ctx?.ui && announced !== current) {
50
+ announced = current;
51
+ for (const notice of [...current.recoveryNotices(), ...sessionNotices(info)]) {
52
+ ctx.ui.notify(notice.message, notice.level);
53
+ }
54
+ }
55
+ return current;
56
+ };
30
57
  pi.on("tool_call", async (event) => {
31
58
  if (process.platform === "win32" && config.isolation === "deltabox" && event.toolName === "bash") {
32
59
  return { block: true, reason: "Git Bash is unavailable under Windows DeltaBox isolation. Use the powershell tool." };
@@ -36,14 +63,9 @@ export function registerExtension(pi, dependencies = defaultDependencies) {
36
63
  config = dependencies.loadConfig(dependencies.cwd());
37
64
  mode = config.review.mode;
38
65
  try {
39
- const info = await getClient().start();
40
- for (const notice of sessionNotices(info)) {
41
- ctx.ui.notify(notice.message, notice.level);
42
- }
66
+ await ensureClient(ctx);
43
67
  }
44
68
  catch (error) {
45
- client?.dispose();
46
- client = null;
47
69
  ctx.ui.notify(`deltabox session start failed: ${String(error)}`, "error");
48
70
  }
49
71
  });
@@ -61,10 +83,11 @@ export function registerExtension(pi, dependencies = defaultDependencies) {
61
83
  }
62
84
  });
63
85
  pi.on("before_agent_start", async (_event, ctx) => {
64
- if (!client || mode !== "task")
86
+ if (mode !== "task")
65
87
  return;
66
88
  try {
67
- await client.reviewBegin("task", "agent-turn");
89
+ // Also the retry point after a failed session start.
90
+ await (await ensureClient(ctx)).reviewBegin("task", "agent-turn");
68
91
  }
69
92
  catch (error) {
70
93
  ctx.ui.notify(`deltabox review start failed: ${String(error)}`, "error");
@@ -87,10 +110,10 @@ export function registerExtension(pi, dependencies = defaultDependencies) {
87
110
  ctx.ui.notify(`deltabox review failed: ${String(error)}`, "error");
88
111
  }
89
112
  });
90
- for (const tool of makeTools(getClient, getConfig)) {
113
+ for (const tool of makeTools(ensureClient, getConfig)) {
91
114
  pi.registerTool(tool);
92
115
  }
93
- registerCommands(pi, getClient, getConfig, (next) => {
116
+ registerCommands(pi, ensureClient, getConfig, (next) => {
94
117
  mode = next;
95
118
  });
96
119
  }
package/dist/tools.js CHANGED
@@ -77,7 +77,9 @@ async function afterMutation(client, config, ctx, source) {
77
77
  await reviewPending(client, (ctx.ui ?? {}), source);
78
78
  }
79
79
  }
80
- export function makeTools(getClient, getConfig) {
80
+ export function makeTools(
81
+ /** Resolves the started client; `ctx` receives any start notices. */
82
+ getClient, getConfig) {
81
83
  const readSchema = Type.Object({
82
84
  path: Type.String({ description: "Path to the file to read" }),
83
85
  offset: Type.Optional(Type.Number({ description: "1-indexed first line" })),
@@ -106,7 +108,7 @@ export function makeTools(getClient, getConfig) {
106
108
  parameters: readSchema,
107
109
  async execute(_id, params, _signal, _onUpdate, ctx) {
108
110
  const p = params;
109
- const client = getClient();
111
+ const client = await getClient(ctx);
110
112
  const absolute = toAbsolute(ctx, p.path);
111
113
  const bytes = await client.readFile(absolute);
112
114
  const text = bytes.toString("utf8");
@@ -125,7 +127,7 @@ export function makeTools(getClient, getConfig) {
125
127
  parameters: pathSchema,
126
128
  async execute(_id, params, _signal, _onUpdate, ctx) {
127
129
  const p = params;
128
- const client = getClient();
130
+ const client = await getClient(ctx);
129
131
  await beforeMutation(client, getConfig());
130
132
  await client.writeFile(toAbsolute(ctx, p.path), p.content);
131
133
  await afterMutation(client, getConfig(), ctx, "write");
@@ -139,7 +141,7 @@ export function makeTools(getClient, getConfig) {
139
141
  parameters: editSchema,
140
142
  async execute(_id, params, _signal, _onUpdate, ctx) {
141
143
  const p = params;
142
- const client = getClient();
144
+ const client = await getClient(ctx);
143
145
  const absolute = toAbsolute(ctx, p.path);
144
146
  await beforeMutation(client, getConfig());
145
147
  const content = (await client.readFile(absolute)).toString("utf8");
@@ -161,7 +163,7 @@ export function makeTools(getClient, getConfig) {
161
163
  parameters: bashSchema,
162
164
  async execute(_id, params, signal, _onUpdate, ctx) {
163
165
  const p = params;
164
- const client = getClient();
166
+ const client = await getClient(ctx);
165
167
  await beforeMutation(client, getConfig());
166
168
  const timeoutMs = p.timeout !== undefined && p.timeout > 0
167
169
  ? p.timeout * 1_000
@@ -192,7 +194,7 @@ export function makeTools(getClient, getConfig) {
192
194
  }),
193
195
  async execute(_id, params, _signal, _onUpdate, ctx) {
194
196
  const p = params;
195
- const client = getClient();
197
+ const client = await getClient(ctx);
196
198
  const target = toAbsolute(ctx, p.path ?? ".");
197
199
  const result = await client.exec(process.platform === "win32" ? powershellArgv(`Get-ChildItem -LiteralPath ${powershellQuote(powershellTarget(ctx.cwd, target))} -File -Recurse | Select-String -Pattern ${powershellQuote(p.pattern)} | ForEach-Object { '{0}:{1}:{2}' -f $_.Path, $_.LineNumber, $_.Line }`) : [
198
200
  bashExecutable(),
@@ -216,7 +218,7 @@ export function makeTools(getClient, getConfig) {
216
218
  }),
217
219
  async execute(_id, params, _signal, _onUpdate, ctx) {
218
220
  const p = params;
219
- const client = getClient();
221
+ const client = await getClient(ctx);
220
222
  const target = toAbsolute(ctx, p.path ?? ".");
221
223
  const pattern = p.pattern ?? "*";
222
224
  const result = await client.exec(process.platform === "win32" ? powershellArgv(`Get-ChildItem -LiteralPath ${powershellQuote(powershellTarget(ctx.cwd, target))} -Recurse -Force | Where-Object { $_.Name -like ${powershellQuote(pattern)} } | ForEach-Object { $_.FullName }`) : [
@@ -240,7 +242,7 @@ export function makeTools(getClient, getConfig) {
240
242
  }),
241
243
  async execute(_id, params, _signal, _onUpdate, ctx) {
242
244
  const p = params;
243
- const client = getClient();
245
+ const client = await getClient(ctx);
244
246
  const target = toAbsolute(ctx, p.path ?? ".");
245
247
  const result = await client.exec(process.platform === "win32"
246
248
  ? powershellArgv(`Get-ChildItem -LiteralPath ${powershellQuote(powershellTarget(ctx.cwd, target))} -Force | Format-Table Mode, Length, Name -AutoSize | Out-String -Width 240`)
@@ -263,7 +265,7 @@ export function makeTools(getClient, getConfig) {
263
265
  if (signal?.aborted)
264
266
  throw new Error("PowerShell command cancelled before execution");
265
267
  const p = params;
266
- const client = getClient();
268
+ const client = await getClient(ctx);
267
269
  const config = getConfig();
268
270
  const argv = powershellArgv(p.command);
269
271
  await beforeMutation(client, config);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-deltabox",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Pi extension: agent-native sandbox sessions with diff/commit/abort, powered by deltabox-lite",
6
6
  "type": "module",
@@ -28,11 +28,11 @@
28
28
  "typebox": "^1.3.10"
29
29
  },
30
30
  "optionalDependencies": {
31
- "deltabox-lite-darwin-arm64": "0.2.0",
32
- "deltabox-lite-darwin-x64": "0.2.0",
33
- "deltabox-lite-linux-arm64": "0.2.0",
34
- "deltabox-lite-linux-x64": "0.2.0",
35
- "deltabox-lite-windows-x64": "0.2.0"
31
+ "deltabox-lite-darwin-arm64": "0.3.0",
32
+ "deltabox-lite-darwin-x64": "0.3.0",
33
+ "deltabox-lite-linux-arm64": "0.3.0",
34
+ "deltabox-lite-linux-x64": "0.3.0",
35
+ "deltabox-lite-windows-x64": "0.3.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@earendil-works/pi-coding-agent": "^0.79.3",