runwarden 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1282 @@
1
+ import { n as createDb, r as policyDecisions, t as initDb } from "./init-Dm_qLwix.js";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { sql } from "drizzle-orm";
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { ToolLoopAgent, tool } from "ai";
7
+ import { z } from "zod";
8
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
9
+ import { hostname } from "node:os";
10
+ // src/contracts/errors.ts
11
+ var AgentRuntimeError = class extends Error {
12
+ kind;
13
+ diagnostics;
14
+ constructor(kind, message, diagnostics = {}, options = {}) {
15
+ super(message, options);
16
+ this.kind = kind;
17
+ this.diagnostics = diagnostics;
18
+ this.name = "AgentRuntimeError";
19
+ }
20
+ };
21
+ // src/db/repositories/invocations.ts
22
+ function mapRow(raw) {
23
+ return {
24
+ id: Number(raw.id),
25
+ scope: raw.scope,
26
+ conversationId: raw.conversation_id ?? null,
27
+ orderingKey: raw.ordering_key ?? null,
28
+ input: raw.input,
29
+ resultText: raw.result_text ?? null,
30
+ idempotencyKey: raw.idempotency_key ?? null,
31
+ status: raw.status,
32
+ attemptCount: Number(raw.attempt_count),
33
+ maxAttempts: Number(raw.max_attempts),
34
+ nextAttemptAt: raw.next_attempt_at,
35
+ claimedAt: raw.claimed_at ?? null,
36
+ claimedBy: raw.claimed_by ?? null,
37
+ leaseHeartbeatAt: raw.lease_heartbeat_at ?? null,
38
+ leaseExpiresAt: raw.lease_expires_at ?? null,
39
+ activeRunId: raw.active_run_id ?? null,
40
+ activeRunRegisteredAt: raw.active_run_registered_at ?? null,
41
+ pendingToolCall: raw.pending_tool_call ?? null,
42
+ startedAt: raw.started_at ?? null,
43
+ completedAt: raw.completed_at ?? null,
44
+ failedAt: raw.failed_at ?? null,
45
+ provider: raw.provider ?? null,
46
+ model: raw.model ?? null,
47
+ lastErrorCode: raw.last_error_code ?? null,
48
+ lastErrorMessage: raw.last_error_message ?? null,
49
+ metadata: raw.metadata ?? null,
50
+ createdAt: raw.created_at,
51
+ updatedAt: raw.updated_at
52
+ };
53
+ }
54
+ function toPendingToolCall(raw) {
55
+ if (typeof raw !== "object" || raw === null) return void 0;
56
+ const toolName = raw.toolName;
57
+ if (typeof toolName !== "string") return void 0;
58
+ return {
59
+ toolName,
60
+ input: raw.input
61
+ };
62
+ }
63
+ function toRecord(row) {
64
+ return {
65
+ ...row.input,
66
+ id: String(row.id),
67
+ status: row.status,
68
+ attemptCount: row.attemptCount,
69
+ resultText: row.resultText ?? void 0,
70
+ pendingToolCall: toPendingToolCall(row.pendingToolCall),
71
+ lastErrorCode: row.lastErrorCode ?? void 0,
72
+ lastErrorMessage: row.lastErrorMessage ?? void 0,
73
+ createdAt: row.createdAt,
74
+ completedAt: row.completedAt ?? void 0
75
+ };
76
+ }
77
+ async function enqueueInvocation(db, input) {
78
+ const first = (await db.execute(sql`
79
+ insert into agent_runtime.invocations
80
+ (scope, conversation_id, ordering_key, input, idempotency_key, max_attempts, metadata)
81
+ values (
82
+ ${input.scope},
83
+ ${input.conversationId ?? null},
84
+ ${input.orderingKey ?? null},
85
+ ${JSON.stringify(input)}::jsonb,
86
+ ${input.idempotencyKey ?? null},
87
+ ${input.maxAttempts ?? 3},
88
+ ${input.metadata ? JSON.stringify(input.metadata) : null}::jsonb
89
+ )
90
+ on conflict (scope, idempotency_key) where idempotency_key is not null
91
+ do nothing
92
+ returning id
93
+ `)).rows[0];
94
+ if (first) return {
95
+ invocationId: String(first.id),
96
+ created: true
97
+ };
98
+ if (!input.idempotencyKey) throw new Error("enqueue inserted no row without an idempotency key");
99
+ const found = (await db.execute(sql`
100
+ select id from agent_runtime.invocations
101
+ where scope = ${input.scope} and idempotency_key = ${input.idempotencyKey}
102
+ limit 1
103
+ `)).rows[0];
104
+ if (!found) throw new Error("enqueue conflicted but no existing row found");
105
+ return {
106
+ invocationId: String(found.id),
107
+ created: false
108
+ };
109
+ }
110
+ async function getInvocationRowById(db, id) {
111
+ const raw = (await db.execute(sql`select * from agent_runtime.invocations where id = ${id} limit 1`)).rows[0];
112
+ return raw ? mapRow(raw) : void 0;
113
+ }
114
+ async function claimInvocations(db, workerId, options) {
115
+ return (await db.execute(sql`
116
+ with exhausted as (
117
+ update agent_runtime.invocations
118
+ set status = 'failed',
119
+ failed_at = now(), completed_at = now(), updated_at = now(),
120
+ last_error_code = 'lease_expired',
121
+ last_error_message = 'Lease expired on the final attempt',
122
+ ${CLEAR_CLAIM}
123
+ where status = 'running' and lease_expires_at < now()
124
+ and attempt_count >= max_attempts
125
+ returning id
126
+ ), candidate as (
127
+ select inv.id
128
+ from agent_runtime.invocations inv
129
+ where inv.attempt_count < inv.max_attempts
130
+ and (
131
+ (inv.status = 'pending' and inv.next_attempt_at <= now())
132
+ or (inv.status = 'running' and inv.lease_expires_at < now())
133
+ )
134
+ and (
135
+ inv.ordering_key is null
136
+ or not exists (
137
+ select 1
138
+ from agent_runtime.invocations pred
139
+ where pred.scope = inv.scope
140
+ and pred.ordering_key = inv.ordering_key
141
+ and pred.id <> inv.id
142
+ and pred.status in ('pending', 'running', 'awaiting_approval')
143
+ and pred.id not in (select id from exhausted)
144
+ and (
145
+ pred.status = 'running'
146
+ or pred.created_at < inv.created_at
147
+ or (pred.created_at = inv.created_at and pred.id < inv.id)
148
+ )
149
+ )
150
+ )
151
+ order by inv.created_at asc, inv.id asc
152
+ for update skip locked
153
+ limit ${options.maxBatchSize}
154
+ )
155
+ update agent_runtime.invocations inv
156
+ set status = 'running',
157
+ attempt_count = inv.attempt_count + 1,
158
+ claimed_at = now(),
159
+ claimed_by = ${workerId},
160
+ lease_heartbeat_at = now(),
161
+ lease_expires_at = now() + (${options.leaseTimeoutMs} * interval '1 millisecond'),
162
+ started_at = coalesce(inv.started_at, now()),
163
+ active_run_id = gen_random_uuid(),
164
+ active_run_registered_at = now(),
165
+ updated_at = now()
166
+ from candidate
167
+ where inv.id = candidate.id
168
+ returning inv.*
169
+ `)).rows.map(mapRow);
170
+ }
171
+ async function heartbeatInvocation(db, id, workerId, runId, leaseTimeoutMs) {
172
+ return (await db.execute(sql`
173
+ update agent_runtime.invocations
174
+ set lease_heartbeat_at = now(),
175
+ lease_expires_at = now() + (${leaseTimeoutMs} * interval '1 millisecond'),
176
+ updated_at = now()
177
+ where id = ${id} and claimed_by = ${workerId} and status = 'running'
178
+ and active_run_id = ${runId}
179
+ returning id
180
+ `)).rows.length > 0;
181
+ }
182
+ const CLEAR_CLAIM = sql`
183
+ claimed_at = null,
184
+ claimed_by = null,
185
+ lease_heartbeat_at = null,
186
+ lease_expires_at = null
187
+ `;
188
+ async function markInvocationSucceeded(db, id, workerId, runId, result) {
189
+ return (await db.execute(sql`
190
+ update agent_runtime.invocations
191
+ set status = 'succeeded',
192
+ result_text = ${result.resultText},
193
+ provider = ${result.provider ?? null},
194
+ model = ${result.model ?? null},
195
+ pending_tool_call = null,
196
+ completed_at = now(),
197
+ failed_at = null,
198
+ ${CLEAR_CLAIM},
199
+ updated_at = now()
200
+ where id = ${id} and claimed_by = ${workerId} and status = 'running'
201
+ and active_run_id = ${runId}
202
+ returning id
203
+ `)).rows.length > 0;
204
+ }
205
+ async function markInvocationAwaitingApproval(db, id, workerId, runId, pendingToolCall) {
206
+ const raw = (await db.execute(sql`
207
+ update agent_runtime.invocations
208
+ set status = 'awaiting_approval',
209
+ pending_tool_call = ${JSON.stringify(pendingToolCall)}::jsonb,
210
+ attempt_count = greatest(attempt_count - 1, 0),
211
+ last_error_code = null,
212
+ last_error_message = null,
213
+ ${CLEAR_CLAIM},
214
+ updated_at = now()
215
+ where id = ${id} and claimed_by = ${workerId} and status = 'running'
216
+ and active_run_id = ${runId}
217
+ returning *
218
+ `)).rows[0];
219
+ return raw ? mapRow(raw) : void 0;
220
+ }
221
+ async function markInvocationFailed(db, id, workerId, runId, error, retryDelayMs) {
222
+ const raw = (await db.execute(sql`
223
+ update agent_runtime.invocations
224
+ set status = (case when attempt_count >= max_attempts then 'failed' else 'pending' end)::agent_runtime.invocation_status,
225
+ next_attempt_at = now() + (${retryDelayMs} * interval '1 millisecond'),
226
+ failed_at = case when attempt_count >= max_attempts then now() else failed_at end,
227
+ completed_at = case when attempt_count >= max_attempts then now() else completed_at end,
228
+ pending_tool_call = case when attempt_count >= max_attempts then null else pending_tool_call end,
229
+ last_error_code = ${error.code},
230
+ last_error_message = ${error.message},
231
+ ${CLEAR_CLAIM},
232
+ updated_at = now()
233
+ where id = ${id} and claimed_by = ${workerId} and status = 'running'
234
+ and active_run_id = ${runId}
235
+ returning *
236
+ `)).rows[0];
237
+ return raw ? mapRow(raw) : void 0;
238
+ }
239
+ // src/db/repositories/approvals.ts
240
+ async function listAwaitingApprovalRows(db, scope) {
241
+ return (scope !== void 0 ? await db.execute(sql`
242
+ select * from agent_runtime.invocations
243
+ where status = 'awaiting_approval' and scope = ${scope}
244
+ order by created_at asc, id asc
245
+ `) : await db.execute(sql`
246
+ select * from agent_runtime.invocations
247
+ where status = 'awaiting_approval'
248
+ order by created_at asc, id asc
249
+ `)).rows.map(mapRow);
250
+ }
251
+ async function resolveInvocationApproval(db, id, resolution, options = {}) {
252
+ return db.transaction(async (tx) => {
253
+ const raw = (await tx.execute(sql`
254
+ select * from agent_runtime.invocations where id = ${id} for update
255
+ `)).rows[0];
256
+ if (!raw) return { outcome: "not_found" };
257
+ const row = mapRow(raw);
258
+ if (row.status !== "awaiting_approval") return {
259
+ outcome: "not_awaiting",
260
+ row
261
+ };
262
+ const pending = toPendingToolCall(row.pendingToolCall);
263
+ const detail = {
264
+ toolInput: pending?.input ?? null,
265
+ ...options.resolvedBy ? { resolvedBy: options.resolvedBy } : {},
266
+ ...options.note ? { note: options.note } : {}
267
+ };
268
+ await tx.execute(sql`
269
+ insert into agent_runtime.policy_decisions
270
+ (scope, invocation_id, run_id, tool_name, rule, decision, detail)
271
+ values (
272
+ ${row.scope},
273
+ ${row.id},
274
+ ${row.activeRunId ?? randomUUID()},
275
+ ${pending?.toolName ?? null},
276
+ 'require_approval',
277
+ ${resolution},
278
+ ${JSON.stringify(detail)}::jsonb
279
+ )
280
+ `);
281
+ const updatedRaw = (resolution === "approved" ? await tx.execute(sql`
282
+ update agent_runtime.invocations
283
+ set status = 'pending',
284
+ next_attempt_at = now(),
285
+ last_error_code = null,
286
+ last_error_message = null,
287
+ updated_at = now()
288
+ where id = ${row.id}
289
+ returning *
290
+ `) : await tx.execute(sql`
291
+ update agent_runtime.invocations
292
+ set status = 'cancelled',
293
+ pending_tool_call = null,
294
+ last_error_code = 'approval_rejected',
295
+ last_error_message = ${options.note ?? "Approval rejected"},
296
+ failed_at = now(),
297
+ completed_at = now(),
298
+ updated_at = now()
299
+ where id = ${row.id}
300
+ returning *
301
+ `)).rows[0];
302
+ return {
303
+ outcome: "resolved",
304
+ row: mapRow(updatedRaw)
305
+ };
306
+ });
307
+ }
308
+ // src/brand.ts
309
+ const RUNTIME_NAME = "runwarden";
310
+ const RUN_ID_HEADER = "X-Runwarden-Run-Id";
311
+ const ERROR_CATEGORY_META_KEY = "runwarden/error-category";
312
+ const IDEMPOTENCY_KEY_META_KEY = "runwarden/idempotency-key";
313
+ // src/mcp/native-mcp-client.ts
314
+ function isTimeoutFailure$1(error) {
315
+ if (!(error instanceof Error)) return false;
316
+ return ["AbortError", "TimeoutError"].includes(error.name) || error.code === -32001;
317
+ }
318
+ function required$1(value, name) {
319
+ if (!value.trim()) throw new Error(`${name} is required`);
320
+ return value;
321
+ }
322
+ function isCorrectable(meta) {
323
+ return meta?.[ERROR_CATEGORY_META_KEY] === "correctable";
324
+ }
325
+ var NativeMcpClient = class {
326
+ endpoint;
327
+ headers;
328
+ timeoutMs;
329
+ maxResultBytes;
330
+ constructor(config) {
331
+ this.endpoint = new URL(required$1(config.endpoint, "endpoint"));
332
+ if (!["http:", "https:"].includes(this.endpoint.protocol)) throw new Error("endpoint must use http or https");
333
+ this.headers = config.headers ?? {};
334
+ this.timeoutMs = config.timeoutMs ?? 3e4;
335
+ this.maxResultBytes = config.maxResultBytes ?? 32768;
336
+ for (const [name, value] of [["timeoutMs", this.timeoutMs], ["maxResultBytes", this.maxResultBytes]]) if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${name} must be a positive integer`);
337
+ }
338
+ async open(input) {
339
+ const client = new Client({
340
+ name: `${RUNTIME_NAME}-runtime`,
341
+ version: "1"
342
+ });
343
+ const transport = new StreamableHTTPClientTransport(this.endpoint, { requestInit: { headers: {
344
+ ...this.headers,
345
+ [RUN_ID_HEADER]: input.runId
346
+ } } });
347
+ try {
348
+ await client.connect(transport, { timeout: Math.min(this.timeoutMs, input.timeoutMs) });
349
+ } catch (error) {
350
+ await client.close().catch(() => void 0);
351
+ if (isTimeoutFailure$1(error)) throw new AgentRuntimeError("timeout", "MCP connection timed out");
352
+ throw new AgentRuntimeError("failure", "MCP connection failed");
353
+ }
354
+ return {
355
+ callTool: async (call) => {
356
+ try {
357
+ const result = await client.callTool({
358
+ name: call.name,
359
+ arguments: call.arguments,
360
+ ...call.idempotencyKey ? { _meta: { [IDEMPOTENCY_KEY_META_KEY]: call.idempotencyKey } } : {}
361
+ }, void 0, { timeout: Math.min(this.timeoutMs, call.timeoutMs) });
362
+ if (!Array.isArray(result.content) || result.isError && !isCorrectable(result._meta)) throw new AgentRuntimeError("failure", "MCP tool call failed");
363
+ const serialized = JSON.stringify(result.content);
364
+ if (Buffer.byteLength(serialized, "utf8") > this.maxResultBytes) throw new AgentRuntimeError("failure", "MCP tool result exceeded limit");
365
+ return serialized;
366
+ } catch (error) {
367
+ if (error instanceof AgentRuntimeError) throw error;
368
+ if (isTimeoutFailure$1(error)) throw new AgentRuntimeError("timeout", "MCP tool call timed out");
369
+ throw new AgentRuntimeError("failure", "MCP tool call failed");
370
+ }
371
+ },
372
+ close: () => client.close()
373
+ };
374
+ }
375
+ };
376
+ // src/runtime/canonical-json.ts
377
+ function canonicalJson(value) {
378
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`;
379
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
380
+ return JSON.stringify(value) ?? "undefined";
381
+ }
382
+ function deriveToolCallIdempotencyKey(invocationId, toolName, input) {
383
+ return createHash("sha256").update(`invocation:${invocationId}\n${toolName}\n${canonicalJson(input)}`).digest("hex");
384
+ }
385
+ // src/runtime/policy-engine.ts
386
+ const TOOL_PROPOSAL_CORRECTION = "Return exactly one tool call for the next required step. Wait for its result before proposing another tool.";
387
+ function isSameToolCall(approved, toolName, input) {
388
+ return approved.toolName === toolName && canonicalJson(approved.input) === canonicalJson(input);
389
+ }
390
+ var PolicyEngine = class {
391
+ policies;
392
+ hooks;
393
+ exactlyOne;
394
+ correctionBudget;
395
+ maxToolCallsPerInvocation;
396
+ pendingCorrection;
397
+ terminal;
398
+ approvedToolCalls = 0;
399
+ approvedToolCall;
400
+ pendingApproval;
401
+ constructor(policies, hooks = {}) {
402
+ this.policies = policies;
403
+ this.hooks = hooks;
404
+ this.exactlyOne = policies.exactlyOneToolCallPerStep ?? true;
405
+ this.correctionBudget = policies.correctionBudget ?? 1;
406
+ this.maxToolCallsPerInvocation = policies.maxToolCallsPerInvocation ?? 8;
407
+ this.approvedToolCall = hooks.approvedToolCall;
408
+ for (const [name, value] of [["correctionBudget", this.correctionBudget], ["maxToolCallsPerInvocation", this.maxToolCallsPerInvocation]]) if (!Number.isSafeInteger(value) || value < (name === "correctionBudget" ? 0 : 1)) throw new Error(`${name} must be a ${name === "correctionBudget" ? "non-negative" : "positive"} integer`);
409
+ }
410
+ get terminalError() {
411
+ return this.terminal;
412
+ }
413
+ get pendingApprovalCall() {
414
+ return this.pendingApproval;
415
+ }
416
+ fail(error) {
417
+ if (!this.terminal || error.diagnostics.code === "audit_persistence_failed") this.terminal = error;
418
+ }
419
+ correctionInstruction() {
420
+ return this.pendingCorrection?.instruction;
421
+ }
422
+ approvalFor(input) {
423
+ if (this.exactlyOne && input.proposalCount > 1) {
424
+ this.record({
425
+ rule: "exactly_one",
426
+ decision: "deny",
427
+ toolName: input.toolName
428
+ });
429
+ return {
430
+ type: "denied",
431
+ reason: TOOL_PROPOSAL_CORRECTION
432
+ };
433
+ }
434
+ const allowlist = typeof this.policies.toolAllowlist === "function" ? this.policies.toolAllowlist(input.scope) : this.policies.toolAllowlist;
435
+ if (allowlist && !allowlist.includes(input.toolName)) {
436
+ this.record({
437
+ rule: "allowlist",
438
+ decision: "deny",
439
+ toolName: input.toolName
440
+ });
441
+ return {
442
+ type: "denied",
443
+ reason: `Tool ${input.toolName} is not available under the current policy.`
444
+ };
445
+ }
446
+ if (this.pendingCorrection?.kind === "input-validation" && input.toolName !== this.pendingCorrection.toolName) {
447
+ this.record({
448
+ rule: "input_validation",
449
+ decision: "deny",
450
+ toolName: input.toolName
451
+ });
452
+ this.terminal ??= new AgentRuntimeError("failure", `Provider did not return a corrected ${this.pendingCorrection.toolName} tool call`);
453
+ return {
454
+ type: "denied",
455
+ reason: "The correction must call the same tool with corrected arguments."
456
+ };
457
+ }
458
+ const requiresApproval = this.policies.requireApproval?.includes(input.toolName);
459
+ const matchesApproval = this.approvedToolCall !== void 0 && isSameToolCall(this.approvedToolCall, input.toolName, input.toolInput);
460
+ if (requiresApproval && !matchesApproval) {
461
+ this.pendingApproval ??= {
462
+ toolName: input.toolName,
463
+ input: input.toolInput
464
+ };
465
+ this.record({
466
+ rule: "require_approval",
467
+ decision: "approval_requested",
468
+ toolName: input.toolName,
469
+ detail: { toolCallId: input.toolCallId }
470
+ });
471
+ this.terminal ??= new AgentRuntimeError("failure", `Tool ${input.toolName} requires approval before execution`, {
472
+ code: "approval_required",
473
+ toolName: input.toolName,
474
+ pendingToolCall: this.pendingApproval
475
+ });
476
+ return {
477
+ type: "denied",
478
+ reason: "This tool call requires approval before it can run."
479
+ };
480
+ }
481
+ if (this.approvedToolCalls >= this.maxToolCallsPerInvocation) {
482
+ this.record({
483
+ rule: "max_tool_calls",
484
+ decision: "deny",
485
+ toolName: input.toolName,
486
+ detail: { maxToolCallsPerInvocation: this.maxToolCallsPerInvocation }
487
+ });
488
+ this.terminal = new AgentRuntimeError("failure", "Tool-call budget exceeded");
489
+ return {
490
+ type: "denied",
491
+ reason: "Tool-call budget exhausted."
492
+ };
493
+ }
494
+ if (requiresApproval && matchesApproval) {
495
+ this.approvedToolCall = void 0;
496
+ this.record({
497
+ rule: "require_approval",
498
+ decision: "allow",
499
+ toolName: input.toolName,
500
+ detail: { viaApproval: true }
501
+ });
502
+ }
503
+ this.approvedToolCalls += 1;
504
+ return "not-applicable";
505
+ }
506
+ afterStep(toolCalls) {
507
+ if (this.terminal) return;
508
+ if (this.pendingCorrection) {
509
+ const only = toolCalls.length === 1 ? toolCalls[0] : void 0;
510
+ if (only && !only.invalid) {
511
+ this.pendingCorrection = void 0;
512
+ return;
513
+ }
514
+ if (this.pendingCorrection.correctionsUsed < this.correctionBudget) {
515
+ const chain = this.pendingCorrection.correctionsUsed;
516
+ this.pendingCorrection = void 0;
517
+ this.handleViolation(toolCalls, chain);
518
+ return;
519
+ }
520
+ this.recordInvalidCalls(toolCalls);
521
+ this.exhaustCorrection(toolCalls);
522
+ return;
523
+ }
524
+ this.handleViolation(toolCalls, 0);
525
+ }
526
+ handleViolation(toolCalls, chainCorrections) {
527
+ this.recordInvalidCalls(toolCalls);
528
+ if (this.exactlyOne && toolCalls.length > 1) {
529
+ if (chainCorrections >= this.correctionBudget) {
530
+ this.exhaustCorrection(toolCalls);
531
+ return;
532
+ }
533
+ this.pendingCorrection = {
534
+ kind: "multi-call",
535
+ instruction: TOOL_PROPOSAL_CORRECTION,
536
+ correctionsUsed: chainCorrections + 1
537
+ };
538
+ this.record({
539
+ rule: "exactly_one",
540
+ decision: "correction_issued"
541
+ });
542
+ return;
543
+ }
544
+ const invalid = toolCalls.find((toolCall) => toolCall.invalid);
545
+ if (!invalid) return;
546
+ const correction = this.hooks.correctionForInvalidCall?.(invalid);
547
+ if (correction) {
548
+ if (chainCorrections >= this.correctionBudget) {
549
+ this.exhaustCorrection(toolCalls);
550
+ return;
551
+ }
552
+ this.pendingCorrection = {
553
+ kind: "input-validation",
554
+ instruction: correction,
555
+ toolName: invalid.toolName,
556
+ correctionsUsed: chainCorrections + 1
557
+ };
558
+ this.record({
559
+ rule: "input_validation",
560
+ decision: "correction_issued",
561
+ toolName: invalid.toolName
562
+ });
563
+ return;
564
+ }
565
+ this.terminal = new AgentRuntimeError("failure", "Provider returned invalid tool input");
566
+ }
567
+ recordInvalidCalls(toolCalls) {
568
+ for (const call of toolCalls) if (call.invalid) this.record({
569
+ rule: "input_validation",
570
+ decision: "deny",
571
+ toolName: call.toolName
572
+ });
573
+ }
574
+ exhaustCorrection(toolCalls) {
575
+ this.record({
576
+ rule: "correction_budget",
577
+ decision: "deny",
578
+ detail: { correctionBudget: this.correctionBudget }
579
+ });
580
+ this.terminal = new AgentRuntimeError("failure", toolCalls.length === 0 ? "Provider did not return a corrected tool call" : toolCalls.length > 1 ? "Provider returned multiple tool calls" : "Provider returned invalid tool input", toolCalls.length > 1 ? { code: "multiple_tool_calls" } : void 0);
581
+ }
582
+ record(decision) {
583
+ try {
584
+ this.hooks.onDecision?.(decision);
585
+ } catch {}
586
+ }
587
+ };
588
+ // src/runtime/ai-sdk-runtime.ts
589
+ const TOOL_EXECUTION_CONTRACT = [
590
+ "Tool execution contract:",
591
+ "- Propose exactly one tool call in each assistant response when tools are needed.",
592
+ "- Wait for that tool result before deciding on the next tool call.",
593
+ "- Omit optional arguments when the user or context did not provide a meaningful value.",
594
+ "- Never use empty strings as placeholders for omitted optional arguments."
595
+ ].join("\n");
596
+ function sum(values) {
597
+ return values.reduce((total, value) => total + value, 0);
598
+ }
599
+ function aggregateStepTimings(steps) {
600
+ return {
601
+ providerCallCount: steps.length,
602
+ totalProviderMs: sum(steps.map((step) => step.performance.responseTimeMs)),
603
+ totalToolMs: sum(steps.flatMap((step) => Object.values(step.performance.toolExecutionMs)))
604
+ };
605
+ }
606
+ function auditErrorCode(error) {
607
+ const code = error.diagnostics.code;
608
+ if (typeof code === "string") return code;
609
+ return error.kind === "timeout" ? "tool_call_timeout" : "tool_call_failed";
610
+ }
611
+ function normalizeProviderName(provider) {
612
+ return provider.endsWith(".chat") ? provider.slice(0, -5) : provider;
613
+ }
614
+ function findAgentRuntimeError(error) {
615
+ let current = error;
616
+ for (let depth = 0; depth < 8 && current != null; depth += 1) {
617
+ if (current instanceof AgentRuntimeError) return current;
618
+ if (!(current instanceof Error)) return void 0;
619
+ current = current.cause;
620
+ }
621
+ }
622
+ function isTimeoutFailure(error) {
623
+ let current = error;
624
+ for (let depth = 0; depth < 8 && current != null; depth += 1) {
625
+ if (current instanceof Error && ["AbortError", "TimeoutError"].includes(current.name)) return true;
626
+ if (!(current instanceof Error)) return false;
627
+ current = current.cause;
628
+ }
629
+ return false;
630
+ }
631
+ function zodObjectShape(schema) {
632
+ let current = schema;
633
+ for (let depth = 0; depth < 6 && current != null; depth += 1) {
634
+ if (current instanceof z.ZodObject) return current.shape;
635
+ const def = current._def;
636
+ current = def?.["schema"] ?? def?.["innerType"];
637
+ }
638
+ }
639
+ function dropBlankOptionalStringArguments(rawArguments, inputShape) {
640
+ if (typeof rawArguments !== "object" || rawArguments === null || Array.isArray(rawArguments)) return rawArguments;
641
+ const normalized = { ...rawArguments };
642
+ for (const [key, fieldSchema] of Object.entries(inputShape)) {
643
+ const value = normalized[key];
644
+ if (typeof value === "string" && value.trim() === "" && fieldSchema.safeParse(void 0).success && !fieldSchema.safeParse(value).success) delete normalized[key];
645
+ }
646
+ return normalized;
647
+ }
648
+ function modelMessages(history, input) {
649
+ return [...history.map((message) => ({
650
+ role: message.role,
651
+ content: message.content
652
+ })), {
653
+ role: "user",
654
+ content: input.prompt
655
+ }];
656
+ }
657
+ var AiSdkNativeRuntime = class {
658
+ options;
659
+ now;
660
+ maxDurationMs;
661
+ toolsByName;
662
+ constructor(options) {
663
+ this.options = options;
664
+ this.now = options.now ?? performance.now.bind(performance);
665
+ this.maxDurationMs = options.policies?.maxDurationMs ?? 12e4;
666
+ if (!Number.isSafeInteger(this.maxDurationMs) || this.maxDurationMs <= 0) throw new Error("maxDurationMs must be a positive integer");
667
+ this.toolsByName = new Map((options.tools ?? []).map((definition) => [definition.name, definition]));
668
+ if (this.toolsByName.size > 0 && !options.mcpClient) throw new Error("mcpClient is required when tools are registered (tools execute through MCP)");
669
+ }
670
+ async invoke(input) {
671
+ const startedAt = this.now();
672
+ const state = {
673
+ currentProposalCount: 0,
674
+ toolCallCount: 0
675
+ };
676
+ const policy = new PolicyEngine(this.options.policies ?? {}, {
677
+ onDecision: (decision) => this.options.onPolicyDecision?.({
678
+ ...decision,
679
+ scope: input.scope,
680
+ invocationId: input.invocationId,
681
+ runId: input.runId
682
+ }),
683
+ correctionForInvalidCall: (call) => this.correctionFor(call),
684
+ approvedToolCall: input.approvedToolCall
685
+ });
686
+ try {
687
+ const systemPrompt = this.options.loadSystemPrompt ? await this.options.loadSystemPrompt(input) : "";
688
+ const contextLoadedAt = this.now();
689
+ const history = this.options.loadHistory ? await this.options.loadHistory(input) : [];
690
+ const historyLoadedAt = this.now();
691
+ const baseInstructions = [systemPrompt, this.options.policies?.exactlyOneToolCallPerStep ?? true ? TOOL_EXECUTION_CONTRACT : ""].filter((part) => part.length > 0).join("\n\n");
692
+ const tools = this.createTools(input, startedAt, state, policy);
693
+ const result = await new ToolLoopAgent({
694
+ model: this.options.model,
695
+ tools,
696
+ instructions: baseInstructions,
697
+ repairToolCall: async ({ toolCall }) => this.repairBlankOptionalStrings(toolCall),
698
+ prepareStep: () => {
699
+ this.remaining(startedAt);
700
+ const correction = policy.correctionInstruction();
701
+ return { instructions: correction ? `${baseInstructions}\n\n${correction}` : baseInstructions };
702
+ },
703
+ onLanguageModelCallEnd: (event) => {
704
+ state.currentProposalCount = event.content.filter((part) => part.type === "tool-call").length;
705
+ },
706
+ toolApproval: ({ toolCall }) => policy.approvalFor({
707
+ toolName: toolCall.toolName,
708
+ toolCallId: toolCall.toolCallId,
709
+ toolInput: toolCall.input,
710
+ proposalCount: state.currentProposalCount,
711
+ scope: input.scope
712
+ }),
713
+ onStepEnd: (step) => {
714
+ policy.afterStep(step.toolCalls);
715
+ },
716
+ stopWhen: () => policy.terminalError != null
717
+ }).generate({
718
+ messages: modelMessages(history, input),
719
+ timeout: this.remaining(startedAt)
720
+ });
721
+ if (policy.terminalError) throw policy.terminalError;
722
+ const text = result.text.trim();
723
+ const provider = normalizeProviderName(result.finalStep.model.provider);
724
+ const model = result.finalStep.model.modelId;
725
+ if (!text) throw new AgentRuntimeError("failure", "Provider response contained no assistant text", {
726
+ provider,
727
+ model
728
+ });
729
+ const completedAt = this.now();
730
+ this.emitMetrics({
731
+ runId: input.runId,
732
+ contextLoadMs: contextLoadedAt - startedAt,
733
+ historyLoadMs: historyLoadedAt - contextLoadedAt,
734
+ toolCallCount: state.toolCallCount,
735
+ ...aggregateStepTimings(result.steps),
736
+ totalMs: completedAt - startedAt
737
+ });
738
+ return {
739
+ invocationId: input.invocationId,
740
+ runId: input.runId,
741
+ text,
742
+ provider,
743
+ model
744
+ };
745
+ } catch (error) {
746
+ const runtimeError = findAgentRuntimeError(error);
747
+ if (runtimeError) throw runtimeError;
748
+ if (isTimeoutFailure(error)) throw new AgentRuntimeError("timeout", "Native runtime timed out");
749
+ throw new AgentRuntimeError("failure", "Native runtime failed");
750
+ } finally {
751
+ await state.session?.then((session) => session.close()).catch(() => void 0);
752
+ }
753
+ }
754
+ createTools(input, startedAt, state, policy) {
755
+ return Object.fromEntries([...this.toolsByName.values()].map((definition) => {
756
+ const name = definition.name;
757
+ return [name, tool({
758
+ description: definition.description,
759
+ inputSchema: definition.inputSchema,
760
+ execute: async (arguments_, options) => {
761
+ const audit = {
762
+ dispatchId: randomUUID(),
763
+ scope: input.scope,
764
+ invocationId: input.invocationId,
765
+ runId: input.runId,
766
+ toolName: name,
767
+ toolCallId: options.toolCallId,
768
+ idempotencyKey: deriveToolCallIdempotencyKey(input.invocationId, name, arguments_),
769
+ input: arguments_
770
+ };
771
+ try {
772
+ await this.emitToolCallAudit({
773
+ ...audit,
774
+ phase: "started"
775
+ });
776
+ } catch (error) {
777
+ policy.fail(findAgentRuntimeError(error) ?? new AgentRuntimeError("failure", "Tool call audit failed"));
778
+ throw error;
779
+ }
780
+ let result;
781
+ try {
782
+ state.session ??= this.options.mcpClient.open({
783
+ runId: input.runId,
784
+ timeoutMs: this.remaining(startedAt)
785
+ });
786
+ const session = await state.session;
787
+ state.toolCallCount += 1;
788
+ result = await session.callTool({
789
+ name,
790
+ arguments: arguments_,
791
+ timeoutMs: this.remaining(startedAt),
792
+ idempotencyKey: audit.idempotencyKey
793
+ });
794
+ } catch (error) {
795
+ const agentError = findAgentRuntimeError(error) ?? new AgentRuntimeError("failure", "MCP tool call failed");
796
+ policy.fail(agentError);
797
+ try {
798
+ await this.emitToolCallAudit({
799
+ ...audit,
800
+ phase: "failed",
801
+ errorCode: auditErrorCode(agentError)
802
+ });
803
+ } catch (auditError) {
804
+ policy.fail(findAgentRuntimeError(auditError) ?? agentError);
805
+ throw auditError;
806
+ }
807
+ throw error;
808
+ }
809
+ try {
810
+ await this.emitToolCallAudit({
811
+ ...audit,
812
+ phase: "succeeded"
813
+ });
814
+ } catch (error) {
815
+ policy.fail(findAgentRuntimeError(error) ?? new AgentRuntimeError("failure", "Tool call audit failed"));
816
+ throw error;
817
+ }
818
+ return result;
819
+ }
820
+ })];
821
+ }));
822
+ }
823
+ async emitToolCallAudit(event) {
824
+ if (!this.options.onToolCallAudit) return;
825
+ try {
826
+ await this.options.onToolCallAudit(event);
827
+ } catch (error) {
828
+ throw new AgentRuntimeError("failure", "Tool call audit persistence failed", { code: "audit_persistence_failed" }, { cause: error });
829
+ }
830
+ }
831
+ correctionFor(call) {
832
+ const definition = this.toolsByName.get(call.toolName);
833
+ if (!definition?.validateInput) return void 0;
834
+ const shape = zodObjectShape(definition.inputSchema);
835
+ const normalized = shape ? dropBlankOptionalStringArguments(call.input, shape) : call.input;
836
+ const verdict = definition.validateInput(normalized);
837
+ return verdict.ok ? void 0 : verdict.correction;
838
+ }
839
+ repairBlankOptionalStrings(toolCall) {
840
+ const definition = this.toolsByName.get(toolCall.toolName);
841
+ if (!definition) return null;
842
+ const shape = zodObjectShape(definition.inputSchema);
843
+ if (!shape) return null;
844
+ let parsed;
845
+ try {
846
+ parsed = JSON.parse(toolCall.input);
847
+ } catch {
848
+ return null;
849
+ }
850
+ const normalized = dropBlankOptionalStringArguments(parsed, shape);
851
+ if (JSON.stringify(normalized) === JSON.stringify(parsed)) return null;
852
+ return {
853
+ type: "tool-call",
854
+ toolCallType: "function",
855
+ toolCallId: toolCall.toolCallId,
856
+ toolName: toolCall.toolName,
857
+ input: JSON.stringify(normalized)
858
+ };
859
+ }
860
+ remaining(startedAt) {
861
+ const remaining = this.maxDurationMs - (this.now() - startedAt);
862
+ if (remaining <= 0) throw new AgentRuntimeError("timeout", "Native runtime timed out");
863
+ return Math.max(1, Math.floor(remaining));
864
+ }
865
+ emitMetrics(metrics) {
866
+ try {
867
+ this.options.onMetrics?.(metrics);
868
+ } catch {}
869
+ }
870
+ };
871
+ // src/runtime/model.ts
872
+ function required(value, name) {
873
+ if (!value.trim()) throw new Error(`${name} is required`);
874
+ return value;
875
+ }
876
+ function withProviderTimeout(fetchImpl, timeoutMs) {
877
+ return async (input, init) => {
878
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
879
+ const signal = init?.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
880
+ return fetchImpl(input, {
881
+ ...init,
882
+ signal
883
+ });
884
+ };
885
+ }
886
+ function openAiCompatible(config, fetchImpl = fetch) {
887
+ const baseUrl = required(config.baseUrl, "baseUrl");
888
+ const apiKey = required(config.apiKey, "apiKey");
889
+ const model = required(config.model, "model");
890
+ const timeoutMs = config.timeoutMs ?? 3e4;
891
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive integer");
892
+ const endpoint = new URL(baseUrl);
893
+ if (!["http:", "https:"].includes(endpoint.protocol)) throw new Error("baseUrl must use http or https");
894
+ return createOpenAICompatible({
895
+ name: "openai-compatible",
896
+ baseURL: baseUrl,
897
+ apiKey,
898
+ fetch: withProviderTimeout(fetchImpl, timeoutMs),
899
+ transformRequestBody: (body) => Array.isArray(body.tools) ? {
900
+ ...body,
901
+ parallel_tool_calls: false
902
+ } : body
903
+ }).chatModel(model);
904
+ }
905
+ // src/define-runtime.ts
906
+ const RUNTIME_INTERNALS = Symbol("runwarden/internals");
907
+ function buildMcpClient(servers, policies) {
908
+ if (!servers || servers.length === 0) return void 0;
909
+ const clients = servers.map((server) => new NativeMcpClient({
910
+ endpoint: server.url,
911
+ headers: server.headers,
912
+ maxResultBytes: policies?.maxToolResultBytes
913
+ }));
914
+ if (clients.length === 1) return clients[0];
915
+ return new RoutingMcpClient(clients, servers);
916
+ }
917
+ var RoutingMcpClient = class {
918
+ clients;
919
+ servers;
920
+ constructor(clients, servers) {
921
+ this.clients = clients;
922
+ this.servers = servers;
923
+ }
924
+ async open(input) {
925
+ const opened = await Promise.allSettled(this.clients.map((client) => client.open(input)));
926
+ const sessions = opened.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
927
+ const failure = opened.find((result) => result.status === "rejected");
928
+ if (failure) {
929
+ await Promise.allSettled(sessions.map((session) => session.close()));
930
+ throw failure.reason;
931
+ }
932
+ const route = (toolName) => {
933
+ const index = this.servers.findIndex((server) => server.tools?.includes(toolName));
934
+ return sessions[index >= 0 ? index : 0];
935
+ };
936
+ return {
937
+ callTool: (call) => route(call.name).callTool(call),
938
+ close: async () => {
939
+ await Promise.allSettled(sessions.map((session) => session.close()));
940
+ }
941
+ };
942
+ }
943
+ };
944
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
945
+ function dbRequired(operation) {
946
+ return new AgentRuntimeError("failure", `${operation} requires a database: pass createDb() as defineRuntime({ db })`, { code: "db_required" });
947
+ }
948
+ function defineRuntime(options) {
949
+ const model = options.model ?? (options.provider ? openAiCompatible(options.provider) : void 0);
950
+ if (!model) throw new Error("defineRuntime requires either `model` or `provider`");
951
+ const mcpClient = options.mcpClient ?? buildMcpClient(options.mcpServers, options.policies);
952
+ const decisionListeners = /* @__PURE__ */ new Set();
953
+ const auditListeners = /* @__PURE__ */ new Set();
954
+ const engine = new AiSdkNativeRuntime({
955
+ model,
956
+ tools: options.tools,
957
+ mcpClient,
958
+ loadSystemPrompt: options.loadSystemPrompt,
959
+ loadHistory: options.loadHistory,
960
+ policies: options.policies,
961
+ onMetrics: options.onMetrics,
962
+ onPolicyDecision: (decision) => {
963
+ for (const listener of decisionListeners) listener(decision);
964
+ options.onPolicyDecision?.(decision);
965
+ },
966
+ onToolCallAudit: async (event) => {
967
+ for (const listener of auditListeners) await listener(event);
968
+ try {
969
+ await options.onToolCallAudit?.(event);
970
+ } catch {}
971
+ }
972
+ });
973
+ const db = options.db;
974
+ async function waitForInvocation(invocationId, opts) {
975
+ if (!db) throw dbRequired("waitForInvocation");
976
+ const deadline = Date.now() + (opts?.waitTimeoutMs ?? 3e5);
977
+ const pollIntervalMs = opts?.pollIntervalMs ?? 250;
978
+ for (;;) {
979
+ const row = await getInvocationRowById(db.db, invocationId);
980
+ if (!row) throw new AgentRuntimeError("failure", `Invocation ${invocationId} was not found`, {
981
+ code: "invocation_not_found",
982
+ invocationId
983
+ });
984
+ if (row.status === "succeeded") return {
985
+ invocationId,
986
+ runId: row.activeRunId,
987
+ text: row.resultText ?? "",
988
+ provider: row.provider ?? void 0,
989
+ model: row.model ?? void 0
990
+ };
991
+ if (row.status === "awaiting_approval") {
992
+ const pending = toPendingToolCall(row.pendingToolCall);
993
+ throw new AgentRuntimeError("failure", `Invocation ${invocationId} is awaiting approval`, {
994
+ code: "approval_required",
995
+ invocationId,
996
+ ...pending ? { toolName: pending.toolName } : {}
997
+ });
998
+ }
999
+ if (row.status === "failed" || row.status === "cancelled") throw new AgentRuntimeError("failure", row.lastErrorMessage ?? `Invocation ${row.status}`, {
1000
+ code: row.lastErrorCode ?? `invocation_${row.status}`,
1001
+ invocationId
1002
+ });
1003
+ if (Date.now() >= deadline) throw new AgentRuntimeError("timeout", `Timed out waiting for invocation ${invocationId}`, { invocationId });
1004
+ await sleep$1(pollIntervalMs);
1005
+ }
1006
+ }
1007
+ async function durableInvoke(input, opts) {
1008
+ const { invocationId } = await enqueueInvocation(db.db, input);
1009
+ return waitForInvocation(invocationId, opts);
1010
+ }
1011
+ async function resolveApproval(id, resolution, opts) {
1012
+ if (!db) throw dbRequired(`${resolution} resolution`);
1013
+ const result = await resolveInvocationApproval(db.db, id, resolution, opts);
1014
+ if (result.outcome === "not_found") throw new AgentRuntimeError("failure", `Invocation ${id} was not found`, {
1015
+ code: "invocation_not_found",
1016
+ invocationId: id
1017
+ });
1018
+ if (result.outcome === "not_awaiting") throw new AgentRuntimeError("failure", `Invocation ${id} is not awaiting approval`, {
1019
+ code: "invocation_not_awaiting_approval",
1020
+ invocationId: id
1021
+ });
1022
+ return toRecord(result.row);
1023
+ }
1024
+ return {
1025
+ engine,
1026
+ invoke: db ? durableInvoke : (input) => engine.invoke({
1027
+ ...input,
1028
+ invocationId: randomUUID(),
1029
+ runId: randomUUID()
1030
+ }),
1031
+ enqueue: async (input) => {
1032
+ if (!db) throw dbRequired("enqueue");
1033
+ return enqueueInvocation(db.db, input);
1034
+ },
1035
+ getInvocation: async (id) => {
1036
+ if (!db) throw dbRequired("getInvocation");
1037
+ const row = await getInvocationRowById(db.db, id);
1038
+ return row ? toRecord(row) : void 0;
1039
+ },
1040
+ waitForInvocation,
1041
+ listPendingApprovals: async (scope) => {
1042
+ if (!db) throw dbRequired("listPendingApprovals");
1043
+ return (await listAwaitingApprovalRows(db.db, scope)).map(toRecord);
1044
+ },
1045
+ approveInvocation: (id, opts) => resolveApproval(id, "approved", opts),
1046
+ rejectInvocation: (id, opts) => resolveApproval(id, "rejected", opts),
1047
+ [RUNTIME_INTERNALS]: {
1048
+ onPolicyDecision: (listener) => {
1049
+ decisionListeners.add(listener);
1050
+ return () => {
1051
+ decisionListeners.delete(listener);
1052
+ };
1053
+ },
1054
+ onToolCallAudit: (listener) => {
1055
+ auditListeners.add(listener);
1056
+ return () => {
1057
+ auditListeners.delete(listener);
1058
+ };
1059
+ }
1060
+ }
1061
+ };
1062
+ }
1063
+ // src/db/repositories/decisions.ts
1064
+ async function insertPolicyDecision(db, decision) {
1065
+ await db.insert(policyDecisions).values({
1066
+ scope: decision.scope,
1067
+ invocationId: Number(decision.invocationId),
1068
+ runId: decision.runId,
1069
+ toolName: decision.toolName ?? null,
1070
+ rule: decision.rule,
1071
+ decision: decision.decision,
1072
+ detail: decision.detail ?? null
1073
+ });
1074
+ }
1075
+ // src/db/repositories/tool-call-audits.ts
1076
+ async function claimToolCallAudit(db, claim) {
1077
+ const first = (await db.execute(sql`
1078
+ insert into agent_runtime.tool_call_audits
1079
+ (invocation_id, scope, run_id, tool_name, idempotency_key, status,
1080
+ requested_at, request_snapshot, metadata)
1081
+ values (
1082
+ ${claim.invocationId},
1083
+ ${claim.scope},
1084
+ ${claim.runId},
1085
+ ${claim.toolName},
1086
+ ${claim.idempotencyKey},
1087
+ 'started',
1088
+ now(),
1089
+ ${JSON.stringify(claim.requestSnapshot)}::jsonb,
1090
+ ${JSON.stringify({
1091
+ ...claim.metadata,
1092
+ dispatchId: claim.dispatchId
1093
+ })}::jsonb
1094
+ )
1095
+ on conflict (scope, tool_name, idempotency_key)
1096
+ where idempotency_key is not null
1097
+ do update set status = 'started',
1098
+ requested_at = now(),
1099
+ completed_at = null,
1100
+ error_code = null,
1101
+ run_id = excluded.run_id,
1102
+ request_snapshot = excluded.request_snapshot,
1103
+ metadata = excluded.metadata
1104
+ returning id
1105
+ `)).rows[0];
1106
+ if (!first) throw new Error("tool call audit claim inserted no row");
1107
+ return Number(first.id);
1108
+ }
1109
+ async function completeToolCallAudit(db, id, status, errorCode, runId, dispatchId) {
1110
+ return (await db.execute(sql`
1111
+ update agent_runtime.tool_call_audits
1112
+ set status = ${status},
1113
+ completed_at = now(),
1114
+ error_code = ${errorCode ?? null}
1115
+ where id = ${id} and status = 'started'
1116
+ and run_id = ${runId}
1117
+ and metadata->>'dispatchId' = ${dispatchId}
1118
+ returning id
1119
+ `)).rows.length > 0;
1120
+ }
1121
+ // src/worker/run-worker.ts
1122
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1123
+ function toAgentError(error) {
1124
+ if (error instanceof AgentRuntimeError) return error;
1125
+ return new AgentRuntimeError("failure", error instanceof Error ? error.message : String(error), { code: "execution_failed" }, error instanceof Error ? { cause: error } : {});
1126
+ }
1127
+ function errorCode(error) {
1128
+ const code = error.diagnostics.code;
1129
+ return typeof code === "string" ? code : "execution_failed";
1130
+ }
1131
+ function pendingFromError(error) {
1132
+ const pending = toPendingToolCall(error.diagnostics.pendingToolCall);
1133
+ if (pending) return pending;
1134
+ const toolName = error.diagnostics.toolName;
1135
+ return {
1136
+ toolName: typeof toolName === "string" ? toolName : "unknown",
1137
+ input: void 0
1138
+ };
1139
+ }
1140
+ function runWorker(options) {
1141
+ const workerId = options.workerId ?? `${hostname()}:${process.pid}:${randomUUID()}`;
1142
+ const leaseTimeoutMs = options.leaseTimeoutMs ?? 12e4;
1143
+ const heartbeatIntervalMs = options.heartbeatIntervalMs ?? 3e4;
1144
+ const retryDelayMs = options.retryDelayMs ?? 6e4;
1145
+ const pollIdleMs = options.pollIdleMs ?? 500;
1146
+ const pollActiveMs = options.pollActiveMs ?? 250;
1147
+ const db = options.db.db;
1148
+ const internals = options.runtime[RUNTIME_INTERNALS];
1149
+ let stopped = false;
1150
+ async function executeOne(row) {
1151
+ const record = toRecord(row);
1152
+ const auditWrites = [];
1153
+ let auditError;
1154
+ const unsubscribe = internals?.onPolicyDecision((decision) => {
1155
+ if (decision.invocationId !== String(row.id) || decision.runId !== row.activeRunId) return;
1156
+ auditWrites.push(insertPolicyDecision(db, decision).catch((error) => {
1157
+ auditError = error;
1158
+ }));
1159
+ });
1160
+ const auditIds = /* @__PURE__ */ new Map();
1161
+ const unsubscribeAudit = internals?.onToolCallAudit?.(async (event) => {
1162
+ if (event.invocationId !== String(row.id) || event.runId !== row.activeRunId) return;
1163
+ if (event.phase === "started") {
1164
+ const auditId = await claimToolCallAudit(db, {
1165
+ invocationId: event.invocationId,
1166
+ scope: event.scope,
1167
+ runId: event.runId,
1168
+ dispatchId: event.dispatchId,
1169
+ toolName: event.toolName,
1170
+ idempotencyKey: event.idempotencyKey,
1171
+ requestSnapshot: event.input ?? null,
1172
+ metadata: event.toolCallId ? { toolCallId: event.toolCallId } : void 0
1173
+ });
1174
+ auditIds.set(event.dispatchId, auditId);
1175
+ return;
1176
+ }
1177
+ const auditId = auditIds.get(event.dispatchId);
1178
+ if (auditId === void 0) throw new Error("Tool audit completion has no started event");
1179
+ if (!await completeToolCallAudit(db, auditId, event.phase, event.errorCode, event.runId, event.dispatchId)) throw new Error("Tool audit completion lost its dispatch claim");
1180
+ auditIds.delete(event.dispatchId);
1181
+ });
1182
+ let leaseLost = false;
1183
+ const heartbeat = setInterval(() => {
1184
+ heartbeatInvocation(db, row.id, workerId, row.activeRunId, leaseTimeoutMs).then((ok) => {
1185
+ if (!ok) leaseLost = true;
1186
+ }).catch(() => void 0);
1187
+ }, heartbeatIntervalMs);
1188
+ heartbeat.unref?.();
1189
+ try {
1190
+ let result;
1191
+ try {
1192
+ result = await options.runtime.engine.invoke({
1193
+ ...row.input,
1194
+ invocationId: String(row.id),
1195
+ runId: row.activeRunId,
1196
+ approvedToolCall: toPendingToolCall(row.pendingToolCall)
1197
+ });
1198
+ } finally {
1199
+ unsubscribe?.();
1200
+ unsubscribeAudit?.();
1201
+ await Promise.all(auditWrites);
1202
+ if (auditError) throw new AgentRuntimeError("failure", "Policy audit persistence failed", { code: "audit_persistence_failed" }, { cause: auditError });
1203
+ }
1204
+ if (leaseLost) return;
1205
+ if (await markInvocationSucceeded(db, row.id, workerId, row.activeRunId, {
1206
+ resultText: result.text,
1207
+ provider: result.provider,
1208
+ model: result.model
1209
+ })) await options.onSucceeded?.({
1210
+ ...record,
1211
+ status: "succeeded",
1212
+ resultText: result.text
1213
+ }, result);
1214
+ } catch (error) {
1215
+ if (leaseLost) return;
1216
+ const agentError = toAgentError(error);
1217
+ if (errorCode(agentError) === "approval_required") {
1218
+ const pendingToolCall = pendingFromError(agentError);
1219
+ const parked = await markInvocationAwaitingApproval(db, row.id, workerId, row.activeRunId, pendingToolCall);
1220
+ if (parked) await options.onAwaitingApproval?.(toRecord(parked), pendingToolCall);
1221
+ return;
1222
+ }
1223
+ const updated = await markInvocationFailed(db, row.id, workerId, row.activeRunId, {
1224
+ code: errorCode(agentError),
1225
+ message: agentError.message
1226
+ }, retryDelayMs);
1227
+ if (updated?.status === "failed") await options.onFailed?.(toRecord(updated), agentError);
1228
+ } finally {
1229
+ clearInterval(heartbeat);
1230
+ }
1231
+ }
1232
+ const loop = (async () => {
1233
+ while (!stopped) {
1234
+ let claimed = [];
1235
+ try {
1236
+ claimed = await claimInvocations(db, workerId, {
1237
+ leaseTimeoutMs,
1238
+ maxBatchSize: 1
1239
+ });
1240
+ } catch {
1241
+ await sleep(pollIdleMs);
1242
+ continue;
1243
+ }
1244
+ if (claimed.length === 0) {
1245
+ await sleep(pollIdleMs);
1246
+ continue;
1247
+ }
1248
+ for (const row of claimed) {
1249
+ if (stopped) break;
1250
+ await executeOne(row);
1251
+ }
1252
+ await sleep(pollActiveMs);
1253
+ }
1254
+ })();
1255
+ return { async stop() {
1256
+ stopped = true;
1257
+ await loop;
1258
+ } };
1259
+ }
1260
+ // src/fake-runtime.ts
1261
+ var FakeAgentRuntime = class {
1262
+ result;
1263
+ invocations = [];
1264
+ constructor(result) {
1265
+ this.result = result;
1266
+ }
1267
+ getInvocationHistory() {
1268
+ return [...this.invocations];
1269
+ }
1270
+ async invoke(input) {
1271
+ const invocationIndex = this.invocations.push(input);
1272
+ if (typeof this.result === "function") return this.result(input, invocationIndex);
1273
+ return this.result ?? {
1274
+ invocationId: input.invocationId,
1275
+ runId: input.runId,
1276
+ text: `Fake runtime response to: ${input.prompt}`,
1277
+ provider: "fake",
1278
+ model: "fake-agent-runtime"
1279
+ };
1280
+ }
1281
+ };
1282
+ export { AgentRuntimeError, ERROR_CATEGORY_META_KEY, FakeAgentRuntime, NativeMcpClient, RUNTIME_NAME, RUN_ID_HEADER, createDb, defineRuntime, initDb, openAiCompatible, runWorker };