@skydiveai/pi-extensions 0.1.0-beta.239 → 0.1.0-beta.2392
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.d.mts +49 -3
- package/dist/index.mjs +2146 -667
- package/package.json +4 -9
package/dist/index.mjs
CHANGED
|
@@ -2,24 +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
|
+
import { Ajv } from "ajv";
|
|
16
|
+
import addFormats from "ajv-formats";
|
|
15
17
|
import { Check, Errors } from "typebox/value";
|
|
18
|
+
import { hc } from "hono/client";
|
|
16
19
|
import { ROOT_CONTEXT, SpanStatusCode, propagation, trace } from "@opentelemetry/api";
|
|
17
20
|
import { W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
18
21
|
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
19
22
|
import { Resource } from "@opentelemetry/resources";
|
|
20
23
|
import { BatchSpanProcessor, NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
|
|
21
24
|
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
|
|
22
|
-
import {
|
|
25
|
+
import { execFile } from "node:child_process";
|
|
26
|
+
import { availableParallelism } from "node:os";
|
|
27
|
+
import { promisify } from "node:util";
|
|
23
28
|
import { parse } from "yaml";
|
|
24
29
|
import { quote } from "shell-quote";
|
|
25
30
|
import { createWriteStream } from "node:fs";
|
|
@@ -256,7 +261,7 @@ function createHealthHandler({ metadata }) {
|
|
|
256
261
|
* read on the hot path before every LLM call), it falls back to the default
|
|
257
262
|
* for that knob and logs once.
|
|
258
263
|
*/
|
|
259
|
-
const log$
|
|
264
|
+
const log$16 = logger.child({ module: "context-management-config" });
|
|
260
265
|
const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
|
|
261
266
|
enabled: false,
|
|
262
267
|
perResultMaxBytes: 16 * 1024,
|
|
@@ -304,7 +309,7 @@ function resolveContextManagementConfig(env = process.env) {
|
|
|
304
309
|
maxModelCallsPerTurn: env.SKYDIVE_CTX_MAX_MODEL_CALLS
|
|
305
310
|
});
|
|
306
311
|
if (!parsed.success) {
|
|
307
|
-
log$
|
|
312
|
+
log$16.warn({
|
|
308
313
|
event: "context_management_config_invalid",
|
|
309
314
|
err: parsed.error
|
|
310
315
|
}, "falling back to default context-management config");
|
|
@@ -415,6 +420,275 @@ function installIterationCap({ session, log }, configOverride = null) {
|
|
|
415
420
|
*/
|
|
416
421
|
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
422
|
//#endregion
|
|
423
|
+
//#region src/extensions/tool-call-summary.ts
|
|
424
|
+
const log$15 = logger.child({ module: "tool-call-summary-extension" });
|
|
425
|
+
/**
|
|
426
|
+
* The injected parameter name: a namespaced sentinel, so it can never collide
|
|
427
|
+
* with a real tool argument and is unmistakable in transcripts and logs. The
|
|
428
|
+
* frontend renderer (ANY-2723) duplicates this literal — keep the two in sync.
|
|
429
|
+
*/
|
|
430
|
+
const TOOL_CALL_SUMMARY_FIELD = "__skydive_summary__";
|
|
431
|
+
/** JSON Schema fragment for the injected parameter. */
|
|
432
|
+
const SUMMARY_PROPERTY = {
|
|
433
|
+
type: "string",
|
|
434
|
+
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\"."
|
|
435
|
+
};
|
|
436
|
+
const jsonSchemaObjectSchema = z.object({
|
|
437
|
+
type: z.unknown().optional(),
|
|
438
|
+
properties: z.record(z.string(), z.unknown()).optional(),
|
|
439
|
+
required: z.array(z.string()).optional(),
|
|
440
|
+
additionalProperties: z.unknown().optional()
|
|
441
|
+
}).passthrough();
|
|
442
|
+
const toolEntrySchema = z.object({
|
|
443
|
+
name: z.string().optional(),
|
|
444
|
+
input_schema: jsonSchemaObjectSchema.optional(),
|
|
445
|
+
parameters: jsonSchemaObjectSchema.optional(),
|
|
446
|
+
function: z.object({
|
|
447
|
+
name: z.string().optional(),
|
|
448
|
+
parameters: jsonSchemaObjectSchema.optional()
|
|
449
|
+
}).passthrough().optional()
|
|
450
|
+
}).passthrough();
|
|
451
|
+
const payloadWithToolsSchema = z.object({ tools: z.array(z.unknown()) }).passthrough();
|
|
452
|
+
/**
|
|
453
|
+
* Add the summary property to one JSON Schema object. Returns the augmented
|
|
454
|
+
* copy, or `null` when the tool should be left untouched: a strict schema
|
|
455
|
+
* (`additionalProperties: false`) whose validation would reject the extra
|
|
456
|
+
* field, or one that already declares a `__skydive_summary__` property of its own.
|
|
457
|
+
*/
|
|
458
|
+
function augmentSchema(schema) {
|
|
459
|
+
if (schema.additionalProperties === false) return null;
|
|
460
|
+
const properties = schema.properties ?? {};
|
|
461
|
+
if ("__skydive_summary__" in properties) return null;
|
|
462
|
+
const required = schema.required ?? [];
|
|
463
|
+
return {
|
|
464
|
+
...schema,
|
|
465
|
+
type: schema.type ?? "object",
|
|
466
|
+
properties: {
|
|
467
|
+
[TOOL_CALL_SUMMARY_FIELD]: SUMMARY_PROPERTY,
|
|
468
|
+
...properties
|
|
469
|
+
},
|
|
470
|
+
required: required.includes("__skydive_summary__") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Augment a single tool entry, dispatching on which provider shape it is.
|
|
475
|
+
* Returns the (possibly rebuilt) entry and whether anything changed. Skipped
|
|
476
|
+
* tools — wrong shape, strict, or name in `strictToolNames` — return unchanged.
|
|
477
|
+
*/
|
|
478
|
+
function augmentToolEntry(entry, strictToolNames) {
|
|
479
|
+
const parsed = toolEntrySchema.safeParse(entry);
|
|
480
|
+
if (!parsed.success) return {
|
|
481
|
+
entry,
|
|
482
|
+
changed: false
|
|
483
|
+
};
|
|
484
|
+
const tool = parsed.data;
|
|
485
|
+
const name = tool.name ?? tool.function?.name ?? null;
|
|
486
|
+
if (name !== null && strictToolNames.has(name)) return {
|
|
487
|
+
entry,
|
|
488
|
+
changed: false
|
|
489
|
+
};
|
|
490
|
+
if (tool.input_schema) {
|
|
491
|
+
const augmented = augmentSchema(tool.input_schema);
|
|
492
|
+
if (!augmented) return {
|
|
493
|
+
entry,
|
|
494
|
+
changed: false
|
|
495
|
+
};
|
|
496
|
+
return {
|
|
497
|
+
entry: {
|
|
498
|
+
...tool,
|
|
499
|
+
input_schema: augmented
|
|
500
|
+
},
|
|
501
|
+
changed: true
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
if (tool.parameters) {
|
|
505
|
+
const augmented = augmentSchema(tool.parameters);
|
|
506
|
+
if (!augmented) return {
|
|
507
|
+
entry,
|
|
508
|
+
changed: false
|
|
509
|
+
};
|
|
510
|
+
return {
|
|
511
|
+
entry: {
|
|
512
|
+
...tool,
|
|
513
|
+
parameters: augmented
|
|
514
|
+
},
|
|
515
|
+
changed: true
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
if (tool.function?.parameters) {
|
|
519
|
+
const augmented = augmentSchema(tool.function.parameters);
|
|
520
|
+
if (!augmented) return {
|
|
521
|
+
entry,
|
|
522
|
+
changed: false
|
|
523
|
+
};
|
|
524
|
+
return {
|
|
525
|
+
entry: {
|
|
526
|
+
...tool,
|
|
527
|
+
function: {
|
|
528
|
+
...tool.function,
|
|
529
|
+
parameters: augmented
|
|
530
|
+
}
|
|
531
|
+
},
|
|
532
|
+
changed: true
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
return {
|
|
536
|
+
entry,
|
|
537
|
+
changed: false
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Inject the summary field into every eligible tool in a provider payload.
|
|
542
|
+
* Returns a new payload when at least one tool was augmented, or `undefined`
|
|
543
|
+
* to signal "no change" (which keeps the original payload, per the
|
|
544
|
+
* `before_provider_request` contract).
|
|
545
|
+
*
|
|
546
|
+
* @param payload The outgoing provider payload (shape varies by provider).
|
|
547
|
+
* @param strictToolNames Names of tools whose registered schema is strict and
|
|
548
|
+
* must be skipped to avoid validation errors.
|
|
549
|
+
*/
|
|
550
|
+
function injectToolCallSummary(payload, strictToolNames) {
|
|
551
|
+
const parsed = payloadWithToolsSchema.safeParse(payload);
|
|
552
|
+
if (!parsed.success || parsed.data.tools.length === 0) return void 0;
|
|
553
|
+
let changed = false;
|
|
554
|
+
const tools = parsed.data.tools.map((entry) => {
|
|
555
|
+
const result = augmentToolEntry(entry, strictToolNames);
|
|
556
|
+
if (result.changed) changed = true;
|
|
557
|
+
return result.entry;
|
|
558
|
+
});
|
|
559
|
+
if (!changed) return void 0;
|
|
560
|
+
return {
|
|
561
|
+
...parsed.data,
|
|
562
|
+
tools
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Names of registered tools whose schema sets `additionalProperties: false`.
|
|
567
|
+
* Pi validates the model's tool args against this registered schema, so the
|
|
568
|
+
* injected field would make a strict tool's call fail validation — skip them.
|
|
569
|
+
*/
|
|
570
|
+
function getStrictToolNames(pi) {
|
|
571
|
+
const names = /* @__PURE__ */ new Set();
|
|
572
|
+
for (const tool of pi.getAllTools()) {
|
|
573
|
+
const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
|
|
574
|
+
if (parsed.success && parsed.data.additionalProperties === false) names.add(tool.name);
|
|
575
|
+
}
|
|
576
|
+
return names;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Whether a tool's own schema declares a `__skydive_summary__` property. We
|
|
580
|
+
* never inject into such a tool, so any value it carries is a real argument
|
|
581
|
+
* and must be left alone.
|
|
582
|
+
*/
|
|
583
|
+
function schemaDeclaresSummary(parameters) {
|
|
584
|
+
const parsed = jsonSchemaObjectSchema.safeParse(parameters);
|
|
585
|
+
return parsed.success && parsed.data.properties != null && "__skydive_summary__" in parsed.data.properties;
|
|
586
|
+
}
|
|
587
|
+
function toolDeclaresSummaryParam(pi, toolName) {
|
|
588
|
+
const tool = pi.getAllTools().find((candidate) => candidate.name === toolName);
|
|
589
|
+
if (!tool) return false;
|
|
590
|
+
return schemaDeclaresSummary(tool.parameters);
|
|
591
|
+
}
|
|
592
|
+
/** A copy of `args` without the injected summary. Never mutates its input. */
|
|
593
|
+
function withoutInjectedSummary(args) {
|
|
594
|
+
if (args == null || typeof args !== "object" || Array.isArray(args)) return args;
|
|
595
|
+
if (!("__skydive_summary__" in args)) return args;
|
|
596
|
+
const { [TOOL_CALL_SUMMARY_FIELD]: _summary, ...rest } = args;
|
|
597
|
+
return rest;
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Register a tool so the injected summary is removed *before* pi validates
|
|
601
|
+
* the model's arguments against the tool's schema.
|
|
602
|
+
*
|
|
603
|
+
* Needed because the `tool_call` strip below runs too late. pi-agent-core's
|
|
604
|
+
* `prepareToolCall` goes: `tool.prepareArguments` → `validateToolArguments` →
|
|
605
|
+
* `beforeToolCall` (which is what dispatches `tool_call`). A tool whose schema
|
|
606
|
+
* sets `additionalProperties: false` therefore rejects the summary and errors
|
|
607
|
+
* the call — client-side, before any request reaches the server — while the
|
|
608
|
+
* strip meant to prevent exactly that sits one step further down.
|
|
609
|
+
*
|
|
610
|
+
* `augmentSchema` already skips strict tools, but that only controls what the
|
|
611
|
+
* model is *told*. It still emits the field on those tools, because every
|
|
612
|
+
* other tool in the list declares it as required for every call. So a server
|
|
613
|
+
* can connect, bind its tools, present a healthy inventory, and have every
|
|
614
|
+
* call fail — and it reads as the server's fault when it is ours.
|
|
615
|
+
*
|
|
616
|
+
* Apply to tools registered from schemas we do not author: MCP servers and
|
|
617
|
+
* local `tools/*.ts`. Tools built here with `Type.Object(...)` do not need it
|
|
618
|
+
* (TypeBox emits no `additionalProperties`, so the field validates fine and
|
|
619
|
+
* the `tool_call` strip removes it in time).
|
|
620
|
+
*
|
|
621
|
+
* Fails open, like the rest of this module: if the strip throws, the original
|
|
622
|
+
* arguments are used rather than failing the call.
|
|
623
|
+
*/
|
|
624
|
+
function withSummaryStrippedBeforeValidation(tool) {
|
|
625
|
+
if (schemaDeclaresSummary(tool.parameters)) return tool;
|
|
626
|
+
const toolPrepare = tool.prepareArguments;
|
|
627
|
+
const prepareArguments = ((args) => {
|
|
628
|
+
let stripped = args;
|
|
629
|
+
try {
|
|
630
|
+
stripped = withoutInjectedSummary(args);
|
|
631
|
+
} catch (err) {
|
|
632
|
+
log$15.error({
|
|
633
|
+
err,
|
|
634
|
+
event: "tool_call_summary_prepare_strip_failed",
|
|
635
|
+
toolName: tool.name
|
|
636
|
+
}, "tool_call_summary pre-validation strip failed; leaving arguments untouched");
|
|
637
|
+
}
|
|
638
|
+
return toolPrepare ? toolPrepare(stripped) : stripped;
|
|
639
|
+
});
|
|
640
|
+
return {
|
|
641
|
+
...tool,
|
|
642
|
+
prepareArguments
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Remove the injected summary from a tool's execution input. No-op when the
|
|
647
|
+
* field is absent, or when the tool genuinely declares a `__skydive_summary__`
|
|
648
|
+
* parameter of its own (which we never inject into, so its value is real).
|
|
649
|
+
* Mutates `input` in place, matching the `tool_call` contract.
|
|
650
|
+
*
|
|
651
|
+
* Fails open: this runs on the critical path of tool execution, and the
|
|
652
|
+
* `getAllTools()` lookup can throw. On any error we leave `input` untouched
|
|
653
|
+
* (the sentinel may pass through to the tool, but a bug here can never break
|
|
654
|
+
* tool execution).
|
|
655
|
+
*/
|
|
656
|
+
function stripInjectedSummary(pi, toolName, input) {
|
|
657
|
+
try {
|
|
658
|
+
if (!("__skydive_summary__" in input)) return;
|
|
659
|
+
if (toolDeclaresSummaryParam(pi, toolName)) return;
|
|
660
|
+
delete input[TOOL_CALL_SUMMARY_FIELD];
|
|
661
|
+
} catch (err) {
|
|
662
|
+
log$15.error({
|
|
663
|
+
err,
|
|
664
|
+
event: "tool_call_summary_strip_failed",
|
|
665
|
+
toolName
|
|
666
|
+
}, "tool_call_summary strip failed; leaving tool input untouched");
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Compute the rewritten payload for a `before_provider_request` event, failing
|
|
671
|
+
* open: on any error the original payload is left untouched so a bug here can
|
|
672
|
+
* never break an LLM call.
|
|
673
|
+
*/
|
|
674
|
+
function buildInjectedPayload(pi, payload) {
|
|
675
|
+
try {
|
|
676
|
+
return injectToolCallSummary(payload, getStrictToolNames(pi));
|
|
677
|
+
} catch (err) {
|
|
678
|
+
log$15.error({
|
|
679
|
+
err,
|
|
680
|
+
event: "tool_call_summary_injection_failed"
|
|
681
|
+
}, "tool_call_summary injection failed; passing payload through unchanged");
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
const toolCallSummaryExtension = (pi) => {
|
|
686
|
+
pi.on("before_provider_request", (event) => buildInjectedPayload(pi, event.payload));
|
|
687
|
+
pi.on("tool_call", (event) => {
|
|
688
|
+
stripInjectedSummary(pi, event.toolName, event.input);
|
|
689
|
+
});
|
|
690
|
+
};
|
|
691
|
+
//#endregion
|
|
418
692
|
//#region src/extensions/local-tools.ts
|
|
419
693
|
/**
|
|
420
694
|
* Local-tools adapter as a pi extension. Mirrors the mcp.ts hot-reload pattern
|
|
@@ -438,7 +712,7 @@ const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task i
|
|
|
438
712
|
* or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
|
|
439
713
|
* `tools/_example.ts` documents the shape without registering.
|
|
440
714
|
*/
|
|
441
|
-
const log$
|
|
715
|
+
const log$14 = logger.child({ module: "local-tools-extension" });
|
|
442
716
|
const TOOLS_DIRNAME = "tools";
|
|
443
717
|
const fileState = /* @__PURE__ */ new Map();
|
|
444
718
|
let pendingLocalToolsUpdate = null;
|
|
@@ -565,7 +839,7 @@ async function reconcileLocalTools({ pi, dir }) {
|
|
|
565
839
|
action = existing ? "refreshed" : "added";
|
|
566
840
|
}
|
|
567
841
|
for (const tool of tools) {
|
|
568
|
-
pi.registerTool(withDefaultPromptSnippet(tool));
|
|
842
|
+
pi.registerTool(withSummaryStrippedBeforeValidation(withDefaultPromptSnippet(tool)));
|
|
569
843
|
summary.totalTools++;
|
|
570
844
|
}
|
|
571
845
|
if (action === "added") summary.added.push(file);
|
|
@@ -582,7 +856,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
|
|
|
582
856
|
dir
|
|
583
857
|
});
|
|
584
858
|
if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
|
|
585
|
-
log$
|
|
859
|
+
log$14.info({
|
|
586
860
|
event: "local_tools_reconcile",
|
|
587
861
|
reason,
|
|
588
862
|
total_tools: summary.totalTools,
|
|
@@ -604,7 +878,7 @@ const localToolsExtension = (pi) => {
|
|
|
604
878
|
reason: "session_start"
|
|
605
879
|
});
|
|
606
880
|
} catch (err) {
|
|
607
|
-
log$
|
|
881
|
+
log$14.error({
|
|
608
882
|
err,
|
|
609
883
|
event: "local_tools_reconcile_failed"
|
|
610
884
|
}, "local tools reconcile failed");
|
|
@@ -616,7 +890,7 @@ const localToolsExtension = (pi) => {
|
|
|
616
890
|
try {
|
|
617
891
|
current = await listToolFiles(dir);
|
|
618
892
|
} catch (err) {
|
|
619
|
-
log$
|
|
893
|
+
log$14.warn({
|
|
620
894
|
err,
|
|
621
895
|
event: "local_tools_listing_failed"
|
|
622
896
|
}, "tools/ listing failed");
|
|
@@ -638,7 +912,7 @@ const localToolsExtension = (pi) => {
|
|
|
638
912
|
reason: "auto_reload"
|
|
639
913
|
});
|
|
640
914
|
} catch (err) {
|
|
641
|
-
log$
|
|
915
|
+
log$14.error({
|
|
642
916
|
err,
|
|
643
917
|
event: "local_tools_auto_reload_failed"
|
|
644
918
|
}, "auto-reload after tools/ change failed");
|
|
@@ -669,6 +943,77 @@ function createStderrBuffer({ maxBytes }) {
|
|
|
669
943
|
};
|
|
670
944
|
}
|
|
671
945
|
//#endregion
|
|
946
|
+
//#region src/extensions/mcp/schema-validator.ts
|
|
947
|
+
/**
|
|
948
|
+
* Lenient JSON-schema validator for MCP tool output schemas.
|
|
949
|
+
*
|
|
950
|
+
* The MCP SDK's `Client.listTools()` eagerly compiles every tool's
|
|
951
|
+
* `outputSchema` (`cacheToolMetadata`), and its default AJV instance
|
|
952
|
+
* compiles `pattern` with the `u` (unicode) flag. Real vendor servers
|
|
953
|
+
* ship legacy Annex-B escapes in their patterns — PayPal's hosted MCP
|
|
954
|
+
* publishes `^https\:\/\/`, whose `\:` is a hard SyntaxError under `/u`
|
|
955
|
+
* ("Invalid regular expression: /^https\:\/\//u: Invalid escape").
|
|
956
|
+
* With the default validator that one schema throws inside `listTools`,
|
|
957
|
+
* the whole server lands in `failed`, and zero tools bind even though
|
|
958
|
+
* the credential is live.
|
|
959
|
+
*
|
|
960
|
+
* Two layers of leniency, both scoped to *output* validation (tool
|
|
961
|
+
* results), never to anything security-relevant:
|
|
962
|
+
*
|
|
963
|
+
* 1. `unicodeRegExp: false` — compile `pattern` without the `u` flag,
|
|
964
|
+
* which restores Annex-B tolerance for escapes like `\:` and matches
|
|
965
|
+
* what most other MCP clients (and JSON Schema's own spec, which
|
|
966
|
+
* does not require unicode mode) accept.
|
|
967
|
+
* 2. A compile failure on one tool's schema must not kill the server:
|
|
968
|
+
* `getValidator` catches the throw and degrades to a pass-through
|
|
969
|
+
* validator for that tool only, so its results are simply not
|
|
970
|
+
* output-validated while every other tool stays fully functional.
|
|
971
|
+
*/
|
|
972
|
+
const log$13 = logger.child({ module: "mcp-schema-validator" });
|
|
973
|
+
function createLenientAjv() {
|
|
974
|
+
const ajv = new Ajv({
|
|
975
|
+
strict: false,
|
|
976
|
+
validateFormats: true,
|
|
977
|
+
validateSchema: false,
|
|
978
|
+
allErrors: true,
|
|
979
|
+
unicodeRegExp: false
|
|
980
|
+
});
|
|
981
|
+
addFormats(ajv);
|
|
982
|
+
return ajv;
|
|
983
|
+
}
|
|
984
|
+
var LenientJsonSchemaValidator = class {
|
|
985
|
+
ajv = createLenientAjv();
|
|
986
|
+
getValidator(schema) {
|
|
987
|
+
let compiled = null;
|
|
988
|
+
try {
|
|
989
|
+
compiled = this.ajv.compile(schema);
|
|
990
|
+
} catch (err) {
|
|
991
|
+
log$13.warn({
|
|
992
|
+
err,
|
|
993
|
+
event: "mcp_output_schema_compile_failed"
|
|
994
|
+
}, "tool outputSchema failed to compile; skipping output validation for this tool");
|
|
995
|
+
return (input) => ({
|
|
996
|
+
valid: true,
|
|
997
|
+
data: input,
|
|
998
|
+
errorMessage: void 0
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
const validate = compiled;
|
|
1002
|
+
return (input) => {
|
|
1003
|
+
if (validate(input)) return {
|
|
1004
|
+
valid: true,
|
|
1005
|
+
data: input,
|
|
1006
|
+
errorMessage: void 0
|
|
1007
|
+
};
|
|
1008
|
+
return {
|
|
1009
|
+
valid: false,
|
|
1010
|
+
data: void 0,
|
|
1011
|
+
errorMessage: this.ajv.errorsText(validate.errors)
|
|
1012
|
+
};
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
//#endregion
|
|
672
1017
|
//#region src/extensions/mcp/connect-client.ts
|
|
673
1018
|
/**
|
|
674
1019
|
* Spawns an MCP server's transport and races the initialize handshake
|
|
@@ -684,6 +1029,68 @@ function createStderrBuffer({ maxBytes }) {
|
|
|
684
1029
|
*/
|
|
685
1030
|
const DEFAULT_CONNECT_TIMEOUT_MS = 5e3;
|
|
686
1031
|
const STDERR_BUFFER_BYTES = 4096;
|
|
1032
|
+
const SESSION_NOT_FOUND_RETRY_DELAYS_MS = [
|
|
1033
|
+
250,
|
|
1034
|
+
500,
|
|
1035
|
+
1e3,
|
|
1036
|
+
2e3,
|
|
1037
|
+
4e3,
|
|
1038
|
+
8e3
|
|
1039
|
+
];
|
|
1040
|
+
function delay(ms) {
|
|
1041
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1042
|
+
}
|
|
1043
|
+
async function fetchWithSessionNotFoundRetry(input, init) {
|
|
1044
|
+
for (let attempt = 0;; attempt += 1) {
|
|
1045
|
+
const response = await fetch(input, init);
|
|
1046
|
+
const sessionId = new Headers(init?.headers).get("mcp-session-id");
|
|
1047
|
+
const retryDelay = SESSION_NOT_FOUND_RETRY_DELAYS_MS[attempt];
|
|
1048
|
+
if (!sessionId || response.status !== 404 || retryDelay === void 0 || !(await response.clone().text()).includes("session_not_found")) return response;
|
|
1049
|
+
await response.body?.cancel();
|
|
1050
|
+
await delay(retryDelay);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Sandbox egress variables a stdio MCP server needs to make outbound HTTPS
|
|
1055
|
+
* calls. The SDK's default child environment is a tiny whitelist (HOME,
|
|
1056
|
+
* LOGNAME, PATH, SHELL, TERM, USER on Linux), which drops NODE_EXTRA_CA_CERTS
|
|
1057
|
+
* — but the sandbox's egress proxy terminates TLS with a private CA, so a
|
|
1058
|
+
* child spawned without it fails every HTTPS request with a bare
|
|
1059
|
+
* `fetch failed` (cause: UNABLE_TO_VERIFY_LEAF_SIGNATURE) that looks like the
|
|
1060
|
+
* remote service is down. Same story for SSL_CERT_FILE (OpenSSL-based
|
|
1061
|
+
* runtimes) and the *_PROXY set. Inherit them from this process so a stdio
|
|
1062
|
+
* server gets working egress like every other process in the sandbox.
|
|
1063
|
+
*/
|
|
1064
|
+
const INHERITED_EGRESS_ENV_VARS = [
|
|
1065
|
+
"NODE_EXTRA_CA_CERTS",
|
|
1066
|
+
"SSL_CERT_FILE",
|
|
1067
|
+
"SSL_CERT_DIR",
|
|
1068
|
+
"REQUESTS_CA_BUNDLE",
|
|
1069
|
+
"CURL_CA_BUNDLE",
|
|
1070
|
+
"HTTP_PROXY",
|
|
1071
|
+
"HTTPS_PROXY",
|
|
1072
|
+
"NO_PROXY",
|
|
1073
|
+
"http_proxy",
|
|
1074
|
+
"https_proxy",
|
|
1075
|
+
"no_proxy"
|
|
1076
|
+
];
|
|
1077
|
+
/**
|
|
1078
|
+
* Environment for a stdio MCP server child: the SDK's safe defaults, plus the
|
|
1079
|
+
* sandbox's egress/TLS variables, plus (last, so it wins) the server's own
|
|
1080
|
+
* configured `env`. Building the merge here — instead of only when `env` is
|
|
1081
|
+
* unset — also fixes the workaround trap where supplying any `env` in
|
|
1082
|
+
* mcp.config.json silently replaced the ENTIRE default set, so a config that
|
|
1083
|
+
* added one API key lost PATH/HOME and the server failed to spawn at all.
|
|
1084
|
+
*/
|
|
1085
|
+
function buildStdioEnv(configured, processEnv = process.env) {
|
|
1086
|
+
const env = { ...getDefaultEnvironment() };
|
|
1087
|
+
for (const key of INHERITED_EGRESS_ENV_VARS) {
|
|
1088
|
+
const value = processEnv[key];
|
|
1089
|
+
if (value !== void 0) env[key] = value;
|
|
1090
|
+
}
|
|
1091
|
+
if (configured) Object.assign(env, configured);
|
|
1092
|
+
return env;
|
|
1093
|
+
}
|
|
687
1094
|
/**
|
|
688
1095
|
* undici's fetch throws `TypeError: fetch failed` with the actual
|
|
689
1096
|
* network error hung off `.cause` (e.g. `getaddrinfo ENOTFOUND ...`,
|
|
@@ -692,8 +1099,21 @@ const STDERR_BUFFER_BYTES = 4096;
|
|
|
692
1099
|
* indistinguishable from any other transport problem. Walk the cause
|
|
693
1100
|
* chain so the agent sees the real underlying error.
|
|
694
1101
|
*/
|
|
695
|
-
|
|
696
|
-
|
|
1102
|
+
/**
|
|
1103
|
+
* True when an error from an http MCP transport (connect, listTools, or a tool
|
|
1104
|
+
* call) is an authentication failure. With no authProvider configured the SDK
|
|
1105
|
+
* surfaces a 401 as `StreamableHTTPError(401)`; older paths translate it to
|
|
1106
|
+
* `UnauthorizedError`. A dead/expired OAuth token (the proxy can no longer
|
|
1107
|
+
* mint one) shows up here on the NEXT request against a previously-connected
|
|
1108
|
+
* client — not just at connect — so reconcile must re-classify such a failure
|
|
1109
|
+
* as `pending_auth` instead of a generic `failed`, keeping the "waiting on
|
|
1110
|
+
* auth" report consistent with `platform auth`.
|
|
1111
|
+
*/
|
|
1112
|
+
function isUnauthorizedError(err) {
|
|
1113
|
+
return err instanceof UnauthorizedError || err instanceof StreamableHTTPError && err.code === 401;
|
|
1114
|
+
}
|
|
1115
|
+
function formatError(err) {
|
|
1116
|
+
if (!(err instanceof Error)) return String(err);
|
|
697
1117
|
const parts = [err.message];
|
|
698
1118
|
let cursor = err.cause;
|
|
699
1119
|
while (cursor instanceof Error) {
|
|
@@ -703,8 +1123,20 @@ function formatError(err) {
|
|
|
703
1123
|
}
|
|
704
1124
|
return parts.join(": ");
|
|
705
1125
|
}
|
|
1126
|
+
function probeAlive(pid) {
|
|
1127
|
+
if (pid === null) return null;
|
|
1128
|
+
try {
|
|
1129
|
+
process.kill(pid, 0);
|
|
1130
|
+
return true;
|
|
1131
|
+
} catch {
|
|
1132
|
+
return false;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
706
1135
|
async function connectHttp(_id, config, client) {
|
|
707
|
-
const transport = new StreamableHTTPClientTransport(new URL(config.url), {
|
|
1136
|
+
const transport = new StreamableHTTPClientTransport(new URL(config.url), {
|
|
1137
|
+
...config.headers !== null ? { requestInit: { headers: config.headers } } : {},
|
|
1138
|
+
fetch: fetchWithSessionNotFoundRetry
|
|
1139
|
+
});
|
|
708
1140
|
try {
|
|
709
1141
|
await client.connect(transport);
|
|
710
1142
|
return {
|
|
@@ -713,12 +1145,12 @@ async function connectHttp(_id, config, client) {
|
|
|
713
1145
|
stderr: null
|
|
714
1146
|
};
|
|
715
1147
|
} catch (err) {
|
|
716
|
-
if (err
|
|
1148
|
+
if (isUnauthorizedError(err)) return {
|
|
717
1149
|
status: "pending_auth",
|
|
718
1150
|
client,
|
|
719
1151
|
stderr: "",
|
|
720
1152
|
stderrBuffer: null,
|
|
721
|
-
cliHint: `platform auth mcp ${config.url}`
|
|
1153
|
+
cliHint: `platform auth mcp ${config.url} --service "<Product>"`
|
|
722
1154
|
};
|
|
723
1155
|
return {
|
|
724
1156
|
status: "failed",
|
|
@@ -732,14 +1164,17 @@ async function connectClient(id, config, opts = {}) {
|
|
|
732
1164
|
const client = new Client({
|
|
733
1165
|
name: "skydive-harness",
|
|
734
1166
|
version: "0.1.0"
|
|
735
|
-
}, {
|
|
1167
|
+
}, {
|
|
1168
|
+
capabilities: {},
|
|
1169
|
+
jsonSchemaValidator: new LenientJsonSchemaValidator()
|
|
1170
|
+
});
|
|
736
1171
|
if (config.transport === "http") return connectHttp(id, config, client);
|
|
737
1172
|
const params = {
|
|
738
1173
|
command: config.command,
|
|
739
1174
|
args: config.args,
|
|
740
|
-
stderr: "pipe"
|
|
1175
|
+
stderr: "pipe",
|
|
1176
|
+
env: buildStdioEnv(config.env)
|
|
741
1177
|
};
|
|
742
|
-
if (config.env !== null) params.env = config.env;
|
|
743
1178
|
if (config.cwd !== null) params.cwd = config.cwd;
|
|
744
1179
|
const transport = new StdioClientTransport(params);
|
|
745
1180
|
const stderrBuffer = createStderrBuffer({ maxBytes: STDERR_BUFFER_BYTES });
|
|
@@ -751,6 +1186,10 @@ async function connectClient(id, config, opts = {}) {
|
|
|
751
1186
|
resolve();
|
|
752
1187
|
};
|
|
753
1188
|
});
|
|
1189
|
+
let stdoutMessages = 0;
|
|
1190
|
+
transport.onmessage = () => {
|
|
1191
|
+
if (stdoutMessages < 1e4) stdoutMessages += 1;
|
|
1192
|
+
};
|
|
754
1193
|
const connectPromise = client.connect(transport);
|
|
755
1194
|
const TIMEOUT_SENTINEL = Symbol("timeout");
|
|
756
1195
|
const result = await Promise.race([
|
|
@@ -768,12 +1207,20 @@ async function connectClient(id, config, opts = {}) {
|
|
|
768
1207
|
error: `server "${id}" exited before completing initialize`,
|
|
769
1208
|
stderr: stderrBuffer.read()
|
|
770
1209
|
};
|
|
771
|
-
if (result === TIMEOUT_SENTINEL)
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1210
|
+
if (result === TIMEOUT_SENTINEL) {
|
|
1211
|
+
const pid = transport.pid;
|
|
1212
|
+
return {
|
|
1213
|
+
status: "timeout",
|
|
1214
|
+
client,
|
|
1215
|
+
stderr: stderrBuffer.read(),
|
|
1216
|
+
stderrBuffer,
|
|
1217
|
+
diagnostics: {
|
|
1218
|
+
pid,
|
|
1219
|
+
alive: probeAlive(pid),
|
|
1220
|
+
stdoutMessages
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
777
1224
|
try {
|
|
778
1225
|
await client.close();
|
|
779
1226
|
} catch {}
|
|
@@ -784,6 +1231,126 @@ async function connectClient(id, config, opts = {}) {
|
|
|
784
1231
|
};
|
|
785
1232
|
}
|
|
786
1233
|
//#endregion
|
|
1234
|
+
//#region src/extensions/mcp/limits.ts
|
|
1235
|
+
/**
|
|
1236
|
+
* Tool-budget guardrails for MCP registration.
|
|
1237
|
+
*
|
|
1238
|
+
* Why this exists: the agent loop sends the *full* tool list — every tool's
|
|
1239
|
+
* name, description, and JSON-schema `parameters` — to the model on every
|
|
1240
|
+
* prompt. MCP servers add tools without bound: a handful of chatty servers (or
|
|
1241
|
+
* one server that exposes 100+ tools, or a few tools with enormous schemas) can
|
|
1242
|
+
* push the registered set past what the model can accept, and the request is
|
|
1243
|
+
* rejected before the turn even runs. Because `reconcile` re-registers from
|
|
1244
|
+
* `mcp.config.json` on *every* turn, an over-limit config bricks the harness on
|
|
1245
|
+
* a loop — the agent can't get a turn to run in order to edit the config back
|
|
1246
|
+
* down. Worse, the person can't tell *why*: tools just stop working.
|
|
1247
|
+
*
|
|
1248
|
+
* What actually overflows the request is *tokens*, not tool count — a few tools
|
|
1249
|
+
* with deeply-nested schemas and long descriptions cost more than a hundred
|
|
1250
|
+
* trivial ones. And how many tokens are safe depends on the *model*: a 200K
|
|
1251
|
+
* context window can afford far more tool surface than a 32K one. So the primary
|
|
1252
|
+
* limiter is a **token budget derived from the active model's context window**,
|
|
1253
|
+
* with a fixed tool-count cap as a coarse secondary guard (and the fallback
|
|
1254
|
+
* when the model — hence its window — isn't known at reconcile time).
|
|
1255
|
+
*
|
|
1256
|
+
* The fix is to make registration bounded and fail-soft. We register in
|
|
1257
|
+
* deterministic config order and stop before we blow the budget, recording how
|
|
1258
|
+
* much we dropped so the agent is *told* it hit the limit and which servers
|
|
1259
|
+
* were truncated. A config that would have bricked the harness now degrades to
|
|
1260
|
+
* "a bounded set of tools plus a loud warning", which the agent can act on by
|
|
1261
|
+
* pruning servers.
|
|
1262
|
+
*
|
|
1263
|
+
* Everything is env-overridable so the ceilings can be tuned per deployment
|
|
1264
|
+
* without a release, but ships with conservative defaults. A cap value of 0 (or
|
|
1265
|
+
* a non-finite / negative override) disables that cap — an explicit escape
|
|
1266
|
+
* hatch, not the default.
|
|
1267
|
+
*/
|
|
1268
|
+
const env = process.env;
|
|
1269
|
+
/**
|
|
1270
|
+
* Fraction of the model's context window we're willing to spend on MCP tool
|
|
1271
|
+
* schemas. Tool definitions are sent on every prompt, so they permanently eat
|
|
1272
|
+
* into the window available for the conversation, but a generous tool budget is
|
|
1273
|
+
* worth more than a marginally larger conversation window given how the harness
|
|
1274
|
+
* is used. 0.35 of a 200K window is ~70K tokens of tool schema, comfortably
|
|
1275
|
+
* more than any sane MCP setup; of a 32K window it's ~11.2K, which still forces
|
|
1276
|
+
* truncation before a small model chokes.
|
|
1277
|
+
*/
|
|
1278
|
+
const DEFAULT_MCP_TOOL_TOKEN_BUDGET_FRACTION = .35;
|
|
1279
|
+
/**
|
|
1280
|
+
* Floor for the token budget when the model's context window is unknown at
|
|
1281
|
+
* reconcile time (e.g. the model hasn't been resolved yet). Generous enough not
|
|
1282
|
+
* to truncate an ordinary tool set, low enough to still catch a runaway.
|
|
1283
|
+
*/
|
|
1284
|
+
const DEFAULT_MCP_TOOL_TOKEN_BUDGET_FLOOR = 16e3;
|
|
1285
|
+
/**
|
|
1286
|
+
* Read a positive-integer cap from an env var, falling back to `fallback`.
|
|
1287
|
+
* A `0` override (or any non-finite / negative value) means "no cap" and is
|
|
1288
|
+
* returned as `Infinity`, so callers can compare against it directly.
|
|
1289
|
+
*/
|
|
1290
|
+
function readCap(raw, fallback) {
|
|
1291
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
1292
|
+
const parsed = Number(raw);
|
|
1293
|
+
if (!Number.isFinite(parsed) || parsed < 0) return Number.POSITIVE_INFINITY;
|
|
1294
|
+
if (parsed === 0) return Number.POSITIVE_INFINITY;
|
|
1295
|
+
return Math.floor(parsed);
|
|
1296
|
+
}
|
|
1297
|
+
/** Read a fraction in (0, 1] from an env var, falling back to `fallback`. */
|
|
1298
|
+
function readFraction(raw, fallback) {
|
|
1299
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
1300
|
+
const parsed = Number(raw);
|
|
1301
|
+
if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1) return fallback;
|
|
1302
|
+
return parsed;
|
|
1303
|
+
}
|
|
1304
|
+
/** Read a non-negative integer from an env var, falling back to `fallback`. */
|
|
1305
|
+
function readNonNegativeInt(raw, fallback) {
|
|
1306
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
1307
|
+
const parsed = Number(raw);
|
|
1308
|
+
if (!Number.isFinite(parsed) || parsed < 0) return fallback;
|
|
1309
|
+
return Math.floor(parsed);
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Resolve the active caps from the environment. Read once per reconcile so a
|
|
1313
|
+
* deployment can retune without a restart, cheap enough not to cache.
|
|
1314
|
+
*/
|
|
1315
|
+
function resolveMcpToolLimits() {
|
|
1316
|
+
return {
|
|
1317
|
+
maxTotalTools: readCap(env["SKYDIVE_MCP_MAX_TOTAL_TOOLS"], 128),
|
|
1318
|
+
maxToolsPerServer: readCap(env["SKYDIVE_MCP_MAX_TOOLS_PER_SERVER"], 50),
|
|
1319
|
+
tokenBudgetFraction: readFraction(env["SKYDIVE_MCP_TOOL_TOKEN_BUDGET_FRACTION"], DEFAULT_MCP_TOOL_TOKEN_BUDGET_FRACTION),
|
|
1320
|
+
tokenBudgetFloor: readNonNegativeInt(env["SKYDIVE_MCP_TOOL_TOKEN_BUDGET_FLOOR"], DEFAULT_MCP_TOOL_TOKEN_BUDGET_FLOOR)
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* The token budget for MCP tool schemas, given the active model's context
|
|
1325
|
+
* window (or undefined when the model isn't known yet).
|
|
1326
|
+
*
|
|
1327
|
+
* With a known window we spend `tokenBudgetFraction` of it, but never less than
|
|
1328
|
+
* the floor — a tiny window shouldn't collapse the budget to near-zero and
|
|
1329
|
+
* strand every tool. With no window we fall back to the floor outright.
|
|
1330
|
+
*/
|
|
1331
|
+
function resolveTokenBudget(limits, contextWindow) {
|
|
1332
|
+
if (contextWindow === void 0 || !Number.isFinite(contextWindow)) return limits.tokenBudgetFloor;
|
|
1333
|
+
return Math.max(limits.tokenBudgetFloor, Math.floor(contextWindow * limits.tokenBudgetFraction));
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Estimate the tokens an MCP tool's *definition* costs in the request. We
|
|
1337
|
+
* serialize what's actually sent to the model — the tool name, its description,
|
|
1338
|
+
* and its JSON-schema parameters — and apply pi's own ~chars/4 heuristic
|
|
1339
|
+
* (`estimateTokens` in the coding agent uses the same convention; there is no
|
|
1340
|
+
* per-provider tokenizer to lean on, and the provider's real usage is only
|
|
1341
|
+
* known after the response). Rough by design, but it tracks the true cost far
|
|
1342
|
+
* better than a flat per-tool count: a fat schema is charged for its fatness.
|
|
1343
|
+
*/
|
|
1344
|
+
function estimateToolTokens(tool) {
|
|
1345
|
+
let chars = tool.name.length + (tool.description?.length ?? 0);
|
|
1346
|
+
if (tool.inputSchema !== void 0 && tool.inputSchema !== null) try {
|
|
1347
|
+
chars += JSON.stringify(tool.inputSchema).length;
|
|
1348
|
+
} catch {
|
|
1349
|
+
chars += 256;
|
|
1350
|
+
}
|
|
1351
|
+
return Math.ceil(chars / 4);
|
|
1352
|
+
}
|
|
1353
|
+
//#endregion
|
|
787
1354
|
//#region src/extensions/mcp/mcp-config.ts
|
|
788
1355
|
/**
|
|
789
1356
|
* mcp.config.json schema + loader. Split out from the extension so it has
|
|
@@ -863,7 +1430,7 @@ async function loadMcpConfig(path) {
|
|
|
863
1430
|
* Clients are keyed by JSON-stringified config and reused across
|
|
864
1431
|
* reloads — only changed configs reconnect.
|
|
865
1432
|
*/
|
|
866
|
-
const log$
|
|
1433
|
+
const log$12 = logger.child({ module: "mcp-extension" });
|
|
867
1434
|
async function closeConnected(connected) {
|
|
868
1435
|
try {
|
|
869
1436
|
await connected.client.close();
|
|
@@ -933,6 +1500,57 @@ function mcpResultToPiContent(result) {
|
|
|
933
1500
|
text: "MCP tool returned no content."
|
|
934
1501
|
}];
|
|
935
1502
|
}
|
|
1503
|
+
const MAX_ENUM_VALUES_LISTED = 12;
|
|
1504
|
+
function formatEnumValues(values) {
|
|
1505
|
+
const shown = values.slice(0, MAX_ENUM_VALUES_LISTED).map((v) => JSON.stringify(v));
|
|
1506
|
+
if (values.length > MAX_ENUM_VALUES_LISTED) shown.push(`… (${values.length} total)`);
|
|
1507
|
+
return shown.join(", ");
|
|
1508
|
+
}
|
|
1509
|
+
function extractEnum(propSchema) {
|
|
1510
|
+
if (Array.isArray(propSchema.enum) && propSchema.enum.length > 0) return propSchema.enum;
|
|
1511
|
+
const items = propSchema.items;
|
|
1512
|
+
if (items !== null && typeof items === "object" && Array.isArray(items.enum) && items.enum.length > 0) return items.enum;
|
|
1513
|
+
return null;
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Build a compact, human-readable constraint hint from an MCP tool's raw JSON
|
|
1517
|
+
* schema so the model sees required fields and each param's allowed enum values
|
|
1518
|
+
* inline in the tool description — the schema pass-through hands pi the server's
|
|
1519
|
+
* schema verbatim, but the model attends to the prose far more than the raw
|
|
1520
|
+
* `enum`/`required` keys. Returns '' when there is nothing worth surfacing.
|
|
1521
|
+
*/
|
|
1522
|
+
function describeToolConstraints(inputSchema) {
|
|
1523
|
+
if (inputSchema === null || typeof inputSchema !== "object") return "";
|
|
1524
|
+
const schema = inputSchema;
|
|
1525
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : [];
|
|
1526
|
+
const properties = schema.properties !== null && typeof schema.properties === "object" ? schema.properties : {};
|
|
1527
|
+
const enumLines = [];
|
|
1528
|
+
for (const [propName, rawProp] of Object.entries(properties)) {
|
|
1529
|
+
if (rawProp === null || typeof rawProp !== "object") continue;
|
|
1530
|
+
const values = extractEnum(rawProp);
|
|
1531
|
+
if (values) enumLines.push(`- \`${propName}\` must be one of: ${formatEnumValues(values)}`);
|
|
1532
|
+
}
|
|
1533
|
+
if (required.length === 0 && enumLines.length === 0) return "";
|
|
1534
|
+
const lines = ["Argument constraints:"];
|
|
1535
|
+
if (required.length > 0) lines.push(`- required: ${required.map((r) => `\`${r}\``).join(", ")}`);
|
|
1536
|
+
lines.push(...enumLines);
|
|
1537
|
+
return lines.join("\n");
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Build the `promptSnippet` a registered MCP tool exposes to the model: the
|
|
1541
|
+
* server's description with the argument-constraint hint appended, falling back
|
|
1542
|
+
* to a labelled placeholder when the server omitted a description AND the schema
|
|
1543
|
+
* carries no constraints (pi's system-prompt builder hides tools whose snippet
|
|
1544
|
+
* is empty — system-prompt.js:49). This is the layer where `describeToolConstraints`
|
|
1545
|
+
* actually reaches the model, so it is exported and tested directly: the pure
|
|
1546
|
+
* hint being correct is necessary but not sufficient; what the model sees is
|
|
1547
|
+
* this composed snippet.
|
|
1548
|
+
*/
|
|
1549
|
+
function buildToolPromptSnippet({ description, inputSchema, serverId }) {
|
|
1550
|
+
const constraintHint = describeToolConstraints(inputSchema);
|
|
1551
|
+
const enriched = constraintHint.length > 0 ? `${description}${description.length > 0 ? "\n\n" : ""}${constraintHint}` : description;
|
|
1552
|
+
return enriched.length > 0 ? enriched : `MCP tool from server "${serverId}".`;
|
|
1553
|
+
}
|
|
936
1554
|
var McpExtension = class {
|
|
937
1555
|
mcpClients = /* @__PURE__ */ new Map();
|
|
938
1556
|
registeredMcpToolNames = /* @__PURE__ */ new Set();
|
|
@@ -952,8 +1570,12 @@ var McpExtension = class {
|
|
|
952
1570
|
const name = makeToolName(serverId, tool.name);
|
|
953
1571
|
const parameters = Type.Unsafe(tool.inputSchema);
|
|
954
1572
|
const description = tool.description?.trim() ?? "";
|
|
955
|
-
const promptSnippet =
|
|
956
|
-
|
|
1573
|
+
const promptSnippet = buildToolPromptSnippet({
|
|
1574
|
+
description,
|
|
1575
|
+
inputSchema: tool.inputSchema,
|
|
1576
|
+
serverId
|
|
1577
|
+
});
|
|
1578
|
+
pi.registerTool(withSummaryStrippedBeforeValidation({
|
|
957
1579
|
name,
|
|
958
1580
|
label: `MCP: ${serverId}/${tool.name}`,
|
|
959
1581
|
description,
|
|
@@ -987,22 +1609,29 @@ var McpExtension = class {
|
|
|
987
1609
|
};
|
|
988
1610
|
}
|
|
989
1611
|
}
|
|
990
|
-
});
|
|
1612
|
+
}));
|
|
991
1613
|
this.registeredMcpToolNames.add(name);
|
|
992
1614
|
}
|
|
993
|
-
async reconcile({ pi, configPath, connectTimeoutMs }) {
|
|
1615
|
+
async reconcile({ pi, configPath, connectTimeoutMs, contextWindow }) {
|
|
994
1616
|
let config;
|
|
995
1617
|
try {
|
|
996
1618
|
config = await loadMcpConfig(configPath);
|
|
997
1619
|
} catch (err) {
|
|
998
1620
|
throw new Error(`Failed to load MCP config: ${err instanceof Error ? err.message : String(err)}`);
|
|
999
1621
|
}
|
|
1622
|
+
const limits = resolveMcpToolLimits();
|
|
1623
|
+
const tokenBudget = resolveTokenBudget(limits, contextWindow);
|
|
1000
1624
|
const summary = {
|
|
1001
1625
|
added: [],
|
|
1002
1626
|
removed: [],
|
|
1003
1627
|
refreshed: [],
|
|
1004
1628
|
errors: [],
|
|
1005
1629
|
totalTools: 0,
|
|
1630
|
+
droppedTools: 0,
|
|
1631
|
+
limits,
|
|
1632
|
+
tokenBudget,
|
|
1633
|
+
tokensUsed: 0,
|
|
1634
|
+
toolCounts: {},
|
|
1006
1635
|
servers: {}
|
|
1007
1636
|
};
|
|
1008
1637
|
const desiredIds = new Set(Object.keys(config.servers));
|
|
@@ -1026,15 +1655,58 @@ var McpExtension = class {
|
|
|
1026
1655
|
if (outcome.error) summary.errors.push(outcome.error);
|
|
1027
1656
|
if (outcome.change === "added") summary.added.push(id);
|
|
1028
1657
|
else if (outcome.change === "refreshed") summary.refreshed.push(id);
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1658
|
+
}
|
|
1659
|
+
const alloc = outcomes.filter((o) => Boolean(o.tools)).map((o) => {
|
|
1660
|
+
const advertised = o.tools.list.length;
|
|
1661
|
+
return {
|
|
1662
|
+
id: o.id,
|
|
1663
|
+
client: o.tools.client,
|
|
1664
|
+
list: o.tools.list,
|
|
1665
|
+
advertised,
|
|
1666
|
+
room: Math.min(advertised, limits.maxToolsPerServer),
|
|
1667
|
+
registered: 0,
|
|
1668
|
+
serverTokens: 0,
|
|
1669
|
+
droppedReason: null
|
|
1670
|
+
};
|
|
1671
|
+
});
|
|
1672
|
+
const maxAdvertised = alloc.reduce((m, s) => Math.max(m, s.advertised), 0);
|
|
1673
|
+
outer: for (let i = 0; i < maxAdvertised; i++) for (const s of alloc) {
|
|
1674
|
+
if (summary.totalTools >= limits.maxTotalTools) {
|
|
1675
|
+
for (const t of alloc) if (t.registered < t.advertised && t.droppedReason === null) t.droppedReason = "total";
|
|
1676
|
+
break outer;
|
|
1677
|
+
}
|
|
1678
|
+
if (i >= s.room) {
|
|
1679
|
+
if (s.registered < s.advertised && s.droppedReason === null) s.droppedReason = "per_server";
|
|
1680
|
+
continue;
|
|
1681
|
+
}
|
|
1682
|
+
const tool = s.list[i];
|
|
1683
|
+
if (tool === void 0) continue;
|
|
1684
|
+
const cost = estimateToolTokens(tool);
|
|
1685
|
+
if (summary.tokensUsed + cost > tokenBudget && summary.totalTools > 0) {
|
|
1686
|
+
for (const t of alloc) if (t.registered < t.advertised && t.droppedReason === null) t.droppedReason = "tokens";
|
|
1687
|
+
break outer;
|
|
1037
1688
|
}
|
|
1689
|
+
this.registerMcpTool({
|
|
1690
|
+
pi,
|
|
1691
|
+
serverId: s.id,
|
|
1692
|
+
client: s.client,
|
|
1693
|
+
tool
|
|
1694
|
+
});
|
|
1695
|
+
s.registered++;
|
|
1696
|
+
s.serverTokens += cost;
|
|
1697
|
+
summary.totalTools++;
|
|
1698
|
+
summary.tokensUsed += cost;
|
|
1699
|
+
}
|
|
1700
|
+
for (const s of alloc) {
|
|
1701
|
+
const dropped = s.advertised - s.registered;
|
|
1702
|
+
const droppedReason = dropped > 0 ? s.droppedReason : null;
|
|
1703
|
+
if (dropped > 0) summary.droppedTools += dropped;
|
|
1704
|
+
summary.toolCounts[s.id] = {
|
|
1705
|
+
advertised: s.advertised,
|
|
1706
|
+
registered: s.registered,
|
|
1707
|
+
tokens: s.serverTokens,
|
|
1708
|
+
droppedReason
|
|
1709
|
+
};
|
|
1038
1710
|
}
|
|
1039
1711
|
return summary;
|
|
1040
1712
|
}
|
|
@@ -1099,7 +1771,8 @@ var McpExtension = class {
|
|
|
1099
1771
|
},
|
|
1100
1772
|
serverStatus: {
|
|
1101
1773
|
status: "timeout",
|
|
1102
|
-
stderr: result.stderr
|
|
1774
|
+
stderr: result.stderr,
|
|
1775
|
+
diagnostics: result.diagnostics
|
|
1103
1776
|
},
|
|
1104
1777
|
change,
|
|
1105
1778
|
error: null,
|
|
@@ -1146,7 +1819,8 @@ var McpExtension = class {
|
|
|
1146
1819
|
},
|
|
1147
1820
|
serverStatus: {
|
|
1148
1821
|
status: "timeout",
|
|
1149
|
-
stderr: retry.stderr
|
|
1822
|
+
stderr: retry.stderr,
|
|
1823
|
+
diagnostics: retry.diagnostics
|
|
1150
1824
|
},
|
|
1151
1825
|
change: null,
|
|
1152
1826
|
error: null,
|
|
@@ -1179,7 +1853,8 @@ var McpExtension = class {
|
|
|
1179
1853
|
store: connected,
|
|
1180
1854
|
serverStatus: {
|
|
1181
1855
|
status: "timeout",
|
|
1182
|
-
stderr
|
|
1856
|
+
stderr,
|
|
1857
|
+
diagnostics: null
|
|
1183
1858
|
},
|
|
1184
1859
|
change: null,
|
|
1185
1860
|
error: null,
|
|
@@ -1190,6 +1865,64 @@ var McpExtension = class {
|
|
|
1190
1865
|
try {
|
|
1191
1866
|
mcpTools = (await connected.client.listTools()).tools;
|
|
1192
1867
|
} catch (err) {
|
|
1868
|
+
if (isUnauthorizedError(err) && serverConfig.transport === "http") {
|
|
1869
|
+
await closeConnected(connected);
|
|
1870
|
+
const retry = await connectClient(id, serverConfig, { connectTimeoutMs });
|
|
1871
|
+
if (retry.status === "pending_auth") return {
|
|
1872
|
+
id,
|
|
1873
|
+
store: {
|
|
1874
|
+
client: retry.client,
|
|
1875
|
+
configKey,
|
|
1876
|
+
status: "pending_auth",
|
|
1877
|
+
stderrBuffer: null,
|
|
1878
|
+
cliHint: retry.cliHint
|
|
1879
|
+
},
|
|
1880
|
+
serverStatus: {
|
|
1881
|
+
status: "pending_auth",
|
|
1882
|
+
stderr: "",
|
|
1883
|
+
cliHint: retry.cliHint
|
|
1884
|
+
},
|
|
1885
|
+
change: null,
|
|
1886
|
+
error: null,
|
|
1887
|
+
tools: null
|
|
1888
|
+
};
|
|
1889
|
+
if (retry.status === "failed") return {
|
|
1890
|
+
id,
|
|
1891
|
+
store: null,
|
|
1892
|
+
serverStatus: {
|
|
1893
|
+
status: "failed",
|
|
1894
|
+
error: retry.error,
|
|
1895
|
+
stderr: retry.stderr
|
|
1896
|
+
},
|
|
1897
|
+
change: null,
|
|
1898
|
+
error: {
|
|
1899
|
+
serverId: id,
|
|
1900
|
+
message: retry.error
|
|
1901
|
+
},
|
|
1902
|
+
tools: null
|
|
1903
|
+
};
|
|
1904
|
+
if (retry.status === "connected") {
|
|
1905
|
+
connected = {
|
|
1906
|
+
client: retry.client,
|
|
1907
|
+
configKey,
|
|
1908
|
+
status: "connected",
|
|
1909
|
+
stderrBuffer: retry.stderr,
|
|
1910
|
+
cliHint: null
|
|
1911
|
+
};
|
|
1912
|
+
mcpTools = (await connected.client.listTools()).tools;
|
|
1913
|
+
return {
|
|
1914
|
+
id,
|
|
1915
|
+
store: connected,
|
|
1916
|
+
serverStatus: { status: "connected" },
|
|
1917
|
+
change: action === "reused" ? "refreshed" : action,
|
|
1918
|
+
error: null,
|
|
1919
|
+
tools: {
|
|
1920
|
+
client: connected.client,
|
|
1921
|
+
list: mcpTools
|
|
1922
|
+
}
|
|
1923
|
+
};
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1193
1926
|
const message = err instanceof Error ? err.message : String(err);
|
|
1194
1927
|
const stderr = connected.stderrBuffer?.read() ?? "";
|
|
1195
1928
|
return {
|
|
@@ -1220,17 +1953,21 @@ var McpExtension = class {
|
|
|
1220
1953
|
}
|
|
1221
1954
|
};
|
|
1222
1955
|
}
|
|
1223
|
-
async reconcileAndRecordMtime({ pi, configPath, reason }) {
|
|
1956
|
+
async reconcileAndRecordMtime({ pi, configPath, reason, contextWindow }) {
|
|
1224
1957
|
const summary = await this.reconcile({
|
|
1225
1958
|
pi,
|
|
1226
|
-
configPath
|
|
1959
|
+
configPath,
|
|
1960
|
+
contextWindow
|
|
1227
1961
|
});
|
|
1228
1962
|
this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
|
|
1229
1963
|
if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
|
|
1230
|
-
log$
|
|
1964
|
+
log$12.info({
|
|
1231
1965
|
event: "mcp_reconcile",
|
|
1232
1966
|
reason,
|
|
1233
1967
|
total_tools: summary.totalTools,
|
|
1968
|
+
tokens_used: summary.tokensUsed,
|
|
1969
|
+
token_budget: summary.tokenBudget,
|
|
1970
|
+
dropped_tools: summary.droppedTools,
|
|
1234
1971
|
added: summary.added,
|
|
1235
1972
|
removed: summary.removed,
|
|
1236
1973
|
refreshed: summary.refreshed,
|
|
@@ -1247,10 +1984,11 @@ var McpExtension = class {
|
|
|
1247
1984
|
await this.reconcileAndRecordMtime({
|
|
1248
1985
|
pi,
|
|
1249
1986
|
configPath,
|
|
1250
|
-
reason: "session_start"
|
|
1987
|
+
reason: "session_start",
|
|
1988
|
+
contextWindow: ctx.model?.contextWindow
|
|
1251
1989
|
});
|
|
1252
1990
|
} catch (err) {
|
|
1253
|
-
log$
|
|
1991
|
+
log$12.error({
|
|
1254
1992
|
err,
|
|
1255
1993
|
event: "mcp_reconcile_failed"
|
|
1256
1994
|
}, "MCP reconcile failed");
|
|
@@ -1262,7 +2000,7 @@ var McpExtension = class {
|
|
|
1262
2000
|
try {
|
|
1263
2001
|
mtime = await readConfigMtimeMs(configPath);
|
|
1264
2002
|
} catch (err) {
|
|
1265
|
-
log$
|
|
2003
|
+
log$12.warn({
|
|
1266
2004
|
err,
|
|
1267
2005
|
event: "mcp_mtime_check_failed"
|
|
1268
2006
|
}, "mtime check on mcp.config.json failed");
|
|
@@ -1273,10 +2011,11 @@ var McpExtension = class {
|
|
|
1273
2011
|
await this.reconcileAndRecordMtime({
|
|
1274
2012
|
pi,
|
|
1275
2013
|
configPath,
|
|
1276
|
-
reason: "auto_reload"
|
|
2014
|
+
reason: "auto_reload",
|
|
2015
|
+
contextWindow: ctx.model?.contextWindow
|
|
1277
2016
|
});
|
|
1278
2017
|
} catch (err) {
|
|
1279
|
-
log$
|
|
2018
|
+
log$12.error({
|
|
1280
2019
|
err,
|
|
1281
2020
|
event: "mcp_auto_reload_failed"
|
|
1282
2021
|
}, "auto-reload after mcp.config.json change failed");
|
|
@@ -1293,7 +2032,8 @@ var McpExtension = class {
|
|
|
1293
2032
|
const summary = await this.reconcileAndRecordMtime({
|
|
1294
2033
|
pi,
|
|
1295
2034
|
configPath,
|
|
1296
|
-
reason: "tool"
|
|
2035
|
+
reason: "tool",
|
|
2036
|
+
contextWindow: ctx.model?.contextWindow
|
|
1297
2037
|
});
|
|
1298
2038
|
return {
|
|
1299
2039
|
content: [{
|
|
@@ -1335,9 +2075,21 @@ function pendingAuthEntries(summary) {
|
|
|
1335
2075
|
function timeoutEntries(summary) {
|
|
1336
2076
|
return Object.entries(summary.servers).flatMap(([id, status]) => status.status === "timeout" ? [{
|
|
1337
2077
|
id,
|
|
1338
|
-
stderr: status.stderr
|
|
2078
|
+
stderr: status.stderr,
|
|
2079
|
+
diagnostics: status.diagnostics
|
|
1339
2080
|
}] : []);
|
|
1340
2081
|
}
|
|
2082
|
+
/**
|
|
2083
|
+
* One line describing what the connect probe learned about a timed-out
|
|
2084
|
+
* stdio child, so an empty stderr is no longer a dead end. Empty array
|
|
2085
|
+
* when the entry was re-surfaced without a fresh probe.
|
|
2086
|
+
*/
|
|
2087
|
+
function timeoutDiagnosticLines(diagnostics) {
|
|
2088
|
+
if (diagnostics === null) return [];
|
|
2089
|
+
const alive = diagnostics.alive === null ? "unknown (no pid)" : diagnostics.alive ? "alive" : "DEAD";
|
|
2090
|
+
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)`;
|
|
2091
|
+
return [` child process: ${alive}${diagnostics.pid !== null ? ` (pid ${diagnostics.pid})` : ""}; ${spoke}`];
|
|
2092
|
+
}
|
|
1341
2093
|
function failedEntries(summary) {
|
|
1342
2094
|
return Object.entries(summary.servers).flatMap(([id, status]) => status.status === "failed" ? [{
|
|
1343
2095
|
id,
|
|
@@ -1345,6 +2097,13 @@ function failedEntries(summary) {
|
|
|
1345
2097
|
stderr: status.stderr
|
|
1346
2098
|
}] : []);
|
|
1347
2099
|
}
|
|
2100
|
+
function appendTimeoutStderrBlock(lines, stderr) {
|
|
2101
|
+
if (!stderr) {
|
|
2102
|
+
lines.push(" stderr: (empty — the child wrote nothing to stderr)");
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
appendStderrBlock(lines, stderr);
|
|
2106
|
+
}
|
|
1348
2107
|
function appendStderrBlock(lines, stderr) {
|
|
1349
2108
|
if (!stderr) return;
|
|
1350
2109
|
lines.push(" stderr:");
|
|
@@ -1352,9 +2111,29 @@ function appendStderrBlock(lines, stderr) {
|
|
|
1352
2111
|
for (const line of stderr.trimEnd().split("\n")) lines.push(` ${line}`);
|
|
1353
2112
|
lines.push(" ---");
|
|
1354
2113
|
}
|
|
2114
|
+
/**
|
|
2115
|
+
* Human-readable lines describing any budget-driven truncation, shared by
|
|
2116
|
+
* `summaryText` (the reload_mcp tool output) and `formatMcpUpdateMessage` (the
|
|
2117
|
+
* synthetic continuation). Empty when nothing was dropped.
|
|
2118
|
+
*/
|
|
2119
|
+
function truncationLines(summary) {
|
|
2120
|
+
if (summary.droppedTools <= 0) return [];
|
|
2121
|
+
const lines = [];
|
|
2122
|
+
const { maxTotalTools, maxToolsPerServer } = summary.limits;
|
|
2123
|
+
const totalCapHint = Number.isFinite(maxTotalTools) ? `${maxTotalTools}` : "unlimited";
|
|
2124
|
+
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"}).`);
|
|
2125
|
+
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.");
|
|
2126
|
+
for (const [id, count] of Object.entries(summary.toolCounts)) {
|
|
2127
|
+
if (count.droppedReason === null) continue;
|
|
2128
|
+
const why = count.droppedReason === "tokens" ? "token budget exhausted" : count.droppedReason === "total" ? "total-tool cap reached" : "per-server cap";
|
|
2129
|
+
lines.push(` - ${id}: registered ${count.registered}/${count.advertised} tools (~${count.tokens} tokens, ${why}).`);
|
|
2130
|
+
}
|
|
2131
|
+
return lines;
|
|
2132
|
+
}
|
|
1355
2133
|
function summaryText(summary) {
|
|
1356
2134
|
const lines = [];
|
|
1357
2135
|
lines.push(`MCP reconcile complete: ${summary.totalTools} tool(s) live.`);
|
|
2136
|
+
lines.push(...truncationLines(summary));
|
|
1358
2137
|
if (summary.added.length > 0) lines.push(` Added: ${summary.added.join(", ")}`);
|
|
1359
2138
|
if (summary.refreshed.length > 0) lines.push(` Refreshed: ${summary.refreshed.join(", ")}`);
|
|
1360
2139
|
if (summary.removed.length > 0) lines.push(` Removed: ${summary.removed.join(", ")}`);
|
|
@@ -1363,11 +2142,12 @@ function summaryText(summary) {
|
|
|
1363
2142
|
lines.push(` run \`${cliHint}\` in the shell to authenticate.`);
|
|
1364
2143
|
appendStderrBlock(lines, stderr);
|
|
1365
2144
|
}
|
|
1366
|
-
for (const { id, stderr } of timeoutEntries(summary)) {
|
|
2145
|
+
for (const { id, stderr, diagnostics } of timeoutEntries(summary)) {
|
|
1367
2146
|
lines.push(` TIMED OUT ${id}:`);
|
|
1368
2147
|
lines.push(` bridge spawned but did not complete initialize in time`);
|
|
1369
2148
|
lines.push(` (usually mcp-remote mid-OAuth — see captured stderr).`);
|
|
1370
|
-
|
|
2149
|
+
lines.push(...timeoutDiagnosticLines(diagnostics));
|
|
2150
|
+
appendTimeoutStderrBlock(lines, stderr);
|
|
1371
2151
|
}
|
|
1372
2152
|
for (const { id, error, stderr } of failedEntries(summary)) {
|
|
1373
2153
|
lines.push(` FAILED ${id}: ${error}`);
|
|
@@ -1380,7 +2160,7 @@ function summaryText(summary) {
|
|
|
1380
2160
|
return lines.join("\n");
|
|
1381
2161
|
}
|
|
1382
2162
|
function summaryHasChanges(summary) {
|
|
1383
|
-
return summary.added.length > 0 || summary.removed.length > 0 || summary.refreshed.length > 0 || summary.errors.length > 0;
|
|
2163
|
+
return summary.added.length > 0 || summary.removed.length > 0 || summary.refreshed.length > 0 || summary.errors.length > 0 || summary.droppedTools > 0;
|
|
1384
2164
|
}
|
|
1385
2165
|
/**
|
|
1386
2166
|
* Format a queued tool-update as a synthetic system-style message for
|
|
@@ -1393,6 +2173,10 @@ function formatMcpUpdateMessage(summary) {
|
|
|
1393
2173
|
if (summary.added.length > 0) lines.push(`Newly available servers: ${summary.added.join(", ")}`);
|
|
1394
2174
|
if (summary.refreshed.length > 0) lines.push(`Refreshed servers: ${summary.refreshed.join(", ")}`);
|
|
1395
2175
|
if (summary.removed.length > 0) lines.push(`Removed servers (and their tools): ${summary.removed.join(", ")}`);
|
|
2176
|
+
if (summary.droppedTools > 0) {
|
|
2177
|
+
lines.push("");
|
|
2178
|
+
lines.push(...truncationLines(summary));
|
|
2179
|
+
}
|
|
1396
2180
|
const pending = pendingAuthEntries(summary);
|
|
1397
2181
|
if (pending.length > 0) {
|
|
1398
2182
|
lines.push("");
|
|
@@ -1408,9 +2192,10 @@ function formatMcpUpdateMessage(summary) {
|
|
|
1408
2192
|
if (timedOut.length > 0) {
|
|
1409
2193
|
lines.push("");
|
|
1410
2194
|
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) {
|
|
2195
|
+
for (const { id, stderr, diagnostics } of timedOut) {
|
|
1412
2196
|
lines.push(` - ${id}:`);
|
|
1413
|
-
|
|
2197
|
+
lines.push(...timeoutDiagnosticLines(diagnostics));
|
|
2198
|
+
appendTimeoutStderrBlock(lines, stderr);
|
|
1414
2199
|
}
|
|
1415
2200
|
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
2201
|
}
|
|
@@ -1499,156 +2284,16 @@ async function runToolUpdateLoop({ session, log }) {
|
|
|
1499
2284
|
}, "reached tool-update continuation cap; further updates will land on next request");
|
|
1500
2285
|
}
|
|
1501
2286
|
//#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
2287
|
//#region src/channel-context-ref.ts
|
|
1643
2288
|
/**
|
|
1644
|
-
* The worker injects
|
|
1645
|
-
* sandbox env (`SKYDIVE_CHANNEL_CONTEXT`) rather than the full context.
|
|
2289
|
+
* The worker injects a small reference — `{ channel, messageId, runId }` —
|
|
2290
|
+
* into the sandbox env (`SKYDIVE_CHANNEL_CONTEXT`) rather than the full context.
|
|
1646
2291
|
*
|
|
1647
2292
|
* The canonical `ChannelContextRef` type + `parseChannelContextRef` live in
|
|
1648
2293
|
* `@createinc/anyone-channels`, but the harness (`@skydiveai/*`) keeps zero
|
|
1649
2294
|
* `@createinc/*` dependencies — importing that package would pull the whole
|
|
1650
|
-
* platform channel stack (Slack/email/Linq SDKs, messaging)
|
|
1651
|
-
*
|
|
2295
|
+
* platform channel stack (Slack/email/Linq SDKs, messaging) just to read one
|
|
2296
|
+
* field. So we validate the field this consumer needs locally instead.
|
|
1652
2297
|
*/
|
|
1653
2298
|
const channelContextRefSchema = z.object({ messageId: z.string().nullable() });
|
|
1654
2299
|
/**
|
|
@@ -1680,31 +2325,96 @@ function apiBaseUrl() {
|
|
|
1680
2325
|
}
|
|
1681
2326
|
//#endregion
|
|
1682
2327
|
//#region src/extensions/platform.ts
|
|
2328
|
+
/**
|
|
2329
|
+
* Platform extension — bridges the agent harness to the Skydive platform daemon.
|
|
2330
|
+
*
|
|
2331
|
+
* Responsibilities:
|
|
2332
|
+
* - Heartbeat: periodic POST to the API so the sandbox manager knows the
|
|
2333
|
+
* agent is alive. Throttled to once per minute, triggered by tool events.
|
|
2334
|
+
* - Session tracking: registers the session with the daemon on start,
|
|
2335
|
+
* streams tool_call / tool_result events so the daemon can track which
|
|
2336
|
+
* session is actively executing, and signals session end on agent_end.
|
|
2337
|
+
* - Channel context: passes the SKYDIVE_CHANNEL_CONTEXT (containing the
|
|
2338
|
+
* messageId) to the daemon so file writes can be attributed to the
|
|
2339
|
+
* correct conversation.
|
|
2340
|
+
*
|
|
2341
|
+
* All daemon POSTs are fire-and-forget — failures are logged but never
|
|
2342
|
+
* block the agent. The daemon may not be running (e.g. local dev without
|
|
2343
|
+
* a sandbox), and that's fine.
|
|
2344
|
+
*/
|
|
1683
2345
|
const HEARTBEAT_THROTTLE_MS = 6e4;
|
|
1684
2346
|
const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
|
|
1685
2347
|
const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
|
|
1686
2348
|
const DAEMON_URL = "http://localhost:38994";
|
|
1687
|
-
const log$
|
|
2349
|
+
const log$11 = logger.child({ module: "platform-ext" });
|
|
1688
2350
|
function sandboxClient() {
|
|
1689
2351
|
const apiUrl = apiBaseUrl();
|
|
1690
2352
|
if (!apiUrl) return null;
|
|
1691
2353
|
return hc(`${apiUrl}/api/v1/sandbox`);
|
|
1692
2354
|
}
|
|
1693
2355
|
/**
|
|
1694
|
-
*
|
|
1695
|
-
*
|
|
1696
|
-
*
|
|
1697
|
-
*
|
|
1698
|
-
*
|
|
1699
|
-
*
|
|
2356
|
+
* Is this box still an unclaimed warm-pool sandbox? (ANY-6000, the
|
|
2357
|
+
* feature-flags half of the ANY-5184 pool 403 wave.)
|
|
2358
|
+
*
|
|
2359
|
+
* `GET /sandbox/feature-flags` is agent-only, so the shared poller's request
|
|
2360
|
+
* from a pool box can only 403 — a guaranteed-failing GET every 60s for the
|
|
2361
|
+
* life of the pool phase. The discriminator is the sandbox token's `type`
|
|
2362
|
+
* claim, read UNVERIFIED (this box never holds the signing secret): not an
|
|
2363
|
+
* authorization decision, only "should I bother calling?", and the api still
|
|
2364
|
+
* authorizes every request.
|
|
2365
|
+
*
|
|
2366
|
+
* Read per call from the daemon's persisted env file, NOT process.env:
|
|
2367
|
+
* claiming a pool box rebinds the token in place (the daemon rewrites this
|
|
2368
|
+
* file) while the harness's process.env keeps the boot snapshot, so a
|
|
2369
|
+
* process-env gate would leave a claimed box permanently skipping — trading a
|
|
2370
|
+
* wasted request for silently frozen flags, which is strictly worse. "Cannot
|
|
2371
|
+
* tell" (no file, no token, unparseable payload) reports false so the poll
|
|
2372
|
+
* proceeds.
|
|
1700
2373
|
*/
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
2374
|
+
const daemonEnvIdentitySchema = z.object({
|
|
2375
|
+
ANYONE_SANDBOX_TOKEN: z.string().optional(),
|
|
2376
|
+
SKYDIVE_SANDBOX_TOKEN: z.string().optional()
|
|
2377
|
+
}).passthrough();
|
|
2378
|
+
const tokenTypeSchema = z.object({ type: z.string() }).passthrough();
|
|
2379
|
+
async function isPoolIdentity() {
|
|
2380
|
+
try {
|
|
2381
|
+
const override = process.env.ANYONE_DAEMON_ENV_CACHE;
|
|
2382
|
+
const candidates = override ? [override] : ["/run/anyone-system/daemon-env.json", "/tmp/.anyone/daemon-env.json"];
|
|
2383
|
+
let raw = null;
|
|
2384
|
+
for (const file of candidates) {
|
|
2385
|
+
raw = await readFile(file, "utf8").catch(() => null);
|
|
2386
|
+
if (raw !== null) break;
|
|
2387
|
+
}
|
|
2388
|
+
if (raw === null) return false;
|
|
2389
|
+
const env = daemonEnvIdentitySchema.safeParse(JSON.parse(raw));
|
|
2390
|
+
if (!env.success) return false;
|
|
2391
|
+
const token = env.data.ANYONE_SANDBOX_TOKEN ?? env.data.SKYDIVE_SANDBOX_TOKEN;
|
|
2392
|
+
if (typeof token !== "string" || token === "") return false;
|
|
2393
|
+
const payload = token.split(".")[1];
|
|
2394
|
+
if (!payload) return false;
|
|
2395
|
+
const claims = tokenTypeSchema.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString("utf8")));
|
|
2396
|
+
return claims.success && claims.data.type === "onboarding-pool";
|
|
2397
|
+
} catch (_err) {
|
|
2398
|
+
return false;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Fetch every harness feature flag in one GET (`{ contextManagement, ... }`
|
|
2403
|
+
* — see apps/anyone/api/src/routes/sandbox-feature-flags.ts). Returns
|
|
2404
|
+
* null when indeterminate (no api url, the request failed, or the box is an
|
|
2405
|
+
* unclaimed pool sandbox whose token the route would 403) so the shared
|
|
2406
|
+
* poller keeps the last-known values rather than flipping on a transient error.
|
|
2407
|
+
* This is the single fetch behind `feature-flags-poll.ts`; extensions read the
|
|
2408
|
+
* polled values there instead of issuing their own GET.
|
|
2409
|
+
*/
|
|
2410
|
+
async function fetchHarnessFlags() {
|
|
2411
|
+
const client = sandboxClient();
|
|
2412
|
+
if (!client) return null;
|
|
2413
|
+
if (await isPoolIdentity()) return null;
|
|
1704
2414
|
try {
|
|
1705
2415
|
const res = await client["feature-flags"].$get();
|
|
1706
2416
|
if (!res.ok) {
|
|
1707
|
-
log$
|
|
2417
|
+
log$11.debug({
|
|
1708
2418
|
status: res.status,
|
|
1709
2419
|
event: "feature_flags_fetch_failed"
|
|
1710
2420
|
}, "feature-flags fetch failed");
|
|
@@ -1713,10 +2423,10 @@ async function fetchHarnessFlags() {
|
|
|
1713
2423
|
const body = await res.json();
|
|
1714
2424
|
return {
|
|
1715
2425
|
contextManagement: body.contextManagement ?? null,
|
|
1716
|
-
|
|
2426
|
+
closingText: body.closingText ?? null
|
|
1717
2427
|
};
|
|
1718
2428
|
} catch (err) {
|
|
1719
|
-
log$
|
|
2429
|
+
log$11.debug({
|
|
1720
2430
|
err,
|
|
1721
2431
|
event: "feature_flags_fetch_error"
|
|
1722
2432
|
}, "feature-flags request errored");
|
|
@@ -1727,7 +2437,7 @@ function postHeartbeat({ messageId }) {
|
|
|
1727
2437
|
const client = sandboxClient();
|
|
1728
2438
|
if (!client) return;
|
|
1729
2439
|
client.heartbeat.$post({ json: { messageId } }).catch((err) => {
|
|
1730
|
-
log$
|
|
2440
|
+
log$11.debug({
|
|
1731
2441
|
err,
|
|
1732
2442
|
event: "heartbeat_failed"
|
|
1733
2443
|
}, "heartbeat failed");
|
|
@@ -1739,7 +2449,7 @@ async function resolveConversationFromApi(messageId) {
|
|
|
1739
2449
|
try {
|
|
1740
2450
|
const res = await client["message-conversation"].$get({ query: { messageId } });
|
|
1741
2451
|
if (!res.ok) {
|
|
1742
|
-
log$
|
|
2452
|
+
log$11.warn({
|
|
1743
2453
|
status: res.status,
|
|
1744
2454
|
messageId,
|
|
1745
2455
|
event: "resolve_conversation_failed"
|
|
@@ -1748,7 +2458,7 @@ async function resolveConversationFromApi(messageId) {
|
|
|
1748
2458
|
}
|
|
1749
2459
|
return (await res.json()).conversationId ?? null;
|
|
1750
2460
|
} catch (err) {
|
|
1751
|
-
log$
|
|
2461
|
+
log$11.warn({
|
|
1752
2462
|
err,
|
|
1753
2463
|
messageId,
|
|
1754
2464
|
event: "resolve_conversation_error"
|
|
@@ -1765,6 +2475,71 @@ async function postBackgroundTaskDone({ messageId, content }) {
|
|
|
1765
2475
|
} });
|
|
1766
2476
|
if (!res.ok) throw new Error(`bg-task-done POST failed: ${res.status}`);
|
|
1767
2477
|
}
|
|
2478
|
+
async function putBackgroundTaskJournalSpec({ messageId, spec }) {
|
|
2479
|
+
const client = sandboxClient();
|
|
2480
|
+
if (!client) return;
|
|
2481
|
+
try {
|
|
2482
|
+
const res = await client["bg-task-journal"].$put({ json: {
|
|
2483
|
+
messageId,
|
|
2484
|
+
spec
|
|
2485
|
+
} });
|
|
2486
|
+
if (!res.ok) log$11.warn({
|
|
2487
|
+
status: res.status,
|
|
2488
|
+
taskId: spec.id,
|
|
2489
|
+
event: "bg_journal_put_failed"
|
|
2490
|
+
}, "bg-task journal PUT failed");
|
|
2491
|
+
} catch (err) {
|
|
2492
|
+
log$11.warn({
|
|
2493
|
+
err,
|
|
2494
|
+
taskId: spec.id,
|
|
2495
|
+
event: "bg_journal_put_failed"
|
|
2496
|
+
}, "bg-task journal PUT threw");
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
|
|
2500
|
+
const client = sandboxClient();
|
|
2501
|
+
if (!client) return;
|
|
2502
|
+
try {
|
|
2503
|
+
await client["bg-task-journal"].$delete({ json: {
|
|
2504
|
+
messageId,
|
|
2505
|
+
taskId
|
|
2506
|
+
} });
|
|
2507
|
+
} catch (err) {
|
|
2508
|
+
log$11.debug({
|
|
2509
|
+
err,
|
|
2510
|
+
taskId,
|
|
2511
|
+
event: "bg_journal_delete_failed"
|
|
2512
|
+
}, "bg-task journal DELETE failed");
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
async function listBackgroundTaskJournalSpecs({ messageId }) {
|
|
2516
|
+
const client = sandboxClient();
|
|
2517
|
+
if (!client) return [];
|
|
2518
|
+
try {
|
|
2519
|
+
const res = await client["bg-task-journal"].$get({ query: { messageId } });
|
|
2520
|
+
if (!res.ok) return [];
|
|
2521
|
+
return (await res.json()).specs ?? [];
|
|
2522
|
+
} catch (err) {
|
|
2523
|
+
log$11.debug({
|
|
2524
|
+
err,
|
|
2525
|
+
event: "bg_journal_list_failed"
|
|
2526
|
+
}, "bg-task journal GET failed");
|
|
2527
|
+
return [];
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
function postBackgroundTasksSnapshot({ messageId, tasks }) {
|
|
2531
|
+
const client = sandboxClient();
|
|
2532
|
+
if (!client || !messageId) return;
|
|
2533
|
+
client["bg-tasks"].$post({ json: {
|
|
2534
|
+
messageId,
|
|
2535
|
+
tasks
|
|
2536
|
+
} }).catch((err) => {
|
|
2537
|
+
log$11.debug({
|
|
2538
|
+
err,
|
|
2539
|
+
event: "bg_tasks_snapshot_failed"
|
|
2540
|
+
}, "bg-tasks snapshot publish failed");
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
1768
2543
|
async function postSubagentSpawn({ messageId, tasks }) {
|
|
1769
2544
|
const client = sandboxClient();
|
|
1770
2545
|
if (!client) throw new Error("no api url for subagent-spawn");
|
|
@@ -1772,8 +2547,19 @@ async function postSubagentSpawn({ messageId, tasks }) {
|
|
|
1772
2547
|
messageId,
|
|
1773
2548
|
tasks
|
|
1774
2549
|
} });
|
|
1775
|
-
if (!res.ok)
|
|
1776
|
-
|
|
2550
|
+
if (!res.ok) {
|
|
2551
|
+
let detail = "";
|
|
2552
|
+
try {
|
|
2553
|
+
const errBody = await res.json();
|
|
2554
|
+
if (errBody && typeof errBody.error === "string") detail = `: ${errBody.error}`;
|
|
2555
|
+
} catch {}
|
|
2556
|
+
throw new Error(`subagent-spawn POST failed (${res.status})${detail}`);
|
|
2557
|
+
}
|
|
2558
|
+
const body = await res.json();
|
|
2559
|
+
return {
|
|
2560
|
+
taskIds: body.taskIds,
|
|
2561
|
+
tasks: body.tasks ?? []
|
|
2562
|
+
};
|
|
1777
2563
|
}
|
|
1778
2564
|
function createHeartbeatThrottle({ messageId }) {
|
|
1779
2565
|
let lastAt = 0;
|
|
@@ -1822,7 +2608,7 @@ function createToolHeartbeat({ messageId }) {
|
|
|
1822
2608
|
}
|
|
1823
2609
|
heartbeatCount++;
|
|
1824
2610
|
if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
|
|
1825
|
-
log$
|
|
2611
|
+
log$11.warn({
|
|
1826
2612
|
heartbeatCount,
|
|
1827
2613
|
activeToolCalls: [...activeToolCalls]
|
|
1828
2614
|
}, "tool heartbeat max reached, stopping");
|
|
@@ -1853,7 +2639,7 @@ function postToDaemon(path, body) {
|
|
|
1853
2639
|
headers: { "content-type": "application/json" },
|
|
1854
2640
|
body: JSON.stringify(body)
|
|
1855
2641
|
}).catch((err) => {
|
|
1856
|
-
log$
|
|
2642
|
+
log$11.debug({
|
|
1857
2643
|
err,
|
|
1858
2644
|
path,
|
|
1859
2645
|
event: "daemon_post_failed"
|
|
@@ -1862,7 +2648,7 @@ function postToDaemon(path, body) {
|
|
|
1862
2648
|
}
|
|
1863
2649
|
function createPlatformExtensions({ sessionId, channelContext }) {
|
|
1864
2650
|
return (pi) => {
|
|
1865
|
-
log$
|
|
2651
|
+
log$11.info({
|
|
1866
2652
|
sessionId,
|
|
1867
2653
|
hasChannelContext: Boolean(channelContext)
|
|
1868
2654
|
}, "platform extension initialized");
|
|
@@ -1911,7 +2697,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
|
|
|
1911
2697
|
});
|
|
1912
2698
|
});
|
|
1913
2699
|
pi.on("agent_end", () => {
|
|
1914
|
-
log$
|
|
2700
|
+
log$11.info({ sessionId }, "session ending");
|
|
1915
2701
|
postToDaemon("/session/end", { sessionId });
|
|
1916
2702
|
});
|
|
1917
2703
|
};
|
|
@@ -1922,37 +2708,34 @@ function createPlatformExtensions({ sessionId, channelContext }) {
|
|
|
1922
2708
|
* Shared harness feature-flag poll.
|
|
1923
2709
|
*
|
|
1924
2710
|
* The api exposes one `/feature-flags` GET that returns every harness flag in a
|
|
1925
|
-
* single response (`{ contextManagement,
|
|
2711
|
+
* single response (`{ contextManagement, closingText, commandFlags }` — see
|
|
1926
2712
|
* apps/anyone/api/src/routes/sandbox-feature-flags.ts). Rather than each
|
|
1927
2713
|
* extension issuing its own GET — and, worse, a *blocking* GET on the
|
|
1928
2714
|
* pre-first-token `session_start` path — a single background poller fetches
|
|
1929
2715
|
* that response once per interval and fans the values out to every subscriber.
|
|
1930
2716
|
*
|
|
1931
|
-
* Why one poller:
|
|
1932
|
-
*
|
|
1933
|
-
*
|
|
1934
|
-
*
|
|
1935
|
-
*
|
|
1936
|
-
* the hot path allocation-only. A cold cache reads as `null` (fail-open to
|
|
1937
|
-
* unregistered); a newly-flipped flag takes effect on the next poll, matching
|
|
1938
|
-
* how context-management already treats its flag.
|
|
2717
|
+
* Why one poller: context-management consumes the `contextManagement` flag and
|
|
2718
|
+
* the closing-text loop consumes `closingText`, both without a blocking GET on
|
|
2719
|
+
* the pre-first-token `session_start` path. Reading the last-polled value keeps
|
|
2720
|
+
* the hot path allocation-only; a cold cache reads as `null` and a
|
|
2721
|
+
* newly-flipped flag takes effect on the next poll.
|
|
1939
2722
|
*
|
|
1940
2723
|
* The poll is fire-and-forget and self-unref'd — it never keeps the process
|
|
1941
2724
|
* alive and an indeterminate result (no api url / transient failure) leaves the
|
|
1942
2725
|
* last-known values untouched so a blip can't silently flip behavior.
|
|
1943
2726
|
*/
|
|
1944
|
-
const log$
|
|
2727
|
+
const log$10 = logger.child({ module: "feature-flags-poll" });
|
|
1945
2728
|
const FLAG_POLL_INTERVAL_MS = 6e4;
|
|
1946
2729
|
let contextManagement = null;
|
|
1947
|
-
let
|
|
2730
|
+
let closingText = null;
|
|
1948
2731
|
const subscribers = {
|
|
1949
2732
|
contextManagement: /* @__PURE__ */ new Set(),
|
|
1950
|
-
|
|
2733
|
+
closingText: /* @__PURE__ */ new Set()
|
|
1951
2734
|
};
|
|
1952
2735
|
let pollerStarted = false;
|
|
1953
2736
|
let firstPollSettled = false;
|
|
1954
2737
|
let resolveFirstPoll = null;
|
|
1955
|
-
|
|
2738
|
+
new Promise((resolve) => {
|
|
1956
2739
|
resolveFirstPoll = resolve;
|
|
1957
2740
|
});
|
|
1958
2741
|
function markFirstPollSettled() {
|
|
@@ -1962,19 +2745,7 @@ function markFirstPollSettled() {
|
|
|
1962
2745
|
}
|
|
1963
2746
|
/** Last-polled value of a flag, or `null` if not yet resolved. */
|
|
1964
2747
|
function getPolledFlag(name) {
|
|
1965
|
-
return name === "
|
|
1966
|
-
}
|
|
1967
|
-
/**
|
|
1968
|
-
* Await the first poll already kicked by `startFeatureFlagPoller` (never a new
|
|
1969
|
-
* GET). Resolves when that poll settles, immediately if it already has, or
|
|
1970
|
-
* immediately when there's no flag source to poll. Callers on the hot path
|
|
1971
|
-
* should race this against their own short timeout so a slow/failed flag
|
|
1972
|
-
* service cannot delay first-token; a timeout just means the caller reads the
|
|
1973
|
-
* still-cold cache and falls back to its default, exactly as before.
|
|
1974
|
-
*/
|
|
1975
|
-
function awaitFirstFlagPoll() {
|
|
1976
|
-
if (firstPollSettled || !hasFlagSource()) return Promise.resolve();
|
|
1977
|
-
return firstPollPromise;
|
|
2748
|
+
return name === "closingText" ? closingText : contextManagement;
|
|
1978
2749
|
}
|
|
1979
2750
|
/**
|
|
1980
2751
|
* Subscribe to changes of a flag. The callback fires only on a *transition*
|
|
@@ -1987,13 +2758,13 @@ function onFlagChange(name, cb) {
|
|
|
1987
2758
|
}
|
|
1988
2759
|
function apply(name, next) {
|
|
1989
2760
|
if (next === null) return;
|
|
1990
|
-
const prev = name === "
|
|
1991
|
-
if (name === "
|
|
1992
|
-
else
|
|
2761
|
+
const prev = name === "closingText" ? closingText : contextManagement;
|
|
2762
|
+
if (name === "closingText") closingText = next;
|
|
2763
|
+
else contextManagement = next;
|
|
1993
2764
|
if (next !== prev) for (const cb of subscribers[name]) try {
|
|
1994
2765
|
cb(next);
|
|
1995
2766
|
} catch (err) {
|
|
1996
|
-
log$
|
|
2767
|
+
log$10.warn({
|
|
1997
2768
|
err,
|
|
1998
2769
|
flag: name
|
|
1999
2770
|
}, "flag subscriber threw");
|
|
@@ -2004,9 +2775,9 @@ async function pollOnce() {
|
|
|
2004
2775
|
const flags = await fetchHarnessFlags();
|
|
2005
2776
|
if (!flags) return;
|
|
2006
2777
|
apply("contextManagement", flags.contextManagement ?? null);
|
|
2007
|
-
apply("
|
|
2778
|
+
apply("closingText", flags.closingText ?? null);
|
|
2008
2779
|
} catch (err) {
|
|
2009
|
-
log$
|
|
2780
|
+
log$10.debug({ err }, "feature-flag poll threw");
|
|
2010
2781
|
}
|
|
2011
2782
|
}
|
|
2012
2783
|
/**
|
|
@@ -2022,6 +2793,569 @@ function startFeatureFlagPoller() {
|
|
|
2022
2793
|
setInterval(() => void pollOnce(), FLAG_POLL_INTERVAL_MS).unref?.();
|
|
2023
2794
|
}
|
|
2024
2795
|
//#endregion
|
|
2796
|
+
//#region src/closing-text-loop.ts
|
|
2797
|
+
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>";
|
|
2798
|
+
function isNonEmptyText(block) {
|
|
2799
|
+
return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
|
|
2800
|
+
}
|
|
2801
|
+
/**
|
|
2802
|
+
* True when the assistant produced no visible text since the human's last
|
|
2803
|
+
* message this turn — i.e. the turn ended on tool calls / thinking only.
|
|
2804
|
+
*
|
|
2805
|
+
* We scan from the end back to the most recent `user` message (the human turn
|
|
2806
|
+
* that triggered this run) and inspect every `assistant` message after it.
|
|
2807
|
+
* A string-content assistant message (rare, but pi allows it) counts as text
|
|
2808
|
+
* when non-blank. `toolResult` and custom messages are ignored.
|
|
2809
|
+
*/
|
|
2810
|
+
function turnEndedWithoutVisibleText(messages) {
|
|
2811
|
+
let sawAssistant = false;
|
|
2812
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2813
|
+
const m = messages[i];
|
|
2814
|
+
if (!m || m.role === "user") break;
|
|
2815
|
+
if (m.role !== "assistant") continue;
|
|
2816
|
+
sawAssistant = true;
|
|
2817
|
+
if (typeof m.content === "string") {
|
|
2818
|
+
if (m.content.trim().length > 0) return false;
|
|
2819
|
+
continue;
|
|
2820
|
+
}
|
|
2821
|
+
if (Array.isArray(m.content) && m.content.some(isNonEmptyText)) return false;
|
|
2822
|
+
}
|
|
2823
|
+
return sawAssistant;
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* True when the last assistant message this turn ended in a way we must not
|
|
2827
|
+
* nudge: a user abort or a provider error. Both already surface their own
|
|
2828
|
+
* terminal signal to the client; a closing-text prompt on top would be noise.
|
|
2829
|
+
*/
|
|
2830
|
+
function turnEndedAbnormally(messages) {
|
|
2831
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2832
|
+
const m = messages[i];
|
|
2833
|
+
if (!m || m.role !== "assistant") continue;
|
|
2834
|
+
return m.stopReason === "aborted" || m.stopReason === "error";
|
|
2835
|
+
}
|
|
2836
|
+
return false;
|
|
2837
|
+
}
|
|
2838
|
+
async function runClosingTextLoop({ session, log, enabled = getPolledFlag("closingText") === true }) {
|
|
2839
|
+
if (!enabled) return;
|
|
2840
|
+
if (turnEndedAbnormally(session.messages)) return;
|
|
2841
|
+
if (!turnEndedWithoutVisibleText(session.messages)) return;
|
|
2842
|
+
log.info({ event: "closing_text_continuation_injected" }, "turn ended on a tool call with no visible reply; injecting a closing-text continuation");
|
|
2843
|
+
await session.sendCustomMessage({
|
|
2844
|
+
customType: "closing-text-nudge",
|
|
2845
|
+
content: CLOSING_TEXT_NUDGE,
|
|
2846
|
+
display: false,
|
|
2847
|
+
details: {}
|
|
2848
|
+
}, { triggerTurn: true });
|
|
2849
|
+
}
|
|
2850
|
+
//#endregion
|
|
2851
|
+
//#region src/tracing.ts
|
|
2852
|
+
const SERVICE_NAME = "skydive-agent-harness";
|
|
2853
|
+
const DAEMON_TRACES_URL = "http://localhost:38994/v1/traces";
|
|
2854
|
+
let provider = null;
|
|
2855
|
+
function initTracing() {
|
|
2856
|
+
if (provider) return;
|
|
2857
|
+
propagation.setGlobalPropagator(new W3CTraceContextPropagator());
|
|
2858
|
+
provider = new NodeTracerProvider({ resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }) });
|
|
2859
|
+
const exporter = new OTLPTraceExporter({ url: DAEMON_TRACES_URL });
|
|
2860
|
+
provider.addSpanProcessor(new BatchSpanProcessor(exporter, { scheduledDelayMillis: 1e3 }));
|
|
2861
|
+
provider.register();
|
|
2862
|
+
logger.info({
|
|
2863
|
+
event: "tracing_enabled",
|
|
2864
|
+
endpoint: DAEMON_TRACES_URL
|
|
2865
|
+
}, "OTel tracing initialized — exporting via daemon");
|
|
2866
|
+
const shutdown = async () => {
|
|
2867
|
+
await shutdownTracing();
|
|
2868
|
+
process.exit(0);
|
|
2869
|
+
};
|
|
2870
|
+
process.on("SIGTERM", shutdown);
|
|
2871
|
+
process.on("SIGINT", shutdown);
|
|
2872
|
+
}
|
|
2873
|
+
function getTracer() {
|
|
2874
|
+
return trace.getTracer(SERVICE_NAME);
|
|
2875
|
+
}
|
|
2876
|
+
function extractRemoteContext() {
|
|
2877
|
+
const traceparent = getCurrentTraceparent();
|
|
2878
|
+
if (!traceparent) return ROOT_CONTEXT;
|
|
2879
|
+
const carrier = { traceparent };
|
|
2880
|
+
return propagation.extract(ROOT_CONTEXT, carrier, {
|
|
2881
|
+
get: (c, key) => c[key],
|
|
2882
|
+
keys: (c) => Object.keys(c)
|
|
2883
|
+
});
|
|
2884
|
+
}
|
|
2885
|
+
async function shutdownTracing() {
|
|
2886
|
+
if (provider) await provider.shutdown();
|
|
2887
|
+
}
|
|
2888
|
+
//#endregion
|
|
2889
|
+
//#region src/harness.ts
|
|
2890
|
+
/**
|
|
2891
|
+
* Skydive composition over @skydiveai/pi-server: wires the platform
|
|
2892
|
+
* defaults (tracing to the daemon, tool-update hot-reload hooks, prewarm
|
|
2893
|
+
* paths, header passthrough for proxy routing, Skydive agent-card
|
|
2894
|
+
* branding) into the generic protocol server, and returns mountable
|
|
2895
|
+
* handlers. The agent supplies the pi session factory (their session.ts)
|
|
2896
|
+
* and owns the express app:
|
|
2897
|
+
*
|
|
2898
|
+
* const { platform, protocols } = createHarness({
|
|
2899
|
+
* cwd: process.cwd(),
|
|
2900
|
+
* createSession,
|
|
2901
|
+
* });
|
|
2902
|
+
* app.get('/health', platform.handlers.health);
|
|
2903
|
+
* app.use(platform.handlers.injectEnv);
|
|
2904
|
+
* app.use(platform.handlers.prewarm); // matches /_skydive/prewarm + legacy alias
|
|
2905
|
+
* app.use(protocols.handlers.all);
|
|
2906
|
+
*/
|
|
2907
|
+
const A2A_PATH = "/a2a";
|
|
2908
|
+
const AGENT_CARD_PATH = "/.well-known/agent-card.json";
|
|
2909
|
+
const PREWARM_PATHS = ["/_skydive/prewarm", "/_anyone/prewarm"];
|
|
2910
|
+
const PASSTHROUGH_HEADER_PREFIXES = ["x-anyone-", "x-skydive-"];
|
|
2911
|
+
function createHarness(options) {
|
|
2912
|
+
initTracing();
|
|
2913
|
+
startFeatureFlagPoller();
|
|
2914
|
+
readPlatformVersions().then((runtimeVersions) => logger.info({
|
|
2915
|
+
event: "runtime_versions",
|
|
2916
|
+
runtimeVersions
|
|
2917
|
+
}, "platform runtime versions"));
|
|
2918
|
+
const serverOptions = {
|
|
2919
|
+
...options,
|
|
2920
|
+
onSessionSetup: options.onSessionSetup ?? ((args) => {
|
|
2921
|
+
installToolUpdateAutoStop(args);
|
|
2922
|
+
installIterationCap(args);
|
|
2923
|
+
}),
|
|
2924
|
+
postPrompt: options.postPrompt ?? (async (args) => {
|
|
2925
|
+
await runToolUpdateLoop(args);
|
|
2926
|
+
await runClosingTextLoop(args);
|
|
2927
|
+
}),
|
|
2928
|
+
passthroughHeaderPrefixes: options.passthroughHeaderPrefixes ?? PASSTHROUGH_HEADER_PREFIXES,
|
|
2929
|
+
prewarmPaths: options.prewarmPaths ?? PREWARM_PATHS
|
|
2930
|
+
};
|
|
2931
|
+
const webHandlers = createProtocolHandlers(serverOptions);
|
|
2932
|
+
const cardOverrides = {
|
|
2933
|
+
name: "Skydive Agent",
|
|
2934
|
+
description: "An AI coding agent powered by the Skydive platform.",
|
|
2935
|
+
...options.agentCard
|
|
2936
|
+
};
|
|
2937
|
+
const agentCardWeb = async (request) => {
|
|
2938
|
+
const url = new URL(request.url);
|
|
2939
|
+
if (request.method !== "GET" || url.pathname !== AGENT_CARD_PATH) return null;
|
|
2940
|
+
return Response.json(buildAgentCard(cardOverrides.url ?? `${url.origin}${A2A_PATH}`, cardOverrides));
|
|
2941
|
+
};
|
|
2942
|
+
const a2a = restHandler({
|
|
2943
|
+
requestHandler: new DefaultRequestHandler(buildAgentCard(cardOverrides.url ?? A2A_PATH, cardOverrides), new InMemoryTaskStore(), createAgentExecutor(serverOptions), new DefaultExecutionEventBusManager()),
|
|
2944
|
+
userBuilder: UserBuilder.noAuthentication
|
|
2945
|
+
});
|
|
2946
|
+
return {
|
|
2947
|
+
platform: { handlers: {
|
|
2948
|
+
/**
|
|
2949
|
+
* Platform health plus the agent's `healthMetadata`. Mount above
|
|
2950
|
+
* injectEnv — health must respond immediately for prewarm
|
|
2951
|
+
* stashing and readiness probes, and injectEnv can wait up to
|
|
2952
|
+
* 10s for env vars during boot.
|
|
2953
|
+
*/
|
|
2954
|
+
health: createHealthHandler({ metadata: options.healthMetadata ?? null }),
|
|
2955
|
+
/** Loads platform env (e2b envd / daemon long-poll). */
|
|
2956
|
+
injectEnv: createPlatformEnvMiddleware(),
|
|
2957
|
+
prewarm: webHandlerToMiddleware(webHandlers.prewarm)
|
|
2958
|
+
} },
|
|
2959
|
+
protocols: { handlers: {
|
|
2960
|
+
/** Express-style; mount at /a2a. */
|
|
2961
|
+
a2a,
|
|
2962
|
+
/** GET /.well-known/agent-card.json. */
|
|
2963
|
+
agentCard: webHandlerToMiddleware(agentCardWeb),
|
|
2964
|
+
/** Mirrors each vendor's API shape. */
|
|
2965
|
+
openai: { v1: {
|
|
2966
|
+
chat: { completions: webHandlerToMiddleware(webHandlers.chatCompletions) },
|
|
2967
|
+
responses: webHandlerToMiddleware(webHandlers.responses)
|
|
2968
|
+
} },
|
|
2969
|
+
anthropic: { v1: { messages: webHandlerToMiddleware(webHandlers.messages) } },
|
|
2970
|
+
/**
|
|
2971
|
+
* Everything in one mount: a2a (+ agent card) at their well-known
|
|
2972
|
+
* paths, then chat-completions / anthropic-messages / responses.
|
|
2973
|
+
* Calls next() when nothing matches.
|
|
2974
|
+
*/
|
|
2975
|
+
all: chainMiddleware([mountAt(A2A_PATH, a2a), webHandlerToMiddleware(composeHandlers([
|
|
2976
|
+
agentCardWeb,
|
|
2977
|
+
webHandlers.chatCompletions,
|
|
2978
|
+
webHandlers.messages,
|
|
2979
|
+
webHandlers.responses
|
|
2980
|
+
]))])
|
|
2981
|
+
} }
|
|
2982
|
+
};
|
|
2983
|
+
}
|
|
2984
|
+
/** Effective bash timeout: the model's value when it gave a positive number, else the default. */
|
|
2985
|
+
function resolveBashTimeout(provided) {
|
|
2986
|
+
return typeof provided === "number" && provided > 0 ? provided : 600;
|
|
2987
|
+
}
|
|
2988
|
+
const bashDefaultTimeoutExtension = (pi) => {
|
|
2989
|
+
pi.on("tool_call", async (event) => {
|
|
2990
|
+
if (event.toolName !== "bash") return;
|
|
2991
|
+
event.input.timeout = resolveBashTimeout(event.input.timeout);
|
|
2992
|
+
});
|
|
2993
|
+
};
|
|
2994
|
+
//#endregion
|
|
2995
|
+
//#region src/extensions/resource-pressure-warning.ts
|
|
2996
|
+
/**
|
|
2997
|
+
* Mid-run resource-pressure warning to the agent.
|
|
2998
|
+
*
|
|
2999
|
+
* The sandbox already detects pressure — the boot scripts cap the
|
|
3000
|
+
* user-workload cgroup (memory.high/memory.max) and watchers log warn/crit
|
|
3001
|
+
* edges for memory and disk — but nothing told the *agent*, so a turn burned
|
|
3002
|
+
* straight to the OOM kill (or a full disk) and only learned about it from
|
|
3003
|
+
* the post-mortem notice. This extension closes that gap in-process: while a
|
|
3004
|
+
* turn is active it polls the agent cgroup and the root filesystem and, the
|
|
3005
|
+
* first time usage crosses a warn threshold, folds a system notification into
|
|
3006
|
+
* the open turn so the agent can checkpoint, shed work (constrain
|
|
3007
|
+
* parallelism, kill a background hog, clean scratch space), or request a
|
|
3008
|
+
* bigger tier BEFORE the kill.
|
|
3009
|
+
*
|
|
3010
|
+
* The notification is triggered by the two conditions that actually kill
|
|
3011
|
+
* work — memory near the cgroup hard cap, disk near full — and reports a
|
|
3012
|
+
* snapshot of all the relevant stats (memory, CPU utilization, disk) so the
|
|
3013
|
+
* agent can tell which resource is the problem and how much headroom the
|
|
3014
|
+
* others have.
|
|
3015
|
+
*
|
|
3016
|
+
* Edge-triggered, once per trigger per turn: the fired flags reset on
|
|
3017
|
+
* agent_start, so a turn that rides a threshold gets one warning per
|
|
3018
|
+
* resource, not a stream. Polling only runs while the agent is active — an
|
|
3019
|
+
* idle sandbox's resource usage is not the agent's problem and there is no
|
|
3020
|
+
* open turn to deliver into anyway.
|
|
3021
|
+
*
|
|
3022
|
+
* Best-effort throughout: any read failure (cgroup absent, controller not
|
|
3023
|
+
* delegated, non-cgroup-v2 host, df missing) reads as "no signal" for that
|
|
3024
|
+
* stat and the extension warns on what it can see — it must never break a
|
|
3025
|
+
* turn over an observability feature.
|
|
3026
|
+
*/
|
|
3027
|
+
const execFileAsync = promisify(execFile);
|
|
3028
|
+
const log$9 = logger.child({ module: "resource-pressure-warning" });
|
|
3029
|
+
const POLL_INTERVAL_MS = 1e4;
|
|
3030
|
+
function envOverride(name) {
|
|
3031
|
+
for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
|
|
3032
|
+
const value = process.env[`${prefix}${name}`];
|
|
3033
|
+
if (value != null && value !== "") return value;
|
|
3034
|
+
}
|
|
3035
|
+
return null;
|
|
3036
|
+
}
|
|
3037
|
+
function cgroupDir() {
|
|
3038
|
+
return envOverride("AGENT_CGROUP") ?? "/sys/fs/cgroup/agent";
|
|
3039
|
+
}
|
|
3040
|
+
function diskRoot() {
|
|
3041
|
+
return envOverride("DISK_ROOT") ?? "/";
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Read a cgroup v2 scalar file. Returns a number, or null for "max"
|
|
3045
|
+
* (uncapped), an empty/absent file, or any read/parse error — an uncapped or
|
|
3046
|
+
* unreadable limit means there is nothing meaningful to warn against.
|
|
3047
|
+
*/
|
|
3048
|
+
async function readScalar(file) {
|
|
3049
|
+
try {
|
|
3050
|
+
const raw = (await readFile(`${cgroupDir()}/${file}`, "utf8")).trim();
|
|
3051
|
+
if (raw === "" || raw === "max") return null;
|
|
3052
|
+
const n = Number(raw);
|
|
3053
|
+
return Number.isFinite(n) ? n : null;
|
|
3054
|
+
} catch (_error) {
|
|
3055
|
+
return null;
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
/**
|
|
3059
|
+
* Read a cgroup v2 "flat keyed" file (one `key value` pair per line, e.g.
|
|
3060
|
+
* cpu.stat) and return the counter for `key`, or null when absent.
|
|
3061
|
+
*/
|
|
3062
|
+
async function readKeyedCounter(file, key) {
|
|
3063
|
+
try {
|
|
3064
|
+
const raw = await readFile(`${cgroupDir()}/${file}`, "utf8");
|
|
3065
|
+
for (const line of raw.split("\n")) {
|
|
3066
|
+
const [k, v] = line.trim().split(/\s+/);
|
|
3067
|
+
if (k === key) {
|
|
3068
|
+
const n = Number(v);
|
|
3069
|
+
return Number.isFinite(n) ? n : null;
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
return null;
|
|
3073
|
+
} catch (_error) {
|
|
3074
|
+
return null;
|
|
3075
|
+
}
|
|
3076
|
+
}
|
|
3077
|
+
/**
|
|
3078
|
+
* Live memory usage as an integer percent of the hard cap, or null when
|
|
3079
|
+
* either side is unreadable/uncapped. Exported for tests.
|
|
3080
|
+
*/
|
|
3081
|
+
async function readMemUsePct() {
|
|
3082
|
+
const [current, max] = await Promise.all([readScalar("memory.current"), readScalar("memory.max")]);
|
|
3083
|
+
if (current === null || max === null || max <= 0) return null;
|
|
3084
|
+
return {
|
|
3085
|
+
pct: Math.floor(current / max * 100),
|
|
3086
|
+
currentBytes: current,
|
|
3087
|
+
maxBytes: max
|
|
3088
|
+
};
|
|
3089
|
+
}
|
|
3090
|
+
/**
|
|
3091
|
+
* Root filesystem used% (df -P Capacity column), or null on any failure.
|
|
3092
|
+
* Exported for tests.
|
|
3093
|
+
*/
|
|
3094
|
+
async function readDiskUsePct() {
|
|
3095
|
+
try {
|
|
3096
|
+
const { stdout } = await execFileAsync("df", ["-P", diskRoot()]);
|
|
3097
|
+
const dataRow = stdout.trim().split("\n")[1];
|
|
3098
|
+
if (dataRow == null) return null;
|
|
3099
|
+
const capacity = dataRow.trim().split(/\s+/)[4];
|
|
3100
|
+
if (capacity == null) return null;
|
|
3101
|
+
const pct = Number(capacity.replace("%", ""));
|
|
3102
|
+
return Number.isFinite(pct) ? pct : null;
|
|
3103
|
+
} catch (_error) {
|
|
3104
|
+
return null;
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
/**
|
|
3108
|
+
* CPU utilization sampler. cgroup v2 exposes cumulative CPU time
|
|
3109
|
+
* (cpu.stat usage_usec); utilization is the delta between two samples over
|
|
3110
|
+
* the wall time between them, normalized by core count. The first call after
|
|
3111
|
+
* construction has no previous sample and returns null.
|
|
3112
|
+
*/
|
|
3113
|
+
function createCpuSampler() {
|
|
3114
|
+
let prevUsageUsec = null;
|
|
3115
|
+
let prevAtMs = null;
|
|
3116
|
+
return async () => {
|
|
3117
|
+
const usage = await readKeyedCounter("cpu.stat", "usage_usec");
|
|
3118
|
+
const now = Date.now();
|
|
3119
|
+
const prev = prevUsageUsec;
|
|
3120
|
+
const prevAt = prevAtMs;
|
|
3121
|
+
prevUsageUsec = usage;
|
|
3122
|
+
prevAtMs = now;
|
|
3123
|
+
if (usage === null || prev === null || prevAt === null) return null;
|
|
3124
|
+
const wallUsec = (now - prevAt) * 1e3;
|
|
3125
|
+
if (wallUsec <= 0) return null;
|
|
3126
|
+
const cores = availableParallelism();
|
|
3127
|
+
const pct = Math.round((usage - prev) / (wallUsec * cores) * 100);
|
|
3128
|
+
return Math.max(0, Math.min(100, pct));
|
|
3129
|
+
};
|
|
3130
|
+
}
|
|
3131
|
+
function fmtMb(bytes) {
|
|
3132
|
+
return Math.round(bytes / 1024 / 1024);
|
|
3133
|
+
}
|
|
3134
|
+
/** The model-facing warning text. Exported for tests. */
|
|
3135
|
+
function resourcePressureWarningText(trigger, { mem, cpuPct, diskPct }) {
|
|
3136
|
+
const stats = [];
|
|
3137
|
+
if (mem) stats.push(`memory ${mem.pct}% of cap (${fmtMb(mem.currentBytes)}/${fmtMb(mem.maxBytes)} MB)`);
|
|
3138
|
+
if (cpuPct !== null) stats.push(`CPU ${cpuPct}%`);
|
|
3139
|
+
if (diskPct !== null) stats.push(`disk ${diskPct}% full`);
|
|
3140
|
+
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.`;
|
|
3141
|
+
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.";
|
|
3142
|
+
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>`;
|
|
3143
|
+
}
|
|
3144
|
+
const resourcePressureWarningExtension = (pi) => {
|
|
3145
|
+
let agentActive = false;
|
|
3146
|
+
let warnedMemThisTurn = false;
|
|
3147
|
+
let warnedDiskThisTurn = false;
|
|
3148
|
+
let timer = null;
|
|
3149
|
+
const sampleCpu = createCpuSampler();
|
|
3150
|
+
async function checkOnce() {
|
|
3151
|
+
if (!agentActive || warnedMemThisTurn && warnedDiskThisTurn) return;
|
|
3152
|
+
const [mem, cpuPct, diskPct] = await Promise.all([
|
|
3153
|
+
readMemUsePct(),
|
|
3154
|
+
sampleCpu(),
|
|
3155
|
+
readDiskUsePct()
|
|
3156
|
+
]);
|
|
3157
|
+
let trigger = null;
|
|
3158
|
+
if (!warnedMemThisTurn && mem !== null && mem.pct >= 80) {
|
|
3159
|
+
trigger = "memory";
|
|
3160
|
+
warnedMemThisTurn = true;
|
|
3161
|
+
} else if (!warnedDiskThisTurn && diskPct !== null && diskPct >= 80) {
|
|
3162
|
+
trigger = "disk";
|
|
3163
|
+
warnedDiskThisTurn = true;
|
|
3164
|
+
}
|
|
3165
|
+
if (trigger === null) return;
|
|
3166
|
+
log$9.warn({
|
|
3167
|
+
trigger,
|
|
3168
|
+
mem,
|
|
3169
|
+
cpuPct,
|
|
3170
|
+
diskPct
|
|
3171
|
+
}, "resource pressure warning delivered to agent");
|
|
3172
|
+
await pi.sendMessage({
|
|
3173
|
+
customType: "anyone-resource-pressure-warning",
|
|
3174
|
+
content: resourcePressureWarningText(trigger, {
|
|
3175
|
+
mem,
|
|
3176
|
+
cpuPct,
|
|
3177
|
+
diskPct
|
|
3178
|
+
}),
|
|
3179
|
+
display: false
|
|
3180
|
+
}, {
|
|
3181
|
+
triggerTurn: true,
|
|
3182
|
+
deliverAs: "followUp"
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
pi.on("agent_start", async () => {
|
|
3186
|
+
agentActive = true;
|
|
3187
|
+
warnedMemThisTurn = false;
|
|
3188
|
+
warnedDiskThisTurn = false;
|
|
3189
|
+
if (!timer) {
|
|
3190
|
+
timer = setInterval(() => {
|
|
3191
|
+
checkOnce().catch((err) => {
|
|
3192
|
+
log$9.error({ err }, "resource pressure check failed");
|
|
3193
|
+
});
|
|
3194
|
+
}, POLL_INTERVAL_MS);
|
|
3195
|
+
timer.unref?.();
|
|
3196
|
+
}
|
|
3197
|
+
});
|
|
3198
|
+
pi.on("agent_end", async () => {
|
|
3199
|
+
agentActive = false;
|
|
3200
|
+
if (timer) {
|
|
3201
|
+
clearInterval(timer);
|
|
3202
|
+
timer = null;
|
|
3203
|
+
}
|
|
3204
|
+
});
|
|
3205
|
+
};
|
|
3206
|
+
//#endregion
|
|
3207
|
+
//#region src/extensions/disk-guard.ts
|
|
3208
|
+
const log$8 = logger.child({ module: "disk-guard" });
|
|
3209
|
+
/**
|
|
3210
|
+
* In-band bypass. The guard is a safety net, not a jail: when the agent knows
|
|
3211
|
+
* a flagged command is genuinely safe (writing to a different mount, a tiny
|
|
3212
|
+
* bounded download, a delete-then-clone one-liner, an emergency it accepts the
|
|
3213
|
+
* risk on) it can force the command through by appending this marker as a
|
|
3214
|
+
* trailing shell comment. Kept as a comment so it never changes what the
|
|
3215
|
+
* command does, and matched case-insensitively with flexible spacing so the
|
|
3216
|
+
* agent doesn't have to reproduce it byte-for-byte.
|
|
3217
|
+
*/
|
|
3218
|
+
const BYPASS_MARKER = /#\s*disk-guard:\s*allow\b/i;
|
|
3219
|
+
/** The exact marker text the block message tells the agent to append. */
|
|
3220
|
+
const BYPASS_HINT = "# disk-guard: allow";
|
|
3221
|
+
/**
|
|
3222
|
+
* Harness-level kill switch: set DISK_GUARD_DISABLE=1 to turn the guard off
|
|
3223
|
+
* entirely. This is the "I own my harness, let me opt out" knob — an agent
|
|
3224
|
+
* that boots its own harness can disable the guard for its whole process
|
|
3225
|
+
* without a code roll, and it's also the fleet-wide escape hatch if the
|
|
3226
|
+
* classifier ever misfires and blocks real work. The bare name is honored
|
|
3227
|
+
* first; the SKYDIVE_/ANYONE_ prefixes are accepted too for consistency with
|
|
3228
|
+
* the other env overrides. Empty/unset/"0"/"false" leave the guard on.
|
|
3229
|
+
*/
|
|
3230
|
+
function guardDisabledByEnv() {
|
|
3231
|
+
for (const name of [
|
|
3232
|
+
"DISK_GUARD_DISABLE",
|
|
3233
|
+
"SKYDIVE_DISK_GUARD_DISABLE",
|
|
3234
|
+
"ANYONE_DISK_GUARD_DISABLE"
|
|
3235
|
+
]) {
|
|
3236
|
+
const value = process.env[name];
|
|
3237
|
+
if (value != null && value !== "" && value !== "0" && value !== "false") return true;
|
|
3238
|
+
}
|
|
3239
|
+
return false;
|
|
3240
|
+
}
|
|
3241
|
+
/** True when the command carries the in-band bypass marker. */
|
|
3242
|
+
function hasBypassMarker(command) {
|
|
3243
|
+
return BYPASS_MARKER.test(command);
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
3246
|
+
* Commands that reclaim space or merely inspect it. If any of these verbs
|
|
3247
|
+
* appears in the command line, we never block — otherwise the guard would trap
|
|
3248
|
+
* the agent by blocking the exact command it needs to dig out. Matched as
|
|
3249
|
+
* whole words so `remove-item` etc. don't accidentally match `rm`.
|
|
3250
|
+
*/
|
|
3251
|
+
const RECLAIM_PATTERNS = [
|
|
3252
|
+
/\brm\b/,
|
|
3253
|
+
/\brmdir\b/,
|
|
3254
|
+
/\bdf\b/,
|
|
3255
|
+
/\bdu\b/,
|
|
3256
|
+
/\bncdu\b/,
|
|
3257
|
+
/\bfind\b[^|]*\s-delete\b/,
|
|
3258
|
+
/\btruncate\b/,
|
|
3259
|
+
/\bgit\s+(gc|prune|clean|worktree\s+remove|worktree\s+prune)\b/,
|
|
3260
|
+
/\b(yarn|npm|pnpm|bun)\s+.*\b(cache\s+clean|cache\s+clear|store\s+prune)\b/,
|
|
3261
|
+
/\bcache\s+(clean|clear|prune)\b/,
|
|
3262
|
+
/\b(docker|podman)\s+.*\bprune\b/,
|
|
3263
|
+
/\bapt(-get)?\s+clean\b/,
|
|
3264
|
+
/\bjournalctl\b[^|]*--vacuum/
|
|
3265
|
+
];
|
|
3266
|
+
/**
|
|
3267
|
+
* File extensions that mean a download is actually LARGE — archives, disk
|
|
3268
|
+
* images, compiled/binary artifacts, model weights, media. A curl/wget is only
|
|
3269
|
+
* gated when it writes one of these; an API/page fetch to a `.json`/`.html`/
|
|
3270
|
+
* `.txt` file is tiny and must not be blocked. Derived from 4,144 real
|
|
3271
|
+
* commands: ~64% of `curl -o` uses were tiny fetches, only ~4% large.
|
|
3272
|
+
*/
|
|
3273
|
+
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)";
|
|
3274
|
+
/**
|
|
3275
|
+
* Commands that consume a meaningful amount of disk. Kept deliberately tight
|
|
3276
|
+
* and high-precision: validated against 4,144 real commands from the last 7
|
|
3277
|
+
* days, the earlier "writes a file" heuristic flagged 82% of everything (a
|
|
3278
|
+
* `curl -o /tmp/x.json` API call is not a disk event). This set flags ~33%,
|
|
3279
|
+
* almost all genuinely large — real installs, clones, big-archive downloads,
|
|
3280
|
+
* extractions. What was DROPPED and why:
|
|
3281
|
+
* - `git fetch` / `git pull` — incremental on an existing clone, usually tiny.
|
|
3282
|
+
* - `git checkout` — overwhelmingly `git checkout <ref> -- <file>` or a
|
|
3283
|
+
* branch switch, ~zero net growth; the rare full materialization isn't
|
|
3284
|
+
* worth the false-positive rate.
|
|
3285
|
+
* - bare `curl -o` / `wget -o` — see BIG_DOWNLOAD_EXT above.
|
|
3286
|
+
* - loose `… build` — matched `--mode=skip-build`, `oxfmt … build`, prose.
|
|
3287
|
+
* The remaining big-disk op in escher is `git clone` and `git worktree add`
|
|
3288
|
+
* (which is really a checkout), both kept.
|
|
3289
|
+
*/
|
|
3290
|
+
const SPACE_HUNGRY_PATTERNS = [
|
|
3291
|
+
/\bgit\s+clone\b/,
|
|
3292
|
+
/\bgit\s+worktree\s+add\b/,
|
|
3293
|
+
/\b(yarn|npm|pnpm|bun)\s+(install|add|ci)\b/,
|
|
3294
|
+
/\byarn\s*$/,
|
|
3295
|
+
/\byarn\s+--(?!version|help)\S/,
|
|
3296
|
+
/\bpip3?\s+install\b/,
|
|
3297
|
+
/\bapt(-get)?\s+install\b/,
|
|
3298
|
+
/\bnpm\s+pack\b/,
|
|
3299
|
+
/\bdocker\s+(build|pull)\b/,
|
|
3300
|
+
new RegExp(`\\b(?:curl|wget)\\b[^\\n]*\\s-[a-zA-Z]*[oO]\\b[^\\n]*\\.${BIG_DOWNLOAD_EXT}\\b`, "i"),
|
|
3301
|
+
new RegExp(`\\b(?:curl|wget)\\b[^\\n]*\\.${BIG_DOWNLOAD_EXT}\\b[^\\n]*\\s-[a-zA-Z]*[oO]\\b`, "i"),
|
|
3302
|
+
/\btar\s+[^\n|]*x[^\n|]*f/,
|
|
3303
|
+
/\bunzip\b/,
|
|
3304
|
+
/\bdd\b[^\n|]*\bof=/
|
|
3305
|
+
];
|
|
3306
|
+
/**
|
|
3307
|
+
* True when the command reclaims or inspects space — these are always allowed,
|
|
3308
|
+
* even on a 100%-full box, so the agent can dig itself out.
|
|
3309
|
+
*/
|
|
3310
|
+
function isReclaimCommand(command) {
|
|
3311
|
+
return RECLAIM_PATTERNS.some((re) => re.test(command));
|
|
3312
|
+
}
|
|
3313
|
+
/**
|
|
3314
|
+
* True when the command is likely to consume a meaningful amount of disk.
|
|
3315
|
+
* A reclaim/inspect command is never space-hungry — the reclaim check wins so a
|
|
3316
|
+
* `git worktree remove` or a `yarn cache clean` is never mistaken for growth.
|
|
3317
|
+
*/
|
|
3318
|
+
function isSpaceHungryCommand(command) {
|
|
3319
|
+
if (isReclaimCommand(command)) return false;
|
|
3320
|
+
return SPACE_HUNGRY_PATTERNS.some((re) => re.test(command));
|
|
3321
|
+
}
|
|
3322
|
+
/**
|
|
3323
|
+
* The decision, factored out and pure so it's exhaustively testable without a
|
|
3324
|
+
* real filesystem. Block only when we have a disk reading, it's at/above the
|
|
3325
|
+
* critical threshold, the command is space-hungry (and not a reclaim), and the
|
|
3326
|
+
* agent hasn't explicitly opted out with the bypass marker.
|
|
3327
|
+
*/
|
|
3328
|
+
function shouldBlockForDisk(command, diskPct) {
|
|
3329
|
+
if (diskPct === null) return false;
|
|
3330
|
+
if (diskPct < 95) return false;
|
|
3331
|
+
if (hasBypassMarker(command)) return false;
|
|
3332
|
+
return isSpaceHungryCommand(command);
|
|
3333
|
+
}
|
|
3334
|
+
/** The agent-facing explanation returned as the blocked tool result. */
|
|
3335
|
+
function diskBlockReason(command, diskPct) {
|
|
3336
|
+
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.`;
|
|
3337
|
+
}
|
|
3338
|
+
const diskGuardExtension = (pi) => {
|
|
3339
|
+
pi.on("tool_call", async (event) => {
|
|
3340
|
+
if (event.toolName !== "bash") return;
|
|
3341
|
+
if (guardDisabledByEnv()) return;
|
|
3342
|
+
const command = event.input.command;
|
|
3343
|
+
if (typeof command !== "string" || command.length === 0) return;
|
|
3344
|
+
if (hasBypassMarker(command)) return;
|
|
3345
|
+
if (!isSpaceHungryCommand(command)) return;
|
|
3346
|
+
const diskPct = await readDiskUsePct();
|
|
3347
|
+
if (!shouldBlockForDisk(command, diskPct)) return;
|
|
3348
|
+
log$8.warn({
|
|
3349
|
+
diskPct,
|
|
3350
|
+
command: command.slice(0, 200)
|
|
3351
|
+
}, "blocked space-hungry bash command on near-full disk");
|
|
3352
|
+
return {
|
|
3353
|
+
block: true,
|
|
3354
|
+
reason: diskBlockReason(command, diskPct)
|
|
3355
|
+
};
|
|
3356
|
+
});
|
|
3357
|
+
};
|
|
3358
|
+
//#endregion
|
|
2025
3359
|
//#region src/extensions/context-management-trim.ts
|
|
2026
3360
|
const CLEARED_PLACEHOLDER = "[old tool result cleared to save context — re-run the tool or re-read the source to recover it]";
|
|
2027
3361
|
/** Rough token estimate (~4 chars/token); good enough for trigger decisions. */
|
|
@@ -2113,7 +3447,7 @@ function transformContextMessages(messages, config, now) {
|
|
|
2113
3447
|
}
|
|
2114
3448
|
//#endregion
|
|
2115
3449
|
//#region src/extensions/context-management.ts
|
|
2116
|
-
const log$
|
|
3450
|
+
const log$7 = logger.child({ module: "context-management-extension" });
|
|
2117
3451
|
function isAnthropicMessagesPayload(payload) {
|
|
2118
3452
|
if (typeof payload !== "object" || payload === null) return false;
|
|
2119
3453
|
const candidate = payload;
|
|
@@ -2178,13 +3512,13 @@ function createContextManagementExtension() {
|
|
|
2178
3512
|
setContextManagementFlagOverride(getPolledFlag("contextManagement"));
|
|
2179
3513
|
onFlagChange("contextManagement", (enabled) => {
|
|
2180
3514
|
setContextManagementFlagOverride(enabled);
|
|
2181
|
-
log$
|
|
3515
|
+
log$7.info({
|
|
2182
3516
|
event: "context_management_flag_update",
|
|
2183
3517
|
enabled
|
|
2184
3518
|
}, "context-management flag updated from platform");
|
|
2185
3519
|
});
|
|
2186
3520
|
startFeatureFlagPoller();
|
|
2187
|
-
log$
|
|
3521
|
+
log$7.info({
|
|
2188
3522
|
event: "context_management_registered",
|
|
2189
3523
|
enabled: initial.enabled,
|
|
2190
3524
|
flagSource: hasFlagSource(),
|
|
@@ -2196,13 +3530,13 @@ function createContextManagementExtension() {
|
|
|
2196
3530
|
const { messages } = event;
|
|
2197
3531
|
try {
|
|
2198
3532
|
const result = transformContextIfEnabled(messages, getContextManagementConfig(), Date.now());
|
|
2199
|
-
if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$
|
|
3533
|
+
if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$7.info({
|
|
2200
3534
|
event: "context_management_applied",
|
|
2201
3535
|
...result.stats
|
|
2202
3536
|
}, "trimmed/cleared tool output before LLM call");
|
|
2203
3537
|
return { messages: result.messages };
|
|
2204
3538
|
} catch (err) {
|
|
2205
|
-
log$
|
|
3539
|
+
log$7.error({
|
|
2206
3540
|
err,
|
|
2207
3541
|
event: "context_management_transform_failed"
|
|
2208
3542
|
}, "context transform failed; passing messages through unchanged");
|
|
@@ -2214,7 +3548,7 @@ function createContextManagementExtension() {
|
|
|
2214
3548
|
}
|
|
2215
3549
|
//#endregion
|
|
2216
3550
|
//#region src/extensions/current-time.ts
|
|
2217
|
-
const log$
|
|
3551
|
+
const log$6 = logger.child({ module: "current-time-extension" });
|
|
2218
3552
|
const PI_DATE_LINE = /^Current date:.*$/m;
|
|
2219
3553
|
function formatCurrentTimeLine(now) {
|
|
2220
3554
|
return `Current date: ${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")} (${new Intl.DateTimeFormat("en-US", {
|
|
@@ -2227,7 +3561,7 @@ const currentTimeExtension = (pi) => {
|
|
|
2227
3561
|
const line = formatCurrentTimeLine(/* @__PURE__ */ new Date());
|
|
2228
3562
|
const base = event.systemPrompt;
|
|
2229
3563
|
if (PI_DATE_LINE.test(base)) {
|
|
2230
|
-
log$
|
|
3564
|
+
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)");
|
|
2231
3565
|
return { systemPrompt: base.replace(PI_DATE_LINE, line) };
|
|
2232
3566
|
}
|
|
2233
3567
|
return { systemPrompt: `${base}\n${line}` };
|
|
@@ -2236,37 +3570,35 @@ const currentTimeExtension = (pi) => {
|
|
|
2236
3570
|
//#endregion
|
|
2237
3571
|
//#region src/memory.ts
|
|
2238
3572
|
/**
|
|
2239
|
-
* In-harness memory
|
|
2240
|
-
*
|
|
2241
|
-
* The agent has an agent-level file-based memory at `<cwd>/.memory/`,
|
|
2242
|
-
* organized by directory:
|
|
3573
|
+
* In-harness memory readers.
|
|
2243
3574
|
*
|
|
2244
|
-
*
|
|
2245
|
-
*
|
|
2246
|
-
* .memory/feedback/<topic>.md
|
|
2247
|
-
* .memory/reference/<topic>.md
|
|
3575
|
+
* The agent has an agent-level file-based memory at `<cwd>/.memory/`, split
|
|
3576
|
+
* into two halves that are surfaced differently:
|
|
2248
3577
|
*
|
|
2249
|
-
*
|
|
2250
|
-
*
|
|
2251
|
-
*
|
|
3578
|
+
* 1. Shared knowledge (projects, lessons, external systems) — indexed by a
|
|
3579
|
+
* single hand-maintained `<cwd>/.memory/MEMORY.md` that the *agent* writes
|
|
3580
|
+
* and curates, Claude-Code style: one line per fact pointing at the file
|
|
3581
|
+
* that holds it. `readMemoryIndexFile` just reads that file; the agent owns
|
|
3582
|
+
* its contents. This is the whole index for the shared half — there is no
|
|
3583
|
+
* derived walk and no per-directory `MEMORY.md`.
|
|
2252
3584
|
*
|
|
2253
|
-
*
|
|
2254
|
-
*
|
|
2255
|
-
*
|
|
2256
|
-
*
|
|
2257
|
-
*
|
|
2258
|
-
*
|
|
2259
|
-
*
|
|
3585
|
+
* 2. Per-person memory — `.memory/users/<id>-<name>/<topic>.md`. This half is
|
|
3586
|
+
* *derived*, not hand-maintained, because it has to be filtered to the one
|
|
3587
|
+
* person on the current turn (a single hand-written index couldn't be
|
|
3588
|
+
* scoped per-user without leaking one person's notes into another's
|
|
3589
|
+
* conversation). `buildMemoryIndex` walks a single user's directory, reads
|
|
3590
|
+
* only the frontmatter of each `.md` (open fd → read first ~4KB → close, in
|
|
3591
|
+
* parallel), and renders an index. Each `.md`'s frontmatter carries `name`
|
|
3592
|
+
* and `description`; bodies are never read — the agent loads a specific
|
|
3593
|
+
* memory's body on demand via the `read` tool.
|
|
2260
3594
|
*
|
|
2261
|
-
* Mtime cache keyed by cwd — within the
|
|
2262
|
-
* is fixed, so this is effectively a single-entry
|
|
2263
|
-
* when any `.md`
|
|
2264
|
-
* memory didn't change reuse the cached
|
|
3595
|
+
* Mtime cache (for the derived per-user half) keyed by cwd — within the
|
|
3596
|
+
* lifetime of a sandbox the cwd is fixed, so this is effectively a single-entry
|
|
3597
|
+
* cache. It invalidates when any `.md` under `users/` is added/modified/
|
|
3598
|
+
* deleted; turns where memory didn't change reuse the cached entries.
|
|
2265
3599
|
*
|
|
2266
|
-
* Frontmatter is parsed as YAML (`yaml` package) and validated with a
|
|
2267
|
-
*
|
|
2268
|
-
* index. The same schema can be reused at write time if we want to
|
|
2269
|
-
* validate before commit.
|
|
3600
|
+
* Frontmatter is parsed as YAML (`yaml` package) and validated with a zod
|
|
3601
|
+
* schema — files that don't match the shape are dropped from the index.
|
|
2270
3602
|
*/
|
|
2271
3603
|
const FRONTMATTER_READ_BYTES = 4096;
|
|
2272
3604
|
const FrontmatterSchema = z.object({
|
|
@@ -2274,33 +3606,118 @@ const FrontmatterSchema = z.object({
|
|
|
2274
3606
|
description: z.string().min(1)
|
|
2275
3607
|
}).passthrough();
|
|
2276
3608
|
const MEMORY_DIRNAME = ".memory";
|
|
2277
|
-
const
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
3609
|
+
const MEMORY_INDEX_FILENAME = "MEMORY.md";
|
|
3610
|
+
const USERS_DIRNAME = "users";
|
|
3611
|
+
/**
|
|
3612
|
+
* The shared-knowledge type dirs from the old frontmatter-indexed layout, used
|
|
3613
|
+
* only to seed a `MEMORY.md` for agents created before it existed (see
|
|
3614
|
+
* `seedMemoryIndexFile`). `users/` is deliberately excluded — per-person memory
|
|
3615
|
+
* stays derived and never lands in the shared, un-scoped `MEMORY.md`.
|
|
3616
|
+
*/
|
|
3617
|
+
const LEGACY_SHARED_TYPES = [
|
|
3618
|
+
{
|
|
3619
|
+
dir: "projects",
|
|
3620
|
+
label: "Projects"
|
|
3621
|
+
},
|
|
3622
|
+
{
|
|
3623
|
+
dir: "feedback",
|
|
3624
|
+
label: "Feedback"
|
|
3625
|
+
},
|
|
3626
|
+
{
|
|
3627
|
+
dir: "reference",
|
|
3628
|
+
label: "Reference"
|
|
3629
|
+
}
|
|
2282
3630
|
];
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
3631
|
+
/**
|
|
3632
|
+
* Soft budget for an injected index block. The index is read and injected into
|
|
3633
|
+
* the system prompt on every turn, so every entry costs context for the rest of
|
|
3634
|
+
* the conversation. Past this size we nudge the agent to consolidate and prune
|
|
3635
|
+
* rather than keep appending. Not a hard cap — nothing is truncated.
|
|
3636
|
+
*/
|
|
3637
|
+
const MEMORY_INDEX_SOFT_BUDGET_CHARS = 2e4;
|
|
3638
|
+
/**
|
|
3639
|
+
* Hard cap on the injected index — double the soft budget. The soft budget only
|
|
3640
|
+
* warns; this actually bounds what we inject so a runaway index can't consume
|
|
3641
|
+
* unbounded context on every turn. Past this, the index is truncated (on a line
|
|
3642
|
+
* boundary) before injection. It's a backstop, not a normal operating point.
|
|
3643
|
+
*/
|
|
3644
|
+
const MEMORY_INDEX_HARD_BUDGET_CHARS = MEMORY_INDEX_SOFT_BUDGET_CHARS * 2;
|
|
3645
|
+
/**
|
|
3646
|
+
* Cheap size summary of a rendered index block, used to surface how much of the
|
|
3647
|
+
* every-turn context budget the index is spending so the agent keeps it lean.
|
|
3648
|
+
* Counts pointer/file lines — both the derived `` - `path` — desc`` form and
|
|
3649
|
+
* the hand-maintained `- [Title](path) — hook` form — not the group headers.
|
|
3650
|
+
*/
|
|
3651
|
+
function summarizeIndex(index) {
|
|
3652
|
+
const entryCount = index.split("\n").filter((line) => /^\s*- (?:`|\[)/.test(line)).length;
|
|
3653
|
+
const charCount = index.length;
|
|
3654
|
+
return {
|
|
3655
|
+
entryCount,
|
|
3656
|
+
charCount,
|
|
3657
|
+
overBudget: charCount > MEMORY_INDEX_SOFT_BUDGET_CHARS
|
|
3658
|
+
};
|
|
3659
|
+
}
|
|
3660
|
+
/**
|
|
3661
|
+
* One-line size note for an index block header, e.g. `12 entries, 3187 chars`.
|
|
3662
|
+
*/
|
|
3663
|
+
function indexSizeNote(index) {
|
|
3664
|
+
const { entryCount, charCount } = summarizeIndex(index);
|
|
3665
|
+
return `${entryCount} ${entryCount === 1 ? "entry" : "entries"}, ${charCount} chars`;
|
|
3666
|
+
}
|
|
3667
|
+
/**
|
|
3668
|
+
* An explicit warning to surface to the agent when an index has grown past its
|
|
3669
|
+
* budget, or `null` when it's within budget. Extensions render this prominently
|
|
3670
|
+
* above the index so the agent prunes before it keeps appending.
|
|
3671
|
+
*/
|
|
3672
|
+
function indexBudgetWarning(index) {
|
|
3673
|
+
const { charCount, overBudget } = summarizeIndex(index);
|
|
3674
|
+
if (!overBudget) return null;
|
|
3675
|
+
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.`;
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* Enforce the hard cap on an index before injection. Under the cap the index is
|
|
3679
|
+
* returned unchanged; over it, the index is truncated on a line boundary and a
|
|
3680
|
+
* notice is appended naming the true size so the agent knows entries are hidden
|
|
3681
|
+
* and must be pruned. This is the actual bound on injected context — callers
|
|
3682
|
+
* still report the true size via {@link indexSizeNote} so nothing is masked.
|
|
3683
|
+
*/
|
|
3684
|
+
function enforceMemoryIndexHardBudget(index) {
|
|
3685
|
+
if (index.length <= 4e4) return index;
|
|
3686
|
+
const clipped = index.slice(0, MEMORY_INDEX_HARD_BUDGET_CHARS);
|
|
3687
|
+
const lastNewline = clipped.lastIndexOf("\n");
|
|
3688
|
+
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.`;
|
|
3689
|
+
}
|
|
3690
|
+
/**
|
|
3691
|
+
* Read the agent's hand-maintained shared index at `.memory/MEMORY.md`.
|
|
3692
|
+
* Returns the trimmed contents, or `null` when the file is absent or empty —
|
|
3693
|
+
* the agent owns this file, so we surface exactly what it wrote.
|
|
3694
|
+
*/
|
|
3695
|
+
async function readMemoryIndexFile({ cwd }) {
|
|
3696
|
+
const path = join(cwd, MEMORY_DIRNAME, MEMORY_INDEX_FILENAME);
|
|
3697
|
+
try {
|
|
3698
|
+
const trimmed = (await readFile(path, "utf-8")).trim();
|
|
3699
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
3700
|
+
} catch {
|
|
3701
|
+
return null;
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
2290
3704
|
const cache = /* @__PURE__ */ new Map();
|
|
2291
3705
|
/**
|
|
3706
|
+
* Build the derived per-person index for a single user.
|
|
3707
|
+
*
|
|
2292
3708
|
* Returns:
|
|
2293
|
-
* - `null` if `.memory/` doesn't exist
|
|
2294
|
-
* - `""` if
|
|
3709
|
+
* - `null` if `.memory/users/` doesn't exist
|
|
3710
|
+
* - `""` if it exists but this user has no memory
|
|
2295
3711
|
* - rendered markdown body (no surrounding header — caller wraps)
|
|
2296
3712
|
*
|
|
2297
|
-
*
|
|
2298
|
-
*
|
|
2299
|
-
*
|
|
3713
|
+
* Scoping by id keeps one person's memory from bleeding into another's
|
|
3714
|
+
* conversation. The mtime-keyed cache stores the raw walked entries (the cost
|
|
3715
|
+
* is the FS walk); filtering by user is cheap and runs per call, so two turns
|
|
3716
|
+
* with different users on the same cwd render correctly from one cached walk.
|
|
2300
3717
|
*/
|
|
2301
|
-
async function buildMemoryIndex({ cwd,
|
|
2302
|
-
const
|
|
2303
|
-
const maxMtimeMs = await maxMtimeAcrossDir(
|
|
3718
|
+
async function buildMemoryIndex({ cwd, userId }) {
|
|
3719
|
+
const usersDirAbs = join(cwd, MEMORY_DIRNAME, USERS_DIRNAME);
|
|
3720
|
+
const maxMtimeMs = await maxMtimeAcrossDir(usersDirAbs);
|
|
2304
3721
|
if (maxMtimeMs === null) {
|
|
2305
3722
|
cache.delete(cwd);
|
|
2306
3723
|
return null;
|
|
@@ -2308,13 +3725,13 @@ async function buildMemoryIndex({ cwd, scope }) {
|
|
|
2308
3725
|
let cached = cache.get(cwd);
|
|
2309
3726
|
if (!cached || cached.builtAtMs < maxMtimeMs) {
|
|
2310
3727
|
cached = {
|
|
2311
|
-
entries: await
|
|
3728
|
+
entries: await collectUserEntries(usersDirAbs, cwd),
|
|
2312
3729
|
builtAtMs: Date.now()
|
|
2313
3730
|
};
|
|
2314
3731
|
cache.set(cwd, cached);
|
|
2315
3732
|
}
|
|
2316
|
-
const visible = cached.entries.filter((entry) =>
|
|
2317
|
-
return visible.length === 0 ? "" :
|
|
3733
|
+
const visible = cached.entries.filter((entry) => entry.subject.startsWith(userId));
|
|
3734
|
+
return visible.length === 0 ? "" : renderUserIndex(visible);
|
|
2318
3735
|
}
|
|
2319
3736
|
async function maxMtimeAcrossDir(dir) {
|
|
2320
3737
|
let dirStat;
|
|
@@ -2362,45 +3779,22 @@ async function listSubdirs(dir) {
|
|
|
2362
3779
|
}
|
|
2363
3780
|
return entries.filter((e) => e.isDirectory()).map((e) => join(dir, e.name));
|
|
2364
3781
|
}
|
|
2365
|
-
async function
|
|
2366
|
-
const
|
|
2367
|
-
await Promise.all(
|
|
2368
|
-
const
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
await
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
subject,
|
|
2382
|
-
relPath: relative(cwd, file)
|
|
2383
|
-
};
|
|
2384
|
-
}));
|
|
2385
|
-
for (const e of parsed) if (e) collected.push(e);
|
|
2386
|
-
}));
|
|
2387
|
-
} else {
|
|
2388
|
-
const files = await listMdFilesShallow(typeDirAbs);
|
|
2389
|
-
const parsed = await Promise.all(files.map(async (file) => {
|
|
2390
|
-
const fm = await readFrontmatterOnly(file);
|
|
2391
|
-
if (!fm?.name || !fm?.description) return null;
|
|
2392
|
-
return {
|
|
2393
|
-
name: fm.name,
|
|
2394
|
-
description: fm.description,
|
|
2395
|
-
type,
|
|
2396
|
-
subject: null,
|
|
2397
|
-
relPath: relative(cwd, file)
|
|
2398
|
-
};
|
|
2399
|
-
}));
|
|
2400
|
-
for (const e of parsed) if (e) collected.push(e);
|
|
2401
|
-
}
|
|
2402
|
-
}));
|
|
2403
|
-
return collected;
|
|
3782
|
+
async function collectUserEntries(usersDirAbs, cwd) {
|
|
3783
|
+
const subjectDirs = await listSubdirs(usersDirAbs);
|
|
3784
|
+
return (await Promise.all(subjectDirs.map(async (subjectDirAbs) => {
|
|
3785
|
+
const subject = basename(subjectDirAbs);
|
|
3786
|
+
const files = await listMdFilesShallow(subjectDirAbs);
|
|
3787
|
+
return (await Promise.all(files.map(async (file) => {
|
|
3788
|
+
const fm = await readFrontmatterOnly(file);
|
|
3789
|
+
if (!fm?.name || !fm?.description) return null;
|
|
3790
|
+
return {
|
|
3791
|
+
name: fm.name,
|
|
3792
|
+
description: fm.description,
|
|
3793
|
+
subject,
|
|
3794
|
+
relPath: relative(cwd, file)
|
|
3795
|
+
};
|
|
3796
|
+
}))).filter((e) => e !== null);
|
|
3797
|
+
}))).flat();
|
|
2404
3798
|
}
|
|
2405
3799
|
async function readFrontmatterOnly(filePath) {
|
|
2406
3800
|
let fh;
|
|
@@ -2431,77 +3825,189 @@ function parseFrontmatter(text) {
|
|
|
2431
3825
|
const result = FrontmatterSchema.safeParse(parsed);
|
|
2432
3826
|
return result.success ? result.data : null;
|
|
2433
3827
|
}
|
|
2434
|
-
function
|
|
2435
|
-
const
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
}
|
|
2441
|
-
|
|
3828
|
+
function renderUserIndex(entries) {
|
|
3829
|
+
const bySubject = /* @__PURE__ */ new Map();
|
|
3830
|
+
for (const e of entries) {
|
|
3831
|
+
const list = bySubject.get(e.subject) ?? [];
|
|
3832
|
+
list.push(e);
|
|
3833
|
+
bySubject.set(e.subject, list);
|
|
3834
|
+
}
|
|
3835
|
+
const lines = ["### Users"];
|
|
3836
|
+
for (const subject of [...bySubject.keys()].sort()) {
|
|
3837
|
+
lines.push(`- **${subject}**`);
|
|
3838
|
+
for (const e of bySubject.get(subject) ?? []) lines.push(` - \`${e.relPath}\` — ${e.description}`);
|
|
3839
|
+
}
|
|
3840
|
+
return lines.join("\n");
|
|
3841
|
+
}
|
|
3842
|
+
/**
|
|
3843
|
+
* One-time migration for agents created before `MEMORY.md` existed. If there is
|
|
3844
|
+
* no hand-maintained `.memory/MEMORY.md` yet but the agent has shared memory
|
|
3845
|
+
* files from the old frontmatter-indexed layout (`projects/`, `feedback/`,
|
|
3846
|
+
* `reference/`), derive a `MEMORY.md` from their frontmatter and write it once.
|
|
3847
|
+
* After that the agent owns the file — this never runs again for that agent and
|
|
3848
|
+
* never clobbers an existing index.
|
|
3849
|
+
*
|
|
3850
|
+
* Returns the seeded contents (also written to disk), or `null` when nothing
|
|
3851
|
+
* was seeded (index already present, or no legacy shared files). A write
|
|
3852
|
+
* failure propagates so the caller can log it; the read path then falls back to
|
|
3853
|
+
* whatever is on disk.
|
|
3854
|
+
*/
|
|
3855
|
+
async function seedMemoryIndexFile({ cwd }) {
|
|
3856
|
+
const memoryDirAbs = join(cwd, MEMORY_DIRNAME);
|
|
3857
|
+
const indexPath = join(memoryDirAbs, MEMORY_INDEX_FILENAME);
|
|
3858
|
+
if (await stat(indexPath).catch(() => null)) return null;
|
|
3859
|
+
const perType = await Promise.all(LEGACY_SHARED_TYPES.map(async ({ dir, label }) => {
|
|
3860
|
+
const typeDirAbs = join(memoryDirAbs, dir);
|
|
3861
|
+
const files = [];
|
|
3862
|
+
await walkMdFiles(typeDirAbs, files);
|
|
3863
|
+
return {
|
|
3864
|
+
label,
|
|
3865
|
+
entries: (await Promise.all(files.map(async (file) => {
|
|
3866
|
+
const fm = await readFrontmatterOnly(file);
|
|
3867
|
+
if (!fm?.name || !fm?.description) return null;
|
|
3868
|
+
return {
|
|
3869
|
+
name: fm.name,
|
|
3870
|
+
description: fm.description,
|
|
3871
|
+
relPath: relative(cwd, file)
|
|
3872
|
+
};
|
|
3873
|
+
}))).filter((e) => !!e)
|
|
3874
|
+
};
|
|
3875
|
+
}));
|
|
3876
|
+
if (perType.every((group) => group.entries.length === 0)) return null;
|
|
3877
|
+
const content = renderSeededIndex(perType);
|
|
3878
|
+
await writeFile(indexPath, `${content}\n`, "utf-8");
|
|
3879
|
+
return content;
|
|
3880
|
+
}
|
|
3881
|
+
function renderSeededIndex(groups) {
|
|
2442
3882
|
const sections = [];
|
|
2443
|
-
for (const
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
const bySubject = /* @__PURE__ */ new Map();
|
|
2449
|
-
for (const e of items) {
|
|
2450
|
-
const subject = e.subject ?? "(unknown)";
|
|
2451
|
-
const list = bySubject.get(subject) ?? [];
|
|
2452
|
-
list.push(e);
|
|
2453
|
-
bySubject.set(subject, list);
|
|
2454
|
-
}
|
|
2455
|
-
const subjects = [...bySubject.keys()].sort();
|
|
2456
|
-
for (const subject of subjects) {
|
|
2457
|
-
sections.push(`- **${subject}**`);
|
|
2458
|
-
for (const e of bySubject.get(subject) ?? []) sections.push(` - \`${e.relPath}\` — ${e.description}`);
|
|
2459
|
-
}
|
|
2460
|
-
} else for (const e of items) sections.push(`- \`${e.relPath}\` — ${e.description}`);
|
|
3883
|
+
for (const { label, entries } of groups) {
|
|
3884
|
+
if (entries.length === 0) continue;
|
|
3885
|
+
sections.push(`### ${label}`);
|
|
3886
|
+
const sorted = [...entries].sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
3887
|
+
for (const e of sorted) sections.push(`- [${e.name}](${e.relPath}) — ${e.description}`);
|
|
2461
3888
|
sections.push("");
|
|
2462
3889
|
}
|
|
2463
3890
|
return sections.join("\n").trimEnd();
|
|
2464
3891
|
}
|
|
3892
|
+
/**
|
|
3893
|
+
* The version at which the hand-maintained `MEMORY.md` layout was introduced.
|
|
3894
|
+
* Used to classify an unversioned `.memory/`: if it already has a `MEMORY.md`
|
|
3895
|
+
* it's on this layout (not the pre-MEMORY.md v1 frontmatter layout), so it
|
|
3896
|
+
* shouldn't be treated as v1 and re-seeded.
|
|
3897
|
+
*/
|
|
3898
|
+
const HAND_MAINTAINED_INDEX_VERSION = 2;
|
|
3899
|
+
const VERSION_FILENAME = ".version";
|
|
3900
|
+
const MEMORY_MIGRATIONS = [{
|
|
3901
|
+
from: 1,
|
|
3902
|
+
to: 2,
|
|
3903
|
+
apply: async ({ cwd }) => {
|
|
3904
|
+
await seedMemoryIndexFile({ cwd });
|
|
3905
|
+
}
|
|
3906
|
+
}];
|
|
3907
|
+
/**
|
|
3908
|
+
* The layout version of an agent's `.memory/`:
|
|
3909
|
+
* - `null` when there's no `.memory/` at all (a fresh agent is current by
|
|
3910
|
+
* construction; nothing to migrate).
|
|
3911
|
+
* - `1` when `.memory/` exists but carries no `.version` marker — i.e. it
|
|
3912
|
+
* predates versioning.
|
|
3913
|
+
* - otherwise the integer in `.memory/.version`.
|
|
3914
|
+
*/
|
|
3915
|
+
async function readMemoryVersion(cwd) {
|
|
3916
|
+
const memoryDirAbs = join(cwd, MEMORY_DIRNAME);
|
|
3917
|
+
if (!(await stat(memoryDirAbs).catch(() => null))?.isDirectory()) return null;
|
|
3918
|
+
const raw = await readFile(join(memoryDirAbs, VERSION_FILENAME), "utf-8").catch(() => null);
|
|
3919
|
+
if (raw === null) return await stat(join(memoryDirAbs, MEMORY_INDEX_FILENAME)).then((s) => s.isFile()).catch(() => false) ? HAND_MAINTAINED_INDEX_VERSION : 1;
|
|
3920
|
+
const parsed = Number.parseInt(raw.trim(), 10);
|
|
3921
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : 1;
|
|
3922
|
+
}
|
|
3923
|
+
async function writeMemoryVersion(cwd, version) {
|
|
3924
|
+
await writeFile(join(cwd, MEMORY_DIRNAME, VERSION_FILENAME), `${version}\n`, "utf-8");
|
|
3925
|
+
}
|
|
3926
|
+
/**
|
|
3927
|
+
* Bring an agent's `.memory/` up to `CURRENT_MEMORY_VERSION` by applying the
|
|
3928
|
+
* ordered migrations. Runs on session start. No-op when there's no `.memory/`
|
|
3929
|
+
* yet or it's already current. Migrations must be idempotent, so a lost/unwritten
|
|
3930
|
+
* version marker (the file isn't committed by the harness) only costs a repeated
|
|
3931
|
+
* no-op, never corruption. Returns the `{ from, to }` actually applied, or
|
|
3932
|
+
* `null` when nothing ran.
|
|
3933
|
+
*/
|
|
3934
|
+
async function migrateMemory({ cwd }) {
|
|
3935
|
+
const from = await readMemoryVersion(cwd);
|
|
3936
|
+
if (from === null || from >= 2) return null;
|
|
3937
|
+
let version = from;
|
|
3938
|
+
while (version < 2) {
|
|
3939
|
+
const migration = MEMORY_MIGRATIONS.find((m) => m.from === version);
|
|
3940
|
+
if (!migration) break;
|
|
3941
|
+
await migration.apply({ cwd });
|
|
3942
|
+
version = migration.to;
|
|
3943
|
+
}
|
|
3944
|
+
await writeMemoryVersion(cwd, version);
|
|
3945
|
+
return {
|
|
3946
|
+
from,
|
|
3947
|
+
to: version
|
|
3948
|
+
};
|
|
3949
|
+
}
|
|
2465
3950
|
//#endregion
|
|
2466
3951
|
//#region src/extensions/memory.ts
|
|
2467
|
-
const log$
|
|
3952
|
+
const log$5 = logger.child({ module: "memory-extension" });
|
|
2468
3953
|
/**
|
|
2469
3954
|
* The standing instructions for the memory system. Always injected (even with
|
|
2470
|
-
*
|
|
3955
|
+
* no `MEMORY.md`) so the agent knows it can persist notes and how. `users/` is
|
|
2471
3956
|
* described by the platform memory extension, which is the only thing that can
|
|
2472
3957
|
* scope it to a person — here we just point at it.
|
|
2473
3958
|
*/
|
|
2474
3959
|
function memoryInstructions(cwd) {
|
|
2475
3960
|
return `## Memory across conversations
|
|
2476
3961
|
|
|
2477
|
-
Persistent notes across conversations live at \`${cwd}/.memory/\` — plain markdown files in your repo
|
|
3962
|
+
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.
|
|
2478
3963
|
|
|
2479
3964
|
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.
|
|
2480
3965
|
|
|
2481
|
-
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
|
|
3966
|
+
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\`.)
|
|
3967
|
+
|
|
3968
|
+
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:
|
|
3969
|
+
- 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.
|
|
3970
|
+
- 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.
|
|
3971
|
+
- 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.
|
|
3972
|
+
- 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.
|
|
3973
|
+
|
|
3974
|
+
Commit and push after editing \`.memory/\` to persist it.`;
|
|
2482
3975
|
}
|
|
2483
3976
|
function composeBlock$1({ cwd, index }) {
|
|
2484
3977
|
const instructions = memoryInstructions(cwd);
|
|
2485
3978
|
if (!index || index.length === 0) return instructions;
|
|
2486
|
-
|
|
3979
|
+
const header = `## Memory index (${indexSizeNote(index)})`;
|
|
3980
|
+
const warning = indexBudgetWarning(index);
|
|
3981
|
+
const rendered = enforceMemoryIndexHardBudget(index);
|
|
3982
|
+
return `${instructions}\n\n${warning ? `${header}\n\n${warning}\n\n${rendered}` : `${header}\n\n${rendered}`}`;
|
|
2487
3983
|
}
|
|
2488
3984
|
const memoryExtension = (pi) => {
|
|
2489
3985
|
let cachedBlock = null;
|
|
2490
3986
|
pi.on("session_start", async (_event, ctx) => {
|
|
2491
3987
|
try {
|
|
2492
|
-
const
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
3988
|
+
const migrated = await migrateMemory({ cwd: ctx.cwd });
|
|
3989
|
+
if (migrated !== null) log$5.info({
|
|
3990
|
+
event: "memory_migrated",
|
|
3991
|
+
from: migrated.from,
|
|
3992
|
+
to: migrated.to
|
|
3993
|
+
}, "migrated memory layout to current version");
|
|
3994
|
+
} catch (err) {
|
|
3995
|
+
log$5.warn({
|
|
3996
|
+
err,
|
|
3997
|
+
event: "memory_migration_failed"
|
|
3998
|
+
}, "memory migration failed; continuing with existing index");
|
|
3999
|
+
}
|
|
4000
|
+
try {
|
|
4001
|
+
const index = await readMemoryIndexFile({ cwd: ctx.cwd });
|
|
2496
4002
|
cachedBlock = composeBlock$1({
|
|
2497
4003
|
cwd: ctx.cwd,
|
|
2498
4004
|
index
|
|
2499
4005
|
});
|
|
2500
4006
|
} catch (err) {
|
|
2501
|
-
log$
|
|
4007
|
+
log$5.warn({
|
|
2502
4008
|
err,
|
|
2503
4009
|
event: "memory_index_failed"
|
|
2504
|
-
}, "memory index
|
|
4010
|
+
}, "memory index read failed; injecting instructions only");
|
|
2505
4011
|
cachedBlock = memoryInstructions(ctx.cwd);
|
|
2506
4012
|
}
|
|
2507
4013
|
});
|
|
@@ -2512,7 +4018,7 @@ const memoryExtension = (pi) => {
|
|
|
2512
4018
|
};
|
|
2513
4019
|
//#endregion
|
|
2514
4020
|
//#region src/extensions/platform-memory.ts
|
|
2515
|
-
const log$
|
|
4021
|
+
const log$4 = logger.child({ module: "platform-memory-extension" });
|
|
2516
4022
|
/**
|
|
2517
4023
|
* Resolve the human on this turn via the API, keyed by the message id.
|
|
2518
4024
|
* `/sandbox/channel-context` only returns a sender for a platform-known
|
|
@@ -2525,13 +4031,13 @@ const log$5 = logger.child({ module: "platform-memory-extension" });
|
|
|
2525
4031
|
async function resolveTurnUser(messageId) {
|
|
2526
4032
|
const client = sandboxClient();
|
|
2527
4033
|
if (!client) {
|
|
2528
|
-
log$
|
|
4034
|
+
log$4.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
|
|
2529
4035
|
return null;
|
|
2530
4036
|
}
|
|
2531
4037
|
try {
|
|
2532
4038
|
const res = await client["channel-context"].$get({ query: { messageId } });
|
|
2533
4039
|
if (!res.ok) {
|
|
2534
|
-
log$
|
|
4040
|
+
log$4.warn({
|
|
2535
4041
|
event: "resolve_turn_user_failed",
|
|
2536
4042
|
status: res.status
|
|
2537
4043
|
}, "channel-context returned non-ok; withholding user memory");
|
|
@@ -2544,7 +4050,7 @@ async function resolveTurnUser(messageId) {
|
|
|
2544
4050
|
displayName: sender.displayName
|
|
2545
4051
|
};
|
|
2546
4052
|
} catch (err) {
|
|
2547
|
-
log$
|
|
4053
|
+
log$4.warn({
|
|
2548
4054
|
err,
|
|
2549
4055
|
event: "resolve_turn_user_failed"
|
|
2550
4056
|
}, "failed to resolve current user; withholding user memory");
|
|
@@ -2560,9 +4066,12 @@ function slugifyName(name) {
|
|
|
2560
4066
|
function composeBlock({ index, user }) {
|
|
2561
4067
|
const instructions = `## Current user memory
|
|
2562
4068
|
|
|
2563
|
-
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.`;
|
|
4069
|
+
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.`;
|
|
2564
4070
|
if (!index || index.length === 0) return instructions;
|
|
2565
|
-
|
|
4071
|
+
const warning = indexBudgetWarning(index);
|
|
4072
|
+
const header = `Memory index (${indexSizeNote(index)}):`;
|
|
4073
|
+
const rendered = enforceMemoryIndexHardBudget(index);
|
|
4074
|
+
return `${instructions}\n\n${warning ? `${warning}\n\n${header}\n\n${rendered}` : `${header}\n\n${rendered}`}`;
|
|
2566
4075
|
}
|
|
2567
4076
|
/**
|
|
2568
4077
|
* Build the platform memory extension. `channelContext` is the per-turn ref
|
|
@@ -2583,15 +4092,12 @@ function createPlatformMemoryExtension({ channelContext }) {
|
|
|
2583
4092
|
cachedBlock = composeBlock({
|
|
2584
4093
|
index: await buildMemoryIndex({
|
|
2585
4094
|
cwd: ctx.cwd,
|
|
2586
|
-
|
|
2587
|
-
kind: "user",
|
|
2588
|
-
userId: user.id
|
|
2589
|
-
}
|
|
4095
|
+
userId: user.id
|
|
2590
4096
|
}),
|
|
2591
4097
|
user
|
|
2592
4098
|
});
|
|
2593
4099
|
} catch (err) {
|
|
2594
|
-
log$
|
|
4100
|
+
log$4.warn({
|
|
2595
4101
|
err,
|
|
2596
4102
|
event: "user_memory_index_failed"
|
|
2597
4103
|
}, "user memory index build failed; skipping injection");
|
|
@@ -2606,7 +4112,7 @@ function createPlatformMemoryExtension({ channelContext }) {
|
|
|
2606
4112
|
}
|
|
2607
4113
|
//#endregion
|
|
2608
4114
|
//#region src/extensions/self-trace.ts
|
|
2609
|
-
const log$
|
|
4115
|
+
const log$3 = logger.child({ module: "self-trace-extension" });
|
|
2610
4116
|
/**
|
|
2611
4117
|
* Reports the agent's own execution as OpenTelemetry spans:
|
|
2612
4118
|
* agent.session → agent.run → agent.turn.N → tool.NAME, with token/cost
|
|
@@ -2631,7 +4137,7 @@ const selfTraceExtension = (pi) => {
|
|
|
2631
4137
|
sessionSpan = tracer.startSpan("agent.session", { attributes: { "agent.model": modelId } }, remoteCtx);
|
|
2632
4138
|
sessionCtx = trace.setSpan(remoteCtx, sessionSpan);
|
|
2633
4139
|
const sc = sessionSpan.spanContext();
|
|
2634
|
-
log$
|
|
4140
|
+
log$3.info({
|
|
2635
4141
|
event: "self_trace_session_start",
|
|
2636
4142
|
trace_id: sc.traceId,
|
|
2637
4143
|
span_id: sc.spanId,
|
|
@@ -2743,13 +4249,13 @@ const selfTraceExtension = (pi) => {
|
|
|
2743
4249
|
* Lives in the harness package — soul.md is content from the agent's
|
|
2744
4250
|
* own git repo, not from the platform — so its handling stays here.
|
|
2745
4251
|
*/
|
|
2746
|
-
const log$
|
|
4252
|
+
const log$2 = logger.child({ module: "soul-extension" });
|
|
2747
4253
|
async function readSoul(cwd) {
|
|
2748
4254
|
try {
|
|
2749
4255
|
return (await readFile(join(cwd, "soul.md"), "utf8")).trim() || null;
|
|
2750
4256
|
} catch (err) {
|
|
2751
4257
|
if (err?.code === "ENOENT") return null;
|
|
2752
|
-
log$
|
|
4258
|
+
log$2.warn({
|
|
2753
4259
|
err,
|
|
2754
4260
|
event: "soul_read_failed"
|
|
2755
4261
|
}, "soul.md read failed");
|
|
@@ -2781,8 +4287,7 @@ const soulExtension = (pi) => {
|
|
|
2781
4287
|
};
|
|
2782
4288
|
//#endregion
|
|
2783
4289
|
//#region src/extensions/subagent/index.ts
|
|
2784
|
-
const log$
|
|
2785
|
-
const COLD_START_FLAG_WAIT_MS = 750;
|
|
4290
|
+
const log$1 = logger.child({ module: "subagent-ext" });
|
|
2786
4291
|
const MAX_TASKS = 8;
|
|
2787
4292
|
const TaskItem = Type.Object({
|
|
2788
4293
|
task: Type.String({ description: "The task to delegate to a subagent run." }),
|
|
@@ -2791,8 +4296,14 @@ const TaskItem = Type.Object({
|
|
|
2791
4296
|
maxLength: 120
|
|
2792
4297
|
}),
|
|
2793
4298
|
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." })),
|
|
2794
|
-
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." }))
|
|
4299
|
+
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." })),
|
|
4300
|
+
timeoutMinutes: Type.Optional(Type.Integer({
|
|
4301
|
+
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.",
|
|
4302
|
+
minimum: 1,
|
|
4303
|
+
maximum: 360
|
|
4304
|
+
}))
|
|
2795
4305
|
});
|
|
4306
|
+
const DEFAULT_SUBAGENT_TIMEOUT_MS = 30 * 6e4;
|
|
2796
4307
|
const SubagentParams = Type.Object({ tasks: Type.Array(TaskItem, {
|
|
2797
4308
|
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.",
|
|
2798
4309
|
minItems: 1,
|
|
@@ -2807,7 +4318,9 @@ function buildTool(messageId) {
|
|
|
2807
4318
|
"Delegate one or more tasks to subagent runs — fresh isolated copies of yourself, each with its own context window, linked to this conversation.",
|
|
2808
4319
|
"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.",
|
|
2809
4320
|
"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.",
|
|
2810
|
-
"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."
|
|
4321
|
+
"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.",
|
|
4322
|
+
"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.",
|
|
4323
|
+
"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."
|
|
2811
4324
|
].join(" "),
|
|
2812
4325
|
promptSnippet: "subagent — delegate tasks to isolated subagent runs; each rewakes you with its result when done",
|
|
2813
4326
|
parameters: SubagentParams,
|
|
@@ -2825,28 +4338,39 @@ function buildTool(messageId) {
|
|
|
2825
4338
|
task: t.task,
|
|
2826
4339
|
title: t.title ?? null,
|
|
2827
4340
|
persona: t.persona ?? null,
|
|
2828
|
-
model: t.model ?? null
|
|
4341
|
+
model: t.model ?? null,
|
|
4342
|
+
timeoutMs: t.timeoutMinutes != null ? t.timeoutMinutes * 6e4 : DEFAULT_SUBAGENT_TIMEOUT_MS
|
|
2829
4343
|
}));
|
|
2830
4344
|
try {
|
|
2831
|
-
const
|
|
4345
|
+
const spawned = await postSubagentSpawn({
|
|
2832
4346
|
messageId,
|
|
2833
4347
|
tasks: spawnTasks
|
|
2834
4348
|
});
|
|
2835
|
-
|
|
4349
|
+
const { taskIds } = spawned;
|
|
4350
|
+
log$1.info({
|
|
2836
4351
|
event: "subagent_spawned",
|
|
2837
4352
|
count: taskIds.length
|
|
2838
4353
|
}, "subagent tasks queued");
|
|
2839
|
-
const
|
|
4354
|
+
const convByTask = new Map(spawned.tasks.map((t) => [t.taskId, t.conversationId]));
|
|
4355
|
+
const lines = taskIds.map((id, i) => {
|
|
4356
|
+
const label = spawnTasks[i]?.title ?? spawnTasks[i]?.task ?? "";
|
|
4357
|
+
const conv = convByTask.get(id);
|
|
4358
|
+
return conv ? `- conversation ${conv}: ${label} (taskId ${id})` : `- ${label} (taskId ${id}, conversation id unavailable — cannot peer this run)`;
|
|
4359
|
+
}).join("\n");
|
|
4360
|
+
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." : "";
|
|
2840
4361
|
return {
|
|
2841
4362
|
content: [{
|
|
2842
4363
|
type: "text",
|
|
2843
|
-
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}`
|
|
4364
|
+
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}`
|
|
2844
4365
|
}],
|
|
2845
|
-
details: {
|
|
4366
|
+
details: {
|
|
4367
|
+
taskIds,
|
|
4368
|
+
tasks: spawned.tasks
|
|
4369
|
+
}
|
|
2846
4370
|
};
|
|
2847
4371
|
} catch (err) {
|
|
2848
4372
|
const message = err instanceof Error ? err.message : String(err);
|
|
2849
|
-
log$
|
|
4373
|
+
log$1.warn({
|
|
2850
4374
|
err,
|
|
2851
4375
|
event: "subagent_spawn_failed"
|
|
2852
4376
|
}, "subagent spawn failed");
|
|
@@ -2863,29 +4387,24 @@ function buildTool(messageId) {
|
|
|
2863
4387
|
};
|
|
2864
4388
|
}
|
|
2865
4389
|
/**
|
|
2866
|
-
* Gated on `harness-subagent-enabled`, read from the shared feature-flag poll.
|
|
2867
4390
|
* The factory takes the session's channel context to resolve the originating
|
|
2868
4391
|
* messageId — the api links each spawned run to the conversation that message
|
|
2869
4392
|
* belongs to and rewakes it on completion (nothing about the parent is piped
|
|
2870
|
-
* from the sandbox beyond that id).
|
|
4393
|
+
* from the sandbox beyond that id). The tool is registered unconditionally at
|
|
4394
|
+
* session_start.
|
|
2871
4395
|
*/
|
|
2872
4396
|
function createSubagentExtension({ channelContext }) {
|
|
2873
4397
|
return (pi) => {
|
|
2874
4398
|
const messageId = extractMessageId(channelContext);
|
|
2875
|
-
startFeatureFlagPoller();
|
|
2876
4399
|
let registered = false;
|
|
2877
4400
|
const registerOnce = () => {
|
|
2878
4401
|
if (registered) return;
|
|
2879
4402
|
registered = true;
|
|
2880
4403
|
pi.registerTool(buildTool(messageId));
|
|
2881
|
-
log$
|
|
4404
|
+
log$1.info({ event: "subagent_enabled" }, "subagent tool registered");
|
|
2882
4405
|
};
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
});
|
|
2886
|
-
pi.on("session_start", async () => {
|
|
2887
|
-
if (getPolledFlag("subagent") === null) await Promise.race([awaitFirstFlagPoll(), new Promise((resolve) => setTimeout(resolve, COLD_START_FLAG_WAIT_MS).unref?.())]);
|
|
2888
|
-
if (getPolledFlag("subagent") === true) registerOnce();
|
|
4406
|
+
pi.on("session_start", () => {
|
|
4407
|
+
registerOnce();
|
|
2889
4408
|
});
|
|
2890
4409
|
};
|
|
2891
4410
|
}
|
|
@@ -2916,214 +4435,6 @@ const toolCallEnvExtension = (pi) => {
|
|
|
2916
4435
|
});
|
|
2917
4436
|
};
|
|
2918
4437
|
//#endregion
|
|
2919
|
-
//#region src/extensions/tool-call-summary.ts
|
|
2920
|
-
const log$1 = logger.child({ module: "tool-call-summary-extension" });
|
|
2921
|
-
/**
|
|
2922
|
-
* The injected parameter name: a namespaced sentinel, so it can never collide
|
|
2923
|
-
* with a real tool argument and is unmistakable in transcripts and logs. The
|
|
2924
|
-
* frontend renderer (ANY-2723) duplicates this literal — keep the two in sync.
|
|
2925
|
-
*/
|
|
2926
|
-
const TOOL_CALL_SUMMARY_FIELD = "__skydive_summary__";
|
|
2927
|
-
/** JSON Schema fragment for the injected parameter. */
|
|
2928
|
-
const SUMMARY_PROPERTY = {
|
|
2929
|
-
type: "string",
|
|
2930
|
-
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\"."
|
|
2931
|
-
};
|
|
2932
|
-
const jsonSchemaObjectSchema = z.object({
|
|
2933
|
-
type: z.unknown().optional(),
|
|
2934
|
-
properties: z.record(z.string(), z.unknown()).optional(),
|
|
2935
|
-
required: z.array(z.string()).optional(),
|
|
2936
|
-
additionalProperties: z.unknown().optional()
|
|
2937
|
-
}).passthrough();
|
|
2938
|
-
const toolEntrySchema = z.object({
|
|
2939
|
-
name: z.string().optional(),
|
|
2940
|
-
input_schema: jsonSchemaObjectSchema.optional(),
|
|
2941
|
-
parameters: jsonSchemaObjectSchema.optional(),
|
|
2942
|
-
function: z.object({
|
|
2943
|
-
name: z.string().optional(),
|
|
2944
|
-
parameters: jsonSchemaObjectSchema.optional()
|
|
2945
|
-
}).passthrough().optional()
|
|
2946
|
-
}).passthrough();
|
|
2947
|
-
const payloadWithToolsSchema = z.object({ tools: z.array(z.unknown()) }).passthrough();
|
|
2948
|
-
/**
|
|
2949
|
-
* Add the summary property to one JSON Schema object. Returns the augmented
|
|
2950
|
-
* copy, or `null` when the tool should be left untouched: a strict schema
|
|
2951
|
-
* (`additionalProperties: false`) whose validation would reject the extra
|
|
2952
|
-
* field, or one that already declares a `__skydive_summary__` property of its own.
|
|
2953
|
-
*/
|
|
2954
|
-
function augmentSchema(schema) {
|
|
2955
|
-
if (schema.additionalProperties === false) return null;
|
|
2956
|
-
const properties = schema.properties ?? {};
|
|
2957
|
-
if ("__skydive_summary__" in properties) return null;
|
|
2958
|
-
const required = schema.required ?? [];
|
|
2959
|
-
return {
|
|
2960
|
-
...schema,
|
|
2961
|
-
type: schema.type ?? "object",
|
|
2962
|
-
properties: {
|
|
2963
|
-
[TOOL_CALL_SUMMARY_FIELD]: SUMMARY_PROPERTY,
|
|
2964
|
-
...properties
|
|
2965
|
-
},
|
|
2966
|
-
required: required.includes("__skydive_summary__") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
|
|
2967
|
-
};
|
|
2968
|
-
}
|
|
2969
|
-
/**
|
|
2970
|
-
* Augment a single tool entry, dispatching on which provider shape it is.
|
|
2971
|
-
* Returns the (possibly rebuilt) entry and whether anything changed. Skipped
|
|
2972
|
-
* tools — wrong shape, strict, or name in `strictToolNames` — return unchanged.
|
|
2973
|
-
*/
|
|
2974
|
-
function augmentToolEntry(entry, strictToolNames) {
|
|
2975
|
-
const parsed = toolEntrySchema.safeParse(entry);
|
|
2976
|
-
if (!parsed.success) return {
|
|
2977
|
-
entry,
|
|
2978
|
-
changed: false
|
|
2979
|
-
};
|
|
2980
|
-
const tool = parsed.data;
|
|
2981
|
-
const name = tool.name ?? tool.function?.name ?? null;
|
|
2982
|
-
if (name !== null && strictToolNames.has(name)) return {
|
|
2983
|
-
entry,
|
|
2984
|
-
changed: false
|
|
2985
|
-
};
|
|
2986
|
-
if (tool.input_schema) {
|
|
2987
|
-
const augmented = augmentSchema(tool.input_schema);
|
|
2988
|
-
if (!augmented) return {
|
|
2989
|
-
entry,
|
|
2990
|
-
changed: false
|
|
2991
|
-
};
|
|
2992
|
-
return {
|
|
2993
|
-
entry: {
|
|
2994
|
-
...tool,
|
|
2995
|
-
input_schema: augmented
|
|
2996
|
-
},
|
|
2997
|
-
changed: true
|
|
2998
|
-
};
|
|
2999
|
-
}
|
|
3000
|
-
if (tool.parameters) {
|
|
3001
|
-
const augmented = augmentSchema(tool.parameters);
|
|
3002
|
-
if (!augmented) return {
|
|
3003
|
-
entry,
|
|
3004
|
-
changed: false
|
|
3005
|
-
};
|
|
3006
|
-
return {
|
|
3007
|
-
entry: {
|
|
3008
|
-
...tool,
|
|
3009
|
-
parameters: augmented
|
|
3010
|
-
},
|
|
3011
|
-
changed: true
|
|
3012
|
-
};
|
|
3013
|
-
}
|
|
3014
|
-
if (tool.function?.parameters) {
|
|
3015
|
-
const augmented = augmentSchema(tool.function.parameters);
|
|
3016
|
-
if (!augmented) return {
|
|
3017
|
-
entry,
|
|
3018
|
-
changed: false
|
|
3019
|
-
};
|
|
3020
|
-
return {
|
|
3021
|
-
entry: {
|
|
3022
|
-
...tool,
|
|
3023
|
-
function: {
|
|
3024
|
-
...tool.function,
|
|
3025
|
-
parameters: augmented
|
|
3026
|
-
}
|
|
3027
|
-
},
|
|
3028
|
-
changed: true
|
|
3029
|
-
};
|
|
3030
|
-
}
|
|
3031
|
-
return {
|
|
3032
|
-
entry,
|
|
3033
|
-
changed: false
|
|
3034
|
-
};
|
|
3035
|
-
}
|
|
3036
|
-
/**
|
|
3037
|
-
* Inject the summary field into every eligible tool in a provider payload.
|
|
3038
|
-
* Returns a new payload when at least one tool was augmented, or `undefined`
|
|
3039
|
-
* to signal "no change" (which keeps the original payload, per the
|
|
3040
|
-
* `before_provider_request` contract).
|
|
3041
|
-
*
|
|
3042
|
-
* @param payload The outgoing provider payload (shape varies by provider).
|
|
3043
|
-
* @param strictToolNames Names of tools whose registered schema is strict and
|
|
3044
|
-
* must be skipped to avoid validation errors.
|
|
3045
|
-
*/
|
|
3046
|
-
function injectToolCallSummary(payload, strictToolNames) {
|
|
3047
|
-
const parsed = payloadWithToolsSchema.safeParse(payload);
|
|
3048
|
-
if (!parsed.success || parsed.data.tools.length === 0) return void 0;
|
|
3049
|
-
let changed = false;
|
|
3050
|
-
const tools = parsed.data.tools.map((entry) => {
|
|
3051
|
-
const result = augmentToolEntry(entry, strictToolNames);
|
|
3052
|
-
if (result.changed) changed = true;
|
|
3053
|
-
return result.entry;
|
|
3054
|
-
});
|
|
3055
|
-
if (!changed) return void 0;
|
|
3056
|
-
return {
|
|
3057
|
-
...parsed.data,
|
|
3058
|
-
tools
|
|
3059
|
-
};
|
|
3060
|
-
}
|
|
3061
|
-
/**
|
|
3062
|
-
* Names of registered tools whose schema sets `additionalProperties: false`.
|
|
3063
|
-
* Pi validates the model's tool args against this registered schema, so the
|
|
3064
|
-
* injected field would make a strict tool's call fail validation — skip them.
|
|
3065
|
-
*/
|
|
3066
|
-
function getStrictToolNames(pi) {
|
|
3067
|
-
const names = /* @__PURE__ */ new Set();
|
|
3068
|
-
for (const tool of pi.getAllTools()) {
|
|
3069
|
-
const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
|
|
3070
|
-
if (parsed.success && parsed.data.additionalProperties === false) names.add(tool.name);
|
|
3071
|
-
}
|
|
3072
|
-
return names;
|
|
3073
|
-
}
|
|
3074
|
-
function toolDeclaresSummaryParam(pi, toolName) {
|
|
3075
|
-
const tool = pi.getAllTools().find((candidate) => candidate.name === toolName);
|
|
3076
|
-
if (!tool) return false;
|
|
3077
|
-
const parsed = jsonSchemaObjectSchema.safeParse(tool.parameters);
|
|
3078
|
-
return parsed.success && parsed.data.properties != null && "__skydive_summary__" in parsed.data.properties;
|
|
3079
|
-
}
|
|
3080
|
-
/**
|
|
3081
|
-
* Remove the injected summary from a tool's execution input. No-op when the
|
|
3082
|
-
* field is absent, or when the tool genuinely declares a `__skydive_summary__`
|
|
3083
|
-
* parameter of its own (which we never inject into, so its value is real).
|
|
3084
|
-
* Mutates `input` in place, matching the `tool_call` contract.
|
|
3085
|
-
*
|
|
3086
|
-
* Fails open: this runs on the critical path of tool execution, and the
|
|
3087
|
-
* `getAllTools()` lookup can throw. On any error we leave `input` untouched
|
|
3088
|
-
* (the sentinel may pass through to the tool, but a bug here can never break
|
|
3089
|
-
* tool execution).
|
|
3090
|
-
*/
|
|
3091
|
-
function stripInjectedSummary(pi, toolName, input) {
|
|
3092
|
-
try {
|
|
3093
|
-
if (!("__skydive_summary__" in input)) return;
|
|
3094
|
-
if (toolDeclaresSummaryParam(pi, toolName)) return;
|
|
3095
|
-
delete input[TOOL_CALL_SUMMARY_FIELD];
|
|
3096
|
-
} catch (err) {
|
|
3097
|
-
log$1.error({
|
|
3098
|
-
err,
|
|
3099
|
-
event: "tool_call_summary_strip_failed",
|
|
3100
|
-
toolName
|
|
3101
|
-
}, "tool_call_summary strip failed; leaving tool input untouched");
|
|
3102
|
-
}
|
|
3103
|
-
}
|
|
3104
|
-
/**
|
|
3105
|
-
* Compute the rewritten payload for a `before_provider_request` event, failing
|
|
3106
|
-
* open: on any error the original payload is left untouched so a bug here can
|
|
3107
|
-
* never break an LLM call.
|
|
3108
|
-
*/
|
|
3109
|
-
function buildInjectedPayload(pi, payload) {
|
|
3110
|
-
try {
|
|
3111
|
-
return injectToolCallSummary(payload, getStrictToolNames(pi));
|
|
3112
|
-
} catch (err) {
|
|
3113
|
-
log$1.error({
|
|
3114
|
-
err,
|
|
3115
|
-
event: "tool_call_summary_injection_failed"
|
|
3116
|
-
}, "tool_call_summary injection failed; passing payload through unchanged");
|
|
3117
|
-
return;
|
|
3118
|
-
}
|
|
3119
|
-
}
|
|
3120
|
-
const toolCallSummaryExtension = (pi) => {
|
|
3121
|
-
pi.on("before_provider_request", (event) => buildInjectedPayload(pi, event.payload));
|
|
3122
|
-
pi.on("tool_call", (event) => {
|
|
3123
|
-
stripInjectedSummary(pi, event.toolName, event.input);
|
|
3124
|
-
});
|
|
3125
|
-
};
|
|
3126
|
-
//#endregion
|
|
3127
4438
|
//#region src/extensions/background-tasks.ts
|
|
3128
4439
|
/**
|
|
3129
4440
|
* Background bash tasks as a pi extension.
|
|
@@ -3163,21 +4474,43 @@ const toolCallSummaryExtension = (pi) => {
|
|
|
3163
4474
|
* from the origin messageId in its channel context (`resolveConversationFromApi`)
|
|
3164
4475
|
* — and every run of the same conversation resolves to the same id, keeping the
|
|
3165
4476
|
* shared map correctly scoped across turns. `bg_*`, the completion wake, and the
|
|
3166
|
-
* next-session injection all filter
|
|
3167
|
-
*
|
|
4477
|
+
* next-session injection all filter by a **scope key** — the resolved
|
|
4478
|
+
* conversation id, or, when a session's conversation is unresolvable (a bare
|
|
4479
|
+
* CLI session, or a run whose channel-context ref carries no messageId), a
|
|
4480
|
+
* sentinel unique to that one session instance. Comparing on the raw
|
|
4481
|
+
* `conversationId` would bucket every unresolvable session together under
|
|
4482
|
+
* `null` and leak one's completion wake / status / next-session injection into
|
|
4483
|
+
* another; the sentinel keeps each isolated so an agent never sees or is woken
|
|
4484
|
+
* by a task from a different chat. Only the output log
|
|
3168
4485
|
* spills to disk (/home/user/.anyone/bg-tasks/<id>.log) to avoid buffering a chatty job
|
|
3169
4486
|
* in memory; exit code and run state live on the in-memory task.
|
|
3170
4487
|
*
|
|
3171
|
-
* **
|
|
3172
|
-
*
|
|
3173
|
-
* respawn,
|
|
3174
|
-
*
|
|
3175
|
-
*
|
|
3176
|
-
*
|
|
3177
|
-
*
|
|
3178
|
-
*
|
|
3179
|
-
*
|
|
3180
|
-
*
|
|
4488
|
+
* **Cross-restart survival is OPT-IN, via `bg_run({ resumable: true })`.**
|
|
4489
|
+
* A non-resumable task's state lives only in the running harness process: a
|
|
4490
|
+
* harness restart (crash → supervisord respawn, `platform harness reload`, or
|
|
4491
|
+
* a sandbox recycle on idle timeout / redeploy / template rebuild) drops the
|
|
4492
|
+
* map and pi's exec children are reaped with it, and the task is gone — the
|
|
4493
|
+
* right behavior for a one-shot side-effecting command, which must never
|
|
4494
|
+
* silently re-run.
|
|
4495
|
+
*
|
|
4496
|
+
* A RESUMABLE task additionally checkpoints its *spec* (command, cwd, labels,
|
|
4497
|
+
* origin messageId — not its live output/exit state) to a durable, api-side
|
|
4498
|
+
* journal keyed by conversation (`/sandbox/bg-task-journal`, redis). On the
|
|
4499
|
+
* NEXT run's `session_start` — which usually lands on a *different*,
|
|
4500
|
+
* cold-provisioned sandbox, which is exactly why the journal is api-side and
|
|
4501
|
+
* not on the sandbox disk — the harness lists the journal and relaunches any
|
|
4502
|
+
* spec it isn't already running, keeping the original id and prepending a
|
|
4503
|
+
* `<resumed-after-restart>` banner so the agent knows it re-ran from scratch,
|
|
4504
|
+
* not continued. The spec is dropped from the journal when the task
|
|
4505
|
+
* finishes/kills. Because relaunch RE-EXECUTES the command, resumable is only
|
|
4506
|
+
* for idempotent, long-lived work (pollers, watchers, retry loops); the tool
|
|
4507
|
+
* description enforces this and the default is false.
|
|
4508
|
+
*
|
|
4509
|
+
* The idle-completion wake (a task finishing while the agent is idle) crosses
|
|
4510
|
+
* the sandbox → platform boundary via a fresh run (`bg-task-done`) for both
|
|
4511
|
+
* resumable and non-resumable tasks; the journal is a separate, additive layer
|
|
4512
|
+
* that only handles a task whose harness dies BEFORE it finishes. This stays
|
|
4513
|
+
* distinct from the scheduled-run (cron) system.
|
|
3181
4514
|
*/
|
|
3182
4515
|
const log = logger.child({ module: "background-tasks-ext" });
|
|
3183
4516
|
const ops = createLocalBashOperations();
|
|
@@ -3188,6 +4521,7 @@ const WATCHDOG_INTERVAL_MS = 3e4;
|
|
|
3188
4521
|
const KEEPALIVE_EVERY_MS = 6e4;
|
|
3189
4522
|
const KEEPALIVE_MAX_MS = 3600 * 1e3;
|
|
3190
4523
|
const STALL_HINT_AFTER_MS = 120 * 1e3;
|
|
4524
|
+
const PUBLISH_DEBOUNCE_MS = 300;
|
|
3191
4525
|
const MAX_LOG_BYTES = 100 * 1024 * 1024;
|
|
3192
4526
|
const DEFAULT_TAIL_LINES = 30;
|
|
3193
4527
|
const TAIL_READ_BYTES = 64 * 1024;
|
|
@@ -3195,11 +4529,12 @@ function taskLabel(meta) {
|
|
|
3195
4529
|
return `${meta.id} "${meta.description ?? meta.command.slice(0, 60)}"`;
|
|
3196
4530
|
}
|
|
3197
4531
|
let taskCounter = 0;
|
|
4532
|
+
let sessionScopeCounter = 0;
|
|
3198
4533
|
const tasks = /* @__PURE__ */ new Map();
|
|
3199
4534
|
let watchdogInterval = null;
|
|
3200
4535
|
let lastKeepaliveAt = 0;
|
|
3201
|
-
function
|
|
3202
|
-
return meta.
|
|
4536
|
+
function sameScope(meta, scopeKey) {
|
|
4537
|
+
return meta.scopeKey === scopeKey;
|
|
3203
4538
|
}
|
|
3204
4539
|
function logPath(id) {
|
|
3205
4540
|
return join(tasksDir(), `${id}.log`);
|
|
@@ -3312,6 +4647,10 @@ function createBackgroundTasksExtension({ channelContext }) {
|
|
|
3312
4647
|
return id;
|
|
3313
4648
|
});
|
|
3314
4649
|
}
|
|
4650
|
+
const unresolvedScopeSentinel = `unresolved:${process.pid.toString(36)}:${(sessionScopeCounter += 1).toString(36)}`;
|
|
4651
|
+
function scopeKey() {
|
|
4652
|
+
return conversationId ?? unresolvedScopeSentinel;
|
|
4653
|
+
}
|
|
3315
4654
|
let agentActive = false;
|
|
3316
4655
|
pi.on("agent_start", async () => {
|
|
3317
4656
|
agentActive = true;
|
|
@@ -3339,13 +4678,16 @@ ${recentOutput}
|
|
|
3339
4678
|
</background-task-finished>
|
|
3340
4679
|
Run bg_logs for the full output.
|
|
3341
4680
|
|
|
3342
|
-
This is a background-task completion, not a message from the user.
|
|
4681
|
+
This is a background-task completion, not a message from the user.
|
|
4682
|
+
For a routine or expected completion, output nothing.
|
|
4683
|
+
Only reply if the outcome changes what the user should know or do,
|
|
4684
|
+
or if you were explicitly waiting to report it.`,
|
|
3343
4685
|
display: false
|
|
3344
4686
|
};
|
|
3345
4687
|
}
|
|
3346
4688
|
async function notifyCompletion(meta) {
|
|
3347
4689
|
if (meta.notified) return;
|
|
3348
|
-
if (agentActive &&
|
|
4690
|
+
if (agentActive && sameScope(meta, scopeKey())) {
|
|
3349
4691
|
meta.notified = true;
|
|
3350
4692
|
pi.sendMessage(await taskDoneMessage(meta), {
|
|
3351
4693
|
triggerTurn: true,
|
|
@@ -3376,9 +4718,83 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3376
4718
|
});
|
|
3377
4719
|
} else log.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
|
|
3378
4720
|
}
|
|
3379
|
-
|
|
4721
|
+
const SNAPSHOT_TAIL_LINES = 40;
|
|
4722
|
+
let lastPublishedSignature = null;
|
|
4723
|
+
let publishInFlight = null;
|
|
4724
|
+
let publishQueued = false;
|
|
4725
|
+
function snapshotSignature(snapshot) {
|
|
4726
|
+
return JSON.stringify(snapshot.map((t) => ({
|
|
4727
|
+
id: t.id,
|
|
4728
|
+
state: t.state,
|
|
4729
|
+
exitCode: t.exitCode,
|
|
4730
|
+
killedReason: t.killedReason,
|
|
4731
|
+
outputTail: t.outputTail
|
|
4732
|
+
})));
|
|
4733
|
+
}
|
|
4734
|
+
async function doPublishSnapshot() {
|
|
4735
|
+
if (!messageId) return;
|
|
4736
|
+
const mine = [...tasks.values()].filter((t) => sameScope(t, scopeKey()));
|
|
4737
|
+
try {
|
|
4738
|
+
const snapshot = await Promise.all(mine.map(async (t) => ({
|
|
4739
|
+
id: t.id,
|
|
4740
|
+
command: t.command,
|
|
4741
|
+
description: t.description,
|
|
4742
|
+
startedAt: t.startedAt,
|
|
4743
|
+
state: t.running ? "running" : "finished",
|
|
4744
|
+
exitCode: t.exitCode,
|
|
4745
|
+
killedReason: t.killedReason,
|
|
4746
|
+
outputTail: await tailLog(t.id, SNAPSHOT_TAIL_LINES)
|
|
4747
|
+
})));
|
|
4748
|
+
const signature = snapshotSignature(snapshot);
|
|
4749
|
+
if (signature === lastPublishedSignature) return;
|
|
4750
|
+
lastPublishedSignature = signature;
|
|
4751
|
+
postBackgroundTasksSnapshot({
|
|
4752
|
+
messageId,
|
|
4753
|
+
tasks: snapshot
|
|
4754
|
+
});
|
|
4755
|
+
} catch (err) {
|
|
4756
|
+
log.debug({
|
|
4757
|
+
err,
|
|
4758
|
+
event: "bg_tasks_snapshot_build_failed"
|
|
4759
|
+
}, "building bg-tasks snapshot failed");
|
|
4760
|
+
}
|
|
4761
|
+
}
|
|
4762
|
+
async function publishSnapshotNow() {
|
|
4763
|
+
if (publishInFlight) {
|
|
4764
|
+
publishQueued = true;
|
|
4765
|
+
return;
|
|
4766
|
+
}
|
|
4767
|
+
publishInFlight = (async () => {
|
|
4768
|
+
try {
|
|
4769
|
+
do {
|
|
4770
|
+
publishQueued = false;
|
|
4771
|
+
await doPublishSnapshot();
|
|
4772
|
+
} while (publishQueued);
|
|
4773
|
+
} finally {
|
|
4774
|
+
publishInFlight = null;
|
|
4775
|
+
}
|
|
4776
|
+
})();
|
|
4777
|
+
await publishInFlight;
|
|
4778
|
+
}
|
|
4779
|
+
let publishTimer = null;
|
|
4780
|
+
function schedulePublishSnapshot() {
|
|
4781
|
+
if (publishTimer) return;
|
|
4782
|
+
publishTimer = setTimeout(() => {
|
|
4783
|
+
publishTimer = null;
|
|
4784
|
+
publishSnapshotNow();
|
|
4785
|
+
}, PUBLISH_DEBOUNCE_MS);
|
|
4786
|
+
publishTimer.unref?.();
|
|
4787
|
+
}
|
|
4788
|
+
async function flushPublishSnapshot() {
|
|
4789
|
+
if (publishTimer) {
|
|
4790
|
+
clearTimeout(publishTimer);
|
|
4791
|
+
publishTimer = null;
|
|
4792
|
+
}
|
|
4793
|
+
await publishSnapshotNow();
|
|
4794
|
+
}
|
|
4795
|
+
async function launchTask({ command, description, cwd, resumable = false, resumedFromJournal = false, id: providedId, startedAt: providedStartedAt }) {
|
|
3380
4796
|
taskCounter += 1;
|
|
3381
|
-
const id = `bg-${process.pid.toString(36)}-${taskCounter}`;
|
|
4797
|
+
const id = providedId ?? `bg-${process.pid.toString(36)}-${taskCounter}`;
|
|
3382
4798
|
try {
|
|
3383
4799
|
await mkdir(tasksDir(), { recursive: true });
|
|
3384
4800
|
} catch (err) {
|
|
@@ -3394,7 +4810,7 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3394
4810
|
taskId: id
|
|
3395
4811
|
}, "bg task log write failed");
|
|
3396
4812
|
});
|
|
3397
|
-
const startedAt = Date.now();
|
|
4813
|
+
const startedAt = providedStartedAt ?? Date.now();
|
|
3398
4814
|
const meta = {
|
|
3399
4815
|
id,
|
|
3400
4816
|
command: stripPlatformExportsForDisplay(command),
|
|
@@ -3402,6 +4818,7 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3402
4818
|
logBytes: 0,
|
|
3403
4819
|
lastOutputAt: startedAt,
|
|
3404
4820
|
conversationId,
|
|
4821
|
+
scopeKey: scopeKey(),
|
|
3405
4822
|
messageId,
|
|
3406
4823
|
description,
|
|
3407
4824
|
notified: false,
|
|
@@ -3409,9 +4826,23 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3409
4826
|
controller: new AbortController(),
|
|
3410
4827
|
running: true,
|
|
3411
4828
|
exitCode: null,
|
|
3412
|
-
error: null
|
|
4829
|
+
error: null,
|
|
4830
|
+
resumable,
|
|
4831
|
+
cwd,
|
|
4832
|
+
resumedFromJournal
|
|
3413
4833
|
};
|
|
3414
4834
|
tasks.set(id, meta);
|
|
4835
|
+
if (resumable && messageId) putBackgroundTaskJournalSpec({
|
|
4836
|
+
messageId,
|
|
4837
|
+
spec: {
|
|
4838
|
+
id,
|
|
4839
|
+
command,
|
|
4840
|
+
cwd,
|
|
4841
|
+
description,
|
|
4842
|
+
startedAt,
|
|
4843
|
+
messageId
|
|
4844
|
+
}
|
|
4845
|
+
});
|
|
3415
4846
|
ops.exec(command, cwd, {
|
|
3416
4847
|
onData: (chunk) => {
|
|
3417
4848
|
meta.logBytes += chunk.length;
|
|
@@ -3437,6 +4868,11 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3437
4868
|
taskId: id,
|
|
3438
4869
|
exitCode: meta.exitCode
|
|
3439
4870
|
}, "bg task finished");
|
|
4871
|
+
if (meta.resumable && meta.messageId) deleteBackgroundTaskJournalSpec({
|
|
4872
|
+
messageId: meta.messageId,
|
|
4873
|
+
taskId: id
|
|
4874
|
+
});
|
|
4875
|
+
schedulePublishSnapshot();
|
|
3440
4876
|
await notifyCompletion(meta);
|
|
3441
4877
|
});
|
|
3442
4878
|
ensureWatchdog();
|
|
@@ -3444,19 +4880,55 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3444
4880
|
taskId: id,
|
|
3445
4881
|
conversationId
|
|
3446
4882
|
}, "bg task started");
|
|
4883
|
+
schedulePublishSnapshot();
|
|
3447
4884
|
return meta;
|
|
3448
4885
|
}
|
|
3449
4886
|
function knownTaskIds() {
|
|
3450
|
-
return [...tasks.values()].filter((t) =>
|
|
4887
|
+
return [...tasks.values()].filter((t) => sameScope(t, scopeKey())).map((t) => t.id).join(", ") || "(none)";
|
|
4888
|
+
}
|
|
4889
|
+
let journalChecked = false;
|
|
4890
|
+
async function rehydrateJournaledTasks() {
|
|
4891
|
+
if (!messageId || journalChecked) return;
|
|
4892
|
+
journalChecked = true;
|
|
4893
|
+
const specs = await listBackgroundTaskJournalSpecs({ messageId });
|
|
4894
|
+
if (specs.length === 0) return;
|
|
4895
|
+
for (const spec of specs) {
|
|
4896
|
+
const live = tasks.get(spec.id);
|
|
4897
|
+
if (live && sameScope(live, scopeKey())) continue;
|
|
4898
|
+
log.info({
|
|
4899
|
+
taskId: spec.id,
|
|
4900
|
+
conversationId
|
|
4901
|
+
}, "relaunching journaled resumable bg task after restart");
|
|
4902
|
+
const meta = await launchTask({
|
|
4903
|
+
command: spec.command,
|
|
4904
|
+
description: spec.description,
|
|
4905
|
+
cwd: spec.cwd,
|
|
4906
|
+
resumable: true,
|
|
4907
|
+
resumedFromJournal: true,
|
|
4908
|
+
id: spec.id,
|
|
4909
|
+
startedAt: spec.startedAt
|
|
4910
|
+
});
|
|
4911
|
+
try {
|
|
4912
|
+
const stream = createWriteStream(logPath(meta.id), { flags: "a" });
|
|
4913
|
+
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`);
|
|
4914
|
+
stream.end();
|
|
4915
|
+
} catch (err) {
|
|
4916
|
+
log.debug({
|
|
4917
|
+
err,
|
|
4918
|
+
taskId: meta.id
|
|
4919
|
+
}, "resume banner write failed");
|
|
4920
|
+
}
|
|
4921
|
+
}
|
|
3451
4922
|
}
|
|
3452
4923
|
pi.on("session_start", async () => {
|
|
3453
|
-
if (tasks.size === 0) return;
|
|
4924
|
+
if (tasks.size === 0 && (!messageId || journalChecked)) return;
|
|
3454
4925
|
await ensureConversationId();
|
|
3455
|
-
|
|
4926
|
+
await rehydrateJournaledTasks();
|
|
4927
|
+
for (const [id, meta] of tasks) if (sameScope(meta, scopeKey()) && !meta.running && meta.notified) {
|
|
3456
4928
|
tasks.delete(id);
|
|
3457
4929
|
await unlink(logPath(id)).catch(() => {});
|
|
3458
4930
|
}
|
|
3459
|
-
const unnotified = [...tasks.values()].filter((t) =>
|
|
4931
|
+
const unnotified = [...tasks.values()].filter((t) => sameScope(t, scopeKey()) && !t.notified && !t.running);
|
|
3460
4932
|
for (const meta of unnotified) {
|
|
3461
4933
|
meta.notified = true;
|
|
3462
4934
|
pi.sendMessage(await taskDoneMessage(meta));
|
|
@@ -3465,7 +4937,9 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3465
4937
|
conversationId,
|
|
3466
4938
|
count: unnotified.length
|
|
3467
4939
|
}, "injected completed bg tasks at session_start");
|
|
3468
|
-
if ([...tasks.values()].some((t) =>
|
|
4940
|
+
if ([...tasks.values()].some((t) => sameScope(t, scopeKey()) && t.running)) ensureWatchdog();
|
|
4941
|
+
lastPublishedSignature = null;
|
|
4942
|
+
await flushPublishSnapshot();
|
|
3469
4943
|
});
|
|
3470
4944
|
function err(text) {
|
|
3471
4945
|
return {
|
|
@@ -3482,11 +4956,11 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3482
4956
|
}
|
|
3483
4957
|
function resolveTask(taskId) {
|
|
3484
4958
|
const exact = tasks.get(taskId);
|
|
3485
|
-
if (exact &&
|
|
4959
|
+
if (exact && sameScope(exact, scopeKey())) return {
|
|
3486
4960
|
error: null,
|
|
3487
4961
|
meta: exact
|
|
3488
4962
|
};
|
|
3489
|
-
const matches = [...tasks.values()].filter((t) =>
|
|
4963
|
+
const matches = [...tasks.values()].filter((t) => sameScope(t, scopeKey()) && t.id.startsWith(taskId));
|
|
3490
4964
|
if (matches.length === 1) return {
|
|
3491
4965
|
error: null,
|
|
3492
4966
|
meta: matches[0]
|
|
@@ -3495,7 +4969,7 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3495
4969
|
return err(`Unknown task ${taskId}. Known tasks: ${knownTaskIds()}`);
|
|
3496
4970
|
}
|
|
3497
4971
|
function listTasks() {
|
|
3498
|
-
const mine = [...tasks.values()].filter((t) =>
|
|
4972
|
+
const mine = [...tasks.values()].filter((t) => sameScope(t, scopeKey()));
|
|
3499
4973
|
if (mine.length === 0) return "No background tasks.";
|
|
3500
4974
|
return mine.map((t) => {
|
|
3501
4975
|
const state = t.running ? "running" : t.exitCode !== null ? `exited ${t.exitCode}${t.killedReason ? ` (killed: ${t.killedReason})` : ""}` : t.killedReason ? `killed: ${t.killedReason}` : "ended";
|
|
@@ -3508,24 +4982,27 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3508
4982
|
const bgRun = {
|
|
3509
4983
|
name: "bg_run",
|
|
3510
4984
|
label: "Run in background",
|
|
3511
|
-
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.",
|
|
3512
|
-
promptSnippet: "bg_run — run a long command without blocking; you are notified on completion",
|
|
4985
|
+
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.",
|
|
4986
|
+
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)",
|
|
3513
4987
|
parameters: Type.Object({
|
|
3514
4988
|
command: Type.String({ description: "Bash command to execute" }),
|
|
3515
|
-
description: Type.Optional(Type.String({ description: "Clear, concise description of what this command does in active voice (2-6 words)." }))
|
|
4989
|
+
description: Type.Optional(Type.String({ description: "Clear, concise description of what this command does in active voice (2-6 words)." })),
|
|
4990
|
+
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." }))
|
|
3516
4991
|
}),
|
|
3517
4992
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3518
4993
|
await ensureConversationId();
|
|
3519
|
-
const { command, description = null } = params;
|
|
4994
|
+
const { command, description = null, resumable = false } = params;
|
|
3520
4995
|
const meta = await launchTask({
|
|
3521
4996
|
command,
|
|
3522
4997
|
description,
|
|
3523
|
-
cwd: ctx.cwd
|
|
4998
|
+
cwd: ctx.cwd,
|
|
4999
|
+
resumable
|
|
3524
5000
|
});
|
|
5001
|
+
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." : "";
|
|
3525
5002
|
return {
|
|
3526
5003
|
content: [{
|
|
3527
5004
|
type: "text",
|
|
3528
|
-
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}"}.`
|
|
5005
|
+
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.`
|
|
3529
5006
|
}],
|
|
3530
5007
|
details: {}
|
|
3531
5008
|
};
|
|
@@ -3554,7 +5031,7 @@ This is a background-task completion, not a message from the user. If it needs n
|
|
|
3554
5031
|
return {
|
|
3555
5032
|
content: [{
|
|
3556
5033
|
type: "text",
|
|
3557
|
-
text: await describeStatus(resolved.meta, lines)
|
|
5034
|
+
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." : ""}`
|
|
3558
5035
|
}],
|
|
3559
5036
|
details: {}
|
|
3560
5037
|
};
|
|
@@ -3645,6 +5122,7 @@ const all = [
|
|
|
3645
5122
|
localToolsExtension,
|
|
3646
5123
|
toolCallEnvExtension,
|
|
3647
5124
|
bashDefaultTimeoutExtension,
|
|
5125
|
+
diskGuardExtension,
|
|
3648
5126
|
toolCallSummaryExtension
|
|
3649
5127
|
];
|
|
3650
5128
|
/**
|
|
@@ -3663,8 +5141,9 @@ function platformExtensions({ sessionId, channelContext }) {
|
|
|
3663
5141
|
selfTraceExtension,
|
|
3664
5142
|
createBackgroundTasksExtension({ channelContext }),
|
|
3665
5143
|
createSubagentExtension({ channelContext }),
|
|
3666
|
-
createContextManagementExtension()
|
|
5144
|
+
createContextManagementExtension(),
|
|
5145
|
+
resourcePressureWarningExtension
|
|
3667
5146
|
];
|
|
3668
5147
|
}
|
|
3669
5148
|
//#endregion
|
|
3670
|
-
export { all, createHarness, createHealthHandler, createPlatformEnvMiddleware, installToolUpdateAutoStop, isPlatformConfigLoaded, loadPlatformConfig, localToolsExtension, mcp_default as mcpExtension, memoryExtension, platformExtensions, runToolUpdateLoop, soulExtension, toolCallEnvExtension };
|
|
5149
|
+
export { all, createHarness, createHealthHandler, createPlatformEnvMiddleware, installToolUpdateAutoStop, isPlatformConfigLoaded, loadPlatformConfig, localToolsExtension, mcp_default as mcpExtension, memoryExtension, platformExtensions, runClosingTextLoop, runToolUpdateLoop, soulExtension, toolCallEnvExtension, turnEndedWithoutVisibleText };
|