@foldrun/core 24.7.2 → 24.8.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/dist/src/engine-common.d.ts +75 -0
- package/dist/src/engine-common.js +142 -0
- package/dist/src/engine-loop.d.ts +11 -41
- package/dist/src/engine-loop.js +49 -142
- package/dist/src/step-exec.js +9 -0
- package/dist/src/translator.d.ts +11 -0
- package/dist/src/translator.js +93 -12
- package/package.json +1 -1
- package/src/engine-common.ts +176 -0
- package/src/engine-loop.ts +48 -173
- package/src/step-exec.ts +7 -0
- package/src/translator.ts +84 -12
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type EngineTool, type ToolOutcome } from "./engine-tools.ts";
|
|
2
|
+
export declare const DEFAULT_MAX_TOKENS = 16000;
|
|
3
|
+
export interface Usage {
|
|
4
|
+
input_tokens: number;
|
|
5
|
+
output_tokens: number;
|
|
6
|
+
cache_creation_input_tokens: number;
|
|
7
|
+
cache_read_input_tokens: number;
|
|
8
|
+
}
|
|
9
|
+
export declare const emptyUsage: () => Usage;
|
|
10
|
+
export declare function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void;
|
|
11
|
+
/** The tier names an agent may write, where the environment names no model
|
|
12
|
+
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
13
|
+
export declare const TIER_DEFAULTS: Record<string, string>;
|
|
14
|
+
export type Json = Record<string, unknown>;
|
|
15
|
+
export type Block = Json & {
|
|
16
|
+
type: string;
|
|
17
|
+
};
|
|
18
|
+
export type HookFn = (input: Json, toolUseId?: string, extra?: {
|
|
19
|
+
signal: AbortSignal;
|
|
20
|
+
}) => Promise<Json | undefined> | Json | undefined;
|
|
21
|
+
export type CanUseTool = (name: string, input: Json, extra: {
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
toolUseID: string;
|
|
24
|
+
}) => Promise<{
|
|
25
|
+
behavior: "allow";
|
|
26
|
+
updatedInput?: Json;
|
|
27
|
+
} | {
|
|
28
|
+
behavior: "deny";
|
|
29
|
+
message: string;
|
|
30
|
+
}>;
|
|
31
|
+
export interface LoopOptions {
|
|
32
|
+
cwd: string;
|
|
33
|
+
env: Record<string, string | undefined>;
|
|
34
|
+
/** What the tools (Bash) get; `env` when not given. foldrun code passes
|
|
35
|
+
* the person's own environment here, so the model key stays with the loop. */
|
|
36
|
+
shellEnv: Record<string, string | undefined>;
|
|
37
|
+
model: string;
|
|
38
|
+
systemPrompt: string;
|
|
39
|
+
tools: EngineTool[];
|
|
40
|
+
maxTurns: number | null;
|
|
41
|
+
partial: boolean;
|
|
42
|
+
pre: HookFn[];
|
|
43
|
+
post: HookFn[];
|
|
44
|
+
canUseTool: CanUseTool | null;
|
|
45
|
+
outer: AbortSignal | null;
|
|
46
|
+
/** The conversation so far, before this prompt: earlier user turns, the
|
|
47
|
+
* model's replies and tool results, as the loop yielded them. */
|
|
48
|
+
history: {
|
|
49
|
+
role: string;
|
|
50
|
+
content: Block[];
|
|
51
|
+
}[];
|
|
52
|
+
}
|
|
53
|
+
export declare function hookFns(hooks: unknown, event: string): HookFn[];
|
|
54
|
+
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
55
|
+
* refuses here, before a model call is paid for. */
|
|
56
|
+
/** `engine` names the loop in what it refuses. */
|
|
57
|
+
export declare function readOptions(options: Json, engine?: string): LoopOptions;
|
|
58
|
+
/** An earlier conversation, checked: user and assistant turns that
|
|
59
|
+
* alternate, starting with the user's, each a list of content blocks. A
|
|
60
|
+
* turn that is not one is refused, not sent half-right to the model. */
|
|
61
|
+
export declare function readHistory(raw: unknown): {
|
|
62
|
+
role: string;
|
|
63
|
+
content: Block[];
|
|
64
|
+
}[];
|
|
65
|
+
export interface Decision {
|
|
66
|
+
input: Json;
|
|
67
|
+
refusal: string | null;
|
|
68
|
+
}
|
|
69
|
+
/** May this call run, and with what input? The order the SDK kept, which
|
|
70
|
+
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
71
|
+
* deny ends it, an allow carries the input the hook settled on and skips
|
|
72
|
+
* the question below — then canUseTool, where confinement lives. */
|
|
73
|
+
export declare function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision>;
|
|
74
|
+
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
75
|
+
export declare function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]>;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// What any loop behind executeStep reads the same way (engine-loop.ts
|
|
2
|
+
// today): the SDK's options, what it refuses before a model call is paid
|
|
3
|
+
// for, the permission order every tool call goes through, and token usage.
|
|
4
|
+
// One copy, so a second loop (a bake-off, FOL-213) cannot hold a hook,
|
|
5
|
+
// limit or confinement check differently. Internal: not part of
|
|
6
|
+
// @foldrun/core's public API.
|
|
7
|
+
import { ENGINE_TOOLS } from "./engine-tools.js";
|
|
8
|
+
export const DEFAULT_MAX_TOKENS = 16_000;
|
|
9
|
+
export const emptyUsage = () => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
10
|
+
export function addUsage(into, u) {
|
|
11
|
+
if (!u)
|
|
12
|
+
return;
|
|
13
|
+
// The closing delta repeats the counts it knows; one that leaves the input
|
|
14
|
+
// side at zero is not saying the input was free.
|
|
15
|
+
for (const k of Object.keys(into)) {
|
|
16
|
+
const v = u[k];
|
|
17
|
+
if (typeof v === "number" && (v > 0 || k === "output_tokens"))
|
|
18
|
+
into[k] = v;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** The tier names an agent may write, where the environment names no model
|
|
22
|
+
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
23
|
+
export const TIER_DEFAULTS = {
|
|
24
|
+
haiku: "claude-haiku-5-5",
|
|
25
|
+
sonnet: "claude-sonnet-5-5",
|
|
26
|
+
opus: "claude-opus-5-5",
|
|
27
|
+
};
|
|
28
|
+
export function hookFns(hooks, event) {
|
|
29
|
+
const groups = hooks?.[event];
|
|
30
|
+
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
31
|
+
}
|
|
32
|
+
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
33
|
+
* refuses here, before a model call is paid for. */
|
|
34
|
+
/** `engine` names the loop in what it refuses. */
|
|
35
|
+
export function readOptions(options, engine = "foldrun") {
|
|
36
|
+
const env = options.env ?? process.env;
|
|
37
|
+
const names = Array.isArray(options.tools) ? options.tools.map(String) : [];
|
|
38
|
+
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
39
|
+
if (unsupported.length) {
|
|
40
|
+
throw new Error(`the ${engine} engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
|
|
41
|
+
}
|
|
42
|
+
const servers = Object.keys(options.mcpServers ?? {});
|
|
43
|
+
if (servers.length) {
|
|
44
|
+
throw new Error(`the ${engine} engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
|
|
45
|
+
}
|
|
46
|
+
if (options.agents && Object.keys(options.agents).length) {
|
|
47
|
+
throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
|
|
48
|
+
}
|
|
49
|
+
const sandbox = options.sandbox;
|
|
50
|
+
// Never read from `env`: that is where a tenant's secrets live.
|
|
51
|
+
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
52
|
+
throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
|
|
53
|
+
}
|
|
54
|
+
const model = String(options.model ?? "");
|
|
55
|
+
if (!model)
|
|
56
|
+
throw new Error(`the ${engine} engine needs a model`);
|
|
57
|
+
// Tools the host brings, as EngineTool objects: they sit beside the
|
|
58
|
+
// built-in ones and go through canUseTool and the hooks like them.
|
|
59
|
+
// foldrun code's cloud_agents is one. A name may not shadow a built-in.
|
|
60
|
+
const extra = [];
|
|
61
|
+
for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
|
|
62
|
+
const tool = t;
|
|
63
|
+
if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
|
|
64
|
+
throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
|
|
65
|
+
}
|
|
66
|
+
if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
|
|
67
|
+
throw new Error(`extraTools: ${tool.name} is already a tool`);
|
|
68
|
+
extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
cwd: String(options.cwd ?? process.cwd()),
|
|
72
|
+
env,
|
|
73
|
+
shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
|
|
74
|
+
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
75
|
+
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
76
|
+
tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
|
|
77
|
+
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
78
|
+
partial: options.includePartialMessages === true,
|
|
79
|
+
pre: hookFns(options.hooks, "PreToolUse"),
|
|
80
|
+
post: hookFns(options.hooks, "PostToolUse"),
|
|
81
|
+
canUseTool: typeof options.canUseTool === "function" ? options.canUseTool : null,
|
|
82
|
+
outer: options.abortController?.signal ?? null,
|
|
83
|
+
history: readHistory(options.history),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** An earlier conversation, checked: user and assistant turns that
|
|
87
|
+
* alternate, starting with the user's, each a list of content blocks. A
|
|
88
|
+
* turn that is not one is refused, not sent half-right to the model. */
|
|
89
|
+
export function readHistory(raw) {
|
|
90
|
+
if (raw == null)
|
|
91
|
+
return [];
|
|
92
|
+
if (!Array.isArray(raw))
|
|
93
|
+
throw new Error("history must be a list of turns");
|
|
94
|
+
return raw.map((t, i) => {
|
|
95
|
+
const role = t?.role;
|
|
96
|
+
const content = t?.content;
|
|
97
|
+
if (role !== (i % 2 === 0 ? "user" : "assistant"))
|
|
98
|
+
throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
|
|
99
|
+
if (!Array.isArray(content) || !content.every((b) => b && typeof b.type === "string"))
|
|
100
|
+
throw new Error(`history turn ${i + 1} has no content blocks`);
|
|
101
|
+
return { role: String(role), content: content };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
/** May this call run, and with what input? The order the SDK kept, which
|
|
105
|
+
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
106
|
+
* deny ends it, an allow carries the input the hook settled on and skips
|
|
107
|
+
* the question below — then canUseTool, where confinement lives. */
|
|
108
|
+
export async function decide(o, name, id, input, sessionId, signal) {
|
|
109
|
+
let current = input;
|
|
110
|
+
let allowed = false;
|
|
111
|
+
for (const hook of o.pre) {
|
|
112
|
+
const out = await hook({ hook_event_name: "PreToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: current, tool_use_id: id }, id, { signal });
|
|
113
|
+
const d = out?.hookSpecificOutput;
|
|
114
|
+
if (!d)
|
|
115
|
+
continue;
|
|
116
|
+
if (d.permissionDecision === "deny")
|
|
117
|
+
return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
118
|
+
if (d.updatedInput)
|
|
119
|
+
current = d.updatedInput;
|
|
120
|
+
if (d.permissionDecision === "allow")
|
|
121
|
+
allowed = true;
|
|
122
|
+
}
|
|
123
|
+
if (!allowed && o.canUseTool) {
|
|
124
|
+
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
125
|
+
if (r.behavior === "deny")
|
|
126
|
+
return { input: current, refusal: r.message || `${name} was refused` };
|
|
127
|
+
if (r.updatedInput)
|
|
128
|
+
current = r.updatedInput;
|
|
129
|
+
}
|
|
130
|
+
return { input: current, refusal: null };
|
|
131
|
+
}
|
|
132
|
+
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
133
|
+
export async function after(o, name, id, input, outcome, sessionId, signal) {
|
|
134
|
+
const added = [];
|
|
135
|
+
for (const hook of o.post) {
|
|
136
|
+
const out = await hook({ hook_event_name: "PostToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: input, tool_response: outcome.text, tool_use_id: id }, id, { signal });
|
|
137
|
+
const context = out?.hookSpecificOutput?.additionalContext;
|
|
138
|
+
if (context)
|
|
139
|
+
added.push(context);
|
|
140
|
+
}
|
|
141
|
+
return added;
|
|
142
|
+
}
|
|
@@ -1,54 +1,24 @@
|
|
|
1
1
|
import type { QueryFn } from "./step-exec.ts";
|
|
2
|
-
import { type
|
|
2
|
+
import { type Json, type Block, type LoopOptions } from "./engine-common.ts";
|
|
3
3
|
/** Which loop runs a step's turns. */
|
|
4
4
|
export type Engine = "sdk" | "foldrun";
|
|
5
|
-
type Json = Record<string, unknown>;
|
|
6
|
-
type Block = Json & {
|
|
7
|
-
type: string;
|
|
8
|
-
};
|
|
9
|
-
type HookFn = (input: Json, toolUseId?: string, extra?: {
|
|
10
|
-
signal: AbortSignal;
|
|
11
|
-
}) => Promise<Json | undefined> | Json | undefined;
|
|
12
|
-
type CanUseTool = (name: string, input: Json, extra: {
|
|
13
|
-
signal: AbortSignal;
|
|
14
|
-
toolUseID: string;
|
|
15
|
-
}) => Promise<{
|
|
16
|
-
behavior: "allow";
|
|
17
|
-
updatedInput?: Json;
|
|
18
|
-
} | {
|
|
19
|
-
behavior: "deny";
|
|
20
|
-
message: string;
|
|
21
|
-
}>;
|
|
22
|
-
interface LoopOptions {
|
|
23
|
-
cwd: string;
|
|
24
|
-
env: Record<string, string | undefined>;
|
|
25
|
-
/** What the tools (Bash) get; `env` when not given. foldrun code passes
|
|
26
|
-
* the person's own environment here, so the model key stays with the loop. */
|
|
27
|
-
shellEnv: Record<string, string | undefined>;
|
|
28
|
-
model: string;
|
|
29
|
-
systemPrompt: string;
|
|
30
|
-
tools: EngineTool[];
|
|
31
|
-
maxTurns: number | null;
|
|
32
|
-
partial: boolean;
|
|
33
|
-
pre: HookFn[];
|
|
34
|
-
post: HookFn[];
|
|
35
|
-
canUseTool: CanUseTool | null;
|
|
36
|
-
outer: AbortSignal | null;
|
|
37
|
-
/** The conversation so far, before this prompt: earlier user turns, the
|
|
38
|
-
* model's replies and tool results, as the loop yielded them. */
|
|
39
|
-
history: {
|
|
40
|
-
role: string;
|
|
41
|
-
content: Block[];
|
|
42
|
-
}[];
|
|
43
|
-
}
|
|
44
5
|
/** The request body for one turn. Cache marks go on the three places a
|
|
45
6
|
* prefix ends: the tools, the system prompt, and the newest message — so
|
|
46
7
|
* each turn reads everything before it from the cache and writes only
|
|
47
8
|
* what is new. The conversation itself is never mutated. */
|
|
9
|
+
/** What a turn that asks for no tool comes to. Only a reply the model ended
|
|
10
|
+
* itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
|
|
11
|
+
* every such turn was "success" — a reply cut off at the output limit
|
|
12
|
+
* included, so a half-written answer passed as a finished step (FOL-211).
|
|
13
|
+
* The partial reply is still the result's text; `errors` says why it is not
|
|
14
|
+
* a finish, the way the SDK's error results do. */
|
|
15
|
+
export declare function endOf(stopReason: string | null, calls: number): {
|
|
16
|
+
subtype: string;
|
|
17
|
+
error?: string;
|
|
18
|
+
};
|
|
48
19
|
export declare function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: {
|
|
49
20
|
role: string;
|
|
50
21
|
content: Block[];
|
|
51
22
|
}[]): Json;
|
|
52
23
|
/** The foldrun engine, as executeStep's model loop. */
|
|
53
24
|
export declare const foldrunQuery: QueryFn;
|
|
54
|
-
export {};
|
package/dist/src/engine-loop.js
CHANGED
|
@@ -34,94 +34,12 @@
|
|
|
34
34
|
// not summarise a full context yet: the model's own stop reason comes back
|
|
35
35
|
// on the result, as it does from the SDK.
|
|
36
36
|
import crypto from "node:crypto";
|
|
37
|
-
import {
|
|
37
|
+
import { killGroups } from "./engine-tools.js";
|
|
38
|
+
import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage } from "./engine-common.js";
|
|
38
39
|
const DEFAULT_BASE = "https://api.anthropic.com";
|
|
39
40
|
const API_VERSION = "2023-06-01";
|
|
40
|
-
const DEFAULT_MAX_TOKENS = 16_000;
|
|
41
41
|
const MODEL_TRIES = 4;
|
|
42
42
|
const RETRY_AFTER_CAP_MS = 30_000;
|
|
43
|
-
/** The tier names an agent may write, where the environment names no model
|
|
44
|
-
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
45
|
-
const TIER_DEFAULTS = {
|
|
46
|
-
haiku: "claude-haiku-5-5",
|
|
47
|
-
sonnet: "claude-sonnet-5-5",
|
|
48
|
-
opus: "claude-opus-5-5",
|
|
49
|
-
};
|
|
50
|
-
function hookFns(hooks, event) {
|
|
51
|
-
const groups = hooks?.[event];
|
|
52
|
-
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
53
|
-
}
|
|
54
|
-
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
55
|
-
* refuses here, before a model call is paid for. */
|
|
56
|
-
function readOptions(options) {
|
|
57
|
-
const env = options.env ?? process.env;
|
|
58
|
-
const names = Array.isArray(options.tools) ? options.tools.map(String) : [];
|
|
59
|
-
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
60
|
-
if (unsupported.length) {
|
|
61
|
-
throw new Error(`the foldrun engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
|
|
62
|
-
}
|
|
63
|
-
const servers = Object.keys(options.mcpServers ?? {});
|
|
64
|
-
if (servers.length) {
|
|
65
|
-
throw new Error(`the foldrun engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
|
|
66
|
-
}
|
|
67
|
-
if (options.agents && Object.keys(options.agents).length) {
|
|
68
|
-
throw new Error("the foldrun engine does not run sub-agents yet — run this agent on the default engine.");
|
|
69
|
-
}
|
|
70
|
-
const sandbox = options.sandbox;
|
|
71
|
-
// Never read from `env`: that is where a tenant's secrets live.
|
|
72
|
-
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
73
|
-
throw new Error("the foldrun engine has no OS sandbox for the shell on this host — run the step in a container.");
|
|
74
|
-
}
|
|
75
|
-
const model = String(options.model ?? "");
|
|
76
|
-
if (!model)
|
|
77
|
-
throw new Error("the foldrun engine needs a model");
|
|
78
|
-
// Tools the host brings, as EngineTool objects: they sit beside the
|
|
79
|
-
// built-in ones and go through canUseTool and the hooks like them.
|
|
80
|
-
// foldrun code's cloud_agents is one. A name may not shadow a built-in.
|
|
81
|
-
const extra = [];
|
|
82
|
-
for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
|
|
83
|
-
const tool = t;
|
|
84
|
-
if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
|
|
85
|
-
throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
|
|
86
|
-
}
|
|
87
|
-
if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
|
|
88
|
-
throw new Error(`extraTools: ${tool.name} is already a tool`);
|
|
89
|
-
extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
|
|
90
|
-
}
|
|
91
|
-
return {
|
|
92
|
-
cwd: String(options.cwd ?? process.cwd()),
|
|
93
|
-
env,
|
|
94
|
-
shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
|
|
95
|
-
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
96
|
-
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
97
|
-
tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
|
|
98
|
-
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
99
|
-
partial: options.includePartialMessages === true,
|
|
100
|
-
pre: hookFns(options.hooks, "PreToolUse"),
|
|
101
|
-
post: hookFns(options.hooks, "PostToolUse"),
|
|
102
|
-
canUseTool: typeof options.canUseTool === "function" ? options.canUseTool : null,
|
|
103
|
-
outer: options.abortController?.signal ?? null,
|
|
104
|
-
history: readHistory(options.history),
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
/** An earlier conversation, checked: user and assistant turns that
|
|
108
|
-
* alternate, starting with the user's, each a list of content blocks. A
|
|
109
|
-
* turn that is not one is refused, not sent half-right to the model. */
|
|
110
|
-
function readHistory(raw) {
|
|
111
|
-
if (raw == null)
|
|
112
|
-
return [];
|
|
113
|
-
if (!Array.isArray(raw))
|
|
114
|
-
throw new Error("history must be a list of turns");
|
|
115
|
-
return raw.map((t, i) => {
|
|
116
|
-
const role = t?.role;
|
|
117
|
-
const content = t?.content;
|
|
118
|
-
if (role !== (i % 2 === 0 ? "user" : "assistant"))
|
|
119
|
-
throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
|
|
120
|
-
if (!Array.isArray(content) || !content.every((b) => b && typeof b.type === "string"))
|
|
121
|
-
throw new Error(`history turn ${i + 1} has no content blocks`);
|
|
122
|
-
return { role: String(role), content: content };
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
43
|
function requestHeaders(env) {
|
|
126
44
|
const headers = { "content-type": "application/json", "anthropic-version": API_VERSION };
|
|
127
45
|
if (env.ANTHROPIC_API_KEY)
|
|
@@ -139,6 +57,31 @@ function requestHeaders(env) {
|
|
|
139
57
|
* prefix ends: the tools, the system prompt, and the newest message — so
|
|
140
58
|
* each turn reads everything before it from the cache and writes only
|
|
141
59
|
* what is new. The conversation itself is never mutated. */
|
|
60
|
+
/** What a turn that asks for no tool comes to. Only a reply the model ended
|
|
61
|
+
* itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
|
|
62
|
+
* every such turn was "success" — a reply cut off at the output limit
|
|
63
|
+
* included, so a half-written answer passed as a finished step (FOL-211).
|
|
64
|
+
* The partial reply is still the result's text; `errors` says why it is not
|
|
65
|
+
* a finish, the way the SDK's error results do. */
|
|
66
|
+
export function endOf(stopReason, calls) {
|
|
67
|
+
switch (stopReason) {
|
|
68
|
+
case "end_turn":
|
|
69
|
+
case "stop_sequence":
|
|
70
|
+
return { subtype: "success" };
|
|
71
|
+
case "max_tokens":
|
|
72
|
+
return { subtype: "error_max_output", error: "the reply was cut off at the output limit (max_output_tokens: in the flow file raises it) — the step did not finish" };
|
|
73
|
+
case "refusal":
|
|
74
|
+
return { subtype: "error_refusal", error: "the model declined to answer (stop reason: refusal) — the step did not finish" };
|
|
75
|
+
case "model_context_window_exceeded":
|
|
76
|
+
return { subtype: "error_context_full", error: "the conversation filled the model's context window — the step did not finish" };
|
|
77
|
+
case "tool_use":
|
|
78
|
+
if (!calls)
|
|
79
|
+
return { subtype: "error_empty_tool_turn", error: "the model said it would call a tool and sent none — the step did not finish" };
|
|
80
|
+
return { subtype: "success" };
|
|
81
|
+
default:
|
|
82
|
+
return { subtype: "error_unknown_stop", error: `the model stopped for a reason this engine does not know (${stopReason ?? "none given"}) — the step did not finish` };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
142
85
|
export function buildRequest(o, messages) {
|
|
143
86
|
const mark = { cache_control: { type: "ephemeral" } };
|
|
144
87
|
const tools = o.tools.map((t, i) => ({
|
|
@@ -209,35 +152,35 @@ async function openStream(o, body, signal) {
|
|
|
209
152
|
async function* sse(res) {
|
|
210
153
|
const decoder = new TextDecoder();
|
|
211
154
|
let buffer = "";
|
|
155
|
+
// SSE ends a line with CRLF, LF or a bare CR (WHATWG). Every one becomes
|
|
156
|
+
// LF here; a CR at the end of a chunk waits for the next, in case it is
|
|
157
|
+
// the first half of a CRLF split across them.
|
|
158
|
+
let held = "";
|
|
212
159
|
for await (const chunk of res.body) {
|
|
213
|
-
|
|
214
|
-
|
|
160
|
+
let text = held + decoder.decode(chunk, { stream: true });
|
|
161
|
+
held = text.endsWith("\r") ? "\r" : "";
|
|
162
|
+
if (held)
|
|
163
|
+
text = text.slice(0, -1);
|
|
164
|
+
buffer += text.replace(/\r\n?/g, "\n");
|
|
165
|
+
for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
|
|
215
166
|
const frame = buffer.slice(0, at);
|
|
216
|
-
buffer = buffer.slice(at
|
|
217
|
-
const data = frame.split(
|
|
167
|
+
buffer = buffer.slice(at + 2);
|
|
168
|
+
const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
|
|
218
169
|
if (!data || data === "[DONE]")
|
|
219
170
|
continue;
|
|
171
|
+
let parsed;
|
|
220
172
|
try {
|
|
221
|
-
|
|
173
|
+
parsed = JSON.parse(data);
|
|
222
174
|
}
|
|
223
175
|
catch {
|
|
224
|
-
//
|
|
176
|
+
// A frame that is not JSON may be a lost piece of the reply: a reply
|
|
177
|
+
// missing words would otherwise pass as whole (Codex, 22 Nov 2026).
|
|
178
|
+
throw new Error("the model stream sent a frame that is not JSON — the reply cannot be trusted whole");
|
|
225
179
|
}
|
|
180
|
+
yield parsed;
|
|
226
181
|
}
|
|
227
182
|
}
|
|
228
183
|
}
|
|
229
|
-
const emptyUsage = () => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
230
|
-
function addUsage(into, u) {
|
|
231
|
-
if (!u)
|
|
232
|
-
return;
|
|
233
|
-
// The closing delta repeats the counts it knows; one that leaves the input
|
|
234
|
-
// side at zero is not saying the input was free.
|
|
235
|
-
for (const k of Object.keys(into)) {
|
|
236
|
-
const v = u[k];
|
|
237
|
-
if (typeof v === "number" && (v > 0 || k === "output_tokens"))
|
|
238
|
-
into[k] = v;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
184
|
/** One model call: yields the raw stream events, returns the whole turn. */
|
|
242
185
|
async function* modelTurn(o, messages, signal) {
|
|
243
186
|
const res = await openStream(o, buildRequest(o, messages), signal);
|
|
@@ -316,45 +259,6 @@ async function* modelTurn(o, messages, signal) {
|
|
|
316
259
|
turn.content = turn.content.filter(Boolean);
|
|
317
260
|
return turn;
|
|
318
261
|
}
|
|
319
|
-
/** May this call run, and with what input? The order the SDK kept, which
|
|
320
|
-
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
321
|
-
* deny ends it, an allow carries the input the hook settled on and skips
|
|
322
|
-
* the question below — then canUseTool, where confinement lives. */
|
|
323
|
-
async function decide(o, name, id, input, sessionId, signal) {
|
|
324
|
-
let current = input;
|
|
325
|
-
let allowed = false;
|
|
326
|
-
for (const hook of o.pre) {
|
|
327
|
-
const out = await hook({ hook_event_name: "PreToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: current, tool_use_id: id }, id, { signal });
|
|
328
|
-
const d = out?.hookSpecificOutput;
|
|
329
|
-
if (!d)
|
|
330
|
-
continue;
|
|
331
|
-
if (d.permissionDecision === "deny")
|
|
332
|
-
return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
333
|
-
if (d.updatedInput)
|
|
334
|
-
current = d.updatedInput;
|
|
335
|
-
if (d.permissionDecision === "allow")
|
|
336
|
-
allowed = true;
|
|
337
|
-
}
|
|
338
|
-
if (!allowed && o.canUseTool) {
|
|
339
|
-
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
340
|
-
if (r.behavior === "deny")
|
|
341
|
-
return { input: current, refusal: r.message || `${name} was refused` };
|
|
342
|
-
if (r.updatedInput)
|
|
343
|
-
current = r.updatedInput;
|
|
344
|
-
}
|
|
345
|
-
return { input: current, refusal: null };
|
|
346
|
-
}
|
|
347
|
-
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
348
|
-
async function after(o, name, id, input, outcome, sessionId, signal) {
|
|
349
|
-
const added = [];
|
|
350
|
-
for (const hook of o.post) {
|
|
351
|
-
const out = await hook({ hook_event_name: "PostToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: input, tool_response: outcome.text, tool_use_id: id }, id, { signal });
|
|
352
|
-
const context = out?.hookSpecificOutput?.additionalContext;
|
|
353
|
-
if (context)
|
|
354
|
-
added.push(context);
|
|
355
|
-
}
|
|
356
|
-
return added;
|
|
357
|
-
}
|
|
358
262
|
async function* run(prompt, o, signal, interrupted) {
|
|
359
263
|
const sessionId = crypto.randomUUID();
|
|
360
264
|
const startedAt = Date.now();
|
|
@@ -427,7 +331,10 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
427
331
|
if (turn.stopReason === "pause_turn" && !calls.length)
|
|
428
332
|
continue;
|
|
429
333
|
if (turn.stopReason !== "tool_use" || !calls.length) {
|
|
430
|
-
|
|
334
|
+
const end = endOf(turn.stopReason, calls.length);
|
|
335
|
+
// A turn that did not finish carries ITS text, empty included — not an
|
|
336
|
+
// earlier turn's "I'll check" passed off as a refusal's words (Codex).
|
|
337
|
+
yield end.error ? { ...result(end.subtype, turn.stopReason), result: text, errors: [end.error] } : result(end.subtype, turn.stopReason);
|
|
431
338
|
return;
|
|
432
339
|
}
|
|
433
340
|
const settle = async (block) => {
|
package/dist/src/step-exec.js
CHANGED
|
@@ -754,6 +754,15 @@ async function executeStepInner(opts, runQuery) {
|
|
|
754
754
|
if (message.subtype === "error_max_turns") {
|
|
755
755
|
emit("error", `stopped after ${opts.maxTurns ?? "its"} turns (max_turns: in the flow file) — the step did not finish`);
|
|
756
756
|
}
|
|
757
|
+
else if (message.subtype !== "success" && opts.engine === "foldrun") {
|
|
758
|
+
// Why it did not finish, when foldrun's loop said: a reply cut off at
|
|
759
|
+
// the output limit, a refusal, a full context (engine-loop.ts endOf).
|
|
760
|
+
// The SDK's own error results are left as they were reported before.
|
|
761
|
+
for (const why of ("errors" in message && Array.isArray(message.errors) ? message.errors : [])) {
|
|
762
|
+
if (typeof why === "string" && why.trim())
|
|
763
|
+
emit("error", why.trim().slice(0, 500));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
757
766
|
costUsd = "total_cost_usd" in message ? (message.total_cost_usd ?? null) : null;
|
|
758
767
|
stopReason = "stop_reason" in message && typeof message.stop_reason === "string" ? message.stop_reason : null;
|
|
759
768
|
if ("num_turns" in message && typeof message.num_turns === "number")
|
package/dist/src/translator.d.ts
CHANGED
|
@@ -132,6 +132,11 @@ export declare function toResponses(req: Json, opts: {
|
|
|
132
132
|
/** What the endpoint can be shown (FOL-163); this shape takes both by default. */
|
|
133
133
|
media?: TranslatorMedia;
|
|
134
134
|
}, drop?: Dropped): Json;
|
|
135
|
+
/** A reply the provider did not finish in a way Anthropic's format can say:
|
|
136
|
+
* the gateway answers it as an error carrying the provider's own reason,
|
|
137
|
+
* never as a normal stop (FOL-211). */
|
|
138
|
+
export declare class UnfinishedReply extends Error {
|
|
139
|
+
}
|
|
135
140
|
/** A finished Chat Completion as an Anthropic message. Pure. */
|
|
136
141
|
export declare function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown, extras?: ToolCallExtras): Json;
|
|
137
142
|
/**
|
|
@@ -169,6 +174,10 @@ export declare class StreamTranslator {
|
|
|
169
174
|
private tools;
|
|
170
175
|
/** The last choice's stop fields: finish_reason and any matched stop. */
|
|
171
176
|
private finish;
|
|
177
|
+
/** The model declined (OpenAI's `delta.refusal`). */
|
|
178
|
+
private refused;
|
|
179
|
+
/** An `error` chunk the provider sent mid-stream: its words, said at the end. */
|
|
180
|
+
private failure;
|
|
172
181
|
private usage;
|
|
173
182
|
private id;
|
|
174
183
|
private readonly model;
|
|
@@ -199,6 +208,8 @@ export declare class ResponsesStreamTranslator {
|
|
|
199
208
|
private blocks;
|
|
200
209
|
private usage;
|
|
201
210
|
private incomplete;
|
|
211
|
+
/** The stream ended with `response.incomplete` (or a response whose status says so). */
|
|
212
|
+
private wasIncomplete;
|
|
202
213
|
private sawTool;
|
|
203
214
|
private sawRefusal;
|
|
204
215
|
/** The stream's last word: completed or incomplete (an answer), or the
|