@juanbenjumea/pi-agy 0.7.3 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.6
4
+
5
+ - Document background tasks and the Antigravity provider in the agent-facing skill guide (usage, lifecycle, and the narrowed background-servers rule), and ignore session-local `.pi/` todo state.
6
+ - Full 297-test gate plus typecheck and package checks pass.
7
+
8
+ ## 0.7.5
9
+
10
+ - Fix CI-only event-loop drain in background tasks: per-task and shutdown timers hold the loop so timeouts always fire, and shutdown clears task timers so abandoned runs cannot pin process exit. (0.7.4 never reached npm — its publish run caught this.)
11
+ - Full gate plus typecheck and package checks pass.
12
+
13
+ ## 0.7.4
14
+
15
+ - Add background agy tasks: `agy_execute background=true` detaches the run and returns a handle immediately; the new `agy_tasks` tool lists, polls, collects, and cancels. Runs keep their `timeout_ms` deadline, serialize on the per-directory lock, record sessions on completion, and are aborted on session shutdown.
16
+ - Keep the preflight health retry inside the remaining timeout budget.
17
+ - Full 297-test gate plus typecheck and package checks pass.
18
+
3
19
  ## 0.7.3
4
20
 
5
21
  - Retry health probes once on timeout so cold-start OAuth stampedes no longer fail delegation runs; auth failures, missing binaries, and cancellations still fail fast. Live smoke probe cap raised for the same cold-start reason.
package/README.md CHANGED
@@ -129,6 +129,7 @@ The deadline never discards finished work:
129
129
 
130
130
  | Param | Description |
131
131
  |-------|-------------|
132
+ | `background` | Return immediately with a task handle instead of waiting; poll with `agy_tasks status` and collect the result. The run keeps its `timeout_ms` deadline; cancel via `agy_tasks`. |
132
133
  | `conversation_id` | Resume agy conversation by ID |
133
134
  | `continue` | `--continue` most recent conversation |
134
135
  | `new_session` | Force fresh session; set `false` to reuse last ID for dir |
@@ -177,6 +178,14 @@ models, custom agents, ages, and one-line task summaries — so agents can find
177
178
  picker. Summaries are stored locally (first ~80 chars of each prompt), and a
178
179
  recorded custom agent is restored when that conversation resumes.
179
180
 
181
+ The `agy_tasks` tool manages background runs started with
182
+ `agy_execute background=true`: `list` shows tasks per directory, `status`
183
+ polls state and recent progress, `collect` returns the terminal result and
184
+ frees the record, and `cancel` aborts a live run. Background runs keep their
185
+ `timeout_ms` deadline, serialize on the per-directory lock like foreground
186
+ runs, and are recorded to the session store on completion so nothing is lost
187
+ when a payload goes uncollected; session shutdown aborts anything still live.
188
+
180
189
  ## Human-callable `/agy` command
181
190
 
182
191
  Run agy directly from the Pi TUI — fast path when fully specified, wizard otherwise:
@@ -35,6 +35,10 @@ import {
35
35
  type AgyMode,
36
36
  } from "./lib/execute.js";
37
37
  import { describeWhen, truncate } from "./lib/output.js";
38
+ import {
39
+ BackgroundTaskRunner,
40
+ summarizeTaskPrompt,
41
+ } from "./lib/background.js";
38
42
  import {
39
43
  AGY_PROVIDER_API,
40
44
  AGY_PROVIDER_ID,
@@ -171,10 +175,18 @@ function registerAgyProvider(pi: ExtensionAPI): void {
171
175
  })();
172
176
  }
173
177
 
178
+ const backgroundRunner = new BackgroundTaskRunner();
179
+
180
+ /** Process-wide background task registry (reset in tests via shutdown). */
181
+ export function getBackgroundRunner(): BackgroundTaskRunner {
182
+ return backgroundRunner;
183
+ }
184
+
174
185
  export default function piAgyExtension(pi: ExtensionAPI) {
175
186
  registerAgyCommand(pi);
176
187
  registerAgyProvider(pi);
177
- // Persistent driver processes must not outlive the session.
188
+ // Persistent driver processes and background runs must not outlive the
189
+ // session (a detached run editing files after exit would be a ghost).
178
190
  try {
179
191
  pi.on?.("session_shutdown", async () => {
180
192
  try {
@@ -182,6 +194,11 @@ export default function piAgyExtension(pi: ExtensionAPI) {
182
194
  } catch {
183
195
  // Shutdown disposal is best effort; turns still work without it.
184
196
  }
197
+ try {
198
+ await getBackgroundRunner().shutdown();
199
+ } catch {
200
+ // Best effort; the OS reaps anything left.
201
+ }
185
202
  });
186
203
  } catch {
187
204
  // Shutdown disposal is best effort; turns still work without it.
@@ -207,6 +224,8 @@ export default function piAgyExtension(pi: ExtensionAPI) {
207
224
  "Keep agy_execute context=none unless the delegated task depends on prior Pi discussion; use summary before recent to minimize disclosure.",
208
225
  "Use agy_usage before choosing a model when quota availability matters; agy_execute also refreshes and returns a quota snapshot.",
209
226
  "Batch related work, prefer digest output for non-write calls, and avoid parallel agy_execute calls within one shared-quota group or directory.",
227
+ "Use background=true for long runs that should not block the turn; poll with agy_tasks status and collect the result when done.",
228
+ "Collect background results promptly: uncollected payloads die with the session (conversations stay resumable), and cancel strays with agy_tasks cancel.",
210
229
  "Always review the git diff and run just ci (or the project gate) after agy_execute with mode=accept-edits.",
211
230
  "Never use agy for irreversible production changes.",
212
231
  "Set an appropriate timeout_ms for large tasks (default 5m).",
@@ -306,6 +325,13 @@ export default function piAgyExtension(pi: ExtensionAPI) {
306
325
  default: true,
307
326
  }),
308
327
  ),
328
+ background: Type.Optional(
329
+ Type.Boolean({
330
+ description:
331
+ "Return immediately with a task handle instead of waiting; poll with agy_tasks status and collect the result. The run keeps its timeout_ms deadline; cancel via agy_tasks.",
332
+ default: false,
333
+ }),
334
+ ),
309
335
  }),
310
336
 
311
337
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
@@ -373,6 +399,36 @@ export default function piAgyExtension(pi: ExtensionAPI) {
373
399
  if (!approved) throw new Error("agy accept-edits cancelled by user");
374
400
  }
375
401
 
402
+ if (params.background) {
403
+ const runner = getBackgroundRunner();
404
+ const handle = runner.start({
405
+ dir: cwd,
406
+ summary: summarizeTaskPrompt(params.prompt),
407
+ model,
408
+ agent,
409
+ timeoutMs,
410
+ run: ({ onProgress, signal }) =>
411
+ executeAgyTask(executionOptions, signal, (progress) => onProgress(progress)).then(
412
+ (result) => ({
413
+ text: result.text,
414
+ conversationId: result.details.conversation_id,
415
+ details: result.details,
416
+ }),
417
+ ),
418
+ });
419
+ return {
420
+ content: [
421
+ {
422
+ type: "text",
423
+ text:
424
+ `started background task ${handle} (${mode}, ${model ?? "default model"}, timeout ${Math.round(timeoutMs / 1000)}s). ` +
425
+ `Poll with agy_tasks status, collect the result with agy_tasks collect.`,
426
+ },
427
+ ],
428
+ details: { handle, mode, model, dir: cwd, timeout_ms: timeoutMs },
429
+ };
430
+ }
431
+
376
432
  const result = await executeAgyTask(
377
433
  executionOptions,
378
434
  abortSignal,
@@ -474,6 +530,124 @@ export default function piAgyExtension(pi: ExtensionAPI) {
474
530
  },
475
531
  });
476
532
 
533
+ pi.registerTool({
534
+ name: "agy_tasks",
535
+ label: "Antigravity Background Tasks",
536
+ description:
537
+ "List, poll, collect, or cancel background agy tasks started with agy_execute background=true. Collecting returns the terminal result and frees the record.",
538
+ promptSnippet: "Poll background agy tasks and collect finished results",
539
+ parameters: Type.Object({
540
+ action: Type.Union(
541
+ [
542
+ Type.Literal("list"),
543
+ Type.Literal("status"),
544
+ Type.Literal("collect"),
545
+ Type.Literal("cancel"),
546
+ ],
547
+ { description: "Task action (default list).", default: "list" },
548
+ ),
549
+ handle: Type.Optional(
550
+ Type.String({
551
+ description: "Task handle from agy_execute (required for status, collect, cancel).",
552
+ }),
553
+ ),
554
+ dir: Type.Optional(
555
+ Type.String({
556
+ description: "Filter listed tasks to a working directory. Defaults to current project root.",
557
+ }),
558
+ ),
559
+ }),
560
+
561
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
562
+ const runner = getBackgroundRunner();
563
+ const action = params.action ?? "list";
564
+ // List/status carry summaries only: full response text and execution
565
+ // details stay behind collect, so polling never bloats the transcript.
566
+ const summarize = (task: {
567
+ handle: string; dir: string; summary: string; model?: string; agent?: string;
568
+ state: string; startedAt: number; updatedAt: number; progress: string[];
569
+ error?: string; conversationId?: string;
570
+ }) => ({
571
+ handle: task.handle,
572
+ dir: task.dir,
573
+ summary: task.summary,
574
+ model: task.model,
575
+ agent: task.agent,
576
+ state: task.state,
577
+ startedAt: task.startedAt,
578
+ updatedAt: task.updatedAt,
579
+ progressTail: task.progress.slice(-3),
580
+ error: task.error,
581
+ conversationId: task.conversationId,
582
+ });
583
+ if (action === "list") {
584
+ const cwd = await resolveToolDir(ctx.cwd, params.dir);
585
+ const tasks = runner.list(cwd);
586
+ if (tasks.length === 0) {
587
+ return {
588
+ content: [{ type: "text", text: `No background agy tasks for ${cwd}.` }],
589
+ details: { dir: cwd, tasks: [] },
590
+ };
591
+ }
592
+ const lines = tasks.map((task) => {
593
+ const age = describeWhen(new Date(task.startedAt).toISOString());
594
+ const latest = task.state === "running" && task.progress.length > 0
595
+ ? ` · latest: ${task.progress[task.progress.length - 1]}`
596
+ : "";
597
+ return `${task.handle} · ${task.state}${task.model ? ` · ${task.model}` : ""} · ${age} · ${task.summary}${latest}`;
598
+ });
599
+ return {
600
+ content: [{ type: "text", text: `background agy tasks for ${cwd}:\n${lines.join("\n")}` }],
601
+ details: { dir: cwd, tasks: tasks.map(summarize) },
602
+ };
603
+ }
604
+ if (!params.handle) throw new Error(`agy_tasks ${action} requires a handle`);
605
+ if (action === "status") {
606
+ const task = runner.get(params.handle);
607
+ if (!task) throw new Error(`unknown background task '${params.handle}'`);
608
+ const elapsed = `${Math.round((Date.now() - task.startedAt) / 1000)}s`;
609
+ const progress = task.progress.length ? `\nrecent progress:\n${task.progress.slice(-5).join("\n")}` : "";
610
+ const outcome = task.state === "running"
611
+ ? ""
612
+ : task.state === "done"
613
+ ? `\nresult: ${truncate(task.text ?? "(empty response)")}`
614
+ : `\n${task.state}${task.error ? `: ${task.error}` : ""}`;
615
+ const conversation = task.conversationId ? `\nconversation: ${task.conversationId}` : "";
616
+ return {
617
+ content: [{
618
+ type: "text",
619
+ text: `${task.handle} · ${task.state} · elapsed ${elapsed} · ${task.summary}${progress}${outcome}${conversation}`,
620
+ }],
621
+ details: { task: summarize(task) },
622
+ };
623
+ }
624
+ if (action === "collect") {
625
+ const task = runner.collect(params.handle);
626
+ const body = task.state === "done"
627
+ ? truncate(task.text ?? "(empty response)")
628
+ : `${task.state}${task.error ? `: ${task.error}` : ""}`;
629
+ const conversation = task.conversationId ? `\nconversation: ${task.conversationId}` : "";
630
+ return {
631
+ content: [{ type: "text", text: `${task.handle} · ${task.state}\n${body}${conversation}` }],
632
+ details: { task },
633
+ };
634
+ }
635
+ const cancelled = runner.cancel(params.handle);
636
+ if (!cancelled) {
637
+ const task = runner.get(params.handle);
638
+ if (!task) throw new Error(`unknown background task '${params.handle}'`);
639
+ return {
640
+ content: [{ type: "text", text: `${task.handle} is already ${task.state}; nothing to cancel.` }],
641
+ details: { task },
642
+ };
643
+ }
644
+ return {
645
+ content: [{ type: "text", text: `${params.handle} cancellation requested; poll status for settlement.` }],
646
+ details: { handle: params.handle, cancelled: true },
647
+ };
648
+ },
649
+ });
650
+
477
651
  pi.registerTool({
478
652
  name: "agy_usage",
479
653
  label: "Antigravity Quota",
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Background agy tasks: detached delegation runs with poll/collect.
3
+ *
4
+ * `start` launches the runner without awaiting it and returns a handle
5
+ * immediately. The run keeps its own timeout deadline (enforced by aborting
6
+ * the task controller, which kills the agy process group downstream) and
7
+ * participates in the per-directory lock like a foreground run — lock waits
8
+ * count against its timeout. `collect` returns the terminal outcome and
9
+ * frees the record; session durability comes from the executor itself,
10
+ * which records conversations on completion, timeout, and cancellation.
11
+ *
12
+ * Records are in-process only: a Pi restart orphans nothing (every live
13
+ * child is killed on shutdown) but drops uncollected payloads — the session
14
+ * store keeps those conversations resumable.
15
+ */
16
+
17
+ import { randomBytes } from "node:crypto";
18
+
19
+ import { conversationSummary } from "./sessions.js";
20
+
21
+ export type BackgroundTaskState = "running" | "done" | "error" | "cancelled" | "timeout";
22
+
23
+ export interface BackgroundRunCallbacks {
24
+ onProgress: (message: string) => void;
25
+ signal: AbortSignal;
26
+ }
27
+
28
+ export interface BackgroundRunOutcome {
29
+ text: string;
30
+ conversationId?: string;
31
+ details?: unknown;
32
+ }
33
+
34
+ export interface BackgroundStartOptions {
35
+ dir: string;
36
+ summary: string;
37
+ model?: string;
38
+ agent?: string;
39
+ timeoutMs: number;
40
+ run: (callbacks: BackgroundRunCallbacks) => Promise<BackgroundRunOutcome>;
41
+ }
42
+
43
+ export interface BackgroundTaskSnapshot {
44
+ handle: string;
45
+ dir: string;
46
+ summary: string;
47
+ model?: string;
48
+ agent?: string;
49
+ state: BackgroundTaskState;
50
+ startedAt: number;
51
+ updatedAt: number;
52
+ /** Bounded recent progress lines (newest last). */
53
+ progress: string[];
54
+ text?: string;
55
+ error?: string;
56
+ conversationId?: string;
57
+ details?: unknown;
58
+ }
59
+
60
+ const MAX_TASKS = 32;
61
+ const MAX_PROGRESS_LINES = 20;
62
+ const MAX_PROGRESS_CHARS = 500;
63
+
64
+ interface TaskRecord {
65
+ handle: string;
66
+ dir: string;
67
+ summary: string;
68
+ model?: string;
69
+ agent?: string;
70
+ state: BackgroundTaskState;
71
+ startedAt: number;
72
+ updatedAt: number;
73
+ progress: string[];
74
+ text?: string;
75
+ error?: string;
76
+ conversationId?: string;
77
+ details?: unknown;
78
+ controller: AbortController;
79
+ timer?: NodeJS.Timeout;
80
+ cancelled: boolean;
81
+ timedOut: boolean;
82
+ settled: Promise<void>;
83
+ }
84
+
85
+ function clipProgress(message: string): string {
86
+ const flat = message.replace(/\s+/g, " ").trim();
87
+ if (!flat) return "";
88
+ return flat.length > MAX_PROGRESS_CHARS ? flat.slice(0, MAX_PROGRESS_CHARS - 1) + "…" : flat;
89
+ }
90
+
91
+ export class BackgroundTaskRunner {
92
+ private readonly tasks = new Map<string, TaskRecord>();
93
+ private readonly maxTasks: number;
94
+ private readonly shutdownTimeoutMs: number;
95
+
96
+ constructor(options?: { maxTasks?: number; shutdownTimeoutMs?: number }) {
97
+ this.maxTasks = Math.max(1, options?.maxTasks ?? MAX_TASKS);
98
+ this.shutdownTimeoutMs = Math.max(1, options?.shutdownTimeoutMs ?? 15_000);
99
+ }
100
+
101
+ /**
102
+ * Start a detached run. Finished records are never evicted behind the
103
+ * agent's back (collect frees them explicitly); when every slot holds a
104
+ * live or uncollected task, starting fails with a state-aware message.
105
+ */
106
+ start(options: BackgroundStartOptions): string {
107
+ if (this.tasks.size >= this.maxTasks) {
108
+ const states = [...this.tasks.values()].map((record) => record.state);
109
+ const finished = states.filter((state) => state !== "running").length;
110
+ throw new Error(
111
+ finished > 0
112
+ ? `background task list is full (${this.maxTasks}); collect finished tasks first`
113
+ : `background task list is full of active runs (${this.maxTasks}); cancel running tasks first`,
114
+ );
115
+ }
116
+ const handle = `agybg-${randomBytes(8).toString("hex")}`;
117
+ const controller = new AbortController();
118
+ const now = Date.now();
119
+ const record: TaskRecord = {
120
+ handle,
121
+ dir: options.dir,
122
+ summary: options.summary,
123
+ model: options.model,
124
+ agent: options.agent,
125
+ state: "running",
126
+ startedAt: now,
127
+ updatedAt: now,
128
+ progress: [],
129
+ controller,
130
+ cancelled: false,
131
+ timedOut: false,
132
+ settled: Promise.resolve(),
133
+ };
134
+ // Ref'd deliberately: this timer guarantees the run settles even if
135
+ // nothing else holds the loop (an unref'd timer lets the loop drain
136
+ // with the task pending, hanging collectors forever). Cleared on settle.
137
+ record.timer = setTimeout(() => {
138
+ record.timedOut = true;
139
+ controller.abort();
140
+ }, Math.max(1, options.timeoutMs));
141
+
142
+ this.tasks.set(handle, record);
143
+ let runPromise: Promise<BackgroundRunOutcome>;
144
+ try {
145
+ runPromise = Promise.resolve(
146
+ options.run({
147
+ onProgress: (message) => {
148
+ const line = clipProgress(message);
149
+ if (!line) return;
150
+ record.progress.push(line);
151
+ if (record.progress.length > MAX_PROGRESS_LINES) {
152
+ record.progress.splice(0, record.progress.length - MAX_PROGRESS_LINES);
153
+ }
154
+ record.updatedAt = Date.now();
155
+ },
156
+ signal: controller.signal,
157
+ }),
158
+ );
159
+ } catch (error) {
160
+ runPromise = Promise.reject(error);
161
+ }
162
+ record.settled = runPromise
163
+ .then(
164
+ (outcome) => {
165
+ record.state = "done";
166
+ record.text = outcome.text;
167
+ record.conversationId = outcome.conversationId;
168
+ record.details = outcome.details;
169
+ record.updatedAt = Date.now();
170
+ },
171
+ (error: unknown) => {
172
+ const message = error instanceof Error ? error.message : String(error);
173
+ // Cancelled wins: only our cancel/shutdown abort with the flag
174
+ // set (the timer is cleared in cancel, so a late fire cannot
175
+ // overwrite). Timeout flag next; the message regex is a backstop
176
+ // for executor-internal deadlines only — never for cancellation,
177
+ // whose wording may appear in unrelated child output.
178
+ if (record.cancelled) record.state = "cancelled";
179
+ else if (record.timedOut || /timed out/i.test(message)) record.state = "timeout";
180
+ else record.state = "error";
181
+ record.error = message;
182
+ const conversationId =
183
+ typeof error === "object" && error !== null
184
+ ? (error as { conversation_id?: unknown }).conversation_id
185
+ : undefined;
186
+ if (typeof conversationId === "string") record.conversationId = conversationId;
187
+ record.updatedAt = Date.now();
188
+ },
189
+ )
190
+ .finally(() => {
191
+ if (record.timer) {
192
+ clearTimeout(record.timer);
193
+ record.timer = undefined;
194
+ }
195
+ });
196
+ // A settlement rejection here would be an unhandled rejection: the
197
+ // handlers above never throw, but belt-and-braces costs nothing.
198
+ record.settled.catch(() => undefined);
199
+ return handle;
200
+ }
201
+
202
+ get(handle: string): BackgroundTaskSnapshot | undefined {
203
+ const record = this.tasks.get(handle);
204
+ return record ? snapshotOf(record) : undefined;
205
+ }
206
+
207
+ /** Snapshots for a directory (exact resolved match), newest last. */
208
+ list(dir?: string): BackgroundTaskSnapshot[] {
209
+ const out: BackgroundTaskSnapshot[] = [];
210
+ for (const record of this.tasks.values()) {
211
+ if (dir !== undefined && record.dir !== dir) continue;
212
+ out.push(snapshotOf(record));
213
+ }
214
+ return out.sort((a, b) => a.startedAt - b.startedAt);
215
+ }
216
+
217
+ /**
218
+ * Return the terminal outcome and free the record. Throws for unknown
219
+ * handles and for tasks that are still running (poll status instead).
220
+ */
221
+ collect(handle: string): BackgroundTaskSnapshot {
222
+ const record = this.tasks.get(handle);
223
+ if (!record) throw new Error(`unknown background task '${handle}'`);
224
+ if (record.state === "running") {
225
+ throw new Error(`background task '${handle}' is still running; poll status instead`);
226
+ }
227
+ this.tasks.delete(handle);
228
+ return snapshotOf(record);
229
+ }
230
+
231
+ /** Cancel a running task; false when unknown or already terminal. */
232
+ cancel(handle: string): boolean {
233
+ const record = this.tasks.get(handle);
234
+ if (!record || record.state !== "running" || record.cancelled) return false;
235
+ record.cancelled = true;
236
+ if (record.timer) {
237
+ clearTimeout(record.timer);
238
+ record.timer = undefined;
239
+ }
240
+ controllerAbort(record);
241
+ return true;
242
+ }
243
+
244
+ /**
245
+ * Abort every running task (session shutdown) and wait for settlement —
246
+ * bounded, so an abort-ignoring runner can delay but never hang teardown.
247
+ */
248
+ async shutdown(): Promise<void> {
249
+ const pending: Array<Promise<void>> = [];
250
+ for (const record of this.tasks.values()) {
251
+ if (record.state === "running") {
252
+ record.cancelled = true;
253
+ // Timers are moot past teardown: clear them so abandoned tasks
254
+ // cannot pin the process open after shutdown returns.
255
+ if (record.timer) {
256
+ clearTimeout(record.timer);
257
+ record.timer = undefined;
258
+ }
259
+ controllerAbort(record);
260
+ pending.push(record.settled);
261
+ }
262
+ }
263
+ if (pending.length === 0) return;
264
+ // Ref'd like the task timers: the bound must hold the loop, or teardown
265
+ // races an empty loop the same way. Cleared below either way.
266
+ let waiter: ReturnType<typeof setTimeout> | undefined;
267
+ try {
268
+ await Promise.race([
269
+ Promise.allSettled(pending).then(() => undefined),
270
+ new Promise<void>((resolve) => {
271
+ waiter = setTimeout(resolve, this.shutdownTimeoutMs);
272
+ }),
273
+ ]);
274
+ } finally {
275
+ if (waiter !== undefined) clearTimeout(waiter);
276
+ }
277
+ }
278
+ }
279
+
280
+ function controllerAbort(record: TaskRecord): void {
281
+ try {
282
+ record.controller.abort();
283
+ } catch {
284
+ // AbortController.abort never throws in practice; guard anyway.
285
+ }
286
+ }
287
+
288
+ function snapshotOf(record: TaskRecord): BackgroundTaskSnapshot {
289
+ return {
290
+ handle: record.handle,
291
+ dir: record.dir,
292
+ summary: record.summary,
293
+ model: record.model,
294
+ agent: record.agent,
295
+ state: record.state,
296
+ startedAt: record.startedAt,
297
+ updatedAt: record.updatedAt,
298
+ progress: [...record.progress],
299
+ text: record.text,
300
+ error: record.error,
301
+ conversationId: record.conversationId,
302
+ details: record.details,
303
+ };
304
+ }
305
+
306
+ /** Prompt summary helper shared with the session store format. */
307
+ export function summarizeTaskPrompt(prompt: string): string {
308
+ return conversationSummary(prompt);
309
+ }
@@ -51,11 +51,17 @@ async function runHealthWithRetry(
51
51
  signal: AbortSignal | undefined,
52
52
  timeoutMs: number | undefined,
53
53
  ): Promise<void> {
54
- const attempt = (): Promise<void> =>
55
- Promise.all([
56
- checkAgyHealth(cwd, signal, timeoutMs),
57
- checkAgyConnectivity(cwd, signal, timeoutMs),
54
+ const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
55
+ const attempt = (): Promise<void> => {
56
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
57
+ if (remaining !== undefined && remaining <= 0) {
58
+ throw new Error("agy timed out before preflight retry");
59
+ }
60
+ return Promise.all([
61
+ checkAgyHealth(cwd, signal, remaining),
62
+ checkAgyConnectivity(cwd, signal, remaining),
58
63
  ]).then(() => undefined);
64
+ };
59
65
  try {
60
66
  await attempt();
61
67
  } catch (error) {
@@ -513,27 +513,26 @@ export function getProviderRunner(dir: string): ProviderTurnRunner {
513
513
  );
514
514
  },
515
515
  resume: async (deliveries, callbacks, resumeSignal, resumeTimeoutMs) => {
516
- // Like run: resumed phases hold the child and must not race
517
- // delegation (or another session's fresh turn) in the directory.
518
- return withDirLock(
519
- dir,
520
- async () => {
521
- const bridge = providerBridges.get(path.resolve(dir));
522
- if (!bridge) throw new Error("agy provider turn has no bridge to resume on");
523
- for (const delivery of deliveries) {
524
- bridge.completePark(delivery.callId, { text: delivery.text, isError: delivery.isError });
525
- }
526
- const end = await driver.continueTurn({
527
- signal: resumeSignal,
528
- timeoutMs: resumeTimeoutMs,
529
- onText: callbacks?.onText,
530
- onActivity: callbacks?.onActivity,
531
- });
532
- return toRunEnd(end);
533
- },
534
- resumeSignal,
535
- resumeTimeoutMs,
536
- );
516
+ // Deliberately lock-free: resume continues an already-running child
517
+ // (no spawn) and taking the lock here deadlocks whenever the parked
518
+ // tool call itself started a lock-holding background run — the resume
519
+ // would wait on the very run it must complete to proceed. The
520
+ // suspended-gap race this opens (a foreign delegation run editing
521
+ // under a live provider child) is inherent to persistent processes;
522
+ // same-directory concurrency stays the agent's to coordinate, and
523
+ // fresh provider turns still serialize on the lock.
524
+ const bridge = providerBridges.get(path.resolve(dir));
525
+ if (!bridge) throw new Error("agy provider turn has no bridge to resume on");
526
+ for (const delivery of deliveries) {
527
+ bridge.completePark(delivery.callId, { text: delivery.text, isError: delivery.isError });
528
+ }
529
+ const end = await driver.continueTurn({
530
+ signal: resumeSignal,
531
+ timeoutMs: resumeTimeoutMs,
532
+ onText: callbacks?.onText,
533
+ onActivity: callbacks?.onActivity,
534
+ });
535
+ return toRunEnd(end);
537
536
  },
538
537
  cancel: () => {
539
538
  driver.cancelSuspended("agy provider turn was cancelled");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanbenjumea/pi-agy",
3
- "version": "0.7.3",
3
+ "version": "0.7.6",
4
4
  "description": "Reliable Antigravity delegation for Pi — quota-aware runs, resumable tasks, repo verification, cancellation, and trustworthy diff summaries.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,8 +47,21 @@ agy_agents
47
47
  agy_execute prompt="Investigate the crash" agent=gsd-debugger mode=plan
48
48
  agy_history
49
49
  agy_usage
50
+ agy_execute prompt="Migrate the build to ESM" mode=plan background=true
51
+ agy_tasks action=list
52
+ agy_tasks action=status handle=<handle>
53
+ agy_tasks action=collect handle=<handle>
54
+ agy_tasks action=cancel handle=<handle>
50
55
  ```
51
56
 
57
+ Background runs (`background=true`) return a task handle immediately instead
58
+ of blocking the turn. Poll with `agy_tasks status`, collect the terminal
59
+ result with `agy_tasks collect` (which frees the record), and cancel strays
60
+ with `agy_tasks cancel`. Runs keep their `timeout_ms` deadline, serialize on
61
+ the per-directory lock, record sessions on completion, and die with the Pi
62
+ session — collect promptly, since uncollected payloads do not survive restart
63
+ (conversations stay resumable via `agy_history`).
64
+
52
65
  ## Modes
53
66
 
54
67
  | Mode | Purpose |
@@ -62,7 +75,7 @@ agy_usage
62
75
  - **Default to `mode=plan`** for exploration; escalate to `accept-edits` only for scoped batches.
63
76
  - **Always review the `git diff`** after agy runs with `accept-edits`.
64
77
  - **Run `just ci`** (or the project gate) after write modes in this repo.
65
- - **Never use agy for irreversible production changes or persistent background servers/watchers.** Delegations are bounded; timeout/cancellation kills the full process tree rather than releasing unowned work.
78
+ - **Never use agy for irreversible production changes or unowned background servers/watchers.** Delegations are bounded; timeout/cancellation kills the full process tree rather than releasing unowned work. The managed exception is `background=true`, whose runs stay timeout-owned, cancellable, lock-serialized, and die with the session.
66
79
  - Reuse `conversation_id` or `continue=true` for multi-step plan → implement → review.
67
80
  - Use `agent` only when the user requests a configured custom agent; call `agy_agents` first when the exact name is unknown. Recorded agent identity is restored on resume.
68
81
  - Keep `context=none` (default) unless the task depends on prior Pi discussion; prefer `summary` over `recent` to minimize disclosure. Context handoff excludes system prompts, thinking, tool arguments/results, images, and custom messages.
@@ -86,3 +99,5 @@ agy_usage
86
99
  - **Diff summary** — accept-edits results append newly-dirty files only; pre-existing dirt is listed separately, never misattributed.
87
100
  - **Per-directory lock** — serializes concurrent agy calls on the same tree across Pi processes (symlink-aware).
88
101
  - **Cancellation** — abort/timeout kills the full agy process tree, and streamed records plus responses are size-bounded; a fully delivered result survives cancellation or timeout, and the conversation stays resumable.
102
+ - **Background tasks** — `agy_execute background=true` detaches with a task handle; `agy_tasks` polls, collects, and cancels. Timeout-owned, lock-serialized, session-recorded, reaped on shutdown.
103
+ - **Antigravity provider** — `antigravity/*` models in Pi's `/model` picker with live catalog discovery, a persistent stream-json driver, and a localhost MCP bridge: read-only Pi context plus mutating Pi tools via parked calls and real shadow `toolCall` turns (normal permissions and review apply). Toggle with `/agy bridge on|off`; attached images are staged as files agy can open.