@juanbenjumea/pi-agy 0.7.6 → 0.7.7

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,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.7
4
+
5
+ - Add dynamic Pi Skills injection (`activate_skill`) to the loopback MCP server, scanning global (`~/.pi/agent/skills`, `~/.agents/skills`) and project (`.pi/skills`, `.agents/skills`) locations, presenting an enum of skills with summaries and returning `SKILL.md` markdown to agy.
6
+ - Add long-running tool escalation and polling (`bridge_poll_result`): tools running longer than 20s escalate with an immediate early-ack response, preventing agy client timeouts (~180s) and allowing agy to poll until the tool settles.
7
+ - Full 299-test gate plus typecheck and package checks pass.
8
+
3
9
  ## 0.7.6
4
10
 
5
11
  - 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.
package/README.md CHANGED
@@ -34,6 +34,8 @@ Requires Node.js >= 20.3.
34
34
  | Concurrency | Unlocked | Per-directory lock (in-process + filesystem, symlink-aware), lock wait counts against the timeout |
35
35
  | Transient failures | Fatal | One retry when agy fails before doing any work |
36
36
  | Cancellation | Direct child only | Full process-tree kill on cancel/timeout via detached process groups; a fully delivered result is preserved |
37
+ | Primary-model picker | None | `antigravity/*` provider with live catalog, persistent driver, MCP tool bridge, and image staging (see below) |
38
+ | Background runs | Blocking only | `background=true` detaches with a handle; `agy_tasks` polls, collects, and cancels under the same timeout and lock |
37
39
 
38
40
  Auth is unchanged: existing `agy` OAuth (`~/.gemini/oauth_creds.json`).
39
41
 
@@ -73,10 +75,11 @@ timeout), so a provider turn never races `agy_execute` in the same directory.
73
75
  Read-only tool bridge: provider turns also get an extra `--add-dir`
74
76
  carrying a localhost MCP server (`pi-agy-tools`) that exposes Pi-side
75
77
  context agy cannot see otherwise — `agy_sessions_list`, `agy_quota_report`,
76
- and `agy_model_catalog`. The server binds 127.0.0.1 with a per-process
77
- shared secret, serves only reads, and never touches your global agy config.
78
- Set `"providerBridge": false` in `agy-config.json` to run provider turns
79
- plain.
78
+ `agy_model_catalog`, and `activate_skill` (which dynamically lists and injects
79
+ Pi Agent Skills from `~/.pi/agent/skills`, `~/.agents/skills`, and `.pi/skills`).
80
+ The server binds 127.0.0.1 with a per-process shared secret, serves only reads,
81
+ and never touches your global agy config. Set `"providerBridge": false` in
82
+ `agy-config.json` to run provider turns plain.
80
83
 
81
84
  Mutating tool bridge: agy turns can also call Pi tools directly. The bridge
82
85
  parks the MCP call, the provider emits a real shadow `toolCall`, and Pi
@@ -84,9 +87,11 @@ executes it with normal permissions, approvals, and diff review; the next
84
87
  turn's `toolResult` completes the parked call and agy continues. Only active
85
88
  non-builtin tools are exposed (`agy_*` and `AskAntigravity` excluded — no
86
89
  recursive delegation); the catalog refreshes per turn and the driver recycles
87
- when it changes so agy always sees a fresh tool list. Suspended turns hold
88
- the agy child with timers off, re-arm on resume, and are abandoned loudly on
89
- cancel, teardown, or a 30-minute stall cap.
90
+ when it changes so agy always sees a fresh tool list. Long calls over 20 seconds
91
+ early-ack with `STILL RUNNING` and a `callId` so agy can poll via
92
+ `bridge_poll_result`, completely avoiding agy's ~180-second MCP client timeout.
93
+ Suspended turns hold the agy child with timers off, re-arm on resume, and are
94
+ abandoned loudly on cancel, teardown, or a 30-minute stall cap.
90
95
 
91
96
  Do not install `@estebanforge/pi-antigravity-bridge` alongside this package:
92
97
  both register the `antigravity` provider id and an `/agy` command.
@@ -41,12 +41,22 @@ import {
41
41
  type AgyProviderModelEntry,
42
42
  } from "./provider-models.js";
43
43
  import { getHistory } from "./sessions.js";
44
+ import {
45
+ ACTIVATE_SKILL_TOOL_NAME,
46
+ formatSkillsSummary,
47
+ readSkillContent,
48
+ scanSkills,
49
+ type SkillEntry,
50
+ } from "./skills.js";
44
51
  import { runPreflightCommand } from "./spawn.js";
45
52
 
46
53
  export const BRIDGE_MCP_KEY = "pi-agy-tools";
47
- /** Built-in read-only tools (sessions, quota, catalog), plus dynamic bridged Pi tools. */
48
- const BUILTIN_TOOL_COUNT = 3;
54
+ /** Built-in read-only tools (sessions, quota, catalog, activate_skill, bridge_poll_result), plus dynamic bridged Pi tools. */
55
+ const BUILTIN_TOOL_COUNT = 5;
49
56
  export const BRIDGE_TOKEN_HEADER = "x-pi-agy-token";
57
+ export const POLL_TOOL_NAME = "bridge_poll_result";
58
+ /** Async escalation threshold: park requests longer than this early-ack so agy's 180s timeout is avoided. */
59
+ export const DEFAULT_PARK_ESCALATE_MS = 20_000;
50
60
  const BRIDGE_MCP_PATH = "/mcp";
51
61
  const MAX_BODY_BYTES = 1024 * 1024;
52
62
  const CATALOG_TTL_MS = 5 * 60_000;
@@ -205,12 +215,20 @@ interface CatalogCache {
205
215
  at: number;
206
216
  }
207
217
 
218
+ export interface StartMcpBridgeOptions {
219
+ escalateAfterMs?: number;
220
+ }
221
+
208
222
  /**
209
223
  * Start the bridge for a workspace directory. Never throws: any failure
210
224
  * cleans up and resolves `undefined` so provider turns proceed plain.
211
225
  */
212
- export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | undefined> {
226
+ export async function startMcpBridge(
227
+ dir: string,
228
+ options?: StartMcpBridgeOptions,
229
+ ): Promise<McpBridgeHandle | undefined> {
213
230
  const token = randomBytes(32).toString("hex");
231
+ const escalateAfterMs = options?.escalateAfterMs ?? DEFAULT_PARK_ESCALATE_MS;
214
232
  let catalogCache: CatalogCache | undefined;
215
233
 
216
234
  const mcp = new McpServer(
@@ -221,45 +239,78 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
221
239
  let bridgedTools: BridgeToolDef[] = [];
222
240
  let parkHandler: BridgeParkHandler | undefined;
223
241
  const parks = new Map<string, (result: BridgeToolResult) => void>();
242
+ const escalations = new Map<
243
+ string,
244
+ { name: string; state: "running" | "done" | "failed"; result?: BridgeToolResult; reason?: string }
245
+ >();
224
246
 
225
- mcp.setRequestHandler(ListToolsRequestSchema, () => ({
226
- tools: [
227
- ...bridgedTools.map((tool) => ({
228
- name: tool.name,
229
- description: `${tool.description} (Pi tool: runs with Pi permissions and review.)`,
230
- inputSchema: tool.inputSchema,
231
- })),
232
- {
233
- name: "agy_sessions_list",
234
- description:
235
- "List recorded agy conversations for a directory (ids, models, ages, summaries) to find a conversation to resume. Read-only.",
236
- inputSchema: {
237
- type: "object",
238
- properties: {
239
- dir: { type: "string", description: "Directory to list. Defaults to the current workspace." },
240
- limit: { type: "number", description: "Maximum entries (default 10, max 10)." },
247
+ mcp.setRequestHandler(ListToolsRequestSchema, () => {
248
+ const skills = scanSkills(dir);
249
+ return {
250
+ tools: [
251
+ ...bridgedTools.map((tool) => ({
252
+ name: tool.name,
253
+ description: `${tool.description} (Pi tool: runs with Pi permissions and review. Long calls over 20s report STILL RUNNING; fetch via ${POLL_TOOL_NAME}.)`,
254
+ inputSchema: tool.inputSchema,
255
+ })),
256
+ {
257
+ name: "agy_sessions_list",
258
+ description:
259
+ "List recorded agy conversations for a directory (ids, models, ages, summaries) to find a conversation to resume. Read-only.",
260
+ inputSchema: {
261
+ type: "object",
262
+ properties: {
263
+ dir: { type: "string", description: "Directory to list. Defaults to the current workspace." },
264
+ limit: { type: "number", description: "Maximum entries (default 10, max 10)." },
265
+ },
241
266
  },
242
267
  },
243
- },
244
- {
245
- name: "agy_quota_report",
246
- description:
247
- "Read current Antigravity model quotas and reset times without spending a model turn. Read-only.",
248
- inputSchema: {
249
- type: "object",
250
- properties: {
251
- model: { type: "string", description: "Optional agy model slug to focus the report." },
268
+ {
269
+ name: "agy_quota_report",
270
+ description:
271
+ "Read current Antigravity model quotas and reset times without spending a model turn. Read-only.",
272
+ inputSchema: {
273
+ type: "object",
274
+ properties: {
275
+ model: { type: "string", description: "Optional agy model slug to focus the report." },
276
+ },
252
277
  },
253
278
  },
254
- },
255
- {
256
- name: "agy_model_catalog",
257
- description:
258
- "List agy models available to this workspace as Pi picker entries (id, agy --model value, effort tiers). Read-only.",
259
- inputSchema: { type: "object", properties: {} },
260
- },
261
- ],
262
- }));
279
+ {
280
+ name: "agy_model_catalog",
281
+ description:
282
+ "List agy models available to this workspace as Pi picker entries (id, agy --model value, effort tiers). Read-only.",
283
+ inputSchema: { type: "object", properties: {} },
284
+ },
285
+ {
286
+ name: ACTIVATE_SKILL_TOOL_NAME,
287
+ description: `Activate a Pi Agent Skill to read its full instructions (SKILL.md). Available skills:\n${formatSkillsSummary(skills)}`,
288
+ inputSchema: {
289
+ type: "object",
290
+ properties: {
291
+ name: {
292
+ type: "string",
293
+ description: "Skill name to activate from the catalog.",
294
+ },
295
+ },
296
+ required: ["name"],
297
+ },
298
+ },
299
+ {
300
+ name: POLL_TOOL_NAME,
301
+ description:
302
+ "Poll the result of a long-running bridged Pi tool call that returned STILL RUNNING.",
303
+ inputSchema: {
304
+ type: "object",
305
+ properties: {
306
+ callId: { type: "string", description: "Call ID returned in the STILL RUNNING message." },
307
+ },
308
+ required: ["callId"],
309
+ },
310
+ },
311
+ ],
312
+ };
313
+ });
263
314
 
264
315
  mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
265
316
  try {
@@ -300,6 +351,52 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
300
351
  `agy models${entries.fallback ? " (fallback catalog — live discovery unavailable)" : ""}:\n${lines.join("\n")}`,
301
352
  );
302
353
  }
354
+ if (name === ACTIVATE_SKILL_TOOL_NAME) {
355
+ const skillName = stringArg(args.name);
356
+ if (!skillName) {
357
+ return toolText("Error: skill 'name' argument is required.", true);
358
+ }
359
+ const skills = scanSkills(dir);
360
+ const found = skills.find((s) => s.name === skillName);
361
+ if (!found) {
362
+ return toolText(`Unknown skill: "${skillName}". Available skills:\n${formatSkillsSummary(skills)}`, true);
363
+ }
364
+ const body = readSkillContent(found);
365
+ return toolText(body);
366
+ }
367
+ if (name === POLL_TOOL_NAME) {
368
+ const callId = stringArg(args.callId);
369
+ if (!callId) {
370
+ return toolText("Error: 'callId' argument is required.", true);
371
+ }
372
+ const record = escalations.get(callId);
373
+ if (!record) {
374
+ return toolText(
375
+ `Error: no escalated bridge call "${callId}". It either finished synchronously or the callId is invalid.`,
376
+ true,
377
+ );
378
+ }
379
+ if (record.state === "running") {
380
+ return toolText(
381
+ `STILL RUNNING: Pi tool "${record.name}" (callId ${callId}) has not finished yet. Poll again shortly.`,
382
+ false,
383
+ );
384
+ }
385
+ if (record.state === "failed") {
386
+ escalations.delete(callId);
387
+ return toolText(
388
+ `Error: Pi tool "${record.name}" failed: ${record.reason ?? "unknown failure"}`,
389
+ true,
390
+ );
391
+ }
392
+ // Delivered done result; clean up escalation entry.
393
+ escalations.delete(callId);
394
+ const result = record.result;
395
+ return {
396
+ content: [{ type: "text" as const, text: result?.text ?? "(no output)" }],
397
+ ...(result?.isError ? { isError: true as const } : {}),
398
+ };
399
+ }
303
400
  const bridged = bridgedTools.find((tool) => tool.name === name);
304
401
  if (bridged) {
305
402
  const callArgs =
@@ -311,8 +408,21 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
311
408
  if (!handler) {
312
409
  return toolText("Pi tool bridge is not awaiting calls right now; retry shortly.", true);
313
410
  }
411
+ let escalateTimer: NodeJS.Timeout | undefined;
412
+ let didEscalate = false;
314
413
  const parked = await new Promise<BridgeToolResult | undefined>((resolve) => {
315
- parks.set(callId, resolve);
414
+ parks.set(callId, (res) => {
415
+ if (escalateTimer) clearTimeout(escalateTimer);
416
+ if (didEscalate) {
417
+ const record = escalations.get(callId);
418
+ if (record) {
419
+ record.state = "done";
420
+ record.result = res;
421
+ }
422
+ } else {
423
+ resolve(res);
424
+ }
425
+ });
316
426
  let accepted = false;
317
427
  try {
318
428
  accepted = handler({ callId, toolName: bridged.piName, args: callArgs });
@@ -322,7 +432,22 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
322
432
  if (!accepted) {
323
433
  parks.delete(callId);
324
434
  resolve(undefined);
435
+ return;
325
436
  }
437
+ // Early-ack escalation: if the tool runs longer than escalateAfterMs,
438
+ // settle the MCP request with STILL RUNNING so agy avoids its 180s timeout.
439
+ escalateTimer = setTimeout(() => {
440
+ didEscalate = true;
441
+ escalations.set(callId, { name: bridged.piName, state: "running" });
442
+ resolve({
443
+ text: [
444
+ `STILL RUNNING: the Pi tool "${bridged.piName}" has not finished yet.`,
445
+ `Call ${POLL_TOOL_NAME} with callId "${callId}" to fetch the result. Poll again if it is still running; you may perform other tasks in between.`,
446
+ ].join("\n"),
447
+ isError: false,
448
+ });
449
+ }, escalateAfterMs);
450
+ (escalateTimer as unknown as { unref?: () => void }).unref?.();
326
451
  });
327
452
  if (!parked) {
328
453
  return toolText("Pi turn is not awaiting tool calls; the call was not executed.", true);
@@ -380,6 +505,12 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
380
505
  });
381
506
 
382
507
  const failAllParks = (message: string): void => {
508
+ for (const [callId, rec] of escalations) {
509
+ if (rec.state === "running") {
510
+ rec.state = "failed";
511
+ rec.reason = message;
512
+ }
513
+ }
383
514
  if (parks.size === 0) return;
384
515
  const pending = [...parks.values()];
385
516
  parks.clear();
@@ -393,6 +524,13 @@ export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | und
393
524
  };
394
525
 
395
526
  const completePark = (callId: string, result: BridgeToolResult): boolean => {
527
+ const esc = escalations.get(callId);
528
+ if (esc && esc.state === "running") {
529
+ esc.state = "done";
530
+ esc.result = result;
531
+ parks.delete(callId);
532
+ return true;
533
+ }
396
534
  const resolve = parks.get(callId);
397
535
  if (!resolve) return false;
398
536
  parks.delete(callId);
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Pi Agent Skills discovery and catalog loader for the MCP bridge.
3
+ *
4
+ * Scans Pi and agents skill locations:
5
+ * - Global: ~/.pi/agent/skills and ~/.agents/skills
6
+ * - Project: .pi/skills and .agents/skills in cwd + ancestors up to git root
7
+ *
8
+ * Exposes a tool `activate_skill` to agy via MCP with an enum of available skills.
9
+ * When called, returns the raw markdown content of the selected skill's SKILL.md.
10
+ */
11
+
12
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
13
+ import * as os from "node:os";
14
+ import * as path from "node:path";
15
+
16
+ export const ACTIVATE_SKILL_TOOL_NAME = "activate_skill";
17
+
18
+ export interface SkillEntry {
19
+ name: string;
20
+ description: string;
21
+ filePath: string;
22
+ dir: string;
23
+ }
24
+
25
+ export interface SkillLocation {
26
+ dir: string;
27
+ style: "pi" | "agents";
28
+ }
29
+
30
+ const MAX_DEPTH = 16;
31
+
32
+ /** Parse `name:` and `description:` out of SKILL.md YAML frontmatter. */
33
+ export function parseSkillFrontmatter(raw: string): { name?: string; description?: string } {
34
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
35
+ if (!match) return {};
36
+ const out: { name?: string; description?: string } = {};
37
+ for (const line of match[1].split(/\r?\n/)) {
38
+ const nameMatch = line.match(/^name:\s*(.+)$/);
39
+ if (nameMatch && !out.name) {
40
+ out.name = nameMatch[1].trim();
41
+ }
42
+ const descMatch = line.match(/^description:\s*(.+)$/);
43
+ if (descMatch && !out.description) {
44
+ out.description = descMatch[1].trim();
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** Get search directories for skills according to Pi & agents conventions. */
51
+ export function getSkillLocations(projectDir?: string, home: string = os.homedir()): SkillLocation[] {
52
+ const locs: SkillLocation[] = [
53
+ { dir: path.join(home, ".pi", "agent", "skills"), style: "pi" },
54
+ { dir: path.join(home, ".agents", "skills"), style: "agents" },
55
+ ];
56
+ if (!projectDir) return locs;
57
+
58
+ locs.push({ dir: path.join(projectDir, ".pi", "skills"), style: "pi" });
59
+
60
+ let cur = path.resolve(projectDir);
61
+ while (true) {
62
+ locs.push({ dir: path.join(cur, ".agents", "skills"), style: "agents" });
63
+ const parent = path.dirname(cur);
64
+ if (parent === cur || existsSync(path.join(cur, ".git"))) break;
65
+ cur = parent;
66
+ }
67
+
68
+ return locs;
69
+ }
70
+
71
+ function readSkillFile(file: string, fallbackName: string): SkillEntry | null {
72
+ let raw = "";
73
+ try {
74
+ raw = readFileSync(file, "utf8").replace(/^\uFEFF/, "");
75
+ } catch {
76
+ return null;
77
+ }
78
+ const fm = parseSkillFrontmatter(raw);
79
+ const description = (fm.description ?? "").trim();
80
+ if (!description) return null;
81
+
82
+ return {
83
+ name: fm.name?.trim() || fallbackName,
84
+ description: description.replace(/\s+/g, " ").slice(0, 160),
85
+ filePath: file,
86
+ dir: path.dirname(file),
87
+ };
88
+ }
89
+
90
+ function scanLocation(loc: SkillLocation): SkillEntry[] {
91
+ const walk = (dir: string, depth: number): SkillEntry[] => {
92
+ if (depth > MAX_DEPTH) return [];
93
+ let entries: string[] = [];
94
+ try {
95
+ entries = readdirSync(dir);
96
+ } catch {
97
+ return [];
98
+ }
99
+ const found: SkillEntry[] = [];
100
+ for (const entry of entries) {
101
+ if (entry.startsWith(".")) continue;
102
+ const full = path.join(dir, entry);
103
+ let isDir = false;
104
+ try {
105
+ const s = statSync(full);
106
+ isDir = s.isDirectory();
107
+ } catch {
108
+ continue;
109
+ }
110
+ if (isDir) {
111
+ const skillMd = path.join(full, "SKILL.md");
112
+ if (existsSync(skillMd)) {
113
+ const skill = readSkillFile(skillMd, entry);
114
+ if (skill) found.push(skill);
115
+ } else {
116
+ found.push(...walk(full, depth + 1));
117
+ }
118
+ continue;
119
+ }
120
+ if (!entry.endsWith(".md") || entry === "SKILL.md") continue;
121
+ const standalone = loc.style === "pi" ? depth === 0 : depth > 0;
122
+ if (!standalone) continue;
123
+ const skill = readSkillFile(full, entry.replace(/\.md$/, ""));
124
+ if (skill) found.push(skill);
125
+ }
126
+ return found;
127
+ };
128
+ return walk(loc.dir, 0);
129
+ }
130
+
131
+ /**
132
+ * Scan for all available Pi skills across standard locations.
133
+ * Deduped by skill name (first found wins).
134
+ */
135
+ export function scanSkills(projectDir?: string, home: string = os.homedir()): SkillEntry[] {
136
+ const seen = new Set<string>();
137
+ const out: SkillEntry[] = [];
138
+ for (const loc of getSkillLocations(projectDir, home)) {
139
+ for (const skill of scanLocation(loc)) {
140
+ if (seen.has(skill.name)) continue;
141
+ seen.add(skill.name);
142
+ out.push(skill);
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /** Format skills for the MCP tool description. */
149
+ export function formatSkillsSummary(skills: SkillEntry[]): string {
150
+ if (skills.length === 0) return "No skills available.";
151
+ return skills.map((s) => `- ${s.name}: ${s.description}`).join("\n");
152
+ }
153
+
154
+ /** Read the markdown content of a skill. */
155
+ export function readSkillContent(skill: SkillEntry): string {
156
+ try {
157
+ return readFileSync(skill.filePath, "utf8");
158
+ } catch (err) {
159
+ return `Error reading skill file: ${err instanceof Error ? err.message : String(err)}`;
160
+ }
161
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanbenjumea/pi-agy",
3
- "version": "0.7.6",
3
+ "version": "0.7.7",
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",
@@ -51,9 +51,9 @@
51
51
  "@sinclair/typebox": "*"
52
52
  },
53
53
  "devDependencies": {
54
- "@earendil-works/pi-ai": "^0.86.1",
55
- "@earendil-works/pi-coding-agent": "^0.86.1",
56
- "@earendil-works/pi-tui": "^0.86.1",
54
+ "@earendil-works/pi-ai": "^0.87.1",
55
+ "@earendil-works/pi-coding-agent": "^0.87.1",
56
+ "@earendil-works/pi-tui": "^0.87.1",
57
57
  "@sinclair/typebox": "^0.34.41",
58
58
  "@types/node": "^22.20.4",
59
59
  "typescript": "^5.0.0"