@skydiveai/pi-extensions 0.1.258-beta.13 → 0.1.258-beta.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +298 -109
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -265,7 +265,7 @@ function createHealthHandler({ metadata }) {
265
265
  const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task is done, if this changes what you can do for the user, record it in `soul.md` so it carries into future conversations rather than being rediscovered from scratch (then commit and push).";
266
266
  //#endregion
267
267
  //#region src/extensions/tool-call-summary.ts
268
- const log$19 = logger.child({ module: "tool-call-summary-extension" });
268
+ const log$21 = logger.child({ module: "tool-call-summary-extension" });
269
269
  /**
270
270
  * The injected parameter name. Deliberately markdown-safe: the previous wire
271
271
  * name (`__skydive_summary__`, now `TOOL_CALL_SUMMARY_FIELD_LEGACY`) carried
@@ -499,7 +499,7 @@ function withSummaryStrippedBeforeValidation(tool) {
499
499
  try {
500
500
  stripped = withoutInjectedSummary(args);
501
501
  } catch (err) {
502
- log$19.error({
502
+ log$21.error({
503
503
  err,
504
504
  event: "tool_call_summary_prepare_strip_failed",
505
505
  toolName: tool.name
@@ -530,7 +530,7 @@ function stripInjectedSummary(pi, toolName, input) {
530
530
  if (toolDeclaresSummaryParam(pi, toolName)) return;
531
531
  for (const field of TOOL_CALL_SUMMARY_FIELDS) delete input[field];
532
532
  } catch (err) {
533
- log$19.error({
533
+ log$21.error({
534
534
  err,
535
535
  event: "tool_call_summary_strip_failed",
536
536
  toolName
@@ -546,7 +546,7 @@ function buildInjectedPayload(pi, payload) {
546
546
  try {
547
547
  return injectToolCallSummary(payload, getStrictToolNames(pi));
548
548
  } catch (err) {
549
- log$19.error({
549
+ log$21.error({
550
550
  err,
551
551
  event: "tool_call_summary_injection_failed"
552
552
  }, "tool_call_summary injection failed; passing payload through unchanged");
@@ -565,7 +565,7 @@ const toolCallSummaryExtension = (pi) => {
565
565
  pi.registerTool(withSummaryStrippedBeforeValidation(createEditToolDefinition(ctx.cwd)));
566
566
  editOverrideRegistered = true;
567
567
  } catch (err) {
568
- log$19.error({
568
+ log$21.error({
569
569
  err,
570
570
  event: "tool_call_summary_edit_override_failed"
571
571
  }, "failed to register summary-tolerant edit tool; built-in remains active");
@@ -596,7 +596,7 @@ const toolCallSummaryExtension = (pi) => {
596
596
  * or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
597
597
  * `tools/_example.ts` documents the shape without registering.
598
598
  */
599
- const log$18 = logger.child({ module: "local-tools-extension" });
599
+ const log$20 = logger.child({ module: "local-tools-extension" });
600
600
  const TOOLS_DIRNAME = "tools";
601
601
  const fileState = /* @__PURE__ */ new Map();
602
602
  let pendingLocalToolsUpdate = null;
@@ -740,7 +740,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
740
740
  dir
741
741
  });
742
742
  if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
743
- log$18.info({
743
+ log$20.info({
744
744
  event: "local_tools_reconcile",
745
745
  reason,
746
746
  total_tools: summary.totalTools,
@@ -762,7 +762,7 @@ const localToolsExtension = (pi) => {
762
762
  reason: "session_start"
763
763
  });
764
764
  } catch (err) {
765
- log$18.error({
765
+ log$20.error({
766
766
  err,
767
767
  event: "local_tools_reconcile_failed"
768
768
  }, "local tools reconcile failed");
@@ -774,7 +774,7 @@ const localToolsExtension = (pi) => {
774
774
  try {
775
775
  current = await listToolFiles(dir);
776
776
  } catch (err) {
777
- log$18.warn({
777
+ log$20.warn({
778
778
  err,
779
779
  event: "local_tools_listing_failed"
780
780
  }, "tools/ listing failed");
@@ -796,7 +796,7 @@ const localToolsExtension = (pi) => {
796
796
  reason: "auto_reload"
797
797
  });
798
798
  } catch (err) {
799
- log$18.error({
799
+ log$20.error({
800
800
  err,
801
801
  event: "local_tools_auto_reload_failed"
802
802
  }, "auto-reload after tools/ change failed");
@@ -1288,17 +1288,23 @@ function legacyMcpToolName({ serverName, toolName }) {
1288
1288
  * a small, focused unit-test surface (typebox validation, error formatting).
1289
1289
  */
1290
1290
  const MCP_CONFIG_FILENAME = "mcp.config.json";
1291
+ const ToolSelectionSchema = {
1292
+ tools: Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()])),
1293
+ excludeTools: Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()]))
1294
+ };
1291
1295
  const StdioServerSchema = Type.Object({
1292
1296
  transport: Type.Literal("stdio"),
1293
1297
  command: Type.String(),
1294
1298
  args: Type.Array(Type.String()),
1295
1299
  env: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()])),
1296
- cwd: Type.Optional(Type.Union([Type.String(), Type.Null()]))
1300
+ cwd: Type.Optional(Type.Union([Type.String(), Type.Null()])),
1301
+ ...ToolSelectionSchema
1297
1302
  });
1298
1303
  const HttpServerSchema = Type.Object({
1299
1304
  transport: Type.Literal("http"),
1300
1305
  url: Type.String(),
1301
- headers: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()]))
1306
+ headers: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()])),
1307
+ ...ToolSelectionSchema
1302
1308
  });
1303
1309
  const ServerSchema = Type.Union([StdioServerSchema, HttpServerSchema]);
1304
1310
  const McpConfigSchema = Type.Object({ servers: Type.Record(Type.String(), ServerSchema) });
@@ -1325,11 +1331,15 @@ async function loadMcpConfig(path) {
1325
1331
  for (const [id, server] of Object.entries(json.servers)) if (server.transport === "stdio") servers[id] = {
1326
1332
  ...server,
1327
1333
  env: server.env ?? null,
1328
- cwd: server.cwd ?? null
1334
+ cwd: server.cwd ?? null,
1335
+ tools: server.tools ?? null,
1336
+ excludeTools: server.excludeTools ?? null
1329
1337
  };
1330
1338
  else servers[id] = {
1331
1339
  ...server,
1332
- headers: server.headers ?? null
1340
+ headers: server.headers ?? null,
1341
+ tools: server.tools ?? null,
1342
+ excludeTools: server.excludeTools ?? null
1333
1343
  };
1334
1344
  return { servers };
1335
1345
  }
@@ -1490,7 +1500,55 @@ function toProviderSafeSchema(inputSchema) {
1490
1500
  * Clients are keyed by JSON-stringified config and reused across
1491
1501
  * reloads — only changed configs reconnect.
1492
1502
  */
1493
- const log$17 = logger.child({ module: "mcp-extension" });
1503
+ const log$19 = logger.child({ module: "mcp-extension" });
1504
+ function resolveToolSelection(server) {
1505
+ return {
1506
+ allow: server?.tools?.length ? new Set(server.tools) : null,
1507
+ deny: new Set(server?.excludeTools ?? [])
1508
+ };
1509
+ }
1510
+ /**
1511
+ * Connection identity of a server config: everything except the per-server
1512
+ * tool selection. `tools`/`excludeTools` only filter the advertised list at
1513
+ * registration time, so an edit to them must re-register tools, not tear
1514
+ * down and re-handshake the client (kills the stdio process, re-runs the
1515
+ * http OAuth/handshake for an identical connection).
1516
+ */
1517
+ function connectionKey(serverConfig) {
1518
+ const { tools: _tools, excludeTools: _excludeTools, ...connection } = serverConfig;
1519
+ return JSON.stringify(connection);
1520
+ }
1521
+ /**
1522
+ * Apply a server's configured tool selection to its advertised list.
1523
+ * Runs BEFORE the budget allocator: a filtered set is what competes for
1524
+ * the per-server / total / token caps, so an allowlisted tool wins the
1525
+ * budget contest instead of being truncated behind tools the config
1526
+ * never asked for. Intentional exclusions are NOT budget drops — they
1527
+ * don't count toward `droppedTools` and produce no truncation warning.
1528
+ */
1529
+ function applyToolSelection(tools, selection) {
1530
+ if (selection.allow === null && selection.deny.size === 0) return {
1531
+ list: tools,
1532
+ filteredOut: 0,
1533
+ unknownTools: [],
1534
+ unknownExcludeTools: []
1535
+ };
1536
+ const kept = [];
1537
+ for (const tool of tools) {
1538
+ if (selection.allow !== null && !selection.allow.has(tool.name)) continue;
1539
+ if (selection.deny.has(tool.name)) continue;
1540
+ kept.push(tool);
1541
+ }
1542
+ const notAdvertised = (names) => [...names].filter((name) => !tools.some((tool) => tool.name === name));
1543
+ const unknownTools = selection.allow === null ? [] : notAdvertised(selection.allow);
1544
+ const unknownExcludeTools = selection.deny.size === 0 ? [] : notAdvertised(selection.deny);
1545
+ return {
1546
+ list: kept,
1547
+ filteredOut: tools.length - kept.length,
1548
+ unknownTools,
1549
+ unknownExcludeTools
1550
+ };
1551
+ }
1494
1552
  async function closeConnected(connected) {
1495
1553
  try {
1496
1554
  await connected.client.close();
@@ -1640,7 +1698,7 @@ function providerSafeTools({ serverId, tools }) {
1640
1698
  for (const tool of tools) {
1641
1699
  const result = toProviderSafeSchema(tool.inputSchema);
1642
1700
  if (!result.ok) {
1643
- log$17.warn({
1701
+ log$19.warn({
1644
1702
  event: "mcp_tool_schema_unsupported",
1645
1703
  server_id: serverId,
1646
1704
  tool_name: tool.name,
@@ -1797,9 +1855,11 @@ var McpExtension = class {
1797
1855
  else if (outcome.change === "refreshed") summary.refreshed.push(id);
1798
1856
  }
1799
1857
  const alloc = outcomes.filter((o) => Boolean(o.tools)).map((o) => {
1858
+ const selection = resolveToolSelection(config.servers[o.id]);
1859
+ const picked = applyToolSelection(o.tools.list, selection);
1800
1860
  const { tools: list, skipped } = providerSafeTools({
1801
1861
  serverId: o.id,
1802
- tools: o.tools.list
1862
+ tools: picked.list
1803
1863
  });
1804
1864
  return {
1805
1865
  id: o.id,
@@ -1807,6 +1867,9 @@ var McpExtension = class {
1807
1867
  list,
1808
1868
  advertised: o.tools.list.length,
1809
1869
  skipped,
1870
+ filtered: picked.filteredOut,
1871
+ unknownTools: picked.unknownTools,
1872
+ unknownExcludeTools: picked.unknownExcludeTools,
1810
1873
  room: Math.min(list.length, limits.maxToolsPerServer),
1811
1874
  registered: 0,
1812
1875
  serverTokens: 0,
@@ -1850,7 +1913,10 @@ var McpExtension = class {
1850
1913
  registered: s.registered,
1851
1914
  tokens: s.serverTokens,
1852
1915
  droppedReason,
1853
- skipped: s.skipped
1916
+ skipped: s.skipped,
1917
+ filtered: s.filtered,
1918
+ unknownTools: s.unknownTools,
1919
+ unknownExcludeTools: s.unknownExcludeTools
1854
1920
  };
1855
1921
  }
1856
1922
  return summary;
@@ -1862,10 +1928,10 @@ var McpExtension = class {
1862
1928
  * map/summary, so callers can run these concurrently.
1863
1929
  */
1864
1930
  async reconcileServer({ id, serverConfig, existing, connectTimeoutMs }) {
1865
- const configKey = JSON.stringify(serverConfig);
1931
+ const configKey = connectionKey(serverConfig);
1866
1932
  let action;
1867
1933
  let connected;
1868
- if (existing && existing.configKey === configKey) {
1934
+ if (existing && existing.connectionKey === configKey) {
1869
1935
  connected = existing;
1870
1936
  action = "reused";
1871
1937
  } else {
@@ -1891,7 +1957,7 @@ var McpExtension = class {
1891
1957
  id,
1892
1958
  store: {
1893
1959
  client: result.client,
1894
- configKey,
1960
+ connectionKey: configKey,
1895
1961
  status: "pending_auth",
1896
1962
  stderrBuffer: result.stderrBuffer,
1897
1963
  cliHint: result.cliHint
@@ -1909,7 +1975,7 @@ var McpExtension = class {
1909
1975
  id,
1910
1976
  store: {
1911
1977
  client: result.client,
1912
- configKey,
1978
+ connectionKey: configKey,
1913
1979
  status: "timeout",
1914
1980
  stderrBuffer: result.stderrBuffer,
1915
1981
  cliHint: null
@@ -1925,7 +1991,7 @@ var McpExtension = class {
1925
1991
  };
1926
1992
  connected = {
1927
1993
  client: result.client,
1928
- configKey,
1994
+ connectionKey: configKey,
1929
1995
  status: "connected",
1930
1996
  stderrBuffer: result.stderr,
1931
1997
  cliHint: null
@@ -1939,7 +2005,7 @@ var McpExtension = class {
1939
2005
  id,
1940
2006
  store: {
1941
2007
  client: retry.client,
1942
- configKey,
2008
+ connectionKey: configKey,
1943
2009
  status: "pending_auth",
1944
2010
  stderrBuffer: null,
1945
2011
  cliHint: retry.cliHint
@@ -1957,7 +2023,7 @@ var McpExtension = class {
1957
2023
  id,
1958
2024
  store: {
1959
2025
  client: retry.client,
1960
- configKey,
2026
+ connectionKey: configKey,
1961
2027
  status: "timeout",
1962
2028
  stderrBuffer: retry.stderrBuffer,
1963
2029
  cliHint: null
@@ -1985,7 +2051,7 @@ var McpExtension = class {
1985
2051
  };
1986
2052
  connected = {
1987
2053
  client: retry.client,
1988
- configKey,
2054
+ connectionKey: configKey,
1989
2055
  status: "connected",
1990
2056
  stderrBuffer: retry.stderr,
1991
2057
  cliHint: null
@@ -2017,7 +2083,7 @@ var McpExtension = class {
2017
2083
  id,
2018
2084
  store: {
2019
2085
  client: retry.client,
2020
- configKey,
2086
+ connectionKey: configKey,
2021
2087
  status: "pending_auth",
2022
2088
  stderrBuffer: null,
2023
2089
  cliHint: retry.cliHint
@@ -2049,7 +2115,7 @@ var McpExtension = class {
2049
2115
  if (retry.status === "connected") {
2050
2116
  connected = {
2051
2117
  client: retry.client,
2052
- configKey,
2118
+ connectionKey: configKey,
2053
2119
  status: "connected",
2054
2120
  stderrBuffer: retry.stderr,
2055
2121
  cliHint: null
@@ -2106,7 +2172,7 @@ var McpExtension = class {
2106
2172
  });
2107
2173
  this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
2108
2174
  if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
2109
- log$17.info({
2175
+ log$19.info({
2110
2176
  event: "mcp_reconcile",
2111
2177
  reason,
2112
2178
  total_tools: summary.totalTools,
@@ -2133,7 +2199,7 @@ var McpExtension = class {
2133
2199
  contextWindow: ctx.model?.contextWindow
2134
2200
  });
2135
2201
  } catch (err) {
2136
- log$17.error({
2202
+ log$19.error({
2137
2203
  err,
2138
2204
  event: "mcp_reconcile_failed"
2139
2205
  }, "MCP reconcile failed");
@@ -2147,7 +2213,7 @@ var McpExtension = class {
2147
2213
  for (const legacy of renamed) {
2148
2214
  if (this.loggedLegacyToolNames.has(legacy)) continue;
2149
2215
  this.loggedLegacyToolNames.add(legacy);
2150
- log$17.info({
2216
+ log$19.info({
2151
2217
  event: "mcp_tool_legacy_name",
2152
2218
  legacy_name: legacy,
2153
2219
  tool_name: this.legacyToolNames.get(legacy)
@@ -2161,7 +2227,7 @@ var McpExtension = class {
2161
2227
  try {
2162
2228
  mtime = await readConfigMtimeMs(configPath);
2163
2229
  } catch (err) {
2164
- log$17.warn({
2230
+ log$19.warn({
2165
2231
  err,
2166
2232
  event: "mcp_mtime_check_failed"
2167
2233
  }, "mtime check on mcp.config.json failed");
@@ -2176,7 +2242,7 @@ var McpExtension = class {
2176
2242
  contextWindow: ctx.model?.contextWindow
2177
2243
  });
2178
2244
  } catch (err) {
2179
- log$17.error({
2245
+ log$19.error({
2180
2246
  err,
2181
2247
  event: "mcp_auto_reload_failed"
2182
2248
  }, "auto-reload after mcp.config.json change failed");
@@ -2304,11 +2370,27 @@ function skippedSchemaLines(summary) {
2304
2370
  for (const [id, count] of entries) for (const { name, reason } of count.skipped) lines.push(` - ${id}/${name}: ${reason}`);
2305
2371
  return lines;
2306
2372
  }
2373
+ /**
2374
+ * Lines naming allowlist entries in mcp.config.json that matched no tool the
2375
+ * server advertises — almost always a typo, and silent otherwise: the agent
2376
+ * just sees a narrower tool set and can't tell the config is wrong.
2377
+ */
2378
+ function unknownToolLines(summary) {
2379
+ const entries = Object.entries(summary.toolCounts).filter(([, count]) => count.unknownTools.length > 0 || count.unknownExcludeTools.length > 0);
2380
+ if (entries.length === 0) return [];
2381
+ const lines = [];
2382
+ for (const [id, count] of entries) {
2383
+ if (count.unknownTools.length > 0) lines.push(` NOTE: ${id}.tools in mcp.config.json names tool(s) the server does not advertise: ${count.unknownTools.join(", ")}.`);
2384
+ if (count.unknownExcludeTools.length > 0) lines.push(` NOTE: ${id}.excludeTools in mcp.config.json names tool(s) the server does not advertise: ${count.unknownExcludeTools.join(", ")}.`);
2385
+ }
2386
+ return lines;
2387
+ }
2307
2388
  function summaryText(summary) {
2308
2389
  const lines = [];
2309
2390
  lines.push(`MCP reconcile complete: ${summary.totalTools} tool(s) live.`);
2310
2391
  lines.push(...truncationLines(summary));
2311
2392
  lines.push(...skippedSchemaLines(summary));
2393
+ lines.push(...unknownToolLines(summary));
2312
2394
  if (summary.added.length > 0) lines.push(` Added: ${summary.added.join(", ")}`);
2313
2395
  if (summary.refreshed.length > 0) lines.push(` Refreshed: ${summary.refreshed.join(", ")}`);
2314
2396
  if (summary.removed.length > 0) lines.push(` Removed: ${summary.removed.join(", ")}`);
@@ -2526,11 +2608,21 @@ const assistantSchema = z.object({
2526
2608
  id: z.string(),
2527
2609
  model: z.string()
2528
2610
  });
2611
+ const sdkToolResultSchema = z.object({ content: z.array(z.object({ type: z.literal("tool_result") })).min(1) });
2529
2612
  function assistantMessage(entry) {
2530
2613
  if (entry.type !== "assistant") return null;
2531
2614
  const parsed = assistantSchema.safeParse(entry.message);
2532
2615
  return parsed.success ? parsed.data : null;
2533
2616
  }
2617
+ /**
2618
+ * Claude Code answers some tool_use blocks itself mid-stream (e.g. "No such
2619
+ * tool available") and persists that result between the response's blocks.
2620
+ * Pi owns tool execution and replays its own results, so these never belong
2621
+ * in the accepted prefix.
2622
+ */
2623
+ function isSdkToolResult(entry) {
2624
+ return entry.type === "user" && sdkToolResultSchema.safeParse(entry.message).success;
2625
+ }
2534
2626
  function contentHash(message) {
2535
2627
  return createHash("sha256").update(JSON.stringify(message.content)).digest("hex");
2536
2628
  }
@@ -2588,7 +2680,7 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2588
2680
  const entry = byId.get(id);
2589
2681
  if (!entry) break;
2590
2682
  const assistant = assistantMessage(entry);
2591
- if (!assistant || assistant.model === "<synthetic>" || acceptedIds.has(assistant.id)) entries.push(entry);
2683
+ if (!isSdkToolResult(entry) && (!assistant || assistant.model === "<synthetic>" || acceptedIds.has(assistant.id))) entries.push(entry);
2592
2684
  id = entry.parentUuid;
2593
2685
  }
2594
2686
  if (id === boundaryId && entries.length) return entries.reverse();
@@ -2866,7 +2958,7 @@ const SEAT_QUERY_TIMEOUTS = {
2866
2958
  preparation: 3e4
2867
2959
  };
2868
2960
  const PI_TOOLS_SERVER = "custom-tools";
2869
- const log$16 = logger.child({ module: "claude-seat-sdk" });
2961
+ const log$18 = logger.child({ module: "claude-seat-sdk" });
2870
2962
  /** Preserve existing MCP names; only ordinary Pi tools need a server prefix. */
2871
2963
  function toolBindings(context) {
2872
2964
  const parsed = (context.tools ?? []).map((definition) => {
@@ -2924,7 +3016,7 @@ var SeatQuery = class {
2924
3016
  this.deadline = setTimeout(() => {
2925
3017
  const err = /* @__PURE__ */ new Error(`Claude seat SDK timed out waiting for ${phase}`);
2926
3018
  err.name = "TimeoutError";
2927
- log$16.error({
3019
+ log$18.error({
2928
3020
  err,
2929
3021
  phase
2930
3022
  }, "Claude seat SDK wait deadline exceeded");
@@ -3105,7 +3197,7 @@ var SeatQuery = class {
3105
3197
  }
3106
3198
  } catch (err) {
3107
3199
  this.failure = err;
3108
- if (!this.controller.signal.aborted) log$16.error({
3200
+ if (!this.controller.signal.aborted) log$18.error({
3109
3201
  err,
3110
3202
  sessionId
3111
3203
  }, "Claude seat SDK query failed");
@@ -3120,7 +3212,7 @@ var SeatQuery = class {
3120
3212
  force: true
3121
3213
  });
3122
3214
  } catch (err) {
3123
- log$16.error({
3215
+ log$18.error({
3124
3216
  err,
3125
3217
  sessionId
3126
3218
  }, "Could not remove Claude seat SDK config");
@@ -3153,10 +3245,26 @@ function mapUsage(usage) {
3153
3245
  //#endregion
3154
3246
  //#region src/extensions/claude-seat-response.ts
3155
3247
  const toolInput = z.record(z.string(), z.unknown());
3156
- function piToolName(name, context) {
3157
- const binding = toolBindings(context).find((binding) => binding.sdkName === name);
3158
- if (!binding) throw new Error(`Claude requested a tool outside the Pi bridge: ${name}`);
3159
- return binding.definition.name;
3248
+ const log$17 = logger.child({ module: "claude-seat-sdk" });
3249
+ /**
3250
+ * Claude sometimes calls a tool by the name it had outside the bridge (Pi's
3251
+ * own name from non-seat history, or a bare MCP tool name). Resolve those when
3252
+ * unambiguous; anything else passes through unbound so Pi's executor returns
3253
+ * its normal not-found error result and the model can recover.
3254
+ */
3255
+ function piToolName({ name, context, sessionId }) {
3256
+ const bindings = toolBindings(context);
3257
+ const exact = bindings.find((binding) => binding.sdkName === name) ?? bindings.find((binding) => binding.definition.name === name);
3258
+ if (exact) return exact.definition.name;
3259
+ const bare = bindings.filter((binding) => binding.toolName === name);
3260
+ const [only] = bare;
3261
+ if (only && bare.length === 1) return only.definition.name;
3262
+ log$17.warn({
3263
+ sessionId,
3264
+ toolName: name,
3265
+ candidates: bare.length
3266
+ }, "Claude requested a tool outside the Pi bridge");
3267
+ return name;
3160
3268
  }
3161
3269
  /** Commit only the accepted SDK attempt: Pi deltas cannot retract retried output. */
3162
3270
  var ModelResponse = class {
@@ -3164,9 +3272,10 @@ var ModelResponse = class {
3164
3272
  pending = [];
3165
3273
  messageId = null;
3166
3274
  stopReason = null;
3167
- constructor(model, context, events) {
3275
+ constructor(model, context, events, sessionId) {
3168
3276
  this.context = context;
3169
3277
  this.events = events;
3278
+ this.sessionId = sessionId;
3170
3279
  this.message = {
3171
3280
  role: "assistant",
3172
3281
  content: [],
@@ -3261,7 +3370,11 @@ var ModelResponse = class {
3261
3370
  block = {
3262
3371
  type: "toolCall",
3263
3372
  id: sdkBlock.id,
3264
- name: piToolName(sdkBlock.name, this.context),
3373
+ name: piToolName({
3374
+ name: sdkBlock.name,
3375
+ context: this.context,
3376
+ sessionId: this.sessionId
3377
+ }),
3265
3378
  arguments: toolInput.parse(sdkBlock.input)
3266
3379
  };
3267
3380
  break;
@@ -3337,7 +3450,7 @@ var ModelResponse = class {
3337
3450
  * each step resumes a private structured snapshot after Pi extensions run.
3338
3451
  * Initially adapted from elidickinson/pi-claude-bridge (MIT).
3339
3452
  */
3340
- const log$15 = logger.child({ module: "claude-seat-sdk" });
3453
+ const log$16 = logger.child({ module: "claude-seat-sdk" });
3341
3454
  const SEAT_SDK_ACTIVITY_EVENT = "claude-seat-sdk:activity";
3342
3455
  /** Session-scoped adapter; only the flagged provider dispatches here. */
3343
3456
  var SeatSdkBridge = class {
@@ -3355,7 +3468,7 @@ var SeatSdkBridge = class {
3355
3468
  }
3356
3469
  stream(model, context, options = {}) {
3357
3470
  const events = createAssistantMessageEventStream();
3358
- const response = new ModelResponse(model, context, events);
3471
+ const response = new ModelResponse(model, context, events, this.deps.sessionId);
3359
3472
  const signal = AbortSignal.any([this.controller.signal, ...options.signal ? [options.signal] : []]);
3360
3473
  (async () => {
3361
3474
  let seatQuery = null;
@@ -3388,7 +3501,7 @@ var SeatSdkBridge = class {
3388
3501
  } else if (message.type === "result") {
3389
3502
  const hasTools = response.hasTools;
3390
3503
  if (message.is_error && !(message.subtype === "error_max_turns" && hasTools)) throw new Error("errors" in message ? message.errors.join("; ") : message.result);
3391
- log$15.info({
3504
+ log$16.info({
3392
3505
  sessionId: this.deps.sessionId,
3393
3506
  queryUsage: mapUsage(message.usage),
3394
3507
  requestUsage: response.message.usage
@@ -3409,7 +3522,7 @@ var SeatSdkBridge = class {
3409
3522
  }
3410
3523
  } catch (err) {
3411
3524
  const reason = (seatQuery?.controller.signal.aborted || signal.aborted) && !(err instanceof Error && err.name === "TimeoutError") ? "aborted" : "error";
3412
- if (reason === "error") log$15.error({
3525
+ if (reason === "error") log$16.error({
3413
3526
  err,
3414
3527
  sessionId: this.deps.sessionId
3415
3528
  }, "Claude seat SDK response failed");
@@ -3480,7 +3593,7 @@ const HEARTBEAT_THROTTLE_MS = 6e4;
3480
3593
  const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
3481
3594
  const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
3482
3595
  const DAEMON_URL = "http://localhost:38994";
3483
- const log$14 = logger.child({ module: "platform-ext" });
3596
+ const log$15 = logger.child({ module: "platform-ext" });
3484
3597
  function sandboxClient() {
3485
3598
  const apiUrl = apiBaseUrl();
3486
3599
  if (!apiUrl) return null;
@@ -3548,7 +3661,7 @@ async function fetchHarnessFlags() {
3548
3661
  try {
3549
3662
  const res = await client["feature-flags"].$get();
3550
3663
  if (!res.ok) {
3551
- log$14.debug({
3664
+ log$15.debug({
3552
3665
  status: res.status,
3553
3666
  event: "feature_flags_fetch_failed"
3554
3667
  }, "feature-flags fetch failed");
@@ -3560,7 +3673,7 @@ async function fetchHarnessFlags() {
3560
3673
  closingText: body.closingText ?? null
3561
3674
  };
3562
3675
  } catch (err) {
3563
- log$14.debug({
3676
+ log$15.debug({
3564
3677
  err,
3565
3678
  event: "feature_flags_fetch_error"
3566
3679
  }, "feature-flags request errored");
@@ -3571,7 +3684,7 @@ function postHeartbeat({ messageId }) {
3571
3684
  const client = sandboxClient();
3572
3685
  if (!client) return;
3573
3686
  client.heartbeat.$post({ json: { messageId } }).catch((err) => {
3574
- log$14.debug({
3687
+ log$15.debug({
3575
3688
  err,
3576
3689
  event: "heartbeat_failed"
3577
3690
  }, "heartbeat failed");
@@ -3583,7 +3696,7 @@ async function resolveConversationFromApi(messageId) {
3583
3696
  try {
3584
3697
  const res = await client["message-conversation"].$get({ query: { messageId } });
3585
3698
  if (!res.ok) {
3586
- log$14.warn({
3699
+ log$15.warn({
3587
3700
  status: res.status,
3588
3701
  messageId,
3589
3702
  event: "resolve_conversation_failed"
@@ -3592,7 +3705,7 @@ async function resolveConversationFromApi(messageId) {
3592
3705
  }
3593
3706
  return (await res.json()).conversationId ?? null;
3594
3707
  } catch (err) {
3595
- log$14.warn({
3708
+ log$15.warn({
3596
3709
  err,
3597
3710
  messageId,
3598
3711
  event: "resolve_conversation_error"
@@ -3617,13 +3730,13 @@ async function putBackgroundTaskJournalSpec({ messageId, spec }) {
3617
3730
  messageId,
3618
3731
  spec
3619
3732
  } });
3620
- if (!res.ok) log$14.warn({
3733
+ if (!res.ok) log$15.warn({
3621
3734
  status: res.status,
3622
3735
  taskId: spec.id,
3623
3736
  event: "bg_journal_put_failed"
3624
3737
  }, "bg-task journal PUT failed");
3625
3738
  } catch (err) {
3626
- log$14.warn({
3739
+ log$15.warn({
3627
3740
  err,
3628
3741
  taskId: spec.id,
3629
3742
  event: "bg_journal_put_failed"
@@ -3639,7 +3752,7 @@ async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
3639
3752
  taskId
3640
3753
  } });
3641
3754
  } catch (err) {
3642
- log$14.debug({
3755
+ log$15.debug({
3643
3756
  err,
3644
3757
  taskId,
3645
3758
  event: "bg_journal_delete_failed"
@@ -3654,7 +3767,7 @@ async function listBackgroundTaskJournalSpecs({ messageId }) {
3654
3767
  if (!res.ok) return [];
3655
3768
  return (await res.json()).specs ?? [];
3656
3769
  } catch (err) {
3657
- log$14.debug({
3770
+ log$15.debug({
3658
3771
  err,
3659
3772
  event: "bg_journal_list_failed"
3660
3773
  }, "bg-task journal GET failed");
@@ -3668,7 +3781,7 @@ function postBackgroundTasksSnapshot({ messageId, tasks }) {
3668
3781
  messageId,
3669
3782
  tasks
3670
3783
  } }).catch((err) => {
3671
- log$14.debug({
3784
+ log$15.debug({
3672
3785
  err,
3673
3786
  event: "bg_tasks_snapshot_failed"
3674
3787
  }, "bg-tasks snapshot publish failed");
@@ -3766,7 +3879,7 @@ function createToolHeartbeat({ messageId }) {
3766
3879
  }
3767
3880
  heartbeatCount++;
3768
3881
  if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
3769
- log$14.warn({
3882
+ log$15.warn({
3770
3883
  heartbeatCount,
3771
3884
  activeToolCalls: [...activeToolCalls]
3772
3885
  }, "tool heartbeat max reached, stopping");
@@ -3797,7 +3910,7 @@ function postToDaemon(path, body) {
3797
3910
  headers: { "content-type": "application/json" },
3798
3911
  body: JSON.stringify(body)
3799
3912
  }).catch((err) => {
3800
- log$14.debug({
3913
+ log$15.debug({
3801
3914
  err,
3802
3915
  path,
3803
3916
  event: "daemon_post_failed"
@@ -3806,7 +3919,7 @@ function postToDaemon(path, body) {
3806
3919
  }
3807
3920
  function createPlatformExtensions({ sessionId, channelContext }) {
3808
3921
  return (pi) => {
3809
- log$14.info({
3922
+ log$15.info({
3810
3923
  sessionId,
3811
3924
  hasChannelContext: Boolean(channelContext)
3812
3925
  }, "platform extension initialized");
@@ -3860,7 +3973,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
3860
3973
  });
3861
3974
  });
3862
3975
  pi.on("agent_end", () => {
3863
- log$14.info({ sessionId }, "session ending");
3976
+ log$15.info({ sessionId }, "session ending");
3864
3977
  postToDaemon("/session/end", { sessionId });
3865
3978
  });
3866
3979
  };
@@ -3892,6 +4005,14 @@ const toolCallEnvExtension = (pi) => {
3892
4005
  });
3893
4006
  };
3894
4007
  //#endregion
4008
+ //#region src/extensions/oom-neutral-bash.ts
4009
+ const OOM_NEUTRAL_PREFIX = "{ echo 0 > /proc/self/oom_score_adj; } 2>/dev/null\n";
4010
+ /** pi's local bash backend with every command reset to a neutral OOM score. */
4011
+ function createOomNeutralBashOperations({ shellPath }) {
4012
+ const local = createLocalBashOperations({ shellPath });
4013
+ return { exec: (command, cwd, options) => local.exec(`${OOM_NEUTRAL_PREFIX}${command}`, cwd, options) };
4014
+ }
4015
+ //#endregion
3895
4016
  //#region src/extensions/background-tasks.ts
3896
4017
  /**
3897
4018
  * Background bash tasks as a pi extension.
@@ -3996,8 +4117,8 @@ const toolCallEnvExtension = (pi) => {
3996
4117
  * semantics; once promoted, the command inherits background-task lifecycle
3997
4118
  * (its own controller) and the foreground kill timeout no longer applies.
3998
4119
  */
3999
- const log$13 = logger.child({ module: "background-tasks-ext" });
4000
- const ops = createLocalBashOperations();
4120
+ const log$14 = logger.child({ module: "background-tasks-ext" });
4121
+ const ops = createOomNeutralBashOperations({ shellPath: void 0 });
4001
4122
  const STEER_BACKGROUND_DEFAULT_SECONDS = 60;
4002
4123
  const STEER_BACKGROUND_ENV_KEYS = ["BASH_STEER_BACKGROUND_SECONDS", "SKYDIVE_BASH_STEER_BACKGROUND_SECONDS"];
4003
4124
  /**
@@ -4011,7 +4132,7 @@ function steerBackgroundThresholdMs() {
4011
4132
  if (raw === void 0 || raw.trim() === "") continue;
4012
4133
  const parsed = Number(raw);
4013
4134
  if (!Number.isFinite(parsed) || parsed < 0) {
4014
- log$13.warn({
4135
+ log$14.warn({
4015
4136
  envKey: key,
4016
4137
  raw
4017
4138
  }, "invalid BASH_STEER_BACKGROUND_SECONDS, using default");
@@ -4040,7 +4161,7 @@ async function notifyBashSteerArrival(args) {
4040
4161
  try {
4041
4162
  await listener();
4042
4163
  } catch (err) {
4043
- log$13.error({
4164
+ log$14.error({
4044
4165
  err,
4045
4166
  sessionId: args.sessionId
4046
4167
  }, "bash steer promotion failed");
@@ -4135,14 +4256,14 @@ function watchdogTick(now) {
4135
4256
  const overSize = meta.logBytes > MAX_LOG_BYTES;
4136
4257
  if (!overRuntime && !overSize) continue;
4137
4258
  const reason = overSize ? `output exceeded ${MAX_LOG_BYTES / (1024 * 1024)}MiB` : `exceeded ${KEEPALIVE_MAX_MS / 6e4}m max runtime`;
4138
- log$13.warn({
4259
+ log$14.warn({
4139
4260
  taskId: meta.id,
4140
4261
  reason
4141
4262
  }, "watchdog killing bg task");
4142
4263
  try {
4143
4264
  killTask(meta, reason);
4144
4265
  } catch (err) {
4145
- log$13.warn({
4266
+ log$14.warn({
4146
4267
  err,
4147
4268
  taskId: meta.id
4148
4269
  }, "watchdog kill failed");
@@ -4201,7 +4322,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4201
4322
  const now = Date.now();
4202
4323
  const promotable = [...foregroundBash.values()].filter((call) => now - call.startedAt >= thresholdMs);
4203
4324
  if (promotable.length === 0) return;
4204
- log$13.info({
4325
+ log$14.info({
4205
4326
  event: "bash_steer_promotion",
4206
4327
  count: promotable.length,
4207
4328
  thresholdSeconds: Math.round(thresholdMs / 1e3),
@@ -4226,7 +4347,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4226
4347
  try {
4227
4348
  await mkdir(tasksDir(), { recursive: true });
4228
4349
  } catch (err) {
4229
- log$13.error({ err }, "bg task adopt: mkdir failed");
4350
+ log$14.error({ err }, "bg task adopt: mkdir failed");
4230
4351
  }
4231
4352
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4232
4353
  logStream.on("error", () => {});
@@ -4253,7 +4374,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4253
4374
  tasks.set(id, meta);
4254
4375
  ensureWatchdog();
4255
4376
  schedulePublishSnapshot();
4256
- log$13.info({
4377
+ log$14.info({
4257
4378
  taskId: id,
4258
4379
  conversationId,
4259
4380
  startedAt: args.startedAt
@@ -4276,7 +4397,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4276
4397
  * handling, timeout kill, and abort semantics.
4277
4398
  */
4278
4399
  function createSteerAwareOperations(base) {
4279
- const localOps = createLocalBashOperations({ shellPath: base.shellPath });
4400
+ const localOps = createOomNeutralBashOperations({ shellPath: base.shellPath });
4280
4401
  return { async exec(command, cwd, execOptions) {
4281
4402
  const thresholdMs = steerBackgroundThresholdMs();
4282
4403
  const toolOnData = execOptions?.onData;
@@ -4406,7 +4527,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4406
4527
  try {
4407
4528
  shellPath = SettingsManager.create(ctx.cwd, getAgentDir()).getShellPath();
4408
4529
  } catch (err) {
4409
- log$13.warn({
4530
+ log$14.warn({
4410
4531
  err,
4411
4532
  cwd: ctx.cwd
4412
4533
  }, "bash steer promotion: shell settings unavailable, using default shell");
@@ -4421,7 +4542,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4421
4542
  ...definition,
4422
4543
  description: `${definition.description}\n\nLong-running bash commands are automatically moved to a background task when a new message arrives while the command has already been running for at least a minute: you get the task id immediately, are woken on completion, and must not depend on the command's output until that wake arrives. Shorter commands finish in the foreground like they always have.`
4423
4544
  });
4424
- log$13.info({
4545
+ log$14.info({
4425
4546
  event: "bash_steer_promotion_enabled",
4426
4547
  thresholdSeconds: Math.round(thresholdMs / 1e3)
4427
4548
  }, "supervised bash tool registered (steer-triggered backgrounding)");
@@ -4464,7 +4585,7 @@ or if you were explicitly waiting to report it.`,
4464
4585
  triggerTurn: true,
4465
4586
  deliverAs: "followUp"
4466
4587
  });
4467
- log$13.info({
4588
+ log$14.info({
4468
4589
  taskId: meta.id,
4469
4590
  conversationId
4470
4591
  }, "bg task completion delivered live (followUp)");
@@ -4472,7 +4593,7 @@ or if you were explicitly waiting to report it.`,
4472
4593
  }
4473
4594
  if (meta.messageId) {
4474
4595
  meta.notified = true;
4475
- log$13.info({
4596
+ log$14.info({
4476
4597
  taskId: meta.id,
4477
4598
  messageId: meta.messageId
4478
4599
  }, "posting idle bg-task-done wake");
@@ -4482,12 +4603,12 @@ or if you were explicitly waiting to report it.`,
4482
4603
  content: message.content
4483
4604
  }).catch((err) => {
4484
4605
  meta.notified = false;
4485
- log$13.warn({
4606
+ log$14.warn({
4486
4607
  err,
4487
4608
  taskId: meta.id
4488
4609
  }, "bg-task-done wake failed; will retry at next session_start");
4489
4610
  });
4490
- } else log$13.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
4611
+ } else log$14.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
4491
4612
  }
4492
4613
  const SNAPSHOT_TAIL_LINES = 40;
4493
4614
  let lastPublishedSignature = null;
@@ -4524,7 +4645,7 @@ or if you were explicitly waiting to report it.`,
4524
4645
  tasks: snapshot
4525
4646
  });
4526
4647
  } catch (err) {
4527
- log$13.debug({
4648
+ log$14.debug({
4528
4649
  err,
4529
4650
  event: "bg_tasks_snapshot_build_failed"
4530
4651
  }, "building bg-tasks snapshot failed");
@@ -4567,7 +4688,7 @@ or if you were explicitly waiting to report it.`,
4567
4688
  logStream.end();
4568
4689
  await finished(logStream).catch(() => {});
4569
4690
  meta.running = false;
4570
- log$13.info({
4691
+ log$14.info({
4571
4692
  taskId: meta.id,
4572
4693
  exitCode: meta.exitCode
4573
4694
  }, "bg task finished");
@@ -4584,14 +4705,14 @@ or if you were explicitly waiting to report it.`,
4584
4705
  try {
4585
4706
  await mkdir(tasksDir(), { recursive: true });
4586
4707
  } catch (err) {
4587
- log$13.error({
4708
+ log$14.error({
4588
4709
  err,
4589
4710
  taskId: id
4590
4711
  }, "background task dir unavailable");
4591
4712
  }
4592
4713
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4593
4714
  logStream.on("error", (err) => {
4594
- log$13.warn({
4715
+ log$14.warn({
4595
4716
  err,
4596
4717
  taskId: id
4597
4718
  }, "bg task log write failed");
@@ -4641,7 +4762,7 @@ or if you were explicitly waiting to report it.`,
4641
4762
  }).catch((err) => {
4642
4763
  if (!meta.controller.signal.aborted) {
4643
4764
  meta.error = err instanceof Error ? err.message : String(err);
4644
- log$13.warn({
4765
+ log$14.warn({
4645
4766
  err,
4646
4767
  taskId: id
4647
4768
  }, "bg task exec error");
@@ -4650,7 +4771,7 @@ or if you were explicitly waiting to report it.`,
4650
4771
  await finishTask(meta, logStream);
4651
4772
  });
4652
4773
  ensureWatchdog();
4653
- log$13.info({
4774
+ log$14.info({
4654
4775
  taskId: id,
4655
4776
  conversationId
4656
4777
  }, "bg task started");
@@ -4669,7 +4790,7 @@ or if you were explicitly waiting to report it.`,
4669
4790
  for (const spec of specs) {
4670
4791
  const live = tasks.get(spec.id);
4671
4792
  if (live && sameScope(live, scopeKey())) continue;
4672
- log$13.info({
4793
+ log$14.info({
4673
4794
  taskId: spec.id,
4674
4795
  conversationId
4675
4796
  }, "relaunching journaled resumable bg task after restart");
@@ -4687,7 +4808,7 @@ or if you were explicitly waiting to report it.`,
4687
4808
  stream.write(`<resumed-after-restart>requeued and relaunched on a new sandbox after the previous one was drained; this is a fresh execution of the command from the start, not a continuation</resumed-after-restart>\n`);
4688
4809
  stream.end();
4689
4810
  } catch (err) {
4690
- log$13.debug({
4811
+ log$14.debug({
4691
4812
  err,
4692
4813
  taskId: meta.id
4693
4814
  }, "resume banner write failed");
@@ -4707,7 +4828,7 @@ or if you were explicitly waiting to report it.`,
4707
4828
  meta.notified = true;
4708
4829
  pi.sendMessage(await taskDoneMessage(meta));
4709
4830
  }
4710
- if (unnotified.length > 0) log$13.info({
4831
+ if (unnotified.length > 0) log$14.info({
4711
4832
  conversationId,
4712
4833
  count: unnotified.length
4713
4834
  }, "injected completed bg tasks at session_start");
@@ -4902,7 +5023,7 @@ or if you were explicitly waiting to report it.`,
4902
5023
  * read on the hot path before every LLM call), it falls back to the default
4903
5024
  * for that knob and logs once.
4904
5025
  */
4905
- const log$12 = logger.child({ module: "context-management-config" });
5026
+ const log$13 = logger.child({ module: "context-management-config" });
4906
5027
  const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
4907
5028
  enabled: false,
4908
5029
  perResultMaxBytes: 16 * 1024,
@@ -4947,7 +5068,7 @@ function resolveContextManagementConfig(env = process.env) {
4947
5068
  clearAtLeastTokens: env.SKYDIVE_CTX_CLEAR_AT_LEAST_TOKENS
4948
5069
  });
4949
5070
  if (!parsed.success) {
4950
- log$12.warn({
5071
+ log$13.warn({
4951
5072
  event: "context_management_config_invalid",
4952
5073
  err: parsed.error
4953
5074
  }, "falling back to default context-management config");
@@ -5031,7 +5152,7 @@ function hasFlagSource(env = process.env) {
5031
5152
  * alive and an indeterminate result (no api url / transient failure) leaves the
5032
5153
  * last-known values untouched so a blip can't silently flip behavior.
5033
5154
  */
5034
- const log$11 = logger.child({ module: "feature-flags-poll" });
5155
+ const log$12 = logger.child({ module: "feature-flags-poll" });
5035
5156
  const FLAG_POLL_INTERVAL_MS = 6e4;
5036
5157
  let contextManagement = null;
5037
5158
  let closingText = null;
@@ -5071,7 +5192,7 @@ function apply(name, next) {
5071
5192
  if (next !== prev) for (const cb of subscribers[name]) try {
5072
5193
  cb(next);
5073
5194
  } catch (err) {
5074
- log$11.warn({
5195
+ log$12.warn({
5075
5196
  err,
5076
5197
  flag: name
5077
5198
  }, "flag subscriber threw");
@@ -5084,7 +5205,7 @@ async function pollOnce() {
5084
5205
  apply("contextManagement", flags.contextManagement ?? null);
5085
5206
  apply("closingText", flags.closingText ?? null);
5086
5207
  } catch (err) {
5087
- log$11.debug({ err }, "feature-flag poll threw");
5208
+ log$12.debug({ err }, "feature-flag poll threw");
5088
5209
  }
5089
5210
  }
5090
5211
  /**
@@ -5286,7 +5407,7 @@ const bashDefaultTimeoutExtension = (pi) => {
5286
5407
  * turn over an observability feature.
5287
5408
  */
5288
5409
  const execFileAsync = promisify(execFile);
5289
- const log$10 = logger.child({ module: "resource-pressure-warning" });
5410
+ const log$11 = logger.child({ module: "resource-pressure-warning" });
5290
5411
  const POLL_INTERVAL_MS = 1e4;
5291
5412
  function envOverride(name) {
5292
5413
  for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
@@ -5483,7 +5604,7 @@ const resourcePressureWarningExtension = (pi) => {
5483
5604
  warnedDiskThisTurn = true;
5484
5605
  }
5485
5606
  if (trigger === null) return;
5486
- log$10.warn({
5607
+ log$11.warn({
5487
5608
  trigger,
5488
5609
  mem,
5489
5610
  cpuPct,
@@ -5521,7 +5642,7 @@ const resourcePressureWarningExtension = (pi) => {
5521
5642
  if (!timer) {
5522
5643
  timer = setInterval(() => {
5523
5644
  checkOnce().catch((err) => {
5524
- log$10.error({ err }, "resource pressure check failed");
5645
+ log$11.error({ err }, "resource pressure check failed");
5525
5646
  });
5526
5647
  }, POLL_INTERVAL_MS);
5527
5648
  timer.unref?.();
@@ -5537,7 +5658,7 @@ const resourcePressureWarningExtension = (pi) => {
5537
5658
  };
5538
5659
  //#endregion
5539
5660
  //#region src/extensions/disk-guard.ts
5540
- const log$9 = logger.child({ module: "disk-guard" });
5661
+ const log$10 = logger.child({ module: "disk-guard" });
5541
5662
  /**
5542
5663
  * In-band bypass. The guard is a safety net, not a jail: when the agent knows
5543
5664
  * a flagged command is genuinely safe (writing to a different mount, a tiny
@@ -5559,7 +5680,7 @@ const BYPASS_HINT$2 = "# disk-guard: allow";
5559
5680
  * first; the SKYDIVE_/ANYONE_ prefixes are accepted too for consistency with
5560
5681
  * the other env overrides. Empty/unset/"0"/"false" leave the guard on.
5561
5682
  */
5562
- function guardDisabledByEnv$2() {
5683
+ function guardDisabledByEnv$3() {
5563
5684
  for (const name of [
5564
5685
  "DISK_GUARD_DISABLE",
5565
5686
  "SKYDIVE_DISK_GUARD_DISABLE",
@@ -5670,14 +5791,14 @@ function diskBlockReason(command, diskPct) {
5670
5791
  const diskGuardExtension = (pi) => {
5671
5792
  pi.on("tool_call", async (event) => {
5672
5793
  if (event.toolName !== "bash") return;
5673
- if (guardDisabledByEnv$2()) return;
5794
+ if (guardDisabledByEnv$3()) return;
5674
5795
  const command = event.input.command;
5675
5796
  if (typeof command !== "string" || command.length === 0) return;
5676
5797
  if (hasBypassMarker$2(command)) return;
5677
5798
  if (!isSpaceHungryCommand(command)) return;
5678
5799
  const diskPct = await readDiskUsePct();
5679
5800
  if (!shouldBlockForDisk(command, diskPct)) return;
5680
- log$9.warn({
5801
+ log$10.warn({
5681
5802
  diskPct,
5682
5803
  command: command.slice(0, 200)
5683
5804
  }, "blocked space-hungry bash command on near-full disk");
@@ -5689,7 +5810,7 @@ const diskGuardExtension = (pi) => {
5689
5810
  };
5690
5811
  //#endregion
5691
5812
  //#region src/extensions/noop-loop-guard.ts
5692
- const log$8 = logger.child({ module: "noop-loop-guard" });
5813
+ const log$9 = logger.child({ module: "noop-loop-guard" });
5693
5814
  /** Length of the rolling window that counts silence commands across streak resets. */
5694
5815
  const SILENCE_WINDOW_MS = 300 * 1e3;
5695
5816
  /** Bare shell no-op: `true` or `:` (case-insensitive). */
@@ -5705,9 +5826,9 @@ const ECHO_ARG_MAX_LEN = 64;
5705
5826
  /** Marker that forces a single command through the guard. */
5706
5827
  const BYPASS_HINT$1 = "noop-guard: allow";
5707
5828
  /** Env vars that turn the guard off for the process. */
5708
- const KILL_SWITCH_KEYS = ["NOOP_LOOP_GUARD_DISABLE", "SKYDIVE_NOOP_LOOP_GUARD_DISABLE"];
5709
- function guardDisabledByEnv$1() {
5710
- return KILL_SWITCH_KEYS.some((key) => {
5829
+ const KILL_SWITCH_KEYS$1 = ["NOOP_LOOP_GUARD_DISABLE", "SKYDIVE_NOOP_LOOP_GUARD_DISABLE"];
5830
+ function guardDisabledByEnv$2() {
5831
+ return KILL_SWITCH_KEYS$1.some((key) => {
5711
5832
  const value = process.env[key];
5712
5833
  return value !== void 0 && value !== "" && value !== "0";
5713
5834
  });
@@ -5831,17 +5952,20 @@ const noopLoopGuardExtension = (pi) => {
5831
5952
  };
5832
5953
  pi.on("tool_call", async (event, ctx) => {
5833
5954
  if (event.toolName !== "bash") return;
5834
- if (guardDisabledByEnv$1()) return;
5835
- const command = event.input.command;
5836
- if (typeof command !== "string" || command.length === 0) return;
5955
+ if (guardDisabledByEnv$2()) return;
5956
+ const rawCommand = event.input.command;
5957
+ if (typeof rawCommand !== "string" || rawCommand.length === 0) return;
5958
+ const command = stripPlatformExportsForDisplay(rawCommand);
5837
5959
  const now = Date.now();
5838
- const bypassed = isSilenceCommand(command) && hasBypassMarker$1(command);
5960
+ const silence = isSilenceCommand(command);
5961
+ const bypassed = silence && hasBypassMarker$1(command);
5839
5962
  const streak = recordNoopCommand(state, command, now);
5963
+ if (!silence) return;
5840
5964
  const windowCount = countSilenceInWindow(state, now);
5841
5965
  if (bypassed) return;
5842
5966
  if (streak < 3 && windowCount < 8) return;
5843
5967
  const aborted = streak >= 25 || windowCount >= 40;
5844
- log$8.warn({
5968
+ log$9.warn({
5845
5969
  streak,
5846
5970
  windowCount,
5847
5971
  aborted,
@@ -5859,6 +5983,70 @@ const noopLoopGuardExtension = (pi) => {
5859
5983
  });
5860
5984
  };
5861
5985
  //#endregion
5986
+ //#region src/extensions/repeat-call-guard.ts
5987
+ const log$8 = logger.child({ module: "repeat-call-guard" });
5988
+ const KILL_SWITCH_KEYS = ["REPEAT_CALL_GUARD_DISABLE", "SKYDIVE_REPEAT_CALL_GUARD_DISABLE"];
5989
+ function guardDisabledByEnv$1() {
5990
+ return KILL_SWITCH_KEYS.some((key) => {
5991
+ const value = process.env[key];
5992
+ return value !== void 0 && value !== "" && value !== "0";
5993
+ });
5994
+ }
5995
+ /**
5996
+ * Identity of a tool call for repeat detection: tool name plus arguments,
5997
+ * minus the fields the platform adds per call.
5998
+ */
5999
+ function toolCallKey({ toolName, input }) {
6000
+ const normalized = {};
6001
+ for (const [key, value] of Object.entries(input)) {
6002
+ if (TOOL_CALL_SUMMARY_FIELDS.includes(key)) continue;
6003
+ normalized[key] = key === "command" && typeof value === "string" ? stripPlatformExportsForDisplay(value) : value;
6004
+ }
6005
+ return `${toolName}\u0000${JSON.stringify(normalized)}`;
6006
+ }
6007
+ /** Count one call against the streak; returns the new streak length. */
6008
+ function recordToolCall(state, key) {
6009
+ state.streak = key === state.lastKey ? state.streak + 1 : 1;
6010
+ state.lastKey = key;
6011
+ return state.streak;
6012
+ }
6013
+ function repeatBlockReason({ toolName, streak, aborted }) {
6014
+ const head = `Repeated call: ${streak} consecutive \`${toolName}\` calls with exactly the same arguments. Repeating it will not change the outcome. If you are done, END THE TURN (reply, or emit nothing to stay silent). If you are waiting on a background task, end the turn: it wakes you when it finishes. Otherwise change approach.`;
6015
+ if (aborted) return `${head} The harness is now stopping this run.`;
6016
+ const remaining = 40 - streak;
6017
+ return `${head} ${remaining} more identical call${remaining === 1 ? "" : "s"} and the harness stops the run.`;
6018
+ }
6019
+ const repeatCallGuardExtension = (pi) => {
6020
+ const state = {
6021
+ lastKey: null,
6022
+ streak: 0
6023
+ };
6024
+ pi.on("tool_call", async (event, ctx) => {
6025
+ if (guardDisabledByEnv$1()) return;
6026
+ const streak = recordToolCall(state, toolCallKey({
6027
+ toolName: event.toolName,
6028
+ input: event.input
6029
+ }));
6030
+ if (streak < 20) return;
6031
+ const aborted = streak >= 40;
6032
+ log$8.warn({
6033
+ toolName: event.toolName,
6034
+ streak,
6035
+ aborted,
6036
+ toolCallId: event.toolCallId
6037
+ }, "repeat-call guard fired");
6038
+ if (aborted) ctx.abort();
6039
+ return {
6040
+ block: true,
6041
+ reason: repeatBlockReason({
6042
+ toolName: event.toolName,
6043
+ streak,
6044
+ aborted
6045
+ })
6046
+ };
6047
+ });
6048
+ };
6049
+ //#endregion
5862
6050
  //#region src/extensions/sleep-guard.ts
5863
6051
  /**
5864
6052
  * Foreground sleep guard: block `sleep` commands that hold the turn open.
@@ -7471,6 +7659,7 @@ const all = [
7471
7659
  bashDefaultTimeoutExtension,
7472
7660
  diskGuardExtension,
7473
7661
  noopLoopGuardExtension,
7662
+ repeatCallGuardExtension,
7474
7663
  sleepGuardExtension,
7475
7664
  toolCallSummaryExtension
7476
7665
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skydiveai/pi-extensions",
3
- "version": "0.1.258-beta.13",
3
+ "version": "0.1.258-beta.130",
4
4
  "homepage": "https://skydive.com",
5
5
  "license": "MIT",
6
6
  "author": "Create, Inc.",