@tangle-network/agent-runtime 0.316.0 → 0.318.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-CvdE2HIU.js → activation-CRG-tjnR.js} +2 -2
- package/dist/{activation-CvdE2HIU.js.map → activation-CRG-tjnR.js.map} +1 -1
- package/dist/{activation-BFDmjaKP.d.ts → activation-RExX9RDm.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{coordination-driver-DGhN8GO9.js → coordination-driver-DK3pI_HB.js} +2 -2
- package/dist/{coordination-driver-DGhN8GO9.js.map → coordination-driver-DK3pI_HB.js.map} +1 -1
- package/dist/{delegate-B5pmSbQa.js → delegate-Co9vJIgE.js} +2 -2
- package/dist/{delegate-B5pmSbQa.js.map → delegate-Co9vJIgE.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +2 -2
- package/dist/{graph-G0j1ysqe.js → graph-DYBCYZjg.js} +5 -5
- package/dist/{graph-G0j1ysqe.js.map → graph-DYBCYZjg.js.map} +1 -1
- package/dist/{improvement-cycle-D7yR6GC2.js → improvement-cycle-jp80l_ZQ.js} +4 -4
- package/dist/{improvement-cycle-D7yR6GC2.js.map → improvement-cycle-jp80l_ZQ.js.map} +1 -1
- package/dist/{index-CUh40yUJ.d.ts → index-CHlWvoo5.d.ts} +85 -52
- package/dist/index.d.ts +4 -4
- package/dist/index.js +8 -8
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +3 -3
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +10 -10
- package/dist/{loop-runner-bin-DQKLUt0l.d.ts → loop-runner-bin-C-QaaVE2.d.ts} +2 -2
- package/dist/{loop-runner-bin-CFVX4oi0.js → loop-runner-bin-C8jLr2gR.js} +3 -3
- package/dist/{loop-runner-bin-CFVX4oi0.js.map → loop-runner-bin-C8jLr2gR.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +2 -2
- package/dist/mcp/index.js +5 -5
- package/dist/{model-policy-DhvyZ8-O.js → model-policy-B-rOb8Nj.js} +37 -2
- package/dist/model-policy-B-rOb8Nj.js.map +1 -0
- package/dist/{openai-tools-u3gWBi3x.d.ts → openai-tools-BuJB3JQH.d.ts} +2 -2
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{provision-supervisor-BQLLrUtn.js → provision-supervisor-CunKnayY.js} +4 -4
- package/dist/{provision-supervisor-BQLLrUtn.js.map → provision-supervisor-CunKnayY.js.map} +1 -1
- package/dist/{runtime-B9BOFyEp.js → runtime-UG5tV_yf.js} +231 -288
- package/dist/runtime-UG5tV_yf.js.map +1 -0
- package/dist/{search-executor-B5ZVFsDV.js → search-executor-DMX6tCY4.js} +3 -3
- package/dist/{search-executor-B5ZVFsDV.js.map → search-executor-DMX6tCY4.js.map} +1 -1
- package/dist/{server-TwpH9aik.js → server-fSBvPPLH.js} +3 -3
- package/dist/{server-TwpH9aik.js.map → server-fSBvPPLH.js.map} +1 -1
- package/dist/{supervise-CU6AuxWY.js → supervise-C41ywfFd.js} +4 -4
- package/dist/{supervise-CU6AuxWY.js.map → supervise-C41ywfFd.js.map} +1 -1
- package/dist/{supervisor-CbFyf48U.js → supervisor-BXEL_Fxe.js} +480 -50
- package/dist/supervisor-BXEL_Fxe.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +12 -12
- package/dist/tool-loop.d.ts +15 -2
- package/dist/tool-loop.js +5 -3
- package/dist/tool-loop.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/package.json +3 -2
- package/skills/agent-graphs/references/authoring.md +7 -0
- package/skills/codemode/SKILL.md +6 -4
- package/skills/codemode/references/runtime-execution.md +56 -11
- package/skills/profile-authoring/SKILL.md +17 -15
- package/dist/model-policy-DhvyZ8-O.js.map +0 -1
- package/dist/runtime-B9BOFyEp.js.map +0 -1
- package/dist/supervisor-CbFyf48U.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError$1, u as RetainedRunAdmissionError } from "./errors-DodWX-cb.js";
|
|
2
2
|
import { $ as randomSuffix, A as verifiedArtifactChunks, B as addSpend, Ct as isDeadlineAbortReason, Et as teardownSurfaces, G as deleteBoxSafe, H as chargedTokens, J as hasCompleteCacheBreakdown, K as errorMessage, O as verifyWorkspaceSnapshotArtifacts, P as deepFreezeCandidate, Q as promptCacheTokenClasses, St as checkInIdleMs, Tt as teardownExecutor, U as cloneSpend, V as addTokenUsage, W as cloneTokenUsage, X as isAsyncIterable$1, Z as mapWithConcurrency, a as verifyAgentCandidateWorkspaceArtifacts, at as throwIfAborted, bt as armDeadlineTimer, ct as zeroSpend, dt as assertResources, et as randomUuid, ft as resourceTelemetry, ht as CHILD_DEADLINE_REASON, i as readAgentCandidateWorkspaceArtifactFiles, it as throwAbort, lt as zeroTokenUsage, mt as ACCEPTED_RESULT_GRACE_MS, nt as sleep, o as verifyAgentCandidateWorkspaceTree, ot as unmeteredSpend, pt as withBudgetResources, q as fnv1a32Hex, rt as stringifySafe, st as withTimeout, tt as roundBoxMinutes, u as verifyAgentCandidateWorkspaceArchive, ut as addResourceSpend, wt as singleFlightTeardown, xt as boundedChildDeadlineAt, yt as ROOT_DEADLINE_REASON } from "./workspace-streams-DkijayqX.js";
|
|
3
3
|
import { runTaskQueue } from "./task-queue.js";
|
|
4
|
-
import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, d as assertRouterAutoDeclaration, f as assertRouterAutoResponse, g as observedModelMatchesDeclared, h as observedModelHasSnapshot, l as profileProviderModel, m as mergeObservedModelIdentity, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-
|
|
4
|
+
import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, d as assertRouterAutoDeclaration, f as assertRouterAutoResponse, g as observedModelMatchesDeclared, h as observedModelHasSnapshot, l as profileProviderModel, m as mergeObservedModelIdentity, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-B-rOb8Nj.js";
|
|
5
5
|
import { n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile } from "./durable-file-DWQA4ooo.js";
|
|
6
6
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
7
7
|
import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, AgentTurnInputSchema, AgentTurnResultSchema, CanonicalStreamEventSchema, ContextTransferRequestSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, REASONING_EFFORTS, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentCandidateArtifactRefSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, agentRunCancellationRequestDigest, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalWorkspaceCwd, exactAgentInteractiveSessionStart, harnessTypeSchema, nativeContextContinuationTurnDigest, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema, workspaceCheckpointRequestDigest, workspaceCheckpointResultMatchesRequest, workspaceCleanupAcknowledgementMatches, workspaceCleanupRequestDigest, workspaceForkRequestDigest, workspaceForkResultMatchesRequest } from "@tangle-network/agent-interface";
|
|
@@ -4650,10 +4650,10 @@ function createOtelExporter(config) {
|
|
|
4650
4650
|
if (!resolvedEndpoint) return void 0;
|
|
4651
4651
|
const url = `${resolvedEndpoint.replace(/\/+$/, "")}/v1/traces`;
|
|
4652
4652
|
const headers = config?.headers ?? parseHeadersFromEnv();
|
|
4653
|
-
const batchSize = positiveInteger(config?.batchSize, 64);
|
|
4653
|
+
const batchSize = positiveInteger$1(config?.batchSize, 64);
|
|
4654
4654
|
const flushIntervalMs = config?.flushIntervalMs ?? 5e3;
|
|
4655
|
-
const maxQueueSize = Math.max(positiveInteger(config?.maxQueueSize, 2048), batchSize);
|
|
4656
|
-
const timeoutMs = positiveInteger(config?.timeoutMs, 1e4);
|
|
4655
|
+
const maxQueueSize = Math.max(positiveInteger$1(config?.maxQueueSize, 2048), batchSize);
|
|
4656
|
+
const timeoutMs = positiveInteger$1(config?.timeoutMs, 1e4);
|
|
4657
4657
|
const resource = { attributes: toOtelAttributes({
|
|
4658
4658
|
"service.name": config?.serviceName ?? "agent-runtime",
|
|
4659
4659
|
...config?.resourceAttributes ?? {}
|
|
@@ -4802,7 +4802,7 @@ function describeFetchError(error) {
|
|
|
4802
4802
|
const code = cause && typeof cause === "object" && "code" in cause && typeof cause.code === "string" ? cause.code : void 0;
|
|
4803
4803
|
return code ? `${error.message} (${code})` : error.message;
|
|
4804
4804
|
}
|
|
4805
|
-
function positiveInteger(value, fallback) {
|
|
4805
|
+
function positiveInteger$1(value, fallback) {
|
|
4806
4806
|
return value !== void 0 && Number.isSafeInteger(value) && value > 0 ? value : fallback;
|
|
4807
4807
|
}
|
|
4808
4808
|
/**
|
|
@@ -5866,6 +5866,270 @@ function priceTokens(work) {
|
|
|
5866
5866
|
return Math.max(0, work.inputTokens - cacheRead - cacheWrite) * price.input + cacheRead * (price.cachedInput ?? price.input) + cacheWrite * (price.cacheWrite ?? price.input) + work.outputTokens * price.output;
|
|
5867
5867
|
}
|
|
5868
5868
|
//#endregion
|
|
5869
|
+
//#region src/runtime/code-mode.ts
|
|
5870
|
+
function positiveInteger(value, fallback, name) {
|
|
5871
|
+
const result = value ?? fallback;
|
|
5872
|
+
if (!Number.isSafeInteger(result) || result < 1) throw new RangeError(`code mode: ${name} must be a positive safe integer`);
|
|
5873
|
+
return result;
|
|
5874
|
+
}
|
|
5875
|
+
/** Render the same tool descriptors that are executed, including their result schemas. */
|
|
5876
|
+
async function describeCodeModeTools(tools, query) {
|
|
5877
|
+
const needle = query?.trim().toLowerCase();
|
|
5878
|
+
const selected = tools.filter((tool) => !needle || tool.name.toLowerCase().includes(needle) || tool.description?.toLowerCase().includes(needle));
|
|
5879
|
+
const { renderDeclarations } = await import("@earendil-works/pi-codemode");
|
|
5880
|
+
return renderDeclarations({ tools: selected.map((tool) => ({
|
|
5881
|
+
name: tool.name,
|
|
5882
|
+
description: tool.description,
|
|
5883
|
+
inputSchema: tool.inputSchema,
|
|
5884
|
+
outputSchema: tool.outputSchema,
|
|
5885
|
+
execute: () => {
|
|
5886
|
+
throw new Error("Declaration-only tool");
|
|
5887
|
+
}
|
|
5888
|
+
})) });
|
|
5889
|
+
}
|
|
5890
|
+
/**
|
|
5891
|
+
* Execute a JS async-function body against Runtime capabilities. The upstream
|
|
5892
|
+
* QuickJS/WASM worker is the boundary; there is no node:vm or unsafe fallback.
|
|
5893
|
+
* Every invocation has a fresh VM. Only successful storeWrites may be committed
|
|
5894
|
+
* by the caller. External tool effects are neither transactional nor retried.
|
|
5895
|
+
*/
|
|
5896
|
+
async function runCodeMode(code, options) {
|
|
5897
|
+
if (typeof code !== "string" || !code.trim()) throw new TypeError("code mode: source is required");
|
|
5898
|
+
options.signal?.throwIfAborted();
|
|
5899
|
+
if (!options.callId.trim()) throw new TypeError("code mode: callId is required");
|
|
5900
|
+
const concurrency = positiveInteger(options.concurrency, 4, "concurrency");
|
|
5901
|
+
const maxCalls = positiveInteger(options.maxCalls, 1024, "maxCalls");
|
|
5902
|
+
const memoryLimitBytes = positiveInteger(options.memoryLimitBytes, 64 * 1024 * 1024, "memoryLimitBytes");
|
|
5903
|
+
const timeoutMs = options.timeoutMs === Infinity ? Infinity : positiveInteger(options.timeoutMs, 3e5, "timeoutMs");
|
|
5904
|
+
if (timeoutMs !== Infinity && timeoutMs > 2147483647) throw new RangeError("code mode: timeoutMs must be at most 2147483647 or Infinity");
|
|
5905
|
+
const { CodemodeSandbox, toCodemodeIdentifier } = await import("@earendil-works/pi-codemode");
|
|
5906
|
+
const names = /* @__PURE__ */ new Set();
|
|
5907
|
+
const identifiers = /* @__PURE__ */ new Set();
|
|
5908
|
+
for (const tool of options.tools) {
|
|
5909
|
+
if (!tool.name || names.has(tool.name)) throw new TypeError(`code mode: duplicate or empty tool ${tool.name}`);
|
|
5910
|
+
names.add(tool.name);
|
|
5911
|
+
const identifier = toCodemodeIdentifier(tool.name);
|
|
5912
|
+
if (identifiers.has(identifier)) throw new TypeError(`code mode: ambiguous tool name ${tool.name} normalizes to ${identifier}`);
|
|
5913
|
+
identifiers.add(identifier);
|
|
5914
|
+
}
|
|
5915
|
+
const callLimit = new AbortController();
|
|
5916
|
+
const executionSignal = options.signal ? AbortSignal.any([options.signal, callLimit.signal]) : callLimit.signal;
|
|
5917
|
+
const queue = new CallQueue(concurrency);
|
|
5918
|
+
let ordinal = 0;
|
|
5919
|
+
const sandbox = new CodemodeSandbox({
|
|
5920
|
+
tools: options.tools.map((tool) => ({
|
|
5921
|
+
name: tool.name,
|
|
5922
|
+
description: tool.description,
|
|
5923
|
+
inputSchema: tool.inputSchema,
|
|
5924
|
+
outputSchema: tool.outputSchema,
|
|
5925
|
+
execute: async (args, { signal }) => {
|
|
5926
|
+
signal.throwIfAborted();
|
|
5927
|
+
const index = ++ordinal;
|
|
5928
|
+
if (index > maxCalls) {
|
|
5929
|
+
const error = /* @__PURE__ */ new Error(`code mode: call limit ${maxCalls} exceeded`);
|
|
5930
|
+
callLimit.abort(error);
|
|
5931
|
+
throw error;
|
|
5932
|
+
}
|
|
5933
|
+
const release = await queue.acquire(signal);
|
|
5934
|
+
try {
|
|
5935
|
+
signal.throwIfAborted();
|
|
5936
|
+
const value = await tool.execute(args, Object.freeze({
|
|
5937
|
+
signal,
|
|
5938
|
+
parentCallId: options.callId,
|
|
5939
|
+
callId: `${options.callId}/tool/${index}`
|
|
5940
|
+
}));
|
|
5941
|
+
signal.throwIfAborted();
|
|
5942
|
+
return value;
|
|
5943
|
+
} finally {
|
|
5944
|
+
release();
|
|
5945
|
+
}
|
|
5946
|
+
}
|
|
5947
|
+
})),
|
|
5948
|
+
timeoutMs,
|
|
5949
|
+
memoryLimitBytes,
|
|
5950
|
+
...options.wasm === void 0 ? {} : { wasm: options.wasm },
|
|
5951
|
+
...options.workerUrl === void 0 ? {} : { workerUrl: options.workerUrl }
|
|
5952
|
+
});
|
|
5953
|
+
try {
|
|
5954
|
+
return await sandbox.execute(code, {
|
|
5955
|
+
signal: executionSignal,
|
|
5956
|
+
store: options.store
|
|
5957
|
+
});
|
|
5958
|
+
} finally {
|
|
5959
|
+
await sandbox.close();
|
|
5960
|
+
}
|
|
5961
|
+
}
|
|
5962
|
+
/** A per-invocation FIFO, not another scheduler. Aborted waiters never dispatch. */
|
|
5963
|
+
var CallQueue = class {
|
|
5964
|
+
active = 0;
|
|
5965
|
+
waiting = [];
|
|
5966
|
+
concurrency;
|
|
5967
|
+
constructor(concurrency) {
|
|
5968
|
+
this.concurrency = concurrency;
|
|
5969
|
+
}
|
|
5970
|
+
acquire(signal) {
|
|
5971
|
+
signal.throwIfAborted();
|
|
5972
|
+
if (this.active < this.concurrency) {
|
|
5973
|
+
this.active++;
|
|
5974
|
+
return Promise.resolve(this.release());
|
|
5975
|
+
}
|
|
5976
|
+
return new Promise((resolve, reject) => {
|
|
5977
|
+
const waiter = {
|
|
5978
|
+
signal,
|
|
5979
|
+
resolve,
|
|
5980
|
+
reject,
|
|
5981
|
+
abort: () => {}
|
|
5982
|
+
};
|
|
5983
|
+
waiter.abort = () => {
|
|
5984
|
+
const index = this.waiting.indexOf(waiter);
|
|
5985
|
+
if (index !== -1) this.waiting.splice(index, 1);
|
|
5986
|
+
reject(signal.reason);
|
|
5987
|
+
};
|
|
5988
|
+
signal.addEventListener("abort", waiter.abort, { once: true });
|
|
5989
|
+
this.waiting.push(waiter);
|
|
5990
|
+
if (signal.aborted) waiter.abort();
|
|
5991
|
+
});
|
|
5992
|
+
}
|
|
5993
|
+
release() {
|
|
5994
|
+
let released = false;
|
|
5995
|
+
return () => {
|
|
5996
|
+
if (released) return;
|
|
5997
|
+
released = true;
|
|
5998
|
+
this.active--;
|
|
5999
|
+
for (;;) {
|
|
6000
|
+
const next = this.waiting.shift();
|
|
6001
|
+
if (!next) return;
|
|
6002
|
+
next.signal.removeEventListener("abort", next.abort);
|
|
6003
|
+
if (next.signal.aborted) {
|
|
6004
|
+
next.reject(next.signal.reason);
|
|
6005
|
+
continue;
|
|
6006
|
+
}
|
|
6007
|
+
this.active++;
|
|
6008
|
+
next.resolve(this.release());
|
|
6009
|
+
return;
|
|
6010
|
+
}
|
|
6011
|
+
};
|
|
6012
|
+
}
|
|
6013
|
+
};
|
|
6014
|
+
/**
|
|
6015
|
+
* Present an existing authorized tool set as code mode. This is used by Runtime's
|
|
6016
|
+
* existing loops; it does not execute a model, create an agent, or grant authority.
|
|
6017
|
+
* One toolset belongs to one conversation. Concurrent programs are refused to
|
|
6018
|
+
* avoid silently losing store writes; concurrency within a program is queued.
|
|
6019
|
+
*/
|
|
6020
|
+
function createCodeModeTools(granted, options = {}) {
|
|
6021
|
+
const reserved = /* @__PURE__ */ new Set(["codemode", "tool_search"]);
|
|
6022
|
+
const names = /* @__PURE__ */ new Set();
|
|
6023
|
+
for (const tool of granted) {
|
|
6024
|
+
if (reserved.has(tool.name)) throw new TypeError(`code mode: ${tool.name} is already present; use the existing code mode, do not nest it`);
|
|
6025
|
+
if (!tool.name || names.has(tool.name)) throw new TypeError(`code mode: duplicate or empty tool ${tool.name}`);
|
|
6026
|
+
names.add(tool.name);
|
|
6027
|
+
}
|
|
6028
|
+
const direct = new Set(options.directTools ?? []);
|
|
6029
|
+
for (const name of direct) if (!names.has(name)) throw new TypeError(`code mode: direct tool ${name} is not granted`);
|
|
6030
|
+
const copied = granted.map((tool) => Object.freeze({
|
|
6031
|
+
...tool,
|
|
6032
|
+
...tool.inputSchema === void 0 ? {} : { inputSchema: structuredClone(tool.inputSchema) },
|
|
6033
|
+
...tool.outputSchema === void 0 ? {} : { outputSchema: structuredClone(tool.outputSchema) }
|
|
6034
|
+
}));
|
|
6035
|
+
const callable = Object.freeze(copied.filter((tool) => !direct.has(tool.name)));
|
|
6036
|
+
let store = structuredClone(options.store ?? {});
|
|
6037
|
+
let running = false;
|
|
6038
|
+
const tools = [
|
|
6039
|
+
{
|
|
6040
|
+
name: "tool_search",
|
|
6041
|
+
description: "Discover the tools available inside codemode. Returns generated TypeScript input and output declarations. Use an optional name/description substring query, or omit it for all tools.",
|
|
6042
|
+
inputSchema: {
|
|
6043
|
+
type: "object",
|
|
6044
|
+
properties: { query: { type: "string" } },
|
|
6045
|
+
additionalProperties: false
|
|
6046
|
+
},
|
|
6047
|
+
execute: async (raw) => {
|
|
6048
|
+
const args = codeModeArguments(raw);
|
|
6049
|
+
if (args.query !== void 0 && typeof args.query !== "string") throw new TypeError("query must be a string");
|
|
6050
|
+
return describeCodeModeTools(callable, args.query);
|
|
6051
|
+
}
|
|
6052
|
+
},
|
|
6053
|
+
{
|
|
6054
|
+
name: "codemode",
|
|
6055
|
+
description: "Run a JavaScript async-function body to compose the granted tools. Call tools.name(args) or tools[\"original-name\"](args); inspect ALL_TOOLS or tool_search to discover them. Await tool calls, use loops and Promise.all, keep intermediate data in variables, and return only the result needed for the next decision. text(value) prints, image({type:\"image\",data,mimeType}) emits an image. store(key,value) and load(key) retain JSON across successful calls in this conversation. No imports, process, filesystem, network, or timers. Side effects are not rolled back or automatically retried.",
|
|
6056
|
+
inputSchema: {
|
|
6057
|
+
type: "object",
|
|
6058
|
+
properties: { code: { type: "string" } },
|
|
6059
|
+
required: ["code"],
|
|
6060
|
+
additionalProperties: false
|
|
6061
|
+
},
|
|
6062
|
+
execute: async (raw, context) => {
|
|
6063
|
+
const args = codeModeArguments(raw);
|
|
6064
|
+
if (typeof args.code !== "string") throw new TypeError("codemode requires {code: string}");
|
|
6065
|
+
if (running) throw new Error("code mode: another program is still running in this conversation");
|
|
6066
|
+
running = true;
|
|
6067
|
+
try {
|
|
6068
|
+
const result = await runCodeMode(args.code, {
|
|
6069
|
+
...options,
|
|
6070
|
+
tools: callable,
|
|
6071
|
+
signal: context.signal,
|
|
6072
|
+
callId: context.callId,
|
|
6073
|
+
store
|
|
6074
|
+
});
|
|
6075
|
+
if (result.ok) {
|
|
6076
|
+
const next = Object.assign(Object.create(null), store, result.storeWrites.set);
|
|
6077
|
+
for (const key of result.storeWrites.delete) delete next[key];
|
|
6078
|
+
store = structuredClone(next);
|
|
6079
|
+
}
|
|
6080
|
+
return result.ok ? {
|
|
6081
|
+
ok: true,
|
|
6082
|
+
value: result.value ?? null,
|
|
6083
|
+
output: result.output
|
|
6084
|
+
} : {
|
|
6085
|
+
ok: false,
|
|
6086
|
+
error: result.error,
|
|
6087
|
+
output: result.output
|
|
6088
|
+
};
|
|
6089
|
+
} finally {
|
|
6090
|
+
running = false;
|
|
6091
|
+
}
|
|
6092
|
+
}
|
|
6093
|
+
},
|
|
6094
|
+
...copied.filter((tool) => direct.has(tool.name))
|
|
6095
|
+
];
|
|
6096
|
+
return {
|
|
6097
|
+
tools: Object.freeze(tools),
|
|
6098
|
+
snapshotStore: () => structuredClone(store)
|
|
6099
|
+
};
|
|
6100
|
+
}
|
|
6101
|
+
/** Model tools have object arguments. Validation against a tool's schema remains host-owned. */
|
|
6102
|
+
function codeModeArguments(value) {
|
|
6103
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("tool arguments must be a JSON object");
|
|
6104
|
+
return value;
|
|
6105
|
+
}
|
|
6106
|
+
/** Preserve legacy text tool results; structured tool handlers keep their actual JSON values. */
|
|
6107
|
+
function toolResultText(value) {
|
|
6108
|
+
return typeof value === "string" ? value : JSON.stringify(value) ?? "null";
|
|
6109
|
+
}
|
|
6110
|
+
/**
|
|
6111
|
+
* OpenAI-compatible output projection. All tool replies must precede the optional
|
|
6112
|
+
* user image message, so the loop appends returned images after the tool batch.
|
|
6113
|
+
* Image bytes never become a stringified pseudo-image in the tool's text.
|
|
6114
|
+
*/
|
|
6115
|
+
function codeModeModelOutput(value) {
|
|
6116
|
+
const reply = value;
|
|
6117
|
+
return {
|
|
6118
|
+
text: JSON.stringify({
|
|
6119
|
+
ok: reply.ok,
|
|
6120
|
+
...reply.ok ? { value: reply.value } : { error: reply.error },
|
|
6121
|
+
output: reply.output.map((item) => item.type === "text" ? item : {
|
|
6122
|
+
type: "image",
|
|
6123
|
+
mimeType: item.mimeType
|
|
6124
|
+
})
|
|
6125
|
+
}),
|
|
6126
|
+
images: reply.output.flatMap((item) => item.type === "image" ? [{
|
|
6127
|
+
type: "image_url",
|
|
6128
|
+
image_url: { url: `data:${item.mimeType};base64,${item.data}` }
|
|
6129
|
+
}] : [])
|
|
6130
|
+
};
|
|
6131
|
+
}
|
|
6132
|
+
//#endregion
|
|
5869
6133
|
//#region src/durable/content-address.ts
|
|
5870
6134
|
/** Stable content address shared by result and trace artifacts. */
|
|
5871
6135
|
function contentAddress(artifact) {
|
|
@@ -7136,26 +7400,28 @@ async function captureProviderCheckpointWorkspace(port, prepare, marker, parent)
|
|
|
7136
7400
|
clearDeadline();
|
|
7137
7401
|
}
|
|
7138
7402
|
}
|
|
7139
|
-
/** Verify a running workspace copy before treating it as retained evidence.
|
|
7140
|
-
|
|
7403
|
+
/** Verify a running workspace copy before treating it as retained evidence. `parent` stops the
|
|
7404
|
+
* copy, in the queue or under way, when its turn ends. */
|
|
7405
|
+
async function captureProviderLiveWorkspace(port, context, parent) {
|
|
7141
7406
|
assertProviderWorkspaceRetentionPort(port, "provider workspace retention");
|
|
7142
7407
|
if (port.captureLive === void 0) throw new ValidationError$1("provider workspace retention: the port has no captureLive");
|
|
7143
7408
|
const timeoutMs = port.liveTimeoutMs ?? port.timeoutMs;
|
|
7144
7409
|
const controller = new AbortController();
|
|
7145
7410
|
const clearDeadline = armDeadlineTimer(timeoutMs, () => controller.abort(/* @__PURE__ */ new Error(`live workspace capture timed out after ${timeoutMs}ms`)), true);
|
|
7411
|
+
const signal = parent === void 0 ? controller.signal : AbortSignal.any([controller.signal, parent]);
|
|
7146
7412
|
try {
|
|
7147
|
-
return await runAbortable(() => withCaptureSlot(checkpointSlots(port),
|
|
7413
|
+
return await runAbortable(() => withCaptureSlot(checkpointSlots(port), signal, async () => {
|
|
7148
7414
|
const tree = detachedSnapshot(await port.captureLive({
|
|
7149
7415
|
...context,
|
|
7150
|
-
signal
|
|
7416
|
+
signal
|
|
7151
7417
|
}), "live workspace capture tree");
|
|
7152
7418
|
if (tree?.kind !== "agent-candidate-workspace-tree") throw new Error("live workspace capture returned no workspace tree");
|
|
7153
7419
|
if ((await verifyAgentCandidateWorkspaceTree(tree, port.artifacts, {
|
|
7154
7420
|
...port.limits === void 0 ? {} : { limits: port.limits },
|
|
7155
|
-
signal
|
|
7421
|
+
signal
|
|
7156
7422
|
})).files.length !== tree.files) throw new Error("live workspace capture tree misstates its file count");
|
|
7157
7423
|
return tree;
|
|
7158
|
-
}),
|
|
7424
|
+
}), signal, `live workspace capture timed out after ${timeoutMs}ms`);
|
|
7159
7425
|
} finally {
|
|
7160
7426
|
clearDeadline();
|
|
7161
7427
|
}
|
|
@@ -11578,13 +11844,18 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
|
|
|
11578
11844
|
const livePort = options.workspaceRetention?.captureLive === void 0 ? void 0 : options.workspaceRetention;
|
|
11579
11845
|
let liveInFlight;
|
|
11580
11846
|
let liveTimer;
|
|
11847
|
+
let liveStop;
|
|
11581
11848
|
const stopLiveMirror = () => {
|
|
11582
11849
|
if (liveTimer !== void 0) clearTimeout(liveTimer);
|
|
11583
11850
|
liveTimer = void 0;
|
|
11851
|
+
liveStop?.abort(/* @__PURE__ */ new Error("live workspace capture stopped: its turn ended"));
|
|
11852
|
+
liveStop = void 0;
|
|
11584
11853
|
};
|
|
11585
11854
|
const startLiveMirror = (next) => {
|
|
11586
11855
|
if (livePort?.liveIntervalMs === void 0) return;
|
|
11587
11856
|
stopLiveMirror();
|
|
11857
|
+
const stop = new AbortController();
|
|
11858
|
+
liveStop = stop;
|
|
11588
11859
|
const schedule = () => {
|
|
11589
11860
|
liveTimer = setTimeout(() => {
|
|
11590
11861
|
if (liveInFlight === void 0 && workspaceCapturePromise === void 0) {
|
|
@@ -11596,7 +11867,7 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
|
|
|
11596
11867
|
providerSessionId,
|
|
11597
11868
|
nativeSessionId: null,
|
|
11598
11869
|
profile: createProfile
|
|
11599
|
-
}).then(() => void 0, () => void 0).finally(() => {
|
|
11870
|
+
}, stop.signal).then(() => void 0, () => void 0).finally(() => {
|
|
11600
11871
|
if (liveInFlight === tracked) liveInFlight = void 0;
|
|
11601
11872
|
});
|
|
11602
11873
|
liveInFlight = tracked;
|
|
@@ -11675,6 +11946,7 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
|
|
|
11675
11946
|
schedule();
|
|
11676
11947
|
};
|
|
11677
11948
|
const finishNativeMirror = async (next, phase) => {
|
|
11949
|
+
stopLiveMirror();
|
|
11678
11950
|
await stopNativeMirror();
|
|
11679
11951
|
if (workspaceSnapshot !== void 0 && !nativeHoldsTranscript) return;
|
|
11680
11952
|
await captureNative(next, phase, void 0, harnessStopped);
|
|
@@ -13475,15 +13747,57 @@ async function runBrainLoop(opts) {
|
|
|
13475
13747
|
let tokensKnown = true;
|
|
13476
13748
|
let completedTurns = 0;
|
|
13477
13749
|
const toolTrace = [];
|
|
13750
|
+
const signal = opts.signal ?? new AbortController().signal;
|
|
13751
|
+
const codeMode = opts.codeMode ? createCodeModeTools(opts.tools.map(({ function: tool }) => ({
|
|
13752
|
+
name: tool.name,
|
|
13753
|
+
description: tool.description,
|
|
13754
|
+
inputSchema: tool.parameters,
|
|
13755
|
+
outputSchema: tool.outputSchema,
|
|
13756
|
+
execute: async (raw, context) => {
|
|
13757
|
+
signal.throwIfAborted();
|
|
13758
|
+
if (opts.hooks?.stopBefore?.(completedTurns + 1)) throw new Error("code mode: Runtime execution has stopped");
|
|
13759
|
+
const args = codeModeArguments(raw);
|
|
13760
|
+
let result;
|
|
13761
|
+
try {
|
|
13762
|
+
result = await opts.execute(tool.name, args, context);
|
|
13763
|
+
} catch (error) {
|
|
13764
|
+
if (context.callId !== context.parentCallId) toolTrace.push({
|
|
13765
|
+
name: tool.name,
|
|
13766
|
+
args: JSON.stringify(args),
|
|
13767
|
+
result: `error: ${error instanceof Error ? error.message : String(error)}`
|
|
13768
|
+
});
|
|
13769
|
+
throw error;
|
|
13770
|
+
}
|
|
13771
|
+
if (context.callId !== context.parentCallId) toolTrace.push({
|
|
13772
|
+
name: tool.name,
|
|
13773
|
+
args: JSON.stringify(args),
|
|
13774
|
+
result: toolResultText(result)
|
|
13775
|
+
});
|
|
13776
|
+
return result;
|
|
13777
|
+
}
|
|
13778
|
+
})), opts.codeMode === true ? {} : opts.codeMode) : void 0;
|
|
13779
|
+
const modelTools = codeMode ? codeMode.tools.map((tool) => ({
|
|
13780
|
+
type: "function",
|
|
13781
|
+
function: {
|
|
13782
|
+
name: tool.name,
|
|
13783
|
+
description: tool.description,
|
|
13784
|
+
parameters: tool.inputSchema
|
|
13785
|
+
}
|
|
13786
|
+
})) : opts.tools;
|
|
13787
|
+
const codeByName = new Map(codeMode?.tools.map((tool) => [tool.name, tool]) ?? []);
|
|
13788
|
+
const retainedCodeMode = () => codeMode ? {
|
|
13789
|
+
codeModeStore: codeMode.snapshotStore(),
|
|
13790
|
+
modelToolNames: modelTools.map((tool) => tool.function.name)
|
|
13791
|
+
} : {};
|
|
13478
13792
|
for (let turn = 1; maxTurns === 0 || turn <= maxTurns; turn += 1) {
|
|
13479
|
-
if (opts.hooks?.stopBefore?.(turn)) break;
|
|
13793
|
+
if (signal.aborted || opts.hooks?.stopBefore?.(turn)) break;
|
|
13480
13794
|
await opts.hooks?.beforeTurn?.(turn, messages);
|
|
13481
|
-
if (opts.hooks?.stopBefore?.(turn)) break;
|
|
13795
|
+
if (signal.aborted || opts.hooks?.stopBefore?.(turn)) break;
|
|
13482
13796
|
if (opts.compaction) {
|
|
13483
13797
|
await maybeCompact(messages, opts.compaction, turn);
|
|
13484
|
-
if (opts.hooks?.stopBefore?.(turn)) break;
|
|
13798
|
+
if (signal.aborted || opts.hooks?.stopBefore?.(turn)) break;
|
|
13485
13799
|
}
|
|
13486
|
-
const r = await opts.chat(messages,
|
|
13800
|
+
const r = await opts.chat(messages, modelTools);
|
|
13487
13801
|
completedTurns = turn;
|
|
13488
13802
|
if (r.usage) {
|
|
13489
13803
|
usage.input += r.usage.input;
|
|
@@ -13511,7 +13825,8 @@ async function runBrainLoop(opts) {
|
|
|
13511
13825
|
toolTrace,
|
|
13512
13826
|
usage,
|
|
13513
13827
|
...tokensKnown ? {} : { tokensKnown: false },
|
|
13514
|
-
messages
|
|
13828
|
+
messages,
|
|
13829
|
+
...retainedCodeMode()
|
|
13515
13830
|
};
|
|
13516
13831
|
}
|
|
13517
13832
|
messages.push({
|
|
@@ -13526,6 +13841,7 @@ async function runBrainLoop(opts) {
|
|
|
13526
13841
|
}
|
|
13527
13842
|
}))
|
|
13528
13843
|
});
|
|
13844
|
+
const images = [];
|
|
13529
13845
|
for (const tc of r.toolCalls) {
|
|
13530
13846
|
toolCalls += 1;
|
|
13531
13847
|
let args = {};
|
|
@@ -13539,7 +13855,32 @@ async function runBrainLoop(opts) {
|
|
|
13539
13855
|
});
|
|
13540
13856
|
continue;
|
|
13541
13857
|
}
|
|
13542
|
-
|
|
13858
|
+
signal.throwIfAborted();
|
|
13859
|
+
let result;
|
|
13860
|
+
let dispatchSucceeded = true;
|
|
13861
|
+
if (codeMode) {
|
|
13862
|
+
const tool = codeByName.get(tc.name);
|
|
13863
|
+
if (!tool) {
|
|
13864
|
+
dispatchSucceeded = false;
|
|
13865
|
+
result = `error: code mode: ${tc.name} is not in the model-visible tool set`;
|
|
13866
|
+
} else try {
|
|
13867
|
+
result = await tool.execute(args, {
|
|
13868
|
+
signal,
|
|
13869
|
+
callId: tc.id,
|
|
13870
|
+
parentCallId: tc.id
|
|
13871
|
+
});
|
|
13872
|
+
} catch (error) {
|
|
13873
|
+
dispatchSucceeded = false;
|
|
13874
|
+
result = `error: ${error instanceof Error ? error.message : String(error)}`;
|
|
13875
|
+
}
|
|
13876
|
+
} else result = await opts.execute(tc.name, args, {
|
|
13877
|
+
signal,
|
|
13878
|
+
callId: tc.id,
|
|
13879
|
+
parentCallId: tc.id
|
|
13880
|
+
});
|
|
13881
|
+
const projected = dispatchSucceeded && codeMode && tc.name === "codemode" ? codeModeModelOutput(result) : void 0;
|
|
13882
|
+
if (projected) images.push(...projected.images);
|
|
13883
|
+
const out = projected?.text ?? toolResultText(result);
|
|
13543
13884
|
messages.push({
|
|
13544
13885
|
role: "tool",
|
|
13545
13886
|
tool_call_id: tc.id,
|
|
@@ -13551,6 +13892,13 @@ async function runBrainLoop(opts) {
|
|
|
13551
13892
|
result: out
|
|
13552
13893
|
});
|
|
13553
13894
|
}
|
|
13895
|
+
if (images.length) messages.push({
|
|
13896
|
+
role: "user",
|
|
13897
|
+
content: [{
|
|
13898
|
+
type: "text",
|
|
13899
|
+
text: "Images emitted by codemode:"
|
|
13900
|
+
}, ...images]
|
|
13901
|
+
});
|
|
13554
13902
|
}
|
|
13555
13903
|
return {
|
|
13556
13904
|
final: lastText,
|
|
@@ -13559,7 +13907,8 @@ async function runBrainLoop(opts) {
|
|
|
13559
13907
|
toolTrace,
|
|
13560
13908
|
usage,
|
|
13561
13909
|
...tokensKnown ? {} : { tokensKnown: false },
|
|
13562
|
-
messages
|
|
13910
|
+
messages,
|
|
13911
|
+
...retainedCodeMode()
|
|
13563
13912
|
};
|
|
13564
13913
|
}
|
|
13565
13914
|
//#endregion
|
|
@@ -13740,7 +14089,10 @@ function toolCompletionBody(cfg, messages, tools, opts) {
|
|
|
13740
14089
|
model: cfg.model,
|
|
13741
14090
|
messages,
|
|
13742
14091
|
...tools.length > 0 ? {
|
|
13743
|
-
tools,
|
|
14092
|
+
tools: tools.map(({ function: { outputSchema: _outputSchema, ...fn }, ...tool }) => ({
|
|
14093
|
+
...tool,
|
|
14094
|
+
function: fn
|
|
14095
|
+
})),
|
|
13744
14096
|
tool_choice: opts?.toolChoice ?? "auto"
|
|
13745
14097
|
} : {},
|
|
13746
14098
|
...opts?.temperature !== void 0 ? { temperature: opts.temperature } : {},
|
|
@@ -20063,6 +20415,55 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20063
20415
|
});
|
|
20064
20416
|
};
|
|
20065
20417
|
const external = linkAbort(signal, controller.signal).signal;
|
|
20418
|
+
const executeGranted = async (name, raw, context) => {
|
|
20419
|
+
external.throwIfAborted();
|
|
20420
|
+
context.signal.throwIfAborted();
|
|
20421
|
+
if (!enabledToolNames.has(name)) throw new ValidationError$1(`tool ${name} is not granted`);
|
|
20422
|
+
const args = codeModeArguments(raw);
|
|
20423
|
+
if (context.callId !== context.parentCallId) executedToolCalls.push({
|
|
20424
|
+
id: context.callId,
|
|
20425
|
+
name,
|
|
20426
|
+
arguments: JSON.stringify(args)
|
|
20427
|
+
});
|
|
20428
|
+
const startedAt = Date.now();
|
|
20429
|
+
let status = "ok";
|
|
20430
|
+
try {
|
|
20431
|
+
return await seam.executeToolCall(name, args, task, context);
|
|
20432
|
+
} catch (error) {
|
|
20433
|
+
status = "error";
|
|
20434
|
+
throw error;
|
|
20435
|
+
} finally {
|
|
20436
|
+
const endedAt = Date.now();
|
|
20437
|
+
try {
|
|
20438
|
+
seam.onToolStep?.({
|
|
20439
|
+
toolName: name,
|
|
20440
|
+
args,
|
|
20441
|
+
status,
|
|
20442
|
+
startedAt,
|
|
20443
|
+
endedAt,
|
|
20444
|
+
durationMs: endedAt - startedAt
|
|
20445
|
+
});
|
|
20446
|
+
} catch {}
|
|
20447
|
+
}
|
|
20448
|
+
};
|
|
20449
|
+
const codeModeConfig = profileExecution.codeMode ?? seam.codeMode;
|
|
20450
|
+
const codeMode = codeModeConfig ? createCodeModeTools(seam.tools.map(({ function: tool }) => ({
|
|
20451
|
+
name: tool.name,
|
|
20452
|
+
description: tool.description,
|
|
20453
|
+
inputSchema: tool.parameters,
|
|
20454
|
+
outputSchema: tool.outputSchema,
|
|
20455
|
+
execute: (args, context) => executeGranted(tool.name, args, context)
|
|
20456
|
+
})), codeModeConfig === true ? {} : codeModeConfig) : void 0;
|
|
20457
|
+
const presentedTools = codeMode ? codeMode.tools.map((tool) => ({
|
|
20458
|
+
type: "function",
|
|
20459
|
+
function: {
|
|
20460
|
+
name: tool.name,
|
|
20461
|
+
description: tool.description,
|
|
20462
|
+
parameters: tool.inputSchema
|
|
20463
|
+
}
|
|
20464
|
+
})) : seam.tools;
|
|
20465
|
+
const modelToolNames = new Set(presentedTools.map((tool) => tool.function.name));
|
|
20466
|
+
const codeByName = new Map(codeMode?.tools.map((tool) => [tool.name, tool]) ?? []);
|
|
20066
20467
|
try {
|
|
20067
20468
|
for (let t = 0; maxTurns === 0 || t < maxTurns; t += 1) {
|
|
20068
20469
|
flush();
|
|
@@ -20083,7 +20484,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20083
20484
|
model,
|
|
20084
20485
|
...profileExecution.retry !== void 0 ? { retry: profileExecution.retry } : {},
|
|
20085
20486
|
...seam.complete ? { complete: seam.complete } : {}
|
|
20086
|
-
}, messages,
|
|
20487
|
+
}, messages, presentedTools, {
|
|
20087
20488
|
...profileExecution.temperature !== void 0 ? { temperature: profileExecution.temperature } : {},
|
|
20088
20489
|
signal: turnController.signal,
|
|
20089
20490
|
onResponse: async (receipt) => {
|
|
@@ -20173,6 +20574,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20173
20574
|
}
|
|
20174
20575
|
}))
|
|
20175
20576
|
});
|
|
20577
|
+
const images = [];
|
|
20176
20578
|
for (let i = 0; i < toolCalls.length; i += 1) {
|
|
20177
20579
|
const tc = toolCalls[i];
|
|
20178
20580
|
const id = tc?.id ?? `call_${i}`;
|
|
@@ -20182,7 +20584,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20182
20584
|
name: toolName,
|
|
20183
20585
|
arguments: tc?.arguments ?? ""
|
|
20184
20586
|
});
|
|
20185
|
-
if (!
|
|
20587
|
+
if (!modelToolNames.has(toolName)) {
|
|
20186
20588
|
messages.push({
|
|
20187
20589
|
role: "tool",
|
|
20188
20590
|
tool_call_id: id,
|
|
@@ -20209,34 +20611,38 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20209
20611
|
continue;
|
|
20210
20612
|
}
|
|
20211
20613
|
let result;
|
|
20212
|
-
let
|
|
20213
|
-
const toolStartedAt = Date.now();
|
|
20614
|
+
let succeeded = true;
|
|
20214
20615
|
try {
|
|
20215
|
-
|
|
20616
|
+
const context = {
|
|
20617
|
+
signal: AbortSignal.any([external, turnController.signal]),
|
|
20618
|
+
callId: id,
|
|
20619
|
+
parentCallId: id
|
|
20620
|
+
};
|
|
20621
|
+
result = codeMode ? await codeByName.get(toolName).execute(args, context) : await executeGranted(toolName, args, context);
|
|
20216
20622
|
} catch (e) {
|
|
20217
|
-
|
|
20623
|
+
succeeded = false;
|
|
20218
20624
|
result = `error: ${e instanceof Error ? e.message : String(e)}`;
|
|
20219
20625
|
}
|
|
20220
|
-
const
|
|
20626
|
+
const projected = succeeded && codeMode && toolName === "codemode" ? codeModeModelOutput(result) : void 0;
|
|
20627
|
+
if (projected) images.push(...projected.images);
|
|
20221
20628
|
messages.push({
|
|
20222
20629
|
role: "tool",
|
|
20223
20630
|
tool_call_id: id,
|
|
20224
|
-
content: result
|
|
20631
|
+
content: projected?.text ?? toolResultText(result)
|
|
20225
20632
|
});
|
|
20226
|
-
try {
|
|
20227
|
-
seam.onToolStep?.({
|
|
20228
|
-
toolName,
|
|
20229
|
-
args,
|
|
20230
|
-
status,
|
|
20231
|
-
startedAt: toolStartedAt,
|
|
20232
|
-
endedAt: toolEndedAt,
|
|
20233
|
-
durationMs: toolEndedAt - toolStartedAt
|
|
20234
|
-
});
|
|
20235
|
-
} catch {}
|
|
20236
20633
|
}
|
|
20634
|
+
if (images.length) messages.push({
|
|
20635
|
+
role: "user",
|
|
20636
|
+
content: [{
|
|
20637
|
+
type: "text",
|
|
20638
|
+
text: "Images emitted by codemode:"
|
|
20639
|
+
}, ...images]
|
|
20640
|
+
});
|
|
20237
20641
|
}
|
|
20238
20642
|
} finally {
|
|
20239
|
-
|
|
20643
|
+
const saved = structuredClone(messages);
|
|
20644
|
+
if (codeMode) await seam.onMessages?.(saved, { codeModeStore: codeMode.snapshotStore() });
|
|
20645
|
+
else await seam.onMessages?.(saved);
|
|
20240
20646
|
}
|
|
20241
20647
|
const estimatedUsd = priceTokens({
|
|
20242
20648
|
model,
|
|
@@ -20256,6 +20662,10 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20256
20662
|
};
|
|
20257
20663
|
const out = {
|
|
20258
20664
|
content: lastText,
|
|
20665
|
+
...codeMode ? {
|
|
20666
|
+
codeModeStore: codeMode.snapshotStore(),
|
|
20667
|
+
modelToolNames: [...modelToolNames]
|
|
20668
|
+
} : {},
|
|
20259
20669
|
...observedModel !== void 0 ? { model: observedModel } : {},
|
|
20260
20670
|
messages,
|
|
20261
20671
|
turns,
|
|
@@ -20309,6 +20719,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20309
20719
|
provider: spec.profile.model?.provider ?? null,
|
|
20310
20720
|
maxTurns,
|
|
20311
20721
|
tools: seam.tools,
|
|
20722
|
+
...seam.codeMode ? { codeMode: seam.codeMode } : {},
|
|
20312
20723
|
temperature: profileExecution.temperature ?? null,
|
|
20313
20724
|
tokenLimits: profileExecution.tokenLimits,
|
|
20314
20725
|
retry: profileExecution.retry ?? null,
|
|
@@ -21474,6 +21885,7 @@ function routerProfileExecution(profile, seam, mode) {
|
|
|
21474
21885
|
const profileEffort = profile.model?.reasoningEffort;
|
|
21475
21886
|
const settings = profileModelExecutionSettings(profile, "routerInlineExecutor");
|
|
21476
21887
|
if (!mode.multiTurn && settings.maxTurns !== void 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.maxTurns requires the router-tools backend");
|
|
21888
|
+
if (!mode.multiTurn && settings.codeMode !== void 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.codeMode requires the router-tools backend");
|
|
21477
21889
|
if (settings.stream === true && seam.complete !== void 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.stream requires the HTTP Router transport; RouterSeam.complete returns one buffered completion and cannot serve a stream");
|
|
21478
21890
|
const declaredTools = profile.tools ?? {};
|
|
21479
21891
|
const suppliedTools = seam.tools ?? [];
|
|
@@ -24526,6 +24938,7 @@ async function captureBeforeCleanup(state, branching, event, events, parent) {
|
|
|
24526
24938
|
const provider = state.provider;
|
|
24527
24939
|
if (provider?.get === void 0) return refuse("the provider cannot reconstruct a fork of the checkpoint", false);
|
|
24528
24940
|
const get = provider.get.bind(provider);
|
|
24941
|
+
if (parent?.aborted) return refuse(`capture failed: ${errorText(abortError(parent, "capture stopped").message)}`, true);
|
|
24529
24942
|
if (branching === void 0) return refuse("source-scoped checkpoint handle unavailable", true);
|
|
24530
24943
|
const material = {
|
|
24531
24944
|
checkpoint: event.checkpoint,
|
|
@@ -24787,12 +25200,23 @@ async function scopeRetainedOwnerSettled(scope) {
|
|
|
24787
25200
|
await state.releasing?.catch(() => void 0);
|
|
24788
25201
|
}
|
|
24789
25202
|
/**
|
|
25203
|
+
* How long one release spends capturing the owner's pending checkpoints, all of them together. A
|
|
25204
|
+
* capture it cuts short keeps its checkpoint and the source, as a failed capture does, and the
|
|
25205
|
+
* release goes on to settle. Each capture is otherwise bounded only by its port, and one at a
|
|
25206
|
+
* time: on Discovery run terraform-dc-model-20261010h-c1 (Runtime 0.314.0) a director's release
|
|
25207
|
+
* waited 00:19:18Z to 01:19:38Z for one capture to reach the port's 60-minute bound, and the run
|
|
25208
|
+
* settled 98 minutes after its deadline. The release captures that finished there took 67 seconds
|
|
25209
|
+
* and 7 and 34 minutes, beside live captures of abandoned directors on the same slots.
|
|
25210
|
+
*/
|
|
25211
|
+
const RELEASE_CHECKPOINT_CAPTURES_MS = 15 * 6e4;
|
|
25212
|
+
/**
|
|
24790
25213
|
* Release the owner's environment once no turn of it will run again: at the run's final
|
|
24791
25214
|
* settlement for the root, and when a nested manager's own scope has finished. A second call while
|
|
24792
25215
|
* one is in flight joins it. The release first waits for the end-of-turn capture of the owner's
|
|
24793
|
-
* last turn, so the capture always precedes the destroy.
|
|
25216
|
+
* last turn, so the capture always precedes the destroy. `capturesMs` bounds the checkpoint
|
|
25217
|
+
* captures it runs ({@link RELEASE_CHECKPOINT_CAPTURES_MS}).
|
|
24794
25218
|
*/
|
|
24795
|
-
function releaseScopeRetainedOwnerEnvironment(scope) {
|
|
25219
|
+
function releaseScopeRetainedOwnerEnvironment(scope, { capturesMs = RELEASE_CHECKPOINT_CAPTURES_MS } = {}) {
|
|
24796
25220
|
const state = owners.get(scope);
|
|
24797
25221
|
const provider = state?.provider;
|
|
24798
25222
|
if (state === void 0 || provider === void 0) return Promise.resolve([]);
|
|
@@ -24800,14 +25224,14 @@ function releaseScopeRetainedOwnerEnvironment(scope) {
|
|
|
24800
25224
|
const tracked = (async () => {
|
|
24801
25225
|
await ownerDriveEnded(state);
|
|
24802
25226
|
await scopeRetainedOwnerTurnEnded(scope);
|
|
24803
|
-
return await releaseOwnerEnvironment(state, provider);
|
|
25227
|
+
return await releaseOwnerEnvironment(state, provider, capturesMs);
|
|
24804
25228
|
})().finally(() => {
|
|
24805
25229
|
if (state.releasing === tracked) delete state.releasing;
|
|
24806
25230
|
});
|
|
24807
25231
|
state.releasing = tracked;
|
|
24808
25232
|
return tracked;
|
|
24809
25233
|
}
|
|
24810
|
-
async function releaseOwnerEnvironment(state, provider) {
|
|
25234
|
+
async function releaseOwnerEnvironment(state, provider, capturesMs) {
|
|
24811
25235
|
const { args } = state;
|
|
24812
25236
|
state.checkpointsUnavailable ??= "released";
|
|
24813
25237
|
await state.checkpointing?.catch(() => void 0);
|
|
@@ -24825,11 +25249,17 @@ async function releaseOwnerEnvironment(state, provider) {
|
|
|
24825
25249
|
const checkpointsKept = [];
|
|
24826
25250
|
const uncapturedSources = /* @__PURE__ */ new Set();
|
|
24827
25251
|
const pending = pendingCheckpoints(events, state).filter((event) => !retentionFailures.has(event.environmentId));
|
|
24828
|
-
|
|
24829
|
-
|
|
24830
|
-
|
|
24831
|
-
|
|
24832
|
-
|
|
25252
|
+
const captures = new AbortController();
|
|
25253
|
+
const capturesTimer = setTimeout(() => captures.abort(/* @__PURE__ */ new Error(`the release's ${capturesMs} ms for checkpoint captures ran out; checkpoint and source kept`)), capturesMs);
|
|
25254
|
+
try {
|
|
25255
|
+
for (const sourceEnvironmentId of new Set(pending.map((event) => event.environmentId))) {
|
|
25256
|
+
const cleaned = await cleanCheckpoints(state, await checkpointHandle(state, sourceEnvironmentId, AbortSignal.any([captures.signal, AbortSignal.timeout(3e4)])), pending.filter((event) => event.environmentId === sourceEnvironmentId), events, captures.signal);
|
|
25257
|
+
checkpointFailures.push(...cleaned.unconfirmed);
|
|
25258
|
+
checkpointsKept.push(...cleaned.refused);
|
|
25259
|
+
for (const refusal of cleaned.refused) if (refusal.needsSource) uncapturedSources.add(sourceEnvironmentId);
|
|
25260
|
+
}
|
|
25261
|
+
} finally {
|
|
25262
|
+
clearTimeout(capturesTimer);
|
|
24833
25263
|
}
|
|
24834
25264
|
const forksUnresolved = await settleCaptureForks(state);
|
|
24835
25265
|
for (const event of checkpointFailures) pendingSources.add(event.environmentId);
|
|
@@ -30220,6 +30650,6 @@ function isNonEmptySpend(s) {
|
|
|
30220
30650
|
return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false || Object.values(s.resources ?? {}).some((resource) => resource.amount > 0 || !resource.known);
|
|
30221
30651
|
}
|
|
30222
30652
|
//#endregion
|
|
30223
|
-
export { environmentReader as $,
|
|
30653
|
+
export { environmentReader as $, unknownExecutionBindingReceipt as $i, parseWorkerToolTraceArtifact as $n, loopEventToOtelSpan as $r, PEER_MAIL_WIRE_KEY as $t, scopeOwnerExecutorNodeContext as A, promptResourceProfileMaterialization as Ai, resolveAgentEnvironmentProvider as An, resolveHarnessTranscriptCapture as Ar, captureReusableExecutorConfig as At, consumeScopeRetainedOwnerResult as B, finalizeRuntimeOwnedPendingExecutor as Bi, InMemoryResultBlobStore as Bn, mergeTraceEnv as Br, createInPlaceCliExecutor as Bt, deriveNodeExecutionIdentity as C, promptOptionsFromAgentTurnInput as Ca, controlProfileMaterialization as Ci, readPromptOptions as Cn, abortError as Cr, createContinuationKeeper as Ct, recordScopeOwnerMaterialization as D, promptControlProfileMaterialization as Di, createAgentEnvironmentProviderRegistry as Dn, harnessTranscriptArtifact as Dr, passedItems as Dt, recordScopeOwnerDriverAttempt as E, profileMaterializationAxes$1 as Ei, LEAF_CONTINUATION_TASK as En, captureHarnessTranscript as Er, failedItems as Et, seatExecutionProfile as F, validateProfileMaterialization as Fi, retainedExecutorSeamKey as Fn, runCodeMode as Fr, snapshotExecutorConfig as Ft, scopeRetainedOwnerContext as G, providerAttemptEvidence as Gi, replaySpawnTree as Gn, resolveRedactor as Gr, workerTraceSeamKey as Gt, prepareScopeRetainedOwnerSeatSwitch as H, knownExecutionBindingReceipt as Hi, insideCursorNamespace as Hn, traceContextToEnv as Hr, readWorkerTraceContext as Ht, abandonScopeRetainedOwnerInvocation as I, worktreeCliProfileMaterialization as Ii, unavailablePauseMs as In, priceTokens as Ir, createWorktreeCliExecutor as It, scopeRetainedOwnerResourceReader as J, runtimeOwnedExecutorExecutionBinding as Ji, readCommittedJsonLines as Jn, buildRuntimeEventOtelSpans as Jr, createActivityLog as Jt, scopeRetainedOwnerJournalRoot as K, recordRuntimeOwnedDriveHarnessProviderEvidence as Ki, isNoEntError as Kn, buildLoopOtelSpans as Kr, taskToPrompt as Kt, beginScopeRetainedOwnerDrive as L, attestRuntimeOwnedPendingExecutor as Li, unavailableSignalOfFailure as Ln, routerTokenPrice as Lr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Lt, SeatChain as M, renderUnsupported as Mi, decodeToolPart as Mn, contentAddress as Mr, cliWorktreeExecutor as Mt, SeatChainExhaustedError as N, sandboxActProfileMaterialization as Ni, sandboxSessionTraceSource as Nn, createCodeModeTools as Nr, createExecutor as Nt, recordScopeOwnerPause as O, promptModelProfileMaterialization as Oi, providerAsExecutor as On, persistHarnessTranscript as Or, verdictFromJudgeScore as Ot, authoredSeatStages as P, unsupportedProfileDimensions as Pi, registerRetainedExecutorPreparation as Pn, describeCodeModeTools as Pr, createExecutorRegistry as Pt, SPAWN_RESOURCE_PATH_MAX_BYTES as Q, runtimeOwnedScopeOwnerRuntime as Qi, isTraceAnalysisStore as Qn, generateSpanId as Qr, DEFAULT_PEER_MAIL_LIMITS as Qt, bindScopeRetainedOwnerEnvironmentId as R, attestRuntimeOwnedScopeOwner as Ri, FileResultBlobStore as Rn, ROUTER_PRICE_SOURCE as Rr, createSteerableSandboxSession as Rt, createScope as S, promptFromAgentTurnInput as Sa, assertProfileMaterialization as Si, assertBoxlessPromptOptions as Sn, RunCancellationReason as Sr, checkVerdictOf as St, meterRuntimeOwnedProviderAttempt as T, fullProfileMaterialization as Ti, runBrainLoop as Tn, runAbortable as Tr, expandQuestions as Tt, prepareScopeRetainedOwnerTask as U, knownMaterializationReceipt as Ui, loadSpawnForest as Un, defaultRedactor as Ur, workerTraceEnv as Ut, noteScopeRetainedOwnerCoordination as V, inheritRuntimeOwnedExecutorAttestation as Vi, InMemorySpawnJournal as Vn, readTraceContextFromEnv as Vr, WORKER_TRACE_PROPAGATION as Vt, reconcileScopeRetainedOwnerEnvironment as W, newExecutionAttemptId as Wi, materializeTreeView as Wn, defaultRedactorIdentityMaterial as Wr, workerTraceHeaders as Wt, scopeRetainedOwnerResult as X, runtimeOwnedExecutorProviderEvidence as Xi, WORKER_TOOL_TRACE_SCHEMA_VERSION as Xn, createOtelExporter as Xr, createInbox as Xt, scopeRetainedOwnerRestorePoint as Y, runtimeOwnedExecutorMaterialization as Yi, writeAllBytes as Yn, createOpenInferenceFileExporter as Yr, readWorkerProgress as Yt, scopeRetainedOwnerTurnEnded as Z, runtimeOwnedPendingExecutorMaterialization as Zi, captureWorkerTraceEvidence as Zn, flatOtelSpan as Zr, AUTHORITY_MARKERS as Zt, isDriverSpec as _, sandboxProgressEvents as _a, localHarnessExecutable as _i, runAgentRounds as _n, retainedCreateMaterial as _r, CONTINUATION_FACTS as _t, collectDelivered as a, projectSandboxOutcome as aa, sanitizeAgentRuntimeEvent as ai, isLiveNodeStatus as an, createBudgetPool as ar, interactiveAdmissionSeamKey as at, assertRecursiveReservationPolicy as b, abortError$1 as ba, terminateProcessTreeAndConfirm as bi, SandboxEvidenceRetentionError as bn, createWorkerSlots as br, admitFinding as bt, runTree as c, canonicalStreamEventFromSandboxEvent as ca, runSettledCommand as ci, bridgeModelRouteRefusal as cn, spendFromUsageEvents as cr, reconnectRetainedInteractiveRun as ct, classifyDriverFailure as d, extractLlmCallEvent as da, createWorktree as di, harnessUsageIsEmpty as dn, bridgeStopSignalKey as dr, freeSlots as dt, unknownMaterializationReceipt as ea, padSpanId as ei, claimsAuthority as en, workerTraceAnalysisStore as er, hostDirectoryReader as et, runDriverWithRetry as f, isSandboxTerminalEvent as fa, removeWorktree as fi, readCodexRolloutSession as fn, errMessage as fr, queueOf as ft, driverExecutorFactory as g, sandboxEventServedBackend as ga, harnessSupportsReasoningEffort as gi, isTerminalDecision as gn, startRetainedRunInEnvironment as gr, CONTINUATIONS_DIR as gt, driverChild as h, notifySandboxEventObserver as ha, harnessInvocation as hi, defaultSelectWinner as hn, startRetainedRun as hr, mapExecutorResult as ht, bestDelivered as i, detachedSnapshot as ia, createRuntimeStreamEventCollector as ii, peerMailVerbNames as in, assertValidBudget as ir, providerVisibleProfile as it, settledToIteration as j, renderProfileMaterializationIssues as ji, createPushTraceSource as jn, retainHarnessTranscript as jr, cliInPlaceExecutor as jt, restoreScopeOwnerAcceptedExecution as k, promptOnlyProfileMaterialization as ki, providerAsSandboxClient as kn, readHarnessTranscript as kr, bindReusableExecutorExecutionId as kt, DriverAttemptsExhaustedError as l, createSandboxToolPartState as la, runWorktreeHarness as li, addHarnessUsage as ln, spendFromUsageTotals as lr, recoverRetainedInteractiveRun as lt, upstreamUnavailableSignal as m, mapSandboxToolEvent as ma, LOCAL_HARNESSES as mi, createSandboxForSpec as mn, recoverRetainedRun as mr, gateOnDeliverable as mt, createRootHandle as n, executableAgentSpecSnapshot as na, toOtelAttributes as ni, isPeerMailEnvelope as nn, BudgetReconcileFault as nr, coordinationMcpAlias as nt, pickBestDelivered as o, readSandboxOutcome as oa, sanitizeKnowledgeReadinessReport as oi, isTerminalNodeStatus as on, meterUsageEvent as or, attachWorker as ot, summarizeDriverAttempts as p, mapSandboxEvent as pa, DEFAULT_LOCAL_HARNESS as pi, TERMINAL_DECISIONS as pn, reconnectRetainedRun as pr, rollingDispatch as pt, scopeRetainedOwnerPriorSpend as q, runtimeOwnedDriveHarnessProviderEvidence as qi, prepareJsonlAppend as qn, buildLoopSpanNodes as qr, DEFAULT_STALL_AFTER_MS as qt, createSupervisor as r, detachedFrozen as ra, createRuntimeEventCollector as ri, peerMailTools as rn, ReservationWaitRefused as rr, coordinationProfileToolPrefix as rt, runFinalizer as s, assertSandboxServedModel as sa, sanitizeRuntimeStreamEvent as si, bridgeAdmissionRefusal as sn, newUsageTotals as sr, readWorkerInteractiveBinding as st, DEFAULT_MAX_DEPTH as t, executableAgentProfileSnapshot as ta, padTraceId as ti, createPeerMailbox as tn, executorFailure as tr, resolveSpawnResourcePaths as tt, HarnessTurnFailedError as u, createSandboxUsageLedger as ua, captureWorktreeDiff as ui, createCodexRolloutStoreReader as un, bridgeRuntimeAttachmentsKey as ur, startRetainedInteractiveRun as ut, withDriverExecutor as v, sumSandboxUsage as va, parseCodexTokenUsage as vi, createSandboxLineage as vn, destroyInteractiveEnvironment as vr, CheckUnavailableError as vt, meterRuntimeOwnedAccounting as w, providerMessageText as wa, defineProfileMaterializationContract as wi, routerBrain as wn, linkAbort as wr, distillFindings as wt, beginScopeOwnerAttempt as x, awaitAbortable$1 as xa, AGENT_PROFILE_MATERIALIZATION_AXES as xi, captureBeforeDestroy as xn, openSlotGroup as xr, bestComposite as xt, SUBTREE_RESULT_LIMIT as y, decodeHarnessUsage as ya, CodexExecutionDiagnosticError as yi, acquireSandbox as yn, environmentGone as yr, admitContinuationPolicy as yt, bindScopeRetainedOwnerProvider as z, authoredProfileDigest as zi, FileSpawnJournal as zn, createPropagatingTraceEmitter as zr, createRouterTranscript as zt };
|
|
30224
30654
|
|
|
30225
|
-
//# sourceMappingURL=supervisor-
|
|
30655
|
+
//# sourceMappingURL=supervisor-BXEL_Fxe.js.map
|