@parcha/agentrun-harness-claude 0.0.0-bootstrap.0 → 0.1.0-beta.29
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/CHANGELOG.md +66 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +57 -0
- package/dist/adapter.d.ts +123 -0
- package/dist/adapter.js +487 -0
- package/dist/binary.d.ts +25 -0
- package/dist/binary.js +71 -0
- package/dist/cli-names.d.ts +7 -0
- package/dist/cli-names.js +17 -0
- package/dist/env.d.ts +81 -0
- package/dist/env.js +92 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +42 -0
- package/dist/harness.d.ts +287 -0
- package/dist/harness.js +881 -0
- package/dist/host/kernel.d.ts +10 -0
- package/dist/host/kernel.js +1 -0
- package/dist/host/machine.d.ts +77 -0
- package/dist/host/machine.js +259 -0
- package/dist/host/policy.d.ts +85 -0
- package/dist/host/policy.js +359 -0
- package/dist/host/process.d.ts +130 -0
- package/dist/host/process.js +31 -0
- package/dist/host/tool-server.d.ts +44 -0
- package/dist/host/tool-server.js +47 -0
- package/dist/ids.d.ts +9 -0
- package/dist/ids.js +17 -0
- package/dist/inbox.d.ts +14 -0
- package/dist/inbox.js +36 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +7 -0
- package/dist/serial.d.ts +3 -0
- package/dist/serial.js +10 -0
- package/dist/spawn.d.ts +51 -0
- package/dist/spawn.js +131 -0
- package/dist/store.d.ts +119 -0
- package/dist/store.js +202 -0
- package/dist/testing/fake-anthropic.d.ts +97 -0
- package/dist/testing/fake-anthropic.js +279 -0
- package/dist/testing/fake-sdk.d.ts +60 -0
- package/dist/testing/fake-sdk.js +402 -0
- package/dist/testing/index.d.ts +3 -0
- package/dist/testing/index.js +5 -0
- package/dist/transcript.d.ts +73 -0
- package/dist/transcript.js +116 -0
- package/dist/versions.d.ts +34 -0
- package/dist/versions.js +76 -0
- package/package.json +78 -1
- package/vendor/durable-harness/UPSTREAM.json +59 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// What the Claude Agent CLI's model requests may carry through the session's model proxy (@parcha/agentrun-kernel/host),
|
|
2
|
+
// written for AgentRun. The routes are the ones the pinned CLI calls:
|
|
3
|
+
// - `HEAD /api/hello`, its connectivity check, answered by the proxy;
|
|
4
|
+
// - `POST /v1/messages?beta=true`, a paid request;
|
|
5
|
+
// - `POST /v1/messages/count_tokens?beta=true`, a free one;
|
|
6
|
+
// each with the headers that pick the API's version and betas (a beta not listed here is refused: a CLI that sends a new
|
|
7
|
+
// one is a CLI this adapter was not checked with).
|
|
8
|
+
// The CLI sends the session's key as a bearer token (`ANTHROPIC_AUTH_TOKEN`); the provider's credential is added by the
|
|
9
|
+
// proxy, as `x-api-key` for Anthropic's API or as a bearer token for a gateway that takes one.
|
|
10
|
+
//
|
|
11
|
+
// A refusal names the field or the kind of thing it refused, never a value from the request (the proxy reports it).
|
|
12
|
+
// A body may carry only the Messages API's own keys (no MCP server, container or service tier). Its model is the session's
|
|
13
|
+
// (or its small model, for the CLI's background calls); `max_tokens` is clamped, and a thinking budget kept below it.
|
|
14
|
+
// Nothing the provider would run or fetch on its own passes: a provider-hosted tool (web search or fetch, code execution,
|
|
15
|
+
// computer use, the server's bash or editor, a tool search) is refused, and a content block may only be of a type the
|
|
16
|
+
// pinned CLI sends (text, thinking, tool calls and results), so no server tool's block, MCP block, image or document
|
|
17
|
+
// passes. A tool of the session's own that is not one of its names (`mcp__hands__<name>`)
|
|
18
|
+
// is dropped, so the model is offered exactly the host's tools. With `webSearch`, one hosted tool passes: Anthropic's web
|
|
19
|
+
// search, exactly as the pinned CLI asks for it in the request its WebSearch tool makes. Usage is read from the stream's
|
|
20
|
+
// `message_start` (input and cache tokens) and its last `message_delta` (output, and the searches the provider ran).
|
|
21
|
+
import { providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
|
|
22
|
+
/** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
|
|
23
|
+
export const OWN_TOOL_PREFIX = "mcp__hands__";
|
|
24
|
+
const ANTHROPIC_HEADERS = ["anthropic-version", "anthropic-beta"];
|
|
25
|
+
export const CLAUDE_MESSAGES_ROUTES = Object.freeze([
|
|
26
|
+
{ method: "HEAD", path: "/api/hello", local: 200 },
|
|
27
|
+
{ method: "POST", path: "/v1/messages", query: ["beta=true"], headers: ANTHROPIC_HEADERS },
|
|
28
|
+
{ method: "POST", path: "/v1/messages/count_tokens", query: ["beta=true"], headers: ANTHROPIC_HEADERS, free: true },
|
|
29
|
+
]);
|
|
30
|
+
/** The `anthropic-beta` values the pinned CLI (2.1.286) sends, recorded per model behind this proxy (the real-CLI test
|
|
31
|
+
* and a probe of claude-sonnet-4-5, claude-sonnet-5-5, claude-opus-5-5 and claude-haiku-5-5): the set depends on the
|
|
32
|
+
* model. Any other is refused, so a CLI or a model that starts sending a new one is seen before it is trusted. */
|
|
33
|
+
export const CLAUDE_BETAS = new Set([
|
|
34
|
+
"claude-code-20250219",
|
|
35
|
+
"context-management-2025-06-27",
|
|
36
|
+
"effort-2025-11-24",
|
|
37
|
+
"interleaved-thinking-2025-05-14",
|
|
38
|
+
"mid-conversation-system-2026-04-07",
|
|
39
|
+
"mid-conversation-tool-changes-2026-07-01",
|
|
40
|
+
"per-turn-control-2026-07-01",
|
|
41
|
+
"prompt-caching-scope-2026-01-05",
|
|
42
|
+
"thinking-token-count-2026-05-13",
|
|
43
|
+
]);
|
|
44
|
+
/** The keys a Messages request may carry, and a token count's. */
|
|
45
|
+
const MESSAGES_KEYS = new Set(["model", "messages", "system", "max_tokens", "metadata", "stop_sequences", "stream", "temperature", "top_k", "top_p", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
|
|
46
|
+
const COUNT_TOKENS_KEYS = new Set(["model", "messages", "system", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
|
|
47
|
+
const OUTPUT_CONFIG_KEYS = new Set(["effort", "format", "task_budget"]);
|
|
48
|
+
/** The content blocks the pinned CLI (2.1.286) sends in a session, recorded behind this proxy (the real-CLI test, with
|
|
49
|
+
* a model that thinks): any other type is refused, so a block the provider runs or resolves on its own (a server
|
|
50
|
+
* tool's call or result, an MCP block, a container upload, an image or document it would fetch) never passes, under
|
|
51
|
+
* whatever name the API gives it. A session's tools answer in text and its prompt is text, so it sends no image or
|
|
52
|
+
* document. */
|
|
53
|
+
export const CLAUDE_BLOCKS = new Set(["text", "thinking", "redacted_thinking", "tool_use", "tool_result"]);
|
|
54
|
+
/** Anthropic's web search server tool as the pinned CLI (2.1.286) asks for it: when the model calls the CLI's WebSearch,
|
|
55
|
+
* the CLI sends a request of its own on the session's model with this one tool (recorded behind a local server,
|
|
56
|
+
* test/fixtures/web-search-request-cli-2.1.286.json): its type and name, `max_uses: 8`, and the domains the model named.
|
|
57
|
+
* A later version (dynamic filtering runs code execution) or any other field is refused. */
|
|
58
|
+
export const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
|
|
59
|
+
const WEB_SEARCH_KEYS = new Set(["type", "name", "max_uses", "allowed_domains", "blocked_domains"]);
|
|
60
|
+
/** The most searches one request may ask the provider for: the pinned CLI's `max_uses`. */
|
|
61
|
+
const WEB_SEARCH_MAX_USES = 8;
|
|
62
|
+
/** What one web search costs on Anthropic's API, in USD, beside the tokens: $10 per 1,000 searches, "Web search tool" in
|
|
63
|
+
* https://platform.claude.com/docs/en/about-claude/pricing (a search that errs is not billed). */
|
|
64
|
+
export const CLAUDE_WEB_SEARCH_USD = 0.01;
|
|
65
|
+
/** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
|
|
66
|
+
export function thinks(body) {
|
|
67
|
+
const thinking = body.thinking;
|
|
68
|
+
if (isPlain(thinking) && (thinking.type === "adaptive" || thinking.type === "enabled"))
|
|
69
|
+
return true;
|
|
70
|
+
const config = body.output_config;
|
|
71
|
+
return isPlain(config) && typeof config.effort === "string" && config.effort.length > 0;
|
|
72
|
+
}
|
|
73
|
+
const isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
74
|
+
const refuse = (status, message) => { throw new ProxyRefusal(status, message); };
|
|
75
|
+
function onlyKeys(body, keys, what) {
|
|
76
|
+
for (const key of Object.keys(body))
|
|
77
|
+
if (!keys.has(key))
|
|
78
|
+
refuse(403, `${what}: a key outside the API's own is not allowed`);
|
|
79
|
+
}
|
|
80
|
+
/** The image types the API takes, which a host tool's image may be. */
|
|
81
|
+
const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
|
|
82
|
+
/** The note the CLI adds beside a tool's image: the file it kept in its own session directory. */
|
|
83
|
+
const LOCAL_IMAGE_NOTE = /^\[Image: source: [^\]\n]+\]$/;
|
|
84
|
+
/** A content list (a message's, the system prompt's, a tool result's): only the block types this session sends. An
|
|
85
|
+
* image only as a host tool answered it: inside its result, inline, of a type the API takes (never one the provider
|
|
86
|
+
* would fetch). */
|
|
87
|
+
function blocks(content, where, inResult = false) {
|
|
88
|
+
if (content === undefined || typeof content === "string")
|
|
89
|
+
return;
|
|
90
|
+
if (!Array.isArray(content))
|
|
91
|
+
refuse(400, `${where} must be a string or a list of blocks`);
|
|
92
|
+
for (const block of content) {
|
|
93
|
+
if (!isPlain(block) || typeof block.type !== "string")
|
|
94
|
+
return refuse(400, `a block in ${where} must be an object with a type`);
|
|
95
|
+
if (inResult && block.type === "image") {
|
|
96
|
+
const source = block.source;
|
|
97
|
+
if (!isPlain(source) || source.type !== "base64" || typeof source.media_type !== "string" || !IMAGE_TYPES.has(source.media_type) || typeof source.data !== "string")
|
|
98
|
+
refuse(403, `${where} holds a block of a type this session does not send`);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (!CLAUDE_BLOCKS.has(block.type))
|
|
102
|
+
refuse(403, `${where} holds a block of a type this session does not send`);
|
|
103
|
+
if (block.type === "tool_result")
|
|
104
|
+
blocks(block.content, "a tool result's content", true);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** A message with the CLI's note of its own image file left out of each tool result that holds the image itself: the
|
|
108
|
+
* note names a path in the session's directory, which differs between a session and its resumption, and says nothing
|
|
109
|
+
* the image doesn't. */
|
|
110
|
+
function withoutImageNotes(message) {
|
|
111
|
+
if (!isPlain(message) || !Array.isArray(message.content))
|
|
112
|
+
return message;
|
|
113
|
+
let changed = false;
|
|
114
|
+
const content = message.content.map((block) => {
|
|
115
|
+
if (!isPlain(block) || block.type !== "tool_result" || !Array.isArray(block.content))
|
|
116
|
+
return block;
|
|
117
|
+
const parts = block.content;
|
|
118
|
+
if (!parts.some((part) => isPlain(part) && part.type === "image"))
|
|
119
|
+
return block;
|
|
120
|
+
const kept = parts.filter((part) => !(isPlain(part) && part.type === "text" && typeof part.text === "string" && LOCAL_IMAGE_NOTE.test(part.text)));
|
|
121
|
+
if (kept.length === parts.length)
|
|
122
|
+
return block;
|
|
123
|
+
changed = true;
|
|
124
|
+
return { ...block, content: kept };
|
|
125
|
+
});
|
|
126
|
+
return changed ? { ...message, content } : message;
|
|
127
|
+
}
|
|
128
|
+
function outputConfig(config) {
|
|
129
|
+
if (config === undefined)
|
|
130
|
+
return;
|
|
131
|
+
if (!isPlain(config))
|
|
132
|
+
return refuse(400, "output_config must be an object");
|
|
133
|
+
onlyKeys(config, OUTPUT_CONFIG_KEYS, "output_config");
|
|
134
|
+
}
|
|
135
|
+
/** Whether `tool` is the web search server tool as the pinned CLI asks for it: its type and name, at most
|
|
136
|
+
* `WEB_SEARCH_MAX_USES` searches, the domains as lists of names, and nothing else. */
|
|
137
|
+
function cliWebSearch(tool) {
|
|
138
|
+
const uses = tool.max_uses;
|
|
139
|
+
const names = (domains) => domains === undefined || (Array.isArray(domains) && domains.every((d) => typeof d === "string"));
|
|
140
|
+
return tool.type === CLAUDE_WEB_SEARCH_TOOL && tool.name === "web_search" && Object.keys(tool).every((key) => WEB_SEARCH_KEYS.has(key))
|
|
141
|
+
&& typeof uses === "number" && Number.isSafeInteger(uses) && uses >= 1 && uses <= WEB_SEARCH_MAX_USES && names(tool.allowed_domains) && names(tool.blocked_domains);
|
|
142
|
+
}
|
|
143
|
+
/** Whether a body offers the web search server tool. */
|
|
144
|
+
const offersWebSearch = (body) => Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === CLAUDE_WEB_SEARCH_TOOL);
|
|
145
|
+
/** The tools the provider gets: client tools of the session's own only; a provider-hosted one is refused, but for the
|
|
146
|
+
* web search tool as the pinned CLI asks for it, when the session has it. */
|
|
147
|
+
function ownTools(tools, allowed, webSearch = false) {
|
|
148
|
+
if (tools === undefined)
|
|
149
|
+
return undefined;
|
|
150
|
+
if (!Array.isArray(tools))
|
|
151
|
+
return refuse(400, "tools is not a list");
|
|
152
|
+
return tools.filter((tool) => {
|
|
153
|
+
if (!isPlain(tool))
|
|
154
|
+
return refuse(400, "a tool must be an object");
|
|
155
|
+
if (webSearch && cliWebSearch(tool))
|
|
156
|
+
return true;
|
|
157
|
+
if (tool.type !== undefined && tool.type !== "custom")
|
|
158
|
+
refuse(403, "a provider-hosted tool is not offered to this session's model");
|
|
159
|
+
return typeof tool.name === "string" && allowed.has(tool.name);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/** Extended thinking's budget stays below `max_tokens` (as clamped); the provider takes no budget below 1024. */
|
|
163
|
+
function thinking(value, maxTokens) {
|
|
164
|
+
if (!isPlain(value) || value.type !== "enabled")
|
|
165
|
+
return value;
|
|
166
|
+
const budget = value.budget_tokens;
|
|
167
|
+
if (typeof budget !== "number" || !Number.isSafeInteger(budget) || budget <= 0)
|
|
168
|
+
return refuse(400, "thinking.budget_tokens must be a positive integer");
|
|
169
|
+
if (budget < maxTokens)
|
|
170
|
+
return value;
|
|
171
|
+
if (maxTokens <= 1024)
|
|
172
|
+
return refuse(400, `thinking.budget_tokens must be below max_tokens (${maxTokens} once clamped) and at least 1024`);
|
|
173
|
+
return { ...value, budget_tokens: maxTokens - 1 };
|
|
174
|
+
}
|
|
175
|
+
/** The tokens a request keeps for its answer when its output is limited, and the least thinking budget the provider
|
|
176
|
+
* takes: a request that thinks may be limited to no less than both. */
|
|
177
|
+
export const ANSWER_TOKENS_LEAST = 1024;
|
|
178
|
+
export const THINKING_BUDGET_LEAST = 1024;
|
|
179
|
+
/** The output tokens a Messages body asks for at most: its `max_tokens` (as `apply` clamped it). */
|
|
180
|
+
export function anthropicOutputAsked(body) {
|
|
181
|
+
return typeof body.max_tokens === "number" && Number.isSafeInteger(body.max_tokens) && body.max_tokens > 0 ? body.max_tokens : undefined;
|
|
182
|
+
}
|
|
183
|
+
/** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
|
|
184
|
+
* budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
|
|
185
|
+
export function anthropicOutputLeast(body) {
|
|
186
|
+
return isPlain(body.thinking) && body.thinking.type === "enabled" ? ANSWER_TOKENS_LEAST + THINKING_BUDGET_LEAST : ANSWER_TOKENS_LEAST;
|
|
187
|
+
}
|
|
188
|
+
/** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
|
|
189
|
+
* and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
|
|
190
|
+
* budget. Only numbers get smaller, so the body is never longer. */
|
|
191
|
+
export function limitAnthropicOutput(body, max) {
|
|
192
|
+
const asked = anthropicOutputAsked(body);
|
|
193
|
+
const limited = asked === undefined ? max : Math.min(asked, max);
|
|
194
|
+
const out = { ...body, max_tokens: limited };
|
|
195
|
+
const thought = body.thinking;
|
|
196
|
+
if (isPlain(thought) && thought.type === "enabled" && typeof thought.budget_tokens === "number") {
|
|
197
|
+
const room = limited - ANSWER_TOKENS_LEAST;
|
|
198
|
+
if (thought.budget_tokens > room) {
|
|
199
|
+
const budget = Math.max(THINKING_BUDGET_LEAST, room);
|
|
200
|
+
if (budget >= limited)
|
|
201
|
+
refuse(400, `max_tokens ${limited} leaves no room for the least thinking budget (${THINKING_BUDGET_LEAST}) and an answer`);
|
|
202
|
+
out.thinking = { ...thought, budget_tokens: budget };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
/** The body the provider gets for a request on `route`. */
|
|
208
|
+
export function applyAnthropic(body, route, options) {
|
|
209
|
+
if (!isPlain(body))
|
|
210
|
+
return refuse(400, "the body is not an object");
|
|
211
|
+
const count = route.path === "/v1/messages/count_tokens";
|
|
212
|
+
onlyKeys(body, count ? COUNT_TOKENS_KEYS : MESSAGES_KEYS, count ? "count_tokens" : "messages");
|
|
213
|
+
outputConfig(body.output_config);
|
|
214
|
+
if (!Array.isArray(body.messages))
|
|
215
|
+
refuse(400, "messages must be a list");
|
|
216
|
+
for (const message of body.messages) {
|
|
217
|
+
if (!isPlain(message))
|
|
218
|
+
refuse(400, "a message must be an object");
|
|
219
|
+
blocks(message.content, "a message's content");
|
|
220
|
+
}
|
|
221
|
+
blocks(body.system, "system");
|
|
222
|
+
const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
|
|
223
|
+
const tools = ownTools(body.tools, allowed, options.webSearch);
|
|
224
|
+
const choice = body.tool_choice;
|
|
225
|
+
const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
|
|
226
|
+
if (isPlain(choice) && choice.type === "tool" && !chosen)
|
|
227
|
+
refuse(403, "tool_choice names a tool this session does not have");
|
|
228
|
+
const small = options.smallModel ?? options.model;
|
|
229
|
+
if (body.model !== options.model && body.model !== small)
|
|
230
|
+
refuse(403, "the model is not this session's");
|
|
231
|
+
const out = { ...body, messages: body.messages.map(withoutImageNotes), ...(tools === undefined ? {} : { tools }) };
|
|
232
|
+
if (count)
|
|
233
|
+
return out;
|
|
234
|
+
// A main-model request that would not think is said, never passed silently (it is still forwarded: the CLI decides
|
|
235
|
+
// its own requests, and this is the record that one went without reasoning).
|
|
236
|
+
if (body.model === options.model && !thinks(body)) {
|
|
237
|
+
try {
|
|
238
|
+
options.onThinkingDisabled?.({ model: options.model });
|
|
239
|
+
}
|
|
240
|
+
catch { /* a host callback never breaks a request */ }
|
|
241
|
+
}
|
|
242
|
+
const most = options.maxOutputTokens ?? 128_000;
|
|
243
|
+
const asked = typeof body.max_tokens === "number" && body.max_tokens > 0 ? body.max_tokens : most;
|
|
244
|
+
const max = Math.min(asked, most);
|
|
245
|
+
return { ...out, max_tokens: max, ...(body.thinking !== undefined ? { thinking: thinking(body.thinking, max) } : {}) };
|
|
246
|
+
}
|
|
247
|
+
/** A non-negative whole count, or undefined. */
|
|
248
|
+
const tokenCount = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
|
|
249
|
+
/** A Messages `usage` object as the proxy books it, or undefined when it says no input or output count, or names web
|
|
250
|
+
* searches by a figure that is not a count (unknown, never zero). */
|
|
251
|
+
function bookedUsage(usage) {
|
|
252
|
+
if (!isPlain(usage))
|
|
253
|
+
return undefined;
|
|
254
|
+
const input = tokenCount(usage.input_tokens);
|
|
255
|
+
const output = tokenCount(usage.output_tokens);
|
|
256
|
+
if (input === undefined || output === undefined)
|
|
257
|
+
return undefined;
|
|
258
|
+
const said = isPlain(usage.server_tool_use) ? usage.server_tool_use.web_search_requests : undefined;
|
|
259
|
+
const webSearches = said === undefined ? 0 : tokenCount(said);
|
|
260
|
+
if (webSearches === undefined)
|
|
261
|
+
return undefined;
|
|
262
|
+
return { input, output, cacheRead: tokenCount(usage.cache_read_input_tokens) ?? 0, cacheWrite: tokenCount(usage.cache_creation_input_tokens) ?? 0, ...(webSearches ? { webSearches } : {}) };
|
|
263
|
+
}
|
|
264
|
+
/** `price` with each web search a response reports added at `CLAUDE_WEB_SEARCH_USD`: the host prices the tokens, the
|
|
265
|
+
* searches are Anthropic's flat rate. An unknown price stays unknown. */
|
|
266
|
+
export function withWebSearches(price) {
|
|
267
|
+
return (model, usage) => {
|
|
268
|
+
const usd = price(model, usage);
|
|
269
|
+
const count = usage.webSearches ?? 0;
|
|
270
|
+
return usd === null || count === 0 ? usd : usd + count * CLAUDE_WEB_SEARCH_USD;
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
|
|
274
|
+
* `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
|
|
275
|
+
* `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
|
|
276
|
+
* own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream that
|
|
277
|
+
* never stopped, or an answer with no readable usage, is unknown. */
|
|
278
|
+
export function anthropicUsage(text) {
|
|
279
|
+
const lines = text.split(/\r?\n/);
|
|
280
|
+
if (!lines.some((line) => line.startsWith("data:") || line.startsWith("event:"))) {
|
|
281
|
+
let body;
|
|
282
|
+
try {
|
|
283
|
+
body = JSON.parse(text);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
return isPlain(body) ? bookedUsage(body.usage) : undefined;
|
|
289
|
+
}
|
|
290
|
+
const events = [];
|
|
291
|
+
for (const line of lines) {
|
|
292
|
+
if (!line.startsWith("data:"))
|
|
293
|
+
continue;
|
|
294
|
+
try {
|
|
295
|
+
const event = JSON.parse(line.slice(5));
|
|
296
|
+
if (isPlain(event))
|
|
297
|
+
events.push(event);
|
|
298
|
+
}
|
|
299
|
+
catch { /* cut at the kept window's edge, or not JSON: skipped */ }
|
|
300
|
+
}
|
|
301
|
+
if (!events.some((e) => e.type === "message_stop"))
|
|
302
|
+
return undefined;
|
|
303
|
+
const started = events.find((e) => e.type === "message_start")?.message;
|
|
304
|
+
const startUsage = isPlain(started) && isPlain(started.usage) ? started.usage : {};
|
|
305
|
+
const lastDelta = events.filter((e) => e.type === "message_delta").at(-1)?.usage;
|
|
306
|
+
return bookedUsage({ ...startUsage, ...(isPlain(lastDelta) ? lastDelta : {}) });
|
|
307
|
+
}
|
|
308
|
+
/** The Claude Agent CLI's provider policy for one session. */
|
|
309
|
+
/** The image blocks in `value`, at any depth (a tool's result holds them). */
|
|
310
|
+
function imagesIn(value) {
|
|
311
|
+
if (Array.isArray(value))
|
|
312
|
+
return value.reduce((n, item) => n + imagesIn(item), 0);
|
|
313
|
+
if (!isPlain(value))
|
|
314
|
+
return 0;
|
|
315
|
+
return (value.type === "image" ? 1 : 0) + Object.values(value).reduce((n, item) => n + imagesIn(item), 0);
|
|
316
|
+
}
|
|
317
|
+
/** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
|
|
318
|
+
* tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
|
|
319
|
+
* can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
|
|
320
|
+
* searches, so its input is unmeasured (undefined), never bounded by its bytes. */
|
|
321
|
+
export function anthropicServerInputOverhead(body, searchAllowance) {
|
|
322
|
+
const searches = offersWebSearch(body);
|
|
323
|
+
if (searches && searchAllowance === undefined)
|
|
324
|
+
return undefined;
|
|
325
|
+
const choice = isPlain(body.tool_choice) ? body.tool_choice.type : undefined;
|
|
326
|
+
const shape = {
|
|
327
|
+
tools: Array.isArray(body.tools) && body.tools.length > 0,
|
|
328
|
+
...(choice === "auto" || choice === "none" || choice === "any" || choice === "tool" ? { toolChoice: choice } : {}),
|
|
329
|
+
images: imagesIn(body.messages),
|
|
330
|
+
};
|
|
331
|
+
return providerInputOverhead("anthropic-messages", shape) + (searches ? searchAllowance : 0);
|
|
332
|
+
}
|
|
333
|
+
export function anthropicPolicy(options) {
|
|
334
|
+
return {
|
|
335
|
+
id: "anthropic",
|
|
336
|
+
routes: CLAUDE_MESSAGES_ROUTES,
|
|
337
|
+
keyOf: (headers) => {
|
|
338
|
+
const auth = String(headers.authorization ?? "");
|
|
339
|
+
return auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
|
340
|
+
},
|
|
341
|
+
authHeaders: (credential) => (options.auth === "bearer" ? { authorization: `Bearer ${credential}` } : { "x-api-key": credential }),
|
|
342
|
+
header: (name, value) => {
|
|
343
|
+
if (name !== "anthropic-beta")
|
|
344
|
+
return value;
|
|
345
|
+
const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v));
|
|
346
|
+
if (unknown.length)
|
|
347
|
+
refuse(403, "an anthropic-beta value is not one the pinned CLI sends");
|
|
348
|
+
return value;
|
|
349
|
+
},
|
|
350
|
+
apply: (body, route) => applyAnthropic(body, route, options),
|
|
351
|
+
// `apply` let through only the session's model or its small one.
|
|
352
|
+
modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
|
|
353
|
+
serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
|
|
354
|
+
outputAsked: anthropicOutputAsked,
|
|
355
|
+
outputLeast: anthropicOutputLeast,
|
|
356
|
+
limitOutput: limitAnthropicOutput,
|
|
357
|
+
usageOf: anthropicUsage,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { DriveContext } from "./kernel.js";
|
|
2
|
+
export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
3
|
+
export type { JournalRecord, TranscriptEntry } from "@parcha/agentrun-kernel/process";
|
|
4
|
+
export type KillSignal = "SIGTERM" | "SIGKILL" | "SIGINT";
|
|
5
|
+
/** A running child of the session. */
|
|
6
|
+
export interface SessionProcess {
|
|
7
|
+
readonly exited: Promise<{
|
|
8
|
+
code: number | null;
|
|
9
|
+
signal: string | null;
|
|
10
|
+
}>;
|
|
11
|
+
stderrTail(): string;
|
|
12
|
+
alive(): boolean;
|
|
13
|
+
kill(signal?: KillSignal): void;
|
|
14
|
+
}
|
|
15
|
+
/** A session machine's private directories. */
|
|
16
|
+
export type CacheDir = "home" | "config" | "tmp" | "cache";
|
|
17
|
+
export interface CacheFile {
|
|
18
|
+
path: string;
|
|
19
|
+
bytes: Uint8Array;
|
|
20
|
+
mode?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface MachineSpawn {
|
|
23
|
+
command: string;
|
|
24
|
+
args?: string[];
|
|
25
|
+
/** The child's environment beyond the machine's allowlist (PATH, LANG, TZ). Nothing else is inherited. */
|
|
26
|
+
env?: Record<string, string>;
|
|
27
|
+
cwd?: string;
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
isolatedCommands?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** Where a session's harness runs: a local machine with private directories and a loopback model proxy. */
|
|
32
|
+
export interface SessionMachine {
|
|
33
|
+
readonly sessionId: string;
|
|
34
|
+
/** The session's working directory: empty, its own, never the host's workspace. */
|
|
35
|
+
readonly root: string;
|
|
36
|
+
readonly dirs: Readonly<Record<CacheDir, string>>;
|
|
37
|
+
readonly signal: AbortSignal;
|
|
38
|
+
/** The model proxy's base URL (loopback), and the per-session key it admits. */
|
|
39
|
+
readonly modelUrl: string;
|
|
40
|
+
readonly modelKey: string;
|
|
41
|
+
/** What the model must hear about this machine (none locally), and its acknowledgement key. */
|
|
42
|
+
readonly notes: readonly string[];
|
|
43
|
+
readonly notesKey?: string;
|
|
44
|
+
spawn(options: MachineSpawn): Promise<SessionProcess>;
|
|
45
|
+
fsync(): Promise<void>;
|
|
46
|
+
close(): Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
/** What a harness's drive asks its machine factory for: the drive, the model route its proxy serves, and its deadline. */
|
|
49
|
+
export interface AcquireMachineRequest {
|
|
50
|
+
ctx: DriveContext;
|
|
51
|
+
model?: GatewayHandler;
|
|
52
|
+
deadline?: number;
|
|
53
|
+
}
|
|
54
|
+
export type AcquireMachine = (request: AcquireMachineRequest) => Promise<SessionMachine>;
|
|
55
|
+
/** Mark a machine as made by this package's factory. */
|
|
56
|
+
export declare function brandMachine<T extends object>(machine: T): T;
|
|
57
|
+
/** Whether a machine was made by this package's factory: the harness refuses any other. */
|
|
58
|
+
export declare const isBrandedMachine: (machine: unknown) => machine is SessionMachine;
|
|
59
|
+
/** One route the model proxy forwards. */
|
|
60
|
+
export interface GatewayRoute {
|
|
61
|
+
method: string;
|
|
62
|
+
path: string;
|
|
63
|
+
/** Request headers passed on to the provider. */
|
|
64
|
+
headers?: readonly string[];
|
|
65
|
+
}
|
|
66
|
+
/** The Claude Agent CLI's one route: the Messages API, with the headers that select its version and betas. */
|
|
67
|
+
export declare const CLAUDE_ROUTES: readonly GatewayRoute[];
|
|
68
|
+
/** A provider-hosted tool the harness may offer (none here: the policy refuses them all). */
|
|
69
|
+
export type ProviderTool = "web_search" | "web_fetch";
|
|
70
|
+
/** The caps a model route can reach. */
|
|
71
|
+
export type GatewayCap = "turnUsd" | "sessionUsd" | "concurrency";
|
|
72
|
+
/** What the harness says about its model route; the machine's proxy serves it (machine.ts, policy.ts). */
|
|
73
|
+
export interface GatewayHandlerOptions {
|
|
74
|
+
routes: readonly GatewayRoute[];
|
|
75
|
+
models: {
|
|
76
|
+
model: string;
|
|
77
|
+
smallModel?: string;
|
|
78
|
+
};
|
|
79
|
+
budget?: {
|
|
80
|
+
turnUsd: number;
|
|
81
|
+
sessionUsd: number;
|
|
82
|
+
};
|
|
83
|
+
ledger?: unknown;
|
|
84
|
+
providerTools?: readonly ProviderTool[];
|
|
85
|
+
network?: string;
|
|
86
|
+
credential: () => Promise<string | undefined> | string | undefined;
|
|
87
|
+
target: string;
|
|
88
|
+
track?: unknown;
|
|
89
|
+
onCap?: (cap: GatewayCap) => void;
|
|
90
|
+
/** The provider refused the session's key: a paid request answered 401, with the provider's own words. No retry can
|
|
91
|
+
* pass, so the harness ends the turn at the first rather than let the CLI retry it for minutes. */
|
|
92
|
+
onKeyRefused?: (detail: string) => void;
|
|
93
|
+
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
94
|
+
}
|
|
95
|
+
export interface GatewayHandler {
|
|
96
|
+
readonly kind: "agentrun-model-route";
|
|
97
|
+
readonly options: GatewayHandlerOptions;
|
|
98
|
+
}
|
|
99
|
+
export declare const gatewayHandler: (options: GatewayHandlerOptions) => GatewayHandler;
|
|
100
|
+
/** The provider credential when the harness is given none: the adapter always gives one, so this refuses. */
|
|
101
|
+
export declare const gatewayCredential: () => Promise<string>;
|
|
102
|
+
/** The provider's base URL when the harness is given none: the adapter always gives one. */
|
|
103
|
+
export declare const gatewayUrl: () => string;
|
|
104
|
+
/** Upstream's model steps (a trace of each request through its gateway). The runner accounts requests here: nothing to trace. */
|
|
105
|
+
export declare class ModelSteps {
|
|
106
|
+
constructor(_ctx: DriveContext, _options?: {
|
|
107
|
+
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
108
|
+
});
|
|
109
|
+
readonly request: () => void;
|
|
110
|
+
settleAbandoned(): Promise<void>;
|
|
111
|
+
close(): Promise<void>;
|
|
112
|
+
}
|
|
113
|
+
export declare function settleAbandonedModelSteps(_ctx: DriveContext): Promise<void>;
|
|
114
|
+
/** Upstream's dollar ledger in the session's journal. The runner accounts spend here: this one records nothing. */
|
|
115
|
+
export interface JournalLedger {
|
|
116
|
+
turn(key: string): void;
|
|
117
|
+
spent(): {
|
|
118
|
+
turnUsd: number;
|
|
119
|
+
sessionUsd: number;
|
|
120
|
+
};
|
|
121
|
+
add(usd: number, info: {
|
|
122
|
+
method: string;
|
|
123
|
+
path: string;
|
|
124
|
+
model?: string;
|
|
125
|
+
estimated?: boolean;
|
|
126
|
+
}): void;
|
|
127
|
+
}
|
|
128
|
+
export declare function journalLedger(_journal: unknown, _options?: {
|
|
129
|
+
records?: readonly unknown[];
|
|
130
|
+
}): JournalLedger;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
2
|
+
const BRAND = Symbol.for("agentrun.claude-agent.session-machine");
|
|
3
|
+
/** Mark a machine as made by this package's factory. */
|
|
4
|
+
export function brandMachine(machine) {
|
|
5
|
+
Object.defineProperty(machine, BRAND, { value: true });
|
|
6
|
+
return machine;
|
|
7
|
+
}
|
|
8
|
+
/** Whether a machine was made by this package's factory: the harness refuses any other. */
|
|
9
|
+
export const isBrandedMachine = (machine) => typeof machine === "object" && machine !== null && machine[BRAND] === true;
|
|
10
|
+
/** The Claude Agent CLI's one route: the Messages API, with the headers that select its version and betas. */
|
|
11
|
+
export const CLAUDE_ROUTES = Object.freeze([{ method: "POST", path: "/v1/messages", headers: ["anthropic-version", "anthropic-beta"] }]);
|
|
12
|
+
export const gatewayHandler = (options) => ({ kind: "agentrun-model-route", options });
|
|
13
|
+
/** The provider credential when the harness is given none: the adapter always gives one, so this refuses. */
|
|
14
|
+
export const gatewayCredential = async () => {
|
|
15
|
+
throw new Error("agentrun-harness-claude: no provider credential was given to the harness");
|
|
16
|
+
};
|
|
17
|
+
/** The provider's base URL when the harness is given none: the adapter always gives one. */
|
|
18
|
+
export const gatewayUrl = () => {
|
|
19
|
+
throw new Error("agentrun-harness-claude: no provider URL was given to the harness");
|
|
20
|
+
};
|
|
21
|
+
/** Upstream's model steps (a trace of each request through its gateway). The runner accounts requests here: nothing to trace. */
|
|
22
|
+
export class ModelSteps {
|
|
23
|
+
constructor(_ctx, _options = {}) { }
|
|
24
|
+
request = () => { };
|
|
25
|
+
async settleAbandoned() { }
|
|
26
|
+
async close() { }
|
|
27
|
+
}
|
|
28
|
+
export async function settleAbandonedModelSteps(_ctx) { }
|
|
29
|
+
export function journalLedger(_journal, _options = {}) {
|
|
30
|
+
return { turn: () => { }, spent: () => ({ turnUsd: 0, sessionUsd: 0 }), add: () => { } };
|
|
31
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** A tool as the model is shown it. */
|
|
2
|
+
export interface ServedTool {
|
|
3
|
+
name: string;
|
|
4
|
+
description: string;
|
|
5
|
+
inputSchema: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** A tool call's result, in MCP's shape: text, and any images the tool answered with (base64). */
|
|
8
|
+
export type ServedResult = {
|
|
9
|
+
content: ({
|
|
10
|
+
type: "text";
|
|
11
|
+
text: string;
|
|
12
|
+
} | {
|
|
13
|
+
type: "image";
|
|
14
|
+
data: string;
|
|
15
|
+
mimeType: string;
|
|
16
|
+
})[];
|
|
17
|
+
isError?: boolean;
|
|
18
|
+
};
|
|
19
|
+
/** The CLI's tool_use id, in a call's `_meta`. */
|
|
20
|
+
export declare const TOOL_USE_ID = "claudecode/toolUseId";
|
|
21
|
+
/** The `_meta` key of a listed tool by which the CLI takes the most characters of its result it passes whole. */
|
|
22
|
+
export declare const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
|
|
23
|
+
/**
|
|
24
|
+
* MAX_MCP_OUTPUT_TOKENS: the host's bound, as tokens. The CLI estimates a result at a quarter of a token a character and
|
|
25
|
+
* 1,600 an image, and counts it exactly only past half its limit, so a result within the bound (with up to fifteen
|
|
26
|
+
* images) is never counted, let alone saved or cut.
|
|
27
|
+
*/
|
|
28
|
+
export declare const MCP_OUTPUT_TOKENS = 120000;
|
|
29
|
+
/** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
|
|
30
|
+
* its result size. */
|
|
31
|
+
export declare const listedTools: (tools: readonly ServedTool[]) => {
|
|
32
|
+
name: string;
|
|
33
|
+
description: string;
|
|
34
|
+
inputSchema: Record<string, unknown>;
|
|
35
|
+
_meta: {
|
|
36
|
+
"anthropic/maxResultSizeChars": number;
|
|
37
|
+
};
|
|
38
|
+
}[];
|
|
39
|
+
/** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. */
|
|
40
|
+
export declare function toolServer(name: string, tools: readonly ServedTool[], call: (tool: string, args: unknown, toolUseId: unknown) => Promise<ServedResult>): Promise<{
|
|
41
|
+
type: "sdk";
|
|
42
|
+
name: string;
|
|
43
|
+
instance: import("@modelcontextprotocol/sdk/server/mcp.js").McpServer;
|
|
44
|
+
}>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The session's host tools, served to the CLI as an in-process MCP server. Written for AgentRun.
|
|
2
|
+
//
|
|
3
|
+
// The Agent SDK's own `tool(name, description, shape)` takes a zod shape and builds a closed object from it, so a tool's
|
|
4
|
+
// schema reached the model as whatever that zod gave back (an open object came out closed, `properties: {}`) and its
|
|
5
|
+
// arguments were parsed through it (an open object's keys arrived as `{}`). This server answers `tools/list` with each
|
|
6
|
+
// tool's JSON Schema as the host gave it, unchanged, and hands `tools/call`'s arguments to the tool as the model sent
|
|
7
|
+
// them: the host (its executor) validates them, as it does for every other harness. The CLI's tool_use id comes in the
|
|
8
|
+
// call's `_meta`, which the durable call record is keyed by.
|
|
9
|
+
//
|
|
10
|
+
// A host tool's result within the host's bound (HOST_RESULT_MAX_CHARS) reaches the model whole. The pinned CLI checks an
|
|
11
|
+
// MCP tool's result twice: past its character limit (50,000 by default, the tool's `anthropic/maxResultSizeChars` up to
|
|
12
|
+
// 500,000 where it gives one) it saves the result to tool-results/<tool_use_id>.json in its config dir and tells the
|
|
13
|
+
// model to read that file, which a confined session cannot; past MAX_MCP_OUTPUT_TOKENS (25,000 by default) it saves the
|
|
14
|
+
// result the same way, or cuts one that holds an image. Each tool is listed with the bound as its maxResultSizeChars,
|
|
15
|
+
// which also spares a text result the token check, and the harness sets MAX_MCP_OUTPUT_TOKENS from it (env.ts).
|
|
16
|
+
import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
|
|
17
|
+
/** The CLI's tool_use id, in a call's `_meta`. */
|
|
18
|
+
export const TOOL_USE_ID = "claudecode/toolUseId";
|
|
19
|
+
/** The `_meta` key of a listed tool by which the CLI takes the most characters of its result it passes whole. */
|
|
20
|
+
export const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
|
|
21
|
+
/**
|
|
22
|
+
* MAX_MCP_OUTPUT_TOKENS: the host's bound, as tokens. The CLI estimates a result at a quarter of a token a character and
|
|
23
|
+
* 1,600 an image, and counts it exactly only past half its limit, so a result within the bound (with up to fifteen
|
|
24
|
+
* images) is never counted, let alone saved or cut.
|
|
25
|
+
*/
|
|
26
|
+
export const MCP_OUTPUT_TOKENS = HOST_RESULT_MAX_CHARS;
|
|
27
|
+
/** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
|
|
28
|
+
* its result size. */
|
|
29
|
+
export const listedTools = (tools) => tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, _meta: { [RESULT_SIZE_KEY]: HOST_RESULT_MAX_CHARS } }));
|
|
30
|
+
/** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. */
|
|
31
|
+
export async function toolServer(name, tools, call) {
|
|
32
|
+
const [{ McpServer }, { CallToolRequestSchema, ListToolsRequestSchema }] = await Promise.all([
|
|
33
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
34
|
+
import("@modelcontextprotocol/sdk/types.js"),
|
|
35
|
+
]);
|
|
36
|
+
const server = new McpServer({ name, version: "1.0.0" }, { capabilities: { tools: {} } });
|
|
37
|
+
const listed = listedTools(tools);
|
|
38
|
+
const names = new Set(tools.map((t) => t.name));
|
|
39
|
+
server.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listed }));
|
|
40
|
+
server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
41
|
+
const { name: tool, arguments: args, _meta } = request.params;
|
|
42
|
+
if (!names.has(tool))
|
|
43
|
+
return { content: [{ type: "text", text: `${tool} is not one of this session's tools` }], isError: true };
|
|
44
|
+
return call(tool, args ?? {}, _meta?.[TOOL_USE_ID]);
|
|
45
|
+
});
|
|
46
|
+
return { type: "sdk", name, instance: server };
|
|
47
|
+
}
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A deterministic UUID for a string: the session id of a run, the `uuid` of
|
|
3
|
+
* the user message a submission becomes. Claude Code wants UUID-shaped ids
|
|
4
|
+
* (`sessionId` must be one), and the same input always gives the same id, so
|
|
5
|
+
* a later drive can find a submission's user entry in the transcript by it.
|
|
6
|
+
*
|
|
7
|
+
* Name-based (SHA-256, formatted with the version-5 and RFC 4122 variant bits).
|
|
8
|
+
*/
|
|
9
|
+
export declare function uuidFrom(name: string): string;
|
package/dist/ids.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
|
+
// From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/ids.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
+
// Changed by Parcha, patches: 002-names
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
/**
|
|
6
|
+
* A deterministic UUID for a string: the session id of a run, the `uuid` of
|
|
7
|
+
* the user message a submission becomes. Claude Code wants UUID-shaped ids
|
|
8
|
+
* (`sessionId` must be one), and the same input always gives the same id, so
|
|
9
|
+
* a later drive can find a submission's user entry in the transcript by it.
|
|
10
|
+
*
|
|
11
|
+
* Name-based (SHA-256, formatted with the version-5 and RFC 4122 variant bits).
|
|
12
|
+
*/
|
|
13
|
+
export function uuidFrom(name) {
|
|
14
|
+
const h = createHash('sha256').update(`agentrun-claude-agent:${name}`).digest('hex');
|
|
15
|
+
const variant = ((Number.parseInt(h[16], 16) & 0x3) | 0x8).toString(16);
|
|
16
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
17
|
+
}
|