@estebanforge/pi-antigravity-bridge 1.10.9 → 1.12.0

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/src/provider.ts CHANGED
@@ -232,15 +232,91 @@ export interface DigestOptions {
232
232
  ownProvider?: string;
233
233
  /** Soft cap on the digest body (0 = unbounded). Default 8000. */
234
234
  maxChars?: number;
235
+ /** Conversation binding state. bound=true (default): own-provider turns
236
+ * are already in agy's resumed DB and are skipped. bound=false: the agy
237
+ * conversation holds NOTHING (fresh conversation from a mid-session
238
+ * model switch, an engine switch, or recreation recovery), so
239
+ * own-provider turns and their tool results ship too. */
240
+ bound?: boolean;
241
+ /** Compaction summary identity already delivered in a previous digest
242
+ * (compactionFingerprint of the stripped summary text). Index identity
243
+ * is wrong: pi rebuilds post-compaction transcripts with the summary at
244
+ * the front, so every compaction lands at the same index; content
245
+ * identity ships a NEW summary exactly once. */
246
+ seenSummaryId?: string;
247
+ }
248
+
249
+ /** Soft cap on the digest body when no tighter budget applies. */
250
+ const DIGEST_MAX_CHARS = 8000;
251
+
252
+ /** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
253
+ * the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
254
+ * and the dropped turn leaves the conversation permanently unresponsive. */
255
+ const STREAM_JSON_PROMPT_CAP = 25_000;
256
+ /** Headroom under the cap for the staged-image note and prompt framing. */
257
+ const STREAM_JSON_PROMPT_MARGIN = 4_096;
258
+
259
+ /** Per-engine digest cap. ACP ships the digest as an embeddedContext
260
+ resource block: no prompt cap applies, so the default cap stands. On
261
+ stream-json the digest rides inline in the prompt, so it must fit under
262
+ the silent-drop budget alongside the user's own prompt bytes. Returns
263
+ null when the budget is already exhausted (ship nothing rather than a
264
+ digest that would push the turn over the drop cap). */
265
+ export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
266
+ if (engine === "acp") return DIGEST_MAX_CHARS;
267
+ const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
268
+ return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
269
+ }
270
+
271
+ /** role:timestamp fingerprint of the message a watermark points at (the
272
+ digest boundary). A transcript mutated under the stored count (/tree,
273
+ /fork, per-call context-hook rewrites) changes the boundary message, so a
274
+ stored fingerprint that no longer match es invalidates the delta window
275
+ and the digest falls back to the full delta (the Codex WebSocket
276
+ continuation baseline-check pattern: verify before you trust a counter). */
277
+ export function boundaryFingerprint(m: Message | undefined): string | undefined {
278
+ return m ? `${m.role}:${m.timestamp}` : undefined;
279
+ }
280
+
281
+ /** Index of the most recent compaction summary in the transcript, -1 if none. */
282
+ export function findLastCompactionIdx(messages: Message[]): number {
283
+ for (let i = messages.length - 1; i >= 0; i--) {
284
+ const m = messages[i];
285
+ if (m.role !== "user") continue;
286
+ if (blocksToText(m.content).includes(COMPACTION_MARKER)) return i;
287
+ }
288
+ return -1;
289
+ }
290
+
291
+ /** Content identity of a compaction summary message (length + FNV-1a of the
292
+ stripped text). pi puts every post-compaction summary at the transcript
293
+ front, so index identity would swallow the second compaction; this id
294
+ ships a new summary exactly once. */
295
+ export function compactionFingerprint(m: Message): string {
296
+ const text = stripCompactionWrapping(blocksToText(m.content));
297
+ let hash = 0x811c9dc5;
298
+ for (let i = 0; i < text.length; i++) {
299
+ hash ^= text.charCodeAt(i);
300
+ hash = Math.imul(hash, 0x01000193);
301
+ }
302
+ return `${text.length}:${(hash >>> 0).toString(16)}`;
235
303
  }
236
304
 
237
305
  /** Build a delta digest of pi-side context agy was not spawned for: the most
238
- * recent compaction summary plus turns since the watermark that were not
239
- * produced by this provider. Pure: no I/O. Exported for unit testing.
306
+ * recent undelivered compaction summary plus turns since the watermark that
307
+ * were not produced by this provider (in bound mode). Pure: no I/O.
308
+ * Exported for unit testing.
309
+ *
310
+ * Delta, not replay: in bound mode skip our own assistant turns
311
+ * (provider === ownProvider) - they are already in agy's resumed DB. In
312
+ * fresh mode (bound: false) the conversation holds nothing, so own turns
313
+ * ship too.
240
314
  *
241
- * Delta, not replay: skip our own assistant turns (provider === ownProvider)
242
- * and clamp the window to after any compaction (pre-compaction detail is
243
- * either already in agy's DB or summarized by the injected summary).
315
+ * Compaction-aware reset: a compaction can shrink the transcript below the
316
+ * stored watermark, which would empty the delta window and silently drop
317
+ * every post-compaction turn. The window instead restarts after the
318
+ * compaction, and the summary itself ships exactly once (tracked by
319
+ * seenSummaryId, content-keyed) to keep steady-state prompts byte-stable.
244
320
  *
245
321
  * Fidelity note: other-provider assistant turns contribute only their text
246
322
  * blocks; tool-call and thinking blocks are dropped. The intent (which tool)
@@ -251,41 +327,46 @@ export function buildContextDigest(
251
327
  opts: DigestOptions = {},
252
328
  ): string {
253
329
  const own = opts.ownProvider ?? "antigravity";
254
- const maxChars = opts.maxChars ?? 8000;
330
+ const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
255
331
  if (messages.length === 0) return "";
256
332
 
257
- let summaryPart: string | null = null;
258
333
  const deltaParts: string[] = [];
259
334
 
260
- // 1. Most-recent compaction summary (scan the whole list; it is never in
261
- // agy's DB, so it is always safe and high-value to inject).
262
- let lastCompactionIdx = -1;
263
- for (let i = messages.length - 1; i >= 0; i--) {
264
- const m = messages[i];
265
- if (m.role !== "user") continue;
266
- const t = blocksToText(m.content);
267
- if (t.includes(COMPACTION_MARKER)) {
268
- lastCompactionIdx = i;
269
- summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(t)}`;
270
- break;
335
+ // 1. Compaction summary (never in agy's DB, so always high-value), but
336
+ // only when THIS summary has not shipped in a previous digest.
337
+ const compactionIdx = findLastCompactionIdx(messages);
338
+ let summaryPart: string | null = null;
339
+ if (compactionIdx >= 0) {
340
+ const summaryMessage = messages[compactionIdx];
341
+ if (compactionFingerprint(summaryMessage) !== opts.seenSummaryId) {
342
+ summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(blocksToText(summaryMessage.content))}`;
271
343
  }
272
344
  }
273
345
 
274
- // 2. Delta since the watermark, excluding the trailing current prompt.
275
- // Clamp start to just after the compaction summary when one is present.
346
+ // 2. Delta window. Two stale-watermark shapes both clamp to after the
347
+ // compaction: a watermark below it (pre-compaction history is dropped
348
+ // or summarized) and a watermark above the transcript (the compaction
349
+ // shrank the list under the stored count; without the clamp the window
350
+ // would be empty and every post-compaction turn silently dropped).
351
+ // Without a compaction, a watermark above the transcript (branch/prune
352
+ // without a marker) falls back to the full delta.
276
353
  let start = Math.max(0, Math.floor(watermark));
277
- if (lastCompactionIdx >= 0) start = Math.max(start, lastCompactionIdx + 1);
354
+ if (compactionIdx >= 0) {
355
+ if (start < compactionIdx + 1 || watermark > messages.length) start = compactionIdx + 1;
356
+ } else if (watermark > messages.length) {
357
+ start = 0;
358
+ }
278
359
  const end = Math.max(0, messages.length - 1);
279
360
  for (let i = start; i < end; i++) {
280
361
  const m = messages[i];
281
362
  if (m.role === "assistant") {
282
- if (m.provider === own) continue; // our own turn: already in agy's DB
363
+ if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
283
364
  const t = blocksToText(m.content).trim();
284
365
  if (!t) continue;
285
366
  deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
286
367
  } else if (m.role === "user") {
287
368
  const t = blocksToText(m.content);
288
- if (t.includes(COMPACTION_MARKER)) continue; // injected as summaryPart
369
+ if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
289
370
  if (!t.trim()) continue;
290
371
  deltaParts.push(`[earlier user message]\n${t}`);
291
372
  } else if (m.role === "toolResult") {
@@ -296,13 +377,18 @@ export function buildContextDigest(
296
377
  }
297
378
  }
298
379
 
299
- // Assemble. The compaction summary is always kept intact (it is the
300
- // canonical compressed history). The DELTA is truncated from the newest end
301
- // backward when over budget: recent context matters more for continuity
302
- // than older detail, so drop the oldest delta first. If even the newest
303
- // single item exceeds the budget, keep its tail slice.
380
+ // Assemble. The compaction summary is clamped to the budget (head kept:
381
+ // a summary reads top-down, and an oversized one must not push a
382
+ // stream-json turn over the silent-drop cap). The DELTA is truncated from
383
+ // the newest end backward when over budget: recent context matters more
384
+ // for continuity than older detail, so drop the oldest delta first. If
385
+ // even the newest single item exceeds the budget, keep its tail slice.
304
386
  const SEP = "\n\n";
305
387
  const MARKER = "[truncated]";
388
+ if (summaryPart && maxChars > 0 && summaryPart.length > maxChars) {
389
+ const room = Math.max(0, maxChars - MARKER.length - 1);
390
+ summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
391
+ }
306
392
  let delta = deltaParts.join(SEP);
307
393
  if (maxChars > 0) {
308
394
  const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
@@ -346,7 +432,7 @@ function newAssistant(model: Model<Api>): AssistantMessage {
346
432
 
347
433
  /** Session key: prefer pi's sessionId (stable per conversation), fall back to
348
434
  * cwd so a single pi process still resumes correctly when sessionId is absent. */
349
- function sessionKey(
435
+ export function sessionKey(
350
436
  options: SimpleStreamOptions | undefined,
351
437
  cwd: string,
352
438
  engine: "stream-json" | "acp",
@@ -814,7 +900,7 @@ export class ToolRoundTrips {
814
900
  ? payload.toolCall.args
815
901
  : {}) as Record<string, unknown>;
816
902
  const mapped = mapNativeToShadow(native, args);
817
- if (!mapped) return deny(`tool ${native} is not in the approval matcher set`);
903
+ if (!mapped) return deny(`tool ${native} did not map to a shadow call (ungated or unresolved target path)`);
818
904
  const entry: PendingRoundTrip = {
819
905
  kind: "approval",
820
906
  name: mapped.shadow,
@@ -1162,10 +1248,10 @@ function emitToolUse(
1162
1248
  }
1163
1249
 
1164
1250
  /** ACP edit-class tool names that carry a file-path arg and land the file on
1165
- * disk (observed live: edit_file, create_file). Read/execute tools also
1166
- * match the arg-shape heuristic but produce no diff (unchanged content), so
1167
- * the gate avoids mislabeling them as edits. */
1168
- const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file"]);
1251
+ * disk (observed live: edit_file, create_file, write_file on agy 1.5.11).
1252
+ * Read/execute tools also match the arg-shape heuristic but produce no diff
1253
+ * (unchanged content), so the gate avoids mislabeling them as edits. */
1254
+ const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file", "write_file"]);
1169
1255
 
1170
1256
  export function consumeActivity(
1171
1257
  stream: AssistantMessageEventStream,
@@ -1348,6 +1434,13 @@ async function runTurnDriver(
1348
1434
  const existing = store.get(key);
1349
1435
  const messageCount = context.messages.length;
1350
1436
  const config = loadConfig();
1437
+ // Settle bookkeeping shared by both store.set paths: the boundary
1438
+ // fingerprint validates next turn's delta window, and the compaction
1439
+ // index suppresses summary re-injection once this turn delivered it.
1440
+ const settleBoundary = boundaryFingerprint(context.messages[messageCount - 1]);
1441
+ // Summary id carried forward from the record; the gate below overwrites it
1442
+ // only when a digest actually ships, so skipped turns never lose it.
1443
+ let settleSummaryId = existing?.digestSummaryId;
1351
1444
 
1352
1445
  // Continuation: resolve parked round-trips from pi's toolResult messages,
1353
1446
  // then re-attach to the still-running agy turn. No new user event is sent:
@@ -1505,11 +1598,50 @@ async function runTurnDriver(
1505
1598
  finalize(stream, blocks, "error", "No user message to send to agy.");
1506
1599
  return;
1507
1600
  }
1508
- const watermark = existing?.lastMessageCount ?? 0;
1601
+ const rawWatermark = existing?.lastMessageCount ?? 0;
1602
+ // Boundary fingerprint check (see boundaryFingerprint): a transcript
1603
+ // mutated under the stored count (/tree, /fork, context-hook rewrites)
1604
+ // resets the delta to the full digest instead of a silently wrong one.
1605
+ // Records written before the fingerprint existed (digestBoundary unset)
1606
+ // trust the count: the old code advanced it the same way, so reseting
1607
+ // would dump a one-time full delta of history agy already holds.
1608
+ const storedBoundary = existing?.digestBoundary;
1609
+ const watermark =
1610
+ rawWatermark > 0 &&
1611
+ (storedBoundary === undefined ||
1612
+ storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]))
1613
+ ? rawWatermark
1614
+ : 0;
1509
1615
  // Late and resume turns re-open the conversation with a synthetic
1510
1616
  // prompt; the digest would re-send context agy already holds (against a
1511
1617
  // stale watermark: a failed pass never advances it), so skip it.
1512
- const digest = config.digest && late.length === 0 && !resume ? buildContextDigest(context.messages, watermark) : "";
1618
+ const engine = deps.engine ?? config.engine;
1619
+ const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
1620
+ const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1621
+ const digest =
1622
+ config.digest && maxChars !== null && late.length === 0 && !resume
1623
+ ? buildContextDigest(context.messages, watermark, {
1624
+ bound: Boolean(existing?.conversationId),
1625
+ seenSummaryId: existing?.digestSummaryId,
1626
+ maxChars,
1627
+ })
1628
+ : "";
1629
+ // Byte-level fail closed (issue #2): the char budget over-reserves for
1630
+ // ASCII but a multibyte digest can still exceed the remaining byte
1631
+ // room. ACP carries no prompt cap, so the check is stream-json only.
1632
+ const digestFinal =
1633
+ digest &&
1634
+ engine !== "acp" &&
1635
+ promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
1636
+ ? ""
1637
+ : digest;
1638
+ // The delivered summary id persists only when a digest actually shipped:
1639
+ // late/resume/budget-skipped turns carry the previous id forward so the
1640
+ // summary is not lost to a turn that never delivered it.
1641
+ if (digestFinal) {
1642
+ const deliveredIdx = findLastCompactionIdx(context.messages);
1643
+ settleSummaryId = deliveredIdx >= 0 ? compactionFingerprint(context.messages[deliveredIdx]) : undefined;
1644
+ }
1513
1645
  // G1 delivery per engine. stream-json: digest rides inline in the prompt
1514
1646
  // (the CLI has no context channel). ACP: the server advertises
1515
1647
  // `embeddedContext`, so the digest ships as a native resource block
@@ -1518,7 +1650,7 @@ async function runTurnDriver(
1518
1650
  // surface, and the model needs the use-for-continuity-only instruction.
1519
1651
  // The uri is suffixed per turn so a deduping server cannot serve stale
1520
1652
  // content on turn 2+.
1521
- const embeddedDigest = deps.engine === "acp" && digest ? digest : undefined;
1653
+ const embeddedDigest = deps.engine === "acp" && digestFinal ? digestFinal : undefined;
1522
1654
  // G10, fresh conversations only (bound conversations ride agy's own
1523
1655
  // history; re-sending would bloat every prompt and bust the cache).
1524
1656
  // stream-json delivery is a staged agent file, NOT prompt text: agy's
@@ -1564,7 +1696,7 @@ async function runTurnDriver(
1564
1696
  const fullPrompt =
1565
1697
  (late.length > 0
1566
1698
  ? buildLateResultPrompt(late, prompt || undefined)
1567
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digest, prompt ?? "")) +
1699
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
1568
1700
  stageImageNote(runImages);
1569
1701
  try {
1570
1702
  handle = await deps.driver.run({
@@ -1641,7 +1773,13 @@ async function runTurnDriver(
1641
1773
  if (!existing) {
1642
1774
  const parkedConv = deps.driver.snapshot().conversationId;
1643
1775
  if (parkedConv) {
1644
- store.set(key, { conversationId: parkedConv, lastStepIdx: -1, lastMessageCount: messageCount });
1776
+ store.set(key, {
1777
+ conversationId: parkedConv,
1778
+ lastStepIdx: -1,
1779
+ lastMessageCount: messageCount,
1780
+ digestBoundary: settleBoundary,
1781
+ digestSummaryId: settleSummaryId,
1782
+ });
1645
1783
  if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
1646
1784
  }
1647
1785
  }
@@ -1765,6 +1903,8 @@ async function runTurnDriver(
1765
1903
  conversationId: outcome.conversationId,
1766
1904
  lastStepIdx: -1,
1767
1905
  lastMessageCount: messageCount,
1906
+ digestBoundary: settleBoundary,
1907
+ digestSummaryId: settleSummaryId,
1768
1908
  });
1769
1909
  if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
1770
1910
  }
package/src/sessions.ts CHANGED
@@ -6,19 +6,15 @@
6
6
  //
7
7
  // The key is options.sessionId when pi provides it, else the cwd (single-
8
8
  // conversation-per-process fallback). Stored at
9
- // ~/.pi/agent/antigravity-bridge/sessions.json with atomic rename.
9
+ // <agentDir>/antigravity-bridge/sessions.json with atomic rename.
10
10
 
11
11
  import fs from "node:fs";
12
- import os from "node:os";
13
12
  import path from "node:path";
13
+ import { bridgeDir } from "./config.js";
14
14
 
15
- const STORE_PATH = path.join(
16
- os.homedir(),
17
- ".pi",
18
- "agent",
19
- "antigravity-bridge",
20
- "sessions.json",
21
- );
15
+ function defaultStorePath(): string {
16
+ return path.join(bridgeDir(), "sessions.json");
17
+ }
22
18
 
23
19
  export interface AgySession {
24
20
  conversationId: string;
@@ -29,6 +25,16 @@ export interface AgySession {
29
25
  * fresh or pre-watermark session. Optional for backward compat with older
30
26
  * persisted sessions that predate the watermark. */
31
27
  lastMessageCount?: number;
28
+ /** role:timestamp fingerprint of messages[lastMessageCount - 1] at write
29
+ * time. The provider compares it against the live boundary message: a
30
+ * mismatch (branch, fork, context-hook rewrite) resets the digest window
31
+ * to the full delta. Optional: absent on records predating the
32
+ * fingerprint, which the provider treats as a mismatch. */
33
+ digestBoundary?: string;
34
+ /** Compaction index already delivered in a previous digest, so the
35
+ * builder neither re-injects that summary nor restarts its window on
36
+ * it. Optional/absent when no compaction existed at write time. */
37
+ digestSummaryId?: string;
32
38
  }
33
39
 
34
40
  type StoreMap = Record<string, AgySession>;
@@ -48,10 +54,14 @@ function narrowStoreMap(parsed: unknown): StoreMap {
48
54
  if (typeof conversationId !== "string") continue;
49
55
  const idx = (value as { lastStepIdx?: unknown }).lastStepIdx;
50
56
  const mc = (value as { lastMessageCount?: unknown }).lastMessageCount;
57
+ const db = (value as { digestBoundary?: unknown }).digestBoundary;
58
+ const dci = (value as { digestSummaryId?: unknown }).digestSummaryId;
51
59
  clean[key] = {
52
60
  conversationId,
53
61
  lastStepIdx: typeof idx === "number" && Number.isFinite(idx) ? idx : -1,
54
62
  lastMessageCount: typeof mc === "number" && Number.isFinite(mc) ? mc : 0,
63
+ ...(typeof db === "string" ? { digestBoundary: db } : {}),
64
+ ...(typeof dci === "string" ? { digestSummaryId: dci } : {}),
55
65
  };
56
66
  }
57
67
  return clean;
@@ -71,7 +81,7 @@ export class SessionStore {
71
81
  private readonly removed = new Set<string>();
72
82
  private writeChain: Promise<void> = Promise.resolve();
73
83
 
74
- constructor(storePath: string = STORE_PATH) {
84
+ constructor(storePath: string = defaultStorePath()) {
75
85
  this.path = storePath;
76
86
  this.load();
77
87
  }
@@ -93,6 +103,8 @@ export class SessionStore {
93
103
  conversationId: s.conversationId,
94
104
  lastStepIdx: s.lastStepIdx ?? -1,
95
105
  lastMessageCount: s.lastMessageCount ?? 0,
106
+ ...(s.digestBoundary !== undefined ? { digestBoundary: s.digestBoundary } : {}),
107
+ ...(s.digestSummaryId !== undefined ? { digestSummaryId: s.digestSummaryId } : {}),
96
108
  };
97
109
  }
98
110
 
package/src/skills.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  import fs from "node:fs";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
12
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
12
13
 
13
14
  export const ACTIVATE_SKILL_TOOL_NAME = "activate_skill";
14
15
 
@@ -41,9 +42,10 @@ function parseFrontmatter(raw: string): { name?: string; description?: string }
41
42
  // "docs/skills.md - Locations") so the bridge's activate_skill catalog
42
43
  // matches the [Skills] list pi shows in its system prompt:
43
44
  //
44
- // - Global: ~/.pi/agent/skills (pi style) and ~/.agents/skills (agents style,
45
+ // - Global: <agentDir>/skills (pi style) and ~/.agents/skills (agents style,
45
46
  // the cross-harness standard).
46
- // - Project: .pi/skills (pi style) and .agents/skills in cwd + ancestors up
47
+ // - Project: <project>/.pi/skills (pi style; CONFIG_DIR_NAME, so rebranded
48
+ // distros relocate it) and .agents/skills in cwd + ancestors up
47
49
  // to the git repo root (agents style).
48
50
  // - Both styles discover every directory holding a SKILL.md, recursively;
49
51
  // grouping folders (no SKILL.md) are descended into and a skill's contents
@@ -64,16 +66,29 @@ export interface SkillLocation {
64
66
 
65
67
  const MAX_DEPTH = 16; // symlink-loop insurance; real catalogs nest 1-2 levels
66
68
 
67
- /** Ordered skill locations for a session: pi global dirs, then project dirs
68
- * (project `.agents/skills` walks cwd ancestors up to the git root). */
69
- export function skillLocations(projectDir?: string, home: string = os.homedir()): SkillLocation[] {
69
+ export interface SkillScanOptions {
70
+ /** Project root: adds the project pi-skills dir and ancestor .agents/skills
71
+ * dirs (walked up to the git root). */
72
+ projectDir?: string;
73
+ /** HOME override for the cross-harness ~/.agents/skills dir (tests). */
74
+ home?: string;
75
+ /** pi agent dir override for pi's user skills dir (tests). */
76
+ agentDir?: string;
77
+ }
78
+
79
+ /** Ordered skill locations for a session, mirroring pi's own loader:
80
+ * <agentDir>/skills, then cross-harness ~/.agents/skills; with a projectDir
81
+ * also <project>/<CONFIG_DIR_NAME>/skills and each ancestor's .agents/skills. */
82
+ export function skillLocations(opts: SkillScanOptions = {}): SkillLocation[] {
83
+ const home = opts.home ?? os.homedir();
84
+ const agentDir = opts.agentDir ?? getAgentDir();
70
85
  const out: SkillLocation[] = [
71
- { dir: path.join(home, ".pi", "agent", "skills"), style: "pi" },
86
+ { dir: path.join(agentDir, "skills"), style: "pi" },
72
87
  { dir: path.join(home, ".agents", "skills"), style: "agents" },
73
88
  ];
74
- if (!projectDir) return out;
75
- out.push({ dir: path.join(projectDir, ".pi", "skills"), style: "pi" });
76
- let dir = path.resolve(projectDir);
89
+ if (!opts.projectDir) return out;
90
+ out.push({ dir: path.join(opts.projectDir, CONFIG_DIR_NAME, "skills"), style: "pi" });
91
+ let dir = path.resolve(opts.projectDir);
77
92
  for (;;) {
78
93
  out.push({ dir: path.join(dir, ".agents", "skills"), style: "agents" });
79
94
  if (path.dirname(dir) === dir || fs.existsSync(path.join(dir, ".git"))) break;
@@ -144,11 +159,11 @@ function scanLocation(loc: SkillLocation): SkillLite[] {
144
159
  }
145
160
 
146
161
  /** pi-faithful skill catalog: every skill pi itself would load, deduped by
147
- * name (first wins). `home` is injectable for tests. */
148
- export function scanSkills(projectDir?: string, home: string = os.homedir()): SkillLite[] {
162
+ * name (first wins). All roots are injectable for tests. */
163
+ export function scanSkills(opts: SkillScanOptions = {}): SkillLite[] {
149
164
  const seen = new Set<string>();
150
165
  const out: SkillLite[] = [];
151
- for (const loc of skillLocations(projectDir, home)) {
166
+ for (const loc of skillLocations(opts)) {
152
167
  for (const skill of scanLocation(loc)) {
153
168
  if (seen.has(skill.name)) continue;
154
169
  seen.add(skill.name);