@skydiveai/pi-extensions 0.1.258-beta.99 → 0.1.259-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +530 -126
  2. package/package.json +6 -5
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");
@@ -1500,7 +1502,7 @@ function toProviderSafeSchema(inputSchema) {
1500
1502
  * Clients are keyed by JSON-stringified config and reused across
1501
1503
  * reloads — only changed configs reconnect.
1502
1504
  */
1503
- const log$17 = logger.child({ module: "mcp-extension" });
1505
+ const log$21 = logger.child({ module: "mcp-extension" });
1504
1506
  function resolveToolSelection(server) {
1505
1507
  return {
1506
1508
  allow: server?.tools?.length ? new Set(server.tools) : null,
@@ -1698,7 +1700,7 @@ function providerSafeTools({ serverId, tools }) {
1698
1700
  for (const tool of tools) {
1699
1701
  const result = toProviderSafeSchema(tool.inputSchema);
1700
1702
  if (!result.ok) {
1701
- log$17.warn({
1703
+ log$21.warn({
1702
1704
  event: "mcp_tool_schema_unsupported",
1703
1705
  server_id: serverId,
1704
1706
  tool_name: tool.name,
@@ -2172,7 +2174,7 @@ var McpExtension = class {
2172
2174
  });
2173
2175
  this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
2174
2176
  if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
2175
- log$17.info({
2177
+ log$21.info({
2176
2178
  event: "mcp_reconcile",
2177
2179
  reason,
2178
2180
  total_tools: summary.totalTools,
@@ -2199,7 +2201,7 @@ var McpExtension = class {
2199
2201
  contextWindow: ctx.model?.contextWindow
2200
2202
  });
2201
2203
  } catch (err) {
2202
- log$17.error({
2204
+ log$21.error({
2203
2205
  err,
2204
2206
  event: "mcp_reconcile_failed"
2205
2207
  }, "MCP reconcile failed");
@@ -2213,7 +2215,7 @@ var McpExtension = class {
2213
2215
  for (const legacy of renamed) {
2214
2216
  if (this.loggedLegacyToolNames.has(legacy)) continue;
2215
2217
  this.loggedLegacyToolNames.add(legacy);
2216
- log$17.info({
2218
+ log$21.info({
2217
2219
  event: "mcp_tool_legacy_name",
2218
2220
  legacy_name: legacy,
2219
2221
  tool_name: this.legacyToolNames.get(legacy)
@@ -2227,7 +2229,7 @@ var McpExtension = class {
2227
2229
  try {
2228
2230
  mtime = await readConfigMtimeMs(configPath);
2229
2231
  } catch (err) {
2230
- log$17.warn({
2232
+ log$21.warn({
2231
2233
  err,
2232
2234
  event: "mcp_mtime_check_failed"
2233
2235
  }, "mtime check on mcp.config.json failed");
@@ -2242,7 +2244,7 @@ var McpExtension = class {
2242
2244
  contextWindow: ctx.model?.contextWindow
2243
2245
  });
2244
2246
  } catch (err) {
2245
- log$17.error({
2247
+ log$21.error({
2246
2248
  err,
2247
2249
  event: "mcp_auto_reload_failed"
2248
2250
  }, "auto-reload after mcp.config.json change failed");
@@ -2608,11 +2610,21 @@ const assistantSchema = z.object({
2608
2610
  id: z.string(),
2609
2611
  model: z.string()
2610
2612
  });
2613
+ const sdkToolResultSchema = z.object({ content: z.array(z.object({ type: z.literal("tool_result") })).min(1) });
2611
2614
  function assistantMessage(entry) {
2612
2615
  if (entry.type !== "assistant") return null;
2613
2616
  const parsed = assistantSchema.safeParse(entry.message);
2614
2617
  return parsed.success ? parsed.data : null;
2615
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
+ }
2616
2628
  function contentHash(message) {
2617
2629
  return createHash("sha256").update(JSON.stringify(message.content)).digest("hex");
2618
2630
  }
@@ -2670,7 +2682,7 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2670
2682
  const entry = byId.get(id);
2671
2683
  if (!entry) break;
2672
2684
  const assistant = assistantMessage(entry);
2673
- 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);
2674
2686
  id = entry.parentUuid;
2675
2687
  }
2676
2688
  if (id === boundaryId && entries.length) return entries.reverse();
@@ -2679,6 +2691,8 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2679
2691
  }
2680
2692
  //#endregion
2681
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.";
2682
2696
  const imageType = z.enum([
2683
2697
  "image/jpeg",
2684
2698
  "image/png",
@@ -2763,7 +2777,7 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
2763
2777
  const hashes = seatPrefixHashes(context, model);
2764
2778
  const messages = [...context.messages];
2765
2779
  const last = messages.at(-1);
2766
- 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;
2767
2781
  if (last?.role === "user") messages.pop();
2768
2782
  if (messages.length === 0) return {
2769
2783
  prompt,
@@ -2877,6 +2891,176 @@ function seatReasoningOptions({ model, context, options }) {
2877
2891
  };
2878
2892
  }
2879
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
2880
3064
  //#region src/extensions/claude-seat-payload.ts
2881
3065
  const payloadSchema = z.strictObject({
2882
3066
  model: z.string(),
@@ -2948,7 +3132,7 @@ const SEAT_QUERY_TIMEOUTS = {
2948
3132
  preparation: 3e4
2949
3133
  };
2950
3134
  const PI_TOOLS_SERVER = "custom-tools";
2951
- const log$16 = logger.child({ module: "claude-seat-sdk" });
3135
+ const log$19 = logger.child({ module: "claude-seat-sdk" });
2952
3136
  /** Preserve existing MCP names; only ordinary Pi tools need a server prefix. */
2953
3137
  function toolBindings(context) {
2954
3138
  const parsed = (context.tools ?? []).map((definition) => {
@@ -3006,7 +3190,7 @@ var SeatQuery = class {
3006
3190
  this.deadline = setTimeout(() => {
3007
3191
  const err = /* @__PURE__ */ new Error(`Claude seat SDK timed out waiting for ${phase}`);
3008
3192
  err.name = "TimeoutError";
3009
- log$16.error({
3193
+ log$19.error({
3010
3194
  err,
3011
3195
  phase
3012
3196
  }, "Claude seat SDK wait deadline exceeded");
@@ -3047,10 +3231,12 @@ var SeatQuery = class {
3047
3231
  async run({ sessionId, cwd }) {
3048
3232
  const { model, context, options } = this.request;
3049
3233
  let configDir = null;
3234
+ let requestProxy = null;
3050
3235
  try {
3051
3236
  if (!options.apiKey) throw new Error("Claude seat SDK requires a seat credential sentinel");
3052
3237
  this.controller.signal.throwIfAborted();
3053
3238
  configDir = await mkdtemp(path.join(os.tmpdir(), "claude-seat-sdk-"));
3239
+ requestProxy = await startSeatRequestProxy({ target: model.baseUrl });
3054
3240
  this.controller.signal.throwIfAborted();
3055
3241
  const bindings = toolBindings(context);
3056
3242
  const servers = /* @__PURE__ */ new Map();
@@ -3145,7 +3331,7 @@ var SeatQuery = class {
3145
3331
  env: buildStdioEnv({
3146
3332
  ANTHROPIC_AUTH_TOKEN: options.apiKey,
3147
3333
  ANTHROPIC_API_KEY: "",
3148
- ANTHROPIC_BASE_URL: model.baseUrl,
3334
+ ANTHROPIC_BASE_URL: requestProxy.url,
3149
3335
  ANTHROPIC_CUSTOM_HEADERS: platformHeaders({
3150
3336
  model,
3151
3337
  options,
@@ -3187,7 +3373,7 @@ var SeatQuery = class {
3187
3373
  }
3188
3374
  } catch (err) {
3189
3375
  this.failure = err;
3190
- if (!this.controller.signal.aborted) log$16.error({
3376
+ if (!this.controller.signal.aborted) log$19.error({
3191
3377
  err,
3192
3378
  sessionId
3193
3379
  }, "Claude seat SDK query failed");
@@ -3196,13 +3382,14 @@ var SeatQuery = class {
3196
3382
  if (this.deadline) clearTimeout(this.deadline);
3197
3383
  this.deadline = null;
3198
3384
  this.wake?.();
3385
+ requestProxy?.close();
3199
3386
  if (configDir) try {
3200
3387
  await rm(configDir, {
3201
3388
  recursive: true,
3202
3389
  force: true
3203
3390
  });
3204
3391
  } catch (err) {
3205
- log$16.error({
3392
+ log$19.error({
3206
3393
  err,
3207
3394
  sessionId
3208
3395
  }, "Could not remove Claude seat SDK config");
@@ -3235,10 +3422,26 @@ function mapUsage(usage) {
3235
3422
  //#endregion
3236
3423
  //#region src/extensions/claude-seat-response.ts
3237
3424
  const toolInput = z.record(z.string(), z.unknown());
3238
- function piToolName(name, context) {
3239
- const binding = toolBindings(context).find((binding) => binding.sdkName === name);
3240
- if (!binding) throw new Error(`Claude requested a tool outside the Pi bridge: ${name}`);
3241
- 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;
3242
3445
  }
3243
3446
  /** Commit only the accepted SDK attempt: Pi deltas cannot retract retried output. */
3244
3447
  var ModelResponse = class {
@@ -3246,9 +3449,10 @@ var ModelResponse = class {
3246
3449
  pending = [];
3247
3450
  messageId = null;
3248
3451
  stopReason = null;
3249
- constructor(model, context, events) {
3452
+ constructor(model, context, events, sessionId) {
3250
3453
  this.context = context;
3251
3454
  this.events = events;
3455
+ this.sessionId = sessionId;
3252
3456
  this.message = {
3253
3457
  role: "assistant",
3254
3458
  content: [],
@@ -3343,7 +3547,11 @@ var ModelResponse = class {
3343
3547
  block = {
3344
3548
  type: "toolCall",
3345
3549
  id: sdkBlock.id,
3346
- name: piToolName(sdkBlock.name, this.context),
3550
+ name: piToolName({
3551
+ name: sdkBlock.name,
3552
+ context: this.context,
3553
+ sessionId: this.sessionId
3554
+ }),
3347
3555
  arguments: toolInput.parse(sdkBlock.input)
3348
3556
  };
3349
3557
  break;
@@ -3419,7 +3627,7 @@ var ModelResponse = class {
3419
3627
  * each step resumes a private structured snapshot after Pi extensions run.
3420
3628
  * Initially adapted from elidickinson/pi-claude-bridge (MIT).
3421
3629
  */
3422
- const log$15 = logger.child({ module: "claude-seat-sdk" });
3630
+ const log$17 = logger.child({ module: "claude-seat-sdk" });
3423
3631
  const SEAT_SDK_ACTIVITY_EVENT = "claude-seat-sdk:activity";
3424
3632
  /** Session-scoped adapter; only the flagged provider dispatches here. */
3425
3633
  var SeatSdkBridge = class {
@@ -3437,7 +3645,7 @@ var SeatSdkBridge = class {
3437
3645
  }
3438
3646
  stream(model, context, options = {}) {
3439
3647
  const events = createAssistantMessageEventStream();
3440
- const response = new ModelResponse(model, context, events);
3648
+ const response = new ModelResponse(model, context, events, this.deps.sessionId);
3441
3649
  const signal = AbortSignal.any([this.controller.signal, ...options.signal ? [options.signal] : []]);
3442
3650
  (async () => {
3443
3651
  let seatQuery = null;
@@ -3470,7 +3678,7 @@ var SeatSdkBridge = class {
3470
3678
  } else if (message.type === "result") {
3471
3679
  const hasTools = response.hasTools;
3472
3680
  if (message.is_error && !(message.subtype === "error_max_turns" && hasTools)) throw new Error("errors" in message ? message.errors.join("; ") : message.result);
3473
- log$15.info({
3681
+ log$17.info({
3474
3682
  sessionId: this.deps.sessionId,
3475
3683
  queryUsage: mapUsage(message.usage),
3476
3684
  requestUsage: response.message.usage
@@ -3491,7 +3699,7 @@ var SeatSdkBridge = class {
3491
3699
  }
3492
3700
  } catch (err) {
3493
3701
  const reason = (seatQuery?.controller.signal.aborted || signal.aborted) && !(err instanceof Error && err.name === "TimeoutError") ? "aborted" : "error";
3494
- if (reason === "error") log$15.error({
3702
+ if (reason === "error") log$17.error({
3495
3703
  err,
3496
3704
  sessionId: this.deps.sessionId
3497
3705
  }, "Claude seat SDK response failed");
@@ -3562,7 +3770,7 @@ const HEARTBEAT_THROTTLE_MS = 6e4;
3562
3770
  const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
3563
3771
  const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
3564
3772
  const DAEMON_URL = "http://localhost:38994";
3565
- const log$14 = logger.child({ module: "platform-ext" });
3773
+ const log$16 = logger.child({ module: "platform-ext" });
3566
3774
  function sandboxClient() {
3567
3775
  const apiUrl = apiBaseUrl();
3568
3776
  if (!apiUrl) return null;
@@ -3630,7 +3838,7 @@ async function fetchHarnessFlags() {
3630
3838
  try {
3631
3839
  const res = await client["feature-flags"].$get();
3632
3840
  if (!res.ok) {
3633
- log$14.debug({
3841
+ log$16.debug({
3634
3842
  status: res.status,
3635
3843
  event: "feature_flags_fetch_failed"
3636
3844
  }, "feature-flags fetch failed");
@@ -3642,7 +3850,7 @@ async function fetchHarnessFlags() {
3642
3850
  closingText: body.closingText ?? null
3643
3851
  };
3644
3852
  } catch (err) {
3645
- log$14.debug({
3853
+ log$16.debug({
3646
3854
  err,
3647
3855
  event: "feature_flags_fetch_error"
3648
3856
  }, "feature-flags request errored");
@@ -3653,7 +3861,7 @@ function postHeartbeat({ messageId }) {
3653
3861
  const client = sandboxClient();
3654
3862
  if (!client) return;
3655
3863
  client.heartbeat.$post({ json: { messageId } }).catch((err) => {
3656
- log$14.debug({
3864
+ log$16.debug({
3657
3865
  err,
3658
3866
  event: "heartbeat_failed"
3659
3867
  }, "heartbeat failed");
@@ -3665,7 +3873,7 @@ async function resolveConversationFromApi(messageId) {
3665
3873
  try {
3666
3874
  const res = await client["message-conversation"].$get({ query: { messageId } });
3667
3875
  if (!res.ok) {
3668
- log$14.warn({
3876
+ log$16.warn({
3669
3877
  status: res.status,
3670
3878
  messageId,
3671
3879
  event: "resolve_conversation_failed"
@@ -3674,7 +3882,7 @@ async function resolveConversationFromApi(messageId) {
3674
3882
  }
3675
3883
  return (await res.json()).conversationId ?? null;
3676
3884
  } catch (err) {
3677
- log$14.warn({
3885
+ log$16.warn({
3678
3886
  err,
3679
3887
  messageId,
3680
3888
  event: "resolve_conversation_error"
@@ -3699,13 +3907,13 @@ async function putBackgroundTaskJournalSpec({ messageId, spec }) {
3699
3907
  messageId,
3700
3908
  spec
3701
3909
  } });
3702
- if (!res.ok) log$14.warn({
3910
+ if (!res.ok) log$16.warn({
3703
3911
  status: res.status,
3704
3912
  taskId: spec.id,
3705
3913
  event: "bg_journal_put_failed"
3706
3914
  }, "bg-task journal PUT failed");
3707
3915
  } catch (err) {
3708
- log$14.warn({
3916
+ log$16.warn({
3709
3917
  err,
3710
3918
  taskId: spec.id,
3711
3919
  event: "bg_journal_put_failed"
@@ -3721,7 +3929,7 @@ async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
3721
3929
  taskId
3722
3930
  } });
3723
3931
  } catch (err) {
3724
- log$14.debug({
3932
+ log$16.debug({
3725
3933
  err,
3726
3934
  taskId,
3727
3935
  event: "bg_journal_delete_failed"
@@ -3736,7 +3944,7 @@ async function listBackgroundTaskJournalSpecs({ messageId }) {
3736
3944
  if (!res.ok) return [];
3737
3945
  return (await res.json()).specs ?? [];
3738
3946
  } catch (err) {
3739
- log$14.debug({
3947
+ log$16.debug({
3740
3948
  err,
3741
3949
  event: "bg_journal_list_failed"
3742
3950
  }, "bg-task journal GET failed");
@@ -3750,7 +3958,7 @@ function postBackgroundTasksSnapshot({ messageId, tasks }) {
3750
3958
  messageId,
3751
3959
  tasks
3752
3960
  } }).catch((err) => {
3753
- log$14.debug({
3961
+ log$16.debug({
3754
3962
  err,
3755
3963
  event: "bg_tasks_snapshot_failed"
3756
3964
  }, "bg-tasks snapshot publish failed");
@@ -3848,7 +4056,7 @@ function createToolHeartbeat({ messageId }) {
3848
4056
  }
3849
4057
  heartbeatCount++;
3850
4058
  if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
3851
- log$14.warn({
4059
+ log$16.warn({
3852
4060
  heartbeatCount,
3853
4061
  activeToolCalls: [...activeToolCalls]
3854
4062
  }, "tool heartbeat max reached, stopping");
@@ -3879,7 +4087,7 @@ function postToDaemon(path, body) {
3879
4087
  headers: { "content-type": "application/json" },
3880
4088
  body: JSON.stringify(body)
3881
4089
  }).catch((err) => {
3882
- log$14.debug({
4090
+ log$16.debug({
3883
4091
  err,
3884
4092
  path,
3885
4093
  event: "daemon_post_failed"
@@ -3888,7 +4096,7 @@ function postToDaemon(path, body) {
3888
4096
  }
3889
4097
  function createPlatformExtensions({ sessionId, channelContext }) {
3890
4098
  return (pi) => {
3891
- log$14.info({
4099
+ log$16.info({
3892
4100
  sessionId,
3893
4101
  hasChannelContext: Boolean(channelContext)
3894
4102
  }, "platform extension initialized");
@@ -3942,7 +4150,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
3942
4150
  });
3943
4151
  });
3944
4152
  pi.on("agent_end", () => {
3945
- log$14.info({ sessionId }, "session ending");
4153
+ log$16.info({ sessionId }, "session ending");
3946
4154
  postToDaemon("/session/end", { sessionId });
3947
4155
  });
3948
4156
  };
@@ -3974,6 +4182,14 @@ const toolCallEnvExtension = (pi) => {
3974
4182
  });
3975
4183
  };
3976
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
3977
4193
  //#region src/extensions/background-tasks.ts
3978
4194
  /**
3979
4195
  * Background bash tasks as a pi extension.
@@ -4078,8 +4294,8 @@ const toolCallEnvExtension = (pi) => {
4078
4294
  * semantics; once promoted, the command inherits background-task lifecycle
4079
4295
  * (its own controller) and the foreground kill timeout no longer applies.
4080
4296
  */
4081
- const log$13 = logger.child({ module: "background-tasks-ext" });
4082
- const ops = createLocalBashOperations();
4297
+ const log$15 = logger.child({ module: "background-tasks-ext" });
4298
+ const ops = createOomNeutralBashOperations({ shellPath: void 0 });
4083
4299
  const STEER_BACKGROUND_DEFAULT_SECONDS = 60;
4084
4300
  const STEER_BACKGROUND_ENV_KEYS = ["BASH_STEER_BACKGROUND_SECONDS", "SKYDIVE_BASH_STEER_BACKGROUND_SECONDS"];
4085
4301
  /**
@@ -4093,7 +4309,7 @@ function steerBackgroundThresholdMs() {
4093
4309
  if (raw === void 0 || raw.trim() === "") continue;
4094
4310
  const parsed = Number(raw);
4095
4311
  if (!Number.isFinite(parsed) || parsed < 0) {
4096
- log$13.warn({
4312
+ log$15.warn({
4097
4313
  envKey: key,
4098
4314
  raw
4099
4315
  }, "invalid BASH_STEER_BACKGROUND_SECONDS, using default");
@@ -4122,7 +4338,7 @@ async function notifyBashSteerArrival(args) {
4122
4338
  try {
4123
4339
  await listener();
4124
4340
  } catch (err) {
4125
- log$13.error({
4341
+ log$15.error({
4126
4342
  err,
4127
4343
  sessionId: args.sessionId
4128
4344
  }, "bash steer promotion failed");
@@ -4217,14 +4433,14 @@ function watchdogTick(now) {
4217
4433
  const overSize = meta.logBytes > MAX_LOG_BYTES;
4218
4434
  if (!overRuntime && !overSize) continue;
4219
4435
  const reason = overSize ? `output exceeded ${MAX_LOG_BYTES / (1024 * 1024)}MiB` : `exceeded ${KEEPALIVE_MAX_MS / 6e4}m max runtime`;
4220
- log$13.warn({
4436
+ log$15.warn({
4221
4437
  taskId: meta.id,
4222
4438
  reason
4223
4439
  }, "watchdog killing bg task");
4224
4440
  try {
4225
4441
  killTask(meta, reason);
4226
4442
  } catch (err) {
4227
- log$13.warn({
4443
+ log$15.warn({
4228
4444
  err,
4229
4445
  taskId: meta.id
4230
4446
  }, "watchdog kill failed");
@@ -4283,7 +4499,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4283
4499
  const now = Date.now();
4284
4500
  const promotable = [...foregroundBash.values()].filter((call) => now - call.startedAt >= thresholdMs);
4285
4501
  if (promotable.length === 0) return;
4286
- log$13.info({
4502
+ log$15.info({
4287
4503
  event: "bash_steer_promotion",
4288
4504
  count: promotable.length,
4289
4505
  thresholdSeconds: Math.round(thresholdMs / 1e3),
@@ -4308,7 +4524,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4308
4524
  try {
4309
4525
  await mkdir(tasksDir(), { recursive: true });
4310
4526
  } catch (err) {
4311
- log$13.error({ err }, "bg task adopt: mkdir failed");
4527
+ log$15.error({ err }, "bg task adopt: mkdir failed");
4312
4528
  }
4313
4529
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4314
4530
  logStream.on("error", () => {});
@@ -4335,7 +4551,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4335
4551
  tasks.set(id, meta);
4336
4552
  ensureWatchdog();
4337
4553
  schedulePublishSnapshot();
4338
- log$13.info({
4554
+ log$15.info({
4339
4555
  taskId: id,
4340
4556
  conversationId,
4341
4557
  startedAt: args.startedAt
@@ -4358,7 +4574,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4358
4574
  * handling, timeout kill, and abort semantics.
4359
4575
  */
4360
4576
  function createSteerAwareOperations(base) {
4361
- const localOps = createLocalBashOperations({ shellPath: base.shellPath });
4577
+ const localOps = createOomNeutralBashOperations({ shellPath: base.shellPath });
4362
4578
  return { async exec(command, cwd, execOptions) {
4363
4579
  const thresholdMs = steerBackgroundThresholdMs();
4364
4580
  const toolOnData = execOptions?.onData;
@@ -4488,7 +4704,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4488
4704
  try {
4489
4705
  shellPath = SettingsManager.create(ctx.cwd, getAgentDir()).getShellPath();
4490
4706
  } catch (err) {
4491
- log$13.warn({
4707
+ log$15.warn({
4492
4708
  err,
4493
4709
  cwd: ctx.cwd
4494
4710
  }, "bash steer promotion: shell settings unavailable, using default shell");
@@ -4503,7 +4719,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
4503
4719
  ...definition,
4504
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.`
4505
4721
  });
4506
- log$13.info({
4722
+ log$15.info({
4507
4723
  event: "bash_steer_promotion_enabled",
4508
4724
  thresholdSeconds: Math.round(thresholdMs / 1e3)
4509
4725
  }, "supervised bash tool registered (steer-triggered backgrounding)");
@@ -4546,7 +4762,7 @@ or if you were explicitly waiting to report it.`,
4546
4762
  triggerTurn: true,
4547
4763
  deliverAs: "followUp"
4548
4764
  });
4549
- log$13.info({
4765
+ log$15.info({
4550
4766
  taskId: meta.id,
4551
4767
  conversationId
4552
4768
  }, "bg task completion delivered live (followUp)");
@@ -4554,7 +4770,7 @@ or if you were explicitly waiting to report it.`,
4554
4770
  }
4555
4771
  if (meta.messageId) {
4556
4772
  meta.notified = true;
4557
- log$13.info({
4773
+ log$15.info({
4558
4774
  taskId: meta.id,
4559
4775
  messageId: meta.messageId
4560
4776
  }, "posting idle bg-task-done wake");
@@ -4564,12 +4780,12 @@ or if you were explicitly waiting to report it.`,
4564
4780
  content: message.content
4565
4781
  }).catch((err) => {
4566
4782
  meta.notified = false;
4567
- log$13.warn({
4783
+ log$15.warn({
4568
4784
  err,
4569
4785
  taskId: meta.id
4570
4786
  }, "bg-task-done wake failed; will retry at next session_start");
4571
4787
  });
4572
- } 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");
4573
4789
  }
4574
4790
  const SNAPSHOT_TAIL_LINES = 40;
4575
4791
  let lastPublishedSignature = null;
@@ -4606,7 +4822,7 @@ or if you were explicitly waiting to report it.`,
4606
4822
  tasks: snapshot
4607
4823
  });
4608
4824
  } catch (err) {
4609
- log$13.debug({
4825
+ log$15.debug({
4610
4826
  err,
4611
4827
  event: "bg_tasks_snapshot_build_failed"
4612
4828
  }, "building bg-tasks snapshot failed");
@@ -4649,7 +4865,7 @@ or if you were explicitly waiting to report it.`,
4649
4865
  logStream.end();
4650
4866
  await finished(logStream).catch(() => {});
4651
4867
  meta.running = false;
4652
- log$13.info({
4868
+ log$15.info({
4653
4869
  taskId: meta.id,
4654
4870
  exitCode: meta.exitCode
4655
4871
  }, "bg task finished");
@@ -4666,14 +4882,14 @@ or if you were explicitly waiting to report it.`,
4666
4882
  try {
4667
4883
  await mkdir(tasksDir(), { recursive: true });
4668
4884
  } catch (err) {
4669
- log$13.error({
4885
+ log$15.error({
4670
4886
  err,
4671
4887
  taskId: id
4672
4888
  }, "background task dir unavailable");
4673
4889
  }
4674
4890
  const logStream = createWriteStream(logPath(id), { flags: "a" });
4675
4891
  logStream.on("error", (err) => {
4676
- log$13.warn({
4892
+ log$15.warn({
4677
4893
  err,
4678
4894
  taskId: id
4679
4895
  }, "bg task log write failed");
@@ -4723,7 +4939,7 @@ or if you were explicitly waiting to report it.`,
4723
4939
  }).catch((err) => {
4724
4940
  if (!meta.controller.signal.aborted) {
4725
4941
  meta.error = err instanceof Error ? err.message : String(err);
4726
- log$13.warn({
4942
+ log$15.warn({
4727
4943
  err,
4728
4944
  taskId: id
4729
4945
  }, "bg task exec error");
@@ -4732,7 +4948,7 @@ or if you were explicitly waiting to report it.`,
4732
4948
  await finishTask(meta, logStream);
4733
4949
  });
4734
4950
  ensureWatchdog();
4735
- log$13.info({
4951
+ log$15.info({
4736
4952
  taskId: id,
4737
4953
  conversationId
4738
4954
  }, "bg task started");
@@ -4751,7 +4967,7 @@ or if you were explicitly waiting to report it.`,
4751
4967
  for (const spec of specs) {
4752
4968
  const live = tasks.get(spec.id);
4753
4969
  if (live && sameScope(live, scopeKey())) continue;
4754
- log$13.info({
4970
+ log$15.info({
4755
4971
  taskId: spec.id,
4756
4972
  conversationId
4757
4973
  }, "relaunching journaled resumable bg task after restart");
@@ -4769,7 +4985,7 @@ or if you were explicitly waiting to report it.`,
4769
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`);
4770
4986
  stream.end();
4771
4987
  } catch (err) {
4772
- log$13.debug({
4988
+ log$15.debug({
4773
4989
  err,
4774
4990
  taskId: meta.id
4775
4991
  }, "resume banner write failed");
@@ -4789,7 +5005,7 @@ or if you were explicitly waiting to report it.`,
4789
5005
  meta.notified = true;
4790
5006
  pi.sendMessage(await taskDoneMessage(meta));
4791
5007
  }
4792
- if (unnotified.length > 0) log$13.info({
5008
+ if (unnotified.length > 0) log$15.info({
4793
5009
  conversationId,
4794
5010
  count: unnotified.length
4795
5011
  }, "injected completed bg tasks at session_start");
@@ -4984,7 +5200,7 @@ or if you were explicitly waiting to report it.`,
4984
5200
  * read on the hot path before every LLM call), it falls back to the default
4985
5201
  * for that knob and logs once.
4986
5202
  */
4987
- const log$12 = logger.child({ module: "context-management-config" });
5203
+ const log$14 = logger.child({ module: "context-management-config" });
4988
5204
  const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
4989
5205
  enabled: false,
4990
5206
  perResultMaxBytes: 16 * 1024,
@@ -5029,7 +5245,7 @@ function resolveContextManagementConfig(env = process.env) {
5029
5245
  clearAtLeastTokens: env.SKYDIVE_CTX_CLEAR_AT_LEAST_TOKENS
5030
5246
  });
5031
5247
  if (!parsed.success) {
5032
- log$12.warn({
5248
+ log$14.warn({
5033
5249
  event: "context_management_config_invalid",
5034
5250
  err: parsed.error
5035
5251
  }, "falling back to default context-management config");
@@ -5113,7 +5329,7 @@ function hasFlagSource(env = process.env) {
5113
5329
  * alive and an indeterminate result (no api url / transient failure) leaves the
5114
5330
  * last-known values untouched so a blip can't silently flip behavior.
5115
5331
  */
5116
- const log$11 = logger.child({ module: "feature-flags-poll" });
5332
+ const log$13 = logger.child({ module: "feature-flags-poll" });
5117
5333
  const FLAG_POLL_INTERVAL_MS = 6e4;
5118
5334
  let contextManagement = null;
5119
5335
  let closingText = null;
@@ -5153,7 +5369,7 @@ function apply(name, next) {
5153
5369
  if (next !== prev) for (const cb of subscribers[name]) try {
5154
5370
  cb(next);
5155
5371
  } catch (err) {
5156
- log$11.warn({
5372
+ log$13.warn({
5157
5373
  err,
5158
5374
  flag: name
5159
5375
  }, "flag subscriber threw");
@@ -5166,7 +5382,7 @@ async function pollOnce() {
5166
5382
  apply("contextManagement", flags.contextManagement ?? null);
5167
5383
  apply("closingText", flags.closingText ?? null);
5168
5384
  } catch (err) {
5169
- log$11.debug({ err }, "feature-flag poll threw");
5385
+ log$13.debug({ err }, "feature-flag poll threw");
5170
5386
  }
5171
5387
  }
5172
5388
  /**
@@ -5367,8 +5583,8 @@ const bashDefaultTimeoutExtension = (pi) => {
5367
5583
  * stat and the extension warns on what it can see — it must never break a
5368
5584
  * turn over an observability feature.
5369
5585
  */
5370
- const execFileAsync = promisify(execFile);
5371
- 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" });
5372
5588
  const POLL_INTERVAL_MS = 1e4;
5373
5589
  function envOverride(name) {
5374
5590
  for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
@@ -5436,7 +5652,7 @@ async function readMemUsePct() {
5436
5652
  */
5437
5653
  async function readDiskUsePct() {
5438
5654
  try {
5439
- const { stdout } = await execFileAsync("df", ["-P", diskRoot()]);
5655
+ const { stdout } = await execFileAsync$1("df", ["-P", diskRoot()]);
5440
5656
  const dataRow = stdout.trim().split("\n")[1];
5441
5657
  if (dataRow == null) return null;
5442
5658
  const capacity = dataRow.trim().split(/\s+/)[4];
@@ -5565,7 +5781,7 @@ const resourcePressureWarningExtension = (pi) => {
5565
5781
  warnedDiskThisTurn = true;
5566
5782
  }
5567
5783
  if (trigger === null) return;
5568
- log$10.warn({
5784
+ log$12.warn({
5569
5785
  trigger,
5570
5786
  mem,
5571
5787
  cpuPct,
@@ -5603,7 +5819,7 @@ const resourcePressureWarningExtension = (pi) => {
5603
5819
  if (!timer) {
5604
5820
  timer = setInterval(() => {
5605
5821
  checkOnce().catch((err) => {
5606
- log$10.error({ err }, "resource pressure check failed");
5822
+ log$12.error({ err }, "resource pressure check failed");
5607
5823
  });
5608
5824
  }, POLL_INTERVAL_MS);
5609
5825
  timer.unref?.();
@@ -5619,7 +5835,7 @@ const resourcePressureWarningExtension = (pi) => {
5619
5835
  };
5620
5836
  //#endregion
5621
5837
  //#region src/extensions/disk-guard.ts
5622
- const log$9 = logger.child({ module: "disk-guard" });
5838
+ const log$11 = logger.child({ module: "disk-guard" });
5623
5839
  /**
5624
5840
  * In-band bypass. The guard is a safety net, not a jail: when the agent knows
5625
5841
  * a flagged command is genuinely safe (writing to a different mount, a tiny
@@ -5641,7 +5857,7 @@ const BYPASS_HINT$2 = "# disk-guard: allow";
5641
5857
  * first; the SKYDIVE_/ANYONE_ prefixes are accepted too for consistency with
5642
5858
  * the other env overrides. Empty/unset/"0"/"false" leave the guard on.
5643
5859
  */
5644
- function guardDisabledByEnv$2() {
5860
+ function guardDisabledByEnv$3() {
5645
5861
  for (const name of [
5646
5862
  "DISK_GUARD_DISABLE",
5647
5863
  "SKYDIVE_DISK_GUARD_DISABLE",
@@ -5752,14 +5968,14 @@ function diskBlockReason(command, diskPct) {
5752
5968
  const diskGuardExtension = (pi) => {
5753
5969
  pi.on("tool_call", async (event) => {
5754
5970
  if (event.toolName !== "bash") return;
5755
- if (guardDisabledByEnv$2()) return;
5971
+ if (guardDisabledByEnv$3()) return;
5756
5972
  const command = event.input.command;
5757
5973
  if (typeof command !== "string" || command.length === 0) return;
5758
5974
  if (hasBypassMarker$2(command)) return;
5759
5975
  if (!isSpaceHungryCommand(command)) return;
5760
5976
  const diskPct = await readDiskUsePct();
5761
5977
  if (!shouldBlockForDisk(command, diskPct)) return;
5762
- log$9.warn({
5978
+ log$11.warn({
5763
5979
  diskPct,
5764
5980
  command: command.slice(0, 200)
5765
5981
  }, "blocked space-hungry bash command on near-full disk");
@@ -5771,7 +5987,7 @@ const diskGuardExtension = (pi) => {
5771
5987
  };
5772
5988
  //#endregion
5773
5989
  //#region src/extensions/noop-loop-guard.ts
5774
- const log$8 = logger.child({ module: "noop-loop-guard" });
5990
+ const log$10 = logger.child({ module: "noop-loop-guard" });
5775
5991
  /** Length of the rolling window that counts silence commands across streak resets. */
5776
5992
  const SILENCE_WINDOW_MS = 300 * 1e3;
5777
5993
  /** Bare shell no-op: `true` or `:` (case-insensitive). */
@@ -5787,9 +6003,9 @@ const ECHO_ARG_MAX_LEN = 64;
5787
6003
  /** Marker that forces a single command through the guard. */
5788
6004
  const BYPASS_HINT$1 = "noop-guard: allow";
5789
6005
  /** Env vars that turn the guard off for the process. */
5790
- const KILL_SWITCH_KEYS = ["NOOP_LOOP_GUARD_DISABLE", "SKYDIVE_NOOP_LOOP_GUARD_DISABLE"];
5791
- function guardDisabledByEnv$1() {
5792
- 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) => {
5793
6009
  const value = process.env[key];
5794
6010
  return value !== void 0 && value !== "" && value !== "0";
5795
6011
  });
@@ -5913,17 +6129,20 @@ const noopLoopGuardExtension = (pi) => {
5913
6129
  };
5914
6130
  pi.on("tool_call", async (event, ctx) => {
5915
6131
  if (event.toolName !== "bash") return;
5916
- if (guardDisabledByEnv$1()) return;
5917
- const command = event.input.command;
5918
- 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);
5919
6136
  const now = Date.now();
5920
- const bypassed = isSilenceCommand(command) && hasBypassMarker$1(command);
6137
+ const silence = isSilenceCommand(command);
6138
+ const bypassed = silence && hasBypassMarker$1(command);
5921
6139
  const streak = recordNoopCommand(state, command, now);
6140
+ if (!silence) return;
5922
6141
  const windowCount = countSilenceInWindow(state, now);
5923
6142
  if (bypassed) return;
5924
6143
  if (streak < 3 && windowCount < 8) return;
5925
6144
  const aborted = streak >= 25 || windowCount >= 40;
5926
- log$8.warn({
6145
+ log$10.warn({
5927
6146
  streak,
5928
6147
  windowCount,
5929
6148
  aborted,
@@ -5941,6 +6160,70 @@ const noopLoopGuardExtension = (pi) => {
5941
6160
  });
5942
6161
  };
5943
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
5944
6227
  //#region src/extensions/sleep-guard.ts
5945
6228
  /**
5946
6229
  * Foreground sleep guard: block `sleep` commands that hold the turn open.
@@ -5990,7 +6273,7 @@ const noopLoopGuardExtension = (pi) => {
5990
6273
  * embedding a script).
5991
6274
  */
5992
6275
  const execFileP = promisify(execFile);
5993
- const log$7 = logger.child({ module: "sleep-guard" });
6276
+ const log$8 = logger.child({ module: "sleep-guard" });
5994
6277
  /** How long the `platform automation create` call may take before we fall back to guidance. */
5995
6278
  const SCHEDULE_TIMEOUT_MS = 15e3;
5996
6279
  /** Title for the one-shot wakes this guard schedules. Visible in the Routines UI. */
@@ -6234,7 +6517,7 @@ async function scheduleSleepWake(seconds, ledger) {
6234
6517
  ], { timeout: SCHEDULE_TIMEOUT_MS });
6235
6518
  return at;
6236
6519
  } catch (err) {
6237
- 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");
6238
6521
  return null;
6239
6522
  }
6240
6523
  }
@@ -6255,7 +6538,7 @@ const sleepGuardExtension = (pi) => {
6255
6538
  if (typeof command !== "string" || command.length === 0) return;
6256
6539
  const violation = shouldBlockForSleep(command);
6257
6540
  if (!violation) return;
6258
- log$7.warn({
6541
+ log$8.warn({
6259
6542
  seconds: violation.seconds,
6260
6543
  leading: violation.leading,
6261
6544
  unboundedLoop: violation.unboundedLoop,
@@ -6264,7 +6547,7 @@ const sleepGuardExtension = (pi) => {
6264
6547
  if (!violation.unboundedLoop && violation.seconds <= 86400 && isPureSleepCommand(blankQuotedRegions(command))) {
6265
6548
  const at = await scheduleSleepWake(violation.seconds, wakeLedger);
6266
6549
  if (at) {
6267
- log$7.info({
6550
+ log$8.info({
6268
6551
  at,
6269
6552
  seconds: violation.seconds
6270
6553
  }, "auto-scheduled sleep wake");
@@ -6372,7 +6655,7 @@ function transformContextMessages(messages, config, now) {
6372
6655
  }
6373
6656
  //#endregion
6374
6657
  //#region src/extensions/context-management.ts
6375
- const log$6 = logger.child({ module: "context-management-extension" });
6658
+ const log$7 = logger.child({ module: "context-management-extension" });
6376
6659
  function isAnthropicMessagesPayload(payload) {
6377
6660
  if (typeof payload !== "object" || payload === null) return false;
6378
6661
  const candidate = payload;
@@ -6437,13 +6720,13 @@ function createContextManagementExtension() {
6437
6720
  setContextManagementFlagOverride(getPolledFlag("contextManagement"));
6438
6721
  onFlagChange("contextManagement", (enabled) => {
6439
6722
  setContextManagementFlagOverride(enabled);
6440
- log$6.info({
6723
+ log$7.info({
6441
6724
  event: "context_management_flag_update",
6442
6725
  enabled
6443
6726
  }, "context-management flag updated from platform");
6444
6727
  });
6445
6728
  startFeatureFlagPoller();
6446
- log$6.info({
6729
+ log$7.info({
6447
6730
  event: "context_management_registered",
6448
6731
  enabled: initial.enabled,
6449
6732
  flagSource: hasFlagSource(),
@@ -6455,13 +6738,13 @@ function createContextManagementExtension() {
6455
6738
  const { messages } = event;
6456
6739
  try {
6457
6740
  const result = transformContextIfEnabled(messages, getContextManagementConfig(), Date.now());
6458
- 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({
6459
6742
  event: "context_management_applied",
6460
6743
  ...result.stats
6461
6744
  }, "trimmed/cleared tool output before LLM call");
6462
6745
  return { messages: result.messages };
6463
6746
  } catch (err) {
6464
- log$6.error({
6747
+ log$7.error({
6465
6748
  err,
6466
6749
  event: "context_management_transform_failed"
6467
6750
  }, "context transform failed; passing messages through unchanged");
@@ -6473,7 +6756,7 @@ function createContextManagementExtension() {
6473
6756
  }
6474
6757
  //#endregion
6475
6758
  //#region src/extensions/current-time.ts
6476
- const log$5 = logger.child({ module: "current-time-extension" });
6759
+ const log$6 = logger.child({ module: "current-time-extension" });
6477
6760
  const PI_DATE_LINE = /^Current date:.*$/m;
6478
6761
  function formatCurrentTimeLine(now) {
6479
6762
  return `Current date: ${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")} (${new Intl.DateTimeFormat("en-US", {
@@ -6486,7 +6769,7 @@ const currentTimeExtension = (pi) => {
6486
6769
  const line = formatCurrentTimeLine(/* @__PURE__ */ new Date());
6487
6770
  const base = event.systemPrompt;
6488
6771
  if (PI_DATE_LINE.test(base)) {
6489
- 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)");
6490
6773
  return { systemPrompt: base.replace(PI_DATE_LINE, line) };
6491
6774
  }
6492
6775
  return { systemPrompt: `${base}\n${line}` };
@@ -6874,7 +7157,7 @@ async function migrateMemory({ cwd }) {
6874
7157
  }
6875
7158
  //#endregion
6876
7159
  //#region src/extensions/memory.ts
6877
- const log$4 = logger.child({ module: "memory-extension" });
7160
+ const log$5 = logger.child({ module: "memory-extension" });
6878
7161
  /**
6879
7162
  * The standing instructions for the memory system. Always injected (even with
6880
7163
  * no `MEMORY.md`) so the agent knows it can persist notes and how. `users/` is
@@ -6911,13 +7194,13 @@ const memoryExtension = (pi) => {
6911
7194
  pi.on("session_start", async (_event, ctx) => {
6912
7195
  try {
6913
7196
  const migrated = await migrateMemory({ cwd: ctx.cwd });
6914
- if (migrated !== null) log$4.info({
7197
+ if (migrated !== null) log$5.info({
6915
7198
  event: "memory_migrated",
6916
7199
  from: migrated.from,
6917
7200
  to: migrated.to
6918
7201
  }, "migrated memory layout to current version");
6919
7202
  } catch (err) {
6920
- log$4.warn({
7203
+ log$5.warn({
6921
7204
  err,
6922
7205
  event: "memory_migration_failed"
6923
7206
  }, "memory migration failed; continuing with existing index");
@@ -6929,7 +7212,7 @@ const memoryExtension = (pi) => {
6929
7212
  index
6930
7213
  });
6931
7214
  } catch (err) {
6932
- log$4.warn({
7215
+ log$5.warn({
6933
7216
  err,
6934
7217
  event: "memory_index_failed"
6935
7218
  }, "memory index read failed; injecting instructions only");
@@ -6943,7 +7226,7 @@ const memoryExtension = (pi) => {
6943
7226
  };
6944
7227
  //#endregion
6945
7228
  //#region src/extensions/platform-memory.ts
6946
- const log$3 = logger.child({ module: "platform-memory-extension" });
7229
+ const log$4 = logger.child({ module: "platform-memory-extension" });
6947
7230
  /**
6948
7231
  * Resolve the human on this turn via the API, keyed by the message id.
6949
7232
  * `/sandbox/channel-context` only returns a sender for a platform-known
@@ -6956,13 +7239,13 @@ const log$3 = logger.child({ module: "platform-memory-extension" });
6956
7239
  async function resolveTurnUser(messageId) {
6957
7240
  const client = sandboxClient();
6958
7241
  if (!client) {
6959
- 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");
6960
7243
  return null;
6961
7244
  }
6962
7245
  try {
6963
7246
  const res = await client["channel-context"].$get({ query: { messageId } });
6964
7247
  if (!res.ok) {
6965
- log$3.warn({
7248
+ log$4.warn({
6966
7249
  event: "resolve_turn_user_failed",
6967
7250
  status: res.status
6968
7251
  }, "channel-context returned non-ok; withholding user memory");
@@ -6975,7 +7258,7 @@ async function resolveTurnUser(messageId) {
6975
7258
  displayName: sender.displayName
6976
7259
  };
6977
7260
  } catch (err) {
6978
- log$3.warn({
7261
+ log$4.warn({
6979
7262
  err,
6980
7263
  event: "resolve_turn_user_failed"
6981
7264
  }, "failed to resolve current user; withholding user memory");
@@ -7022,7 +7305,7 @@ function createPlatformMemoryExtension({ channelContext }) {
7022
7305
  user
7023
7306
  });
7024
7307
  } catch (err) {
7025
- log$3.warn({
7308
+ log$4.warn({
7026
7309
  err,
7027
7310
  event: "user_memory_index_failed"
7028
7311
  }, "user memory index build failed; skipping injection");
@@ -7054,7 +7337,7 @@ const providerApiCompatExtension = (pi) => {
7054
7337
  };
7055
7338
  //#endregion
7056
7339
  //#region src/extensions/self-trace.ts
7057
- const log$2 = logger.child({ module: "self-trace-extension" });
7340
+ const log$3 = logger.child({ module: "self-trace-extension" });
7058
7341
  /**
7059
7342
  * Reports the agent's own execution as OpenTelemetry spans:
7060
7343
  * agent.session → agent.run → agent.turn.N → tool.NAME, with token/cost
@@ -7079,7 +7362,7 @@ const selfTraceExtension = (pi) => {
7079
7362
  sessionSpan = tracer.startSpan("agent.session", { attributes: { "agent.model": modelId } }, remoteCtx);
7080
7363
  sessionCtx = trace.setSpan(remoteCtx, sessionSpan);
7081
7364
  const sc = sessionSpan.spanContext();
7082
- log$2.info({
7365
+ log$3.info({
7083
7366
  event: "self_trace_session_start",
7084
7367
  trace_id: sc.traceId,
7085
7368
  span_id: sc.spanId,
@@ -7191,13 +7474,13 @@ const selfTraceExtension = (pi) => {
7191
7474
  * Lives in the harness package — soul.md is content from the agent's
7192
7475
  * own git repo, not from the platform — so its handling stays here.
7193
7476
  */
7194
- const log$1 = logger.child({ module: "soul-extension" });
7477
+ const log$2 = logger.child({ module: "soul-extension" });
7195
7478
  async function readSoul(cwd) {
7196
7479
  try {
7197
7480
  return (await readFile(join(cwd, "soul.md"), "utf8")).trim() || null;
7198
7481
  } catch (err) {
7199
7482
  if (err?.code === "ENOENT") return null;
7200
- log$1.warn({
7483
+ log$2.warn({
7201
7484
  err,
7202
7485
  event: "soul_read_failed"
7203
7486
  }, "soul.md read failed");
@@ -7229,7 +7512,7 @@ const soulExtension = (pi) => {
7229
7512
  };
7230
7513
  //#endregion
7231
7514
  //#region src/extensions/subagent/index.ts
7232
- const log = logger.child({ module: "subagent-ext" });
7515
+ const log$1 = logger.child({ module: "subagent-ext" });
7233
7516
  const MAX_TASKS = 8;
7234
7517
  const SpawnTaskItem = Type.Object({
7235
7518
  task: Type.String({ description: "The task to delegate to a subagent run." }),
@@ -7329,7 +7612,7 @@ function buildTool(messageId) {
7329
7612
  };
7330
7613
  } catch (err) {
7331
7614
  const message = err instanceof Error ? err.message : String(err);
7332
- log.warn({
7615
+ log$1.warn({
7333
7616
  err,
7334
7617
  event: "subagent_rearm_failed",
7335
7618
  taskId: task.taskId
@@ -7342,7 +7625,7 @@ function buildTool(messageId) {
7342
7625
  }
7343
7626
  }));
7344
7627
  const { taskIds } = spawned;
7345
- log.info({
7628
+ log$1.info({
7346
7629
  event: "subagent_spawned",
7347
7630
  count: taskIds.length
7348
7631
  }, "subagent tasks queued");
@@ -7373,7 +7656,7 @@ function buildTool(messageId) {
7373
7656
  };
7374
7657
  } catch (err) {
7375
7658
  const message = err instanceof Error ? err.message : String(err);
7376
- log.warn({
7659
+ log$1.warn({
7377
7660
  err,
7378
7661
  event: "subagent_spawn_failed"
7379
7662
  }, "subagent request failed");
@@ -7404,7 +7687,7 @@ function createSubagentExtension({ channelContext }) {
7404
7687
  if (registered) return;
7405
7688
  registered = true;
7406
7689
  pi.registerTool(buildTool(messageId));
7407
- log.info({ event: "subagent_enabled" }, "subagent tool registered");
7690
+ log$1.info({ event: "subagent_enabled" }, "subagent tool registered");
7408
7691
  };
7409
7692
  pi.on("session_start", () => {
7410
7693
  registerOnce();
@@ -7412,6 +7695,125 @@ function createSubagentExtension({ channelContext }) {
7412
7695
  };
7413
7696
  }
7414
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
7415
7817
  //#region src/extensions/tool-history.ts
7416
7818
  const VALID_NAME_RE = /^[a-zA-Z0-9_-]+$/;
7417
7819
  function isValidToolName(name) {
@@ -7553,6 +7955,7 @@ const all = [
7553
7955
  bashDefaultTimeoutExtension,
7554
7956
  diskGuardExtension,
7555
7957
  noopLoopGuardExtension,
7958
+ repeatCallGuardExtension,
7556
7959
  sleepGuardExtension,
7557
7960
  toolCallSummaryExtension
7558
7961
  ];
@@ -7579,6 +7982,7 @@ function platformExtensions({ sessionId, channelContext }) {
7579
7982
  createSubagentExtension({ channelContext }),
7580
7983
  createContextManagementExtension(),
7581
7984
  resourcePressureWarningExtension,
7985
+ templateBuildPushExtension,
7582
7986
  tool_history_default
7583
7987
  ];
7584
7988
  }