@skydiveai/pi-extensions 0.1.0-beta.252 → 0.1.0-beta.2525

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2,25 +2,29 @@ import { createRequire } from "node:module";
2
2
  import { DefaultExecutionEventBusManager, DefaultRequestHandler, InMemoryTaskStore } from "@a2a-js/sdk/server";
3
3
  import { UserBuilder, restHandler } from "@a2a-js/sdk/server/express";
4
4
  import { buildAgentCard, chainMiddleware, composeHandlers, createAgentExecutor, createProtocolHandlers, getCurrentTraceparent, logger, mountAt, requestHeaders, requestUrl, webHandlerToMiddleware } from "@skydiveai/pi-server";
5
- import { mkdir, open, readFile, readdir, stat, unlink } from "node:fs/promises";
5
+ import { mkdir, open, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, join, relative, resolve } from "node:path";
7
7
  import { z } from "zod";
8
8
  import { pathToFileURL } from "node:url";
9
9
  import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
10
10
  import { Type } from "typebox";
11
11
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
12
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
12
+ import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
13
13
  import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
14
14
  import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
15
15
  import { Check, Errors } from "typebox/value";
16
+ import { hc } from "hono/client";
16
17
  import { ROOT_CONTEXT, SpanStatusCode, propagation, trace } from "@opentelemetry/api";
17
18
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
18
19
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
19
20
  import { Resource } from "@opentelemetry/resources";
20
21
  import { BatchSpanProcessor, NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
21
22
  import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
22
- import { hc } from "hono/client";
23
+ import { execFile } from "node:child_process";
24
+ import { availableParallelism } from "node:os";
25
+ import { promisify } from "node:util";
23
26
  import { parse } from "yaml";
27
+ import { getModels } from "@earendil-works/pi-ai";
24
28
  import { quote } from "shell-quote";
25
29
  import { createWriteStream } from "node:fs";
26
30
  import { finished } from "node:stream/promises";
@@ -256,7 +260,7 @@ function createHealthHandler({ metadata }) {
256
260
  * read on the hot path before every LLM call), it falls back to the default
257
261
  * for that knob and logs once.
258
262
  */
259
- const log$13 = logger.child({ module: "context-management-config" });
263
+ const log$15 = logger.child({ module: "context-management-config" });
260
264
  const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
261
265
  enabled: false,
262
266
  perResultMaxBytes: 16 * 1024,
@@ -304,7 +308,7 @@ function resolveContextManagementConfig(env = process.env) {
304
308
  maxModelCallsPerTurn: env.SKYDIVE_CTX_MAX_MODEL_CALLS
305
309
  });
306
310
  if (!parsed.success) {
307
- log$13.warn({
311
+ log$15.warn({
308
312
  event: "context_management_config_invalid",
309
313
  err: parsed.error
310
314
  }, "falling back to default context-management config");
@@ -415,6 +419,275 @@ function installIterationCap({ session, log }, configOverride = null) {
415
419
  */
416
420
  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).";
417
421
  //#endregion
422
+ //#region src/extensions/tool-call-summary.ts
423
+ const log$14 = logger.child({ module: "tool-call-summary-extension" });
424
+ /**
425
+ * The injected parameter name: a namespaced sentinel, so it can never collide
426
+ * with a real tool argument and is unmistakable in transcripts and logs. The
427
+ * frontend renderer (ANY-2723) duplicates this literal — keep the two in sync.
428
+ */
429
+ const TOOL_CALL_SUMMARY_FIELD = "__skydive_summary__";
430
+ /** JSON Schema fragment for the injected parameter. */
431
+ const SUMMARY_PROPERTY = {
432
+ type: "string",
433
+ description: "Required for every tool call. A concise, specific summary (max ~8 words) of what THIS call does and why, written for a person watching the conversation, e.g. \"Searching feedback for billing complaints\" or \"Reading the auth middleware\". Address the user directly in second person: the summary is read by the user, so refer to their things as \"your\", never in third person — \"Reading your emails\", not \"Reading his emails\". Always use the present progressive tense, since it is shown while the call runs: \"Updating your Slack\", never \"Updated your Slack\". Make each summary distinct from your other tool calls; never reuse a generic label like \"Search query\" or \"Running command\"."
434
+ };
435
+ const jsonSchemaObjectSchema = z.object({
436
+ type: z.unknown().optional(),
437
+ properties: z.record(z.string(), z.unknown()).optional(),
438
+ required: z.array(z.string()).optional(),
439
+ additionalProperties: z.unknown().optional()
440
+ }).passthrough();
441
+ const toolEntrySchema = z.object({
442
+ name: z.string().optional(),
443
+ input_schema: jsonSchemaObjectSchema.optional(),
444
+ parameters: jsonSchemaObjectSchema.optional(),
445
+ function: z.object({
446
+ name: z.string().optional(),
447
+ parameters: jsonSchemaObjectSchema.optional()
448
+ }).passthrough().optional()
449
+ }).passthrough();
450
+ const payloadWithToolsSchema = z.object({ tools: z.array(z.unknown()) }).passthrough();
451
+ /**
452
+ * Add the summary property to one JSON Schema object. Returns the augmented
453
+ * copy, or `null` when the tool should be left untouched: a strict schema
454
+ * (`additionalProperties: false`) whose validation would reject the extra
455
+ * field, or one that already declares a `__skydive_summary__` property of its own.
456
+ */
457
+ function augmentSchema(schema) {
458
+ if (schema.additionalProperties === false) return null;
459
+ const properties = schema.properties ?? {};
460
+ if ("__skydive_summary__" in properties) return null;
461
+ const required = schema.required ?? [];
462
+ return {
463
+ ...schema,
464
+ type: schema.type ?? "object",
465
+ properties: {
466
+ [TOOL_CALL_SUMMARY_FIELD]: SUMMARY_PROPERTY,
467
+ ...properties
468
+ },
469
+ required: required.includes("__skydive_summary__") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
470
+ };
471
+ }
472
+ /**
473
+ * Augment a single tool entry, dispatching on which provider shape it is.
474
+ * Returns the (possibly rebuilt) entry and whether anything changed. Skipped
475
+ * tools — wrong shape, strict, or name in `strictToolNames` — return unchanged.
476
+ */
477
+ function augmentToolEntry(entry, strictToolNames) {
478
+ const parsed = toolEntrySchema.safeParse(entry);
479
+ if (!parsed.success) return {
480
+ entry,
481
+ changed: false
482
+ };
483
+ const tool = parsed.data;
484
+ const name = tool.name ?? tool.function?.name ?? null;
485
+ if (name !== null && strictToolNames.has(name)) return {
486
+ entry,
487
+ changed: false
488
+ };
489
+ if (tool.input_schema) {
490
+ const augmented = augmentSchema(tool.input_schema);
491
+ if (!augmented) return {
492
+ entry,
493
+ changed: false
494
+ };
495
+ return {
496
+ entry: {
497
+ ...tool,
498
+ input_schema: augmented
499
+ },
500
+ changed: true
501
+ };
502
+ }
503
+ if (tool.parameters) {
504
+ const augmented = augmentSchema(tool.parameters);
505
+ if (!augmented) return {
506
+ entry,
507
+ changed: false
508
+ };
509
+ return {
510
+ entry: {
511
+ ...tool,
512
+ parameters: augmented
513
+ },
514
+ changed: true
515
+ };
516
+ }
517
+ if (tool.function?.parameters) {
518
+ const augmented = augmentSchema(tool.function.parameters);
519
+ if (!augmented) return {
520
+ entry,
521
+ changed: false
522
+ };
523
+ return {
524
+ entry: {
525
+ ...tool,
526
+ function: {
527
+ ...tool.function,
528
+ parameters: augmented
529
+ }
530
+ },
531
+ changed: true
532
+ };
533
+ }
534
+ return {
535
+ entry,
536
+ changed: false
537
+ };
538
+ }
539
+ /**
540
+ * Inject the summary field into every eligible tool in a provider payload.
541
+ * Returns a new payload when at least one tool was augmented, or `undefined`
542
+ * to signal "no change" (which keeps the original payload, per the
543
+ * `before_provider_request` contract).
544
+ *
545
+ * @param payload The outgoing provider payload (shape varies by provider).
546
+ * @param strictToolNames Names of tools whose registered schema is strict and
547
+ * must be skipped to avoid validation errors.
548
+ */
549
+ function injectToolCallSummary(payload, strictToolNames) {
550
+ const parsed = payloadWithToolsSchema.safeParse(payload);
551
+ if (!parsed.success || parsed.data.tools.length === 0) return void 0;
552
+ let changed = false;
553
+ const tools = parsed.data.tools.map((entry) => {
554
+ const result = augmentToolEntry(entry, strictToolNames);
555
+ if (result.changed) changed = true;
556
+ return result.entry;
557
+ });
558
+ if (!changed) return void 0;
559
+ return {
560
+ ...parsed.data,
561
+ tools
562
+ };
563
+ }
564
+ /**
565
+ * Names of registered tools whose schema sets `additionalProperties: false`.
566
+ * Pi validates the model's tool args against this registered schema, so the
567
+ * injected field would make a strict tool's call fail validation — skip them.
568
+ */
569
+ function getStrictToolNames(pi) {
570
+ const names = /* @__PURE__ */ new Set();
571
+ for (const tool of pi.getAllTools()) {
572
+ const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
573
+ if (parsed.success && parsed.data.additionalProperties === false) names.add(tool.name);
574
+ }
575
+ return names;
576
+ }
577
+ /**
578
+ * Whether a tool's own schema declares a `__skydive_summary__` property. We
579
+ * never inject into such a tool, so any value it carries is a real argument
580
+ * and must be left alone.
581
+ */
582
+ function schemaDeclaresSummary(parameters) {
583
+ const parsed = jsonSchemaObjectSchema.safeParse(parameters);
584
+ return parsed.success && parsed.data.properties != null && "__skydive_summary__" in parsed.data.properties;
585
+ }
586
+ function toolDeclaresSummaryParam(pi, toolName) {
587
+ const tool = pi.getAllTools().find((candidate) => candidate.name === toolName);
588
+ if (!tool) return false;
589
+ return schemaDeclaresSummary(tool.parameters);
590
+ }
591
+ /** A copy of `args` without the injected summary. Never mutates its input. */
592
+ function withoutInjectedSummary(args) {
593
+ if (args == null || typeof args !== "object" || Array.isArray(args)) return args;
594
+ if (!("__skydive_summary__" in args)) return args;
595
+ const { [TOOL_CALL_SUMMARY_FIELD]: _summary, ...rest } = args;
596
+ return rest;
597
+ }
598
+ /**
599
+ * Register a tool so the injected summary is removed *before* pi validates
600
+ * the model's arguments against the tool's schema.
601
+ *
602
+ * Needed because the `tool_call` strip below runs too late. pi-agent-core's
603
+ * `prepareToolCall` goes: `tool.prepareArguments` → `validateToolArguments` →
604
+ * `beforeToolCall` (which is what dispatches `tool_call`). A tool whose schema
605
+ * sets `additionalProperties: false` therefore rejects the summary and errors
606
+ * the call — client-side, before any request reaches the server — while the
607
+ * strip meant to prevent exactly that sits one step further down.
608
+ *
609
+ * `augmentSchema` already skips strict tools, but that only controls what the
610
+ * model is *told*. It still emits the field on those tools, because every
611
+ * other tool in the list declares it as required for every call. So a server
612
+ * can connect, bind its tools, present a healthy inventory, and have every
613
+ * call fail — and it reads as the server's fault when it is ours.
614
+ *
615
+ * Apply to tools registered from schemas we do not author: MCP servers and
616
+ * local `tools/*.ts`. Tools built here with `Type.Object(...)` do not need it
617
+ * (TypeBox emits no `additionalProperties`, so the field validates fine and
618
+ * the `tool_call` strip removes it in time).
619
+ *
620
+ * Fails open, like the rest of this module: if the strip throws, the original
621
+ * arguments are used rather than failing the call.
622
+ */
623
+ function withSummaryStrippedBeforeValidation(tool) {
624
+ if (schemaDeclaresSummary(tool.parameters)) return tool;
625
+ const toolPrepare = tool.prepareArguments;
626
+ const prepareArguments = ((args) => {
627
+ let stripped = args;
628
+ try {
629
+ stripped = withoutInjectedSummary(args);
630
+ } catch (err) {
631
+ log$14.error({
632
+ err,
633
+ event: "tool_call_summary_prepare_strip_failed",
634
+ toolName: tool.name
635
+ }, "tool_call_summary pre-validation strip failed; leaving arguments untouched");
636
+ }
637
+ return toolPrepare ? toolPrepare(stripped) : stripped;
638
+ });
639
+ return {
640
+ ...tool,
641
+ prepareArguments
642
+ };
643
+ }
644
+ /**
645
+ * Remove the injected summary from a tool's execution input. No-op when the
646
+ * field is absent, or when the tool genuinely declares a `__skydive_summary__`
647
+ * parameter of its own (which we never inject into, so its value is real).
648
+ * Mutates `input` in place, matching the `tool_call` contract.
649
+ *
650
+ * Fails open: this runs on the critical path of tool execution, and the
651
+ * `getAllTools()` lookup can throw. On any error we leave `input` untouched
652
+ * (the sentinel may pass through to the tool, but a bug here can never break
653
+ * tool execution).
654
+ */
655
+ function stripInjectedSummary(pi, toolName, input) {
656
+ try {
657
+ if (!("__skydive_summary__" in input)) return;
658
+ if (toolDeclaresSummaryParam(pi, toolName)) return;
659
+ delete input[TOOL_CALL_SUMMARY_FIELD];
660
+ } catch (err) {
661
+ log$14.error({
662
+ err,
663
+ event: "tool_call_summary_strip_failed",
664
+ toolName
665
+ }, "tool_call_summary strip failed; leaving tool input untouched");
666
+ }
667
+ }
668
+ /**
669
+ * Compute the rewritten payload for a `before_provider_request` event, failing
670
+ * open: on any error the original payload is left untouched so a bug here can
671
+ * never break an LLM call.
672
+ */
673
+ function buildInjectedPayload(pi, payload) {
674
+ try {
675
+ return injectToolCallSummary(payload, getStrictToolNames(pi));
676
+ } catch (err) {
677
+ log$14.error({
678
+ err,
679
+ event: "tool_call_summary_injection_failed"
680
+ }, "tool_call_summary injection failed; passing payload through unchanged");
681
+ return;
682
+ }
683
+ }
684
+ const toolCallSummaryExtension = (pi) => {
685
+ pi.on("before_provider_request", (event) => buildInjectedPayload(pi, event.payload));
686
+ pi.on("tool_call", (event) => {
687
+ stripInjectedSummary(pi, event.toolName, event.input);
688
+ });
689
+ };
690
+ //#endregion
418
691
  //#region src/extensions/local-tools.ts
419
692
  /**
420
693
  * Local-tools adapter as a pi extension. Mirrors the mcp.ts hot-reload pattern
@@ -438,7 +711,7 @@ const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task i
438
711
  * or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
439
712
  * `tools/_example.ts` documents the shape without registering.
440
713
  */
441
- const log$12 = logger.child({ module: "local-tools-extension" });
714
+ const log$13 = logger.child({ module: "local-tools-extension" });
442
715
  const TOOLS_DIRNAME = "tools";
443
716
  const fileState = /* @__PURE__ */ new Map();
444
717
  let pendingLocalToolsUpdate = null;
@@ -565,7 +838,7 @@ async function reconcileLocalTools({ pi, dir }) {
565
838
  action = existing ? "refreshed" : "added";
566
839
  }
567
840
  for (const tool of tools) {
568
- pi.registerTool(withDefaultPromptSnippet(tool));
841
+ pi.registerTool(withSummaryStrippedBeforeValidation(withDefaultPromptSnippet(tool)));
569
842
  summary.totalTools++;
570
843
  }
571
844
  if (action === "added") summary.added.push(file);
@@ -582,7 +855,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
582
855
  dir
583
856
  });
584
857
  if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
585
- log$12.info({
858
+ log$13.info({
586
859
  event: "local_tools_reconcile",
587
860
  reason,
588
861
  total_tools: summary.totalTools,
@@ -604,7 +877,7 @@ const localToolsExtension = (pi) => {
604
877
  reason: "session_start"
605
878
  });
606
879
  } catch (err) {
607
- log$12.error({
880
+ log$13.error({
608
881
  err,
609
882
  event: "local_tools_reconcile_failed"
610
883
  }, "local tools reconcile failed");
@@ -616,7 +889,7 @@ const localToolsExtension = (pi) => {
616
889
  try {
617
890
  current = await listToolFiles(dir);
618
891
  } catch (err) {
619
- log$12.warn({
892
+ log$13.warn({
620
893
  err,
621
894
  event: "local_tools_listing_failed"
622
895
  }, "tools/ listing failed");
@@ -638,7 +911,7 @@ const localToolsExtension = (pi) => {
638
911
  reason: "auto_reload"
639
912
  });
640
913
  } catch (err) {
641
- log$12.error({
914
+ log$13.error({
642
915
  err,
643
916
  event: "local_tools_auto_reload_failed"
644
917
  }, "auto-reload after tools/ change failed");
@@ -682,8 +955,80 @@ function createStderrBuffer({ maxBytes }) {
682
955
  * The transport stays alive — caller holds the client so the bridge's
683
956
  * callback server keeps listening and a later reconcile re-probes.
684
957
  */
958
+ var SkipOutputSchemaValidation = class {
959
+ getValidator(_schema) {
960
+ return (input) => ({
961
+ valid: true,
962
+ data: input,
963
+ errorMessage: void 0
964
+ });
965
+ }
966
+ };
967
+ const skipOutputSchemaValidation = new SkipOutputSchemaValidation();
685
968
  const DEFAULT_CONNECT_TIMEOUT_MS = 5e3;
686
969
  const STDERR_BUFFER_BYTES = 4096;
970
+ const SESSION_NOT_FOUND_RETRY_DELAYS_MS = [
971
+ 250,
972
+ 500,
973
+ 1e3,
974
+ 2e3,
975
+ 4e3,
976
+ 8e3
977
+ ];
978
+ function delay(ms) {
979
+ return new Promise((resolve) => setTimeout(resolve, ms));
980
+ }
981
+ async function fetchWithSessionNotFoundRetry(input, init) {
982
+ for (let attempt = 0;; attempt += 1) {
983
+ const response = await fetch(input, init);
984
+ const sessionId = new Headers(init?.headers).get("mcp-session-id");
985
+ const retryDelay = SESSION_NOT_FOUND_RETRY_DELAYS_MS[attempt];
986
+ if (!sessionId || response.status !== 404 || retryDelay === void 0 || !(await response.clone().text()).includes("session_not_found")) return response;
987
+ await response.body?.cancel();
988
+ await delay(retryDelay);
989
+ }
990
+ }
991
+ /**
992
+ * Sandbox egress variables a stdio MCP server needs to make outbound HTTPS
993
+ * calls. The SDK's default child environment is a tiny whitelist (HOME,
994
+ * LOGNAME, PATH, SHELL, TERM, USER on Linux), which drops NODE_EXTRA_CA_CERTS
995
+ * — but the sandbox's egress proxy terminates TLS with a private CA, so a
996
+ * child spawned without it fails every HTTPS request with a bare
997
+ * `fetch failed` (cause: UNABLE_TO_VERIFY_LEAF_SIGNATURE) that looks like the
998
+ * remote service is down. Same story for SSL_CERT_FILE (OpenSSL-based
999
+ * runtimes) and the *_PROXY set. Inherit them from this process so a stdio
1000
+ * server gets working egress like every other process in the sandbox.
1001
+ */
1002
+ const INHERITED_EGRESS_ENV_VARS = [
1003
+ "NODE_EXTRA_CA_CERTS",
1004
+ "SSL_CERT_FILE",
1005
+ "SSL_CERT_DIR",
1006
+ "REQUESTS_CA_BUNDLE",
1007
+ "CURL_CA_BUNDLE",
1008
+ "HTTP_PROXY",
1009
+ "HTTPS_PROXY",
1010
+ "NO_PROXY",
1011
+ "http_proxy",
1012
+ "https_proxy",
1013
+ "no_proxy"
1014
+ ];
1015
+ /**
1016
+ * Environment for a stdio MCP server child: the SDK's safe defaults, plus the
1017
+ * sandbox's egress/TLS variables, plus (last, so it wins) the server's own
1018
+ * configured `env`. Building the merge here — instead of only when `env` is
1019
+ * unset — also fixes the workaround trap where supplying any `env` in
1020
+ * mcp.config.json silently replaced the ENTIRE default set, so a config that
1021
+ * added one API key lost PATH/HOME and the server failed to spawn at all.
1022
+ */
1023
+ function buildStdioEnv(configured, processEnv = process.env) {
1024
+ const env = { ...getDefaultEnvironment() };
1025
+ for (const key of INHERITED_EGRESS_ENV_VARS) {
1026
+ const value = processEnv[key];
1027
+ if (value !== void 0) env[key] = value;
1028
+ }
1029
+ if (configured) Object.assign(env, configured);
1030
+ return env;
1031
+ }
687
1032
  /**
688
1033
  * undici's fetch throws `TypeError: fetch failed` with the actual
689
1034
  * network error hung off `.cause` (e.g. `getaddrinfo ENOTFOUND ...`,
@@ -692,6 +1037,19 @@ const STDERR_BUFFER_BYTES = 4096;
692
1037
  * indistinguishable from any other transport problem. Walk the cause
693
1038
  * chain so the agent sees the real underlying error.
694
1039
  */
1040
+ /**
1041
+ * True when an error from an http MCP transport (connect, listTools, or a tool
1042
+ * call) is an authentication failure. With no authProvider configured the SDK
1043
+ * surfaces a 401 as `StreamableHTTPError(401)`; older paths translate it to
1044
+ * `UnauthorizedError`. A dead/expired OAuth token (the proxy can no longer
1045
+ * mint one) shows up here on the NEXT request against a previously-connected
1046
+ * client — not just at connect — so reconcile must re-classify such a failure
1047
+ * as `pending_auth` instead of a generic `failed`, keeping the "waiting on
1048
+ * auth" report consistent with `platform auth`.
1049
+ */
1050
+ function isUnauthorizedError(err) {
1051
+ return err instanceof UnauthorizedError || err instanceof StreamableHTTPError && err.code === 401;
1052
+ }
695
1053
  function formatError(err) {
696
1054
  if (!(err instanceof Error)) return String(err);
697
1055
  const parts = [err.message];
@@ -703,8 +1061,20 @@ function formatError(err) {
703
1061
  }
704
1062
  return parts.join(": ");
705
1063
  }
1064
+ function probeAlive(pid) {
1065
+ if (pid === null) return null;
1066
+ try {
1067
+ process.kill(pid, 0);
1068
+ return true;
1069
+ } catch {
1070
+ return false;
1071
+ }
1072
+ }
706
1073
  async function connectHttp(_id, config, client) {
707
- const transport = new StreamableHTTPClientTransport(new URL(config.url), { ...config.headers !== null ? { requestInit: { headers: config.headers } } : {} });
1074
+ const transport = new StreamableHTTPClientTransport(new URL(config.url), {
1075
+ ...config.headers !== null ? { requestInit: { headers: config.headers } } : {},
1076
+ fetch: fetchWithSessionNotFoundRetry
1077
+ });
708
1078
  try {
709
1079
  await client.connect(transport);
710
1080
  return {
@@ -713,12 +1083,12 @@ async function connectHttp(_id, config, client) {
713
1083
  stderr: null
714
1084
  };
715
1085
  } catch (err) {
716
- if (err instanceof UnauthorizedError || err instanceof StreamableHTTPError && err.code === 401) return {
1086
+ if (isUnauthorizedError(err)) return {
717
1087
  status: "pending_auth",
718
1088
  client,
719
1089
  stderr: "",
720
1090
  stderrBuffer: null,
721
- cliHint: `platform auth mcp ${config.url}`
1091
+ cliHint: `platform auth mcp ${config.url} --service "<Product>"`
722
1092
  };
723
1093
  return {
724
1094
  status: "failed",
@@ -732,14 +1102,17 @@ async function connectClient(id, config, opts = {}) {
732
1102
  const client = new Client({
733
1103
  name: "skydive-harness",
734
1104
  version: "0.1.0"
735
- }, { capabilities: {} });
1105
+ }, {
1106
+ capabilities: {},
1107
+ jsonSchemaValidator: skipOutputSchemaValidation
1108
+ });
736
1109
  if (config.transport === "http") return connectHttp(id, config, client);
737
1110
  const params = {
738
1111
  command: config.command,
739
1112
  args: config.args,
740
- stderr: "pipe"
1113
+ stderr: "pipe",
1114
+ env: buildStdioEnv(config.env)
741
1115
  };
742
- if (config.env !== null) params.env = config.env;
743
1116
  if (config.cwd !== null) params.cwd = config.cwd;
744
1117
  const transport = new StdioClientTransport(params);
745
1118
  const stderrBuffer = createStderrBuffer({ maxBytes: STDERR_BUFFER_BYTES });
@@ -751,6 +1124,10 @@ async function connectClient(id, config, opts = {}) {
751
1124
  resolve();
752
1125
  };
753
1126
  });
1127
+ let stdoutMessages = 0;
1128
+ transport.onmessage = () => {
1129
+ if (stdoutMessages < 1e4) stdoutMessages += 1;
1130
+ };
754
1131
  const connectPromise = client.connect(transport);
755
1132
  const TIMEOUT_SENTINEL = Symbol("timeout");
756
1133
  const result = await Promise.race([
@@ -768,12 +1145,20 @@ async function connectClient(id, config, opts = {}) {
768
1145
  error: `server "${id}" exited before completing initialize`,
769
1146
  stderr: stderrBuffer.read()
770
1147
  };
771
- if (result === TIMEOUT_SENTINEL) return {
772
- status: "timeout",
773
- client,
774
- stderr: stderrBuffer.read(),
775
- stderrBuffer
776
- };
1148
+ if (result === TIMEOUT_SENTINEL) {
1149
+ const pid = transport.pid;
1150
+ return {
1151
+ status: "timeout",
1152
+ client,
1153
+ stderr: stderrBuffer.read(),
1154
+ stderrBuffer,
1155
+ diagnostics: {
1156
+ pid,
1157
+ alive: probeAlive(pid),
1158
+ stdoutMessages
1159
+ }
1160
+ };
1161
+ }
777
1162
  try {
778
1163
  await client.close();
779
1164
  } catch {}
@@ -784,7 +1169,127 @@ async function connectClient(id, config, opts = {}) {
784
1169
  };
785
1170
  }
786
1171
  //#endregion
787
- //#region src/extensions/mcp/mcp-config.ts
1172
+ //#region src/extensions/mcp/limits.ts
1173
+ /**
1174
+ * Tool-budget guardrails for MCP registration.
1175
+ *
1176
+ * Why this exists: the agent loop sends the *full* tool list — every tool's
1177
+ * name, description, and JSON-schema `parameters` — to the model on every
1178
+ * prompt. MCP servers add tools without bound: a handful of chatty servers (or
1179
+ * one server that exposes 100+ tools, or a few tools with enormous schemas) can
1180
+ * push the registered set past what the model can accept, and the request is
1181
+ * rejected before the turn even runs. Because `reconcile` re-registers from
1182
+ * `mcp.config.json` on *every* turn, an over-limit config bricks the harness on
1183
+ * a loop — the agent can't get a turn to run in order to edit the config back
1184
+ * down. Worse, the person can't tell *why*: tools just stop working.
1185
+ *
1186
+ * What actually overflows the request is *tokens*, not tool count — a few tools
1187
+ * with deeply-nested schemas and long descriptions cost more than a hundred
1188
+ * trivial ones. And how many tokens are safe depends on the *model*: a 200K
1189
+ * context window can afford far more tool surface than a 32K one. So the primary
1190
+ * limiter is a **token budget derived from the active model's context window**,
1191
+ * with a fixed tool-count cap as a coarse secondary guard (and the fallback
1192
+ * when the model — hence its window — isn't known at reconcile time).
1193
+ *
1194
+ * The fix is to make registration bounded and fail-soft. We register in
1195
+ * deterministic config order and stop before we blow the budget, recording how
1196
+ * much we dropped so the agent is *told* it hit the limit and which servers
1197
+ * were truncated. A config that would have bricked the harness now degrades to
1198
+ * "a bounded set of tools plus a loud warning", which the agent can act on by
1199
+ * pruning servers.
1200
+ *
1201
+ * Everything is env-overridable so the ceilings can be tuned per deployment
1202
+ * without a release, but ships with conservative defaults. A cap value of 0 (or
1203
+ * a non-finite / negative override) disables that cap — an explicit escape
1204
+ * hatch, not the default.
1205
+ */
1206
+ const env = process.env;
1207
+ /**
1208
+ * Fraction of the model's context window we're willing to spend on MCP tool
1209
+ * schemas. Tool definitions are sent on every prompt, so they permanently eat
1210
+ * into the window available for the conversation, but a generous tool budget is
1211
+ * worth more than a marginally larger conversation window given how the harness
1212
+ * is used. 0.35 of a 200K window is ~70K tokens of tool schema, comfortably
1213
+ * more than any sane MCP setup; of a 32K window it's ~11.2K, which still forces
1214
+ * truncation before a small model chokes.
1215
+ */
1216
+ const DEFAULT_MCP_TOOL_TOKEN_BUDGET_FRACTION = .35;
1217
+ /**
1218
+ * Floor for the token budget when the model's context window is unknown at
1219
+ * reconcile time (e.g. the model hasn't been resolved yet). Generous enough not
1220
+ * to truncate an ordinary tool set, low enough to still catch a runaway.
1221
+ */
1222
+ const DEFAULT_MCP_TOOL_TOKEN_BUDGET_FLOOR = 16e3;
1223
+ /**
1224
+ * Read a positive-integer cap from an env var, falling back to `fallback`.
1225
+ * A `0` override (or any non-finite / negative value) means "no cap" and is
1226
+ * returned as `Infinity`, so callers can compare against it directly.
1227
+ */
1228
+ function readCap(raw, fallback) {
1229
+ if (raw === void 0 || raw.trim() === "") return fallback;
1230
+ const parsed = Number(raw);
1231
+ if (!Number.isFinite(parsed) || parsed < 0) return Number.POSITIVE_INFINITY;
1232
+ if (parsed === 0) return Number.POSITIVE_INFINITY;
1233
+ return Math.floor(parsed);
1234
+ }
1235
+ /** Read a fraction in (0, 1] from an env var, falling back to `fallback`. */
1236
+ function readFraction(raw, fallback) {
1237
+ if (raw === void 0 || raw.trim() === "") return fallback;
1238
+ const parsed = Number(raw);
1239
+ if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1) return fallback;
1240
+ return parsed;
1241
+ }
1242
+ /** Read a non-negative integer from an env var, falling back to `fallback`. */
1243
+ function readNonNegativeInt(raw, fallback) {
1244
+ if (raw === void 0 || raw.trim() === "") return fallback;
1245
+ const parsed = Number(raw);
1246
+ if (!Number.isFinite(parsed) || parsed < 0) return fallback;
1247
+ return Math.floor(parsed);
1248
+ }
1249
+ /**
1250
+ * Resolve the active caps from the environment. Read once per reconcile so a
1251
+ * deployment can retune without a restart, cheap enough not to cache.
1252
+ */
1253
+ function resolveMcpToolLimits() {
1254
+ return {
1255
+ maxTotalTools: readCap(env["SKYDIVE_MCP_MAX_TOTAL_TOOLS"], 128),
1256
+ maxToolsPerServer: readCap(env["SKYDIVE_MCP_MAX_TOOLS_PER_SERVER"], 50),
1257
+ tokenBudgetFraction: readFraction(env["SKYDIVE_MCP_TOOL_TOKEN_BUDGET_FRACTION"], DEFAULT_MCP_TOOL_TOKEN_BUDGET_FRACTION),
1258
+ tokenBudgetFloor: readNonNegativeInt(env["SKYDIVE_MCP_TOOL_TOKEN_BUDGET_FLOOR"], DEFAULT_MCP_TOOL_TOKEN_BUDGET_FLOOR)
1259
+ };
1260
+ }
1261
+ /**
1262
+ * The token budget for MCP tool schemas, given the active model's context
1263
+ * window (or undefined when the model isn't known yet).
1264
+ *
1265
+ * With a known window we spend `tokenBudgetFraction` of it, but never less than
1266
+ * the floor — a tiny window shouldn't collapse the budget to near-zero and
1267
+ * strand every tool. With no window we fall back to the floor outright.
1268
+ */
1269
+ function resolveTokenBudget(limits, contextWindow) {
1270
+ if (contextWindow === void 0 || !Number.isFinite(contextWindow)) return limits.tokenBudgetFloor;
1271
+ return Math.max(limits.tokenBudgetFloor, Math.floor(contextWindow * limits.tokenBudgetFraction));
1272
+ }
1273
+ /**
1274
+ * Estimate the tokens an MCP tool's *definition* costs in the request. We
1275
+ * serialize what's actually sent to the model — the tool name, its description,
1276
+ * and its JSON-schema parameters — and apply pi's own ~chars/4 heuristic
1277
+ * (`estimateTokens` in the coding agent uses the same convention; there is no
1278
+ * per-provider tokenizer to lean on, and the provider's real usage is only
1279
+ * known after the response). Rough by design, but it tracks the true cost far
1280
+ * better than a flat per-tool count: a fat schema is charged for its fatness.
1281
+ */
1282
+ function estimateToolTokens(tool) {
1283
+ let chars = tool.name.length + (tool.description?.length ?? 0);
1284
+ if (tool.inputSchema !== void 0 && tool.inputSchema !== null) try {
1285
+ chars += JSON.stringify(tool.inputSchema).length;
1286
+ } catch {
1287
+ chars += 256;
1288
+ }
1289
+ return Math.ceil(chars / 4);
1290
+ }
1291
+ //#endregion
1292
+ //#region src/extensions/mcp/mcp-config.ts
788
1293
  /**
789
1294
  * mcp.config.json schema + loader. Split out from the extension so it has
790
1295
  * a small, focused unit-test surface (typebox validation, error formatting).
@@ -863,7 +1368,7 @@ async function loadMcpConfig(path) {
863
1368
  * Clients are keyed by JSON-stringified config and reused across
864
1369
  * reloads — only changed configs reconnect.
865
1370
  */
866
- const log$11 = logger.child({ module: "mcp-extension" });
1371
+ const log$12 = logger.child({ module: "mcp-extension" });
867
1372
  async function closeConnected(connected) {
868
1373
  try {
869
1374
  await connected.client.close();
@@ -933,6 +1438,57 @@ function mcpResultToPiContent(result) {
933
1438
  text: "MCP tool returned no content."
934
1439
  }];
935
1440
  }
1441
+ const MAX_ENUM_VALUES_LISTED = 12;
1442
+ function formatEnumValues(values) {
1443
+ const shown = values.slice(0, MAX_ENUM_VALUES_LISTED).map((v) => JSON.stringify(v));
1444
+ if (values.length > MAX_ENUM_VALUES_LISTED) shown.push(`… (${values.length} total)`);
1445
+ return shown.join(", ");
1446
+ }
1447
+ function extractEnum(propSchema) {
1448
+ if (Array.isArray(propSchema.enum) && propSchema.enum.length > 0) return propSchema.enum;
1449
+ const items = propSchema.items;
1450
+ if (items !== null && typeof items === "object" && Array.isArray(items.enum) && items.enum.length > 0) return items.enum;
1451
+ return null;
1452
+ }
1453
+ /**
1454
+ * Build a compact, human-readable constraint hint from an MCP tool's raw JSON
1455
+ * schema so the model sees required fields and each param's allowed enum values
1456
+ * inline in the tool description — the schema pass-through hands pi the server's
1457
+ * schema verbatim, but the model attends to the prose far more than the raw
1458
+ * `enum`/`required` keys. Returns '' when there is nothing worth surfacing.
1459
+ */
1460
+ function describeToolConstraints(inputSchema) {
1461
+ if (inputSchema === null || typeof inputSchema !== "object") return "";
1462
+ const schema = inputSchema;
1463
+ const required = Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : [];
1464
+ const properties = schema.properties !== null && typeof schema.properties === "object" ? schema.properties : {};
1465
+ const enumLines = [];
1466
+ for (const [propName, rawProp] of Object.entries(properties)) {
1467
+ if (rawProp === null || typeof rawProp !== "object") continue;
1468
+ const values = extractEnum(rawProp);
1469
+ if (values) enumLines.push(`- \`${propName}\` must be one of: ${formatEnumValues(values)}`);
1470
+ }
1471
+ if (required.length === 0 && enumLines.length === 0) return "";
1472
+ const lines = ["Argument constraints:"];
1473
+ if (required.length > 0) lines.push(`- required: ${required.map((r) => `\`${r}\``).join(", ")}`);
1474
+ lines.push(...enumLines);
1475
+ return lines.join("\n");
1476
+ }
1477
+ /**
1478
+ * Build the `promptSnippet` a registered MCP tool exposes to the model: the
1479
+ * server's description with the argument-constraint hint appended, falling back
1480
+ * to a labelled placeholder when the server omitted a description AND the schema
1481
+ * carries no constraints (pi's system-prompt builder hides tools whose snippet
1482
+ * is empty — system-prompt.js:49). This is the layer where `describeToolConstraints`
1483
+ * actually reaches the model, so it is exported and tested directly: the pure
1484
+ * hint being correct is necessary but not sufficient; what the model sees is
1485
+ * this composed snippet.
1486
+ */
1487
+ function buildToolPromptSnippet({ description, inputSchema, serverId }) {
1488
+ const constraintHint = describeToolConstraints(inputSchema);
1489
+ const enriched = constraintHint.length > 0 ? `${description}${description.length > 0 ? "\n\n" : ""}${constraintHint}` : description;
1490
+ return enriched.length > 0 ? enriched : `MCP tool from server "${serverId}".`;
1491
+ }
936
1492
  var McpExtension = class {
937
1493
  mcpClients = /* @__PURE__ */ new Map();
938
1494
  registeredMcpToolNames = /* @__PURE__ */ new Set();
@@ -952,8 +1508,12 @@ var McpExtension = class {
952
1508
  const name = makeToolName(serverId, tool.name);
953
1509
  const parameters = Type.Unsafe(tool.inputSchema);
954
1510
  const description = tool.description?.trim() ?? "";
955
- const promptSnippet = description.length > 0 ? description : `MCP tool from server "${serverId}".`;
956
- pi.registerTool({
1511
+ const promptSnippet = buildToolPromptSnippet({
1512
+ description,
1513
+ inputSchema: tool.inputSchema,
1514
+ serverId
1515
+ });
1516
+ pi.registerTool(withSummaryStrippedBeforeValidation({
957
1517
  name,
958
1518
  label: `MCP: ${serverId}/${tool.name}`,
959
1519
  description,
@@ -987,22 +1547,29 @@ var McpExtension = class {
987
1547
  };
988
1548
  }
989
1549
  }
990
- });
1550
+ }));
991
1551
  this.registeredMcpToolNames.add(name);
992
1552
  }
993
- async reconcile({ pi, configPath, connectTimeoutMs }) {
1553
+ async reconcile({ pi, configPath, connectTimeoutMs, contextWindow }) {
994
1554
  let config;
995
1555
  try {
996
1556
  config = await loadMcpConfig(configPath);
997
1557
  } catch (err) {
998
1558
  throw new Error(`Failed to load MCP config: ${err instanceof Error ? err.message : String(err)}`);
999
1559
  }
1560
+ const limits = resolveMcpToolLimits();
1561
+ const tokenBudget = resolveTokenBudget(limits, contextWindow);
1000
1562
  const summary = {
1001
1563
  added: [],
1002
1564
  removed: [],
1003
1565
  refreshed: [],
1004
1566
  errors: [],
1005
1567
  totalTools: 0,
1568
+ droppedTools: 0,
1569
+ limits,
1570
+ tokenBudget,
1571
+ tokensUsed: 0,
1572
+ toolCounts: {},
1006
1573
  servers: {}
1007
1574
  };
1008
1575
  const desiredIds = new Set(Object.keys(config.servers));
@@ -1026,15 +1593,58 @@ var McpExtension = class {
1026
1593
  if (outcome.error) summary.errors.push(outcome.error);
1027
1594
  if (outcome.change === "added") summary.added.push(id);
1028
1595
  else if (outcome.change === "refreshed") summary.refreshed.push(id);
1029
- if (outcome.tools) for (const tool of outcome.tools.list) {
1030
- this.registerMcpTool({
1031
- pi,
1032
- serverId: id,
1033
- client: outcome.tools.client,
1034
- tool
1035
- });
1036
- summary.totalTools++;
1596
+ }
1597
+ const alloc = outcomes.filter((o) => Boolean(o.tools)).map((o) => {
1598
+ const advertised = o.tools.list.length;
1599
+ return {
1600
+ id: o.id,
1601
+ client: o.tools.client,
1602
+ list: o.tools.list,
1603
+ advertised,
1604
+ room: Math.min(advertised, limits.maxToolsPerServer),
1605
+ registered: 0,
1606
+ serverTokens: 0,
1607
+ droppedReason: null
1608
+ };
1609
+ });
1610
+ const maxAdvertised = alloc.reduce((m, s) => Math.max(m, s.advertised), 0);
1611
+ outer: for (let i = 0; i < maxAdvertised; i++) for (const s of alloc) {
1612
+ if (summary.totalTools >= limits.maxTotalTools) {
1613
+ for (const t of alloc) if (t.registered < t.advertised && t.droppedReason === null) t.droppedReason = "total";
1614
+ break outer;
1615
+ }
1616
+ if (i >= s.room) {
1617
+ if (s.registered < s.advertised && s.droppedReason === null) s.droppedReason = "per_server";
1618
+ continue;
1619
+ }
1620
+ const tool = s.list[i];
1621
+ if (tool === void 0) continue;
1622
+ const cost = estimateToolTokens(tool);
1623
+ if (summary.tokensUsed + cost > tokenBudget && summary.totalTools > 0) {
1624
+ for (const t of alloc) if (t.registered < t.advertised && t.droppedReason === null) t.droppedReason = "tokens";
1625
+ break outer;
1037
1626
  }
1627
+ this.registerMcpTool({
1628
+ pi,
1629
+ serverId: s.id,
1630
+ client: s.client,
1631
+ tool
1632
+ });
1633
+ s.registered++;
1634
+ s.serverTokens += cost;
1635
+ summary.totalTools++;
1636
+ summary.tokensUsed += cost;
1637
+ }
1638
+ for (const s of alloc) {
1639
+ const dropped = s.advertised - s.registered;
1640
+ const droppedReason = dropped > 0 ? s.droppedReason : null;
1641
+ if (dropped > 0) summary.droppedTools += dropped;
1642
+ summary.toolCounts[s.id] = {
1643
+ advertised: s.advertised,
1644
+ registered: s.registered,
1645
+ tokens: s.serverTokens,
1646
+ droppedReason
1647
+ };
1038
1648
  }
1039
1649
  return summary;
1040
1650
  }
@@ -1099,7 +1709,8 @@ var McpExtension = class {
1099
1709
  },
1100
1710
  serverStatus: {
1101
1711
  status: "timeout",
1102
- stderr: result.stderr
1712
+ stderr: result.stderr,
1713
+ diagnostics: result.diagnostics
1103
1714
  },
1104
1715
  change,
1105
1716
  error: null,
@@ -1146,7 +1757,8 @@ var McpExtension = class {
1146
1757
  },
1147
1758
  serverStatus: {
1148
1759
  status: "timeout",
1149
- stderr: retry.stderr
1760
+ stderr: retry.stderr,
1761
+ diagnostics: retry.diagnostics
1150
1762
  },
1151
1763
  change: null,
1152
1764
  error: null,
@@ -1179,7 +1791,8 @@ var McpExtension = class {
1179
1791
  store: connected,
1180
1792
  serverStatus: {
1181
1793
  status: "timeout",
1182
- stderr
1794
+ stderr,
1795
+ diagnostics: null
1183
1796
  },
1184
1797
  change: null,
1185
1798
  error: null,
@@ -1190,6 +1803,64 @@ var McpExtension = class {
1190
1803
  try {
1191
1804
  mcpTools = (await connected.client.listTools()).tools;
1192
1805
  } catch (err) {
1806
+ if (isUnauthorizedError(err) && serverConfig.transport === "http") {
1807
+ await closeConnected(connected);
1808
+ const retry = await connectClient(id, serverConfig, { connectTimeoutMs });
1809
+ if (retry.status === "pending_auth") return {
1810
+ id,
1811
+ store: {
1812
+ client: retry.client,
1813
+ configKey,
1814
+ status: "pending_auth",
1815
+ stderrBuffer: null,
1816
+ cliHint: retry.cliHint
1817
+ },
1818
+ serverStatus: {
1819
+ status: "pending_auth",
1820
+ stderr: "",
1821
+ cliHint: retry.cliHint
1822
+ },
1823
+ change: null,
1824
+ error: null,
1825
+ tools: null
1826
+ };
1827
+ if (retry.status === "failed") return {
1828
+ id,
1829
+ store: null,
1830
+ serverStatus: {
1831
+ status: "failed",
1832
+ error: retry.error,
1833
+ stderr: retry.stderr
1834
+ },
1835
+ change: null,
1836
+ error: {
1837
+ serverId: id,
1838
+ message: retry.error
1839
+ },
1840
+ tools: null
1841
+ };
1842
+ if (retry.status === "connected") {
1843
+ connected = {
1844
+ client: retry.client,
1845
+ configKey,
1846
+ status: "connected",
1847
+ stderrBuffer: retry.stderr,
1848
+ cliHint: null
1849
+ };
1850
+ mcpTools = (await connected.client.listTools()).tools;
1851
+ return {
1852
+ id,
1853
+ store: connected,
1854
+ serverStatus: { status: "connected" },
1855
+ change: action === "reused" ? "refreshed" : action,
1856
+ error: null,
1857
+ tools: {
1858
+ client: connected.client,
1859
+ list: mcpTools
1860
+ }
1861
+ };
1862
+ }
1863
+ }
1193
1864
  const message = err instanceof Error ? err.message : String(err);
1194
1865
  const stderr = connected.stderrBuffer?.read() ?? "";
1195
1866
  return {
@@ -1220,17 +1891,21 @@ var McpExtension = class {
1220
1891
  }
1221
1892
  };
1222
1893
  }
1223
- async reconcileAndRecordMtime({ pi, configPath, reason }) {
1894
+ async reconcileAndRecordMtime({ pi, configPath, reason, contextWindow }) {
1224
1895
  const summary = await this.reconcile({
1225
1896
  pi,
1226
- configPath
1897
+ configPath,
1898
+ contextWindow
1227
1899
  });
1228
1900
  this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
1229
1901
  if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
1230
- log$11.info({
1902
+ log$12.info({
1231
1903
  event: "mcp_reconcile",
1232
1904
  reason,
1233
1905
  total_tools: summary.totalTools,
1906
+ tokens_used: summary.tokensUsed,
1907
+ token_budget: summary.tokenBudget,
1908
+ dropped_tools: summary.droppedTools,
1234
1909
  added: summary.added,
1235
1910
  removed: summary.removed,
1236
1911
  refreshed: summary.refreshed,
@@ -1247,10 +1922,11 @@ var McpExtension = class {
1247
1922
  await this.reconcileAndRecordMtime({
1248
1923
  pi,
1249
1924
  configPath,
1250
- reason: "session_start"
1925
+ reason: "session_start",
1926
+ contextWindow: ctx.model?.contextWindow
1251
1927
  });
1252
1928
  } catch (err) {
1253
- log$11.error({
1929
+ log$12.error({
1254
1930
  err,
1255
1931
  event: "mcp_reconcile_failed"
1256
1932
  }, "MCP reconcile failed");
@@ -1262,7 +1938,7 @@ var McpExtension = class {
1262
1938
  try {
1263
1939
  mtime = await readConfigMtimeMs(configPath);
1264
1940
  } catch (err) {
1265
- log$11.warn({
1941
+ log$12.warn({
1266
1942
  err,
1267
1943
  event: "mcp_mtime_check_failed"
1268
1944
  }, "mtime check on mcp.config.json failed");
@@ -1273,10 +1949,11 @@ var McpExtension = class {
1273
1949
  await this.reconcileAndRecordMtime({
1274
1950
  pi,
1275
1951
  configPath,
1276
- reason: "auto_reload"
1952
+ reason: "auto_reload",
1953
+ contextWindow: ctx.model?.contextWindow
1277
1954
  });
1278
1955
  } catch (err) {
1279
- log$11.error({
1956
+ log$12.error({
1280
1957
  err,
1281
1958
  event: "mcp_auto_reload_failed"
1282
1959
  }, "auto-reload after mcp.config.json change failed");
@@ -1293,7 +1970,8 @@ var McpExtension = class {
1293
1970
  const summary = await this.reconcileAndRecordMtime({
1294
1971
  pi,
1295
1972
  configPath,
1296
- reason: "tool"
1973
+ reason: "tool",
1974
+ contextWindow: ctx.model?.contextWindow
1297
1975
  });
1298
1976
  return {
1299
1977
  content: [{
@@ -1335,9 +2013,21 @@ function pendingAuthEntries(summary) {
1335
2013
  function timeoutEntries(summary) {
1336
2014
  return Object.entries(summary.servers).flatMap(([id, status]) => status.status === "timeout" ? [{
1337
2015
  id,
1338
- stderr: status.stderr
2016
+ stderr: status.stderr,
2017
+ diagnostics: status.diagnostics
1339
2018
  }] : []);
1340
2019
  }
2020
+ /**
2021
+ * One line describing what the connect probe learned about a timed-out
2022
+ * stdio child, so an empty stderr is no longer a dead end. Empty array
2023
+ * when the entry was re-surfaced without a fresh probe.
2024
+ */
2025
+ function timeoutDiagnosticLines(diagnostics) {
2026
+ if (diagnostics === null) return [];
2027
+ const alive = diagnostics.alive === null ? "unknown (no pid)" : diagnostics.alive ? "alive" : "DEAD";
2028
+ const spoke = diagnostics.stdoutMessages === 0 ? "no JSON-RPC received on stdout (initialize never answered — slow startup, or blocked e.g. on OAuth)" : `${diagnostics.stdoutMessages} JSON-RPC message(s) received on stdout (server spoke but the handshake stalled)`;
2029
+ return [` child process: ${alive}${diagnostics.pid !== null ? ` (pid ${diagnostics.pid})` : ""}; ${spoke}`];
2030
+ }
1341
2031
  function failedEntries(summary) {
1342
2032
  return Object.entries(summary.servers).flatMap(([id, status]) => status.status === "failed" ? [{
1343
2033
  id,
@@ -1345,6 +2035,13 @@ function failedEntries(summary) {
1345
2035
  stderr: status.stderr
1346
2036
  }] : []);
1347
2037
  }
2038
+ function appendTimeoutStderrBlock(lines, stderr) {
2039
+ if (!stderr) {
2040
+ lines.push(" stderr: (empty — the child wrote nothing to stderr)");
2041
+ return;
2042
+ }
2043
+ appendStderrBlock(lines, stderr);
2044
+ }
1348
2045
  function appendStderrBlock(lines, stderr) {
1349
2046
  if (!stderr) return;
1350
2047
  lines.push(" stderr:");
@@ -1352,9 +2049,29 @@ function appendStderrBlock(lines, stderr) {
1352
2049
  for (const line of stderr.trimEnd().split("\n")) lines.push(` ${line}`);
1353
2050
  lines.push(" ---");
1354
2051
  }
2052
+ /**
2053
+ * Human-readable lines describing any budget-driven truncation, shared by
2054
+ * `summaryText` (the reload_mcp tool output) and `formatMcpUpdateMessage` (the
2055
+ * synthetic continuation). Empty when nothing was dropped.
2056
+ */
2057
+ function truncationLines(summary) {
2058
+ if (summary.droppedTools <= 0) return [];
2059
+ const lines = [];
2060
+ const { maxTotalTools, maxToolsPerServer } = summary.limits;
2061
+ const totalCapHint = Number.isFinite(maxTotalTools) ? `${maxTotalTools}` : "unlimited";
2062
+ lines.push(` WARNING: ${summary.droppedTools} MCP tool(s) were NOT registered because a tool budget was hit (token budget: ~${summary.tokenBudget} tokens, used ~${summary.tokensUsed}; total-tool cap: ${totalCapHint}, per-server cap: ${Number.isFinite(maxToolsPerServer) ? maxToolsPerServer : "unlimited"}).`);
2063
+ lines.push(" Tool definitions are sent to the model on every prompt; too many (or too-large) tool schemas push the request over the limit, so they are budgeted against the model context window. Prune servers from mcp.config.json to bring the tool surface down.");
2064
+ for (const [id, count] of Object.entries(summary.toolCounts)) {
2065
+ if (count.droppedReason === null) continue;
2066
+ const why = count.droppedReason === "tokens" ? "token budget exhausted" : count.droppedReason === "total" ? "total-tool cap reached" : "per-server cap";
2067
+ lines.push(` - ${id}: registered ${count.registered}/${count.advertised} tools (~${count.tokens} tokens, ${why}).`);
2068
+ }
2069
+ return lines;
2070
+ }
1355
2071
  function summaryText(summary) {
1356
2072
  const lines = [];
1357
2073
  lines.push(`MCP reconcile complete: ${summary.totalTools} tool(s) live.`);
2074
+ lines.push(...truncationLines(summary));
1358
2075
  if (summary.added.length > 0) lines.push(` Added: ${summary.added.join(", ")}`);
1359
2076
  if (summary.refreshed.length > 0) lines.push(` Refreshed: ${summary.refreshed.join(", ")}`);
1360
2077
  if (summary.removed.length > 0) lines.push(` Removed: ${summary.removed.join(", ")}`);
@@ -1363,11 +2080,12 @@ function summaryText(summary) {
1363
2080
  lines.push(` run \`${cliHint}\` in the shell to authenticate.`);
1364
2081
  appendStderrBlock(lines, stderr);
1365
2082
  }
1366
- for (const { id, stderr } of timeoutEntries(summary)) {
2083
+ for (const { id, stderr, diagnostics } of timeoutEntries(summary)) {
1367
2084
  lines.push(` TIMED OUT ${id}:`);
1368
2085
  lines.push(` bridge spawned but did not complete initialize in time`);
1369
2086
  lines.push(` (usually mcp-remote mid-OAuth — see captured stderr).`);
1370
- appendStderrBlock(lines, stderr);
2087
+ lines.push(...timeoutDiagnosticLines(diagnostics));
2088
+ appendTimeoutStderrBlock(lines, stderr);
1371
2089
  }
1372
2090
  for (const { id, error, stderr } of failedEntries(summary)) {
1373
2091
  lines.push(` FAILED ${id}: ${error}`);
@@ -1380,7 +2098,7 @@ function summaryText(summary) {
1380
2098
  return lines.join("\n");
1381
2099
  }
1382
2100
  function summaryHasChanges(summary) {
1383
- return summary.added.length > 0 || summary.removed.length > 0 || summary.refreshed.length > 0 || summary.errors.length > 0;
2101
+ return summary.added.length > 0 || summary.removed.length > 0 || summary.refreshed.length > 0 || summary.errors.length > 0 || summary.droppedTools > 0;
1384
2102
  }
1385
2103
  /**
1386
2104
  * Format a queued tool-update as a synthetic system-style message for
@@ -1393,6 +2111,10 @@ function formatMcpUpdateMessage(summary) {
1393
2111
  if (summary.added.length > 0) lines.push(`Newly available servers: ${summary.added.join(", ")}`);
1394
2112
  if (summary.refreshed.length > 0) lines.push(`Refreshed servers: ${summary.refreshed.join(", ")}`);
1395
2113
  if (summary.removed.length > 0) lines.push(`Removed servers (and their tools): ${summary.removed.join(", ")}`);
2114
+ if (summary.droppedTools > 0) {
2115
+ lines.push("");
2116
+ lines.push(...truncationLines(summary));
2117
+ }
1396
2118
  const pending = pendingAuthEntries(summary);
1397
2119
  if (pending.length > 0) {
1398
2120
  lines.push("");
@@ -1408,9 +2130,10 @@ function formatMcpUpdateMessage(summary) {
1408
2130
  if (timedOut.length > 0) {
1409
2131
  lines.push("");
1410
2132
  lines.push("Servers that timed out during initialize (bridge is still alive in the background; usually mcp-remote-style stdio bridges mid-OAuth):");
1411
- for (const { id, stderr } of timedOut) {
2133
+ for (const { id, stderr, diagnostics } of timedOut) {
1412
2134
  lines.push(` - ${id}:`);
1413
- appendStderrBlock(lines, stderr);
2135
+ lines.push(...timeoutDiagnosticLines(diagnostics));
2136
+ appendTimeoutStderrBlock(lines, stderr);
1414
2137
  }
1415
2138
  lines.push("If the bridge prints an auth URL in its stderr, share it with the user. Then call `reload_mcp` once they've finished.");
1416
2139
  }
@@ -1499,156 +2222,16 @@ async function runToolUpdateLoop({ session, log }) {
1499
2222
  }, "reached tool-update continuation cap; further updates will land on next request");
1500
2223
  }
1501
2224
  //#endregion
1502
- //#region src/tracing.ts
1503
- const SERVICE_NAME = "skydive-agent-harness";
1504
- const DAEMON_TRACES_URL = "http://localhost:38994/v1/traces";
1505
- let provider = null;
1506
- function initTracing() {
1507
- if (provider) return;
1508
- propagation.setGlobalPropagator(new W3CTraceContextPropagator());
1509
- provider = new NodeTracerProvider({ resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }) });
1510
- const exporter = new OTLPTraceExporter({ url: DAEMON_TRACES_URL });
1511
- provider.addSpanProcessor(new BatchSpanProcessor(exporter, { scheduledDelayMillis: 1e3 }));
1512
- provider.register();
1513
- logger.info({
1514
- event: "tracing_enabled",
1515
- endpoint: DAEMON_TRACES_URL
1516
- }, "OTel tracing initialized — exporting via daemon");
1517
- const shutdown = async () => {
1518
- await shutdownTracing();
1519
- process.exit(0);
1520
- };
1521
- process.on("SIGTERM", shutdown);
1522
- process.on("SIGINT", shutdown);
1523
- }
1524
- function getTracer() {
1525
- return trace.getTracer(SERVICE_NAME);
1526
- }
1527
- function extractRemoteContext() {
1528
- const traceparent = getCurrentTraceparent();
1529
- if (!traceparent) return ROOT_CONTEXT;
1530
- const carrier = { traceparent };
1531
- return propagation.extract(ROOT_CONTEXT, carrier, {
1532
- get: (c, key) => c[key],
1533
- keys: (c) => Object.keys(c)
1534
- });
1535
- }
1536
- async function shutdownTracing() {
1537
- if (provider) await provider.shutdown();
1538
- }
1539
- //#endregion
1540
- //#region src/harness.ts
1541
- /**
1542
- * Skydive composition over @skydiveai/pi-server: wires the platform
1543
- * defaults (tracing to the daemon, tool-update hot-reload hooks, prewarm
1544
- * paths, header passthrough for proxy routing, Skydive agent-card
1545
- * branding) into the generic protocol server, and returns mountable
1546
- * handlers. The agent supplies the pi session factory (their session.ts)
1547
- * and owns the express app:
1548
- *
1549
- * const { platform, protocols } = createHarness({
1550
- * cwd: process.cwd(),
1551
- * createSession,
1552
- * });
1553
- * app.get('/health', platform.handlers.health);
1554
- * app.use(platform.handlers.injectEnv);
1555
- * app.use(platform.handlers.prewarm); // matches /_skydive/prewarm + legacy alias
1556
- * app.use(protocols.handlers.all);
1557
- */
1558
- const A2A_PATH = "/a2a";
1559
- const AGENT_CARD_PATH = "/.well-known/agent-card.json";
1560
- const PREWARM_PATHS = ["/_skydive/prewarm", "/_anyone/prewarm"];
1561
- const PASSTHROUGH_HEADER_PREFIXES = ["x-anyone-", "x-skydive-"];
1562
- function createHarness(options) {
1563
- initTracing();
1564
- readPlatformVersions().then((runtimeVersions) => logger.info({
1565
- event: "runtime_versions",
1566
- runtimeVersions
1567
- }, "platform runtime versions"));
1568
- const serverOptions = {
1569
- ...options,
1570
- onSessionSetup: options.onSessionSetup ?? ((args) => {
1571
- installToolUpdateAutoStop(args);
1572
- installIterationCap(args);
1573
- }),
1574
- postPrompt: options.postPrompt ?? runToolUpdateLoop,
1575
- passthroughHeaderPrefixes: options.passthroughHeaderPrefixes ?? PASSTHROUGH_HEADER_PREFIXES,
1576
- prewarmPaths: options.prewarmPaths ?? PREWARM_PATHS
1577
- };
1578
- const webHandlers = createProtocolHandlers(serverOptions);
1579
- const cardOverrides = {
1580
- name: "Skydive Agent",
1581
- description: "An AI coding agent powered by the Skydive platform.",
1582
- ...options.agentCard
1583
- };
1584
- const agentCardWeb = async (request) => {
1585
- const url = new URL(request.url);
1586
- if (request.method !== "GET" || url.pathname !== AGENT_CARD_PATH) return null;
1587
- return Response.json(buildAgentCard(cardOverrides.url ?? `${url.origin}${A2A_PATH}`, cardOverrides));
1588
- };
1589
- const a2a = restHandler({
1590
- requestHandler: new DefaultRequestHandler(buildAgentCard(cardOverrides.url ?? A2A_PATH, cardOverrides), new InMemoryTaskStore(), createAgentExecutor(serverOptions), new DefaultExecutionEventBusManager()),
1591
- userBuilder: UserBuilder.noAuthentication
1592
- });
1593
- return {
1594
- platform: { handlers: {
1595
- /**
1596
- * Platform health plus the agent's `healthMetadata`. Mount above
1597
- * injectEnv — health must respond immediately for prewarm
1598
- * stashing and readiness probes, and injectEnv can wait up to
1599
- * 10s for env vars during boot.
1600
- */
1601
- health: createHealthHandler({ metadata: options.healthMetadata ?? null }),
1602
- /** Loads platform env (e2b envd / daemon long-poll). */
1603
- injectEnv: createPlatformEnvMiddleware(),
1604
- prewarm: webHandlerToMiddleware(webHandlers.prewarm)
1605
- } },
1606
- protocols: { handlers: {
1607
- /** Express-style; mount at /a2a. */
1608
- a2a,
1609
- /** GET /.well-known/agent-card.json. */
1610
- agentCard: webHandlerToMiddleware(agentCardWeb),
1611
- /** Mirrors each vendor's API shape. */
1612
- openai: { v1: {
1613
- chat: { completions: webHandlerToMiddleware(webHandlers.chatCompletions) },
1614
- responses: webHandlerToMiddleware(webHandlers.responses)
1615
- } },
1616
- anthropic: { v1: { messages: webHandlerToMiddleware(webHandlers.messages) } },
1617
- /**
1618
- * Everything in one mount: a2a (+ agent card) at their well-known
1619
- * paths, then chat-completions / anthropic-messages / responses.
1620
- * Calls next() when nothing matches.
1621
- */
1622
- all: chainMiddleware([mountAt(A2A_PATH, a2a), webHandlerToMiddleware(composeHandlers([
1623
- agentCardWeb,
1624
- webHandlers.chatCompletions,
1625
- webHandlers.messages,
1626
- webHandlers.responses
1627
- ]))])
1628
- } }
1629
- };
1630
- }
1631
- /** Effective bash timeout: the model's value when it gave a positive number, else the default. */
1632
- function resolveBashTimeout(provided) {
1633
- return typeof provided === "number" && provided > 0 ? provided : 600;
1634
- }
1635
- const bashDefaultTimeoutExtension = (pi) => {
1636
- pi.on("tool_call", async (event) => {
1637
- if (event.toolName !== "bash") return;
1638
- event.input.timeout = resolveBashTimeout(event.input.timeout);
1639
- });
1640
- };
1641
- //#endregion
1642
2225
  //#region src/channel-context-ref.ts
1643
2226
  /**
1644
- * The worker injects only a reference — `{ channel, messageId }` — into the
1645
- * sandbox env (`SKYDIVE_CHANNEL_CONTEXT`) rather than the full context.
2227
+ * The worker injects a small reference — `{ channel, messageId, runId }` —
2228
+ * into the sandbox env (`SKYDIVE_CHANNEL_CONTEXT`) rather than the full context.
1646
2229
  *
1647
2230
  * The canonical `ChannelContextRef` type + `parseChannelContextRef` live in
1648
2231
  * `@createinc/anyone-channels`, but the harness (`@skydiveai/*`) keeps zero
1649
2232
  * `@createinc/*` dependencies — importing that package would pull the whole
1650
- * platform channel stack (Slack/email/Linq SDKs, messaging) in just to read
1651
- * two fields. So we validate the (stable) shape locally instead.
2233
+ * platform channel stack (Slack/email/Linq SDKs, messaging) just to read one
2234
+ * field. So we validate the field this consumer needs locally instead.
1652
2235
  */
1653
2236
  const channelContextRefSchema = z.object({ messageId: z.string().nullable() });
1654
2237
  /**
@@ -1680,20 +2263,84 @@ function apiBaseUrl() {
1680
2263
  }
1681
2264
  //#endregion
1682
2265
  //#region src/extensions/platform.ts
2266
+ /**
2267
+ * Platform extension — bridges the agent harness to the Skydive platform daemon.
2268
+ *
2269
+ * Responsibilities:
2270
+ * - Heartbeat: periodic POST to the API so the sandbox manager knows the
2271
+ * agent is alive. Throttled to once per minute, triggered by tool events.
2272
+ * - Session tracking: registers the session with the daemon on start,
2273
+ * streams tool_call / tool_result events so the daemon can track which
2274
+ * session is actively executing, and signals session end on agent_end.
2275
+ * - Channel context: passes the SKYDIVE_CHANNEL_CONTEXT (containing the
2276
+ * messageId) to the daemon so file writes can be attributed to the
2277
+ * correct conversation.
2278
+ *
2279
+ * All daemon POSTs are fire-and-forget — failures are logged but never
2280
+ * block the agent. The daemon may not be running (e.g. local dev without
2281
+ * a sandbox), and that's fine.
2282
+ */
1683
2283
  const HEARTBEAT_THROTTLE_MS = 6e4;
1684
2284
  const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
1685
2285
  const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
1686
2286
  const DAEMON_URL = "http://localhost:38994";
1687
- const log$10 = logger.child({ module: "platform-ext" });
2287
+ const log$11 = logger.child({ module: "platform-ext" });
1688
2288
  function sandboxClient() {
1689
2289
  const apiUrl = apiBaseUrl();
1690
2290
  if (!apiUrl) return null;
1691
2291
  return hc(`${apiUrl}/api/v1/sandbox`);
1692
2292
  }
1693
2293
  /**
2294
+ * Is this box still an unclaimed warm-pool sandbox? (ANY-6000, the
2295
+ * feature-flags half of the ANY-5184 pool 403 wave.)
2296
+ *
2297
+ * `GET /sandbox/feature-flags` is agent-only, so the shared poller's request
2298
+ * from a pool box can only 403 — a guaranteed-failing GET every 60s for the
2299
+ * life of the pool phase. The discriminator is the sandbox token's `type`
2300
+ * claim, read UNVERIFIED (this box never holds the signing secret): not an
2301
+ * authorization decision, only "should I bother calling?", and the api still
2302
+ * authorizes every request.
2303
+ *
2304
+ * Read per call from the daemon's persisted env file, NOT process.env:
2305
+ * claiming a pool box rebinds the token in place (the daemon rewrites this
2306
+ * file) while the harness's process.env keeps the boot snapshot, so a
2307
+ * process-env gate would leave a claimed box permanently skipping — trading a
2308
+ * wasted request for silently frozen flags, which is strictly worse. "Cannot
2309
+ * tell" (no file, no token, unparseable payload) reports false so the poll
2310
+ * proceeds.
2311
+ */
2312
+ const daemonEnvIdentitySchema = z.object({
2313
+ ANYONE_SANDBOX_TOKEN: z.string().optional(),
2314
+ SKYDIVE_SANDBOX_TOKEN: z.string().optional()
2315
+ }).passthrough();
2316
+ const tokenTypeSchema = z.object({ type: z.string() }).passthrough();
2317
+ async function isPoolIdentity() {
2318
+ try {
2319
+ const override = process.env.ANYONE_DAEMON_ENV_CACHE;
2320
+ const candidates = override ? [override] : ["/run/anyone-system/daemon-env.json", "/tmp/.anyone/daemon-env.json"];
2321
+ let raw = null;
2322
+ for (const file of candidates) {
2323
+ raw = await readFile(file, "utf8").catch(() => null);
2324
+ if (raw !== null) break;
2325
+ }
2326
+ if (raw === null) return false;
2327
+ const env = daemonEnvIdentitySchema.safeParse(JSON.parse(raw));
2328
+ if (!env.success) return false;
2329
+ const token = env.data.ANYONE_SANDBOX_TOKEN ?? env.data.SKYDIVE_SANDBOX_TOKEN;
2330
+ if (typeof token !== "string" || token === "") return false;
2331
+ const payload = token.split(".")[1];
2332
+ if (!payload) return false;
2333
+ const claims = tokenTypeSchema.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString("utf8")));
2334
+ return claims.success && claims.data.type === "onboarding-pool";
2335
+ } catch (_err) {
2336
+ return false;
2337
+ }
2338
+ }
2339
+ /**
1694
2340
  * Fetch every harness feature flag in one GET (`{ contextManagement, ... }`
1695
2341
  * — see apps/anyone/api/src/routes/sandbox-feature-flags.ts). Returns
1696
- * null when indeterminate (no api url, or the request failed) so the shared
2342
+ * null when indeterminate (no api url, the request failed, or the box is an
2343
+ * unclaimed pool sandbox whose token the route would 403) so the shared
1697
2344
  * poller keeps the last-known values rather than flipping on a transient error.
1698
2345
  * This is the single fetch behind `feature-flags-poll.ts`; extensions read the
1699
2346
  * polled values there instead of issuing their own GET.
@@ -1701,18 +2348,23 @@ function sandboxClient() {
1701
2348
  async function fetchHarnessFlags() {
1702
2349
  const client = sandboxClient();
1703
2350
  if (!client) return null;
2351
+ if (await isPoolIdentity()) return null;
1704
2352
  try {
1705
2353
  const res = await client["feature-flags"].$get();
1706
2354
  if (!res.ok) {
1707
- log$10.debug({
2355
+ log$11.debug({
1708
2356
  status: res.status,
1709
2357
  event: "feature_flags_fetch_failed"
1710
2358
  }, "feature-flags fetch failed");
1711
2359
  return null;
1712
2360
  }
1713
- return { contextManagement: (await res.json()).contextManagement ?? null };
2361
+ const body = await res.json();
2362
+ return {
2363
+ contextManagement: body.contextManagement ?? null,
2364
+ closingText: body.closingText ?? null
2365
+ };
1714
2366
  } catch (err) {
1715
- log$10.debug({
2367
+ log$11.debug({
1716
2368
  err,
1717
2369
  event: "feature_flags_fetch_error"
1718
2370
  }, "feature-flags request errored");
@@ -1723,7 +2375,7 @@ function postHeartbeat({ messageId }) {
1723
2375
  const client = sandboxClient();
1724
2376
  if (!client) return;
1725
2377
  client.heartbeat.$post({ json: { messageId } }).catch((err) => {
1726
- log$10.debug({
2378
+ log$11.debug({
1727
2379
  err,
1728
2380
  event: "heartbeat_failed"
1729
2381
  }, "heartbeat failed");
@@ -1735,7 +2387,7 @@ async function resolveConversationFromApi(messageId) {
1735
2387
  try {
1736
2388
  const res = await client["message-conversation"].$get({ query: { messageId } });
1737
2389
  if (!res.ok) {
1738
- log$10.warn({
2390
+ log$11.warn({
1739
2391
  status: res.status,
1740
2392
  messageId,
1741
2393
  event: "resolve_conversation_failed"
@@ -1744,7 +2396,7 @@ async function resolveConversationFromApi(messageId) {
1744
2396
  }
1745
2397
  return (await res.json()).conversationId ?? null;
1746
2398
  } catch (err) {
1747
- log$10.warn({
2399
+ log$11.warn({
1748
2400
  err,
1749
2401
  messageId,
1750
2402
  event: "resolve_conversation_error"
@@ -1761,18 +2413,94 @@ async function postBackgroundTaskDone({ messageId, content }) {
1761
2413
  } });
1762
2414
  if (!res.ok) throw new Error(`bg-task-done POST failed: ${res.status}`);
1763
2415
  }
1764
- async function postSubagentSpawn({ messageId, tasks }) {
2416
+ async function putBackgroundTaskJournalSpec({ messageId, spec }) {
1765
2417
  const client = sandboxClient();
1766
- if (!client) throw new Error("no api url for subagent-spawn");
1767
- const res = await client["subagent-spawn"].$post({ json: {
1768
- messageId,
1769
- tasks
1770
- } });
1771
- if (!res.ok) throw new Error(`subagent-spawn POST failed: ${res.status}`);
1772
- return { taskIds: (await res.json()).taskIds };
2418
+ if (!client) return;
2419
+ try {
2420
+ const res = await client["bg-task-journal"].$put({ json: {
2421
+ messageId,
2422
+ spec
2423
+ } });
2424
+ if (!res.ok) log$11.warn({
2425
+ status: res.status,
2426
+ taskId: spec.id,
2427
+ event: "bg_journal_put_failed"
2428
+ }, "bg-task journal PUT failed");
2429
+ } catch (err) {
2430
+ log$11.warn({
2431
+ err,
2432
+ taskId: spec.id,
2433
+ event: "bg_journal_put_failed"
2434
+ }, "bg-task journal PUT threw");
2435
+ }
1773
2436
  }
1774
- function createHeartbeatThrottle({ messageId }) {
1775
- let lastAt = 0;
2437
+ async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
2438
+ const client = sandboxClient();
2439
+ if (!client) return;
2440
+ try {
2441
+ await client["bg-task-journal"].$delete({ json: {
2442
+ messageId,
2443
+ taskId
2444
+ } });
2445
+ } catch (err) {
2446
+ log$11.debug({
2447
+ err,
2448
+ taskId,
2449
+ event: "bg_journal_delete_failed"
2450
+ }, "bg-task journal DELETE failed");
2451
+ }
2452
+ }
2453
+ async function listBackgroundTaskJournalSpecs({ messageId }) {
2454
+ const client = sandboxClient();
2455
+ if (!client) return [];
2456
+ try {
2457
+ const res = await client["bg-task-journal"].$get({ query: { messageId } });
2458
+ if (!res.ok) return [];
2459
+ return (await res.json()).specs ?? [];
2460
+ } catch (err) {
2461
+ log$11.debug({
2462
+ err,
2463
+ event: "bg_journal_list_failed"
2464
+ }, "bg-task journal GET failed");
2465
+ return [];
2466
+ }
2467
+ }
2468
+ function postBackgroundTasksSnapshot({ messageId, tasks }) {
2469
+ const client = sandboxClient();
2470
+ if (!client || !messageId) return;
2471
+ client["bg-tasks"].$post({ json: {
2472
+ messageId,
2473
+ tasks
2474
+ } }).catch((err) => {
2475
+ log$11.debug({
2476
+ err,
2477
+ event: "bg_tasks_snapshot_failed"
2478
+ }, "bg-tasks snapshot publish failed");
2479
+ });
2480
+ }
2481
+ async function postSubagentSpawn({ messageId, tasks }) {
2482
+ const client = sandboxClient();
2483
+ if (!client) throw new Error("no api url for subagent-spawn");
2484
+ const res = await client["subagent-spawn"].$post({ json: {
2485
+ messageId,
2486
+ tasks
2487
+ } });
2488
+ if (!res.ok) {
2489
+ let detail = "";
2490
+ try {
2491
+ const errBody = await res.json();
2492
+ if (errBody && typeof errBody.error === "string") detail = `: ${errBody.error}`;
2493
+ } catch {}
2494
+ throw new Error(`subagent-spawn POST failed (${res.status})${detail}`);
2495
+ }
2496
+ const body = await res.json();
2497
+ return {
2498
+ taskIds: body.taskIds,
2499
+ tasks: body.tasks ?? []
2500
+ };
2501
+ }
2502
+ function createHeartbeatThrottle({ messageId }) {
2503
+ let lastAt = 0;
1776
2504
  let pending = null;
1777
2505
  function send() {
1778
2506
  const now = Date.now();
@@ -1818,7 +2546,7 @@ function createToolHeartbeat({ messageId }) {
1818
2546
  }
1819
2547
  heartbeatCount++;
1820
2548
  if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
1821
- log$10.warn({
2549
+ log$11.warn({
1822
2550
  heartbeatCount,
1823
2551
  activeToolCalls: [...activeToolCalls]
1824
2552
  }, "tool heartbeat max reached, stopping");
@@ -1849,7 +2577,7 @@ function postToDaemon(path, body) {
1849
2577
  headers: { "content-type": "application/json" },
1850
2578
  body: JSON.stringify(body)
1851
2579
  }).catch((err) => {
1852
- log$10.debug({
2580
+ log$11.debug({
1853
2581
  err,
1854
2582
  path,
1855
2583
  event: "daemon_post_failed"
@@ -1858,7 +2586,7 @@ function postToDaemon(path, body) {
1858
2586
  }
1859
2587
  function createPlatformExtensions({ sessionId, channelContext }) {
1860
2588
  return (pi) => {
1861
- log$10.info({
2589
+ log$11.info({
1862
2590
  sessionId,
1863
2591
  hasChannelContext: Boolean(channelContext)
1864
2592
  }, "platform extension initialized");
@@ -1907,7 +2635,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
1907
2635
  });
1908
2636
  });
1909
2637
  pi.on("agent_end", () => {
1910
- log$10.info({ sessionId }, "session ending");
2638
+ log$11.info({ sessionId }, "session ending");
1911
2639
  postToDaemon("/session/end", { sessionId });
1912
2640
  });
1913
2641
  };
@@ -1918,25 +2646,30 @@ function createPlatformExtensions({ sessionId, channelContext }) {
1918
2646
  * Shared harness feature-flag poll.
1919
2647
  *
1920
2648
  * The api exposes one `/feature-flags` GET that returns every harness flag in a
1921
- * single response (`{ contextManagement, commandFlags }` — see
2649
+ * single response (`{ contextManagement, closingText, commandFlags }` — see
1922
2650
  * apps/anyone/api/src/routes/sandbox-feature-flags.ts). Rather than each
1923
2651
  * extension issuing its own GET — and, worse, a *blocking* GET on the
1924
2652
  * pre-first-token `session_start` path — a single background poller fetches
1925
2653
  * that response once per interval and fans the values out to every subscriber.
1926
2654
  *
1927
- * Why one poller: context-management consumes the `contextManagement` flag
1928
- * without a blocking GET on the pre-first-token `session_start` path. Reading
1929
- * the last-polled value keeps the hot path allocation-only; a cold cache reads
1930
- * as `null` and a newly-flipped flag takes effect on the next poll.
2655
+ * Why one poller: context-management consumes the `contextManagement` flag and
2656
+ * the closing-text loop consumes `closingText`, both without a blocking GET on
2657
+ * the pre-first-token `session_start` path. Reading the last-polled value keeps
2658
+ * the hot path allocation-only; a cold cache reads as `null` and a
2659
+ * newly-flipped flag takes effect on the next poll.
1931
2660
  *
1932
2661
  * The poll is fire-and-forget and self-unref'd — it never keeps the process
1933
2662
  * alive and an indeterminate result (no api url / transient failure) leaves the
1934
2663
  * last-known values untouched so a blip can't silently flip behavior.
1935
2664
  */
1936
- const log$9 = logger.child({ module: "feature-flags-poll" });
2665
+ const log$10 = logger.child({ module: "feature-flags-poll" });
1937
2666
  const FLAG_POLL_INTERVAL_MS = 6e4;
1938
2667
  let contextManagement = null;
1939
- const subscribers = { contextManagement: /* @__PURE__ */ new Set() };
2668
+ let closingText = null;
2669
+ const subscribers = {
2670
+ contextManagement: /* @__PURE__ */ new Set(),
2671
+ closingText: /* @__PURE__ */ new Set()
2672
+ };
1940
2673
  let pollerStarted = false;
1941
2674
  let firstPollSettled = false;
1942
2675
  let resolveFirstPoll = null;
@@ -1949,8 +2682,8 @@ function markFirstPollSettled() {
1949
2682
  resolveFirstPoll?.();
1950
2683
  }
1951
2684
  /** Last-polled value of a flag, or `null` if not yet resolved. */
1952
- function getPolledFlag(_name) {
1953
- return contextManagement;
2685
+ function getPolledFlag(name) {
2686
+ return name === "closingText" ? closingText : contextManagement;
1954
2687
  }
1955
2688
  /**
1956
2689
  * Subscribe to changes of a flag. The callback fires only on a *transition*
@@ -1963,12 +2696,13 @@ function onFlagChange(name, cb) {
1963
2696
  }
1964
2697
  function apply(name, next) {
1965
2698
  if (next === null) return;
1966
- const prev = contextManagement;
1967
- contextManagement = next;
2699
+ const prev = name === "closingText" ? closingText : contextManagement;
2700
+ if (name === "closingText") closingText = next;
2701
+ else contextManagement = next;
1968
2702
  if (next !== prev) for (const cb of subscribers[name]) try {
1969
2703
  cb(next);
1970
2704
  } catch (err) {
1971
- log$9.warn({
2705
+ log$10.warn({
1972
2706
  err,
1973
2707
  flag: name
1974
2708
  }, "flag subscriber threw");
@@ -1979,8 +2713,9 @@ async function pollOnce() {
1979
2713
  const flags = await fetchHarnessFlags();
1980
2714
  if (!flags) return;
1981
2715
  apply("contextManagement", flags.contextManagement ?? null);
2716
+ apply("closingText", flags.closingText ?? null);
1982
2717
  } catch (err) {
1983
- log$9.debug({ err }, "feature-flag poll threw");
2718
+ log$10.debug({ err }, "feature-flag poll threw");
1984
2719
  }
1985
2720
  }
1986
2721
  /**
@@ -1996,6 +2731,569 @@ function startFeatureFlagPoller() {
1996
2731
  setInterval(() => void pollOnce(), FLAG_POLL_INTERVAL_MS).unref?.();
1997
2732
  }
1998
2733
  //#endregion
2734
+ //#region src/closing-text-loop.ts
2735
+ const CLOSING_TEXT_NUDGE = "<system_notification>You ended that turn on a tool call without writing any reply to the user. Write a brief closing message now: what you did and the outcome. Do not call any more tools unless you genuinely still need to.</system_notification>";
2736
+ function isNonEmptyText(block) {
2737
+ return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
2738
+ }
2739
+ /**
2740
+ * True when the assistant produced no visible text since the human's last
2741
+ * message this turn — i.e. the turn ended on tool calls / thinking only.
2742
+ *
2743
+ * We scan from the end back to the most recent `user` message (the human turn
2744
+ * that triggered this run) and inspect every `assistant` message after it.
2745
+ * A string-content assistant message (rare, but pi allows it) counts as text
2746
+ * when non-blank. `toolResult` and custom messages are ignored.
2747
+ */
2748
+ function turnEndedWithoutVisibleText(messages) {
2749
+ let sawAssistant = false;
2750
+ for (let i = messages.length - 1; i >= 0; i--) {
2751
+ const m = messages[i];
2752
+ if (!m || m.role === "user") break;
2753
+ if (m.role !== "assistant") continue;
2754
+ sawAssistant = true;
2755
+ if (typeof m.content === "string") {
2756
+ if (m.content.trim().length > 0) return false;
2757
+ continue;
2758
+ }
2759
+ if (Array.isArray(m.content) && m.content.some(isNonEmptyText)) return false;
2760
+ }
2761
+ return sawAssistant;
2762
+ }
2763
+ /**
2764
+ * True when the last assistant message this turn ended in a way we must not
2765
+ * nudge: a user abort or a provider error. Both already surface their own
2766
+ * terminal signal to the client; a closing-text prompt on top would be noise.
2767
+ */
2768
+ function turnEndedAbnormally(messages) {
2769
+ for (let i = messages.length - 1; i >= 0; i--) {
2770
+ const m = messages[i];
2771
+ if (!m || m.role !== "assistant") continue;
2772
+ return m.stopReason === "aborted" || m.stopReason === "error";
2773
+ }
2774
+ return false;
2775
+ }
2776
+ async function runClosingTextLoop({ session, log, enabled = getPolledFlag("closingText") === true }) {
2777
+ if (!enabled) return;
2778
+ if (turnEndedAbnormally(session.messages)) return;
2779
+ if (!turnEndedWithoutVisibleText(session.messages)) return;
2780
+ log.info({ event: "closing_text_continuation_injected" }, "turn ended on a tool call with no visible reply; injecting a closing-text continuation");
2781
+ await session.sendCustomMessage({
2782
+ customType: "closing-text-nudge",
2783
+ content: CLOSING_TEXT_NUDGE,
2784
+ display: false,
2785
+ details: {}
2786
+ }, { triggerTurn: true });
2787
+ }
2788
+ //#endregion
2789
+ //#region src/tracing.ts
2790
+ const SERVICE_NAME = "skydive-agent-harness";
2791
+ const DAEMON_TRACES_URL = "http://localhost:38994/v1/traces";
2792
+ let provider = null;
2793
+ function initTracing() {
2794
+ if (provider) return;
2795
+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());
2796
+ provider = new NodeTracerProvider({ resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }) });
2797
+ const exporter = new OTLPTraceExporter({ url: DAEMON_TRACES_URL });
2798
+ provider.addSpanProcessor(new BatchSpanProcessor(exporter, { scheduledDelayMillis: 1e3 }));
2799
+ provider.register();
2800
+ logger.info({
2801
+ event: "tracing_enabled",
2802
+ endpoint: DAEMON_TRACES_URL
2803
+ }, "OTel tracing initialized — exporting via daemon");
2804
+ const shutdown = async () => {
2805
+ await shutdownTracing();
2806
+ process.exit(0);
2807
+ };
2808
+ process.on("SIGTERM", shutdown);
2809
+ process.on("SIGINT", shutdown);
2810
+ }
2811
+ function getTracer() {
2812
+ return trace.getTracer(SERVICE_NAME);
2813
+ }
2814
+ function extractRemoteContext() {
2815
+ const traceparent = getCurrentTraceparent();
2816
+ if (!traceparent) return ROOT_CONTEXT;
2817
+ const carrier = { traceparent };
2818
+ return propagation.extract(ROOT_CONTEXT, carrier, {
2819
+ get: (c, key) => c[key],
2820
+ keys: (c) => Object.keys(c)
2821
+ });
2822
+ }
2823
+ async function shutdownTracing() {
2824
+ if (provider) await provider.shutdown();
2825
+ }
2826
+ //#endregion
2827
+ //#region src/harness.ts
2828
+ /**
2829
+ * Skydive composition over @skydiveai/pi-server: wires the platform
2830
+ * defaults (tracing to the daemon, tool-update hot-reload hooks, prewarm
2831
+ * paths, header passthrough for proxy routing, Skydive agent-card
2832
+ * branding) into the generic protocol server, and returns mountable
2833
+ * handlers. The agent supplies the pi session factory (their session.ts)
2834
+ * and owns the express app:
2835
+ *
2836
+ * const { platform, protocols } = createHarness({
2837
+ * cwd: process.cwd(),
2838
+ * createSession,
2839
+ * });
2840
+ * app.get('/health', platform.handlers.health);
2841
+ * app.use(platform.handlers.injectEnv);
2842
+ * app.use(platform.handlers.prewarm); // matches /_skydive/prewarm + legacy alias
2843
+ * app.use(protocols.handlers.all);
2844
+ */
2845
+ const A2A_PATH = "/a2a";
2846
+ const AGENT_CARD_PATH = "/.well-known/agent-card.json";
2847
+ const PREWARM_PATHS = ["/_skydive/prewarm", "/_anyone/prewarm"];
2848
+ const PASSTHROUGH_HEADER_PREFIXES = ["x-anyone-", "x-skydive-"];
2849
+ function createHarness(options) {
2850
+ initTracing();
2851
+ startFeatureFlagPoller();
2852
+ readPlatformVersions().then((runtimeVersions) => logger.info({
2853
+ event: "runtime_versions",
2854
+ runtimeVersions
2855
+ }, "platform runtime versions"));
2856
+ const serverOptions = {
2857
+ ...options,
2858
+ onSessionSetup: options.onSessionSetup ?? ((args) => {
2859
+ installToolUpdateAutoStop(args);
2860
+ installIterationCap(args);
2861
+ }),
2862
+ postPrompt: options.postPrompt ?? (async (args) => {
2863
+ await runToolUpdateLoop(args);
2864
+ await runClosingTextLoop(args);
2865
+ }),
2866
+ passthroughHeaderPrefixes: options.passthroughHeaderPrefixes ?? PASSTHROUGH_HEADER_PREFIXES,
2867
+ prewarmPaths: options.prewarmPaths ?? PREWARM_PATHS
2868
+ };
2869
+ const webHandlers = createProtocolHandlers(serverOptions);
2870
+ const cardOverrides = {
2871
+ name: "Skydive Agent",
2872
+ description: "An AI coding agent powered by the Skydive platform.",
2873
+ ...options.agentCard
2874
+ };
2875
+ const agentCardWeb = async (request) => {
2876
+ const url = new URL(request.url);
2877
+ if (request.method !== "GET" || url.pathname !== AGENT_CARD_PATH) return null;
2878
+ return Response.json(buildAgentCard(cardOverrides.url ?? `${url.origin}${A2A_PATH}`, cardOverrides));
2879
+ };
2880
+ const a2a = restHandler({
2881
+ requestHandler: new DefaultRequestHandler(buildAgentCard(cardOverrides.url ?? A2A_PATH, cardOverrides), new InMemoryTaskStore(), createAgentExecutor(serverOptions), new DefaultExecutionEventBusManager()),
2882
+ userBuilder: UserBuilder.noAuthentication
2883
+ });
2884
+ return {
2885
+ platform: { handlers: {
2886
+ /**
2887
+ * Platform health plus the agent's `healthMetadata`. Mount above
2888
+ * injectEnv — health must respond immediately for prewarm
2889
+ * stashing and readiness probes, and injectEnv can wait up to
2890
+ * 10s for env vars during boot.
2891
+ */
2892
+ health: createHealthHandler({ metadata: options.healthMetadata ?? null }),
2893
+ /** Loads platform env (e2b envd / daemon long-poll). */
2894
+ injectEnv: createPlatformEnvMiddleware(),
2895
+ prewarm: webHandlerToMiddleware(webHandlers.prewarm)
2896
+ } },
2897
+ protocols: { handlers: {
2898
+ /** Express-style; mount at /a2a. */
2899
+ a2a,
2900
+ /** GET /.well-known/agent-card.json. */
2901
+ agentCard: webHandlerToMiddleware(agentCardWeb),
2902
+ /** Mirrors each vendor's API shape. */
2903
+ openai: { v1: {
2904
+ chat: { completions: webHandlerToMiddleware(webHandlers.chatCompletions) },
2905
+ responses: webHandlerToMiddleware(webHandlers.responses)
2906
+ } },
2907
+ anthropic: { v1: { messages: webHandlerToMiddleware(webHandlers.messages) } },
2908
+ /**
2909
+ * Everything in one mount: a2a (+ agent card) at their well-known
2910
+ * paths, then chat-completions / anthropic-messages / responses.
2911
+ * Calls next() when nothing matches.
2912
+ */
2913
+ all: chainMiddleware([mountAt(A2A_PATH, a2a), webHandlerToMiddleware(composeHandlers([
2914
+ agentCardWeb,
2915
+ webHandlers.chatCompletions,
2916
+ webHandlers.messages,
2917
+ webHandlers.responses
2918
+ ]))])
2919
+ } }
2920
+ };
2921
+ }
2922
+ /** Effective bash timeout: the model's value when it gave a positive number, else the default. */
2923
+ function resolveBashTimeout(provided) {
2924
+ return typeof provided === "number" && provided > 0 ? provided : 600;
2925
+ }
2926
+ const bashDefaultTimeoutExtension = (pi) => {
2927
+ pi.on("tool_call", async (event) => {
2928
+ if (event.toolName !== "bash") return;
2929
+ event.input.timeout = resolveBashTimeout(event.input.timeout);
2930
+ });
2931
+ };
2932
+ //#endregion
2933
+ //#region src/extensions/resource-pressure-warning.ts
2934
+ /**
2935
+ * Mid-run resource-pressure warning to the agent.
2936
+ *
2937
+ * The sandbox already detects pressure — the boot scripts cap the
2938
+ * user-workload cgroup (memory.high/memory.max) and watchers log warn/crit
2939
+ * edges for memory and disk — but nothing told the *agent*, so a turn burned
2940
+ * straight to the OOM kill (or a full disk) and only learned about it from
2941
+ * the post-mortem notice. This extension closes that gap in-process: while a
2942
+ * turn is active it polls the agent cgroup and the root filesystem and, the
2943
+ * first time usage crosses a warn threshold, folds a system notification into
2944
+ * the open turn so the agent can checkpoint, shed work (constrain
2945
+ * parallelism, kill a background hog, clean scratch space), or request a
2946
+ * bigger tier BEFORE the kill.
2947
+ *
2948
+ * The notification is triggered by the two conditions that actually kill
2949
+ * work — memory near the cgroup hard cap, disk near full — and reports a
2950
+ * snapshot of all the relevant stats (memory, CPU utilization, disk) so the
2951
+ * agent can tell which resource is the problem and how much headroom the
2952
+ * others have.
2953
+ *
2954
+ * Edge-triggered, once per trigger per turn: the fired flags reset on
2955
+ * agent_start, so a turn that rides a threshold gets one warning per
2956
+ * resource, not a stream. Polling only runs while the agent is active — an
2957
+ * idle sandbox's resource usage is not the agent's problem and there is no
2958
+ * open turn to deliver into anyway.
2959
+ *
2960
+ * Best-effort throughout: any read failure (cgroup absent, controller not
2961
+ * delegated, non-cgroup-v2 host, df missing) reads as "no signal" for that
2962
+ * stat and the extension warns on what it can see — it must never break a
2963
+ * turn over an observability feature.
2964
+ */
2965
+ const execFileAsync = promisify(execFile);
2966
+ const log$9 = logger.child({ module: "resource-pressure-warning" });
2967
+ const POLL_INTERVAL_MS = 1e4;
2968
+ function envOverride(name) {
2969
+ for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
2970
+ const value = process.env[`${prefix}${name}`];
2971
+ if (value != null && value !== "") return value;
2972
+ }
2973
+ return null;
2974
+ }
2975
+ function cgroupDir() {
2976
+ return envOverride("AGENT_CGROUP") ?? "/sys/fs/cgroup/agent";
2977
+ }
2978
+ function diskRoot() {
2979
+ return envOverride("DISK_ROOT") ?? "/";
2980
+ }
2981
+ /**
2982
+ * Read a cgroup v2 scalar file. Returns a number, or null for "max"
2983
+ * (uncapped), an empty/absent file, or any read/parse error — an uncapped or
2984
+ * unreadable limit means there is nothing meaningful to warn against.
2985
+ */
2986
+ async function readScalar(file) {
2987
+ try {
2988
+ const raw = (await readFile(`${cgroupDir()}/${file}`, "utf8")).trim();
2989
+ if (raw === "" || raw === "max") return null;
2990
+ const n = Number(raw);
2991
+ return Number.isFinite(n) ? n : null;
2992
+ } catch (_error) {
2993
+ return null;
2994
+ }
2995
+ }
2996
+ /**
2997
+ * Read a cgroup v2 "flat keyed" file (one `key value` pair per line, e.g.
2998
+ * cpu.stat) and return the counter for `key`, or null when absent.
2999
+ */
3000
+ async function readKeyedCounter(file, key) {
3001
+ try {
3002
+ const raw = await readFile(`${cgroupDir()}/${file}`, "utf8");
3003
+ for (const line of raw.split("\n")) {
3004
+ const [k, v] = line.trim().split(/\s+/);
3005
+ if (k === key) {
3006
+ const n = Number(v);
3007
+ return Number.isFinite(n) ? n : null;
3008
+ }
3009
+ }
3010
+ return null;
3011
+ } catch (_error) {
3012
+ return null;
3013
+ }
3014
+ }
3015
+ /**
3016
+ * Live memory usage as an integer percent of the hard cap, or null when
3017
+ * either side is unreadable/uncapped. Exported for tests.
3018
+ */
3019
+ async function readMemUsePct() {
3020
+ const [current, max] = await Promise.all([readScalar("memory.current"), readScalar("memory.max")]);
3021
+ if (current === null || max === null || max <= 0) return null;
3022
+ return {
3023
+ pct: Math.floor(current / max * 100),
3024
+ currentBytes: current,
3025
+ maxBytes: max
3026
+ };
3027
+ }
3028
+ /**
3029
+ * Root filesystem used% (df -P Capacity column), or null on any failure.
3030
+ * Exported for tests.
3031
+ */
3032
+ async function readDiskUsePct() {
3033
+ try {
3034
+ const { stdout } = await execFileAsync("df", ["-P", diskRoot()]);
3035
+ const dataRow = stdout.trim().split("\n")[1];
3036
+ if (dataRow == null) return null;
3037
+ const capacity = dataRow.trim().split(/\s+/)[4];
3038
+ if (capacity == null) return null;
3039
+ const pct = Number(capacity.replace("%", ""));
3040
+ return Number.isFinite(pct) ? pct : null;
3041
+ } catch (_error) {
3042
+ return null;
3043
+ }
3044
+ }
3045
+ /**
3046
+ * CPU utilization sampler. cgroup v2 exposes cumulative CPU time
3047
+ * (cpu.stat usage_usec); utilization is the delta between two samples over
3048
+ * the wall time between them, normalized by core count. The first call after
3049
+ * construction has no previous sample and returns null.
3050
+ */
3051
+ function createCpuSampler() {
3052
+ let prevUsageUsec = null;
3053
+ let prevAtMs = null;
3054
+ return async () => {
3055
+ const usage = await readKeyedCounter("cpu.stat", "usage_usec");
3056
+ const now = Date.now();
3057
+ const prev = prevUsageUsec;
3058
+ const prevAt = prevAtMs;
3059
+ prevUsageUsec = usage;
3060
+ prevAtMs = now;
3061
+ if (usage === null || prev === null || prevAt === null) return null;
3062
+ const wallUsec = (now - prevAt) * 1e3;
3063
+ if (wallUsec <= 0) return null;
3064
+ const cores = availableParallelism();
3065
+ const pct = Math.round((usage - prev) / (wallUsec * cores) * 100);
3066
+ return Math.max(0, Math.min(100, pct));
3067
+ };
3068
+ }
3069
+ function fmtMb(bytes) {
3070
+ return Math.round(bytes / 1024 / 1024);
3071
+ }
3072
+ /** The model-facing warning text. Exported for tests. */
3073
+ function resourcePressureWarningText(trigger, { mem, cpuPct, diskPct }) {
3074
+ const stats = [];
3075
+ if (mem) stats.push(`memory ${mem.pct}% of cap (${fmtMb(mem.currentBytes)}/${fmtMb(mem.maxBytes)} MB)`);
3076
+ if (cpuPct !== null) stats.push(`CPU ${cpuPct}%`);
3077
+ if (diskPct !== null) stats.push(`disk ${diskPct}% full`);
3078
+ const lead = trigger === "memory" ? `Your sandbox is at ${mem?.pct}% of its memory cap. If usage keeps climbing, the kernel will kill the offending process and this turn may die with it.` : `Your sandbox's disk is ${diskPct}% full. If it fills completely, writes will start failing and this turn may die with them.`;
3079
+ const remedy = trigger === "memory" ? "checkpoint in-flight work (commit and push), then reduce the footprint — constrain parallelism, run heavy steps sequentially, or kill background processes you no longer need." : "checkpoint in-flight work (commit and push), then free space — clean build artifacts, caches, and scratch files you no longer need.";
3080
+ return `<system_notification>${lead} Current usage: ${stats.join(", ")}. Act now: ${remedy} If the workload genuinely needs more resources, request a bigger sandbox with \`platform compute request\`. This is an automated resource warning, not a message from the user; continue the task, adjusted.</system_notification>`;
3081
+ }
3082
+ const resourcePressureWarningExtension = (pi) => {
3083
+ let agentActive = false;
3084
+ let warnedMemThisTurn = false;
3085
+ let warnedDiskThisTurn = false;
3086
+ let timer = null;
3087
+ const sampleCpu = createCpuSampler();
3088
+ async function checkOnce() {
3089
+ if (!agentActive || warnedMemThisTurn && warnedDiskThisTurn) return;
3090
+ const [mem, cpuPct, diskPct] = await Promise.all([
3091
+ readMemUsePct(),
3092
+ sampleCpu(),
3093
+ readDiskUsePct()
3094
+ ]);
3095
+ let trigger = null;
3096
+ if (!warnedMemThisTurn && mem !== null && mem.pct >= 80) {
3097
+ trigger = "memory";
3098
+ warnedMemThisTurn = true;
3099
+ } else if (!warnedDiskThisTurn && diskPct !== null && diskPct >= 80) {
3100
+ trigger = "disk";
3101
+ warnedDiskThisTurn = true;
3102
+ }
3103
+ if (trigger === null) return;
3104
+ log$9.warn({
3105
+ trigger,
3106
+ mem,
3107
+ cpuPct,
3108
+ diskPct
3109
+ }, "resource pressure warning delivered to agent");
3110
+ await pi.sendMessage({
3111
+ customType: "anyone-resource-pressure-warning",
3112
+ content: resourcePressureWarningText(trigger, {
3113
+ mem,
3114
+ cpuPct,
3115
+ diskPct
3116
+ }),
3117
+ display: false
3118
+ }, {
3119
+ triggerTurn: true,
3120
+ deliverAs: "followUp"
3121
+ });
3122
+ }
3123
+ pi.on("agent_start", async () => {
3124
+ agentActive = true;
3125
+ warnedMemThisTurn = false;
3126
+ warnedDiskThisTurn = false;
3127
+ if (!timer) {
3128
+ timer = setInterval(() => {
3129
+ checkOnce().catch((err) => {
3130
+ log$9.error({ err }, "resource pressure check failed");
3131
+ });
3132
+ }, POLL_INTERVAL_MS);
3133
+ timer.unref?.();
3134
+ }
3135
+ });
3136
+ pi.on("agent_end", async () => {
3137
+ agentActive = false;
3138
+ if (timer) {
3139
+ clearInterval(timer);
3140
+ timer = null;
3141
+ }
3142
+ });
3143
+ };
3144
+ //#endregion
3145
+ //#region src/extensions/disk-guard.ts
3146
+ const log$8 = logger.child({ module: "disk-guard" });
3147
+ /**
3148
+ * In-band bypass. The guard is a safety net, not a jail: when the agent knows
3149
+ * a flagged command is genuinely safe (writing to a different mount, a tiny
3150
+ * bounded download, a delete-then-clone one-liner, an emergency it accepts the
3151
+ * risk on) it can force the command through by appending this marker as a
3152
+ * trailing shell comment. Kept as a comment so it never changes what the
3153
+ * command does, and matched case-insensitively with flexible spacing so the
3154
+ * agent doesn't have to reproduce it byte-for-byte.
3155
+ */
3156
+ const BYPASS_MARKER = /#\s*disk-guard:\s*allow\b/i;
3157
+ /** The exact marker text the block message tells the agent to append. */
3158
+ const BYPASS_HINT = "# disk-guard: allow";
3159
+ /**
3160
+ * Harness-level kill switch: set DISK_GUARD_DISABLE=1 to turn the guard off
3161
+ * entirely. This is the "I own my harness, let me opt out" knob — an agent
3162
+ * that boots its own harness can disable the guard for its whole process
3163
+ * without a code roll, and it's also the fleet-wide escape hatch if the
3164
+ * classifier ever misfires and blocks real work. The bare name is honored
3165
+ * first; the SKYDIVE_/ANYONE_ prefixes are accepted too for consistency with
3166
+ * the other env overrides. Empty/unset/"0"/"false" leave the guard on.
3167
+ */
3168
+ function guardDisabledByEnv() {
3169
+ for (const name of [
3170
+ "DISK_GUARD_DISABLE",
3171
+ "SKYDIVE_DISK_GUARD_DISABLE",
3172
+ "ANYONE_DISK_GUARD_DISABLE"
3173
+ ]) {
3174
+ const value = process.env[name];
3175
+ if (value != null && value !== "" && value !== "0" && value !== "false") return true;
3176
+ }
3177
+ return false;
3178
+ }
3179
+ /** True when the command carries the in-band bypass marker. */
3180
+ function hasBypassMarker(command) {
3181
+ return BYPASS_MARKER.test(command);
3182
+ }
3183
+ /**
3184
+ * Commands that reclaim space or merely inspect it. If any of these verbs
3185
+ * appears in the command line, we never block — otherwise the guard would trap
3186
+ * the agent by blocking the exact command it needs to dig out. Matched as
3187
+ * whole words so `remove-item` etc. don't accidentally match `rm`.
3188
+ */
3189
+ const RECLAIM_PATTERNS = [
3190
+ /\brm\b/,
3191
+ /\brmdir\b/,
3192
+ /\bdf\b/,
3193
+ /\bdu\b/,
3194
+ /\bncdu\b/,
3195
+ /\bfind\b[^|]*\s-delete\b/,
3196
+ /\btruncate\b/,
3197
+ /\bgit\s+(gc|prune|clean|worktree\s+remove|worktree\s+prune)\b/,
3198
+ /\b(yarn|npm|pnpm|bun)\s+.*\b(cache\s+clean|cache\s+clear|store\s+prune)\b/,
3199
+ /\bcache\s+(clean|clear|prune)\b/,
3200
+ /\b(docker|podman)\s+.*\bprune\b/,
3201
+ /\bapt(-get)?\s+clean\b/,
3202
+ /\bjournalctl\b[^|]*--vacuum/
3203
+ ];
3204
+ /**
3205
+ * File extensions that mean a download is actually LARGE — archives, disk
3206
+ * images, compiled/binary artifacts, model weights, media. A curl/wget is only
3207
+ * gated when it writes one of these; an API/page fetch to a `.json`/`.html`/
3208
+ * `.txt` file is tiny and must not be blocked. Derived from 4,144 real
3209
+ * commands: ~64% of `curl -o` uses were tiny fetches, only ~4% large.
3210
+ */
3211
+ const BIG_DOWNLOAD_EXT = "(?:tar\\.gz|tgz|tar|zip|iso|gz|bz2|xz|zst|deb|rpm|pkg|dmg|whl|jar|7z|img|mp4|mov|avi|mkv|onnx|gguf|safetensors|bin|node)";
3212
+ /**
3213
+ * Commands that consume a meaningful amount of disk. Kept deliberately tight
3214
+ * and high-precision: validated against 4,144 real commands from the last 7
3215
+ * days, the earlier "writes a file" heuristic flagged 82% of everything (a
3216
+ * `curl -o /tmp/x.json` API call is not a disk event). This set flags ~33%,
3217
+ * almost all genuinely large — real installs, clones, big-archive downloads,
3218
+ * extractions. What was DROPPED and why:
3219
+ * - `git fetch` / `git pull` — incremental on an existing clone, usually tiny.
3220
+ * - `git checkout` — overwhelmingly `git checkout <ref> -- <file>` or a
3221
+ * branch switch, ~zero net growth; the rare full materialization isn't
3222
+ * worth the false-positive rate.
3223
+ * - bare `curl -o` / `wget -o` — see BIG_DOWNLOAD_EXT above.
3224
+ * - loose `… build` — matched `--mode=skip-build`, `oxfmt … build`, prose.
3225
+ * The remaining big-disk op in escher is `git clone` and `git worktree add`
3226
+ * (which is really a checkout), both kept.
3227
+ */
3228
+ const SPACE_HUNGRY_PATTERNS = [
3229
+ /\bgit\s+clone\b/,
3230
+ /\bgit\s+worktree\s+add\b/,
3231
+ /\b(yarn|npm|pnpm|bun)\s+(install|add|ci)\b/,
3232
+ /\byarn\s*$/,
3233
+ /\byarn\s+--(?!version|help)\S/,
3234
+ /\bpip3?\s+install\b/,
3235
+ /\bapt(-get)?\s+install\b/,
3236
+ /\bnpm\s+pack\b/,
3237
+ /\bdocker\s+(build|pull)\b/,
3238
+ new RegExp(`\\b(?:curl|wget)\\b[^\\n]*\\s-[a-zA-Z]*[oO]\\b[^\\n]*\\.${BIG_DOWNLOAD_EXT}\\b`, "i"),
3239
+ new RegExp(`\\b(?:curl|wget)\\b[^\\n]*\\.${BIG_DOWNLOAD_EXT}\\b[^\\n]*\\s-[a-zA-Z]*[oO]\\b`, "i"),
3240
+ /\btar\s+[^\n|]*x[^\n|]*f/,
3241
+ /\bunzip\b/,
3242
+ /\bdd\b[^\n|]*\bof=/
3243
+ ];
3244
+ /**
3245
+ * True when the command reclaims or inspects space — these are always allowed,
3246
+ * even on a 100%-full box, so the agent can dig itself out.
3247
+ */
3248
+ function isReclaimCommand(command) {
3249
+ return RECLAIM_PATTERNS.some((re) => re.test(command));
3250
+ }
3251
+ /**
3252
+ * True when the command is likely to consume a meaningful amount of disk.
3253
+ * A reclaim/inspect command is never space-hungry — the reclaim check wins so a
3254
+ * `git worktree remove` or a `yarn cache clean` is never mistaken for growth.
3255
+ */
3256
+ function isSpaceHungryCommand(command) {
3257
+ if (isReclaimCommand(command)) return false;
3258
+ return SPACE_HUNGRY_PATTERNS.some((re) => re.test(command));
3259
+ }
3260
+ /**
3261
+ * The decision, factored out and pure so it's exhaustively testable without a
3262
+ * real filesystem. Block only when we have a disk reading, it's at/above the
3263
+ * critical threshold, the command is space-hungry (and not a reclaim), and the
3264
+ * agent hasn't explicitly opted out with the bypass marker.
3265
+ */
3266
+ function shouldBlockForDisk(command, diskPct) {
3267
+ if (diskPct === null) return false;
3268
+ if (diskPct < 95) return false;
3269
+ if (hasBypassMarker(command)) return false;
3270
+ return isSpaceHungryCommand(command);
3271
+ }
3272
+ /** The agent-facing explanation returned as the blocked tool result. */
3273
+ function diskBlockReason(command, diskPct) {
3274
+ return `Blocked: the sandbox disk is ${diskPct}% full and this command (\`${command.trim().slice(0, 120)}\`) writes a large amount, so it would fail partway with ENOSPC and leave a corrupt result. Reclaim space FIRST, then retry. Free ONLY what THIS conversation created — scratch/build output you wrote this run, downloads you're done with, and worktrees/branches whose work you've already committed and pushed (\`git worktree remove\`, \`yarn cache clean\`, delete your own scratch). Do NOT blindly wipe /tmp or delete a clone/worktree you don't recognize — other conversations share this box. Check headroom with \`df -h /\` and \`du -sh ~/workspace/* 2>/dev/null\`. If you genuinely can't free enough, stop and tell the user you're blocked on disk rather than retrying the write. If you're certain this command is safe anyway (writes elsewhere, tiny bounded size, delete-then-write), force it through by appending \` ${BYPASS_HINT}\` to the command.`;
3275
+ }
3276
+ const diskGuardExtension = (pi) => {
3277
+ pi.on("tool_call", async (event) => {
3278
+ if (event.toolName !== "bash") return;
3279
+ if (guardDisabledByEnv()) return;
3280
+ const command = event.input.command;
3281
+ if (typeof command !== "string" || command.length === 0) return;
3282
+ if (hasBypassMarker(command)) return;
3283
+ if (!isSpaceHungryCommand(command)) return;
3284
+ const diskPct = await readDiskUsePct();
3285
+ if (!shouldBlockForDisk(command, diskPct)) return;
3286
+ log$8.warn({
3287
+ diskPct,
3288
+ command: command.slice(0, 200)
3289
+ }, "blocked space-hungry bash command on near-full disk");
3290
+ return {
3291
+ block: true,
3292
+ reason: diskBlockReason(command, diskPct)
3293
+ };
3294
+ });
3295
+ };
3296
+ //#endregion
1999
3297
  //#region src/extensions/context-management-trim.ts
2000
3298
  const CLEARED_PLACEHOLDER = "[old tool result cleared to save context — re-run the tool or re-read the source to recover it]";
2001
3299
  /** Rough token estimate (~4 chars/token); good enough for trigger decisions. */
@@ -2087,7 +3385,7 @@ function transformContextMessages(messages, config, now) {
2087
3385
  }
2088
3386
  //#endregion
2089
3387
  //#region src/extensions/context-management.ts
2090
- const log$8 = logger.child({ module: "context-management-extension" });
3388
+ const log$7 = logger.child({ module: "context-management-extension" });
2091
3389
  function isAnthropicMessagesPayload(payload) {
2092
3390
  if (typeof payload !== "object" || payload === null) return false;
2093
3391
  const candidate = payload;
@@ -2152,13 +3450,13 @@ function createContextManagementExtension() {
2152
3450
  setContextManagementFlagOverride(getPolledFlag("contextManagement"));
2153
3451
  onFlagChange("contextManagement", (enabled) => {
2154
3452
  setContextManagementFlagOverride(enabled);
2155
- log$8.info({
3453
+ log$7.info({
2156
3454
  event: "context_management_flag_update",
2157
3455
  enabled
2158
3456
  }, "context-management flag updated from platform");
2159
3457
  });
2160
3458
  startFeatureFlagPoller();
2161
- log$8.info({
3459
+ log$7.info({
2162
3460
  event: "context_management_registered",
2163
3461
  enabled: initial.enabled,
2164
3462
  flagSource: hasFlagSource(),
@@ -2170,13 +3468,13 @@ function createContextManagementExtension() {
2170
3468
  const { messages } = event;
2171
3469
  try {
2172
3470
  const result = transformContextIfEnabled(messages, getContextManagementConfig(), Date.now());
2173
- if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$8.info({
3471
+ if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$7.info({
2174
3472
  event: "context_management_applied",
2175
3473
  ...result.stats
2176
3474
  }, "trimmed/cleared tool output before LLM call");
2177
3475
  return { messages: result.messages };
2178
3476
  } catch (err) {
2179
- log$8.error({
3477
+ log$7.error({
2180
3478
  err,
2181
3479
  event: "context_management_transform_failed"
2182
3480
  }, "context transform failed; passing messages through unchanged");
@@ -2188,7 +3486,7 @@ function createContextManagementExtension() {
2188
3486
  }
2189
3487
  //#endregion
2190
3488
  //#region src/extensions/current-time.ts
2191
- const log$7 = logger.child({ module: "current-time-extension" });
3489
+ const log$6 = logger.child({ module: "current-time-extension" });
2192
3490
  const PI_DATE_LINE = /^Current date:.*$/m;
2193
3491
  function formatCurrentTimeLine(now) {
2194
3492
  return `Current date: ${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")} (${new Intl.DateTimeFormat("en-US", {
@@ -2201,7 +3499,7 @@ const currentTimeExtension = (pi) => {
2201
3499
  const line = formatCurrentTimeLine(/* @__PURE__ */ new Date());
2202
3500
  const base = event.systemPrompt;
2203
3501
  if (PI_DATE_LINE.test(base)) {
2204
- log$7.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)");
3502
+ 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)");
2205
3503
  return { systemPrompt: base.replace(PI_DATE_LINE, line) };
2206
3504
  }
2207
3505
  return { systemPrompt: `${base}\n${line}` };
@@ -2210,37 +3508,35 @@ const currentTimeExtension = (pi) => {
2210
3508
  //#endregion
2211
3509
  //#region src/memory.ts
2212
3510
  /**
2213
- * In-harness memory index builder.
2214
- *
2215
- * The agent has an agent-level file-based memory at `<cwd>/.memory/`,
2216
- * organized by directory:
3511
+ * In-harness memory readers.
2217
3512
  *
2218
- * .memory/users/<id>-<name>/<topic>.md
2219
- * .memory/projects/<project_slug>/<topic>.md
2220
- * .memory/feedback/<topic>.md
2221
- * .memory/reference/<topic>.md
3513
+ * The agent has an agent-level file-based memory at `<cwd>/.memory/`, split
3514
+ * into two halves that are surfaced differently:
2222
3515
  *
2223
- * The path encodes type and subject (for `users/`, the subject is the
2224
- * person's stable id with a readable name suffix); each `.md` file's
2225
- * frontmatter only carries `name` and `description`.
3516
+ * 1. Shared knowledge (projects, lessons, external systems) — indexed by a
3517
+ * single hand-maintained `<cwd>/.memory/MEMORY.md` that the *agent* writes
3518
+ * and curates, Claude-Code style: one line per fact pointing at the file
3519
+ * that holds it. `readMemoryIndexFile` just reads that file; the agent owns
3520
+ * its contents. This is the whole index for the shared half — there is no
3521
+ * derived walk and no per-directory `MEMORY.md`.
2226
3522
  *
2227
- * `buildMemoryIndex` walks `.memory/` by type directory, reads only the
2228
- * frontmatter of each `.md` (open fd → read first ~4KB → close, in
2229
- * parallel), and renders a markdown index grouped by type and (where
2230
- * applicable) by subject. Files outside the four type directories are
2231
- * ignored. Bodies are never read — the agent loads a specific memory's
2232
- * body on demand via the `read` tool when the index entry says it's
2233
- * relevant.
3523
+ * 2. Per-person memory — `.memory/users/<id>-<name>/<topic>.md`. This half is
3524
+ * *derived*, not hand-maintained, because it has to be filtered to the one
3525
+ * person on the current turn (a single hand-written index couldn't be
3526
+ * scoped per-user without leaking one person's notes into another's
3527
+ * conversation). `buildMemoryIndex` walks a single user's directory, reads
3528
+ * only the frontmatter of each `.md` (open fd → read first ~4KB → close, in
3529
+ * parallel), and renders an index. Each `.md`'s frontmatter carries `name`
3530
+ * and `description`; bodies are never read — the agent loads a specific
3531
+ * memory's body on demand via the `read` tool.
2234
3532
  *
2235
- * Mtime cache keyed by cwd — within the lifetime of a sandbox the cwd
2236
- * is fixed, so this is effectively a single-entry cache. Cache invalidates
2237
- * when any `.md` in the tree is added/modified/deleted; turns where
2238
- * memory didn't change reuse the cached string.
3533
+ * Mtime cache (for the derived per-user half) keyed by cwd — within the
3534
+ * lifetime of a sandbox the cwd is fixed, so this is effectively a single-entry
3535
+ * cache. It invalidates when any `.md` under `users/` is added/modified/
3536
+ * deleted; turns where memory didn't change reuse the cached entries.
2239
3537
  *
2240
- * Frontmatter is parsed as YAML (`yaml` package) and validated with a
2241
- * zod schema — files that don't match the shape are dropped from the
2242
- * index. The same schema can be reused at write time if we want to
2243
- * validate before commit.
3538
+ * Frontmatter is parsed as YAML (`yaml` package) and validated with a zod
3539
+ * schema — files that don't match the shape are dropped from the index.
2244
3540
  */
2245
3541
  const FRONTMATTER_READ_BYTES = 4096;
2246
3542
  const FrontmatterSchema = z.object({
@@ -2248,33 +3544,118 @@ const FrontmatterSchema = z.object({
2248
3544
  description: z.string().min(1)
2249
3545
  }).passthrough();
2250
3546
  const MEMORY_DIRNAME = ".memory";
2251
- const TYPE_DIRS = [
2252
- "users",
2253
- "projects",
2254
- "feedback",
2255
- "reference"
3547
+ const MEMORY_INDEX_FILENAME = "MEMORY.md";
3548
+ const USERS_DIRNAME = "users";
3549
+ /**
3550
+ * The shared-knowledge type dirs from the old frontmatter-indexed layout, used
3551
+ * only to seed a `MEMORY.md` for agents created before it existed (see
3552
+ * `seedMemoryIndexFile`). `users/` is deliberately excluded — per-person memory
3553
+ * stays derived and never lands in the shared, un-scoped `MEMORY.md`.
3554
+ */
3555
+ const LEGACY_SHARED_TYPES = [
3556
+ {
3557
+ dir: "projects",
3558
+ label: "Projects"
3559
+ },
3560
+ {
3561
+ dir: "feedback",
3562
+ label: "Feedback"
3563
+ },
3564
+ {
3565
+ dir: "reference",
3566
+ label: "Reference"
3567
+ }
2256
3568
  ];
2257
- const TYPES_WITH_SUBJECT = new Set(["users", "projects"]);
2258
- const TYPE_LABELS = {
2259
- users: "Users",
2260
- projects: "Projects",
2261
- feedback: "Feedback",
2262
- reference: "Reference"
2263
- };
3569
+ /**
3570
+ * Soft budget for an injected index block. The index is read and injected into
3571
+ * the system prompt on every turn, so every entry costs context for the rest of
3572
+ * the conversation. Past this size we nudge the agent to consolidate and prune
3573
+ * rather than keep appending. Not a hard cap — nothing is truncated.
3574
+ */
3575
+ const MEMORY_INDEX_SOFT_BUDGET_CHARS = 2e4;
3576
+ /**
3577
+ * Hard cap on the injected index — double the soft budget. The soft budget only
3578
+ * warns; this actually bounds what we inject so a runaway index can't consume
3579
+ * unbounded context on every turn. Past this, the index is truncated (on a line
3580
+ * boundary) before injection. It's a backstop, not a normal operating point.
3581
+ */
3582
+ const MEMORY_INDEX_HARD_BUDGET_CHARS = MEMORY_INDEX_SOFT_BUDGET_CHARS * 2;
3583
+ /**
3584
+ * Cheap size summary of a rendered index block, used to surface how much of the
3585
+ * every-turn context budget the index is spending so the agent keeps it lean.
3586
+ * Counts pointer/file lines — both the derived `` - `path` — desc`` form and
3587
+ * the hand-maintained `- [Title](path) — hook` form — not the group headers.
3588
+ */
3589
+ function summarizeIndex(index) {
3590
+ const entryCount = index.split("\n").filter((line) => /^\s*- (?:`|\[)/.test(line)).length;
3591
+ const charCount = index.length;
3592
+ return {
3593
+ entryCount,
3594
+ charCount,
3595
+ overBudget: charCount > MEMORY_INDEX_SOFT_BUDGET_CHARS
3596
+ };
3597
+ }
3598
+ /**
3599
+ * One-line size note for an index block header, e.g. `12 entries, 3187 chars`.
3600
+ */
3601
+ function indexSizeNote(index) {
3602
+ const { entryCount, charCount } = summarizeIndex(index);
3603
+ return `${entryCount} ${entryCount === 1 ? "entry" : "entries"}, ${charCount} chars`;
3604
+ }
3605
+ /**
3606
+ * An explicit warning to surface to the agent when an index has grown past its
3607
+ * budget, or `null` when it's within budget. Extensions render this prominently
3608
+ * above the index so the agent prunes before it keeps appending.
3609
+ */
3610
+ function indexBudgetWarning(index) {
3611
+ const { charCount, overBudget } = summarizeIndex(index);
3612
+ if (!overBudget) return null;
3613
+ return `⚠️ This memory index is ${charCount} chars, over its ${MEMORY_INDEX_SOFT_BUDGET_CHARS}-char budget. It's costing you context on every turn — consolidate duplicate entries and delete stale ones to bring it back under budget before adding anything new.`;
3614
+ }
3615
+ /**
3616
+ * Enforce the hard cap on an index before injection. Under the cap the index is
3617
+ * returned unchanged; over it, the index is truncated on a line boundary and a
3618
+ * notice is appended naming the true size so the agent knows entries are hidden
3619
+ * and must be pruned. This is the actual bound on injected context — callers
3620
+ * still report the true size via {@link indexSizeNote} so nothing is masked.
3621
+ */
3622
+ function enforceMemoryIndexHardBudget(index) {
3623
+ if (index.length <= 4e4) return index;
3624
+ const clipped = index.slice(0, MEMORY_INDEX_HARD_BUDGET_CHARS);
3625
+ const lastNewline = clipped.lastIndexOf("\n");
3626
+ return `${lastNewline > 0 ? clipped.slice(0, lastNewline) : clipped}\n\n⚠️ Memory index truncated at ${MEMORY_INDEX_HARD_BUDGET_CHARS} chars (it is ${index.length}). Entries past this point are NOT shown. Prune the index now — delete stale entries and consolidate duplicates.`;
3627
+ }
3628
+ /**
3629
+ * Read the agent's hand-maintained shared index at `.memory/MEMORY.md`.
3630
+ * Returns the trimmed contents, or `null` when the file is absent or empty —
3631
+ * the agent owns this file, so we surface exactly what it wrote.
3632
+ */
3633
+ async function readMemoryIndexFile({ cwd }) {
3634
+ const path = join(cwd, MEMORY_DIRNAME, MEMORY_INDEX_FILENAME);
3635
+ try {
3636
+ const trimmed = (await readFile(path, "utf-8")).trim();
3637
+ return trimmed.length > 0 ? trimmed : null;
3638
+ } catch {
3639
+ return null;
3640
+ }
3641
+ }
2264
3642
  const cache = /* @__PURE__ */ new Map();
2265
3643
  /**
3644
+ * Build the derived per-person index for a single user.
3645
+ *
2266
3646
  * Returns:
2267
- * - `null` if `.memory/` doesn't exist
2268
- * - `""` if the dir exists but contains nothing in the requested scope
3647
+ * - `null` if `.memory/users/` doesn't exist
3648
+ * - `""` if it exists but this user has no memory
2269
3649
  * - rendered markdown body (no surrounding header — caller wraps)
2270
3650
  *
2271
- * The mtime-keyed cache stores the raw walked entries (the cost is the FS
2272
- * walk); filtering by scope is cheap and runs per call, so two turns with
2273
- * different scopes on the same cwd render correctly from one cached walk.
3651
+ * Scoping by id keeps one person's memory from bleeding into another's
3652
+ * conversation. The mtime-keyed cache stores the raw walked entries (the cost
3653
+ * is the FS walk); filtering by user is cheap and runs per call, so two turns
3654
+ * with different users on the same cwd render correctly from one cached walk.
2274
3655
  */
2275
- async function buildMemoryIndex({ cwd, scope }) {
2276
- const memoryDirAbs = join(cwd, MEMORY_DIRNAME);
2277
- const maxMtimeMs = await maxMtimeAcrossDir(memoryDirAbs);
3656
+ async function buildMemoryIndex({ cwd, userId }) {
3657
+ const usersDirAbs = join(cwd, MEMORY_DIRNAME, USERS_DIRNAME);
3658
+ const maxMtimeMs = await maxMtimeAcrossDir(usersDirAbs);
2278
3659
  if (maxMtimeMs === null) {
2279
3660
  cache.delete(cwd);
2280
3661
  return null;
@@ -2282,13 +3663,13 @@ async function buildMemoryIndex({ cwd, scope }) {
2282
3663
  let cached = cache.get(cwd);
2283
3664
  if (!cached || cached.builtAtMs < maxMtimeMs) {
2284
3665
  cached = {
2285
- entries: await collectEntries(memoryDirAbs, cwd),
3666
+ entries: await collectUserEntries(usersDirAbs, cwd),
2286
3667
  builtAtMs: Date.now()
2287
3668
  };
2288
3669
  cache.set(cwd, cached);
2289
3670
  }
2290
- const visible = cached.entries.filter((entry) => scope.kind === "user" ? entry.type === "users" && entry.subject?.startsWith(scope.userId) === true : entry.type !== "users");
2291
- return visible.length === 0 ? "" : renderIndex(visible);
3671
+ const visible = cached.entries.filter((entry) => entry.subject.startsWith(userId));
3672
+ return visible.length === 0 ? "" : renderUserIndex(visible);
2292
3673
  }
2293
3674
  async function maxMtimeAcrossDir(dir) {
2294
3675
  let dirStat;
@@ -2336,45 +3717,22 @@ async function listSubdirs(dir) {
2336
3717
  }
2337
3718
  return entries.filter((e) => e.isDirectory()).map((e) => join(dir, e.name));
2338
3719
  }
2339
- async function collectEntries(rootDirAbs, cwd) {
2340
- const collected = [];
2341
- await Promise.all(TYPE_DIRS.map(async (type) => {
2342
- const typeDirAbs = join(rootDirAbs, type);
2343
- if (TYPES_WITH_SUBJECT.has(type)) {
2344
- const subjectDirs = await listSubdirs(typeDirAbs);
2345
- await Promise.all(subjectDirs.map(async (subjectDirAbs) => {
2346
- const subject = basename(subjectDirAbs);
2347
- const files = await listMdFilesShallow(subjectDirAbs);
2348
- const parsed = await Promise.all(files.map(async (file) => {
2349
- const fm = await readFrontmatterOnly(file);
2350
- if (!fm?.name || !fm?.description) return null;
2351
- return {
2352
- name: fm.name,
2353
- description: fm.description,
2354
- type,
2355
- subject,
2356
- relPath: relative(cwd, file)
2357
- };
2358
- }));
2359
- for (const e of parsed) if (e) collected.push(e);
2360
- }));
2361
- } else {
2362
- const files = await listMdFilesShallow(typeDirAbs);
2363
- const parsed = await Promise.all(files.map(async (file) => {
2364
- const fm = await readFrontmatterOnly(file);
2365
- if (!fm?.name || !fm?.description) return null;
2366
- return {
2367
- name: fm.name,
2368
- description: fm.description,
2369
- type,
2370
- subject: null,
2371
- relPath: relative(cwd, file)
2372
- };
2373
- }));
2374
- for (const e of parsed) if (e) collected.push(e);
2375
- }
2376
- }));
2377
- return collected;
3720
+ async function collectUserEntries(usersDirAbs, cwd) {
3721
+ const subjectDirs = await listSubdirs(usersDirAbs);
3722
+ return (await Promise.all(subjectDirs.map(async (subjectDirAbs) => {
3723
+ const subject = basename(subjectDirAbs);
3724
+ const files = await listMdFilesShallow(subjectDirAbs);
3725
+ return (await Promise.all(files.map(async (file) => {
3726
+ const fm = await readFrontmatterOnly(file);
3727
+ if (!fm?.name || !fm?.description) return null;
3728
+ return {
3729
+ name: fm.name,
3730
+ description: fm.description,
3731
+ subject,
3732
+ relPath: relative(cwd, file)
3733
+ };
3734
+ }))).filter((e) => e !== null);
3735
+ }))).flat();
2378
3736
  }
2379
3737
  async function readFrontmatterOnly(filePath) {
2380
3738
  let fh;
@@ -2405,77 +3763,189 @@ function parseFrontmatter(text) {
2405
3763
  const result = FrontmatterSchema.safeParse(parsed);
2406
3764
  return result.success ? result.data : null;
2407
3765
  }
2408
- function renderIndex(entries) {
2409
- const byType = {
2410
- users: [],
2411
- projects: [],
2412
- feedback: [],
2413
- reference: []
2414
- };
2415
- for (const e of entries) byType[e.type].push(e);
3766
+ function renderUserIndex(entries) {
3767
+ const bySubject = /* @__PURE__ */ new Map();
3768
+ for (const e of entries) {
3769
+ const list = bySubject.get(e.subject) ?? [];
3770
+ list.push(e);
3771
+ bySubject.set(e.subject, list);
3772
+ }
3773
+ const lines = ["### Users"];
3774
+ for (const subject of [...bySubject.keys()].sort()) {
3775
+ lines.push(`- **${subject}**`);
3776
+ for (const e of bySubject.get(subject) ?? []) lines.push(` - \`${e.relPath}\` — ${e.description}`);
3777
+ }
3778
+ return lines.join("\n");
3779
+ }
3780
+ /**
3781
+ * One-time migration for agents created before `MEMORY.md` existed. If there is
3782
+ * no hand-maintained `.memory/MEMORY.md` yet but the agent has shared memory
3783
+ * files from the old frontmatter-indexed layout (`projects/`, `feedback/`,
3784
+ * `reference/`), derive a `MEMORY.md` from their frontmatter and write it once.
3785
+ * After that the agent owns the file — this never runs again for that agent and
3786
+ * never clobbers an existing index.
3787
+ *
3788
+ * Returns the seeded contents (also written to disk), or `null` when nothing
3789
+ * was seeded (index already present, or no legacy shared files). A write
3790
+ * failure propagates so the caller can log it; the read path then falls back to
3791
+ * whatever is on disk.
3792
+ */
3793
+ async function seedMemoryIndexFile({ cwd }) {
3794
+ const memoryDirAbs = join(cwd, MEMORY_DIRNAME);
3795
+ const indexPath = join(memoryDirAbs, MEMORY_INDEX_FILENAME);
3796
+ if (await stat(indexPath).catch(() => null)) return null;
3797
+ const perType = await Promise.all(LEGACY_SHARED_TYPES.map(async ({ dir, label }) => {
3798
+ const typeDirAbs = join(memoryDirAbs, dir);
3799
+ const files = [];
3800
+ await walkMdFiles(typeDirAbs, files);
3801
+ return {
3802
+ label,
3803
+ entries: (await Promise.all(files.map(async (file) => {
3804
+ const fm = await readFrontmatterOnly(file);
3805
+ if (!fm?.name || !fm?.description) return null;
3806
+ return {
3807
+ name: fm.name,
3808
+ description: fm.description,
3809
+ relPath: relative(cwd, file)
3810
+ };
3811
+ }))).filter((e) => !!e)
3812
+ };
3813
+ }));
3814
+ if (perType.every((group) => group.entries.length === 0)) return null;
3815
+ const content = renderSeededIndex(perType);
3816
+ await writeFile(indexPath, `${content}\n`, "utf-8");
3817
+ return content;
3818
+ }
3819
+ function renderSeededIndex(groups) {
2416
3820
  const sections = [];
2417
- for (const type of TYPE_DIRS) {
2418
- const items = byType[type];
2419
- if (items.length === 0) continue;
2420
- sections.push(`### ${TYPE_LABELS[type]}`);
2421
- if (TYPES_WITH_SUBJECT.has(type)) {
2422
- const bySubject = /* @__PURE__ */ new Map();
2423
- for (const e of items) {
2424
- const subject = e.subject ?? "(unknown)";
2425
- const list = bySubject.get(subject) ?? [];
2426
- list.push(e);
2427
- bySubject.set(subject, list);
2428
- }
2429
- const subjects = [...bySubject.keys()].sort();
2430
- for (const subject of subjects) {
2431
- sections.push(`- **${subject}**`);
2432
- for (const e of bySubject.get(subject) ?? []) sections.push(` - \`${e.relPath}\` — ${e.description}`);
2433
- }
2434
- } else for (const e of items) sections.push(`- \`${e.relPath}\` — ${e.description}`);
3821
+ for (const { label, entries } of groups) {
3822
+ if (entries.length === 0) continue;
3823
+ sections.push(`### ${label}`);
3824
+ const sorted = [...entries].sort((a, b) => a.relPath.localeCompare(b.relPath));
3825
+ for (const e of sorted) sections.push(`- [${e.name}](${e.relPath}) — ${e.description}`);
2435
3826
  sections.push("");
2436
3827
  }
2437
3828
  return sections.join("\n").trimEnd();
2438
3829
  }
3830
+ /**
3831
+ * The version at which the hand-maintained `MEMORY.md` layout was introduced.
3832
+ * Used to classify an unversioned `.memory/`: if it already has a `MEMORY.md`
3833
+ * it's on this layout (not the pre-MEMORY.md v1 frontmatter layout), so it
3834
+ * shouldn't be treated as v1 and re-seeded.
3835
+ */
3836
+ const HAND_MAINTAINED_INDEX_VERSION = 2;
3837
+ const VERSION_FILENAME = ".version";
3838
+ const MEMORY_MIGRATIONS = [{
3839
+ from: 1,
3840
+ to: 2,
3841
+ apply: async ({ cwd }) => {
3842
+ await seedMemoryIndexFile({ cwd });
3843
+ }
3844
+ }];
3845
+ /**
3846
+ * The layout version of an agent's `.memory/`:
3847
+ * - `null` when there's no `.memory/` at all (a fresh agent is current by
3848
+ * construction; nothing to migrate).
3849
+ * - `1` when `.memory/` exists but carries no `.version` marker — i.e. it
3850
+ * predates versioning.
3851
+ * - otherwise the integer in `.memory/.version`.
3852
+ */
3853
+ async function readMemoryVersion(cwd) {
3854
+ const memoryDirAbs = join(cwd, MEMORY_DIRNAME);
3855
+ if (!(await stat(memoryDirAbs).catch(() => null))?.isDirectory()) return null;
3856
+ const raw = await readFile(join(memoryDirAbs, VERSION_FILENAME), "utf-8").catch(() => null);
3857
+ if (raw === null) return await stat(join(memoryDirAbs, MEMORY_INDEX_FILENAME)).then((s) => s.isFile()).catch(() => false) ? HAND_MAINTAINED_INDEX_VERSION : 1;
3858
+ const parsed = Number.parseInt(raw.trim(), 10);
3859
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 1;
3860
+ }
3861
+ async function writeMemoryVersion(cwd, version) {
3862
+ await writeFile(join(cwd, MEMORY_DIRNAME, VERSION_FILENAME), `${version}\n`, "utf-8");
3863
+ }
3864
+ /**
3865
+ * Bring an agent's `.memory/` up to `CURRENT_MEMORY_VERSION` by applying the
3866
+ * ordered migrations. Runs on session start. No-op when there's no `.memory/`
3867
+ * yet or it's already current. Migrations must be idempotent, so a lost/unwritten
3868
+ * version marker (the file isn't committed by the harness) only costs a repeated
3869
+ * no-op, never corruption. Returns the `{ from, to }` actually applied, or
3870
+ * `null` when nothing ran.
3871
+ */
3872
+ async function migrateMemory({ cwd }) {
3873
+ const from = await readMemoryVersion(cwd);
3874
+ if (from === null || from >= 2) return null;
3875
+ let version = from;
3876
+ while (version < 2) {
3877
+ const migration = MEMORY_MIGRATIONS.find((m) => m.from === version);
3878
+ if (!migration) break;
3879
+ await migration.apply({ cwd });
3880
+ version = migration.to;
3881
+ }
3882
+ await writeMemoryVersion(cwd, version);
3883
+ return {
3884
+ from,
3885
+ to: version
3886
+ };
3887
+ }
2439
3888
  //#endregion
2440
3889
  //#region src/extensions/memory.ts
2441
- const log$6 = logger.child({ module: "memory-extension" });
3890
+ const log$5 = logger.child({ module: "memory-extension" });
2442
3891
  /**
2443
3892
  * The standing instructions for the memory system. Always injected (even with
2444
- * an empty `.memory/`) so the agent knows it can persist notes. `users/` is
3893
+ * no `MEMORY.md`) so the agent knows it can persist notes and how. `users/` is
2445
3894
  * described by the platform memory extension, which is the only thing that can
2446
3895
  * scope it to a person — here we just point at it.
2447
3896
  */
2448
3897
  function memoryInstructions(cwd) {
2449
3898
  return `## Memory across conversations
2450
3899
 
2451
- Persistent notes across conversations live at \`${cwd}/.memory/\` — plain markdown files in your repo. The harness builds and injects an **index** of these files (paths + one-line descriptions) into your system prompt every turn; **bodies are NOT auto-loaded** — when an index entry looks relevant, use your \`read\` tool to load that specific file.
3900
+ Persistent notes across conversations live at \`${cwd}/.memory/\` — plain markdown files in your repo, one fact per file. You maintain a hand-written index of them at \`${cwd}/.memory/MEMORY.md\`, and the harness injects that index into your system prompt every turn. **Bodies are NOT auto-loaded** — when an index line looks relevant, use your \`read\` tool to load that specific file.
2452
3901
 
2453
3902
  Memory records **what happened**: facts you learned, events, investigation findings, project and system details worth carrying forward. It is NOT where behavior goes. A standing rule about how you should act — a "from now on, always/never …", a tone or format preference, a workflow convention a user wants you to follow — belongs in \`soul.md\` (see the Persona / Standing instructions section), not here. When a note is really an instruction about your behavior, write it to \`soul.md\`; when it is a fact or a record of something that occurred, write it here.
2454
3903
 
2455
- Shared knowledge is laid out as \`projects/<slug>/<topic>.md\` for project and system context, \`feedback/<topic>.md\` for concrete lessons learned from something that happened (the event and what it taught you — not a free-floating rule; the rule itself, if durable, goes in \`soul.md\`), and \`reference/<topic>.md\` for how external systems work. (Notes about a specific person live under \`users/\` and are shown separately, scoped to whoever you're talking to.) Each file's frontmatter declares \`name\` and \`description\` (the description is what shows up in the index, so make it a one-line behavior-triggering hook). Commit and push after writing to persist it.`;
3904
+ You own \`MEMORY.md\`. When you learn something durable, write the fact to its own \`.md\` file and add a one-line pointer to \`MEMORY.md\` in the form \`- [Title](relative/path.md) — one-line hook\`, where the hook is what tells future-you when to open the file. \`MEMORY.md\` is an *index*, never a store — put the actual content in the topic file and only a pointer line in \`MEMORY.md\`; do not inline a fact's body into the index even when it seems cheaper. Start each topic file with \`name:\`/\`description:\` frontmatter (the \`description\` is the one-line hook) so the index can be re-seeded, re-derived, or linted from the files themselves. When a fact changes, edit both the file and its line; when it stops being true, delete the file and its line. Shared knowledge is laid out as \`projects/<slug>/<topic>.md\` for project and system context, \`feedback/<topic>.md\` for concrete lessons learned from something that happened (the event and what it taught you — not a free-floating rule; the rule itself, if durable, goes in \`soul.md\`), and \`reference/<topic>.md\` for how external systems work. (Notes about a specific person live under \`users/\` and are indexed for you separately, scoped to whoever you're talking to — don't put people's private notes in the shared \`MEMORY.md\`.)
3905
+
3906
+ Keep \`MEMORY.md\` lean. It's re-injected on *every* turn, so a small, high-signal index is worth far more than an exhaustive one — curate it like a tightly-edited table of contents, not a log:
3907
+ - Be selective. Only record something durable that will matter in a *future* conversation. Don't record what only matters right now, what you can re-derive on demand, or what's already obvious from the repo.
3908
+ - Consolidate before you create. Before adding a line, scan \`MEMORY.md\` for one that already covers the topic; if it exists, \`read\` that file and rewrite it with the new facts merged in rather than adding a near-duplicate. One fact per file, but don't fragment a topic across many thin files.
3909
+ - Prune as you go. Delete lines (and their files) that are wrong, stale, or superseded. The index header reports its size — when it's flagged over budget, consolidate and delete before adding anything new.
3910
+ - Write dates absolute, not relative. Resolve "last week" / "yesterday" to a concrete date when you record it (e.g. "on 7/3 Dhruv told me to …"), so the note still reads correctly in a future conversation.
3911
+
3912
+ Commit and push after editing \`.memory/\` to persist it.`;
2456
3913
  }
2457
3914
  function composeBlock$1({ cwd, index }) {
2458
3915
  const instructions = memoryInstructions(cwd);
2459
3916
  if (!index || index.length === 0) return instructions;
2460
- return `${instructions}\n\n## Memory index\n\n${index}`;
3917
+ const header = `## Memory index (${indexSizeNote(index)})`;
3918
+ const warning = indexBudgetWarning(index);
3919
+ const rendered = enforceMemoryIndexHardBudget(index);
3920
+ return `${instructions}\n\n${warning ? `${header}\n\n${warning}\n\n${rendered}` : `${header}\n\n${rendered}`}`;
2461
3921
  }
2462
3922
  const memoryExtension = (pi) => {
2463
3923
  let cachedBlock = null;
2464
3924
  pi.on("session_start", async (_event, ctx) => {
2465
3925
  try {
2466
- const index = await buildMemoryIndex({
2467
- cwd: ctx.cwd,
2468
- scope: { kind: "shared" }
2469
- });
3926
+ const migrated = await migrateMemory({ cwd: ctx.cwd });
3927
+ if (migrated !== null) log$5.info({
3928
+ event: "memory_migrated",
3929
+ from: migrated.from,
3930
+ to: migrated.to
3931
+ }, "migrated memory layout to current version");
3932
+ } catch (err) {
3933
+ log$5.warn({
3934
+ err,
3935
+ event: "memory_migration_failed"
3936
+ }, "memory migration failed; continuing with existing index");
3937
+ }
3938
+ try {
3939
+ const index = await readMemoryIndexFile({ cwd: ctx.cwd });
2470
3940
  cachedBlock = composeBlock$1({
2471
3941
  cwd: ctx.cwd,
2472
3942
  index
2473
3943
  });
2474
3944
  } catch (err) {
2475
- log$6.warn({
3945
+ log$5.warn({
2476
3946
  err,
2477
3947
  event: "memory_index_failed"
2478
- }, "memory index build failed; injecting instructions only");
3948
+ }, "memory index read failed; injecting instructions only");
2479
3949
  cachedBlock = memoryInstructions(ctx.cwd);
2480
3950
  }
2481
3951
  });
@@ -2486,7 +3956,7 @@ const memoryExtension = (pi) => {
2486
3956
  };
2487
3957
  //#endregion
2488
3958
  //#region src/extensions/platform-memory.ts
2489
- const log$5 = logger.child({ module: "platform-memory-extension" });
3959
+ const log$4 = logger.child({ module: "platform-memory-extension" });
2490
3960
  /**
2491
3961
  * Resolve the human on this turn via the API, keyed by the message id.
2492
3962
  * `/sandbox/channel-context` only returns a sender for a platform-known
@@ -2499,13 +3969,13 @@ const log$5 = logger.child({ module: "platform-memory-extension" });
2499
3969
  async function resolveTurnUser(messageId) {
2500
3970
  const client = sandboxClient();
2501
3971
  if (!client) {
2502
- log$5.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
3972
+ log$4.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
2503
3973
  return null;
2504
3974
  }
2505
3975
  try {
2506
3976
  const res = await client["channel-context"].$get({ query: { messageId } });
2507
3977
  if (!res.ok) {
2508
- log$5.warn({
3978
+ log$4.warn({
2509
3979
  event: "resolve_turn_user_failed",
2510
3980
  status: res.status
2511
3981
  }, "channel-context returned non-ok; withholding user memory");
@@ -2518,7 +3988,7 @@ async function resolveTurnUser(messageId) {
2518
3988
  displayName: sender.displayName
2519
3989
  };
2520
3990
  } catch (err) {
2521
- log$5.warn({
3991
+ log$4.warn({
2522
3992
  err,
2523
3993
  event: "resolve_turn_user_failed"
2524
3994
  }, "failed to resolve current user; withholding user memory");
@@ -2534,9 +4004,12 @@ function slugifyName(name) {
2534
4004
  function composeBlock({ index, user }) {
2535
4005
  const instructions = `## Current user memory
2536
4006
 
2537
- Notes about the person on this turn — the only \`users/\` memory you can see. Store anything you learn about them under \`${`.memory/users/${user.id}-${slugifyName(user.displayName)}/`}<topic>.md\`, using exactly this directory. Other people's \`users/\` notes are never shown, so never address someone by a name you only find in memory.`;
4007
+ Notes about the person on this turn — the only \`users/\` memory you can see. Store anything you learn about them under \`${`.memory/users/${user.id}-${slugifyName(user.displayName)}/`}<topic>.md\`, using exactly this directory. Other people's \`users/\` notes are never shown, so never address someone by a name you only find in memory. Keep it lean and be selective — this is re-injected every turn; consolidate related facts into one file and delete what's stale rather than piling on near-duplicates.`;
2538
4008
  if (!index || index.length === 0) return instructions;
2539
- return `${instructions}\n\n${index}`;
4009
+ const warning = indexBudgetWarning(index);
4010
+ const header = `Memory index (${indexSizeNote(index)}):`;
4011
+ const rendered = enforceMemoryIndexHardBudget(index);
4012
+ return `${instructions}\n\n${warning ? `${warning}\n\n${header}\n\n${rendered}` : `${header}\n\n${rendered}`}`;
2540
4013
  }
2541
4014
  /**
2542
4015
  * Build the platform memory extension. `channelContext` is the per-turn ref
@@ -2557,15 +4030,12 @@ function createPlatformMemoryExtension({ channelContext }) {
2557
4030
  cachedBlock = composeBlock({
2558
4031
  index: await buildMemoryIndex({
2559
4032
  cwd: ctx.cwd,
2560
- scope: {
2561
- kind: "user",
2562
- userId: user.id
2563
- }
4033
+ userId: user.id
2564
4034
  }),
2565
4035
  user
2566
4036
  });
2567
4037
  } catch (err) {
2568
- log$5.warn({
4038
+ log$4.warn({
2569
4039
  err,
2570
4040
  event: "user_memory_index_failed"
2571
4041
  }, "user memory index build failed; skipping injection");
@@ -2579,8 +4049,22 @@ function createPlatformMemoryExtension({ channelContext }) {
2579
4049
  };
2580
4050
  }
2581
4051
  //#endregion
4052
+ //#region src/extensions/provider-api-compat.ts
4053
+ const OPENAI_COMPATIBLE_PROVIDERS = ["google", "openai"];
4054
+ const OPENAI_COMPLETIONS_API = "openai-completions";
4055
+ /**
4056
+ * Keep older harnesses compatible with provider-native model specs that use
4057
+ * the OpenAI-compatible wire through the transparent proxy.
4058
+ */
4059
+ const providerApiCompatExtension = (pi) => {
4060
+ for (const provider of OPENAI_COMPATIBLE_PROVIDERS) pi.registerProvider(provider, { models: getModels(provider).map((model) => ({
4061
+ ...model,
4062
+ api: OPENAI_COMPLETIONS_API
4063
+ })) });
4064
+ };
4065
+ //#endregion
2582
4066
  //#region src/extensions/self-trace.ts
2583
- const log$4 = logger.child({ module: "self-trace-extension" });
4067
+ const log$3 = logger.child({ module: "self-trace-extension" });
2584
4068
  /**
2585
4069
  * Reports the agent's own execution as OpenTelemetry spans:
2586
4070
  * agent.session → agent.run → agent.turn.N → tool.NAME, with token/cost
@@ -2605,7 +4089,7 @@ const selfTraceExtension = (pi) => {
2605
4089
  sessionSpan = tracer.startSpan("agent.session", { attributes: { "agent.model": modelId } }, remoteCtx);
2606
4090
  sessionCtx = trace.setSpan(remoteCtx, sessionSpan);
2607
4091
  const sc = sessionSpan.spanContext();
2608
- log$4.info({
4092
+ log$3.info({
2609
4093
  event: "self_trace_session_start",
2610
4094
  trace_id: sc.traceId,
2611
4095
  span_id: sc.spanId,
@@ -2717,13 +4201,13 @@ const selfTraceExtension = (pi) => {
2717
4201
  * Lives in the harness package — soul.md is content from the agent's
2718
4202
  * own git repo, not from the platform — so its handling stays here.
2719
4203
  */
2720
- const log$3 = logger.child({ module: "soul-extension" });
4204
+ const log$2 = logger.child({ module: "soul-extension" });
2721
4205
  async function readSoul(cwd) {
2722
4206
  try {
2723
4207
  return (await readFile(join(cwd, "soul.md"), "utf8")).trim() || null;
2724
4208
  } catch (err) {
2725
4209
  if (err?.code === "ENOENT") return null;
2726
- log$3.warn({
4210
+ log$2.warn({
2727
4211
  err,
2728
4212
  event: "soul_read_failed"
2729
4213
  }, "soul.md read failed");
@@ -2755,7 +4239,7 @@ const soulExtension = (pi) => {
2755
4239
  };
2756
4240
  //#endregion
2757
4241
  //#region src/extensions/subagent/index.ts
2758
- const log$2 = logger.child({ module: "subagent-ext" });
4242
+ const log$1 = logger.child({ module: "subagent-ext" });
2759
4243
  const MAX_TASKS = 8;
2760
4244
  const TaskItem = Type.Object({
2761
4245
  task: Type.String({ description: "The task to delegate to a subagent run." }),
@@ -2764,8 +4248,14 @@ const TaskItem = Type.Object({
2764
4248
  maxLength: 120
2765
4249
  }),
2766
4250
  persona: Type.Optional(Type.String({ description: "Optional extra system prompt / role for this task, applied ON TOP of the child run's own default persona (your full identity and soul are still there underneath). Omit to run with just your default persona." })),
2767
- model: Type.Optional(Type.String({ description: "Optional model id to run this subagent on. PREFER A LOWER-COST, FASTER MODEL when the task is well-scoped and does not need your full reasoning depth — most delegated subtasks (searching, summarizing, mechanical edits, gathering or reformatting data, running a check) run just as well on a lighter model and cost far less. Reserve a top-tier model for subtasks that genuinely need deep reasoning or careful judgment. Must be a real catalogued model id. Omit to inherit your own model. If you are locked to a Google-compliant model, only compliant models are accepted." }))
4251
+ model: Type.Optional(Type.String({ description: "Optional model id to run this subagent on. PREFER A LOWER-COST, FASTER MODEL when the task is well-scoped and does not need your full reasoning depth — most delegated subtasks (searching, summarizing, mechanical edits, gathering or reformatting data, running a check) run just as well on a lighter model and cost far less. Reserve a top-tier model for subtasks that genuinely need deep reasoning or careful judgment. Must be a real catalogued model id. Omit to inherit your own model. If you are locked to a Google-compliant model, only compliant models are accepted." })),
4252
+ timeoutMinutes: Type.Optional(Type.Integer({
4253
+ description: "Optional wall-clock timeout for this subagent, in minutes. If the run is still going after this long it is ended and you are rewoken with a timeout result, so a hung subagent can never strand you. Omit for the default (30 minutes). Raise it for genuinely long work (a big migration, a large audit); lower it for a quick lookup. Range 1-360.",
4254
+ minimum: 1,
4255
+ maximum: 360
4256
+ }))
2768
4257
  });
4258
+ const DEFAULT_SUBAGENT_TIMEOUT_MS = 30 * 6e4;
2769
4259
  const SubagentParams = Type.Object({ tasks: Type.Array(TaskItem, {
2770
4260
  description: "One or more tasks to delegate. Each spawns an isolated subagent run linked to this conversation; they run in parallel and each rewakes you with its result when it finishes.",
2771
4261
  minItems: 1,
@@ -2780,7 +4270,9 @@ function buildTool(messageId) {
2780
4270
  "Delegate one or more tasks to subagent runs — fresh isolated copies of yourself, each with its own context window, linked to this conversation.",
2781
4271
  "Use it to parallelize independent work, to keep a large or noisy subtask out of your own context, or to run a task under a specialized persona.",
2782
4272
  "Fire-and-forget: this returns immediately after queueing. It does NOT wait for results. Each subagent runs on its own and, when it finishes, sends you its result on this thread — so queue the work, then keep going or end your turn. To chain, re-delegate after a result lands.",
2783
- "Pass tasks: [{ task, title, persona?, model? }]. title is a short 3-6 word name for the task — it is shown to the person in the chat as that subagent's row, so name the work rather than restating the prompt. persona is an optional extra system prompt layered ON TOP of your default persona for that task (it adds to, it does not replace, your identity); omit it to run with just your default persona. model is an optional model id for that task — prefer a lower-cost, faster model for well-scoped subtasks that don't need deep reasoning, and reserve a top-tier model for the ones that do; omit it to inherit your own model."
4273
+ "Pass tasks: [{ task, title, persona?, model? }]. title is a short 3-6 word name for the task — it is shown to the person in the chat as that subagent's row, so name the work rather than restating the prompt. persona is an optional extra system prompt layered ON TOP of your default persona for that task (it adds to, it does not replace, your identity); omit it to run with just your default persona. model is an optional model id for that task — prefer a lower-cost, faster model for well-scoped subtasks that don't need deep reasoning, and reserve a top-tier model for the ones that do; omit it to inherit your own model.",
4274
+ "Peering: each queued task comes back with its own conversation id. A subagent is a real linked conversation, so to see what one is doing RIGHT NOW while it runs — its reasoning, the tools it has called and their results, its progress — read that conversation with `platform conversations show <conversationId>` (you are already authorized; it is your own delegated run). Check in that way instead of waiting blind for the final result. The read reflects the child's persisted state, which lags a few seconds behind live (tool results land as they complete; in-progress reasoning can be up to ~5s stale), so peek between checkpoints rather than polling in a tight loop.",
4275
+ "Steering: to add context, correct course, or answer a question a subagent needs mid-run, post to its conversation with `platform conversations post <conversationId> --message \"...\"`. If the subagent is still running, your message lands as a live steer picked up in that same turn; if it has gone idle, it queues as its next turn. This is the same primitive as any conversation message — there is no separate steer channel."
2784
4276
  ].join(" "),
2785
4277
  promptSnippet: "subagent — delegate tasks to isolated subagent runs; each rewakes you with its result when done",
2786
4278
  parameters: SubagentParams,
@@ -2798,28 +4290,39 @@ function buildTool(messageId) {
2798
4290
  task: t.task,
2799
4291
  title: t.title ?? null,
2800
4292
  persona: t.persona ?? null,
2801
- model: t.model ?? null
4293
+ model: t.model ?? null,
4294
+ timeoutMs: t.timeoutMinutes != null ? t.timeoutMinutes * 6e4 : DEFAULT_SUBAGENT_TIMEOUT_MS
2802
4295
  }));
2803
4296
  try {
2804
- const { taskIds } = await postSubagentSpawn({
4297
+ const spawned = await postSubagentSpawn({
2805
4298
  messageId,
2806
4299
  tasks: spawnTasks
2807
4300
  });
2808
- log$2.info({
4301
+ const { taskIds } = spawned;
4302
+ log$1.info({
2809
4303
  event: "subagent_spawned",
2810
4304
  count: taskIds.length
2811
4305
  }, "subagent tasks queued");
2812
- const lines = taskIds.map((id, i) => `- ${id}: ${spawnTasks[i]?.title ?? spawnTasks[i]?.task ?? ""}`).join("\n");
4306
+ const convByTask = new Map(spawned.tasks.map((t) => [t.taskId, t.conversationId]));
4307
+ const lines = taskIds.map((id, i) => {
4308
+ const label = spawnTasks[i]?.title ?? spawnTasks[i]?.task ?? "";
4309
+ const conv = convByTask.get(id);
4310
+ return conv ? `- conversation ${conv}: ${label} (taskId ${id})` : `- ${label} (taskId ${id}, conversation id unavailable — cannot peer this run)`;
4311
+ }).join("\n");
4312
+ const peerHint = spawned.tasks.length ? "\nEach subagent runs on its own conversation (id shown per task above). To SEE what one is doing while it runs, read it with `platform conversations show <conversationId>`. To STEER one mid-run — add context, correct course, answer a question — post to its conversation with `platform conversations post <conversationId> --message \"...\"`; it lands as a live steer if the subagent is still running, or as its next turn if it has gone idle." : "";
2813
4313
  return {
2814
4314
  content: [{
2815
4315
  type: "text",
2816
- text: `Queued ${taskIds.length} subagent ${taskIds.length === 1 ? "run" : "runs"}. Each runs on its own and will send you its result on this thread when it finishes — keep working or end your turn meanwhile.\n${lines}`
4316
+ text: `Queued ${taskIds.length} subagent ${taskIds.length === 1 ? "run" : "runs"}. Each runs on its own and will send you its result on this thread when it finishes — keep working or end your turn meanwhile.\n${lines}${peerHint}`
2817
4317
  }],
2818
- details: { taskIds }
4318
+ details: {
4319
+ taskIds,
4320
+ tasks: spawned.tasks
4321
+ }
2819
4322
  };
2820
4323
  } catch (err) {
2821
4324
  const message = err instanceof Error ? err.message : String(err);
2822
- log$2.warn({
4325
+ log$1.warn({
2823
4326
  err,
2824
4327
  event: "subagent_spawn_failed"
2825
4328
  }, "subagent spawn failed");
@@ -2850,7 +4353,7 @@ function createSubagentExtension({ channelContext }) {
2850
4353
  if (registered) return;
2851
4354
  registered = true;
2852
4355
  pi.registerTool(buildTool(messageId));
2853
- log$2.info({ event: "subagent_enabled" }, "subagent tool registered");
4356
+ log$1.info({ event: "subagent_enabled" }, "subagent tool registered");
2854
4357
  };
2855
4358
  pi.on("session_start", () => {
2856
4359
  registerOnce();
@@ -2858,6 +4361,69 @@ function createSubagentExtension({ channelContext }) {
2858
4361
  };
2859
4362
  }
2860
4363
  //#endregion
4364
+ //#region src/extensions/proactive-result.ts
4365
+ const contextSchema = z.object({
4366
+ proactiveAction: z.literal(true),
4367
+ runId: z.string().uuid(),
4368
+ messageId: z.string().uuid()
4369
+ });
4370
+ function createProactiveResultExtension({ channelContext }) {
4371
+ return (pi) => {
4372
+ if (!channelContext) return;
4373
+ let context;
4374
+ try {
4375
+ context = contextSchema.safeParse(JSON.parse(channelContext));
4376
+ } catch (_error) {
4377
+ return;
4378
+ }
4379
+ if (!context.success) return;
4380
+ const { runId, messageId } = context.data;
4381
+ let registered = false;
4382
+ pi.on("session_start", async () => {
4383
+ if (registered) return;
4384
+ const client = sandboxClient();
4385
+ if (!client) return;
4386
+ try {
4387
+ const response = await client["proactive-result"].$get({ query: {
4388
+ runId,
4389
+ messageId
4390
+ } });
4391
+ if (response.status === 404) return;
4392
+ if (!response.ok) throw new Error(`proactive result discovery failed: ${response.status}`);
4393
+ const { tool } = await response.json();
4394
+ if (!tool) return;
4395
+ pi.registerTool({
4396
+ name: tool.name,
4397
+ label: "Submit proactive result",
4398
+ description: tool.description,
4399
+ parameters: Type.Unsafe(tool.parameters),
4400
+ async execute(_toolCallId, result, signal) {
4401
+ const submitted = await client["proactive-result"].$post({ json: {
4402
+ runId,
4403
+ messageId,
4404
+ result
4405
+ } }, { init: { signal } });
4406
+ return {
4407
+ content: [{
4408
+ type: "text",
4409
+ text: await submitted.text()
4410
+ }],
4411
+ isError: !submitted.ok,
4412
+ details: {}
4413
+ };
4414
+ }
4415
+ });
4416
+ registered = true;
4417
+ } catch (err) {
4418
+ logger.warn({
4419
+ err,
4420
+ runId
4421
+ }, "proactive result tool unavailable; platform CLI submission remains available");
4422
+ }
4423
+ });
4424
+ };
4425
+ }
4426
+ //#endregion
2861
4427
  //#region src/extensions/tool-call-env.ts
2862
4428
  const TOOL_CALL_ID_VAR = "TOOL_CALL_ID";
2863
4429
  function shellQuoteValue(value) {
@@ -2884,214 +4450,6 @@ const toolCallEnvExtension = (pi) => {
2884
4450
  });
2885
4451
  };
2886
4452
  //#endregion
2887
- //#region src/extensions/tool-call-summary.ts
2888
- const log$1 = logger.child({ module: "tool-call-summary-extension" });
2889
- /**
2890
- * The injected parameter name: a namespaced sentinel, so it can never collide
2891
- * with a real tool argument and is unmistakable in transcripts and logs. The
2892
- * frontend renderer (ANY-2723) duplicates this literal — keep the two in sync.
2893
- */
2894
- const TOOL_CALL_SUMMARY_FIELD = "__skydive_summary__";
2895
- /** JSON Schema fragment for the injected parameter. */
2896
- const SUMMARY_PROPERTY = {
2897
- type: "string",
2898
- description: "Required for every tool call. A concise, specific summary (max ~8 words) of what THIS call does and why, written for a person watching the conversation, e.g. \"Searching feedback for billing complaints\" or \"Reading the auth middleware\". Address the user directly in second person: the summary is read by the user, so refer to their things as \"your\", never in third person — \"Reading your emails\", not \"Reading his emails\". Always use the present progressive tense, since it is shown while the call runs: \"Updating your Slack\", never \"Updated your Slack\". Make each summary distinct from your other tool calls; never reuse a generic label like \"Search query\" or \"Running command\"."
2899
- };
2900
- const jsonSchemaObjectSchema = z.object({
2901
- type: z.unknown().optional(),
2902
- properties: z.record(z.string(), z.unknown()).optional(),
2903
- required: z.array(z.string()).optional(),
2904
- additionalProperties: z.unknown().optional()
2905
- }).passthrough();
2906
- const toolEntrySchema = z.object({
2907
- name: z.string().optional(),
2908
- input_schema: jsonSchemaObjectSchema.optional(),
2909
- parameters: jsonSchemaObjectSchema.optional(),
2910
- function: z.object({
2911
- name: z.string().optional(),
2912
- parameters: jsonSchemaObjectSchema.optional()
2913
- }).passthrough().optional()
2914
- }).passthrough();
2915
- const payloadWithToolsSchema = z.object({ tools: z.array(z.unknown()) }).passthrough();
2916
- /**
2917
- * Add the summary property to one JSON Schema object. Returns the augmented
2918
- * copy, or `null` when the tool should be left untouched: a strict schema
2919
- * (`additionalProperties: false`) whose validation would reject the extra
2920
- * field, or one that already declares a `__skydive_summary__` property of its own.
2921
- */
2922
- function augmentSchema(schema) {
2923
- if (schema.additionalProperties === false) return null;
2924
- const properties = schema.properties ?? {};
2925
- if ("__skydive_summary__" in properties) return null;
2926
- const required = schema.required ?? [];
2927
- return {
2928
- ...schema,
2929
- type: schema.type ?? "object",
2930
- properties: {
2931
- [TOOL_CALL_SUMMARY_FIELD]: SUMMARY_PROPERTY,
2932
- ...properties
2933
- },
2934
- required: required.includes("__skydive_summary__") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
2935
- };
2936
- }
2937
- /**
2938
- * Augment a single tool entry, dispatching on which provider shape it is.
2939
- * Returns the (possibly rebuilt) entry and whether anything changed. Skipped
2940
- * tools — wrong shape, strict, or name in `strictToolNames` — return unchanged.
2941
- */
2942
- function augmentToolEntry(entry, strictToolNames) {
2943
- const parsed = toolEntrySchema.safeParse(entry);
2944
- if (!parsed.success) return {
2945
- entry,
2946
- changed: false
2947
- };
2948
- const tool = parsed.data;
2949
- const name = tool.name ?? tool.function?.name ?? null;
2950
- if (name !== null && strictToolNames.has(name)) return {
2951
- entry,
2952
- changed: false
2953
- };
2954
- if (tool.input_schema) {
2955
- const augmented = augmentSchema(tool.input_schema);
2956
- if (!augmented) return {
2957
- entry,
2958
- changed: false
2959
- };
2960
- return {
2961
- entry: {
2962
- ...tool,
2963
- input_schema: augmented
2964
- },
2965
- changed: true
2966
- };
2967
- }
2968
- if (tool.parameters) {
2969
- const augmented = augmentSchema(tool.parameters);
2970
- if (!augmented) return {
2971
- entry,
2972
- changed: false
2973
- };
2974
- return {
2975
- entry: {
2976
- ...tool,
2977
- parameters: augmented
2978
- },
2979
- changed: true
2980
- };
2981
- }
2982
- if (tool.function?.parameters) {
2983
- const augmented = augmentSchema(tool.function.parameters);
2984
- if (!augmented) return {
2985
- entry,
2986
- changed: false
2987
- };
2988
- return {
2989
- entry: {
2990
- ...tool,
2991
- function: {
2992
- ...tool.function,
2993
- parameters: augmented
2994
- }
2995
- },
2996
- changed: true
2997
- };
2998
- }
2999
- return {
3000
- entry,
3001
- changed: false
3002
- };
3003
- }
3004
- /**
3005
- * Inject the summary field into every eligible tool in a provider payload.
3006
- * Returns a new payload when at least one tool was augmented, or `undefined`
3007
- * to signal "no change" (which keeps the original payload, per the
3008
- * `before_provider_request` contract).
3009
- *
3010
- * @param payload The outgoing provider payload (shape varies by provider).
3011
- * @param strictToolNames Names of tools whose registered schema is strict and
3012
- * must be skipped to avoid validation errors.
3013
- */
3014
- function injectToolCallSummary(payload, strictToolNames) {
3015
- const parsed = payloadWithToolsSchema.safeParse(payload);
3016
- if (!parsed.success || parsed.data.tools.length === 0) return void 0;
3017
- let changed = false;
3018
- const tools = parsed.data.tools.map((entry) => {
3019
- const result = augmentToolEntry(entry, strictToolNames);
3020
- if (result.changed) changed = true;
3021
- return result.entry;
3022
- });
3023
- if (!changed) return void 0;
3024
- return {
3025
- ...parsed.data,
3026
- tools
3027
- };
3028
- }
3029
- /**
3030
- * Names of registered tools whose schema sets `additionalProperties: false`.
3031
- * Pi validates the model's tool args against this registered schema, so the
3032
- * injected field would make a strict tool's call fail validation — skip them.
3033
- */
3034
- function getStrictToolNames(pi) {
3035
- const names = /* @__PURE__ */ new Set();
3036
- for (const tool of pi.getAllTools()) {
3037
- const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
3038
- if (parsed.success && parsed.data.additionalProperties === false) names.add(tool.name);
3039
- }
3040
- return names;
3041
- }
3042
- function toolDeclaresSummaryParam(pi, toolName) {
3043
- const tool = pi.getAllTools().find((candidate) => candidate.name === toolName);
3044
- if (!tool) return false;
3045
- const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
3046
- return parsed.success && parsed.data.properties != null && "__skydive_summary__" in parsed.data.properties;
3047
- }
3048
- /**
3049
- * Remove the injected summary from a tool's execution input. No-op when the
3050
- * field is absent, or when the tool genuinely declares a `__skydive_summary__`
3051
- * parameter of its own (which we never inject into, so its value is real).
3052
- * Mutates `input` in place, matching the `tool_call` contract.
3053
- *
3054
- * Fails open: this runs on the critical path of tool execution, and the
3055
- * `getAllTools()` lookup can throw. On any error we leave `input` untouched
3056
- * (the sentinel may pass through to the tool, but a bug here can never break
3057
- * tool execution).
3058
- */
3059
- function stripInjectedSummary(pi, toolName, input) {
3060
- try {
3061
- if (!("__skydive_summary__" in input)) return;
3062
- if (toolDeclaresSummaryParam(pi, toolName)) return;
3063
- delete input[TOOL_CALL_SUMMARY_FIELD];
3064
- } catch (err) {
3065
- log$1.error({
3066
- err,
3067
- event: "tool_call_summary_strip_failed",
3068
- toolName
3069
- }, "tool_call_summary strip failed; leaving tool input untouched");
3070
- }
3071
- }
3072
- /**
3073
- * Compute the rewritten payload for a `before_provider_request` event, failing
3074
- * open: on any error the original payload is left untouched so a bug here can
3075
- * never break an LLM call.
3076
- */
3077
- function buildInjectedPayload(pi, payload) {
3078
- try {
3079
- return injectToolCallSummary(payload, getStrictToolNames(pi));
3080
- } catch (err) {
3081
- log$1.error({
3082
- err,
3083
- event: "tool_call_summary_injection_failed"
3084
- }, "tool_call_summary injection failed; passing payload through unchanged");
3085
- return;
3086
- }
3087
- }
3088
- const toolCallSummaryExtension = (pi) => {
3089
- pi.on("before_provider_request", (event) => buildInjectedPayload(pi, event.payload));
3090
- pi.on("tool_call", (event) => {
3091
- stripInjectedSummary(pi, event.toolName, event.input);
3092
- });
3093
- };
3094
- //#endregion
3095
4453
  //#region src/extensions/background-tasks.ts
3096
4454
  /**
3097
4455
  * Background bash tasks as a pi extension.
@@ -3131,21 +4489,43 @@ const toolCallSummaryExtension = (pi) => {
3131
4489
  * from the origin messageId in its channel context (`resolveConversationFromApi`)
3132
4490
  * — and every run of the same conversation resolves to the same id, keeping the
3133
4491
  * shared map correctly scoped across turns. `bg_*`, the completion wake, and the
3134
- * next-session injection all filter to the resolved conversation — an agent
3135
- * never sees or is woken by a task from a different chat. Only the output log
4492
+ * next-session injection all filter by a **scope key** — the resolved
4493
+ * conversation id, or, when a session's conversation is unresolvable (a bare
4494
+ * CLI session, or a run whose channel-context ref carries no messageId), a
4495
+ * sentinel unique to that one session instance. Comparing on the raw
4496
+ * `conversationId` would bucket every unresolvable session together under
4497
+ * `null` and leak one's completion wake / status / next-session injection into
4498
+ * another; the sentinel keeps each isolated so an agent never sees or is woken
4499
+ * by a task from a different chat. Only the output log
3136
4500
  * spills to disk (/home/user/.anyone/bg-tasks/<id>.log) to avoid buffering a chatty job
3137
4501
  * in memory; exit code and run state live on the in-memory task.
3138
4502
  *
3139
- * **No cross-restart survival (v1, deliberate).** Task state lives only in
3140
- * the running harness process. A harness restart (crash → supervisord
3141
- * respawn, or `platform harness reload` after the agent edits its own
3142
- * harness) drops the map and pi's exec children are reaped with it. We don't
3143
- * resurrect from disk because the common next-run case cold-provisions a
3144
- * *different* sandbox anyway (warm reuse is the minority in prod), so on-disk
3145
- * state would rarely be the box the next run lands on. The idle-completion wake
3146
- * does cross the sandbox → platform boundary (a fresh run via `bg-task-done`),
3147
- * but a task whose harness dies before it finishes is gone — it is not
3148
- * resurrected, and this stays distinct from the scheduled-run (cron) system.
4503
+ * **Cross-restart survival is OPT-IN, via `bg_run({ resumable: true })`.**
4504
+ * A non-resumable task's state lives only in the running harness process: a
4505
+ * harness restart (crash → supervisord respawn, `platform harness reload`, or
4506
+ * a sandbox recycle on idle timeout / redeploy / template rebuild) drops the
4507
+ * map and pi's exec children are reaped with it, and the task is gone — the
4508
+ * right behavior for a one-shot side-effecting command, which must never
4509
+ * silently re-run.
4510
+ *
4511
+ * A RESUMABLE task additionally checkpoints its *spec* (command, cwd, labels,
4512
+ * origin messageId — not its live output/exit state) to a durable, api-side
4513
+ * journal keyed by conversation (`/sandbox/bg-task-journal`, redis). On the
4514
+ * NEXT run's `session_start` — which usually lands on a *different*,
4515
+ * cold-provisioned sandbox, which is exactly why the journal is api-side and
4516
+ * not on the sandbox disk — the harness lists the journal and relaunches any
4517
+ * spec it isn't already running, keeping the original id and prepending a
4518
+ * `<resumed-after-restart>` banner so the agent knows it re-ran from scratch,
4519
+ * not continued. The spec is dropped from the journal when the task
4520
+ * finishes/kills. Because relaunch RE-EXECUTES the command, resumable is only
4521
+ * for idempotent, long-lived work (pollers, watchers, retry loops); the tool
4522
+ * description enforces this and the default is false.
4523
+ *
4524
+ * The idle-completion wake (a task finishing while the agent is idle) crosses
4525
+ * the sandbox → platform boundary via a fresh run (`bg-task-done`) for both
4526
+ * resumable and non-resumable tasks; the journal is a separate, additive layer
4527
+ * that only handles a task whose harness dies BEFORE it finishes. This stays
4528
+ * distinct from the scheduled-run (cron) system.
3149
4529
  */
3150
4530
  const log = logger.child({ module: "background-tasks-ext" });
3151
4531
  const ops = createLocalBashOperations();
@@ -3156,6 +4536,7 @@ const WATCHDOG_INTERVAL_MS = 3e4;
3156
4536
  const KEEPALIVE_EVERY_MS = 6e4;
3157
4537
  const KEEPALIVE_MAX_MS = 3600 * 1e3;
3158
4538
  const STALL_HINT_AFTER_MS = 120 * 1e3;
4539
+ const PUBLISH_DEBOUNCE_MS = 300;
3159
4540
  const MAX_LOG_BYTES = 100 * 1024 * 1024;
3160
4541
  const DEFAULT_TAIL_LINES = 30;
3161
4542
  const TAIL_READ_BYTES = 64 * 1024;
@@ -3163,11 +4544,12 @@ function taskLabel(meta) {
3163
4544
  return `${meta.id} "${meta.description ?? meta.command.slice(0, 60)}"`;
3164
4545
  }
3165
4546
  let taskCounter = 0;
4547
+ let sessionScopeCounter = 0;
3166
4548
  const tasks = /* @__PURE__ */ new Map();
3167
4549
  let watchdogInterval = null;
3168
4550
  let lastKeepaliveAt = 0;
3169
- function sameConversation(meta, conversationId) {
3170
- return meta.conversationId === conversationId;
4551
+ function sameScope(meta, scopeKey) {
4552
+ return meta.scopeKey === scopeKey;
3171
4553
  }
3172
4554
  function logPath(id) {
3173
4555
  return join(tasksDir(), `${id}.log`);
@@ -3280,6 +4662,10 @@ function createBackgroundTasksExtension({ channelContext }) {
3280
4662
  return id;
3281
4663
  });
3282
4664
  }
4665
+ const unresolvedScopeSentinel = `unresolved:${process.pid.toString(36)}:${(sessionScopeCounter += 1).toString(36)}`;
4666
+ function scopeKey() {
4667
+ return conversationId ?? unresolvedScopeSentinel;
4668
+ }
3283
4669
  let agentActive = false;
3284
4670
  pi.on("agent_start", async () => {
3285
4671
  agentActive = true;
@@ -3307,13 +4693,16 @@ ${recentOutput}
3307
4693
  </background-task-finished>
3308
4694
  Run bg_logs for the full output.
3309
4695
 
3310
- This is a background-task completion, not a message from the user. If it needs no user-facing response — a routine or expected finish, a leftover or self-killed process, nothing the user must act on or would want to know right now — call \`platform channel suppress-reply\` and output nothing. Only send a message if the outcome changes what the user should do or know, or if you were explicitly waiting to report this result.`,
4696
+ This is a background-task completion, not a message from the user.
4697
+ For a routine or expected completion, output nothing.
4698
+ Only reply if the outcome changes what the user should know or do,
4699
+ or if you were explicitly waiting to report it.`,
3311
4700
  display: false
3312
4701
  };
3313
4702
  }
3314
4703
  async function notifyCompletion(meta) {
3315
4704
  if (meta.notified) return;
3316
- if (agentActive && sameConversation(meta, conversationId)) {
4705
+ if (agentActive && sameScope(meta, scopeKey())) {
3317
4706
  meta.notified = true;
3318
4707
  pi.sendMessage(await taskDoneMessage(meta), {
3319
4708
  triggerTurn: true,
@@ -3344,9 +4733,83 @@ This is a background-task completion, not a message from the user. If it needs n
3344
4733
  });
3345
4734
  } else log.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
3346
4735
  }
3347
- async function launchTask({ command, description, cwd }) {
4736
+ const SNAPSHOT_TAIL_LINES = 40;
4737
+ let lastPublishedSignature = null;
4738
+ let publishInFlight = null;
4739
+ let publishQueued = false;
4740
+ function snapshotSignature(snapshot) {
4741
+ return JSON.stringify(snapshot.map((t) => ({
4742
+ id: t.id,
4743
+ state: t.state,
4744
+ exitCode: t.exitCode,
4745
+ killedReason: t.killedReason,
4746
+ outputTail: t.outputTail
4747
+ })));
4748
+ }
4749
+ async function doPublishSnapshot() {
4750
+ if (!messageId) return;
4751
+ const mine = [...tasks.values()].filter((t) => sameScope(t, scopeKey()));
4752
+ try {
4753
+ const snapshot = await Promise.all(mine.map(async (t) => ({
4754
+ id: t.id,
4755
+ command: t.command,
4756
+ description: t.description,
4757
+ startedAt: t.startedAt,
4758
+ state: t.running ? "running" : "finished",
4759
+ exitCode: t.exitCode,
4760
+ killedReason: t.killedReason,
4761
+ outputTail: await tailLog(t.id, SNAPSHOT_TAIL_LINES)
4762
+ })));
4763
+ const signature = snapshotSignature(snapshot);
4764
+ if (signature === lastPublishedSignature) return;
4765
+ lastPublishedSignature = signature;
4766
+ postBackgroundTasksSnapshot({
4767
+ messageId,
4768
+ tasks: snapshot
4769
+ });
4770
+ } catch (err) {
4771
+ log.debug({
4772
+ err,
4773
+ event: "bg_tasks_snapshot_build_failed"
4774
+ }, "building bg-tasks snapshot failed");
4775
+ }
4776
+ }
4777
+ async function publishSnapshotNow() {
4778
+ if (publishInFlight) {
4779
+ publishQueued = true;
4780
+ return;
4781
+ }
4782
+ publishInFlight = (async () => {
4783
+ try {
4784
+ do {
4785
+ publishQueued = false;
4786
+ await doPublishSnapshot();
4787
+ } while (publishQueued);
4788
+ } finally {
4789
+ publishInFlight = null;
4790
+ }
4791
+ })();
4792
+ await publishInFlight;
4793
+ }
4794
+ let publishTimer = null;
4795
+ function schedulePublishSnapshot() {
4796
+ if (publishTimer) return;
4797
+ publishTimer = setTimeout(() => {
4798
+ publishTimer = null;
4799
+ publishSnapshotNow();
4800
+ }, PUBLISH_DEBOUNCE_MS);
4801
+ publishTimer.unref?.();
4802
+ }
4803
+ async function flushPublishSnapshot() {
4804
+ if (publishTimer) {
4805
+ clearTimeout(publishTimer);
4806
+ publishTimer = null;
4807
+ }
4808
+ await publishSnapshotNow();
4809
+ }
4810
+ async function launchTask({ command, description, cwd, resumable = false, resumedFromJournal = false, id: providedId, startedAt: providedStartedAt }) {
3348
4811
  taskCounter += 1;
3349
- const id = `bg-${process.pid.toString(36)}-${taskCounter}`;
4812
+ const id = providedId ?? `bg-${process.pid.toString(36)}-${taskCounter}`;
3350
4813
  try {
3351
4814
  await mkdir(tasksDir(), { recursive: true });
3352
4815
  } catch (err) {
@@ -3362,7 +4825,7 @@ This is a background-task completion, not a message from the user. If it needs n
3362
4825
  taskId: id
3363
4826
  }, "bg task log write failed");
3364
4827
  });
3365
- const startedAt = Date.now();
4828
+ const startedAt = providedStartedAt ?? Date.now();
3366
4829
  const meta = {
3367
4830
  id,
3368
4831
  command: stripPlatformExportsForDisplay(command),
@@ -3370,6 +4833,7 @@ This is a background-task completion, not a message from the user. If it needs n
3370
4833
  logBytes: 0,
3371
4834
  lastOutputAt: startedAt,
3372
4835
  conversationId,
4836
+ scopeKey: scopeKey(),
3373
4837
  messageId,
3374
4838
  description,
3375
4839
  notified: false,
@@ -3377,9 +4841,23 @@ This is a background-task completion, not a message from the user. If it needs n
3377
4841
  controller: new AbortController(),
3378
4842
  running: true,
3379
4843
  exitCode: null,
3380
- error: null
4844
+ error: null,
4845
+ resumable,
4846
+ cwd,
4847
+ resumedFromJournal
3381
4848
  };
3382
4849
  tasks.set(id, meta);
4850
+ if (resumable && messageId) putBackgroundTaskJournalSpec({
4851
+ messageId,
4852
+ spec: {
4853
+ id,
4854
+ command,
4855
+ cwd,
4856
+ description,
4857
+ startedAt,
4858
+ messageId
4859
+ }
4860
+ });
3383
4861
  ops.exec(command, cwd, {
3384
4862
  onData: (chunk) => {
3385
4863
  meta.logBytes += chunk.length;
@@ -3405,6 +4883,11 @@ This is a background-task completion, not a message from the user. If it needs n
3405
4883
  taskId: id,
3406
4884
  exitCode: meta.exitCode
3407
4885
  }, "bg task finished");
4886
+ if (meta.resumable && meta.messageId) deleteBackgroundTaskJournalSpec({
4887
+ messageId: meta.messageId,
4888
+ taskId: id
4889
+ });
4890
+ schedulePublishSnapshot();
3408
4891
  await notifyCompletion(meta);
3409
4892
  });
3410
4893
  ensureWatchdog();
@@ -3412,19 +4895,55 @@ This is a background-task completion, not a message from the user. If it needs n
3412
4895
  taskId: id,
3413
4896
  conversationId
3414
4897
  }, "bg task started");
4898
+ schedulePublishSnapshot();
3415
4899
  return meta;
3416
4900
  }
3417
4901
  function knownTaskIds() {
3418
- return [...tasks.values()].filter((t) => sameConversation(t, conversationId)).map((t) => t.id).join(", ") || "(none)";
4902
+ return [...tasks.values()].filter((t) => sameScope(t, scopeKey())).map((t) => t.id).join(", ") || "(none)";
4903
+ }
4904
+ let journalChecked = false;
4905
+ async function rehydrateJournaledTasks() {
4906
+ if (!messageId || journalChecked) return;
4907
+ journalChecked = true;
4908
+ const specs = await listBackgroundTaskJournalSpecs({ messageId });
4909
+ if (specs.length === 0) return;
4910
+ for (const spec of specs) {
4911
+ const live = tasks.get(spec.id);
4912
+ if (live && sameScope(live, scopeKey())) continue;
4913
+ log.info({
4914
+ taskId: spec.id,
4915
+ conversationId
4916
+ }, "relaunching journaled resumable bg task after restart");
4917
+ const meta = await launchTask({
4918
+ command: spec.command,
4919
+ description: spec.description,
4920
+ cwd: spec.cwd,
4921
+ resumable: true,
4922
+ resumedFromJournal: true,
4923
+ id: spec.id,
4924
+ startedAt: spec.startedAt
4925
+ });
4926
+ try {
4927
+ const stream = createWriteStream(logPath(meta.id), { flags: "a" });
4928
+ 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`);
4929
+ stream.end();
4930
+ } catch (err) {
4931
+ log.debug({
4932
+ err,
4933
+ taskId: meta.id
4934
+ }, "resume banner write failed");
4935
+ }
4936
+ }
3419
4937
  }
3420
4938
  pi.on("session_start", async () => {
3421
- if (tasks.size === 0) return;
4939
+ if (tasks.size === 0 && (!messageId || journalChecked)) return;
3422
4940
  await ensureConversationId();
3423
- for (const [id, meta] of tasks) if (sameConversation(meta, conversationId) && !meta.running && meta.notified) {
4941
+ await rehydrateJournaledTasks();
4942
+ for (const [id, meta] of tasks) if (sameScope(meta, scopeKey()) && !meta.running && meta.notified) {
3424
4943
  tasks.delete(id);
3425
4944
  await unlink(logPath(id)).catch(() => {});
3426
4945
  }
3427
- const unnotified = [...tasks.values()].filter((t) => sameConversation(t, conversationId) && !t.notified && !t.running);
4946
+ const unnotified = [...tasks.values()].filter((t) => sameScope(t, scopeKey()) && !t.notified && !t.running);
3428
4947
  for (const meta of unnotified) {
3429
4948
  meta.notified = true;
3430
4949
  pi.sendMessage(await taskDoneMessage(meta));
@@ -3433,7 +4952,9 @@ This is a background-task completion, not a message from the user. If it needs n
3433
4952
  conversationId,
3434
4953
  count: unnotified.length
3435
4954
  }, "injected completed bg tasks at session_start");
3436
- if ([...tasks.values()].some((t) => sameConversation(t, conversationId) && t.running)) ensureWatchdog();
4955
+ if ([...tasks.values()].some((t) => sameScope(t, scopeKey()) && t.running)) ensureWatchdog();
4956
+ lastPublishedSignature = null;
4957
+ await flushPublishSnapshot();
3437
4958
  });
3438
4959
  function err(text) {
3439
4960
  return {
@@ -3450,11 +4971,11 @@ This is a background-task completion, not a message from the user. If it needs n
3450
4971
  }
3451
4972
  function resolveTask(taskId) {
3452
4973
  const exact = tasks.get(taskId);
3453
- if (exact && sameConversation(exact, conversationId)) return {
4974
+ if (exact && sameScope(exact, scopeKey())) return {
3454
4975
  error: null,
3455
4976
  meta: exact
3456
4977
  };
3457
- const matches = [...tasks.values()].filter((t) => sameConversation(t, conversationId) && t.id.startsWith(taskId));
4978
+ const matches = [...tasks.values()].filter((t) => sameScope(t, scopeKey()) && t.id.startsWith(taskId));
3458
4979
  if (matches.length === 1) return {
3459
4980
  error: null,
3460
4981
  meta: matches[0]
@@ -3463,7 +4984,7 @@ This is a background-task completion, not a message from the user. If it needs n
3463
4984
  return err(`Unknown task ${taskId}. Known tasks: ${knownTaskIds()}`);
3464
4985
  }
3465
4986
  function listTasks() {
3466
- const mine = [...tasks.values()].filter((t) => sameConversation(t, conversationId));
4987
+ const mine = [...tasks.values()].filter((t) => sameScope(t, scopeKey()));
3467
4988
  if (mine.length === 0) return "No background tasks.";
3468
4989
  return mine.map((t) => {
3469
4990
  const state = t.running ? "running" : t.exitCode !== null ? `exited ${t.exitCode}${t.killedReason ? ` (killed: ${t.killedReason})` : ""}` : t.killedReason ? `killed: ${t.killedReason}` : "ended";
@@ -3476,24 +4997,27 @@ This is a background-task completion, not a message from the user. If it needs n
3476
4997
  const bgRun = {
3477
4998
  name: "bg_run",
3478
4999
  label: "Run in background",
3479
- description: "Run a bash command in the background. Returns immediately with a task id; output streams to a log file. You are sent a message when it finishes — keep working or end your turn meanwhile. Use for anything over a couple of minutes (builds, batch jobs, retry loops, downloads). Inspect with bg_status / bg_logs, stop with bg_kill.",
3480
- promptSnippet: "bg_run — run a long command without blocking; you are notified on completion",
5000
+ description: "Run a bash command in the background. Returns immediately with a task id; output streams to a log file. You are sent a message when it finishes — keep working or end your turn meanwhile. Use for anything over a couple of minutes (builds, batch jobs, retry loops, downloads). Inspect with bg_status / bg_logs, stop with bg_kill. Pass resumable:true ONLY for an idempotent, long-lived command (a poller/watcher/retry loop) that should be requeued and relaunched on your next run if the sandbox goes away before it finishes (a sandbox is drained and replaced with a fresh one, not restarted in place) — the requeue re-runs the command from scratch, so never mark a one-shot side-effecting job (a migration, an apply, a send) resumable.",
5001
+ promptSnippet: "bg_run — run a long command without blocking; you are notified on completion (resumable:true requeues the task onto a fresh sandbox if the current one is drained, idempotent commands only)",
3481
5002
  parameters: Type.Object({
3482
5003
  command: Type.String({ description: "Bash command to execute" }),
3483
- description: Type.Optional(Type.String({ description: "Clear, concise description of what this command does in active voice (2-6 words)." }))
5004
+ description: Type.Optional(Type.String({ description: "Clear, concise description of what this command does in active voice (2-6 words)." })),
5005
+ resumable: Type.Optional(Type.Boolean({ description: "When true, this task is requeued and relaunched on your next run if the sandbox it is running on goes away before it finishes (a sandbox is drained and replaced with a fresh one, rather than restarted in place, so an in-flight task would otherwise be lost). Use ONLY for idempotent, long-lived commands (pollers, watchers, retry loops) — the requeue re-runs the command from scratch on the new sandbox, so never set this on a one-shot side-effecting command." }))
3484
5006
  }),
3485
5007
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3486
5008
  await ensureConversationId();
3487
- const { command, description = null } = params;
5009
+ const { command, description = null, resumable = false } = params;
3488
5010
  const meta = await launchTask({
3489
5011
  command,
3490
5012
  description,
3491
- cwd: ctx.cwd
5013
+ cwd: ctx.cwd,
5014
+ resumable
3492
5015
  });
5016
+ const resumeNote = resumable && meta.messageId ? "\nResumable: if this sandbox is drained before the task finishes, it will be requeued and relaunched from the start on your next run." : resumable ? "\nNote: resumable was requested but this session has no durable conversation, so it will NOT be requeued if the sandbox is drained." : "";
3493
5017
  return {
3494
5018
  content: [{
3495
5019
  type: "text",
3496
- text: `Started background task ${taskLabel(meta)}.\nlog: ${logPath(meta.id)}\nYou will get a message when it finishes. Check on it with bg_status {"taskId":"${meta.id}"}.`
5020
+ text: `Started background task ${taskLabel(meta)}.\nlog: ${logPath(meta.id)}\nYou will get a message when it finishes. Check on it with bg_status {"taskId":"${meta.id}"}.${resumeNote}\n\nProgress is already visible to the user. Output nothing unless the user asked for an update.`
3497
5021
  }],
3498
5022
  details: {}
3499
5023
  };
@@ -3522,7 +5046,7 @@ This is a background-task completion, not a message from the user. If it needs n
3522
5046
  return {
3523
5047
  content: [{
3524
5048
  type: "text",
3525
- text: await describeStatus(resolved.meta, lines)
5049
+ text: `${await describeStatus(resolved.meta, lines)}${resolved.meta.running ? "\n\nProgress is already visible to the user. Output nothing unless the user asked for an update." : ""}`
3526
5050
  }],
3527
5051
  details: {}
3528
5052
  };
@@ -3613,6 +5137,7 @@ const all = [
3613
5137
  localToolsExtension,
3614
5138
  toolCallEnvExtension,
3615
5139
  bashDefaultTimeoutExtension,
5140
+ diskGuardExtension,
3616
5141
  toolCallSummaryExtension
3617
5142
  ];
3618
5143
  /**
@@ -3623,6 +5148,7 @@ const all = [
3623
5148
  */
3624
5149
  function platformExtensions({ sessionId, channelContext }) {
3625
5150
  return [
5151
+ providerApiCompatExtension,
3626
5152
  createPlatformExtensions({
3627
5153
  sessionId,
3628
5154
  channelContext
@@ -3631,8 +5157,10 @@ function platformExtensions({ sessionId, channelContext }) {
3631
5157
  selfTraceExtension,
3632
5158
  createBackgroundTasksExtension({ channelContext }),
3633
5159
  createSubagentExtension({ channelContext }),
3634
- createContextManagementExtension()
5160
+ createProactiveResultExtension({ channelContext }),
5161
+ createContextManagementExtension(),
5162
+ resourcePressureWarningExtension
3635
5163
  ];
3636
5164
  }
3637
5165
  //#endregion
3638
- export { all, createHarness, createHealthHandler, createPlatformEnvMiddleware, installToolUpdateAutoStop, isPlatformConfigLoaded, loadPlatformConfig, localToolsExtension, mcp_default as mcpExtension, memoryExtension, platformExtensions, runToolUpdateLoop, soulExtension, toolCallEnvExtension };
5166
+ export { all, createHarness, createHealthHandler, createPlatformEnvMiddleware, installToolUpdateAutoStop, isPlatformConfigLoaded, loadPlatformConfig, localToolsExtension, mcp_default as mcpExtension, memoryExtension, platformExtensions, providerApiCompatExtension, runClosingTextLoop, runToolUpdateLoop, soulExtension, toolCallEnvExtension, turnEndedWithoutVisibleText };