@sixb/pg 0.2.4 → 0.2.6
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/agents/agent-storage.d.ts +4 -0
- package/dist/agents/agent-storage.d.ts.map +1 -1
- package/dist/agents/approvals.d.ts +2 -1
- package/dist/agents/approvals.d.ts.map +1 -1
- package/dist/agents/checkpoints.d.ts +2 -1
- package/dist/agents/checkpoints.d.ts.map +1 -1
- package/dist/agents/inbox.d.ts +23 -0
- package/dist/agents/inbox.d.ts.map +1 -0
- package/dist/agents/messages.d.ts +2 -1
- package/dist/agents/messages.d.ts.map +1 -1
- package/dist/agents/reads.d.ts +9 -0
- package/dist/agents/reads.d.ts.map +1 -0
- package/dist/agents/runs.d.ts +2 -1
- package/dist/agents/runs.d.ts.map +1 -1
- package/dist/agents/threads.d.ts.map +1 -1
- package/dist/index.js +1212 -87
- package/dist/index.js.map +17 -15
- package/dist/latest-run-query.d.ts +3 -1
- package/dist/latest-run-query.d.ts.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/ontology-storage/replacement-plans.d.ts.map +1 -1
- package/dist/pg-ai-cost-storage.d.ts.map +1 -1
- package/dist/pg-artifact-storage.d.ts +4 -1
- package/dist/pg-artifact-storage.d.ts.map +1 -1
- package/dist/pg-sync-run-storage.d.ts +2 -1
- package/dist/pg-sync-run-storage.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/agents/agent-storage.ts +6 -0
- package/src/agents/approvals.ts +44 -0
- package/src/agents/checkpoints.ts +26 -0
- package/src/agents/inbox.ts +421 -0
- package/src/agents/messages.ts +81 -2
- package/src/agents/reads.ts +160 -0
- package/src/agents/runs.ts +25 -0
- package/src/agents/threads.ts +95 -11
- package/src/latest-run-query.ts +8 -1
- package/src/migrations/103-script-executions.sql +145 -0
- package/src/migrations/104-artifact-pdfs.sql +18 -0
- package/src/migrations/105-guest-comment-links.sql +17 -0
- package/src/migrations/106-agent-thread-inbox.sql +36 -0
- package/src/migrations/107-agent-inbox-edits.sql +3 -0
- package/src/migrations/108-agent-thread-reads.sql +73 -0
- package/src/migrations/109-sync-run-connections.sql +6 -0
- package/src/migrations.ts +14 -0
- package/src/ontology-storage/replacement-plans.ts +51 -1
- package/src/pg-ai-cost-storage.ts +35 -20
- package/src/pg-artifact-storage.ts +67 -9
- package/src/pg-sync-run-storage.ts +69 -0
package/dist/index.js
CHANGED
|
@@ -513,6 +513,40 @@ class PgAgentApprovalStore {
|
|
|
513
513
|
const stopped = rows.filter((row) => row.newly_stopped).length;
|
|
514
514
|
return { cancelled: cancelled.sort(compareApprovals), stopped };
|
|
515
515
|
}
|
|
516
|
+
async rewind(input) {
|
|
517
|
+
const runIds = [...new Set(input.runIds)];
|
|
518
|
+
const clearedIds = [...new Set(input.clearedMessageIds ?? [])];
|
|
519
|
+
const cancelledAt = new Date(input.cancelledAt ?? new Date);
|
|
520
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
521
|
+
if (clearedIds.length > 0) {
|
|
522
|
+
await tx`
|
|
523
|
+
UPDATE agent_approvals
|
|
524
|
+
SET reported_in_message_id = NULL
|
|
525
|
+
WHERE project_id = ${input.projectId}
|
|
526
|
+
AND thread_id = ${input.threadId}
|
|
527
|
+
AND reported_in_message_id = ANY(${tx.array(clearedIds)}::text[])
|
|
528
|
+
`;
|
|
529
|
+
}
|
|
530
|
+
if (runIds.length === 0)
|
|
531
|
+
return { cancelled: [], deleted: 0 };
|
|
532
|
+
const removed = await tx`
|
|
533
|
+
DELETE FROM agent_approvals
|
|
534
|
+
WHERE project_id = ${input.projectId}
|
|
535
|
+
AND thread_id = ${input.threadId}
|
|
536
|
+
AND run_id = ANY(${tx.array(runIds)}::text[])
|
|
537
|
+
RETURNING *
|
|
538
|
+
`;
|
|
539
|
+
const cancelled = removed.filter((row) => row.status === "pending").map((row) => {
|
|
540
|
+
const parsed = rowToApproval(row);
|
|
541
|
+
return {
|
|
542
|
+
...parsed,
|
|
543
|
+
status: "cancelled",
|
|
544
|
+
turnStoppedAt: parsed.turnStoppedAt ?? cancelledAt
|
|
545
|
+
};
|
|
546
|
+
}).sort(compareApprovals);
|
|
547
|
+
return { cancelled, deleted: removed.length };
|
|
548
|
+
});
|
|
549
|
+
}
|
|
516
550
|
async holdsRun(input) {
|
|
517
551
|
return pgHoldsRun(this.sql, input.projectId, input.runId);
|
|
518
552
|
}
|
|
@@ -674,7 +708,8 @@ import {
|
|
|
674
708
|
assertAgentContextCheckpointAnchors,
|
|
675
709
|
assertAgentContextCheckpointAuthority,
|
|
676
710
|
assertAgentContextCheckpointReplayState,
|
|
677
|
-
assertCreateAgentContextCheckpointInput
|
|
711
|
+
assertCreateAgentContextCheckpointInput,
|
|
712
|
+
assertDeleteAgentContextCheckpointsAfterSeqInput
|
|
678
713
|
} from "@sixb/core/internal/agent-run-storage-provider";
|
|
679
714
|
import {
|
|
680
715
|
AgentStorageError as AgentStorageError2
|
|
@@ -814,6 +849,28 @@ class PgAgentContextCheckpointStore {
|
|
|
814
849
|
`;
|
|
815
850
|
return row ? rowToContextCheckpointRecord(row) : null;
|
|
816
851
|
}
|
|
852
|
+
async deleteAfterSeq(input) {
|
|
853
|
+
assertDeleteAgentContextCheckpointsAfterSeqInput(input, "SixbPg");
|
|
854
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
855
|
+
const rows = await tx`
|
|
856
|
+
SELECT id FROM agent_context_checkpoints
|
|
857
|
+
WHERE project_id = ${input.projectId}
|
|
858
|
+
AND thread_id = ${input.threadId}
|
|
859
|
+
AND observed_head_seq > ${input.afterSeq}
|
|
860
|
+
ORDER BY summarized_through_seq DESC, created_at DESC, id DESC
|
|
861
|
+
FOR UPDATE
|
|
862
|
+
`;
|
|
863
|
+
if (rows.length === 0)
|
|
864
|
+
return 0;
|
|
865
|
+
for (const row of rows) {
|
|
866
|
+
await tx`
|
|
867
|
+
DELETE FROM agent_context_checkpoints
|
|
868
|
+
WHERE project_id = ${input.projectId} AND id = ${row.id}
|
|
869
|
+
`;
|
|
870
|
+
}
|
|
871
|
+
return rows.length;
|
|
872
|
+
});
|
|
873
|
+
}
|
|
817
874
|
async getByRunIds(input) {
|
|
818
875
|
const runIds = [...new Set(input.runIds)];
|
|
819
876
|
if (runIds.length === 0)
|
|
@@ -937,6 +994,336 @@ function rowToSession(row) {
|
|
|
937
994
|
};
|
|
938
995
|
}
|
|
939
996
|
|
|
997
|
+
// src/agents/inbox.ts
|
|
998
|
+
import {
|
|
999
|
+
assertEnqueueAgentInboxItemInput,
|
|
1000
|
+
assertInboxRunOwnership,
|
|
1001
|
+
assertInboxThreadAcceptsItem,
|
|
1002
|
+
assertTakeAgentInboxSteersInput,
|
|
1003
|
+
assertUpdateAgentInboxItemInput,
|
|
1004
|
+
newAgentInboxItemRecord,
|
|
1005
|
+
updatedAgentInboxItemRecord
|
|
1006
|
+
} from "@sixb/core/internal/agent-run-storage-provider";
|
|
1007
|
+
import {
|
|
1008
|
+
AgentStorageError as AgentStorageError3
|
|
1009
|
+
} from "@sixb/core/storage";
|
|
1010
|
+
class PgAgentInboxStore {
|
|
1011
|
+
sql;
|
|
1012
|
+
constructor(sql) {
|
|
1013
|
+
this.sql = sql;
|
|
1014
|
+
}
|
|
1015
|
+
async enqueue(input) {
|
|
1016
|
+
assertEnqueueAgentInboxItemInput(input, "SixbPg");
|
|
1017
|
+
try {
|
|
1018
|
+
return await runPgTransaction(this.sql, async (tx) => {
|
|
1019
|
+
const [existing] = await tx`
|
|
1020
|
+
SELECT * FROM agent_thread_inbox
|
|
1021
|
+
WHERE project_id = ${input.projectId} AND id = ${input.id}
|
|
1022
|
+
FOR UPDATE
|
|
1023
|
+
`;
|
|
1024
|
+
if (existing) {
|
|
1025
|
+
if (existing.thread_id === input.threadId) {
|
|
1026
|
+
return { item: rowToInboxItem(existing), created: false };
|
|
1027
|
+
}
|
|
1028
|
+
throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent inbox item '${input.id}' already exists on another thread in project '${input.projectId}'.`);
|
|
1029
|
+
}
|
|
1030
|
+
const [thread] = await tx`
|
|
1031
|
+
SELECT id, kind, status, active_run_id FROM agent_threads
|
|
1032
|
+
WHERE project_id = ${input.projectId} AND id = ${input.threadId}
|
|
1033
|
+
FOR UPDATE
|
|
1034
|
+
`;
|
|
1035
|
+
const [counts] = await tx`
|
|
1036
|
+
SELECT COUNT(*) AS count, COALESCE(MAX(seq), 0) AS max_seq
|
|
1037
|
+
FROM agent_thread_inbox
|
|
1038
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1039
|
+
`;
|
|
1040
|
+
assertInboxThreadAcceptsItem(thread ?? null, input.threadId, input.projectId, Number(counts?.count ?? 0), "SixbPg");
|
|
1041
|
+
const [existingMessage] = await tx`
|
|
1042
|
+
SELECT id FROM agent_messages
|
|
1043
|
+
WHERE project_id = ${input.projectId} AND id = ${input.messageId}
|
|
1044
|
+
`;
|
|
1045
|
+
if (existingMessage) {
|
|
1046
|
+
throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent message '${input.messageId}' already exists for project '${input.projectId}'.`);
|
|
1047
|
+
}
|
|
1048
|
+
const record = newAgentInboxItemRecord(input, Number(counts?.max_seq ?? 0) + 1);
|
|
1049
|
+
const [inserted] = await tx`
|
|
1050
|
+
INSERT INTO agent_thread_inbox (
|
|
1051
|
+
project_id, id, thread_id, message_id, seq,
|
|
1052
|
+
author_principal_type, author_principal_id, mode, parts, spec,
|
|
1053
|
+
time_zone, locale, immediate, replaces_message_id, execution_id, created_at, updated_at
|
|
1054
|
+
) VALUES (
|
|
1055
|
+
${record.projectId},
|
|
1056
|
+
${record.id},
|
|
1057
|
+
${record.threadId},
|
|
1058
|
+
${record.messageId},
|
|
1059
|
+
${record.seq},
|
|
1060
|
+
${record.authorPrincipal.type},
|
|
1061
|
+
${record.authorPrincipal.id},
|
|
1062
|
+
${record.mode},
|
|
1063
|
+
${JSON.stringify(record.parts)}::text::jsonb,
|
|
1064
|
+
${record.spec === undefined ? null : JSON.stringify(record.spec)}::text::jsonb,
|
|
1065
|
+
${record.timeZone ?? null},
|
|
1066
|
+
${record.locale ?? null},
|
|
1067
|
+
${Boolean(record.immediate)},
|
|
1068
|
+
${record.replacesMessageId ?? null},
|
|
1069
|
+
${record.executionId ?? null},
|
|
1070
|
+
${record.createdAt},
|
|
1071
|
+
${record.updatedAt}
|
|
1072
|
+
)
|
|
1073
|
+
RETURNING *
|
|
1074
|
+
`;
|
|
1075
|
+
return { item: rowToInboxItem(inserted), created: true };
|
|
1076
|
+
});
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
if (isUniqueViolation(error)) {
|
|
1079
|
+
throw new AgentStorageError3("duplicate_id", `[SixbPg] Agent inbox item or message id already exists for project '${input.projectId}'.`);
|
|
1080
|
+
}
|
|
1081
|
+
throw error;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
async getById(params) {
|
|
1085
|
+
const [row] = await this.sql`
|
|
1086
|
+
SELECT * FROM agent_thread_inbox
|
|
1087
|
+
WHERE project_id = ${params.projectId} AND id = ${params.id}
|
|
1088
|
+
`;
|
|
1089
|
+
return row ? rowToInboxItem(row) : null;
|
|
1090
|
+
}
|
|
1091
|
+
async list(input) {
|
|
1092
|
+
const includeClaimed = input.includeClaimed ?? true;
|
|
1093
|
+
const rows = includeClaimed ? await this.sql`
|
|
1094
|
+
SELECT * FROM agent_thread_inbox
|
|
1095
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1096
|
+
ORDER BY seq ASC
|
|
1097
|
+
` : await this.sql`
|
|
1098
|
+
SELECT * FROM agent_thread_inbox
|
|
1099
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1100
|
+
AND claimed_by_run_id IS NULL
|
|
1101
|
+
ORDER BY seq ASC
|
|
1102
|
+
`;
|
|
1103
|
+
return rows.map(rowToInboxItem);
|
|
1104
|
+
}
|
|
1105
|
+
async listWaitingThreads(input) {
|
|
1106
|
+
const rows = await this.sql`
|
|
1107
|
+
SELECT DISTINCT inbox.thread_id
|
|
1108
|
+
FROM agent_thread_inbox inbox
|
|
1109
|
+
JOIN agent_threads thread
|
|
1110
|
+
ON thread.project_id = inbox.project_id AND thread.id = inbox.thread_id
|
|
1111
|
+
WHERE inbox.project_id = ${input.projectId}
|
|
1112
|
+
AND inbox.created_at < ${input.createdBefore}
|
|
1113
|
+
AND inbox.thread_id > ${input.afterThreadId ?? ""}
|
|
1114
|
+
AND thread.active_run_id IS NULL
|
|
1115
|
+
ORDER BY inbox.thread_id ASC
|
|
1116
|
+
LIMIT ${input.limit}
|
|
1117
|
+
`;
|
|
1118
|
+
return rows.map((row) => row.thread_id);
|
|
1119
|
+
}
|
|
1120
|
+
async update(input) {
|
|
1121
|
+
assertUpdateAgentInboxItemInput(input, "SixbPg");
|
|
1122
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1123
|
+
const [current] = await tx`
|
|
1124
|
+
SELECT * FROM agent_thread_inbox
|
|
1125
|
+
WHERE project_id = ${input.projectId} AND id = ${input.id}
|
|
1126
|
+
FOR UPDATE
|
|
1127
|
+
`;
|
|
1128
|
+
if (!current || current.thread_id !== input.threadId)
|
|
1129
|
+
return null;
|
|
1130
|
+
const next = updatedAgentInboxItemRecord(rowToInboxItem(current), input);
|
|
1131
|
+
const [updated] = await tx`
|
|
1132
|
+
UPDATE agent_thread_inbox
|
|
1133
|
+
SET
|
|
1134
|
+
mode = ${next.mode},
|
|
1135
|
+
parts = ${JSON.stringify(next.parts)}::text::jsonb,
|
|
1136
|
+
spec = ${next.spec === undefined ? null : JSON.stringify(next.spec)}::text::jsonb,
|
|
1137
|
+
immediate = ${Boolean(next.immediate)},
|
|
1138
|
+
updated_at = ${next.updatedAt}
|
|
1139
|
+
WHERE project_id = ${next.projectId} AND id = ${next.id}
|
|
1140
|
+
RETURNING *
|
|
1141
|
+
`;
|
|
1142
|
+
return updated ? rowToInboxItem(updated) : null;
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
async remove(input) {
|
|
1146
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1147
|
+
const [current] = await tx`
|
|
1148
|
+
SELECT * FROM agent_thread_inbox
|
|
1149
|
+
WHERE project_id = ${input.projectId} AND id = ${input.id}
|
|
1150
|
+
FOR UPDATE
|
|
1151
|
+
`;
|
|
1152
|
+
if (!current || current.thread_id !== input.threadId)
|
|
1153
|
+
return null;
|
|
1154
|
+
if (current.claimed_by_run_id !== null) {
|
|
1155
|
+
throw new AgentStorageError3("invalid_state", `[SixbPg] Agent inbox item '${current.id}' was already claimed by run '${current.claimed_by_run_id}'.`);
|
|
1156
|
+
}
|
|
1157
|
+
await tx`
|
|
1158
|
+
DELETE FROM agent_thread_inbox
|
|
1159
|
+
WHERE project_id = ${input.projectId} AND id = ${input.id}
|
|
1160
|
+
`;
|
|
1161
|
+
return rowToInboxItem(current);
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
async takeSteers(input) {
|
|
1165
|
+
assertTakeAgentInboxSteersInput(input, "SixbPg");
|
|
1166
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1167
|
+
const run = await lockRun2(tx, input.projectId, input.runId);
|
|
1168
|
+
assertInboxRunOwnership(run, input, "SixbPg");
|
|
1169
|
+
const updatedAt = new Date;
|
|
1170
|
+
const rows = await tx`
|
|
1171
|
+
UPDATE agent_thread_inbox
|
|
1172
|
+
SET
|
|
1173
|
+
claimed_by_run_id = ${input.runId},
|
|
1174
|
+
claimed_by_token = ${input.executionToken},
|
|
1175
|
+
claimed_by_step = ${input.stepIndex},
|
|
1176
|
+
claimed_after_answer = ${input.afterAnswer ? true : null}::boolean,
|
|
1177
|
+
updated_at = ${updatedAt}
|
|
1178
|
+
WHERE project_id = ${input.projectId}
|
|
1179
|
+
AND thread_id = ${input.threadId}
|
|
1180
|
+
AND (
|
|
1181
|
+
claimed_by_run_id IS NULL
|
|
1182
|
+
OR claimed_by_run_id <> ${input.runId}
|
|
1183
|
+
OR claimed_by_token <> ${input.executionToken}
|
|
1184
|
+
)
|
|
1185
|
+
AND mode = 'steer'
|
|
1186
|
+
AND immediate = FALSE
|
|
1187
|
+
AND author_principal_type = ${input.authorPrincipal.type}
|
|
1188
|
+
AND author_principal_id = ${input.authorPrincipal.id}
|
|
1189
|
+
RETURNING *
|
|
1190
|
+
`;
|
|
1191
|
+
return rows.map(rowToInboxItem).sort((left, right) => left.seq - right.seq);
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
async consumeClaimed(input) {
|
|
1195
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1196
|
+
const run = await lockRun2(tx, input.projectId, input.runId);
|
|
1197
|
+
assertInboxRunOwnership(run, input, "SixbPg");
|
|
1198
|
+
const claimed = await tx`
|
|
1199
|
+
SELECT * FROM agent_thread_inbox
|
|
1200
|
+
WHERE project_id = ${input.projectId}
|
|
1201
|
+
AND thread_id = ${input.threadId}
|
|
1202
|
+
AND claimed_by_run_id = ${input.runId}
|
|
1203
|
+
AND claimed_by_token = ${input.executionToken}
|
|
1204
|
+
ORDER BY seq ASC
|
|
1205
|
+
FOR UPDATE
|
|
1206
|
+
`;
|
|
1207
|
+
if (claimed.length === 0)
|
|
1208
|
+
return [];
|
|
1209
|
+
const persisted = new Set(input.messageIds);
|
|
1210
|
+
const updatedAt = new Date;
|
|
1211
|
+
const consumed = [];
|
|
1212
|
+
for (const row of claimed) {
|
|
1213
|
+
if (persisted.has(row.message_id)) {
|
|
1214
|
+
await tx`
|
|
1215
|
+
DELETE FROM agent_thread_inbox
|
|
1216
|
+
WHERE project_id = ${row.project_id} AND id = ${row.id}
|
|
1217
|
+
`;
|
|
1218
|
+
consumed.push(rowToInboxItem(row));
|
|
1219
|
+
} else {
|
|
1220
|
+
await tx`
|
|
1221
|
+
UPDATE agent_thread_inbox
|
|
1222
|
+
SET
|
|
1223
|
+
claimed_by_run_id = NULL,
|
|
1224
|
+
claimed_by_token = NULL,
|
|
1225
|
+
claimed_by_step = NULL,
|
|
1226
|
+
claimed_after_answer = NULL,
|
|
1227
|
+
updated_at = ${updatedAt}
|
|
1228
|
+
WHERE project_id = ${row.project_id} AND id = ${row.id}
|
|
1229
|
+
`;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
return consumed;
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
async releaseClaimed(input) {
|
|
1236
|
+
const updatedAt = new Date;
|
|
1237
|
+
const rows = await this.sql`
|
|
1238
|
+
UPDATE agent_thread_inbox
|
|
1239
|
+
SET
|
|
1240
|
+
claimed_by_run_id = NULL,
|
|
1241
|
+
claimed_by_token = NULL,
|
|
1242
|
+
claimed_by_step = NULL,
|
|
1243
|
+
claimed_after_answer = NULL,
|
|
1244
|
+
updated_at = ${updatedAt}
|
|
1245
|
+
WHERE project_id = ${input.projectId} AND claimed_by_run_id = ${input.runId}
|
|
1246
|
+
RETURNING id
|
|
1247
|
+
`;
|
|
1248
|
+
return rows.length;
|
|
1249
|
+
}
|
|
1250
|
+
async takeNextQueued(input) {
|
|
1251
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1252
|
+
const [thread] = await tx`
|
|
1253
|
+
SELECT id, kind, status, active_run_id FROM agent_threads
|
|
1254
|
+
WHERE project_id = ${input.projectId} AND id = ${input.threadId}
|
|
1255
|
+
FOR UPDATE
|
|
1256
|
+
`;
|
|
1257
|
+
if (!thread || thread.status !== "active" || thread.active_run_id !== null)
|
|
1258
|
+
return null;
|
|
1259
|
+
const [winner] = await tx`
|
|
1260
|
+
SELECT * FROM agent_thread_inbox
|
|
1261
|
+
WHERE project_id = ${input.projectId}
|
|
1262
|
+
AND thread_id = ${input.threadId}
|
|
1263
|
+
AND claimed_by_run_id IS NULL
|
|
1264
|
+
AND (${!input.onlyImmediate}::boolean OR immediate = TRUE)
|
|
1265
|
+
AND (
|
|
1266
|
+
${input.authorPrincipal?.id ?? null}::text IS NULL
|
|
1267
|
+
OR (author_principal_type = ${input.authorPrincipal?.type ?? null}
|
|
1268
|
+
AND author_principal_id = ${input.authorPrincipal?.id ?? null})
|
|
1269
|
+
)
|
|
1270
|
+
ORDER BY
|
|
1271
|
+
CASE WHEN immediate = TRUE THEN 0 WHEN mode = 'steer' THEN 1 ELSE 2 END ASC,
|
|
1272
|
+
seq ASC
|
|
1273
|
+
LIMIT 1
|
|
1274
|
+
FOR UPDATE
|
|
1275
|
+
`;
|
|
1276
|
+
if (!winner)
|
|
1277
|
+
return null;
|
|
1278
|
+
await tx`
|
|
1279
|
+
DELETE FROM agent_thread_inbox
|
|
1280
|
+
WHERE project_id = ${winner.project_id} AND id = ${winner.id}
|
|
1281
|
+
`;
|
|
1282
|
+
return rowToInboxItem(winner);
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
async function lockRun2(tx, projectId, id) {
|
|
1287
|
+
const [row] = await tx`
|
|
1288
|
+
SELECT * FROM agent_runs WHERE project_id = ${projectId} AND id = ${id} FOR UPDATE
|
|
1289
|
+
`;
|
|
1290
|
+
return row ? rowToRunRecord(row) : null;
|
|
1291
|
+
}
|
|
1292
|
+
function parseJson2(value) {
|
|
1293
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
1294
|
+
}
|
|
1295
|
+
function rowToInboxItem(row) {
|
|
1296
|
+
const spec = row.spec === null ? undefined : parseJson2(row.spec);
|
|
1297
|
+
const claimedBy = row.claimed_by_run_id !== null && row.claimed_by_token !== null && row.claimed_by_step !== null ? {
|
|
1298
|
+
runId: row.claimed_by_run_id,
|
|
1299
|
+
executionToken: row.claimed_by_token,
|
|
1300
|
+
stepIndex: Number(row.claimed_by_step),
|
|
1301
|
+
...row.claimed_after_answer === true ? { afterAnswer: true } : {}
|
|
1302
|
+
} : undefined;
|
|
1303
|
+
return {
|
|
1304
|
+
id: row.id,
|
|
1305
|
+
projectId: row.project_id,
|
|
1306
|
+
threadId: row.thread_id,
|
|
1307
|
+
messageId: row.message_id,
|
|
1308
|
+
seq: Number(row.seq),
|
|
1309
|
+
authorPrincipal: {
|
|
1310
|
+
type: row.author_principal_type,
|
|
1311
|
+
id: row.author_principal_id
|
|
1312
|
+
},
|
|
1313
|
+
mode: row.mode,
|
|
1314
|
+
parts: parseJson2(row.parts),
|
|
1315
|
+
...spec ? { spec } : {},
|
|
1316
|
+
...row.time_zone ? { timeZone: row.time_zone } : {},
|
|
1317
|
+
...row.locale ? { locale: row.locale } : {},
|
|
1318
|
+
...row.immediate ? { immediate: true } : {},
|
|
1319
|
+
...row.replaces_message_id ? { replacesMessageId: row.replaces_message_id } : {},
|
|
1320
|
+
...row.execution_id ? { executionId: row.execution_id } : {},
|
|
1321
|
+
...claimedBy ? { claimedBy } : {},
|
|
1322
|
+
createdAt: new Date(row.created_at),
|
|
1323
|
+
updatedAt: new Date(row.updated_at)
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
|
|
940
1327
|
// src/agents/memory.ts
|
|
941
1328
|
import {
|
|
942
1329
|
agentMemoryConflicts,
|
|
@@ -1066,10 +1453,13 @@ class PgAgentMemoryStore {
|
|
|
1066
1453
|
}
|
|
1067
1454
|
|
|
1068
1455
|
// src/agents/messages.ts
|
|
1069
|
-
import {
|
|
1456
|
+
import {
|
|
1457
|
+
assertDeleteAgentMessagesFromSeqInput,
|
|
1458
|
+
countsAsThreadMessage
|
|
1459
|
+
} from "@sixb/core/internal/agent-run-storage-provider";
|
|
1070
1460
|
import { AGENT_MESSAGE_CONTENT_VERSION } from "@sixb/core/internal/agents";
|
|
1071
1461
|
import {
|
|
1072
|
-
AgentStorageError as
|
|
1462
|
+
AgentStorageError as AgentStorageError4
|
|
1073
1463
|
} from "@sixb/core/storage";
|
|
1074
1464
|
class PgAgentMessageStore {
|
|
1075
1465
|
sql;
|
|
@@ -1087,7 +1477,7 @@ class PgAgentMessageStore {
|
|
|
1087
1477
|
FOR UPDATE
|
|
1088
1478
|
`;
|
|
1089
1479
|
if (!run) {
|
|
1090
|
-
throw new
|
|
1480
|
+
throw new AgentStorageError4("run_not_found", `[SixbPg] Agent run '${input.runId}' not found for project '${input.projectId}'.`);
|
|
1091
1481
|
}
|
|
1092
1482
|
}
|
|
1093
1483
|
const [thread] = await tx`
|
|
@@ -1096,7 +1486,7 @@ class PgAgentMessageStore {
|
|
|
1096
1486
|
FOR UPDATE
|
|
1097
1487
|
`;
|
|
1098
1488
|
if (!thread) {
|
|
1099
|
-
throw new
|
|
1489
|
+
throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1100
1490
|
}
|
|
1101
1491
|
const [seqRow] = await tx`
|
|
1102
1492
|
SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM agent_messages
|
|
@@ -1146,7 +1536,7 @@ class PgAgentMessageStore {
|
|
|
1146
1536
|
});
|
|
1147
1537
|
} catch (error) {
|
|
1148
1538
|
if (isUniqueViolation(error)) {
|
|
1149
|
-
throw new
|
|
1539
|
+
throw new AgentStorageError4("duplicate_id", `[SixbPg] Agent message '${input.id}' already exists for project '${input.projectId}'.`);
|
|
1150
1540
|
}
|
|
1151
1541
|
throw error;
|
|
1152
1542
|
}
|
|
@@ -1161,7 +1551,7 @@ class PgAgentMessageStore {
|
|
|
1161
1551
|
FOR SHARE
|
|
1162
1552
|
`;
|
|
1163
1553
|
if (!owner) {
|
|
1164
|
-
throw new
|
|
1554
|
+
throw new AgentStorageError4("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.fence.runId}'.`);
|
|
1165
1555
|
}
|
|
1166
1556
|
}
|
|
1167
1557
|
const [thread] = await tx`
|
|
@@ -1170,7 +1560,7 @@ class PgAgentMessageStore {
|
|
|
1170
1560
|
FOR UPDATE
|
|
1171
1561
|
`;
|
|
1172
1562
|
if (!thread) {
|
|
1173
|
-
throw new
|
|
1563
|
+
throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1174
1564
|
}
|
|
1175
1565
|
const deleted = await tx`
|
|
1176
1566
|
DELETE FROM agent_messages
|
|
@@ -1182,6 +1572,48 @@ class PgAgentMessageStore {
|
|
|
1182
1572
|
if (deleted.length === 0) {
|
|
1183
1573
|
return 0;
|
|
1184
1574
|
}
|
|
1575
|
+
await clampReadsToHead(tx, input);
|
|
1576
|
+
const counted = deleted.filter((row) => countsAsThreadMessage({
|
|
1577
|
+
parts: typeof row.parts === "string" ? JSON.parse(row.parts) : row.parts
|
|
1578
|
+
})).length;
|
|
1579
|
+
const updatedAt = new Date;
|
|
1580
|
+
await tx`
|
|
1581
|
+
UPDATE agent_threads
|
|
1582
|
+
SET
|
|
1583
|
+
message_count = GREATEST(message_count - ${counted}, 0),
|
|
1584
|
+
last_message_at = (
|
|
1585
|
+
SELECT created_at FROM agent_messages
|
|
1586
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1587
|
+
ORDER BY seq DESC
|
|
1588
|
+
LIMIT 1
|
|
1589
|
+
),
|
|
1590
|
+
updated_at = ${updatedAt}
|
|
1591
|
+
WHERE project_id = ${input.projectId} AND id = ${input.threadId}
|
|
1592
|
+
`;
|
|
1593
|
+
return deleted.length;
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
async deleteFromSeq(input) {
|
|
1597
|
+
assertDeleteAgentMessagesFromSeqInput(input, "SixbPg");
|
|
1598
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1599
|
+
const [thread] = await tx`
|
|
1600
|
+
SELECT id FROM agent_threads
|
|
1601
|
+
WHERE project_id = ${input.projectId} AND id = ${input.threadId}
|
|
1602
|
+
FOR UPDATE
|
|
1603
|
+
`;
|
|
1604
|
+
if (!thread) {
|
|
1605
|
+
throw new AgentStorageError4("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1606
|
+
}
|
|
1607
|
+
const deleted = await tx`
|
|
1608
|
+
DELETE FROM agent_messages
|
|
1609
|
+
WHERE project_id = ${input.projectId}
|
|
1610
|
+
AND thread_id = ${input.threadId}
|
|
1611
|
+
AND seq >= ${input.fromSeq}
|
|
1612
|
+
RETURNING id, parts
|
|
1613
|
+
`;
|
|
1614
|
+
if (deleted.length === 0)
|
|
1615
|
+
return 0;
|
|
1616
|
+
await clampReadsToHead(tx, input);
|
|
1185
1617
|
const counted = deleted.filter((row) => countsAsThreadMessage({
|
|
1186
1618
|
parts: typeof row.parts === "string" ? JSON.parse(row.parts) : row.parts
|
|
1187
1619
|
})).length;
|
|
@@ -1238,6 +1670,142 @@ class PgAgentMessageStore {
|
|
|
1238
1670
|
return { messages: rows.map(rowToMessageRecord), hasMore, total };
|
|
1239
1671
|
}
|
|
1240
1672
|
}
|
|
1673
|
+
async function clampReadsToHead(tx, input) {
|
|
1674
|
+
await tx`
|
|
1675
|
+
UPDATE agent_thread_reads
|
|
1676
|
+
SET through_seq = head.seq
|
|
1677
|
+
FROM (
|
|
1678
|
+
SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages
|
|
1679
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1680
|
+
) AS head
|
|
1681
|
+
WHERE agent_thread_reads.project_id = ${input.projectId}
|
|
1682
|
+
AND agent_thread_reads.thread_id = ${input.threadId}
|
|
1683
|
+
AND agent_thread_reads.through_seq > head.seq
|
|
1684
|
+
`;
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
// src/agents/reads.ts
|
|
1688
|
+
import {
|
|
1689
|
+
AgentStorageError as AgentStorageError5
|
|
1690
|
+
} from "@sixb/core/storage";
|
|
1691
|
+
class PgAgentThreadReadStore {
|
|
1692
|
+
sql;
|
|
1693
|
+
constructor(sql) {
|
|
1694
|
+
this.sql = sql;
|
|
1695
|
+
}
|
|
1696
|
+
async mark(input) {
|
|
1697
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
1698
|
+
const [thread] = await tx`
|
|
1699
|
+
SELECT id FROM agent_threads
|
|
1700
|
+
WHERE project_id = ${input.projectId} AND id = ${input.threadId}
|
|
1701
|
+
FOR SHARE
|
|
1702
|
+
`;
|
|
1703
|
+
if (!thread) {
|
|
1704
|
+
throw new AgentStorageError5("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1705
|
+
}
|
|
1706
|
+
const reached = await reachedSeq(tx, input);
|
|
1707
|
+
if (reached !== null) {
|
|
1708
|
+
await tx`
|
|
1709
|
+
INSERT INTO agent_thread_reads (
|
|
1710
|
+
project_id,
|
|
1711
|
+
thread_id,
|
|
1712
|
+
principal_type,
|
|
1713
|
+
principal_id,
|
|
1714
|
+
through_seq,
|
|
1715
|
+
read_at
|
|
1716
|
+
) VALUES (
|
|
1717
|
+
${input.projectId},
|
|
1718
|
+
${input.threadId},
|
|
1719
|
+
'user',
|
|
1720
|
+
${input.principal.id},
|
|
1721
|
+
${reached},
|
|
1722
|
+
${input.readAt ?? new Date}
|
|
1723
|
+
)
|
|
1724
|
+
ON CONFLICT (project_id, thread_id, principal_type, principal_id) DO UPDATE SET
|
|
1725
|
+
through_seq = GREATEST(agent_thread_reads.through_seq, EXCLUDED.through_seq),
|
|
1726
|
+
read_at = GREATEST(agent_thread_reads.read_at, EXCLUDED.read_at)
|
|
1727
|
+
`;
|
|
1728
|
+
}
|
|
1729
|
+
const [state] = await readStates(tx, input.projectId, input.principal.id, [input.threadId]);
|
|
1730
|
+
if (!state) {
|
|
1731
|
+
throw new Error(`[SixbPg] Agent thread '${input.threadId}' lost its read state.`);
|
|
1732
|
+
}
|
|
1733
|
+
return state;
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
async list(input) {
|
|
1737
|
+
if (input.threadIds.length === 0)
|
|
1738
|
+
return [];
|
|
1739
|
+
return readStates(this.sql, input.projectId, input.principal.id, [...new Set(input.threadIds)]);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
async function reachedSeq(tx, input) {
|
|
1743
|
+
if (input.throughMessageId === undefined) {
|
|
1744
|
+
const [head] = await tx`
|
|
1745
|
+
SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages
|
|
1746
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
1747
|
+
`;
|
|
1748
|
+
return Number(head?.seq ?? 0);
|
|
1749
|
+
}
|
|
1750
|
+
const [message] = await tx`
|
|
1751
|
+
SELECT seq FROM agent_messages
|
|
1752
|
+
WHERE project_id = ${input.projectId}
|
|
1753
|
+
AND thread_id = ${input.threadId}
|
|
1754
|
+
AND id = ${input.throughMessageId}
|
|
1755
|
+
`;
|
|
1756
|
+
return message ? Number(message.seq) : null;
|
|
1757
|
+
}
|
|
1758
|
+
async function readStates(sql, projectId, principalId, threadIds) {
|
|
1759
|
+
const rows = await sql`
|
|
1760
|
+
SELECT
|
|
1761
|
+
place.thread_id,
|
|
1762
|
+
place.head_seq,
|
|
1763
|
+
LEAST(COALESCE(place.through_seq, 0), place.head_seq) AS through_seq,
|
|
1764
|
+
place.read_at,
|
|
1765
|
+
(
|
|
1766
|
+
SELECT COUNT(*) FROM agent_messages AS message
|
|
1767
|
+
WHERE message.project_id = ${projectId}
|
|
1768
|
+
AND message.thread_id = place.thread_id
|
|
1769
|
+
AND message.seq > COALESCE(place.through_seq, 0)
|
|
1770
|
+
AND (
|
|
1771
|
+
message.role <> 'user'
|
|
1772
|
+
OR message.author_principal_type IS DISTINCT FROM 'user'
|
|
1773
|
+
OR message.author_principal_id IS DISTINCT FROM ${principalId}
|
|
1774
|
+
)
|
|
1775
|
+
AND NOT (
|
|
1776
|
+
jsonb_array_length(message.parts) > 0 AND NOT EXISTS (
|
|
1777
|
+
SELECT 1 FROM jsonb_array_elements(message.parts) AS part
|
|
1778
|
+
WHERE part->>'type' <> 'approval-outcome'
|
|
1779
|
+
)
|
|
1780
|
+
)
|
|
1781
|
+
) AS unread
|
|
1782
|
+
FROM (
|
|
1783
|
+
SELECT
|
|
1784
|
+
thread.id AS thread_id,
|
|
1785
|
+
(
|
|
1786
|
+
SELECT COALESCE(MAX(seq), 0) FROM agent_messages
|
|
1787
|
+
WHERE project_id = thread.project_id AND thread_id = thread.id
|
|
1788
|
+
) AS head_seq,
|
|
1789
|
+
reading.through_seq,
|
|
1790
|
+
reading.read_at
|
|
1791
|
+
FROM agent_threads AS thread
|
|
1792
|
+
LEFT JOIN agent_thread_reads AS reading
|
|
1793
|
+
ON reading.project_id = thread.project_id
|
|
1794
|
+
AND reading.thread_id = thread.id
|
|
1795
|
+
AND reading.principal_type = 'user'
|
|
1796
|
+
AND reading.principal_id = ${principalId}
|
|
1797
|
+
WHERE thread.project_id = ${projectId}
|
|
1798
|
+
AND thread.id = ANY(${sql.array([...threadIds])}::text[])
|
|
1799
|
+
) AS place
|
|
1800
|
+
`;
|
|
1801
|
+
return rows.map((row) => ({
|
|
1802
|
+
threadId: row.thread_id,
|
|
1803
|
+
throughSeq: Number(row.through_seq),
|
|
1804
|
+
headSeq: Number(row.head_seq),
|
|
1805
|
+
unread: Number(row.unread),
|
|
1806
|
+
...row.read_at === null ? {} : { readAt: new Date(row.read_at) }
|
|
1807
|
+
}));
|
|
1808
|
+
}
|
|
1241
1809
|
|
|
1242
1810
|
// src/agents/runs.ts
|
|
1243
1811
|
import {
|
|
@@ -1258,7 +1826,7 @@ import { AGENT_MESSAGE_CONTENT_VERSION as AGENT_MESSAGE_CONTENT_VERSION2 } from
|
|
|
1258
1826
|
import { serializeSixbFailure } from "@sixb/core/internal/errors";
|
|
1259
1827
|
import {
|
|
1260
1828
|
AGENT_RUN_FAILURE_CODES as AGENT_RUN_FAILURE_CODES2,
|
|
1261
|
-
AgentStorageError as
|
|
1829
|
+
AgentStorageError as AgentStorageError6
|
|
1262
1830
|
} from "@sixb/core/storage";
|
|
1263
1831
|
|
|
1264
1832
|
// src/run-list-query.ts
|
|
@@ -1343,11 +1911,11 @@ class PgAgentRunStore {
|
|
|
1343
1911
|
FOR UPDATE
|
|
1344
1912
|
`;
|
|
1345
1913
|
if (!thread) {
|
|
1346
|
-
throw new
|
|
1914
|
+
throw new AgentStorageError6("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1347
1915
|
}
|
|
1348
1916
|
assertConversationThreadRow(thread, "takes turns", "SixbPg");
|
|
1349
1917
|
if (thread.active_run_id !== null) {
|
|
1350
|
-
throw new
|
|
1918
|
+
throw new AgentStorageError6("active_run_exists", `[SixbPg] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`);
|
|
1351
1919
|
}
|
|
1352
1920
|
assertTurnInThreadPlace(thread.runs_on, input.spec, input.threadId, "SixbPg");
|
|
1353
1921
|
const [row] = await tx`
|
|
@@ -1388,7 +1956,7 @@ class PgAgentRunStore {
|
|
|
1388
1956
|
});
|
|
1389
1957
|
} catch (error) {
|
|
1390
1958
|
if (isUniqueViolation(error)) {
|
|
1391
|
-
throw new
|
|
1959
|
+
throw new AgentStorageError6("duplicate_id", `[SixbPg] Agent run '${input.id}' already exists for project '${input.projectId}'.`);
|
|
1392
1960
|
}
|
|
1393
1961
|
throw error;
|
|
1394
1962
|
}
|
|
@@ -1409,7 +1977,7 @@ class PgAgentRunStore {
|
|
|
1409
1977
|
FOR UPDATE
|
|
1410
1978
|
`;
|
|
1411
1979
|
if (!parent || parent.kind !== "conversation") {
|
|
1412
|
-
throw new
|
|
1980
|
+
throw new AgentStorageError6("run_not_found", `[SixbPg] Parent Agent run '${input.parentRunId}' was not found.`);
|
|
1413
1981
|
}
|
|
1414
1982
|
const [existingRow] = await tx`
|
|
1415
1983
|
SELECT * FROM agent_runs
|
|
@@ -1419,16 +1987,16 @@ class PgAgentRunStore {
|
|
|
1419
1987
|
const existing = rowToRunRecord(existingRow);
|
|
1420
1988
|
if (subagentRunMatchesCreateInput(existing, input))
|
|
1421
1989
|
return existing;
|
|
1422
|
-
throw new
|
|
1990
|
+
throw new AgentStorageError6("duplicate_id", `[SixbPg] Subagent run '${input.id}' already exists with different immutable inputs.`);
|
|
1423
1991
|
}
|
|
1424
1992
|
if (parent.status !== "running") {
|
|
1425
|
-
throw new
|
|
1993
|
+
throw new AgentStorageError6("invalid_state", `[SixbPg] Parent Agent run '${parent.id}' is not running (status '${parent.status}').`);
|
|
1426
1994
|
}
|
|
1427
1995
|
if (execution.source.type !== "execution" || execution.source.executionId !== parent.execution_id) {
|
|
1428
|
-
throw new
|
|
1996
|
+
throw new AgentStorageError6("invalid_input", `[SixbPg] Subagent execution '${execution.id}' is not a child of parent execution '${parent.execution_id}'.`);
|
|
1429
1997
|
}
|
|
1430
1998
|
if (parent.execution_token !== input.parentExecutionToken) {
|
|
1431
|
-
throw new
|
|
1999
|
+
throw new AgentStorageError6("execution_lost", `[SixbPg] Parent Agent run '${parent.id}' is no longer owned by this execution.`);
|
|
1432
2000
|
}
|
|
1433
2001
|
const [countRow] = await tx`
|
|
1434
2002
|
SELECT COUNT(*)::bigint AS count FROM agent_runs
|
|
@@ -1438,7 +2006,7 @@ class PgAgentRunStore {
|
|
|
1438
2006
|
`;
|
|
1439
2007
|
const activeChildren = Number(countRow?.count ?? 0);
|
|
1440
2008
|
if (activeChildren >= input.maxActiveChildren) {
|
|
1441
|
-
throw new
|
|
2009
|
+
throw new AgentStorageError6("active_child_limit", `[SixbPg] Agent run '${parent.id}' already has ${activeChildren} active subagents.`);
|
|
1442
2010
|
}
|
|
1443
2011
|
const createdAt = input.createdAt ?? new Date;
|
|
1444
2012
|
await claimChildThread(tx, input, parent, createdAt);
|
|
@@ -1475,7 +2043,7 @@ class PgAgentRunStore {
|
|
|
1475
2043
|
});
|
|
1476
2044
|
} catch (error) {
|
|
1477
2045
|
if (isUniqueViolation(error)) {
|
|
1478
|
-
throw new
|
|
2046
|
+
throw new AgentStorageError6("duplicate_id", `[SixbPg] Subagent run '${input.id}' conflicts with an existing durable spawn.`);
|
|
1479
2047
|
}
|
|
1480
2048
|
throw error;
|
|
1481
2049
|
}
|
|
@@ -1527,7 +2095,7 @@ class PgAgentRunStore {
|
|
|
1527
2095
|
return runPgTransaction(this.sql, async (tx) => {
|
|
1528
2096
|
const run = await this.lockRunning(tx, input.projectId, input.id);
|
|
1529
2097
|
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
|
|
2098
|
+
throw new AgentStorageError6("invalid_state", `[SixbPg] Agent run '${input.id}' is still held by its runner, whose lease has not lapsed.`);
|
|
1531
2099
|
}
|
|
1532
2100
|
const [row] = await tx`
|
|
1533
2101
|
UPDATE agent_runs
|
|
@@ -1545,7 +2113,7 @@ class PgAgentRunStore {
|
|
|
1545
2113
|
return runPgTransaction(this.sql, async (tx) => {
|
|
1546
2114
|
const run = await this.lockRunning(tx, input.projectId, input.id);
|
|
1547
2115
|
if (run.execution_token !== input.executionToken) {
|
|
1548
|
-
throw new
|
|
2116
|
+
throw new AgentStorageError6("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
|
|
1549
2117
|
}
|
|
1550
2118
|
const [row] = await tx`
|
|
1551
2119
|
UPDATE agent_runs
|
|
@@ -1571,7 +2139,7 @@ class PgAgentRunStore {
|
|
|
1571
2139
|
return rowToRunRecord(updated);
|
|
1572
2140
|
const current = await this.getById(input);
|
|
1573
2141
|
if (!current) {
|
|
1574
|
-
throw new
|
|
2142
|
+
throw new AgentStorageError6("run_not_found", `[SixbPg] Agent run '${input.id}' not found for project '${input.projectId}'.`);
|
|
1575
2143
|
}
|
|
1576
2144
|
return current;
|
|
1577
2145
|
}
|
|
@@ -1582,7 +2150,7 @@ class PgAgentRunStore {
|
|
|
1582
2150
|
const run = await this.lockRunning(tx, input.projectId, input.id);
|
|
1583
2151
|
assertAgentRunFinishPayload(run.kind, input, run.id, "SixbPg");
|
|
1584
2152
|
if (run.execution_token !== input.executionToken) {
|
|
1585
|
-
throw new
|
|
2153
|
+
throw new AgentStorageError6("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.id}'.`);
|
|
1586
2154
|
}
|
|
1587
2155
|
if (input.finishReason === "awaiting_approval") {
|
|
1588
2156
|
assertAwaitingApprovalFinish({
|
|
@@ -1647,6 +2215,12 @@ class PgAgentRunStore {
|
|
|
1647
2215
|
AND child.kind = 'subagent'
|
|
1648
2216
|
${input.spawnKey === undefined ? this.sql`` : this.sql`AND child.spawn_key = ${input.spawnKey}`}
|
|
1649
2217
|
${input.finishReason === undefined ? this.sql`` : this.sql`AND child.finish_reason = ${input.finishReason}`}
|
|
2218
|
+
${input.retainedTurnsOnly ? this.sql`AND EXISTS (
|
|
2219
|
+
SELECT 1 FROM agent_messages m
|
|
2220
|
+
WHERE m.project_id = turn.project_id
|
|
2221
|
+
AND m.thread_id = turn.thread_id
|
|
2222
|
+
AND m.id = turn.trigger_message_id
|
|
2223
|
+
)` : this.sql``}
|
|
1650
2224
|
ORDER BY COALESCE(turn.started_at, turn.created_at) DESC, turn.id DESC,
|
|
1651
2225
|
child.created_at DESC, child.id DESC
|
|
1652
2226
|
LIMIT ${input.limit ?? 100}
|
|
@@ -1656,6 +2230,18 @@ class PgAgentRunStore {
|
|
|
1656
2230
|
return run.kind === "subagent" ? [run] : [];
|
|
1657
2231
|
});
|
|
1658
2232
|
}
|
|
2233
|
+
async latestByThread(input) {
|
|
2234
|
+
if (input.threadIds.length === 0)
|
|
2235
|
+
return [];
|
|
2236
|
+
const rows = await this.sql`
|
|
2237
|
+
SELECT DISTINCT ON (thread_id) *
|
|
2238
|
+
FROM agent_runs
|
|
2239
|
+
WHERE project_id = ${input.projectId}
|
|
2240
|
+
AND thread_id = ANY(${this.sql.array([...input.threadIds])}::text[])
|
|
2241
|
+
ORDER BY thread_id, created_at DESC, id DESC
|
|
2242
|
+
`;
|
|
2243
|
+
return rows.map(rowToRunRecord);
|
|
2244
|
+
}
|
|
1659
2245
|
async list(input) {
|
|
1660
2246
|
if (hasEmptyStatuses(input) || input.kinds?.length === 0) {
|
|
1661
2247
|
return { runs: [], hasMore: false, total: 0 };
|
|
@@ -1701,10 +2287,10 @@ class PgAgentRunStore {
|
|
|
1701
2287
|
FOR UPDATE
|
|
1702
2288
|
`;
|
|
1703
2289
|
if (!row) {
|
|
1704
|
-
throw new
|
|
2290
|
+
throw new AgentStorageError6("run_not_found", `[SixbPg] Agent run '${id}' not found for project '${projectId}'.`);
|
|
1705
2291
|
}
|
|
1706
2292
|
if (row.status !== status) {
|
|
1707
|
-
throw new
|
|
2293
|
+
throw new AgentStorageError6("invalid_state", `[SixbPg] Agent run '${id}' is not ${status} (status '${row.status}').`);
|
|
1708
2294
|
}
|
|
1709
2295
|
return row;
|
|
1710
2296
|
}
|
|
@@ -1735,7 +2321,7 @@ async function claimChildThread(tx, input, parent, createdAt) {
|
|
|
1735
2321
|
SELECT * FROM agent_threads WHERE project_id = ${input.projectId} AND id = ${parent.thread_id}
|
|
1736
2322
|
`;
|
|
1737
2323
|
if (!conversation) {
|
|
1738
|
-
throw new
|
|
2324
|
+
throw new AgentStorageError6("thread_not_found", `[SixbPg] Agent thread '${parent.thread_id}' not found for project '${input.projectId}'.`);
|
|
1739
2325
|
}
|
|
1740
2326
|
const thread = newSubagentThreadRecord(input, rowToThreadRecord(conversation), createdAt);
|
|
1741
2327
|
await tx`
|
|
@@ -1774,7 +2360,7 @@ async function settleFinishedRunApprovals(tx, kind, input, completedAt) {
|
|
|
1774
2360
|
// src/agents/settings.ts
|
|
1775
2361
|
import { assertAgentApprovalModeInput } from "@sixb/core/internal/agent-run-storage-provider";
|
|
1776
2362
|
import {
|
|
1777
|
-
AgentStorageError as
|
|
2363
|
+
AgentStorageError as AgentStorageError7
|
|
1778
2364
|
} from "@sixb/core/storage";
|
|
1779
2365
|
class PgAgentApprovalModeStore {
|
|
1780
2366
|
sql;
|
|
@@ -1848,7 +2434,7 @@ class PgAgentApprovalModeStore {
|
|
|
1848
2434
|
}
|
|
1849
2435
|
}
|
|
1850
2436
|
function threadNotFound(input) {
|
|
1851
|
-
return new
|
|
2437
|
+
return new AgentStorageError7("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
1852
2438
|
}
|
|
1853
2439
|
|
|
1854
2440
|
// src/agents/threads.ts
|
|
@@ -1862,12 +2448,13 @@ import {
|
|
|
1862
2448
|
participantsToAdd,
|
|
1863
2449
|
planAgentThreadFork,
|
|
1864
2450
|
queuedTurnInCloud,
|
|
2451
|
+
queuedTurnOnComputer,
|
|
1865
2452
|
remapArtifactIds,
|
|
1866
2453
|
snapshotAgentThreadSandboxParams as snapshotAgentThreadSandboxParams2,
|
|
1867
2454
|
transitionAgentThreadSandbox
|
|
1868
2455
|
} from "@sixb/core/internal/agent-run-storage-provider";
|
|
1869
2456
|
import {
|
|
1870
|
-
AgentStorageError as
|
|
2457
|
+
AgentStorageError as AgentStorageError8
|
|
1871
2458
|
} from "@sixb/core/storage";
|
|
1872
2459
|
class PgAgentThreadStore {
|
|
1873
2460
|
sql;
|
|
@@ -1876,7 +2463,7 @@ class PgAgentThreadStore {
|
|
|
1876
2463
|
}
|
|
1877
2464
|
async transitionSandbox(input) {
|
|
1878
2465
|
return runPgTransaction(this.sql, async (tx) => {
|
|
1879
|
-
const runs = input.action === "recreate" ? [] : await tx`
|
|
2466
|
+
const runs = input.action === "recreate" || input.action === "restore" ? [] : await tx`
|
|
1880
2467
|
SELECT * FROM agent_runs WHERE project_id = ${input.projectId} AND id = ${input.runId}
|
|
1881
2468
|
FOR UPDATE
|
|
1882
2469
|
`;
|
|
@@ -1929,7 +2516,7 @@ class PgAgentThreadStore {
|
|
|
1929
2516
|
return rowToThreadRecord(row);
|
|
1930
2517
|
} catch (error) {
|
|
1931
2518
|
if (isUniqueViolation(error)) {
|
|
1932
|
-
throw new
|
|
2519
|
+
throw new AgentStorageError8("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
|
|
1933
2520
|
}
|
|
1934
2521
|
throw error;
|
|
1935
2522
|
}
|
|
@@ -1943,7 +2530,7 @@ class PgAgentThreadStore {
|
|
|
1943
2530
|
FOR SHARE
|
|
1944
2531
|
`;
|
|
1945
2532
|
if (!source) {
|
|
1946
|
-
throw new
|
|
2533
|
+
throw new AgentStorageError8("thread_not_found", `[SixbPg] Agent thread '${input.sourceThreadId}' not found for project '${input.projectId}'.`);
|
|
1947
2534
|
}
|
|
1948
2535
|
assertConversationThreadRow2(source, "can be forked", "SixbPg");
|
|
1949
2536
|
const [activeRun] = source.active_run_id === null ? [] : await tx`
|
|
@@ -2010,6 +2597,31 @@ class PgAgentThreadStore {
|
|
|
2010
2597
|
)
|
|
2011
2598
|
RETURNING *
|
|
2012
2599
|
`;
|
|
2600
|
+
if (input.ownerPrincipal.type === "user") {
|
|
2601
|
+
await tx`
|
|
2602
|
+
INSERT INTO agent_thread_reads (
|
|
2603
|
+
project_id,
|
|
2604
|
+
thread_id,
|
|
2605
|
+
principal_type,
|
|
2606
|
+
principal_id,
|
|
2607
|
+
through_seq,
|
|
2608
|
+
read_at
|
|
2609
|
+
)
|
|
2610
|
+
SELECT
|
|
2611
|
+
${input.projectId},
|
|
2612
|
+
${input.id},
|
|
2613
|
+
'user',
|
|
2614
|
+
${input.ownerPrincipal.id},
|
|
2615
|
+
LEAST(source.through_seq, ${plan.headSeq}),
|
|
2616
|
+
source.read_at
|
|
2617
|
+
FROM agent_thread_reads AS source
|
|
2618
|
+
WHERE source.project_id = ${input.projectId}
|
|
2619
|
+
AND source.thread_id = ${input.sourceThreadId}
|
|
2620
|
+
AND source.principal_type = 'user'
|
|
2621
|
+
AND source.principal_id = ${input.ownerPrincipal.id}
|
|
2622
|
+
ON CONFLICT DO NOTHING
|
|
2623
|
+
`;
|
|
2624
|
+
}
|
|
2013
2625
|
if (plan.messages.length > 0) {
|
|
2014
2626
|
await tx`
|
|
2015
2627
|
INSERT INTO agent_messages (
|
|
@@ -2057,7 +2669,7 @@ class PgAgentThreadStore {
|
|
|
2057
2669
|
});
|
|
2058
2670
|
} catch (error) {
|
|
2059
2671
|
if (isUniqueViolationOf(error, "agent_threads_pkey")) {
|
|
2060
|
-
throw new
|
|
2672
|
+
throw new AgentStorageError8("duplicate_id", `[SixbPg] Agent thread '${input.id}' already exists for project '${input.projectId}'.`);
|
|
2061
2673
|
}
|
|
2062
2674
|
throw error;
|
|
2063
2675
|
}
|
|
@@ -2150,7 +2762,7 @@ class PgAgentThreadStore {
|
|
|
2150
2762
|
FOR UPDATE
|
|
2151
2763
|
`;
|
|
2152
2764
|
if (!thread) {
|
|
2153
|
-
throw new
|
|
2765
|
+
throw new AgentStorageError8("thread_not_found", `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`);
|
|
2154
2766
|
}
|
|
2155
2767
|
assertConversationThreadRow2(thread, "has participants", "SixbPg");
|
|
2156
2768
|
const existing = await selectParticipants(tx, input.projectId, [input.threadId]);
|
|
@@ -2158,48 +2770,99 @@ class PgAgentThreadStore {
|
|
|
2158
2770
|
const addedAt = input.addedAt ?? new Date;
|
|
2159
2771
|
for (const principal of added) {
|
|
2160
2772
|
await tx`
|
|
2161
|
-
INSERT INTO agent_thread_participants (
|
|
2773
|
+
INSERT INTO agent_thread_participants (
|
|
2774
|
+
project_id,
|
|
2775
|
+
thread_id,
|
|
2776
|
+
principal_type,
|
|
2777
|
+
principal_id,
|
|
2778
|
+
added_at,
|
|
2779
|
+
added_by_type,
|
|
2780
|
+
added_by_id
|
|
2781
|
+
) VALUES (
|
|
2782
|
+
${input.projectId},
|
|
2783
|
+
${input.threadId},
|
|
2784
|
+
${principal.type},
|
|
2785
|
+
${principal.id},
|
|
2786
|
+
${addedAt},
|
|
2787
|
+
${input.addedBy.type},
|
|
2788
|
+
${input.addedBy.id}
|
|
2789
|
+
)
|
|
2790
|
+
`;
|
|
2791
|
+
}
|
|
2792
|
+
for (const principal of added) {
|
|
2793
|
+
await tx`
|
|
2794
|
+
INSERT INTO agent_thread_reads (
|
|
2162
2795
|
project_id,
|
|
2163
2796
|
thread_id,
|
|
2164
2797
|
principal_type,
|
|
2165
2798
|
principal_id,
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
added_by_id
|
|
2799
|
+
through_seq,
|
|
2800
|
+
read_at
|
|
2169
2801
|
) VALUES (
|
|
2170
2802
|
${input.projectId},
|
|
2171
2803
|
${input.threadId},
|
|
2172
2804
|
${principal.type},
|
|
2173
2805
|
${principal.id},
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2806
|
+
(
|
|
2807
|
+
SELECT COALESCE(MAX(seq), 0) FROM agent_messages
|
|
2808
|
+
WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
|
|
2809
|
+
),
|
|
2810
|
+
${addedAt}
|
|
2177
2811
|
)
|
|
2812
|
+
ON CONFLICT (project_id, thread_id, principal_type, principal_id) DO UPDATE SET
|
|
2813
|
+
through_seq = EXCLUDED.through_seq,
|
|
2814
|
+
read_at = EXCLUDED.read_at
|
|
2178
2815
|
`;
|
|
2179
2816
|
}
|
|
2180
2817
|
return added.length === 0 ? existing : selectParticipants(tx, input.projectId, [input.threadId]);
|
|
2181
2818
|
});
|
|
2182
2819
|
}
|
|
2183
2820
|
async removeParticipant(input) {
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2821
|
+
return runPgTransaction(this.sql, async (tx) => {
|
|
2822
|
+
const rows = await tx`
|
|
2823
|
+
DELETE FROM agent_thread_participants
|
|
2824
|
+
WHERE project_id = ${input.projectId}
|
|
2825
|
+
AND thread_id = ${input.threadId}
|
|
2826
|
+
AND principal_type = ${input.principal.type}
|
|
2827
|
+
AND principal_id = ${input.principal.id}
|
|
2828
|
+
RETURNING principal_id
|
|
2829
|
+
`;
|
|
2830
|
+
await tx`
|
|
2831
|
+
DELETE FROM agent_thread_reads
|
|
2832
|
+
WHERE project_id = ${input.projectId}
|
|
2833
|
+
AND thread_id = ${input.threadId}
|
|
2834
|
+
AND principal_type = ${input.principal.type}
|
|
2835
|
+
AND principal_id = ${input.principal.id}
|
|
2836
|
+
`;
|
|
2837
|
+
return rows.length > 0;
|
|
2838
|
+
});
|
|
2193
2839
|
}
|
|
2194
2840
|
async assignComputer(input) {
|
|
2195
2841
|
assertAgentThreadComputer(input.computer, "SixbPg");
|
|
2196
2842
|
return runPgTransaction(this.sql, async (tx) => {
|
|
2197
2843
|
const { thread, active } = await lockThreadAndActiveRun(tx, input);
|
|
2198
2844
|
assertAssignableComputer(thread, active, input.computer, input.id, "SixbPg");
|
|
2845
|
+
const queued = queuedTurnOnComputer(active, input.computer);
|
|
2846
|
+
if (queued) {
|
|
2847
|
+
await tx`
|
|
2848
|
+
UPDATE agent_runs SET spec = ${JSON.stringify(queued.spec)}::text::jsonb
|
|
2849
|
+
WHERE project_id = ${input.projectId} AND id = ${queued.id}
|
|
2850
|
+
`;
|
|
2851
|
+
}
|
|
2852
|
+
if (thread.runsOn !== "computer") {
|
|
2853
|
+
await tx`
|
|
2854
|
+
UPDATE agent_threads
|
|
2855
|
+
SET sandbox_state = jsonb_set(sandbox_state, '{status}', '"unavailable"'::jsonb)
|
|
2856
|
+
WHERE project_id = ${input.projectId}
|
|
2857
|
+
AND parent_thread_id = ${input.id}
|
|
2858
|
+
AND sandbox_state->>'status' IN ('new', 'ready')
|
|
2859
|
+
`;
|
|
2860
|
+
}
|
|
2199
2861
|
const movedAt = movesComputerPlace(thread, input.computer) ? input.movedAt ?? new Date : null;
|
|
2200
2862
|
const [assigned] = await tx`
|
|
2201
2863
|
UPDATE agent_threads
|
|
2202
|
-
SET
|
|
2864
|
+
SET runs_on = 'computer',
|
|
2865
|
+
computer_id = ${input.computer.id},
|
|
2203
2866
|
computer_name = ${input.computer.name},
|
|
2204
2867
|
computer_folder = ${input.computer.folder},
|
|
2205
2868
|
moved_at = COALESCE(${movedAt}::timestamptz, moved_at)
|
|
@@ -2259,7 +2922,7 @@ async function lockThreadAndActiveRun(tx, input) {
|
|
|
2259
2922
|
};
|
|
2260
2923
|
}
|
|
2261
2924
|
if (attempt >= 3) {
|
|
2262
|
-
throw new
|
|
2925
|
+
throw new AgentStorageError8("invalid_state", `[SixbPg] Agent thread '${input.id}' kept changing turns while it moved: try again.`);
|
|
2263
2926
|
}
|
|
2264
2927
|
}
|
|
2265
2928
|
}
|
|
@@ -2389,6 +3052,7 @@ class PgAgentTokenRateStore {
|
|
|
2389
3052
|
// src/agents/agent-storage.ts
|
|
2390
3053
|
class PgAgentStorage {
|
|
2391
3054
|
threads;
|
|
3055
|
+
reads;
|
|
2392
3056
|
runs;
|
|
2393
3057
|
messages;
|
|
2394
3058
|
checkpoints;
|
|
@@ -2397,8 +3061,10 @@ class PgAgentStorage {
|
|
|
2397
3061
|
approvalModes;
|
|
2398
3062
|
computers;
|
|
2399
3063
|
tokenRates;
|
|
3064
|
+
inbox;
|
|
2400
3065
|
constructor(options) {
|
|
2401
3066
|
this.threads = new PgAgentThreadStore(options.sql);
|
|
3067
|
+
this.reads = new PgAgentThreadReadStore(options.sql);
|
|
2402
3068
|
this.runs = new PgAgentRunStore(options.sql, options.executions);
|
|
2403
3069
|
this.messages = new PgAgentMessageStore(options.sql);
|
|
2404
3070
|
this.checkpoints = new PgAgentContextCheckpointStore(options.sql);
|
|
@@ -2407,6 +3073,7 @@ class PgAgentStorage {
|
|
|
2407
3073
|
this.approvalModes = new PgAgentApprovalModeStore(options.sql);
|
|
2408
3074
|
this.computers = new PgAgentComputerSessionStore(options.sql);
|
|
2409
3075
|
this.tokenRates = new PgAgentTokenRateStore(options.sql);
|
|
3076
|
+
this.inbox = new PgAgentInboxStore(options.sql);
|
|
2410
3077
|
}
|
|
2411
3078
|
}
|
|
2412
3079
|
// src/auth-storage/auth-storage.ts
|
|
@@ -10687,6 +11354,325 @@ ALTER TABLE auth_users
|
|
|
10687
11354
|
);
|
|
10688
11355
|
`;
|
|
10689
11356
|
|
|
11357
|
+
// src/migrations/103-script-executions.sql
|
|
11358
|
+
var _103_script_executions_default = `-- \`sixb run\` records each script run as an execution: a script executor, the script's path as its
|
|
11359
|
+
-- source, and authority that holds nothing beyond the run id the executor already names.
|
|
11360
|
+
ALTER TABLE executions
|
|
11361
|
+
DROP CONSTRAINT executions_executor_kind_check,
|
|
11362
|
+
ADD CONSTRAINT executions_executor_kind_check CHECK (
|
|
11363
|
+
executor_kind IN (
|
|
11364
|
+
'request', 'action', 'pipeline', 'projection', 'rule', 'sync', 'webhook', 'workflow',
|
|
11365
|
+
'agent', 'kernel', 'script'
|
|
11366
|
+
)
|
|
11367
|
+
),
|
|
11368
|
+
DROP CONSTRAINT executions_source_kind_check,
|
|
11369
|
+
ADD CONSTRAINT executions_source_kind_check CHECK (
|
|
11370
|
+
source_kind IN (
|
|
11371
|
+
'http', 'webhook', 'schedule', 'event', 'datasetVersion', 'execution', 'ontologyCommit',
|
|
11372
|
+
'script'
|
|
11373
|
+
)
|
|
11374
|
+
),
|
|
11375
|
+
DROP CONSTRAINT executions_authority_kind_check,
|
|
11376
|
+
ADD CONSTRAINT executions_authority_kind_check CHECK (
|
|
11377
|
+
authority_kind IN ('principal', 'trustedPrimitive', 'delegated', 'kernel', 'script', 'disabled')
|
|
11378
|
+
),
|
|
11379
|
+
DROP CONSTRAINT executions_authority_shape_check,
|
|
11380
|
+
ADD CONSTRAINT executions_authority_shape_check CHECK (
|
|
11381
|
+
(
|
|
11382
|
+
authority_kind = 'principal'
|
|
11383
|
+
AND num_nonnulls(authority_user_id, authority_service_account_id) = 1
|
|
11384
|
+
AND num_nonnulls(authority_session_id, authority_access_token_id) <= 1
|
|
11385
|
+
AND (authority_session_id IS NULL OR authority_user_id IS NOT NULL)
|
|
11386
|
+
AND authority_primitive_kind IS NULL
|
|
11387
|
+
AND authority_primitive_id IS NULL
|
|
11388
|
+
AND authority_kernel_operation IS NULL
|
|
11389
|
+
AND authority_delegation_kind IS NULL
|
|
11390
|
+
AND authority_delegation_id IS NULL
|
|
11391
|
+
AND authority_delegation_session_id IS NULL
|
|
11392
|
+
)
|
|
11393
|
+
OR (
|
|
11394
|
+
authority_kind = 'trustedPrimitive'
|
|
11395
|
+
AND authority_user_id IS NULL
|
|
11396
|
+
AND authority_service_account_id IS NULL
|
|
11397
|
+
AND authority_session_id IS NULL
|
|
11398
|
+
AND authority_access_token_id IS NULL
|
|
11399
|
+
AND authority_primitive_kind IS NOT NULL
|
|
11400
|
+
AND authority_primitive_id IS NOT NULL
|
|
11401
|
+
AND length(trim(authority_primitive_id)) > 0
|
|
11402
|
+
AND authority_kernel_operation IS NULL
|
|
11403
|
+
AND authority_delegation_kind IS NULL
|
|
11404
|
+
AND authority_delegation_id IS NULL
|
|
11405
|
+
AND authority_delegation_session_id IS NULL
|
|
11406
|
+
)
|
|
11407
|
+
OR (
|
|
11408
|
+
authority_kind = 'delegated'
|
|
11409
|
+
AND authority_user_id IS NULL
|
|
11410
|
+
AND authority_service_account_id IS NULL
|
|
11411
|
+
AND authority_session_id IS NULL
|
|
11412
|
+
AND authority_access_token_id IS NULL
|
|
11413
|
+
AND authority_primitive_kind IS NULL
|
|
11414
|
+
AND authority_primitive_id IS NULL
|
|
11415
|
+
AND authority_kernel_operation IS NULL
|
|
11416
|
+
AND authority_delegation_kind IS NOT NULL
|
|
11417
|
+
AND authority_delegation_kind = 'share'
|
|
11418
|
+
AND authority_delegation_id IS NOT NULL
|
|
11419
|
+
AND length(trim(authority_delegation_id)) > 0
|
|
11420
|
+
AND authority_delegation_session_id IS NOT NULL
|
|
11421
|
+
AND length(trim(authority_delegation_session_id)) > 0
|
|
11422
|
+
)
|
|
11423
|
+
OR (
|
|
11424
|
+
authority_kind = 'kernel'
|
|
11425
|
+
AND authority_user_id IS NULL
|
|
11426
|
+
AND authority_service_account_id IS NULL
|
|
11427
|
+
AND authority_session_id IS NULL
|
|
11428
|
+
AND authority_access_token_id IS NULL
|
|
11429
|
+
AND authority_primitive_kind IS NULL
|
|
11430
|
+
AND authority_primitive_id IS NULL
|
|
11431
|
+
AND authority_kernel_operation IS NOT NULL
|
|
11432
|
+
AND authority_delegation_kind IS NULL
|
|
11433
|
+
AND authority_delegation_id IS NULL
|
|
11434
|
+
AND authority_delegation_session_id IS NULL
|
|
11435
|
+
)
|
|
11436
|
+
OR (
|
|
11437
|
+
-- A script's authority is its run id, which \`executor_id\` already holds.
|
|
11438
|
+
authority_kind IN ('script', 'disabled')
|
|
11439
|
+
AND authority_user_id IS NULL
|
|
11440
|
+
AND authority_service_account_id IS NULL
|
|
11441
|
+
AND authority_session_id IS NULL
|
|
11442
|
+
AND authority_access_token_id IS NULL
|
|
11443
|
+
AND authority_primitive_kind IS NULL
|
|
11444
|
+
AND authority_primitive_id IS NULL
|
|
11445
|
+
AND authority_kernel_operation IS NULL
|
|
11446
|
+
AND authority_delegation_kind IS NULL
|
|
11447
|
+
AND authority_delegation_id IS NULL
|
|
11448
|
+
AND authority_delegation_session_id IS NULL
|
|
11449
|
+
)
|
|
11450
|
+
),
|
|
11451
|
+
DROP CONSTRAINT executions_executor_authority_check,
|
|
11452
|
+
ADD CONSTRAINT executions_executor_authority_check CHECK (
|
|
11453
|
+
(
|
|
11454
|
+
executor_kind = 'request'
|
|
11455
|
+
AND source_kind = 'http'
|
|
11456
|
+
AND executor_id = source_id
|
|
11457
|
+
AND (
|
|
11458
|
+
(
|
|
11459
|
+
authority_kind = 'principal'
|
|
11460
|
+
AND requested_by_user_id IS NOT DISTINCT FROM authority_user_id
|
|
11461
|
+
AND requested_by_service_account_id IS NOT DISTINCT FROM authority_service_account_id
|
|
11462
|
+
)
|
|
11463
|
+
OR (
|
|
11464
|
+
authority_kind IN ('delegated', 'disabled')
|
|
11465
|
+
AND requested_by_user_id IS NULL
|
|
11466
|
+
AND requested_by_service_account_id IS NULL
|
|
11467
|
+
)
|
|
11468
|
+
)
|
|
11469
|
+
)
|
|
11470
|
+
OR (
|
|
11471
|
+
executor_kind IN ('action', 'pipeline', 'projection', 'rule', 'sync', 'webhook', 'workflow')
|
|
11472
|
+
AND source_kind <> 'script'
|
|
11473
|
+
AND authority_kind = 'trustedPrimitive'
|
|
11474
|
+
AND executor_kind = authority_primitive_kind
|
|
11475
|
+
)
|
|
11476
|
+
OR (
|
|
11477
|
+
executor_kind = 'agent'
|
|
11478
|
+
AND source_kind = 'execution'
|
|
11479
|
+
AND (
|
|
11480
|
+
(
|
|
11481
|
+
authority_kind = 'principal'
|
|
11482
|
+
AND authority_service_account_id IS NOT NULL
|
|
11483
|
+
AND authority_session_id IS NULL
|
|
11484
|
+
AND authority_access_token_id IS NULL
|
|
11485
|
+
)
|
|
11486
|
+
OR (
|
|
11487
|
+
authority_kind = 'principal'
|
|
11488
|
+
AND authority_user_id IS NOT NULL
|
|
11489
|
+
AND num_nonnulls(authority_session_id, authority_access_token_id) = 1
|
|
11490
|
+
)
|
|
11491
|
+
OR authority_kind = 'disabled'
|
|
11492
|
+
)
|
|
11493
|
+
)
|
|
11494
|
+
OR (executor_kind = 'kernel' AND authority_kind = 'kernel' AND source_kind <> 'script')
|
|
11495
|
+
OR (
|
|
11496
|
+
executor_kind = 'script'
|
|
11497
|
+
AND source_kind = 'script'
|
|
11498
|
+
AND authority_kind = 'script'
|
|
11499
|
+
AND requested_by_user_id IS NULL
|
|
11500
|
+
AND requested_by_service_account_id IS NULL
|
|
11501
|
+
)
|
|
11502
|
+
);
|
|
11503
|
+
`;
|
|
11504
|
+
|
|
11505
|
+
// src/migrations/104-artifact-pdfs.sql
|
|
11506
|
+
var _104_artifact_pdfs_default = `-- A designed document printed to PDF, kept under its render key: a hash of what it prints, which
|
|
11507
|
+
-- its version names. Versions that print the same share it, so no artifact owns one and deleting
|
|
11508
|
+
-- an artifact leaves them. The first PDF kept under a key stays. When it could not be printed, why
|
|
11509
|
+
-- is kept in its place, until it prints or someone asks for it again.
|
|
11510
|
+
CREATE TABLE artifact_pdfs (
|
|
11511
|
+
project_id TEXT NOT NULL,
|
|
11512
|
+
render_key TEXT NOT NULL CHECK (length(render_key) > 0),
|
|
11513
|
+
file JSONB,
|
|
11514
|
+
pages INTEGER CHECK (pages > 0),
|
|
11515
|
+
failure TEXT,
|
|
11516
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
11517
|
+
PRIMARY KEY (project_id, render_key),
|
|
11518
|
+
-- A PDF with its pages, or why there is none.
|
|
11519
|
+
CHECK (
|
|
11520
|
+
(failure IS NULL AND file IS NOT NULL AND pages IS NOT NULL)
|
|
11521
|
+
OR (failure IS NOT NULL AND file IS NULL AND pages IS NULL)
|
|
11522
|
+
)
|
|
11523
|
+
);
|
|
11524
|
+
`;
|
|
11525
|
+
|
|
11526
|
+
// src/migrations/105-guest-comment-links.sql
|
|
11527
|
+
var _105_guest_comment_links_default = `-- A guest's comment keeps the shared link they came through, by its grant: whoever opens that link,
|
|
11528
|
+
-- in any session, reads the threads its guests started, and no other. Comments written before take
|
|
11529
|
+
-- it from their session, which keeps its grant.
|
|
11530
|
+
ALTER TABLE artifact_comments ADD COLUMN author_grant_id TEXT;
|
|
11531
|
+
|
|
11532
|
+
UPDATE artifact_comments AS comment
|
|
11533
|
+
SET author_grant_id = session.grant_id
|
|
11534
|
+
FROM share_sessions AS session
|
|
11535
|
+
WHERE comment.author_principal_type = 'guest'
|
|
11536
|
+
AND session.project_id = comment.project_id
|
|
11537
|
+
AND session.id = comment.author_principal_id;
|
|
11538
|
+
|
|
11539
|
+
ALTER TABLE artifact_comments
|
|
11540
|
+
ADD CONSTRAINT artifact_comments_author_grant_check CHECK (
|
|
11541
|
+
(author_principal_type = 'guest') = (author_grant_id IS NOT NULL)
|
|
11542
|
+
AND (author_grant_id IS NULL OR length(author_grant_id) > 0)
|
|
11543
|
+
);
|
|
11544
|
+
`;
|
|
11545
|
+
|
|
11546
|
+
// src/migrations/106-agent-thread-inbox.sql
|
|
11547
|
+
var _106_agent_thread_inbox_default = `-- Mid-run steers and queued follow-up messages held outside \`agent_messages\` until delivered.
|
|
11548
|
+
CREATE TABLE agent_thread_inbox (
|
|
11549
|
+
project_id TEXT NOT NULL,
|
|
11550
|
+
id TEXT NOT NULL CHECK (length(trim(id)) > 0),
|
|
11551
|
+
thread_id TEXT NOT NULL,
|
|
11552
|
+
message_id TEXT NOT NULL CHECK (length(trim(message_id)) > 0),
|
|
11553
|
+
seq INTEGER NOT NULL CHECK (seq > 0),
|
|
11554
|
+
author_principal_type TEXT NOT NULL
|
|
11555
|
+
CHECK (author_principal_type IN ('user', 'serviceAccount', 'system')),
|
|
11556
|
+
author_principal_id TEXT NOT NULL CHECK (length(author_principal_id) > 0),
|
|
11557
|
+
mode TEXT NOT NULL CHECK (mode IN ('steer', 'queue')),
|
|
11558
|
+
parts JSONB NOT NULL,
|
|
11559
|
+
spec JSONB,
|
|
11560
|
+
time_zone TEXT,
|
|
11561
|
+
locale TEXT,
|
|
11562
|
+
immediate BOOLEAN NOT NULL DEFAULT FALSE,
|
|
11563
|
+
-- The request that sent it, whose child execution a turn that starts it runs as.
|
|
11564
|
+
execution_id TEXT,
|
|
11565
|
+
claimed_by_run_id TEXT,
|
|
11566
|
+
claimed_by_token TEXT,
|
|
11567
|
+
claimed_by_step INTEGER,
|
|
11568
|
+
claimed_after_answer BOOLEAN,
|
|
11569
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
11570
|
+
updated_at TIMESTAMPTZ NOT NULL,
|
|
11571
|
+
PRIMARY KEY (project_id, id),
|
|
11572
|
+
UNIQUE (project_id, message_id),
|
|
11573
|
+
UNIQUE (project_id, thread_id, seq),
|
|
11574
|
+
FOREIGN KEY (project_id, thread_id) REFERENCES agent_threads (project_id, id) ON DELETE CASCADE
|
|
11575
|
+
);
|
|
11576
|
+
|
|
11577
|
+
CREATE INDEX idx_agent_thread_inbox_thread_seq
|
|
11578
|
+
ON agent_thread_inbox (project_id, thread_id, seq);
|
|
11579
|
+
|
|
11580
|
+
CREATE INDEX idx_agent_thread_inbox_claimed_run
|
|
11581
|
+
ON agent_thread_inbox (project_id, claimed_by_run_id)
|
|
11582
|
+
WHERE claimed_by_run_id IS NOT NULL;
|
|
11583
|
+
`;
|
|
11584
|
+
|
|
11585
|
+
// src/migrations/107-agent-inbox-edits.sql
|
|
11586
|
+
var _107_agent_inbox_edits_default = `-- An edit sent while a turn runs waits here for that turn to end, then rewinds the thread to the
|
|
11587
|
+
-- message it replaces.
|
|
11588
|
+
ALTER TABLE agent_thread_inbox ADD COLUMN replaces_message_id TEXT;
|
|
11589
|
+
`;
|
|
11590
|
+
|
|
11591
|
+
// src/migrations/108-agent-thread-reads.sql
|
|
11592
|
+
var _108_agent_thread_reads_default = `-- Where each person's reading of a conversation has reached: the seq of the last message they saw.
|
|
11593
|
+
-- Nothing writes here when a message arrives: new ones sit past it until the reader moves it. A
|
|
11594
|
+
-- retry or an edit that deletes messages pulls every place inside them back to just before them,
|
|
11595
|
+
-- because the numbers they held go to what replaces them.
|
|
11596
|
+
CREATE TABLE agent_thread_reads (
|
|
11597
|
+
project_id TEXT NOT NULL,
|
|
11598
|
+
thread_id TEXT NOT NULL,
|
|
11599
|
+
principal_type TEXT NOT NULL CHECK (principal_type = 'user'),
|
|
11600
|
+
principal_id TEXT NOT NULL CHECK (length(principal_id) > 0),
|
|
11601
|
+
through_seq INTEGER NOT NULL CHECK (through_seq >= 0),
|
|
11602
|
+
read_at TIMESTAMPTZ NOT NULL,
|
|
11603
|
+
PRIMARY KEY (project_id, thread_id, principal_type, principal_id),
|
|
11604
|
+
FOREIGN KEY (project_id, thread_id) REFERENCES agent_threads (project_id, id) ON DELETE CASCADE
|
|
11605
|
+
);
|
|
11606
|
+
|
|
11607
|
+
-- Everyone starts caught up: the first deploy must not mark every thread that already existed as
|
|
11608
|
+
-- new. Only a person reads, so an owner that is system code or a service account gets no row; it
|
|
11609
|
+
-- would break the CHECK above. From here on, a participant gets a row when they join, and an
|
|
11610
|
+
-- owner when they first mark the thread read: until then, they read as 0.
|
|
11611
|
+
INSERT INTO agent_thread_reads (
|
|
11612
|
+
project_id,
|
|
11613
|
+
thread_id,
|
|
11614
|
+
principal_type,
|
|
11615
|
+
principal_id,
|
|
11616
|
+
through_seq,
|
|
11617
|
+
read_at
|
|
11618
|
+
)
|
|
11619
|
+
SELECT
|
|
11620
|
+
project_id,
|
|
11621
|
+
id,
|
|
11622
|
+
owner_principal_type,
|
|
11623
|
+
owner_principal_id,
|
|
11624
|
+
COALESCE(
|
|
11625
|
+
(
|
|
11626
|
+
SELECT MAX(seq) FROM agent_messages
|
|
11627
|
+
WHERE agent_messages.project_id = agent_threads.project_id
|
|
11628
|
+
AND agent_messages.thread_id = agent_threads.id
|
|
11629
|
+
),
|
|
11630
|
+
0
|
|
11631
|
+
),
|
|
11632
|
+
now()
|
|
11633
|
+
FROM agent_threads
|
|
11634
|
+
WHERE kind = 'conversation'
|
|
11635
|
+
AND owner_principal_type = 'user'
|
|
11636
|
+
ON CONFLICT DO NOTHING;
|
|
11637
|
+
|
|
11638
|
+
INSERT INTO agent_thread_reads (
|
|
11639
|
+
project_id,
|
|
11640
|
+
thread_id,
|
|
11641
|
+
principal_type,
|
|
11642
|
+
principal_id,
|
|
11643
|
+
through_seq,
|
|
11644
|
+
read_at
|
|
11645
|
+
)
|
|
11646
|
+
SELECT
|
|
11647
|
+
participant.project_id,
|
|
11648
|
+
participant.thread_id,
|
|
11649
|
+
participant.principal_type,
|
|
11650
|
+
participant.principal_id,
|
|
11651
|
+
COALESCE(
|
|
11652
|
+
(
|
|
11653
|
+
SELECT MAX(seq) FROM agent_messages
|
|
11654
|
+
WHERE agent_messages.project_id = thread.project_id
|
|
11655
|
+
AND agent_messages.thread_id = thread.id
|
|
11656
|
+
),
|
|
11657
|
+
0
|
|
11658
|
+
),
|
|
11659
|
+
now()
|
|
11660
|
+
FROM agent_thread_participants AS participant
|
|
11661
|
+
JOIN agent_threads AS thread
|
|
11662
|
+
ON thread.project_id = participant.project_id
|
|
11663
|
+
AND thread.id = participant.thread_id
|
|
11664
|
+
ON CONFLICT DO NOTHING;
|
|
11665
|
+
`;
|
|
11666
|
+
|
|
11667
|
+
// src/migrations/109-sync-run-connections.sql
|
|
11668
|
+
var _109_sync_run_connections_default = `-- A sync of an OAuth connector runs once per connection. The column stays NULL for a sync of a
|
|
11669
|
+
-- static connector, and for runs from before this migration.
|
|
11670
|
+
ALTER TABLE sync_runs ADD COLUMN connection_id TEXT;
|
|
11671
|
+
|
|
11672
|
+
CREATE INDEX idx_sync_runs_project_sync_connection_started
|
|
11673
|
+
ON sync_runs (project_id, sync_id, connection_id, COALESCE(started_at, queued_at) DESC);
|
|
11674
|
+
`;
|
|
11675
|
+
|
|
10690
11676
|
// src/migrations.ts
|
|
10691
11677
|
var POSTGRES_STORAGE_ADAPTER_ID = "SixbPostgresStorage";
|
|
10692
11678
|
function pgSql(id, sqlText) {
|
|
@@ -10955,7 +11941,14 @@ var postgresStorageMigrations = defineMigrations({
|
|
|
10955
11941
|
pgSql("099-object-artifact-refs", _099_object_artifact_refs_default),
|
|
10956
11942
|
pgSql("100-shared-link-guests", _100_shared_link_guests_default),
|
|
10957
11943
|
pgSql("101-connector-connection-owners", _101_connector_connection_owners_default),
|
|
10958
|
-
pgSql("102-user-suspension-source", _102_user_suspension_source_default)
|
|
11944
|
+
pgSql("102-user-suspension-source", _102_user_suspension_source_default),
|
|
11945
|
+
pgSql("103-script-executions", _103_script_executions_default),
|
|
11946
|
+
pgSql("104-artifact-pdfs", _104_artifact_pdfs_default),
|
|
11947
|
+
pgSql("105-guest-comment-links", _105_guest_comment_links_default),
|
|
11948
|
+
pgSql("106-agent-thread-inbox", _106_agent_thread_inbox_default),
|
|
11949
|
+
pgSql("107-agent-inbox-edits", _107_agent_inbox_edits_default),
|
|
11950
|
+
pgSql("108-agent-thread-reads", _108_agent_thread_reads_default),
|
|
11951
|
+
pgSql("109-sync-run-connections", _109_sync_run_connections_default)
|
|
10959
11952
|
]
|
|
10960
11953
|
});
|
|
10961
11954
|
|
|
@@ -16127,6 +17120,38 @@ function revision(kind) {
|
|
|
16127
17120
|
const key = "identities.identity_key";
|
|
16128
17121
|
return kind === "object" ? `${objectRevision(`(${key}::jsonb->>0)`, `(${key}::jsonb->>1)`)}::text` : `${linkRevision(key)}::text`;
|
|
16129
17122
|
}
|
|
17123
|
+
async function planCreatedObjects(sql, input, versionId, objectTypeId) {
|
|
17124
|
+
const rootKey = jsonTupleExpression([
|
|
17125
|
+
`'"object"'`,
|
|
17126
|
+
"to_jsonb(overrides.object_type_id)::text",
|
|
17127
|
+
"to_jsonb(overrides.primary_id)::text"
|
|
17128
|
+
]);
|
|
17129
|
+
const planned = await sql`
|
|
17130
|
+
WITH keyed AS (
|
|
17131
|
+
SELECT ${sql.unsafe(columnKeyExpression(["object_type_id", "primary_id"]))} AS identity_key
|
|
17132
|
+
FROM ontology_object_overrides AS overrides
|
|
17133
|
+
WHERE overrides.project_id = ${input.projectId} AND overrides.object_type_id = ${objectTypeId}
|
|
17134
|
+
AND overrides.value->>'kind' = 'create'
|
|
17135
|
+
AND NOT EXISTS (
|
|
17136
|
+
SELECT 1 FROM ontology_source_roots AS live
|
|
17137
|
+
JOIN ontology_sources AS versions ON versions.version_id = live.version_id
|
|
17138
|
+
WHERE live.project_id = overrides.project_id
|
|
17139
|
+
AND live.root_key = ${sql.unsafe(rootKey)}
|
|
17140
|
+
AND live.retired_at IS NULL AND NOT live.deleted
|
|
17141
|
+
AND versions.source_id = ${input.source.projectionId}
|
|
17142
|
+
AND versions.status IN ${sql.unsafe(PUBLISHED)}
|
|
17143
|
+
)
|
|
17144
|
+
)
|
|
17145
|
+
INSERT INTO ${sql(IDENTITIES)} (
|
|
17146
|
+
version_id, entity_kind, identity_key, sort_key, diff_required, expand_at, source_key,
|
|
17147
|
+
target_key
|
|
17148
|
+
)
|
|
17149
|
+
SELECT ${versionId}, 'object', identity_key, ${sql.unsafe(SORT_KEY)}, TRUE, NULL, NULL, NULL
|
|
17150
|
+
FROM keyed
|
|
17151
|
+
ON CONFLICT DO NOTHING
|
|
17152
|
+
`;
|
|
17153
|
+
return planned.count;
|
|
17154
|
+
}
|
|
16130
17155
|
|
|
16131
17156
|
class PgOntologyReplacementPlanStorage {
|
|
16132
17157
|
sql;
|
|
@@ -16197,7 +17222,8 @@ class PgOntologyReplacementPlanStorage {
|
|
|
16197
17222
|
target_key
|
|
16198
17223
|
FROM keyed
|
|
16199
17224
|
`;
|
|
16200
|
-
|
|
17225
|
+
const created = input.createdObjects ? await planCreatedObjects(sql, input, candidate.version_id, input.createdObjects.objectTypeId) : 0;
|
|
17226
|
+
if (opened.count + created >= ANALYZE_ROWS)
|
|
16201
17227
|
await analyzePlans(sql);
|
|
16202
17228
|
return { committedAt: commit.committedAt };
|
|
16203
17229
|
});
|
|
@@ -20239,6 +21265,7 @@ function pageViewFromRow(row) {
|
|
|
20239
21265
|
}
|
|
20240
21266
|
|
|
20241
21267
|
// src/pg-ai-cost-storage.ts
|
|
21268
|
+
import { wallClockInstant } from "@sixb/core/calendar";
|
|
20242
21269
|
import {
|
|
20243
21270
|
aiAccountingModelKind,
|
|
20244
21271
|
aiModelCallCostDetails,
|
|
@@ -20784,6 +21811,7 @@ class PgAiCostStorage {
|
|
|
20784
21811
|
const query = normalizeAiAccountingQuery(input);
|
|
20785
21812
|
const providerId = query.providerId ?? null;
|
|
20786
21813
|
const modelId = query.modelId ?? null;
|
|
21814
|
+
const timeZone = query.timeZone;
|
|
20787
21815
|
const filter = pgAccountingFilterValues(query);
|
|
20788
21816
|
const rows = await this.sql`
|
|
20789
21817
|
WITH filtered AS (
|
|
@@ -20870,29 +21898,31 @@ class PgAiCostStorage {
|
|
|
20870
21898
|
NULL::text AS key_1,
|
|
20871
21899
|
NULL::text AS key_2,
|
|
20872
21900
|
NULL::text AS key_3,
|
|
20873
|
-
NULL::
|
|
21901
|
+
NULL::text AS bucket_start,
|
|
20874
21902
|
classified.*
|
|
20875
21903
|
FROM classified
|
|
20876
21904
|
UNION ALL
|
|
20877
21905
|
SELECT 'series', NULL, NULL, NULL,
|
|
20878
|
-
|
|
20879
|
-
|
|
20880
|
-
date_trunc('hour', occurred_at AT TIME ZONE
|
|
20881
|
-
|
|
20882
|
-
date_trunc('
|
|
20883
|
-
|
|
20884
|
-
|
|
21906
|
+
to_char(
|
|
21907
|
+
CASE ${input.bucket}::text
|
|
21908
|
+
WHEN 'hour' THEN date_trunc('hour', occurred_at AT TIME ZONE ${timeZone})
|
|
21909
|
+
WHEN 'day' THEN date_trunc('day', occurred_at AT TIME ZONE ${timeZone})
|
|
21910
|
+
ELSE date_trunc('week', occurred_at AT TIME ZONE ${timeZone})
|
|
21911
|
+
END,
|
|
21912
|
+
'YYYY-MM-DD"T"HH24:MI:SS"Z"'
|
|
21913
|
+
),
|
|
20885
21914
|
classified.*
|
|
20886
21915
|
FROM classified
|
|
20887
21916
|
UNION ALL
|
|
20888
21917
|
SELECT 'modelSeries', provider_id, requested_model_id, NULL,
|
|
20889
|
-
|
|
20890
|
-
|
|
20891
|
-
date_trunc('hour', occurred_at AT TIME ZONE
|
|
20892
|
-
|
|
20893
|
-
date_trunc('
|
|
20894
|
-
|
|
20895
|
-
|
|
21918
|
+
to_char(
|
|
21919
|
+
CASE ${input.bucket}::text
|
|
21920
|
+
WHEN 'hour' THEN date_trunc('hour', occurred_at AT TIME ZONE ${timeZone})
|
|
21921
|
+
WHEN 'day' THEN date_trunc('day', occurred_at AT TIME ZONE ${timeZone})
|
|
21922
|
+
ELSE date_trunc('week', occurred_at AT TIME ZONE ${timeZone})
|
|
21923
|
+
END,
|
|
21924
|
+
'YYYY-MM-DD"T"HH24:MI:SS"Z"'
|
|
21925
|
+
),
|
|
20896
21926
|
classified.*
|
|
20897
21927
|
FROM classified
|
|
20898
21928
|
UNION ALL
|
|
@@ -20958,7 +21988,7 @@ class PgAiCostStorage {
|
|
|
20958
21988
|
FROM expanded
|
|
20959
21989
|
GROUP BY dimension, key_1, key_2, key_3, bucket_start, amount_currency
|
|
20960
21990
|
`;
|
|
20961
|
-
return buildAiAccountingOverviewFromFragments(input, rows.map(aggregateFragmentFromRow));
|
|
21991
|
+
return buildAiAccountingOverviewFromFragments(input, rows.map((row) => aggregateFragmentFromRow(row, timeZone)));
|
|
20962
21992
|
}
|
|
20963
21993
|
async listModelCalls(input) {
|
|
20964
21994
|
const query = normalizeAiModelCallAccountingQuery2(input);
|
|
@@ -21116,15 +22146,15 @@ async function findUsage(sql, projectId, id) {
|
|
|
21116
22146
|
`;
|
|
21117
22147
|
return row ? usageFromRow2(row, []) : null;
|
|
21118
22148
|
}
|
|
21119
|
-
function aggregateFragmentFromRow(row) {
|
|
22149
|
+
function aggregateFragmentFromRow(row, timeZone) {
|
|
21120
22150
|
const dimensionKeys = row.dimension === "model" ? { providerId: required2(row.key_1), modelId: required2(row.key_2) } : row.dimension === "modelSeries" ? {
|
|
21121
22151
|
providerId: required2(row.key_1),
|
|
21122
22152
|
modelId: required2(row.key_2),
|
|
21123
|
-
start:
|
|
22153
|
+
start: wallClockInstant(required2(row.bucket_start), timeZone)
|
|
21124
22154
|
} : row.dimension === "person" ? row.key_1 && row.key_2 ? { requesterType: row.key_1, requesterId: row.key_2 } : {} : row.dimension === "kind" ? withModelKind(aiAccountingModelKind(row.key_1)) : row.dimension === "agent" ? {
|
|
21125
22155
|
agentKind: required2(row.key_1),
|
|
21126
22156
|
...row.key_1 === "workflowAgent" ? { workflowId: required2(row.key_2), agentStepId: required2(row.key_3) } : {}
|
|
21127
|
-
} : row.dimension === "workflow" ? { workflowId: required2(row.key_1) } : row.dimension === "series" ? { start:
|
|
22157
|
+
} : row.dimension === "workflow" ? { workflowId: required2(row.key_1) } : row.dimension === "series" ? { start: wallClockInstant(required2(row.bucket_start), timeZone) } : {};
|
|
21128
22158
|
return {
|
|
21129
22159
|
dimension: row.dimension,
|
|
21130
22160
|
...dimensionKeys,
|
|
@@ -21982,6 +23012,7 @@ import {
|
|
|
21982
23012
|
parseArtifactBoardPreviewRow,
|
|
21983
23013
|
parseArtifactCommentRow,
|
|
21984
23014
|
parseArtifactFrameGrantRow,
|
|
23015
|
+
parseArtifactPdfRow,
|
|
21985
23016
|
parseArtifactRestorePointRow,
|
|
21986
23017
|
parseArtifactRow,
|
|
21987
23018
|
parseArtifactStateRow,
|
|
@@ -22018,7 +23049,8 @@ var FRAME_GRANT_COLUMNS = `
|
|
|
22018
23049
|
var COMMENT_COLUMNS = `
|
|
22019
23050
|
project_id AS "projectId", artifact_id AS "artifactId", id, parent_id AS "parentId", anchor,
|
|
22020
23051
|
body, author_principal_type AS "authorPrincipalType", author_principal_id AS "authorPrincipalId",
|
|
22021
|
-
author_name AS "authorName",
|
|
23052
|
+
author_name AS "authorName", author_grant_id AS "authorGrantId",
|
|
23053
|
+
created_at AS "createdAt", resolved_at AS "resolvedAt",
|
|
22022
23054
|
resolved_by_principal_type AS "resolvedByPrincipalType",
|
|
22023
23055
|
resolved_by_principal_id AS "resolvedByPrincipalId",
|
|
22024
23056
|
origin_thread_id AS "originThreadId", origin_run_id AS "originRunId"
|
|
@@ -22028,6 +23060,10 @@ var BOARD_PREVIEW_COLUMNS = `
|
|
|
22028
23060
|
project_id AS "projectId", render_key AS "renderKey", theme, size, file,
|
|
22029
23061
|
created_at AS "createdAt"
|
|
22030
23062
|
`;
|
|
23063
|
+
var PDF_COLUMNS = `
|
|
23064
|
+
project_id AS "projectId", render_key AS "renderKey", file, pages, failure,
|
|
23065
|
+
created_at AS "createdAt"
|
|
23066
|
+
`;
|
|
22031
23067
|
|
|
22032
23068
|
class PgArtifactStorage {
|
|
22033
23069
|
sql;
|
|
@@ -22195,7 +23231,8 @@ class PgArtifactStorage {
|
|
|
22195
23231
|
}
|
|
22196
23232
|
async undoTurnWrites(input) {
|
|
22197
23233
|
return runPgTransaction(this.sql, async (tx) => {
|
|
22198
|
-
const { projectId, turnRunId } = input;
|
|
23234
|
+
const { projectId, turnRunId, laterTurnRunIds = [] } = input;
|
|
23235
|
+
const later = tx.array([...laterTurnRunIds]);
|
|
22199
23236
|
await tx`
|
|
22200
23237
|
SELECT id FROM artifacts
|
|
22201
23238
|
WHERE project_id = ${projectId} AND id IN (
|
|
@@ -22207,7 +23244,10 @@ class PgArtifactStorage {
|
|
|
22207
23244
|
`;
|
|
22208
23245
|
const rows = await tx`
|
|
22209
23246
|
SELECT w.artifact_id AS "artifactId", w.created, w.revision, w.writes,
|
|
22210
|
-
a.revision AS "currentRevision"
|
|
23247
|
+
a.revision AS "currentRevision",
|
|
23248
|
+
(SELECT COALESCE(SUM(l.writes), 0) FROM artifact_turn_writes l
|
|
23249
|
+
WHERE l.project_id = w.project_id AND l.artifact_id = w.artifact_id
|
|
23250
|
+
AND l.turn_run_id = ANY(${later}::text[])) AS "laterWrites"
|
|
22211
23251
|
FROM artifact_turn_writes w
|
|
22212
23252
|
JOIN artifacts a ON a.project_id = w.project_id AND a.id = w.artifact_id
|
|
22213
23253
|
WHERE w.project_id = ${projectId} AND w.turn_run_id = ${turnRunId}
|
|
@@ -22216,7 +23256,8 @@ class PgArtifactStorage {
|
|
|
22216
23256
|
const restored = [];
|
|
22217
23257
|
const deleted = [];
|
|
22218
23258
|
for (const row of rows) {
|
|
22219
|
-
const
|
|
23259
|
+
const own = parseArtifactTurnWriteRow(row);
|
|
23260
|
+
const write = { ...own, writes: own.writes + Number(row.laterWrites) };
|
|
22220
23261
|
const revision = Number(row.currentRevision);
|
|
22221
23262
|
if (write.created) {
|
|
22222
23263
|
if (!turnUndoable({ write, revision }))
|
|
@@ -22237,14 +23278,20 @@ class PgArtifactStorage {
|
|
|
22237
23278
|
}
|
|
22238
23279
|
if (restored.length > 0) {
|
|
22239
23280
|
const undone = restored.map(({ artifact }) => artifact.id);
|
|
23281
|
+
const turns = tx.array([turnRunId, ...laterTurnRunIds]);
|
|
22240
23282
|
await tx`
|
|
22241
23283
|
DELETE FROM artifact_restore_points
|
|
22242
|
-
WHERE project_id = ${projectId} AND turn_run_id = ${
|
|
23284
|
+
WHERE project_id = ${projectId} AND turn_run_id = ANY(${turns}::text[])
|
|
22243
23285
|
AND artifact_id IN ${tx(undone)}
|
|
22244
23286
|
`;
|
|
22245
23287
|
await tx`
|
|
22246
23288
|
DELETE FROM artifact_threads
|
|
22247
|
-
WHERE project_id = ${projectId} AND linked_by_run_id = ${
|
|
23289
|
+
WHERE project_id = ${projectId} AND linked_by_run_id = ANY(${turns}::text[])
|
|
23290
|
+
AND NOT copied AND artifact_id IN ${tx(undone)}
|
|
23291
|
+
`;
|
|
23292
|
+
await tx`
|
|
23293
|
+
DELETE FROM artifact_turn_writes
|
|
23294
|
+
WHERE project_id = ${projectId} AND turn_run_id = ANY(${later}::text[])
|
|
22248
23295
|
AND artifact_id IN ${tx(undone)}
|
|
22249
23296
|
`;
|
|
22250
23297
|
}
|
|
@@ -22545,6 +23592,35 @@ class PgArtifactStorage {
|
|
|
22545
23592
|
}
|
|
22546
23593
|
});
|
|
22547
23594
|
}
|
|
23595
|
+
async getPdf(input) {
|
|
23596
|
+
const [row] = await this.sql`
|
|
23597
|
+
SELECT ${this.sql.unsafe(PDF_COLUMNS)} FROM artifact_pdfs
|
|
23598
|
+
WHERE project_id = ${input.projectId} AND render_key = ${input.renderKey}
|
|
23599
|
+
`;
|
|
23600
|
+
return row ? parseArtifactPdfRow(row) : null;
|
|
23601
|
+
}
|
|
23602
|
+
async putPdf(input) {
|
|
23603
|
+
const printed = "failure" in input ? null : input;
|
|
23604
|
+
await this.sql`
|
|
23605
|
+
INSERT INTO artifact_pdfs (project_id, render_key, file, pages, failure, created_at)
|
|
23606
|
+
VALUES (
|
|
23607
|
+
${input.projectId}, ${input.renderKey},
|
|
23608
|
+
${printed ? JSON.stringify(printed.file) : null}::text::jsonb, ${printed?.pages ?? null},
|
|
23609
|
+
${"failure" in input ? input.failure : null}, ${input.createdAt}
|
|
23610
|
+
)
|
|
23611
|
+
ON CONFLICT (project_id, render_key) DO UPDATE SET
|
|
23612
|
+
file = excluded.file, pages = excluded.pages, failure = NULL,
|
|
23613
|
+
created_at = excluded.created_at
|
|
23614
|
+
WHERE artifact_pdfs.failure IS NOT NULL AND excluded.failure IS NULL
|
|
23615
|
+
`;
|
|
23616
|
+
}
|
|
23617
|
+
async clearPdfFailure(input) {
|
|
23618
|
+
await this.sql`
|
|
23619
|
+
DELETE FROM artifact_pdfs
|
|
23620
|
+
WHERE project_id = ${input.projectId} AND render_key = ${input.renderKey}
|
|
23621
|
+
AND failure IS NOT NULL
|
|
23622
|
+
`;
|
|
23623
|
+
}
|
|
22548
23624
|
async createComment(input) {
|
|
22549
23625
|
return runPgTransaction(this.sql, async (tx) => {
|
|
22550
23626
|
if (!await lockArtifact(tx, input.projectId, input.artifactId)) {
|
|
@@ -22571,15 +23647,17 @@ class PgArtifactStorage {
|
|
|
22571
23647
|
if (input.author.type === "guest" && (counted?.guests ?? 0) >= ARTIFACT_COMMENT_LIMITS.maxGuestComments) {
|
|
22572
23648
|
throw artifactStorageErrors.guestCommentsFull(input.artifactId);
|
|
22573
23649
|
}
|
|
23650
|
+
const guest = input.author.type === "guest" ? input.author : undefined;
|
|
22574
23651
|
const [row] = await tx`
|
|
22575
23652
|
INSERT INTO artifact_comments (
|
|
22576
23653
|
project_id, artifact_id, id, parent_id, anchor, body, author_principal_type,
|
|
22577
|
-
author_principal_id, author_name, created_at, origin_thread_id,
|
|
23654
|
+
author_principal_id, author_name, author_grant_id, created_at, origin_thread_id,
|
|
23655
|
+
origin_run_id
|
|
22578
23656
|
) VALUES (
|
|
22579
23657
|
${input.projectId}, ${input.artifactId}, ${input.id}, ${input.parentId ?? null},
|
|
22580
23658
|
${JSON.stringify(commentAnchor(input.anchor))}::text::jsonb, ${input.body},
|
|
22581
23659
|
${input.author.type}, ${input.author.id},
|
|
22582
|
-
${
|
|
23660
|
+
${guest?.name ?? null}, ${guest?.grantId ?? null}, ${input.createdAt},
|
|
22583
23661
|
${input.origin?.threadId ?? null}, ${input.origin?.runId ?? null}
|
|
22584
23662
|
)
|
|
22585
23663
|
RETURNING ${tx.unsafe(COMMENT_COLUMNS)}
|
|
@@ -23500,11 +24578,16 @@ async function queryLatestRunsByOwnerId(input) {
|
|
|
23500
24578
|
parameters.push(input.excludedStatus);
|
|
23501
24579
|
statusFilter = ` AND status <> $${parameters.length}`;
|
|
23502
24580
|
}
|
|
24581
|
+
const bind = (value) => {
|
|
24582
|
+
parameters.push(value);
|
|
24583
|
+
return `$${parameters.length}`;
|
|
24584
|
+
};
|
|
24585
|
+
const filter = input.filter === undefined ? "" : ` AND ${input.filter(bind)}`;
|
|
23503
24586
|
const orderColumn = input.tableName === "sync_runs" || input.tableName === "pipeline_runs" || input.tableName === "projection_runs" ? "COALESCE(started_at, queued_at)" : "started_at";
|
|
23504
24587
|
const rows = await input.sql.unsafe(`
|
|
23505
24588
|
SELECT DISTINCT ON (${input.ownerColumn}) ${input.selectList ?? "*"}
|
|
23506
24589
|
FROM ${input.tableName}
|
|
23507
|
-
WHERE project_id = $1 AND ${input.ownerColumn} IN (${placeholders})${statusFilter}
|
|
24590
|
+
WHERE project_id = $1 AND ${input.ownerColumn} IN (${placeholders})${statusFilter}${filter}
|
|
23508
24591
|
ORDER BY ${input.ownerColumn}, ${orderColumn} DESC, id DESC
|
|
23509
24592
|
`, parameters);
|
|
23510
24593
|
const latestByOwnerId = new Map(rows.map((row) => [input.ownerIdFor(row), row]));
|
|
@@ -24823,6 +25906,7 @@ class PgSyncRunStorage {
|
|
|
24823
25906
|
id,
|
|
24824
25907
|
execution_id,
|
|
24825
25908
|
sync_id,
|
|
25909
|
+
connection_id,
|
|
24826
25910
|
dataset_id,
|
|
24827
25911
|
mode,
|
|
24828
25912
|
status,
|
|
@@ -24835,6 +25919,7 @@ class PgSyncRunStorage {
|
|
|
24835
25919
|
${input.id},
|
|
24836
25920
|
${input.executionId},
|
|
24837
25921
|
${input.syncId},
|
|
25922
|
+
${input.connectionId ?? null},
|
|
24838
25923
|
${input.datasetId},
|
|
24839
25924
|
${input.mode},
|
|
24840
25925
|
${"queued"},
|
|
@@ -24985,6 +26070,18 @@ class PgSyncRunStorage {
|
|
|
24985
26070
|
whereClauses.push(`sync_id IN (${placeholders.join(", ")})`);
|
|
24986
26071
|
params.push(...input.syncIds);
|
|
24987
26072
|
}
|
|
26073
|
+
if (input.connectionId === null) {
|
|
26074
|
+
whereClauses.push("connection_id IS NULL");
|
|
26075
|
+
} else if (input.connectionId !== undefined) {
|
|
26076
|
+
whereClauses.push(`connection_id = $${index++}`);
|
|
26077
|
+
params.push(input.connectionId);
|
|
26078
|
+
}
|
|
26079
|
+
if (input.visibleConnectionIds) {
|
|
26080
|
+
whereClauses.push(visibleConnectionsClause(input.visibleConnectionIds, (value) => {
|
|
26081
|
+
params.push(value);
|
|
26082
|
+
return `$${index++}`;
|
|
26083
|
+
}));
|
|
26084
|
+
}
|
|
24988
26085
|
if (input.datasetId) {
|
|
24989
26086
|
whereClauses.push(`dataset_id = $${index++}`);
|
|
24990
26087
|
params.push(input.datasetId);
|
|
@@ -25008,6 +26105,7 @@ class PgSyncRunStorage {
|
|
|
25008
26105
|
};
|
|
25009
26106
|
}
|
|
25010
26107
|
async listLatestBySyncIds(input) {
|
|
26108
|
+
const { visibleConnectionIds } = input;
|
|
25011
26109
|
const rows = await queryLatestRunsByOwnerId({
|
|
25012
26110
|
sql: this.sql,
|
|
25013
26111
|
tableName: "sync_runs",
|
|
@@ -25015,12 +26113,38 @@ class PgSyncRunStorage {
|
|
|
25015
26113
|
ownerIds: input.syncIds,
|
|
25016
26114
|
projectId: input.projectId,
|
|
25017
26115
|
ownerIdFor: (row) => row.sync_id,
|
|
25018
|
-
selectList: "*, checkpoint IS NOT NULL AS checkpoint_present"
|
|
26116
|
+
selectList: "*, checkpoint IS NOT NULL AS checkpoint_present",
|
|
26117
|
+
...visibleConnectionIds === undefined ? {} : { filter: (bind) => visibleConnectionsClause(visibleConnectionIds, bind) }
|
|
25019
26118
|
});
|
|
25020
26119
|
return {
|
|
25021
26120
|
runs: rows.map(rowToSyncRunRecord)
|
|
25022
26121
|
};
|
|
25023
26122
|
}
|
|
26123
|
+
async listLatestByConnection(input) {
|
|
26124
|
+
if (input.syncIds.length === 0 || input.connectionIds?.length === 0)
|
|
26125
|
+
return { runs: [] };
|
|
26126
|
+
const params = [input.projectId];
|
|
26127
|
+
const placeholders = (values) => values.map((value) => {
|
|
26128
|
+
params.push(value);
|
|
26129
|
+
return `$${params.length}`;
|
|
26130
|
+
}).join(", ");
|
|
26131
|
+
const syncFilter = `sync_id IN (${placeholders(input.syncIds)})`;
|
|
26132
|
+
const connectionFilter = input.connectionIds === undefined ? "connection_id IS NOT NULL" : `connection_id IN (${placeholders(input.connectionIds)})`;
|
|
26133
|
+
const rows = await this.sql.unsafe(`
|
|
26134
|
+
SELECT DISTINCT ON (sync_id, connection_id)
|
|
26135
|
+
*, checkpoint IS NOT NULL AS checkpoint_present
|
|
26136
|
+
FROM sync_runs
|
|
26137
|
+
WHERE project_id = $1 AND ${syncFilter} AND ${connectionFilter}
|
|
26138
|
+
ORDER BY sync_id, connection_id, COALESCE(started_at, queued_at) DESC, id DESC
|
|
26139
|
+
`, params);
|
|
26140
|
+
return { runs: rows.map(rowToSyncRunRecord) };
|
|
26141
|
+
}
|
|
26142
|
+
}
|
|
26143
|
+
function visibleConnectionsClause(connectionIds, bind) {
|
|
26144
|
+
if (connectionIds.length === 0)
|
|
26145
|
+
return "connection_id IS NULL";
|
|
26146
|
+
const placeholders = connectionIds.map((id) => bind(id)).join(", ");
|
|
26147
|
+
return `(connection_id IS NULL OR connection_id IN (${placeholders}))`;
|
|
25024
26148
|
}
|
|
25025
26149
|
function staleExecution2(id) {
|
|
25026
26150
|
return new SyncRunError(`[SixbPg] Execution token is no longer current on sync run '${id}'.`);
|
|
@@ -25037,6 +26161,7 @@ function rowToSyncRunRecord(row) {
|
|
|
25037
26161
|
projectId: row.project_id,
|
|
25038
26162
|
executionId: row.execution_id,
|
|
25039
26163
|
syncId: row.sync_id,
|
|
26164
|
+
...row.connection_id === null ? {} : { connectionId: row.connection_id },
|
|
25040
26165
|
datasetId: row.dataset_id,
|
|
25041
26166
|
mode: row.mode,
|
|
25042
26167
|
status: row.status,
|
|
@@ -26281,8 +27406,8 @@ function rowToWorkflowAgentNodeRunRecord(row) {
|
|
|
26281
27406
|
prompt: row.prompt,
|
|
26282
27407
|
...row.model_id ? { modelId: row.model_id } : {},
|
|
26283
27408
|
...row.finish_reason ? { finishReason: row.finish_reason } : {},
|
|
26284
|
-
...row.trace ? { trace:
|
|
26285
|
-
...row.diagnostics ? { diagnostics:
|
|
27409
|
+
...row.trace ? { trace: parseJson3(row.trace) } : {},
|
|
27410
|
+
...row.diagnostics ? { diagnostics: parseJson3(row.diagnostics) } : {},
|
|
26286
27411
|
...row.error ? { error: parseSixbFailure7(row.error, AGENT_RUN_FAILURE_CODES3) } : {},
|
|
26287
27412
|
attempt: Number(row.attempt),
|
|
26288
27413
|
...row.execution_token && row.execution_queue_lease_expires_at ? {
|
|
@@ -26296,7 +27421,7 @@ function rowToWorkflowAgentNodeRunRecord(row) {
|
|
|
26296
27421
|
...row.completed_at ? { completedAt: new Date(row.completed_at) } : {}
|
|
26297
27422
|
};
|
|
26298
27423
|
}
|
|
26299
|
-
function
|
|
27424
|
+
function parseJson3(value) {
|
|
26300
27425
|
return typeof value === "string" ? JSON.parse(value) : value;
|
|
26301
27426
|
}
|
|
26302
27427
|
function assertWorkflowRunExecutionOwnership(row, token) {
|
|
@@ -26864,4 +27989,4 @@ export {
|
|
|
26864
27989
|
migratePostgresStorage
|
|
26865
27990
|
};
|
|
26866
27991
|
|
|
26867
|
-
//# debugId=
|
|
27992
|
+
//# debugId=63365A4D0CD9409564756E2164756E21
|