runwarden 0.0.0-stage → 0.2.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.
@@ -0,0 +1,242 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { createHash } from "node:crypto";
3
+ import { sql } from "drizzle-orm";
4
+ import { drizzle } from "drizzle-orm/node-postgres";
5
+ import { Pool } from "pg";
6
+ import { bigint, index, integer, jsonb, pgSchema, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
7
+ import { readFile, readdir } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ // src/db/schema.ts
11
+ var schema_exports = /* @__PURE__ */ __exportAll({
12
+ invocationStatusEnum: () => invocationStatusEnum,
13
+ invocations: () => invocations,
14
+ policyDecisions: () => policyDecisions,
15
+ runtimeSchema: () => runtimeSchema,
16
+ toolCallAudits: () => toolCallAudits,
17
+ toolCallStatusEnum: () => toolCallStatusEnum,
18
+ workerLeases: () => workerLeases
19
+ });
20
+ const runtimeSchema = pgSchema("agent_runtime");
21
+ const invocationStatusEnum = runtimeSchema.enum("invocation_status", [
22
+ "pending",
23
+ "running",
24
+ "awaiting_approval",
25
+ "succeeded",
26
+ "failed",
27
+ "cancelled"
28
+ ]);
29
+ const toolCallStatusEnum = runtimeSchema.enum("tool_call_status", [
30
+ "started",
31
+ "succeeded",
32
+ "failed"
33
+ ]);
34
+ const createdAtColumn = () => timestamp("created_at", {
35
+ withTimezone: true,
36
+ mode: "date"
37
+ }).notNull().defaultNow();
38
+ const timestamps = () => ({
39
+ createdAt: createdAtColumn(),
40
+ updatedAt: timestamp("updated_at", {
41
+ withTimezone: true,
42
+ mode: "date"
43
+ }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
44
+ });
45
+ const invocations = runtimeSchema.table("invocations", {
46
+ id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
47
+ scope: text("scope").notNull(),
48
+ conversationId: text("conversation_id"),
49
+ orderingKey: text("ordering_key"),
50
+ input: jsonb("input").$type().notNull(),
51
+ resultText: text("result_text"),
52
+ idempotencyKey: text("idempotency_key"),
53
+ status: invocationStatusEnum("status").notNull().default("pending").$type(),
54
+ attemptCount: integer("attempt_count").notNull().default(0),
55
+ maxAttempts: integer("max_attempts").notNull().default(3),
56
+ nextAttemptAt: timestamp("next_attempt_at", {
57
+ withTimezone: true,
58
+ mode: "date"
59
+ }).notNull().defaultNow(),
60
+ claimedAt: timestamp("claimed_at", {
61
+ withTimezone: true,
62
+ mode: "date"
63
+ }),
64
+ claimedBy: text("claimed_by"),
65
+ leaseHeartbeatAt: timestamp("lease_heartbeat_at", {
66
+ withTimezone: true,
67
+ mode: "date"
68
+ }),
69
+ leaseExpiresAt: timestamp("lease_expires_at", {
70
+ withTimezone: true,
71
+ mode: "date"
72
+ }),
73
+ activeRunId: uuid("active_run_id"),
74
+ activeRunRegisteredAt: timestamp("active_run_registered_at", {
75
+ withTimezone: true,
76
+ mode: "date"
77
+ }),
78
+ pendingToolCall: jsonb("pending_tool_call"),
79
+ startedAt: timestamp("started_at", {
80
+ withTimezone: true,
81
+ mode: "date"
82
+ }),
83
+ completedAt: timestamp("completed_at", {
84
+ withTimezone: true,
85
+ mode: "date"
86
+ }),
87
+ failedAt: timestamp("failed_at", {
88
+ withTimezone: true,
89
+ mode: "date"
90
+ }),
91
+ provider: text("provider"),
92
+ model: text("model"),
93
+ lastErrorCode: text("last_error_code"),
94
+ lastErrorMessage: text("last_error_message"),
95
+ metadata: jsonb("metadata").$type(),
96
+ ...timestamps()
97
+ }, (table) => [
98
+ uniqueIndex("invocations_scope_idempotency_key_unique").on(table.scope, table.idempotencyKey).where(sql`${table.idempotencyKey} is not null`),
99
+ uniqueIndex("invocations_active_run_id_unique").on(table.activeRunId).where(sql`${table.activeRunId} is not null`),
100
+ index("invocations_status_next_attempt_idx").on(table.status, table.nextAttemptAt),
101
+ index("invocations_status_lease_expires_idx").on(table.status, table.leaseExpiresAt),
102
+ index("invocations_scope_status_next_attempt_idx").on(table.scope, table.status, table.nextAttemptAt),
103
+ index("invocations_scope_created_idx").on(table.scope, table.createdAt)
104
+ ]);
105
+ const toolCallAudits = runtimeSchema.table("tool_call_audits", {
106
+ id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
107
+ invocationId: bigint("invocation_id", { mode: "number" }).notNull().references(() => invocations.id),
108
+ scope: text("scope").notNull(),
109
+ runId: uuid("run_id"),
110
+ toolName: text("tool_name").notNull(),
111
+ idempotencyKey: text("idempotency_key"),
112
+ status: toolCallStatusEnum("status").notNull(),
113
+ requestedAt: timestamp("requested_at", {
114
+ withTimezone: true,
115
+ mode: "date"
116
+ }).notNull().defaultNow(),
117
+ completedAt: timestamp("completed_at", {
118
+ withTimezone: true,
119
+ mode: "date"
120
+ }),
121
+ errorCode: text("error_code"),
122
+ requestSnapshot: jsonb("request_snapshot"),
123
+ metadata: jsonb("metadata").$type(),
124
+ createdAt: createdAtColumn()
125
+ }, (table) => [
126
+ uniqueIndex("tool_call_audits_scope_tool_idempotency_unique").on(table.scope, table.toolName, table.idempotencyKey).where(sql`${table.idempotencyKey} is not null`),
127
+ index("tool_call_audits_invocation_idx").on(table.invocationId),
128
+ index("tool_call_audits_run_idx").on(table.runId)
129
+ ]);
130
+ const policyDecisions = runtimeSchema.table("policy_decisions", {
131
+ id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
132
+ scope: text("scope").notNull(),
133
+ invocationId: bigint("invocation_id", { mode: "number" }).notNull().references(() => invocations.id),
134
+ runId: uuid("run_id").notNull(),
135
+ toolName: text("tool_name"),
136
+ rule: text("rule").$type().notNull(),
137
+ decision: text("decision").$type().notNull(),
138
+ detail: jsonb("detail").$type(),
139
+ createdAt: createdAtColumn()
140
+ }, (table) => [index("policy_decisions_invocation_idx").on(table.invocationId), index("policy_decisions_run_idx").on(table.runId)]);
141
+ const workerLeases = runtimeSchema.table("worker_leases", {
142
+ name: text("name").primaryKey(),
143
+ holderId: text("holder_id").notNull(),
144
+ acquiredAt: timestamp("acquired_at", {
145
+ withTimezone: true,
146
+ mode: "date"
147
+ }).notNull().defaultNow(),
148
+ heartbeatAt: timestamp("heartbeat_at", {
149
+ withTimezone: true,
150
+ mode: "date"
151
+ }).notNull().defaultNow(),
152
+ expiresAt: timestamp("expires_at", {
153
+ withTimezone: true,
154
+ mode: "date"
155
+ }).notNull()
156
+ });
157
+ // src/db/client.ts
158
+ var DbHandle = class {
159
+ db;
160
+ pool;
161
+ kind = "runwarden/database";
162
+ constructor(db, pool) {
163
+ this.db = db;
164
+ this.pool = pool;
165
+ }
166
+ async close() {
167
+ await this.pool.end();
168
+ }
169
+ };
170
+ function createDb(connectionString) {
171
+ const pool = new Pool({ connectionString });
172
+ pool.on("error", (error) => {
173
+ if (error.message.includes("terminating connection")) return;
174
+ console.error("runwarden: database pool error", error);
175
+ });
176
+ return new DbHandle(drizzle(pool, { schema: schema_exports }), pool);
177
+ }
178
+ // src/db/init.ts
179
+ const LEDGER_DDL = `
180
+ create table if not exists agent_runtime.schema_migrations (
181
+ name text primary key,
182
+ hash text not null,
183
+ applied_at timestamptz not null default now()
184
+ )
185
+ `;
186
+ const PACKAGE_NAME = "runwarden";
187
+ async function resolveMigrationsDir(moduleUrl) {
188
+ let dir = path.dirname(fileURLToPath(moduleUrl));
189
+ for (;;) {
190
+ if ((await readFile(path.join(dir, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null))?.name === PACKAGE_NAME) {
191
+ const migrationsDir = path.join(dir, "migrations");
192
+ if ((await readdir(migrationsDir).catch(() => null))?.some((file) => file.endsWith(".sql"))) return migrationsDir;
193
+ throw new Error(`runwarden: no .sql migrations found in ${migrationsDir}. The installation looks incomplete; reinstall runwarden or pass InitOptions.migrationsDir.`);
194
+ }
195
+ const parent = path.dirname(dir);
196
+ if (parent === dir) break;
197
+ dir = parent;
198
+ }
199
+ throw new Error(`runwarden: could not locate the runwarden package root from ${fileURLToPath(moduleUrl)}. Pass InitOptions.migrationsDir to initDb.`);
200
+ }
201
+ async function initDb(handle, options = {}) {
202
+ const dir = options.migrationsDir ?? await resolveMigrationsDir(import.meta.url);
203
+ const entries = await readdir(dir).catch(() => null);
204
+ if (!entries) throw new Error(`runwarden: migrations directory not found: ${dir}. Pass InitOptions.migrationsDir if the migrations live elsewhere.`);
205
+ const files = entries.filter((file) => file.endsWith(".sql")).sort();
206
+ if (files.length === 0) throw new Error(`runwarden: no .sql migrations found in ${dir}. Pass InitOptions.migrationsDir if the migrations live elsewhere.`);
207
+ const client = await handle.pool.connect();
208
+ try {
209
+ await client.query(`select pg_advisory_lock(hashtext('runwarden:init'))`);
210
+ try {
211
+ await client.query("create schema if not exists agent_runtime");
212
+ await client.query(LEDGER_DDL);
213
+ const { rows } = await client.query("select name from agent_runtime.schema_migrations");
214
+ const done = new Set(rows.map((row) => row.name));
215
+ const applied = [];
216
+ for (const file of files) {
217
+ if (done.has(file)) continue;
218
+ const text = await readFile(path.join(dir, file), "utf8");
219
+ const hash = createHash("sha256").update(text).digest("hex");
220
+ await client.query("begin");
221
+ try {
222
+ for (const statement of text.split("--> statement-breakpoint").map((part) => part.trim()).filter(Boolean)) await client.query(statement);
223
+ await client.query("insert into agent_runtime.schema_migrations (name, hash) values ($1, $2)", [file, hash]);
224
+ await client.query("commit");
225
+ } catch (error) {
226
+ await client.query("rollback");
227
+ throw error;
228
+ }
229
+ applied.push(file);
230
+ }
231
+ return {
232
+ applied,
233
+ alreadyApplied: files.filter((file) => done.has(file))
234
+ };
235
+ } finally {
236
+ await client.query(`select pg_advisory_unlock(hashtext('runwarden:init'))`);
237
+ }
238
+ } finally {
239
+ client.release();
240
+ }
241
+ }
242
+ export { createDb as n, policyDecisions as r, initDb as t };
@@ -0,0 +1,12 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ export { __exportAll as t };
@@ -0,0 +1,84 @@
1
+ CREATE SCHEMA IF NOT EXISTS "agent_runtime";
2
+ --> statement-breakpoint
3
+ CREATE TYPE "agent_runtime"."invocation_status" AS ENUM('pending', 'running', 'awaiting_approval', 'succeeded', 'failed', 'cancelled');--> statement-breakpoint
4
+ CREATE TYPE "agent_runtime"."tool_call_status" AS ENUM('started', 'succeeded', 'failed');--> statement-breakpoint
5
+ CREATE TABLE "agent_runtime"."invocations" (
6
+ "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "agent_runtime"."invocations_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),
7
+ "scope" text NOT NULL,
8
+ "conversation_id" text,
9
+ "ordering_key" text,
10
+ "input" jsonb NOT NULL,
11
+ "result_text" text,
12
+ "idempotency_key" text,
13
+ "status" "agent_runtime"."invocation_status" DEFAULT 'pending' NOT NULL,
14
+ "attempt_count" integer DEFAULT 0 NOT NULL,
15
+ "max_attempts" integer DEFAULT 3 NOT NULL,
16
+ "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL,
17
+ "claimed_at" timestamp with time zone,
18
+ "claimed_by" text,
19
+ "lease_heartbeat_at" timestamp with time zone,
20
+ "lease_expires_at" timestamp with time zone,
21
+ "active_run_id" uuid,
22
+ "active_run_registered_at" timestamp with time zone,
23
+ "pending_tool_call" jsonb,
24
+ "started_at" timestamp with time zone,
25
+ "completed_at" timestamp with time zone,
26
+ "failed_at" timestamp with time zone,
27
+ "provider" text,
28
+ "model" text,
29
+ "last_error_code" text,
30
+ "last_error_message" text,
31
+ "metadata" jsonb,
32
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
33
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
34
+ );
35
+ --> statement-breakpoint
36
+ CREATE TABLE "agent_runtime"."policy_decisions" (
37
+ "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "agent_runtime"."policy_decisions_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),
38
+ "scope" text NOT NULL,
39
+ "invocation_id" bigint NOT NULL,
40
+ "run_id" uuid NOT NULL,
41
+ "tool_name" text,
42
+ "rule" text NOT NULL,
43
+ "decision" text NOT NULL,
44
+ "detail" jsonb,
45
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
46
+ );
47
+ --> statement-breakpoint
48
+ CREATE TABLE "agent_runtime"."tool_call_audits" (
49
+ "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "agent_runtime"."tool_call_audits_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),
50
+ "invocation_id" bigint NOT NULL,
51
+ "scope" text NOT NULL,
52
+ "run_id" uuid,
53
+ "tool_name" text NOT NULL,
54
+ "idempotency_key" text,
55
+ "status" "agent_runtime"."tool_call_status" NOT NULL,
56
+ "requested_at" timestamp with time zone DEFAULT now() NOT NULL,
57
+ "completed_at" timestamp with time zone,
58
+ "error_code" text,
59
+ "request_snapshot" jsonb,
60
+ "metadata" jsonb,
61
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
62
+ );
63
+ --> statement-breakpoint
64
+ CREATE TABLE "agent_runtime"."worker_leases" (
65
+ "name" text PRIMARY KEY NOT NULL,
66
+ "holder_id" text NOT NULL,
67
+ "acquired_at" timestamp with time zone DEFAULT now() NOT NULL,
68
+ "heartbeat_at" timestamp with time zone DEFAULT now() NOT NULL,
69
+ "expires_at" timestamp with time zone NOT NULL
70
+ );
71
+ --> statement-breakpoint
72
+ ALTER TABLE "agent_runtime"."policy_decisions" ADD CONSTRAINT "policy_decisions_invocation_id_invocations_id_fk" FOREIGN KEY ("invocation_id") REFERENCES "agent_runtime"."invocations"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
73
+ ALTER TABLE "agent_runtime"."tool_call_audits" ADD CONSTRAINT "tool_call_audits_invocation_id_invocations_id_fk" FOREIGN KEY ("invocation_id") REFERENCES "agent_runtime"."invocations"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
74
+ CREATE UNIQUE INDEX "invocations_scope_idempotency_key_unique" ON "agent_runtime"."invocations" USING btree ("scope","idempotency_key") WHERE "agent_runtime"."invocations"."idempotency_key" is not null;--> statement-breakpoint
75
+ CREATE UNIQUE INDEX "invocations_active_run_id_unique" ON "agent_runtime"."invocations" USING btree ("active_run_id") WHERE "agent_runtime"."invocations"."active_run_id" is not null;--> statement-breakpoint
76
+ CREATE INDEX "invocations_status_next_attempt_idx" ON "agent_runtime"."invocations" USING btree ("status","next_attempt_at");--> statement-breakpoint
77
+ CREATE INDEX "invocations_status_lease_expires_idx" ON "agent_runtime"."invocations" USING btree ("status","lease_expires_at");--> statement-breakpoint
78
+ CREATE INDEX "invocations_scope_status_next_attempt_idx" ON "agent_runtime"."invocations" USING btree ("scope","status","next_attempt_at");--> statement-breakpoint
79
+ CREATE INDEX "invocations_scope_created_idx" ON "agent_runtime"."invocations" USING btree ("scope","created_at");--> statement-breakpoint
80
+ CREATE INDEX "policy_decisions_invocation_idx" ON "agent_runtime"."policy_decisions" USING btree ("invocation_id");--> statement-breakpoint
81
+ CREATE INDEX "policy_decisions_run_idx" ON "agent_runtime"."policy_decisions" USING btree ("run_id");--> statement-breakpoint
82
+ CREATE UNIQUE INDEX "tool_call_audits_scope_tool_idempotency_unique" ON "agent_runtime"."tool_call_audits" USING btree ("scope","tool_name","idempotency_key") WHERE "agent_runtime"."tool_call_audits"."idempotency_key" is not null;--> statement-breakpoint
83
+ CREATE INDEX "tool_call_audits_invocation_idx" ON "agent_runtime"."tool_call_audits" USING btree ("invocation_id");--> statement-breakpoint
84
+ CREATE INDEX "tool_call_audits_run_idx" ON "agent_runtime"."tool_call_audits" USING btree ("run_id");