@relayfx/sdk 0.0.26 → 0.0.27

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 CHANGED
@@ -2196,16 +2196,19 @@ __export(exports_envelope_repository, {
2196
2196
  ackReady: () => ackReady,
2197
2197
  acceptEnvelope: () => acceptEnvelope,
2198
2198
  WaitState: () => WaitState,
2199
+ WaitRow: () => WaitRow,
2199
2200
  WaitNotFound: () => WaitNotFound,
2200
2201
  Service: () => Service9,
2202
+ EnvelopeRow: () => EnvelopeRow,
2201
2203
  EnvelopeRepositoryError: () => EnvelopeRepositoryError,
2202
2204
  EnvelopeReadyState: () => EnvelopeReadyState,
2205
+ EnvelopeReadyRow: () => EnvelopeReadyRow,
2203
2206
  EnvelopeReadyNotFound: () => EnvelopeReadyNotFound,
2204
2207
  EnvelopeReadyClaimMismatch: () => EnvelopeReadyClaimMismatch,
2205
2208
  EnvelopeNotFound: () => EnvelopeNotFound
2206
2209
  });
2207
- import { and as and2, asc as asc5, desc as desc2, eq as eq6, inArray, lte, or, sql as sql5 } from "drizzle-orm";
2208
2210
  import { Context as Context9, Effect as Effect9, Layer as Layer9, Schema as Schema19 } from "effect";
2211
+ import * as SqlClient6 from "effect/unstable/sql/SqlClient";
2209
2212
  var WaitState = Schema19.Literals(["open", "resolved", "timed_out", "cancelled"]).annotate({
2210
2213
  identifier: "Relay.Store.WaitState"
2211
2214
  });
@@ -2241,87 +2244,98 @@ class EnvelopeReadyClaimMismatch extends Schema19.TaggedErrorClass()("EnvelopeRe
2241
2244
 
2242
2245
  class Service9 extends Context9.Service()("@relayfx/store-sql/EnvelopeRepository") {
2243
2246
  }
2247
+ var DbTimestamp = Schema19.Union([Schema19.Date, Schema19.String, Schema19.Number]);
2248
+ var NullableDbTimestamp = Schema19.Union([Schema19.Date, Schema19.String, Schema19.Number, Schema19.Null]);
2249
+ var NullableString = Schema19.Union([Schema19.String, Schema19.Null]);
2250
+ var EnvelopeRow = Schema19.Struct({
2251
+ id: Schema19.String,
2252
+ execution_id: Schema19.String,
2253
+ from_address_id: Schema19.String,
2254
+ to_address_id: Schema19.String,
2255
+ content_json: Schema19.Unknown,
2256
+ wait_json: Schema19.Unknown,
2257
+ correlation_key: NullableString,
2258
+ metadata_json: Schema19.Unknown,
2259
+ created_at: DbTimestamp
2260
+ }).annotate({ identifier: "Relay.Envelope.Row" });
2261
+ var WaitRow = Schema19.Struct({
2262
+ id: Schema19.String,
2263
+ execution_id: Schema19.String,
2264
+ envelope_id: NullableString,
2265
+ mode: Schema19.String,
2266
+ correlation_key: NullableString,
2267
+ state: Schema19.String,
2268
+ metadata_json: Schema19.Unknown,
2269
+ created_at: DbTimestamp,
2270
+ resolved_at: NullableDbTimestamp
2271
+ }).annotate({ identifier: "Relay.Wait.Row" });
2272
+ var EnvelopeReadyRow = Schema19.Struct({
2273
+ id: Schema19.String,
2274
+ envelope_id: Schema19.String,
2275
+ route_type: Schema19.String,
2276
+ route_key: Schema19.String,
2277
+ state: Schema19.String,
2278
+ available_at: DbTimestamp,
2279
+ attempt: Schema19.Number,
2280
+ claim_owner: NullableString,
2281
+ claim_expires_at: NullableDbTimestamp,
2282
+ last_error: NullableString,
2283
+ idempotency_key: NullableString,
2284
+ metadata_json: Schema19.Unknown,
2285
+ created_at: DbTimestamp,
2286
+ updated_at: DbTimestamp,
2287
+ claimed_at: NullableDbTimestamp,
2288
+ acknowledged_at: NullableDbTimestamp
2289
+ }).annotate({ identifier: "Relay.EnvelopeReady.Row" });
2244
2290
  var metadata3 = (input) => input ?? {};
2245
- var toEnvelopeRow = (tenantId2, input) => ({
2246
- tenantId: tenantId2,
2247
- id: input.id,
2248
- executionId: input.execution_id,
2249
- fromAddressId: input.from,
2250
- toAddressId: input.to,
2251
- contentJson: input.content,
2252
- metadataJson: metadata3(input.metadata),
2253
- createdAt: toPgDate(input.created_at),
2254
- ...input.wait === undefined ? {} : { waitJson: input.wait },
2255
- ...input.correlation_key === undefined ? {} : { correlationKey: input.correlation_key }
2256
- });
2257
- var toEnvelope = (row) => ({
2258
- id: row.id,
2259
- execution_id: row.executionId,
2260
- from: row.fromAddressId,
2261
- to: row.toAddressId,
2262
- content: row.contentJson,
2263
- ...row.waitJson === null ? {} : { wait: row.waitJson },
2264
- ...row.correlationKey === null ? {} : { correlation_key: row.correlationKey },
2265
- metadata: row.metadataJson,
2266
- created_at: fromPgDate(row.createdAt)
2267
- });
2268
- var toWaitInsert = (tenantId2, input) => {
2269
- if (input.waitId === undefined || input.envelope.wait === undefined)
2270
- return;
2291
+ var decodeMetadata = (value) => decodeJson(value);
2292
+ var toEnvelope = (row) => {
2293
+ const wait = row.wait_json === null || row.wait_json === undefined ? undefined : decodeJson(row.wait_json);
2271
2294
  return {
2272
- tenantId: tenantId2,
2273
- id: input.waitId,
2274
- executionId: input.envelope.execution_id,
2275
- envelopeId: input.envelope.id,
2276
- mode: input.envelope.wait.mode,
2277
- metadataJson: metadata3(input.envelope.wait.metadata),
2278
- createdAt: toPgDate(input.envelope.created_at),
2279
- ...input.envelope.wait.correlation_key === undefined ? {} : { correlationKey: input.envelope.wait.correlation_key }
2295
+ id: exports_ids_schema.EnvelopeId.make(row.id),
2296
+ execution_id: exports_ids_schema.ExecutionId.make(row.execution_id),
2297
+ from: exports_ids_schema.AddressId.make(row.from_address_id),
2298
+ to: exports_ids_schema.AddressId.make(row.to_address_id),
2299
+ content: decodeJson(row.content_json),
2300
+ ...wait === undefined ? {} : { wait },
2301
+ ...row.correlation_key === null ? {} : { correlation_key: row.correlation_key },
2302
+ metadata: decodeMetadata(row.metadata_json),
2303
+ created_at: fromDbTimestamp(row.created_at)
2280
2304
  };
2281
2305
  };
2282
2306
  var toWaitRecord = (row) => {
2283
- const resolvedAt = fromNullablePgDate(row.resolvedAt);
2307
+ const resolvedAt = fromNullableDbTimestamp(row.resolved_at);
2284
2308
  return {
2285
- id: row.id,
2286
- executionId: row.executionId,
2287
- ...row.envelopeId === null ? {} : { envelopeId: row.envelopeId },
2309
+ id: exports_ids_schema.WaitId.make(row.id),
2310
+ executionId: exports_ids_schema.ExecutionId.make(row.execution_id),
2311
+ ...row.envelope_id === null ? {} : { envelopeId: exports_ids_schema.EnvelopeId.make(row.envelope_id) },
2288
2312
  mode: row.mode,
2289
- ...row.correlationKey === null ? {} : { correlationKey: row.correlationKey },
2313
+ ...row.correlation_key === null ? {} : { correlationKey: row.correlation_key },
2290
2314
  state: row.state,
2291
- metadata: row.metadataJson,
2292
- createdAt: fromPgDate(row.createdAt),
2315
+ metadata: decodeMetadata(row.metadata_json),
2316
+ createdAt: fromDbTimestamp(row.created_at),
2293
2317
  ...resolvedAt === undefined ? {} : { resolvedAt }
2294
2318
  };
2295
2319
  };
2296
- var toReadyInsert = (tenantId2, envelope, input) => ({
2297
- tenantId: tenantId2,
2298
- id: input.id,
2299
- envelopeId: envelope.id,
2300
- routeType: input.routeType,
2301
- routeKey: input.routeKey,
2302
- availableAt: toPgDate(input.availableAt),
2303
- metadataJson: metadata3(input.metadata),
2304
- ...input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }
2305
- });
2306
2320
  var toReadyRecord = (row) => {
2307
- const claimExpiresAt = fromNullablePgDate(row.claimExpiresAt);
2308
- const claimedAt = fromNullablePgDate(row.claimedAt);
2309
- const acknowledgedAt = fromNullablePgDate(row.acknowledgedAt);
2321
+ const claimExpiresAt = fromNullableDbTimestamp(row.claim_expires_at);
2322
+ const claimedAt = fromNullableDbTimestamp(row.claimed_at);
2323
+ const acknowledgedAt = fromNullableDbTimestamp(row.acknowledged_at);
2310
2324
  return {
2311
- id: row.id,
2312
- envelopeId: row.envelopeId,
2313
- routeType: row.routeType,
2314
- routeKey: row.routeKey,
2325
+ id: exports_ids_schema.EnvelopeReadyId.make(row.id),
2326
+ envelopeId: exports_ids_schema.EnvelopeId.make(row.envelope_id),
2327
+ routeType: row.route_type,
2328
+ routeKey: row.route_key,
2315
2329
  state: row.state,
2316
- availableAt: fromPgDate(row.availableAt),
2330
+ availableAt: fromDbTimestamp(row.available_at),
2317
2331
  attempt: row.attempt,
2318
- ...row.claimOwner === null ? {} : { claimOwner: row.claimOwner },
2332
+ ...row.claim_owner === null ? {} : { claimOwner: row.claim_owner },
2319
2333
  ...claimExpiresAt === undefined ? {} : { claimExpiresAt },
2320
- ...row.lastError === null ? {} : { lastError: row.lastError },
2321
- ...row.idempotencyKey === null ? {} : { idempotencyKey: row.idempotencyKey },
2322
- metadata: row.metadataJson,
2323
- createdAt: fromPgDate(row.createdAt),
2324
- updatedAt: fromPgDate(row.updatedAt),
2334
+ ...row.last_error === null ? {} : { lastError: row.last_error },
2335
+ ...row.idempotency_key === null ? {} : { idempotencyKey: row.idempotency_key },
2336
+ metadata: decodeMetadata(row.metadata_json),
2337
+ createdAt: fromDbTimestamp(row.created_at),
2338
+ updatedAt: fromDbTimestamp(row.updated_at),
2325
2339
  ...claimedAt === undefined ? {} : { claimedAt },
2326
2340
  ...acknowledgedAt === undefined ? {} : { acknowledgedAt }
2327
2341
  };
@@ -2334,50 +2348,85 @@ var accepted = (input) => ({
2334
2348
  var maxListWaitsLimit = 500;
2335
2349
  var defaultListWaitsLimit = 50;
2336
2350
  var listWaitsLimit = (input) => Math.min(Math.max(input.limit ?? defaultListWaitsLimit, 1), maxListWaitsLimit);
2337
- var listWaitsConditions = (input) => [
2338
- input.executionId === undefined ? undefined : eq6(relayWaits.executionId, input.executionId),
2339
- input.state === undefined ? undefined : eq6(relayWaits.state, input.state)
2340
- ].filter((condition) => condition !== undefined);
2341
2351
  var compareWaitsDesc = (left, right) => right.createdAt - left.createdAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
2342
- var mapDatabaseError5 = (effect) => effect.pipe(Effect9.mapError((error) => new EnvelopeRepositoryError({ message: String(error) })));
2352
+ var toRepositoryError2 = (error) => new EnvelopeRepositoryError({ message: String(error) });
2353
+ var decodeEnvelopeRow = (row) => Schema19.decodeUnknownEffect(EnvelopeRow)(row).pipe(Effect9.mapError(toRepositoryError2));
2354
+ var decodeWaitRow = (row) => Schema19.decodeUnknownEffect(WaitRow)(row).pipe(Effect9.mapError(toRepositoryError2));
2355
+ var decodeReadyRow = (row) => Schema19.decodeUnknownEffect(EnvelopeReadyRow)(row).pipe(Effect9.mapError(toRepositoryError2));
2356
+ var waitColumnsText = "id, execution_id, envelope_id, mode, correlation_key, state, metadata_json, created_at, resolved_at";
2357
+ var readyColumnsText = "id, envelope_id, route_type, route_key, state, available_at, attempt, claim_owner, claim_expires_at, last_error, idempotency_key, metadata_json, created_at, updated_at, claimed_at, acknowledged_at";
2358
+ var envelopeColumnsText = "id, execution_id, from_address_id, to_address_id, content_json, wait_json, correlation_key, metadata_json, created_at";
2343
2359
  var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2344
- const db = yield* Service;
2360
+ const sql5 = yield* SqlClient6.SqlClient;
2361
+ const ts = (millis) => timestampParam(sql5, millis);
2362
+ const waitColumns = sql5.literal(waitColumnsText);
2363
+ const readyColumns = sql5.literal(readyColumnsText);
2364
+ const envelopeColumns = sql5.literal(envelopeColumnsText);
2365
+ const selectWaitById = (tenantId2, id2) => sql5`
2366
+ SELECT ${waitColumns}
2367
+ FROM relay_waits
2368
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
2369
+ `;
2370
+ const selectReadyById = (tenantId2, id2) => sql5`
2371
+ SELECT ${readyColumns}
2372
+ FROM relay_envelope_ready
2373
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
2374
+ `;
2375
+ const getWaitRow = (tenantId2, id2) => Effect9.gen(function* () {
2376
+ const rows = yield* selectWaitById(tenantId2, id2).pipe(Effect9.mapError(toRepositoryError2));
2377
+ return rows[0] === undefined ? undefined : yield* decodeWaitRow(rows[0]);
2378
+ });
2379
+ const getReadyRow = (tenantId2, id2) => Effect9.gen(function* () {
2380
+ const rows = yield* selectReadyById(tenantId2, id2).pipe(Effect9.mapError(toRepositoryError2));
2381
+ return rows[0] === undefined ? undefined : yield* decodeReadyRow(rows[0]);
2382
+ });
2345
2383
  const acceptEnvelope = Effect9.fn("EnvelopeRepository.acceptEnvelope")(function* (input) {
2346
2384
  const tenantId2 = yield* current;
2347
- const wait = toWaitInsert(tenantId2, input);
2348
- yield* mapDatabaseError5(db.transaction((tx) => Effect9.gen(function* () {
2349
- yield* tx.insert(relayEnvelopes).values(toEnvelopeRow(tenantId2, input.envelope));
2350
- if (wait !== undefined) {
2351
- yield* tx.insert(relayWaits).values(wait);
2385
+ const envelope = input.envelope;
2386
+ const wait = envelope.wait;
2387
+ const waitId = input.waitId;
2388
+ const ready = input.ready;
2389
+ yield* sql5.withTransaction(Effect9.gen(function* () {
2390
+ yield* sql5`
2391
+ INSERT INTO relay_envelopes (tenant_id, id, execution_id, from_address_id, to_address_id, content_json, wait_json, correlation_key, metadata_json, created_at)
2392
+ VALUES (${tenantId2}, ${envelope.id}, ${envelope.execution_id}, ${envelope.from}, ${envelope.to}, ${encodeJson(envelope.content)}, ${wait === undefined ? null : encodeJson(wait)}, ${envelope.correlation_key ?? null}, ${encodeJson(metadata3(envelope.metadata))}, ${ts(envelope.created_at)})
2393
+ `;
2394
+ if (waitId !== undefined && wait !== undefined) {
2395
+ yield* sql5`
2396
+ INSERT INTO relay_waits (tenant_id, id, execution_id, envelope_id, mode, correlation_key, state, metadata_json, created_at)
2397
+ VALUES (${tenantId2}, ${waitId}, ${envelope.execution_id}, ${envelope.id}, ${wait.mode}, ${wait.correlation_key ?? null}, 'open', ${encodeJson(metadata3(wait.metadata))}, ${ts(envelope.created_at)})
2398
+ `;
2352
2399
  }
2353
- if (input.ready !== undefined) {
2354
- yield* tx.insert(relayEnvelopeReady).values(toReadyInsert(tenantId2, input.envelope, input.ready));
2400
+ if (ready !== undefined) {
2401
+ yield* sql5`
2402
+ INSERT INTO relay_envelope_ready (tenant_id, id, envelope_id, route_type, route_key, state, available_at, attempt, idempotency_key, metadata_json, created_at, updated_at)
2403
+ VALUES (${tenantId2}, ${ready.id}, ${envelope.id}, ${ready.routeType}, ${ready.routeKey}, 'ready', ${ts(ready.availableAt)}, 0, ${ready.idempotencyKey ?? null}, ${encodeJson(metadata3(ready.metadata))}, ${ts(envelope.created_at)}, ${ts(envelope.created_at)})
2404
+ `;
2355
2405
  }
2356
- })));
2406
+ })).pipe(Effect9.mapError(toRepositoryError2));
2357
2407
  return accepted(input);
2358
2408
  });
2359
2409
  const getEnvelope = Effect9.fn("EnvelopeRepository.getEnvelope")(function* (id2) {
2360
2410
  const tenantId2 = yield* current;
2361
- const rows = yield* mapDatabaseError5(db.select().from(relayEnvelopes).where(predicate(tenantId2, relayEnvelopes.tenantId, eq6(relayEnvelopes.id, id2))).limit(1));
2362
- return rows[0] === undefined ? undefined : toEnvelope(rows[0]);
2411
+ const rows = yield* sql5`
2412
+ SELECT ${envelopeColumns}
2413
+ FROM relay_envelopes
2414
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
2415
+ `.pipe(Effect9.mapError(toRepositoryError2));
2416
+ return rows[0] === undefined ? undefined : toEnvelope(yield* decodeEnvelopeRow(rows[0]));
2363
2417
  });
2364
2418
  const getWait = Effect9.fn("EnvelopeRepository.getWait")(function* (id2) {
2365
2419
  const tenantId2 = yield* current;
2366
- const rows = yield* mapDatabaseError5(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, eq6(relayWaits.id, id2))).limit(1));
2367
- return rows[0] === undefined ? undefined : toWaitRecord(rows[0]);
2420
+ const row = yield* getWaitRow(tenantId2, id2);
2421
+ return row === undefined ? undefined : toWaitRecord(row);
2368
2422
  });
2369
2423
  const createWait = Effect9.fn("EnvelopeRepository.createWait")(function* (input) {
2370
2424
  const tenantId2 = yield* current;
2371
- const rows = yield* mapDatabaseError5(db.insert(relayWaits).values({
2372
- tenantId: tenantId2,
2373
- id: input.waitId,
2374
- executionId: input.executionId,
2375
- mode: input.mode,
2376
- metadataJson: metadata3(input.metadata),
2377
- createdAt: toPgDate(input.createdAt),
2378
- ...input.correlationKey === undefined ? {} : { correlationKey: input.correlationKey }
2379
- }).returning());
2380
- const row = rows[0];
2425
+ yield* sql5`
2426
+ INSERT INTO relay_waits (tenant_id, id, execution_id, envelope_id, mode, correlation_key, state, metadata_json, created_at)
2427
+ VALUES (${tenantId2}, ${input.waitId}, ${input.executionId}, ${null}, ${input.mode}, ${input.correlationKey ?? null}, 'open', ${encodeJson(metadata3(input.metadata))}, ${ts(input.createdAt)})
2428
+ `.pipe(Effect9.mapError(toRepositoryError2));
2429
+ const row = yield* getWaitRow(tenantId2, input.waitId);
2381
2430
  if (row === undefined) {
2382
2431
  return yield* Effect9.fail(new EnvelopeRepositoryError({ message: `Wait ${input.waitId} was not persisted` }));
2383
2432
  }
@@ -2385,79 +2434,232 @@ var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2385
2434
  });
2386
2435
  const listWaits = Effect9.fn("EnvelopeRepository.listWaits")(function* (input) {
2387
2436
  const tenantId2 = yield* current;
2388
- const rows = yield* mapDatabaseError5(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, ...listWaitsConditions(input))).orderBy(desc2(relayWaits.createdAt), desc2(relayWaits.id)).limit(listWaitsLimit(input)));
2389
- return rows.map(toWaitRecord);
2437
+ const conditions = [
2438
+ sql5`tenant_id = ${tenantId2}`,
2439
+ ...input.executionId === undefined ? [] : [sql5`execution_id = ${input.executionId}`],
2440
+ ...input.state === undefined ? [] : [sql5`state = ${input.state}`]
2441
+ ];
2442
+ const rows = yield* sql5`
2443
+ SELECT ${waitColumns}
2444
+ FROM relay_waits
2445
+ WHERE ${sql5.and(conditions)}
2446
+ ORDER BY created_at DESC, id DESC
2447
+ LIMIT ${sql5.literal(String(listWaitsLimit(input)))}
2448
+ `.pipe(Effect9.mapError(toRepositoryError2));
2449
+ const records = [];
2450
+ for (const row of rows) {
2451
+ records.push(toWaitRecord(yield* decodeWaitRow(row)));
2452
+ }
2453
+ return records;
2454
+ });
2455
+ const claimablePredicate = (input) => sql5.or([
2456
+ sql5.and([sql5`state = 'ready'`, sql5`available_at <= ${ts(input.now)}`]),
2457
+ sql5.and([
2458
+ sql5`state = 'claimed'`,
2459
+ sql5`claim_expires_at IS NOT NULL`,
2460
+ sql5`claim_expires_at <= ${ts(input.now)}`
2461
+ ])
2462
+ ]);
2463
+ const claimConditions = (tenantId2, input) => sql5.and([
2464
+ sql5`tenant_id = ${tenantId2}`,
2465
+ sql5`route_type = ${input.routeType}`,
2466
+ ...input.routeKey === undefined ? [] : [sql5`route_key = ${input.routeKey}`],
2467
+ claimablePredicate(input)
2468
+ ]);
2469
+ const claimUpdateSet = (input) => sql5`
2470
+ state = 'claimed',
2471
+ claim_owner = ${input.workerId},
2472
+ claim_expires_at = ${ts(input.claimExpiresAt)},
2473
+ claimed_at = ${ts(input.now)},
2474
+ updated_at = ${ts(input.now)},
2475
+ attempt = attempt + 1
2476
+ `;
2477
+ const runClaimReady = sql5.onDialectOrElse({
2478
+ mysql: () => (tenantId2, input) => sql5.withTransaction(Effect9.gen(function* () {
2479
+ const candidates = yield* sql5`
2480
+ SELECT id FROM relay_envelope_ready
2481
+ WHERE ${claimConditions(tenantId2, input)}
2482
+ ORDER BY available_at ASC, created_at ASC
2483
+ LIMIT 1
2484
+ FOR UPDATE
2485
+ `;
2486
+ const candidate = candidates[0];
2487
+ if (candidate === undefined)
2488
+ return [];
2489
+ yield* sql5`
2490
+ UPDATE relay_envelope_ready
2491
+ SET ${claimUpdateSet(input)}
2492
+ WHERE tenant_id = ${tenantId2} AND id = ${candidate.id} AND ${claimablePredicate(input)}
2493
+ `;
2494
+ const rows = yield* sql5`
2495
+ SELECT ${readyColumns}
2496
+ FROM relay_envelope_ready
2497
+ WHERE tenant_id = ${tenantId2} AND id = ${candidate.id}
2498
+ `;
2499
+ const row = rows[0];
2500
+ if (row === undefined || row.state !== "claimed" || row.claim_owner !== input.workerId)
2501
+ return [];
2502
+ return rows;
2503
+ })),
2504
+ orElse: () => (tenantId2, input) => Effect9.gen(function* () {
2505
+ const candidates = yield* sql5`
2506
+ SELECT id FROM relay_envelope_ready
2507
+ WHERE ${claimConditions(tenantId2, input)}
2508
+ ORDER BY available_at ASC, created_at ASC
2509
+ LIMIT 1
2510
+ `;
2511
+ const candidate = candidates[0];
2512
+ if (candidate === undefined)
2513
+ return [];
2514
+ return yield* sql5`
2515
+ UPDATE relay_envelope_ready
2516
+ SET ${claimUpdateSet(input)}
2517
+ WHERE tenant_id = ${tenantId2} AND id = ${candidate.id} AND ${claimablePredicate(input)}
2518
+ RETURNING ${readyColumns}
2519
+ `;
2520
+ })
2390
2521
  });
2391
2522
  const claimReady = Effect9.fn("EnvelopeRepository.claimReady")(function* (input) {
2392
2523
  const tenantId2 = yield* current;
2393
- const candidate = db.select({ id: relayEnvelopeReady.id }).from(relayEnvelopeReady).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq6(relayEnvelopeReady.routeType, input.routeType), input.routeKey === undefined ? undefined : eq6(relayEnvelopeReady.routeKey, input.routeKey), or(and2(eq6(relayEnvelopeReady.state, "ready"), lte(relayEnvelopeReady.availableAt, toPgDate(input.now))), and2(eq6(relayEnvelopeReady.state, "claimed"), lte(relayEnvelopeReady.claimExpiresAt, toPgDate(input.now)))))).orderBy(asc5(relayEnvelopeReady.availableAt), asc5(relayEnvelopeReady.createdAt)).limit(1).for("update", { skipLocked: true });
2394
- const rows = yield* mapDatabaseError5(db.update(relayEnvelopeReady).set({
2395
- state: "claimed",
2396
- claimOwner: input.workerId,
2397
- claimExpiresAt: toPgDate(input.claimExpiresAt),
2398
- claimedAt: toPgDate(input.now),
2399
- updatedAt: toPgDate(input.now),
2400
- attempt: sql5`${relayEnvelopeReady.attempt} + 1`
2401
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, inArray(relayEnvelopeReady.id, candidate))).returning());
2402
- return rows[0] === undefined ? undefined : toReadyRecord(rows[0]);
2524
+ const rows = yield* runClaimReady(tenantId2, input).pipe(Effect9.mapError(toRepositoryError2));
2525
+ return rows[0] === undefined ? undefined : toReadyRecord(yield* decodeReadyRow(rows[0]));
2526
+ });
2527
+ const runReleaseReady = sql5.onDialectOrElse({
2528
+ mysql: () => (tenantId2, input) => sql5.withTransaction(Effect9.gen(function* () {
2529
+ const locked = yield* sql5`
2530
+ SELECT ${readyColumns}
2531
+ FROM relay_envelope_ready
2532
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id}
2533
+ FOR UPDATE
2534
+ `;
2535
+ const current2 = locked[0];
2536
+ if (current2 === undefined || current2.state !== "claimed" || current2.claim_owner !== input.workerId) {
2537
+ return [];
2538
+ }
2539
+ yield* sql5`
2540
+ UPDATE relay_envelope_ready
2541
+ SET state = 'ready',
2542
+ available_at = ${ts(input.nextAvailableAt)},
2543
+ claim_owner = NULL,
2544
+ claim_expires_at = NULL,
2545
+ last_error = ${input.error ?? null},
2546
+ updated_at = ${ts(input.nextAvailableAt)}
2547
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id}
2548
+ `;
2549
+ return yield* selectReadyById(tenantId2, input.id);
2550
+ })),
2551
+ orElse: () => (tenantId2, input) => sql5`
2552
+ UPDATE relay_envelope_ready
2553
+ SET state = 'ready',
2554
+ available_at = ${ts(input.nextAvailableAt)},
2555
+ claim_owner = NULL,
2556
+ claim_expires_at = NULL,
2557
+ last_error = ${input.error ?? null},
2558
+ updated_at = ${ts(input.nextAvailableAt)}
2559
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id} AND claim_owner = ${input.workerId} AND state = 'claimed'
2560
+ RETURNING ${readyColumns}
2561
+ `
2403
2562
  });
2404
2563
  const releaseReady = Effect9.fn("EnvelopeRepository.releaseReady")(function* (input) {
2405
2564
  const tenantId2 = yield* current;
2406
- const rows = yield* mapDatabaseError5(db.update(relayEnvelopeReady).set({
2407
- state: "ready",
2408
- availableAt: toPgDate(input.nextAvailableAt),
2409
- claimOwner: null,
2410
- claimExpiresAt: null,
2411
- lastError: input.error ?? null,
2412
- updatedAt: toPgDate(input.nextAvailableAt)
2413
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq6(relayEnvelopeReady.id, input.id), eq6(relayEnvelopeReady.claimOwner, input.workerId), eq6(relayEnvelopeReady.state, "claimed"))).returning());
2414
- const row = rows[0];
2415
- if (row !== undefined)
2416
- return toReadyRecord(row);
2417
- const current2 = yield* getReadyRow(db, tenantId2, input.id);
2565
+ const rows = yield* runReleaseReady(tenantId2, input).pipe(Effect9.mapError(toRepositoryError2));
2566
+ if (rows[0] !== undefined)
2567
+ return toReadyRecord(yield* decodeReadyRow(rows[0]));
2568
+ const current2 = yield* getReadyRow(tenantId2, input.id);
2418
2569
  if (current2 === undefined)
2419
2570
  return yield* Effect9.fail(new EnvelopeReadyNotFound({ id: input.id }));
2420
- if (current2.state === "acknowledged" && current2.claimOwner === input.workerId)
2571
+ if (current2.state === "acknowledged" && current2.claim_owner === input.workerId)
2421
2572
  return toReadyRecord(current2);
2422
2573
  return yield* Effect9.fail(new EnvelopeReadyClaimMismatch({ id: input.id, worker_id: input.workerId }));
2423
2574
  });
2575
+ const runAckReady = sql5.onDialectOrElse({
2576
+ mysql: () => (tenantId2, input) => sql5.withTransaction(Effect9.gen(function* () {
2577
+ const locked = yield* sql5`
2578
+ SELECT ${readyColumns}
2579
+ FROM relay_envelope_ready
2580
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id}
2581
+ FOR UPDATE
2582
+ `;
2583
+ const current2 = locked[0];
2584
+ if (current2 === undefined || current2.state !== "claimed" || current2.claim_owner !== input.workerId) {
2585
+ return [];
2586
+ }
2587
+ yield* sql5`
2588
+ UPDATE relay_envelope_ready
2589
+ SET state = 'acknowledged',
2590
+ acknowledged_at = ${ts(input.now)},
2591
+ updated_at = ${ts(input.now)}
2592
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id}
2593
+ `;
2594
+ return yield* selectReadyById(tenantId2, input.id);
2595
+ })),
2596
+ orElse: () => (tenantId2, input) => sql5`
2597
+ UPDATE relay_envelope_ready
2598
+ SET state = 'acknowledged',
2599
+ acknowledged_at = ${ts(input.now)},
2600
+ updated_at = ${ts(input.now)}
2601
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id} AND claim_owner = ${input.workerId} AND state = 'claimed'
2602
+ RETURNING ${readyColumns}
2603
+ `
2604
+ });
2424
2605
  const ackReady = Effect9.fn("EnvelopeRepository.ackReady")(function* (input) {
2425
2606
  const tenantId2 = yield* current;
2426
- const rows = yield* mapDatabaseError5(db.update(relayEnvelopeReady).set({
2427
- state: "acknowledged",
2428
- acknowledgedAt: toPgDate(input.now),
2429
- updatedAt: toPgDate(input.now)
2430
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq6(relayEnvelopeReady.id, input.id), eq6(relayEnvelopeReady.claimOwner, input.workerId), eq6(relayEnvelopeReady.state, "claimed"))).returning());
2431
- const row = rows[0];
2432
- if (row !== undefined)
2433
- return toReadyRecord(row);
2434
- const current2 = yield* getReadyRow(db, tenantId2, input.id);
2607
+ const rows = yield* runAckReady(tenantId2, input).pipe(Effect9.mapError(toRepositoryError2));
2608
+ if (rows[0] !== undefined)
2609
+ return toReadyRecord(yield* decodeReadyRow(rows[0]));
2610
+ const current2 = yield* getReadyRow(tenantId2, input.id);
2435
2611
  if (current2 === undefined)
2436
2612
  return yield* Effect9.fail(new EnvelopeReadyNotFound({ id: input.id }));
2437
- if (current2.state === "acknowledged" && current2.claimOwner === input.workerId)
2613
+ if (current2.state === "acknowledged" && current2.claim_owner === input.workerId)
2438
2614
  return toReadyRecord(current2);
2439
2615
  return yield* Effect9.fail(new EnvelopeReadyClaimMismatch({ id: input.id, worker_id: input.workerId }));
2440
2616
  });
2617
+ const runCompleteWait = sql5.onDialectOrElse({
2618
+ mysql: () => (tenantId2, input, merged) => sql5.withTransaction(Effect9.gen(function* () {
2619
+ const locked = yield* sql5`
2620
+ SELECT ${waitColumns}
2621
+ FROM relay_waits
2622
+ WHERE tenant_id = ${tenantId2} AND id = ${input.waitId}
2623
+ FOR UPDATE
2624
+ `;
2625
+ const current2 = locked[0];
2626
+ if (current2 === undefined || current2.state !== "open")
2627
+ return [];
2628
+ yield* sql5`
2629
+ UPDATE relay_waits
2630
+ SET state = ${input.state},
2631
+ resolved_at = ${ts(input.completedAt)},
2632
+ metadata_json = ${encodeJson(merged)}
2633
+ WHERE tenant_id = ${tenantId2} AND id = ${input.waitId}
2634
+ `;
2635
+ return yield* selectWaitById(tenantId2, input.waitId);
2636
+ })),
2637
+ orElse: () => (tenantId2, input, merged) => sql5`
2638
+ UPDATE relay_waits
2639
+ SET state = ${input.state},
2640
+ resolved_at = ${ts(input.completedAt)},
2641
+ metadata_json = ${encodeJson(merged)}
2642
+ WHERE tenant_id = ${tenantId2} AND id = ${input.waitId} AND state = 'open'
2643
+ RETURNING ${waitColumns}
2644
+ `
2645
+ });
2441
2646
  const completeWait = Effect9.fn("EnvelopeRepository.completeWait")(function* (input) {
2442
2647
  const tenantId2 = yield* current;
2443
- const current2 = yield* getWaitRow(db, tenantId2, input.waitId);
2648
+ const current2 = yield* getWaitRow(tenantId2, input.waitId);
2444
2649
  if (current2 === undefined)
2445
2650
  return yield* Effect9.fail(new WaitNotFound({ id: input.waitId }));
2446
- if (current2.state !== "open")
2447
- return { wait: toWaitRecord(current2), transitioned: false };
2448
- const rows = yield* mapDatabaseError5(db.update(relayWaits).set({
2449
- state: input.state,
2450
- resolvedAt: toPgDate(input.completedAt),
2451
- metadataJson: { ...current2.metadataJson, ...metadata3(input.metadata) }
2452
- }).where(predicate(tenantId2, relayWaits.tenantId, eq6(relayWaits.id, input.waitId), eq6(relayWaits.state, "open"))).returning());
2453
- const row = rows[0];
2454
- if (row === undefined) {
2455
- const latest = yield* getWaitRow(db, tenantId2, input.waitId);
2651
+ const currentRecord = toWaitRecord(current2);
2652
+ if (currentRecord.state !== "open")
2653
+ return { wait: currentRecord, transitioned: false };
2654
+ const merged = { ...currentRecord.metadata, ...metadata3(input.metadata) };
2655
+ const rows = yield* runCompleteWait(tenantId2, input, merged).pipe(Effect9.mapError(toRepositoryError2));
2656
+ if (rows[0] === undefined) {
2657
+ const latest = yield* getWaitRow(tenantId2, input.waitId);
2456
2658
  if (latest === undefined)
2457
2659
  return yield* Effect9.fail(new WaitNotFound({ id: input.waitId }));
2458
2660
  return { wait: toWaitRecord(latest), transitioned: false };
2459
2661
  }
2460
- return { wait: toWaitRecord(row), transitioned: true };
2662
+ return { wait: toWaitRecord(yield* decodeWaitRow(rows[0])), transitioned: true };
2461
2663
  });
2462
2664
  const resolveWait = Effect9.fn("EnvelopeRepository.resolveWait")(function* (input) {
2463
2665
  const result = yield* completeWait({
@@ -2481,8 +2683,6 @@ var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2481
2683
  resolveWait
2482
2684
  });
2483
2685
  }));
2484
- var getReadyRow = (db, tenantId2, id2) => mapDatabaseError5(db.select().from(relayEnvelopeReady).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq6(relayEnvelopeReady.id, id2))).limit(1)).pipe(Effect9.map((rows) => rows[0]));
2485
- var getWaitRow = (db, tenantId2, id2) => mapDatabaseError5(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, eq6(relayWaits.id, id2))).limit(1)).pipe(Effect9.map((rows) => rows[0]));
2486
2686
  var memoryLayer7 = Layer9.sync(Service9, () => {
2487
2687
  const envelopes = new Map;
2488
2688
  const waits = new Map;
@@ -2692,7 +2892,7 @@ __export(exports_execution_event_repository, {
2692
2892
  ExecutionEventCursorNotFound: () => ExecutionEventCursorNotFound,
2693
2893
  DuplicateExecutionEvent: () => DuplicateExecutionEvent
2694
2894
  });
2695
- import { asc as asc6, desc as desc3, eq as eq7, gt, max, or as or2, sql as sql6 } from "drizzle-orm";
2895
+ import { asc as asc5, desc as desc2, eq as eq6, gt, max, or, sql as sql5 } from "drizzle-orm";
2696
2896
  import { Context as Context10, Effect as Effect10, Filter, Layer as Layer10, Option as Option2, Schema as Schema20, Stream } from "effect";
2697
2897
  var executionEventsChannel = "relay_execution_events";
2698
2898
 
@@ -2756,7 +2956,7 @@ var toEvent = (row) => ({
2756
2956
  data: row.dataJson,
2757
2957
  created_at: fromPgDate(row.createdAt)
2758
2958
  });
2759
- var mapDatabaseError6 = (effect) => effect.pipe(Effect10.mapError((error) => new ExecutionEventRepositoryError({ message: String(error) })));
2959
+ var mapDatabaseError5 = (effect) => effect.pipe(Effect10.mapError((error) => new ExecutionEventRepositoryError({ message: String(error) })));
2760
2960
  var mapSqlError = (error) => new ExecutionEventRepositoryError({ message: String(error) });
2761
2961
  var appendedSignalPayload = (tenantId2, event) => JSON.stringify({ tenantId: tenantId2, executionId: event.execution_id, sequence: event.sequence });
2762
2962
  var parseAppendedSignal = (tenantId2, executionId, payload) => {
@@ -2802,7 +3002,7 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2802
3002
  const db = yield* Service;
2803
3003
  const append = Effect10.fn("ExecutionEventRepository.append")(function* (input) {
2804
3004
  const tenantId2 = yield* current;
2805
- const previousRows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.execution_id))).orderBy(desc3(relayExecutionEvents.sequence)).limit(1));
3005
+ const previousRows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.execution_id))).orderBy(desc2(relayExecutionEvents.sequence)).limit(1));
2806
3006
  const previous = previousRows[0];
2807
3007
  if (previous !== undefined && input.sequence === previous.sequence) {
2808
3008
  return yield* Effect10.fail(duplicateError(input));
@@ -2814,11 +3014,11 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2814
3014
  previous_sequence: previous.sequence
2815
3015
  }));
2816
3016
  }
2817
- const duplicateCursorRows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.cursor, input.cursor))).limit(1));
3017
+ const duplicateCursorRows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.cursor, input.cursor))).limit(1));
2818
3018
  if (duplicateCursorRows[0] !== undefined) {
2819
3019
  return yield* Effect10.fail(duplicateError(input));
2820
3020
  }
2821
- const rows = yield* mapDatabaseError6(db.insert(relayExecutionEvents).values(toRow(tenantId2, input)).returning());
3021
+ const rows = yield* mapDatabaseError5(db.insert(relayExecutionEvents).values(toRow(tenantId2, input)).returning());
2822
3022
  const row = rows[0];
2823
3023
  if (row === undefined) {
2824
3024
  return yield* Effect10.fail(new ExecutionEventRepositoryError({ message: "Execution event append returned no row" }));
@@ -2828,49 +3028,49 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2828
3028
  const list4 = Effect10.fn("ExecutionEventRepository.list")(function* (input) {
2829
3029
  const tenantId2 = yield* current;
2830
3030
  if (input.afterCursor === undefined) {
2831
- const rows2 = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId))).orderBy(asc6(relayExecutionEvents.sequence)).limit(listLimit(input)));
3031
+ const rows2 = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId))).orderBy(asc5(relayExecutionEvents.sequence)).limit(listLimit(input)));
2832
3032
  return rows2.map(toEvent);
2833
3033
  }
2834
- const cursorRows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), eq7(relayExecutionEvents.cursor, input.afterCursor))).limit(1));
3034
+ const cursorRows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), eq6(relayExecutionEvents.cursor, input.afterCursor))).limit(1));
2835
3035
  const cursorRow = cursorRows[0];
2836
3036
  if (cursorRow === undefined) {
2837
3037
  return yield* Effect10.fail(new ExecutionEventCursorNotFound({ execution_id: input.executionId, cursor: input.afterCursor }));
2838
3038
  }
2839
- const rows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), gt(relayExecutionEvents.sequence, cursorRow.sequence))).orderBy(asc6(relayExecutionEvents.sequence)).limit(listLimit(input)));
3039
+ const rows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), gt(relayExecutionEvents.sequence, cursorRow.sequence))).orderBy(asc5(relayExecutionEvents.sequence)).limit(listLimit(input)));
2840
3040
  return rows.map(toEvent);
2841
3041
  });
2842
3042
  const findBySequenceOrCursor = Effect10.fn("ExecutionEventRepository.findBySequenceOrCursor")(function* (input) {
2843
3043
  const tenantId2 = yield* current;
2844
- const rows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), or2(eq7(relayExecutionEvents.sequence, input.sequence), eq7(relayExecutionEvents.cursor, input.cursor)))).orderBy(asc6(relayExecutionEvents.sequence)).limit(1));
3044
+ const rows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), or(eq6(relayExecutionEvents.sequence, input.sequence), eq6(relayExecutionEvents.cursor, input.cursor)))).orderBy(asc5(relayExecutionEvents.sequence)).limit(1));
2845
3045
  const row = rows[0];
2846
3046
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2847
3047
  });
2848
3048
  const findByCursor = Effect10.fn("ExecutionEventRepository.findByCursor")(function* (input) {
2849
3049
  const tenantId2 = yield* current;
2850
- const rows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), eq7(relayExecutionEvents.cursor, input.cursor))).limit(1));
3050
+ const rows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), eq6(relayExecutionEvents.cursor, input.cursor))).limit(1));
2851
3051
  const row = rows[0];
2852
3052
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2853
3053
  });
2854
3054
  const findFirstByTypeAfterSequence = Effect10.fn("ExecutionEventRepository.findFirstByTypeAfterSequence")(function* (input) {
2855
3055
  const tenantId2 = yield* current;
2856
- const rows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), eq7(relayExecutionEvents.type, input.type), gt(relayExecutionEvents.sequence, input.afterSequence))).orderBy(asc6(relayExecutionEvents.sequence)).limit(1));
3056
+ const rows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), eq6(relayExecutionEvents.type, input.type), gt(relayExecutionEvents.sequence, input.afterSequence))).orderBy(asc5(relayExecutionEvents.sequence)).limit(1));
2857
3057
  const row = rows[0];
2858
3058
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2859
3059
  });
2860
3060
  const maxSequence = Effect10.fn("ExecutionEventRepository.maxSequence")(function* (executionId) {
2861
3061
  const tenantId2 = yield* current;
2862
- const rows = yield* mapDatabaseError6(db.select({ value: max(relayExecutionEvents.sequence) }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, executionId))));
3062
+ const rows = yield* mapDatabaseError5(db.select({ value: max(relayExecutionEvents.sequence) }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, executionId))));
2863
3063
  const value = rows[0]?.value;
2864
3064
  return value === null || value === undefined ? undefined : value;
2865
3065
  });
2866
3066
  const sumUsage = Effect10.fn("ExecutionEventRepository.sumUsage")(function* (executionId) {
2867
3067
  const tenantId2 = yield* current;
2868
- const rows = yield* mapDatabaseError6(db.select({
2869
- value: sql6`sum(
3068
+ const rows = yield* mapDatabaseError5(db.select({
3069
+ value: sql5`sum(
2870
3070
  coalesce((${relayExecutionEvents.dataJson} ->> 'input_tokens')::bigint, 0)
2871
3071
  + coalesce((${relayExecutionEvents.dataJson} ->> 'output_tokens')::bigint, 0)
2872
3072
  )`
2873
- }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, executionId), eq7(relayExecutionEvents.type, usageReportedEventType))));
3073
+ }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, executionId), eq6(relayExecutionEvents.type, usageReportedEventType))));
2874
3074
  const value = rows[0]?.value;
2875
3075
  return value === null || value === undefined ? 0 : Number(value);
2876
3076
  });
@@ -2881,7 +3081,7 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2881
3081
  const appendedSignals = (executionId) => Stream.unwrap(current.pipe(Effect10.map((tenantId2) => db.$client.listen(executionEventsChannel).pipe(Stream.mapError(mapSqlError), Stream.filterMap(Filter.fromPredicateOption((payload) => parseAppendedSignal(tenantId2, executionId, payload)))))));
2882
3082
  const listAfterSequence = Effect10.fn("ExecutionEventRepository.listAfterSequence")(function* (input) {
2883
3083
  const tenantId2 = yield* current;
2884
- const rows = yield* mapDatabaseError6(db.select().from(relayExecutionEvents).where(input.afterSequence === undefined ? predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId)) : predicate(tenantId2, relayExecutionEvents.tenantId, eq7(relayExecutionEvents.executionId, input.executionId), gt(relayExecutionEvents.sequence, input.afterSequence))).orderBy(asc6(relayExecutionEvents.sequence)).limit(input.limit));
3084
+ const rows = yield* mapDatabaseError5(db.select().from(relayExecutionEvents).where(input.afterSequence === undefined ? predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId)) : predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, input.executionId), gt(relayExecutionEvents.sequence, input.afterSequence))).orderBy(asc5(relayExecutionEvents.sequence)).limit(input.limit));
2885
3085
  return rows.map(toEvent);
2886
3086
  });
2887
3087
  return Service10.of({
@@ -2997,12 +3197,13 @@ __export(exports_execution_repository, {
2997
3197
  get: () => get5,
2998
3198
  create: () => create2,
2999
3199
  Service: () => Service11,
3200
+ ExecutionRow: () => ExecutionRow,
3000
3201
  ExecutionRepositoryError: () => ExecutionRepositoryError,
3001
3202
  ExecutionNotFound: () => ExecutionNotFound,
3002
3203
  DuplicateExecution: () => DuplicateExecution
3003
3204
  });
3004
- import { and as and3, desc as desc4, eq as eq8, lt, or as or3 } from "drizzle-orm";
3005
3205
  import { Context as Context11, Effect as Effect11, Layer as Layer11, Schema as Schema21 } from "effect";
3206
+ import * as SqlClient8 from "effect/unstable/sql/SqlClient";
3006
3207
  class ExecutionRepositoryError extends Schema21.TaggedErrorClass()("ExecutionRepositoryError", {
3007
3208
  message: Schema21.String
3008
3209
  }) {
@@ -3020,6 +3221,19 @@ class ExecutionNotFound extends Schema21.TaggedErrorClass()("ExecutionNotFound",
3020
3221
 
3021
3222
  class Service11 extends Context11.Service()("@relayfx/store-sql/ExecutionRepository") {
3022
3223
  }
3224
+ var ExecutionRow = Schema21.Struct({
3225
+ id: Schema21.String,
3226
+ root_address_id: Schema21.String,
3227
+ session_id: Schema21.NullishOr(Schema21.String),
3228
+ status: Schema21.String,
3229
+ agent_definition_id: Schema21.NullishOr(Schema21.String),
3230
+ agent_definition_revision: Schema21.NullishOr(Schema21.Number),
3231
+ agent_definition_snapshot_json: Schema21.NullishOr(Schema21.Unknown),
3232
+ agent_definition_tool_input_schema_digests_json: Schema21.Unknown,
3233
+ metadata_json: Schema21.Unknown,
3234
+ created_at: Schema21.Union([Schema21.Date, Schema21.String, Schema21.Number]),
3235
+ updated_at: Schema21.Union([Schema21.Date, Schema21.String, Schema21.Number])
3236
+ }).annotate({ identifier: "Relay.Execution.Row" });
3023
3237
  var metadata4 = (input) => input ?? {};
3024
3238
  var nonEmptyDigests2 = (digests) => digests === undefined || Object.keys(digests).length === 0 ? undefined : structuredClone(digests);
3025
3239
  var hasCompleteAgentDefinitionPin = (input) => {
@@ -3052,37 +3266,25 @@ var cloneRecord3 = (record2) => ({
3052
3266
  ...record2.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshot: cloneAgentDefinition(record2.agentDefinitionSnapshot) },
3053
3267
  ...record2.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests: structuredClone(record2.agentDefinitionToolInputSchemaDigests) }
3054
3268
  });
3055
- var toInsert2 = (tenantId2, input) => ({
3056
- tenantId: tenantId2,
3057
- id: input.id,
3058
- rootAddressId: input.rootAddressId,
3059
- ...input.sessionId === undefined ? {} : { sessionId: input.sessionId },
3060
- status: input.status,
3061
- ...input.agentDefinitionId === undefined ? {} : { agentDefinitionId: input.agentDefinitionId },
3062
- ...input.agentDefinitionRevision === undefined ? {} : { agentDefinitionRevision: input.agentDefinitionRevision },
3063
- ...input.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshotJson: cloneAgentDefinition(input.agentDefinitionSnapshot) },
3064
- ...input.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigestsJson: input.agentDefinitionToolInputSchemaDigests },
3065
- metadataJson: metadata4(input.metadata),
3066
- createdAt: toPgDate(input.createdAt),
3067
- updatedAt: toPgDate(input.createdAt)
3068
- });
3069
3269
  var toRecord5 = (row) => {
3070
- const agentDefinitionToolInputSchemaDigests = nonEmptyDigests2(row.agentDefinitionToolInputSchemaDigestsJson);
3270
+ const snapshotJson = row.agent_definition_snapshot_json;
3271
+ const digests = nonEmptyDigests2(decodeJson(row.agent_definition_tool_input_schema_digests_json));
3071
3272
  return {
3072
- id: row.id,
3073
- rootAddressId: row.rootAddressId,
3074
- ...row.sessionId === null || row.sessionId === undefined ? {} : { sessionId: row.sessionId },
3273
+ id: exports_ids_schema.ExecutionId.make(row.id),
3274
+ rootAddressId: exports_ids_schema.AddressId.make(row.root_address_id),
3275
+ ...row.session_id === null || row.session_id === undefined ? {} : { sessionId: exports_ids_schema.SessionId.make(row.session_id) },
3075
3276
  status: row.status,
3076
- ...row.agentDefinitionId === null || row.agentDefinitionId === undefined ? {} : { agentDefinitionId: row.agentDefinitionId },
3077
- ...row.agentDefinitionRevision === null || row.agentDefinitionRevision === undefined ? {} : { agentDefinitionRevision: row.agentDefinitionRevision },
3078
- ...row.agentDefinitionSnapshotJson === null || row.agentDefinitionSnapshotJson === undefined ? {} : { agentDefinitionSnapshot: cloneAgentDefinition(row.agentDefinitionSnapshotJson) },
3079
- ...agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests },
3080
- metadata: row.metadataJson,
3081
- createdAt: fromPgDate(row.createdAt),
3082
- updatedAt: fromPgDate(row.updatedAt)
3277
+ ...row.agent_definition_id === null || row.agent_definition_id === undefined ? {} : { agentDefinitionId: exports_ids_schema.AgentDefinitionId.make(row.agent_definition_id) },
3278
+ ...row.agent_definition_revision === null || row.agent_definition_revision === undefined ? {} : { agentDefinitionRevision: row.agent_definition_revision },
3279
+ ...snapshotJson === null || snapshotJson === undefined ? {} : { agentDefinitionSnapshot: cloneAgentDefinition(decodeJson(snapshotJson)) },
3280
+ ...digests === undefined ? {} : { agentDefinitionToolInputSchemaDigests: digests },
3281
+ metadata: decodeJson(row.metadata_json),
3282
+ createdAt: fromDbTimestamp(row.created_at),
3283
+ updatedAt: fromDbTimestamp(row.updated_at)
3083
3284
  };
3084
3285
  };
3085
- var mapDatabaseError7 = (effect) => effect.pipe(Effect11.mapError((error) => new ExecutionRepositoryError({ message: String(error) })));
3286
+ var toRepositoryError3 = (error) => new ExecutionRepositoryError({ message: String(error) });
3287
+ var decodeRow2 = (row) => Schema21.decodeUnknownEffect(ExecutionRow)(row).pipe(Effect11.mapError(toRepositoryError3));
3086
3288
  var maxListLimit2 = 100;
3087
3289
  var defaultListLimit = 50;
3088
3290
  var listLimit2 = (input) => Math.min(Math.max(input.limit ?? defaultListLimit, 1), maxListLimit2);
@@ -3092,51 +3294,127 @@ var nextCursorOf = (records, fetched, limit) => {
3092
3294
  };
3093
3295
  var compareDesc = (left, right) => right.updatedAt - left.updatedAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
3094
3296
  var afterCursor = (record2, cursor) => cursor === undefined || record2.updatedAt < cursor.updatedAt || record2.updatedAt === cursor.updatedAt && record2.id < cursor.id;
3095
- var listConditions = (input) => [
3096
- input.rootAddressId === undefined ? undefined : eq8(relayExecutions.rootAddressId, input.rootAddressId),
3097
- input.sessionId === undefined ? undefined : eq8(relayExecutions.sessionId, input.sessionId),
3098
- input.status === undefined ? undefined : eq8(relayExecutions.status, input.status),
3099
- input.cursor === undefined ? undefined : or3(lt(relayExecutions.updatedAt, toPgDate(input.cursor.updatedAt)), and3(eq8(relayExecutions.updatedAt, toPgDate(input.cursor.updatedAt)), lt(relayExecutions.id, input.cursor.id)))
3100
- ].filter((condition) => condition !== undefined);
3101
3297
  var layer11 = Layer11.effect(Service11, Effect11.gen(function* () {
3102
- const db = yield* Service;
3298
+ const sql6 = yield* SqlClient8.SqlClient;
3299
+ const columns = sql6.literal([
3300
+ "id",
3301
+ "root_address_id",
3302
+ "session_id",
3303
+ "status",
3304
+ "agent_definition_id",
3305
+ "agent_definition_revision",
3306
+ "agent_definition_snapshot_json",
3307
+ "agent_definition_tool_input_schema_digests_json",
3308
+ "metadata_json",
3309
+ "created_at",
3310
+ "updated_at"
3311
+ ].join(", "));
3312
+ const selectByKey = (tenantId2, id2) => sql6`
3313
+ SELECT ${columns}
3314
+ FROM relay_executions
3315
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
3316
+ `;
3317
+ const insertStatement = (tenantId2, input) => sql6`
3318
+ INSERT INTO relay_executions (
3319
+ tenant_id, ${columns}
3320
+ )
3321
+ VALUES (
3322
+ ${tenantId2},
3323
+ ${input.id},
3324
+ ${input.rootAddressId},
3325
+ ${input.sessionId ?? null},
3326
+ ${input.status},
3327
+ ${input.agentDefinitionId ?? null},
3328
+ ${input.agentDefinitionRevision ?? null},
3329
+ ${input.agentDefinitionSnapshot === undefined ? null : encodeJson(input.agentDefinitionSnapshot)},
3330
+ ${encodeJson(input.agentDefinitionToolInputSchemaDigests ?? {})},
3331
+ ${encodeJson(metadata4(input.metadata))},
3332
+ ${timestampParam(sql6, input.createdAt)},
3333
+ ${timestampParam(sql6, input.createdAt)}
3334
+ )
3335
+ `;
3336
+ const insertExecution = sql6.onDialectOrElse({
3337
+ mysql: () => (tenantId2, input) => sql6.withTransaction(Effect11.gen(function* () {
3338
+ yield* insertStatement(tenantId2, input);
3339
+ return yield* selectByKey(tenantId2, input.id);
3340
+ })),
3341
+ orElse: () => (tenantId2, input) => sql6`
3342
+ ${insertStatement(tenantId2, input)}
3343
+ RETURNING ${columns}
3344
+ `
3345
+ });
3346
+ const updateStatement = (tenantId2, input) => sql6`
3347
+ UPDATE relay_executions
3348
+ SET status = ${input.status},
3349
+ metadata_json = ${encodeJson(metadata4(input.metadata))},
3350
+ updated_at = ${timestampParam(sql6, input.updatedAt)}
3351
+ WHERE tenant_id = ${tenantId2} AND id = ${input.id}
3352
+ `;
3353
+ const updateExecution = sql6.onDialectOrElse({
3354
+ mysql: () => (tenantId2, input) => sql6.withTransaction(Effect11.gen(function* () {
3355
+ yield* updateStatement(tenantId2, input);
3356
+ return yield* selectByKey(tenantId2, input.id);
3357
+ })),
3358
+ orElse: () => (tenantId2, input) => sql6`
3359
+ ${updateStatement(tenantId2, input)}
3360
+ RETURNING ${columns}
3361
+ `
3362
+ });
3363
+ const listConditions = (tenantId2, input) => [
3364
+ sql6`tenant_id = ${tenantId2}`,
3365
+ ...input.rootAddressId === undefined ? [] : [sql6`root_address_id = ${input.rootAddressId}`],
3366
+ ...input.sessionId === undefined ? [] : [sql6`session_id = ${input.sessionId}`],
3367
+ ...input.status === undefined ? [] : [sql6`status = ${input.status}`],
3368
+ ...input.cursor === undefined ? [] : [
3369
+ sql6.or([
3370
+ sql6`updated_at < ${timestampParam(sql6, input.cursor.updatedAt)}`,
3371
+ sql6.and([
3372
+ sql6`updated_at = ${timestampParam(sql6, input.cursor.updatedAt)}`,
3373
+ sql6`id < ${input.cursor.id}`
3374
+ ])
3375
+ ])
3376
+ ]
3377
+ ];
3103
3378
  const create2 = Effect11.fn("ExecutionRepository.create")(function* (input) {
3104
3379
  const tenantId2 = yield* current;
3105
3380
  yield* validateCreateInput(input);
3106
- const existing = yield* mapDatabaseError7(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq8(relayExecutions.id, input.id))).limit(1));
3381
+ const existing = yield* selectByKey(tenantId2, input.id).pipe(Effect11.mapError(toRepositoryError3));
3107
3382
  if (existing[0] !== undefined)
3108
3383
  return yield* Effect11.fail(new DuplicateExecution({ id: input.id }));
3109
- const rows = yield* mapDatabaseError7(db.insert(relayExecutions).values(toInsert2(tenantId2, input)).returning());
3384
+ const rows = yield* insertExecution(tenantId2, input).pipe(Effect11.mapError(toRepositoryError3));
3110
3385
  const row = rows[0];
3111
3386
  if (row === undefined) {
3112
3387
  return yield* Effect11.fail(new ExecutionRepositoryError({ message: "Execution insert returned no row" }));
3113
3388
  }
3114
- return toRecord5(row);
3389
+ return toRecord5(yield* decodeRow2(row));
3115
3390
  });
3116
3391
  const get5 = Effect11.fn("ExecutionRepository.get")(function* (id2) {
3117
3392
  const tenantId2 = yield* current;
3118
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq8(relayExecutions.id, id2))).limit(1));
3119
- return rows[0] === undefined ? undefined : toRecord5(rows[0]);
3393
+ const rows = yield* selectByKey(tenantId2, id2).pipe(Effect11.mapError(toRepositoryError3));
3394
+ return rows[0] === undefined ? undefined : toRecord5(yield* decodeRow2(rows[0]));
3120
3395
  });
3121
3396
  const list5 = Effect11.fn("ExecutionRepository.list")(function* (input) {
3122
3397
  const tenantId2 = yield* current;
3123
3398
  const limit = listLimit2(input);
3124
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, ...listConditions(input))).orderBy(desc4(relayExecutions.updatedAt), desc4(relayExecutions.id)).limit(limit + 1));
3125
- const records = rows.slice(0, limit).map(toRecord5);
3399
+ const rows = yield* sql6`
3400
+ SELECT ${columns}
3401
+ FROM relay_executions
3402
+ WHERE ${sql6.and(listConditions(tenantId2, input))}
3403
+ ORDER BY updated_at DESC, id DESC
3404
+ LIMIT ${sql6.literal(String(limit + 1))}
3405
+ `.pipe(Effect11.mapError(toRepositoryError3));
3406
+ const decoded = yield* Effect11.forEach(rows.slice(0, limit), decodeRow2);
3407
+ const records = decoded.map(toRecord5);
3126
3408
  const nextCursor = nextCursorOf(records, rows.length, limit);
3127
3409
  return nextCursor === undefined ? { records } : { records, nextCursor };
3128
3410
  });
3129
3411
  const transition = Effect11.fn("ExecutionRepository.transition")(function* (input) {
3130
3412
  const tenantId2 = yield* current;
3131
- const rows = yield* mapDatabaseError7(db.update(relayExecutions).set({
3132
- status: input.status,
3133
- metadataJson: metadata4(input.metadata),
3134
- updatedAt: toPgDate(input.updatedAt)
3135
- }).where(predicate(tenantId2, relayExecutions.tenantId, eq8(relayExecutions.id, input.id))).returning());
3413
+ const rows = yield* updateExecution(tenantId2, input).pipe(Effect11.mapError(toRepositoryError3));
3136
3414
  const row = rows[0];
3137
3415
  if (row === undefined)
3138
3416
  return yield* Effect11.fail(new ExecutionNotFound({ id: input.id }));
3139
- return toRecord5(row);
3417
+ return toRecord5(yield* decodeRow2(row));
3140
3418
  });
3141
3419
  return Service11.of({ create: create2, get: get5, list: list5, transition });
3142
3420
  }));
@@ -3211,7 +3489,7 @@ var transition = Effect11.fn("ExecutionRepository.transition.call")(function* (i
3211
3489
  return yield* repository.transition(input);
3212
3490
  });
3213
3491
  // ../store-sql/src/idempotency/idempotency-repository.ts
3214
- import { eq as eq9, sql as sql7 } from "drizzle-orm";
3492
+ import { eq as eq7, sql as sql6 } from "drizzle-orm";
3215
3493
  import { Context as Context12, Effect as Effect12, HashMap, Layer as Layer12, Option as Option3, Ref, Schema as Schema22, Semaphore } from "effect";
3216
3494
  class IdempotencyRepositoryError extends Schema22.TaggedErrorClass()("IdempotencyRepositoryError", {
3217
3495
  message: Schema22.String
@@ -3234,7 +3512,7 @@ var toRecord6 = (row) => {
3234
3512
  ...expiresAt === undefined ? {} : { expiresAt }
3235
3513
  };
3236
3514
  };
3237
- var toInsert3 = (tenantId2, input, result) => ({
3515
+ var toInsert2 = (tenantId2, input, result) => ({
3238
3516
  tenantId: tenantId2,
3239
3517
  id: operationId(input),
3240
3518
  scope: input.scope,
@@ -3251,17 +3529,17 @@ var layer12 = Layer12.effect(Service12, Effect12.gen(function* () {
3251
3529
  const runOnce = (input, create3) => Effect12.gen(function* () {
3252
3530
  const tenantId2 = yield* current;
3253
3531
  return yield* db.transaction((tx) => Effect12.gen(function* () {
3254
- yield* tx.execute(sql7`select pg_advisory_xact_lock(hashtextextended(${`${tenantId2}:${operationId(input)}`}, 0))`);
3255
- const existingRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq9(relayIdempotencyKeys.scope, input.scope), eq9(relayIdempotencyKeys.operation, input.operation), eq9(relayIdempotencyKeys.key, input.key))).limit(1);
3532
+ yield* tx.execute(sql6`select pg_advisory_xact_lock(hashtextextended(${`${tenantId2}:${operationId(input)}`}, 0))`);
3533
+ const existingRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq7(relayIdempotencyKeys.scope, input.scope), eq7(relayIdempotencyKeys.operation, input.operation), eq7(relayIdempotencyKeys.key, input.key))).limit(1);
3256
3534
  const existing = existingRows[0];
3257
3535
  if (existing !== undefined)
3258
3536
  return { replayed: true, record: toRecord6(existing) };
3259
3537
  const result = yield* create3;
3260
- const rows = yield* tx.insert(relayIdempotencyKeys).values(toInsert3(tenantId2, input, result)).onConflictDoNothing().returning();
3538
+ const rows = yield* tx.insert(relayIdempotencyKeys).values(toInsert2(tenantId2, input, result)).onConflictDoNothing().returning();
3261
3539
  const row = rows[0];
3262
3540
  if (row !== undefined)
3263
3541
  return { replayed: false, record: toRecord6(row) };
3264
- const winnerRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq9(relayIdempotencyKeys.scope, input.scope), eq9(relayIdempotencyKeys.operation, input.operation), eq9(relayIdempotencyKeys.key, input.key))).limit(1);
3542
+ const winnerRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq7(relayIdempotencyKeys.scope, input.scope), eq7(relayIdempotencyKeys.operation, input.operation), eq7(relayIdempotencyKeys.key, input.key))).limit(1);
3265
3543
  const winner = winnerRows[0];
3266
3544
  if (winner === undefined) {
3267
3545
  return yield* Effect12.fail(new IdempotencyRepositoryError({ message: "Idempotency insert returned no row" }));
@@ -3311,7 +3589,7 @@ __export(exports_memory_repository, {
3311
3589
  Service: () => Service13,
3312
3590
  MemoryRepositoryError: () => MemoryRepositoryError
3313
3591
  });
3314
- import { sql as sql8 } from "drizzle-orm";
3592
+ import { sql as sql7 } from "drizzle-orm";
3315
3593
  import { Context as Context13, Effect as Effect13, Layer as Layer13, Ref as Ref2, Schema as Schema23 } from "effect";
3316
3594
  class MemoryRepositoryError extends Schema23.TaggedErrorClass()("MemoryRepositoryError", {
3317
3595
  message: Schema23.String
@@ -3338,7 +3616,7 @@ var queryRowToRecord = (row) => ({
3338
3616
  metadata: row.metadataJson,
3339
3617
  createdAt: fromPgDate(row.createdAt)
3340
3618
  });
3341
- var mapDatabaseError8 = (effect) => effect.pipe(Effect13.mapError((error) => new MemoryRepositoryError({ message: String(error) })));
3619
+ var mapDatabaseError6 = (effect) => effect.pipe(Effect13.mapError((error) => new MemoryRepositoryError({ message: String(error) })));
3342
3620
  var parsePgFloatArray = (value) => {
3343
3621
  const body = value.startsWith("{") && value.endsWith("}") ? value.slice(1, -1) : value;
3344
3622
  if (body.length === 0)
@@ -3382,7 +3660,7 @@ var layer13 = Layer13.effect(Service13, Effect13.gen(function* () {
3382
3660
  const upsert2 = Effect13.fn("MemoryRepository.upsert")(function* (input) {
3383
3661
  const tenantId2 = yield* current;
3384
3662
  yield* validateVector("embedding", input.embedding);
3385
- const rows = yield* mapDatabaseError8(db.insert(relayMemoryRecords).values({
3663
+ const rows = yield* mapDatabaseError6(db.insert(relayMemoryRecords).values({
3386
3664
  tenantId: tenantId2,
3387
3665
  id: input.id,
3388
3666
  agent: input.agent,
@@ -3412,8 +3690,8 @@ var layer13 = Layer13.effect(Service13, Effect13.gen(function* () {
3412
3690
  yield* validateVector("query embedding", input.embedding);
3413
3691
  if (input.topK <= 0)
3414
3692
  return [];
3415
- const queryEmbeddingSql = sql8`array[${sql8.join(input.embedding.map((value) => sql8`${value}`), sql8`, `)}]::double precision[]`;
3416
- const rows = yield* mapDatabaseError8(db.execute(sql8`
3693
+ const queryEmbeddingSql = sql7`array[${sql7.join(input.embedding.map((value) => sql7`${value}`), sql7`, `)}]::double precision[]`;
3694
+ const rows = yield* mapDatabaseError6(db.execute(sql7`
3417
3695
  with query_embedding as (
3418
3696
  select ${queryEmbeddingSql} as embedding
3419
3697
  ),
@@ -3553,7 +3831,7 @@ __export(exports_permission_rule_repository, {
3553
3831
  Service: () => Service14,
3554
3832
  PermissionRuleRepositoryError: () => PermissionRuleRepositoryError
3555
3833
  });
3556
- import { asc as asc7, eq as eq10 } from "drizzle-orm";
3834
+ import { asc as asc6, eq as eq8 } from "drizzle-orm";
3557
3835
  import { Context as Context14, Effect as Effect14, Layer as Layer14, Schema as Schema24 } from "effect";
3558
3836
  class PermissionRuleRepositoryError extends Schema24.TaggedErrorClass()("PermissionRuleRepositoryError", {
3559
3837
  message: Schema24.String
@@ -3568,13 +3846,13 @@ var toRecord8 = (row) => ({
3568
3846
  rule: row.ruleJson,
3569
3847
  createdAt: fromPgDate(row.createdAt)
3570
3848
  });
3571
- var mapDatabaseError9 = (effect) => effect.pipe(Effect14.mapError((error) => new PermissionRuleRepositoryError({ message: String(error) })));
3849
+ var mapDatabaseError7 = (effect) => effect.pipe(Effect14.mapError((error) => new PermissionRuleRepositoryError({ message: String(error) })));
3572
3850
  var memoryKey = (agent, scope, pattern) => `${agent}\x00${scope}\x00${pattern}`;
3573
3851
  var layer14 = Layer14.effect(Service14, Effect14.gen(function* () {
3574
3852
  const db = yield* Service;
3575
3853
  const remember = Effect14.fn("PermissionRuleRepository.remember")(function* (input) {
3576
3854
  const tenantId2 = yield* current;
3577
- const rows = yield* mapDatabaseError9(db.insert(relayPermissionRules).values({
3855
+ const rows = yield* mapDatabaseError7(db.insert(relayPermissionRules).values({
3578
3856
  tenantId: tenantId2,
3579
3857
  agent: input.agent,
3580
3858
  scope: input.scope,
@@ -3601,7 +3879,7 @@ var layer14 = Layer14.effect(Service14, Effect14.gen(function* () {
3601
3879
  });
3602
3880
  const list6 = Effect14.fn("PermissionRuleRepository.list")(function* (input) {
3603
3881
  const tenantId2 = yield* current;
3604
- const rows = yield* mapDatabaseError9(db.select().from(relayPermissionRules).where(predicate(tenantId2, relayPermissionRules.tenantId, eq10(relayPermissionRules.agent, input.agent), eq10(relayPermissionRules.scope, input.scope))).orderBy(asc7(relayPermissionRules.createdAt), asc7(relayPermissionRules.pattern)));
3882
+ const rows = yield* mapDatabaseError7(db.select().from(relayPermissionRules).where(predicate(tenantId2, relayPermissionRules.tenantId, eq8(relayPermissionRules.agent, input.agent), eq8(relayPermissionRules.scope, input.scope))).orderBy(asc6(relayPermissionRules.createdAt), asc6(relayPermissionRules.pattern)));
3605
3883
  return rows.map(toRecord8);
3606
3884
  });
3607
3885
  return Service14.of({ remember, list: list6 });
@@ -3644,7 +3922,7 @@ __export(exports_context_epoch_repository, {
3644
3922
  Service: () => Service15,
3645
3923
  ContextEpochRepositoryError: () => ContextEpochRepositoryError
3646
3924
  });
3647
- import { eq as eq11 } from "drizzle-orm";
3925
+ import { eq as eq9 } from "drizzle-orm";
3648
3926
  import { Context as Context15, Effect as Effect15, Layer as Layer15, Schema as Schema25 } from "effect";
3649
3927
  class ContextEpochRepositoryError extends Schema25.TaggedErrorClass()("ContextEpochRepositoryError", {
3650
3928
  message: Schema25.String
@@ -3659,7 +3937,7 @@ var toRecord9 = (row) => ({
3659
3937
  dynamicSourceIds: row.dynamicSourceIdsJson,
3660
3938
  openedAt: fromPgDate(row.openedAt)
3661
3939
  });
3662
- var mapDatabaseError10 = (effect) => effect.pipe(Effect15.mapError((error) => new ContextEpochRepositoryError({ message: String(error) })));
3940
+ var mapDatabaseError8 = (effect) => effect.pipe(Effect15.mapError((error) => new ContextEpochRepositoryError({ message: String(error) })));
3663
3941
  var sameEpoch = (record2, input) => record2.baseline === input.baseline && JSON.stringify(record2.dynamicSourceIds) === JSON.stringify(input.dynamicSourceIds);
3664
3942
  var conflict2 = (executionId) => new ContextEpochRepositoryError({ message: `Context epoch already exists with different payload: ${executionId}` });
3665
3943
  var cloneRecord5 = (record2) => structuredClone(record2);
@@ -3667,12 +3945,12 @@ var layer15 = Layer15.effect(Service15, Effect15.gen(function* () {
3667
3945
  const db = yield* Service;
3668
3946
  const get6 = Effect15.fn("ContextEpochRepository.get")(function* (executionId) {
3669
3947
  const tenantId2 = yield* current;
3670
- const rows = yield* mapDatabaseError10(db.select().from(relayExecutionContextEpochs).where(predicate(tenantId2, relayExecutionContextEpochs.tenantId, eq11(relayExecutionContextEpochs.executionId, executionId))).limit(1));
3948
+ const rows = yield* mapDatabaseError8(db.select().from(relayExecutionContextEpochs).where(predicate(tenantId2, relayExecutionContextEpochs.tenantId, eq9(relayExecutionContextEpochs.executionId, executionId))).limit(1));
3671
3949
  return rows[0] === undefined ? undefined : toRecord9(rows[0]);
3672
3950
  });
3673
3951
  const save2 = Effect15.fn("ContextEpochRepository.save")(function* (input) {
3674
3952
  const tenantId2 = yield* current;
3675
- const rows = yield* mapDatabaseError10(db.insert(relayExecutionContextEpochs).values({
3953
+ const rows = yield* mapDatabaseError8(db.insert(relayExecutionContextEpochs).values({
3676
3954
  tenantId: tenantId2,
3677
3955
  executionId: input.executionId,
3678
3956
  baseline: input.baseline,
@@ -3746,7 +4024,7 @@ __export(exports_schedule_repository, {
3746
4024
  ScheduleNotFound: () => ScheduleNotFound,
3747
4025
  ScheduleClaimMismatch: () => ScheduleClaimMismatch
3748
4026
  });
3749
- import { and as and4, asc as asc8, eq as eq12, inArray as inArray2, lte as lte2, or as or4, sql as sql9 } from "drizzle-orm";
4027
+ import { and as and2, asc as asc7, eq as eq10, inArray, lte, or as or2, sql as sql8 } from "drizzle-orm";
3750
4028
  import { Context as Context16, Effect as Effect16, Layer as Layer16, Schema as Schema26 } from "effect";
3751
4029
  class ScheduleRepositoryError extends Schema26.TaggedErrorClass()("ScheduleRepositoryError", {
3752
4030
  message: Schema26.String
@@ -3782,7 +4060,7 @@ var validationError = (input) => {
3782
4060
  }
3783
4061
  return;
3784
4062
  };
3785
- var toInsert4 = (tenantId2, input) => ({
4063
+ var toInsert3 = (tenantId2, input) => ({
3786
4064
  tenantId: tenantId2,
3787
4065
  id: input.id,
3788
4066
  kind: input.kind,
@@ -3813,12 +4091,12 @@ var toRecord10 = (row) => ({
3813
4091
  created_at: fromPgDate(row.createdAt),
3814
4092
  updated_at: fromPgDate(row.updatedAt)
3815
4093
  });
3816
- var mapDatabaseError11 = (effect) => effect.pipe(Effect16.mapError((error) => new ScheduleRepositoryError({ message: String(error) })));
4094
+ var mapDatabaseError9 = (effect) => effect.pipe(Effect16.mapError((error) => new ScheduleRepositoryError({ message: String(error) })));
3817
4095
  var cancellableStates = new Set(["active", "claimed"]);
3818
4096
  var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3819
4097
  const db = yield* Service;
3820
- const getRow = (tenantId2, id2) => mapDatabaseError11(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq12(relaySchedules.id, id2))).limit(1)).pipe(Effect16.map((rows) => rows[0]));
3821
- const getByIdempotencyKey = (tenantId2, key2) => mapDatabaseError11(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq12(relaySchedules.idempotencyKey, key2))).limit(1)).pipe(Effect16.map((rows) => rows[0]));
4098
+ const getRow = (tenantId2, id2) => mapDatabaseError9(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq10(relaySchedules.id, id2))).limit(1)).pipe(Effect16.map((rows) => rows[0]));
4099
+ const getByIdempotencyKey = (tenantId2, key2) => mapDatabaseError9(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq10(relaySchedules.idempotencyKey, key2))).limit(1)).pipe(Effect16.map((rows) => rows[0]));
3822
4100
  const create3 = Effect16.fn("ScheduleRepository.create")(function* (input) {
3823
4101
  const tenantId2 = yield* current;
3824
4102
  const invalid = validationError(input);
@@ -3829,7 +4107,7 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3829
4107
  if (existing !== undefined)
3830
4108
  return toRecord10(existing);
3831
4109
  }
3832
- const rows = yield* mapDatabaseError11(db.insert(relaySchedules).values(toInsert4(tenantId2, input)).returning());
4110
+ const rows = yield* mapDatabaseError9(db.insert(relaySchedules).values(toInsert3(tenantId2, input)).returning());
3833
4111
  const row = rows[0];
3834
4112
  if (row === undefined) {
3835
4113
  return yield* Effect16.fail(new ScheduleRepositoryError({ message: `Schedule ${input.id} was not persisted` }));
@@ -3843,17 +4121,17 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3843
4121
  });
3844
4122
  const list7 = Effect16.fn("ScheduleRepository.list")(function* (input) {
3845
4123
  const tenantId2 = yield* current;
3846
- const rows = yield* mapDatabaseError11(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, input.state === undefined ? undefined : eq12(relaySchedules.state, input.state))).orderBy(asc8(relaySchedules.nextRunAt), asc8(relaySchedules.createdAt)));
4124
+ const rows = yield* mapDatabaseError9(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, input.state === undefined ? undefined : eq10(relaySchedules.state, input.state))).orderBy(asc7(relaySchedules.nextRunAt), asc7(relaySchedules.createdAt)));
3847
4125
  return rows.map(toRecord10);
3848
4126
  });
3849
4127
  const cancel = Effect16.fn("ScheduleRepository.cancel")(function* (input) {
3850
4128
  const tenantId2 = yield* current;
3851
- const rows = yield* mapDatabaseError11(db.update(relaySchedules).set({
4129
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3852
4130
  state: "cancelled",
3853
4131
  claimOwner: null,
3854
4132
  claimExpiresAt: null,
3855
4133
  updatedAt: toPgDate(input.cancelledAt)
3856
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq12(relaySchedules.id, input.id), inArray2(relaySchedules.state, [...cancellableStates]))).returning());
4134
+ }).where(predicate(tenantId2, relaySchedules.tenantId, eq10(relaySchedules.id, input.id), inArray(relaySchedules.state, [...cancellableStates]))).returning());
3857
4135
  const row = rows[0];
3858
4136
  if (row !== undefined)
3859
4137
  return toRecord10(row);
@@ -3866,23 +4144,23 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3866
4144
  });
3867
4145
  const claimDue = Effect16.fn("ScheduleRepository.claimDue")(function* (input) {
3868
4146
  const tenantId2 = yield* current;
3869
- const candidate = db.select({ id: relaySchedules.id }).from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, or4(and4(eq12(relaySchedules.state, "active"), lte2(relaySchedules.nextRunAt, toPgDate(input.now))), and4(eq12(relaySchedules.state, "claimed"), lte2(relaySchedules.claimExpiresAt, toPgDate(input.now)))))).orderBy(asc8(relaySchedules.nextRunAt), asc8(relaySchedules.createdAt)).limit(1).for("update", { skipLocked: true });
3870
- const rows = yield* mapDatabaseError11(db.update(relaySchedules).set({
4147
+ const candidate = db.select({ id: relaySchedules.id }).from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, or2(and2(eq10(relaySchedules.state, "active"), lte(relaySchedules.nextRunAt, toPgDate(input.now))), and2(eq10(relaySchedules.state, "claimed"), lte(relaySchedules.claimExpiresAt, toPgDate(input.now)))))).orderBy(asc7(relaySchedules.nextRunAt), asc7(relaySchedules.createdAt)).limit(1).for("update", { skipLocked: true });
4148
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3871
4149
  state: "claimed",
3872
4150
  claimOwner: input.workerId,
3873
4151
  claimExpiresAt: toPgDate(input.claimExpiresAt),
3874
4152
  updatedAt: toPgDate(input.now),
3875
- attempt: sql9`${relaySchedules.attempt} + 1`
3876
- }).where(predicate(tenantId2, relaySchedules.tenantId, inArray2(relaySchedules.id, candidate))).returning());
4153
+ attempt: sql8`${relaySchedules.attempt} + 1`
4154
+ }).where(predicate(tenantId2, relaySchedules.tenantId, inArray(relaySchedules.id, candidate))).returning());
3877
4155
  return rows[0] === undefined ? undefined : toRecord10(rows[0]);
3878
4156
  });
3879
4157
  const ack = Effect16.fn("ScheduleRepository.ack")(function* (input) {
3880
4158
  const tenantId2 = yield* current;
3881
- const rows = yield* mapDatabaseError11(db.update(relaySchedules).set({
4159
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3882
4160
  ...input.nextRunAt === undefined ? { state: "completed" } : { state: "active", nextRunAt: toPgDate(input.nextRunAt), claimOwner: null },
3883
4161
  claimExpiresAt: null,
3884
4162
  updatedAt: toPgDate(input.now)
3885
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq12(relaySchedules.id, input.id), eq12(relaySchedules.claimOwner, input.workerId), eq12(relaySchedules.state, "claimed"))).returning());
4163
+ }).where(predicate(tenantId2, relaySchedules.tenantId, eq10(relaySchedules.id, input.id), eq10(relaySchedules.claimOwner, input.workerId), eq10(relaySchedules.state, "claimed"))).returning());
3886
4164
  const row = rows[0];
3887
4165
  if (row !== undefined)
3888
4166
  return toRecord10(row);
@@ -3895,14 +4173,14 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3895
4173
  });
3896
4174
  const release = Effect16.fn("ScheduleRepository.release")(function* (input) {
3897
4175
  const tenantId2 = yield* current;
3898
- const rows = yield* mapDatabaseError11(db.update(relaySchedules).set({
4176
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3899
4177
  state: "active",
3900
4178
  nextRunAt: toPgDate(input.nextAvailableAt),
3901
4179
  claimOwner: null,
3902
4180
  claimExpiresAt: null,
3903
4181
  lastError: input.error,
3904
4182
  updatedAt: toPgDate(input.nextAvailableAt)
3905
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq12(relaySchedules.id, input.id), eq12(relaySchedules.claimOwner, input.workerId), eq12(relaySchedules.state, "claimed"))).returning());
4183
+ }).where(predicate(tenantId2, relaySchedules.tenantId, eq10(relaySchedules.id, input.id), eq10(relaySchedules.claimOwner, input.workerId), eq10(relaySchedules.state, "claimed"))).returning());
3906
4184
  const row = rows[0];
3907
4185
  if (row !== undefined)
3908
4186
  return toRecord10(row);
@@ -4079,12 +4357,14 @@ __export(exports_session_repository, {
4079
4357
  create: () => create4,
4080
4358
  countEntries: () => countEntries,
4081
4359
  appendEntry: () => appendEntry,
4360
+ SessionRow: () => SessionRow,
4082
4361
  SessionRepositoryError: () => SessionRepositoryError,
4362
+ SessionEntryRow: () => SessionEntryRow,
4083
4363
  Service: () => Service17,
4084
4364
  DuplicateSession: () => DuplicateSession
4085
4365
  });
4086
- import { and as and5, count, desc as desc5, eq as eq13, lt as lt2, or as or5 } from "drizzle-orm";
4087
4366
  import { Context as Context17, Effect as Effect17, Layer as Layer17, Schema as Schema27 } from "effect";
4367
+ import * as SqlClient10 from "effect/unstable/sql/SqlClient";
4088
4368
  class SessionRepositoryError extends Schema27.TaggedErrorClass()("SessionRepositoryError", {
4089
4369
  message: Schema27.String
4090
4370
  }) {
@@ -4097,14 +4377,33 @@ class DuplicateSession extends Schema27.TaggedErrorClass()("DuplicateSession", {
4097
4377
 
4098
4378
  class Service17 extends Context17.Service()("@relayfx/store-sql/SessionRepository") {
4099
4379
  }
4380
+ var SessionRow = Schema27.Struct({
4381
+ id: Schema27.String,
4382
+ root_address_id: Schema27.String,
4383
+ leaf_entry_id: Schema27.Union([Schema27.String, Schema27.Null, Schema27.Undefined]),
4384
+ metadata_json: Schema27.Unknown,
4385
+ created_at: Schema27.Union([Schema27.Date, Schema27.String, Schema27.Number]),
4386
+ updated_at: Schema27.Union([Schema27.Date, Schema27.String, Schema27.Number])
4387
+ }).annotate({ identifier: "Relay.Session.Row" });
4388
+ var SessionEntryRow = Schema27.Struct({
4389
+ id: Schema27.String,
4390
+ session_id: Schema27.String,
4391
+ parent_id: Schema27.Union([Schema27.String, Schema27.Null, Schema27.Undefined]),
4392
+ tag: Schema27.String,
4393
+ payload_json: Schema27.Unknown,
4394
+ created_at: Schema27.Union([Schema27.Date, Schema27.String, Schema27.Number])
4395
+ }).annotate({ identifier: "Relay.SessionEntry.Row" });
4396
+ var CountRow = Schema27.Struct({
4397
+ value: Schema27.Union([Schema27.Number, Schema27.String, Schema27.BigInt])
4398
+ }).annotate({ identifier: "Relay.SessionEntry.CountRow" });
4100
4399
  var metadata7 = (input) => input ?? {};
4101
4400
  var toSessionRecord = (row) => ({
4102
- id: row.id,
4103
- rootAddressId: row.rootAddressId,
4104
- ...row.leafEntryId === null || row.leafEntryId === undefined ? {} : { leafEntryId: row.leafEntryId },
4105
- metadata: row.metadataJson,
4106
- createdAt: fromPgDate(row.createdAt),
4107
- updatedAt: fromPgDate(row.updatedAt)
4401
+ id: exports_ids_schema.SessionId.make(row.id),
4402
+ rootAddressId: exports_ids_schema.AddressId.make(row.root_address_id),
4403
+ ...row.leaf_entry_id === null || row.leaf_entry_id === undefined ? {} : { leafEntryId: exports_ids_schema.SessionEntryId.make(row.leaf_entry_id) },
4404
+ metadata: decodeJson(row.metadata_json),
4405
+ createdAt: fromDbTimestamp(row.created_at),
4406
+ updatedAt: fromDbTimestamp(row.updated_at)
4108
4407
  });
4109
4408
  var payloadFromInput = (input) => {
4110
4409
  switch (input._tag) {
@@ -4127,12 +4426,12 @@ var payloadFromInput = (input) => {
4127
4426
  }
4128
4427
  };
4129
4428
  var toEntryRecord = (row) => {
4130
- const payload = row.payloadJson;
4429
+ const payload = decodeJson(row.payload_json);
4131
4430
  const base = {
4132
- id: row.id,
4133
- sessionId: row.sessionId,
4134
- parentId: row.parentId,
4135
- createdAt: fromPgDate(row.createdAt),
4431
+ id: exports_ids_schema.SessionEntryId.make(row.id),
4432
+ sessionId: exports_ids_schema.SessionId.make(row.session_id),
4433
+ parentId: row.parent_id === null || row.parent_id === undefined ? null : exports_ids_schema.SessionEntryId.make(row.parent_id),
4434
+ createdAt: fromDbTimestamp(row.created_at),
4136
4435
  ...payload.metadata === undefined ? {} : { metadata: payload.metadata }
4137
4436
  };
4138
4437
  switch (row.tag) {
@@ -4159,8 +4458,11 @@ var toEntryRecord = (row) => {
4159
4458
  return Effect17.fail(new SessionRepositoryError({ message: `Unknown session entry tag: ${row.tag}` }));
4160
4459
  }
4161
4460
  };
4162
- var mapDatabaseError12 = (effect) => effect.pipe(Effect17.mapError((error) => new SessionRepositoryError({ message: String(error) })));
4163
- var mapWriteError = (effect) => effect.pipe(Effect17.mapError((error) => error instanceof SessionRepositoryError ? error : new SessionRepositoryError({ message: String(error) })));
4461
+ var toRepositoryError4 = (error) => error instanceof SessionRepositoryError ? error : new SessionRepositoryError({ message: String(error) });
4462
+ var mapRepositoryError = (effect) => effect.pipe(Effect17.mapError(toRepositoryError4));
4463
+ var decodeSessionRow = (row) => Schema27.decodeUnknownEffect(SessionRow)(row).pipe(Effect17.mapError(toRepositoryError4));
4464
+ var decodeEntryRow = (row) => Schema27.decodeUnknownEffect(SessionEntryRow)(row).pipe(Effect17.mapError(toRepositoryError4));
4465
+ var decodeCountRow = (row) => Schema27.decodeUnknownEffect(CountRow)(row).pipe(Effect17.mapError(toRepositoryError4));
4164
4466
  var maxListLimit3 = 100;
4165
4467
  var defaultListLimit2 = 50;
4166
4468
  var listLimit3 = (input) => Math.min(Math.max(input.limit ?? defaultListLimit2, 1), maxListLimit3);
@@ -4170,10 +4472,6 @@ var nextCursorOf2 = (records, fetched, limit) => {
4170
4472
  };
4171
4473
  var compareDesc2 = (left, right) => right.updatedAt - left.updatedAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
4172
4474
  var afterCursor2 = (record2, cursor) => cursor === undefined || record2.updatedAt < cursor.updatedAt || record2.updatedAt === cursor.updatedAt && record2.id < cursor.id;
4173
- var listConditions2 = (input) => [
4174
- input.rootAddressId === undefined ? undefined : eq13(relaySessions.rootAddressId, input.rootAddressId),
4175
- input.cursor === undefined ? undefined : or5(lt2(relaySessions.updatedAt, toPgDate(input.cursor.updatedAt)), and5(eq13(relaySessions.updatedAt, toPgDate(input.cursor.updatedAt)), lt2(relaySessions.id, input.cursor.id)))
4176
- ].filter((condition) => condition !== undefined);
4177
4475
  var comparableEntry = (entry) => {
4178
4476
  const { createdAt: _createdAt, ...value } = entry;
4179
4477
  return value;
@@ -4214,19 +4512,58 @@ var validateCompaction = (currentPath, input) => {
4214
4512
  return currentPath.some((item) => item.id === entry.firstKeptEntryId) ? Effect17.void : Effect17.fail(missingEntry(entry.firstKeptEntryId));
4215
4513
  };
4216
4514
  var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4217
- const db = yield* Service;
4515
+ const sql9 = yield* SqlClient10.SqlClient;
4516
+ const selectSessionByKey = (tenantId2, id2) => sql9`
4517
+ SELECT id, root_address_id, leaf_entry_id, metadata_json, created_at, updated_at
4518
+ FROM relay_sessions
4519
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
4520
+ `;
4521
+ const selectEntryByKey = (tenantId2, sessionId, id2) => sql9`
4522
+ SELECT id, session_id, parent_id, tag, payload_json, created_at
4523
+ FROM relay_session_entries
4524
+ WHERE tenant_id = ${tenantId2} AND id = ${id2} AND session_id = ${sessionId}
4525
+ `;
4526
+ const insertSession = (tenantId2, input) => sql9`
4527
+ INSERT INTO relay_sessions (tenant_id, id, root_address_id, metadata_json, created_at, updated_at)
4528
+ VALUES (${tenantId2}, ${input.id}, ${input.rootAddressId}, ${encodeJson(metadata7(input.metadata))}, ${timestampParam(sql9, input.timestamp)}, ${timestampParam(sql9, input.timestamp)})
4529
+ `;
4530
+ const touchSession = (tenantId2, id2, updatedAt) => sql9`
4531
+ UPDATE relay_sessions
4532
+ SET updated_at = ${timestampParam(sql9, updatedAt)}
4533
+ WHERE tenant_id = ${tenantId2} AND id = ${id2}
4534
+ `;
4535
+ const updateLeaf = (tenantId2, input) => sql9`
4536
+ UPDATE relay_sessions
4537
+ SET leaf_entry_id = ${input.id}, updated_at = ${timestampParam(sql9, input.updatedAt)}
4538
+ WHERE tenant_id = ${tenantId2} AND id = ${input.sessionId}
4539
+ `;
4540
+ const insertEntryIfAbsent = sql9.onDialectOrElse({
4541
+ mysql: () => (tenantId2, input) => sql9`
4542
+ INSERT IGNORE INTO relay_session_entries (tenant_id, id, session_id, parent_id, tag, payload_json, created_at)
4543
+ VALUES (${tenantId2}, ${input.id}, ${input.sessionId}, ${input.parentId}, ${input.input._tag}, ${encodeJson(payloadFromInput(input.input))}, ${timestampParam(sql9, input.createdAt)})
4544
+ `,
4545
+ orElse: () => (tenantId2, input) => sql9`
4546
+ INSERT INTO relay_session_entries (tenant_id, id, session_id, parent_id, tag, payload_json, created_at)
4547
+ VALUES (${tenantId2}, ${input.id}, ${input.sessionId}, ${input.parentId}, ${input.input._tag}, ${encodeJson(payloadFromInput(input.input))}, ${timestampParam(sql9, input.createdAt)})
4548
+ ON CONFLICT (tenant_id, id) DO NOTHING
4549
+ `
4550
+ });
4218
4551
  const getForTenant = Effect17.fn("SessionRepository.getForTenant")(function* (tenantId2, id2) {
4219
- const rows = yield* mapDatabaseError12(db.select().from(relaySessions).where(predicate(tenantId2, relaySessions.tenantId, eq13(relaySessions.id, id2))).limit(1));
4220
- return rows[0] === undefined ? undefined : toSessionRecord(rows[0]);
4552
+ const rows = yield* mapRepositoryError(selectSessionByKey(tenantId2, id2));
4553
+ return rows[0] === undefined ? undefined : toSessionRecord(yield* decodeSessionRow(rows[0]));
4554
+ });
4555
+ const requireSession = Effect17.fn("SessionRepository.requireSession")(function* (tenantId2, id2) {
4556
+ const session = yield* getForTenant(tenantId2, id2);
4557
+ if (session === undefined)
4558
+ return yield* Effect17.fail(missingSession(id2));
4559
+ return session;
4221
4560
  });
4222
4561
  const entryById = Effect17.fn("SessionRepository.entryById")(function* (tenantId2, sessionId, id2) {
4223
- const rows = yield* mapDatabaseError12(db.select().from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq13(relaySessionEntries.id, id2), eq13(relaySessionEntries.sessionId, sessionId))).limit(1));
4224
- return rows[0] === undefined ? undefined : yield* toEntryRecord(rows[0]);
4562
+ const rows = yield* mapRepositoryError(selectEntryByKey(tenantId2, sessionId, id2));
4563
+ return rows[0] === undefined ? undefined : yield* toEntryRecord(yield* decodeEntryRow(rows[0]));
4225
4564
  });
4226
4565
  const pathForTenant = Effect17.fn("SessionRepository.pathForTenant")(function* (tenantId2, input) {
4227
- const session = yield* getForTenant(tenantId2, input.sessionId);
4228
- if (session === undefined)
4229
- return yield* Effect17.fail(missingSession(input.sessionId));
4566
+ const session = yield* requireSession(tenantId2, input.sessionId);
4230
4567
  const start = input.leafId ?? session.leafEntryId;
4231
4568
  if (start === undefined)
4232
4569
  return [];
@@ -4255,18 +4592,16 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4255
4592
  const existing = yield* getForTenant(tenantId2, input.id);
4256
4593
  if (existing !== undefined)
4257
4594
  return yield* Effect17.fail(new DuplicateSession({ id: input.id }));
4258
- const rows = yield* mapDatabaseError12(db.insert(relaySessions).values({
4259
- tenantId: tenantId2,
4595
+ yield* mapRepositoryError(insertSession(tenantId2, {
4260
4596
  id: input.id,
4261
4597
  rootAddressId: input.rootAddressId,
4262
- metadataJson: metadata7(input.metadata),
4263
- createdAt: toPgDate(input.createdAt),
4264
- updatedAt: toPgDate(input.createdAt)
4265
- }).returning());
4266
- const row = rows[0];
4267
- if (row === undefined)
4598
+ ...input.metadata === undefined ? {} : { metadata: input.metadata },
4599
+ timestamp: input.createdAt
4600
+ }));
4601
+ const created = yield* getForTenant(tenantId2, input.id);
4602
+ if (created === undefined)
4268
4603
  return yield* Effect17.fail(new SessionRepositoryError({ message: "Session insert returned no row" }));
4269
- return toSessionRecord(row);
4604
+ return created;
4270
4605
  });
4271
4606
  const ensure = Effect17.fn("SessionRepository.ensure")(function* (input) {
4272
4607
  const tenantId2 = yield* current;
@@ -4274,24 +4609,19 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4274
4609
  if (existing !== undefined) {
4275
4610
  if (existing.rootAddressId !== input.rootAddressId)
4276
4611
  return yield* Effect17.fail(rootMismatch(input.id));
4277
- const rows2 = yield* mapDatabaseError12(db.update(relaySessions).set({ updatedAt: toPgDate(input.now) }).where(predicate(tenantId2, relaySessions.tenantId, eq13(relaySessions.id, input.id))).returning());
4278
- const row2 = rows2[0];
4279
- if (row2 === undefined)
4280
- return yield* Effect17.fail(missingSession(input.id));
4281
- return toSessionRecord(row2);
4612
+ yield* mapRepositoryError(touchSession(tenantId2, input.id, input.now));
4613
+ return yield* requireSession(tenantId2, input.id);
4282
4614
  }
4283
- const rows = yield* mapDatabaseError12(db.insert(relaySessions).values({
4284
- tenantId: tenantId2,
4615
+ yield* mapRepositoryError(insertSession(tenantId2, {
4285
4616
  id: input.id,
4286
4617
  rootAddressId: input.rootAddressId,
4287
- metadataJson: metadata7(input.metadata),
4288
- createdAt: toPgDate(input.now),
4289
- updatedAt: toPgDate(input.now)
4290
- }).returning());
4291
- const row = rows[0];
4292
- if (row === undefined)
4618
+ ...input.metadata === undefined ? {} : { metadata: input.metadata },
4619
+ timestamp: input.now
4620
+ }));
4621
+ const created = yield* getForTenant(tenantId2, input.id);
4622
+ if (created === undefined)
4293
4623
  return yield* Effect17.fail(new SessionRepositoryError({ message: "Session insert returned no row" }));
4294
- return toSessionRecord(row);
4624
+ return created;
4295
4625
  });
4296
4626
  const get8 = Effect17.fn("SessionRepository.get")(function* (id2) {
4297
4627
  const tenantId2 = yield* current;
@@ -4300,36 +4630,46 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4300
4630
  const list8 = Effect17.fn("SessionRepository.list")(function* (input) {
4301
4631
  const tenantId2 = yield* current;
4302
4632
  const limit = listLimit3(input);
4303
- const rows = yield* mapDatabaseError12(db.select().from(relaySessions).where(predicate(tenantId2, relaySessions.tenantId, ...listConditions2(input))).orderBy(desc5(relaySessions.updatedAt), desc5(relaySessions.id)).limit(limit + 1));
4304
- const records = rows.slice(0, limit).map(toSessionRecord);
4633
+ const conditions = [sql9`tenant_id = ${tenantId2}`];
4634
+ if (input.rootAddressId !== undefined) {
4635
+ conditions.push(sql9`root_address_id = ${input.rootAddressId}`);
4636
+ }
4637
+ if (input.cursor !== undefined) {
4638
+ const cursorTimestamp = timestampParam(sql9, input.cursor.updatedAt);
4639
+ conditions.push(sql9.or([
4640
+ sql9`updated_at < ${cursorTimestamp}`,
4641
+ sql9.and([sql9`updated_at = ${cursorTimestamp}`, sql9`id < ${input.cursor.id}`])
4642
+ ]));
4643
+ }
4644
+ const rows = yield* mapRepositoryError(sql9`
4645
+ SELECT id, root_address_id, leaf_entry_id, metadata_json, created_at, updated_at
4646
+ FROM relay_sessions
4647
+ WHERE ${sql9.and(conditions)}
4648
+ ORDER BY updated_at DESC, id DESC
4649
+ LIMIT ${sql9.literal(String(limit + 1))}
4650
+ `);
4651
+ const records = yield* Effect17.forEach(rows.slice(0, limit), (row) => decodeSessionRow(row).pipe(Effect17.map(toSessionRecord)));
4305
4652
  const nextCursor = nextCursorOf2(records, rows.length, limit);
4306
4653
  return nextCursor === undefined ? { records } : { records, nextCursor };
4307
4654
  });
4308
4655
  const touch = Effect17.fn("SessionRepository.touch")(function* (input) {
4309
4656
  const tenantId2 = yield* current;
4310
- const rows = yield* mapDatabaseError12(db.update(relaySessions).set({ updatedAt: toPgDate(input.updatedAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq13(relaySessions.id, input.id))).returning());
4311
- const row = rows[0];
4312
- if (row === undefined)
4313
- return yield* Effect17.fail(missingSession(input.id));
4314
- return toSessionRecord(row);
4657
+ yield* mapRepositoryError(touchSession(tenantId2, input.id, input.updatedAt));
4658
+ return yield* requireSession(tenantId2, input.id);
4315
4659
  });
4316
4660
  const leaf = Effect17.fn("SessionRepository.leaf")(function* (sessionId) {
4317
4661
  const tenantId2 = yield* current;
4318
- const session = yield* getForTenant(tenantId2, sessionId);
4319
- if (session === undefined)
4320
- return yield* Effect17.fail(missingSession(sessionId));
4662
+ const session = yield* requireSession(tenantId2, sessionId);
4321
4663
  return session.leafEntryId ?? null;
4322
4664
  });
4323
4665
  const setLeafForTenant = Effect17.fn("SessionRepository.setLeafForTenant")(function* (tenantId2, input) {
4324
- const session = yield* getForTenant(tenantId2, input.sessionId);
4325
- if (session === undefined)
4326
- return yield* Effect17.fail(missingSession(input.sessionId));
4666
+ yield* requireSession(tenantId2, input.sessionId);
4327
4667
  if (input.id !== null) {
4328
4668
  const entry = yield* entryById(tenantId2, input.sessionId, input.id);
4329
4669
  if (entry === undefined)
4330
4670
  return yield* Effect17.fail(missingEntry(input.id));
4331
4671
  }
4332
- yield* mapDatabaseError12(db.update(relaySessions).set({ leafEntryId: input.id, updatedAt: toPgDate(input.updatedAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq13(relaySessions.id, input.sessionId))));
4672
+ yield* mapRepositoryError(updateLeaf(tenantId2, input));
4333
4673
  });
4334
4674
  const setLeaf = Effect17.fn("SessionRepository.setLeaf")(function* (input) {
4335
4675
  const tenantId2 = yield* current;
@@ -4337,9 +4677,7 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4337
4677
  });
4338
4678
  const appendEntry = Effect17.fn("SessionRepository.appendEntry")(function* (input) {
4339
4679
  const tenantId2 = yield* current;
4340
- const session = yield* getForTenant(tenantId2, input.sessionId);
4341
- if (session === undefined)
4342
- return yield* Effect17.fail(missingSession(input.sessionId));
4680
+ const session = yield* requireSession(tenantId2, input.sessionId);
4343
4681
  const existing = yield* entryById(tenantId2, input.sessionId, input.id);
4344
4682
  const desired = appendToRecord(input);
4345
4683
  if (existing !== undefined) {
@@ -4355,27 +4693,18 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4355
4693
  }
4356
4694
  const currentPath = session.leafEntryId === undefined ? [] : yield* pathForTenant(tenantId2, { sessionId: input.sessionId });
4357
4695
  yield* validateCompaction(currentPath, input);
4358
- return yield* mapWriteError(db.transaction((tx) => Effect17.gen(function* () {
4359
- const rows = yield* tx.insert(relaySessionEntries).values({
4360
- tenantId: tenantId2,
4361
- id: input.id,
4362
- sessionId: input.sessionId,
4363
- parentId: input.parentId,
4364
- tag: input.input._tag,
4365
- payloadJson: payloadFromInput(input.input),
4366
- createdAt: toPgDate(input.createdAt)
4367
- }).onConflictDoNothing({ target: [relaySessionEntries.tenantId, relaySessionEntries.id] }).returning();
4368
- const row = rows[0];
4369
- const record2 = row === undefined ? yield* tx.select().from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq13(relaySessionEntries.id, input.id), eq13(relaySessionEntries.sessionId, input.sessionId))).limit(1).pipe(Effect17.flatMap((existingRows) => {
4370
- const existingRow = existingRows[0];
4371
- if (existingRow === undefined) {
4372
- return Effect17.fail(new SessionRepositoryError({ message: "Session entry insert returned no row" }));
4373
- }
4374
- return toEntryRecord(existingRow);
4375
- })) : yield* toEntryRecord(row);
4696
+ return yield* mapRepositoryError(sql9.withTransaction(Effect17.gen(function* () {
4697
+ yield* insertEntryIfAbsent(tenantId2, input);
4698
+ const entryRows = yield* selectEntryByKey(tenantId2, input.sessionId, input.id);
4699
+ const entryRow = entryRows[0];
4700
+ if (entryRow === undefined) {
4701
+ return yield* Effect17.fail(new SessionRepositoryError({ message: "Session entry insert returned no row" }));
4702
+ }
4703
+ const record2 = yield* toEntryRecord(yield* decodeEntryRow(entryRow));
4376
4704
  if (!sameEntry(record2, desired))
4377
4705
  return yield* Effect17.fail(conflictingEntry(input.id));
4378
- const sessionRows = yield* tx.update(relaySessions).set({ leafEntryId: input.id, updatedAt: toPgDate(input.createdAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq13(relaySessions.id, input.sessionId))).returning();
4706
+ yield* updateLeaf(tenantId2, { sessionId: input.sessionId, id: input.id, updatedAt: input.createdAt });
4707
+ const sessionRows = yield* selectSessionByKey(tenantId2, input.sessionId);
4379
4708
  if (sessionRows[0] === undefined)
4380
4709
  return yield* Effect17.fail(missingSession(input.sessionId));
4381
4710
  return record2;
@@ -4383,8 +4712,15 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4383
4712
  });
4384
4713
  const countEntries = Effect17.fn("SessionRepository.countEntries")(function* (sessionId) {
4385
4714
  const tenantId2 = yield* current;
4386
- const rows = yield* mapDatabaseError12(db.select({ value: count() }).from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq13(relaySessionEntries.sessionId, sessionId))));
4387
- return Number(rows[0]?.value ?? 0);
4715
+ const rows = yield* mapRepositoryError(sql9`
4716
+ SELECT COUNT(*) AS value
4717
+ FROM relay_session_entries
4718
+ WHERE tenant_id = ${tenantId2} AND session_id = ${sessionId}
4719
+ `);
4720
+ if (rows[0] === undefined)
4721
+ return 0;
4722
+ const counted = yield* decodeCountRow(rows[0]);
4723
+ return Number(counted.value);
4388
4724
  });
4389
4725
  return Service17.of({ create: create4, ensure, get: get8, list: list8, touch, appendEntry, countEntries, path, setLeaf, leaf });
4390
4726
  }));
@@ -4572,7 +4908,7 @@ __export(exports_skill_definition_repository, {
4572
4908
  SkillDefinitionRepositoryError: () => SkillDefinitionRepositoryError,
4573
4909
  Service: () => Service18
4574
4910
  });
4575
- import { asc as asc9, desc as desc6, eq as eq14, inArray as inArray3, sql as sql10 } from "drizzle-orm";
4911
+ import { asc as asc8, desc as desc3, eq as eq11, inArray as inArray2, sql as sql9 } from "drizzle-orm";
4576
4912
  import { Context as Context18, Effect as Effect18, HashSet, Layer as Layer18, Schema as Schema28, Semaphore as Semaphore2 } from "effect";
4577
4913
  class SkillDefinitionRepositoryError extends Schema28.TaggedErrorClass()("SkillDefinitionRepositoryError", {
4578
4914
  message: Schema28.String
@@ -4635,10 +4971,10 @@ var missingSkillMessage = (requested, records) => {
4635
4971
  const found = HashSet.fromIterable(records.map((record2) => record2.id));
4636
4972
  return `Skill definition not found: ${requested.find((id2) => !HashSet.has(found, id2)) ?? requested[0]}`;
4637
4973
  };
4638
- var mapDatabaseError13 = (effect) => effect.pipe(Effect18.mapError((error) => new SkillDefinitionRepositoryError({ message: String(error) })));
4974
+ var mapDatabaseError10 = (effect) => effect.pipe(Effect18.mapError((error) => new SkillDefinitionRepositoryError({ message: String(error) })));
4639
4975
  var mapPutError2 = (effect) => effect.pipe(Effect18.mapError((error) => error instanceof SkillDefinitionRepositoryError ? error : new SkillDefinitionRepositoryError({ message: String(error) })));
4640
4976
  var skillPinLockKey = (tenantId2, executionId) => `skill-pins:${tenantId2}:${executionId}`;
4641
- var lockExecutionPins = (db, tenantId2, executionId) => mapDatabaseError13(db.execute(sql10`select pg_advisory_xact_lock(hashtext(${skillPinLockKey(tenantId2, executionId)}))`)).pipe(Effect18.asVoid);
4977
+ var lockExecutionPins = (db, tenantId2, executionId) => mapDatabaseError10(db.execute(sql9`select pg_advisory_xact_lock(hashtext(${skillPinLockKey(tenantId2, executionId)}))`)).pipe(Effect18.asVoid);
4642
4978
  var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4643
4979
  const db = yield* Service;
4644
4980
  const put2 = Effect18.fn("SkillDefinitionRepository.put")(function* (input) {
@@ -4656,7 +4992,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4656
4992
  target: [relaySkillDefinitions.tenantId, relaySkillDefinitions.id],
4657
4993
  set: {
4658
4994
  name: input.definition.frontmatter.name,
4659
- currentRevision: sql10`${relaySkillDefinitions.currentRevision} + 1`,
4995
+ currentRevision: sql9`${relaySkillDefinitions.currentRevision} + 1`,
4660
4996
  definitionJson: input.definition,
4661
4997
  updatedAt: toPgDate(input.now)
4662
4998
  }
@@ -4681,32 +5017,32 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4681
5017
  });
4682
5018
  const get9 = Effect18.fn("SkillDefinitionRepository.get")(function* (id2) {
4683
5019
  const tenantId2 = yield* current;
4684
- const rows = yield* mapDatabaseError13(db.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId, eq14(relaySkillDefinitions.id, id2))).limit(1));
5020
+ const rows = yield* mapDatabaseError10(db.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId, eq11(relaySkillDefinitions.id, id2))).limit(1));
4685
5021
  return rows[0] === undefined ? undefined : toRecord11(rows[0]);
4686
5022
  });
4687
5023
  const getRevision2 = Effect18.fn("SkillDefinitionRepository.getRevision")(function* (input) {
4688
5024
  const tenantId2 = yield* current;
4689
- const rows = yield* mapDatabaseError13(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq14(relaySkillDefinitionRevisions.skillDefinitionId, input.id), eq14(relaySkillDefinitionRevisions.revision, input.revision))).limit(1));
5025
+ const rows = yield* mapDatabaseError10(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq11(relaySkillDefinitionRevisions.skillDefinitionId, input.id), eq11(relaySkillDefinitionRevisions.revision, input.revision))).limit(1));
4690
5026
  return rows[0] === undefined ? undefined : toRevisionRecord2(rows[0]);
4691
5027
  });
4692
5028
  const list9 = Effect18.fn("SkillDefinitionRepository.list")(function* () {
4693
5029
  const tenantId2 = yield* current;
4694
- const rows = yield* mapDatabaseError13(db.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId)).orderBy(desc6(relaySkillDefinitions.createdAt), asc9(relaySkillDefinitions.id)));
5030
+ const rows = yield* mapDatabaseError10(db.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId)).orderBy(desc3(relaySkillDefinitions.createdAt), asc8(relaySkillDefinitions.id)));
4695
5031
  return rows.map(toRecord11);
4696
5032
  });
4697
5033
  const listRevisions2 = Effect18.fn("SkillDefinitionRepository.listRevisions")(function* (id2) {
4698
5034
  const tenantId2 = yield* current;
4699
- const rows = yield* mapDatabaseError13(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq14(relaySkillDefinitionRevisions.skillDefinitionId, id2))).orderBy(desc6(relaySkillDefinitionRevisions.revision)));
5035
+ const rows = yield* mapDatabaseError10(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq11(relaySkillDefinitionRevisions.skillDefinitionId, id2))).orderBy(desc3(relaySkillDefinitionRevisions.revision)));
4700
5036
  return rows.map(toRevisionRecord2);
4701
5037
  });
4702
5038
  const listPins = Effect18.fn("SkillDefinitionRepository.listPins")(function* (executionId) {
4703
5039
  const tenantId2 = yield* current;
4704
- const rows = yield* mapDatabaseError13(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq14(relayExecutionSkillPins.executionId, executionId))).orderBy(asc9(relayExecutionSkillPins.skillDefinitionId)));
5040
+ const rows = yield* mapDatabaseError10(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq11(relayExecutionSkillPins.executionId, executionId))).orderBy(asc8(relayExecutionSkillPins.skillDefinitionId)));
4705
5041
  return rows.map(toPinRecord);
4706
5042
  });
4707
5043
  const getPinned = Effect18.fn("SkillDefinitionRepository.getPinned")(function* (input) {
4708
5044
  const tenantId2 = yield* current;
4709
- const rows = yield* mapDatabaseError13(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq14(relayExecutionSkillPins.executionId, input.executionId), eq14(relayExecutionSkillPins.skillDefinitionId, input.skillDefinitionId))).limit(1));
5045
+ const rows = yield* mapDatabaseError10(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq11(relayExecutionSkillPins.executionId, input.executionId), eq11(relayExecutionSkillPins.skillDefinitionId, input.skillDefinitionId))).limit(1));
4710
5046
  return rows[0] === undefined ? undefined : toPinRecord(rows[0]);
4711
5047
  });
4712
5048
  const pinExecution = Effect18.fn("SkillDefinitionRepository.pinExecution")(function* (input) {
@@ -4716,7 +5052,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4716
5052
  return [];
4717
5053
  return yield* mapPutError2(db.transaction((tx) => Effect18.gen(function* () {
4718
5054
  yield* lockExecutionPins(tx, tenantId2, input.executionId);
4719
- const existingRows = yield* tx.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq14(relayExecutionSkillPins.executionId, input.executionId))).orderBy(asc9(relayExecutionSkillPins.skillDefinitionId));
5055
+ const existingRows = yield* tx.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq11(relayExecutionSkillPins.executionId, input.executionId))).orderBy(asc8(relayExecutionSkillPins.skillDefinitionId));
4720
5056
  if (existingRows.length > 0) {
4721
5057
  const existing = existingRows.map(toPinRecord);
4722
5058
  if (!sameIdSet(existing.map((record2) => record2.skillDefinitionId), requestedIds)) {
@@ -4726,7 +5062,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4726
5062
  }
4727
5063
  return existing;
4728
5064
  }
4729
- const currentRows = yield* tx.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId, inArray3(relaySkillDefinitions.id, [...requestedIds])));
5065
+ const currentRows = yield* tx.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId, inArray2(relaySkillDefinitions.id, [...requestedIds])));
4730
5066
  const currentRecords = currentRows.map(toRecord11);
4731
5067
  if (currentRecords.length !== requestedIds.length) {
4732
5068
  return yield* Effect18.fail(new SkillDefinitionRepositoryError({ message: missingSkillMessage(requestedIds, currentRecords) }));
@@ -4873,10 +5209,12 @@ __export(exports_steering_repository, {
4873
5209
  appendForRunning: () => appendForRunning,
4874
5210
  append: () => append2,
4875
5211
  SteeringRepositoryError: () => SteeringRepositoryError,
5212
+ SteeringMessageRow: () => SteeringMessageRow,
5213
+ SteeringDrainRow: () => SteeringDrainRow,
4876
5214
  Service: () => Service19
4877
5215
  });
4878
- import { asc as asc10, eq as eq15, inArray as inArray4, isNull, max as max2, sql as sql11 } from "drizzle-orm";
4879
5216
  import { Context as Context19, Effect as Effect19, Layer as Layer19, Ref as Ref3, Schema as Schema29 } from "effect";
5217
+ import * as SqlClient12 from "effect/unstable/sql/SqlClient";
4880
5218
  class SteeringRepositoryError extends Schema29.TaggedErrorClass()("SteeringRepositoryError", {
4881
5219
  message: Schema29.String
4882
5220
  }) {
@@ -4885,26 +5223,45 @@ class SteeringRepositoryError extends Schema29.TaggedErrorClass()("SteeringRepos
4885
5223
  class Service19 extends Context19.Service()("@relayfx/store-sql/SteeringRepository") {
4886
5224
  }
4887
5225
  var SteeringKindSchema = Schema29.Literals(["steering", "follow_up"]);
4888
- var mapDatabaseError14 = (effect) => effect.pipe(Effect19.mapError((error) => new SteeringRepositoryError({ message: String(error) })));
4889
- var mapTransactionError = (effect) => effect.pipe(Effect19.mapError((error) => error instanceof SteeringRepositoryError ? error : new SteeringRepositoryError({ message: String(error) })));
5226
+ var DbTimestamp2 = Schema29.Union([Schema29.Date, Schema29.String, Schema29.Number]);
5227
+ var SteeringMessageRow = Schema29.Struct({
5228
+ execution_id: Schema29.String,
5229
+ kind: SteeringKindSchema,
5230
+ sequence: Schema29.Union([Schema29.Number, Schema29.String]),
5231
+ content_json: Schema29.Unknown,
5232
+ drain_id: Schema29.NullishOr(Schema29.String),
5233
+ consumed_at: Schema29.NullishOr(DbTimestamp2),
5234
+ created_at: DbTimestamp2
5235
+ }).annotate({ identifier: "Relay.SteeringMessage.Row" });
5236
+ var SteeringDrainRow = Schema29.Struct({
5237
+ execution_id: Schema29.String,
5238
+ kind: SteeringKindSchema,
5239
+ drain_id: Schema29.String,
5240
+ message_sequences_json: Schema29.Unknown,
5241
+ created_at: DbTimestamp2
5242
+ }).annotate({ identifier: "Relay.SteeringDrain.Row" });
5243
+ var toRepositoryError5 = (error) => new SteeringRepositoryError({ message: String(error) });
5244
+ var mapTransactionError = (effect) => effect.pipe(Effect19.mapError((error) => error instanceof SteeringRepositoryError ? error : toRepositoryError5(error)));
5245
+ var decodeMessageRow = (row) => Schema29.decodeUnknownEffect(SteeringMessageRow)(row).pipe(Effect19.mapError(toRepositoryError5));
5246
+ var decodeDrainRow = (row) => Schema29.decodeUnknownEffect(SteeringDrainRow)(row).pipe(Effect19.mapError(toRepositoryError5));
4890
5247
  var toMessageRecord = (row) => {
4891
- const consumedAt = fromNullablePgDate(row.consumedAt);
5248
+ const consumedAt = fromNullableDbTimestamp(row.consumed_at);
4892
5249
  return {
4893
- executionId: exports_ids_schema.ExecutionId.make(row.executionId),
4894
- kind: Schema29.decodeUnknownSync(SteeringKindSchema)(row.kind),
4895
- sequence: row.sequence,
4896
- content: row.contentJson,
4897
- ...row.drainId === null || row.drainId === undefined ? {} : { drainId: row.drainId },
5250
+ executionId: exports_ids_schema.ExecutionId.make(row.execution_id),
5251
+ kind: row.kind,
5252
+ sequence: Number(row.sequence),
5253
+ content: decodeJson(row.content_json),
5254
+ ...row.drain_id === null || row.drain_id === undefined ? {} : { drainId: row.drain_id },
4898
5255
  ...consumedAt === undefined ? {} : { consumedAt },
4899
- createdAt: fromPgDate(row.createdAt)
5256
+ createdAt: fromDbTimestamp(row.created_at)
4900
5257
  };
4901
5258
  };
4902
5259
  var toDrainRecord = (row) => ({
4903
- executionId: exports_ids_schema.ExecutionId.make(row.executionId),
4904
- kind: Schema29.decodeUnknownSync(SteeringKindSchema)(row.kind),
4905
- drainId: row.drainId,
4906
- messageSequences: row.messageSequencesJson,
4907
- createdAt: fromPgDate(row.createdAt)
5260
+ executionId: exports_ids_schema.ExecutionId.make(row.execution_id),
5261
+ kind: row.kind,
5262
+ drainId: row.drain_id,
5263
+ messageSequences: decodeJson(row.message_sequences_json).map(Number),
5264
+ createdAt: fromDbTimestamp(row.created_at)
4908
5265
  });
4909
5266
  var queueKey = (tenantId2, executionId, kind) => JSON.stringify([tenantId2, executionId, kind]);
4910
5267
  var drainKey = (tenantId2, executionId, kind, drainId) => JSON.stringify([tenantId2, executionId, kind, drainId]);
@@ -4923,94 +5280,161 @@ var consumedMessage = (message, input) => ({
4923
5280
  consumedAt: input.consumedAt,
4924
5281
  createdAt: message.createdAt
4925
5282
  });
4926
- var messagesForDrain = (db, tenantId2, drain) => Effect19.gen(function* () {
4927
- if (drain.messageSequences.length === 0)
4928
- return { drain, messages: [] };
4929
- const rows = yield* mapDatabaseError14(db.select().from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq15(relaySteeringMessages.executionId, drain.executionId), eq15(relaySteeringMessages.kind, drain.kind), inArray4(relaySteeringMessages.sequence, [...drain.messageSequences]))).orderBy(asc10(relaySteeringMessages.sequence)));
4930
- return { drain, messages: rows.map(toMessageRecord) };
4931
- });
4932
- var findDrain = (db, tenantId2, input) => Effect19.gen(function* () {
4933
- const rows = yield* mapDatabaseError14(db.select().from(relaySteeringDrains).where(predicate(tenantId2, relaySteeringDrains.tenantId, eq15(relaySteeringDrains.executionId, input.executionId), eq15(relaySteeringDrains.kind, input.kind), eq15(relaySteeringDrains.drainId, input.drainId))).limit(1));
4934
- const row = rows[0];
4935
- return row === undefined ? undefined : toDrainRecord(row);
4936
- });
4937
- var lockQueue = (db, tenantId2, executionId, kind) => mapDatabaseError14(db.execute(sql11`select pg_advisory_xact_lock(hashtext(${queueKey(tenantId2, executionId, kind)}))`)).pipe(Effect19.asVoid);
4938
- var runningExecutionStatus = (db, tenantId2, executionId) => db.select({ status: relayExecutions.status }).from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq15(relayExecutions.id, executionId))).for("update").limit(1).pipe(Effect19.map((rows) => rows[0]?.status));
4939
5283
  var layer19 = Layer19.effect(Service19, Effect19.gen(function* () {
4940
- const db = yield* Service;
4941
- const appendInTransaction = Effect19.fn("SteeringRepository.appendInTransaction")(function* (tx, tenantId2, input) {
4942
- yield* lockQueue(tx, tenantId2, input.executionId, input.kind);
4943
- const sequenceRows = yield* tx.select({ value: max2(relaySteeringMessages.sequence) }).from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq15(relaySteeringMessages.executionId, input.executionId), eq15(relaySteeringMessages.kind, input.kind)));
4944
- const sequence = Number(sequenceRows[0]?.value ?? -1) + 1;
4945
- const rows = yield* tx.insert(relaySteeringMessages).values({
4946
- tenantId: tenantId2,
4947
- executionId: input.executionId,
4948
- kind: input.kind,
4949
- sequence,
4950
- contentJson: input.content,
4951
- createdAt: toPgDate(input.createdAt)
4952
- }).returning();
5284
+ const sql10 = yield* SqlClient12.SqlClient;
5285
+ const lockQueue = sql10.onDialectOrElse({
5286
+ pg: () => (tenantId2, executionId, kind) => sql10`SELECT pg_advisory_xact_lock(hashtext(${queueKey(tenantId2, executionId, kind)}))`.pipe(Effect19.asVoid),
5287
+ orElse: () => () => Effect19.void
5288
+ });
5289
+ const selectMessagesBySequences = (tenantId2, executionId, kind, sequences) => sql10`
5290
+ SELECT execution_id, kind, sequence, content_json, drain_id, consumed_at, created_at
5291
+ FROM relay_steering_messages
5292
+ WHERE tenant_id = ${tenantId2}
5293
+ AND execution_id = ${executionId}
5294
+ AND kind = ${kind}
5295
+ AND ${sql10.in("sequence", sequences)}
5296
+ ORDER BY sequence ASC
5297
+ `;
5298
+ const selectDrain = (tenantId2, input) => sql10`
5299
+ SELECT execution_id, kind, drain_id, message_sequences_json, created_at
5300
+ FROM relay_steering_drains
5301
+ WHERE tenant_id = ${tenantId2}
5302
+ AND execution_id = ${input.executionId}
5303
+ AND kind = ${input.kind}
5304
+ AND drain_id = ${input.drainId}
5305
+ `;
5306
+ const findDrain = Effect19.fn("SteeringRepository.findDrain")(function* (tenantId2, input) {
5307
+ const rows = yield* selectDrain(tenantId2, input).pipe(Effect19.mapError(toRepositoryError5));
5308
+ return rows[0] === undefined ? undefined : toDrainRecord(yield* decodeDrainRow(rows[0]));
5309
+ });
5310
+ const messagesForDrain = Effect19.fn("SteeringRepository.messagesForDrain")(function* (tenantId2, drain) {
5311
+ if (drain.messageSequences.length === 0)
5312
+ return { drain, messages: [] };
5313
+ const rows = yield* selectMessagesBySequences(tenantId2, drain.executionId, drain.kind, [
5314
+ ...drain.messageSequences
5315
+ ]).pipe(Effect19.mapError(toRepositoryError5));
5316
+ const messages = yield* Effect19.forEach(rows, (row) => decodeMessageRow(row).pipe(Effect19.map(toMessageRecord)));
5317
+ return { drain, messages };
5318
+ });
5319
+ const insertMessage = sql10.onDialectOrElse({
5320
+ mysql: () => (tenantId2, input, sequence) => Effect19.gen(function* () {
5321
+ yield* sql10`
5322
+ INSERT INTO relay_steering_messages (tenant_id, execution_id, kind, sequence, content_json, created_at)
5323
+ VALUES (${tenantId2}, ${input.executionId}, ${input.kind}, ${sequence}, ${encodeJson(input.content)}, ${timestampParam(sql10, input.createdAt)})
5324
+ `;
5325
+ return yield* selectMessagesBySequences(tenantId2, input.executionId, input.kind, [sequence]);
5326
+ }),
5327
+ orElse: () => (tenantId2, input, sequence) => sql10`
5328
+ INSERT INTO relay_steering_messages (tenant_id, execution_id, kind, sequence, content_json, created_at)
5329
+ VALUES (${tenantId2}, ${input.executionId}, ${input.kind}, ${sequence}, ${encodeJson(input.content)}, ${timestampParam(sql10, input.createdAt)})
5330
+ RETURNING execution_id, kind, sequence, content_json, drain_id, consumed_at, created_at
5331
+ `
5332
+ });
5333
+ const insertDrain = sql10.onDialectOrElse({
5334
+ mysql: () => (tenantId2, input, sequences) => Effect19.gen(function* () {
5335
+ yield* sql10`
5336
+ INSERT INTO relay_steering_drains (tenant_id, execution_id, kind, drain_id, message_sequences_json, created_at)
5337
+ VALUES (${tenantId2}, ${input.executionId}, ${input.kind}, ${input.drainId}, ${encodeJson(sequences)}, ${timestampParam(sql10, input.createdAt)})
5338
+ `;
5339
+ return yield* selectDrain(tenantId2, input);
5340
+ }),
5341
+ orElse: () => (tenantId2, input, sequences) => sql10`
5342
+ INSERT INTO relay_steering_drains (tenant_id, execution_id, kind, drain_id, message_sequences_json, created_at)
5343
+ VALUES (${tenantId2}, ${input.executionId}, ${input.kind}, ${input.drainId}, ${encodeJson(sequences)}, ${timestampParam(sql10, input.createdAt)})
5344
+ RETURNING execution_id, kind, drain_id, message_sequences_json, created_at
5345
+ `
5346
+ });
5347
+ const selectExecutionStatus = sql10.onDialectOrElse({
5348
+ sqlite: () => (tenantId2, executionId) => sql10`
5349
+ SELECT status
5350
+ FROM relay_executions
5351
+ WHERE tenant_id = ${tenantId2} AND id = ${executionId}
5352
+ LIMIT 1
5353
+ `,
5354
+ orElse: () => (tenantId2, executionId) => sql10`
5355
+ SELECT status
5356
+ FROM relay_executions
5357
+ WHERE tenant_id = ${tenantId2} AND id = ${executionId}
5358
+ LIMIT 1
5359
+ FOR UPDATE
5360
+ `
5361
+ });
5362
+ const appendInTransaction = Effect19.fn("SteeringRepository.appendInTransaction")(function* (tenantId2, input) {
5363
+ yield* lockQueue(tenantId2, input.executionId, input.kind);
5364
+ const sequenceRows = yield* sql10`
5365
+ SELECT COALESCE(MAX(sequence), -1) + 1 AS next_sequence
5366
+ FROM relay_steering_messages
5367
+ WHERE tenant_id = ${tenantId2}
5368
+ AND execution_id = ${input.executionId}
5369
+ AND kind = ${input.kind}
5370
+ `;
5371
+ const sequence = Number(sequenceRows[0]?.next_sequence ?? 0);
5372
+ const rows = yield* insertMessage(tenantId2, input, sequence);
4953
5373
  const row = rows[0];
4954
5374
  if (row === undefined) {
4955
5375
  return yield* Effect19.fail(new SteeringRepositoryError({ message: "Steering message insert returned no row" }));
4956
5376
  }
4957
- return toMessageRecord(row);
5377
+ return toMessageRecord(yield* decodeMessageRow(row));
4958
5378
  });
4959
5379
  const append2 = Effect19.fn("SteeringRepository.append")(function* (input) {
4960
5380
  const tenantId2 = yield* current;
4961
- return yield* mapTransactionError(db.transaction((tx) => appendInTransaction(tx, tenantId2, input)));
5381
+ return yield* sql10.withTransaction(appendInTransaction(tenantId2, input)).pipe(mapTransactionError);
4962
5382
  });
4963
5383
  const appendForRunning = Effect19.fn("SteeringRepository.appendForRunning")(function* (input) {
4964
5384
  const tenantId2 = yield* current;
4965
- return yield* mapTransactionError(db.transaction((tx) => Effect19.gen(function* () {
4966
- const scopedTx = tx;
4967
- const status = yield* runningExecutionStatus(scopedTx, tenantId2, input.executionId);
5385
+ return yield* sql10.withTransaction(Effect19.gen(function* () {
5386
+ const statusRows = yield* selectExecutionStatus(tenantId2, input.executionId);
5387
+ const status = statusRows[0]?.status;
4968
5388
  if (status === undefined) {
4969
5389
  return yield* Effect19.fail(new SteeringRepositoryError({ message: `Execution not found: ${input.executionId}` }));
4970
5390
  }
4971
5391
  if (status !== "running") {
4972
5392
  return yield* Effect19.fail(new SteeringRepositoryError({ message: `Execution is not running: ${input.executionId}` }));
4973
5393
  }
4974
- return yield* appendInTransaction(scopedTx, tenantId2, input);
4975
- })));
5394
+ return yield* appendInTransaction(tenantId2, input);
5395
+ })).pipe(mapTransactionError);
4976
5396
  });
4977
5397
  const drainUnconsumed = Effect19.fn("SteeringRepository.drainUnconsumed")(function* (input) {
4978
5398
  const tenantId2 = yield* current;
4979
- const existing = yield* findDrain(db, tenantId2, input);
5399
+ const existing = yield* findDrain(tenantId2, input);
4980
5400
  if (existing !== undefined)
4981
- return yield* messagesForDrain(db, tenantId2, existing);
4982
- return yield* mapTransactionError(db.transaction((tx) => Effect19.gen(function* () {
4983
- const scopedTx = tx;
4984
- yield* lockQueue(scopedTx, tenantId2, input.executionId, input.kind);
4985
- const existingAfterLock = yield* findDrain(scopedTx, tenantId2, input);
5401
+ return yield* messagesForDrain(tenantId2, existing);
5402
+ return yield* sql10.withTransaction(Effect19.gen(function* () {
5403
+ yield* lockQueue(tenantId2, input.executionId, input.kind);
5404
+ const existingAfterLock = yield* findDrain(tenantId2, input);
4986
5405
  if (existingAfterLock !== undefined)
4987
- return yield* messagesForDrain(scopedTx, tenantId2, existingAfterLock);
4988
- const query2 = tx.select().from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq15(relaySteeringMessages.executionId, input.executionId), eq15(relaySteeringMessages.kind, input.kind), isNull(relaySteeringMessages.consumedAt))).orderBy(asc10(relaySteeringMessages.sequence));
4989
- const rows = input.mode === "one-at-a-time" ? yield* query2.limit(1) : yield* query2;
4990
- const sequences = rows.map((row) => row.sequence);
4991
- const messages = sequences.length === 0 ? [] : yield* tx.update(relaySteeringMessages).set({
4992
- drainId: input.drainId,
4993
- consumedAt: toPgDate(input.consumedAt)
4994
- }).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq15(relaySteeringMessages.executionId, input.executionId), eq15(relaySteeringMessages.kind, input.kind), inArray4(relaySteeringMessages.sequence, sequences))).returning();
4995
- const messageBySequence = new Map(messages.map((message) => [message.sequence, message]));
4996
- const orderedMessages = sequences.flatMap((sequence) => {
4997
- const message = messageBySequence.get(sequence);
4998
- return message === undefined ? [] : [message];
4999
- });
5000
- const drainRows = yield* tx.insert(relaySteeringDrains).values({
5001
- tenantId: tenantId2,
5002
- executionId: input.executionId,
5003
- kind: input.kind,
5004
- drainId: input.drainId,
5005
- messageSequencesJson: sequences,
5006
- createdAt: toPgDate(input.createdAt)
5007
- }).returning();
5406
+ return yield* messagesForDrain(tenantId2, existingAfterLock);
5407
+ const unconsumedRows = yield* sql10`
5408
+ SELECT execution_id, kind, sequence, content_json, drain_id, consumed_at, created_at
5409
+ FROM relay_steering_messages
5410
+ WHERE tenant_id = ${tenantId2}
5411
+ AND execution_id = ${input.executionId}
5412
+ AND kind = ${input.kind}
5413
+ AND consumed_at IS NULL
5414
+ ORDER BY sequence ASC
5415
+ ${input.mode === "one-at-a-time" ? sql10.literal("LIMIT 1") : sql10.literal("")}
5416
+ `;
5417
+ const unconsumed = yield* Effect19.forEach(unconsumedRows, decodeMessageRow);
5418
+ const sequences = unconsumed.map((row) => Number(row.sequence));
5419
+ if (sequences.length > 0) {
5420
+ yield* sql10`
5421
+ UPDATE relay_steering_messages
5422
+ SET drain_id = ${input.drainId}, consumed_at = ${timestampParam(sql10, input.consumedAt)}
5423
+ WHERE tenant_id = ${tenantId2}
5424
+ AND execution_id = ${input.executionId}
5425
+ AND kind = ${input.kind}
5426
+ AND ${sql10.in("sequence", sequences)}
5427
+ `;
5428
+ }
5429
+ const messageRows = sequences.length === 0 ? [] : yield* selectMessagesBySequences(tenantId2, input.executionId, input.kind, sequences);
5430
+ const messages = yield* Effect19.forEach(messageRows, (row) => decodeMessageRow(row).pipe(Effect19.map(toMessageRecord)));
5431
+ const drainRows = yield* insertDrain(tenantId2, input, sequences);
5008
5432
  const drainRow = drainRows[0];
5009
5433
  if (drainRow === undefined) {
5010
5434
  return yield* Effect19.fail(new SteeringRepositoryError({ message: "Steering drain insert returned no row" }));
5011
5435
  }
5012
- return { drain: toDrainRecord(drainRow), messages: orderedMessages.map(toMessageRecord) };
5013
- })));
5436
+ return { drain: toDrainRecord(yield* decodeDrainRow(drainRow)), messages };
5437
+ })).pipe(mapTransactionError);
5014
5438
  });
5015
5439
  return Service19.of({ append: append2, appendForRunning, drainUnconsumed });
5016
5440
  }));
@@ -5111,7 +5535,7 @@ __export(exports_tool_call_repository, {
5111
5535
  DuplicateToolResult: () => DuplicateToolResult,
5112
5536
  DuplicateToolCall: () => DuplicateToolCall
5113
5537
  });
5114
- import { asc as asc11, eq as eq16 } from "drizzle-orm";
5538
+ import { asc as asc9, eq as eq12 } from "drizzle-orm";
5115
5539
  import { Context as Context20, Effect as Effect20, Layer as Layer20, Schema as Schema30 } from "effect";
5116
5540
  class ToolCallRepositoryError extends Schema30.TaggedErrorClass()("ToolCallRepositoryError", {
5117
5541
  message: Schema30.String
@@ -5172,15 +5596,15 @@ var toResultRecord = (row) => ({
5172
5596
  },
5173
5597
  createdAt: fromPgDate(row.createdAt)
5174
5598
  });
5175
- var mapDatabaseError15 = (effect) => effect.pipe(Effect20.mapError((error) => new ToolCallRepositoryError({ message: String(error) })));
5599
+ var mapDatabaseError11 = (effect) => effect.pipe(Effect20.mapError((error) => new ToolCallRepositoryError({ message: String(error) })));
5176
5600
  var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5177
5601
  const db = yield* Service;
5178
5602
  const recordCall = Effect20.fn("ToolCallRepository.recordCall")(function* (input) {
5179
5603
  const tenantId2 = yield* current;
5180
- const existingRows = yield* mapDatabaseError15(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq16(relayToolCalls.id, input.call.id))).limit(1));
5604
+ const existingRows = yield* mapDatabaseError11(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq12(relayToolCalls.id, input.call.id))).limit(1));
5181
5605
  if (existingRows[0] !== undefined)
5182
5606
  return yield* Effect20.fail(new DuplicateToolCall({ id: input.call.id }));
5183
- const rows = yield* mapDatabaseError15(db.insert(relayToolCalls).values(toCallInsert(tenantId2, input)).returning());
5607
+ const rows = yield* mapDatabaseError11(db.insert(relayToolCalls).values(toCallInsert(tenantId2, input)).returning());
5184
5608
  const row = rows[0];
5185
5609
  if (row === undefined) {
5186
5610
  return yield* Effect20.fail(new ToolCallRepositoryError({ message: "Tool call insert returned no row" }));
@@ -5189,24 +5613,24 @@ var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5189
5613
  });
5190
5614
  const getCall = Effect20.fn("ToolCallRepository.getCall")(function* (id2) {
5191
5615
  const tenantId2 = yield* current;
5192
- const rows = yield* mapDatabaseError15(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq16(relayToolCalls.id, id2))).limit(1));
5616
+ const rows = yield* mapDatabaseError11(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq12(relayToolCalls.id, id2))).limit(1));
5193
5617
  return rows[0] === undefined ? undefined : toCallRecord(rows[0]);
5194
5618
  });
5195
5619
  const listCalls = Effect20.fn("ToolCallRepository.listCalls")(function* (executionId) {
5196
5620
  const tenantId2 = yield* current;
5197
- const rows = yield* mapDatabaseError15(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq16(relayToolCalls.executionId, executionId))).orderBy(asc11(relayToolCalls.createdAt)));
5621
+ const rows = yield* mapDatabaseError11(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq12(relayToolCalls.executionId, executionId))).orderBy(asc9(relayToolCalls.createdAt)));
5198
5622
  return rows.map(toCallRecord);
5199
5623
  });
5200
5624
  const recordResult = Effect20.fn("ToolCallRepository.recordResult")(function* (input) {
5201
5625
  const tenantId2 = yield* current;
5202
- const callRows = yield* mapDatabaseError15(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq16(relayToolCalls.id, input.result.call_id))).limit(1));
5626
+ const callRows = yield* mapDatabaseError11(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq12(relayToolCalls.id, input.result.call_id))).limit(1));
5203
5627
  if (callRows[0] === undefined)
5204
5628
  return yield* Effect20.fail(new ToolCallNotFound({ id: input.result.call_id }));
5205
- const existingRows = yield* mapDatabaseError15(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq16(relayToolResults.toolCallId, input.result.call_id))).limit(1));
5629
+ const existingRows = yield* mapDatabaseError11(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq12(relayToolResults.toolCallId, input.result.call_id))).limit(1));
5206
5630
  if (existingRows[0] !== undefined) {
5207
5631
  return yield* Effect20.fail(new DuplicateToolResult({ call_id: input.result.call_id }));
5208
5632
  }
5209
- const rows = yield* mapDatabaseError15(db.insert(relayToolResults).values(toResultInsert(tenantId2, input)).returning());
5633
+ const rows = yield* mapDatabaseError11(db.insert(relayToolResults).values(toResultInsert(tenantId2, input)).returning());
5210
5634
  const row = rows[0];
5211
5635
  if (row === undefined) {
5212
5636
  return yield* Effect20.fail(new ToolCallRepositoryError({ message: "Tool result insert returned no row" }));
@@ -5215,7 +5639,7 @@ var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5215
5639
  });
5216
5640
  const getResult = Effect20.fn("ToolCallRepository.getResult")(function* (callId) {
5217
5641
  const tenantId2 = yield* current;
5218
- const rows = yield* mapDatabaseError15(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq16(relayToolResults.toolCallId, callId))).limit(1));
5642
+ const rows = yield* mapDatabaseError11(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq12(relayToolResults.toolCallId, callId))).limit(1));
5219
5643
  return rows[0] === undefined ? undefined : toResultRecord(rows[0]);
5220
5644
  });
5221
5645
  return Service20.of({ recordCall, getCall, listCalls, recordResult, getResult });
@@ -5296,7 +5720,7 @@ __export(exports_workspace_lease_repository, {
5296
5720
  Service: () => Service21,
5297
5721
  DuplicateWorkspaceLease: () => DuplicateWorkspaceLease
5298
5722
  });
5299
- import { eq as eq17, notInArray } from "drizzle-orm";
5723
+ import { eq as eq13, notInArray } from "drizzle-orm";
5300
5724
  import { Context as Context21, Effect as Effect21, Layer as Layer21, Schema as Schema31 } from "effect";
5301
5725
  class WorkspaceLeaseRepositoryError extends Schema31.TaggedErrorClass()("WorkspaceLeaseRepositoryError", {
5302
5726
  message: Schema31.String
@@ -5366,8 +5790,8 @@ var toSnapshotRecord = (row) => ({
5366
5790
  metadata: row.metadataJson,
5367
5791
  created_at: fromPgDate(row.createdAt)
5368
5792
  });
5369
- var mapDatabaseError16 = (effect) => effect.pipe(Effect21.mapError((error) => new WorkspaceLeaseRepositoryError({ message: String(error) })));
5370
- var updateLease = (db, tenantId2, executionId, values) => mapDatabaseError16(db.update(relayWorkspaceLeases).set(values).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq17(relayWorkspaceLeases.executionId, executionId))).returning()).pipe(Effect21.flatMap((rows) => {
5793
+ var mapDatabaseError12 = (effect) => effect.pipe(Effect21.mapError((error) => new WorkspaceLeaseRepositoryError({ message: String(error) })));
5794
+ var updateLease = (db, tenantId2, executionId, values) => mapDatabaseError12(db.update(relayWorkspaceLeases).set(values).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq13(relayWorkspaceLeases.executionId, executionId))).returning()).pipe(Effect21.flatMap((rows) => {
5371
5795
  const row = rows[0];
5372
5796
  if (row === undefined)
5373
5797
  return Effect21.fail(new WorkspaceLeaseNotFound({ execution_id: executionId }));
@@ -5377,16 +5801,16 @@ var layer21 = Layer21.effect(Service21, Effect21.gen(function* () {
5377
5801
  const db = yield* Service;
5378
5802
  const getByExecution = Effect21.fn("WorkspaceLeaseRepository.getByExecution")(function* (id2) {
5379
5803
  const tenantId2 = yield* current;
5380
- const rows = yield* mapDatabaseError16(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq17(relayWorkspaceLeases.executionId, id2))).limit(1));
5804
+ const rows = yield* mapDatabaseError12(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq13(relayWorkspaceLeases.executionId, id2))).limit(1));
5381
5805
  return rows[0] === undefined ? undefined : toLeaseRecord(rows[0]);
5382
5806
  });
5383
5807
  const plan = Effect21.fn("WorkspaceLeaseRepository.plan")(function* (input) {
5384
5808
  const tenantId2 = yield* current;
5385
- const existing = yield* mapDatabaseError16(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq17(relayWorkspaceLeases.executionId, input.executionId), notInArray(relayWorkspaceLeases.status, [...terminalStatuses]))).limit(1));
5809
+ const existing = yield* mapDatabaseError12(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq13(relayWorkspaceLeases.executionId, input.executionId), notInArray(relayWorkspaceLeases.status, [...terminalStatuses]))).limit(1));
5386
5810
  if (existing[0] !== undefined) {
5387
5811
  return yield* Effect21.fail(new DuplicateWorkspaceLease({ execution_id: input.executionId }));
5388
5812
  }
5389
- const rows = yield* mapDatabaseError16(db.insert(relayWorkspaceLeases).values(toPlanInsert(tenantId2, input)).returning());
5813
+ const rows = yield* mapDatabaseError12(db.insert(relayWorkspaceLeases).values(toPlanInsert(tenantId2, input)).returning());
5390
5814
  const row = rows[0];
5391
5815
  if (row === undefined) {
5392
5816
  return yield* Effect21.fail(new WorkspaceLeaseRepositoryError({ message: "Workspace lease insert returned no row" }));
@@ -5418,11 +5842,11 @@ var layer21 = Layer21.effect(Service21, Effect21.gen(function* () {
5418
5842
  });
5419
5843
  const recordSnapshot = Effect21.fn("WorkspaceLeaseRepository.recordSnapshot")(function* (input) {
5420
5844
  const tenantId2 = yield* current;
5421
- const leaseRows = yield* mapDatabaseError16(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq17(relayWorkspaceLeases.executionId, input.executionId))).limit(1));
5845
+ const leaseRows = yield* mapDatabaseError12(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq13(relayWorkspaceLeases.executionId, input.executionId))).limit(1));
5422
5846
  if (leaseRows[0] === undefined) {
5423
5847
  return yield* Effect21.fail(new WorkspaceLeaseNotFound({ execution_id: input.executionId }));
5424
5848
  }
5425
- const rows = yield* mapDatabaseError16(db.insert(relayWorkspaceSnapshots).values(toSnapshotInsert(tenantId2, input)).returning());
5849
+ const rows = yield* mapDatabaseError12(db.insert(relayWorkspaceSnapshots).values(toSnapshotInsert(tenantId2, input)).returning());
5426
5850
  const row = rows[0];
5427
5851
  if (row === undefined) {
5428
5852
  return yield* Effect21.fail(new WorkspaceLeaseRepositoryError({ message: "Workspace snapshot insert returned no row" }));
@@ -5608,7 +6032,7 @@ var recordWaitTransitioned = (state) => Metric.update(Metric.withAttributes(wait
5608
6032
  var recordChildRunSpawned = (kind) => Metric.update(Metric.withAttributes(childRunSpawned, { kind }), 1);
5609
6033
  var recordAddressResolved = (routeKind) => Metric.update(Metric.withAttributes(addressResolved, { route_kind: routeKind }), 1);
5610
6034
  var recordEventAppended = (eventType) => Metric.update(Metric.withAttributes(eventAppended, { event_type: eventType }), 1);
5611
- var recordEventReplayed = (source, count2) => Metric.update(Metric.withAttributes(eventReplayed, { source }), count2);
6035
+ var recordEventReplayed = (source, count) => Metric.update(Metric.withAttributes(eventReplayed, { source }), count);
5612
6036
  var recordRunnerReadinessChecked = (database) => Metric.update(Metric.withAttributes(runnerReadinessChecked, { database }), 1);
5613
6037
  var recordModelUsage = (input) => Effect22.gen(function* () {
5614
6038
  yield* Metric.update(Metric.withAttributes(modelTokens, { direction: "input", provider: input.provider, model: input.model }), input.inputTokens);
@@ -5674,7 +6098,7 @@ var recordFromEntry = (entry) => ({
5674
6098
  });
5675
6099
  var entryIdFor = (addressId) => exports_ids_schema.AddressBookEntryId.make(`address-book:${addressId}`);
5676
6100
  var validateRoute = (route) => Schema32.decodeUnknownEffect(Route2)(route).pipe(Effect23.mapError((error) => new AddressBookServiceError({ message: String(error) })));
5677
- var mapRepositoryError = (error) => {
6101
+ var mapRepositoryError2 = (error) => {
5678
6102
  if (error._tag === "AddressNotFound") {
5679
6103
  return new AddressNotFound2({ address_id: error.address_id });
5680
6104
  }
@@ -5685,7 +6109,7 @@ var layerFromRepository = Layer22.effect(Service22, Effect23.gen(function* () {
5685
6109
  return Service22.of({
5686
6110
  resolve: Effect23.fn("AddressBook.repository.resolve")(function* (addressId) {
5687
6111
  yield* Effect23.annotateCurrentSpan("relay.address.id", addressId);
5688
- const entry = yield* repository.resolve(addressId).pipe(Effect23.mapError(mapRepositoryError));
6112
+ const entry = yield* repository.resolve(addressId).pipe(Effect23.mapError(mapRepositoryError2));
5689
6113
  const route = yield* resolveRoute(addressId, routeFromEntry(entry));
5690
6114
  yield* Effect23.annotateCurrentSpan({
5691
6115
  "relay.route.kind": route.kind,
@@ -6108,7 +6532,7 @@ var memoryLayer21 = Layer23.effect(Service23, Effect25.gen(function* () {
6108
6532
  }),
6109
6533
  maxSequence: Effect25.fn("EventLog.memory.maxSequence")(function* (executionId) {
6110
6534
  const executionEvents = yield* allEvents(executionId);
6111
- return executionEvents.length === 0 ? undefined : executionEvents.reduce((max3, event) => event.sequence > max3 ? event.sequence : max3, executionEvents[0].sequence);
6535
+ return executionEvents.length === 0 ? undefined : executionEvents.reduce((max2, event) => event.sequence > max2 ? event.sequence : max2, executionEvents[0].sequence);
6112
6536
  }),
6113
6537
  sumUsage: Effect25.fn("EventLog.memory.sumUsage")(function* (executionId) {
6114
6538
  const executionEvents = yield* allEvents(executionId);
@@ -6194,7 +6618,7 @@ class WaitServiceError extends Schema34.TaggedErrorClass()("WaitServiceError", {
6194
6618
 
6195
6619
  class Service24 extends Context24.Service()("@relayfx/runtime/WaitService") {
6196
6620
  }
6197
- var mapRepositoryError2 = (error) => {
6621
+ var mapRepositoryError3 = (error) => {
6198
6622
  if (error._tag === "WaitNotFound")
6199
6623
  return new WaitNotFound2({ wait_id: error.id });
6200
6624
  return new WaitServiceError({ message: error.message });
@@ -6269,7 +6693,7 @@ var createTimeoutSchedule = Effect26.fn("WaitService.createTimeoutSchedule")(fun
6269
6693
  }).pipe(Effect26.mapError((error) => new WaitServiceError({ message: error.message })));
6270
6694
  });
6271
6695
  var complete = Effect26.fn("WaitService.complete")(function* (repository, eventLog, input, event) {
6272
- const result = yield* repository.completeWait(input).pipe(Effect26.mapError(mapRepositoryError2));
6696
+ const result = yield* repository.completeWait(input).pipe(Effect26.mapError(mapRepositoryError3));
6273
6697
  if (result.transitioned) {
6274
6698
  yield* eventLog.append(event(result.wait)).pipe(Effect26.mapError(mapEventLogError));
6275
6699
  }
@@ -6429,7 +6853,7 @@ var validateInput = (tool, input) => {
6429
6853
  return Effect27.void;
6430
6854
  return Schema35.decodeUnknownEffect(tool.inputSchema)(input.call.input).pipe(Effect27.mapError((error) => new ToolInputInvalid({ tool_name: input.call.name, message: error.message })), Effect27.asVoid);
6431
6855
  };
6432
- var mapRepositoryError3 = (error) => new ToolRuntimeError({ message: error._tag });
6856
+ var mapRepositoryError4 = (error) => new ToolRuntimeError({ message: error._tag });
6433
6857
  var mapEventLogError2 = (error) => new ToolRuntimeError({ message: error._tag });
6434
6858
  var preserveToolError = (toolName, error) => {
6435
6859
  if (typeof error === "object" && error !== null && "_tag" in error) {
@@ -6446,7 +6870,7 @@ var preserveToolError = (toolName, error) => {
6446
6870
  message: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
6447
6871
  });
6448
6872
  };
6449
- var preserveRecordResultError = (error) => error._tag === "ToolRuntimeError" ? error : mapRepositoryError3(error);
6873
+ var preserveRecordResultError = (error) => error._tag === "ToolRuntimeError" ? error : mapRepositoryError4(error);
6450
6874
  var requestedEvent = (input) => ({
6451
6875
  id: exports_ids_schema.EventId.make(`event:${input.call.id}:tool-requested`),
6452
6876
  execution_id: input.executionId,
@@ -6603,12 +7027,12 @@ var resolveApproval = (waits, eventLog, input) => Effect27.gen(function* () {
6603
7027
  return { _tag: "approved" };
6604
7028
  return { _tag: "denied", reason: deniedReason(existing.state) };
6605
7029
  });
6606
- var recordRequested = (repository, eventLog, input) => repository.getCall(input.call.id).pipe(Effect27.mapError(mapRepositoryError3), Effect27.flatMap((existing) => {
7030
+ var recordRequested = (repository, eventLog, input) => repository.getCall(input.call.id).pipe(Effect27.mapError(mapRepositoryError4), Effect27.flatMap((existing) => {
6607
7031
  if (existing !== undefined)
6608
7032
  return Effect27.void;
6609
- return repository.recordCall({ executionId: input.executionId, call: input.call, createdAt: input.createdAt }).pipe(Effect27.mapError(mapRepositoryError3), Effect27.flatMap(() => appendIdempotentTo(eventLog, requestedEvent(input)).pipe(Effect27.mapError(mapEventLogError2))), Effect27.asVoid);
7033
+ return repository.recordCall({ executionId: input.executionId, call: input.call, createdAt: input.createdAt }).pipe(Effect27.mapError(mapRepositoryError4), Effect27.flatMap(() => appendIdempotentTo(eventLog, requestedEvent(input)).pipe(Effect27.mapError(mapEventLogError2))), Effect27.asVoid);
6610
7034
  }));
6611
- var recordReceived = (repository, eventLog, input, result) => repository.recordResult({ result, createdAt: input.createdAt + 1 }).pipe(Effect27.catchTag("DuplicateToolResult", () => repository.getResult(result.call_id).pipe(Effect27.mapError(mapRepositoryError3), Effect27.flatMap((existing) => existing === undefined ? Effect27.fail(new ToolRuntimeError({ message: "DuplicateToolResult" })) : Effect27.succeed(existing)))), Effect27.mapError(preserveRecordResultError), Effect27.flatMap((record2) => appendIdempotentTo(eventLog, resultEvent(input, record2.result)).pipe(Effect27.mapError(mapEventLogError2), Effect27.as(record2.result))));
7035
+ var recordReceived = (repository, eventLog, input, result) => repository.recordResult({ result, createdAt: input.createdAt + 1 }).pipe(Effect27.catchTag("DuplicateToolResult", () => repository.getResult(result.call_id).pipe(Effect27.mapError(mapRepositoryError4), Effect27.flatMap((existing) => existing === undefined ? Effect27.fail(new ToolRuntimeError({ message: "DuplicateToolResult" })) : Effect27.succeed(existing)))), Effect27.mapError(preserveRecordResultError), Effect27.flatMap((record2) => appendIdempotentTo(eventLog, resultEvent(input, record2.result)).pipe(Effect27.mapError(mapEventLogError2), Effect27.as(record2.result))));
6612
7036
  var definitionFromAiTool = (tool, permissions = []) => ({
6613
7037
  name: tool.name,
6614
7038
  description: Ai.Tool.getDescription(tool) ?? "",
@@ -6632,7 +7056,7 @@ var layer23 = (initialTools = []) => Layer25.effect(Service25, Effect27.gen(func
6632
7056
  if (tool === undefined) {
6633
7057
  return yield* Effect27.fail(new ToolNotRegistered({ tool_name: input.call.name }));
6634
7058
  }
6635
- const existingResult = yield* repository.getResult(input.call.id).pipe(Effect27.mapError(mapRepositoryError3));
7059
+ const existingResult = yield* repository.getResult(input.call.id).pipe(Effect27.mapError(mapRepositoryError4));
6636
7060
  if (existingResult !== undefined)
6637
7061
  return existingResult.result;
6638
7062
  return yield* Effect27.gen(function* () {
@@ -6712,7 +7136,7 @@ var toPublicRevisionRecord = (record2) => ({
6712
7136
  ...record2.toolInputSchemaDigests === undefined ? {} : { tool_input_schema_digests: record2.toolInputSchemaDigests },
6713
7137
  created_at: record2.createdAt
6714
7138
  });
6715
- var mapRepositoryError4 = (error) => new AgentRegistryError({ message: error.message });
7139
+ var mapRepositoryError5 = (error) => new AgentRegistryError({ message: error.message });
6716
7140
  var hasText = (value) => value === undefined || value.trim().length > 0;
6717
7141
  var requireText = (value, field) => value.trim().length === 0 ? Effect28.fail(new AgentDefinitionInvalid({ message: `${field} must not be blank` })) : Effect28.void;
6718
7142
  var requireOptionalText = (value, field) => hasText(value) ? Effect28.void : Effect28.fail(new AgentDefinitionInvalid({ message: `${field} must not be blank` }));
@@ -6791,23 +7215,23 @@ var layer24 = Layer26.effect(Service26, Effect28.gen(function* () {
6791
7215
  const selectedToolNames = input.definition.tool_names.filter((toolName) => toolDefinitions.some((definition) => definition.name === toolName));
6792
7216
  const crypto = yield* Effect28.serviceOption(Crypto2.Crypto);
6793
7217
  const toolInputSchemaDigests = selectedToolNames.length === 0 ? {} : Option7.isNone(crypto) ? yield* Effect28.fail(new AgentRegistryError({ message: "Tool input schema digest computation requires Crypto" })) : yield* digestDefinitions(toolDefinitions, selectedToolNames).pipe(Effect28.provideService(Crypto2.Crypto, crypto.value), Effect28.mapError((error) => new AgentRegistryError({ message: String(error) })));
6794
- const record2 = yield* repository.put({ id: input.id, definition: input.definition, toolInputSchemaDigests, now }).pipe(Effect28.mapError(mapRepositoryError4));
7218
+ const record2 = yield* repository.put({ id: input.id, definition: input.definition, toolInputSchemaDigests, now }).pipe(Effect28.mapError(mapRepositoryError5));
6795
7219
  return { record: toPublicRecord(record2) };
6796
7220
  }),
6797
7221
  get: Effect28.fn("AgentRegistry.get")(function* (id2) {
6798
- const record2 = yield* repository.get(id2).pipe(Effect28.mapError(mapRepositoryError4));
7222
+ const record2 = yield* repository.get(id2).pipe(Effect28.mapError(mapRepositoryError5));
6799
7223
  return record2 === undefined ? undefined : toPublicRecord(record2);
6800
7224
  }),
6801
7225
  getRevision: Effect28.fn("AgentRegistry.getRevision")(function* (input) {
6802
- const record2 = yield* repository.getRevision(input).pipe(Effect28.mapError(mapRepositoryError4));
7226
+ const record2 = yield* repository.getRevision(input).pipe(Effect28.mapError(mapRepositoryError5));
6803
7227
  return record2 === undefined ? undefined : toPublicRevisionRecord(record2);
6804
7228
  }),
6805
7229
  list: Effect28.fn("AgentRegistry.list")(function* () {
6806
- const records = yield* repository.list().pipe(Effect28.mapError(mapRepositoryError4));
7230
+ const records = yield* repository.list().pipe(Effect28.mapError(mapRepositoryError5));
6807
7231
  return { records: records.map(toPublicRecord) };
6808
7232
  }),
6809
7233
  listRevisions: Effect28.fn("AgentRegistry.listRevisions")(function* (id2) {
6810
- const records = yield* repository.listRevisions(id2).pipe(Effect28.mapError(mapRepositoryError4));
7234
+ const records = yield* repository.listRevisions(id2).pipe(Effect28.mapError(mapRepositoryError5));
6811
7235
  return { records: records.map(toPublicRevisionRecord) };
6812
7236
  })
6813
7237
  });
@@ -8748,7 +9172,7 @@ var spawnedEvent = (input, kind, context, presetName, workspaceRef) => ({
8748
9172
  },
8749
9173
  created_at: input.createdAt
8750
9174
  });
8751
- var mapRepositoryError5 = (error) => new ChildRunServiceError({ message: error._tag });
9175
+ var mapRepositoryError6 = (error) => new ChildRunServiceError({ message: error._tag });
8752
9176
  var mapEventLogError3 = (error) => new ChildRunServiceError({ message: error._tag });
8753
9177
  var persistChild = Effect50.fn("ChildRunService.persistChild")(function* (repository, eventLog, input, kind, context, presetName) {
8754
9178
  const workspaceRef = yield* childWorkspaceRef(input, context);
@@ -8759,7 +9183,7 @@ var persistChild = Effect50.fn("ChildRunService.persistChild")(function* (reposi
8759
9183
  status: "queued",
8760
9184
  metadata: childMetadata(kind, context, presetName, workspaceRef),
8761
9185
  createdAt: input.createdAt
8762
- }).pipe(Effect50.mapError(mapRepositoryError5));
9186
+ }).pipe(Effect50.mapError(mapRepositoryError6));
8763
9187
  yield* eventLog.append(spawnedEvent(input, kind, context, presetName, workspaceRef)).pipe(Effect50.mapError(mapEventLogError3));
8764
9188
  return acceptedOutput(input);
8765
9189
  });
@@ -8901,7 +9325,7 @@ var hasDynamicOverride = (input) => input.instructions !== undefined || input.mo
8901
9325
  var childExecutionId = (context) => exports_ids_schema.ChildExecutionId.make(`${context.executionId}:child:${context.call.id}`);
8902
9326
  var childAddressId = (id2) => exports_ids_schema.AddressId.make(`address:child:${id2}`);
8903
9327
  var childWaitId = (id2) => exports_ids_schema.WaitId.make(`wait:child:${id2}`);
8904
- var nextEventSequence = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect51.map((max3) => max3 === undefined ? 0 : max3 + 1), Effect51.mapError((error) => new ToolRuntimeError({ message: error.message })));
9328
+ var nextEventSequence = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect51.map((max2) => max2 === undefined ? 0 : max2 + 1), Effect51.mapError((error) => new ToolRuntimeError({ message: error.message })));
8905
9329
  var mapChildRunError = (activeToolName, error) => new ToolExecutionFailed({ tool_name: activeToolName, message: error._tag });
8906
9330
  var mapWaitError = (error) => new ToolRuntimeError({ message: error._tag === "WaitNotFound" ? error.wait_id : error.message });
8907
9331
  var spawnInput = (config, input, context, id2) => ({
@@ -9814,7 +10238,7 @@ var layer39 = exports_approvals.autoApprove;
9814
10238
  // ../runtime/src/agent/relay-compaction.ts
9815
10239
  import { Clock as Clock4, Effect as Effect60, Layer as Layer54 } from "effect";
9816
10240
  var checkpointId = (input) => `compaction:${input.executionId}:turn:${input.turn}:keep:${input.firstKeptEntryId}`;
9817
- var mapRepositoryError6 = (error) => new exports_compaction.CompactionError({ message: error.message, cause: error });
10241
+ var mapRepositoryError7 = (error) => new exports_compaction.CompactionError({ message: error.message, cause: error });
9818
10242
  var sameCheckpointBoundary = (record2, input) => record2.firstKeptEntryId === input.firstKeptEntryId && record2.turn === input.turn;
9819
10243
  var defaultOptions = (options) => ({
9820
10244
  ...options?.contextWindow === undefined ? {} : { contextWindow: options.contextWindow },
@@ -9833,7 +10257,7 @@ var strategy = (config) => {
9833
10257
  firstKeptEntryId: plan2.firstKeptEntryId
9834
10258
  });
9835
10259
  return Effect60.gen(function* () {
9836
- const existing = yield* config.repository.get({ executionId: config.executionId, checkpointId: id2 }).pipe(Effect60.mapError(mapRepositoryError6));
10260
+ const existing = yield* config.repository.get({ executionId: config.executionId, checkpointId: id2 }).pipe(Effect60.mapError(mapRepositoryError7));
9837
10261
  if (existing !== undefined)
9838
10262
  return existing.summary;
9839
10263
  const summary = yield* base.summarize(plan2, request);
@@ -9847,7 +10271,7 @@ var strategy = (config) => {
9847
10271
  createdAt
9848
10272
  };
9849
10273
  const record2 = yield* config.repository.record(input).pipe(Effect60.matchEffect({
9850
- onFailure: (error) => config.repository.get({ executionId: config.executionId, checkpointId: id2 }).pipe(Effect60.mapError(mapRepositoryError6), Effect60.flatMap((saved) => saved !== undefined && sameCheckpointBoundary(saved, input) ? Effect60.succeed(saved) : Effect60.fail(mapRepositoryError6(error)))),
10274
+ onFailure: (error) => config.repository.get({ executionId: config.executionId, checkpointId: id2 }).pipe(Effect60.mapError(mapRepositoryError7), Effect60.flatMap((saved) => saved !== undefined && sameCheckpointBoundary(saved, input) ? Effect60.succeed(saved) : Effect60.fail(mapRepositoryError7(error)))),
9851
10275
  onSuccess: Effect60.succeed
9852
10276
  }));
9853
10277
  return record2.summary;
@@ -9909,7 +10333,7 @@ var evaluateDecision = Effect61.fn("RelayPermissions.evaluateDecision")(function
9909
10333
  });
9910
10334
  var permissionError = (message) => new exports_permissions.PermissionError({ message });
9911
10335
  var createdAtForSequence = (config, sequence) => config.startedAt + sequence - config.eventSequence;
9912
- var nextLoggedSequence = (eventLog, executionId, fallback) => eventLog.maxSequence(executionId).pipe(Effect61.mapError((error) => permissionError(error.message)), Effect61.map((max3) => max3 === undefined ? fallback : Math.max(max3 + 1, fallback)));
10336
+ var nextLoggedSequence = (eventLog, executionId, fallback) => eventLog.maxSequence(executionId).pipe(Effect61.mapError((error) => permissionError(error.message)), Effect61.map((max2) => max2 === undefined ? fallback : Math.max(max2 + 1, fallback)));
9913
10337
  var allocateEventSequence = Effect61.fn("RelayPermissions.allocateEventSequence")(function* (config) {
9914
10338
  const fallback = yield* config.allocator.allocate(1);
9915
10339
  const sequence = yield* nextLoggedSequence(config.eventLog, config.executionId, fallback);
@@ -10141,7 +10565,7 @@ var errorDetail = (error) => {
10141
10565
  return error.tool_name;
10142
10566
  }
10143
10567
  };
10144
- var nextLoggedSequence2 = (eventLog, executionId, fallback) => eventLog.maxSequence(executionId).pipe(Effect63.map((max3) => max3 === undefined ? fallback : Math.max(max3 + 1, fallback)), Effect63.catch(() => Effect63.succeed(fallback)));
10568
+ var nextLoggedSequence2 = (eventLog, executionId, fallback) => eventLog.maxSequence(executionId).pipe(Effect63.map((max2) => max2 === undefined ? fallback : Math.max(max2 + 1, fallback)), Effect63.catch(() => Effect63.succeed(fallback)));
10145
10569
  var requestedCursor = (executionId, callId) => `${executionId}:tool:${callId}:requested`;
10146
10570
  var hasRequestedEvent = (config, callId) => config.eventLog.findByCursor({
10147
10571
  executionId: config.executionId,
@@ -10226,7 +10650,7 @@ var layer43 = Layer58.effect(exports_tool_output.ToolOutputStore, Service37.pipe
10226
10650
  // ../runtime/src/agent/sequence-allocator.ts
10227
10651
  import { Effect as Effect65, Ref as Ref17 } from "effect";
10228
10652
  var make12 = (first) => Ref17.make(first).pipe(Effect65.map((ref) => ({
10229
- allocate: (count2) => Ref17.getAndUpdate(ref, (value) => value + count2),
10653
+ allocate: (count) => Ref17.getAndUpdate(ref, (value) => value + count),
10230
10654
  current: Ref17.get(ref),
10231
10655
  resetTo: (sequence) => Ref17.set(ref, sequence)
10232
10656
  })));
@@ -10877,7 +11301,7 @@ var make13 = Effect67.fn("ParentNotifier.make")(function* (options) {
10877
11301
  const eventLog = yield* Service23;
10878
11302
  const repository = yield* exports_child_execution_repository.Service;
10879
11303
  const waits = yield* Service24;
10880
- const nextSequence = (executionId) => eventLog.maxSequence(executionId).pipe(Effect67.map((max3) => max3 === undefined ? 0 : max3 + 1), Effect67.mapError(toParentNotifyError));
11304
+ const nextSequence = (executionId) => eventLog.maxSequence(executionId).pipe(Effect67.map((max2) => max2 === undefined ? 0 : max2 + 1), Effect67.mapError(toParentNotifyError));
10881
11305
  const appendTerminalEvent = (input) => Effect67.gen(function* () {
10882
11306
  const sequence = yield* nextSequence(input.parentExecutionId);
10883
11307
  const event = childRunEvent(input, sequence);
@@ -10988,7 +11412,7 @@ var toPublicPinRecord = (record2) => ({
10988
11412
  skill_definition_snapshot: record2.skillDefinitionSnapshot,
10989
11413
  created_at: record2.createdAt
10990
11414
  });
10991
- var mapRepositoryError7 = (error) => new SkillRegistryError({ message: error.message });
11415
+ var mapRepositoryError8 = (error) => new SkillRegistryError({ message: error.message });
10992
11416
  var requireText2 = (value, field) => value.trim().length === 0 ? Effect68.fail(new SkillDefinitionInvalid({ message: `${field} must not be blank` })) : Effect68.void;
10993
11417
  var requireOptionalText2 = (value, field) => value === undefined || value.trim().length > 0 ? Effect68.void : Effect68.fail(new SkillDefinitionInvalid({ message: `${field} must not be blank` }));
10994
11418
  var validateDefinition2 = Effect68.fn("SkillRegistry.validateDefinition")(function* (definition) {
@@ -11033,23 +11457,23 @@ var layer45 = Layer61.effect(Service42, Effect68.gen(function* () {
11033
11457
  register: Effect68.fn("SkillRegistry.register")(function* (input) {
11034
11458
  yield* validateDefinition2(input.definition);
11035
11459
  const now = yield* Clock7.currentTimeMillis;
11036
- const record2 = yield* repository.put({ id: input.id, definition: input.definition, now }).pipe(Effect68.mapError(mapRepositoryError7));
11460
+ const record2 = yield* repository.put({ id: input.id, definition: input.definition, now }).pipe(Effect68.mapError(mapRepositoryError8));
11037
11461
  return { record: toPublicRecord2(record2) };
11038
11462
  }),
11039
11463
  get: Effect68.fn("SkillRegistry.get")(function* (id2) {
11040
- const record2 = yield* repository.get(id2).pipe(Effect68.mapError(mapRepositoryError7));
11464
+ const record2 = yield* repository.get(id2).pipe(Effect68.mapError(mapRepositoryError8));
11041
11465
  return record2 === undefined ? undefined : toPublicRecord2(record2);
11042
11466
  }),
11043
11467
  getRevision: Effect68.fn("SkillRegistry.getRevision")(function* (input) {
11044
- const record2 = yield* repository.getRevision(input).pipe(Effect68.mapError(mapRepositoryError7));
11468
+ const record2 = yield* repository.getRevision(input).pipe(Effect68.mapError(mapRepositoryError8));
11045
11469
  return record2 === undefined ? undefined : toPublicRevisionRecord2(record2);
11046
11470
  }),
11047
11471
  list: Effect68.fn("SkillRegistry.list")(function* () {
11048
- const records = yield* repository.list().pipe(Effect68.mapError(mapRepositoryError7));
11472
+ const records = yield* repository.list().pipe(Effect68.mapError(mapRepositoryError8));
11049
11473
  return { records: records.map(toPublicRecord2) };
11050
11474
  }),
11051
11475
  listRevisions: Effect68.fn("SkillRegistry.listRevisions")(function* (id2) {
11052
- const records = yield* repository.listRevisions(id2).pipe(Effect68.mapError(mapRepositoryError7));
11476
+ const records = yield* repository.listRevisions(id2).pipe(Effect68.mapError(mapRepositoryError8));
11053
11477
  return { records: records.map(toPublicRevisionRecord2) };
11054
11478
  }),
11055
11479
  pinExecution: Effect68.fn("SkillRegistry.pinExecution")(function* (input) {
@@ -11058,15 +11482,15 @@ var layer45 = Layer61.effect(Service42, Effect68.gen(function* () {
11058
11482
  executionId: input.execution_id,
11059
11483
  skillDefinitionIds: input.skill_definition_ids,
11060
11484
  now
11061
- }).pipe(Effect68.mapError(mapRepositoryError7));
11485
+ }).pipe(Effect68.mapError(mapRepositoryError8));
11062
11486
  return { records: records.map(toPublicPinRecord) };
11063
11487
  }),
11064
11488
  listPins: Effect68.fn("SkillRegistry.listPins")(function* (executionId) {
11065
- const records = yield* repository.listPins(executionId).pipe(Effect68.mapError(mapRepositoryError7));
11489
+ const records = yield* repository.listPins(executionId).pipe(Effect68.mapError(mapRepositoryError8));
11066
11490
  return { records: records.map(toPublicPinRecord) };
11067
11491
  }),
11068
11492
  getPinned: Effect68.fn("SkillRegistry.getPinned")(function* (input) {
11069
- const record2 = yield* repository.getPinned(input).pipe(Effect68.mapError(mapRepositoryError7));
11493
+ const record2 = yield* repository.getPinned(input).pipe(Effect68.mapError(mapRepositoryError8));
11070
11494
  return record2 === undefined ? undefined : toPublicPinRecord(record2);
11071
11495
  })
11072
11496
  });
@@ -11154,7 +11578,7 @@ var toExecution = (record2) => ({
11154
11578
  created_at: record2.createdAt,
11155
11579
  updated_at: record2.updatedAt
11156
11580
  });
11157
- var mapRepositoryError8 = (error) => new ExecutionServiceError({ message: error._tag });
11581
+ var mapRepositoryError9 = (error) => new ExecutionServiceError({ message: error._tag });
11158
11582
  var mapEventLogError4 = (error) => new ExecutionServiceError({ message: error._tag });
11159
11583
  var mapChildRunError2 = (error) => new ExecutionServiceError({ message: error._tag });
11160
11584
  var childExecutionId2 = (input) => input.child_execution_id ?? exports_ids_schema.ChildExecutionId.make(`${input.execution_id}:child:${input.address_id}`);
@@ -11164,8 +11588,8 @@ var hasCompleteAgentDefinitionPin2 = (input) => {
11164
11588
  input.agentDefinitionRevision !== undefined,
11165
11589
  input.agentDefinitionSnapshot !== undefined
11166
11590
  ];
11167
- const count2 = present.filter(Boolean).length;
11168
- return count2 === 0 || count2 === present.length;
11591
+ const count = present.filter(Boolean).length;
11592
+ return count === 0 || count === present.length;
11169
11593
  };
11170
11594
  var validateAcceptInput = (input) => !hasCompleteAgentDefinitionPin2(input) ? Effect69.fail(new ExecutionServiceError({
11171
11595
  message: "agent definition pin must include id, revision, and snapshot together"
@@ -11207,8 +11631,8 @@ var presetMap2 = (presets) => new Map(Object.entries(presets ?? {}).map(([name,
11207
11631
  var nextEventSequence2 = Effect69.fn("ExecutionService.nextEventSequence")(function* (eventLog, input) {
11208
11632
  if (input.event_sequence !== undefined)
11209
11633
  return input.event_sequence;
11210
- const max3 = yield* eventLog.maxSequence(input.execution_id).pipe(Effect69.mapError(mapEventLogError4));
11211
- return max3 === undefined ? 0 : max3 + 1;
11634
+ const max2 = yield* eventLog.maxSequence(input.execution_id).pipe(Effect69.mapError(mapEventLogError4));
11635
+ return max2 === undefined ? 0 : max2 + 1;
11212
11636
  });
11213
11637
  var childRunBaseInput = Effect69.fn("ExecutionService.childRunBaseInput")(function* (eventLog, input) {
11214
11638
  const eventSequence = yield* nextEventSequence2(eventLog, input);
@@ -11305,7 +11729,7 @@ var updateStatus2 = Effect69.fn("ExecutionService.updateStatus")(function* (repo
11305
11729
  status,
11306
11730
  updatedAt,
11307
11731
  ...metadata11 === undefined ? {} : { metadata: metadata11 }
11308
- }).pipe(Effect69.mapError(mapRepositoryError8));
11732
+ }).pipe(Effect69.mapError(mapRepositoryError9));
11309
11733
  return toExecution(record2);
11310
11734
  });
11311
11735
  var layer46 = Layer62.effect(Service43, Effect69.gen(function* () {
@@ -11340,7 +11764,7 @@ var layer46 = Layer62.effect(Service43, Effect69.gen(function* () {
11340
11764
  ...input.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshot: input.agentDefinitionSnapshot },
11341
11765
  ...input.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests: input.agentDefinitionToolInputSchemaDigests },
11342
11766
  ...input.metadata === undefined ? {} : { metadata: input.metadata }
11343
- }).pipe(Effect69.mapError(mapRepositoryError8));
11767
+ }).pipe(Effect69.mapError(mapRepositoryError9));
11344
11768
  yield* eventLog.append(acceptedEvent(input)).pipe(Effect69.mapError(mapEventLogError4));
11345
11769
  yield* recordExecutionAccepted;
11346
11770
  return toExecution(record2);
@@ -11514,13 +11938,13 @@ var selectedDefinitions = (input) => {
11514
11938
  var requiresWorkspace = (definition) => definition.requirements?.some((requirement) => requirement.type === "workspace") ?? false;
11515
11939
  var needsWorkspace = (input) => selectedDefinitions(input).some(requiresWorkspace);
11516
11940
  var leaseId = (executionId) => exports_ids_schema.WorkspaceLeaseId.make(`workspace-lease:${executionId}`);
11517
- var mapRepositoryError9 = (error) => new WorkspacePlannerError({ message: error._tag });
11941
+ var mapRepositoryError10 = (error) => new WorkspacePlannerError({ message: error._tag });
11518
11942
  var mapEventLogError5 = (error) => new WorkspacePlannerError({ message: error._tag });
11519
11943
  var providerOrMissing = (executionId) => Effect71.serviceOption(Service29).pipe(Effect71.flatMap((provider) => Option25.match(provider, {
11520
11944
  onNone: () => Effect71.fail(new WorkspaceRuntimeMissing({ execution_id: executionId })),
11521
11945
  onSome: Effect71.succeed
11522
11946
  })));
11523
- var nextEventSequence3 = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect71.map((max3) => max3 === undefined ? 0 : max3 + 1), Effect71.catch(() => Effect71.succeed(0)));
11947
+ var nextEventSequence3 = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect71.map((max2) => max2 === undefined ? 0 : max2 + 1), Effect71.catch(() => Effect71.succeed(0)));
11524
11948
  var workspaceEvent = (type, lease, sequence, createdAt) => ({
11525
11949
  id: exports_ids_schema.EventId.make(`event:${lease.execution_id}:workspace:${type}:${sequence}`),
11526
11950
  execution_id: lease.execution_id,
@@ -11556,13 +11980,13 @@ var missingRef = (executionId) => new WorkspaceLeaseMissingRef({ execution_id: e
11556
11980
  var ensureFromExisting = Effect71.fn("WorkspacePlanner.ensureFromExisting")(function* (repository, eventLog, provider, lease, input) {
11557
11981
  if (lease.sandbox_ref === undefined) {
11558
11982
  const handle2 = yield* provider.acquire(providerAcquireSpec(input));
11559
- const running2 = yield* repository.markRunning({ executionId: input.executionId, sandboxRef: handle2.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
11983
+ const running2 = yield* repository.markRunning({ executionId: input.executionId, sandboxRef: handle2.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11560
11984
  const sequence2 = yield* nextEventSequence3(eventLog, input.executionId);
11561
11985
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.acquired", running2, sequence2, input.now);
11562
11986
  return planResult(running2, handle2);
11563
11987
  }
11564
11988
  const handle = yield* provider.resume(lease.sandbox_ref);
11565
- const running = yield* repository.markResumed({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
11989
+ const running = yield* repository.markResumed({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11566
11990
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11567
11991
  yield* appendWorkspaceEvent(eventLog, "workspace.resumed", running, sequence, input.now);
11568
11992
  return planResult(running, handle);
@@ -11575,21 +11999,21 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11575
11999
  if (!needsWorkspace(input))
11576
12000
  return;
11577
12001
  const provider = yield* providerOrMissing(input.executionId);
11578
- const existing = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12002
+ const existing = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11579
12003
  if (existing !== undefined && existing.status !== "released" && existing.status !== "failed") {
11580
12004
  return yield* ensureFromExisting(repository, eventLog, provider, existing, input);
11581
12005
  }
11582
- const planned = yield* repository.plan(planInput(input, provider)).pipe(Effect71.mapError(mapRepositoryError9));
12006
+ const planned = yield* repository.plan(planInput(input, provider)).pipe(Effect71.mapError(mapRepositoryError10));
11583
12007
  let sequence = yield* nextEventSequence3(eventLog, input.executionId);
11584
12008
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.planned", planned, sequence, input.now);
11585
12009
  const handle = yield* provider.acquire(providerAcquireSpec(input));
11586
- const running = yield* repository.markRunning({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
12010
+ const running = yield* repository.markRunning({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11587
12011
  sequence += 1;
11588
12012
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.acquired", running, sequence, input.now);
11589
12013
  return planResult(running, handle);
11590
12014
  }),
11591
12015
  suspend: Effect71.fn("WorkspacePlanner.suspend")(function* (input) {
11592
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12016
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11593
12017
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11594
12018
  return;
11595
12019
  if (lease.sandbox_ref === undefined)
@@ -11604,26 +12028,26 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11604
12028
  if (provider.capabilities.can_suspend) {
11605
12029
  yield* provider.suspend(lease.sandbox_ref);
11606
12030
  }
11607
- const suspended2 = yield* repository.markSuspended({ executionId: input.executionId, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
12031
+ const suspended2 = yield* repository.markSuspended({ executionId: input.executionId, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11608
12032
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11609
12033
  yield* appendWorkspaceEvent(eventLog, "workspace.suspended", suspended2, sequence, input.now);
11610
12034
  return suspended2;
11611
12035
  }),
11612
12036
  resume: Effect71.fn("WorkspacePlanner.resume")(function* (input) {
11613
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12037
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11614
12038
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11615
12039
  return;
11616
12040
  if (lease.sandbox_ref === undefined)
11617
12041
  return yield* Effect71.fail(missingRef(input.executionId));
11618
12042
  const provider = yield* providerOrMissing(input.executionId);
11619
12043
  const handle = yield* provider.resume(lease.sandbox_ref);
11620
- const running = yield* repository.markResumed({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
12044
+ const running = yield* repository.markResumed({ executionId: input.executionId, sandboxRef: handle.ref, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11621
12045
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11622
12046
  yield* appendWorkspaceEvent(eventLog, "workspace.resumed", running, sequence, input.now);
11623
12047
  return planResult(running, handle);
11624
12048
  }),
11625
12049
  attach: Effect71.fn("WorkspacePlanner.attach")(function* (input) {
11626
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12050
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11627
12051
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11628
12052
  return;
11629
12053
  if (lease.sandbox_ref === undefined)
@@ -11633,27 +12057,27 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11633
12057
  return planResult(lease, handle);
11634
12058
  }),
11635
12059
  release: Effect71.fn("WorkspacePlanner.release")(function* (input) {
11636
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12060
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11637
12061
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11638
12062
  return;
11639
12063
  if (lease.sandbox_ref === undefined)
11640
12064
  return yield* Effect71.fail(missingRef(input.executionId));
11641
12065
  const provider = yield* providerOrMissing(input.executionId);
11642
12066
  yield* provider.destroy(lease.sandbox_ref);
11643
- const released = yield* repository.markReleased({ executionId: input.executionId, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError9));
12067
+ const released = yield* repository.markReleased({ executionId: input.executionId, updatedAt: input.now }).pipe(Effect71.mapError(mapRepositoryError10));
11644
12068
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11645
12069
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.released", released, sequence, input.now);
11646
12070
  return released;
11647
12071
  }),
11648
12072
  fail: Effect71.fn("WorkspacePlanner.fail")(function* (input) {
11649
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12073
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11650
12074
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11651
12075
  return;
11652
12076
  const failed = yield* repository.markFailed({
11653
12077
  executionId: input.executionId,
11654
12078
  updatedAt: input.now,
11655
12079
  ...input.metadata === undefined ? {} : { metadata: input.metadata }
11656
- }).pipe(Effect71.mapError(mapRepositoryError9));
12080
+ }).pipe(Effect71.mapError(mapRepositoryError10));
11657
12081
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11658
12082
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.failed", failed, sequence, input.now);
11659
12083
  return failed;
@@ -11798,7 +12222,7 @@ var mapWaitError2 = (error) => new ExecutionWorkflowFailed({
11798
12222
  message: error._tag === "WaitNotFound" ? `Wait not found: ${error.wait_id}` : error.message
11799
12223
  });
11800
12224
  var mapAddressResolutionError = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11801
- var mapRepositoryError10 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
12225
+ var mapRepositoryError11 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11802
12226
  var mapChildExecutionRepositoryError = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11803
12227
  var mapSkillRegistryError = (error) => new ExecutionWorkflowFailed({ message: error.message });
11804
12228
  var mapEventLogError6 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
@@ -11888,7 +12312,7 @@ var openChildStatuses = new Set(["queued", "running", "waiting"]);
11888
12312
  var childCancelReason = "parent cancelled";
11889
12313
  var cancelChildExecution = Effect72.fn("ExecutionWorkflow.cancelChildExecution")(function* (executionId, cancelledAt) {
11890
12314
  const repository = yield* exports_execution_repository.Service;
11891
- const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError10));
12315
+ const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError11));
11892
12316
  if (record2 === undefined || terminalExecutionStatuses.has(record2.status))
11893
12317
  return;
11894
12318
  if (record2.status === "waiting") {
@@ -11923,7 +12347,7 @@ var cancelChildExecution = Effect72.fn("ExecutionWorkflow.cancelChildExecution")
11923
12347
  cancellation_requested: true,
11924
12348
  cancellation_reason: childCancelReason
11925
12349
  }
11926
- }).pipe(Effect72.mapError(mapRepositoryError10));
12350
+ }).pipe(Effect72.mapError(mapRepositoryError11));
11927
12351
  });
11928
12352
  var cancelOpenChildren = Effect72.fn("ExecutionWorkflow.cancelOpenChildren")(function* (executionId, cancelledAt) {
11929
12353
  const children = yield* exports_child_execution_repository.listByExecution(executionId).pipe(Effect72.mapError(mapChildExecutionRepositoryError));
@@ -11964,7 +12388,7 @@ var loadCancellationRequested = (input, turn) => Activity.make({
11964
12388
  error: ExecutionWorkflowFailed,
11965
12389
  execute: Effect72.gen(function* () {
11966
12390
  const repository = yield* exports_execution_repository.Service;
11967
- const record2 = yield* repository.get(input.execution_id).pipe(Effect72.mapError(mapRepositoryError10));
12391
+ const record2 = yield* repository.get(input.execution_id).pipe(Effect72.mapError(mapRepositoryError11));
11968
12392
  return record2?.metadata?.cancellation_requested === true;
11969
12393
  })
11970
12394
  });
@@ -11987,7 +12411,7 @@ var markWaiting = (input, repository, wait) => Activity.make({
11987
12411
  wait_state: wait.state,
11988
12412
  ...generationMetadata(workflowGenerationForStart(input))
11989
12413
  }
11990
- }).pipe(Effect72.mapError(mapRepositoryError10), Effect72.map((record2) => ({
12414
+ }).pipe(Effect72.mapError(mapRepositoryError11), Effect72.map((record2) => ({
11991
12415
  id: record2.id,
11992
12416
  root_address_id: record2.rootAddressId,
11993
12417
  ...record2.sessionId === undefined ? {} : { session_id: record2.sessionId },
@@ -12076,7 +12500,7 @@ var steeringEnabledForStart = (input) => {
12076
12500
  return executionSetting === true;
12077
12501
  return steeringMetadataValue(input.agent_definition_snapshot?.metadata) === true;
12078
12502
  };
12079
- var nextEventSequence4 = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect72.map((max3) => max3 === undefined ? 0 : max3 + 1), Effect72.mapError(mapEventLogError6));
12503
+ var nextEventSequence4 = (eventLog, executionId) => eventLog.maxSequence(executionId).pipe(Effect72.map((max2) => max2 === undefined ? 0 : max2 + 1), Effect72.mapError(mapEventLogError6));
12080
12504
  var ensureWorkspace = (input) => Activity.make({
12081
12505
  name: ActivityNames.ensureWorkspace,
12082
12506
  success: Schema66.UndefinedOr(exports_workspace_schema.WorkspaceLeaseRecord),
@@ -12403,7 +12827,7 @@ var startRequest = Effect72.fn("ExecutionWorkflow.startRequest")(function* (inpu
12403
12827
  });
12404
12828
  var cancelRequest = Effect72.fn("ExecutionWorkflow.cancelRequest")(function* (input) {
12405
12829
  const repository = yield* exports_execution_repository.Service;
12406
- const record2 = yield* repository.get(input.execution_id).pipe(Effect72.mapError(mapRepositoryError10));
12830
+ const record2 = yield* repository.get(input.execution_id).pipe(Effect72.mapError(mapRepositoryError11));
12407
12831
  if (record2 === undefined) {
12408
12832
  return yield* Effect72.fail(new ExecutionWorkflowFailed({ message: `Execution not found: ${input.execution_id}` }));
12409
12833
  }
@@ -12443,7 +12867,7 @@ var cancelRequest = Effect72.fn("ExecutionWorkflow.cancelRequest")(function* (in
12443
12867
  cancellation_requested: true,
12444
12868
  ...input.reason === undefined ? {} : { cancellation_reason: input.reason }
12445
12869
  }
12446
- }).pipe(Effect72.mapError(mapRepositoryError10));
12870
+ }).pipe(Effect72.mapError(mapRepositoryError11));
12447
12871
  return { execution_id: record2.id, status: record2.status };
12448
12872
  });
12449
12873
  var poll = (executionId) => StartExecutionWorkflow.poll(executionId);
@@ -12460,7 +12884,7 @@ var workflowExecutionIdForExecution = (executionId, workflowGeneration = 0) => S
12460
12884
  });
12461
12885
  var activeWorkflowExecutionIdForExecution = Effect72.fn("ExecutionWorkflow.activeWorkflowExecutionIdForExecution")(function* (executionId) {
12462
12886
  const repository = yield* exports_execution_repository.Service;
12463
- const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError10));
12887
+ const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError11));
12464
12888
  return yield* workflowExecutionIdForExecution(executionId, record2 === undefined ? 0 : workflowGenerationFromRecord(record2));
12465
12889
  });
12466
12890
  var signalWait = Effect72.fn("ExecutionWorkflow.signalWait")(function* (input) {
@@ -12552,7 +12976,7 @@ var mapAddressBookError2 = (error) => {
12552
12976
  }
12553
12977
  return new EnvelopeServiceError({ message: error.message });
12554
12978
  };
12555
- var mapRepositoryError11 = (error) => new EnvelopeServiceError({ message: error.message });
12979
+ var mapRepositoryError12 = (error) => new EnvelopeServiceError({ message: error.message });
12556
12980
  var mapEventLogError7 = (error) => new EnvelopeServiceError({ message: error._tag });
12557
12981
  var envelopeFrom = (input) => ({
12558
12982
  id: input.envelopeId,
@@ -12647,7 +13071,7 @@ var layer50 = Layer66.effect(Service46, Effect73.gen(function* () {
12647
13071
  envelope,
12648
13072
  ...waitId === undefined ? {} : { waitId },
12649
13073
  ...ready === undefined ? {} : { ready }
12650
- }).pipe(Effect73.mapError(mapRepositoryError11));
13074
+ }).pipe(Effect73.mapError(mapRepositoryError12));
12651
13075
  yield* eventLog.append(acceptedEvent2(input)).pipe(Effect73.mapError(mapEventLogError7));
12652
13076
  yield* eventLog.append(routedEvent(input, route)).pipe(Effect73.mapError(mapEventLogError7));
12653
13077
  if (ready !== undefined) {
@@ -12787,8 +13211,8 @@ var dispatchMetadata = (schedule) => ({
12787
13211
  schedule_id: schedule.id
12788
13212
  });
12789
13213
  var nextEventSequence5 = Effect75.fn("SchedulerService.nextEventSequence")(function* (eventLog, executionId) {
12790
- const max3 = yield* eventLog.maxSequence(executionId).pipe(Effect75.mapError(toSchedulerError));
12791
- return max3 === undefined ? 0 : max3 + 1;
13214
+ const max2 = yield* eventLog.maxSequence(executionId).pipe(Effect75.mapError(toSchedulerError));
13215
+ return max2 === undefined ? 0 : max2 + 1;
12792
13216
  });
12793
13217
  var make14 = Effect75.gen(function* () {
12794
13218
  const schedules = yield* exports_schedule_repository.Service;
@@ -13631,8 +14055,8 @@ var toLease = (record2) => ({
13631
14055
  claim_expires_at: record2.claimExpiresAt ?? record2.updatedAt
13632
14056
  });
13633
14057
  var nextEventSequence6 = Effect78.fn("Client.nextEventSequence")(function* (eventLog, executionId) {
13634
- const max3 = yield* eventLog.maxSequence(executionId).pipe(Effect78.mapError(toClientError));
13635
- return max3 === undefined ? 0 : max3 + 1;
14058
+ const max2 = yield* eventLog.maxSequence(executionId).pipe(Effect78.mapError(toClientError));
14059
+ return max2 === undefined ? 0 : max2 + 1;
13636
14060
  });
13637
14061
  var wakeRuntime = Effect78.fn("Client.wakeRuntime")(function* (waits, eventLog, executionRepository, makeExecutionClient, input) {
13638
14062
  const wait = yield* waits.get(input.wait_id).pipe(Effect78.mapError(toClientError));