hiveagents-runtime 0.1.0-beta.1 → 0.1.0-beta.3

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.
Files changed (62) hide show
  1. package/README.md +9 -5
  2. package/dist/adapter-kit.d.ts +4 -4
  3. package/dist/adapter-kit.js +2 -1
  4. package/dist/{agent-D0HS38G3.d.ts → agent-Bj5YPrO7.d.ts} +2 -2
  5. package/dist/{agent-OLSXNGNN.js → agent-D6OXR7UF.js} +9 -8
  6. package/dist/{agent-readiness-V36OJME4.js → agent-readiness-KSGNKTGK.js} +3 -3
  7. package/dist/chunk-2RK74GCA.js +2397 -0
  8. package/dist/chunk-2RK74GCA.js.map +1 -0
  9. package/dist/chunk-6FIXXWNM.js +1 -0
  10. package/dist/{chunk-ALLOMOUN.js → chunk-DAXPAV2L.js} +2 -2
  11. package/dist/{chunk-3B3JW4U3.js → chunk-DQEMIGKC.js} +5 -5
  12. package/dist/{chunk-SRJUZJKV.js → chunk-G6JV7WV6.js} +2 -2
  13. package/dist/{chunk-SRJUZJKV.js.map → chunk-G6JV7WV6.js.map} +1 -1
  14. package/dist/{chunk-TIZKGD4R.js → chunk-RH5A5U7G.js} +2 -2
  15. package/dist/{chunk-DBFXFWQZ.js → chunk-RX3XZENU.js} +93 -93
  16. package/dist/chunk-RX3XZENU.js.map +1 -0
  17. package/dist/{chunk-2RUEC63U.js → chunk-TWGEYWMO.js} +2 -2
  18. package/dist/{chunk-GJ4FTDBJ.js → chunk-UZPDDQVJ.js} +6 -6
  19. package/dist/{chunk-COKYQUTK.js → chunk-WVT5SEKC.js} +2 -2
  20. package/dist/cli.js +9 -8
  21. package/dist/cli.js.map +1 -1
  22. package/dist/{errors-DgehLwqI.d.ts → errors-BNHvvjn9.d.ts} +1 -1
  23. package/dist/{execution-halt-CW0Oi9s9.d.ts → execution-halt-B8G0fOKS.d.ts} +1 -1
  24. package/dist/{execution-types-UJ6gAF48.d.ts → execution-types-ClYYqPQP.d.ts} +1 -1
  25. package/dist/hosted-runtime.d.ts +3 -3
  26. package/dist/hosted-runtime.js +5 -4
  27. package/dist/hosted-runtime.js.map +1 -1
  28. package/dist/index.d.ts +25 -8
  29. package/dist/index.js +16 -9
  30. package/dist/index.js.map +1 -1
  31. package/dist/orchestration/dynamic.d.ts +3 -3
  32. package/dist/orchestration/dynamic.js +4 -4
  33. package/dist/orchestration/index.d.ts +7 -7
  34. package/dist/orchestration/index.js +19 -13
  35. package/dist/orchestration/index.js.map +1 -1
  36. package/dist/orchestration/log.d.ts +4 -4
  37. package/dist/{provider-XCpWjJ6a.d.ts → provider-DX5Mf0uq.d.ts} +1 -1
  38. package/dist/routing/index.d.ts +6 -6
  39. package/dist/routing/index.js +9 -8
  40. package/dist/routing/index.js.map +1 -1
  41. package/dist/routing/learning/index.d.ts +5 -5
  42. package/dist/routing/learning/index.js +9 -8
  43. package/dist/routing/learning/index.js.map +1 -1
  44. package/dist/{runtime-C6Cu2fvw.d.ts → runtime-BSjrnxeF.d.ts} +2 -2
  45. package/dist/{runtime-Y72XJFFO.js → runtime-OISPXS4I.js} +6 -5
  46. package/dist/runtime-OISPXS4I.js.map +1 -0
  47. package/dist/{types-BBRKjIc7.d.ts → types-CIqkKXix.d.ts} +1 -1
  48. package/docs/releases/0.1.0-beta.3.md +13 -0
  49. package/package.json +3 -3
  50. package/dist/chunk-C2DN6KL4.js +0 -853
  51. package/dist/chunk-C2DN6KL4.js.map +0 -1
  52. package/dist/chunk-DBFXFWQZ.js.map +0 -1
  53. package/docs/releases/0.1.0-beta.1.md +0 -13
  54. /package/dist/{agent-OLSXNGNN.js.map → agent-D6OXR7UF.js.map} +0 -0
  55. /package/dist/{agent-readiness-V36OJME4.js.map → agent-readiness-KSGNKTGK.js.map} +0 -0
  56. /package/dist/{runtime-Y72XJFFO.js.map → chunk-6FIXXWNM.js.map} +0 -0
  57. /package/dist/{chunk-ALLOMOUN.js.map → chunk-DAXPAV2L.js.map} +0 -0
  58. /package/dist/{chunk-3B3JW4U3.js.map → chunk-DQEMIGKC.js.map} +0 -0
  59. /package/dist/{chunk-TIZKGD4R.js.map → chunk-RH5A5U7G.js.map} +0 -0
  60. /package/dist/{chunk-2RUEC63U.js.map → chunk-TWGEYWMO.js.map} +0 -0
  61. /package/dist/{chunk-GJ4FTDBJ.js.map → chunk-UZPDDQVJ.js.map} +0 -0
  62. /package/dist/{chunk-COKYQUTK.js.map → chunk-WVT5SEKC.js.map} +0 -0
@@ -1,853 +0,0 @@
1
- import {
2
- boundedInteger,
3
- captureIdentity,
4
- createRequiredLogCapture,
5
- field
6
- } from "./chunk-J7VAYJKM.js";
7
- import {
8
- AdapterRegistry,
9
- EXEC_TRANSPORT_TOKENS,
10
- RUNTIME_ADAPTER_VERSION,
11
- assertRespondPolicy,
12
- snapshotProvider
13
- } from "./chunk-SRJUZJKV.js";
14
- import {
15
- CodexExecAdapter,
16
- ExecStreamPump,
17
- assessCliCompatibility,
18
- classifyClaudeFailure,
19
- compatibilityModels,
20
- isSafeSessionId,
21
- numberValue,
22
- parseObject,
23
- resolveModel,
24
- stringValue
25
- } from "./chunk-2RUEC63U.js";
26
- import {
27
- method,
28
- object
29
- } from "./chunk-EEUYQFCP.js";
30
- import {
31
- ExecDiscovery,
32
- confirmedUsageRetryAt,
33
- guardJsonlFrames,
34
- jsonlFrames,
35
- readProviderRateLimits,
36
- resolveProviderRateLimits
37
- } from "./chunk-DBFXFWQZ.js";
38
- import {
39
- runProcess
40
- } from "./chunk-7LDQKJKI.js";
41
- import {
42
- ExecutionHaltedError,
43
- isExecutionHalted
44
- } from "./chunk-NCNSHOF7.js";
45
- import {
46
- AmbiguousModelError,
47
- UnexpectedAuthSourceError,
48
- UnknownModelError,
49
- UnknownProviderError
50
- } from "./chunk-TG7NTMTR.js";
51
-
52
- // src/adapters/claude/exec-adapter.ts
53
- import { randomUUID } from "node:crypto";
54
- import { readFile } from "node:fs/promises";
55
- import { homedir } from "node:os";
56
- import { join, resolve } from "node:path";
57
-
58
- // src/adapters/claude/protocol.ts
59
- function setNumber(target, key, value) {
60
- const parsed = numberValue(value);
61
- if (parsed !== void 0) target[key] = parsed;
62
- }
63
- function parseUsage(event) {
64
- const rawModels = event.modelUsage;
65
- if (typeof rawModels === "object" && rawModels !== null && !Array.isArray(rawModels)) {
66
- const perModel = {};
67
- let inputTokens = 0;
68
- let outputTokens = 0;
69
- let cachedInputTokens = 0;
70
- let cacheCreationTokens = 0;
71
- let reportedCostUsd = 0;
72
- for (const [model, raw] of Object.entries(rawModels)) {
73
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
74
- const value2 = raw;
75
- const usage2 = {};
76
- setNumber(usage2, "inputTokens", value2.inputTokens);
77
- setNumber(usage2, "outputTokens", value2.outputTokens);
78
- setNumber(usage2, "cachedInputTokens", value2.cacheReadInputTokens);
79
- setNumber(usage2, "cacheCreationTokens", value2.cacheCreationInputTokens);
80
- setNumber(usage2, "reportedCostUsd", value2.costUSD);
81
- perModel[model] = usage2;
82
- inputTokens += usage2.inputTokens ?? 0;
83
- outputTokens += usage2.outputTokens ?? 0;
84
- cachedInputTokens += usage2.cachedInputTokens ?? 0;
85
- cacheCreationTokens += usage2.cacheCreationTokens ?? 0;
86
- reportedCostUsd += usage2.reportedCostUsd ?? 0;
87
- }
88
- if (Object.keys(perModel).length > 0) {
89
- const totalCost = numberValue(event.total_cost_usd);
90
- const hasReportedCost = totalCost !== void 0 || Object.values(perModel).some((m) => m.reportedCostUsd !== void 0);
91
- return {
92
- inputTokens,
93
- outputTokens,
94
- cachedInputTokens,
95
- cacheCreationTokens,
96
- perModel,
97
- // Sin costo reportado por el CLI no se inventa un 0 api-equivalent.
98
- ...hasReportedCost ? { reportedCostUsd: totalCost ?? reportedCostUsd } : {},
99
- costMeaning: hasReportedCost ? "api-equivalent" : "unavailable"
100
- };
101
- }
102
- }
103
- const rawUsage = event.usage;
104
- if (typeof rawUsage !== "object" || rawUsage === null || Array.isArray(rawUsage)) return void 0;
105
- const value = rawUsage;
106
- const usage = {
107
- costMeaning: numberValue(event.total_cost_usd) === void 0 ? "unavailable" : "api-equivalent"
108
- };
109
- setNumber(usage, "inputTokens", value.input_tokens);
110
- setNumber(usage, "outputTokens", value.output_tokens);
111
- setNumber(usage, "cachedInputTokens", value.cache_read_input_tokens);
112
- setNumber(usage, "cacheCreationTokens", value.cache_creation_input_tokens);
113
- setNumber(usage, "reportedCostUsd", event.total_cost_usd);
114
- return usage;
115
- }
116
- function parseClaudeJsonl(raw, state = { toolFallbackIndex: 0 }) {
117
- const events = [];
118
- const nativeEvents = [];
119
- let sessionId;
120
- let text = "";
121
- let output;
122
- let usage;
123
- let terminalEvent;
124
- let failure;
125
- for (const line of jsonlFrames(raw)) {
126
- if (!line.trim()) continue;
127
- const event = parseObject(line);
128
- if (!event) {
129
- events.push({ type: "provider.event", provider: "claude", event: { type: "non-json-output", line } });
130
- continue;
131
- }
132
- nativeEvents.push(event);
133
- const limits = resolveProviderRateLimits(readProviderRateLimits("claude", event));
134
- if (limits) {
135
- events.push({ type: "provider.event", provider: "claude", event: limits });
136
- continue;
137
- }
138
- const type = stringValue(event.type);
139
- if (type === "system" && event.subtype === "init") {
140
- sessionId = stringValue(event.session_id) ?? sessionId;
141
- } else if (type === "stream_event") {
142
- const nested = event.event;
143
- if (typeof nested === "object" && nested !== null && !Array.isArray(nested)) {
144
- const delta = nested.delta;
145
- if (typeof delta === "object" && delta !== null && !Array.isArray(delta)) {
146
- const deltaText = stringValue(delta.text);
147
- if (deltaText !== void 0) events.push({ type: "message.delta", text: deltaText });
148
- else events.push({ type: "provider.event", provider: "claude", event });
149
- }
150
- }
151
- } else if (type === "assistant") {
152
- const message = event.message;
153
- const content = typeof message === "object" && message !== null && !Array.isArray(message) ? message.content : void 0;
154
- if (Array.isArray(content)) {
155
- for (const block of content) {
156
- if (typeof block !== "object" || block === null || Array.isArray(block)) continue;
157
- const value = block;
158
- if (value.type === "tool_use") {
159
- events.push({
160
- type: "tool.started",
161
- // One counter for a complete transcript or the incremental turn.
162
- id: stringValue(value.id) ?? `claude-tool-${state.toolFallbackIndex++}`,
163
- name: stringValue(value.name) ?? "unknown",
164
- ...value.input === void 0 ? {} : { input: value.input }
165
- });
166
- }
167
- }
168
- }
169
- } else if (type === "result") {
170
- terminalEvent = event;
171
- sessionId = stringValue(event.session_id) ?? sessionId;
172
- text = stringValue(event.result) ?? "";
173
- output = event.structured_output;
174
- usage = parseUsage(event);
175
- events.push({ type: "message.completed", text });
176
- if (event.is_error === true || event.terminal_reason === "api_error") {
177
- failure = classifyClaudeFailure(event);
178
- }
179
- } else {
180
- events.push({ type: "provider.event", provider: "claude", event });
181
- }
182
- }
183
- if (!terminalEvent && !failure) {
184
- failure = { kind: "protocol", message: "Claude stream ended without a result event" };
185
- }
186
- const retryAt = confirmedUsageRetryAt(events);
187
- if (failure && terminalEvent?.api_error_status === 429 && retryAt !== void 0)
188
- failure = { kind: "usage-limit", message: "Provider usage limit reached" };
189
- if (failure?.kind === "usage-limit" && retryAt !== void 0) failure = { ...failure, retryAt };
190
- return {
191
- completed: terminalEvent !== void 0 && failure === void 0,
192
- failed: failure !== void 0,
193
- refused: false,
194
- ...sessionId === void 0 ? {} : { sessionId },
195
- text,
196
- ...output === void 0 ? {} : { output },
197
- ...usage === void 0 ? {} : { usage },
198
- events,
199
- ...failure === void 0 ? {} : { failure },
200
- ...terminalEvent === void 0 ? {} : { terminalEvent },
201
- nativeEvents
202
- };
203
- }
204
-
205
- // src/adapters/claude/exec-adapter.ts
206
- function claudeProviderArgs(options) {
207
- if (!options) return [];
208
- if (options.systemPromptMode !== void 0 && !["append", "replace"].includes(String(options.systemPromptMode))) {
209
- throw new TypeError("systemPromptMode must be append or replace.");
210
- }
211
- const args = [];
212
- if (options.tools !== void 0) {
213
- if (!Array.isArray(options.tools) || !options.tools.every((tool) => typeof tool === "string" && /^[A-Za-z][A-Za-z0-9_]*$/.test(tool))) {
214
- throw new TypeError("Claude tools must be an array of built-in tool names.");
215
- }
216
- args.push("--tools", options.tools.join(","));
217
- }
218
- if (options.strictMcpConfig !== void 0) {
219
- if (typeof options.strictMcpConfig !== "boolean") throw new TypeError("strictMcpConfig must be boolean.");
220
- if (options.strictMcpConfig) args.push("--strict-mcp-config");
221
- }
222
- if (options.mcpConfigs !== void 0) {
223
- if (!Array.isArray(options.mcpConfigs) || !options.mcpConfigs.every((config) => typeof config === "string" && config.trim() !== "" && !config.includes("\0") && !config.startsWith("-"))) {
224
- throw new TypeError("Claude MCP configs must be non-empty paths or JSON strings.");
225
- }
226
- if (options.mcpConfigs.length) args.push("--mcp-config", ...options.mcpConfigs);
227
- }
228
- args.push(...claudeSettingsArgs(options));
229
- return args;
230
- }
231
- function claudeSettingsArgs(options) {
232
- if (options?.settings === void 0) return [];
233
- const settings = typeof options.settings === "string" ? options.settings : options.settings !== null && typeof options.settings === "object" && !Array.isArray(options.settings) ? JSON.stringify(options.settings) : void 0;
234
- if (!settings || settings.includes("\0") || settings.startsWith("-")) throw new TypeError("Claude settings must be a path or JSON object.");
235
- return ["--settings", settings];
236
- }
237
- function buildClaudeExecArgs(request, newSessionId) {
238
- const args = [
239
- "-p",
240
- "--output-format",
241
- "stream-json",
242
- "--verbose",
243
- "--include-partial-messages",
244
- "--model",
245
- request.modelId
246
- ];
247
- if (request.mode === "resume" || request.mode === "fork") {
248
- if (!request.sessionId) throw new TypeError(`${request.mode} requires a sessionId`);
249
- if (!isSafeSessionId(request.sessionId)) throw new TypeError("sessionId is not a safe CLI argument");
250
- args.push("--resume", request.sessionId);
251
- if (request.mode === "fork") args.push("--fork-session");
252
- } else {
253
- args.push("--session-id", newSessionId);
254
- }
255
- if (request.instructions) args.push(request.providerOptions?.systemPromptMode === "replace" ? "--system-prompt" : "--append-system-prompt", request.instructions);
256
- if (request.effort) args.push("--effort", request.effort);
257
- if (request.outputSchema) args.push("--json-schema", JSON.stringify(request.outputSchema));
258
- args.push(...claudeProviderArgs(request.providerOptions));
259
- if (request.permissionArgs.includes("dontAsk") && Array.isArray(request.providerOptions?.tools) && request.providerOptions.tools.includes("WebSearch")) args.push("--allowed-tools", "WebSearch");
260
- args.push(...request.contextArgs, ...request.permissionArgs);
261
- return args;
262
- }
263
- function namesApiBilling(vars) {
264
- return Boolean(vars.ANTHROPIC_AUTH_TOKEN || vars.ANTHROPIC_PROFILE || vars.ANTHROPIC_FEDERATION_RULE_ID && vars.ANTHROPIC_ORGANIZATION_ID);
265
- }
266
- async function explicitClaudeSettings(settings, cwd) {
267
- if (typeof settings !== "string") return settings;
268
- try {
269
- return JSON.parse(settings.trimStart().startsWith("{") ? settings : await readFile(resolve(cwd, settings), "utf8"));
270
- } catch {
271
- throw new TypeError("Claude settings must be valid JSON or a readable JSON file.");
272
- }
273
- }
274
- async function settingsMoveBilling(turn, env) {
275
- const files = [join(turn.cwd, ".claude", "settings.json"), join(turn.cwd, ".claude", "settings.local.json")];
276
- if (!turn.contextArgs.includes("--setting-sources")) {
277
- files.push(join(env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), ".claude"), "settings.json"));
278
- }
279
- const layers = await Promise.all(files.map((file) => readFile(file, "utf8").then((text) => JSON.parse(text)).catch(() => void 0)));
280
- layers.push(await explicitClaudeSettings(turn.providerOptions?.settings, turn.cwd));
281
- return layers.some((layer) => {
282
- const block = layer?.env;
283
- if (typeof block !== "object" || block === null) return false;
284
- const vars = block;
285
- return Boolean(vars.ANTHROPIC_API_KEY || vars.ANTHROPIC_BASE_URL) || namesApiBilling(vars);
286
- });
287
- }
288
- function parseClaudeAuth(raw, env, movedBySettings) {
289
- try {
290
- const value = JSON.parse(raw);
291
- const authenticated = value.loggedIn === true;
292
- const method2 = typeof value.authMethod === "string" ? value.authMethod.toLowerCase() : "";
293
- const loginSource = !authenticated ? "unknown" : method2.includes("claude.ai") || method2.includes("oauth") ? "subscription" : method2.includes("api") ? "api-key" : method2.includes("bedrock") || method2.includes("vertex") ? "cloud-provider" : "unknown";
294
- const keyInUse = typeof value.apiKeySource === "string" && !["", "none"].includes(value.apiKeySource) || namesApiBilling(env) || movedBySettings;
295
- const source = loginSource === "subscription" && keyInUse ? "api-key" : loginSource;
296
- const plan = typeof value.subscriptionType === "string" && source === loginSource ? value.subscriptionType : void 0;
297
- return {
298
- authenticated,
299
- source,
300
- ...plan === void 0 ? {} : { account: { plan } }
301
- };
302
- } catch {
303
- return { authenticated: false, source: "unknown" };
304
- }
305
- }
306
- var ClaudeExecAdapter = class {
307
- id = "claude";
308
- #runner;
309
- #probeRunner;
310
- #discovery;
311
- constructor(options = {}) {
312
- this.#runner = options.runner ?? runProcess;
313
- this.#probeRunner = options.probeRunner ?? this.#runner;
314
- this.#discovery = new ExecDiscovery("claude", this.#probeRunner, options.target);
315
- }
316
- #target(env) {
317
- return this.#discovery.target(env);
318
- }
319
- async detect(env, context) {
320
- return this.#discovery.detect(env, context);
321
- }
322
- async auth(env, context, turn) {
323
- const target = this.#target(env);
324
- if (!target) return { authenticated: false, source: "unknown" };
325
- const turnArgs = turn ? [...turn.contextArgs, ...claudeSettingsArgs(turn.providerOptions)] : [];
326
- const movedBySettings = turn ? await settingsMoveBilling(turn, env) : false;
327
- const outcome = await this.#probeRunner({
328
- command: target.command,
329
- args: [...target.argsPrefix, ...turnArgs, "auth", "status", "--json"],
330
- cwd: turn?.cwd ?? process.cwd(),
331
- env,
332
- stdin: "",
333
- timeoutMs: Math.min(15e3, context?.remainingMs() ?? 15e3),
334
- ...context ? { signal: context.signal } : {},
335
- maxOutputBytes: 64 * 1024
336
- });
337
- return parseClaudeAuth(outcome.stdout, env, movedBySettings);
338
- }
339
- async models() {
340
- return compatibilityModels("claude");
341
- }
342
- async compatibility(env, version, context) {
343
- const target = this.#target(env);
344
- if (!target) return void 0;
345
- const outcome = await this.#probeRunner({
346
- command: target.command,
347
- args: [...target.argsPrefix, "--help"],
348
- cwd: process.cwd(),
349
- env,
350
- stdin: "",
351
- timeoutMs: Math.min(15e3, context?.remainingMs() ?? 15e3),
352
- ...context ? { signal: context.signal } : {},
353
- maxOutputBytes: 256 * 1024
354
- });
355
- const assessment = assessCliCompatibility("claude", version, {
356
- main: `${outcome.stdout}
357
- ${outcome.stderr}`
358
- });
359
- return { ...assessment, features: { ...assessment.features, refusalDetection: "unsupported" } };
360
- }
361
- async execute(request) {
362
- const target = this.#target(request.env);
363
- if (!target) {
364
- return {
365
- completed: false,
366
- failed: true,
367
- refused: false,
368
- text: "",
369
- events: [],
370
- failure: { kind: "provider-unavailable", message: "Claude CLI not found" },
371
- nativeEvents: []
372
- };
373
- }
374
- const outcome = await guardJsonlFrames((onStdout) => this.#runner({
375
- command: target.command,
376
- args: [...target.argsPrefix, ...buildClaudeExecArgs(request, randomUUID())],
377
- cwd: request.cwd,
378
- env: request.env,
379
- stdin: request.prompt,
380
- timeoutMs: request.timeoutMs,
381
- maxOutputBytes: request.maxOutputBytes,
382
- onStdout,
383
- ...request.signal === void 0 ? {} : { signal: request.signal }
384
- }));
385
- const result = parseClaudeJsonl(outcome.stdout);
386
- if (outcome.code !== 0 && result.failure?.kind === "protocol") {
387
- return {
388
- ...result,
389
- failure: classifyClaudeFailure({ result: outcome.stderr.trim() || `Claude exited with code ${outcome.code}` })
390
- };
391
- }
392
- return result;
393
- }
394
- async *stream(request) {
395
- const target = this.#target(request.env);
396
- if (!target) {
397
- yield {
398
- kind: "result",
399
- result: {
400
- completed: false,
401
- failed: true,
402
- refused: false,
403
- text: "",
404
- events: [],
405
- failure: { kind: "provider-unavailable", message: "Claude CLI not found" },
406
- nativeEvents: []
407
- }
408
- };
409
- return;
410
- }
411
- const parseState = { toolFallbackIndex: 0 };
412
- const pump = new ExecStreamPump(request.signal, (line) => parseClaudeJsonl(line, parseState), parseClaudeJsonl);
413
- const execution = this.#runner({
414
- command: target.command,
415
- args: [...target.argsPrefix, ...buildClaudeExecArgs(request, randomUUID())],
416
- cwd: request.cwd,
417
- env: request.env,
418
- stdin: request.prompt,
419
- timeoutMs: request.timeoutMs,
420
- maxOutputBytes: request.maxOutputBytes,
421
- captureStdout: false,
422
- // The pump retains the incremental result; legacy runners still receive onStdout.
423
- signal: pump.signal,
424
- onStdout: pump.onStdout,
425
- onStdoutAsync: pump.onStdoutAsync,
426
- onFailure: (error) => pump.fail(error)
427
- }).then((outcome) => pump.finish((parsed) => {
428
- let result = parsed;
429
- if (outcome.code !== 0 && result.failure?.kind === "protocol") {
430
- result = {
431
- ...result,
432
- failure: classifyClaudeFailure({ result: outcome.stderr.trim() || `Claude exited with code ${outcome.code}` })
433
- };
434
- }
435
- return result;
436
- })).catch((error) => pump.fail(error));
437
- try {
438
- yield* pump.items();
439
- } catch (error) {
440
- pump.cancel();
441
- if (request.awaitSettlement) {
442
- await execution;
443
- throw pump.afterSettlement(error);
444
- }
445
- throw error;
446
- } finally {
447
- pump.cancel();
448
- if (request.awaitSettlement) await execution;
449
- }
450
- }
451
- };
452
-
453
- // src/core/context.ts
454
- function normalizeContextPolicy(policy = {}) {
455
- return {
456
- profile: policy.profile ?? "native",
457
- memory: policy.memory ?? "inherit"
458
- };
459
- }
460
- function translateContext(provider, requested = {}) {
461
- if (provider !== "claude" && provider !== "codex") throw new UnknownProviderError(provider);
462
- const policy = normalizeContextPolicy(requested);
463
- const args = [];
464
- const unsupported = [];
465
- const warnings = [];
466
- const active = [];
467
- const inactive = [];
468
- const unavoidable = ["admin-managed-policy"];
469
- const unknown = [];
470
- if (provider === "claude") {
471
- if (policy.profile === "native") {
472
- active.push("user-settings", "project-settings", "discovered-instructions", "skills", "hooks", "plugins", "mcp");
473
- } else if (policy.profile === "project") {
474
- args.push("--setting-sources", "project,local");
475
- active.push("project-settings", "local-settings", "discovered-instructions");
476
- inactive.push("user-settings");
477
- unknown.push("provider-memory");
478
- } else {
479
- args.push("--safe-mode");
480
- inactive.push("discovered-instructions", "skills", "hooks", "plugins", "mcp", "provider-memory");
481
- active.push("authentication", "model-selection", "built-in-tools", "permissions");
482
- }
483
- if (policy.memory === "read-only") unsupported.push("memory.read-only");
484
- if (policy.memory === "off" && policy.profile !== "clean") {
485
- unsupported.push("memory.off-without-clean-profile");
486
- }
487
- } else {
488
- if (policy.profile === "native") {
489
- active.push("user-config", "project-config", "AGENTS.md", "rules", "skills", "hooks", "plugins", "mcp");
490
- } else if (policy.profile === "project") {
491
- args.push("--ignore-user-config");
492
- inactive.push("user-config");
493
- active.push("project-config", "AGENTS.md", "rules");
494
- unsupported.push("context.project.global-instructions");
495
- } else {
496
- args.push("--ignore-user-config", "--ignore-rules");
497
- inactive.push("user-config", "rules");
498
- unsupported.push("context.clean.project-instructions", "context.clean.plugins-skills-hooks-mcp");
499
- unknown.push("AGENTS.md", "plugins", "skills", "hooks", "mcp");
500
- }
501
- if (policy.memory === "off") {
502
- args.push("--disable", "memories");
503
- inactive.push("provider-memory");
504
- } else if (policy.memory === "read-only") {
505
- unsupported.push("memory.read-only");
506
- } else {
507
- unknown.push("provider-memory");
508
- }
509
- }
510
- if (unsupported.length > 0) {
511
- warnings.push(`Context policy is not fully enforceable by ${provider} exec`);
512
- }
513
- return {
514
- args,
515
- unsupported,
516
- warnings,
517
- report: {
518
- profile: policy.profile,
519
- memory: policy.memory,
520
- active: [...new Set(active)],
521
- inactive: [...new Set(inactive)],
522
- unavoidable,
523
- unknown: [...new Set(unknown)]
524
- }
525
- };
526
- }
527
-
528
- // src/core/permissions.ts
529
- function translatePermissions(provider, requested, transport = "exec") {
530
- if (provider !== "claude" && provider !== "codex") throw new UnknownProviderError(provider);
531
- if (requested.mode === "respond" && (provider !== "claude" || transport !== "exec")) {
532
- throw new TypeError("respond is only supported by Claude exec");
533
- }
534
- if (!["analyze", "respond", "edit", "unrestricted"].includes(requested.mode)) {
535
- throw new TypeError("Unknown permission mode");
536
- }
537
- const args = [];
538
- const unsupported = [];
539
- const warnings = [];
540
- const enforcedBy = [];
541
- let filesystem = "unknown";
542
- let network = "provider-default";
543
- let approvals = "non-interactive";
544
- if (provider === "claude") {
545
- if (requested.mode === "respond") {
546
- args.push("--permission-mode", "dontAsk", "--strict-mcp-config");
547
- filesystem = "no filesystem tools; harness tool restriction, not an OS sandbox";
548
- approvals = "deny-unapproved";
549
- enforcedBy.push("harness");
550
- } else if (requested.mode === "analyze") {
551
- args.push("--permission-mode", "plan");
552
- filesystem = "provider plan mode; write prevention is not an OS sandbox";
553
- enforcedBy.push("harness");
554
- } else if (requested.mode === "edit") {
555
- args.push("--permission-mode", "acceptEdits");
556
- filesystem = "provider edit permissions within configured roots";
557
- enforcedBy.push("harness");
558
- warnings.push("Exec cannot answer interactive approval requests");
559
- } else {
560
- args.push("--dangerously-skip-permissions");
561
- filesystem = "unrestricted";
562
- network = "unrestricted";
563
- approvals = "bypassed";
564
- warnings.push("Claude permission checks are bypassed");
565
- }
566
- if (requested.network === "deny") unsupported.push("network.deny");
567
- if (requested.network === "allow") network = "provider-default; not guaranteed";
568
- } else {
569
- const never = transport === "exec" ? ["--ask-for-approval", "never"] : [];
570
- if (requested.mode === "analyze") {
571
- args.push("--sandbox", "read-only", ...never);
572
- filesystem = "read-only sandbox";
573
- enforcedBy.push("sandbox");
574
- if (never.length) approvals = "never; escalation requests are rejected";
575
- } else if (requested.mode === "edit") {
576
- args.push("--sandbox", "workspace-write", ...never);
577
- filesystem = "workspace-write sandbox";
578
- enforcedBy.push("sandbox");
579
- if (never.length) approvals = "never; escalation requests are rejected";
580
- warnings.push("Exec cannot answer interactive approval requests");
581
- } else {
582
- args.push("--dangerously-bypass-approvals-and-sandbox");
583
- filesystem = "unrestricted";
584
- network = "unrestricted";
585
- approvals = "bypassed";
586
- warnings.push("Codex approvals and sandbox are bypassed");
587
- }
588
- if (requested.network === "deny") unsupported.push("network.deny");
589
- if (requested.network === "allow") network = "provider-default; not guaranteed";
590
- }
591
- for (const directory of requested.additionalDirectories ?? []) {
592
- args.push("--add-dir", directory);
593
- }
594
- if (requested.minimumEnforcement && !enforcedBy.includes(requested.minimumEnforcement)) {
595
- unsupported.push(`minimumEnforcement.${requested.minimumEnforcement}`);
596
- }
597
- if (transport === "control" && requested.mode !== "unrestricted") {
598
- approvals = provider === "claude" ? "interactive" : "interactive; decline-only for command and file-change escalations below unrestricted";
599
- const execWarning = warnings.indexOf("Exec cannot answer interactive approval requests");
600
- if (execWarning !== -1) warnings.splice(execWarning, 1);
601
- }
602
- return {
603
- args,
604
- report: {
605
- requested: { ...requested },
606
- effective: { filesystem, network, approvals, enforcedBy },
607
- unsupported,
608
- warnings
609
- }
610
- };
611
- }
612
-
613
- // src/core/builtin-providers.ts
614
- function builtin(id, options = {}) {
615
- const runner = options.runner;
616
- const probeRunner = options.probeRunner;
617
- if (runner !== void 0 && typeof runner !== "function") throw new TypeError("runner must be a function");
618
- if (probeRunner !== void 0 && typeof probeRunner !== "function") throw new TypeError("probeRunner must be a function");
619
- const create = (target) => {
620
- const adapterOptions = { ...runner === void 0 ? {} : { runner }, ...probeRunner === void 0 ? {} : { probeRunner }, ...target === void 0 ? {} : { target } };
621
- return id === "claude" ? new ClaudeExecAdapter(adapterOptions) : new CodexExecAdapter(adapterOptions);
622
- };
623
- return {
624
- apiVersion: 1,
625
- id,
626
- exec: {
627
- adapter: create(),
628
- token: EXEC_TRANSPORT_TOKENS[id],
629
- adapterVersion: RUNTIME_ADAPTER_VERSION,
630
- withTarget: create
631
- },
632
- modelCatalog: compatibilityModels(id),
633
- resolveModel: (nativeId) => resolveModel(`${id}/${nativeId}`),
634
- execCapabilities: { tokenDeltas: id === "claude" ? "unverified" : "unsupported" },
635
- translateContext: (requested) => translateContext(id, requested),
636
- translatePermissions: (requested, transport) => translatePermissions(id, requested, transport),
637
- validateOptions: (options2, transport) => {
638
- assertRespondPolicy(options2, id, transport);
639
- const config = id === "codex" && options2.requireAuth === "subscription" ? options2.providerOptions?.codex?.config : void 0;
640
- if (config && (config.profile !== void 0 || config.openai_base_url !== void 0 || (config.model_provider ?? "openai") !== "openai")) throw new UnexpectedAuthSourceError(id, {
641
- transport,
642
- retryable: false,
643
- sanitizedDiagnostics: { detectedSource: "provider-config" }
644
- });
645
- }
646
- };
647
- }
648
- function createClaudeProvider(options) {
649
- return builtin("claude", options);
650
- }
651
- function createCodexProvider(options) {
652
- return builtin("codex", options);
653
- }
654
-
655
- // src/orchestration/log/capture-runtime.ts
656
- import { randomUUID as randomUUID2 } from "node:crypto";
657
- function createRuntimeCapture(options) {
658
- object(options, ["store", "identity", "maxPending", "maxWriteMs"]);
659
- const base = captureIdentity(options.identity), maxPending = boundedInteger(options.maxPending ?? 2, 1, 64), maxWriteMs = boundedInteger(options.maxWriteMs ?? 5e3, 1, 3e4);
660
- const append = method(options.store, "append");
661
- let pending = 0, failure;
662
- const stopped = new AbortController();
663
- const fail = (cause) => {
664
- if (!failure) {
665
- failure = isExecutionHalted(cause) ? cause : new ExecutionHaltedError({}, { cause });
666
- stopped.abort(failure);
667
- }
668
- return failure;
669
- };
670
- const store = Object.freeze({ append(commit) {
671
- if (failure) return Promise.reject(failure);
672
- if (pending >= maxPending) return Promise.reject(fail(Error("CAPTURE_CAPACITY")));
673
- pending++;
674
- let work;
675
- try {
676
- work = Promise.resolve(append(commit));
677
- } catch (error) {
678
- pending--;
679
- return Promise.reject(fail(error));
680
- }
681
- return work.then((receipt) => receipt, (error) => {
682
- throw fail(error);
683
- }).finally(() => {
684
- pending--;
685
- });
686
- } });
687
- return Object.freeze({ bindAgent() {
688
- const identity = captureIdentity({ ...base, agentId: `agent-${randomUUID2()}` });
689
- return Object.freeze({ identity, assertActive() {
690
- if (failure) throw failure;
691
- }, create(model, transport, phase, signal, session) {
692
- if (failure) throw failure;
693
- const operationSignal = signal ? AbortSignal.any([signal, stopped.signal]) : stopped.signal;
694
- const capture = createRequiredLogCapture({ store, identity, actual: { provider: model.provider, model: model.id, transport, phase, attemptId: randomUUID2(), ...session ? { sessionId: session.id, transportEpoch: session.transportEpoch } : {} }, maxPending, maxWriteMs, signal: operationSignal });
695
- capture.signal.addEventListener("abort", () => {
696
- fail(capture.signal.reason);
697
- }, { once: true });
698
- return Object.freeze({
699
- ...capture,
700
- signal: AbortSignal.any([capture.signal, stopped.signal]),
701
- async run(work) {
702
- try {
703
- return await capture.run(work);
704
- } catch (error) {
705
- if (isExecutionHalted(error)) fail(error);
706
- throw error;
707
- }
708
- }
709
- });
710
- } });
711
- } });
712
- }
713
-
714
- // src/core/runtime.ts
715
- var Runtime = class {
716
- #registry = new AdapterRegistry();
717
- #providers = /* @__PURE__ */ new Map();
718
- #legacyAdapters;
719
- #capture;
720
- #memory;
721
- constructor(options = {}) {
722
- const memory = options.memory;
723
- if (memory !== void 0 && (typeof memory !== "object" || memory === null || typeof memory.scope !== "function")) {
724
- throw new TypeError("The Runtime memory default must be an object whose scope is a function");
725
- }
726
- this.#memory = memory === void 0 ? void 0 : Object.freeze({ ...memory });
727
- const capture = field(options, "capture");
728
- this.#capture = capture === void 0 ? void 0 : createRuntimeCapture(capture);
729
- this.#legacyAdapters = options.adapters !== void 0;
730
- if (options.providers && (options.adapters || options.controlAdapters)) {
731
- throw new TypeError("providers cannot be combined with adapters or controlAdapters");
732
- }
733
- const providers = options.providers ?? [createClaudeProvider(), createCodexProvider()];
734
- for (const input of providers) {
735
- const registration = snapshotProvider(input);
736
- if (this.#providers.has(registration.id)) {
737
- throw new TypeError(`Provider ${registration.id} is already registered`);
738
- }
739
- this.#providers.set(registration.id, registration);
740
- if (!options.adapters) this.#registry.registerExec(registration.exec);
741
- if (registration.control) this.#registry.registerControl(registration.control);
742
- }
743
- for (const adapter of options.adapters ?? []) {
744
- this.#registry.registerExec({ adapter });
745
- }
746
- for (const registration of options.controlAdapters ?? []) {
747
- this.#registry.registerControl(registration);
748
- }
749
- }
750
- get registry() {
751
- return this.#registry;
752
- }
753
- bindLogCapture() {
754
- return this.#capture?.bindAgent();
755
- }
756
- /** The memory every Agent of this Runtime gets unless it says otherwise. */
757
- memoryDefault() {
758
- return this.#memory;
759
- }
760
- registration(provider) {
761
- const registration = this.#providers.get(provider);
762
- if (!registration) throw new UnknownProviderError(provider);
763
- return registration;
764
- }
765
- resolveModel(requested) {
766
- const value = requested.trim();
767
- if (!value) throw new UnknownModelError(requested);
768
- const slash = value.indexOf("/");
769
- if (slash > 0) {
770
- const prefix = value.slice(0, slash);
771
- const provider = ["claude", "codex"].includes(prefix.toLowerCase()) ? prefix.toLowerCase() : prefix;
772
- const native = value.slice(slash + 1);
773
- if (!native) throw new UnknownModelError(requested);
774
- const registration = this.registration(provider);
775
- const known = this.#find(registration, native);
776
- const model = known ?? registration.resolveModel(native);
777
- if (model.provider !== provider || !model.id.trim()) {
778
- throw new TypeError("Resolved model provider mismatch");
779
- }
780
- return structuredClone(model);
781
- }
782
- const matches = [...this.#providers.values()].flatMap((registration) => {
783
- const match = this.#find(registration, value);
784
- return match ? [match] : [];
785
- });
786
- if (matches.length > 1 || ["best", "default"].includes(value.toLowerCase()) && this.#providers.size > 1) {
787
- throw new AmbiguousModelError(requested, matches.length ? matches.map((model) => model.provider) : [...this.#providers.keys()]);
788
- }
789
- if (matches[0]) return structuredClone(matches[0]);
790
- const inferred = value.toLowerCase().startsWith("claude-") ? "claude" : value.toLowerCase().startsWith("gpt-") || /^o\d/.test(value.toLowerCase()) ? "codex" : void 0;
791
- if (inferred && this.#providers.has(inferred)) {
792
- const model = this.registration(inferred).resolveModel(value);
793
- if (model.provider !== inferred || !model.id.trim()) throw new TypeError("Resolved model provider mismatch");
794
- return structuredClone(model);
795
- }
796
- try {
797
- resolveModel(requested);
798
- } catch (error) {
799
- if (error instanceof UnknownModelError) throw error;
800
- }
801
- throw new UnknownModelError(requested);
802
- }
803
- #find(registration, id) {
804
- const builtin2 = registration.id === "claude" || registration.id === "codex";
805
- const value = builtin2 ? id.toLowerCase() : id;
806
- return registration.modelCatalog.find((model) => model.id === value || model.aliases.includes(value));
807
- }
808
- async models(provider) {
809
- if (this.#legacyAdapters) {
810
- const ids = provider === void 0 ? this.providers() : [provider];
811
- const catalogs = await Promise.all(ids.map(async (id) => {
812
- const models = await this.adapter(id).models();
813
- if (models.some((model) => model.provider !== id)) throw new TypeError("Model catalog provider mismatch");
814
- return structuredClone(models);
815
- }));
816
- return catalogs.flat();
817
- }
818
- const providers = provider === void 0 ? [...this.#providers.values()] : [this.registration(provider)];
819
- return providers.flatMap((registration) => structuredClone([...registration.modelCatalog]));
820
- }
821
- adapter(provider) {
822
- const registration = this.#registry.execRegistration(provider);
823
- if (!registration) throw new UnknownProviderError(provider);
824
- return registration.adapter;
825
- }
826
- adapterWithTarget(provider, target) {
827
- const registration = this.#registry.execRegistration(provider);
828
- if (!registration) throw new UnknownProviderError(provider);
829
- const adapter = registration.withTarget?.(target) ?? registration.adapter;
830
- if (adapter.id !== provider) throw new TypeError("Bound adapter provider mismatch");
831
- return adapter;
832
- }
833
- controlRegistration(provider) {
834
- return this.#registry.control(provider);
835
- }
836
- providers() {
837
- return this.#registry.providers();
838
- }
839
- };
840
- var defaultRuntime = new Runtime();
841
-
842
- export {
843
- parseClaudeJsonl,
844
- ClaudeExecAdapter,
845
- normalizeContextPolicy,
846
- translateContext,
847
- translatePermissions,
848
- createClaudeProvider,
849
- createCodexProvider,
850
- Runtime,
851
- defaultRuntime
852
- };
853
- //# sourceMappingURL=chunk-C2DN6KL4.js.map