@skydiveai/pi-extensions 0.1.258-beta.133 → 0.1.258-beta.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +408 -142
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -25,6 +25,8 @@ import { execFile, spawn } from "node:child_process";
|
|
|
25
25
|
import os, { availableParallelism } from "node:os";
|
|
26
26
|
import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
27
27
|
import { adjustMaxTokensForThinking, clampMaxTokensToContext } from "@earendil-works/pi-ai-runtime/api/simple-options";
|
|
28
|
+
import { createServer } from "node:http";
|
|
29
|
+
import { buffer } from "node:stream/consumers";
|
|
28
30
|
import { quote } from "shell-quote";
|
|
29
31
|
import { ROOT_CONTEXT, SpanStatusCode, propagation, trace } from "@opentelemetry/api";
|
|
30
32
|
import { W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
@@ -265,7 +267,7 @@ function createHealthHandler({ metadata }) {
|
|
|
265
267
|
const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task is done, if this changes what you can do for the user, record it in `soul.md` so it carries into future conversations rather than being rediscovered from scratch (then commit and push).";
|
|
266
268
|
//#endregion
|
|
267
269
|
//#region src/extensions/tool-call-summary.ts
|
|
268
|
-
const log$
|
|
270
|
+
const log$23 = logger.child({ module: "tool-call-summary-extension" });
|
|
269
271
|
/**
|
|
270
272
|
* The injected parameter name. Deliberately markdown-safe: the previous wire
|
|
271
273
|
* name (`__skydive_summary__`, now `TOOL_CALL_SUMMARY_FIELD_LEGACY`) carried
|
|
@@ -499,7 +501,7 @@ function withSummaryStrippedBeforeValidation(tool) {
|
|
|
499
501
|
try {
|
|
500
502
|
stripped = withoutInjectedSummary(args);
|
|
501
503
|
} catch (err) {
|
|
502
|
-
log$
|
|
504
|
+
log$23.error({
|
|
503
505
|
err,
|
|
504
506
|
event: "tool_call_summary_prepare_strip_failed",
|
|
505
507
|
toolName: tool.name
|
|
@@ -530,7 +532,7 @@ function stripInjectedSummary(pi, toolName, input) {
|
|
|
530
532
|
if (toolDeclaresSummaryParam(pi, toolName)) return;
|
|
531
533
|
for (const field of TOOL_CALL_SUMMARY_FIELDS) delete input[field];
|
|
532
534
|
} catch (err) {
|
|
533
|
-
log$
|
|
535
|
+
log$23.error({
|
|
534
536
|
err,
|
|
535
537
|
event: "tool_call_summary_strip_failed",
|
|
536
538
|
toolName
|
|
@@ -546,7 +548,7 @@ function buildInjectedPayload(pi, payload) {
|
|
|
546
548
|
try {
|
|
547
549
|
return injectToolCallSummary(payload, getStrictToolNames(pi));
|
|
548
550
|
} catch (err) {
|
|
549
|
-
log$
|
|
551
|
+
log$23.error({
|
|
550
552
|
err,
|
|
551
553
|
event: "tool_call_summary_injection_failed"
|
|
552
554
|
}, "tool_call_summary injection failed; passing payload through unchanged");
|
|
@@ -565,7 +567,7 @@ const toolCallSummaryExtension = (pi) => {
|
|
|
565
567
|
pi.registerTool(withSummaryStrippedBeforeValidation(createEditToolDefinition(ctx.cwd)));
|
|
566
568
|
editOverrideRegistered = true;
|
|
567
569
|
} catch (err) {
|
|
568
|
-
log$
|
|
570
|
+
log$23.error({
|
|
569
571
|
err,
|
|
570
572
|
event: "tool_call_summary_edit_override_failed"
|
|
571
573
|
}, "failed to register summary-tolerant edit tool; built-in remains active");
|
|
@@ -596,7 +598,7 @@ const toolCallSummaryExtension = (pi) => {
|
|
|
596
598
|
* or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
|
|
597
599
|
* `tools/_example.ts` documents the shape without registering.
|
|
598
600
|
*/
|
|
599
|
-
const log$
|
|
601
|
+
const log$22 = logger.child({ module: "local-tools-extension" });
|
|
600
602
|
const TOOLS_DIRNAME = "tools";
|
|
601
603
|
const fileState = /* @__PURE__ */ new Map();
|
|
602
604
|
let pendingLocalToolsUpdate = null;
|
|
@@ -740,7 +742,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
|
|
|
740
742
|
dir
|
|
741
743
|
});
|
|
742
744
|
if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
|
|
743
|
-
log$
|
|
745
|
+
log$22.info({
|
|
744
746
|
event: "local_tools_reconcile",
|
|
745
747
|
reason,
|
|
746
748
|
total_tools: summary.totalTools,
|
|
@@ -762,7 +764,7 @@ const localToolsExtension = (pi) => {
|
|
|
762
764
|
reason: "session_start"
|
|
763
765
|
});
|
|
764
766
|
} catch (err) {
|
|
765
|
-
log$
|
|
767
|
+
log$22.error({
|
|
766
768
|
err,
|
|
767
769
|
event: "local_tools_reconcile_failed"
|
|
768
770
|
}, "local tools reconcile failed");
|
|
@@ -774,7 +776,7 @@ const localToolsExtension = (pi) => {
|
|
|
774
776
|
try {
|
|
775
777
|
current = await listToolFiles(dir);
|
|
776
778
|
} catch (err) {
|
|
777
|
-
log$
|
|
779
|
+
log$22.warn({
|
|
778
780
|
err,
|
|
779
781
|
event: "local_tools_listing_failed"
|
|
780
782
|
}, "tools/ listing failed");
|
|
@@ -796,7 +798,7 @@ const localToolsExtension = (pi) => {
|
|
|
796
798
|
reason: "auto_reload"
|
|
797
799
|
});
|
|
798
800
|
} catch (err) {
|
|
799
|
-
log$
|
|
801
|
+
log$22.error({
|
|
800
802
|
err,
|
|
801
803
|
event: "local_tools_auto_reload_failed"
|
|
802
804
|
}, "auto-reload after tools/ change failed");
|
|
@@ -1500,7 +1502,7 @@ function toProviderSafeSchema(inputSchema) {
|
|
|
1500
1502
|
* Clients are keyed by JSON-stringified config and reused across
|
|
1501
1503
|
* reloads — only changed configs reconnect.
|
|
1502
1504
|
*/
|
|
1503
|
-
const log$
|
|
1505
|
+
const log$21 = logger.child({ module: "mcp-extension" });
|
|
1504
1506
|
function resolveToolSelection(server) {
|
|
1505
1507
|
return {
|
|
1506
1508
|
allow: server?.tools?.length ? new Set(server.tools) : null,
|
|
@@ -1698,7 +1700,7 @@ function providerSafeTools({ serverId, tools }) {
|
|
|
1698
1700
|
for (const tool of tools) {
|
|
1699
1701
|
const result = toProviderSafeSchema(tool.inputSchema);
|
|
1700
1702
|
if (!result.ok) {
|
|
1701
|
-
log$
|
|
1703
|
+
log$21.warn({
|
|
1702
1704
|
event: "mcp_tool_schema_unsupported",
|
|
1703
1705
|
server_id: serverId,
|
|
1704
1706
|
tool_name: tool.name,
|
|
@@ -2172,7 +2174,7 @@ var McpExtension = class {
|
|
|
2172
2174
|
});
|
|
2173
2175
|
this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
|
|
2174
2176
|
if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
|
|
2175
|
-
log$
|
|
2177
|
+
log$21.info({
|
|
2176
2178
|
event: "mcp_reconcile",
|
|
2177
2179
|
reason,
|
|
2178
2180
|
total_tools: summary.totalTools,
|
|
@@ -2199,7 +2201,7 @@ var McpExtension = class {
|
|
|
2199
2201
|
contextWindow: ctx.model?.contextWindow
|
|
2200
2202
|
});
|
|
2201
2203
|
} catch (err) {
|
|
2202
|
-
log$
|
|
2204
|
+
log$21.error({
|
|
2203
2205
|
err,
|
|
2204
2206
|
event: "mcp_reconcile_failed"
|
|
2205
2207
|
}, "MCP reconcile failed");
|
|
@@ -2213,7 +2215,7 @@ var McpExtension = class {
|
|
|
2213
2215
|
for (const legacy of renamed) {
|
|
2214
2216
|
if (this.loggedLegacyToolNames.has(legacy)) continue;
|
|
2215
2217
|
this.loggedLegacyToolNames.add(legacy);
|
|
2216
|
-
log$
|
|
2218
|
+
log$21.info({
|
|
2217
2219
|
event: "mcp_tool_legacy_name",
|
|
2218
2220
|
legacy_name: legacy,
|
|
2219
2221
|
tool_name: this.legacyToolNames.get(legacy)
|
|
@@ -2227,7 +2229,7 @@ var McpExtension = class {
|
|
|
2227
2229
|
try {
|
|
2228
2230
|
mtime = await readConfigMtimeMs(configPath);
|
|
2229
2231
|
} catch (err) {
|
|
2230
|
-
log$
|
|
2232
|
+
log$21.warn({
|
|
2231
2233
|
err,
|
|
2232
2234
|
event: "mcp_mtime_check_failed"
|
|
2233
2235
|
}, "mtime check on mcp.config.json failed");
|
|
@@ -2242,7 +2244,7 @@ var McpExtension = class {
|
|
|
2242
2244
|
contextWindow: ctx.model?.contextWindow
|
|
2243
2245
|
});
|
|
2244
2246
|
} catch (err) {
|
|
2245
|
-
log$
|
|
2247
|
+
log$21.error({
|
|
2246
2248
|
err,
|
|
2247
2249
|
event: "mcp_auto_reload_failed"
|
|
2248
2250
|
}, "auto-reload after mcp.config.json change failed");
|
|
@@ -2608,12 +2610,6 @@ const assistantSchema = z.object({
|
|
|
2608
2610
|
id: z.string(),
|
|
2609
2611
|
model: z.string()
|
|
2610
2612
|
});
|
|
2611
|
-
/** Sent as the SDK prompt when Pi's context ends with tool results. */
|
|
2612
|
-
const SEAT_CONTINUE_PROMPT = "Continue from the existing conversation and tool results.";
|
|
2613
|
-
const continuePromptSchema = z.object({ content: z.union([z.literal(SEAT_CONTINUE_PROMPT), z.tuple([z.object({
|
|
2614
|
-
type: z.literal("text"),
|
|
2615
|
-
text: z.literal(SEAT_CONTINUE_PROMPT)
|
|
2616
|
-
})])]) });
|
|
2617
2613
|
const sdkToolResultSchema = z.object({ content: z.array(z.object({ type: z.literal("tool_result") })).min(1) });
|
|
2618
2614
|
function assistantMessage(entry) {
|
|
2619
2615
|
if (entry.type !== "assistant") return null;
|
|
@@ -2629,30 +2625,6 @@ function assistantMessage(entry) {
|
|
|
2629
2625
|
function isSdkToolResult(entry) {
|
|
2630
2626
|
return entry.type === "user" && sdkToolResultSchema.safeParse(entry.message).success;
|
|
2631
2627
|
}
|
|
2632
|
-
/**
|
|
2633
|
-
* On resume, the pinned CLI inserts a `<synthetic>` "No response requested."
|
|
2634
|
-
* assistant turn after a trailing tool_result, before the continuation prompt.
|
|
2635
|
-
* Each tool step therefore stores one placeholder pair. Inside the current turn
|
|
2636
|
-
* the pair must stay so the cached prefix is byte-identical between steps, but
|
|
2637
|
-
* once a newer user message exists it is dropped: otherwise the model rereads
|
|
2638
|
-
* itself saying "No response requested." once per historical tool step.
|
|
2639
|
-
* Only our own continuation prompt goes with it; when a steer was the prompt,
|
|
2640
|
-
* the user's text follows the synthetic turn and must be kept.
|
|
2641
|
-
*/
|
|
2642
|
-
function withoutResumePlaceholders(entries) {
|
|
2643
|
-
let dropPrompt = false;
|
|
2644
|
-
return entries.filter((entry) => {
|
|
2645
|
-
if (assistantMessage(entry)?.model === "<synthetic>") {
|
|
2646
|
-
dropPrompt = true;
|
|
2647
|
-
return false;
|
|
2648
|
-
}
|
|
2649
|
-
if (dropPrompt && entry.type === "user") {
|
|
2650
|
-
dropPrompt = false;
|
|
2651
|
-
return !continuePromptSchema.safeParse(entry.message).success;
|
|
2652
|
-
}
|
|
2653
|
-
return true;
|
|
2654
|
-
});
|
|
2655
|
-
}
|
|
2656
2628
|
function contentHash(message) {
|
|
2657
2629
|
return createHash("sha256").update(JSON.stringify(message.content)).digest("hex");
|
|
2658
2630
|
}
|
|
@@ -2719,6 +2691,8 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
|
|
|
2719
2691
|
}
|
|
2720
2692
|
//#endregion
|
|
2721
2693
|
//#region src/extensions/claude-seat-history.ts
|
|
2694
|
+
/** Sent as the SDK prompt when Pi's context ends with tool results. */
|
|
2695
|
+
const SEAT_CONTINUE_PROMPT = "Continue from the existing conversation and tool results.";
|
|
2722
2696
|
const imageType = z.enum([
|
|
2723
2697
|
"image/jpeg",
|
|
2724
2698
|
"image/png",
|
|
@@ -2810,7 +2784,6 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
|
|
|
2810
2784
|
resume: null,
|
|
2811
2785
|
boundaryId: null
|
|
2812
2786
|
};
|
|
2813
|
-
const lastUserIndex = context.messages.findLastIndex((message) => message.role === "user");
|
|
2814
2787
|
const sessionId = randomUUID();
|
|
2815
2788
|
let parentUuid = null;
|
|
2816
2789
|
const entries = messages.flatMap((message, index) => {
|
|
@@ -2820,7 +2793,7 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
|
|
|
2820
2793
|
const nextHash = hashes[index + 1];
|
|
2821
2794
|
if (message.role === "user" && next?.role === "assistant" && nextHash && seatTranscript(next, nextHash)?.replacesUser) return [];
|
|
2822
2795
|
const preserved = message.role === "assistant" ? seatTranscript(message, prefixHash) : null;
|
|
2823
|
-
if (preserved) return
|
|
2796
|
+
if (preserved) return preserved.entries.map((entry) => {
|
|
2824
2797
|
const uuid = randomUUID();
|
|
2825
2798
|
const replay = {
|
|
2826
2799
|
...entry,
|
|
@@ -2918,6 +2891,176 @@ function seatReasoningOptions({ model, context, options }) {
|
|
|
2918
2891
|
};
|
|
2919
2892
|
}
|
|
2920
2893
|
//#endregion
|
|
2894
|
+
//#region src/extensions/claude-seat-request-proxy.ts
|
|
2895
|
+
const log$20 = logger.child({ module: "claude-seat-request-proxy" });
|
|
2896
|
+
const RESUME_PLACEHOLDER = "No response requested.";
|
|
2897
|
+
const blockSchema = z.record(z.string(), z.json());
|
|
2898
|
+
const messageSchema = z.object({
|
|
2899
|
+
role: z.string(),
|
|
2900
|
+
content: z.union([z.string(), z.array(blockSchema)])
|
|
2901
|
+
}).catchall(z.json());
|
|
2902
|
+
const requestSchema = z.object({ messages: z.array(messageSchema) }).catchall(z.json());
|
|
2903
|
+
function blocks(message) {
|
|
2904
|
+
return typeof message.content === "string" ? [{
|
|
2905
|
+
type: "text",
|
|
2906
|
+
text: message.content
|
|
2907
|
+
}] : message.content;
|
|
2908
|
+
}
|
|
2909
|
+
/** The text of a message made of exactly one text block, else null. */
|
|
2910
|
+
function soleText(message) {
|
|
2911
|
+
if (!message) return null;
|
|
2912
|
+
const [only, ...rest] = blocks(message);
|
|
2913
|
+
return only?.type === "text" && rest.length === 0 ? only.text : null;
|
|
2914
|
+
}
|
|
2915
|
+
function hasToolResult(message) {
|
|
2916
|
+
return message?.role === "user" && blocks(message).some((block) => block.type === "tool_result");
|
|
2917
|
+
}
|
|
2918
|
+
function isPlaceholder(message) {
|
|
2919
|
+
return message.role === "assistant" && soleText(message) === RESUME_PLACEHOLDER;
|
|
2920
|
+
}
|
|
2921
|
+
function isContinuePrompt(message) {
|
|
2922
|
+
return message?.role === "user" && soleText(message) === "Continue from the existing conversation and tool results.";
|
|
2923
|
+
}
|
|
2924
|
+
/**
|
|
2925
|
+
* On resume, the pinned Claude Code CLI inserts a synthetic "No response
|
|
2926
|
+
* requested." assistant turn before any prompt that follows a tool_result.
|
|
2927
|
+
* Removing it (and our own continuation prompt) from every request keeps the
|
|
2928
|
+
* model from rereading itself saying it once per tool step. Applying the same
|
|
2929
|
+
* rewrite to every request keeps prefixes byte-identical across steps, so the
|
|
2930
|
+
* prompt cache and thinking signatures see one stable history.
|
|
2931
|
+
*/
|
|
2932
|
+
function stripResumePlaceholders(messages) {
|
|
2933
|
+
const kept = [];
|
|
2934
|
+
let cacheControl = null;
|
|
2935
|
+
for (let index = 0; index < messages.length; index++) {
|
|
2936
|
+
const message = messages[index];
|
|
2937
|
+
if (!message) continue;
|
|
2938
|
+
const next = messages[index + 1];
|
|
2939
|
+
if (isPlaceholder(message) && hasToolResult(messages[index - 1]) && next?.role === "user") {
|
|
2940
|
+
const dropped = isContinuePrompt(next) ? [message, next] : [message];
|
|
2941
|
+
for (const block of dropped.flatMap(blocks)) if (block.cache_control !== void 0) cacheControl = block.cache_control;
|
|
2942
|
+
if (dropped.length === 2) index++;
|
|
2943
|
+
continue;
|
|
2944
|
+
}
|
|
2945
|
+
kept.push(message);
|
|
2946
|
+
}
|
|
2947
|
+
const merged = [];
|
|
2948
|
+
for (const message of kept) {
|
|
2949
|
+
const previous = merged.at(-1);
|
|
2950
|
+
if (previous?.role === message.role && (message.role === "user" || message.role === "assistant")) merged[merged.length - 1] = {
|
|
2951
|
+
...previous,
|
|
2952
|
+
content: [...blocks(previous), ...blocks(message)]
|
|
2953
|
+
};
|
|
2954
|
+
else merged.push(message);
|
|
2955
|
+
}
|
|
2956
|
+
const last = merged.at(-1);
|
|
2957
|
+
if (cacheControl !== null && last) {
|
|
2958
|
+
const content = blocks(last).map((block) => {
|
|
2959
|
+
const { cache_control: _, ...rest } = block;
|
|
2960
|
+
return rest;
|
|
2961
|
+
});
|
|
2962
|
+
const tail = content.at(-1);
|
|
2963
|
+
if (tail) content[content.length - 1] = {
|
|
2964
|
+
...tail,
|
|
2965
|
+
cache_control: cacheControl
|
|
2966
|
+
};
|
|
2967
|
+
merged[merged.length - 1] = {
|
|
2968
|
+
...last,
|
|
2969
|
+
content
|
|
2970
|
+
};
|
|
2971
|
+
}
|
|
2972
|
+
return {
|
|
2973
|
+
messages: merged,
|
|
2974
|
+
removed: messages.length - kept.length
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
const jsonSchema = z.string().transform((text, ctx) => {
|
|
2978
|
+
try {
|
|
2979
|
+
return JSON.parse(text);
|
|
2980
|
+
} catch {
|
|
2981
|
+
ctx.addIssue({
|
|
2982
|
+
code: "custom",
|
|
2983
|
+
message: "Request body is not JSON"
|
|
2984
|
+
});
|
|
2985
|
+
return z.NEVER;
|
|
2986
|
+
}
|
|
2987
|
+
});
|
|
2988
|
+
function rewriteBody(body) {
|
|
2989
|
+
const parsed = jsonSchema.pipe(requestSchema).safeParse(body.toString());
|
|
2990
|
+
if (!parsed.success) {
|
|
2991
|
+
log$20.warn({ err: parsed.error }, "Claude seat request did not match the expected shape; forwarding as is");
|
|
2992
|
+
return body;
|
|
2993
|
+
}
|
|
2994
|
+
const { messages, removed } = stripResumePlaceholders(parsed.data.messages);
|
|
2995
|
+
if (removed === 0) return body;
|
|
2996
|
+
return Buffer.from(JSON.stringify({
|
|
2997
|
+
...parsed.data,
|
|
2998
|
+
messages
|
|
2999
|
+
}));
|
|
3000
|
+
}
|
|
3001
|
+
const HOP_BY_HOP = new Set([
|
|
3002
|
+
"host",
|
|
3003
|
+
"connection",
|
|
3004
|
+
"content-length",
|
|
3005
|
+
"transfer-encoding",
|
|
3006
|
+
"keep-alive"
|
|
3007
|
+
]);
|
|
3008
|
+
/**
|
|
3009
|
+
* Local hop between the Claude Code CLI and the seat's upstream base URL. It
|
|
3010
|
+
* forwards everything unchanged except Messages API bodies, which lose the
|
|
3011
|
+
* CLI's resume placeholders (see `stripResumePlaceholders`).
|
|
3012
|
+
*/
|
|
3013
|
+
async function startSeatRequestProxy({ target }) {
|
|
3014
|
+
const base = target.replace(/\/+$/, "");
|
|
3015
|
+
const server = createServer(async (request, response) => {
|
|
3016
|
+
const upstreamAbort = new AbortController();
|
|
3017
|
+
response.once("close", () => upstreamAbort.abort());
|
|
3018
|
+
try {
|
|
3019
|
+
const raw = await buffer(request);
|
|
3020
|
+
const body = request.method === "POST" && request.url?.startsWith("/v1/messages") ? rewriteBody(raw) : raw;
|
|
3021
|
+
const headers = new Headers();
|
|
3022
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
3023
|
+
if (value === void 0 || HOP_BY_HOP.has(name)) continue;
|
|
3024
|
+
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
3025
|
+
}
|
|
3026
|
+
const upstream = await fetch(`${base}${request.url ?? ""}`, {
|
|
3027
|
+
method: request.method,
|
|
3028
|
+
headers,
|
|
3029
|
+
body: ["GET", "HEAD"].includes(request.method ?? "") ? null : new Uint8Array(body),
|
|
3030
|
+
signal: upstreamAbort.signal
|
|
3031
|
+
});
|
|
3032
|
+
const responseHeaders = {};
|
|
3033
|
+
upstream.headers.forEach((value, name) => {
|
|
3034
|
+
if (!HOP_BY_HOP.has(name) && name !== "content-encoding") responseHeaders[name] = value;
|
|
3035
|
+
});
|
|
3036
|
+
response.writeHead(upstream.status, responseHeaders);
|
|
3037
|
+
if (!upstream.body) {
|
|
3038
|
+
response.end();
|
|
3039
|
+
return;
|
|
3040
|
+
}
|
|
3041
|
+
const reader = upstream.body.getReader();
|
|
3042
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) if (!response.write(chunk.value)) await once(response, "drain", { signal: upstreamAbort.signal });
|
|
3043
|
+
response.end();
|
|
3044
|
+
} catch (err) {
|
|
3045
|
+
if (upstreamAbort.signal.aborted) return;
|
|
3046
|
+
log$20.error({ err }, "Claude seat request proxy failed to forward");
|
|
3047
|
+
if (!response.headersSent) response.writeHead(502);
|
|
3048
|
+
response.end();
|
|
3049
|
+
}
|
|
3050
|
+
});
|
|
3051
|
+
server.listen(0, "127.0.0.1");
|
|
3052
|
+
await once(server, "listening");
|
|
3053
|
+
const address = server.address();
|
|
3054
|
+
if (!address || typeof address === "string") throw new Error("Claude seat request proxy has no TCP address");
|
|
3055
|
+
return {
|
|
3056
|
+
url: `http://127.0.0.1:${address.port}`,
|
|
3057
|
+
close: () => {
|
|
3058
|
+
server.closeAllConnections();
|
|
3059
|
+
server.close();
|
|
3060
|
+
}
|
|
3061
|
+
};
|
|
3062
|
+
}
|
|
3063
|
+
//#endregion
|
|
2921
3064
|
//#region src/extensions/claude-seat-payload.ts
|
|
2922
3065
|
const payloadSchema = z.strictObject({
|
|
2923
3066
|
model: z.string(),
|
|
@@ -2989,7 +3132,7 @@ const SEAT_QUERY_TIMEOUTS = {
|
|
|
2989
3132
|
preparation: 3e4
|
|
2990
3133
|
};
|
|
2991
3134
|
const PI_TOOLS_SERVER = "custom-tools";
|
|
2992
|
-
const log$
|
|
3135
|
+
const log$19 = logger.child({ module: "claude-seat-sdk" });
|
|
2993
3136
|
/** Preserve existing MCP names; only ordinary Pi tools need a server prefix. */
|
|
2994
3137
|
function toolBindings(context) {
|
|
2995
3138
|
const parsed = (context.tools ?? []).map((definition) => {
|
|
@@ -3047,7 +3190,7 @@ var SeatQuery = class {
|
|
|
3047
3190
|
this.deadline = setTimeout(() => {
|
|
3048
3191
|
const err = /* @__PURE__ */ new Error(`Claude seat SDK timed out waiting for ${phase}`);
|
|
3049
3192
|
err.name = "TimeoutError";
|
|
3050
|
-
log$
|
|
3193
|
+
log$19.error({
|
|
3051
3194
|
err,
|
|
3052
3195
|
phase
|
|
3053
3196
|
}, "Claude seat SDK wait deadline exceeded");
|
|
@@ -3088,10 +3231,12 @@ var SeatQuery = class {
|
|
|
3088
3231
|
async run({ sessionId, cwd }) {
|
|
3089
3232
|
const { model, context, options } = this.request;
|
|
3090
3233
|
let configDir = null;
|
|
3234
|
+
let requestProxy = null;
|
|
3091
3235
|
try {
|
|
3092
3236
|
if (!options.apiKey) throw new Error("Claude seat SDK requires a seat credential sentinel");
|
|
3093
3237
|
this.controller.signal.throwIfAborted();
|
|
3094
3238
|
configDir = await mkdtemp(path.join(os.tmpdir(), "claude-seat-sdk-"));
|
|
3239
|
+
requestProxy = await startSeatRequestProxy({ target: model.baseUrl });
|
|
3095
3240
|
this.controller.signal.throwIfAborted();
|
|
3096
3241
|
const bindings = toolBindings(context);
|
|
3097
3242
|
const servers = /* @__PURE__ */ new Map();
|
|
@@ -3186,7 +3331,7 @@ var SeatQuery = class {
|
|
|
3186
3331
|
env: buildStdioEnv({
|
|
3187
3332
|
ANTHROPIC_AUTH_TOKEN: options.apiKey,
|
|
3188
3333
|
ANTHROPIC_API_KEY: "",
|
|
3189
|
-
ANTHROPIC_BASE_URL:
|
|
3334
|
+
ANTHROPIC_BASE_URL: requestProxy.url,
|
|
3190
3335
|
ANTHROPIC_CUSTOM_HEADERS: platformHeaders({
|
|
3191
3336
|
model,
|
|
3192
3337
|
options,
|
|
@@ -3228,7 +3373,7 @@ var SeatQuery = class {
|
|
|
3228
3373
|
}
|
|
3229
3374
|
} catch (err) {
|
|
3230
3375
|
this.failure = err;
|
|
3231
|
-
if (!this.controller.signal.aborted) log$
|
|
3376
|
+
if (!this.controller.signal.aborted) log$19.error({
|
|
3232
3377
|
err,
|
|
3233
3378
|
sessionId
|
|
3234
3379
|
}, "Claude seat SDK query failed");
|
|
@@ -3237,13 +3382,14 @@ var SeatQuery = class {
|
|
|
3237
3382
|
if (this.deadline) clearTimeout(this.deadline);
|
|
3238
3383
|
this.deadline = null;
|
|
3239
3384
|
this.wake?.();
|
|
3385
|
+
requestProxy?.close();
|
|
3240
3386
|
if (configDir) try {
|
|
3241
3387
|
await rm(configDir, {
|
|
3242
3388
|
recursive: true,
|
|
3243
3389
|
force: true
|
|
3244
3390
|
});
|
|
3245
3391
|
} catch (err) {
|
|
3246
|
-
log$
|
|
3392
|
+
log$19.error({
|
|
3247
3393
|
err,
|
|
3248
3394
|
sessionId
|
|
3249
3395
|
}, "Could not remove Claude seat SDK config");
|
|
@@ -3276,7 +3422,7 @@ function mapUsage(usage) {
|
|
|
3276
3422
|
//#endregion
|
|
3277
3423
|
//#region src/extensions/claude-seat-response.ts
|
|
3278
3424
|
const toolInput = z.record(z.string(), z.unknown());
|
|
3279
|
-
const log$
|
|
3425
|
+
const log$18 = logger.child({ module: "claude-seat-sdk" });
|
|
3280
3426
|
/**
|
|
3281
3427
|
* Claude sometimes calls a tool by the name it had outside the bridge (Pi's
|
|
3282
3428
|
* own name from non-seat history, or a bare MCP tool name). Resolve those when
|
|
@@ -3290,7 +3436,7 @@ function piToolName({ name, context, sessionId }) {
|
|
|
3290
3436
|
const bare = bindings.filter((binding) => binding.toolName === name);
|
|
3291
3437
|
const [only] = bare;
|
|
3292
3438
|
if (only && bare.length === 1) return only.definition.name;
|
|
3293
|
-
log$
|
|
3439
|
+
log$18.warn({
|
|
3294
3440
|
sessionId,
|
|
3295
3441
|
toolName: name,
|
|
3296
3442
|
candidates: bare.length
|
|
@@ -3481,7 +3627,7 @@ var ModelResponse = class {
|
|
|
3481
3627
|
* each step resumes a private structured snapshot after Pi extensions run.
|
|
3482
3628
|
* Initially adapted from elidickinson/pi-claude-bridge (MIT).
|
|
3483
3629
|
*/
|
|
3484
|
-
const log$
|
|
3630
|
+
const log$17 = logger.child({ module: "claude-seat-sdk" });
|
|
3485
3631
|
const SEAT_SDK_ACTIVITY_EVENT = "claude-seat-sdk:activity";
|
|
3486
3632
|
/** Session-scoped adapter; only the flagged provider dispatches here. */
|
|
3487
3633
|
var SeatSdkBridge = class {
|
|
@@ -3532,7 +3678,7 @@ var SeatSdkBridge = class {
|
|
|
3532
3678
|
} else if (message.type === "result") {
|
|
3533
3679
|
const hasTools = response.hasTools;
|
|
3534
3680
|
if (message.is_error && !(message.subtype === "error_max_turns" && hasTools)) throw new Error("errors" in message ? message.errors.join("; ") : message.result);
|
|
3535
|
-
log$
|
|
3681
|
+
log$17.info({
|
|
3536
3682
|
sessionId: this.deps.sessionId,
|
|
3537
3683
|
queryUsage: mapUsage(message.usage),
|
|
3538
3684
|
requestUsage: response.message.usage
|
|
@@ -3553,7 +3699,7 @@ var SeatSdkBridge = class {
|
|
|
3553
3699
|
}
|
|
3554
3700
|
} catch (err) {
|
|
3555
3701
|
const reason = (seatQuery?.controller.signal.aborted || signal.aborted) && !(err instanceof Error && err.name === "TimeoutError") ? "aborted" : "error";
|
|
3556
|
-
if (reason === "error") log$
|
|
3702
|
+
if (reason === "error") log$17.error({
|
|
3557
3703
|
err,
|
|
3558
3704
|
sessionId: this.deps.sessionId
|
|
3559
3705
|
}, "Claude seat SDK response failed");
|
|
@@ -3624,7 +3770,7 @@ const HEARTBEAT_THROTTLE_MS = 6e4;
|
|
|
3624
3770
|
const TOOL_HEARTBEAT_INTERVAL_MS = 5e3;
|
|
3625
3771
|
const MAX_TOOL_HEARTBEATS = 1440 * 60 * 1e3 / TOOL_HEARTBEAT_INTERVAL_MS;
|
|
3626
3772
|
const DAEMON_URL = "http://localhost:38994";
|
|
3627
|
-
const log$
|
|
3773
|
+
const log$16 = logger.child({ module: "platform-ext" });
|
|
3628
3774
|
function sandboxClient() {
|
|
3629
3775
|
const apiUrl = apiBaseUrl();
|
|
3630
3776
|
if (!apiUrl) return null;
|
|
@@ -3692,7 +3838,7 @@ async function fetchHarnessFlags() {
|
|
|
3692
3838
|
try {
|
|
3693
3839
|
const res = await client["feature-flags"].$get();
|
|
3694
3840
|
if (!res.ok) {
|
|
3695
|
-
log$
|
|
3841
|
+
log$16.debug({
|
|
3696
3842
|
status: res.status,
|
|
3697
3843
|
event: "feature_flags_fetch_failed"
|
|
3698
3844
|
}, "feature-flags fetch failed");
|
|
@@ -3704,7 +3850,7 @@ async function fetchHarnessFlags() {
|
|
|
3704
3850
|
closingText: body.closingText ?? null
|
|
3705
3851
|
};
|
|
3706
3852
|
} catch (err) {
|
|
3707
|
-
log$
|
|
3853
|
+
log$16.debug({
|
|
3708
3854
|
err,
|
|
3709
3855
|
event: "feature_flags_fetch_error"
|
|
3710
3856
|
}, "feature-flags request errored");
|
|
@@ -3715,7 +3861,7 @@ function postHeartbeat({ messageId }) {
|
|
|
3715
3861
|
const client = sandboxClient();
|
|
3716
3862
|
if (!client) return;
|
|
3717
3863
|
client.heartbeat.$post({ json: { messageId } }).catch((err) => {
|
|
3718
|
-
log$
|
|
3864
|
+
log$16.debug({
|
|
3719
3865
|
err,
|
|
3720
3866
|
event: "heartbeat_failed"
|
|
3721
3867
|
}, "heartbeat failed");
|
|
@@ -3727,7 +3873,7 @@ async function resolveConversationFromApi(messageId) {
|
|
|
3727
3873
|
try {
|
|
3728
3874
|
const res = await client["message-conversation"].$get({ query: { messageId } });
|
|
3729
3875
|
if (!res.ok) {
|
|
3730
|
-
log$
|
|
3876
|
+
log$16.warn({
|
|
3731
3877
|
status: res.status,
|
|
3732
3878
|
messageId,
|
|
3733
3879
|
event: "resolve_conversation_failed"
|
|
@@ -3736,7 +3882,7 @@ async function resolveConversationFromApi(messageId) {
|
|
|
3736
3882
|
}
|
|
3737
3883
|
return (await res.json()).conversationId ?? null;
|
|
3738
3884
|
} catch (err) {
|
|
3739
|
-
log$
|
|
3885
|
+
log$16.warn({
|
|
3740
3886
|
err,
|
|
3741
3887
|
messageId,
|
|
3742
3888
|
event: "resolve_conversation_error"
|
|
@@ -3761,13 +3907,13 @@ async function putBackgroundTaskJournalSpec({ messageId, spec }) {
|
|
|
3761
3907
|
messageId,
|
|
3762
3908
|
spec
|
|
3763
3909
|
} });
|
|
3764
|
-
if (!res.ok) log$
|
|
3910
|
+
if (!res.ok) log$16.warn({
|
|
3765
3911
|
status: res.status,
|
|
3766
3912
|
taskId: spec.id,
|
|
3767
3913
|
event: "bg_journal_put_failed"
|
|
3768
3914
|
}, "bg-task journal PUT failed");
|
|
3769
3915
|
} catch (err) {
|
|
3770
|
-
log$
|
|
3916
|
+
log$16.warn({
|
|
3771
3917
|
err,
|
|
3772
3918
|
taskId: spec.id,
|
|
3773
3919
|
event: "bg_journal_put_failed"
|
|
@@ -3783,7 +3929,7 @@ async function deleteBackgroundTaskJournalSpec({ messageId, taskId }) {
|
|
|
3783
3929
|
taskId
|
|
3784
3930
|
} });
|
|
3785
3931
|
} catch (err) {
|
|
3786
|
-
log$
|
|
3932
|
+
log$16.debug({
|
|
3787
3933
|
err,
|
|
3788
3934
|
taskId,
|
|
3789
3935
|
event: "bg_journal_delete_failed"
|
|
@@ -3798,7 +3944,7 @@ async function listBackgroundTaskJournalSpecs({ messageId }) {
|
|
|
3798
3944
|
if (!res.ok) return [];
|
|
3799
3945
|
return (await res.json()).specs ?? [];
|
|
3800
3946
|
} catch (err) {
|
|
3801
|
-
log$
|
|
3947
|
+
log$16.debug({
|
|
3802
3948
|
err,
|
|
3803
3949
|
event: "bg_journal_list_failed"
|
|
3804
3950
|
}, "bg-task journal GET failed");
|
|
@@ -3812,7 +3958,7 @@ function postBackgroundTasksSnapshot({ messageId, tasks }) {
|
|
|
3812
3958
|
messageId,
|
|
3813
3959
|
tasks
|
|
3814
3960
|
} }).catch((err) => {
|
|
3815
|
-
log$
|
|
3961
|
+
log$16.debug({
|
|
3816
3962
|
err,
|
|
3817
3963
|
event: "bg_tasks_snapshot_failed"
|
|
3818
3964
|
}, "bg-tasks snapshot publish failed");
|
|
@@ -3910,7 +4056,7 @@ function createToolHeartbeat({ messageId }) {
|
|
|
3910
4056
|
}
|
|
3911
4057
|
heartbeatCount++;
|
|
3912
4058
|
if (heartbeatCount > MAX_TOOL_HEARTBEATS) {
|
|
3913
|
-
log$
|
|
4059
|
+
log$16.warn({
|
|
3914
4060
|
heartbeatCount,
|
|
3915
4061
|
activeToolCalls: [...activeToolCalls]
|
|
3916
4062
|
}, "tool heartbeat max reached, stopping");
|
|
@@ -3941,7 +4087,7 @@ function postToDaemon(path, body) {
|
|
|
3941
4087
|
headers: { "content-type": "application/json" },
|
|
3942
4088
|
body: JSON.stringify(body)
|
|
3943
4089
|
}).catch((err) => {
|
|
3944
|
-
log$
|
|
4090
|
+
log$16.debug({
|
|
3945
4091
|
err,
|
|
3946
4092
|
path,
|
|
3947
4093
|
event: "daemon_post_failed"
|
|
@@ -3950,7 +4096,7 @@ function postToDaemon(path, body) {
|
|
|
3950
4096
|
}
|
|
3951
4097
|
function createPlatformExtensions({ sessionId, channelContext }) {
|
|
3952
4098
|
return (pi) => {
|
|
3953
|
-
log$
|
|
4099
|
+
log$16.info({
|
|
3954
4100
|
sessionId,
|
|
3955
4101
|
hasChannelContext: Boolean(channelContext)
|
|
3956
4102
|
}, "platform extension initialized");
|
|
@@ -4004,7 +4150,7 @@ function createPlatformExtensions({ sessionId, channelContext }) {
|
|
|
4004
4150
|
});
|
|
4005
4151
|
});
|
|
4006
4152
|
pi.on("agent_end", () => {
|
|
4007
|
-
log$
|
|
4153
|
+
log$16.info({ sessionId }, "session ending");
|
|
4008
4154
|
postToDaemon("/session/end", { sessionId });
|
|
4009
4155
|
});
|
|
4010
4156
|
};
|
|
@@ -4148,7 +4294,7 @@ function createOomNeutralBashOperations({ shellPath }) {
|
|
|
4148
4294
|
* semantics; once promoted, the command inherits background-task lifecycle
|
|
4149
4295
|
* (its own controller) and the foreground kill timeout no longer applies.
|
|
4150
4296
|
*/
|
|
4151
|
-
const log$
|
|
4297
|
+
const log$15 = logger.child({ module: "background-tasks-ext" });
|
|
4152
4298
|
const ops = createOomNeutralBashOperations({ shellPath: void 0 });
|
|
4153
4299
|
const STEER_BACKGROUND_DEFAULT_SECONDS = 60;
|
|
4154
4300
|
const STEER_BACKGROUND_ENV_KEYS = ["BASH_STEER_BACKGROUND_SECONDS", "SKYDIVE_BASH_STEER_BACKGROUND_SECONDS"];
|
|
@@ -4163,7 +4309,7 @@ function steerBackgroundThresholdMs() {
|
|
|
4163
4309
|
if (raw === void 0 || raw.trim() === "") continue;
|
|
4164
4310
|
const parsed = Number(raw);
|
|
4165
4311
|
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
4166
|
-
log$
|
|
4312
|
+
log$15.warn({
|
|
4167
4313
|
envKey: key,
|
|
4168
4314
|
raw
|
|
4169
4315
|
}, "invalid BASH_STEER_BACKGROUND_SECONDS, using default");
|
|
@@ -4192,7 +4338,7 @@ async function notifyBashSteerArrival(args) {
|
|
|
4192
4338
|
try {
|
|
4193
4339
|
await listener();
|
|
4194
4340
|
} catch (err) {
|
|
4195
|
-
log$
|
|
4341
|
+
log$15.error({
|
|
4196
4342
|
err,
|
|
4197
4343
|
sessionId: args.sessionId
|
|
4198
4344
|
}, "bash steer promotion failed");
|
|
@@ -4287,14 +4433,14 @@ function watchdogTick(now) {
|
|
|
4287
4433
|
const overSize = meta.logBytes > MAX_LOG_BYTES;
|
|
4288
4434
|
if (!overRuntime && !overSize) continue;
|
|
4289
4435
|
const reason = overSize ? `output exceeded ${MAX_LOG_BYTES / (1024 * 1024)}MiB` : `exceeded ${KEEPALIVE_MAX_MS / 6e4}m max runtime`;
|
|
4290
|
-
log$
|
|
4436
|
+
log$15.warn({
|
|
4291
4437
|
taskId: meta.id,
|
|
4292
4438
|
reason
|
|
4293
4439
|
}, "watchdog killing bg task");
|
|
4294
4440
|
try {
|
|
4295
4441
|
killTask(meta, reason);
|
|
4296
4442
|
} catch (err) {
|
|
4297
|
-
log$
|
|
4443
|
+
log$15.warn({
|
|
4298
4444
|
err,
|
|
4299
4445
|
taskId: meta.id
|
|
4300
4446
|
}, "watchdog kill failed");
|
|
@@ -4353,7 +4499,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
|
|
|
4353
4499
|
const now = Date.now();
|
|
4354
4500
|
const promotable = [...foregroundBash.values()].filter((call) => now - call.startedAt >= thresholdMs);
|
|
4355
4501
|
if (promotable.length === 0) return;
|
|
4356
|
-
log$
|
|
4502
|
+
log$15.info({
|
|
4357
4503
|
event: "bash_steer_promotion",
|
|
4358
4504
|
count: promotable.length,
|
|
4359
4505
|
thresholdSeconds: Math.round(thresholdMs / 1e3),
|
|
@@ -4378,7 +4524,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
|
|
|
4378
4524
|
try {
|
|
4379
4525
|
await mkdir(tasksDir(), { recursive: true });
|
|
4380
4526
|
} catch (err) {
|
|
4381
|
-
log$
|
|
4527
|
+
log$15.error({ err }, "bg task adopt: mkdir failed");
|
|
4382
4528
|
}
|
|
4383
4529
|
const logStream = createWriteStream(logPath(id), { flags: "a" });
|
|
4384
4530
|
logStream.on("error", () => {});
|
|
@@ -4405,7 +4551,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
|
|
|
4405
4551
|
tasks.set(id, meta);
|
|
4406
4552
|
ensureWatchdog();
|
|
4407
4553
|
schedulePublishSnapshot();
|
|
4408
|
-
log$
|
|
4554
|
+
log$15.info({
|
|
4409
4555
|
taskId: id,
|
|
4410
4556
|
conversationId,
|
|
4411
4557
|
startedAt: args.startedAt
|
|
@@ -4558,7 +4704,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
|
|
|
4558
4704
|
try {
|
|
4559
4705
|
shellPath = SettingsManager.create(ctx.cwd, getAgentDir()).getShellPath();
|
|
4560
4706
|
} catch (err) {
|
|
4561
|
-
log$
|
|
4707
|
+
log$15.warn({
|
|
4562
4708
|
err,
|
|
4563
4709
|
cwd: ctx.cwd
|
|
4564
4710
|
}, "bash steer promotion: shell settings unavailable, using default shell");
|
|
@@ -4573,7 +4719,7 @@ function createBackgroundTasksExtension({ channelContext, sessionId }) {
|
|
|
4573
4719
|
...definition,
|
|
4574
4720
|
description: `${definition.description}\n\nLong-running bash commands are automatically moved to a background task when a new message arrives while the command has already been running for at least a minute: you get the task id immediately, are woken on completion, and must not depend on the command's output until that wake arrives. Shorter commands finish in the foreground like they always have.`
|
|
4575
4721
|
});
|
|
4576
|
-
log$
|
|
4722
|
+
log$15.info({
|
|
4577
4723
|
event: "bash_steer_promotion_enabled",
|
|
4578
4724
|
thresholdSeconds: Math.round(thresholdMs / 1e3)
|
|
4579
4725
|
}, "supervised bash tool registered (steer-triggered backgrounding)");
|
|
@@ -4616,7 +4762,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4616
4762
|
triggerTurn: true,
|
|
4617
4763
|
deliverAs: "followUp"
|
|
4618
4764
|
});
|
|
4619
|
-
log$
|
|
4765
|
+
log$15.info({
|
|
4620
4766
|
taskId: meta.id,
|
|
4621
4767
|
conversationId
|
|
4622
4768
|
}, "bg task completion delivered live (followUp)");
|
|
@@ -4624,7 +4770,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4624
4770
|
}
|
|
4625
4771
|
if (meta.messageId) {
|
|
4626
4772
|
meta.notified = true;
|
|
4627
|
-
log$
|
|
4773
|
+
log$15.info({
|
|
4628
4774
|
taskId: meta.id,
|
|
4629
4775
|
messageId: meta.messageId
|
|
4630
4776
|
}, "posting idle bg-task-done wake");
|
|
@@ -4634,12 +4780,12 @@ or if you were explicitly waiting to report it.`,
|
|
|
4634
4780
|
content: message.content
|
|
4635
4781
|
}).catch((err) => {
|
|
4636
4782
|
meta.notified = false;
|
|
4637
|
-
log$
|
|
4783
|
+
log$15.warn({
|
|
4638
4784
|
err,
|
|
4639
4785
|
taskId: meta.id
|
|
4640
4786
|
}, "bg-task-done wake failed; will retry at next session_start");
|
|
4641
4787
|
});
|
|
4642
|
-
} else log$
|
|
4788
|
+
} else log$15.info({ taskId: meta.id }, "bg task completed idle with no origin message; deferring to next session_start");
|
|
4643
4789
|
}
|
|
4644
4790
|
const SNAPSHOT_TAIL_LINES = 40;
|
|
4645
4791
|
let lastPublishedSignature = null;
|
|
@@ -4676,7 +4822,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4676
4822
|
tasks: snapshot
|
|
4677
4823
|
});
|
|
4678
4824
|
} catch (err) {
|
|
4679
|
-
log$
|
|
4825
|
+
log$15.debug({
|
|
4680
4826
|
err,
|
|
4681
4827
|
event: "bg_tasks_snapshot_build_failed"
|
|
4682
4828
|
}, "building bg-tasks snapshot failed");
|
|
@@ -4719,7 +4865,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4719
4865
|
logStream.end();
|
|
4720
4866
|
await finished(logStream).catch(() => {});
|
|
4721
4867
|
meta.running = false;
|
|
4722
|
-
log$
|
|
4868
|
+
log$15.info({
|
|
4723
4869
|
taskId: meta.id,
|
|
4724
4870
|
exitCode: meta.exitCode
|
|
4725
4871
|
}, "bg task finished");
|
|
@@ -4736,14 +4882,14 @@ or if you were explicitly waiting to report it.`,
|
|
|
4736
4882
|
try {
|
|
4737
4883
|
await mkdir(tasksDir(), { recursive: true });
|
|
4738
4884
|
} catch (err) {
|
|
4739
|
-
log$
|
|
4885
|
+
log$15.error({
|
|
4740
4886
|
err,
|
|
4741
4887
|
taskId: id
|
|
4742
4888
|
}, "background task dir unavailable");
|
|
4743
4889
|
}
|
|
4744
4890
|
const logStream = createWriteStream(logPath(id), { flags: "a" });
|
|
4745
4891
|
logStream.on("error", (err) => {
|
|
4746
|
-
log$
|
|
4892
|
+
log$15.warn({
|
|
4747
4893
|
err,
|
|
4748
4894
|
taskId: id
|
|
4749
4895
|
}, "bg task log write failed");
|
|
@@ -4793,7 +4939,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4793
4939
|
}).catch((err) => {
|
|
4794
4940
|
if (!meta.controller.signal.aborted) {
|
|
4795
4941
|
meta.error = err instanceof Error ? err.message : String(err);
|
|
4796
|
-
log$
|
|
4942
|
+
log$15.warn({
|
|
4797
4943
|
err,
|
|
4798
4944
|
taskId: id
|
|
4799
4945
|
}, "bg task exec error");
|
|
@@ -4802,7 +4948,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4802
4948
|
await finishTask(meta, logStream);
|
|
4803
4949
|
});
|
|
4804
4950
|
ensureWatchdog();
|
|
4805
|
-
log$
|
|
4951
|
+
log$15.info({
|
|
4806
4952
|
taskId: id,
|
|
4807
4953
|
conversationId
|
|
4808
4954
|
}, "bg task started");
|
|
@@ -4821,7 +4967,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4821
4967
|
for (const spec of specs) {
|
|
4822
4968
|
const live = tasks.get(spec.id);
|
|
4823
4969
|
if (live && sameScope(live, scopeKey())) continue;
|
|
4824
|
-
log$
|
|
4970
|
+
log$15.info({
|
|
4825
4971
|
taskId: spec.id,
|
|
4826
4972
|
conversationId
|
|
4827
4973
|
}, "relaunching journaled resumable bg task after restart");
|
|
@@ -4839,7 +4985,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4839
4985
|
stream.write(`<resumed-after-restart>requeued and relaunched on a new sandbox after the previous one was drained; this is a fresh execution of the command from the start, not a continuation</resumed-after-restart>\n`);
|
|
4840
4986
|
stream.end();
|
|
4841
4987
|
} catch (err) {
|
|
4842
|
-
log$
|
|
4988
|
+
log$15.debug({
|
|
4843
4989
|
err,
|
|
4844
4990
|
taskId: meta.id
|
|
4845
4991
|
}, "resume banner write failed");
|
|
@@ -4859,7 +5005,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
4859
5005
|
meta.notified = true;
|
|
4860
5006
|
pi.sendMessage(await taskDoneMessage(meta));
|
|
4861
5007
|
}
|
|
4862
|
-
if (unnotified.length > 0) log$
|
|
5008
|
+
if (unnotified.length > 0) log$15.info({
|
|
4863
5009
|
conversationId,
|
|
4864
5010
|
count: unnotified.length
|
|
4865
5011
|
}, "injected completed bg tasks at session_start");
|
|
@@ -5054,7 +5200,7 @@ or if you were explicitly waiting to report it.`,
|
|
|
5054
5200
|
* read on the hot path before every LLM call), it falls back to the default
|
|
5055
5201
|
* for that knob and logs once.
|
|
5056
5202
|
*/
|
|
5057
|
-
const log$
|
|
5203
|
+
const log$14 = logger.child({ module: "context-management-config" });
|
|
5058
5204
|
const DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
|
|
5059
5205
|
enabled: false,
|
|
5060
5206
|
perResultMaxBytes: 16 * 1024,
|
|
@@ -5099,7 +5245,7 @@ function resolveContextManagementConfig(env = process.env) {
|
|
|
5099
5245
|
clearAtLeastTokens: env.SKYDIVE_CTX_CLEAR_AT_LEAST_TOKENS
|
|
5100
5246
|
});
|
|
5101
5247
|
if (!parsed.success) {
|
|
5102
|
-
log$
|
|
5248
|
+
log$14.warn({
|
|
5103
5249
|
event: "context_management_config_invalid",
|
|
5104
5250
|
err: parsed.error
|
|
5105
5251
|
}, "falling back to default context-management config");
|
|
@@ -5183,7 +5329,7 @@ function hasFlagSource(env = process.env) {
|
|
|
5183
5329
|
* alive and an indeterminate result (no api url / transient failure) leaves the
|
|
5184
5330
|
* last-known values untouched so a blip can't silently flip behavior.
|
|
5185
5331
|
*/
|
|
5186
|
-
const log$
|
|
5332
|
+
const log$13 = logger.child({ module: "feature-flags-poll" });
|
|
5187
5333
|
const FLAG_POLL_INTERVAL_MS = 6e4;
|
|
5188
5334
|
let contextManagement = null;
|
|
5189
5335
|
let closingText = null;
|
|
@@ -5223,7 +5369,7 @@ function apply(name, next) {
|
|
|
5223
5369
|
if (next !== prev) for (const cb of subscribers[name]) try {
|
|
5224
5370
|
cb(next);
|
|
5225
5371
|
} catch (err) {
|
|
5226
|
-
log$
|
|
5372
|
+
log$13.warn({
|
|
5227
5373
|
err,
|
|
5228
5374
|
flag: name
|
|
5229
5375
|
}, "flag subscriber threw");
|
|
@@ -5236,7 +5382,7 @@ async function pollOnce() {
|
|
|
5236
5382
|
apply("contextManagement", flags.contextManagement ?? null);
|
|
5237
5383
|
apply("closingText", flags.closingText ?? null);
|
|
5238
5384
|
} catch (err) {
|
|
5239
|
-
log$
|
|
5385
|
+
log$13.debug({ err }, "feature-flag poll threw");
|
|
5240
5386
|
}
|
|
5241
5387
|
}
|
|
5242
5388
|
/**
|
|
@@ -5437,8 +5583,8 @@ const bashDefaultTimeoutExtension = (pi) => {
|
|
|
5437
5583
|
* stat and the extension warns on what it can see — it must never break a
|
|
5438
5584
|
* turn over an observability feature.
|
|
5439
5585
|
*/
|
|
5440
|
-
const execFileAsync = promisify(execFile);
|
|
5441
|
-
const log$
|
|
5586
|
+
const execFileAsync$1 = promisify(execFile);
|
|
5587
|
+
const log$12 = logger.child({ module: "resource-pressure-warning" });
|
|
5442
5588
|
const POLL_INTERVAL_MS = 1e4;
|
|
5443
5589
|
function envOverride(name) {
|
|
5444
5590
|
for (const prefix of ["SKYDIVE_", "ANYONE_"]) {
|
|
@@ -5506,7 +5652,7 @@ async function readMemUsePct() {
|
|
|
5506
5652
|
*/
|
|
5507
5653
|
async function readDiskUsePct() {
|
|
5508
5654
|
try {
|
|
5509
|
-
const { stdout } = await execFileAsync("df", ["-P", diskRoot()]);
|
|
5655
|
+
const { stdout } = await execFileAsync$1("df", ["-P", diskRoot()]);
|
|
5510
5656
|
const dataRow = stdout.trim().split("\n")[1];
|
|
5511
5657
|
if (dataRow == null) return null;
|
|
5512
5658
|
const capacity = dataRow.trim().split(/\s+/)[4];
|
|
@@ -5635,7 +5781,7 @@ const resourcePressureWarningExtension = (pi) => {
|
|
|
5635
5781
|
warnedDiskThisTurn = true;
|
|
5636
5782
|
}
|
|
5637
5783
|
if (trigger === null) return;
|
|
5638
|
-
log$
|
|
5784
|
+
log$12.warn({
|
|
5639
5785
|
trigger,
|
|
5640
5786
|
mem,
|
|
5641
5787
|
cpuPct,
|
|
@@ -5673,7 +5819,7 @@ const resourcePressureWarningExtension = (pi) => {
|
|
|
5673
5819
|
if (!timer) {
|
|
5674
5820
|
timer = setInterval(() => {
|
|
5675
5821
|
checkOnce().catch((err) => {
|
|
5676
|
-
log$
|
|
5822
|
+
log$12.error({ err }, "resource pressure check failed");
|
|
5677
5823
|
});
|
|
5678
5824
|
}, POLL_INTERVAL_MS);
|
|
5679
5825
|
timer.unref?.();
|
|
@@ -5689,7 +5835,7 @@ const resourcePressureWarningExtension = (pi) => {
|
|
|
5689
5835
|
};
|
|
5690
5836
|
//#endregion
|
|
5691
5837
|
//#region src/extensions/disk-guard.ts
|
|
5692
|
-
const log$
|
|
5838
|
+
const log$11 = logger.child({ module: "disk-guard" });
|
|
5693
5839
|
/**
|
|
5694
5840
|
* In-band bypass. The guard is a safety net, not a jail: when the agent knows
|
|
5695
5841
|
* a flagged command is genuinely safe (writing to a different mount, a tiny
|
|
@@ -5829,7 +5975,7 @@ const diskGuardExtension = (pi) => {
|
|
|
5829
5975
|
if (!isSpaceHungryCommand(command)) return;
|
|
5830
5976
|
const diskPct = await readDiskUsePct();
|
|
5831
5977
|
if (!shouldBlockForDisk(command, diskPct)) return;
|
|
5832
|
-
log$
|
|
5978
|
+
log$11.warn({
|
|
5833
5979
|
diskPct,
|
|
5834
5980
|
command: command.slice(0, 200)
|
|
5835
5981
|
}, "blocked space-hungry bash command on near-full disk");
|
|
@@ -5841,7 +5987,7 @@ const diskGuardExtension = (pi) => {
|
|
|
5841
5987
|
};
|
|
5842
5988
|
//#endregion
|
|
5843
5989
|
//#region src/extensions/noop-loop-guard.ts
|
|
5844
|
-
const log$
|
|
5990
|
+
const log$10 = logger.child({ module: "noop-loop-guard" });
|
|
5845
5991
|
/** Length of the rolling window that counts silence commands across streak resets. */
|
|
5846
5992
|
const SILENCE_WINDOW_MS = 300 * 1e3;
|
|
5847
5993
|
/** Bare shell no-op: `true` or `:` (case-insensitive). */
|
|
@@ -5996,7 +6142,7 @@ const noopLoopGuardExtension = (pi) => {
|
|
|
5996
6142
|
if (bypassed) return;
|
|
5997
6143
|
if (streak < 3 && windowCount < 8) return;
|
|
5998
6144
|
const aborted = streak >= 25 || windowCount >= 40;
|
|
5999
|
-
log$
|
|
6145
|
+
log$10.warn({
|
|
6000
6146
|
streak,
|
|
6001
6147
|
windowCount,
|
|
6002
6148
|
aborted,
|
|
@@ -6015,7 +6161,7 @@ const noopLoopGuardExtension = (pi) => {
|
|
|
6015
6161
|
};
|
|
6016
6162
|
//#endregion
|
|
6017
6163
|
//#region src/extensions/repeat-call-guard.ts
|
|
6018
|
-
const log$
|
|
6164
|
+
const log$9 = logger.child({ module: "repeat-call-guard" });
|
|
6019
6165
|
const KILL_SWITCH_KEYS = ["REPEAT_CALL_GUARD_DISABLE", "SKYDIVE_REPEAT_CALL_GUARD_DISABLE"];
|
|
6020
6166
|
function guardDisabledByEnv$1() {
|
|
6021
6167
|
return KILL_SWITCH_KEYS.some((key) => {
|
|
@@ -6060,7 +6206,7 @@ const repeatCallGuardExtension = (pi) => {
|
|
|
6060
6206
|
}));
|
|
6061
6207
|
if (streak < 20) return;
|
|
6062
6208
|
const aborted = streak >= 40;
|
|
6063
|
-
log$
|
|
6209
|
+
log$9.warn({
|
|
6064
6210
|
toolName: event.toolName,
|
|
6065
6211
|
streak,
|
|
6066
6212
|
aborted,
|
|
@@ -6127,7 +6273,7 @@ const repeatCallGuardExtension = (pi) => {
|
|
|
6127
6273
|
* embedding a script).
|
|
6128
6274
|
*/
|
|
6129
6275
|
const execFileP = promisify(execFile);
|
|
6130
|
-
const log$
|
|
6276
|
+
const log$8 = logger.child({ module: "sleep-guard" });
|
|
6131
6277
|
/** How long the `platform automation create` call may take before we fall back to guidance. */
|
|
6132
6278
|
const SCHEDULE_TIMEOUT_MS = 15e3;
|
|
6133
6279
|
/** Title for the one-shot wakes this guard schedules. Visible in the Routines UI. */
|
|
@@ -6371,7 +6517,7 @@ async function scheduleSleepWake(seconds, ledger) {
|
|
|
6371
6517
|
], { timeout: SCHEDULE_TIMEOUT_MS });
|
|
6372
6518
|
return at;
|
|
6373
6519
|
} catch (err) {
|
|
6374
|
-
log$
|
|
6520
|
+
log$8.warn({ err }, "failed to auto-schedule sleep wake; falling back to guidance");
|
|
6375
6521
|
return null;
|
|
6376
6522
|
}
|
|
6377
6523
|
}
|
|
@@ -6392,7 +6538,7 @@ const sleepGuardExtension = (pi) => {
|
|
|
6392
6538
|
if (typeof command !== "string" || command.length === 0) return;
|
|
6393
6539
|
const violation = shouldBlockForSleep(command);
|
|
6394
6540
|
if (!violation) return;
|
|
6395
|
-
log$
|
|
6541
|
+
log$8.warn({
|
|
6396
6542
|
seconds: violation.seconds,
|
|
6397
6543
|
leading: violation.leading,
|
|
6398
6544
|
unboundedLoop: violation.unboundedLoop,
|
|
@@ -6401,7 +6547,7 @@ const sleepGuardExtension = (pi) => {
|
|
|
6401
6547
|
if (!violation.unboundedLoop && violation.seconds <= 86400 && isPureSleepCommand(blankQuotedRegions(command))) {
|
|
6402
6548
|
const at = await scheduleSleepWake(violation.seconds, wakeLedger);
|
|
6403
6549
|
if (at) {
|
|
6404
|
-
log$
|
|
6550
|
+
log$8.info({
|
|
6405
6551
|
at,
|
|
6406
6552
|
seconds: violation.seconds
|
|
6407
6553
|
}, "auto-scheduled sleep wake");
|
|
@@ -6509,7 +6655,7 @@ function transformContextMessages(messages, config, now) {
|
|
|
6509
6655
|
}
|
|
6510
6656
|
//#endregion
|
|
6511
6657
|
//#region src/extensions/context-management.ts
|
|
6512
|
-
const log$
|
|
6658
|
+
const log$7 = logger.child({ module: "context-management-extension" });
|
|
6513
6659
|
function isAnthropicMessagesPayload(payload) {
|
|
6514
6660
|
if (typeof payload !== "object" || payload === null) return false;
|
|
6515
6661
|
const candidate = payload;
|
|
@@ -6574,13 +6720,13 @@ function createContextManagementExtension() {
|
|
|
6574
6720
|
setContextManagementFlagOverride(getPolledFlag("contextManagement"));
|
|
6575
6721
|
onFlagChange("contextManagement", (enabled) => {
|
|
6576
6722
|
setContextManagementFlagOverride(enabled);
|
|
6577
|
-
log$
|
|
6723
|
+
log$7.info({
|
|
6578
6724
|
event: "context_management_flag_update",
|
|
6579
6725
|
enabled
|
|
6580
6726
|
}, "context-management flag updated from platform");
|
|
6581
6727
|
});
|
|
6582
6728
|
startFeatureFlagPoller();
|
|
6583
|
-
log$
|
|
6729
|
+
log$7.info({
|
|
6584
6730
|
event: "context_management_registered",
|
|
6585
6731
|
enabled: initial.enabled,
|
|
6586
6732
|
flagSource: hasFlagSource(),
|
|
@@ -6592,13 +6738,13 @@ function createContextManagementExtension() {
|
|
|
6592
6738
|
const { messages } = event;
|
|
6593
6739
|
try {
|
|
6594
6740
|
const result = transformContextIfEnabled(messages, getContextManagementConfig(), Date.now());
|
|
6595
|
-
if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$
|
|
6741
|
+
if (result.stats && (result.stats.clearedResults > 0 || result.stats.trimmedResults > 0)) log$7.info({
|
|
6596
6742
|
event: "context_management_applied",
|
|
6597
6743
|
...result.stats
|
|
6598
6744
|
}, "trimmed/cleared tool output before LLM call");
|
|
6599
6745
|
return { messages: result.messages };
|
|
6600
6746
|
} catch (err) {
|
|
6601
|
-
log$
|
|
6747
|
+
log$7.error({
|
|
6602
6748
|
err,
|
|
6603
6749
|
event: "context_management_transform_failed"
|
|
6604
6750
|
}, "context transform failed; passing messages through unchanged");
|
|
@@ -6610,7 +6756,7 @@ function createContextManagementExtension() {
|
|
|
6610
6756
|
}
|
|
6611
6757
|
//#endregion
|
|
6612
6758
|
//#region src/extensions/current-time.ts
|
|
6613
|
-
const log$
|
|
6759
|
+
const log$6 = logger.child({ module: "current-time-extension" });
|
|
6614
6760
|
const PI_DATE_LINE = /^Current date:.*$/m;
|
|
6615
6761
|
function formatCurrentTimeLine(now) {
|
|
6616
6762
|
return `Current date: ${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")} (${new Intl.DateTimeFormat("en-US", {
|
|
@@ -6623,7 +6769,7 @@ const currentTimeExtension = (pi) => {
|
|
|
6623
6769
|
const line = formatCurrentTimeLine(/* @__PURE__ */ new Date());
|
|
6624
6770
|
const base = event.systemPrompt;
|
|
6625
6771
|
if (PI_DATE_LINE.test(base)) {
|
|
6626
|
-
log$
|
|
6772
|
+
log$6.info({ event: "pi_date_line_present" }, "pi base prompt carries its own 'Current date:' line again; replacing it in place (pi prompt format may have changed)");
|
|
6627
6773
|
return { systemPrompt: base.replace(PI_DATE_LINE, line) };
|
|
6628
6774
|
}
|
|
6629
6775
|
return { systemPrompt: `${base}\n${line}` };
|
|
@@ -7011,7 +7157,7 @@ async function migrateMemory({ cwd }) {
|
|
|
7011
7157
|
}
|
|
7012
7158
|
//#endregion
|
|
7013
7159
|
//#region src/extensions/memory.ts
|
|
7014
|
-
const log$
|
|
7160
|
+
const log$5 = logger.child({ module: "memory-extension" });
|
|
7015
7161
|
/**
|
|
7016
7162
|
* The standing instructions for the memory system. Always injected (even with
|
|
7017
7163
|
* no `MEMORY.md`) so the agent knows it can persist notes and how. `users/` is
|
|
@@ -7048,13 +7194,13 @@ const memoryExtension = (pi) => {
|
|
|
7048
7194
|
pi.on("session_start", async (_event, ctx) => {
|
|
7049
7195
|
try {
|
|
7050
7196
|
const migrated = await migrateMemory({ cwd: ctx.cwd });
|
|
7051
|
-
if (migrated !== null) log$
|
|
7197
|
+
if (migrated !== null) log$5.info({
|
|
7052
7198
|
event: "memory_migrated",
|
|
7053
7199
|
from: migrated.from,
|
|
7054
7200
|
to: migrated.to
|
|
7055
7201
|
}, "migrated memory layout to current version");
|
|
7056
7202
|
} catch (err) {
|
|
7057
|
-
log$
|
|
7203
|
+
log$5.warn({
|
|
7058
7204
|
err,
|
|
7059
7205
|
event: "memory_migration_failed"
|
|
7060
7206
|
}, "memory migration failed; continuing with existing index");
|
|
@@ -7066,7 +7212,7 @@ const memoryExtension = (pi) => {
|
|
|
7066
7212
|
index
|
|
7067
7213
|
});
|
|
7068
7214
|
} catch (err) {
|
|
7069
|
-
log$
|
|
7215
|
+
log$5.warn({
|
|
7070
7216
|
err,
|
|
7071
7217
|
event: "memory_index_failed"
|
|
7072
7218
|
}, "memory index read failed; injecting instructions only");
|
|
@@ -7080,7 +7226,7 @@ const memoryExtension = (pi) => {
|
|
|
7080
7226
|
};
|
|
7081
7227
|
//#endregion
|
|
7082
7228
|
//#region src/extensions/platform-memory.ts
|
|
7083
|
-
const log$
|
|
7229
|
+
const log$4 = logger.child({ module: "platform-memory-extension" });
|
|
7084
7230
|
/**
|
|
7085
7231
|
* Resolve the human on this turn via the API, keyed by the message id.
|
|
7086
7232
|
* `/sandbox/channel-context` only returns a sender for a platform-known
|
|
@@ -7093,13 +7239,13 @@ const log$3 = logger.child({ module: "platform-memory-extension" });
|
|
|
7093
7239
|
async function resolveTurnUser(messageId) {
|
|
7094
7240
|
const client = sandboxClient();
|
|
7095
7241
|
if (!client) {
|
|
7096
|
-
log$
|
|
7242
|
+
log$4.debug({ event: "resolve_turn_user_no_api_url" }, "no API url in env; withholding user memory");
|
|
7097
7243
|
return null;
|
|
7098
7244
|
}
|
|
7099
7245
|
try {
|
|
7100
7246
|
const res = await client["channel-context"].$get({ query: { messageId } });
|
|
7101
7247
|
if (!res.ok) {
|
|
7102
|
-
log$
|
|
7248
|
+
log$4.warn({
|
|
7103
7249
|
event: "resolve_turn_user_failed",
|
|
7104
7250
|
status: res.status
|
|
7105
7251
|
}, "channel-context returned non-ok; withholding user memory");
|
|
@@ -7112,7 +7258,7 @@ async function resolveTurnUser(messageId) {
|
|
|
7112
7258
|
displayName: sender.displayName
|
|
7113
7259
|
};
|
|
7114
7260
|
} catch (err) {
|
|
7115
|
-
log$
|
|
7261
|
+
log$4.warn({
|
|
7116
7262
|
err,
|
|
7117
7263
|
event: "resolve_turn_user_failed"
|
|
7118
7264
|
}, "failed to resolve current user; withholding user memory");
|
|
@@ -7159,7 +7305,7 @@ function createPlatformMemoryExtension({ channelContext }) {
|
|
|
7159
7305
|
user
|
|
7160
7306
|
});
|
|
7161
7307
|
} catch (err) {
|
|
7162
|
-
log$
|
|
7308
|
+
log$4.warn({
|
|
7163
7309
|
err,
|
|
7164
7310
|
event: "user_memory_index_failed"
|
|
7165
7311
|
}, "user memory index build failed; skipping injection");
|
|
@@ -7191,7 +7337,7 @@ const providerApiCompatExtension = (pi) => {
|
|
|
7191
7337
|
};
|
|
7192
7338
|
//#endregion
|
|
7193
7339
|
//#region src/extensions/self-trace.ts
|
|
7194
|
-
const log$
|
|
7340
|
+
const log$3 = logger.child({ module: "self-trace-extension" });
|
|
7195
7341
|
/**
|
|
7196
7342
|
* Reports the agent's own execution as OpenTelemetry spans:
|
|
7197
7343
|
* agent.session → agent.run → agent.turn.N → tool.NAME, with token/cost
|
|
@@ -7216,7 +7362,7 @@ const selfTraceExtension = (pi) => {
|
|
|
7216
7362
|
sessionSpan = tracer.startSpan("agent.session", { attributes: { "agent.model": modelId } }, remoteCtx);
|
|
7217
7363
|
sessionCtx = trace.setSpan(remoteCtx, sessionSpan);
|
|
7218
7364
|
const sc = sessionSpan.spanContext();
|
|
7219
|
-
log$
|
|
7365
|
+
log$3.info({
|
|
7220
7366
|
event: "self_trace_session_start",
|
|
7221
7367
|
trace_id: sc.traceId,
|
|
7222
7368
|
span_id: sc.spanId,
|
|
@@ -7328,13 +7474,13 @@ const selfTraceExtension = (pi) => {
|
|
|
7328
7474
|
* Lives in the harness package — soul.md is content from the agent's
|
|
7329
7475
|
* own git repo, not from the platform — so its handling stays here.
|
|
7330
7476
|
*/
|
|
7331
|
-
const log$
|
|
7477
|
+
const log$2 = logger.child({ module: "soul-extension" });
|
|
7332
7478
|
async function readSoul(cwd) {
|
|
7333
7479
|
try {
|
|
7334
7480
|
return (await readFile(join(cwd, "soul.md"), "utf8")).trim() || null;
|
|
7335
7481
|
} catch (err) {
|
|
7336
7482
|
if (err?.code === "ENOENT") return null;
|
|
7337
|
-
log$
|
|
7483
|
+
log$2.warn({
|
|
7338
7484
|
err,
|
|
7339
7485
|
event: "soul_read_failed"
|
|
7340
7486
|
}, "soul.md read failed");
|
|
@@ -7366,7 +7512,7 @@ const soulExtension = (pi) => {
|
|
|
7366
7512
|
};
|
|
7367
7513
|
//#endregion
|
|
7368
7514
|
//#region src/extensions/subagent/index.ts
|
|
7369
|
-
const log = logger.child({ module: "subagent-ext" });
|
|
7515
|
+
const log$1 = logger.child({ module: "subagent-ext" });
|
|
7370
7516
|
const MAX_TASKS = 8;
|
|
7371
7517
|
const SpawnTaskItem = Type.Object({
|
|
7372
7518
|
task: Type.String({ description: "The task to delegate to a subagent run." }),
|
|
@@ -7466,7 +7612,7 @@ function buildTool(messageId) {
|
|
|
7466
7612
|
};
|
|
7467
7613
|
} catch (err) {
|
|
7468
7614
|
const message = err instanceof Error ? err.message : String(err);
|
|
7469
|
-
log.warn({
|
|
7615
|
+
log$1.warn({
|
|
7470
7616
|
err,
|
|
7471
7617
|
event: "subagent_rearm_failed",
|
|
7472
7618
|
taskId: task.taskId
|
|
@@ -7479,7 +7625,7 @@ function buildTool(messageId) {
|
|
|
7479
7625
|
}
|
|
7480
7626
|
}));
|
|
7481
7627
|
const { taskIds } = spawned;
|
|
7482
|
-
log.info({
|
|
7628
|
+
log$1.info({
|
|
7483
7629
|
event: "subagent_spawned",
|
|
7484
7630
|
count: taskIds.length
|
|
7485
7631
|
}, "subagent tasks queued");
|
|
@@ -7510,7 +7656,7 @@ function buildTool(messageId) {
|
|
|
7510
7656
|
};
|
|
7511
7657
|
} catch (err) {
|
|
7512
7658
|
const message = err instanceof Error ? err.message : String(err);
|
|
7513
|
-
log.warn({
|
|
7659
|
+
log$1.warn({
|
|
7514
7660
|
err,
|
|
7515
7661
|
event: "subagent_spawn_failed"
|
|
7516
7662
|
}, "subagent request failed");
|
|
@@ -7541,7 +7687,7 @@ function createSubagentExtension({ channelContext }) {
|
|
|
7541
7687
|
if (registered) return;
|
|
7542
7688
|
registered = true;
|
|
7543
7689
|
pi.registerTool(buildTool(messageId));
|
|
7544
|
-
log.info({ event: "subagent_enabled" }, "subagent tool registered");
|
|
7690
|
+
log$1.info({ event: "subagent_enabled" }, "subagent tool registered");
|
|
7545
7691
|
};
|
|
7546
7692
|
pi.on("session_start", () => {
|
|
7547
7693
|
registerOnce();
|
|
@@ -7549,6 +7695,125 @@ function createSubagentExtension({ channelContext }) {
|
|
|
7549
7695
|
};
|
|
7550
7696
|
}
|
|
7551
7697
|
//#endregion
|
|
7698
|
+
//#region src/extensions/template-build-push.ts
|
|
7699
|
+
/**
|
|
7700
|
+
* Same-turn notice that a push started a template build.
|
|
7701
|
+
*
|
|
7702
|
+
* An agent's `Dockerfile` / `install.sh` / lockfiles are BAKED: changing one
|
|
7703
|
+
* does not take effect when the file is written, nor when it is pushed, but
|
|
7704
|
+
* when a template build of that commit succeeds — minutes later, out of band,
|
|
7705
|
+
* with no result delivered anywhere the agent looks. So an agent edits its
|
|
7706
|
+
* Dockerfile, pushes, sees a clean `git push`, and reasonably concludes it is
|
|
7707
|
+
* done. If that build fails, it will go on answering from the last image that
|
|
7708
|
+
* built, and every later commit fails the same way.
|
|
7709
|
+
*
|
|
7710
|
+
* This closes the gap at the only moment the agent still has full context for
|
|
7711
|
+
* why it touched those files: the push itself. The notice appends one line to
|
|
7712
|
+
* the push's own tool result pointing at `platform builds wait`. It does not
|
|
7713
|
+
* block, does not wait for the build, and adds no request — it is a string
|
|
7714
|
+
* append onto a result that has already returned.
|
|
7715
|
+
*
|
|
7716
|
+
* Deliberately narrow: only a push whose diff touches a baked path says
|
|
7717
|
+
* anything. A push of ordinary code is not waiting on a build and must stay
|
|
7718
|
+
* silent, or the line becomes background noise that gets skimmed past.
|
|
7719
|
+
*
|
|
7720
|
+
* Best-effort throughout. Any failure to read the range or the diff leaves
|
|
7721
|
+
* the tool result exactly as it was — this is a hint, and a hint must never
|
|
7722
|
+
* be able to break a push.
|
|
7723
|
+
*/
|
|
7724
|
+
const execFileAsync = promisify(execFile);
|
|
7725
|
+
const log = logger.child({ module: "template-build-push" });
|
|
7726
|
+
/**
|
|
7727
|
+
* Repo paths whose contents are baked into the template image.
|
|
7728
|
+
*
|
|
7729
|
+
* MUST stay identical to `BAKED_BUILD_PATHS` in
|
|
7730
|
+
* `apps/anyone/agent-lifecycle/src/agentPush.ts`, which is what the server
|
|
7731
|
+
* actually classifies pushes with. It is duplicated rather than imported
|
|
7732
|
+
* because the harness carries zero `@createinc/*` dependencies; the pair is
|
|
7733
|
+
* pinned by `template-build-push.contract.test.ts`, the same arrangement the
|
|
7734
|
+
* untrusted fence uses.
|
|
7735
|
+
*/
|
|
7736
|
+
const BAKED_BUILD_PATHS = new Set([
|
|
7737
|
+
"Dockerfile",
|
|
7738
|
+
"install.sh",
|
|
7739
|
+
"package.json",
|
|
7740
|
+
"package-lock.json",
|
|
7741
|
+
".npmrc",
|
|
7742
|
+
"yarn.lock",
|
|
7743
|
+
".yarnrc.yml",
|
|
7744
|
+
".yarnrc",
|
|
7745
|
+
"bun.lock",
|
|
7746
|
+
"bun.lockb",
|
|
7747
|
+
".bunfig.toml",
|
|
7748
|
+
"pnpm-lock.yaml"
|
|
7749
|
+
]);
|
|
7750
|
+
const BUILD_STARTED_NOTICE = "Note: this push changed a file that is baked into your computer image (Dockerfile / install.sh / a lockfile), so it started a template build. The change is NOT live here until that build succeeds — a failed build leaves you running the previous image, silently. Run `platform builds wait` to confirm it built before you rely on anything the change added, or treat it as unfinished work and check back with `platform builds show`.";
|
|
7751
|
+
/** True for a bash command that is (or contains) a `git push`. */
|
|
7752
|
+
function isGitPush(command) {
|
|
7753
|
+
return /(^|[\s;&|(])git\s+(?:\S+\s+)*?push(\s|$)/.test(command);
|
|
7754
|
+
}
|
|
7755
|
+
/**
|
|
7756
|
+
* The commit range a push reported, parsed from git's own output.
|
|
7757
|
+
*
|
|
7758
|
+
* git writes the range on the ref line of a successful push
|
|
7759
|
+
* (` abc1234..def5678 main -> main`). Reading it back is what lets the
|
|
7760
|
+
* diff be scoped to exactly what was pushed, with no guessing about upstream
|
|
7761
|
+
* tracking state. A new branch (`* [new branch]`) reports no range, which is
|
|
7762
|
+
* why {@link parsePushedRange} returns null there and the caller falls back
|
|
7763
|
+
* to notifying — a first push of a repo is overwhelmingly one that carries a
|
|
7764
|
+
* Dockerfile.
|
|
7765
|
+
*/
|
|
7766
|
+
function parsePushedRange(output) {
|
|
7767
|
+
const match = output.match(/\b([0-9a-f]{7,40})\.\.([0-9a-f]{7,40})\b/);
|
|
7768
|
+
if (!match) return null;
|
|
7769
|
+
return `${match[1]}..${match[2]}`;
|
|
7770
|
+
}
|
|
7771
|
+
/** True when a forced update (`+ abc..def (forced update)`) or a new ref. */
|
|
7772
|
+
function isNewRef(output) {
|
|
7773
|
+
return /\[new (?:branch|tag)\]/.test(output);
|
|
7774
|
+
}
|
|
7775
|
+
async function touchedBakedPath({ cwd, range }) {
|
|
7776
|
+
const { stdout } = await execFileAsync("git", [
|
|
7777
|
+
"diff",
|
|
7778
|
+
"--name-only",
|
|
7779
|
+
range
|
|
7780
|
+
], {
|
|
7781
|
+
cwd,
|
|
7782
|
+
timeout: 5e3,
|
|
7783
|
+
maxBuffer: 4 * 1024 * 1024
|
|
7784
|
+
});
|
|
7785
|
+
return stdout.split("\n").map((line) => line.trim()).some((path) => path.length > 0 && BAKED_BUILD_PATHS.has(path));
|
|
7786
|
+
}
|
|
7787
|
+
const templateBuildPushExtension = (pi) => {
|
|
7788
|
+
pi.on("tool_result", async (event, ctx) => {
|
|
7789
|
+
if (event.toolName !== "bash") return;
|
|
7790
|
+
if (event.isError) return;
|
|
7791
|
+
const command = event.input.command;
|
|
7792
|
+
if (typeof command !== "string" || !isGitPush(command)) return;
|
|
7793
|
+
const output = event.content.map((part) => part.type === "text" ? part.text : "").join("\n");
|
|
7794
|
+
let notify = false;
|
|
7795
|
+
try {
|
|
7796
|
+
const range = parsePushedRange(output);
|
|
7797
|
+
if (range === null) notify = isNewRef(output);
|
|
7798
|
+
else notify = await touchedBakedPath({
|
|
7799
|
+
cwd: ctx.cwd,
|
|
7800
|
+
range
|
|
7801
|
+
});
|
|
7802
|
+
} catch (err) {
|
|
7803
|
+
log.warn({
|
|
7804
|
+
err,
|
|
7805
|
+
event: "template_build_push_classify_failed"
|
|
7806
|
+
}, "could not classify pushed paths; leaving the push result unchanged");
|
|
7807
|
+
return;
|
|
7808
|
+
}
|
|
7809
|
+
if (!notify) return;
|
|
7810
|
+
return { content: [...event.content, {
|
|
7811
|
+
type: "text",
|
|
7812
|
+
text: `\n${BUILD_STARTED_NOTICE}`
|
|
7813
|
+
}] };
|
|
7814
|
+
});
|
|
7815
|
+
};
|
|
7816
|
+
//#endregion
|
|
7552
7817
|
//#region src/extensions/tool-history.ts
|
|
7553
7818
|
const VALID_NAME_RE = /^[a-zA-Z0-9_-]+$/;
|
|
7554
7819
|
function isValidToolName(name) {
|
|
@@ -7717,6 +7982,7 @@ function platformExtensions({ sessionId, channelContext }) {
|
|
|
7717
7982
|
createSubagentExtension({ channelContext }),
|
|
7718
7983
|
createContextManagementExtension(),
|
|
7719
7984
|
resourcePressureWarningExtension,
|
|
7985
|
+
templateBuildPushExtension,
|
|
7720
7986
|
tool_history_default
|
|
7721
7987
|
];
|
|
7722
7988
|
}
|