@mnaimfaizy/agent-kit 1.0.0-beta.12 → 1.0.0-beta.14

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.
@@ -0,0 +1,197 @@
1
+ // The `anthropic` provider profile (ADR 0023): everything the model proxy's
2
+ // core (../core.mjs) knows about the Anthropic API. The real credential goes
3
+ // in as `x-api-key` for an API key, or, on the subscription path (#375), as
4
+ // the bearer value of `Authorization` and nothing else, so every other header
5
+ // Claude Code sends (its OAuth beta header among them) passes on as it is and
6
+ // need not be known here.
7
+ //
8
+ // What it lets through is only what the sandboxed Claude Code needs:
9
+ // - only `POST` to the Messages API's own two paths (FORWARDED);
10
+ // - only a body with nothing that makes the model API act outside the sandbox:
11
+ // no server-side tool (any `tools` entry but a client tool with an
12
+ // `input_schema`), no `mcp_servers` or `container`, and no content that
13
+ // names a file or URL for the API to fetch. Every beta feature that acts on
14
+ // the API's side is turned on through one of those body fields, so the beta
15
+ // header itself passes as Claude Code sent it.
16
+
17
+ /** The model API every forwarded request goes to. */
18
+ export const MODEL_API = "https://api.anthropic.com";
19
+
20
+ /** A path must be under /v1/ and not UNCOUNTED_PATH before it is matched against ROUTES. */
21
+ const MODEL_PATH = /^\/v1\//;
22
+
23
+ /**
24
+ * Paths whose spend an answer's `usage` would not show (a batch is billed
25
+ * later, outside this run), so the token cap could not hold: refused.
26
+ */
27
+ const UNCOUNTED_PATH = /^\/v1\/(messages\/batches|complete)(\/|$)/i;
28
+
29
+ /** The call that spends tokens, and the one that only counts them. */
30
+ const ROUTES = Object.freeze([
31
+ Object.freeze({ method: "POST", path: "/v1/messages", spends: true }),
32
+ Object.freeze({ method: "POST", path: "/v1/messages/count_tokens", spends: false }),
33
+ ]);
34
+
35
+ /** The only requests forwarded, by decoded path, and only as `POST`: Claude Code's Messages API calls. */
36
+ export const FORWARDED = Object.freeze(ROUTES.map((r) => r.path));
37
+
38
+ /** The largest request body the proxy reads, judges and forwards. */
39
+ export const MAX_REQUEST = 32 * 1024 * 1024;
40
+
41
+ /**
42
+ * A request's input tokens, estimated from its body for its reservation:
43
+ * one token per this many bytes, which is fewer bytes than any ordinary text
44
+ * takes per token, so the estimate is high rather than low.
45
+ */
46
+ const BYTES_PER_TOKEN = 2;
47
+
48
+ /** How deep the body's messages and system blocks are walked; deeper is refused. */
49
+ const MAX_DEPTH = 64;
50
+
51
+ /** The `usage` fields the cap counts: every kind of token billed. */
52
+ export const COUNTED_USAGE = Object.freeze([
53
+ "input_tokens",
54
+ "cache_creation_input_tokens",
55
+ "cache_read_input_tokens",
56
+ "output_tokens",
57
+ ]);
58
+
59
+ /** The header an API key goes in, as the caller sends its key and the proxy writes the real one. */
60
+ const API_KEY_HEADER = "x-api-key";
61
+
62
+ /**
63
+ * The request headers never passed on, beyond the hop-by-hop and standard
64
+ * credential headers the core drops itself. Every other header passes.
65
+ */
66
+ const NEVER_FORWARDED = Object.freeze([API_KEY_HEADER]);
67
+
68
+ /** The Messages API's error type for each of the proxy's own refusals. */
69
+ const ERROR_TYPES = Object.freeze({
70
+ unauthenticated: "authentication_error",
71
+ cap_reached: "permission_error",
72
+ invalid_request: "invalid_request_error",
73
+ too_large: "request_too_large",
74
+ busy: "rate_limit_error",
75
+ });
76
+
77
+ /** Content sources that make the model API fetch something: a URL, or a file it holds. */
78
+ const FETCHED_SOURCE = new Set(["url", "file"]);
79
+
80
+ /** Content blocks that hand the model API something to act on outside the request. */
81
+ const ACTING_BLOCK = new Set(["container_upload", "mcp_tool_use", "server_tool_use"]);
82
+
83
+ /**
84
+ * Why a Messages API request body is refused, or null. The body must be a
85
+ * JSON object; no `mcp_servers` or `container`; every `tools` entry a
86
+ * client tool (no `type`, or `custom`, and an `input_schema` object), so no
87
+ * server-side tool; and nothing in `messages` or `system` that names a URL
88
+ * or a file for the API to fetch, or an upload or server-side call.
89
+ * @param {unknown} body
90
+ * @returns {string | null} a short, fixed reason, never the sandbox's text
91
+ */
92
+ export function requestRefusal(body) {
93
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
94
+ return "a body that is not a JSON object";
95
+ }
96
+ for (const key of ["mcp_servers", "container"]) {
97
+ if (Object.hasOwn(body, key)) return `a request with ${key}`;
98
+ }
99
+ if (Object.hasOwn(body, "tools")) {
100
+ if (!Array.isArray(body.tools)) return "tools that are not a list";
101
+ for (const tool of body.tools) {
102
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
103
+ return "a tool that is not an object";
104
+ }
105
+ if (tool.type !== undefined && tool.type !== "custom") return "a server-side tool";
106
+ if (tool.input_schema === null || typeof tool.input_schema !== "object") {
107
+ return "a tool with no input_schema";
108
+ }
109
+ }
110
+ }
111
+ for (const key of ["messages", "system"]) {
112
+ if (!Object.hasOwn(body, key)) continue;
113
+ const why = contentRefusal(body[key], 0);
114
+ if (why) return why;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /** @param {unknown} value @param {number} depth @returns {string | null} */
120
+ function contentRefusal(value, depth) {
121
+ if (value === null || typeof value !== "object") return null;
122
+ if (depth > MAX_DEPTH) return "content nested too deeply";
123
+ if (Array.isArray(value)) {
124
+ for (const item of value) {
125
+ const why = contentRefusal(item, depth + 1);
126
+ if (why) return why;
127
+ }
128
+ return null;
129
+ }
130
+ if (typeof value.type === "string" && ACTING_BLOCK.has(value.type)) {
131
+ return `a ${value.type} block`;
132
+ }
133
+ if (Object.hasOwn(value, "file_id")) return "a file reference";
134
+ const source = value.source;
135
+ if (source && typeof source === "object" && FETCHED_SOURCE.has(source.type)) {
136
+ return `a ${source.type} source`;
137
+ }
138
+ for (const child of Object.values(value)) {
139
+ const why = contentRefusal(child, depth + 1);
140
+ if (why) return why;
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * The `usage` of one answer, each token counted once: each kind in
147
+ * COUNTED_USAGE, from a JSON body or from a stream's `message_start` and
148
+ * `message_delta` events. A stream's usage is cumulative, so each kind counts
149
+ * its highest value once.
150
+ * @returns {(answer: any) => number} the tokens the body or event newly reports
151
+ */
152
+ function usageReducer() {
153
+ const seen = Object.fromEntries(COUNTED_USAGE.map((k) => [k, 0]));
154
+ return (answer) => {
155
+ const usage = answer?.usage ?? answer?.message?.usage;
156
+ if (!usage || typeof usage !== "object") return 0;
157
+ let added = 0;
158
+ for (const key of COUNTED_USAGE) {
159
+ const n = usage[key];
160
+ if (typeof n === "number" && Number.isFinite(n) && n > seen[key]) {
161
+ added += n - seen[key];
162
+ seen[key] = n;
163
+ }
164
+ }
165
+ return added;
166
+ };
167
+ }
168
+
169
+ /** @type {Readonly<import("../core.mjs").ProviderProfile>} */
170
+ export const anthropic = Object.freeze({
171
+ upstream: MODEL_API,
172
+ credentialKinds: Object.freeze({
173
+ "api-key": (credential) => [API_KEY_HEADER, credential],
174
+ subscription: (credential) => ["authorization", `Bearer ${credential}`],
175
+ }),
176
+ keyHeaders: Object.freeze([API_KEY_HEADER]),
177
+ forwardsHeader: (header) => !NEVER_FORWARDED.includes(header),
178
+ inScope: (path, decoded) =>
179
+ MODEL_PATH.test(path) && MODEL_PATH.test(decoded) && !UNCOUNTED_PATH.test(decoded),
180
+ routes: ROUTES,
181
+ refusals: Object.freeze({
182
+ scope: "only the model API's /v1/ paths",
183
+ route: "only POST to the Messages API",
184
+ }),
185
+ maxRequestBytes: MAX_REQUEST,
186
+ requestRefusal,
187
+ inputEstimate: (body) => Math.ceil(body.length / BYTES_PER_TOKEN),
188
+ declaredLimit: (body) => body.max_tokens,
189
+ errorBody: (kind, message) => ({
190
+ type: "error",
191
+ error: { type: ERROR_TYPES[kind], message },
192
+ }),
193
+ streamHint: /"(usage|model)"/,
194
+ // A JSON body names its model, and so does a stream's `message_start`.
195
+ answeringModel: (answer) => answer?.model ?? answer?.message?.model,
196
+ usageReducer,
197
+ });
@@ -0,0 +1,110 @@
1
+ // The stub model's `anthropic` dialect (ADR 0031): how a Messages API request
2
+ // reads and how an answer is written, whole or as a stream. The stub itself
3
+ // (../stub.mjs) holds the script; this holds the wire shapes. Node core only
4
+ // (ADR 0001).
5
+
6
+ /** The tokens every answer reports, so the proxy has usage to count. */
7
+ const USAGE = Object.freeze({ input_tokens: 10, output_tokens: 5 });
8
+
9
+ /** A tool result's text: a string, or its text blocks joined. */
10
+ function textOf(content) {
11
+ if (typeof content === "string") return content;
12
+ if (!Array.isArray(content)) return "";
13
+ return content.map((block) => (typeof block?.text === "string" ? block.text : "")).join("");
14
+ }
15
+
16
+ /** The Messages API answer's body for one turn. */
17
+ function message({ id, model, turn }) {
18
+ const content = turn.call
19
+ ? [{ type: "tool_use", id: turn.call.id, name: turn.call.name, input: turn.call.input }]
20
+ : [{ type: "text", text: turn.text }];
21
+ return {
22
+ id,
23
+ type: "message",
24
+ role: "assistant",
25
+ model,
26
+ content,
27
+ stop_reason: turn.call ? "tool_use" : "end_turn",
28
+ stop_sequence: null,
29
+ usage: { ...USAGE },
30
+ };
31
+ }
32
+
33
+ /** The same answer as the API's server-sent events. */
34
+ function stream(whole) {
35
+ const [block] = whole.content;
36
+ const isCall = block.type === "tool_use";
37
+ const events = [
38
+ [
39
+ "message_start",
40
+ {
41
+ message: {
42
+ ...whole,
43
+ content: [],
44
+ stop_reason: null,
45
+ usage: { input_tokens: USAGE.input_tokens, output_tokens: 1 },
46
+ },
47
+ },
48
+ ],
49
+ [
50
+ "content_block_start",
51
+ { index: 0, content_block: isCall ? { ...block, input: {} } : { type: "text", text: "" } },
52
+ ],
53
+ [
54
+ "content_block_delta",
55
+ {
56
+ index: 0,
57
+ delta: isCall
58
+ ? { type: "input_json_delta", partial_json: JSON.stringify(block.input) }
59
+ : { type: "text_delta", text: block.text },
60
+ },
61
+ ],
62
+ ["content_block_stop", { index: 0 }],
63
+ [
64
+ "message_delta",
65
+ {
66
+ delta: { stop_reason: whole.stop_reason, stop_sequence: null },
67
+ usage: { output_tokens: USAGE.output_tokens },
68
+ },
69
+ ],
70
+ ["message_stop", {}],
71
+ ];
72
+ return events
73
+ .map(([type, data]) => `event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
74
+ .join("");
75
+ }
76
+
77
+ /** @type {Readonly<import("../stub.mjs").StubDialect>} */
78
+ export const anthropicDialect = Object.freeze({
79
+ /** The tools a request declares. */
80
+ tools: (request) => request.tools,
81
+ /** The input a shell tool is called with: its command, and a timeout when it takes one. */
82
+ shellInput: (tool, command, timeoutMs) => ({
83
+ command,
84
+ ...(tool.input_schema?.properties?.timeout ? { timeout: timeoutMs } : {}),
85
+ }),
86
+ /** Every tool result the conversation holds. */
87
+ toolResults: (request) =>
88
+ (Array.isArray(request.messages) ? request.messages : [])
89
+ .flatMap((m) => (Array.isArray(m?.content) ? m.content : []))
90
+ .filter((block) => block?.type === "tool_result")
91
+ .map((block) => ({
92
+ id: String(block.tool_use_id),
93
+ text: textOf(block.content),
94
+ isError: block.is_error === true,
95
+ })),
96
+ /** The answer to a POST of `path`, or null for a path this dialect does not speak. */
97
+ answer({ path, request, id, turn }) {
98
+ if (path === "/v1/messages/count_tokens") {
99
+ return json({ input_tokens: USAGE.input_tokens });
100
+ }
101
+ if (path !== "/v1/messages") return null;
102
+ const whole = message({ id, model: String(request.model ?? "stub-model"), turn: turn() });
103
+ if (request.stream !== true) return json(whole);
104
+ return { type: "text/event-stream", body: stream(whole) };
105
+ },
106
+ });
107
+
108
+ function json(body) {
109
+ return { type: "application/json", body: JSON.stringify(body) };
110
+ }
@@ -0,0 +1,174 @@
1
+ // The stub model (ADR 0031): a kit-owned scripted server that stands in for
2
+ // a model API behind the real model proxy, as the proxy's upstream. It
3
+ // answers a harness with a fixed list of shell commands, one tool call per
4
+ // turn, calling the shell tool it picks from the tools the request declares,
5
+ // and ends once each has its result. So the live suite can make a real,
6
+ // pinned harness attempt exactly what it wants attempted, with no key, no
7
+ // spend and the same answers on every run.
8
+ //
9
+ // It also records every request that reached it, which is everything the
10
+ // harness sent past the proxy: the live suite's host-side evidence. It speaks
11
+ // one provider's wire shapes per dialect (stub-dialects/). It holds no
12
+ // credential and is not part of any Consumer's run. Node core only (ADR 0001).
13
+
14
+ import { createServer } from "node:http";
15
+ import { anthropicDialect } from "./stub-dialects/anthropic.mjs";
16
+
17
+ /** The names harnesses give their shell tool, preferred over any other tool that takes a command. */
18
+ const SHELL_NAMES = /^(bash|shell|local_shell|exec_command|run_shell_command|run_terminal_cmd)$/i;
19
+
20
+ /** The largest request the stub reads: the proxy forwards no larger one. */
21
+ const MAX_REQUEST = 32 * 1024 * 1024;
22
+
23
+ /** How long a tool call may run, for a shell tool that takes a timeout. */
24
+ const COMMAND_TIMEOUT_MS = 120_000;
25
+
26
+ /** How much of each result the closing answer repeats, so the harness's own output holds it. */
27
+ const MAX_ECHO = 4000;
28
+
29
+ /**
30
+ * @typedef {{
31
+ * tools: (request: any) => unknown,
32
+ * shellInput: (tool: any, command: string, timeoutMs: number) => object,
33
+ * toolResults: (request: any) => Array<{ id: string, text: string, isError: boolean }>,
34
+ * answer: (opts: { path: string, request: any, id: string, turn: () => Turn }) =>
35
+ * { type: string, body: string } | null,
36
+ * }} StubDialect
37
+ * @typedef {{ call?: { id: string, name: string, input: object }, text?: string }} Turn
38
+ * One turn of the script: a tool call, or the closing text.
39
+ */
40
+
41
+ /**
42
+ * The shell tool among `tools`, or null: the one named `preferred` when a
43
+ * name is given, else a tool with a shell's name, else the first whose input
44
+ * takes a `command` string.
45
+ * @param {unknown} tools
46
+ * @param {string} [preferred] a Custom harness file's `probe_shell_tool`
47
+ * @returns {any}
48
+ */
49
+ export function pickShellTool(tools, preferred) {
50
+ if (!Array.isArray(tools)) return null;
51
+ const declared = tools.filter((t) => typeof t?.name === "string");
52
+ if (preferred !== undefined) return declared.find((t) => t.name === preferred) ?? null;
53
+ const runs = declared.filter((t) => t.input_schema?.properties?.command?.type === "string");
54
+ return runs.find((t) => SHELL_NAMES.test(t.name)) ?? runs[0] ?? null;
55
+ }
56
+
57
+ /**
58
+ * Start the stub model.
59
+ * @param {{ commands?: string[], shellTool?: string, bind?: string, dialect?: StubDialect }} [opts]
60
+ * `commands` is the script. `shellTool` names the tool to call, for a
61
+ * harness whose shell tool the request does not make plain.
62
+ * @returns {Promise<{
63
+ * url: string,
64
+ * requests: Array<{ method: string, path: string, headers: Record<string, unknown>, body: string }>,
65
+ * results: () => Array<{ index: number, text: string, isError: boolean }>,
66
+ * shellTool: () => string | null,
67
+ * script: (commands: string[]) => void,
68
+ * close: () => Promise<void>,
69
+ * }>} `results` are the current script's tool results, by command, as the
70
+ * harness last sent them. `shellTool` is the tool the stub called, or null
71
+ * if no request declared one. `script` replaces the script.
72
+ */
73
+ export async function startStubModel({
74
+ commands = [],
75
+ shellTool,
76
+ bind = "127.0.0.1",
77
+ dialect = anthropicDialect,
78
+ } = {}) {
79
+ const requests = [];
80
+ let generation = 0;
81
+ let script = [...commands];
82
+ let answers = 0;
83
+ let called = null;
84
+ /** @type {Map<number, { index: number, text: string, isError: boolean }>} */
85
+ const results = new Map();
86
+
87
+ /** The id of the current script's call `index`, so no other script's result counts as its. */
88
+ const callId = (index) => `toolu_stub_${generation}_${index}`;
89
+ const indexOf = (id) => {
90
+ const prefix = `toolu_stub_${generation}_`;
91
+ return id.startsWith(prefix) ? Number(id.slice(prefix.length)) : -1;
92
+ };
93
+
94
+ /** The next turn: the command after the last one the conversation has a result for. */
95
+ function turnFor(request) {
96
+ let next = 0;
97
+ for (const result of dialect.toolResults(request)) {
98
+ const index = indexOf(result.id);
99
+ if (!Number.isInteger(index) || index < 0 || index >= script.length) continue;
100
+ results.set(index, { index, text: result.text, isError: result.isError });
101
+ next = Math.max(next, index + 1);
102
+ }
103
+ const tool = pickShellTool(dialect.tools(request), shellTool);
104
+ // A request with no shell tool (a harness's own side calls) runs nothing.
105
+ if (!tool) return { text: "stub model: no shell tool was declared." };
106
+ if (next < script.length) {
107
+ called = tool.name;
108
+ return {
109
+ call: {
110
+ id: callId(next),
111
+ name: tool.name,
112
+ input: dialect.shellInput(tool, script[next], COMMAND_TIMEOUT_MS),
113
+ },
114
+ };
115
+ }
116
+ const echo = [...results.values()].map((r) => r.text.slice(0, MAX_ECHO));
117
+ return { text: ["stub model: the script is done.", ...echo].join("\n") };
118
+ }
119
+
120
+ const server = createServer((req, res) => {
121
+ const chunks = [];
122
+ let size = 0;
123
+ req.on("data", (chunk) => {
124
+ size += chunk.length;
125
+ if (size <= MAX_REQUEST) chunks.push(chunk);
126
+ });
127
+ req.on("error", () => res.destroy());
128
+ req.on("end", () => {
129
+ const body = Buffer.concat(chunks).toString("utf8");
130
+ const url = req.url ?? "";
131
+ requests.push({ method: req.method ?? "", path: url, headers: { ...req.headers }, body });
132
+ let request = null;
133
+ try {
134
+ request = JSON.parse(body);
135
+ } catch {
136
+ request = null;
137
+ }
138
+ const answer =
139
+ req.method === "POST" && request && typeof request === "object"
140
+ ? dialect.answer({
141
+ path: url.split("?")[0],
142
+ request,
143
+ id: `msg_stub_${(answers += 1)}`,
144
+ turn: () => turnFor(request),
145
+ })
146
+ : null;
147
+ if (!answer) {
148
+ res.writeHead(404).end("stub model: not a route it speaks\n");
149
+ return;
150
+ }
151
+ res.writeHead(200, { "content-type": answer.type }).end(answer.body);
152
+ });
153
+ });
154
+ await new Promise((resolve, reject) => {
155
+ server.once("error", reject);
156
+ server.listen(0, bind, () => resolve(undefined));
157
+ });
158
+ const address = server.address();
159
+ return {
160
+ url: `http://${bind}:${typeof address === "object" && address ? address.port : 0}`,
161
+ requests,
162
+ results: () => [...results.values()].sort((a, b) => a.index - b.index),
163
+ shellTool: () => called,
164
+ script(next) {
165
+ generation += 1;
166
+ script = [...next];
167
+ results.clear();
168
+ },
169
+ close: () => {
170
+ server.closeAllConnections();
171
+ return new Promise((resolve) => server.close(() => resolve(undefined)));
172
+ },
173
+ };
174
+ }
@@ -1,25 +0,0 @@
1
- // The Claude Code every sandbox runs: one pinned version, installed with npm,
2
- // with the auto-updater off both by environment and by managed settings in
3
- // /etc/claude-code, which the repository's own project settings cannot
4
- // override. Both drivers layer it into an image with Docker: the Docker
5
- // driver as its runtime's image, the Docker Sandboxes driver as the template
6
- // it loads into sbx (#375).
7
-
8
- /** The Claude Code version every sandbox runs, pinned. */
9
- export const CLAUDE_CODE_VERSION = "2.1.328";
10
-
11
- /** The environment that keeps the auto-updater off. */
12
- export const AUTO_UPDATER_OFF = "DISABLE_AUTOUPDATER=1";
13
-
14
- const MANAGED_SETTINGS = JSON.stringify({ env: { DISABLE_AUTOUPDATER: "1" } });
15
-
16
- const INSTALL = [
17
- `npm install --global @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION} \\`,
18
- " && mkdir -p /etc/claude-code \\",
19
- ` && printf '%s\\n' '${MANAGED_SETTINGS}' > /etc/claude-code/managed-settings.json`,
20
- ];
21
-
22
- /** The Dockerfile that layers the pinned Claude Code on `base`. It needs npm in `base`. */
23
- export function layerDockerfile(base) {
24
- return [`FROM ${base}`, `ENV ${AUTO_UPDATER_OFF}`, `RUN ${INSTALL.join("\n")}`, ""].join("\n");
25
- }