@skydiveai/pi-extensions 0.1.258-beta.14 → 0.1.258-beta.141

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 +628 -142
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -25,6 +25,8 @@ import { execFile, spawn } from "node:child_process";
25
25
  import os, { availableParallelism } from "node:os";
26
26
  import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
27
27
  import { adjustMaxTokensForThinking, clampMaxTokensToContext } from "@earendil-works/pi-ai-runtime/api/simple-options";
28
+ import { createServer } from "node:http";
29
+ import { buffer } from "node:stream/consumers";
28
30
  import { quote } from "shell-quote";
29
31
  import { ROOT_CONTEXT, SpanStatusCode, propagation, trace } from "@opentelemetry/api";
30
32
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
@@ -265,7 +267,7 @@ function createHealthHandler({ metadata }) {
265
267
  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
268
  //#endregion
267
269
  //#region src/extensions/tool-call-summary.ts
268
- const log$19 = logger.child({ module: "tool-call-summary-extension" });
270
+ const log$23 = logger.child({ module: "tool-call-summary-extension" });
269
271
  /**
270
272
  * The injected parameter name. Deliberately markdown-safe: the previous wire
271
273
  * name (`__skydive_summary__`, now `TOOL_CALL_SUMMARY_FIELD_LEGACY`) carried
@@ -499,7 +501,7 @@ function withSummaryStrippedBeforeValidation(tool) {
499
501
  try {
500
502
  stripped = withoutInjectedSummary(args);
501
503
  } catch (err) {
502
- log$19.error({
504
+ log$23.error({
503
505
  err,
504
506
  event: "tool_call_summary_prepare_strip_failed",
505
507
  toolName: tool.name
@@ -530,7 +532,7 @@ function stripInjectedSummary(pi, toolName, input) {
530
532
  if (toolDeclaresSummaryParam(pi, toolName)) return;
531
533
  for (const field of TOOL_CALL_SUMMARY_FIELDS) delete input[field];
532
534
  } catch (err) {
533
- log$19.error({
535
+ log$23.error({
534
536
  err,
535
537
  event: "tool_call_summary_strip_failed",
536
538
  toolName
@@ -546,7 +548,7 @@ function buildInjectedPayload(pi, payload) {
546
548
  try {
547
549
  return injectToolCallSummary(payload, getStrictToolNames(pi));
548
550
  } catch (err) {
549
- log$19.error({
551
+ log$23.error({
550
552
  err,
551
553
  event: "tool_call_summary_injection_failed"
552
554
  }, "tool_call_summary injection failed; passing payload through unchanged");
@@ -565,7 +567,7 @@ const toolCallSummaryExtension = (pi) => {
565
567
  pi.registerTool(withSummaryStrippedBeforeValidation(createEditToolDefinition(ctx.cwd)));
566
568
  editOverrideRegistered = true;
567
569
  } catch (err) {
568
- log$19.error({
570
+ log$23.error({
569
571
  err,
570
572
  event: "tool_call_summary_edit_override_failed"
571
573
  }, "failed to register summary-tolerant edit tool; built-in remains active");
@@ -596,7 +598,7 @@ const toolCallSummaryExtension = (pi) => {
596
598
  * or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
597
599
  * `tools/_example.ts` documents the shape without registering.
598
600
  */
599
- const log$18 = logger.child({ module: "local-tools-extension" });
601
+ const log$22 = logger.child({ module: "local-tools-extension" });
600
602
  const TOOLS_DIRNAME = "tools";
601
603
  const fileState = /* @__PURE__ */ new Map();
602
604
  let pendingLocalToolsUpdate = null;
@@ -740,7 +742,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
740
742
  dir
741
743
  });
742
744
  if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
743
- log$18.info({
745
+ log$22.info({
744
746
  event: "local_tools_reconcile",
745
747
  reason,
746
748
  total_tools: summary.totalTools,
@@ -762,7 +764,7 @@ const localToolsExtension = (pi) => {
762
764
  reason: "session_start"
763
765
  });
764
766
  } catch (err) {
765
- log$18.error({
767
+ log$22.error({
766
768
  err,
767
769
  event: "local_tools_reconcile_failed"
768
770
  }, "local tools reconcile failed");
@@ -774,7 +776,7 @@ const localToolsExtension = (pi) => {
774
776
  try {
775
777
  current = await listToolFiles(dir);
776
778
  } catch (err) {
777
- log$18.warn({
779
+ log$22.warn({
778
780
  err,
779
781
  event: "local_tools_listing_failed"
780
782
  }, "tools/ listing failed");
@@ -796,7 +798,7 @@ const localToolsExtension = (pi) => {
796
798
  reason: "auto_reload"
797
799
  });
798
800
  } catch (err) {
799
- log$18.error({
801
+ log$22.error({
800
802
  err,
801
803
  event: "local_tools_auto_reload_failed"
802
804
  }, "auto-reload after tools/ change failed");
@@ -1288,17 +1290,23 @@ function legacyMcpToolName({ serverName, toolName }) {
1288
1290
  * a small, focused unit-test surface (typebox validation, error formatting).
1289
1291
  */
1290
1292
  const MCP_CONFIG_FILENAME = "mcp.config.json";
1293
+ const ToolSelectionSchema = {
1294
+ tools: Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()])),
1295
+ excludeTools: Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()]))
1296
+ };
1291
1297
  const StdioServerSchema = Type.Object({
1292
1298
  transport: Type.Literal("stdio"),
1293
1299
  command: Type.String(),
1294
1300
  args: Type.Array(Type.String()),
1295
1301
  env: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()])),
1296
- cwd: Type.Optional(Type.Union([Type.String(), Type.Null()]))
1302
+ cwd: Type.Optional(Type.Union([Type.String(), Type.Null()])),
1303
+ ...ToolSelectionSchema
1297
1304
  });
1298
1305
  const HttpServerSchema = Type.Object({
1299
1306
  transport: Type.Literal("http"),
1300
1307
  url: Type.String(),
1301
- headers: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()]))
1308
+ headers: Type.Optional(Type.Union([Type.Record(Type.String(), Type.String()), Type.Null()])),
1309
+ ...ToolSelectionSchema
1302
1310
  });
1303
1311
  const ServerSchema = Type.Union([StdioServerSchema, HttpServerSchema]);
1304
1312
  const McpConfigSchema = Type.Object({ servers: Type.Record(Type.String(), ServerSchema) });
@@ -1325,11 +1333,15 @@ async function loadMcpConfig(path) {
1325
1333
  for (const [id, server] of Object.entries(json.servers)) if (server.transport === "stdio") servers[id] = {
1326
1334
  ...server,
1327
1335
  env: server.env ?? null,
1328
- cwd: server.cwd ?? null
1336
+ cwd: server.cwd ?? null,
1337
+ tools: server.tools ?? null,
1338
+ excludeTools: server.excludeTools ?? null
1329
1339
  };
1330
1340
  else servers[id] = {
1331
1341
  ...server,
1332
- headers: server.headers ?? null
1342
+ headers: server.headers ?? null,
1343
+ tools: server.tools ?? null,
1344
+ excludeTools: server.excludeTools ?? null
1333
1345
  };
1334
1346
  return { servers };
1335
1347
  }
@@ -1490,7 +1502,55 @@ function toProviderSafeSchema(inputSchema) {
1490
1502
  * Clients are keyed by JSON-stringified config and reused across
1491
1503
  * reloads — only changed configs reconnect.
1492
1504
  */
1493
- const log$17 = logger.child({ module: "mcp-extension" });
1505
+ const log$21 = logger.child({ module: "mcp-extension" });
1506
+ function resolveToolSelection(server) {
1507
+ return {
1508
+ allow: server?.tools?.length ? new Set(server.tools) : null,
1509
+ deny: new Set(server?.excludeTools ?? [])
1510
+ };
1511
+ }
1512
+ /**
1513
+ * Connection identity of a server config: everything except the per-server
1514
+ * tool selection. `tools`/`excludeTools` only filter the advertised list at
1515
+ * registration time, so an edit to them must re-register tools, not tear
1516
+ * down and re-handshake the client (kills the stdio process, re-runs the
1517
+ * http OAuth/handshake for an identical connection).
1518
+ */
1519
+ function connectionKey(serverConfig) {
1520
+ const { tools: _tools, excludeTools: _excludeTools, ...connection } = serverConfig;
1521
+ return JSON.stringify(connection);
1522
+ }
1523
+ /**
1524
+ * Apply a server's configured tool selection to its advertised list.
1525
+ * Runs BEFORE the budget allocator: a filtered set is what competes for
1526
+ * the per-server / total / token caps, so an allowlisted tool wins the
1527
+ * budget contest instead of being truncated behind tools the config
1528
+ * never asked for. Intentional exclusions are NOT budget drops — they
1529
+ * don't count toward `droppedTools` and produce no truncation warning.
1530
+ */
1531
+ function applyToolSelection(tools, selection) {
1532
+ if (selection.allow === null && selection.deny.size === 0) return {
1533
+ list: tools,
1534
+ filteredOut: 0,
1535
+ unknownTools: [],
1536
+ unknownExcludeTools: []
1537
+ };
1538
+ const kept = [];
1539
+ for (const tool of tools) {
1540
+ if (selection.allow !== null && !selection.allow.has(tool.name)) continue;
1541
+ if (selection.deny.has(tool.name)) continue;
1542
+ kept.push(tool);
1543
+ }
1544
+ const notAdvertised = (names) => [...names].filter((name) => !tools.some((tool) => tool.name === name));
1545
+ const unknownTools = selection.allow === null ? [] : notAdvertised(selection.allow);
1546
+ const unknownExcludeTools = selection.deny.size === 0 ? [] : notAdvertised(selection.deny);
1547
+ return {
1548
+ list: kept,
1549
+ filteredOut: tools.length - kept.length,
1550
+ unknownTools,
1551
+ unknownExcludeTools
1552
+ };
1553
+ }
1494
1554
  async function closeConnected(connected) {
1495
1555
  try {
1496
1556
  await connected.client.close();
@@ -1640,7 +1700,7 @@ function providerSafeTools({ serverId, tools }) {
1640
1700
  for (const tool of tools) {
1641
1701
  const result = toProviderSafeSchema(tool.inputSchema);
1642
1702
  if (!result.ok) {
1643
- log$17.warn({
1703
+ log$21.warn({
1644
1704
  event: "mcp_tool_schema_unsupported",
1645
1705
  server_id: serverId,
1646
1706
  tool_name: tool.name,
@@ -1797,9 +1857,11 @@ var McpExtension = class {
1797
1857
  else if (outcome.change === "refreshed") summary.refreshed.push(id);
1798
1858
  }
1799
1859
  const alloc = outcomes.filter((o) => Boolean(o.tools)).map((o) => {
1860
+ const selection = resolveToolSelection(config.servers[o.id]);
1861
+ const picked = applyToolSelection(o.tools.list, selection);
1800
1862
  const { tools: list, skipped } = providerSafeTools({
1801
1863
  serverId: o.id,
1802
- tools: o.tools.list
1864
+ tools: picked.list
1803
1865
  });
1804
1866
  return {
1805
1867
  id: o.id,
@@ -1807,6 +1869,9 @@ var McpExtension = class {
1807
1869
  list,
1808
1870
  advertised: o.tools.list.length,
1809
1871
  skipped,
1872
+ filtered: picked.filteredOut,
1873
+ unknownTools: picked.unknownTools,
1874
+ unknownExcludeTools: picked.unknownExcludeTools,
1810
1875
  room: Math.min(list.length, limits.maxToolsPerServer),
1811
1876
  registered: 0,
1812
1877
  serverTokens: 0,
@@ -1850,7 +1915,10 @@ var McpExtension = class {
1850
1915
  registered: s.registered,
1851
1916
  tokens: s.serverTokens,
1852
1917
  droppedReason,
1853
- skipped: s.skipped
1918
+ skipped: s.skipped,
1919
+ filtered: s.filtered,
1920
+ unknownTools: s.unknownTools,
1921
+ unknownExcludeTools: s.unknownExcludeTools
1854
1922
  };
1855
1923
  }
1856
1924
  return summary;
@@ -1862,10 +1930,10 @@ var McpExtension = class {
1862
1930
  * map/summary, so callers can run these concurrently.
1863
1931
  */
1864
1932
  async reconcileServer({ id, serverConfig, existing, connectTimeoutMs }) {
1865
- const configKey = JSON.stringify(serverConfig);
1933
+ const configKey = connectionKey(serverConfig);
1866
1934
  let action;
1867
1935
  let connected;
1868
- if (existing && existing.configKey === configKey) {
1936
+ if (existing && existing.connectionKey === configKey) {
1869
1937
  connected = existing;
1870
1938
  action = "reused";
1871
1939
  } else {
@@ -1891,7 +1959,7 @@ var McpExtension = class {
1891
1959
  id,
1892
1960
  store: {
1893
1961
  client: result.client,
1894
- configKey,
1962
+ connectionKey: configKey,
1895
1963
  status: "pending_auth",
1896
1964
  stderrBuffer: result.stderrBuffer,
1897
1965
  cliHint: result.cliHint
@@ -1909,7 +1977,7 @@ var McpExtension = class {
1909
1977
  id,
1910
1978
  store: {
1911
1979
  client: result.client,
1912
- configKey,
1980
+ connectionKey: configKey,
1913
1981
  status: "timeout",
1914
1982
  stderrBuffer: result.stderrBuffer,
1915
1983
  cliHint: null
@@ -1925,7 +1993,7 @@ var McpExtension = class {
1925
1993
  };
1926
1994
  connected = {
1927
1995
  client: result.client,
1928
- configKey,
1996
+ connectionKey: configKey,
1929
1997
  status: "connected",
1930
1998
  stderrBuffer: result.stderr,
1931
1999
  cliHint: null
@@ -1939,7 +2007,7 @@ var McpExtension = class {
1939
2007
  id,
1940
2008
  store: {
1941
2009
  client: retry.client,
1942
- configKey,
2010
+ connectionKey: configKey,
1943
2011
  status: "pending_auth",
1944
2012
  stderrBuffer: null,
1945
2013
  cliHint: retry.cliHint
@@ -1957,7 +2025,7 @@ var McpExtension = class {
1957
2025
  id,
1958
2026
  store: {
1959
2027
  client: retry.client,
1960
- configKey,
2028
+ connectionKey: configKey,
1961
2029
  status: "timeout",
1962
2030
  stderrBuffer: retry.stderrBuffer,
1963
2031
  cliHint: null
@@ -1985,7 +2053,7 @@ var McpExtension = class {
1985
2053
  };
1986
2054
  connected = {
1987
2055
  client: retry.client,
1988
- configKey,
2056
+ connectionKey: configKey,
1989
2057
  status: "connected",
1990
2058
  stderrBuffer: retry.stderr,
1991
2059
  cliHint: null
@@ -2017,7 +2085,7 @@ var McpExtension = class {
2017
2085
  id,
2018
2086
  store: {
2019
2087
  client: retry.client,
2020
- configKey,
2088
+ connectionKey: configKey,
2021
2089
  status: "pending_auth",
2022
2090
  stderrBuffer: null,
2023
2091
  cliHint: retry.cliHint
@@ -2049,7 +2117,7 @@ var McpExtension = class {
2049
2117
  if (retry.status === "connected") {
2050
2118
  connected = {
2051
2119
  client: retry.client,
2052
- configKey,
2120
+ connectionKey: configKey,
2053
2121
  status: "connected",
2054
2122
  stderrBuffer: retry.stderr,
2055
2123
  cliHint: null
@@ -2106,7 +2174,7 @@ var McpExtension = class {
2106
2174
  });
2107
2175
  this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
2108
2176
  if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
2109
- log$17.info({
2177
+ log$21.info({
2110
2178
  event: "mcp_reconcile",
2111
2179
  reason,
2112
2180
  total_tools: summary.totalTools,
@@ -2133,7 +2201,7 @@ var McpExtension = class {
2133
2201
  contextWindow: ctx.model?.contextWindow
2134
2202
  });
2135
2203
  } catch (err) {
2136
- log$17.error({
2204
+ log$21.error({
2137
2205
  err,
2138
2206
  event: "mcp_reconcile_failed"
2139
2207
  }, "MCP reconcile failed");
@@ -2147,7 +2215,7 @@ var McpExtension = class {
2147
2215
  for (const legacy of renamed) {
2148
2216
  if (this.loggedLegacyToolNames.has(legacy)) continue;
2149
2217
  this.loggedLegacyToolNames.add(legacy);
2150
- log$17.info({
2218
+ log$21.info({
2151
2219
  event: "mcp_tool_legacy_name",
2152
2220
  legacy_name: legacy,
2153
2221
  tool_name: this.legacyToolNames.get(legacy)
@@ -2161,7 +2229,7 @@ var McpExtension = class {
2161
2229
  try {
2162
2230
  mtime = await readConfigMtimeMs(configPath);
2163
2231
  } catch (err) {
2164
- log$17.warn({
2232
+ log$21.warn({
2165
2233
  err,
2166
2234
  event: "mcp_mtime_check_failed"
2167
2235
  }, "mtime check on mcp.config.json failed");
@@ -2176,7 +2244,7 @@ var McpExtension = class {
2176
2244
  contextWindow: ctx.model?.contextWindow
2177
2245
  });
2178
2246
  } catch (err) {
2179
- log$17.error({
2247
+ log$21.error({
2180
2248
  err,
2181
2249
  event: "mcp_auto_reload_failed"
2182
2250
  }, "auto-reload after mcp.config.json change failed");
@@ -2304,11 +2372,27 @@ function skippedSchemaLines(summary) {
2304
2372
  for (const [id, count] of entries) for (const { name, reason } of count.skipped) lines.push(` - ${id}/${name}: ${reason}`);
2305
2373
  return lines;
2306
2374
  }
2375
+ /**
2376
+ * Lines naming allowlist entries in mcp.config.json that matched no tool the
2377
+ * server advertises — almost always a typo, and silent otherwise: the agent
2378
+ * just sees a narrower tool set and can't tell the config is wrong.
2379
+ */
2380
+ function unknownToolLines(summary) {
2381
+ const entries = Object.entries(summary.toolCounts).filter(([, count]) => count.unknownTools.length > 0 || count.unknownExcludeTools.length > 0);
2382
+ if (entries.length === 0) return [];
2383
+ const lines = [];
2384
+ for (const [id, count] of entries) {
2385
+ 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(", ")}.`);
2386
+ 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(", ")}.`);
2387
+ }
2388
+ return lines;
2389
+ }
2307
2390
  function summaryText(summary) {
2308
2391
  const lines = [];
2309
2392
  lines.push(`MCP reconcile complete: ${summary.totalTools} tool(s) live.`);
2310
2393
  lines.push(...truncationLines(summary));
2311
2394
  lines.push(...skippedSchemaLines(summary));
2395
+ lines.push(...unknownToolLines(summary));
2312
2396
  if (summary.added.length > 0) lines.push(` Added: ${summary.added.join(", ")}`);
2313
2397
  if (summary.refreshed.length > 0) lines.push(` Refreshed: ${summary.refreshed.join(", ")}`);
2314
2398
  if (summary.removed.length > 0) lines.push(` Removed: ${summary.removed.join(", ")}`);
@@ -2526,11 +2610,21 @@ const assistantSchema = z.object({
2526
2610
  id: z.string(),
2527
2611
  model: z.string()
2528
2612
  });
2613
+ const sdkToolResultSchema = z.object({ content: z.array(z.object({ type: z.literal("tool_result") })).min(1) });
2529
2614
  function assistantMessage(entry) {
2530
2615
  if (entry.type !== "assistant") return null;
2531
2616
  const parsed = assistantSchema.safeParse(entry.message);
2532
2617
  return parsed.success ? parsed.data : null;
2533
2618
  }
2619
+ /**
2620
+ * Claude Code answers some tool_use blocks itself mid-stream (e.g. "No such
2621
+ * tool available") and persists that result between the response's blocks.
2622
+ * Pi owns tool execution and replays its own results, so these never belong
2623
+ * in the accepted prefix.
2624
+ */
2625
+ function isSdkToolResult(entry) {
2626
+ return entry.type === "user" && sdkToolResultSchema.safeParse(entry.message).success;
2627
+ }
2534
2628
  function contentHash(message) {
2535
2629
  return createHash("sha256").update(JSON.stringify(message.content)).digest("hex");
2536
2630
  }
@@ -2588,7 +2682,7 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2588
2682
  const entry = byId.get(id);
2589
2683
  if (!entry) break;
2590
2684
  const assistant = assistantMessage(entry);
2591
- if (!assistant || assistant.model === "<synthetic>" || acceptedIds.has(assistant.id)) entries.push(entry);
2685
+ if (!isSdkToolResult(entry) && (!assistant || assistant.model === "<synthetic>" || acceptedIds.has(assistant.id))) entries.push(entry);
2592
2686
  id = entry.parentUuid;
2593
2687
  }
2594
2688
  if (id === boundaryId && entries.length) return entries.reverse();
@@ -2597,6 +2691,8 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2597
2691
  }
2598
2692
  //#endregion
2599
2693
  //#region src/extensions/claude-seat-history.ts
2694
+ /** Sent as the SDK prompt when Pi's context ends with tool results. */
2695
+ const SEAT_CONTINUE_PROMPT = "Continue from the existing conversation and tool results.";
2600
2696
  const imageType = z.enum([
2601
2697
  "image/jpeg",
2602
2698
  "image/png",
@@ -2681,7 +2777,7 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
2681
2777
  const hashes = seatPrefixHashes(context, model);
2682
2778
  const messages = [...context.messages];
2683
2779
  const last = messages.at(-1);
2684
- const prompt = last?.role === "user" ? userContent(last.content) : "Continue from the existing conversation and tool results.";
2780
+ const prompt = last?.role === "user" ? userContent(last.content) : SEAT_CONTINUE_PROMPT;
2685
2781
  if (last?.role === "user") messages.pop();
2686
2782
  if (messages.length === 0) return {
2687
2783
  prompt,
@@ -2795,6 +2891,176 @@ function seatReasoningOptions({ model, context, options }) {
2795
2891
  };
2796
2892
  }
2797
2893
  //#endregion
2894
+ //#region src/extensions/claude-seat-request-proxy.ts
2895
+ const log$20 = logger.child({ module: "claude-seat-request-proxy" });
2896
+ const RESUME_PLACEHOLDER = "No response requested.";
2897
+ const blockSchema = z.record(z.string(), z.json());
2898
+ const messageSchema = z.object({
2899
+ role: z.string(),
2900
+ content: z.union([z.string(), z.array(blockSchema)])
2901
+ }).catchall(z.json());
2902
+ const requestSchema = z.object({ messages: z.array(messageSchema) }).catchall(z.json());
2903
+ function blocks(message) {
2904
+ return typeof message.content === "string" ? [{
2905
+ type: "text",
2906
+ text: message.content
2907
+ }] : message.content;
2908
+ }
2909
+ /** The text of a message made of exactly one text block, else null. */
2910
+ function soleText(message) {
2911
+ if (!message) return null;
2912
+ const [only, ...rest] = blocks(message);
2913
+ return only?.type === "text" && rest.length === 0 ? only.text : null;
2914
+ }
2915
+ function hasToolResult(message) {
2916
+ return message?.role === "user" && blocks(message).some((block) => block.type === "tool_result");
2917
+ }
2918
+ function isPlaceholder(message) {
2919
+ return message.role === "assistant" && soleText(message) === RESUME_PLACEHOLDER;
2920
+ }
2921
+ function isContinuePrompt(message) {
2922
+ return message?.role === "user" && soleText(message) === "Continue from the existing conversation and tool results.";
2923
+ }
2924
+ /**
2925
+ * On resume, the pinned Claude Code CLI inserts a synthetic "No response
2926
+ * requested." assistant turn before any prompt that follows a tool_result.
2927
+ * Removing it (and our own continuation prompt) from every request keeps the
2928
+ * model from rereading itself saying it once per tool step. Applying the same
2929
+ * rewrite to every request keeps prefixes byte-identical across steps, so the
2930
+ * prompt cache and thinking signatures see one stable history.
2931
+ */
2932
+ function stripResumePlaceholders(messages) {
2933
+ const kept = [];
2934
+ let cacheControl = null;
2935
+ for (let index = 0; index < messages.length; index++) {
2936
+ const message = messages[index];
2937
+ if (!message) continue;
2938
+ const next = messages[index + 1];
2939
+ if (isPlaceholder(message) && hasToolResult(messages[index - 1]) && next?.role === "user") {
2940
+ const dropped = isContinuePrompt(next) ? [message, next] : [message];
2941
+ for (const block of dropped.flatMap(blocks)) if (block.cache_control !== void 0) cacheControl = block.cache_control;
2942
+ if (dropped.length === 2) index++;
2943
+ continue;
2944
+ }
2945
+ kept.push(message);
2946
+ }
2947
+ const merged = [];
2948
+ for (const message of kept) {
2949
+ const previous = merged.at(-1);
2950
+ if (previous?.role === message.role && (message.role === "user" || message.role === "assistant")) merged[merged.length - 1] = {
2951
+ ...previous,
2952
+ content: [...blocks(previous), ...blocks(message)]
2953
+ };
2954
+ else merged.push(message);
2955
+ }
2956
+ const last = merged.at(-1);
2957
+ if (cacheControl !== null && last) {
2958
+ const content = blocks(last).map((block) => {
2959
+ const { cache_control: _, ...rest } = block;
2960
+ return rest;
2961
+ });
2962
+ const tail = content.at(-1);
2963
+ if (tail) content[content.length - 1] = {
2964
+ ...tail,
2965
+ cache_control: cacheControl
2966
+ };
2967
+ merged[merged.length - 1] = {
2968
+ ...last,
2969
+ content
2970
+ };
2971
+ }
2972
+ return {
2973
+ messages: merged,
2974
+ removed: messages.length - kept.length
2975
+ };
2976
+ }
2977
+ const jsonSchema = z.string().transform((text, ctx) => {
2978
+ try {
2979
+ return JSON.parse(text);
2980
+ } catch {
2981
+ ctx.addIssue({
2982
+ code: "custom",
2983
+ message: "Request body is not JSON"
2984
+ });
2985
+ return z.NEVER;
2986
+ }
2987
+ });
2988
+ function rewriteBody(body) {
2989
+ const parsed = jsonSchema.pipe(requestSchema).safeParse(body.toString());
2990
+ if (!parsed.success) {
2991
+ log$20.warn({ err: parsed.error }, "Claude seat request did not match the expected shape; forwarding as is");
2992
+ return body;
2993
+ }
2994
+ const { messages, removed } = stripResumePlaceholders(parsed.data.messages);
2995
+ if (removed === 0) return body;
2996
+ return Buffer.from(JSON.stringify({
2997
+ ...parsed.data,
2998
+ messages
2999
+ }));
3000
+ }
3001
+ const HOP_BY_HOP = new Set([
3002
+ "host",
3003
+ "connection",
3004
+ "content-length",
3005
+ "transfer-encoding",
3006
+ "keep-alive"
3007
+ ]);
3008
+ /**
3009
+ * Local hop between the Claude Code CLI and the seat's upstream base URL. It
3010
+ * forwards everything unchanged except Messages API bodies, which lose the
3011
+ * CLI's resume placeholders (see `stripResumePlaceholders`).
3012
+ */
3013
+ async function startSeatRequestProxy({ target }) {
3014
+ const base = target.replace(/\/+$/, "");
3015
+ const server = createServer(async (request, response) => {
3016
+ const upstreamAbort = new AbortController();
3017
+ response.once("close", () => upstreamAbort.abort());
3018
+ try {
3019
+ const raw = await buffer(request);
3020
+ const body = request.method === "POST" && request.url?.startsWith("/v1/messages") ? rewriteBody(raw) : raw;
3021
+ const headers = new Headers();
3022
+ for (const [name, value] of Object.entries(request.headers)) {
3023
+ if (value === void 0 || HOP_BY_HOP.has(name)) continue;
3024
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
3025
+ }
3026
+ const upstream = await fetch(`${base}${request.url ?? ""}`, {
3027
+ method: request.method,
3028
+ headers,
3029
+ body: ["GET", "HEAD"].includes(request.method ?? "") ? null : new Uint8Array(body),
3030
+ signal: upstreamAbort.signal
3031
+ });
3032
+ const responseHeaders = {};
3033
+ upstream.headers.forEach((value, name) => {
3034
+ if (!HOP_BY_HOP.has(name) && name !== "content-encoding") responseHeaders[name] = value;
3035
+ });
3036
+ response.writeHead(upstream.status, responseHeaders);
3037
+ if (!upstream.body) {
3038
+ response.end();
3039
+ return;
3040
+ }
3041
+ const reader = upstream.body.getReader();
3042
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) if (!response.write(chunk.value)) await once(response, "drain", { signal: upstreamAbort.signal });
3043
+ response.end();
3044
+ } catch (err) {
3045
+ if (upstreamAbort.signal.aborted) return;
3046
+ log$20.error({ err }, "Claude seat request proxy failed to forward");
3047
+ if (!response.headersSent) response.writeHead(502);
3048
+ response.end();
3049
+ }
3050
+ });
3051
+ server.listen(0, "127.0.0.1");
3052
+ await once(server, "listening");
3053
+ const address = server.address();
3054
+ if (!address || typeof address === "string") throw new Error("Claude seat request proxy has no TCP address");
3055
+ return {
3056
+ url: `http://127.0.0.1:${address.port}`,
3057
+ close: () => {
3058
+ server.closeAllConnections();
3059
+ server.close();
3060
+ }
3061
+ };
3062
+ }
3063
+ //#endregion
2798
3064
  //#region src/extensions/claude-seat-payload.ts
2799
3065
  const payloadSchema = z.strictObject({
2800
3066
  model: z.string(),
@@ -2866,7 +3132,7 @@ const SEAT_QUERY_TIMEOUTS = {
2866
3132
  preparation: 3e4
2867
3133
  };
2868
3134
  const PI_TOOLS_SERVER = "custom-tools";
2869
- const log$16 = logger.child({ module: "claude-seat-sdk" });
3135
+ const log$19 = logger.child({ module: "claude-seat-sdk" });
2870
3136
  /** Preserve existing MCP names; only ordinary Pi tools need a server prefix. */
2871
3137
  function toolBindings(context) {
2872
3138
  const parsed = (context.tools ?? []).map((definition) => {
@@ -2924,7 +3190,7 @@ var SeatQuery = class {
2924
3190
  this.deadline = setTimeout(() => {
2925
3191
  const err = /* @__PURE__ */ new Error(`Claude seat SDK timed out waiting for ${phase}`);
2926
3192
  err.name = "TimeoutError";
2927
- log$16.error({
3193
+ log$19.error({
2928
3194
  err,
2929
3195
  phase
2930
3196
  }, "Claude seat SDK wait deadline exceeded");
@@ -2965,10 +3231,12 @@ var SeatQuery = class {
2965
3231
  async run({ sessionId, cwd }) {
2966
3232
  const { model, context, options } = this.request;
2967
3233
  let configDir = null;
3234
+ let requestProxy = null;
2968
3235
  try {
2969
3236
  if (!options.apiKey) throw new Error("Claude seat SDK requires a seat credential sentinel");
2970
3237
  this.controller.signal.throwIfAborted();
2971
3238
  configDir = await mkdtemp(path.join(os.tmpdir(), "claude-seat-sdk-"));
3239
+ requestProxy = await startSeatRequestProxy({ target: model.baseUrl });
2972
3240
  this.controller.signal.throwIfAborted();
2973
3241
  const bindings = toolBindings(context);
2974
3242
  const servers = /* @__PURE__ */ new Map();
@@ -3063,7 +3331,7 @@ var SeatQuery = class {
3063
3331
  env: buildStdioEnv({
3064
3332
  ANTHROPIC_AUTH_TOKEN: options.apiKey,
3065
3333
  ANTHROPIC_API_KEY: "",
3066
- ANTHROPIC_BASE_URL: model.baseUrl,
3334
+ ANTHROPIC_BASE_URL: requestProxy.url,
3067
3335
  ANTHROPIC_CUSTOM_HEADERS: platformHeaders({
3068
3336
  model,
3069
3337
  options,
@@ -3105,7 +3373,7 @@ var SeatQuery = class {
3105
3373
  }
3106
3374
  } catch (err) {
3107
3375
  this.failure = err;
3108
- if (!this.controller.signal.aborted) log$16.error({
3376
+ if (!this.controller.signal.aborted) log$19.error({
3109
3377
  err,
3110
3378
  sessionId
3111
3379
  }, "Claude seat SDK query failed");
@@ -3114,13 +3382,14 @@ var SeatQuery = class {
3114
3382
  if (this.deadline) clearTimeout(this.deadline);
3115
3383
  this.deadline = null;
3116
3384
  this.wake?.();
3385
+ requestProxy?.close();
3117
3386
  if (configDir) try {
3118
3387
  await rm(configDir, {
3119
3388
  recursive: true,
3120
3389
  force: true
3121
3390
  });
3122
3391
  } catch (err) {
3123
- log$16.error({
3392
+ log$19.error({
3124
3393
  err,
3125
3394
  sessionId
3126
3395
  }, "Could not remove Claude seat SDK config");
@@ -3153,10 +3422,26 @@ function mapUsage(usage) {
3153
3422
  //#endregion
3154
3423
  //#region src/extensions/claude-seat-response.ts
3155
3424
  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;
3425
+ const log$18 = logger.child({ module: "claude-seat-sdk" });
3426
+ /**
3427
+ * Claude sometimes calls a tool by the name it had outside the bridge (Pi's
3428
+ * own name from non-seat history, or a bare MCP tool name). Resolve those when
3429
+ * unambiguous; anything else passes through unbound so Pi's executor returns
3430
+ * its normal not-found error result and the model can recover.
3431
+ */
3432
+ function piToolName({ name, context, sessionId }) {
3433
+ const bindings = toolBindings(context);
3434
+ const exact = bindings.find((binding) => binding.sdkName === name) ?? bindings.find((binding) => binding.definition.name === name);
3435
+ if (exact) return exact.definition.name;
3436
+ const bare = bindings.filter((binding) => binding.toolName === name);
3437
+ const [only] = bare;
3438
+ if (only && bare.length === 1) return only.definition.name;
3439
+ log$18.warn({
3440
+ sessionId,
3441
+ toolName: name,
3442
+ candidates: bare.length
3443
+ }, "Claude requested a tool outside the Pi bridge");
3444
+ return name;
3160
3445
  }
3161
3446
  /** Commit only the accepted SDK attempt: Pi deltas cannot retract retried output. */
3162
3447
  var ModelResponse = class {
@@ -3164,9 +3449,10 @@ var ModelResponse = class {
3164
3449
  pending = [];
3165
3450
  messageId = null;
3166
3451
  stopReason = null;
3167
- constructor(model, context, events) {
3452
+ constructor(model, context, events, sessionId) {
3168
3453
  this.context = context;
3169
3454
  this.events = events;
3455
+ this.sessionId = sessionId;
3170
3456
  this.message = {
3171
3457
  role: "assistant",
3172
3458
  content: [],
@@ -3261,7 +3547,11 @@ var ModelResponse = class {
3261
3547
  block = {
3262
3548
  type: "toolCall",
3263
3549
  id: sdkBlock.id,
3264
- name: piToolName(sdkBlock.name, this.context),
3550
+ name: piToolName({
3551
+ name: sdkBlock.name,
3552
+ context: this.context,
3553
+ sessionId: this.sessionId
3554
+ }),
3265
3555
  arguments: toolInput.parse(sdkBlock.input)
3266
3556
  };
3267
3557
  break;
@@ -3337,7 +3627,7 @@ var ModelResponse = class {
3337
3627
  * each step resumes a private structured snapshot after Pi extensions run.
3338
3628
  * Initially adapted from elidickinson/pi-claude-bridge (MIT).
3339
3629
  */
3340
- const log$15 = logger.child({ module: "claude-seat-sdk" });
3630
+ const log$17 = logger.child({ module: "claude-seat-sdk" });
3341
3631
  const SEAT_SDK_ACTIVITY_EVENT = "claude-seat-sdk:activity";
3342
3632
  /** Session-scoped adapter; only the flagged provider dispatches here. */
3343
3633
  var SeatSdkBridge = class {
@@ -3355,7 +3645,7 @@ var SeatSdkBridge = class {
3355
3645
  }
3356
3646
  stream(model, context, options = {}) {
3357
3647
  const events = createAssistantMessageEventStream();
3358
- const response = new ModelResponse(model, context, events);
3648
+ const response = new ModelResponse(model, context, events, this.deps.sessionId);
3359
3649
  const signal = AbortSignal.any([this.controller.signal, ...options.signal ? [options.signal] : []]);
3360
3650
  (async () => {
3361
3651
  let seatQuery = null;
@@ -3388,7 +3678,7 @@ var SeatSdkBridge = class {
3388
3678
  } else if (message.type === "result") {
3389
3679
  const hasTools = response.hasTools;
3390
3680
  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({
3681
+ log$17.info({
3392
3682
  sessionId: this.deps.sessionId,
3393
3683
  queryUsage: mapUsage(message.usage),
3394
3684
  requestUsage: response.message.usage
@@ -3409,7 +3699,7 @@ var SeatSdkBridge = class {
3409
3699
  }
3410
3700
  } catch (err) {
3411
3701
  const reason = (seatQuery?.controller.signal.aborted || signal.aborted) && !(err instanceof Error && err.name === "TimeoutError") ? "aborted" : "error";
3412
- if (reason === "error") log$15.error({
3702
+ if (reason === "error") log$17.error({
3413
3703
  err,
3414
3704
  sessionId: this.deps.sessionId
3415
3705
  }, "Claude seat SDK response failed");
@@ -3480,7 +3770,7 @@ const HEARTBEAT_THROTTLE_MS = 6e4;
3480
3770
  const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
3481
3771
  const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
3482
3772
  const DAEMON_URL = "http://localhost:38994";
3483
- const log$14 = logger.child({ module: "platform-ext" });
3773
+ const log$16 = logger.child({ module: "platform-ext" });
3484
3774
  function sandboxClient() {
3485
3775
  const apiUrl = apiBaseUrl();
3486
3776
  if (!apiUrl) return null;
@@ -3548,7 +3838,7 @@ async function fetchHarnessFlags() {
3548
3838
  try {
3549
3839
  const res = await client["feature-flags"].$get();
3550
3840
  if (!res.ok) {
3551
- log$14.debug({
3841
+ log$16.debug({
3552
3842
  status: res.status,
3553
3843
  event: "feature_flags_fetch_failed"
3554
3844
  }, "feature-flags fetch failed");
@@ -3560,7 +3850,7 @@ async function fetchHarnessFlags() {
3560
3850
  closingText: body.closingText ?? null
3561
3851
  };
3562
3852
  } catch (err) {
3563
- log$14.debug({
3853
+ log$16.debug({
3564
3854
  err,
3565
3855
  event: "feature_flags_fetch_error"
3566
3856
  }, "feature-flags request errored");
@@ -3571,7 +3861,7 @@ function postHeartbeat({ messageId }) {
3571
3861
  const client = sandboxClient();
3572
3862
  if (!client) return;
3573
3863
  client.heartbeat.$post({ json: { messageId } }).catch((err) => {
3574
- log$14.debug({
3864
+ log$16.debug({
3575
3865
  err,
3576
3866
  event: "heartbeat_failed"
3577
3867
  }, "heartbeat failed");
@@ -3583,7 +3873,7 @@ async function resolveConversationFromApi(messageId) {
3583
3873
  try {
3584
3874
  const res = await client["message-conversation"].$get({ query: { messageId } });
3585
3875
  if (!res.ok) {
3586
- log$14.warn({
3876
+ log$16.warn({
3587
3877
  status: res.status,
3588
3878
  messageId,
3589
3879
  event: "resolve_conversation_failed"
@@ -3592,7 +3882,7 @@ async function resolveConversationFromApi(messageId) {
3592
3882
  }
3593
3883
  return (await res.json()).conversationId ?? null;
3594
3884
  } catch (err) {
3595
- log$14.warn({
3885
+ log$16.warn({
3596
3886
  err,
3597
3887
  messageId,
3598
3888
  event: "resolve_conversation_error"
@@ -3617,13 +3907,13 @@ async function putBackgroundTaskJournalSpec({ messageId, spec }) {
3617
3907
  messageId,
3618
3908
  spec
3619
3909
  } });
3620
- if (!res.ok) log$14.warn({
3910
+ if (!res.ok) log$16.warn({
3621
3911
  status: res.status,
3622
3912
  taskId: spec.id,
3623
3913
  event: "bg_journal_put_failed"
3624
3914
  }, "bg-task journal PUT failed");
3625
3915
  } catch (err) {
3626
- log$14.warn({
3916
+ log$16.warn({
3627
3917
  err,
3628
3918
  taskId: spec.id,
3629
3919
  event: "bg_journal_put_failed"
@@ -3639,7 +3929,7 @@ async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
3639
3929
  taskId
3640
3930
  } });
3641
3931
  } catch (err) {
3642
- log$14.debug({
3932
+ log$16.debug({
3643
3933
  err,
3644
3934
  taskId,
3645
3935
  event: "bg_journal_delete_failed"
@@ -3654,7 +3944,7 @@ async function listBackgroundTaskJournalSpecs({ messageId }) {
3654
3944
  if (!res.ok) return [];
3655
3945
  return (await res.json()).specs ?? [];
3656
3946
  } catch (err) {
3657
- log$14.debug({
3947
+ log$16.debug({
3658
3948
  err,
3659
3949
  event: "bg_journal_list_failed"
3660
3950
  }, "bg-task journal GET failed");
@@ -3668,7 +3958,7 @@ function postBackgroundTasksSnapshot({ messageId, tasks }) {
3668
3958
  messageId,
3669
3959
  tasks
3670
3960
  } }).catch((err) => {
3671
- log$14.debug({
3961
+ log$16.debug({
3672
3962
  err,
3673
3963
  event: "bg_tasks_snapshot_failed"
3674
3964
  }, "bg-tasks snapshot publish failed");
@@ -3766,7 +4056,7 @@ function createToolHeartbeat({ messageId }) {
3766
4056
  }
3767
4057
  heartbeatCount++;
3768
4058
  if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
3769
- log$14.warn({
4059
+ log$16.warn({
3770
4060
  heartbeatCount,
3771
4061
  activeToolCalls: [...activeToolCalls]
3772
4062
  }, "tool heartbeat max reached, stopping");
@@ -3797,7 +4087,7 @@ function postToDaemon(path, body) {
3797
4087
  headers: { "content-type": "application/json" },
3798
4088
  body: JSON.stringify(body)
3799
4089
  }).catch((err) => {
3800
- log$14.debug({
4090
+ log$16.debug({
3801
4091
  err,
3802
4092
  path,
3803
4093
  event: "daemon_post_failed"
@@ -3806,7 +4096,7 @@ function postToDaemon(path, body) {
3806
4096
  }
3807
4097
  function createPlatformExtensions({ sessionId, channelContext }) {
3808
4098
  return (pi) => {
3809
- log$14.info({
4099
+ log$16.info({
3810
4100
  sessionId,
3811
4101
  hasChannelContext: Boolean(channelContext)
3812
4102
  }, "platform extension initialized");
@@ -3860,7 +4150,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
3860
4150
  });
3861
4151
  });
3862
4152
  pi.on("agent_end", () => {
3863
- log$14.info({ sessionId }, "session ending");
4153
+ log$16.info({ sessionId }, "session ending");
3864
4154
  postToDaemon("/session/end", { sessionId });
3865
4155
  });
3866
4156
  };
@@ -3892,6 +4182,14 @@ const toolCallEnvExtension = (pi) => {
3892
4182
  });
3893
4183
  };
3894
4184
  //#endregion
4185
+ //#region src/extensions/oom-neutral-bash.ts
4186
+ const OOM_NEUTRAL_PREFIX = "{ echo 0 > /proc/self/oom_score_adj; } 2>/dev/null\n";
4187
+ /** pi's local bash backend with every command reset to a neutral OOM score. */
4188
+ function createOomNeutralBashOperations({ shellPath }) {
4189
+ const local = createLocalBashOperations({ shellPath });
4190
+ return { exec: (command, cwd, options) => local.exec(`${OOM_NEUTRAL_PREFIX}${command}`, cwd, options) };
4191
+ }
4192
+ //#endregion
3895
4193
  //#region src/extensions/background-tasks.ts
3896
4194
  /**
3897
4195
  * Background bash tasks as a pi extension.
@@ -3996,8 +4294,8 @@ const toolCallEnvExtension = (pi) => {
3996
4294
  * semantics; once promoted, the command inherits background-task lifecycle
3997
4295
  * (its own controller) and the foreground kill timeout no longer applies.
3998
4296
  */
3999
- const log$13 = logger.child({ module: "background-tasks-ext" });
4000
- const ops = createLocalBashOperations();
4297
+ const log$15 = logger.child({ module: "background-tasks-ext" });
4298
+ const ops = createOomNeutralBashOperations({ shellPath: void 0 });
4001
4299
  const STEER_BACKGROUND_DEFAULT_SECONDS = 60;
4002
4300
  const STEER_BACKGROUND_ENV_KEYS = ["BASH_STEER_BACKGROUND_SECONDS", "SKYDIVE_BASH_STEER_BACKGROUND_SECONDS"];
4003
4301
  /**
@@ -4011,7 +4309,7 @@ function steerBackgroundThresholdMs() {
4011
4309
  if (raw === void 0 || raw.trim() === "") continue;
4012
4310
  const parsed = Number(raw);
4013
4311
  if (!Number.isFinite(parsed) || parsed < 0) {
4014
- log$13.warn({
4312
+ log$15.warn({
4015
4313
  envKey: key,
4016
4314
  raw
4017
4315
  }, "invalid BASH_STEER_BACKGROUND_SECONDS, using default");
@@ -4040,7 +4338,7 @@ async function notifyBashSteerArrival(args) {
4040
4338
  try {
4041
4339
  await listener();
4042
4340
  } catch (err) {
4043
- log$13.error({
4341
+ log$15.error({
4044
4342
  err,
4045
4343
  sessionId: args.sessionId
4046
4344
  }, "bash steer promotion failed");
@@ -4135,14 +4433,14 @@ function watchdogTick(now) {
4135
4433
  const overSize = meta.logBytes > MAX_LOG_BYTES;
4136
4434
  if (!overRuntime && !overSize) continue;
4137
4435
  const reason = overSize ? `output exceeded ${MAX_LOG_BYTES / (1024 * 1024)}MiB` : `exceeded ${KEEPALIVE_MAX_MS / 6e4}m max runtime`;
4138
- log$13.warn({
4436
+ log$15.warn({
4139
4437
  taskId: meta.id,
4140
4438
  reason
4141
4439
  }, "watchdog killing bg task");
4142
4440
  try {
4143
4441
  killTask(meta, reason);
4144
4442
  } catch (err) {
4145
- log$13.warn({
4443
+ log$15.warn({
4146
4444
  err,
4147
4445
  taskId: meta.id
4148
4446
  }, "watchdog kill failed");
@@ -4201,7 +4499,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4201
4499
  const now = Date.now();
4202
4500
  const promotable = [...foregroundBash.values()].filter((call) => now - call.startedAt >= thresholdMs);
4203
4501
  if (promotable.length === 0) return;
4204
- log$13.info({
4502
+ log$15.info({
4205
4503
  event: "bash_steer_promotion",
4206
4504
  count: promotable.length,
4207
4505
  thresholdSeconds: Math.round(thresholdMs / 1e3),
@@ -4226,7 +4524,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4226
4524
  try {
4227
4525
  await mkdir(tasksDir(), { recursive: true });
4228
4526
  } catch (err) {
4229
- log$13.error({ err }, "bg task adopt: mkdir failed");
4527
+ log$15.error({ err }, "bg task adopt: mkdir failed");
4230
4528
  }
4231
4529
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4232
4530
  logStream.on("error", () => {});
@@ -4253,7 +4551,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4253
4551
  tasks.set(id, meta);
4254
4552
  ensureWatchdog();
4255
4553
  schedulePublishSnapshot();
4256
- log$13.info({
4554
+ log$15.info({
4257
4555
  taskId: id,
4258
4556
  conversationId,
4259
4557
  startedAt: args.startedAt
@@ -4276,7 +4574,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4276
4574
  * handling, timeout kill, and abort semantics.
4277
4575
  */
4278
4576
  function createSteerAwareOperations(base) {
4279
- const localOps = createLocalBashOperations({ shellPath: base.shellPath });
4577
+ const localOps = createOomNeutralBashOperations({ shellPath: base.shellPath });
4280
4578
  return { async exec(command, cwd, execOptions) {
4281
4579
  const thresholdMs = steerBackgroundThresholdMs();
4282
4580
  const toolOnData = execOptions?.onData;
@@ -4406,7 +4704,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4406
4704
  try {
4407
4705
  shellPath = SettingsManager.create(ctx.cwd, getAgentDir()).getShellPath();
4408
4706
  } catch (err) {
4409
- log$13.warn({
4707
+ log$15.warn({
4410
4708
  err,
4411
4709
  cwd: ctx.cwd
4412
4710
  }, "bash steer promotion: shell settings unavailable, using default shell");
@@ -4421,7 +4719,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4421
4719
  ...definition,
4422
4720
  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
4721
  });
4424
- log$13.info({
4722
+ log$15.info({
4425
4723
  event: "bash_steer_promotion_enabled",
4426
4724
  thresholdSeconds: Math.round(thresholdMs / 1e3)
4427
4725
  }, "supervised bash tool registered (steer-triggered backgrounding)");
@@ -4464,7 +4762,7 @@ or if you were explicitly waiting to report it.`,
4464
4762
  triggerTurn: true,
4465
4763
  deliverAs: "followUp"
4466
4764
  });
4467
- log$13.info({
4765
+ log$15.info({
4468
4766
  taskId: meta.id,
4469
4767
  conversationId
4470
4768
  }, "bg task completion delivered live (followUp)");
@@ -4472,7 +4770,7 @@ or if you were explicitly waiting to report it.`,
4472
4770
  }
4473
4771
  if (meta.messageId) {
4474
4772
  meta.notified = true;
4475
- log$13.info({
4773
+ log$15.info({
4476
4774
  taskId: meta.id,
4477
4775
  messageId: meta.messageId
4478
4776
  }, "posting idle bg-task-done wake");
@@ -4482,12 +4780,12 @@ or if you were explicitly waiting to report it.`,
4482
4780
  content: message.content
4483
4781
  }).catch((err) => {
4484
4782
  meta.notified = false;
4485
- log$13.warn({
4783
+ log$15.warn({
4486
4784
  err,
4487
4785
  taskId: meta.id
4488
4786
  }, "bg-task-done wake failed; will retry at next session_start");
4489
4787
  });
4490
- } else log$13.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
4788
+ } else log$15.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
4491
4789
  }
4492
4790
  const SNAPSHOT_TAIL_LINES = 40;
4493
4791
  let lastPublishedSignature = null;
@@ -4524,7 +4822,7 @@ or if you were explicitly waiting to report it.`,
4524
4822
  tasks: snapshot
4525
4823
  });
4526
4824
  } catch (err) {
4527
- log$13.debug({
4825
+ log$15.debug({
4528
4826
  err,
4529
4827
  event: "bg_tasks_snapshot_build_failed"
4530
4828
  }, "building bg-tasks snapshot failed");
@@ -4567,7 +4865,7 @@ or if you were explicitly waiting to report it.`,
4567
4865
  logStream.end();
4568
4866
  await finished(logStream).catch(() => {});
4569
4867
  meta.running = false;
4570
- log$13.info({
4868
+ log$15.info({
4571
4869
  taskId: meta.id,
4572
4870
  exitCode: meta.exitCode
4573
4871
  }, "bg task finished");
@@ -4584,14 +4882,14 @@ or if you were explicitly waiting to report it.`,
4584
4882
  try {
4585
4883
  await mkdir(tasksDir(), { recursive: true });
4586
4884
  } catch (err) {
4587
- log$13.error({
4885
+ log$15.error({
4588
4886
  err,
4589
4887
  taskId: id
4590
4888
  }, "background task dir unavailable");
4591
4889
  }
4592
4890
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4593
4891
  logStream.on("error", (err) => {
4594
- log$13.warn({
4892
+ log$15.warn({
4595
4893
  err,
4596
4894
  taskId: id
4597
4895
  }, "bg task log write failed");
@@ -4641,7 +4939,7 @@ or if you were explicitly waiting to report it.`,
4641
4939
  }).catch((err) => {
4642
4940
  if (!meta.controller.signal.aborted) {
4643
4941
  meta.error = err instanceof Error ? err.message : String(err);
4644
- log$13.warn({
4942
+ log$15.warn({
4645
4943
  err,
4646
4944
  taskId: id
4647
4945
  }, "bg task exec error");
@@ -4650,7 +4948,7 @@ or if you were explicitly waiting to report it.`,
4650
4948
  await finishTask(meta, logStream);
4651
4949
  });
4652
4950
  ensureWatchdog();
4653
- log$13.info({
4951
+ log$15.info({
4654
4952
  taskId: id,
4655
4953
  conversationId
4656
4954
  }, "bg task started");
@@ -4669,7 +4967,7 @@ or if you were explicitly waiting to report it.`,
4669
4967
  for (const spec of specs) {
4670
4968
  const live = tasks.get(spec.id);
4671
4969
  if (live && sameScope(live, scopeKey())) continue;
4672
- log$13.info({
4970
+ log$15.info({
4673
4971
  taskId: spec.id,
4674
4972
  conversationId
4675
4973
  }, "relaunching journaled resumable bg task after restart");
@@ -4687,7 +4985,7 @@ or if you were explicitly waiting to report it.`,
4687
4985
  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
4986
  stream.end();
4689
4987
  } catch (err) {
4690
- log$13.debug({
4988
+ log$15.debug({
4691
4989
  err,
4692
4990
  taskId: meta.id
4693
4991
  }, "resume banner write failed");
@@ -4707,7 +5005,7 @@ or if you were explicitly waiting to report it.`,
4707
5005
  meta.notified = true;
4708
5006
  pi.sendMessage(await taskDoneMessage(meta));
4709
5007
  }
4710
- if (unnotified.length > 0) log$13.info({
5008
+ if (unnotified.length > 0) log$15.info({
4711
5009
  conversationId,
4712
5010
  count: unnotified.length
4713
5011
  }, "injected completed bg tasks at session_start");
@@ -4902,7 +5200,7 @@ or if you were explicitly waiting to report it.`,
4902
5200
  * read on the hot path before every LLM call), it falls back to the default
4903
5201
  * for that knob and logs once.
4904
5202
  */
4905
- const log$12 = logger.child({ module: "context-management-config" });
5203
+ const log$14 = logger.child({ module: "context-management-config" });
4906
5204
  const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
4907
5205
  enabled: false,
4908
5206
  perResultMaxBytes: 16 * 1024,
@@ -4947,7 +5245,7 @@ function resolveContextManagementConfig(env = process.env) {
4947
5245
  clearAtLeastTokens: env.SKYDIVE_CTX_CLEAR_AT_LEAST_TOKENS
4948
5246
  });
4949
5247
  if (!parsed.success) {
4950
- log$12.warn({
5248
+ log$14.warn({
4951
5249
  event: "context_management_config_invalid",
4952
5250
  err: parsed.error
4953
5251
  }, "falling back to default context-management config");
@@ -5031,7 +5329,7 @@ function hasFlagSource(env = process.env) {
5031
5329
  * alive and an indeterminate result (no api url / transient failure) leaves the
5032
5330
  * last-known values untouched so a blip can't silently flip behavior.
5033
5331
  */
5034
- const log$11 = logger.child({ module: "feature-flags-poll" });
5332
+ const log$13 = logger.child({ module: "feature-flags-poll" });
5035
5333
  const FLAG_POLL_INTERVAL_MS = 6e4;
5036
5334
  let contextManagement = null;
5037
5335
  let closingText = null;
@@ -5071,7 +5369,7 @@ function apply(name, next) {
5071
5369
  if (next !== prev) for (const cb of subscribers[name]) try {
5072
5370
  cb(next);
5073
5371
  } catch (err) {
5074
- log$11.warn({
5372
+ log$13.warn({
5075
5373
  err,
5076
5374
  flag: name
5077
5375
  }, "flag subscriber threw");
@@ -5084,7 +5382,7 @@ async function pollOnce() {
5084
5382
  apply("contextManagement", flags.contextManagement ?? null);
5085
5383
  apply("closingText", flags.closingText ?? null);
5086
5384
  } catch (err) {
5087
- log$11.debug({ err }, "feature-flag poll threw");
5385
+ log$13.debug({ err }, "feature-flag poll threw");
5088
5386
  }
5089
5387
  }
5090
5388
  /**
@@ -5285,8 +5583,8 @@ const bashDefaultTimeoutExtension = (pi) => {
5285
5583
  * stat and the extension warns on what it can see — it must never break a
5286
5584
  * turn over an observability feature.
5287
5585
  */
5288
- const execFileAsync = promisify(execFile);
5289
- const log$10 = logger.child({ module: "resource-pressure-warning" });
5586
+ const execFileAsync$1 = promisify(execFile);
5587
+ const log$12 = logger.child({ module: "resource-pressure-warning" });
5290
5588
  const POLL_INTERVAL_MS = 1e4;
5291
5589
  function envOverride(name) {
5292
5590
  for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
@@ -5354,7 +5652,7 @@ async function readMemUsePct() {
5354
5652
  */
5355
5653
  async function readDiskUsePct() {
5356
5654
  try {
5357
- const { stdout } = await execFileAsync("df", ["-P", diskRoot()]);
5655
+ const { stdout } = await execFileAsync$1("df", ["-P", diskRoot()]);
5358
5656
  const dataRow = stdout.trim().split("\n")[1];
5359
5657
  if (dataRow == null) return null;
5360
5658
  const capacity = dataRow.trim().split(/\s+/)[4];
@@ -5483,7 +5781,7 @@ const resourcePressureWarningExtension = (pi) => {
5483
5781
  warnedDiskThisTurn = true;
5484
5782
  }
5485
5783
  if (trigger === null) return;
5486
- log$10.warn({
5784
+ log$12.warn({
5487
5785
  trigger,
5488
5786
  mem,
5489
5787
  cpuPct,
@@ -5521,7 +5819,7 @@ const resourcePressureWarningExtension = (pi) => {
5521
5819
  if (!timer) {
5522
5820
  timer = setInterval(() => {
5523
5821
  checkOnce().catch((err) => {
5524
- log$10.error({ err }, "resource pressure check failed");
5822
+ log$12.error({ err }, "resource pressure check failed");
5525
5823
  });
5526
5824
  }, POLL_INTERVAL_MS);
5527
5825
  timer.unref?.();
@@ -5537,7 +5835,7 @@ const resourcePressureWarningExtension = (pi) => {
5537
5835
  };
5538
5836
  //#endregion
5539
5837
  //#region src/extensions/disk-guard.ts
5540
- const log$9 = logger.child({ module: "disk-guard" });
5838
+ const log$11 = logger.child({ module: "disk-guard" });
5541
5839
  /**
5542
5840
  * In-band bypass. The guard is a safety net, not a jail: when the agent knows
5543
5841
  * a flagged command is genuinely safe (writing to a different mount, a tiny
@@ -5559,7 +5857,7 @@ const BYPASS_HINT$2 = "# disk-guard: allow";
5559
5857
  * first; the SKYDIVE_/ANYONE_ prefixes are accepted too for consistency with
5560
5858
  * the other env overrides. Empty/unset/"0"/"false" leave the guard on.
5561
5859
  */
5562
- function guardDisabledByEnv$2() {
5860
+ function guardDisabledByEnv$3() {
5563
5861
  for (const name of [
5564
5862
  "DISK_GUARD_DISABLE",
5565
5863
  "SKYDIVE_DISK_GUARD_DISABLE",
@@ -5670,14 +5968,14 @@ function diskBlockReason(command, diskPct) {
5670
5968
  const diskGuardExtension = (pi) => {
5671
5969
  pi.on("tool_call", async (event) => {
5672
5970
  if (event.toolName !== "bash") return;
5673
- if (guardDisabledByEnv$2()) return;
5971
+ if (guardDisabledByEnv$3()) return;
5674
5972
  const command = event.input.command;
5675
5973
  if (typeof command !== "string" || command.length === 0) return;
5676
5974
  if (hasBypassMarker$2(command)) return;
5677
5975
  if (!isSpaceHungryCommand(command)) return;
5678
5976
  const diskPct = await readDiskUsePct();
5679
5977
  if (!shouldBlockForDisk(command, diskPct)) return;
5680
- log$9.warn({
5978
+ log$11.warn({
5681
5979
  diskPct,
5682
5980
  command: command.slice(0, 200)
5683
5981
  }, "blocked space-hungry bash command on near-full disk");
@@ -5689,7 +5987,7 @@ const diskGuardExtension = (pi) => {
5689
5987
  };
5690
5988
  //#endregion
5691
5989
  //#region src/extensions/noop-loop-guard.ts
5692
- const log$8 = logger.child({ module: "noop-loop-guard" });
5990
+ const log$10 = logger.child({ module: "noop-loop-guard" });
5693
5991
  /** Length of the rolling window that counts silence commands across streak resets. */
5694
5992
  const SILENCE_WINDOW_MS = 300 * 1e3;
5695
5993
  /** Bare shell no-op: `true` or `:` (case-insensitive). */
@@ -5705,9 +6003,9 @@ const ECHO_ARG_MAX_LEN = 64;
5705
6003
  /** Marker that forces a single command through the guard. */
5706
6004
  const BYPASS_HINT$1 = "noop-guard: allow";
5707
6005
  /** 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) => {
6006
+ const KILL_SWITCH_KEYS$1 = ["NOOP_LOOP_GUARD_DISABLE", "SKYDIVE_NOOP_LOOP_GUARD_DISABLE"];
6007
+ function guardDisabledByEnv$2() {
6008
+ return KILL_SWITCH_KEYS$1.some((key) => {
5711
6009
  const value = process.env[key];
5712
6010
  return value !== void 0 && value !== "" && value !== "0";
5713
6011
  });
@@ -5831,17 +6129,20 @@ const noopLoopGuardExtension = (pi) => {
5831
6129
  };
5832
6130
  pi.on("tool_call", async (event, ctx) => {
5833
6131
  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;
6132
+ if (guardDisabledByEnv$2()) return;
6133
+ const rawCommand = event.input.command;
6134
+ if (typeof rawCommand !== "string" || rawCommand.length === 0) return;
6135
+ const command = stripPlatformExportsForDisplay(rawCommand);
5837
6136
  const now = Date.now();
5838
- const bypassed = isSilenceCommand(command) && hasBypassMarker$1(command);
6137
+ const silence = isSilenceCommand(command);
6138
+ const bypassed = silence && hasBypassMarker$1(command);
5839
6139
  const streak = recordNoopCommand(state, command, now);
6140
+ if (!silence) return;
5840
6141
  const windowCount = countSilenceInWindow(state, now);
5841
6142
  if (bypassed) return;
5842
6143
  if (streak < 3 && windowCount < 8) return;
5843
6144
  const aborted = streak >= 25 || windowCount >= 40;
5844
- log$8.warn({
6145
+ log$10.warn({
5845
6146
  streak,
5846
6147
  windowCount,
5847
6148
  aborted,
@@ -5859,6 +6160,70 @@ const noopLoopGuardExtension = (pi) => {
5859
6160
  });
5860
6161
  };
5861
6162
  //#endregion
6163
+ //#region src/extensions/repeat-call-guard.ts
6164
+ const log$9 = logger.child({ module: "repeat-call-guard" });
6165
+ const KILL_SWITCH_KEYS = ["REPEAT_CALL_GUARD_DISABLE", "SKYDIVE_REPEAT_CALL_GUARD_DISABLE"];
6166
+ function guardDisabledByEnv$1() {
6167
+ return KILL_SWITCH_KEYS.some((key) => {
6168
+ const value = process.env[key];
6169
+ return value !== void 0 && value !== "" && value !== "0";
6170
+ });
6171
+ }
6172
+ /**
6173
+ * Identity of a tool call for repeat detection: tool name plus arguments,
6174
+ * minus the fields the platform adds per call.
6175
+ */
6176
+ function toolCallKey({ toolName, input }) {
6177
+ const normalized = {};
6178
+ for (const [key, value] of Object.entries(input)) {
6179
+ if (TOOL_CALL_SUMMARY_FIELDS.includes(key)) continue;
6180
+ normalized[key] = key === "command" && typeof value === "string" ? stripPlatformExportsForDisplay(value) : value;
6181
+ }
6182
+ return `${toolName}\u0000${JSON.stringify(normalized)}`;
6183
+ }
6184
+ /** Count one call against the streak; returns the new streak length. */
6185
+ function recordToolCall(state, key) {
6186
+ state.streak = key === state.lastKey ? state.streak + 1 : 1;
6187
+ state.lastKey = key;
6188
+ return state.streak;
6189
+ }
6190
+ function repeatBlockReason({ toolName, streak, aborted }) {
6191
+ 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.`;
6192
+ if (aborted) return `${head} The harness is now stopping this run.`;
6193
+ const remaining = 40 - streak;
6194
+ return `${head} ${remaining} more identical call${remaining === 1 ? "" : "s"} and the harness stops the run.`;
6195
+ }
6196
+ const repeatCallGuardExtension = (pi) => {
6197
+ const state = {
6198
+ lastKey: null,
6199
+ streak: 0
6200
+ };
6201
+ pi.on("tool_call", async (event, ctx) => {
6202
+ if (guardDisabledByEnv$1()) return;
6203
+ const streak = recordToolCall(state, toolCallKey({
6204
+ toolName: event.toolName,
6205
+ input: event.input
6206
+ }));
6207
+ if (streak < 20) return;
6208
+ const aborted = streak >= 40;
6209
+ log$9.warn({
6210
+ toolName: event.toolName,
6211
+ streak,
6212
+ aborted,
6213
+ toolCallId: event.toolCallId
6214
+ }, "repeat-call guard fired");
6215
+ if (aborted) ctx.abort();
6216
+ return {
6217
+ block: true,
6218
+ reason: repeatBlockReason({
6219
+ toolName: event.toolName,
6220
+ streak,
6221
+ aborted
6222
+ })
6223
+ };
6224
+ });
6225
+ };
6226
+ //#endregion
5862
6227
  //#region src/extensions/sleep-guard.ts
5863
6228
  /**
5864
6229
  * Foreground sleep guard: block `sleep` commands that hold the turn open.
@@ -5908,7 +6273,7 @@ const noopLoopGuardExtension = (pi) => {
5908
6273
  * embedding a script).
5909
6274
  */
5910
6275
  const execFileP = promisify(execFile);
5911
- const log$7 = logger.child({ module: "sleep-guard" });
6276
+ const log$8 = logger.child({ module: "sleep-guard" });
5912
6277
  /** How long the `platform automation create` call may take before we fall back to guidance. */
5913
6278
  const SCHEDULE_TIMEOUT_MS = 15e3;
5914
6279
  /** Title for the one-shot wakes this guard schedules. Visible in the Routines UI. */
@@ -6152,7 +6517,7 @@ async function scheduleSleepWake(seconds, ledger) {
6152
6517
  ], { timeout: SCHEDULE_TIMEOUT_MS });
6153
6518
  return at;
6154
6519
  } catch (err) {
6155
- log$7.warn({ err }, "failed to auto-schedule sleep wake; falling back to guidance");
6520
+ log$8.warn({ err }, "failed to auto-schedule sleep wake; falling back to guidance");
6156
6521
  return null;
6157
6522
  }
6158
6523
  }
@@ -6173,7 +6538,7 @@ const sleepGuardExtension = (pi) => {
6173
6538
  if (typeof command !== "string" || command.length === 0) return;
6174
6539
  const violation = shouldBlockForSleep(command);
6175
6540
  if (!violation) return;
6176
- log$7.warn({
6541
+ log$8.warn({
6177
6542
  seconds: violation.seconds,
6178
6543
  leading: violation.leading,
6179
6544
  unboundedLoop: violation.unboundedLoop,
@@ -6182,7 +6547,7 @@ const sleepGuardExtension = (pi) => {
6182
6547
  if (!violation.unboundedLoop && violation.seconds <= 86400 && isPureSleepCommand(blankQuotedRegions(command))) {
6183
6548
  const at = await scheduleSleepWake(violation.seconds, wakeLedger);
6184
6549
  if (at) {
6185
- log$7.info({
6550
+ log$8.info({
6186
6551
  at,
6187
6552
  seconds: violation.seconds
6188
6553
  }, "auto-scheduled sleep wake");
@@ -6290,7 +6655,7 @@ function transformContextMessages(messages, config, now) {
6290
6655
  }
6291
6656
  //#endregion
6292
6657
  //#region src/extensions/context-management.ts
6293
- const log$6 = logger.child({ module: "context-management-extension" });
6658
+ const log$7 = logger.child({ module: "context-management-extension" });
6294
6659
  function isAnthropicMessagesPayload(payload) {
6295
6660
  if (typeof payload !== "object" || payload === null) return false;
6296
6661
  const candidate = payload;
@@ -6355,13 +6720,13 @@ function createContextManagementExtension() {
6355
6720
  setContextManagementFlagOverride(getPolledFlag("contextManagement"));
6356
6721
  onFlagChange("contextManagement", (enabled) => {
6357
6722
  setContextManagementFlagOverride(enabled);
6358
- log$6.info({
6723
+ log$7.info({
6359
6724
  event: "context_management_flag_update",
6360
6725
  enabled
6361
6726
  }, "context-management flag updated from platform");
6362
6727
  });
6363
6728
  startFeatureFlagPoller();
6364
- log$6.info({
6729
+ log$7.info({
6365
6730
  event: "context_management_registered",
6366
6731
  enabled: initial.enabled,
6367
6732
  flagSource: hasFlagSource(),
@@ -6373,13 +6738,13 @@ function createContextManagementExtension() {
6373
6738
  const { messages } = event;
6374
6739
  try {
6375
6740
  const result = transformContextIfEnabled(messages, getContextManagementConfig(), Date.now());
6376
- if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$6.info({
6741
+ if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$7.info({
6377
6742
  event: "context_management_applied",
6378
6743
  ...result.stats
6379
6744
  }, "trimmed/cleared tool output before LLM call");
6380
6745
  return { messages: result.messages };
6381
6746
  } catch (err) {
6382
- log$6.error({
6747
+ log$7.error({
6383
6748
  err,
6384
6749
  event: "context_management_transform_failed"
6385
6750
  }, "context transform failed; passing messages through unchanged");
@@ -6391,7 +6756,7 @@ function createContextManagementExtension() {
6391
6756
  }
6392
6757
  //#endregion
6393
6758
  //#region src/extensions/current-time.ts
6394
- const log$5 = logger.child({ module: "current-time-extension" });
6759
+ const log$6 = logger.child({ module: "current-time-extension" });
6395
6760
  const PI_DATE_LINE = /^Current date:.*$/m;
6396
6761
  function formatCurrentTimeLine(now) {
6397
6762
  return `Current date: ${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")} (${new Intl.DateTimeFormat("en-US", {
@@ -6404,7 +6769,7 @@ const currentTimeExtension = (pi) => {
6404
6769
  const line = formatCurrentTimeLine(/* @__PURE__ */ new Date());
6405
6770
  const base = event.systemPrompt;
6406
6771
  if (PI_DATE_LINE.test(base)) {
6407
- log$5.info({ event: "pi_date_line_present" }, "pi base prompt carries its own 'Current date:' line again; replacing it in place (pi prompt format may have changed)");
6772
+ log$6.info({ event: "pi_date_line_present" }, "pi base prompt carries its own 'Current date:' line again; replacing it in place (pi prompt format may have changed)");
6408
6773
  return { systemPrompt: base.replace(PI_DATE_LINE, line) };
6409
6774
  }
6410
6775
  return { systemPrompt: `${base}\n${line}` };
@@ -6792,7 +7157,7 @@ async function migrateMemory({ cwd }) {
6792
7157
  }
6793
7158
  //#endregion
6794
7159
  //#region src/extensions/memory.ts
6795
- const log$4 = logger.child({ module: "memory-extension" });
7160
+ const log$5 = logger.child({ module: "memory-extension" });
6796
7161
  /**
6797
7162
  * The standing instructions for the memory system. Always injected (even with
6798
7163
  * no `MEMORY.md`) so the agent knows it can persist notes and how. `users/` is
@@ -6829,13 +7194,13 @@ const memoryExtension = (pi) => {
6829
7194
  pi.on("session_start", async (_event, ctx) => {
6830
7195
  try {
6831
7196
  const migrated = await migrateMemory({ cwd: ctx.cwd });
6832
- if (migrated !== null) log$4.info({
7197
+ if (migrated !== null) log$5.info({
6833
7198
  event: "memory_migrated",
6834
7199
  from: migrated.from,
6835
7200
  to: migrated.to
6836
7201
  }, "migrated memory layout to current version");
6837
7202
  } catch (err) {
6838
- log$4.warn({
7203
+ log$5.warn({
6839
7204
  err,
6840
7205
  event: "memory_migration_failed"
6841
7206
  }, "memory migration failed; continuing with existing index");
@@ -6847,7 +7212,7 @@ const memoryExtension = (pi) => {
6847
7212
  index
6848
7213
  });
6849
7214
  } catch (err) {
6850
- log$4.warn({
7215
+ log$5.warn({
6851
7216
  err,
6852
7217
  event: "memory_index_failed"
6853
7218
  }, "memory index read failed; injecting instructions only");
@@ -6861,7 +7226,7 @@ const memoryExtension = (pi) => {
6861
7226
  };
6862
7227
  //#endregion
6863
7228
  //#region src/extensions/platform-memory.ts
6864
- const log$3 = logger.child({ module: "platform-memory-extension" });
7229
+ const log$4 = logger.child({ module: "platform-memory-extension" });
6865
7230
  /**
6866
7231
  * Resolve the human on this turn via the API, keyed by the message id.
6867
7232
  * `/sandbox/channel-context` only returns a sender for a platform-known
@@ -6874,13 +7239,13 @@ const log$3 = logger.child({ module: "platform-memory-extension" });
6874
7239
  async function resolveTurnUser(messageId) {
6875
7240
  const client = sandboxClient();
6876
7241
  if (!client) {
6877
- log$3.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
7242
+ log$4.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
6878
7243
  return null;
6879
7244
  }
6880
7245
  try {
6881
7246
  const res = await client["channel-context"].$get({ query: { messageId } });
6882
7247
  if (!res.ok) {
6883
- log$3.warn({
7248
+ log$4.warn({
6884
7249
  event: "resolve_turn_user_failed",
6885
7250
  status: res.status
6886
7251
  }, "channel-context returned non-ok; withholding user memory");
@@ -6893,7 +7258,7 @@ async function resolveTurnUser(messageId) {
6893
7258
  displayName: sender.displayName
6894
7259
  };
6895
7260
  } catch (err) {
6896
- log$3.warn({
7261
+ log$4.warn({
6897
7262
  err,
6898
7263
  event: "resolve_turn_user_failed"
6899
7264
  }, "failed to resolve current user; withholding user memory");
@@ -6940,7 +7305,7 @@ function createPlatformMemoryExtension({ channelContext }) {
6940
7305
  user
6941
7306
  });
6942
7307
  } catch (err) {
6943
- log$3.warn({
7308
+ log$4.warn({
6944
7309
  err,
6945
7310
  event: "user_memory_index_failed"
6946
7311
  }, "user memory index build failed; skipping injection");
@@ -6972,7 +7337,7 @@ const providerApiCompatExtension = (pi) => {
6972
7337
  };
6973
7338
  //#endregion
6974
7339
  //#region src/extensions/self-trace.ts
6975
- const log$2 = logger.child({ module: "self-trace-extension" });
7340
+ const log$3 = logger.child({ module: "self-trace-extension" });
6976
7341
  /**
6977
7342
  * Reports the agent's own execution as OpenTelemetry spans:
6978
7343
  * agent.session → agent.run → agent.turn.N → tool.NAME, with token/cost
@@ -6997,7 +7362,7 @@ const selfTraceExtension = (pi) => {
6997
7362
  sessionSpan = tracer.startSpan("agent.session", { attributes: { "agent.model": modelId } }, remoteCtx);
6998
7363
  sessionCtx = trace.setSpan(remoteCtx, sessionSpan);
6999
7364
  const sc = sessionSpan.spanContext();
7000
- log$2.info({
7365
+ log$3.info({
7001
7366
  event: "self_trace_session_start",
7002
7367
  trace_id: sc.traceId,
7003
7368
  span_id: sc.spanId,
@@ -7109,13 +7474,13 @@ const selfTraceExtension = (pi) => {
7109
7474
  * Lives in the harness package — soul.md is content from the agent's
7110
7475
  * own git repo, not from the platform — so its handling stays here.
7111
7476
  */
7112
- const log$1 = logger.child({ module: "soul-extension" });
7477
+ const log$2 = logger.child({ module: "soul-extension" });
7113
7478
  async function readSoul(cwd) {
7114
7479
  try {
7115
7480
  return (await readFile(join(cwd, "soul.md"), "utf8")).trim() || null;
7116
7481
  } catch (err) {
7117
7482
  if (err?.code === "ENOENT") return null;
7118
- log$1.warn({
7483
+ log$2.warn({
7119
7484
  err,
7120
7485
  event: "soul_read_failed"
7121
7486
  }, "soul.md read failed");
@@ -7147,7 +7512,7 @@ const soulExtension = (pi) => {
7147
7512
  };
7148
7513
  //#endregion
7149
7514
  //#region src/extensions/subagent/index.ts
7150
- const log = logger.child({ module: "subagent-ext" });
7515
+ const log$1 = logger.child({ module: "subagent-ext" });
7151
7516
  const MAX_TASKS = 8;
7152
7517
  const SpawnTaskItem = Type.Object({
7153
7518
  task: Type.String({ description: "The task to delegate to a subagent run." }),
@@ -7247,7 +7612,7 @@ function buildTool(messageId) {
7247
7612
  };
7248
7613
  } catch (err) {
7249
7614
  const message = err instanceof Error ? err.message : String(err);
7250
- log.warn({
7615
+ log$1.warn({
7251
7616
  err,
7252
7617
  event: "subagent_rearm_failed",
7253
7618
  taskId: task.taskId
@@ -7260,7 +7625,7 @@ function buildTool(messageId) {
7260
7625
  }
7261
7626
  }));
7262
7627
  const { taskIds } = spawned;
7263
- log.info({
7628
+ log$1.info({
7264
7629
  event: "subagent_spawned",
7265
7630
  count: taskIds.length
7266
7631
  }, "subagent tasks queued");
@@ -7291,7 +7656,7 @@ function buildTool(messageId) {
7291
7656
  };
7292
7657
  } catch (err) {
7293
7658
  const message = err instanceof Error ? err.message : String(err);
7294
- log.warn({
7659
+ log$1.warn({
7295
7660
  err,
7296
7661
  event: "subagent_spawn_failed"
7297
7662
  }, "subagent request failed");
@@ -7322,7 +7687,7 @@ function createSubagentExtension({ channelContext }) {
7322
7687
  if (registered) return;
7323
7688
  registered = true;
7324
7689
  pi.registerTool(buildTool(messageId));
7325
- log.info({ event: "subagent_enabled" }, "subagent tool registered");
7690
+ log$1.info({ event: "subagent_enabled" }, "subagent tool registered");
7326
7691
  };
7327
7692
  pi.on("session_start", () => {
7328
7693
  registerOnce();
@@ -7330,6 +7695,125 @@ function createSubagentExtension({ channelContext }) {
7330
7695
  };
7331
7696
  }
7332
7697
  //#endregion
7698
+ //#region src/extensions/template-build-push.ts
7699
+ /**
7700
+ * Same-turn notice that a push started a template build.
7701
+ *
7702
+ * An agent's `Dockerfile` / `install.sh` / lockfiles are BAKED: changing one
7703
+ * does not take effect when the file is written, nor when it is pushed, but
7704
+ * when a template build of that commit succeeds — minutes later, out of band,
7705
+ * with no result delivered anywhere the agent looks. So an agent edits its
7706
+ * Dockerfile, pushes, sees a clean `git push`, and reasonably concludes it is
7707
+ * done. If that build fails, it will go on answering from the last image that
7708
+ * built, and every later commit fails the same way.
7709
+ *
7710
+ * This closes the gap at the only moment the agent still has full context for
7711
+ * why it touched those files: the push itself. The notice appends one line to
7712
+ * the push's own tool result pointing at `platform builds wait`. It does not
7713
+ * block, does not wait for the build, and adds no request — it is a string
7714
+ * append onto a result that has already returned.
7715
+ *
7716
+ * Deliberately narrow: only a push whose diff touches a baked path says
7717
+ * anything. A push of ordinary code is not waiting on a build and must stay
7718
+ * silent, or the line becomes background noise that gets skimmed past.
7719
+ *
7720
+ * Best-effort throughout. Any failure to read the range or the diff leaves
7721
+ * the tool result exactly as it was — this is a hint, and a hint must never
7722
+ * be able to break a push.
7723
+ */
7724
+ const execFileAsync = promisify(execFile);
7725
+ const log = logger.child({ module: "template-build-push" });
7726
+ /**
7727
+ * Repo paths whose contents are baked into the template image.
7728
+ *
7729
+ * MUST stay identical to `BAKED_BUILD_PATHS` in
7730
+ * `apps/anyone/agent-lifecycle/src/agentPush.ts`, which is what the server
7731
+ * actually classifies pushes with. It is duplicated rather than imported
7732
+ * because the harness carries zero `@createinc/*` dependencies; the pair is
7733
+ * pinned by `template-build-push.contract.test.ts`, the same arrangement the
7734
+ * untrusted fence uses.
7735
+ */
7736
+ const BAKED_BUILD_PATHS = new Set([
7737
+ "Dockerfile",
7738
+ "install.sh",
7739
+ "package.json",
7740
+ "package-lock.json",
7741
+ ".npmrc",
7742
+ "yarn.lock",
7743
+ ".yarnrc.yml",
7744
+ ".yarnrc",
7745
+ "bun.lock",
7746
+ "bun.lockb",
7747
+ ".bunfig.toml",
7748
+ "pnpm-lock.yaml"
7749
+ ]);
7750
+ const BUILD_STARTED_NOTICE = "Note: this push changed a file that is baked into your computer image (Dockerfile / install.sh / a lockfile), so it started a template build. The change is NOT live here until that build succeeds — a failed build leaves you running the previous image, silently. Run `platform builds wait` to confirm it built before you rely on anything the change added, or treat it as unfinished work and check back with `platform builds show`.";
7751
+ /** True for a bash command that is (or contains) a `git push`. */
7752
+ function isGitPush(command) {
7753
+ return /(^|[\s;&|(])git\s+(?:\S+\s+)*?push(\s|$)/.test(command);
7754
+ }
7755
+ /**
7756
+ * The commit range a push reported, parsed from git's own output.
7757
+ *
7758
+ * git writes the range on the ref line of a successful push
7759
+ * (` abc1234..def5678 main -> main`). Reading it back is what lets the
7760
+ * diff be scoped to exactly what was pushed, with no guessing about upstream
7761
+ * tracking state. A new branch (`* [new branch]`) reports no range, which is
7762
+ * why {@link parsePushedRange} returns null there and the caller falls back
7763
+ * to notifying — a first push of a repo is overwhelmingly one that carries a
7764
+ * Dockerfile.
7765
+ */
7766
+ function parsePushedRange(output) {
7767
+ const match = output.match(/\b([0-9a-f]{7,40})\.\.([0-9a-f]{7,40})\b/);
7768
+ if (!match) return null;
7769
+ return `${match[1]}..${match[2]}`;
7770
+ }
7771
+ /** True when a forced update (`+ abc..def (forced update)`) or a new ref. */
7772
+ function isNewRef(output) {
7773
+ return /\[new (?:branch|tag)\]/.test(output);
7774
+ }
7775
+ async function touchedBakedPath({ cwd, range }) {
7776
+ const { stdout } = await execFileAsync("git", [
7777
+ "diff",
7778
+ "--name-only",
7779
+ range
7780
+ ], {
7781
+ cwd,
7782
+ timeout: 5e3,
7783
+ maxBuffer: 4 * 1024 * 1024
7784
+ });
7785
+ return stdout.split("\n").map((line) => line.trim()).some((path) => path.length > 0 && BAKED_BUILD_PATHS.has(path));
7786
+ }
7787
+ const templateBuildPushExtension = (pi) => {
7788
+ pi.on("tool_result", async (event, ctx) => {
7789
+ if (event.toolName !== "bash") return;
7790
+ if (event.isError) return;
7791
+ const command = event.input.command;
7792
+ if (typeof command !== "string" || !isGitPush(command)) return;
7793
+ const output = event.content.map((part) => part.type === "text" ? part.text : "").join("\n");
7794
+ let notify = false;
7795
+ try {
7796
+ const range = parsePushedRange(output);
7797
+ if (range === null) notify = isNewRef(output);
7798
+ else notify = await touchedBakedPath({
7799
+ cwd: ctx.cwd,
7800
+ range
7801
+ });
7802
+ } catch (err) {
7803
+ log.warn({
7804
+ err,
7805
+ event: "template_build_push_classify_failed"
7806
+ }, "could not classify pushed paths; leaving the push result unchanged");
7807
+ return;
7808
+ }
7809
+ if (!notify) return;
7810
+ return { content: [...event.content, {
7811
+ type: "text",
7812
+ text: `\n${BUILD_STARTED_NOTICE}`
7813
+ }] };
7814
+ });
7815
+ };
7816
+ //#endregion
7333
7817
  //#region src/extensions/tool-history.ts
7334
7818
  const VALID_NAME_RE = /^[a-zA-Z0-9_-]+$/;
7335
7819
  function isValidToolName(name) {
@@ -7471,6 +7955,7 @@ const all = [
7471
7955
  bashDefaultTimeoutExtension,
7472
7956
  diskGuardExtension,
7473
7957
  noopLoopGuardExtension,
7958
+ repeatCallGuardExtension,
7474
7959
  sleepGuardExtension,
7475
7960
  toolCallSummaryExtension
7476
7961
  ];
@@ -7497,6 +7982,7 @@ function platformExtensions({ sessionId, channelContext }) {
7497
7982
  createSubagentExtension({ channelContext }),
7498
7983
  createContextManagementExtension(),
7499
7984
  resourcePressureWarningExtension,
7985
+ templateBuildPushExtension,
7500
7986
  tool_history_default
7501
7987
  ];
7502
7988
  }