@tangle-network/agent-runtime 0.91.0 → 0.92.1
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/README.md +4 -2
- package/dist/agent.d.ts +3 -3
- package/dist/agent.js +106 -25
- package/dist/agent.js.map +1 -1
- package/dist/{mcp-serve-verifier-XsX8rkB9.d.ts → agentic-generator-B8oeE2Yv.d.ts} +6 -33
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/candidate-execution/index.d.ts +104 -0
- package/dist/candidate-execution/index.js +34 -0
- package/dist/candidate-execution/index.js.map +1 -0
- package/dist/chunk-3D2RHC4K.js +73 -0
- package/dist/chunk-3D2RHC4K.js.map +1 -0
- package/dist/chunk-3MDZX7YU.js +125 -0
- package/dist/chunk-3MDZX7YU.js.map +1 -0
- package/dist/chunk-4FPXIMSI.js +659 -0
- package/dist/chunk-4FPXIMSI.js.map +1 -0
- package/dist/chunk-6O73TRHW.js +142 -0
- package/dist/chunk-6O73TRHW.js.map +1 -0
- package/dist/chunk-A62TP7SK.js +4784 -0
- package/dist/chunk-A62TP7SK.js.map +1 -0
- package/dist/{chunk-AD7JW4QG.js → chunk-BVVRQ4YC.js} +23 -1231
- package/dist/chunk-BVVRQ4YC.js.map +1 -0
- package/dist/chunk-FDJ7AHXG.js +1229 -0
- package/dist/chunk-FDJ7AHXG.js.map +1 -0
- package/dist/{chunk-FF77IBQM.js → chunk-FRBHUNQ7.js} +2 -141
- package/dist/chunk-FRBHUNQ7.js.map +1 -0
- package/dist/chunk-J2K6WIG6.js +2172 -0
- package/dist/chunk-J2K6WIG6.js.map +1 -0
- package/dist/{chunk-JRS3YSRZ.js → chunk-LQQPGRKT.js} +2 -2
- package/dist/{chunk-IOUUITQA.js → chunk-P6B3Z7PR.js} +3 -3
- package/dist/chunk-PH65PR4F.js +860 -0
- package/dist/chunk-PH65PR4F.js.map +1 -0
- package/dist/{chunk-7ON74BQO.js → chunk-R5GWDTM3.js} +2 -2
- package/dist/{chunk-DWWII6N2.js → chunk-TKJ3Q6CQ.js} +2 -2
- package/dist/{chunk-NC66AM3S.js → chunk-UO2L5VTP.js} +32 -1413
- package/dist/chunk-UO2L5VTP.js.map +1 -0
- package/dist/{chunk-BZF3KQ6G.js → chunk-VSWBYWFK.js} +4 -122
- package/dist/chunk-VSWBYWFK.js.map +1 -0
- package/dist/{completion-gate-DkAnUmpb.d.ts → completion-gate-BLaiN0-X.d.ts} +1 -1
- package/dist/{coordination-rRj5hjJK.d.ts → coordination-DxJ83oZA.d.ts} +12 -5
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +2 -1
- package/dist/improve-CUVCq7xg.d.ts +152 -0
- package/dist/{improvement-adapter-CDR8QNVM.d.ts → improvement-adapter-BieWeK5J.d.ts} +16 -0
- package/dist/index.d.ts +27 -1092
- package/dist/index.js +108 -6491
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +160 -13
- package/dist/intelligence.js +534 -59
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +6 -6
- package/dist/knowledge.js +6 -4
- package/dist/lifecycle.d.ts +2 -1
- package/dist/lifecycle.js +5 -3
- package/dist/lifecycle.js.map +1 -1
- package/dist/{loop-runner-bin-DTbZVGfM.d.ts → loop-runner-bin-kKUNGLyV.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +8 -5
- package/dist/loops.d.ts +16 -16
- package/dist/loops.js +47 -41
- package/dist/mcp/bin.js +6 -4
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -8
- package/dist/mcp/index.js +9 -6
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp-serve-verifier-Bg4C3p5S.d.ts +34 -0
- package/dist/{openai-tools-C4ZfUD4L.d.ts → openai-tools-E3woykz9.d.ts} +1 -1
- package/dist/prepare-Z08a4heC.d.ts +713 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/{router-client-DJImUDlm.d.ts → sanitize-C9go6tXj.d.ts} +113 -1
- package/dist/{structural-rollout-MwlpgQ-6.d.ts → structural-rollout-DHGDbhvR.d.ts} +3 -3
- package/dist/{supervise-DPmYPk0j.d.ts → supervise-T2pazU3G.d.ts} +4 -4
- package/dist/{types-SyuwunY_.d.ts → types-B00NtbCs.d.ts} +1 -1
- package/dist/{types-eMNgWgFi.d.ts → types-DAdIm4AC.d.ts} +1 -1
- package/dist/{worktree-fanout-BDFQIO-Y.d.ts → worktree-fanout-BUb2Ag02.d.ts} +3 -3
- package/package.json +11 -6
- package/skills/build-with-agent-runtime/SKILL.md +1 -1
- package/dist/chunk-AD7JW4QG.js.map +0 -1
- package/dist/chunk-BZF3KQ6G.js.map +0 -1
- package/dist/chunk-FF77IBQM.js.map +0 -1
- package/dist/chunk-IVGYLCFH.js +0 -381
- package/dist/chunk-IVGYLCFH.js.map +0 -1
- package/dist/chunk-NC66AM3S.js.map +0 -1
- /package/dist/{chunk-JRS3YSRZ.js.map → chunk-LQQPGRKT.js.map} +0 -0
- /package/dist/{chunk-IOUUITQA.js.map → chunk-P6B3Z7PR.js.map} +0 -0
- /package/dist/{chunk-7ON74BQO.js.map → chunk-R5GWDTM3.js.map} +0 -0
- /package/dist/{chunk-DWWII6N2.js.map → chunk-TKJ3Q6CQ.js.map} +0 -0
|
@@ -1,112 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
try {
|
|
5
|
-
await box.delete();
|
|
6
|
-
return true;
|
|
7
|
-
} catch {
|
|
8
|
-
return false;
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
function randomSuffix(len = 8) {
|
|
12
|
-
return Math.random().toString(36).slice(2, 2 + len);
|
|
13
|
-
}
|
|
14
|
-
function randomUuid() {
|
|
15
|
-
return crypto.randomUUID();
|
|
16
|
-
}
|
|
17
|
-
function abortError() {
|
|
18
|
-
const err = new Error("aborted");
|
|
19
|
-
err.name = "AbortError";
|
|
20
|
-
return err;
|
|
21
|
-
}
|
|
22
|
-
function throwAbort() {
|
|
23
|
-
throw abortError();
|
|
24
|
-
}
|
|
25
|
-
function throwIfAborted(signal) {
|
|
26
|
-
if (signal?.aborted) throw abortError();
|
|
27
|
-
}
|
|
28
|
-
function isAbortError(err) {
|
|
29
|
-
return err instanceof Error && err.name === "AbortError";
|
|
30
|
-
}
|
|
31
|
-
function sleep(ms, signal) {
|
|
32
|
-
return new Promise((resolve) => {
|
|
33
|
-
if (signal?.aborted) {
|
|
34
|
-
resolve();
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
let onAbort;
|
|
38
|
-
const timer = setTimeout(() => {
|
|
39
|
-
if (onAbort && signal) signal.removeEventListener("abort", onAbort);
|
|
40
|
-
resolve();
|
|
41
|
-
}, ms);
|
|
42
|
-
if (signal) {
|
|
43
|
-
onAbort = () => {
|
|
44
|
-
clearTimeout(timer);
|
|
45
|
-
resolve();
|
|
46
|
-
};
|
|
47
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
function withTimeout(promise, ms) {
|
|
52
|
-
return new Promise((resolve) => {
|
|
53
|
-
const timer = setTimeout(() => resolve(void 0), ms);
|
|
54
|
-
promise.then(
|
|
55
|
-
(value) => {
|
|
56
|
-
clearTimeout(timer);
|
|
57
|
-
resolve(value);
|
|
58
|
-
},
|
|
59
|
-
() => {
|
|
60
|
-
clearTimeout(timer);
|
|
61
|
-
resolve(void 0);
|
|
62
|
-
}
|
|
63
|
-
);
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
function stringifySafe(value, opts = {}) {
|
|
67
|
-
let s;
|
|
68
|
-
try {
|
|
69
|
-
if (typeof value === "string") {
|
|
70
|
-
s = value;
|
|
71
|
-
} else {
|
|
72
|
-
const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
|
|
73
|
-
s = json ?? String(value);
|
|
74
|
-
}
|
|
75
|
-
} catch {
|
|
76
|
-
s = String(value);
|
|
77
|
-
}
|
|
78
|
-
if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}\u2026`;
|
|
79
|
-
return s;
|
|
80
|
-
}
|
|
81
|
-
function zeroTokenUsage() {
|
|
82
|
-
return { input: 0, output: 0 };
|
|
83
|
-
}
|
|
84
|
-
function addTokenUsage(acc, delta) {
|
|
85
|
-
acc.input += delta.input ?? 0;
|
|
86
|
-
acc.output += delta.output ?? 0;
|
|
87
|
-
}
|
|
88
|
-
async function mapWithConcurrency(items, limit, fn) {
|
|
89
|
-
const bound = Math.max(1, Math.floor(limit));
|
|
90
|
-
const results = new Array(items.length);
|
|
91
|
-
let next = 0;
|
|
92
|
-
let failed = false;
|
|
93
|
-
const worker = async () => {
|
|
94
|
-
while (!failed) {
|
|
95
|
-
const i = next;
|
|
96
|
-
next += 1;
|
|
97
|
-
if (i >= items.length) return;
|
|
98
|
-
try {
|
|
99
|
-
results[i] = await fn(items[i], i);
|
|
100
|
-
} catch (err) {
|
|
101
|
-
failed = true;
|
|
102
|
-
throw err;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
const workerCount = Math.min(bound, items.length);
|
|
107
|
-
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
|
108
|
-
return results;
|
|
109
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
zeroTokenUsage
|
|
3
|
+
} from "./chunk-3MDZX7YU.js";
|
|
110
4
|
|
|
111
5
|
// src/runtime/environment-provider.ts
|
|
112
6
|
var ValidationError = class extends Error {
|
|
@@ -904,22 +798,10 @@ function hasFork(box) {
|
|
|
904
798
|
}
|
|
905
799
|
|
|
906
800
|
export {
|
|
907
|
-
deleteBoxSafe,
|
|
908
|
-
randomSuffix,
|
|
909
|
-
randomUuid,
|
|
910
|
-
throwAbort,
|
|
911
|
-
throwIfAborted,
|
|
912
|
-
isAbortError,
|
|
913
|
-
sleep,
|
|
914
|
-
withTimeout,
|
|
915
|
-
stringifySafe,
|
|
916
|
-
zeroTokenUsage,
|
|
917
|
-
addTokenUsage,
|
|
918
|
-
mapWithConcurrency,
|
|
919
801
|
createAgentEnvironmentProviderRegistry,
|
|
920
802
|
resolveAgentEnvironmentProvider,
|
|
921
803
|
providerAsSandboxClient,
|
|
922
804
|
sandboxClientAsProvider,
|
|
923
805
|
providerAsExecutor
|
|
924
806
|
};
|
|
925
|
-
//# sourceMappingURL=chunk-
|
|
807
|
+
//# sourceMappingURL=chunk-VSWBYWFK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/environment-provider.ts"],"sourcesContent":["import type {\n AgentProfile,\n AgentProfileValidationResult,\n InputPart,\n TokenUsage,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n BackendType,\n CreateSandboxOptions,\n PromptOptions,\n PromptResult,\n SandboxEvent,\n ExecResult as SandboxExecResult,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport type {\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './supervise/types'\nimport type { LoopSandboxPlacement, SandboxClient } from './types'\nimport { zeroTokenUsage } from './util'\n\n// Keep this file loadable from the lean `./environment-provider` export without agent-eval installed.\nclass ValidationError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n WorkspaceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\n\n/** Provider object or registry name accepted by runtime provider adapters.\n * @experimental */\nexport type AgentEnvironmentProviderRef = AgentEnvironmentProvider | string\n\n/** In-memory registry for named `AgentEnvironmentProvider` instances.\n * @experimental */\nexport interface AgentEnvironmentProviderRegistry {\n register(provider: AgentEnvironmentProvider, options?: { replace?: boolean }): void\n has(name: string): boolean\n get(name: string): AgentEnvironmentProvider | undefined\n require(name: string): AgentEnvironmentProvider\n names(): string[]\n providers(): AgentEnvironmentProvider[]\n capabilities(name: string): Promise<AgentEnvironmentCapabilities>\n}\n\n/** Create a registry that resolves provider names to concrete provider instances.\n * @experimental */\nexport function createAgentEnvironmentProviderRegistry(\n providers: Iterable<AgentEnvironmentProvider> = [],\n): AgentEnvironmentProviderRegistry {\n const entries = new Map<string, AgentEnvironmentProvider>()\n\n const registry: AgentEnvironmentProviderRegistry = {\n register(provider, options = {}): void {\n if (!provider.name) {\n throw new ValidationError('agent environment provider registry: provider.name required')\n }\n if (!options.replace && entries.has(provider.name)) {\n throw new ValidationError(\n `agent environment provider registry: provider \"${provider.name}\" already registered`,\n )\n }\n entries.set(provider.name, provider)\n },\n has(name): boolean {\n return entries.has(name)\n },\n get(name): AgentEnvironmentProvider | undefined {\n return entries.get(name)\n },\n require(name): AgentEnvironmentProvider {\n const provider = entries.get(name)\n if (!provider) {\n const available = Array.from(entries.keys()).sort()\n const suffix = available.length > 0 ? `; available: ${available.join(', ')}` : ''\n throw new ValidationError(\n `agent environment provider registry: provider \"${name}\" is not registered${suffix}`,\n )\n }\n return provider\n },\n names(): string[] {\n return Array.from(entries.keys()).sort()\n },\n providers(): AgentEnvironmentProvider[] {\n return registry.names().map((name) => registry.require(name))\n },\n async capabilities(name): Promise<AgentEnvironmentCapabilities> {\n return registry.require(name).capabilities()\n },\n }\n\n for (const provider of providers) registry.register(provider)\n return registry\n}\n\n/** Resolve a provider instance or registry name, failing loudly when a name is unknown.\n * @experimental */\nexport function resolveAgentEnvironmentProvider(\n provider: AgentEnvironmentProviderRef,\n registry?: AgentEnvironmentProviderRegistry,\n): AgentEnvironmentProvider {\n if (typeof provider !== 'string') return provider\n if (!registry) {\n throw new ValidationError(\n `agent environment provider \"${provider}\" requires an AgentEnvironmentProviderRegistry`,\n )\n }\n return registry.require(provider)\n}\n\n/** Options for exposing an `AgentEnvironmentProvider` through the legacy sandbox client port.\n * @experimental */\nexport interface ProviderAsSandboxClientOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n requireTerminalEvent?: boolean\n mapCreateOptions?: (\n options: CreateSandboxOptions | undefined,\n ) => Partial<CreateAgentEnvironmentInput>\n}\n\n/** Adapt a neutral environment provider to the `SandboxClient` interface used by existing loop paths.\n * @experimental */\nexport function providerAsSandboxClient(\n provider: AgentEnvironmentProvider,\n options: ProviderAsSandboxClientOptions = {},\n): SandboxClient {\n return {\n async create(createOptions?: CreateSandboxOptions): Promise<SandboxInstance> {\n const mapped = {\n ...(options.defaults ?? {}),\n ...createInputFromSandboxOptions(createOptions),\n ...(options.mapCreateOptions?.(createOptions) ?? {}),\n }\n if (mapped.profile === undefined) {\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): profile required in defaults or CreateSandboxOptions.backend.profile`,\n )\n }\n const environment = await provider.create(mapped as CreateAgentEnvironmentInput)\n return environmentAsSandboxInstance(environment, {\n requireTerminalEvent: options.requireTerminalEvent ?? true,\n })\n },\n }\n}\n\n/** Options for wrapping the current Tangle sandbox client as an environment provider.\n * @experimental */\nexport interface SandboxClientProviderOptions {\n name?: string\n defaultBackend?: BackendType\n capabilities?:\n | AgentEnvironmentCapabilities\n | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>)\n validateProfile?: (\n profile: AgentProfileRef,\n ) => AgentProfileValidationResult | Promise<AgentProfileValidationResult>\n mapCreateInput?: (input: CreateAgentEnvironmentInput) => CreateSandboxOptions\n}\n\n/** Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.\n * @experimental */\nexport function sandboxClientAsProvider(\n client: SandboxClient,\n options: SandboxClientProviderOptions = {},\n): AgentEnvironmentProvider {\n const providerName = options.name ?? 'tangle-sandbox'\n return {\n name: providerName,\n capabilities: async () => {\n if (options.capabilities) {\n return typeof options.capabilities === 'function'\n ? options.capabilities()\n : options.capabilities\n }\n return defaultTangleSandboxCapabilities()\n },\n ...(options.validateProfile ? { validateProfile: options.validateProfile } : {}),\n async create(input: CreateAgentEnvironmentInput): Promise<AgentEnvironment> {\n const createOptions =\n options.mapCreateInput?.(input) ??\n sandboxOptionsFromCreateInput(input, options.defaultBackend ?? 'opencode')\n const box = await client.create(createOptions)\n return sandboxInstanceAsEnvironment(box, providerName, client)\n },\n ...(hasGet(client)\n ? {\n async get(id: string): Promise<AgentEnvironment | null> {\n const box = await client.get(id)\n return box ? sandboxInstanceAsEnvironment(box, providerName, client) : null\n },\n }\n : {}),\n ...(hasList(client)\n ? {\n async list(query?: AgentEnvironmentQuery): Promise<AgentEnvironmentSummary[]> {\n const boxes = await client.list(query?.providerOptions)\n return boxes.map((box) => ({\n id: String(box.id),\n provider: providerName,\n name: typeof box.name === 'string' ? box.name : undefined,\n status: statusFromUnknown(readBoxStatus(box)),\n metadata: readBoxMetadata(box),\n }))\n },\n }\n : {}),\n }\n}\n\n/** Options for running a provider as a supervise-mode executor.\n * @experimental */\nexport interface ProviderExecutorOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n runtime?: Runtime\n destroyOnSettle?: boolean\n requireTerminalEvent?: boolean\n taskToTurn?: (task: unknown, specProfile: AgentProfile) => AgentTurnInput\n}\n\n/** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.\n * @experimental */\nexport function providerAsExecutor(\n provider: AgentEnvironmentProvider,\n options: ProviderExecutorOptions = {},\n): ExecutorFactory<unknown> {\n return (spec, ctx) => createProviderExecutor(provider, spec.profile, ctx, options)\n}\n\nfunction createProviderExecutor(\n provider: AgentEnvironmentProvider,\n profile: AgentProfile,\n ctx: ExecutorContext,\n options: ProviderExecutorOptions,\n): Executor<unknown> {\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let environment: AgentEnvironment | undefined\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: options.runtime ?? (provider.name as Runtime),\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamProviderExecutor({\n provider,\n profile,\n task,\n signal,\n controller,\n options,\n onEnvironment: (env) => {\n environment = env\n },\n onArtifact: (next) => {\n artifact = next\n },\n })\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n await environment?.destroy?.()\n return { destroyed: true }\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError(\n `providerAsExecutor(${provider.name}): resultArtifact() read before stream drained`,\n )\n }\n return artifact\n },\n }\n}\n\ninterface StreamProviderExecutorArgs {\n provider: AgentEnvironmentProvider\n profile: AgentProfile\n task: unknown\n signal: AbortSignal\n controller: AbortController\n options: ProviderExecutorOptions\n onEnvironment: (environment: AgentEnvironment) => void\n onArtifact: (artifact: ExecutorResult<unknown>) => void\n}\n\nasync function* streamProviderExecutor(\n args: StreamProviderExecutorArgs,\n): AsyncIterable<UsageEvent> {\n const started = Date.now()\n const linked = mergeAbortSignals(args.signal, args.controller.signal)\n const environment = await args.provider.create({\n ...(args.options.defaults ?? {}),\n profile: args.profile,\n signal: linked,\n })\n args.onEnvironment(environment)\n\n const turn =\n args.options.taskToTurn?.(args.task, args.profile) ?? taskToTurnInput(args.task, linked)\n const events: AgentEnvironmentEvent[] = []\n const tokens = zeroTokenUsage()\n let usd = 0\n let text = ''\n let terminal = false\n try {\n for await (const event of environment.stream({ ...turn, signal: linked })) {\n events.push(event)\n text += textFromEnvironmentEvent(event)\n const usage = usageFromEnvironmentEvent(event)\n if (usage.input || usage.output) {\n tokens.input += usage.input\n tokens.output += usage.output\n yield { kind: 'tokens', input: usage.input, output: usage.output }\n }\n if (usage.usd) {\n usd += usage.usd\n yield { kind: 'cost', usd: usage.usd }\n }\n if (isTerminalEnvironmentEvent(event)) terminal = true\n }\n if ((args.options.requireTerminalEvent ?? true) && !terminal) {\n throw new ValidationError(\n `providerAsExecutor(${args.provider.name}): stream ended without a terminal result/done/status event`,\n )\n }\n yield { kind: 'iteration' }\n const result = resultFromEvents(events, text)\n const spent: Spend = {\n iterations: 1,\n tokens,\n usd,\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef(`provider:${args.provider.name}`, result),\n out: result,\n spent,\n })\n } finally {\n if (args.options.destroyOnSettle ?? true) await environment.destroy?.()\n }\n}\n\nfunction createInputFromSandboxOptions(\n options: CreateSandboxOptions | undefined,\n): Partial<CreateAgentEnvironmentInput> {\n const profile = options?.backend?.profile as AgentProfileRef | undefined\n const backend = options?.backend?.type\n return {\n ...(profile !== undefined ? { profile } : {}),\n ...(backend ? { backend } : {}),\n workspace: {\n ...(options?.environment ? { environment: options.environment } : {}),\n ...(options?.image ? { image: options.image } : {}),\n ...(options?.git?.url ? { repoUrl: options.git.url } : {}),\n ...(options?.git?.ref ? { gitRef: options.git.ref } : {}),\n },\n ...(options?.resources ? { resources: options.resources as ResourceRequest } : {}),\n ...(options?.env ? { env: options.env } : {}),\n ...(options?.secrets ? { secrets: options.secrets } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n providerOptions: { sandboxCreateOptions: options ?? {} },\n }\n}\n\nfunction sandboxOptionsFromCreateInput(\n input: CreateAgentEnvironmentInput,\n defaultBackend: BackendType,\n): CreateSandboxOptions {\n const backendType = (input.backend ?? defaultBackend) as BackendType\n const workspace = input.workspace ?? {}\n const providerOptions = input.providerOptions?.sandboxCreateOptions\n const base =\n providerOptions && typeof providerOptions === 'object'\n ? ({ ...(providerOptions as CreateSandboxOptions) } as CreateSandboxOptions)\n : ({} satisfies CreateSandboxOptions)\n return {\n ...base,\n ...(workspace.environment ? { environment: workspace.environment } : {}),\n ...(workspace.image ? { image: workspace.image } : {}),\n ...(workspace.repoUrl ? { git: { url: workspace.repoUrl, ref: workspace.gitRef } } : {}),\n ...(input.resources ? { resources: input.resources as CreateSandboxOptions['resources'] } : {}),\n ...(input.env ? { env: input.env } : {}),\n ...(Array.isArray(input.secrets) ? { secrets: input.secrets } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n ...(input.name ? { name: input.name } : {}),\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n backend: {\n ...(base.backend ?? {}),\n type: backendType,\n profile: input.profile,\n },\n }\n}\n\nfunction environmentAsSandboxInstance(\n environment: AgentEnvironment,\n options: { requireTerminalEvent: boolean },\n): SandboxInstance {\n const box = {\n id: environment.id,\n name: environment.name,\n status: 'running',\n async refresh(): Promise<void> {\n await environment.refresh?.()\n },\n async *streamPrompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): AsyncGenerator<SandboxEvent> {\n let terminal = false\n const input = turnInputFromPrompt(message, promptOptions)\n for await (const event of environment.stream(input)) {\n if (isTerminalEnvironmentEvent(event)) terminal = true\n const usageEvent = usageSandboxEvent(event)\n if (usageEvent) yield usageEvent\n yield sandboxEventFromEnvironmentEvent(event)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): stream ended without a terminal result/done/status event`,\n )\n }\n },\n async prompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): Promise<PromptResult> {\n const events: AgentEnvironmentEvent[] = []\n let text = ''\n let usage: TokenUsage | undefined\n let terminal = false\n for await (const event of environment.stream(turnInputFromPrompt(message, promptOptions))) {\n events.push(event)\n if (isTerminalEnvironmentEvent(event)) terminal = true\n text += textFromEnvironmentEvent(event)\n usage = mergeTokenUsage(usage, event.usage)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): prompt ended without a terminal result/done/status event`,\n )\n }\n return promptResultCompat(\n {\n response: resultFromEvents(events, text).content,\n success: true,\n durationMs: 0,\n ...(usage ? { usage } : {}),\n },\n 'success',\n )\n },\n ...(environment.dispatch\n ? {\n async dispatchPrompt(message: string | InputPart[], promptOptions?: PromptOptions) {\n const session = await environment.dispatch?.(\n turnInputFromPrompt(message, promptOptions),\n )\n if (!session)\n throw new ValidationError('providerAsSandboxClient: dispatch returned no session')\n return sandboxDispatchResultFromSessionRef(session)\n },\n }\n : {}),\n ...(environment.session\n ? {\n session(id: string) {\n return sessionAsSandboxSession(environment.session?.(id))\n },\n }\n : {}),\n ...(environment.read ? { read: environment.read.bind(environment) } : {}),\n ...(environment.write ? { write: environment.write.bind(environment) } : {}),\n ...(environment.exec\n ? {\n exec: environment.exec.bind(environment),\n }\n : {}),\n ...(environment.checkpoint\n ? {\n async checkpoint(checkpointOptions?: CheckpointRequest) {\n const checkpoint = await environment.checkpoint?.(checkpointOptions)\n return { checkpointId: checkpoint?.id, id: checkpoint?.id }\n },\n }\n : {}),\n ...(environment.fork\n ? {\n async fork(checkpointId: string, forkOptions?: ForkRequest) {\n const forked = await environment.fork?.({ id: checkpointId }, forkOptions)\n if (!forked)\n throw new ValidationError('providerAsSandboxClient: fork returned no environment')\n return environmentAsSandboxInstance(forked, options)\n },\n }\n : {}),\n async delete(): Promise<void> {\n await environment.destroy?.()\n },\n }\n return box as unknown as SandboxInstance\n}\n\nfunction sandboxInstanceAsEnvironment(\n box: SandboxInstance,\n providerName: string,\n client: SandboxClient,\n): AgentEnvironment {\n const environment: AgentEnvironment = {\n id: String(box.id),\n provider: providerName,\n ...(typeof box.name === 'string' ? { name: box.name } : {}),\n async status(): Promise<AgentEnvironmentStatus> {\n await maybeRefresh(box)\n return statusFromUnknown(readBoxStatus(box))\n },\n async *stream(input: AgentTurnInput): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of box.streamPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )) {\n yield environmentEventFromSandboxEvent(event)\n }\n },\n ...(hasDispatchPrompt(box)\n ? {\n async dispatch(input: AgentTurnInput): Promise<AgentSessionRef> {\n const dispatched = await box.dispatchPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )\n return sessionRefFromSandboxDispatch(dispatched, providerName)\n },\n }\n : {}),\n ...(hasSession(box)\n ? {\n session(id: string): AgentSession {\n return sandboxSessionAsAgentSession(box.session(id))\n },\n }\n : {}),\n ...(hasRead(box) ? { read: box.read.bind(box) } : {}),\n ...(hasWrite(box) ? { write: box.write.bind(box) } : {}),\n ...(hasExec(box)\n ? {\n async exec(command: string, options?: ExecRequest): Promise<ExecResult> {\n return execResultFromSandboxExecResult(await box.exec(command, options as never))\n },\n }\n : {}),\n ...(hasCheckpoint(box)\n ? {\n async checkpoint(options?: CheckpointRequest): Promise<CheckpointRef> {\n const result = await box.checkpoint(options as never)\n return { id: checkpointIdFromResult(result), provider: providerName }\n },\n }\n : {}),\n ...(hasFork(box)\n ? {\n async fork(checkpoint: CheckpointRef, options?: ForkRequest): Promise<AgentEnvironment> {\n const forked = await box.fork(checkpoint.id, options as never)\n return sandboxInstanceAsEnvironment(forked, providerName, client)\n },\n }\n : {}),\n async placement(): Promise<PlacementInfo> {\n return placementInfoFromLoopPlacement(client.describePlacement?.(box), box)\n },\n async refresh(): Promise<void> {\n await maybeRefresh(box)\n },\n async destroy(): Promise<void> {\n await destroyBox(box)\n },\n }\n return environment\n}\n\nfunction sandboxSessionAsAgentSession(session: SandboxSessionLike): AgentSession {\n return {\n id: session.id,\n async status(): Promise<AgentSessionStatus | null> {\n const status = await session.status()\n if (!status) return null\n return sessionStatusFromUnknown((status as { status?: unknown }).status)\n },\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of session.events(options))\n yield environmentEventFromSandboxEvent(event)\n },\n async result(): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(await session.result())\n },\n async prompt(input: AgentTurnInput): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(\n await session.prompt(promptFromTurnInput(input), promptOptionsFromTurnInput(input)),\n )\n },\n cancel(): Promise<void> {\n return session.cancel()\n },\n }\n}\n\nfunction sessionAsSandboxSession(session: AgentSession | undefined): unknown {\n if (!session) throw new ValidationError('providerAsSandboxClient: session(id) returned undefined')\n return {\n id: session.id,\n status: session.status.bind(session),\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncGenerator<SandboxEvent> {\n for await (const event of session.events(options))\n yield sandboxEventFromEnvironmentEvent(event)\n },\n async result(): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(await session.result())\n },\n async prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(\n await session.prompt(turnInputFromPrompt(message, options)),\n )\n },\n cancel: session.cancel.bind(session),\n }\n}\n\nfunction environmentEventFromSandboxEvent(event: SandboxEvent): AgentEnvironmentEvent {\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n return {\n type: String(event.type),\n data,\n ...(event.id ? { id: event.id } : {}),\n usage: tokenUsageFromData(data),\n providerEvent: event,\n }\n}\n\nfunction sandboxEventFromEnvironmentEvent(event: AgentEnvironmentEvent): SandboxEvent {\n return {\n type: event.type,\n data: {\n ...event.data,\n ...(event.usage ? { usage: tokenUsageData(event.usage) } : {}),\n },\n ...(event.id ? { id: event.id } : {}),\n }\n}\n\nfunction usageSandboxEvent(event: AgentEnvironmentEvent): SandboxEvent | undefined {\n if (!event.usage || isUsageType(event.type)) return undefined\n const usage = tokenUsageData(event.usage)\n if (\n usage.inputTokens === undefined &&\n usage.outputTokens === undefined &&\n usage.totalCostUsd === undefined\n ) {\n return undefined\n }\n return { type: 'llm_call', data: usage }\n}\n\nfunction tokenUsageData(usage: TokenUsage): Record<string, number | undefined> {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalCostUsd: usage.cost,\n }\n}\n\nfunction turnInputFromPrompt(\n message: string | InputPart[],\n options?: PromptOptions,\n): AgentTurnInput {\n return {\n ...(typeof message === 'string' ? { prompt: message } : { parts: message }),\n ...(options?.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options?.model ? { model: options.model } : {}),\n ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n ...(options?.executionId ? { executionId: options.executionId } : {}),\n ...(options?.lastEventId ? { lastEventId: options.lastEventId } : {}),\n ...(options?.turnId ? { turnId: options.turnId } : {}),\n ...(options?.detach !== undefined ? { detach: options.detach } : {}),\n ...(options?.context ? { context: options.context } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.backend ? { providerOptions: { backend: options.backend } } : {}),\n }\n}\n\nfunction promptFromTurnInput(input: AgentTurnInput): string | InputPart[] {\n if (input.parts) return input.parts\n return input.prompt ?? ''\n}\n\nfunction promptOptionsFromTurnInput(input: AgentTurnInput): PromptOptions {\n return {\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.model ? { model: input.model } : {}),\n ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n ...(input.lastEventId ? { lastEventId: input.lastEventId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.detach !== undefined ? { detach: input.detach } : {}),\n }\n}\n\nfunction taskToTurnInput(task: unknown, signal: AbortSignal): AgentTurnInput {\n return { prompt: taskToPrompt(task), signal }\n}\n\nfunction taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const record = task as Record<string, unknown>\n for (const key of ['prompt', 'content', 'task', 'message']) {\n if (typeof record[key] === 'string') return record[key]\n }\n }\n return JSON.stringify(task)\n}\n\nfunction resultFromEvents(\n events: AgentEnvironmentEvent[],\n fallbackText: string,\n): { content: string; events: AgentEnvironmentEvent[] } {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n const text = event ? resultTextFromData(event.data) : undefined\n if (text !== undefined) return { content: text, events }\n }\n return { content: fallbackText, events }\n}\n\nfunction textFromEnvironmentEvent(event: AgentEnvironmentEvent): string {\n if (\n typeof event.normalized === 'object' &&\n event.normalized &&\n event.normalized.type === 'message.part.updated'\n ) {\n return typeof event.normalized.delta === 'string' ? event.normalized.delta : ''\n }\n const data = event.data\n for (const key of ['delta', 'chunk', 'content', 'text']) {\n if (typeof data[key] === 'string' && !isTerminalEnvironmentEvent(event)) return data[key]\n }\n return ''\n}\n\nfunction resultTextFromData(data: Record<string, unknown>): string | undefined {\n for (const key of ['finalText', 'text', 'response', 'resultSummary', 'content']) {\n if (typeof data[key] === 'string') return data[key]\n }\n return undefined\n}\n\nfunction isTerminalEnvironmentEvent(event: AgentEnvironmentEvent): boolean {\n if (event.type === 'result' || event.type === 'done' || event.type === 'final') return true\n if (event.type.endsWith('.completed') || event.type.endsWith('.failed')) return true\n if (event.type === 'status') {\n const status = event.data.status\n return status === 'completed' || status === 'failed' || status === 'cancelled'\n }\n return false\n}\n\nfunction isUsageType(type: string): boolean {\n return type === 'llm_call' || type === 'usage' || type === 'cost.usage'\n}\n\nfunction usageFromEnvironmentEvent(event: AgentEnvironmentEvent): {\n input: number\n output: number\n usd: number\n} {\n const usage = event.usage ?? tokenUsageFromData(event.data)\n return {\n input: finiteNumber(usage?.inputTokens) ?? 0,\n output: finiteNumber(usage?.outputTokens) ?? 0,\n usd:\n finiteNumber(usage?.cost) ??\n finiteNumber(event.data.costUsd) ??\n finiteNumber(event.data.totalCostUsd) ??\n 0,\n }\n}\n\nfunction tokenUsageFromData(data: Record<string, unknown>): TokenUsage | undefined {\n const usageRecord =\n data.usage && typeof data.usage === 'object'\n ? (data.usage as Record<string, unknown>)\n : data.tokenUsage && typeof data.tokenUsage === 'object'\n ? (data.tokenUsage as Record<string, unknown>)\n : data\n const inputTokens =\n finiteNumber(usageRecord.inputTokens) ??\n finiteNumber(usageRecord.tokensIn) ??\n finiteNumber(usageRecord.prompt_tokens)\n const outputTokens =\n finiteNumber(usageRecord.outputTokens) ??\n finiteNumber(usageRecord.tokensOut) ??\n finiteNumber(usageRecord.completion_tokens)\n const cost =\n finiteNumber(usageRecord.cost) ??\n finiteNumber(usageRecord.costUsd) ??\n finiteNumber(usageRecord.totalCostUsd) ??\n finiteNumber(data.costUsd) ??\n finiteNumber(data.totalCostUsd)\n if (inputTokens === undefined && outputTokens === undefined && cost === undefined)\n return undefined\n return {\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n ...(cost !== undefined ? { cost } : {}),\n }\n}\n\nfunction mergeTokenUsage(\n left: TokenUsage | undefined,\n right: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (!left) return right\n if (!right) return left\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n ...(left.cost !== undefined || right.cost !== undefined\n ? { cost: (left.cost ?? 0) + (right.cost ?? 0) }\n : {}),\n }\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\ntype PromptResultCompatInput = {\n response?: string\n success: boolean\n error?: string\n traceId?: string\n durationMs: number\n usage?: PromptResult['usage']\n}\n\nfunction promptResultCompat(\n input: PromptResultCompatInput,\n status: 'success' | 'failed',\n): PromptResult {\n // sandbox 0.8 omitted `status`; sandbox 0.9 requires it. Emit it at runtime\n // while keeping this adapter type-checkable across the supported peer range.\n return { ...input, status } as unknown as PromptResult\n}\n\nfunction promptResultFromAgentTurnResult(result: AgentTurnResult): PromptResult {\n return promptResultCompat(\n {\n response: result.text,\n success: result.success,\n durationMs: 0,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage ? { usage: result.usage } : {}),\n },\n result.success ? 'success' : 'failed',\n )\n}\n\nfunction agentTurnResultFromPromptResult(result: PromptResult): AgentTurnResult {\n const record = result as unknown as Record<string, unknown>\n const text =\n typeof record.response === 'string'\n ? record.response\n : typeof record.text === 'string'\n ? record.text\n : typeof record.finalText === 'string'\n ? record.finalText\n : ''\n const success = typeof record.success === 'boolean' ? record.success : true\n return {\n text,\n success,\n ...(typeof record.error === 'string' ? { error: record.error } : {}),\n usage: tokenUsageFromData(record),\n }\n}\n\nfunction sandboxDispatchResultFromSessionRef(session: AgentSessionRef): Record<string, unknown> {\n const hasStatus = session.metadata && Object.hasOwn(session.metadata, 'status')\n const status = hasStatus ? sessionStatusFromUnknown(session.metadata?.status) : 'running'\n return {\n sessionId: session.id,\n status,\n alreadyExisted: session.metadata?.alreadyExisted === true,\n }\n}\n\nfunction sessionRefFromSandboxDispatch(dispatched: unknown, providerName: string): AgentSessionRef {\n const record =\n dispatched && typeof dispatched === 'object'\n ? (dispatched as Record<string, unknown>)\n : undefined\n const id = record?.sessionId ?? record?.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session id')\n }\n if (!record) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session record')\n }\n return {\n id,\n provider: providerName,\n metadata: {\n ...(record.status ? { status: record.status } : {}),\n ...(record.alreadyExisted !== undefined ? { alreadyExisted: record.alreadyExisted } : {}),\n },\n }\n}\n\nfunction execResultFromSandboxExecResult(result: SandboxExecResult): ExecResult {\n const record = result as unknown as Record<string, unknown>\n const exitCode = finiteNumber(record.exitCode) ?? finiteNumber(record.code)\n if (exitCode === undefined) {\n throw new ValidationError('sandboxClientAsProvider: exec returned no exit code')\n }\n return {\n exitCode,\n stdout: typeof record.stdout === 'string' ? record.stdout : '',\n stderr: typeof record.stderr === 'string' ? record.stderr : '',\n }\n}\n\nfunction statusFromUnknown(status: unknown): AgentEnvironmentStatus {\n if (status === 'pending' || status === 'provisioning' || status === 'running') return status\n if (status === 'stopped' || status === 'failed' || status === 'expired') return status\n if (status === 'completed') return 'stopped'\n if (status === 'cancelled') return 'stopped'\n return 'unknown'\n}\n\nfunction sessionStatusFromUnknown(status: unknown): AgentSessionStatus | null {\n if (status === 'completed' || status === 'cancelled') return status\n return statusFromUnknown(status)\n}\n\nfunction readBoxStatus(box: SandboxInstance): unknown {\n return (box as unknown as { status?: unknown }).status\n}\n\nfunction readBoxMetadata(box: SandboxInstance): Record<string, unknown> | undefined {\n const metadata = (box as unknown as { metadata?: unknown }).metadata\n return metadata && typeof metadata === 'object'\n ? (metadata as Record<string, unknown>)\n : undefined\n}\n\nasync function maybeRefresh(box: SandboxInstance): Promise<void> {\n const refresh = (box as unknown as { refresh?: () => Promise<void> }).refresh\n if (typeof refresh === 'function') await refresh.call(box)\n}\n\nasync function destroyBox(box: SandboxInstance): Promise<void> {\n const deleteBox = (box as unknown as { delete?: () => Promise<void> }).delete\n if (typeof deleteBox === 'function') await deleteBox.call(box)\n}\n\nfunction placementInfoFromLoopPlacement(\n placement: LoopSandboxPlacement | undefined,\n box: SandboxInstance,\n): PlacementInfo {\n if (!placement) return { kind: 'sandbox', sandboxId: String(box.id) }\n return {\n kind: placement.kind === 'fleet' ? 'fleet' : 'sandbox',\n ...(placement.sandboxId ? { sandboxId: placement.sandboxId } : { sandboxId: String(box.id) }),\n ...(placement.fleetId ? { fleetId: placement.fleetId } : {}),\n ...(placement.machineId ? { machineId: placement.machineId } : {}),\n }\n}\n\nfunction checkpointIdFromResult(result: unknown): string {\n const record = result && typeof result === 'object' ? (result as Record<string, unknown>) : {}\n const id = record.checkpointId ?? record.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: checkpoint returned no checkpoint id')\n }\n return id\n}\n\nfunction defaultTangleSandboxCapabilities(): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: true,\n systemPrompt: true,\n instructions: true,\n tools: true,\n permissions: true,\n mcp: true,\n subagents: true,\n resources: {\n files: true,\n instructions: true,\n tools: true,\n skills: true,\n agents: true,\n commands: true,\n },\n hooks: true,\n modes: true,\n runtimeUpdate: true,\n validation: true,\n },\n streaming: { live: true, replay: true, detach: true, turnIdempotency: true },\n sessions: { continue: true, list: true, messages: true },\n workspace: { read: true, write: true, exec: true, git: true, upload: true, download: true },\n branching: { checkpoint: true, fork: true },\n placement: true,\n usage: true,\n confidential: true,\n }\n}\n\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): AbortSignal {\n const controller = new AbortController()\n const abort = () => controller.abort()\n if (a.aborted || b.aborted) controller.abort()\n else {\n a.addEventListener('abort', abort, { once: true })\n b.addEventListener('abort', abort, { once: true })\n }\n return controller.signal\n}\n\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `${prefix}:${(hash >>> 0).toString(16).padStart(8, '0')}`\n}\n\nfunction hasGet(\n client: SandboxClient,\n): client is SandboxClient & { get(id: string): Promise<SandboxInstance | null> } {\n return typeof (client as { get?: unknown }).get === 'function'\n}\n\nfunction hasList(\n client: SandboxClient,\n): client is SandboxClient & { list(options?: unknown): Promise<SandboxInstance[]> } {\n return typeof (client as { list?: unknown }).list === 'function'\n}\n\nfunction hasDispatchPrompt(box: SandboxInstance): box is SandboxInstance & {\n dispatchPrompt(message: string | InputPart[], options?: PromptOptions): Promise<unknown>\n} {\n return typeof (box as { dispatchPrompt?: unknown }).dispatchPrompt === 'function'\n}\n\nfunction hasSession(\n box: SandboxInstance,\n): box is SandboxInstance & { session(id: string): SandboxSessionLike } {\n return typeof (box as { session?: unknown }).session === 'function'\n}\n\nfunction hasRead(box: SandboxInstance): box is SandboxInstance & {\n read(path: string, options?: { sessionId?: string }): Promise<string>\n} {\n return typeof (box as { read?: unknown }).read === 'function'\n}\n\nfunction hasWrite(\n box: SandboxInstance,\n): box is SandboxInstance & { write(path: string, content: string): Promise<void> } {\n return typeof (box as { write?: unknown }).write === 'function'\n}\n\nfunction hasExec(box: SandboxInstance): box is SandboxInstance & {\n exec(command: string, options?: unknown): Promise<SandboxExecResult>\n} {\n return typeof (box as { exec?: unknown }).exec === 'function'\n}\n\nfunction hasCheckpoint(\n box: SandboxInstance,\n): box is SandboxInstance & { checkpoint(options?: unknown): Promise<unknown> } {\n return typeof (box as { checkpoint?: unknown }).checkpoint === 'function'\n}\n\nfunction hasFork(box: SandboxInstance): box is SandboxInstance & {\n fork(checkpointId: string, options?: unknown): Promise<SandboxInstance>\n} {\n return typeof (box as { fork?: unknown }).fork === 'function'\n}\n\ninterface SandboxSessionLike {\n readonly id: string\n status(): Promise<unknown | null>\n events(options?: { since?: string; signal?: AbortSignal }): AsyncIterable<SandboxEvent>\n result(): Promise<PromptResult>\n prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult>\n cancel(): Promise<void>\n}\n"],"mappings":";;;;;AAmDA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAClC,YAAY,SAAiB,SAA+B;AAC1D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AA6CO,SAAS,uCACd,YAAgD,CAAC,GACf;AAClC,QAAM,UAAU,oBAAI,IAAsC;AAE1D,QAAM,WAA6C;AAAA,IACjD,SAAS,UAAU,UAAU,CAAC,GAAS;AACrC,UAAI,CAAC,SAAS,MAAM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AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;","names":[]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { E as ExecutorFactory, h as ExecutorRegistry, e as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-
|
|
1
|
+
import { E as ExecutorFactory, h as ExecutorRegistry, e as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-DAdIm4AC.js';
|
|
2
2
|
import { AgentProfile } from '@tangle-network/agent-interface';
|
|
3
3
|
import { U as UiLens, a as UiFinding, C as CoderTask } from './substrate-DO2GHNg2.js';
|
|
4
|
-
import { S as SandboxClient, E as ExecCtx,
|
|
4
|
+
import { S as SandboxClient, E as ExecCtx, h as LoopTraceEmitter, g as LoopTraceEvent, b as RuntimeStreamEvent, e as AgentRunSpec } from './types-B00NtbCs.js';
|
|
5
5
|
import { BackendType, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
|
|
6
6
|
import { AgentEvalError } from '@tangle-network/agent-eval';
|
|
7
|
-
import { b as ToolSpec, R as RouterConfig } from './
|
|
8
|
-
import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-
|
|
7
|
+
import { b as ToolSpec, c as RuntimeTelemetryOptions, R as RouterConfig } from './sanitize-C9go6tXj.js';
|
|
8
|
+
import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-BLaiN0-X.js';
|
|
9
9
|
import { L as LocalHarness } from './local-harness-dcD5WTTr.js';
|
|
10
10
|
import { ProviderExecutorOptions, AgentEnvironmentProviderRegistry } from './environment-provider.js';
|
|
11
11
|
import { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider';
|
|
@@ -570,6 +570,7 @@ declare function composeLoopTraceEmitters(...emitters: ReadonlyArray<LoopTraceEm
|
|
|
570
570
|
* The exporter accepts both raw OtelSpan objects and LoopTraceEvents
|
|
571
571
|
* (which get converted to OTLP spans automatically).
|
|
572
572
|
*/
|
|
573
|
+
|
|
573
574
|
interface OtelExportConfig {
|
|
574
575
|
/** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */
|
|
575
576
|
endpoint?: string;
|
|
@@ -628,6 +629,12 @@ declare function loopEventToOtelSpan(event: {
|
|
|
628
629
|
timestamp: number;
|
|
629
630
|
payload: object;
|
|
630
631
|
}, traceId: string, parentSpanId?: string): OtelSpan;
|
|
632
|
+
interface RuntimeEventOtelOptions extends RuntimeTelemetryOptions {
|
|
633
|
+
/** Final customer redactor applied after the schema-aware runtime sanitizer. */
|
|
634
|
+
redact?: (value: unknown) => unknown;
|
|
635
|
+
}
|
|
636
|
+
/** Convert normalized runtime events into lossless, redacted child spans. */
|
|
637
|
+
declare function buildRuntimeEventOtelSpans(events: ReadonlyArray<RuntimeStreamEvent>, traceId: string, parentSpanId?: string, options?: RuntimeEventOtelOptions): OtelSpan[];
|
|
631
638
|
/**
|
|
632
639
|
* Sink-neutral node in a reconstructed loop span tree. The root node's
|
|
633
640
|
* `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL
|
|
@@ -2314,4 +2321,4 @@ interface CoordinationTools {
|
|
|
2314
2321
|
/** Build the driver's MCP tools over a live scope. */
|
|
2315
2322
|
declare function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools;
|
|
2316
2323
|
|
|
2317
|
-
export { type DelegationStatus as $, type AnalystRegistry as A, type DelegateResearchArgs as B, type CappedDelegationTrace as C, type DelegationExecutor as D, type ExecutorConfig as E, type FleetHandle as F, type DelegateResearchConfig as G, type DelegateResearchResult as H, type DelegateResult as I, type DelegateRunCtx as J, type DelegateUiAuditConfig as K, type DelegateUiAuditRoute as L, type MakeWorkerAgent as M, type DelegationError as N, type DelegationFeedbackSnapshot as O, type DelegationHistoryEntry as P, DelegationPersistenceError as Q, type DelegationProfile as R, type DelegationProgress as S, type DelegationRecord as T, type UiAuditorDelegate as U, type DelegationResultPayload as V, type DelegationResumeContext as W, type DelegationResumeDriver as X, type DelegationResumeTick as Y, type DelegationRunContext as Z, DelegationStateCorruptError as _, DelegationTaskQueue as a, validateDelegateArgs as a$, type DelegationStore as a0, type DelegationTaskQueueOptions as a1, type DelegationTraceCaps as a2, type DelegationTraceCollector as a3, type DelegationTraceSpan as a4, type DetachedSessionDelegateOptions as a5, type DetachedSessionRefParts as a6, type DetachedTurn as a7, type DetachedTurnResumeDriverOptions as a8, type DetachedWinnerSelection as a9, type SubmitInput as aA, type SubmitOutput as aB, type TraceContext as aC, type UiAuditorDelegationOutput as aD, buildDelegationTraceSpans as aE, capDelegationTrace as aF, coderTaskFromArgs as aG, composeLoopTraceEmitters as aH, createCoordinationTools as aI, createDelegateHandler as aJ, createDelegationTraceCollector as aK, createDetachedTurnResumeDriver as aL, createFleetWorkspaceExecutor as aM, createInProcessTransport as aN, createMcpServer as aO, createPropagatingTraceEmitter as aP, createSiblingSandboxExecutor as aQ, detachedSessionDelegate as aR, detachedTurnEvents as aS, eventToSnapshot as aT, formatDetachedSessionRef as aU, hashIdempotencyInput as aV, parseDetachedSessionRef as aW, readTraceContextFromEnv as aX, runDetachedTurn as aY, settleDetachedCoderTurn as aZ, traceContextToEnv as a_, type DriveTurnCapableBox as aa, type DriveTurnTick as ab, type FeedbackEvent as ac, type FeedbackRating as ad, type FeedbackRefersTo as ae, FileDelegationStore as af, type FileDelegationStoreOptions as ag, type FleetWorkspaceExecutorOptions as ah, InMemoryDelegationStore as ai, InMemoryFeedbackStore as aj, type JsonRpcMessage as ak, type JsonRpcResponse as al, type McpServer as am, type McpServerOptions as an, type McpToolDescriptor as ao, type McpTransport as ap, type Question as aq, type QuestionDecision as ar, type QuestionPolicy as as, type QuestionRecord as at, type ResearchOutputShape as au, type ResearchSource as av, type RunDetachedTurnOptions as aw, type SettleDetachedCoderTurnOptions as ax, type SettledWorker as ay, type SiblingSandboxExecutorOptions as az, type FeedbackStore as b, type EvalRunEvent as b0, type EvalRunGeneration as b1, type EvalRunsExportConfig as b2, type EvalRunsExportResult as b3, INTELLIGENCE_WIRE_VERSION as b4, type LoopSpanNode as b5, type OtelAttribute as b6, type OtelExportConfig as b7, type OtelExporter as b8, type OtelSpan as b9,
|
|
2324
|
+
export { type DelegationStatus as $, type AnalystRegistry as A, type DelegateResearchArgs as B, type CappedDelegationTrace as C, type DelegationExecutor as D, type ExecutorConfig as E, type FleetHandle as F, type DelegateResearchConfig as G, type DelegateResearchResult as H, type DelegateResult as I, type DelegateRunCtx as J, type DelegateUiAuditConfig as K, type DelegateUiAuditRoute as L, type MakeWorkerAgent as M, type DelegationError as N, type DelegationFeedbackSnapshot as O, type DelegationHistoryEntry as P, DelegationPersistenceError as Q, type DelegationProfile as R, type DelegationProgress as S, type DelegationRecord as T, type UiAuditorDelegate as U, type DelegationResultPayload as V, type DelegationResumeContext as W, type DelegationResumeDriver as X, type DelegationResumeTick as Y, type DelegationRunContext as Z, DelegationStateCorruptError as _, DelegationTaskQueue as a, validateDelegateArgs as a$, type DelegationStore as a0, type DelegationTaskQueueOptions as a1, type DelegationTraceCaps as a2, type DelegationTraceCollector as a3, type DelegationTraceSpan as a4, type DetachedSessionDelegateOptions as a5, type DetachedSessionRefParts as a6, type DetachedTurn as a7, type DetachedTurnResumeDriverOptions as a8, type DetachedWinnerSelection as a9, type SubmitInput as aA, type SubmitOutput as aB, type TraceContext as aC, type UiAuditorDelegationOutput as aD, buildDelegationTraceSpans as aE, capDelegationTrace as aF, coderTaskFromArgs as aG, composeLoopTraceEmitters as aH, createCoordinationTools as aI, createDelegateHandler as aJ, createDelegationTraceCollector as aK, createDetachedTurnResumeDriver as aL, createFleetWorkspaceExecutor as aM, createInProcessTransport as aN, createMcpServer as aO, createPropagatingTraceEmitter as aP, createSiblingSandboxExecutor as aQ, detachedSessionDelegate as aR, detachedTurnEvents as aS, eventToSnapshot as aT, formatDetachedSessionRef as aU, hashIdempotencyInput as aV, parseDetachedSessionRef as aW, readTraceContextFromEnv as aX, runDetachedTurn as aY, settleDetachedCoderTurn as aZ, traceContextToEnv as a_, type DriveTurnCapableBox as aa, type DriveTurnTick as ab, type FeedbackEvent as ac, type FeedbackRating as ad, type FeedbackRefersTo as ae, FileDelegationStore as af, type FileDelegationStoreOptions as ag, type FleetWorkspaceExecutorOptions as ah, InMemoryDelegationStore as ai, InMemoryFeedbackStore as aj, type JsonRpcMessage as ak, type JsonRpcResponse as al, type McpServer as am, type McpServerOptions as an, type McpToolDescriptor as ao, type McpTransport as ap, type Question as aq, type QuestionDecision as ar, type QuestionPolicy as as, type QuestionRecord as at, type ResearchOutputShape as au, type ResearchSource as av, type RunDetachedTurnOptions as aw, type SettleDetachedCoderTurnOptions as ax, type SettledWorker as ay, type SiblingSandboxExecutorOptions as az, type FeedbackStore as b, type EvalRunEvent as b0, type EvalRunGeneration as b1, type EvalRunsExportConfig as b2, type EvalRunsExportResult as b3, INTELLIGENCE_WIRE_VERSION as b4, type LoopSpanNode as b5, type OtelAttribute as b6, type OtelExportConfig as b7, type OtelExporter as b8, type OtelSpan as b9, type RuntimeEventOtelOptions as ba, buildLoopOtelSpans as bb, buildLoopSpanNodes as bc, buildRuntimeEventOtelSpans as bd, createOtelExporter as be, exportEvalRuns as bf, loopEventToOtelSpan as bg, type BusEvent as bh, type BusRecord as bi, type BusStats as bj, type EventBus as bk, type ProviderSeam as bl, type PublishOptions as bm, cliWorktreeExecutor as bn, createEventBus as bo, createExecutor as bp, createExecutorRegistry as bq, type DelegateFeedbackResult as c, type DelegateFeedbackArgs as d, type DelegateUiAuditArgs as e, type DelegateUiAuditResult as f, type DelegationHistoryResult as g, type DelegationHistoryArgs as h, type DelegationStatusResult as i, type DelegationStatusArgs as j, type CoderDelegate as k, type CoderReview as l, type CoderReviewer as m, type CoordinationEvent as n, type CoordinationTools as o, type CoordinationToolsOptions as p, DELEGATE_DESCRIPTION as q, DELEGATE_INPUT_SCHEMA as r, DELEGATE_TOOL_NAME as s, DELEGATION_TRACE_MAX_BYTES as t, DELEGATION_TRACE_MAX_SPANS as u, type DelegateArgs as v, type DelegateCodeArgs as w, type DelegateCodeConfig as x, type DelegateCodeResult as y, type DelegateHandlerOptions as z };
|
|
@@ -2,8 +2,8 @@ import { AgentProfile, AgentProfileValidationResult } from '@tangle-network/agen
|
|
|
2
2
|
import { CreateAgentEnvironmentInput, AgentTurnInput, AgentEnvironmentProvider, AgentEnvironmentCapabilities, AgentProfileRef } from '@tangle-network/agent-interface/environment-provider';
|
|
3
3
|
export { AgentEnvironment, AgentEnvironmentCapabilities, AgentEnvironmentEvent, AgentEnvironmentProvider, AgentEnvironmentQuery, AgentEnvironmentStatus, AgentEnvironmentSummary, AgentProfileRef, AgentSession, AgentSessionRef, AgentSessionStatus, AgentTurnInput, AgentTurnResult, CheckpointRef, CheckpointRequest, CreateAgentEnvironmentInput, ExecRequest, ExecResult, ForkRequest, PlacementInfo, ResourceRequest, WorkspaceRequest } from '@tangle-network/agent-interface/environment-provider';
|
|
4
4
|
import { CreateSandboxOptions, BackendType } from '@tangle-network/sandbox';
|
|
5
|
-
import { R as Runtime, E as ExecutorFactory } from './types-
|
|
6
|
-
import { S as SandboxClient } from './types-
|
|
5
|
+
import { R as Runtime, E as ExecutorFactory } from './types-DAdIm4AC.js';
|
|
6
|
+
import { S as SandboxClient } from './types-B00NtbCs.js';
|
|
7
7
|
import '@tangle-network/agent-eval';
|
|
8
8
|
|
|
9
9
|
/** Provider object or registry name accepted by runtime provider adapters.
|
|
@@ -4,7 +4,8 @@ import {
|
|
|
4
4
|
providerAsSandboxClient,
|
|
5
5
|
resolveAgentEnvironmentProvider,
|
|
6
6
|
sandboxClientAsProvider
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-VSWBYWFK.js";
|
|
8
|
+
import "./chunk-3MDZX7YU.js";
|
|
8
9
|
import "./chunk-DGUM43GV.js";
|
|
9
10
|
export {
|
|
10
11
|
createAgentEnvironmentProviderRegistry,
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { Scenario, SelfImproveOptions, SurfaceProposer, SelfImproveResult } from '@tangle-network/agent-eval/contract';
|
|
2
|
+
import { AgentProfile } from '@tangle-network/agent-interface';
|
|
3
|
+
import { L as LocalHarness } from './local-harness-dcD5WTTr.js';
|
|
4
|
+
import { V as Verifier, C as CandidateGenerator } from './agentic-generator-B8oeE2Yv.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
*
|
|
8
|
+
* `improve` — the ONE public, surface-pluggable RSI verb.
|
|
9
|
+
*
|
|
10
|
+
* A thin facade over agent-eval's `selfImprove` (the held-out-gated closed
|
|
11
|
+
* loop). It removes the two things a caller otherwise has to know to drive the
|
|
12
|
+
* loop by hand: WHICH `MutableSurface` of the profile is being optimized, and
|
|
13
|
+
* WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the
|
|
14
|
+
* facade picks the matching default proposer, extracts the baseline surface from
|
|
15
|
+
* the profile, runs `selfImprove`, and (on a ship verdict) writes the promoted
|
|
16
|
+
* winner back into the corresponding profile field.
|
|
17
|
+
*
|
|
18
|
+
* - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.
|
|
19
|
+
* - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.
|
|
20
|
+
* - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete
|
|
21
|
+
* canonical AgentProfile JSON in one candidate.
|
|
22
|
+
* - `surface: 'rollout-policy'` → `rolloutPolicyProposer` mutates the
|
|
23
|
+
* inference-time `StructuralRolloutPolicy` dials ({ k, repairRounds, testgen })
|
|
24
|
+
* persisted in `profile.extensions['structural-rollout']` — deterministic
|
|
25
|
+
* bounded neighbor enumeration; the held-out gate does the deciding. No-op
|
|
26
|
+
* (nothing proposed, nothing shipped) when the profile has no such extension.
|
|
27
|
+
* - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `workflow`, `agent-profile`, `code`} → no zero-config default
|
|
28
|
+
* proposer exists (a code/config proposer needs caller-supplied wiring — a
|
|
29
|
+
* worktree repo root, a candidate generator, a serializer). The facade
|
|
30
|
+
* requires an explicit `opts.generator` for these and throws a `ConfigError`
|
|
31
|
+
* otherwise. This is a designed boundary, not a missing default: there is
|
|
32
|
+
* no safe value the facade could invent for those surfaces. Code also
|
|
33
|
+
* requires `opts.code.repoRoot` so its incumbent is a real isolated checkout.
|
|
34
|
+
*
|
|
35
|
+
* Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes
|
|
36
|
+
* straight through to `selfImprove`.
|
|
37
|
+
*
|
|
38
|
+
* @experimental
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/** The agent-profile lever `improve` optimizes. Mirrors the AgentProfile-law
|
|
42
|
+
* profile levers; `code` is the implementation-tier surface, `rollout-policy`
|
|
43
|
+
* the inference-time structuralRollout dials
|
|
44
|
+
* (`profile.extensions['structural-rollout']`). */
|
|
45
|
+
type ImproveSurface = 'prompt' | 'skills' | 'tools' | 'mcp' | 'hooks' | 'subagents' | 'workflow' | 'agent-profile' | 'code' | 'rollout-policy';
|
|
46
|
+
type ImproveOptions<TScenario extends Scenario, TArtifact> = Omit<SelfImproveOptions<TScenario, TArtifact>, 'analyzeGeneration' | 'baselineSurface' | 'findings' | 'gate' | 'proposer'> & {
|
|
47
|
+
/** Which profile lever to optimize. Default `'prompt'`. Selects the default
|
|
48
|
+
* generator + the baseline-surface extraction shape. */
|
|
49
|
+
surface?: ImproveSurface;
|
|
50
|
+
/** The `SurfaceProposer` that mutates the surface. When unset, the facade
|
|
51
|
+
* picks the default for `surface` (`gepaProposer` for prompt, `skillOptProposer`
|
|
52
|
+
* for skills); surfaces with no default REQUIRE this (fail-loud otherwise). */
|
|
53
|
+
generator?: SurfaceProposer;
|
|
54
|
+
/** Gate mode. `'holdout'` (default) runs the held-out promotion gate;
|
|
55
|
+
* `'none'` is a baseline-only run (`budget.generations = 0`). */
|
|
56
|
+
gate?: 'holdout' | 'none';
|
|
57
|
+
/** Restrict the run to this subset of models. When set, the reflection model
|
|
58
|
+
* (`llm.model`, or the default when unset) must be a member, or `improve()` throws
|
|
59
|
+
* a `ConfigError` before the generator is built. Unset = unrestricted. */
|
|
60
|
+
allowedModels?: readonly string[];
|
|
61
|
+
/** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).
|
|
62
|
+
* DEFAULT: the built-in failure distiller — after each generation it turns the
|
|
63
|
+
* worst-scoring/errored cells into structured findings ({ scenario, composite,
|
|
64
|
+
* notes, error }) for the NEXT proposal round, so the proposer reasons over what
|
|
65
|
+
* actually failed instead of a static seed. Pass your own producer (e.g. a
|
|
66
|
+
* trace-analyst over the runDir's traces) to replace it; pass `null` to disable
|
|
67
|
+
* and keep the static `findings` all the way through. */
|
|
68
|
+
analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null;
|
|
69
|
+
/** META-HARNESS mode: instead of the ~400-char distilled findings, feed the
|
|
70
|
+
* proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's
|
|
71
|
+
* real run traces under `runDir` (per-cell `spans.jsonl` event logs +
|
|
72
|
+
* `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose
|
|
73
|
+
* instruction — so the coding agent reads the actual failures itself rather than
|
|
74
|
+
* a pre-summary. Requires a REAL `runDir` (that is where the traces live).
|
|
75
|
+
* Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`
|
|
76
|
+
* (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag
|
|
77
|
+
* is the one-line enable. Default `false` (the distiller stays the default). */
|
|
78
|
+
rawTraceContext?: boolean;
|
|
79
|
+
/** CODE-surface wiring: name `surface: 'code'`, point at a repo, and the
|
|
80
|
+
* facade assembles the whole candidate pipeline — an isolated incumbent plus git worktrees
|
|
81
|
+
* (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic
|
|
82
|
+
* generator (a real coding harness edits each candidate worktree; a `verify`
|
|
83
|
+
* hook gates candidates before they are ever measured). Ignored when
|
|
84
|
+
* `opts.generator` is supplied. Required for every code run because a real
|
|
85
|
+
* repository and base ref are necessary to measure the incumbent. */
|
|
86
|
+
code?: ImproveCodeOptions;
|
|
87
|
+
/** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,
|
|
88
|
+
* `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)
|
|
89
|
+
* — which `skillOptProposer` (a document patcher) cannot meaningfully edit.
|
|
90
|
+
* Provide the document CONTENT to optimize + a `writeBack` to persist the
|
|
91
|
+
* shipped winner (the profile ref points at a file the caller owns). This is
|
|
92
|
+
* what makes skillOpt reachable through improve(). */
|
|
93
|
+
skills?: ImproveSkillsOptions;
|
|
94
|
+
/** Custom held-back-exam decision. The string `gate` above controls whether
|
|
95
|
+
* the exam runs; this callback controls how its evidence decides promotion. */
|
|
96
|
+
promotionGate?: SelfImproveOptions<TScenario, TArtifact>['gate'];
|
|
97
|
+
};
|
|
98
|
+
interface ImproveSkillsOptions {
|
|
99
|
+
/** The skill document's current text — the baseline `skillOptProposer` patches. */
|
|
100
|
+
document: string;
|
|
101
|
+
/** Persist the shipped winner document (write the file the profile ref points at).
|
|
102
|
+
* Called only on a ship verdict. When omitted, the winner is still returned in
|
|
103
|
+
* `result.raw.winner.surface` for the caller to materialize. */
|
|
104
|
+
writeBack?: (winnerDocument: string) => void;
|
|
105
|
+
}
|
|
106
|
+
interface ImproveCodeOptions {
|
|
107
|
+
/** Repo root candidate worktrees fork from. */
|
|
108
|
+
repoRoot: string;
|
|
109
|
+
/** Base ref candidates fork from. Default `main`. */
|
|
110
|
+
baseRef?: string;
|
|
111
|
+
/** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */
|
|
112
|
+
worktreeDir?: string;
|
|
113
|
+
/** Coding harness the agentic generator runs in each worktree. Default `claude`. */
|
|
114
|
+
harness?: LocalHarness;
|
|
115
|
+
/** Verify a candidate worktree before it becomes a measurable surface; failures
|
|
116
|
+
* feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */
|
|
117
|
+
verify?: Verifier;
|
|
118
|
+
/** Per-shot wall-clock timeout for the harness (ms). */
|
|
119
|
+
timeoutMs?: number;
|
|
120
|
+
/** Byte-producer override — the test seam and the escape hatch for custom
|
|
121
|
+
* candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */
|
|
122
|
+
generator?: CandidateGenerator;
|
|
123
|
+
}
|
|
124
|
+
interface ImproveResult<TScenario extends Scenario, TArtifact> {
|
|
125
|
+
/** The profile after improvement: the winner surface applied back into the
|
|
126
|
+
* matching field when the gate shipped, else the input profile unchanged. */
|
|
127
|
+
profile: AgentProfile;
|
|
128
|
+
/** True when `gateDecision === 'ship'`. */
|
|
129
|
+
shipped: boolean;
|
|
130
|
+
/** Held-out lift (`winner − baseline` composite). */
|
|
131
|
+
lift: number;
|
|
132
|
+
/** The five-valued gate verdict from `selfImprove`. */
|
|
133
|
+
gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision'];
|
|
134
|
+
/** Full `selfImprove` result for advanced inspection. */
|
|
135
|
+
raw: SelfImproveResult<TScenario, TArtifact>;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Run the held-out-gated self-improvement loop on ONE profile surface.
|
|
139
|
+
*
|
|
140
|
+
* @example Optimize the system prompt, default holdout gate:
|
|
141
|
+
*
|
|
142
|
+
* const out = await improve(profile, findings, {
|
|
143
|
+
* surface: 'prompt',
|
|
144
|
+
* scenarios,
|
|
145
|
+
* judge,
|
|
146
|
+
* agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),
|
|
147
|
+
* })
|
|
148
|
+
* if (out.shipped) deploy(out.profile)
|
|
149
|
+
*/
|
|
150
|
+
declare function improve<TScenario extends Scenario, TArtifact>(profile: AgentProfile, findings: unknown[], opts: ImproveOptions<TScenario, TArtifact>): Promise<ImproveResult<TScenario, TArtifact>>;
|
|
151
|
+
|
|
152
|
+
export { type ImproveSurface as I, type ImproveOptions as a, type ImproveResult as b, type ImproveCodeOptions as c, type ImproveSkillsOptions as d, improve as i };
|
|
@@ -52,6 +52,22 @@ interface AgentSurfaces {
|
|
|
52
52
|
rag?: string;
|
|
53
53
|
/** Optional: single file defining the output schema (Zod / JSON Schema). */
|
|
54
54
|
outputSchema?: string;
|
|
55
|
+
/** Optional: directory containing Agent Skill packages. */
|
|
56
|
+
skills?: string;
|
|
57
|
+
/** Optional: directory containing MCP server/tool configuration. */
|
|
58
|
+
mcp?: string;
|
|
59
|
+
/** Optional: directory containing hook definitions. */
|
|
60
|
+
hooks?: string;
|
|
61
|
+
/** Optional: directory containing subagent definitions. */
|
|
62
|
+
subagents?: string;
|
|
63
|
+
/** Optional: directory containing orchestration/workflow policies. */
|
|
64
|
+
workflows?: string;
|
|
65
|
+
/** Optional: single file containing rollout-policy settings. */
|
|
66
|
+
rolloutPolicy?: string;
|
|
67
|
+
/** Optional: single canonical AgentProfile file. */
|
|
68
|
+
agentProfile?: string;
|
|
69
|
+
/** Optional: source root for code findings. */
|
|
70
|
+
code?: string;
|
|
55
71
|
}
|
|
56
72
|
interface ResolvedSurface {
|
|
57
73
|
/** Absolute filesystem path the operator can `cat` / `vim`. */
|