@sixb/pg 0.2.3 → 0.2.5

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
@@ -937,6 +937,334 @@ function rowToSession(row) {
937
937
  };
938
938
  }
939
939
 
940
+ // src/agents/inbox.ts
941
+ import {
942
+ assertEnqueueAgentInboxItemInput,
943
+ assertInboxRunOwnership,
944
+ assertInboxThreadAcceptsItem,
945
+ assertTakeAgentInboxSteersInput,
946
+ assertUpdateAgentInboxItemInput,
947
+ newAgentInboxItemRecord,
948
+ updatedAgentInboxItemRecord
949
+ } from "@sixb/core/internal/agent-run-storage-provider";
950
+ import {
951
+ AgentStorageError as AgentStorageError3
952
+ } from "@sixb/core/storage";
953
+ class PgAgentInboxStore {
954
+ sql;
955
+ constructor(sql) {
956
+ this.sql = sql;
957
+ }
958
+ async enqueue(input) {
959
+ assertEnqueueAgentInboxItemInput(input, "SixbPg");
960
+ try {
961
+ return await runPgTransaction(this.sql, async (tx) => {
962
+ const [existing] = await tx`
963
+ SELECT * FROM agent_thread_inbox
964
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
965
+ FOR UPDATE
966
+ `;
967
+ if (existing) {
968
+ if (existing.thread_id === input.threadId) {
969
+ return { item: rowToInboxItem(existing), created: false };
970
+ }
971
+ throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent inbox item '${input.id}' already exists on another thread in project '${input.projectId}'.`);
972
+ }
973
+ const [thread] = await tx`
974
+ SELECT id, kind, status, active_run_id FROM agent_threads
975
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
976
+ FOR UPDATE
977
+ `;
978
+ const [counts] = await tx`
979
+ SELECT COUNT(*) AS count, COALESCE(MAX(seq), 0) AS max_seq
980
+ FROM agent_thread_inbox
981
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
982
+ `;
983
+ assertInboxThreadAcceptsItem(thread ?? null, input.threadId, input.projectId, Number(counts?.count ?? 0), "SixbPg");
984
+ const [existingMessage] = await tx`
985
+ SELECT id FROM agent_messages
986
+ WHERE project_id = ${input.projectId} AND id = ${input.messageId}
987
+ `;
988
+ if (existingMessage) {
989
+ throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent message '${input.messageId}' already exists for project '${input.projectId}'.`);
990
+ }
991
+ const record = newAgentInboxItemRecord(input, Number(counts?.max_seq ?? 0) + 1);
992
+ const [inserted] = await tx`
993
+ INSERT INTO agent_thread_inbox (
994
+ project_id, id, thread_id, message_id, seq,
995
+ author_principal_type, author_principal_id, mode, parts, spec,
996
+ time_zone, locale, immediate, execution_id, created_at, updated_at
997
+ ) VALUES (
998
+ ${record.projectId},
999
+ ${record.id},
1000
+ ${record.threadId},
1001
+ ${record.messageId},
1002
+ ${record.seq},
1003
+ ${record.authorPrincipal.type},
1004
+ ${record.authorPrincipal.id},
1005
+ ${record.mode},
1006
+ ${JSON.stringify(record.parts)}::text::jsonb,
1007
+ ${record.spec === undefined ? null : JSON.stringify(record.spec)}::text::jsonb,
1008
+ ${record.timeZone ?? null},
1009
+ ${record.locale ?? null},
1010
+ ${Boolean(record.immediate)},
1011
+ ${record.executionId ?? null},
1012
+ ${record.createdAt},
1013
+ ${record.updatedAt}
1014
+ )
1015
+ RETURNING *
1016
+ `;
1017
+ return { item: rowToInboxItem(inserted), created: true };
1018
+ });
1019
+ } catch (error) {
1020
+ if (isUniqueViolation(error)) {
1021
+ throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent inbox item or message id already exists for project '${input.projectId}'.`);
1022
+ }
1023
+ throw error;
1024
+ }
1025
+ }
1026
+ async getById(params) {
1027
+ const [row] = await this.sql`
1028
+ SELECT * FROM agent_thread_inbox
1029
+ WHERE project_id = ${params.projectId} AND id = ${params.id}
1030
+ `;
1031
+ return row ? rowToInboxItem(row) : null;
1032
+ }
1033
+ async list(input) {
1034
+ const includeClaimed = input.includeClaimed ?? true;
1035
+ const rows = includeClaimed ? await this.sql`
1036
+ SELECT * FROM agent_thread_inbox
1037
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
1038
+ ORDER BY seq ASC
1039
+ ` : await this.sql`
1040
+ SELECT * FROM agent_thread_inbox
1041
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
1042
+ AND claimed_by_run_id IS NULL
1043
+ ORDER BY seq ASC
1044
+ `;
1045
+ return rows.map(rowToInboxItem);
1046
+ }
1047
+ async listWaitingThreads(input) {
1048
+ const rows = await this.sql`
1049
+ SELECT DISTINCT inbox.thread_id
1050
+ FROM agent_thread_inbox inbox
1051
+ JOIN agent_threads thread
1052
+ ON thread.project_id = inbox.project_id AND thread.id = inbox.thread_id
1053
+ WHERE inbox.project_id = ${input.projectId}
1054
+ AND inbox.created_at < ${input.createdBefore}
1055
+ AND inbox.thread_id > ${input.afterThreadId ?? ""}
1056
+ AND thread.active_run_id IS NULL
1057
+ ORDER BY inbox.thread_id ASC
1058
+ LIMIT ${input.limit}
1059
+ `;
1060
+ return rows.map((row) => row.thread_id);
1061
+ }
1062
+ async update(input) {
1063
+ assertUpdateAgentInboxItemInput(input, "SixbPg");
1064
+ return runPgTransaction(this.sql, async (tx) => {
1065
+ const [current] = await tx`
1066
+ SELECT * FROM agent_thread_inbox
1067
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
1068
+ FOR UPDATE
1069
+ `;
1070
+ if (!current || current.thread_id !== input.threadId)
1071
+ return null;
1072
+ const next = updatedAgentInboxItemRecord(rowToInboxItem(current), input);
1073
+ const [updated] = await tx`
1074
+ UPDATE agent_thread_inbox
1075
+ SET
1076
+ mode = ${next.mode},
1077
+ parts = ${JSON.stringify(next.parts)}::text::jsonb,
1078
+ spec = ${next.spec === undefined ? null : JSON.stringify(next.spec)}::text::jsonb,
1079
+ immediate = ${Boolean(next.immediate)},
1080
+ updated_at = ${next.updatedAt}
1081
+ WHERE project_id = ${next.projectId} AND id = ${next.id}
1082
+ RETURNING *
1083
+ `;
1084
+ return updated ? rowToInboxItem(updated) : null;
1085
+ });
1086
+ }
1087
+ async remove(input) {
1088
+ return runPgTransaction(this.sql, async (tx) => {
1089
+ const [current] = await tx`
1090
+ SELECT * FROM agent_thread_inbox
1091
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
1092
+ FOR UPDATE
1093
+ `;
1094
+ if (!current || current.thread_id !== input.threadId)
1095
+ return null;
1096
+ if (current.claimed_by_run_id !== null) {
1097
+ throw new AgentStorageError3("invalid_state", `[SixbPg] Agent inbox item '${current.id}' was already claimed by run '${current.claimed_by_run_id}'.`);
1098
+ }
1099
+ await tx`
1100
+ DELETE FROM agent_thread_inbox
1101
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
1102
+ `;
1103
+ return rowToInboxItem(current);
1104
+ });
1105
+ }
1106
+ async takeSteers(input) {
1107
+ assertTakeAgentInboxSteersInput(input, "SixbPg");
1108
+ return runPgTransaction(this.sql, async (tx) => {
1109
+ const run = await lockRun2(tx, input.projectId, input.runId);
1110
+ assertInboxRunOwnership(run, input, "SixbPg");
1111
+ const updatedAt = new Date;
1112
+ const rows = await tx`
1113
+ UPDATE agent_thread_inbox
1114
+ SET
1115
+ claimed_by_run_id = ${input.runId},
1116
+ claimed_by_token = ${input.executionToken},
1117
+ claimed_by_step = ${input.stepIndex},
1118
+ claimed_after_answer = ${input.afterAnswer ? true : null}::boolean,
1119
+ updated_at = ${updatedAt}
1120
+ WHERE project_id = ${input.projectId}
1121
+ AND thread_id = ${input.threadId}
1122
+ AND (
1123
+ claimed_by_run_id IS NULL
1124
+ OR claimed_by_run_id <> ${input.runId}
1125
+ OR claimed_by_token <> ${input.executionToken}
1126
+ )
1127
+ AND mode = 'steer'
1128
+ AND immediate = FALSE
1129
+ AND author_principal_type = ${input.authorPrincipal.type}
1130
+ AND author_principal_id = ${input.authorPrincipal.id}
1131
+ RETURNING *
1132
+ `;
1133
+ return rows.map(rowToInboxItem).sort((left, right) => left.seq - right.seq);
1134
+ });
1135
+ }
1136
+ async consumeClaimed(input) {
1137
+ return runPgTransaction(this.sql, async (tx) => {
1138
+ const run = await lockRun2(tx, input.projectId, input.runId);
1139
+ assertInboxRunOwnership(run, input, "SixbPg");
1140
+ const claimed = await tx`
1141
+ SELECT * FROM agent_thread_inbox
1142
+ WHERE project_id = ${input.projectId}
1143
+ AND thread_id = ${input.threadId}
1144
+ AND claimed_by_run_id = ${input.runId}
1145
+ AND claimed_by_token = ${input.executionToken}
1146
+ ORDER BY seq ASC
1147
+ FOR UPDATE
1148
+ `;
1149
+ if (claimed.length === 0)
1150
+ return [];
1151
+ const persisted = new Set(input.messageIds);
1152
+ const updatedAt = new Date;
1153
+ const consumed = [];
1154
+ for (const row of claimed) {
1155
+ if (persisted.has(row.message_id)) {
1156
+ await tx`
1157
+ DELETE FROM agent_thread_inbox
1158
+ WHERE project_id = ${row.project_id} AND id = ${row.id}
1159
+ `;
1160
+ consumed.push(rowToInboxItem(row));
1161
+ } else {
1162
+ await tx`
1163
+ UPDATE agent_thread_inbox
1164
+ SET
1165
+ claimed_by_run_id = NULL,
1166
+ claimed_by_token = NULL,
1167
+ claimed_by_step = NULL,
1168
+ claimed_after_answer = NULL,
1169
+ updated_at = ${updatedAt}
1170
+ WHERE project_id = ${row.project_id} AND id = ${row.id}
1171
+ `;
1172
+ }
1173
+ }
1174
+ return consumed;
1175
+ });
1176
+ }
1177
+ async releaseClaimed(input) {
1178
+ const updatedAt = new Date;
1179
+ const rows = await this.sql`
1180
+ UPDATE agent_thread_inbox
1181
+ SET
1182
+ claimed_by_run_id = NULL,
1183
+ claimed_by_token = NULL,
1184
+ claimed_by_step = NULL,
1185
+ claimed_after_answer = NULL,
1186
+ updated_at = ${updatedAt}
1187
+ WHERE project_id = ${input.projectId} AND claimed_by_run_id = ${input.runId}
1188
+ RETURNING id
1189
+ `;
1190
+ return rows.length;
1191
+ }
1192
+ async takeNextQueued(input) {
1193
+ return runPgTransaction(this.sql, async (tx) => {
1194
+ const [thread] = await tx`
1195
+ SELECT id, kind, status, active_run_id FROM agent_threads
1196
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
1197
+ FOR UPDATE
1198
+ `;
1199
+ if (!thread || thread.status !== "active" || thread.active_run_id !== null)
1200
+ return null;
1201
+ const [winner] = await tx`
1202
+ SELECT * FROM agent_thread_inbox
1203
+ WHERE project_id = ${input.projectId}
1204
+ AND thread_id = ${input.threadId}
1205
+ AND claimed_by_run_id IS NULL
1206
+ AND (${!input.onlyImmediate}::boolean OR immediate = TRUE)
1207
+ AND (
1208
+ ${input.authorPrincipal?.id ?? null}::text IS NULL
1209
+ OR (author_principal_type = ${input.authorPrincipal?.type ?? null}
1210
+ AND author_principal_id = ${input.authorPrincipal?.id ?? null})
1211
+ )
1212
+ ORDER BY
1213
+ CASE WHEN immediate = TRUE THEN 0 WHEN mode = 'steer' THEN 1 ELSE 2 END ASC,
1214
+ seq ASC
1215
+ LIMIT 1
1216
+ FOR UPDATE
1217
+ `;
1218
+ if (!winner)
1219
+ return null;
1220
+ await tx`
1221
+ DELETE FROM agent_thread_inbox
1222
+ WHERE project_id = ${winner.project_id} AND id = ${winner.id}
1223
+ `;
1224
+ return rowToInboxItem(winner);
1225
+ });
1226
+ }
1227
+ }
1228
+ async function lockRun2(tx, projectId, id) {
1229
+ const [row] = await tx`
1230
+ SELECT * FROM agent_runs WHERE project_id = ${projectId} AND id = ${id} FOR UPDATE
1231
+ `;
1232
+ return row ? rowToRunRecord(row) : null;
1233
+ }
1234
+ function parseJson2(value) {
1235
+ return typeof value === "string" ? JSON.parse(value) : value;
1236
+ }
1237
+ function rowToInboxItem(row) {
1238
+ const spec = row.spec === null ? undefined : parseJson2(row.spec);
1239
+ const claimedBy = row.claimed_by_run_id !== null && row.claimed_by_token !== null && row.claimed_by_step !== null ? {
1240
+ runId: row.claimed_by_run_id,
1241
+ executionToken: row.claimed_by_token,
1242
+ stepIndex: Number(row.claimed_by_step),
1243
+ ...row.claimed_after_answer === true ? { afterAnswer: true } : {}
1244
+ } : undefined;
1245
+ return {
1246
+ id: row.id,
1247
+ projectId: row.project_id,
1248
+ threadId: row.thread_id,
1249
+ messageId: row.message_id,
1250
+ seq: Number(row.seq),
1251
+ authorPrincipal: {
1252
+ type: row.author_principal_type,
1253
+ id: row.author_principal_id
1254
+ },
1255
+ mode: row.mode,
1256
+ parts: parseJson2(row.parts),
1257
+ ...spec ? { spec } : {},
1258
+ ...row.time_zone ? { timeZone: row.time_zone } : {},
1259
+ ...row.locale ? { locale: row.locale } : {},
1260
+ ...row.immediate ? { immediate: true } : {},
1261
+ ...row.execution_id ? { executionId: row.execution_id } : {},
1262
+ ...claimedBy ? { claimedBy } : {},
1263
+ createdAt: new Date(row.created_at),
1264
+ updatedAt: new Date(row.updated_at)
1265
+ };
1266
+ }
1267
+
940
1268
  // src/agents/memory.ts
941
1269
  import {
942
1270
  agentMemoryConflicts,
@@ -1069,7 +1397,7 @@ class PgAgentMemoryStore {
1069
1397
  import { countsAsThreadMessage } from "@sixb/core/internal/agent-run-storage-provider";
1070
1398
  import { AGENT_MESSAGE_CONTENT_VERSION } from "@sixb/core/internal/agents";
1071
1399
  import {
1072
- AgentStorageError as AgentStorageError3
1400
+ AgentStorageError as AgentStorageError4
1073
1401
  } from "@sixb/core/storage";
1074
1402
  class PgAgentMessageStore {
1075
1403
  sql;
@@ -1087,7 +1415,7 @@ class PgAgentMessageStore {
1087
1415
  FOR UPDATE
1088
1416
  `;
1089
1417
  if (!run) {
1090
- throw new AgentStorageError3("run_not_found", `[SixbPg] Agent run '${input.runId}' not found for project '${input.projectId}'.`);
1418
+ throw new AgentStorageError4("run_not_found", `[SixbPg] Agent run '${input.runId}' not found for project '${input.projectId}'.`);
1091
1419
  }
1092
1420
  }
1093
1421
  const [thread] = await tx`
@@ -1096,7 +1424,7 @@ class PgAgentMessageStore {
1096
1424
  FOR UPDATE
1097
1425
  `;
1098
1426
  if (!thread) {
1099
- throw new AgentStorageError3("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1427
+ throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1100
1428
  }
1101
1429
  const [seqRow] = await tx`
1102
1430
  SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM agent_messages
@@ -1146,7 +1474,7 @@ class PgAgentMessageStore {
1146
1474
  });
1147
1475
  } catch (error) {
1148
1476
  if (isUniqueViolation(error)) {
1149
- throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent message '${input.id}' already exists for project '${input.projectId}'.`);
1477
+ throw new AgentStorageError4("duplicate_id", `[SixbPg] Agent message '${input.id}' already exists for project '${input.projectId}'.`);
1150
1478
  }
1151
1479
  throw error;
1152
1480
  }
@@ -1161,7 +1489,7 @@ class PgAgentMessageStore {
1161
1489
  FOR SHARE
1162
1490
  `;
1163
1491
  if (!owner) {
1164
- throw new AgentStorageError3("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.fence.runId}'.`);
1492
+ throw new AgentStorageError4("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.fence.runId}'.`);
1165
1493
  }
1166
1494
  }
1167
1495
  const [thread] = await tx`
@@ -1170,7 +1498,7 @@ class PgAgentMessageStore {
1170
1498
  FOR UPDATE
1171
1499
  `;
1172
1500
  if (!thread) {
1173
- throw new AgentStorageError3("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1501
+ throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1174
1502
  }
1175
1503
  const deleted = await tx`
1176
1504
  DELETE FROM agent_messages
@@ -1258,7 +1586,7 @@ import { AGENT_MESSAGE_CONTENT_VERSION as AGENT_MESSAGE_CONTENT_VERSION2 } from
1258
1586
  import { serializeSixbFailure } from "@sixb/core/internal/errors";
1259
1587
  import {
1260
1588
  AGENT_RUN_FAILURE_CODES as AGENT_RUN_FAILURE_CODES2,
1261
- AgentStorageError as AgentStorageError4
1589
+ AgentStorageError as AgentStorageError5
1262
1590
  } from "@sixb/core/storage";
1263
1591
 
1264
1592
  // src/run-list-query.ts
@@ -1343,11 +1671,11 @@ class PgAgentRunStore {
1343
1671
  FOR UPDATE
1344
1672
  `;
1345
1673
  if (!thread) {
1346
- throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1674
+ throw new AgentStorageError5("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1347
1675
  }
1348
1676
  assertConversationThreadRow(thread, "takes turns", "SixbPg");
1349
1677
  if (thread.active_run_id !== null) {
1350
- throw new AgentStorageError4("active_run_exists", `[SixbPg] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`);
1678
+ throw new AgentStorageError5("active_run_exists", `[SixbPg] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`);
1351
1679
  }
1352
1680
  assertTurnInThreadPlace(thread.runs_on, input.spec, input.threadId, "SixbPg");
1353
1681
  const [row] = await tx`
@@ -1388,7 +1716,7 @@ class PgAgentRunStore {
1388
1716
  });
1389
1717
  } catch (error) {
1390
1718
  if (isUniqueViolation(error)) {
1391
- throw new AgentStorageError4("duplicate_id", `[SixbPg] Agent run '${input.id}' already exists for project '${input.projectId}'.`);
1719
+ throw new AgentStorageError5("duplicate_id", `[SixbPg] Agent run '${input.id}' already exists for project '${input.projectId}'.`);
1392
1720
  }
1393
1721
  throw error;
1394
1722
  }
@@ -1409,7 +1737,7 @@ class PgAgentRunStore {
1409
1737
  FOR UPDATE
1410
1738
  `;
1411
1739
  if (!parent || parent.kind !== "conversation") {
1412
- throw new AgentStorageError4("run_not_found", `[SixbPg] Parent Agent run '${input.parentRunId}' was not found.`);
1740
+ throw new AgentStorageError5("run_not_found", `[SixbPg] Parent Agent run '${input.parentRunId}' was not found.`);
1413
1741
  }
1414
1742
  const [existingRow] = await tx`
1415
1743
  SELECT * FROM agent_runs
@@ -1419,16 +1747,16 @@ class PgAgentRunStore {
1419
1747
  const existing = rowToRunRecord(existingRow);
1420
1748
  if (subagentRunMatchesCreateInput(existing, input))
1421
1749
  return existing;
1422
- throw new AgentStorageError4("duplicate_id", `[SixbPg] Subagent run '${input.id}' already exists with different immutable inputs.`);
1750
+ throw new AgentStorageError5("duplicate_id", `[SixbPg] Subagent run '${input.id}' already exists with different immutable inputs.`);
1423
1751
  }
1424
1752
  if (parent.status !== "running") {
1425
- throw new AgentStorageError4("invalid_state", `[SixbPg] Parent Agent run '${parent.id}' is not running (status '${parent.status}').`);
1753
+ throw new AgentStorageError5("invalid_state", `[SixbPg] Parent Agent run '${parent.id}' is not running (status '${parent.status}').`);
1426
1754
  }
1427
1755
  if (execution.source.type !== "execution" || execution.source.executionId !== parent.execution_id) {
1428
- throw new AgentStorageError4("invalid_input", `[SixbPg] Subagent execution '${execution.id}' is not a child of parent execution '${parent.execution_id}'.`);
1756
+ throw new AgentStorageError5("invalid_input", `[SixbPg] Subagent execution '${execution.id}' is not a child of parent execution '${parent.execution_id}'.`);
1429
1757
  }
1430
1758
  if (parent.execution_token !== input.parentExecutionToken) {
1431
- throw new AgentStorageError4("execution_lost", `[SixbPg] Parent Agent run '${parent.id}' is no longer owned by this execution.`);
1759
+ throw new AgentStorageError5("execution_lost", `[SixbPg] Parent Agent run '${parent.id}' is no longer owned by this execution.`);
1432
1760
  }
1433
1761
  const [countRow] = await tx`
1434
1762
  SELECT COUNT(*)::bigint AS count FROM agent_runs
@@ -1438,7 +1766,7 @@ class PgAgentRunStore {
1438
1766
  `;
1439
1767
  const activeChildren = Number(countRow?.count ?? 0);
1440
1768
  if (activeChildren >= input.maxActiveChildren) {
1441
- throw new AgentStorageError4("active_child_limit", `[SixbPg] Agent run '${parent.id}' already has ${activeChildren} active subagents.`);
1769
+ throw new AgentStorageError5("active_child_limit", `[SixbPg] Agent run '${parent.id}' already has ${activeChildren} active subagents.`);
1442
1770
  }
1443
1771
  const createdAt = input.createdAt ?? new Date;
1444
1772
  await claimChildThread(tx, input, parent, createdAt);
@@ -1475,7 +1803,7 @@ class PgAgentRunStore {
1475
1803
  });
1476
1804
  } catch (error) {
1477
1805
  if (isUniqueViolation(error)) {
1478
- throw new AgentStorageError4("duplicate_id", `[SixbPg] Subagent run '${input.id}' conflicts with an existing durable spawn.`);
1806
+ throw new AgentStorageError5("duplicate_id", `[SixbPg] Subagent run '${input.id}' conflicts with an existing durable spawn.`);
1479
1807
  }
1480
1808
  throw error;
1481
1809
  }
@@ -1527,7 +1855,7 @@ class PgAgentRunStore {
1527
1855
  return runPgTransaction(this.sql, async (tx) => {
1528
1856
  const run = await this.lockRunning(tx, input.projectId, input.id);
1529
1857
  if (input.ifLapsedBy && run.execution_queue_lease_expires_at !== null && new Date(run.execution_queue_lease_expires_at).getTime() > input.ifLapsedBy.getTime()) {
1530
- throw new AgentStorageError4("invalid_state", `[SixbPg] Agent run '${input.id}' is still held by its runner, whose lease has not lapsed.`);
1858
+ throw new AgentStorageError5("invalid_state", `[SixbPg] Agent run '${input.id}' is still held by its runner, whose lease has not lapsed.`);
1531
1859
  }
1532
1860
  const [row] = await tx`
1533
1861
  UPDATE agent_runs
@@ -1545,7 +1873,7 @@ class PgAgentRunStore {
1545
1873
  return runPgTransaction(this.sql, async (tx) => {
1546
1874
  const run = await this.lockRunning(tx, input.projectId, input.id);
1547
1875
  if (run.execution_token !== input.executionToken) {
1548
- throw new AgentStorageError4("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
1876
+ throw new AgentStorageError5("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
1549
1877
  }
1550
1878
  const [row] = await tx`
1551
1879
  UPDATE agent_runs
@@ -1571,7 +1899,7 @@ class PgAgentRunStore {
1571
1899
  return rowToRunRecord(updated);
1572
1900
  const current = await this.getById(input);
1573
1901
  if (!current) {
1574
- throw new AgentStorageError4("run_not_found", `[SixbPg] Agent run '${input.id}' not found for project '${input.projectId}'.`);
1902
+ throw new AgentStorageError5("run_not_found", `[SixbPg] Agent run '${input.id}' not found for project '${input.projectId}'.`);
1575
1903
  }
1576
1904
  return current;
1577
1905
  }
@@ -1582,7 +1910,7 @@ class PgAgentRunStore {
1582
1910
  const run = await this.lockRunning(tx, input.projectId, input.id);
1583
1911
  assertAgentRunFinishPayload(run.kind, input, run.id, "SixbPg");
1584
1912
  if (run.execution_token !== input.executionToken) {
1585
- throw new AgentStorageError4("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
1913
+ throw new AgentStorageError5("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
1586
1914
  }
1587
1915
  if (input.finishReason === "awaiting_approval") {
1588
1916
  assertAwaitingApprovalFinish({
@@ -1701,10 +2029,10 @@ class PgAgentRunStore {
1701
2029
  FOR UPDATE
1702
2030
  `;
1703
2031
  if (!row) {
1704
- throw new AgentStorageError4("run_not_found", `[SixbPg] Agent run '${id}' not found for project '${projectId}'.`);
2032
+ throw new AgentStorageError5("run_not_found", `[SixbPg] Agent run '${id}' not found for project '${projectId}'.`);
1705
2033
  }
1706
2034
  if (row.status !== status) {
1707
- throw new AgentStorageError4("invalid_state", `[SixbPg] Agent run '${id}' is not ${status} (status '${row.status}').`);
2035
+ throw new AgentStorageError5("invalid_state", `[SixbPg] Agent run '${id}' is not ${status} (status '${row.status}').`);
1708
2036
  }
1709
2037
  return row;
1710
2038
  }
@@ -1735,7 +2063,7 @@ async function claimChildThread(tx, input, parent, createdAt) {
1735
2063
  SELECT * FROM agent_threads WHERE project_id = ${input.projectId} AND id = ${parent.thread_id}
1736
2064
  `;
1737
2065
  if (!conversation) {
1738
- throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${parent.thread_id}' not found for project '${input.projectId}'.`);
2066
+ throw new AgentStorageError5("thread_not_found", `[SixbPg] Agent thread '${parent.thread_id}' not found for project '${input.projectId}'.`);
1739
2067
  }
1740
2068
  const thread = newSubagentThreadRecord(input, rowToThreadRecord(conversation), createdAt);
1741
2069
  await tx`
@@ -1774,7 +2102,7 @@ async function settleFinishedRunApprovals(tx, kind, input, completedAt) {
1774
2102
  // src/agents/settings.ts
1775
2103
  import { assertAgentApprovalModeInput } from "@sixb/core/internal/agent-run-storage-provider";
1776
2104
  import {
1777
- AgentStorageError as AgentStorageError5
2105
+ AgentStorageError as AgentStorageError6
1778
2106
  } from "@sixb/core/storage";
1779
2107
  class PgAgentApprovalModeStore {
1780
2108
  sql;
@@ -1848,7 +2176,7 @@ class PgAgentApprovalModeStore {
1848
2176
  }
1849
2177
  }
1850
2178
  function threadNotFound(input) {
1851
- return new AgentStorageError5("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
2179
+ return new AgentStorageError6("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
1852
2180
  }
1853
2181
 
1854
2182
  // src/agents/threads.ts
@@ -1867,7 +2195,7 @@ import {
1867
2195
  transitionAgentThreadSandbox
1868
2196
  } from "@sixb/core/internal/agent-run-storage-provider";
1869
2197
  import {
1870
- AgentStorageError as AgentStorageError6
2198
+ AgentStorageError as AgentStorageError7
1871
2199
  } from "@sixb/core/storage";
1872
2200
  class PgAgentThreadStore {
1873
2201
  sql;
@@ -1876,7 +2204,7 @@ class PgAgentThreadStore {
1876
2204
  }
1877
2205
  async transitionSandbox(input) {
1878
2206
  return runPgTransaction(this.sql, async (tx) => {
1879
- const runs = input.action === "recreate" ? [] : await tx`
2207
+ const runs = input.action === "recreate" || input.action === "restore" ? [] : await tx`
1880
2208
  SELECT * FROM agent_runs WHERE project_id = ${input.projectId} AND id = ${input.runId}
1881
2209
  FOR UPDATE
1882
2210
  `;
@@ -1929,7 +2257,7 @@ class PgAgentThreadStore {
1929
2257
  return rowToThreadRecord(row);
1930
2258
  } catch (error) {
1931
2259
  if (isUniqueViolation(error)) {
1932
- throw new AgentStorageError6("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
2260
+ throw new AgentStorageError7("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
1933
2261
  }
1934
2262
  throw error;
1935
2263
  }
@@ -1943,7 +2271,7 @@ class PgAgentThreadStore {
1943
2271
  FOR SHARE
1944
2272
  `;
1945
2273
  if (!source) {
1946
- throw new AgentStorageError6("thread_not_found", `[SixbPg] Agent thread '${input.sourceThreadId}' not found for project '${input.projectId}'.`);
2274
+ throw new AgentStorageError7("thread_not_found", `[SixbPg] Agent thread '${input.sourceThreadId}' not found for project '${input.projectId}'.`);
1947
2275
  }
1948
2276
  assertConversationThreadRow2(source, "can be forked", "SixbPg");
1949
2277
  const [activeRun] = source.active_run_id === null ? [] : await tx`
@@ -2057,7 +2385,7 @@ class PgAgentThreadStore {
2057
2385
  });
2058
2386
  } catch (error) {
2059
2387
  if (isUniqueViolationOf(error, "agent_threads_pkey")) {
2060
- throw new AgentStorageError6("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
2388
+ throw new AgentStorageError7("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
2061
2389
  }
2062
2390
  throw error;
2063
2391
  }
@@ -2150,7 +2478,7 @@ class PgAgentThreadStore {
2150
2478
  FOR UPDATE
2151
2479
  `;
2152
2480
  if (!thread) {
2153
- throw new AgentStorageError6("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
2481
+ throw new AgentStorageError7("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
2154
2482
  }
2155
2483
  assertConversationThreadRow2(thread, "has participants", "SixbPg");
2156
2484
  const existing = await selectParticipants(tx, input.projectId, [input.threadId]);
@@ -2259,7 +2587,7 @@ async function lockThreadAndActiveRun(tx, input) {
2259
2587
  };
2260
2588
  }
2261
2589
  if (attempt >= 3) {
2262
- throw new AgentStorageError6("invalid_state", `[SixbPg] Agent thread '${input.id}' kept changing turns while it moved: try again.`);
2590
+ throw new AgentStorageError7("invalid_state", `[SixbPg] Agent thread '${input.id}' kept changing turns while it moved: try again.`);
2263
2591
  }
2264
2592
  }
2265
2593
  }
@@ -2397,6 +2725,7 @@ class PgAgentStorage {
2397
2725
  approvalModes;
2398
2726
  computers;
2399
2727
  tokenRates;
2728
+ inbox;
2400
2729
  constructor(options) {
2401
2730
  this.threads = new PgAgentThreadStore(options.sql);
2402
2731
  this.runs = new PgAgentRunStore(options.sql, options.executions);
@@ -2407,6 +2736,7 @@ class PgAgentStorage {
2407
2736
  this.approvalModes = new PgAgentApprovalModeStore(options.sql);
2408
2737
  this.computers = new PgAgentComputerSessionStore(options.sql);
2409
2738
  this.tokenRates = new PgAgentTokenRateStore(options.sql);
2739
+ this.inbox = new PgAgentInboxStore(options.sql);
2410
2740
  }
2411
2741
  }
2412
2742
  // src/auth-storage/auth-storage.ts
@@ -10687,6 +11017,234 @@ ALTER TABLE auth_users
10687
11017
  );
10688
11018
  `;
10689
11019
 
11020
+ // src/migrations/103-script-executions.sql
11021
+ var _103_script_executions_default = `-- \`sixb run\` records each script run as an execution: a script executor, the script's path as its
11022
+ -- source, and authority that holds nothing beyond the run id the executor already names.
11023
+ ALTER TABLE executions
11024
+ DROP CONSTRAINT executions_executor_kind_check,
11025
+ ADD CONSTRAINT executions_executor_kind_check CHECK (
11026
+ executor_kind IN (
11027
+ 'request', 'action', 'pipeline', 'projection', 'rule', 'sync', 'webhook', 'workflow',
11028
+ 'agent', 'kernel', 'script'
11029
+ )
11030
+ ),
11031
+ DROP CONSTRAINT executions_source_kind_check,
11032
+ ADD CONSTRAINT executions_source_kind_check CHECK (
11033
+ source_kind IN (
11034
+ 'http', 'webhook', 'schedule', 'event', 'datasetVersion', 'execution', 'ontologyCommit',
11035
+ 'script'
11036
+ )
11037
+ ),
11038
+ DROP CONSTRAINT executions_authority_kind_check,
11039
+ ADD CONSTRAINT executions_authority_kind_check CHECK (
11040
+ authority_kind IN ('principal', 'trustedPrimitive', 'delegated', 'kernel', 'script', 'disabled')
11041
+ ),
11042
+ DROP CONSTRAINT executions_authority_shape_check,
11043
+ ADD CONSTRAINT executions_authority_shape_check CHECK (
11044
+ (
11045
+ authority_kind = 'principal'
11046
+ AND num_nonnulls(authority_user_id, authority_service_account_id) = 1
11047
+ AND num_nonnulls(authority_session_id, authority_access_token_id) <= 1
11048
+ AND (authority_session_id IS NULL OR authority_user_id IS NOT NULL)
11049
+ AND authority_primitive_kind IS NULL
11050
+ AND authority_primitive_id IS NULL
11051
+ AND authority_kernel_operation IS NULL
11052
+ AND authority_delegation_kind IS NULL
11053
+ AND authority_delegation_id IS NULL
11054
+ AND authority_delegation_session_id IS NULL
11055
+ )
11056
+ OR (
11057
+ authority_kind = 'trustedPrimitive'
11058
+ AND authority_user_id IS NULL
11059
+ AND authority_service_account_id IS NULL
11060
+ AND authority_session_id IS NULL
11061
+ AND authority_access_token_id IS NULL
11062
+ AND authority_primitive_kind IS NOT NULL
11063
+ AND authority_primitive_id IS NOT NULL
11064
+ AND length(trim(authority_primitive_id)) > 0
11065
+ AND authority_kernel_operation IS NULL
11066
+ AND authority_delegation_kind IS NULL
11067
+ AND authority_delegation_id IS NULL
11068
+ AND authority_delegation_session_id IS NULL
11069
+ )
11070
+ OR (
11071
+ authority_kind = 'delegated'
11072
+ AND authority_user_id IS NULL
11073
+ AND authority_service_account_id IS NULL
11074
+ AND authority_session_id IS NULL
11075
+ AND authority_access_token_id IS NULL
11076
+ AND authority_primitive_kind IS NULL
11077
+ AND authority_primitive_id IS NULL
11078
+ AND authority_kernel_operation IS NULL
11079
+ AND authority_delegation_kind IS NOT NULL
11080
+ AND authority_delegation_kind = 'share'
11081
+ AND authority_delegation_id IS NOT NULL
11082
+ AND length(trim(authority_delegation_id)) > 0
11083
+ AND authority_delegation_session_id IS NOT NULL
11084
+ AND length(trim(authority_delegation_session_id)) > 0
11085
+ )
11086
+ OR (
11087
+ authority_kind = 'kernel'
11088
+ AND authority_user_id IS NULL
11089
+ AND authority_service_account_id IS NULL
11090
+ AND authority_session_id IS NULL
11091
+ AND authority_access_token_id IS NULL
11092
+ AND authority_primitive_kind IS NULL
11093
+ AND authority_primitive_id IS NULL
11094
+ AND authority_kernel_operation IS NOT NULL
11095
+ AND authority_delegation_kind IS NULL
11096
+ AND authority_delegation_id IS NULL
11097
+ AND authority_delegation_session_id IS NULL
11098
+ )
11099
+ OR (
11100
+ -- A script's authority is its run id, which \`executor_id\` already holds.
11101
+ authority_kind IN ('script', 'disabled')
11102
+ AND authority_user_id IS NULL
11103
+ AND authority_service_account_id IS NULL
11104
+ AND authority_session_id IS NULL
11105
+ AND authority_access_token_id IS NULL
11106
+ AND authority_primitive_kind IS NULL
11107
+ AND authority_primitive_id IS NULL
11108
+ AND authority_kernel_operation IS NULL
11109
+ AND authority_delegation_kind IS NULL
11110
+ AND authority_delegation_id IS NULL
11111
+ AND authority_delegation_session_id IS NULL
11112
+ )
11113
+ ),
11114
+ DROP CONSTRAINT executions_executor_authority_check,
11115
+ ADD CONSTRAINT executions_executor_authority_check CHECK (
11116
+ (
11117
+ executor_kind = 'request'
11118
+ AND source_kind = 'http'
11119
+ AND executor_id = source_id
11120
+ AND (
11121
+ (
11122
+ authority_kind = 'principal'
11123
+ AND requested_by_user_id IS NOT DISTINCT FROM authority_user_id
11124
+ AND requested_by_service_account_id IS NOT DISTINCT FROM authority_service_account_id
11125
+ )
11126
+ OR (
11127
+ authority_kind IN ('delegated', 'disabled')
11128
+ AND requested_by_user_id IS NULL
11129
+ AND requested_by_service_account_id IS NULL
11130
+ )
11131
+ )
11132
+ )
11133
+ OR (
11134
+ executor_kind IN ('action', 'pipeline', 'projection', 'rule', 'sync', 'webhook', 'workflow')
11135
+ AND source_kind <> 'script'
11136
+ AND authority_kind = 'trustedPrimitive'
11137
+ AND executor_kind = authority_primitive_kind
11138
+ )
11139
+ OR (
11140
+ executor_kind = 'agent'
11141
+ AND source_kind = 'execution'
11142
+ AND (
11143
+ (
11144
+ authority_kind = 'principal'
11145
+ AND authority_service_account_id IS NOT NULL
11146
+ AND authority_session_id IS NULL
11147
+ AND authority_access_token_id IS NULL
11148
+ )
11149
+ OR (
11150
+ authority_kind = 'principal'
11151
+ AND authority_user_id IS NOT NULL
11152
+ AND num_nonnulls(authority_session_id, authority_access_token_id) = 1
11153
+ )
11154
+ OR authority_kind = 'disabled'
11155
+ )
11156
+ )
11157
+ OR (executor_kind = 'kernel' AND authority_kind = 'kernel' AND source_kind <> 'script')
11158
+ OR (
11159
+ executor_kind = 'script'
11160
+ AND source_kind = 'script'
11161
+ AND authority_kind = 'script'
11162
+ AND requested_by_user_id IS NULL
11163
+ AND requested_by_service_account_id IS NULL
11164
+ )
11165
+ );
11166
+ `;
11167
+
11168
+ // src/migrations/104-artifact-pdfs.sql
11169
+ var _104_artifact_pdfs_default = `-- A designed document printed to PDF, kept under its render key: a hash of what it prints, which
11170
+ -- its version names. Versions that print the same share it, so no artifact owns one and deleting
11171
+ -- an artifact leaves them. The first PDF kept under a key stays. When it could not be printed, why
11172
+ -- is kept in its place, until it prints or someone asks for it again.
11173
+ CREATE TABLE artifact_pdfs (
11174
+ project_id TEXT NOT NULL,
11175
+ render_key TEXT NOT NULL CHECK (length(render_key) > 0),
11176
+ file JSONB,
11177
+ pages INTEGER CHECK (pages > 0),
11178
+ failure TEXT,
11179
+ created_at TIMESTAMPTZ NOT NULL,
11180
+ PRIMARY KEY (project_id, render_key),
11181
+ -- A PDF with its pages, or why there is none.
11182
+ CHECK (
11183
+ (failure IS NULL AND file IS NOT NULL AND pages IS NOT NULL)
11184
+ OR (failure IS NOT NULL AND file IS NULL AND pages IS NULL)
11185
+ )
11186
+ );
11187
+ `;
11188
+
11189
+ // src/migrations/105-guest-comment-links.sql
11190
+ var _105_guest_comment_links_default = `-- A guest's comment keeps the shared link they came through, by its grant: whoever opens that link,
11191
+ -- in any session, reads the threads its guests started, and no other. Comments written before take
11192
+ -- it from their session, which keeps its grant.
11193
+ ALTER TABLE artifact_comments ADD COLUMN author_grant_id TEXT;
11194
+
11195
+ UPDATE artifact_comments AS comment
11196
+ SET author_grant_id = session.grant_id
11197
+ FROM share_sessions AS session
11198
+ WHERE comment.author_principal_type = 'guest'
11199
+ AND session.project_id = comment.project_id
11200
+ AND session.id = comment.author_principal_id;
11201
+
11202
+ ALTER TABLE artifact_comments
11203
+ ADD CONSTRAINT artifact_comments_author_grant_check CHECK (
11204
+ (author_principal_type = 'guest') = (author_grant_id IS NOT NULL)
11205
+ AND (author_grant_id IS NULL OR length(author_grant_id) > 0)
11206
+ );
11207
+ `;
11208
+
11209
+ // src/migrations/106-agent-thread-inbox.sql
11210
+ var _106_agent_thread_inbox_default = `-- Mid-run steers and queued follow-up messages held outside \`agent_messages\` until delivered.
11211
+ CREATE TABLE agent_thread_inbox (
11212
+ project_id TEXT NOT NULL,
11213
+ id TEXT NOT NULL CHECK (length(trim(id)) > 0),
11214
+ thread_id TEXT NOT NULL,
11215
+ message_id TEXT NOT NULL CHECK (length(trim(message_id)) > 0),
11216
+ seq INTEGER NOT NULL CHECK (seq > 0),
11217
+ author_principal_type TEXT NOT NULL
11218
+ CHECK (author_principal_type IN ('user', 'serviceAccount', 'system')),
11219
+ author_principal_id TEXT NOT NULL CHECK (length(author_principal_id) > 0),
11220
+ mode TEXT NOT NULL CHECK (mode IN ('steer', 'queue')),
11221
+ parts JSONB NOT NULL,
11222
+ spec JSONB,
11223
+ time_zone TEXT,
11224
+ locale TEXT,
11225
+ immediate BOOLEAN NOT NULL DEFAULT FALSE,
11226
+ -- The request that sent it, whose child execution a turn that starts it runs as.
11227
+ execution_id TEXT,
11228
+ claimed_by_run_id TEXT,
11229
+ claimed_by_token TEXT,
11230
+ claimed_by_step INTEGER,
11231
+ claimed_after_answer BOOLEAN,
11232
+ created_at TIMESTAMPTZ NOT NULL,
11233
+ updated_at TIMESTAMPTZ NOT NULL,
11234
+ PRIMARY KEY (project_id, id),
11235
+ UNIQUE (project_id, message_id),
11236
+ UNIQUE (project_id, thread_id, seq),
11237
+ FOREIGN KEY (project_id, thread_id) REFERENCES agent_threads (project_id, id) ON DELETE CASCADE
11238
+ );
11239
+
11240
+ CREATE INDEX idx_agent_thread_inbox_thread_seq
11241
+ ON agent_thread_inbox (project_id, thread_id, seq);
11242
+
11243
+ CREATE INDEX idx_agent_thread_inbox_claimed_run
11244
+ ON agent_thread_inbox (project_id, claimed_by_run_id)
11245
+ WHERE claimed_by_run_id IS NOT NULL;
11246
+ `;
11247
+
10690
11248
  // src/migrations.ts
10691
11249
  var POSTGRES_STORAGE_ADAPTER_ID = "SixbPostgresStorage";
10692
11250
  function pgSql(id, sqlText) {
@@ -10955,7 +11513,11 @@ var postgresStorageMigrations = defineMigrations({
10955
11513
  pgSql("099-object-artifact-refs", _099_object_artifact_refs_default),
10956
11514
  pgSql("100-shared-link-guests", _100_shared_link_guests_default),
10957
11515
  pgSql("101-connector-connection-owners", _101_connector_connection_owners_default),
10958
- pgSql("102-user-suspension-source", _102_user_suspension_source_default)
11516
+ pgSql("102-user-suspension-source", _102_user_suspension_source_default),
11517
+ pgSql("103-script-executions", _103_script_executions_default),
11518
+ pgSql("104-artifact-pdfs", _104_artifact_pdfs_default),
11519
+ pgSql("105-guest-comment-links", _105_guest_comment_links_default),
11520
+ pgSql("106-agent-thread-inbox", _106_agent_thread_inbox_default)
10959
11521
  ]
10960
11522
  });
10961
11523
 
@@ -16127,6 +16689,38 @@ function revision(kind) {
16127
16689
  const key = "identities.identity_key";
16128
16690
  return kind === "object" ? `${objectRevision(`(${key}::jsonb->>0)`, `(${key}::jsonb->>1)`)}::text` : `${linkRevision(key)}::text`;
16129
16691
  }
16692
+ async function planCreatedObjects(sql, input, versionId, objectTypeId) {
16693
+ const rootKey = jsonTupleExpression([
16694
+ `'"object"'`,
16695
+ "to_jsonb(overrides.object_type_id)::text",
16696
+ "to_jsonb(overrides.primary_id)::text"
16697
+ ]);
16698
+ const planned = await sql`
16699
+ WITH keyed AS (
16700
+ SELECT ${sql.unsafe(columnKeyExpression(["object_type_id", "primary_id"]))} AS identity_key
16701
+ FROM ontology_object_overrides AS overrides
16702
+ WHERE overrides.project_id = ${input.projectId} AND overrides.object_type_id = ${objectTypeId}
16703
+ AND overrides.value->>'kind' = 'create'
16704
+ AND NOT EXISTS (
16705
+ SELECT 1 FROM ontology_source_roots AS live
16706
+ JOIN ontology_sources AS versions ON versions.version_id = live.version_id
16707
+ WHERE live.project_id = overrides.project_id
16708
+ AND live.root_key = ${sql.unsafe(rootKey)}
16709
+ AND live.retired_at IS NULL AND NOT live.deleted
16710
+ AND versions.source_id = ${input.source.projectionId}
16711
+ AND versions.status IN ${sql.unsafe(PUBLISHED)}
16712
+ )
16713
+ )
16714
+ INSERT INTO ${sql(IDENTITIES)} (
16715
+ version_id, entity_kind, identity_key, sort_key, diff_required, expand_at, source_key,
16716
+ target_key
16717
+ )
16718
+ SELECT ${versionId}, 'object', identity_key, ${sql.unsafe(SORT_KEY)}, TRUE, NULL, NULL, NULL
16719
+ FROM keyed
16720
+ ON CONFLICT DO NOTHING
16721
+ `;
16722
+ return planned.count;
16723
+ }
16130
16724
 
16131
16725
  class PgOntologyReplacementPlanStorage {
16132
16726
  sql;
@@ -16197,7 +16791,8 @@ class PgOntologyReplacementPlanStorage {
16197
16791
  target_key
16198
16792
  FROM keyed
16199
16793
  `;
16200
- if (opened.count >= ANALYZE_ROWS)
16794
+ const created = input.createdObjects ? await planCreatedObjects(sql, input, candidate.version_id, input.createdObjects.objectTypeId) : 0;
16795
+ if (opened.count + created >= ANALYZE_ROWS)
16201
16796
  await analyzePlans(sql);
16202
16797
  return { committedAt: commit.committedAt };
16203
16798
  });
@@ -21982,6 +22577,7 @@ import {
21982
22577
  parseArtifactBoardPreviewRow,
21983
22578
  parseArtifactCommentRow,
21984
22579
  parseArtifactFrameGrantRow,
22580
+ parseArtifactPdfRow,
21985
22581
  parseArtifactRestorePointRow,
21986
22582
  parseArtifactRow,
21987
22583
  parseArtifactStateRow,
@@ -22018,7 +22614,8 @@ var FRAME_GRANT_COLUMNS = `
22018
22614
  var COMMENT_COLUMNS = `
22019
22615
  project_id AS "projectId", artifact_id AS "artifactId", id, parent_id AS "parentId", anchor,
22020
22616
  body, author_principal_type AS "authorPrincipalType", author_principal_id AS "authorPrincipalId",
22021
- author_name AS "authorName", created_at AS "createdAt", resolved_at AS "resolvedAt",
22617
+ author_name AS "authorName", author_grant_id AS "authorGrantId",
22618
+ created_at AS "createdAt", resolved_at AS "resolvedAt",
22022
22619
  resolved_by_principal_type AS "resolvedByPrincipalType",
22023
22620
  resolved_by_principal_id AS "resolvedByPrincipalId",
22024
22621
  origin_thread_id AS "originThreadId", origin_run_id AS "originRunId"
@@ -22028,6 +22625,10 @@ var BOARD_PREVIEW_COLUMNS = `
22028
22625
  project_id AS "projectId", render_key AS "renderKey", theme, size, file,
22029
22626
  created_at AS "createdAt"
22030
22627
  `;
22628
+ var PDF_COLUMNS = `
22629
+ project_id AS "projectId", render_key AS "renderKey", file, pages, failure,
22630
+ created_at AS "createdAt"
22631
+ `;
22031
22632
 
22032
22633
  class PgArtifactStorage {
22033
22634
  sql;
@@ -22545,6 +23146,35 @@ class PgArtifactStorage {
22545
23146
  }
22546
23147
  });
22547
23148
  }
23149
+ async getPdf(input) {
23150
+ const [row] = await this.sql`
23151
+ SELECT ${this.sql.unsafe(PDF_COLUMNS)} FROM artifact_pdfs
23152
+ WHERE project_id = ${input.projectId} AND render_key = ${input.renderKey}
23153
+ `;
23154
+ return row ? parseArtifactPdfRow(row) : null;
23155
+ }
23156
+ async putPdf(input) {
23157
+ const printed = "failure" in input ? null : input;
23158
+ await this.sql`
23159
+ INSERT INTO artifact_pdfs (project_id, render_key, file, pages, failure, created_at)
23160
+ VALUES (
23161
+ ${input.projectId}, ${input.renderKey},
23162
+ ${printed ? JSON.stringify(printed.file) : null}::text::jsonb, ${printed?.pages ?? null},
23163
+ ${"failure" in input ? input.failure : null}, ${input.createdAt}
23164
+ )
23165
+ ON CONFLICT (project_id, render_key) DO UPDATE SET
23166
+ file = excluded.file, pages = excluded.pages, failure = NULL,
23167
+ created_at = excluded.created_at
23168
+ WHERE artifact_pdfs.failure IS NOT NULL AND excluded.failure IS NULL
23169
+ `;
23170
+ }
23171
+ async clearPdfFailure(input) {
23172
+ await this.sql`
23173
+ DELETE FROM artifact_pdfs
23174
+ WHERE project_id = ${input.projectId} AND render_key = ${input.renderKey}
23175
+ AND failure IS NOT NULL
23176
+ `;
23177
+ }
22548
23178
  async createComment(input) {
22549
23179
  return runPgTransaction(this.sql, async (tx) => {
22550
23180
  if (!await lockArtifact(tx, input.projectId, input.artifactId)) {
@@ -22571,15 +23201,17 @@ class PgArtifactStorage {
22571
23201
  if (input.author.type === "guest" && (counted?.guests ?? 0) >= ARTIFACT_COMMENT_LIMITS.maxGuestComments) {
22572
23202
  throw artifactStorageErrors.guestCommentsFull(input.artifactId);
22573
23203
  }
23204
+ const guest = input.author.type === "guest" ? input.author : undefined;
22574
23205
  const [row] = await tx`
22575
23206
  INSERT INTO artifact_comments (
22576
23207
  project_id, artifact_id, id, parent_id, anchor, body, author_principal_type,
22577
- author_principal_id, author_name, created_at, origin_thread_id, origin_run_id
23208
+ author_principal_id, author_name, author_grant_id, created_at, origin_thread_id,
23209
+ origin_run_id
22578
23210
  ) VALUES (
22579
23211
  ${input.projectId}, ${input.artifactId}, ${input.id}, ${input.parentId ?? null},
22580
23212
  ${JSON.stringify(commentAnchor(input.anchor))}::text::jsonb, ${input.body},
22581
23213
  ${input.author.type}, ${input.author.id},
22582
- ${input.author.type === "guest" ? input.author.name : null}, ${input.createdAt},
23214
+ ${guest?.name ?? null}, ${guest?.grantId ?? null}, ${input.createdAt},
22583
23215
  ${input.origin?.threadId ?? null}, ${input.origin?.runId ?? null}
22584
23216
  )
22585
23217
  RETURNING ${tx.unsafe(COMMENT_COLUMNS)}
@@ -26281,8 +26913,8 @@ function rowToWorkflowAgentNodeRunRecord(row) {
26281
26913
  prompt: row.prompt,
26282
26914
  ...row.model_id ? { modelId: row.model_id } : {},
26283
26915
  ...row.finish_reason ? { finishReason: row.finish_reason } : {},
26284
- ...row.trace ? { trace: parseJson2(row.trace) } : {},
26285
- ...row.diagnostics ? { diagnostics: parseJson2(row.diagnostics) } : {},
26916
+ ...row.trace ? { trace: parseJson3(row.trace) } : {},
26917
+ ...row.diagnostics ? { diagnostics: parseJson3(row.diagnostics) } : {},
26286
26918
  ...row.error ? { error: parseSixbFailure7(row.error, AGENT_RUN_FAILURE_CODES3) } : {},
26287
26919
  attempt: Number(row.attempt),
26288
26920
  ...row.execution_token && row.execution_queue_lease_expires_at ? {
@@ -26296,7 +26928,7 @@ function rowToWorkflowAgentNodeRunRecord(row) {
26296
26928
  ...row.completed_at ? { completedAt: new Date(row.completed_at) } : {}
26297
26929
  };
26298
26930
  }
26299
- function parseJson2(value) {
26931
+ function parseJson3(value) {
26300
26932
  return typeof value === "string" ? JSON.parse(value) : value;
26301
26933
  }
26302
26934
  function assertWorkflowRunExecutionOwnership(row, token) {
@@ -26864,4 +27496,4 @@ export {
26864
27496
  migratePostgresStorage
26865
27497
  };
26866
27498
 
26867
- //# debugId=3787CB9C13986BA564756E2164756E21
27499
+ //# debugId=09F6338290C837D364756E2164756E21