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