@relayfx/sdk 0.0.25 → 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
@@ -13,6 +13,7 @@ var __export = (target, all) => {
13
13
  set: __exportSetter.bind(all, name)
14
14
  });
15
15
  };
16
+ var __require = import.meta.require;
16
17
 
17
18
  // src/adapter-outbox.ts
18
19
  var exports_adapter_outbox = {};
@@ -893,7 +894,6 @@ __export(exports_database_service, {
893
894
  });
894
895
  import * as MysqlClient from "@effect/sql-mysql2/MysqlClient";
895
896
  import * as PgClient from "@effect/sql-pg/PgClient";
896
- import * as SqliteClient from "@effect/sql-sqlite-bun/SqliteClient";
897
897
  import * as PgDrizzle from "drizzle-orm/effect-postgres";
898
898
  import { sql } from "drizzle-orm";
899
899
  import { Config, Context, DateTime, Effect, Layer, Redacted, Schema as Schema12 } from "effect";
@@ -941,9 +941,9 @@ var MysqlClientLive = MysqlClient.layerConfig({
941
941
  url: Config.redacted("DATABASE_URL").pipe(Config.withDefault(Redacted.make("mysql://relay:relay@localhost:5546/relay"))),
942
942
  maxConnections: Config.int("RELAY_SQL_MAX_CONNECTIONS").pipe(Config.withDefault(8))
943
943
  });
944
- var SqliteClientLive = SqliteClient.layerConfig({
944
+ var SqliteClientLive = Layer.unwrap(Effect.promise(() => import("@effect/sql-sqlite-bun/SqliteClient")).pipe(Effect.map((SqliteClient) => SqliteClient.layerConfig({
945
945
  filename: Config.string("RELAY_SQLITE_FILE").pipe(Config.withDefault("relay.sqlite"))
946
- });
946
+ }))));
947
947
  var timestampParam = (client, millis) => client.onDialectOrElse({
948
948
  sqlite: () => millis,
949
949
  orElse: () => toPgDate(millis)
@@ -1539,10 +1539,11 @@ __export(exports_agent_chat_repository, {
1539
1539
  layer: () => layer4,
1540
1540
  get: () => get,
1541
1541
  Service: () => Service4,
1542
+ AgentChatRow: () => AgentChatRow,
1542
1543
  AgentChatRepositoryError: () => AgentChatRepositoryError
1543
1544
  });
1544
- import { eq as eq3 } from "drizzle-orm";
1545
1545
  import { Context as Context4, Effect as Effect4, Layer as Layer4, Schema as Schema14 } from "effect";
1546
+ import * as SqlClient3 from "effect/unstable/sql/SqlClient";
1546
1547
  class AgentChatRepositoryError extends Schema14.TaggedErrorClass()("AgentChatRepositoryError", {
1547
1548
  message: Schema14.String
1548
1549
  }) {
@@ -1550,35 +1551,58 @@ class AgentChatRepositoryError extends Schema14.TaggedErrorClass()("AgentChatRep
1550
1551
 
1551
1552
  class Service4 extends Context4.Service()("@relayfx/store-sql/AgentChatRepository") {
1552
1553
  }
1554
+ var AgentChatRow = Schema14.Struct({
1555
+ execution_id: Schema14.String,
1556
+ export_json: Schema14.Unknown,
1557
+ updated_at: Schema14.Union([Schema14.Date, Schema14.String, Schema14.Number])
1558
+ }).annotate({ identifier: "Relay.AgentChat.Row" });
1553
1559
  var toRecord = (row) => ({
1554
- executionId: row.executionId,
1555
- exportData: row.exportJson,
1556
- updatedAt: fromPgDate(row.updatedAt)
1560
+ executionId: exports_ids_schema.ExecutionId.make(row.execution_id),
1561
+ exportData: decodeJson(row.export_json),
1562
+ updatedAt: fromDbTimestamp(row.updated_at)
1557
1563
  });
1558
- var mapDatabaseError2 = (effect) => effect.pipe(Effect4.mapError((error) => new AgentChatRepositoryError({ message: String(error) })));
1564
+ var toRepositoryError = (error) => new AgentChatRepositoryError({ message: String(error) });
1565
+ var decodeRow = (row) => Schema14.decodeUnknownEffect(AgentChatRow)(row).pipe(Effect4.mapError(toRepositoryError));
1559
1566
  var layer4 = Layer4.effect(Service4, Effect4.gen(function* () {
1560
- const db = yield* Service;
1567
+ const sql4 = yield* SqlClient3.SqlClient;
1568
+ const selectByKey = (tenantId2, executionId) => sql4`
1569
+ SELECT execution_id, export_json, updated_at
1570
+ FROM relay_agent_chats
1571
+ WHERE tenant_id = ${tenantId2} AND execution_id = ${executionId}
1572
+ `;
1573
+ const upsert2 = sql4.onDialectOrElse({
1574
+ mysql: () => (tenantId2, input) => sql4.withTransaction(Effect4.gen(function* () {
1575
+ yield* sql4`
1576
+ INSERT INTO relay_agent_chats (tenant_id, execution_id, export_json, updated_at)
1577
+ VALUES (${tenantId2}, ${input.executionId}, ${encodeJson(input.exportData)}, ${timestampParam(sql4, input.updatedAt)})
1578
+ ON DUPLICATE KEY UPDATE
1579
+ export_json = VALUES(export_json),
1580
+ updated_at = VALUES(updated_at)
1581
+ `;
1582
+ return yield* selectByKey(tenantId2, input.executionId);
1583
+ })),
1584
+ orElse: () => (tenantId2, input) => sql4`
1585
+ INSERT INTO relay_agent_chats (tenant_id, execution_id, export_json, updated_at)
1586
+ VALUES (${tenantId2}, ${input.executionId}, ${encodeJson(input.exportData)}, ${timestampParam(sql4, input.updatedAt)})
1587
+ ON CONFLICT (tenant_id, execution_id) DO UPDATE SET
1588
+ export_json = excluded.export_json,
1589
+ updated_at = excluded.updated_at
1590
+ RETURNING execution_id, export_json, updated_at
1591
+ `
1592
+ });
1561
1593
  const save = Effect4.fn("AgentChatRepository.save")(function* (input) {
1562
1594
  const tenantId2 = yield* current;
1563
- const rows = yield* mapDatabaseError2(db.insert(relayAgentChats).values({
1564
- tenantId: tenantId2,
1565
- executionId: input.executionId,
1566
- exportJson: input.exportData,
1567
- updatedAt: toPgDate(input.updatedAt)
1568
- }).onConflictDoUpdate({
1569
- target: [relayAgentChats.tenantId, relayAgentChats.executionId],
1570
- set: { exportJson: input.exportData, updatedAt: toPgDate(input.updatedAt) }
1571
- }).returning());
1595
+ const rows = yield* upsert2(tenantId2, input).pipe(Effect4.mapError(toRepositoryError));
1572
1596
  const row = rows[0];
1573
1597
  if (row === undefined) {
1574
1598
  return yield* Effect4.fail(new AgentChatRepositoryError({ message: "Agent chat upsert returned no row" }));
1575
1599
  }
1576
- return toRecord(row);
1600
+ return toRecord(yield* decodeRow(row));
1577
1601
  });
1578
1602
  const get = Effect4.fn("AgentChatRepository.get")(function* (executionId) {
1579
1603
  const tenantId2 = yield* current;
1580
- const rows = yield* mapDatabaseError2(db.select().from(relayAgentChats).where(predicate(tenantId2, relayAgentChats.tenantId, eq3(relayAgentChats.executionId, executionId))).limit(1));
1581
- return rows[0] === undefined ? undefined : toRecord(rows[0]);
1604
+ const rows = yield* selectByKey(tenantId2, executionId).pipe(Effect4.mapError(toRepositoryError));
1605
+ return rows[0] === undefined ? undefined : toRecord(yield* decodeRow(rows[0]));
1582
1606
  });
1583
1607
  return Service4.of({ save, get });
1584
1608
  }));
@@ -1622,7 +1646,7 @@ __export(exports_agent_definition_repository, {
1622
1646
  Service: () => Service5,
1623
1647
  AgentDefinitionRepositoryError: () => AgentDefinitionRepositoryError
1624
1648
  });
1625
- import { asc as asc2, desc, eq as eq4, sql as sql4 } from "drizzle-orm";
1649
+ import { asc as asc2, desc, eq as eq3, sql as sql4 } from "drizzle-orm";
1626
1650
  import { Context as Context5, Effect as Effect5, Layer as Layer5, Schema as Schema15 } from "effect";
1627
1651
  class AgentDefinitionRepositoryError extends Schema15.TaggedErrorClass()("AgentDefinitionRepositoryError", {
1628
1652
  message: Schema15.String
@@ -1669,14 +1693,14 @@ var compareByCreatedAtDesc = (left, right) => {
1669
1693
  const createdAt = right.createdAt - left.createdAt;
1670
1694
  return createdAt === 0 ? left.id.localeCompare(right.id) : createdAt;
1671
1695
  };
1672
- var mapDatabaseError3 = (effect) => effect.pipe(Effect5.mapError((error) => new AgentDefinitionRepositoryError({ message: String(error) })));
1696
+ var mapDatabaseError2 = (effect) => effect.pipe(Effect5.mapError((error) => new AgentDefinitionRepositoryError({ message: String(error) })));
1673
1697
  var mapPutError = (effect) => effect.pipe(Effect5.mapError((error) => error instanceof AgentDefinitionRepositoryError ? error : new AgentDefinitionRepositoryError({ message: String(error) })));
1674
1698
  var layer5 = Layer5.effect(Service5, Effect5.gen(function* () {
1675
1699
  const db = yield* Service;
1676
1700
  const put = Effect5.fn("AgentDefinitionRepository.put")(function* (input) {
1677
1701
  const tenantId2 = yield* current;
1678
1702
  return yield* mapPutError(db.transaction((tx) => Effect5.gen(function* () {
1679
- const existingRows = yield* tx.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq4(relayAgentDefinitions.id, input.id))).for("update").limit(1);
1703
+ const existingRows = yield* tx.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq3(relayAgentDefinitions.id, input.id))).for("update").limit(1);
1680
1704
  const existing = existingRows[0];
1681
1705
  if (existing !== undefined && sameDefinitionContent(existing.definitionJson, input.definition)) {
1682
1706
  return toRecord2(existing);
@@ -1696,7 +1720,7 @@ var layer5 = Layer5.effect(Service5, Effect5.gen(function* () {
1696
1720
  definitionJson: input.definition,
1697
1721
  toolInputSchemaDigestsJson: input.toolInputSchemaDigests ?? {},
1698
1722
  updatedAt: toPgDate(input.now)
1699
- }).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq4(relayAgentDefinitions.id, input.id))).returning();
1723
+ }).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq3(relayAgentDefinitions.id, input.id))).returning();
1700
1724
  const row = rows[0];
1701
1725
  if (row === undefined) {
1702
1726
  return yield* Effect5.fail(new AgentDefinitionRepositoryError({ message: "Agent definition put returned no row" }));
@@ -1718,22 +1742,22 @@ var layer5 = Layer5.effect(Service5, Effect5.gen(function* () {
1718
1742
  });
1719
1743
  const get2 = Effect5.fn("AgentDefinitionRepository.get")(function* (id2) {
1720
1744
  const tenantId2 = yield* current;
1721
- const rows = yield* mapDatabaseError3(db.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq4(relayAgentDefinitions.id, id2))).limit(1));
1745
+ const rows = yield* mapDatabaseError2(db.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId, eq3(relayAgentDefinitions.id, id2))).limit(1));
1722
1746
  return rows[0] === undefined ? undefined : toRecord2(rows[0]);
1723
1747
  });
1724
1748
  const getRevision = Effect5.fn("AgentDefinitionRepository.getRevision")(function* (input) {
1725
1749
  const tenantId2 = yield* current;
1726
- const rows = yield* mapDatabaseError3(db.select().from(relayAgentDefinitionRevisions).where(predicate(tenantId2, relayAgentDefinitionRevisions.tenantId, eq4(relayAgentDefinitionRevisions.agentDefinitionId, input.id), eq4(relayAgentDefinitionRevisions.revision, input.revision))).limit(1));
1750
+ const rows = yield* mapDatabaseError2(db.select().from(relayAgentDefinitionRevisions).where(predicate(tenantId2, relayAgentDefinitionRevisions.tenantId, eq3(relayAgentDefinitionRevisions.agentDefinitionId, input.id), eq3(relayAgentDefinitionRevisions.revision, input.revision))).limit(1));
1727
1751
  return rows[0] === undefined ? undefined : toRevisionRecord(rows[0]);
1728
1752
  });
1729
1753
  const list2 = Effect5.fn("AgentDefinitionRepository.list")(function* () {
1730
1754
  const tenantId2 = yield* current;
1731
- const rows = yield* mapDatabaseError3(db.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId)).orderBy(desc(relayAgentDefinitions.createdAt), asc2(relayAgentDefinitions.id)));
1755
+ const rows = yield* mapDatabaseError2(db.select().from(relayAgentDefinitions).where(predicate(tenantId2, relayAgentDefinitions.tenantId)).orderBy(desc(relayAgentDefinitions.createdAt), asc2(relayAgentDefinitions.id)));
1732
1756
  return rows.map(toRecord2);
1733
1757
  });
1734
1758
  const listRevisions = Effect5.fn("AgentDefinitionRepository.listRevisions")(function* (id2) {
1735
1759
  const tenantId2 = yield* current;
1736
- const rows = yield* mapDatabaseError3(db.select().from(relayAgentDefinitionRevisions).where(predicate(tenantId2, relayAgentDefinitionRevisions.tenantId, eq4(relayAgentDefinitionRevisions.agentDefinitionId, id2))).orderBy(desc(relayAgentDefinitionRevisions.revision)));
1760
+ const rows = yield* mapDatabaseError2(db.select().from(relayAgentDefinitionRevisions).where(predicate(tenantId2, relayAgentDefinitionRevisions.tenantId, eq3(relayAgentDefinitionRevisions.agentDefinitionId, id2))).orderBy(desc(relayAgentDefinitionRevisions.revision)));
1737
1761
  return rows.map(toRevisionRecord);
1738
1762
  });
1739
1763
  return Service5.of({ put, get: get2, getRevision, list: list2, listRevisions });
@@ -1824,7 +1848,7 @@ __export(exports_child_execution_repository, {
1824
1848
  ChildExecutionRepositoryError: () => ChildExecutionRepositoryError,
1825
1849
  ChildExecutionNotFound: () => ChildExecutionNotFound
1826
1850
  });
1827
- import { asc as asc3, eq as eq5 } from "drizzle-orm";
1851
+ import { asc as asc3, eq as eq4 } from "drizzle-orm";
1828
1852
  import { Context as Context6, Effect as Effect6, Layer as Layer6, Schema as Schema16 } from "effect";
1829
1853
  class ChildExecutionRepositoryError extends Schema16.TaggedErrorClass()("ChildExecutionRepositoryError", {
1830
1854
  message: Schema16.String
@@ -1863,15 +1887,15 @@ var toRecord3 = (row) => ({
1863
1887
  createdAt: fromPgDate(row.createdAt),
1864
1888
  updatedAt: fromPgDate(row.updatedAt)
1865
1889
  });
1866
- var mapDatabaseError4 = (effect) => effect.pipe(Effect6.mapError((error) => new ChildExecutionRepositoryError({ message: String(error) })));
1890
+ var mapDatabaseError3 = (effect) => effect.pipe(Effect6.mapError((error) => new ChildExecutionRepositoryError({ message: String(error) })));
1867
1891
  var layer6 = Layer6.effect(Service6, Effect6.gen(function* () {
1868
1892
  const db = yield* Service;
1869
1893
  const create = Effect6.fn("ChildExecutionRepository.create")(function* (input) {
1870
1894
  const tenantId2 = yield* current;
1871
- const existing = yield* mapDatabaseError4(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq5(relayChildExecutions.id, input.id))).limit(1));
1895
+ const existing = yield* mapDatabaseError3(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq4(relayChildExecutions.id, input.id))).limit(1));
1872
1896
  if (existing[0] !== undefined)
1873
1897
  return yield* Effect6.fail(new DuplicateChildExecution({ id: input.id }));
1874
- const rows = yield* mapDatabaseError4(db.insert(relayChildExecutions).values(toInsert(tenantId2, input)).returning());
1898
+ const rows = yield* mapDatabaseError3(db.insert(relayChildExecutions).values(toInsert(tenantId2, input)).returning());
1875
1899
  const row = rows[0];
1876
1900
  if (row === undefined) {
1877
1901
  return yield* Effect6.fail(new ChildExecutionRepositoryError({ message: "Child execution insert returned no row" }));
@@ -1880,21 +1904,21 @@ var layer6 = Layer6.effect(Service6, Effect6.gen(function* () {
1880
1904
  });
1881
1905
  const get3 = Effect6.fn("ChildExecutionRepository.get")(function* (id2) {
1882
1906
  const tenantId2 = yield* current;
1883
- const rows = yield* mapDatabaseError4(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq5(relayChildExecutions.id, id2))).limit(1));
1907
+ const rows = yield* mapDatabaseError3(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq4(relayChildExecutions.id, id2))).limit(1));
1884
1908
  return rows[0] === undefined ? undefined : toRecord3(rows[0]);
1885
1909
  });
1886
1910
  const listByExecution = Effect6.fn("ChildExecutionRepository.listByExecution")(function* (executionId) {
1887
1911
  const tenantId2 = yield* current;
1888
- const rows = yield* mapDatabaseError4(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq5(relayChildExecutions.executionId, executionId))).orderBy(asc3(relayChildExecutions.createdAt)));
1912
+ const rows = yield* mapDatabaseError3(db.select().from(relayChildExecutions).where(predicate(tenantId2, relayChildExecutions.tenantId, eq4(relayChildExecutions.executionId, executionId))).orderBy(asc3(relayChildExecutions.createdAt)));
1889
1913
  return rows.map(toRecord3);
1890
1914
  });
1891
1915
  const updateStatus = Effect6.fn("ChildExecutionRepository.updateStatus")(function* (input) {
1892
1916
  const tenantId2 = yield* current;
1893
- const rows = yield* mapDatabaseError4(db.update(relayChildExecutions).set({
1917
+ const rows = yield* mapDatabaseError3(db.update(relayChildExecutions).set({
1894
1918
  status: input.status,
1895
1919
  updatedAt: toPgDate(input.updatedAt),
1896
1920
  ...input.metadata === undefined ? {} : { metadataJson: input.metadata }
1897
- }).where(predicate(tenantId2, relayChildExecutions.tenantId, eq5(relayChildExecutions.id, input.id))).returning());
1921
+ }).where(predicate(tenantId2, relayChildExecutions.tenantId, eq4(relayChildExecutions.id, input.id))).returning());
1898
1922
  const row = rows[0];
1899
1923
  if (row === undefined)
1900
1924
  return yield* Effect6.fail(new ChildExecutionNotFound({ id: input.id }));
@@ -1972,7 +1996,7 @@ __export(exports_cluster_registry_repository, {
1972
1996
  ClusterRegistryError: () => ClusterRegistryError
1973
1997
  });
1974
1998
  import { Context as Context7, Effect as Effect7, Layer as Layer7, Schema as Schema17 } from "effect";
1975
- import { SqlClient as SqlClient3, SqlSchema } from "effect/unstable/sql";
1999
+ import { SqlClient as SqlClient5, SqlSchema } from "effect/unstable/sql";
1976
2000
 
1977
2001
  class ClusterRegistryError extends Schema17.TaggedErrorClass()("ClusterRegistryError", {
1978
2002
  message: Schema17.String
@@ -1998,7 +2022,7 @@ var toRunnerRecord = (row) => ({
1998
2022
  });
1999
2023
  var toRegistryError = (error) => new ClusterRegistryError({ message: String(error) });
2000
2024
  var layer7 = Layer7.effect(Service7, Effect7.gen(function* () {
2001
- const sql5 = yield* SqlClient3.SqlClient;
2025
+ const sql5 = yield* SqlClient5.SqlClient;
2002
2026
  const runnersQuery = SqlSchema.findAll({
2003
2027
  Request: Schema17.Void,
2004
2028
  Result: RunnerRow,
@@ -2051,7 +2075,7 @@ __export(exports_compaction_repository, {
2051
2075
  Service: () => Service8,
2052
2076
  CompactionRepositoryError: () => CompactionRepositoryError
2053
2077
  });
2054
- import { asc as asc4, eq as eq6 } from "drizzle-orm";
2078
+ import { asc as asc4, eq as eq5 } from "drizzle-orm";
2055
2079
  import { Context as Context8, Effect as Effect8, Layer as Layer8, Schema as Schema18 } from "effect";
2056
2080
  class CompactionRepositoryError extends Schema18.TaggedErrorClass()("CompactionRepositoryError", {
2057
2081
  message: Schema18.String
@@ -2068,7 +2092,7 @@ var toRecord4 = (row) => ({
2068
2092
  turn: row.turn,
2069
2093
  createdAt: fromPgDate(row.createdAt)
2070
2094
  });
2071
- var mapDatabaseError5 = (effect) => effect.pipe(Effect8.mapError((error) => new CompactionRepositoryError({ message: String(error) })));
2095
+ var mapDatabaseError4 = (effect) => effect.pipe(Effect8.mapError((error) => new CompactionRepositoryError({ message: String(error) })));
2072
2096
  var key = (input) => `${input.executionId}:${input.checkpointId}`;
2073
2097
  var sameCheckpoint = (record, input) => record.summary === input.summary && record.firstKeptEntryId === input.firstKeptEntryId && record.turn === input.turn;
2074
2098
  var conflict = (input) => new CompactionRepositoryError({
@@ -2079,7 +2103,7 @@ var layer8 = Layer8.effect(Service8, Effect8.gen(function* () {
2079
2103
  const db = yield* Service;
2080
2104
  const get4 = Effect8.fn("CompactionRepository.get")(function* (input) {
2081
2105
  const tenantId2 = yield* current;
2082
- const rows = yield* mapDatabaseError5(db.select().from(relayAgentCompactions).where(predicate(tenantId2, relayAgentCompactions.tenantId, eq6(relayAgentCompactions.executionId, input.executionId), eq6(relayAgentCompactions.checkpointId, input.checkpointId))).limit(1));
2106
+ const rows = yield* mapDatabaseError4(db.select().from(relayAgentCompactions).where(predicate(tenantId2, relayAgentCompactions.tenantId, eq5(relayAgentCompactions.executionId, input.executionId), eq5(relayAgentCompactions.checkpointId, input.checkpointId))).limit(1));
2083
2107
  return rows[0] === undefined ? undefined : toRecord4(rows[0]);
2084
2108
  });
2085
2109
  const record = Effect8.fn("CompactionRepository.record")(function* (input) {
@@ -2090,7 +2114,7 @@ var layer8 = Layer8.effect(Service8, Effect8.gen(function* () {
2090
2114
  return yield* Effect8.fail(conflict(input));
2091
2115
  return existing;
2092
2116
  }
2093
- const rows = yield* mapDatabaseError5(db.insert(relayAgentCompactions).values({
2117
+ const rows = yield* mapDatabaseError4(db.insert(relayAgentCompactions).values({
2094
2118
  tenantId: tenantId2,
2095
2119
  executionId: input.executionId,
2096
2120
  checkpointId: input.checkpointId,
@@ -2115,7 +2139,7 @@ var layer8 = Layer8.effect(Service8, Effect8.gen(function* () {
2115
2139
  });
2116
2140
  const list3 = Effect8.fn("CompactionRepository.list")(function* (executionId) {
2117
2141
  const tenantId2 = yield* current;
2118
- const rows = yield* mapDatabaseError5(db.select().from(relayAgentCompactions).where(predicate(tenantId2, relayAgentCompactions.tenantId, eq6(relayAgentCompactions.executionId, executionId))).orderBy(asc4(relayAgentCompactions.turn), asc4(relayAgentCompactions.checkpointId)));
2142
+ const rows = yield* mapDatabaseError4(db.select().from(relayAgentCompactions).where(predicate(tenantId2, relayAgentCompactions.tenantId, eq5(relayAgentCompactions.executionId, executionId))).orderBy(asc4(relayAgentCompactions.turn), asc4(relayAgentCompactions.checkpointId)));
2119
2143
  return rows.map(toRecord4);
2120
2144
  });
2121
2145
  return Service8.of({ get: get4, record, list: list3 });
@@ -2172,16 +2196,19 @@ __export(exports_envelope_repository, {
2172
2196
  ackReady: () => ackReady,
2173
2197
  acceptEnvelope: () => acceptEnvelope,
2174
2198
  WaitState: () => WaitState,
2199
+ WaitRow: () => WaitRow,
2175
2200
  WaitNotFound: () => WaitNotFound,
2176
2201
  Service: () => Service9,
2202
+ EnvelopeRow: () => EnvelopeRow,
2177
2203
  EnvelopeRepositoryError: () => EnvelopeRepositoryError,
2178
2204
  EnvelopeReadyState: () => EnvelopeReadyState,
2205
+ EnvelopeReadyRow: () => EnvelopeReadyRow,
2179
2206
  EnvelopeReadyNotFound: () => EnvelopeReadyNotFound,
2180
2207
  EnvelopeReadyClaimMismatch: () => EnvelopeReadyClaimMismatch,
2181
2208
  EnvelopeNotFound: () => EnvelopeNotFound
2182
2209
  });
2183
- import { and as and2, asc as asc5, desc as desc2, eq as eq7, inArray, lte, or, sql as sql5 } from "drizzle-orm";
2184
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";
2185
2212
  var WaitState = Schema19.Literals(["open", "resolved", "timed_out", "cancelled"]).annotate({
2186
2213
  identifier: "Relay.Store.WaitState"
2187
2214
  });
@@ -2217,87 +2244,98 @@ class EnvelopeReadyClaimMismatch extends Schema19.TaggedErrorClass()("EnvelopeRe
2217
2244
 
2218
2245
  class Service9 extends Context9.Service()("@relayfx/store-sql/EnvelopeRepository") {
2219
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" });
2220
2290
  var metadata3 = (input) => input ?? {};
2221
- var toEnvelopeRow = (tenantId2, input) => ({
2222
- tenantId: tenantId2,
2223
- id: input.id,
2224
- executionId: input.execution_id,
2225
- fromAddressId: input.from,
2226
- toAddressId: input.to,
2227
- contentJson: input.content,
2228
- metadataJson: metadata3(input.metadata),
2229
- createdAt: toPgDate(input.created_at),
2230
- ...input.wait === undefined ? {} : { waitJson: input.wait },
2231
- ...input.correlation_key === undefined ? {} : { correlationKey: input.correlation_key }
2232
- });
2233
- var toEnvelope = (row) => ({
2234
- id: row.id,
2235
- execution_id: row.executionId,
2236
- from: row.fromAddressId,
2237
- to: row.toAddressId,
2238
- content: row.contentJson,
2239
- ...row.waitJson === null ? {} : { wait: row.waitJson },
2240
- ...row.correlationKey === null ? {} : { correlation_key: row.correlationKey },
2241
- metadata: row.metadataJson,
2242
- created_at: fromPgDate(row.createdAt)
2243
- });
2244
- var toWaitInsert = (tenantId2, input) => {
2245
- if (input.waitId === undefined || input.envelope.wait === undefined)
2246
- 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);
2247
2294
  return {
2248
- tenantId: tenantId2,
2249
- id: input.waitId,
2250
- executionId: input.envelope.execution_id,
2251
- envelopeId: input.envelope.id,
2252
- mode: input.envelope.wait.mode,
2253
- metadataJson: metadata3(input.envelope.wait.metadata),
2254
- createdAt: toPgDate(input.envelope.created_at),
2255
- ...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)
2256
2304
  };
2257
2305
  };
2258
2306
  var toWaitRecord = (row) => {
2259
- const resolvedAt = fromNullablePgDate(row.resolvedAt);
2307
+ const resolvedAt = fromNullableDbTimestamp(row.resolved_at);
2260
2308
  return {
2261
- id: row.id,
2262
- executionId: row.executionId,
2263
- ...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) },
2264
2312
  mode: row.mode,
2265
- ...row.correlationKey === null ? {} : { correlationKey: row.correlationKey },
2313
+ ...row.correlation_key === null ? {} : { correlationKey: row.correlation_key },
2266
2314
  state: row.state,
2267
- metadata: row.metadataJson,
2268
- createdAt: fromPgDate(row.createdAt),
2315
+ metadata: decodeMetadata(row.metadata_json),
2316
+ createdAt: fromDbTimestamp(row.created_at),
2269
2317
  ...resolvedAt === undefined ? {} : { resolvedAt }
2270
2318
  };
2271
2319
  };
2272
- var toReadyInsert = (tenantId2, envelope, input) => ({
2273
- tenantId: tenantId2,
2274
- id: input.id,
2275
- envelopeId: envelope.id,
2276
- routeType: input.routeType,
2277
- routeKey: input.routeKey,
2278
- availableAt: toPgDate(input.availableAt),
2279
- metadataJson: metadata3(input.metadata),
2280
- ...input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }
2281
- });
2282
2320
  var toReadyRecord = (row) => {
2283
- const claimExpiresAt = fromNullablePgDate(row.claimExpiresAt);
2284
- const claimedAt = fromNullablePgDate(row.claimedAt);
2285
- 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);
2286
2324
  return {
2287
- id: row.id,
2288
- envelopeId: row.envelopeId,
2289
- routeType: row.routeType,
2290
- 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,
2291
2329
  state: row.state,
2292
- availableAt: fromPgDate(row.availableAt),
2330
+ availableAt: fromDbTimestamp(row.available_at),
2293
2331
  attempt: row.attempt,
2294
- ...row.claimOwner === null ? {} : { claimOwner: row.claimOwner },
2332
+ ...row.claim_owner === null ? {} : { claimOwner: row.claim_owner },
2295
2333
  ...claimExpiresAt === undefined ? {} : { claimExpiresAt },
2296
- ...row.lastError === null ? {} : { lastError: row.lastError },
2297
- ...row.idempotencyKey === null ? {} : { idempotencyKey: row.idempotencyKey },
2298
- metadata: row.metadataJson,
2299
- createdAt: fromPgDate(row.createdAt),
2300
- 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),
2301
2339
  ...claimedAt === undefined ? {} : { claimedAt },
2302
2340
  ...acknowledgedAt === undefined ? {} : { acknowledgedAt }
2303
2341
  };
@@ -2310,50 +2348,85 @@ var accepted = (input) => ({
2310
2348
  var maxListWaitsLimit = 500;
2311
2349
  var defaultListWaitsLimit = 50;
2312
2350
  var listWaitsLimit = (input) => Math.min(Math.max(input.limit ?? defaultListWaitsLimit, 1), maxListWaitsLimit);
2313
- var listWaitsConditions = (input) => [
2314
- input.executionId === undefined ? undefined : eq7(relayWaits.executionId, input.executionId),
2315
- input.state === undefined ? undefined : eq7(relayWaits.state, input.state)
2316
- ].filter((condition) => condition !== undefined);
2317
2351
  var compareWaitsDesc = (left, right) => right.createdAt - left.createdAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
2318
- var mapDatabaseError6 = (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";
2319
2359
  var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2320
- 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
+ });
2321
2383
  const acceptEnvelope = Effect9.fn("EnvelopeRepository.acceptEnvelope")(function* (input) {
2322
2384
  const tenantId2 = yield* current;
2323
- const wait = toWaitInsert(tenantId2, input);
2324
- yield* mapDatabaseError6(db.transaction((tx) => Effect9.gen(function* () {
2325
- yield* tx.insert(relayEnvelopes).values(toEnvelopeRow(tenantId2, input.envelope));
2326
- if (wait !== undefined) {
2327
- 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
+ `;
2328
2399
  }
2329
- if (input.ready !== undefined) {
2330
- 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
+ `;
2331
2405
  }
2332
- })));
2406
+ })).pipe(Effect9.mapError(toRepositoryError2));
2333
2407
  return accepted(input);
2334
2408
  });
2335
2409
  const getEnvelope = Effect9.fn("EnvelopeRepository.getEnvelope")(function* (id2) {
2336
2410
  const tenantId2 = yield* current;
2337
- const rows = yield* mapDatabaseError6(db.select().from(relayEnvelopes).where(predicate(tenantId2, relayEnvelopes.tenantId, eq7(relayEnvelopes.id, id2))).limit(1));
2338
- 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]));
2339
2417
  });
2340
2418
  const getWait = Effect9.fn("EnvelopeRepository.getWait")(function* (id2) {
2341
2419
  const tenantId2 = yield* current;
2342
- const rows = yield* mapDatabaseError6(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, eq7(relayWaits.id, id2))).limit(1));
2343
- return rows[0] === undefined ? undefined : toWaitRecord(rows[0]);
2420
+ const row = yield* getWaitRow(tenantId2, id2);
2421
+ return row === undefined ? undefined : toWaitRecord(row);
2344
2422
  });
2345
2423
  const createWait = Effect9.fn("EnvelopeRepository.createWait")(function* (input) {
2346
2424
  const tenantId2 = yield* current;
2347
- const rows = yield* mapDatabaseError6(db.insert(relayWaits).values({
2348
- tenantId: tenantId2,
2349
- id: input.waitId,
2350
- executionId: input.executionId,
2351
- mode: input.mode,
2352
- metadataJson: metadata3(input.metadata),
2353
- createdAt: toPgDate(input.createdAt),
2354
- ...input.correlationKey === undefined ? {} : { correlationKey: input.correlationKey }
2355
- }).returning());
2356
- 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);
2357
2430
  if (row === undefined) {
2358
2431
  return yield* Effect9.fail(new EnvelopeRepositoryError({ message: `Wait ${input.waitId} was not persisted` }));
2359
2432
  }
@@ -2361,79 +2434,232 @@ var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2361
2434
  });
2362
2435
  const listWaits = Effect9.fn("EnvelopeRepository.listWaits")(function* (input) {
2363
2436
  const tenantId2 = yield* current;
2364
- const rows = yield* mapDatabaseError6(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, ...listWaitsConditions(input))).orderBy(desc2(relayWaits.createdAt), desc2(relayWaits.id)).limit(listWaitsLimit(input)));
2365
- 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
+ })
2366
2521
  });
2367
2522
  const claimReady = Effect9.fn("EnvelopeRepository.claimReady")(function* (input) {
2368
2523
  const tenantId2 = yield* current;
2369
- const candidate = db.select({ id: relayEnvelopeReady.id }).from(relayEnvelopeReady).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq7(relayEnvelopeReady.routeType, input.routeType), input.routeKey === undefined ? undefined : eq7(relayEnvelopeReady.routeKey, input.routeKey), or(and2(eq7(relayEnvelopeReady.state, "ready"), lte(relayEnvelopeReady.availableAt, toPgDate(input.now))), and2(eq7(relayEnvelopeReady.state, "claimed"), lte(relayEnvelopeReady.claimExpiresAt, toPgDate(input.now)))))).orderBy(asc5(relayEnvelopeReady.availableAt), asc5(relayEnvelopeReady.createdAt)).limit(1).for("update", { skipLocked: true });
2370
- const rows = yield* mapDatabaseError6(db.update(relayEnvelopeReady).set({
2371
- state: "claimed",
2372
- claimOwner: input.workerId,
2373
- claimExpiresAt: toPgDate(input.claimExpiresAt),
2374
- claimedAt: toPgDate(input.now),
2375
- updatedAt: toPgDate(input.now),
2376
- attempt: sql5`${relayEnvelopeReady.attempt} + 1`
2377
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, inArray(relayEnvelopeReady.id, candidate))).returning());
2378
- 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
+ `
2379
2562
  });
2380
2563
  const releaseReady = Effect9.fn("EnvelopeRepository.releaseReady")(function* (input) {
2381
2564
  const tenantId2 = yield* current;
2382
- const rows = yield* mapDatabaseError6(db.update(relayEnvelopeReady).set({
2383
- state: "ready",
2384
- availableAt: toPgDate(input.nextAvailableAt),
2385
- claimOwner: null,
2386
- claimExpiresAt: null,
2387
- lastError: input.error ?? null,
2388
- updatedAt: toPgDate(input.nextAvailableAt)
2389
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq7(relayEnvelopeReady.id, input.id), eq7(relayEnvelopeReady.claimOwner, input.workerId), eq7(relayEnvelopeReady.state, "claimed"))).returning());
2390
- const row = rows[0];
2391
- if (row !== undefined)
2392
- return toReadyRecord(row);
2393
- 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);
2394
2569
  if (current2 === undefined)
2395
2570
  return yield* Effect9.fail(new EnvelopeReadyNotFound({ id: input.id }));
2396
- if (current2.state === "acknowledged" && current2.claimOwner === input.workerId)
2571
+ if (current2.state === "acknowledged" && current2.claim_owner === input.workerId)
2397
2572
  return toReadyRecord(current2);
2398
2573
  return yield* Effect9.fail(new EnvelopeReadyClaimMismatch({ id: input.id, worker_id: input.workerId }));
2399
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
+ });
2400
2605
  const ackReady = Effect9.fn("EnvelopeRepository.ackReady")(function* (input) {
2401
2606
  const tenantId2 = yield* current;
2402
- const rows = yield* mapDatabaseError6(db.update(relayEnvelopeReady).set({
2403
- state: "acknowledged",
2404
- acknowledgedAt: toPgDate(input.now),
2405
- updatedAt: toPgDate(input.now)
2406
- }).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq7(relayEnvelopeReady.id, input.id), eq7(relayEnvelopeReady.claimOwner, input.workerId), eq7(relayEnvelopeReady.state, "claimed"))).returning());
2407
- const row = rows[0];
2408
- if (row !== undefined)
2409
- return toReadyRecord(row);
2410
- 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);
2411
2611
  if (current2 === undefined)
2412
2612
  return yield* Effect9.fail(new EnvelopeReadyNotFound({ id: input.id }));
2413
- if (current2.state === "acknowledged" && current2.claimOwner === input.workerId)
2613
+ if (current2.state === "acknowledged" && current2.claim_owner === input.workerId)
2414
2614
  return toReadyRecord(current2);
2415
2615
  return yield* Effect9.fail(new EnvelopeReadyClaimMismatch({ id: input.id, worker_id: input.workerId }));
2416
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
+ });
2417
2646
  const completeWait = Effect9.fn("EnvelopeRepository.completeWait")(function* (input) {
2418
2647
  const tenantId2 = yield* current;
2419
- const current2 = yield* getWaitRow(db, tenantId2, input.waitId);
2648
+ const current2 = yield* getWaitRow(tenantId2, input.waitId);
2420
2649
  if (current2 === undefined)
2421
2650
  return yield* Effect9.fail(new WaitNotFound({ id: input.waitId }));
2422
- if (current2.state !== "open")
2423
- return { wait: toWaitRecord(current2), transitioned: false };
2424
- const rows = yield* mapDatabaseError6(db.update(relayWaits).set({
2425
- state: input.state,
2426
- resolvedAt: toPgDate(input.completedAt),
2427
- metadataJson: { ...current2.metadataJson, ...metadata3(input.metadata) }
2428
- }).where(predicate(tenantId2, relayWaits.tenantId, eq7(relayWaits.id, input.waitId), eq7(relayWaits.state, "open"))).returning());
2429
- const row = rows[0];
2430
- if (row === undefined) {
2431
- 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);
2432
2658
  if (latest === undefined)
2433
2659
  return yield* Effect9.fail(new WaitNotFound({ id: input.waitId }));
2434
2660
  return { wait: toWaitRecord(latest), transitioned: false };
2435
2661
  }
2436
- return { wait: toWaitRecord(row), transitioned: true };
2662
+ return { wait: toWaitRecord(yield* decodeWaitRow(rows[0])), transitioned: true };
2437
2663
  });
2438
2664
  const resolveWait = Effect9.fn("EnvelopeRepository.resolveWait")(function* (input) {
2439
2665
  const result = yield* completeWait({
@@ -2457,8 +2683,6 @@ var layer9 = Layer9.effect(Service9, Effect9.gen(function* () {
2457
2683
  resolveWait
2458
2684
  });
2459
2685
  }));
2460
- var getReadyRow = (db, tenantId2, id2) => mapDatabaseError6(db.select().from(relayEnvelopeReady).where(predicate(tenantId2, relayEnvelopeReady.tenantId, eq7(relayEnvelopeReady.id, id2))).limit(1)).pipe(Effect9.map((rows) => rows[0]));
2461
- var getWaitRow = (db, tenantId2, id2) => mapDatabaseError6(db.select().from(relayWaits).where(predicate(tenantId2, relayWaits.tenantId, eq7(relayWaits.id, id2))).limit(1)).pipe(Effect9.map((rows) => rows[0]));
2462
2686
  var memoryLayer7 = Layer9.sync(Service9, () => {
2463
2687
  const envelopes = new Map;
2464
2688
  const waits = new Map;
@@ -2668,7 +2892,7 @@ __export(exports_execution_event_repository, {
2668
2892
  ExecutionEventCursorNotFound: () => ExecutionEventCursorNotFound,
2669
2893
  DuplicateExecutionEvent: () => DuplicateExecutionEvent
2670
2894
  });
2671
- import { asc as asc6, desc as desc3, eq as eq8, 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";
2672
2896
  import { Context as Context10, Effect as Effect10, Filter, Layer as Layer10, Option as Option2, Schema as Schema20, Stream } from "effect";
2673
2897
  var executionEventsChannel = "relay_execution_events";
2674
2898
 
@@ -2732,7 +2956,7 @@ var toEvent = (row) => ({
2732
2956
  data: row.dataJson,
2733
2957
  created_at: fromPgDate(row.createdAt)
2734
2958
  });
2735
- var mapDatabaseError7 = (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) })));
2736
2960
  var mapSqlError = (error) => new ExecutionEventRepositoryError({ message: String(error) });
2737
2961
  var appendedSignalPayload = (tenantId2, event) => JSON.stringify({ tenantId: tenantId2, executionId: event.execution_id, sequence: event.sequence });
2738
2962
  var parseAppendedSignal = (tenantId2, executionId, payload) => {
@@ -2778,7 +3002,7 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2778
3002
  const db = yield* Service;
2779
3003
  const append = Effect10.fn("ExecutionEventRepository.append")(function* (input) {
2780
3004
  const tenantId2 = yield* current;
2781
- const previousRows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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));
2782
3006
  const previous = previousRows[0];
2783
3007
  if (previous !== undefined && input.sequence === previous.sequence) {
2784
3008
  return yield* Effect10.fail(duplicateError(input));
@@ -2790,11 +3014,11 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2790
3014
  previous_sequence: previous.sequence
2791
3015
  }));
2792
3016
  }
2793
- const duplicateCursorRows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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));
2794
3018
  if (duplicateCursorRows[0] !== undefined) {
2795
3019
  return yield* Effect10.fail(duplicateError(input));
2796
3020
  }
2797
- const rows = yield* mapDatabaseError7(db.insert(relayExecutionEvents).values(toRow(tenantId2, input)).returning());
3021
+ const rows = yield* mapDatabaseError5(db.insert(relayExecutionEvents).values(toRow(tenantId2, input)).returning());
2798
3022
  const row = rows[0];
2799
3023
  if (row === undefined) {
2800
3024
  return yield* Effect10.fail(new ExecutionEventRepositoryError({ message: "Execution event append returned no row" }));
@@ -2804,49 +3028,49 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2804
3028
  const list4 = Effect10.fn("ExecutionEventRepository.list")(function* (input) {
2805
3029
  const tenantId2 = yield* current;
2806
3030
  if (input.afterCursor === undefined) {
2807
- const rows2 = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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)));
2808
3032
  return rows2.map(toEvent);
2809
3033
  }
2810
- const cursorRows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, input.executionId), eq8(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));
2811
3035
  const cursorRow = cursorRows[0];
2812
3036
  if (cursorRow === undefined) {
2813
3037
  return yield* Effect10.fail(new ExecutionEventCursorNotFound({ execution_id: input.executionId, cursor: input.afterCursor }));
2814
3038
  }
2815
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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)));
2816
3040
  return rows.map(toEvent);
2817
3041
  });
2818
3042
  const findBySequenceOrCursor = Effect10.fn("ExecutionEventRepository.findBySequenceOrCursor")(function* (input) {
2819
3043
  const tenantId2 = yield* current;
2820
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, input.executionId), or2(eq8(relayExecutionEvents.sequence, input.sequence), eq8(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));
2821
3045
  const row = rows[0];
2822
3046
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2823
3047
  });
2824
3048
  const findByCursor = Effect10.fn("ExecutionEventRepository.findByCursor")(function* (input) {
2825
3049
  const tenantId2 = yield* current;
2826
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, input.executionId), eq8(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));
2827
3051
  const row = rows[0];
2828
3052
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2829
3053
  });
2830
3054
  const findFirstByTypeAfterSequence = Effect10.fn("ExecutionEventRepository.findFirstByTypeAfterSequence")(function* (input) {
2831
3055
  const tenantId2 = yield* current;
2832
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, input.executionId), eq8(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));
2833
3057
  const row = rows[0];
2834
3058
  return row === undefined ? Option2.none() : Option2.some(toEvent(row));
2835
3059
  });
2836
3060
  const maxSequence = Effect10.fn("ExecutionEventRepository.maxSequence")(function* (executionId) {
2837
3061
  const tenantId2 = yield* current;
2838
- const rows = yield* mapDatabaseError7(db.select({ value: max(relayExecutionEvents.sequence) }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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))));
2839
3063
  const value = rows[0]?.value;
2840
3064
  return value === null || value === undefined ? undefined : value;
2841
3065
  });
2842
3066
  const sumUsage = Effect10.fn("ExecutionEventRepository.sumUsage")(function* (executionId) {
2843
3067
  const tenantId2 = yield* current;
2844
- const rows = yield* mapDatabaseError7(db.select({
2845
- value: sql6`sum(
3068
+ const rows = yield* mapDatabaseError5(db.select({
3069
+ value: sql5`sum(
2846
3070
  coalesce((${relayExecutionEvents.dataJson} ->> 'input_tokens')::bigint, 0)
2847
3071
  + coalesce((${relayExecutionEvents.dataJson} ->> 'output_tokens')::bigint, 0)
2848
3072
  )`
2849
- }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, executionId), eq8(relayExecutionEvents.type, usageReportedEventType))));
3073
+ }).from(relayExecutionEvents).where(predicate(tenantId2, relayExecutionEvents.tenantId, eq6(relayExecutionEvents.executionId, executionId), eq6(relayExecutionEvents.type, usageReportedEventType))));
2850
3074
  const value = rows[0]?.value;
2851
3075
  return value === null || value === undefined ? 0 : Number(value);
2852
3076
  });
@@ -2857,7 +3081,7 @@ var layer10 = Layer10.effect(Service10, Effect10.gen(function* () {
2857
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)))))));
2858
3082
  const listAfterSequence = Effect10.fn("ExecutionEventRepository.listAfterSequence")(function* (input) {
2859
3083
  const tenantId2 = yield* current;
2860
- const rows = yield* mapDatabaseError7(db.select().from(relayExecutionEvents).where(input.afterSequence === undefined ? predicate(tenantId2, relayExecutionEvents.tenantId, eq8(relayExecutionEvents.executionId, input.executionId)) : predicate(tenantId2, relayExecutionEvents.tenantId, eq8(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));
2861
3085
  return rows.map(toEvent);
2862
3086
  });
2863
3087
  return Service10.of({
@@ -2973,12 +3197,13 @@ __export(exports_execution_repository, {
2973
3197
  get: () => get5,
2974
3198
  create: () => create2,
2975
3199
  Service: () => Service11,
3200
+ ExecutionRow: () => ExecutionRow,
2976
3201
  ExecutionRepositoryError: () => ExecutionRepositoryError,
2977
3202
  ExecutionNotFound: () => ExecutionNotFound,
2978
3203
  DuplicateExecution: () => DuplicateExecution
2979
3204
  });
2980
- import { and as and3, desc as desc4, eq as eq9, lt, or as or3 } from "drizzle-orm";
2981
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";
2982
3207
  class ExecutionRepositoryError extends Schema21.TaggedErrorClass()("ExecutionRepositoryError", {
2983
3208
  message: Schema21.String
2984
3209
  }) {
@@ -2996,6 +3221,19 @@ class ExecutionNotFound extends Schema21.TaggedErrorClass()("ExecutionNotFound",
2996
3221
 
2997
3222
  class Service11 extends Context11.Service()("@relayfx/store-sql/ExecutionRepository") {
2998
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" });
2999
3237
  var metadata4 = (input) => input ?? {};
3000
3238
  var nonEmptyDigests2 = (digests) => digests === undefined || Object.keys(digests).length === 0 ? undefined : structuredClone(digests);
3001
3239
  var hasCompleteAgentDefinitionPin = (input) => {
@@ -3028,37 +3266,25 @@ var cloneRecord3 = (record2) => ({
3028
3266
  ...record2.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshot: cloneAgentDefinition(record2.agentDefinitionSnapshot) },
3029
3267
  ...record2.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests: structuredClone(record2.agentDefinitionToolInputSchemaDigests) }
3030
3268
  });
3031
- var toInsert2 = (tenantId2, input) => ({
3032
- tenantId: tenantId2,
3033
- id: input.id,
3034
- rootAddressId: input.rootAddressId,
3035
- ...input.sessionId === undefined ? {} : { sessionId: input.sessionId },
3036
- status: input.status,
3037
- ...input.agentDefinitionId === undefined ? {} : { agentDefinitionId: input.agentDefinitionId },
3038
- ...input.agentDefinitionRevision === undefined ? {} : { agentDefinitionRevision: input.agentDefinitionRevision },
3039
- ...input.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshotJson: cloneAgentDefinition(input.agentDefinitionSnapshot) },
3040
- ...input.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigestsJson: input.agentDefinitionToolInputSchemaDigests },
3041
- metadataJson: metadata4(input.metadata),
3042
- createdAt: toPgDate(input.createdAt),
3043
- updatedAt: toPgDate(input.createdAt)
3044
- });
3045
3269
  var toRecord5 = (row) => {
3046
- 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));
3047
3272
  return {
3048
- id: row.id,
3049
- rootAddressId: row.rootAddressId,
3050
- ...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) },
3051
3276
  status: row.status,
3052
- ...row.agentDefinitionId === null || row.agentDefinitionId === undefined ? {} : { agentDefinitionId: row.agentDefinitionId },
3053
- ...row.agentDefinitionRevision === null || row.agentDefinitionRevision === undefined ? {} : { agentDefinitionRevision: row.agentDefinitionRevision },
3054
- ...row.agentDefinitionSnapshotJson === null || row.agentDefinitionSnapshotJson === undefined ? {} : { agentDefinitionSnapshot: cloneAgentDefinition(row.agentDefinitionSnapshotJson) },
3055
- ...agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests },
3056
- metadata: row.metadataJson,
3057
- createdAt: fromPgDate(row.createdAt),
3058
- 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)
3059
3284
  };
3060
3285
  };
3061
- var mapDatabaseError8 = (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));
3062
3288
  var maxListLimit2 = 100;
3063
3289
  var defaultListLimit = 50;
3064
3290
  var listLimit2 = (input) => Math.min(Math.max(input.limit ?? defaultListLimit, 1), maxListLimit2);
@@ -3068,51 +3294,127 @@ var nextCursorOf = (records, fetched, limit) => {
3068
3294
  };
3069
3295
  var compareDesc = (left, right) => right.updatedAt - left.updatedAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
3070
3296
  var afterCursor = (record2, cursor) => cursor === undefined || record2.updatedAt < cursor.updatedAt || record2.updatedAt === cursor.updatedAt && record2.id < cursor.id;
3071
- var listConditions = (input) => [
3072
- input.rootAddressId === undefined ? undefined : eq9(relayExecutions.rootAddressId, input.rootAddressId),
3073
- input.sessionId === undefined ? undefined : eq9(relayExecutions.sessionId, input.sessionId),
3074
- input.status === undefined ? undefined : eq9(relayExecutions.status, input.status),
3075
- input.cursor === undefined ? undefined : or3(lt(relayExecutions.updatedAt, toPgDate(input.cursor.updatedAt)), and3(eq9(relayExecutions.updatedAt, toPgDate(input.cursor.updatedAt)), lt(relayExecutions.id, input.cursor.id)))
3076
- ].filter((condition) => condition !== undefined);
3077
3297
  var layer11 = Layer11.effect(Service11, Effect11.gen(function* () {
3078
- 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
+ ];
3079
3378
  const create2 = Effect11.fn("ExecutionRepository.create")(function* (input) {
3080
3379
  const tenantId2 = yield* current;
3081
3380
  yield* validateCreateInput(input);
3082
- const existing = yield* mapDatabaseError8(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq9(relayExecutions.id, input.id))).limit(1));
3381
+ const existing = yield* selectByKey(tenantId2, input.id).pipe(Effect11.mapError(toRepositoryError3));
3083
3382
  if (existing[0] !== undefined)
3084
3383
  return yield* Effect11.fail(new DuplicateExecution({ id: input.id }));
3085
- const rows = yield* mapDatabaseError8(db.insert(relayExecutions).values(toInsert2(tenantId2, input)).returning());
3384
+ const rows = yield* insertExecution(tenantId2, input).pipe(Effect11.mapError(toRepositoryError3));
3086
3385
  const row = rows[0];
3087
3386
  if (row === undefined) {
3088
3387
  return yield* Effect11.fail(new ExecutionRepositoryError({ message: "Execution insert returned no row" }));
3089
3388
  }
3090
- return toRecord5(row);
3389
+ return toRecord5(yield* decodeRow2(row));
3091
3390
  });
3092
3391
  const get5 = Effect11.fn("ExecutionRepository.get")(function* (id2) {
3093
3392
  const tenantId2 = yield* current;
3094
- const rows = yield* mapDatabaseError8(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq9(relayExecutions.id, id2))).limit(1));
3095
- 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]));
3096
3395
  });
3097
3396
  const list5 = Effect11.fn("ExecutionRepository.list")(function* (input) {
3098
3397
  const tenantId2 = yield* current;
3099
3398
  const limit = listLimit2(input);
3100
- const rows = yield* mapDatabaseError8(db.select().from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, ...listConditions(input))).orderBy(desc4(relayExecutions.updatedAt), desc4(relayExecutions.id)).limit(limit + 1));
3101
- 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);
3102
3408
  const nextCursor = nextCursorOf(records, rows.length, limit);
3103
3409
  return nextCursor === undefined ? { records } : { records, nextCursor };
3104
3410
  });
3105
3411
  const transition = Effect11.fn("ExecutionRepository.transition")(function* (input) {
3106
3412
  const tenantId2 = yield* current;
3107
- const rows = yield* mapDatabaseError8(db.update(relayExecutions).set({
3108
- status: input.status,
3109
- metadataJson: metadata4(input.metadata),
3110
- updatedAt: toPgDate(input.updatedAt)
3111
- }).where(predicate(tenantId2, relayExecutions.tenantId, eq9(relayExecutions.id, input.id))).returning());
3413
+ const rows = yield* updateExecution(tenantId2, input).pipe(Effect11.mapError(toRepositoryError3));
3112
3414
  const row = rows[0];
3113
3415
  if (row === undefined)
3114
3416
  return yield* Effect11.fail(new ExecutionNotFound({ id: input.id }));
3115
- return toRecord5(row);
3417
+ return toRecord5(yield* decodeRow2(row));
3116
3418
  });
3117
3419
  return Service11.of({ create: create2, get: get5, list: list5, transition });
3118
3420
  }));
@@ -3187,7 +3489,7 @@ var transition = Effect11.fn("ExecutionRepository.transition.call")(function* (i
3187
3489
  return yield* repository.transition(input);
3188
3490
  });
3189
3491
  // ../store-sql/src/idempotency/idempotency-repository.ts
3190
- import { eq as eq10, sql as sql7 } from "drizzle-orm";
3492
+ import { eq as eq7, sql as sql6 } from "drizzle-orm";
3191
3493
  import { Context as Context12, Effect as Effect12, HashMap, Layer as Layer12, Option as Option3, Ref, Schema as Schema22, Semaphore } from "effect";
3192
3494
  class IdempotencyRepositoryError extends Schema22.TaggedErrorClass()("IdempotencyRepositoryError", {
3193
3495
  message: Schema22.String
@@ -3210,7 +3512,7 @@ var toRecord6 = (row) => {
3210
3512
  ...expiresAt === undefined ? {} : { expiresAt }
3211
3513
  };
3212
3514
  };
3213
- var toInsert3 = (tenantId2, input, result) => ({
3515
+ var toInsert2 = (tenantId2, input, result) => ({
3214
3516
  tenantId: tenantId2,
3215
3517
  id: operationId(input),
3216
3518
  scope: input.scope,
@@ -3227,17 +3529,17 @@ var layer12 = Layer12.effect(Service12, Effect12.gen(function* () {
3227
3529
  const runOnce = (input, create3) => Effect12.gen(function* () {
3228
3530
  const tenantId2 = yield* current;
3229
3531
  return yield* db.transaction((tx) => Effect12.gen(function* () {
3230
- yield* tx.execute(sql7`select pg_advisory_xact_lock(hashtextextended(${`${tenantId2}:${operationId(input)}`}, 0))`);
3231
- const existingRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq10(relayIdempotencyKeys.scope, input.scope), eq10(relayIdempotencyKeys.operation, input.operation), eq10(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);
3232
3534
  const existing = existingRows[0];
3233
3535
  if (existing !== undefined)
3234
3536
  return { replayed: true, record: toRecord6(existing) };
3235
3537
  const result = yield* create3;
3236
- 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();
3237
3539
  const row = rows[0];
3238
3540
  if (row !== undefined)
3239
3541
  return { replayed: false, record: toRecord6(row) };
3240
- const winnerRows = yield* tx.select().from(relayIdempotencyKeys).where(predicate(tenantId2, relayIdempotencyKeys.tenantId, eq10(relayIdempotencyKeys.scope, input.scope), eq10(relayIdempotencyKeys.operation, input.operation), eq10(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);
3241
3543
  const winner = winnerRows[0];
3242
3544
  if (winner === undefined) {
3243
3545
  return yield* Effect12.fail(new IdempotencyRepositoryError({ message: "Idempotency insert returned no row" }));
@@ -3287,7 +3589,7 @@ __export(exports_memory_repository, {
3287
3589
  Service: () => Service13,
3288
3590
  MemoryRepositoryError: () => MemoryRepositoryError
3289
3591
  });
3290
- import { sql as sql8 } from "drizzle-orm";
3592
+ import { sql as sql7 } from "drizzle-orm";
3291
3593
  import { Context as Context13, Effect as Effect13, Layer as Layer13, Ref as Ref2, Schema as Schema23 } from "effect";
3292
3594
  class MemoryRepositoryError extends Schema23.TaggedErrorClass()("MemoryRepositoryError", {
3293
3595
  message: Schema23.String
@@ -3314,7 +3616,7 @@ var queryRowToRecord = (row) => ({
3314
3616
  metadata: row.metadataJson,
3315
3617
  createdAt: fromPgDate(row.createdAt)
3316
3618
  });
3317
- var mapDatabaseError9 = (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) })));
3318
3620
  var parsePgFloatArray = (value) => {
3319
3621
  const body = value.startsWith("{") && value.endsWith("}") ? value.slice(1, -1) : value;
3320
3622
  if (body.length === 0)
@@ -3358,7 +3660,7 @@ var layer13 = Layer13.effect(Service13, Effect13.gen(function* () {
3358
3660
  const upsert2 = Effect13.fn("MemoryRepository.upsert")(function* (input) {
3359
3661
  const tenantId2 = yield* current;
3360
3662
  yield* validateVector("embedding", input.embedding);
3361
- const rows = yield* mapDatabaseError9(db.insert(relayMemoryRecords).values({
3663
+ const rows = yield* mapDatabaseError6(db.insert(relayMemoryRecords).values({
3362
3664
  tenantId: tenantId2,
3363
3665
  id: input.id,
3364
3666
  agent: input.agent,
@@ -3388,8 +3690,8 @@ var layer13 = Layer13.effect(Service13, Effect13.gen(function* () {
3388
3690
  yield* validateVector("query embedding", input.embedding);
3389
3691
  if (input.topK <= 0)
3390
3692
  return [];
3391
- const queryEmbeddingSql = sql8`array[${sql8.join(input.embedding.map((value) => sql8`${value}`), sql8`, `)}]::double precision[]`;
3392
- const rows = yield* mapDatabaseError9(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`
3393
3695
  with query_embedding as (
3394
3696
  select ${queryEmbeddingSql} as embedding
3395
3697
  ),
@@ -3529,7 +3831,7 @@ __export(exports_permission_rule_repository, {
3529
3831
  Service: () => Service14,
3530
3832
  PermissionRuleRepositoryError: () => PermissionRuleRepositoryError
3531
3833
  });
3532
- import { asc as asc7, eq as eq11 } from "drizzle-orm";
3834
+ import { asc as asc6, eq as eq8 } from "drizzle-orm";
3533
3835
  import { Context as Context14, Effect as Effect14, Layer as Layer14, Schema as Schema24 } from "effect";
3534
3836
  class PermissionRuleRepositoryError extends Schema24.TaggedErrorClass()("PermissionRuleRepositoryError", {
3535
3837
  message: Schema24.String
@@ -3544,13 +3846,13 @@ var toRecord8 = (row) => ({
3544
3846
  rule: row.ruleJson,
3545
3847
  createdAt: fromPgDate(row.createdAt)
3546
3848
  });
3547
- var mapDatabaseError10 = (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) })));
3548
3850
  var memoryKey = (agent, scope, pattern) => `${agent}\x00${scope}\x00${pattern}`;
3549
3851
  var layer14 = Layer14.effect(Service14, Effect14.gen(function* () {
3550
3852
  const db = yield* Service;
3551
3853
  const remember = Effect14.fn("PermissionRuleRepository.remember")(function* (input) {
3552
3854
  const tenantId2 = yield* current;
3553
- const rows = yield* mapDatabaseError10(db.insert(relayPermissionRules).values({
3855
+ const rows = yield* mapDatabaseError7(db.insert(relayPermissionRules).values({
3554
3856
  tenantId: tenantId2,
3555
3857
  agent: input.agent,
3556
3858
  scope: input.scope,
@@ -3577,7 +3879,7 @@ var layer14 = Layer14.effect(Service14, Effect14.gen(function* () {
3577
3879
  });
3578
3880
  const list6 = Effect14.fn("PermissionRuleRepository.list")(function* (input) {
3579
3881
  const tenantId2 = yield* current;
3580
- const rows = yield* mapDatabaseError10(db.select().from(relayPermissionRules).where(predicate(tenantId2, relayPermissionRules.tenantId, eq11(relayPermissionRules.agent, input.agent), eq11(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)));
3581
3883
  return rows.map(toRecord8);
3582
3884
  });
3583
3885
  return Service14.of({ remember, list: list6 });
@@ -3620,7 +3922,7 @@ __export(exports_context_epoch_repository, {
3620
3922
  Service: () => Service15,
3621
3923
  ContextEpochRepositoryError: () => ContextEpochRepositoryError
3622
3924
  });
3623
- import { eq as eq12 } from "drizzle-orm";
3925
+ import { eq as eq9 } from "drizzle-orm";
3624
3926
  import { Context as Context15, Effect as Effect15, Layer as Layer15, Schema as Schema25 } from "effect";
3625
3927
  class ContextEpochRepositoryError extends Schema25.TaggedErrorClass()("ContextEpochRepositoryError", {
3626
3928
  message: Schema25.String
@@ -3635,7 +3937,7 @@ var toRecord9 = (row) => ({
3635
3937
  dynamicSourceIds: row.dynamicSourceIdsJson,
3636
3938
  openedAt: fromPgDate(row.openedAt)
3637
3939
  });
3638
- var mapDatabaseError11 = (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) })));
3639
3941
  var sameEpoch = (record2, input) => record2.baseline === input.baseline && JSON.stringify(record2.dynamicSourceIds) === JSON.stringify(input.dynamicSourceIds);
3640
3942
  var conflict2 = (executionId) => new ContextEpochRepositoryError({ message: `Context epoch already exists with different payload: ${executionId}` });
3641
3943
  var cloneRecord5 = (record2) => structuredClone(record2);
@@ -3643,12 +3945,12 @@ var layer15 = Layer15.effect(Service15, Effect15.gen(function* () {
3643
3945
  const db = yield* Service;
3644
3946
  const get6 = Effect15.fn("ContextEpochRepository.get")(function* (executionId) {
3645
3947
  const tenantId2 = yield* current;
3646
- const rows = yield* mapDatabaseError11(db.select().from(relayExecutionContextEpochs).where(predicate(tenantId2, relayExecutionContextEpochs.tenantId, eq12(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));
3647
3949
  return rows[0] === undefined ? undefined : toRecord9(rows[0]);
3648
3950
  });
3649
3951
  const save2 = Effect15.fn("ContextEpochRepository.save")(function* (input) {
3650
3952
  const tenantId2 = yield* current;
3651
- const rows = yield* mapDatabaseError11(db.insert(relayExecutionContextEpochs).values({
3953
+ const rows = yield* mapDatabaseError8(db.insert(relayExecutionContextEpochs).values({
3652
3954
  tenantId: tenantId2,
3653
3955
  executionId: input.executionId,
3654
3956
  baseline: input.baseline,
@@ -3722,7 +4024,7 @@ __export(exports_schedule_repository, {
3722
4024
  ScheduleNotFound: () => ScheduleNotFound,
3723
4025
  ScheduleClaimMismatch: () => ScheduleClaimMismatch
3724
4026
  });
3725
- import { and as and4, asc as asc8, eq as eq13, 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";
3726
4028
  import { Context as Context16, Effect as Effect16, Layer as Layer16, Schema as Schema26 } from "effect";
3727
4029
  class ScheduleRepositoryError extends Schema26.TaggedErrorClass()("ScheduleRepositoryError", {
3728
4030
  message: Schema26.String
@@ -3758,7 +4060,7 @@ var validationError = (input) => {
3758
4060
  }
3759
4061
  return;
3760
4062
  };
3761
- var toInsert4 = (tenantId2, input) => ({
4063
+ var toInsert3 = (tenantId2, input) => ({
3762
4064
  tenantId: tenantId2,
3763
4065
  id: input.id,
3764
4066
  kind: input.kind,
@@ -3789,12 +4091,12 @@ var toRecord10 = (row) => ({
3789
4091
  created_at: fromPgDate(row.createdAt),
3790
4092
  updated_at: fromPgDate(row.updatedAt)
3791
4093
  });
3792
- var mapDatabaseError12 = (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) })));
3793
4095
  var cancellableStates = new Set(["active", "claimed"]);
3794
4096
  var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3795
4097
  const db = yield* Service;
3796
- const getRow = (tenantId2, id2) => mapDatabaseError12(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq13(relaySchedules.id, id2))).limit(1)).pipe(Effect16.map((rows) => rows[0]));
3797
- const getByIdempotencyKey = (tenantId2, key2) => mapDatabaseError12(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, eq13(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]));
3798
4100
  const create3 = Effect16.fn("ScheduleRepository.create")(function* (input) {
3799
4101
  const tenantId2 = yield* current;
3800
4102
  const invalid = validationError(input);
@@ -3805,7 +4107,7 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3805
4107
  if (existing !== undefined)
3806
4108
  return toRecord10(existing);
3807
4109
  }
3808
- const rows = yield* mapDatabaseError12(db.insert(relaySchedules).values(toInsert4(tenantId2, input)).returning());
4110
+ const rows = yield* mapDatabaseError9(db.insert(relaySchedules).values(toInsert3(tenantId2, input)).returning());
3809
4111
  const row = rows[0];
3810
4112
  if (row === undefined) {
3811
4113
  return yield* Effect16.fail(new ScheduleRepositoryError({ message: `Schedule ${input.id} was not persisted` }));
@@ -3819,17 +4121,17 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3819
4121
  });
3820
4122
  const list7 = Effect16.fn("ScheduleRepository.list")(function* (input) {
3821
4123
  const tenantId2 = yield* current;
3822
- const rows = yield* mapDatabaseError12(db.select().from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, input.state === undefined ? undefined : eq13(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)));
3823
4125
  return rows.map(toRecord10);
3824
4126
  });
3825
4127
  const cancel = Effect16.fn("ScheduleRepository.cancel")(function* (input) {
3826
4128
  const tenantId2 = yield* current;
3827
- const rows = yield* mapDatabaseError12(db.update(relaySchedules).set({
4129
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3828
4130
  state: "cancelled",
3829
4131
  claimOwner: null,
3830
4132
  claimExpiresAt: null,
3831
4133
  updatedAt: toPgDate(input.cancelledAt)
3832
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq13(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());
3833
4135
  const row = rows[0];
3834
4136
  if (row !== undefined)
3835
4137
  return toRecord10(row);
@@ -3842,23 +4144,23 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3842
4144
  });
3843
4145
  const claimDue = Effect16.fn("ScheduleRepository.claimDue")(function* (input) {
3844
4146
  const tenantId2 = yield* current;
3845
- const candidate = db.select({ id: relaySchedules.id }).from(relaySchedules).where(predicate(tenantId2, relaySchedules.tenantId, or4(and4(eq13(relaySchedules.state, "active"), lte2(relaySchedules.nextRunAt, toPgDate(input.now))), and4(eq13(relaySchedules.state, "claimed"), lte2(relaySchedules.claimExpiresAt, toPgDate(input.now)))))).orderBy(asc8(relaySchedules.nextRunAt), asc8(relaySchedules.createdAt)).limit(1).for("update", { skipLocked: true });
3846
- const rows = yield* mapDatabaseError12(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({
3847
4149
  state: "claimed",
3848
4150
  claimOwner: input.workerId,
3849
4151
  claimExpiresAt: toPgDate(input.claimExpiresAt),
3850
4152
  updatedAt: toPgDate(input.now),
3851
- attempt: sql9`${relaySchedules.attempt} + 1`
3852
- }).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());
3853
4155
  return rows[0] === undefined ? undefined : toRecord10(rows[0]);
3854
4156
  });
3855
4157
  const ack = Effect16.fn("ScheduleRepository.ack")(function* (input) {
3856
4158
  const tenantId2 = yield* current;
3857
- const rows = yield* mapDatabaseError12(db.update(relaySchedules).set({
4159
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3858
4160
  ...input.nextRunAt === undefined ? { state: "completed" } : { state: "active", nextRunAt: toPgDate(input.nextRunAt), claimOwner: null },
3859
4161
  claimExpiresAt: null,
3860
4162
  updatedAt: toPgDate(input.now)
3861
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq13(relaySchedules.id, input.id), eq13(relaySchedules.claimOwner, input.workerId), eq13(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());
3862
4164
  const row = rows[0];
3863
4165
  if (row !== undefined)
3864
4166
  return toRecord10(row);
@@ -3871,14 +4173,14 @@ var layer16 = Layer16.effect(Service16, Effect16.gen(function* () {
3871
4173
  });
3872
4174
  const release = Effect16.fn("ScheduleRepository.release")(function* (input) {
3873
4175
  const tenantId2 = yield* current;
3874
- const rows = yield* mapDatabaseError12(db.update(relaySchedules).set({
4176
+ const rows = yield* mapDatabaseError9(db.update(relaySchedules).set({
3875
4177
  state: "active",
3876
4178
  nextRunAt: toPgDate(input.nextAvailableAt),
3877
4179
  claimOwner: null,
3878
4180
  claimExpiresAt: null,
3879
4181
  lastError: input.error,
3880
4182
  updatedAt: toPgDate(input.nextAvailableAt)
3881
- }).where(predicate(tenantId2, relaySchedules.tenantId, eq13(relaySchedules.id, input.id), eq13(relaySchedules.claimOwner, input.workerId), eq13(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());
3882
4184
  const row = rows[0];
3883
4185
  if (row !== undefined)
3884
4186
  return toRecord10(row);
@@ -4055,12 +4357,14 @@ __export(exports_session_repository, {
4055
4357
  create: () => create4,
4056
4358
  countEntries: () => countEntries,
4057
4359
  appendEntry: () => appendEntry,
4360
+ SessionRow: () => SessionRow,
4058
4361
  SessionRepositoryError: () => SessionRepositoryError,
4362
+ SessionEntryRow: () => SessionEntryRow,
4059
4363
  Service: () => Service17,
4060
4364
  DuplicateSession: () => DuplicateSession
4061
4365
  });
4062
- import { and as and5, count, desc as desc5, eq as eq14, lt as lt2, or as or5 } from "drizzle-orm";
4063
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";
4064
4368
  class SessionRepositoryError extends Schema27.TaggedErrorClass()("SessionRepositoryError", {
4065
4369
  message: Schema27.String
4066
4370
  }) {
@@ -4073,14 +4377,33 @@ class DuplicateSession extends Schema27.TaggedErrorClass()("DuplicateSession", {
4073
4377
 
4074
4378
  class Service17 extends Context17.Service()("@relayfx/store-sql/SessionRepository") {
4075
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" });
4076
4399
  var metadata7 = (input) => input ?? {};
4077
4400
  var toSessionRecord = (row) => ({
4078
- id: row.id,
4079
- rootAddressId: row.rootAddressId,
4080
- ...row.leafEntryId === null || row.leafEntryId === undefined ? {} : { leafEntryId: row.leafEntryId },
4081
- metadata: row.metadataJson,
4082
- createdAt: fromPgDate(row.createdAt),
4083
- 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)
4084
4407
  });
4085
4408
  var payloadFromInput = (input) => {
4086
4409
  switch (input._tag) {
@@ -4103,12 +4426,12 @@ var payloadFromInput = (input) => {
4103
4426
  }
4104
4427
  };
4105
4428
  var toEntryRecord = (row) => {
4106
- const payload = row.payloadJson;
4429
+ const payload = decodeJson(row.payload_json);
4107
4430
  const base = {
4108
- id: row.id,
4109
- sessionId: row.sessionId,
4110
- parentId: row.parentId,
4111
- 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),
4112
4435
  ...payload.metadata === undefined ? {} : { metadata: payload.metadata }
4113
4436
  };
4114
4437
  switch (row.tag) {
@@ -4135,8 +4458,11 @@ var toEntryRecord = (row) => {
4135
4458
  return Effect17.fail(new SessionRepositoryError({ message: `Unknown session entry tag: ${row.tag}` }));
4136
4459
  }
4137
4460
  };
4138
- var mapDatabaseError13 = (effect) => effect.pipe(Effect17.mapError((error) => new SessionRepositoryError({ message: String(error) })));
4139
- 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));
4140
4466
  var maxListLimit3 = 100;
4141
4467
  var defaultListLimit2 = 50;
4142
4468
  var listLimit3 = (input) => Math.min(Math.max(input.limit ?? defaultListLimit2, 1), maxListLimit3);
@@ -4146,10 +4472,6 @@ var nextCursorOf2 = (records, fetched, limit) => {
4146
4472
  };
4147
4473
  var compareDesc2 = (left, right) => right.updatedAt - left.updatedAt || (left.id < right.id ? 1 : left.id > right.id ? -1 : 0);
4148
4474
  var afterCursor2 = (record2, cursor) => cursor === undefined || record2.updatedAt < cursor.updatedAt || record2.updatedAt === cursor.updatedAt && record2.id < cursor.id;
4149
- var listConditions2 = (input) => [
4150
- input.rootAddressId === undefined ? undefined : eq14(relaySessions.rootAddressId, input.rootAddressId),
4151
- input.cursor === undefined ? undefined : or5(lt2(relaySessions.updatedAt, toPgDate(input.cursor.updatedAt)), and5(eq14(relaySessions.updatedAt, toPgDate(input.cursor.updatedAt)), lt2(relaySessions.id, input.cursor.id)))
4152
- ].filter((condition) => condition !== undefined);
4153
4475
  var comparableEntry = (entry) => {
4154
4476
  const { createdAt: _createdAt, ...value } = entry;
4155
4477
  return value;
@@ -4190,19 +4512,58 @@ var validateCompaction = (currentPath, input) => {
4190
4512
  return currentPath.some((item) => item.id === entry.firstKeptEntryId) ? Effect17.void : Effect17.fail(missingEntry(entry.firstKeptEntryId));
4191
4513
  };
4192
4514
  var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4193
- 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
+ });
4194
4551
  const getForTenant = Effect17.fn("SessionRepository.getForTenant")(function* (tenantId2, id2) {
4195
- const rows = yield* mapDatabaseError13(db.select().from(relaySessions).where(predicate(tenantId2, relaySessions.tenantId, eq14(relaySessions.id, id2))).limit(1));
4196
- 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;
4197
4560
  });
4198
4561
  const entryById = Effect17.fn("SessionRepository.entryById")(function* (tenantId2, sessionId, id2) {
4199
- const rows = yield* mapDatabaseError13(db.select().from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq14(relaySessionEntries.id, id2), eq14(relaySessionEntries.sessionId, sessionId))).limit(1));
4200
- 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]));
4201
4564
  });
4202
4565
  const pathForTenant = Effect17.fn("SessionRepository.pathForTenant")(function* (tenantId2, input) {
4203
- const session = yield* getForTenant(tenantId2, input.sessionId);
4204
- if (session === undefined)
4205
- return yield* Effect17.fail(missingSession(input.sessionId));
4566
+ const session = yield* requireSession(tenantId2, input.sessionId);
4206
4567
  const start = input.leafId ?? session.leafEntryId;
4207
4568
  if (start === undefined)
4208
4569
  return [];
@@ -4231,18 +4592,16 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4231
4592
  const existing = yield* getForTenant(tenantId2, input.id);
4232
4593
  if (existing !== undefined)
4233
4594
  return yield* Effect17.fail(new DuplicateSession({ id: input.id }));
4234
- const rows = yield* mapDatabaseError13(db.insert(relaySessions).values({
4235
- tenantId: tenantId2,
4595
+ yield* mapRepositoryError(insertSession(tenantId2, {
4236
4596
  id: input.id,
4237
4597
  rootAddressId: input.rootAddressId,
4238
- metadataJson: metadata7(input.metadata),
4239
- createdAt: toPgDate(input.createdAt),
4240
- updatedAt: toPgDate(input.createdAt)
4241
- }).returning());
4242
- const row = rows[0];
4243
- 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)
4244
4603
  return yield* Effect17.fail(new SessionRepositoryError({ message: "Session insert returned no row" }));
4245
- return toSessionRecord(row);
4604
+ return created;
4246
4605
  });
4247
4606
  const ensure = Effect17.fn("SessionRepository.ensure")(function* (input) {
4248
4607
  const tenantId2 = yield* current;
@@ -4250,24 +4609,19 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4250
4609
  if (existing !== undefined) {
4251
4610
  if (existing.rootAddressId !== input.rootAddressId)
4252
4611
  return yield* Effect17.fail(rootMismatch(input.id));
4253
- const rows2 = yield* mapDatabaseError13(db.update(relaySessions).set({ updatedAt: toPgDate(input.now) }).where(predicate(tenantId2, relaySessions.tenantId, eq14(relaySessions.id, input.id))).returning());
4254
- const row2 = rows2[0];
4255
- if (row2 === undefined)
4256
- return yield* Effect17.fail(missingSession(input.id));
4257
- return toSessionRecord(row2);
4612
+ yield* mapRepositoryError(touchSession(tenantId2, input.id, input.now));
4613
+ return yield* requireSession(tenantId2, input.id);
4258
4614
  }
4259
- const rows = yield* mapDatabaseError13(db.insert(relaySessions).values({
4260
- tenantId: tenantId2,
4615
+ yield* mapRepositoryError(insertSession(tenantId2, {
4261
4616
  id: input.id,
4262
4617
  rootAddressId: input.rootAddressId,
4263
- metadataJson: metadata7(input.metadata),
4264
- createdAt: toPgDate(input.now),
4265
- updatedAt: toPgDate(input.now)
4266
- }).returning());
4267
- const row = rows[0];
4268
- 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)
4269
4623
  return yield* Effect17.fail(new SessionRepositoryError({ message: "Session insert returned no row" }));
4270
- return toSessionRecord(row);
4624
+ return created;
4271
4625
  });
4272
4626
  const get8 = Effect17.fn("SessionRepository.get")(function* (id2) {
4273
4627
  const tenantId2 = yield* current;
@@ -4276,36 +4630,46 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4276
4630
  const list8 = Effect17.fn("SessionRepository.list")(function* (input) {
4277
4631
  const tenantId2 = yield* current;
4278
4632
  const limit = listLimit3(input);
4279
- const rows = yield* mapDatabaseError13(db.select().from(relaySessions).where(predicate(tenantId2, relaySessions.tenantId, ...listConditions2(input))).orderBy(desc5(relaySessions.updatedAt), desc5(relaySessions.id)).limit(limit + 1));
4280
- 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)));
4281
4652
  const nextCursor = nextCursorOf2(records, rows.length, limit);
4282
4653
  return nextCursor === undefined ? { records } : { records, nextCursor };
4283
4654
  });
4284
4655
  const touch = Effect17.fn("SessionRepository.touch")(function* (input) {
4285
4656
  const tenantId2 = yield* current;
4286
- const rows = yield* mapDatabaseError13(db.update(relaySessions).set({ updatedAt: toPgDate(input.updatedAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq14(relaySessions.id, input.id))).returning());
4287
- const row = rows[0];
4288
- if (row === undefined)
4289
- return yield* Effect17.fail(missingSession(input.id));
4290
- return toSessionRecord(row);
4657
+ yield* mapRepositoryError(touchSession(tenantId2, input.id, input.updatedAt));
4658
+ return yield* requireSession(tenantId2, input.id);
4291
4659
  });
4292
4660
  const leaf = Effect17.fn("SessionRepository.leaf")(function* (sessionId) {
4293
4661
  const tenantId2 = yield* current;
4294
- const session = yield* getForTenant(tenantId2, sessionId);
4295
- if (session === undefined)
4296
- return yield* Effect17.fail(missingSession(sessionId));
4662
+ const session = yield* requireSession(tenantId2, sessionId);
4297
4663
  return session.leafEntryId ?? null;
4298
4664
  });
4299
4665
  const setLeafForTenant = Effect17.fn("SessionRepository.setLeafForTenant")(function* (tenantId2, input) {
4300
- const session = yield* getForTenant(tenantId2, input.sessionId);
4301
- if (session === undefined)
4302
- return yield* Effect17.fail(missingSession(input.sessionId));
4666
+ yield* requireSession(tenantId2, input.sessionId);
4303
4667
  if (input.id !== null) {
4304
4668
  const entry = yield* entryById(tenantId2, input.sessionId, input.id);
4305
4669
  if (entry === undefined)
4306
4670
  return yield* Effect17.fail(missingEntry(input.id));
4307
4671
  }
4308
- yield* mapDatabaseError13(db.update(relaySessions).set({ leafEntryId: input.id, updatedAt: toPgDate(input.updatedAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq14(relaySessions.id, input.sessionId))));
4672
+ yield* mapRepositoryError(updateLeaf(tenantId2, input));
4309
4673
  });
4310
4674
  const setLeaf = Effect17.fn("SessionRepository.setLeaf")(function* (input) {
4311
4675
  const tenantId2 = yield* current;
@@ -4313,9 +4677,7 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4313
4677
  });
4314
4678
  const appendEntry = Effect17.fn("SessionRepository.appendEntry")(function* (input) {
4315
4679
  const tenantId2 = yield* current;
4316
- const session = yield* getForTenant(tenantId2, input.sessionId);
4317
- if (session === undefined)
4318
- return yield* Effect17.fail(missingSession(input.sessionId));
4680
+ const session = yield* requireSession(tenantId2, input.sessionId);
4319
4681
  const existing = yield* entryById(tenantId2, input.sessionId, input.id);
4320
4682
  const desired = appendToRecord(input);
4321
4683
  if (existing !== undefined) {
@@ -4331,27 +4693,18 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4331
4693
  }
4332
4694
  const currentPath = session.leafEntryId === undefined ? [] : yield* pathForTenant(tenantId2, { sessionId: input.sessionId });
4333
4695
  yield* validateCompaction(currentPath, input);
4334
- return yield* mapWriteError(db.transaction((tx) => Effect17.gen(function* () {
4335
- const rows = yield* tx.insert(relaySessionEntries).values({
4336
- tenantId: tenantId2,
4337
- id: input.id,
4338
- sessionId: input.sessionId,
4339
- parentId: input.parentId,
4340
- tag: input.input._tag,
4341
- payloadJson: payloadFromInput(input.input),
4342
- createdAt: toPgDate(input.createdAt)
4343
- }).onConflictDoNothing({ target: [relaySessionEntries.tenantId, relaySessionEntries.id] }).returning();
4344
- const row = rows[0];
4345
- const record2 = row === undefined ? yield* tx.select().from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq14(relaySessionEntries.id, input.id), eq14(relaySessionEntries.sessionId, input.sessionId))).limit(1).pipe(Effect17.flatMap((existingRows) => {
4346
- const existingRow = existingRows[0];
4347
- if (existingRow === undefined) {
4348
- return Effect17.fail(new SessionRepositoryError({ message: "Session entry insert returned no row" }));
4349
- }
4350
- return toEntryRecord(existingRow);
4351
- })) : 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));
4352
4704
  if (!sameEntry(record2, desired))
4353
4705
  return yield* Effect17.fail(conflictingEntry(input.id));
4354
- const sessionRows = yield* tx.update(relaySessions).set({ leafEntryId: input.id, updatedAt: toPgDate(input.createdAt) }).where(predicate(tenantId2, relaySessions.tenantId, eq14(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);
4355
4708
  if (sessionRows[0] === undefined)
4356
4709
  return yield* Effect17.fail(missingSession(input.sessionId));
4357
4710
  return record2;
@@ -4359,8 +4712,15 @@ var layer17 = Layer17.effect(Service17, Effect17.gen(function* () {
4359
4712
  });
4360
4713
  const countEntries = Effect17.fn("SessionRepository.countEntries")(function* (sessionId) {
4361
4714
  const tenantId2 = yield* current;
4362
- const rows = yield* mapDatabaseError13(db.select({ value: count() }).from(relaySessionEntries).where(predicate(tenantId2, relaySessionEntries.tenantId, eq14(relaySessionEntries.sessionId, sessionId))));
4363
- 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);
4364
4724
  });
4365
4725
  return Service17.of({ create: create4, ensure, get: get8, list: list8, touch, appendEntry, countEntries, path, setLeaf, leaf });
4366
4726
  }));
@@ -4548,7 +4908,7 @@ __export(exports_skill_definition_repository, {
4548
4908
  SkillDefinitionRepositoryError: () => SkillDefinitionRepositoryError,
4549
4909
  Service: () => Service18
4550
4910
  });
4551
- import { asc as asc9, desc as desc6, eq as eq15, 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";
4552
4912
  import { Context as Context18, Effect as Effect18, HashSet, Layer as Layer18, Schema as Schema28, Semaphore as Semaphore2 } from "effect";
4553
4913
  class SkillDefinitionRepositoryError extends Schema28.TaggedErrorClass()("SkillDefinitionRepositoryError", {
4554
4914
  message: Schema28.String
@@ -4611,10 +4971,10 @@ var missingSkillMessage = (requested, records) => {
4611
4971
  const found = HashSet.fromIterable(records.map((record2) => record2.id));
4612
4972
  return `Skill definition not found: ${requested.find((id2) => !HashSet.has(found, id2)) ?? requested[0]}`;
4613
4973
  };
4614
- var mapDatabaseError14 = (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) })));
4615
4975
  var mapPutError2 = (effect) => effect.pipe(Effect18.mapError((error) => error instanceof SkillDefinitionRepositoryError ? error : new SkillDefinitionRepositoryError({ message: String(error) })));
4616
4976
  var skillPinLockKey = (tenantId2, executionId) => `skill-pins:${tenantId2}:${executionId}`;
4617
- var lockExecutionPins = (db, tenantId2, executionId) => mapDatabaseError14(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);
4618
4978
  var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4619
4979
  const db = yield* Service;
4620
4980
  const put2 = Effect18.fn("SkillDefinitionRepository.put")(function* (input) {
@@ -4632,7 +4992,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4632
4992
  target: [relaySkillDefinitions.tenantId, relaySkillDefinitions.id],
4633
4993
  set: {
4634
4994
  name: input.definition.frontmatter.name,
4635
- currentRevision: sql10`${relaySkillDefinitions.currentRevision} + 1`,
4995
+ currentRevision: sql9`${relaySkillDefinitions.currentRevision} + 1`,
4636
4996
  definitionJson: input.definition,
4637
4997
  updatedAt: toPgDate(input.now)
4638
4998
  }
@@ -4657,32 +5017,32 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4657
5017
  });
4658
5018
  const get9 = Effect18.fn("SkillDefinitionRepository.get")(function* (id2) {
4659
5019
  const tenantId2 = yield* current;
4660
- const rows = yield* mapDatabaseError14(db.select().from(relaySkillDefinitions).where(predicate(tenantId2, relaySkillDefinitions.tenantId, eq15(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));
4661
5021
  return rows[0] === undefined ? undefined : toRecord11(rows[0]);
4662
5022
  });
4663
5023
  const getRevision2 = Effect18.fn("SkillDefinitionRepository.getRevision")(function* (input) {
4664
5024
  const tenantId2 = yield* current;
4665
- const rows = yield* mapDatabaseError14(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq15(relaySkillDefinitionRevisions.skillDefinitionId, input.id), eq15(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));
4666
5026
  return rows[0] === undefined ? undefined : toRevisionRecord2(rows[0]);
4667
5027
  });
4668
5028
  const list9 = Effect18.fn("SkillDefinitionRepository.list")(function* () {
4669
5029
  const tenantId2 = yield* current;
4670
- const rows = yield* mapDatabaseError14(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)));
4671
5031
  return rows.map(toRecord11);
4672
5032
  });
4673
5033
  const listRevisions2 = Effect18.fn("SkillDefinitionRepository.listRevisions")(function* (id2) {
4674
5034
  const tenantId2 = yield* current;
4675
- const rows = yield* mapDatabaseError14(db.select().from(relaySkillDefinitionRevisions).where(predicate(tenantId2, relaySkillDefinitionRevisions.tenantId, eq15(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)));
4676
5036
  return rows.map(toRevisionRecord2);
4677
5037
  });
4678
5038
  const listPins = Effect18.fn("SkillDefinitionRepository.listPins")(function* (executionId) {
4679
5039
  const tenantId2 = yield* current;
4680
- const rows = yield* mapDatabaseError14(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq15(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)));
4681
5041
  return rows.map(toPinRecord);
4682
5042
  });
4683
5043
  const getPinned = Effect18.fn("SkillDefinitionRepository.getPinned")(function* (input) {
4684
5044
  const tenantId2 = yield* current;
4685
- const rows = yield* mapDatabaseError14(db.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq15(relayExecutionSkillPins.executionId, input.executionId), eq15(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));
4686
5046
  return rows[0] === undefined ? undefined : toPinRecord(rows[0]);
4687
5047
  });
4688
5048
  const pinExecution = Effect18.fn("SkillDefinitionRepository.pinExecution")(function* (input) {
@@ -4692,7 +5052,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4692
5052
  return [];
4693
5053
  return yield* mapPutError2(db.transaction((tx) => Effect18.gen(function* () {
4694
5054
  yield* lockExecutionPins(tx, tenantId2, input.executionId);
4695
- const existingRows = yield* tx.select().from(relayExecutionSkillPins).where(predicate(tenantId2, relayExecutionSkillPins.tenantId, eq15(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));
4696
5056
  if (existingRows.length > 0) {
4697
5057
  const existing = existingRows.map(toPinRecord);
4698
5058
  if (!sameIdSet(existing.map((record2) => record2.skillDefinitionId), requestedIds)) {
@@ -4702,7 +5062,7 @@ var layer18 = Layer18.effect(Service18, Effect18.gen(function* () {
4702
5062
  }
4703
5063
  return existing;
4704
5064
  }
4705
- 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])));
4706
5066
  const currentRecords = currentRows.map(toRecord11);
4707
5067
  if (currentRecords.length !== requestedIds.length) {
4708
5068
  return yield* Effect18.fail(new SkillDefinitionRepositoryError({ message: missingSkillMessage(requestedIds, currentRecords) }));
@@ -4849,10 +5209,12 @@ __export(exports_steering_repository, {
4849
5209
  appendForRunning: () => appendForRunning,
4850
5210
  append: () => append2,
4851
5211
  SteeringRepositoryError: () => SteeringRepositoryError,
5212
+ SteeringMessageRow: () => SteeringMessageRow,
5213
+ SteeringDrainRow: () => SteeringDrainRow,
4852
5214
  Service: () => Service19
4853
5215
  });
4854
- import { asc as asc10, eq as eq16, inArray as inArray4, isNull, max as max2, sql as sql11 } from "drizzle-orm";
4855
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";
4856
5218
  class SteeringRepositoryError extends Schema29.TaggedErrorClass()("SteeringRepositoryError", {
4857
5219
  message: Schema29.String
4858
5220
  }) {
@@ -4861,26 +5223,45 @@ class SteeringRepositoryError extends Schema29.TaggedErrorClass()("SteeringRepos
4861
5223
  class Service19 extends Context19.Service()("@relayfx/store-sql/SteeringRepository") {
4862
5224
  }
4863
5225
  var SteeringKindSchema = Schema29.Literals(["steering", "follow_up"]);
4864
- var mapDatabaseError15 = (effect) => effect.pipe(Effect19.mapError((error) => new SteeringRepositoryError({ message: String(error) })));
4865
- 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));
4866
5247
  var toMessageRecord = (row) => {
4867
- const consumedAt = fromNullablePgDate(row.consumedAt);
5248
+ const consumedAt = fromNullableDbTimestamp(row.consumed_at);
4868
5249
  return {
4869
- executionId: exports_ids_schema.ExecutionId.make(row.executionId),
4870
- kind: Schema29.decodeUnknownSync(SteeringKindSchema)(row.kind),
4871
- sequence: row.sequence,
4872
- content: row.contentJson,
4873
- ...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 },
4874
5255
  ...consumedAt === undefined ? {} : { consumedAt },
4875
- createdAt: fromPgDate(row.createdAt)
5256
+ createdAt: fromDbTimestamp(row.created_at)
4876
5257
  };
4877
5258
  };
4878
5259
  var toDrainRecord = (row) => ({
4879
- executionId: exports_ids_schema.ExecutionId.make(row.executionId),
4880
- kind: Schema29.decodeUnknownSync(SteeringKindSchema)(row.kind),
4881
- drainId: row.drainId,
4882
- messageSequences: row.messageSequencesJson,
4883
- 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)
4884
5265
  });
4885
5266
  var queueKey = (tenantId2, executionId, kind) => JSON.stringify([tenantId2, executionId, kind]);
4886
5267
  var drainKey = (tenantId2, executionId, kind, drainId) => JSON.stringify([tenantId2, executionId, kind, drainId]);
@@ -4899,94 +5280,161 @@ var consumedMessage = (message, input) => ({
4899
5280
  consumedAt: input.consumedAt,
4900
5281
  createdAt: message.createdAt
4901
5282
  });
4902
- var messagesForDrain = (db, tenantId2, drain) => Effect19.gen(function* () {
4903
- if (drain.messageSequences.length === 0)
4904
- return { drain, messages: [] };
4905
- const rows = yield* mapDatabaseError15(db.select().from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq16(relaySteeringMessages.executionId, drain.executionId), eq16(relaySteeringMessages.kind, drain.kind), inArray4(relaySteeringMessages.sequence, [...drain.messageSequences]))).orderBy(asc10(relaySteeringMessages.sequence)));
4906
- return { drain, messages: rows.map(toMessageRecord) };
4907
- });
4908
- var findDrain = (db, tenantId2, input) => Effect19.gen(function* () {
4909
- const rows = yield* mapDatabaseError15(db.select().from(relaySteeringDrains).where(predicate(tenantId2, relaySteeringDrains.tenantId, eq16(relaySteeringDrains.executionId, input.executionId), eq16(relaySteeringDrains.kind, input.kind), eq16(relaySteeringDrains.drainId, input.drainId))).limit(1));
4910
- const row = rows[0];
4911
- return row === undefined ? undefined : toDrainRecord(row);
4912
- });
4913
- var lockQueue = (db, tenantId2, executionId, kind) => mapDatabaseError15(db.execute(sql11`select pg_advisory_xact_lock(hashtext(${queueKey(tenantId2, executionId, kind)}))`)).pipe(Effect19.asVoid);
4914
- var runningExecutionStatus = (db, tenantId2, executionId) => db.select({ status: relayExecutions.status }).from(relayExecutions).where(predicate(tenantId2, relayExecutions.tenantId, eq16(relayExecutions.id, executionId))).for("update").limit(1).pipe(Effect19.map((rows) => rows[0]?.status));
4915
5283
  var layer19 = Layer19.effect(Service19, Effect19.gen(function* () {
4916
- const db = yield* Service;
4917
- const appendInTransaction = Effect19.fn("SteeringRepository.appendInTransaction")(function* (tx, tenantId2, input) {
4918
- yield* lockQueue(tx, tenantId2, input.executionId, input.kind);
4919
- const sequenceRows = yield* tx.select({ value: max2(relaySteeringMessages.sequence) }).from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq16(relaySteeringMessages.executionId, input.executionId), eq16(relaySteeringMessages.kind, input.kind)));
4920
- const sequence = Number(sequenceRows[0]?.value ?? -1) + 1;
4921
- const rows = yield* tx.insert(relaySteeringMessages).values({
4922
- tenantId: tenantId2,
4923
- executionId: input.executionId,
4924
- kind: input.kind,
4925
- sequence,
4926
- contentJson: input.content,
4927
- createdAt: toPgDate(input.createdAt)
4928
- }).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);
4929
5373
  const row = rows[0];
4930
5374
  if (row === undefined) {
4931
5375
  return yield* Effect19.fail(new SteeringRepositoryError({ message: "Steering message insert returned no row" }));
4932
5376
  }
4933
- return toMessageRecord(row);
5377
+ return toMessageRecord(yield* decodeMessageRow(row));
4934
5378
  });
4935
5379
  const append2 = Effect19.fn("SteeringRepository.append")(function* (input) {
4936
5380
  const tenantId2 = yield* current;
4937
- return yield* mapTransactionError(db.transaction((tx) => appendInTransaction(tx, tenantId2, input)));
5381
+ return yield* sql10.withTransaction(appendInTransaction(tenantId2, input)).pipe(mapTransactionError);
4938
5382
  });
4939
5383
  const appendForRunning = Effect19.fn("SteeringRepository.appendForRunning")(function* (input) {
4940
5384
  const tenantId2 = yield* current;
4941
- return yield* mapTransactionError(db.transaction((tx) => Effect19.gen(function* () {
4942
- const scopedTx = tx;
4943
- 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;
4944
5388
  if (status === undefined) {
4945
5389
  return yield* Effect19.fail(new SteeringRepositoryError({ message: `Execution not found: ${input.executionId}` }));
4946
5390
  }
4947
5391
  if (status !== "running") {
4948
5392
  return yield* Effect19.fail(new SteeringRepositoryError({ message: `Execution is not running: ${input.executionId}` }));
4949
5393
  }
4950
- return yield* appendInTransaction(scopedTx, tenantId2, input);
4951
- })));
5394
+ return yield* appendInTransaction(tenantId2, input);
5395
+ })).pipe(mapTransactionError);
4952
5396
  });
4953
5397
  const drainUnconsumed = Effect19.fn("SteeringRepository.drainUnconsumed")(function* (input) {
4954
5398
  const tenantId2 = yield* current;
4955
- const existing = yield* findDrain(db, tenantId2, input);
5399
+ const existing = yield* findDrain(tenantId2, input);
4956
5400
  if (existing !== undefined)
4957
- return yield* messagesForDrain(db, tenantId2, existing);
4958
- return yield* mapTransactionError(db.transaction((tx) => Effect19.gen(function* () {
4959
- const scopedTx = tx;
4960
- yield* lockQueue(scopedTx, tenantId2, input.executionId, input.kind);
4961
- 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);
4962
5405
  if (existingAfterLock !== undefined)
4963
- return yield* messagesForDrain(scopedTx, tenantId2, existingAfterLock);
4964
- const query2 = tx.select().from(relaySteeringMessages).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq16(relaySteeringMessages.executionId, input.executionId), eq16(relaySteeringMessages.kind, input.kind), isNull(relaySteeringMessages.consumedAt))).orderBy(asc10(relaySteeringMessages.sequence));
4965
- const rows = input.mode === "one-at-a-time" ? yield* query2.limit(1) : yield* query2;
4966
- const sequences = rows.map((row) => row.sequence);
4967
- const messages = sequences.length === 0 ? [] : yield* tx.update(relaySteeringMessages).set({
4968
- drainId: input.drainId,
4969
- consumedAt: toPgDate(input.consumedAt)
4970
- }).where(predicate(tenantId2, relaySteeringMessages.tenantId, eq16(relaySteeringMessages.executionId, input.executionId), eq16(relaySteeringMessages.kind, input.kind), inArray4(relaySteeringMessages.sequence, sequences))).returning();
4971
- const messageBySequence = new Map(messages.map((message) => [message.sequence, message]));
4972
- const orderedMessages = sequences.flatMap((sequence) => {
4973
- const message = messageBySequence.get(sequence);
4974
- return message === undefined ? [] : [message];
4975
- });
4976
- const drainRows = yield* tx.insert(relaySteeringDrains).values({
4977
- tenantId: tenantId2,
4978
- executionId: input.executionId,
4979
- kind: input.kind,
4980
- drainId: input.drainId,
4981
- messageSequencesJson: sequences,
4982
- createdAt: toPgDate(input.createdAt)
4983
- }).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);
4984
5432
  const drainRow = drainRows[0];
4985
5433
  if (drainRow === undefined) {
4986
5434
  return yield* Effect19.fail(new SteeringRepositoryError({ message: "Steering drain insert returned no row" }));
4987
5435
  }
4988
- return { drain: toDrainRecord(drainRow), messages: orderedMessages.map(toMessageRecord) };
4989
- })));
5436
+ return { drain: toDrainRecord(yield* decodeDrainRow(drainRow)), messages };
5437
+ })).pipe(mapTransactionError);
4990
5438
  });
4991
5439
  return Service19.of({ append: append2, appendForRunning, drainUnconsumed });
4992
5440
  }));
@@ -5087,7 +5535,7 @@ __export(exports_tool_call_repository, {
5087
5535
  DuplicateToolResult: () => DuplicateToolResult,
5088
5536
  DuplicateToolCall: () => DuplicateToolCall
5089
5537
  });
5090
- import { asc as asc11, eq as eq17 } from "drizzle-orm";
5538
+ import { asc as asc9, eq as eq12 } from "drizzle-orm";
5091
5539
  import { Context as Context20, Effect as Effect20, Layer as Layer20, Schema as Schema30 } from "effect";
5092
5540
  class ToolCallRepositoryError extends Schema30.TaggedErrorClass()("ToolCallRepositoryError", {
5093
5541
  message: Schema30.String
@@ -5148,15 +5596,15 @@ var toResultRecord = (row) => ({
5148
5596
  },
5149
5597
  createdAt: fromPgDate(row.createdAt)
5150
5598
  });
5151
- var mapDatabaseError16 = (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) })));
5152
5600
  var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5153
5601
  const db = yield* Service;
5154
5602
  const recordCall = Effect20.fn("ToolCallRepository.recordCall")(function* (input) {
5155
5603
  const tenantId2 = yield* current;
5156
- const existingRows = yield* mapDatabaseError16(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq17(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));
5157
5605
  if (existingRows[0] !== undefined)
5158
5606
  return yield* Effect20.fail(new DuplicateToolCall({ id: input.call.id }));
5159
- const rows = yield* mapDatabaseError16(db.insert(relayToolCalls).values(toCallInsert(tenantId2, input)).returning());
5607
+ const rows = yield* mapDatabaseError11(db.insert(relayToolCalls).values(toCallInsert(tenantId2, input)).returning());
5160
5608
  const row = rows[0];
5161
5609
  if (row === undefined) {
5162
5610
  return yield* Effect20.fail(new ToolCallRepositoryError({ message: "Tool call insert returned no row" }));
@@ -5165,24 +5613,24 @@ var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5165
5613
  });
5166
5614
  const getCall = Effect20.fn("ToolCallRepository.getCall")(function* (id2) {
5167
5615
  const tenantId2 = yield* current;
5168
- const rows = yield* mapDatabaseError16(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq17(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));
5169
5617
  return rows[0] === undefined ? undefined : toCallRecord(rows[0]);
5170
5618
  });
5171
5619
  const listCalls = Effect20.fn("ToolCallRepository.listCalls")(function* (executionId) {
5172
5620
  const tenantId2 = yield* current;
5173
- const rows = yield* mapDatabaseError16(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq17(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)));
5174
5622
  return rows.map(toCallRecord);
5175
5623
  });
5176
5624
  const recordResult = Effect20.fn("ToolCallRepository.recordResult")(function* (input) {
5177
5625
  const tenantId2 = yield* current;
5178
- const callRows = yield* mapDatabaseError16(db.select().from(relayToolCalls).where(predicate(tenantId2, relayToolCalls.tenantId, eq17(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));
5179
5627
  if (callRows[0] === undefined)
5180
5628
  return yield* Effect20.fail(new ToolCallNotFound({ id: input.result.call_id }));
5181
- const existingRows = yield* mapDatabaseError16(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq17(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));
5182
5630
  if (existingRows[0] !== undefined) {
5183
5631
  return yield* Effect20.fail(new DuplicateToolResult({ call_id: input.result.call_id }));
5184
5632
  }
5185
- const rows = yield* mapDatabaseError16(db.insert(relayToolResults).values(toResultInsert(tenantId2, input)).returning());
5633
+ const rows = yield* mapDatabaseError11(db.insert(relayToolResults).values(toResultInsert(tenantId2, input)).returning());
5186
5634
  const row = rows[0];
5187
5635
  if (row === undefined) {
5188
5636
  return yield* Effect20.fail(new ToolCallRepositoryError({ message: "Tool result insert returned no row" }));
@@ -5191,7 +5639,7 @@ var layer20 = Layer20.effect(Service20, Effect20.gen(function* () {
5191
5639
  });
5192
5640
  const getResult = Effect20.fn("ToolCallRepository.getResult")(function* (callId) {
5193
5641
  const tenantId2 = yield* current;
5194
- const rows = yield* mapDatabaseError16(db.select().from(relayToolResults).where(predicate(tenantId2, relayToolResults.tenantId, eq17(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));
5195
5643
  return rows[0] === undefined ? undefined : toResultRecord(rows[0]);
5196
5644
  });
5197
5645
  return Service20.of({ recordCall, getCall, listCalls, recordResult, getResult });
@@ -5272,7 +5720,7 @@ __export(exports_workspace_lease_repository, {
5272
5720
  Service: () => Service21,
5273
5721
  DuplicateWorkspaceLease: () => DuplicateWorkspaceLease
5274
5722
  });
5275
- import { eq as eq18, notInArray } from "drizzle-orm";
5723
+ import { eq as eq13, notInArray } from "drizzle-orm";
5276
5724
  import { Context as Context21, Effect as Effect21, Layer as Layer21, Schema as Schema31 } from "effect";
5277
5725
  class WorkspaceLeaseRepositoryError extends Schema31.TaggedErrorClass()("WorkspaceLeaseRepositoryError", {
5278
5726
  message: Schema31.String
@@ -5342,8 +5790,8 @@ var toSnapshotRecord = (row) => ({
5342
5790
  metadata: row.metadataJson,
5343
5791
  created_at: fromPgDate(row.createdAt)
5344
5792
  });
5345
- var mapDatabaseError17 = (effect) => effect.pipe(Effect21.mapError((error) => new WorkspaceLeaseRepositoryError({ message: String(error) })));
5346
- var updateLease = (db, tenantId2, executionId, values) => mapDatabaseError17(db.update(relayWorkspaceLeases).set(values).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq18(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) => {
5347
5795
  const row = rows[0];
5348
5796
  if (row === undefined)
5349
5797
  return Effect21.fail(new WorkspaceLeaseNotFound({ execution_id: executionId }));
@@ -5353,16 +5801,16 @@ var layer21 = Layer21.effect(Service21, Effect21.gen(function* () {
5353
5801
  const db = yield* Service;
5354
5802
  const getByExecution = Effect21.fn("WorkspaceLeaseRepository.getByExecution")(function* (id2) {
5355
5803
  const tenantId2 = yield* current;
5356
- const rows = yield* mapDatabaseError17(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq18(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));
5357
5805
  return rows[0] === undefined ? undefined : toLeaseRecord(rows[0]);
5358
5806
  });
5359
5807
  const plan = Effect21.fn("WorkspaceLeaseRepository.plan")(function* (input) {
5360
5808
  const tenantId2 = yield* current;
5361
- const existing = yield* mapDatabaseError17(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq18(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));
5362
5810
  if (existing[0] !== undefined) {
5363
5811
  return yield* Effect21.fail(new DuplicateWorkspaceLease({ execution_id: input.executionId }));
5364
5812
  }
5365
- const rows = yield* mapDatabaseError17(db.insert(relayWorkspaceLeases).values(toPlanInsert(tenantId2, input)).returning());
5813
+ const rows = yield* mapDatabaseError12(db.insert(relayWorkspaceLeases).values(toPlanInsert(tenantId2, input)).returning());
5366
5814
  const row = rows[0];
5367
5815
  if (row === undefined) {
5368
5816
  return yield* Effect21.fail(new WorkspaceLeaseRepositoryError({ message: "Workspace lease insert returned no row" }));
@@ -5394,11 +5842,11 @@ var layer21 = Layer21.effect(Service21, Effect21.gen(function* () {
5394
5842
  });
5395
5843
  const recordSnapshot = Effect21.fn("WorkspaceLeaseRepository.recordSnapshot")(function* (input) {
5396
5844
  const tenantId2 = yield* current;
5397
- const leaseRows = yield* mapDatabaseError17(db.select().from(relayWorkspaceLeases).where(predicate(tenantId2, relayWorkspaceLeases.tenantId, eq18(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));
5398
5846
  if (leaseRows[0] === undefined) {
5399
5847
  return yield* Effect21.fail(new WorkspaceLeaseNotFound({ execution_id: input.executionId }));
5400
5848
  }
5401
- const rows = yield* mapDatabaseError17(db.insert(relayWorkspaceSnapshots).values(toSnapshotInsert(tenantId2, input)).returning());
5849
+ const rows = yield* mapDatabaseError12(db.insert(relayWorkspaceSnapshots).values(toSnapshotInsert(tenantId2, input)).returning());
5402
5850
  const row = rows[0];
5403
5851
  if (row === undefined) {
5404
5852
  return yield* Effect21.fail(new WorkspaceLeaseRepositoryError({ message: "Workspace snapshot insert returned no row" }));
@@ -5584,7 +6032,7 @@ var recordWaitTransitioned = (state) => Metric.update(Metric.withAttributes(wait
5584
6032
  var recordChildRunSpawned = (kind) => Metric.update(Metric.withAttributes(childRunSpawned, { kind }), 1);
5585
6033
  var recordAddressResolved = (routeKind) => Metric.update(Metric.withAttributes(addressResolved, { route_kind: routeKind }), 1);
5586
6034
  var recordEventAppended = (eventType) => Metric.update(Metric.withAttributes(eventAppended, { event_type: eventType }), 1);
5587
- var recordEventReplayed = (source, count2) => Metric.update(Metric.withAttributes(eventReplayed, { source }), count2);
6035
+ var recordEventReplayed = (source, count) => Metric.update(Metric.withAttributes(eventReplayed, { source }), count);
5588
6036
  var recordRunnerReadinessChecked = (database) => Metric.update(Metric.withAttributes(runnerReadinessChecked, { database }), 1);
5589
6037
  var recordModelUsage = (input) => Effect22.gen(function* () {
5590
6038
  yield* Metric.update(Metric.withAttributes(modelTokens, { direction: "input", provider: input.provider, model: input.model }), input.inputTokens);
@@ -5650,7 +6098,7 @@ var recordFromEntry = (entry) => ({
5650
6098
  });
5651
6099
  var entryIdFor = (addressId) => exports_ids_schema.AddressBookEntryId.make(`address-book:${addressId}`);
5652
6100
  var validateRoute = (route) => Schema32.decodeUnknownEffect(Route2)(route).pipe(Effect23.mapError((error) => new AddressBookServiceError({ message: String(error) })));
5653
- var mapRepositoryError = (error) => {
6101
+ var mapRepositoryError2 = (error) => {
5654
6102
  if (error._tag === "AddressNotFound") {
5655
6103
  return new AddressNotFound2({ address_id: error.address_id });
5656
6104
  }
@@ -5661,7 +6109,7 @@ var layerFromRepository = Layer22.effect(Service22, Effect23.gen(function* () {
5661
6109
  return Service22.of({
5662
6110
  resolve: Effect23.fn("AddressBook.repository.resolve")(function* (addressId) {
5663
6111
  yield* Effect23.annotateCurrentSpan("relay.address.id", addressId);
5664
- const entry = yield* repository.resolve(addressId).pipe(Effect23.mapError(mapRepositoryError));
6112
+ const entry = yield* repository.resolve(addressId).pipe(Effect23.mapError(mapRepositoryError2));
5665
6113
  const route = yield* resolveRoute(addressId, routeFromEntry(entry));
5666
6114
  yield* Effect23.annotateCurrentSpan({
5667
6115
  "relay.route.kind": route.kind,
@@ -6084,7 +6532,7 @@ var memoryLayer21 = Layer23.effect(Service23, Effect25.gen(function* () {
6084
6532
  }),
6085
6533
  maxSequence: Effect25.fn("EventLog.memory.maxSequence")(function* (executionId) {
6086
6534
  const executionEvents = yield* allEvents(executionId);
6087
- 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);
6088
6536
  }),
6089
6537
  sumUsage: Effect25.fn("EventLog.memory.sumUsage")(function* (executionId) {
6090
6538
  const executionEvents = yield* allEvents(executionId);
@@ -6170,7 +6618,7 @@ class WaitServiceError extends Schema34.TaggedErrorClass()("WaitServiceError", {
6170
6618
 
6171
6619
  class Service24 extends Context24.Service()("@relayfx/runtime/WaitService") {
6172
6620
  }
6173
- var mapRepositoryError2 = (error) => {
6621
+ var mapRepositoryError3 = (error) => {
6174
6622
  if (error._tag === "WaitNotFound")
6175
6623
  return new WaitNotFound2({ wait_id: error.id });
6176
6624
  return new WaitServiceError({ message: error.message });
@@ -6245,7 +6693,7 @@ var createTimeoutSchedule = Effect26.fn("WaitService.createTimeoutSchedule")(fun
6245
6693
  }).pipe(Effect26.mapError((error) => new WaitServiceError({ message: error.message })));
6246
6694
  });
6247
6695
  var complete = Effect26.fn("WaitService.complete")(function* (repository, eventLog, input, event) {
6248
- const result = yield* repository.completeWait(input).pipe(Effect26.mapError(mapRepositoryError2));
6696
+ const result = yield* repository.completeWait(input).pipe(Effect26.mapError(mapRepositoryError3));
6249
6697
  if (result.transitioned) {
6250
6698
  yield* eventLog.append(event(result.wait)).pipe(Effect26.mapError(mapEventLogError));
6251
6699
  }
@@ -6405,7 +6853,7 @@ var validateInput = (tool, input) => {
6405
6853
  return Effect27.void;
6406
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);
6407
6855
  };
6408
- var mapRepositoryError3 = (error) => new ToolRuntimeError({ message: error._tag });
6856
+ var mapRepositoryError4 = (error) => new ToolRuntimeError({ message: error._tag });
6409
6857
  var mapEventLogError2 = (error) => new ToolRuntimeError({ message: error._tag });
6410
6858
  var preserveToolError = (toolName, error) => {
6411
6859
  if (typeof error === "object" && error !== null && "_tag" in error) {
@@ -6422,7 +6870,7 @@ var preserveToolError = (toolName, error) => {
6422
6870
  message: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
6423
6871
  });
6424
6872
  };
6425
- var preserveRecordResultError = (error) => error._tag === "ToolRuntimeError" ? error : mapRepositoryError3(error);
6873
+ var preserveRecordResultError = (error) => error._tag === "ToolRuntimeError" ? error : mapRepositoryError4(error);
6426
6874
  var requestedEvent = (input) => ({
6427
6875
  id: exports_ids_schema.EventId.make(`event:${input.call.id}:tool-requested`),
6428
6876
  execution_id: input.executionId,
@@ -6579,12 +7027,12 @@ var resolveApproval = (waits, eventLog, input) => Effect27.gen(function* () {
6579
7027
  return { _tag: "approved" };
6580
7028
  return { _tag: "denied", reason: deniedReason(existing.state) };
6581
7029
  });
6582
- 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) => {
6583
7031
  if (existing !== undefined)
6584
7032
  return Effect27.void;
6585
- 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);
6586
7034
  }));
6587
- 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))));
6588
7036
  var definitionFromAiTool = (tool, permissions = []) => ({
6589
7037
  name: tool.name,
6590
7038
  description: Ai.Tool.getDescription(tool) ?? "",
@@ -6608,7 +7056,7 @@ var layer23 = (initialTools = []) => Layer25.effect(Service25, Effect27.gen(func
6608
7056
  if (tool === undefined) {
6609
7057
  return yield* Effect27.fail(new ToolNotRegistered({ tool_name: input.call.name }));
6610
7058
  }
6611
- 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));
6612
7060
  if (existingResult !== undefined)
6613
7061
  return existingResult.result;
6614
7062
  return yield* Effect27.gen(function* () {
@@ -6688,7 +7136,7 @@ var toPublicRevisionRecord = (record2) => ({
6688
7136
  ...record2.toolInputSchemaDigests === undefined ? {} : { tool_input_schema_digests: record2.toolInputSchemaDigests },
6689
7137
  created_at: record2.createdAt
6690
7138
  });
6691
- var mapRepositoryError4 = (error) => new AgentRegistryError({ message: error.message });
7139
+ var mapRepositoryError5 = (error) => new AgentRegistryError({ message: error.message });
6692
7140
  var hasText = (value) => value === undefined || value.trim().length > 0;
6693
7141
  var requireText = (value, field) => value.trim().length === 0 ? Effect28.fail(new AgentDefinitionInvalid({ message: `${field} must not be blank` })) : Effect28.void;
6694
7142
  var requireOptionalText = (value, field) => hasText(value) ? Effect28.void : Effect28.fail(new AgentDefinitionInvalid({ message: `${field} must not be blank` }));
@@ -6767,23 +7215,23 @@ var layer24 = Layer26.effect(Service26, Effect28.gen(function* () {
6767
7215
  const selectedToolNames = input.definition.tool_names.filter((toolName) => toolDefinitions.some((definition) => definition.name === toolName));
6768
7216
  const crypto = yield* Effect28.serviceOption(Crypto2.Crypto);
6769
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) })));
6770
- 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));
6771
7219
  return { record: toPublicRecord(record2) };
6772
7220
  }),
6773
7221
  get: Effect28.fn("AgentRegistry.get")(function* (id2) {
6774
- const record2 = yield* repository.get(id2).pipe(Effect28.mapError(mapRepositoryError4));
7222
+ const record2 = yield* repository.get(id2).pipe(Effect28.mapError(mapRepositoryError5));
6775
7223
  return record2 === undefined ? undefined : toPublicRecord(record2);
6776
7224
  }),
6777
7225
  getRevision: Effect28.fn("AgentRegistry.getRevision")(function* (input) {
6778
- const record2 = yield* repository.getRevision(input).pipe(Effect28.mapError(mapRepositoryError4));
7226
+ const record2 = yield* repository.getRevision(input).pipe(Effect28.mapError(mapRepositoryError5));
6779
7227
  return record2 === undefined ? undefined : toPublicRevisionRecord(record2);
6780
7228
  }),
6781
7229
  list: Effect28.fn("AgentRegistry.list")(function* () {
6782
- const records = yield* repository.list().pipe(Effect28.mapError(mapRepositoryError4));
7230
+ const records = yield* repository.list().pipe(Effect28.mapError(mapRepositoryError5));
6783
7231
  return { records: records.map(toPublicRecord) };
6784
7232
  }),
6785
7233
  listRevisions: Effect28.fn("AgentRegistry.listRevisions")(function* (id2) {
6786
- const records = yield* repository.listRevisions(id2).pipe(Effect28.mapError(mapRepositoryError4));
7234
+ const records = yield* repository.listRevisions(id2).pipe(Effect28.mapError(mapRepositoryError5));
6787
7235
  return { records: records.map(toPublicRevisionRecord) };
6788
7236
  })
6789
7237
  });
@@ -8724,7 +9172,7 @@ var spawnedEvent = (input, kind, context, presetName, workspaceRef) => ({
8724
9172
  },
8725
9173
  created_at: input.createdAt
8726
9174
  });
8727
- var mapRepositoryError5 = (error) => new ChildRunServiceError({ message: error._tag });
9175
+ var mapRepositoryError6 = (error) => new ChildRunServiceError({ message: error._tag });
8728
9176
  var mapEventLogError3 = (error) => new ChildRunServiceError({ message: error._tag });
8729
9177
  var persistChild = Effect50.fn("ChildRunService.persistChild")(function* (repository, eventLog, input, kind, context, presetName) {
8730
9178
  const workspaceRef = yield* childWorkspaceRef(input, context);
@@ -8735,7 +9183,7 @@ var persistChild = Effect50.fn("ChildRunService.persistChild")(function* (reposi
8735
9183
  status: "queued",
8736
9184
  metadata: childMetadata(kind, context, presetName, workspaceRef),
8737
9185
  createdAt: input.createdAt
8738
- }).pipe(Effect50.mapError(mapRepositoryError5));
9186
+ }).pipe(Effect50.mapError(mapRepositoryError6));
8739
9187
  yield* eventLog.append(spawnedEvent(input, kind, context, presetName, workspaceRef)).pipe(Effect50.mapError(mapEventLogError3));
8740
9188
  return acceptedOutput(input);
8741
9189
  });
@@ -8877,7 +9325,7 @@ var hasDynamicOverride = (input) => input.instructions !== undefined || input.mo
8877
9325
  var childExecutionId = (context) => exports_ids_schema.ChildExecutionId.make(`${context.executionId}:child:${context.call.id}`);
8878
9326
  var childAddressId = (id2) => exports_ids_schema.AddressId.make(`address:child:${id2}`);
8879
9327
  var childWaitId = (id2) => exports_ids_schema.WaitId.make(`wait:child:${id2}`);
8880
- 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 })));
8881
9329
  var mapChildRunError = (activeToolName, error) => new ToolExecutionFailed({ tool_name: activeToolName, message: error._tag });
8882
9330
  var mapWaitError = (error) => new ToolRuntimeError({ message: error._tag === "WaitNotFound" ? error.wait_id : error.message });
8883
9331
  var spawnInput = (config, input, context, id2) => ({
@@ -9790,7 +10238,7 @@ var layer39 = exports_approvals.autoApprove;
9790
10238
  // ../runtime/src/agent/relay-compaction.ts
9791
10239
  import { Clock as Clock4, Effect as Effect60, Layer as Layer54 } from "effect";
9792
10240
  var checkpointId = (input) => `compaction:${input.executionId}:turn:${input.turn}:keep:${input.firstKeptEntryId}`;
9793
- 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 });
9794
10242
  var sameCheckpointBoundary = (record2, input) => record2.firstKeptEntryId === input.firstKeptEntryId && record2.turn === input.turn;
9795
10243
  var defaultOptions = (options) => ({
9796
10244
  ...options?.contextWindow === undefined ? {} : { contextWindow: options.contextWindow },
@@ -9809,7 +10257,7 @@ var strategy = (config) => {
9809
10257
  firstKeptEntryId: plan2.firstKeptEntryId
9810
10258
  });
9811
10259
  return Effect60.gen(function* () {
9812
- 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));
9813
10261
  if (existing !== undefined)
9814
10262
  return existing.summary;
9815
10263
  const summary = yield* base.summarize(plan2, request);
@@ -9823,7 +10271,7 @@ var strategy = (config) => {
9823
10271
  createdAt
9824
10272
  };
9825
10273
  const record2 = yield* config.repository.record(input).pipe(Effect60.matchEffect({
9826
- 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)))),
9827
10275
  onSuccess: Effect60.succeed
9828
10276
  }));
9829
10277
  return record2.summary;
@@ -9885,7 +10333,7 @@ var evaluateDecision = Effect61.fn("RelayPermissions.evaluateDecision")(function
9885
10333
  });
9886
10334
  var permissionError = (message) => new exports_permissions.PermissionError({ message });
9887
10335
  var createdAtForSequence = (config, sequence) => config.startedAt + sequence - config.eventSequence;
9888
- 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)));
9889
10337
  var allocateEventSequence = Effect61.fn("RelayPermissions.allocateEventSequence")(function* (config) {
9890
10338
  const fallback = yield* config.allocator.allocate(1);
9891
10339
  const sequence = yield* nextLoggedSequence(config.eventLog, config.executionId, fallback);
@@ -10117,7 +10565,7 @@ var errorDetail = (error) => {
10117
10565
  return error.tool_name;
10118
10566
  }
10119
10567
  };
10120
- 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)));
10121
10569
  var requestedCursor = (executionId, callId) => `${executionId}:tool:${callId}:requested`;
10122
10570
  var hasRequestedEvent = (config, callId) => config.eventLog.findByCursor({
10123
10571
  executionId: config.executionId,
@@ -10202,7 +10650,7 @@ var layer43 = Layer58.effect(exports_tool_output.ToolOutputStore, Service37.pipe
10202
10650
  // ../runtime/src/agent/sequence-allocator.ts
10203
10651
  import { Effect as Effect65, Ref as Ref17 } from "effect";
10204
10652
  var make12 = (first) => Ref17.make(first).pipe(Effect65.map((ref) => ({
10205
- allocate: (count2) => Ref17.getAndUpdate(ref, (value) => value + count2),
10653
+ allocate: (count) => Ref17.getAndUpdate(ref, (value) => value + count),
10206
10654
  current: Ref17.get(ref),
10207
10655
  resetTo: (sequence) => Ref17.set(ref, sequence)
10208
10656
  })));
@@ -10853,7 +11301,7 @@ var make13 = Effect67.fn("ParentNotifier.make")(function* (options) {
10853
11301
  const eventLog = yield* Service23;
10854
11302
  const repository = yield* exports_child_execution_repository.Service;
10855
11303
  const waits = yield* Service24;
10856
- 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));
10857
11305
  const appendTerminalEvent = (input) => Effect67.gen(function* () {
10858
11306
  const sequence = yield* nextSequence(input.parentExecutionId);
10859
11307
  const event = childRunEvent(input, sequence);
@@ -10964,7 +11412,7 @@ var toPublicPinRecord = (record2) => ({
10964
11412
  skill_definition_snapshot: record2.skillDefinitionSnapshot,
10965
11413
  created_at: record2.createdAt
10966
11414
  });
10967
- var mapRepositoryError7 = (error) => new SkillRegistryError({ message: error.message });
11415
+ var mapRepositoryError8 = (error) => new SkillRegistryError({ message: error.message });
10968
11416
  var requireText2 = (value, field) => value.trim().length === 0 ? Effect68.fail(new SkillDefinitionInvalid({ message: `${field} must not be blank` })) : Effect68.void;
10969
11417
  var requireOptionalText2 = (value, field) => value === undefined || value.trim().length > 0 ? Effect68.void : Effect68.fail(new SkillDefinitionInvalid({ message: `${field} must not be blank` }));
10970
11418
  var validateDefinition2 = Effect68.fn("SkillRegistry.validateDefinition")(function* (definition) {
@@ -11009,23 +11457,23 @@ var layer45 = Layer61.effect(Service42, Effect68.gen(function* () {
11009
11457
  register: Effect68.fn("SkillRegistry.register")(function* (input) {
11010
11458
  yield* validateDefinition2(input.definition);
11011
11459
  const now = yield* Clock7.currentTimeMillis;
11012
- 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));
11013
11461
  return { record: toPublicRecord2(record2) };
11014
11462
  }),
11015
11463
  get: Effect68.fn("SkillRegistry.get")(function* (id2) {
11016
- const record2 = yield* repository.get(id2).pipe(Effect68.mapError(mapRepositoryError7));
11464
+ const record2 = yield* repository.get(id2).pipe(Effect68.mapError(mapRepositoryError8));
11017
11465
  return record2 === undefined ? undefined : toPublicRecord2(record2);
11018
11466
  }),
11019
11467
  getRevision: Effect68.fn("SkillRegistry.getRevision")(function* (input) {
11020
- const record2 = yield* repository.getRevision(input).pipe(Effect68.mapError(mapRepositoryError7));
11468
+ const record2 = yield* repository.getRevision(input).pipe(Effect68.mapError(mapRepositoryError8));
11021
11469
  return record2 === undefined ? undefined : toPublicRevisionRecord2(record2);
11022
11470
  }),
11023
11471
  list: Effect68.fn("SkillRegistry.list")(function* () {
11024
- const records = yield* repository.list().pipe(Effect68.mapError(mapRepositoryError7));
11472
+ const records = yield* repository.list().pipe(Effect68.mapError(mapRepositoryError8));
11025
11473
  return { records: records.map(toPublicRecord2) };
11026
11474
  }),
11027
11475
  listRevisions: Effect68.fn("SkillRegistry.listRevisions")(function* (id2) {
11028
- const records = yield* repository.listRevisions(id2).pipe(Effect68.mapError(mapRepositoryError7));
11476
+ const records = yield* repository.listRevisions(id2).pipe(Effect68.mapError(mapRepositoryError8));
11029
11477
  return { records: records.map(toPublicRevisionRecord2) };
11030
11478
  }),
11031
11479
  pinExecution: Effect68.fn("SkillRegistry.pinExecution")(function* (input) {
@@ -11034,15 +11482,15 @@ var layer45 = Layer61.effect(Service42, Effect68.gen(function* () {
11034
11482
  executionId: input.execution_id,
11035
11483
  skillDefinitionIds: input.skill_definition_ids,
11036
11484
  now
11037
- }).pipe(Effect68.mapError(mapRepositoryError7));
11485
+ }).pipe(Effect68.mapError(mapRepositoryError8));
11038
11486
  return { records: records.map(toPublicPinRecord) };
11039
11487
  }),
11040
11488
  listPins: Effect68.fn("SkillRegistry.listPins")(function* (executionId) {
11041
- const records = yield* repository.listPins(executionId).pipe(Effect68.mapError(mapRepositoryError7));
11489
+ const records = yield* repository.listPins(executionId).pipe(Effect68.mapError(mapRepositoryError8));
11042
11490
  return { records: records.map(toPublicPinRecord) };
11043
11491
  }),
11044
11492
  getPinned: Effect68.fn("SkillRegistry.getPinned")(function* (input) {
11045
- const record2 = yield* repository.getPinned(input).pipe(Effect68.mapError(mapRepositoryError7));
11493
+ const record2 = yield* repository.getPinned(input).pipe(Effect68.mapError(mapRepositoryError8));
11046
11494
  return record2 === undefined ? undefined : toPublicPinRecord(record2);
11047
11495
  })
11048
11496
  });
@@ -11130,7 +11578,7 @@ var toExecution = (record2) => ({
11130
11578
  created_at: record2.createdAt,
11131
11579
  updated_at: record2.updatedAt
11132
11580
  });
11133
- var mapRepositoryError8 = (error) => new ExecutionServiceError({ message: error._tag });
11581
+ var mapRepositoryError9 = (error) => new ExecutionServiceError({ message: error._tag });
11134
11582
  var mapEventLogError4 = (error) => new ExecutionServiceError({ message: error._tag });
11135
11583
  var mapChildRunError2 = (error) => new ExecutionServiceError({ message: error._tag });
11136
11584
  var childExecutionId2 = (input) => input.child_execution_id ?? exports_ids_schema.ChildExecutionId.make(`${input.execution_id}:child:${input.address_id}`);
@@ -11140,8 +11588,8 @@ var hasCompleteAgentDefinitionPin2 = (input) => {
11140
11588
  input.agentDefinitionRevision !== undefined,
11141
11589
  input.agentDefinitionSnapshot !== undefined
11142
11590
  ];
11143
- const count2 = present.filter(Boolean).length;
11144
- return count2 === 0 || count2 === present.length;
11591
+ const count = present.filter(Boolean).length;
11592
+ return count === 0 || count === present.length;
11145
11593
  };
11146
11594
  var validateAcceptInput = (input) => !hasCompleteAgentDefinitionPin2(input) ? Effect69.fail(new ExecutionServiceError({
11147
11595
  message: "agent definition pin must include id, revision, and snapshot together"
@@ -11183,8 +11631,8 @@ var presetMap2 = (presets) => new Map(Object.entries(presets ?? {}).map(([name,
11183
11631
  var nextEventSequence2 = Effect69.fn("ExecutionService.nextEventSequence")(function* (eventLog, input) {
11184
11632
  if (input.event_sequence !== undefined)
11185
11633
  return input.event_sequence;
11186
- const max3 = yield* eventLog.maxSequence(input.execution_id).pipe(Effect69.mapError(mapEventLogError4));
11187
- 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;
11188
11636
  });
11189
11637
  var childRunBaseInput = Effect69.fn("ExecutionService.childRunBaseInput")(function* (eventLog, input) {
11190
11638
  const eventSequence = yield* nextEventSequence2(eventLog, input);
@@ -11281,7 +11729,7 @@ var updateStatus2 = Effect69.fn("ExecutionService.updateStatus")(function* (repo
11281
11729
  status,
11282
11730
  updatedAt,
11283
11731
  ...metadata11 === undefined ? {} : { metadata: metadata11 }
11284
- }).pipe(Effect69.mapError(mapRepositoryError8));
11732
+ }).pipe(Effect69.mapError(mapRepositoryError9));
11285
11733
  return toExecution(record2);
11286
11734
  });
11287
11735
  var layer46 = Layer62.effect(Service43, Effect69.gen(function* () {
@@ -11316,7 +11764,7 @@ var layer46 = Layer62.effect(Service43, Effect69.gen(function* () {
11316
11764
  ...input.agentDefinitionSnapshot === undefined ? {} : { agentDefinitionSnapshot: input.agentDefinitionSnapshot },
11317
11765
  ...input.agentDefinitionToolInputSchemaDigests === undefined ? {} : { agentDefinitionToolInputSchemaDigests: input.agentDefinitionToolInputSchemaDigests },
11318
11766
  ...input.metadata === undefined ? {} : { metadata: input.metadata }
11319
- }).pipe(Effect69.mapError(mapRepositoryError8));
11767
+ }).pipe(Effect69.mapError(mapRepositoryError9));
11320
11768
  yield* eventLog.append(acceptedEvent(input)).pipe(Effect69.mapError(mapEventLogError4));
11321
11769
  yield* recordExecutionAccepted;
11322
11770
  return toExecution(record2);
@@ -11490,13 +11938,13 @@ var selectedDefinitions = (input) => {
11490
11938
  var requiresWorkspace = (definition) => definition.requirements?.some((requirement) => requirement.type === "workspace") ?? false;
11491
11939
  var needsWorkspace = (input) => selectedDefinitions(input).some(requiresWorkspace);
11492
11940
  var leaseId = (executionId) => exports_ids_schema.WorkspaceLeaseId.make(`workspace-lease:${executionId}`);
11493
- var mapRepositoryError9 = (error) => new WorkspacePlannerError({ message: error._tag });
11941
+ var mapRepositoryError10 = (error) => new WorkspacePlannerError({ message: error._tag });
11494
11942
  var mapEventLogError5 = (error) => new WorkspacePlannerError({ message: error._tag });
11495
11943
  var providerOrMissing = (executionId) => Effect71.serviceOption(Service29).pipe(Effect71.flatMap((provider) => Option25.match(provider, {
11496
11944
  onNone: () => Effect71.fail(new WorkspaceRuntimeMissing({ execution_id: executionId })),
11497
11945
  onSome: Effect71.succeed
11498
11946
  })));
11499
- 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)));
11500
11948
  var workspaceEvent = (type, lease, sequence, createdAt) => ({
11501
11949
  id: exports_ids_schema.EventId.make(`event:${lease.execution_id}:workspace:${type}:${sequence}`),
11502
11950
  execution_id: lease.execution_id,
@@ -11532,13 +11980,13 @@ var missingRef = (executionId) => new WorkspaceLeaseMissingRef({ execution_id: e
11532
11980
  var ensureFromExisting = Effect71.fn("WorkspacePlanner.ensureFromExisting")(function* (repository, eventLog, provider, lease, input) {
11533
11981
  if (lease.sandbox_ref === undefined) {
11534
11982
  const handle2 = yield* provider.acquire(providerAcquireSpec(input));
11535
- 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));
11536
11984
  const sequence2 = yield* nextEventSequence3(eventLog, input.executionId);
11537
11985
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.acquired", running2, sequence2, input.now);
11538
11986
  return planResult(running2, handle2);
11539
11987
  }
11540
11988
  const handle = yield* provider.resume(lease.sandbox_ref);
11541
- 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));
11542
11990
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11543
11991
  yield* appendWorkspaceEvent(eventLog, "workspace.resumed", running, sequence, input.now);
11544
11992
  return planResult(running, handle);
@@ -11551,21 +11999,21 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11551
11999
  if (!needsWorkspace(input))
11552
12000
  return;
11553
12001
  const provider = yield* providerOrMissing(input.executionId);
11554
- const existing = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12002
+ const existing = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11555
12003
  if (existing !== undefined && existing.status !== "released" && existing.status !== "failed") {
11556
12004
  return yield* ensureFromExisting(repository, eventLog, provider, existing, input);
11557
12005
  }
11558
- 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));
11559
12007
  let sequence = yield* nextEventSequence3(eventLog, input.executionId);
11560
12008
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.planned", planned, sequence, input.now);
11561
12009
  const handle = yield* provider.acquire(providerAcquireSpec(input));
11562
- 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));
11563
12011
  sequence += 1;
11564
12012
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.acquired", running, sequence, input.now);
11565
12013
  return planResult(running, handle);
11566
12014
  }),
11567
12015
  suspend: Effect71.fn("WorkspacePlanner.suspend")(function* (input) {
11568
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12016
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11569
12017
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11570
12018
  return;
11571
12019
  if (lease.sandbox_ref === undefined)
@@ -11580,26 +12028,26 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11580
12028
  if (provider.capabilities.can_suspend) {
11581
12029
  yield* provider.suspend(lease.sandbox_ref);
11582
12030
  }
11583
- 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));
11584
12032
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11585
12033
  yield* appendWorkspaceEvent(eventLog, "workspace.suspended", suspended2, sequence, input.now);
11586
12034
  return suspended2;
11587
12035
  }),
11588
12036
  resume: Effect71.fn("WorkspacePlanner.resume")(function* (input) {
11589
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12037
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11590
12038
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11591
12039
  return;
11592
12040
  if (lease.sandbox_ref === undefined)
11593
12041
  return yield* Effect71.fail(missingRef(input.executionId));
11594
12042
  const provider = yield* providerOrMissing(input.executionId);
11595
12043
  const handle = yield* provider.resume(lease.sandbox_ref);
11596
- 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));
11597
12045
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11598
12046
  yield* appendWorkspaceEvent(eventLog, "workspace.resumed", running, sequence, input.now);
11599
12047
  return planResult(running, handle);
11600
12048
  }),
11601
12049
  attach: Effect71.fn("WorkspacePlanner.attach")(function* (input) {
11602
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12050
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11603
12051
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11604
12052
  return;
11605
12053
  if (lease.sandbox_ref === undefined)
@@ -11609,27 +12057,27 @@ var layer47 = Layer64.effect(Service45, Effect71.gen(function* () {
11609
12057
  return planResult(lease, handle);
11610
12058
  }),
11611
12059
  release: Effect71.fn("WorkspacePlanner.release")(function* (input) {
11612
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12060
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11613
12061
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11614
12062
  return;
11615
12063
  if (lease.sandbox_ref === undefined)
11616
12064
  return yield* Effect71.fail(missingRef(input.executionId));
11617
12065
  const provider = yield* providerOrMissing(input.executionId);
11618
12066
  yield* provider.destroy(lease.sandbox_ref);
11619
- 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));
11620
12068
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11621
12069
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.released", released, sequence, input.now);
11622
12070
  return released;
11623
12071
  }),
11624
12072
  fail: Effect71.fn("WorkspacePlanner.fail")(function* (input) {
11625
- const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError9));
12073
+ const lease = yield* repository.getByExecution(input.executionId).pipe(Effect71.mapError(mapRepositoryError10));
11626
12074
  if (lease === undefined || lease.status === "released" || lease.status === "failed")
11627
12075
  return;
11628
12076
  const failed = yield* repository.markFailed({
11629
12077
  executionId: input.executionId,
11630
12078
  updatedAt: input.now,
11631
12079
  ...input.metadata === undefined ? {} : { metadata: input.metadata }
11632
- }).pipe(Effect71.mapError(mapRepositoryError9));
12080
+ }).pipe(Effect71.mapError(mapRepositoryError10));
11633
12081
  const sequence = yield* nextEventSequence3(eventLog, input.executionId);
11634
12082
  yield* appendWorkspaceEvent(eventLog, "workspace.lease.failed", failed, sequence, input.now);
11635
12083
  return failed;
@@ -11774,7 +12222,7 @@ var mapWaitError2 = (error) => new ExecutionWorkflowFailed({
11774
12222
  message: error._tag === "WaitNotFound" ? `Wait not found: ${error.wait_id}` : error.message
11775
12223
  });
11776
12224
  var mapAddressResolutionError = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11777
- var mapRepositoryError10 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
12225
+ var mapRepositoryError11 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11778
12226
  var mapChildExecutionRepositoryError = (error) => new ExecutionWorkflowFailed({ message: error._tag });
11779
12227
  var mapSkillRegistryError = (error) => new ExecutionWorkflowFailed({ message: error.message });
11780
12228
  var mapEventLogError6 = (error) => new ExecutionWorkflowFailed({ message: error._tag });
@@ -11864,7 +12312,7 @@ var openChildStatuses = new Set(["queued", "running", "waiting"]);
11864
12312
  var childCancelReason = "parent cancelled";
11865
12313
  var cancelChildExecution = Effect72.fn("ExecutionWorkflow.cancelChildExecution")(function* (executionId, cancelledAt) {
11866
12314
  const repository = yield* exports_execution_repository.Service;
11867
- const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError10));
12315
+ const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError11));
11868
12316
  if (record2 === undefined || terminalExecutionStatuses.has(record2.status))
11869
12317
  return;
11870
12318
  if (record2.status === "waiting") {
@@ -11899,7 +12347,7 @@ var cancelChildExecution = Effect72.fn("ExecutionWorkflow.cancelChildExecution")
11899
12347
  cancellation_requested: true,
11900
12348
  cancellation_reason: childCancelReason
11901
12349
  }
11902
- }).pipe(Effect72.mapError(mapRepositoryError10));
12350
+ }).pipe(Effect72.mapError(mapRepositoryError11));
11903
12351
  });
11904
12352
  var cancelOpenChildren = Effect72.fn("ExecutionWorkflow.cancelOpenChildren")(function* (executionId, cancelledAt) {
11905
12353
  const children = yield* exports_child_execution_repository.listByExecution(executionId).pipe(Effect72.mapError(mapChildExecutionRepositoryError));
@@ -11940,7 +12388,7 @@ var loadCancellationRequested = (input, turn) => Activity.make({
11940
12388
  error: ExecutionWorkflowFailed,
11941
12389
  execute: Effect72.gen(function* () {
11942
12390
  const repository = yield* exports_execution_repository.Service;
11943
- 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));
11944
12392
  return record2?.metadata?.cancellation_requested === true;
11945
12393
  })
11946
12394
  });
@@ -11963,7 +12411,7 @@ var markWaiting = (input, repository, wait) => Activity.make({
11963
12411
  wait_state: wait.state,
11964
12412
  ...generationMetadata(workflowGenerationForStart(input))
11965
12413
  }
11966
- }).pipe(Effect72.mapError(mapRepositoryError10), Effect72.map((record2) => ({
12414
+ }).pipe(Effect72.mapError(mapRepositoryError11), Effect72.map((record2) => ({
11967
12415
  id: record2.id,
11968
12416
  root_address_id: record2.rootAddressId,
11969
12417
  ...record2.sessionId === undefined ? {} : { session_id: record2.sessionId },
@@ -12052,7 +12500,7 @@ var steeringEnabledForStart = (input) => {
12052
12500
  return executionSetting === true;
12053
12501
  return steeringMetadataValue(input.agent_definition_snapshot?.metadata) === true;
12054
12502
  };
12055
- 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));
12056
12504
  var ensureWorkspace = (input) => Activity.make({
12057
12505
  name: ActivityNames.ensureWorkspace,
12058
12506
  success: Schema66.UndefinedOr(exports_workspace_schema.WorkspaceLeaseRecord),
@@ -12379,7 +12827,7 @@ var startRequest = Effect72.fn("ExecutionWorkflow.startRequest")(function* (inpu
12379
12827
  });
12380
12828
  var cancelRequest = Effect72.fn("ExecutionWorkflow.cancelRequest")(function* (input) {
12381
12829
  const repository = yield* exports_execution_repository.Service;
12382
- 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));
12383
12831
  if (record2 === undefined) {
12384
12832
  return yield* Effect72.fail(new ExecutionWorkflowFailed({ message: `Execution not found: ${input.execution_id}` }));
12385
12833
  }
@@ -12419,7 +12867,7 @@ var cancelRequest = Effect72.fn("ExecutionWorkflow.cancelRequest")(function* (in
12419
12867
  cancellation_requested: true,
12420
12868
  ...input.reason === undefined ? {} : { cancellation_reason: input.reason }
12421
12869
  }
12422
- }).pipe(Effect72.mapError(mapRepositoryError10));
12870
+ }).pipe(Effect72.mapError(mapRepositoryError11));
12423
12871
  return { execution_id: record2.id, status: record2.status };
12424
12872
  });
12425
12873
  var poll = (executionId) => StartExecutionWorkflow.poll(executionId);
@@ -12436,7 +12884,7 @@ var workflowExecutionIdForExecution = (executionId, workflowGeneration = 0) => S
12436
12884
  });
12437
12885
  var activeWorkflowExecutionIdForExecution = Effect72.fn("ExecutionWorkflow.activeWorkflowExecutionIdForExecution")(function* (executionId) {
12438
12886
  const repository = yield* exports_execution_repository.Service;
12439
- const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError10));
12887
+ const record2 = yield* repository.get(executionId).pipe(Effect72.mapError(mapRepositoryError11));
12440
12888
  return yield* workflowExecutionIdForExecution(executionId, record2 === undefined ? 0 : workflowGenerationFromRecord(record2));
12441
12889
  });
12442
12890
  var signalWait = Effect72.fn("ExecutionWorkflow.signalWait")(function* (input) {
@@ -12528,7 +12976,7 @@ var mapAddressBookError2 = (error) => {
12528
12976
  }
12529
12977
  return new EnvelopeServiceError({ message: error.message });
12530
12978
  };
12531
- var mapRepositoryError11 = (error) => new EnvelopeServiceError({ message: error.message });
12979
+ var mapRepositoryError12 = (error) => new EnvelopeServiceError({ message: error.message });
12532
12980
  var mapEventLogError7 = (error) => new EnvelopeServiceError({ message: error._tag });
12533
12981
  var envelopeFrom = (input) => ({
12534
12982
  id: input.envelopeId,
@@ -12623,7 +13071,7 @@ var layer50 = Layer66.effect(Service46, Effect73.gen(function* () {
12623
13071
  envelope,
12624
13072
  ...waitId === undefined ? {} : { waitId },
12625
13073
  ...ready === undefined ? {} : { ready }
12626
- }).pipe(Effect73.mapError(mapRepositoryError11));
13074
+ }).pipe(Effect73.mapError(mapRepositoryError12));
12627
13075
  yield* eventLog.append(acceptedEvent2(input)).pipe(Effect73.mapError(mapEventLogError7));
12628
13076
  yield* eventLog.append(routedEvent(input, route)).pipe(Effect73.mapError(mapEventLogError7));
12629
13077
  if (ready !== undefined) {
@@ -12763,8 +13211,8 @@ var dispatchMetadata = (schedule) => ({
12763
13211
  schedule_id: schedule.id
12764
13212
  });
12765
13213
  var nextEventSequence5 = Effect75.fn("SchedulerService.nextEventSequence")(function* (eventLog, executionId) {
12766
- const max3 = yield* eventLog.maxSequence(executionId).pipe(Effect75.mapError(toSchedulerError));
12767
- return max3 === undefined ? 0 : max3 + 1;
13214
+ const max2 = yield* eventLog.maxSequence(executionId).pipe(Effect75.mapError(toSchedulerError));
13215
+ return max2 === undefined ? 0 : max2 + 1;
12768
13216
  });
12769
13217
  var make14 = Effect75.gen(function* () {
12770
13218
  const schedules = yield* exports_schedule_repository.Service;
@@ -13607,8 +14055,8 @@ var toLease = (record2) => ({
13607
14055
  claim_expires_at: record2.claimExpiresAt ?? record2.updatedAt
13608
14056
  });
13609
14057
  var nextEventSequence6 = Effect78.fn("Client.nextEventSequence")(function* (eventLog, executionId) {
13610
- const max3 = yield* eventLog.maxSequence(executionId).pipe(Effect78.mapError(toClientError));
13611
- return max3 === undefined ? 0 : max3 + 1;
14058
+ const max2 = yield* eventLog.maxSequence(executionId).pipe(Effect78.mapError(toClientError));
14059
+ return max2 === undefined ? 0 : max2 + 1;
13612
14060
  });
13613
14061
  var wakeRuntime = Effect78.fn("Client.wakeRuntime")(function* (waits, eventLog, executionRepository, makeExecutionClient, input) {
13614
14062
  const wait = yield* waits.get(input.wait_id).pipe(Effect78.mapError(toClientError));