runwarden 0.2.0 → 0.3.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/README.md CHANGED
@@ -344,6 +344,33 @@ The end of a quickstart run prints that trail. A typical run:
344
344
  tool_call_audit invocation=<id> tool=billing__refund status=succeeded idempotency_key=<prefix>...
345
345
  ```
346
346
 
347
+ ## Run IDs
348
+
349
+ Every attempt of an invocation carries a run ID. It fences the attempt's
350
+ lease, travels to MCP servers as the `X-Runwarden-Run-Id` header, and is
351
+ stamped on policy decisions and tool call audits, so your own logs and
352
+ systems can correlate with Runwarden's records.
353
+
354
+ Who generates it depends on how the invocation runs:
355
+
356
+ - **Direct execution** (`invoke()` on a runtime without a database):
357
+ pass `runId` in the invocation input to use your own ID verbatim. This
358
+ is the seam for hosts that register their own run IDs, such as a
359
+ worker that resolves each attempt in its own tables. When omitted, a
360
+ random UUID is generated per invocation.
361
+ - **Durable execution** (a database plus `runWorker`): attempts are
362
+ fenced, so every attempt needs a fresh ID and a caller-supplied `runId`
363
+ is rejected instead of being silently ignored. To control the format,
364
+ pass `generateRunId` to `defineRuntime`; the worker calls it each time
365
+ it goes to claim work and uses the returned value for the attempt it
366
+ takes (a claim that finds no work discards the value unused, so the
367
+ factory must be cheap and safe to call often). The worker checks that
368
+ each value is a UUID (the run ID is stored in a Postgres `uuid`
369
+ column) and fails loudly on anything else. Returning a unique value
370
+ on every call is the factory's contract: a duplicate that is still in
371
+ use violates the unique index on active run IDs and fails that claim,
372
+ and attempt fencing assumes run IDs are never reused.
373
+
347
374
  ## Limitations
348
375
 
349
376
  - **Not for massive throughput:** Runwarden targets indie and solo scale:
package/dist/index.d.ts CHANGED
@@ -48,6 +48,7 @@ export declare class AgentRuntimeError extends Error {
48
48
  interface InvocationInput {
49
49
  scope: string;
50
50
  prompt: string;
51
+ runId?: string;
51
52
  conversationId?: string;
52
53
  orderingKey?: string;
53
54
  context?: Record<string, unknown>;
@@ -1141,6 +1142,7 @@ interface RuntimeInternals {
1141
1142
  onPolicyDecision(listener: (decision: PolicyDecision) => void): () => void;
1142
1143
  onToolCallAudit?: (listener: (event: ToolCallAuditEvent) => Promise<void>) => () => void;
1143
1144
  notifyInvocationSettled?: (invocation: InvocationRecord) => Promise<void>;
1145
+ generateRunId?: () => string;
1144
1146
  }
1145
1147
  interface DefineRuntimeOptions {
1146
1148
  db?: DatabaseHandle;
@@ -1156,6 +1158,7 @@ interface DefineRuntimeOptions {
1156
1158
  onPolicyDecision?: (decision: PolicyDecision) => void;
1157
1159
  onToolCallAudit?: ToolCallAuditSink;
1158
1160
  onInvocationSettled?: InvocationSettledListener;
1161
+ generateRunId?: () => string;
1159
1162
  }
1160
1163
  interface InvokeOptions {
1161
1164
  waitTimeoutMs?: number;
package/dist/index.js CHANGED
@@ -112,6 +112,7 @@ async function getInvocationRowById(db, id) {
112
112
  return raw ? mapRow(raw) : void 0;
113
113
  }
114
114
  async function claimInvocations(db, workerId, options) {
115
+ if (options.runId !== void 0 && options.maxBatchSize !== 1) throw new Error("ClaimOptions.runId requires maxBatchSize of 1: a single runId cannot identify multiple attempts");
115
116
  const result = await db.execute(sql`
116
117
  with exhausted as (
117
118
  update agent_runtime.invocations
@@ -160,7 +161,7 @@ async function claimInvocations(db, workerId, options) {
160
161
  lease_heartbeat_at = now(),
161
162
  lease_expires_at = now() + (${options.leaseTimeoutMs} * interval '1 millisecond'),
162
163
  started_at = coalesce(inv.started_at, now()),
163
- active_run_id = gen_random_uuid(),
164
+ active_run_id = coalesce(${options.runId ?? null}::uuid, gen_random_uuid()),
164
165
  active_run_registered_at = now(),
165
166
  updated_at = now()
166
167
  from candidate
@@ -957,6 +958,9 @@ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
957
958
  function dbRequired(operation) {
958
959
  return new AgentRuntimeError("failure", `${operation} requires a database: pass createDb() as defineRuntime({ db })`, { code: "db_required" });
959
960
  }
961
+ function callerRunIdRejected() {
962
+ return new AgentRuntimeError("failure", "InvocationInput.runId is only honored for direct execution without a database. Durable invocations mint a fresh runId per attempt; use defineRuntime({ generateRunId }) to control how those runIds are generated.", { code: "caller_run_id_in_durable_mode" });
963
+ }
960
964
  function defineRuntime(options) {
961
965
  const model = options.model ?? (options.provider ? openAiCompatible(options.provider) : void 0);
962
966
  if (!model) throw new Error("defineRuntime requires either `model` or `provider`");
@@ -1022,6 +1026,7 @@ function defineRuntime(options) {
1022
1026
  }
1023
1027
  }
1024
1028
  async function durableInvoke(input, opts) {
1029
+ if (input.runId !== void 0) throw callerRunIdRejected();
1025
1030
  const { invocationId } = await enqueueInvocation(db.db, input);
1026
1031
  return waitForInvocation(invocationId, opts);
1027
1032
  }
@@ -1045,10 +1050,11 @@ function defineRuntime(options) {
1045
1050
  invoke: db ? durableInvoke : (input) => engine.invoke({
1046
1051
  ...input,
1047
1052
  invocationId: randomUUID(),
1048
- runId: randomUUID()
1053
+ runId: input.runId ?? randomUUID()
1049
1054
  }),
1050
1055
  enqueue: async (input) => {
1051
1056
  if (!db) throw dbRequired("enqueue");
1057
+ if (input.runId !== void 0) throw callerRunIdRejected();
1052
1058
  return enqueueInvocation(db.db, input);
1053
1059
  },
1054
1060
  getInvocation: async (id) => {
@@ -1076,7 +1082,8 @@ function defineRuntime(options) {
1076
1082
  auditListeners.delete(listener);
1077
1083
  };
1078
1084
  },
1079
- notifyInvocationSettled
1085
+ notifyInvocationSettled,
1086
+ generateRunId: options.generateRunId
1080
1087
  }
1081
1088
  };
1082
1089
  }
@@ -1278,12 +1285,18 @@ function runWorker(options) {
1278
1285
  }
1279
1286
  const loop = (async () => {
1280
1287
  while (!stopped) {
1288
+ let claimRunId;
1289
+ if (internals?.generateRunId) {
1290
+ claimRunId = internals.generateRunId();
1291
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(claimRunId)) throw new Error(`generateRunId must return a UUID string, got: ${claimRunId}`);
1292
+ }
1281
1293
  let claimed = [];
1282
1294
  try {
1283
1295
  try {
1284
1296
  const result = await claimInvocations(db, workerId, {
1285
1297
  leaseTimeoutMs,
1286
- maxBatchSize: 1
1298
+ maxBatchSize: 1,
1299
+ runId: claimRunId
1287
1300
  });
1288
1301
  claimed = result.claimed.map((row) => ({
1289
1302
  row,
@@ -1306,6 +1319,7 @@ function runWorker(options) {
1306
1319
  await sleep(claimed.length === 0 ? pollIdleMs : pollActiveMs);
1307
1320
  }
1308
1321
  })();
1322
+ loop.catch(() => {});
1309
1323
  return { async stop() {
1310
1324
  stopped = true;
1311
1325
  await loop;
package/package.json CHANGED
@@ -90,7 +90,7 @@
90
90
  "url": "git+https://github.com/happyeric77/runwarden.git"
91
91
  },
92
92
  "scripts": {
93
- "build": "tsdown",
93
+ "build": "tsdown --config-loader tsx",
94
94
  "demo": "tsx examples/governed-invocation.ts",
95
95
  "format": "prettier --write '**/*.{ts,json,md}'",
96
96
  "format:check": "prettier --check '**/*.{ts,json,md}'",
@@ -103,5 +103,5 @@
103
103
  "sideEffects": false,
104
104
  "type": "module",
105
105
  "types": "./dist/index.d.ts",
106
- "version": "0.2.0"
106
+ "version": "0.3.0"
107
107
  }