@truefoundry/trueforge 0.183.0 → 0.183.2
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/controller-main.js +1023 -56
- package/dist/controller-main.js.map +1 -1
- package/dist/main.js +633 -118
- package/dist/main.js.map +1 -1
- package/dist/postgres/migrations/20260727_000001_init.js +45 -1
- package/dist/postgres/migrations/20260727_000001_init.js.map +1 -1
- package/dist/postgres/migrations/20261030_000001_memory_ingest_cursor.js +15 -0
- package/dist/postgres/migrations/20261030_000001_memory_ingest_cursor.js.map +1 -0
- package/dist/sqlite/migrations/20261030_000001_memory_ingest_cursor.js +25 -0
- package/dist/sqlite/migrations/20261030_000001_memory_ingest_cursor.js.map +1 -0
- package/package.json +2 -2
package/dist/controller-main.js
CHANGED
|
@@ -198,6 +198,16 @@ function parsePublicBaseUrl(raw) {
|
|
|
198
198
|
const path3 = segments.length === 0 ? "" : `/${segments.join("/")}`;
|
|
199
199
|
return `${parsed.origin}${path3}`;
|
|
200
200
|
}
|
|
201
|
+
function parseTrueFoundryMemoryProvider(raw) {
|
|
202
|
+
if (raw === void 0 || raw.trim() === "") {
|
|
203
|
+
return void 0;
|
|
204
|
+
}
|
|
205
|
+
const value = raw.trim();
|
|
206
|
+
if (value === "zep") {
|
|
207
|
+
return value;
|
|
208
|
+
}
|
|
209
|
+
throw new Error(`Environment variable TRUEFOUNDRY_MEMORY_PROVIDER must be "zep", got ${JSON.stringify(raw)}`);
|
|
210
|
+
}
|
|
201
211
|
function parseTrueFoundrySandboxProvider(raw) {
|
|
202
212
|
if (raw === void 0 || raw.trim() === "") {
|
|
203
213
|
return void 0;
|
|
@@ -757,7 +767,22 @@ var configuration = standalone ? {
|
|
|
757
767
|
getEnv("TRUEFOUNDRY_WEB_SEARCH_PROVIDER", { required: false })
|
|
758
768
|
),
|
|
759
769
|
TRUEFOUNDRY_AUTH_SERVER_URL: getEnv("TRUEFOUNDRY_AUTH_SERVER_URL", { required: false }),
|
|
760
|
-
TRUEFOUNDRY_TENANT_NAME: getEnv("TRUEFOUNDRY_TENANT_NAME", { required: false })
|
|
770
|
+
TRUEFOUNDRY_TENANT_NAME: getEnv("TRUEFOUNDRY_TENANT_NAME", { required: false }),
|
|
771
|
+
TRUEFOUNDRY_MEMORY_ENABLED: parseBoolean({
|
|
772
|
+
envKey: "TRUEFOUNDRY_MEMORY_ENABLED",
|
|
773
|
+
raw: getEnv("TRUEFOUNDRY_MEMORY_ENABLED"),
|
|
774
|
+
defaultValue: false
|
|
775
|
+
}),
|
|
776
|
+
TRUEFOUNDRY_MEMORY_PROVIDER: parseTrueFoundryMemoryProvider(
|
|
777
|
+
getEnv("TRUEFOUNDRY_MEMORY_PROVIDER", { required: false })
|
|
778
|
+
),
|
|
779
|
+
TRUEFOUNDRY_MEMORY_API_KEY: getEnv("TRUEFOUNDRY_MEMORY_API_KEY", { required: false }),
|
|
780
|
+
TRUEFOUNDRY_MEMORY_SERVER_URL: getEnv("TRUEFOUNDRY_MEMORY_SERVER_URL", { required: false }),
|
|
781
|
+
TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST: parseJsonStringArrayEnv({
|
|
782
|
+
envKey: "TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST",
|
|
783
|
+
raw: getEnv("TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST")
|
|
784
|
+
}),
|
|
785
|
+
TRUEFOUNDRY_MEMORY_SETTINGS: getEnv("TRUEFOUNDRY_MEMORY_SETTINGS", { required: false })
|
|
761
786
|
};
|
|
762
787
|
function isOidcConfigured(value) {
|
|
763
788
|
return !value.STANDALONE && value.OIDC !== void 0;
|
|
@@ -801,6 +826,25 @@ if (isTrueFoundryModeEnabled(configuration)) {
|
|
|
801
826
|
);
|
|
802
827
|
}
|
|
803
828
|
}
|
|
829
|
+
if (configuration.TRUEFOUNDRY_MEMORY_ENABLED) {
|
|
830
|
+
if (configuration.TRUEFOUNDRY_MEMORY_PROVIDER === void 0) {
|
|
831
|
+
throw new Error(
|
|
832
|
+
'TRUEFOUNDRY_MEMORY_ENABLED is true but TRUEFOUNDRY_MEMORY_PROVIDER is not set. Set TRUEFOUNDRY_MEMORY_PROVIDER to "zep", or set TRUEFOUNDRY_MEMORY_ENABLED=false.'
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
if (configuration.TRUEFOUNDRY_MEMORY_API_KEY === void 0) {
|
|
836
|
+
throw new Error(
|
|
837
|
+
"TRUEFOUNDRY_MEMORY_PROVIDER=zep requires TRUEFOUNDRY_MEMORY_API_KEY, or set TRUEFOUNDRY_MEMORY_ENABLED=false."
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
if (configuration.TRUEFOUNDRY_MEMORY_SETTINGS !== void 0) {
|
|
841
|
+
try {
|
|
842
|
+
JSON.parse(configuration.TRUEFOUNDRY_MEMORY_SETTINGS);
|
|
843
|
+
} catch (error) {
|
|
844
|
+
throw new Error("TRUEFOUNDRY_MEMORY_SETTINGS must be valid JSON", { cause: error });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
804
848
|
}
|
|
805
849
|
if (!configuration.STANDALONE && configuration.TRUEFORGE_API_KEY.trim() === "") {
|
|
806
850
|
throw new Error("TRUEFORGE_API_KEY must not be empty when STANDALONE=false.");
|
|
@@ -905,6 +949,822 @@ var Controller = class {
|
|
|
905
949
|
}
|
|
906
950
|
};
|
|
907
951
|
|
|
952
|
+
// src/memory/zep/ZepMemoryProvider.ts
|
|
953
|
+
import { z as z2 } from "zod";
|
|
954
|
+
|
|
955
|
+
// src/memory/MemoryProvider.ts
|
|
956
|
+
var MemoryIngestError = class extends Error {
|
|
957
|
+
externalThreadId;
|
|
958
|
+
constructor({
|
|
959
|
+
message,
|
|
960
|
+
externalThreadId,
|
|
961
|
+
cause
|
|
962
|
+
}) {
|
|
963
|
+
super(message, { cause });
|
|
964
|
+
this.name = "MemoryIngestError";
|
|
965
|
+
this.externalThreadId = externalThreadId;
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
|
|
969
|
+
// src/memory/scope.ts
|
|
970
|
+
import { createHash } from "crypto";
|
|
971
|
+
var DEFAULT_MEMORY_AGENT_KEY = "trueforge";
|
|
972
|
+
var UI_SESSION_SOURCE = "ui";
|
|
973
|
+
function memoryScopeKey({
|
|
974
|
+
tenantId,
|
|
975
|
+
agentKey,
|
|
976
|
+
subjectId
|
|
977
|
+
}) {
|
|
978
|
+
const digest = createHash("sha256").update(JSON.stringify([tenantId, agentKey, subjectId])).digest("hex");
|
|
979
|
+
return `tfg-${digest}`;
|
|
980
|
+
}
|
|
981
|
+
function resolveMemoryScope(session) {
|
|
982
|
+
if (session.createAgentSession) {
|
|
983
|
+
return void 0;
|
|
984
|
+
}
|
|
985
|
+
const tenantId = session.tenantId;
|
|
986
|
+
const subjectId = session.createdBySubject.subject_id;
|
|
987
|
+
if (session.agentId !== null) {
|
|
988
|
+
if (!session.agentMemoryEnabled) {
|
|
989
|
+
return void 0;
|
|
990
|
+
}
|
|
991
|
+
return {
|
|
992
|
+
type: "agent",
|
|
993
|
+
tenantId,
|
|
994
|
+
subjectId,
|
|
995
|
+
agentId: session.agentId,
|
|
996
|
+
key: memoryScopeKey({ tenantId, agentKey: session.agentId, subjectId })
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
if (session.tfgSource !== UI_SESSION_SOURCE) {
|
|
1000
|
+
return void 0;
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
type: "default",
|
|
1004
|
+
tenantId,
|
|
1005
|
+
subjectId,
|
|
1006
|
+
agentId: null,
|
|
1007
|
+
key: memoryScopeKey({ tenantId, agentKey: DEFAULT_MEMORY_AGENT_KEY, subjectId })
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// src/memory/zep/ZepMemoryProvider.ts
|
|
1012
|
+
var ZEP_DEFAULT_BASE_URL = "https://api.getzep.com/api/v4";
|
|
1013
|
+
var PROVIDER_NAME = "zep";
|
|
1014
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
1015
|
+
var DEFAULT_MAX_ATTEMPTS = 4;
|
|
1016
|
+
var BASE_BACKOFF_MS = 500;
|
|
1017
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
1018
|
+
var ZepUuidResponseSchema = z2.object({ uuid: z2.string().min(1) });
|
|
1019
|
+
var ZepMessagesResponseSchema = z2.object({
|
|
1020
|
+
items: z2.array(z2.object({ metadata: z2.record(z2.string(), z2.unknown()).nullish() }))
|
|
1021
|
+
});
|
|
1022
|
+
var ZepRequestError = class extends Error {
|
|
1023
|
+
operation;
|
|
1024
|
+
/** HTTP status; null when no response arrived (network error or timeout). */
|
|
1025
|
+
status;
|
|
1026
|
+
constructor({
|
|
1027
|
+
operation,
|
|
1028
|
+
status,
|
|
1029
|
+
message,
|
|
1030
|
+
cause
|
|
1031
|
+
}) {
|
|
1032
|
+
super(message, { cause });
|
|
1033
|
+
this.name = "ZepRequestError";
|
|
1034
|
+
this.operation = operation;
|
|
1035
|
+
this.status = status;
|
|
1036
|
+
}
|
|
1037
|
+
};
|
|
1038
|
+
function isRetryableStatus(status) {
|
|
1039
|
+
return status === 429 || status >= 500;
|
|
1040
|
+
}
|
|
1041
|
+
function retryAfterMs(response) {
|
|
1042
|
+
const header = response.headers.get("retry-after");
|
|
1043
|
+
if (header === null) {
|
|
1044
|
+
return void 0;
|
|
1045
|
+
}
|
|
1046
|
+
const seconds = Number(header);
|
|
1047
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
1048
|
+
return seconds * 1e3;
|
|
1049
|
+
}
|
|
1050
|
+
const date = Date.parse(header);
|
|
1051
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
1052
|
+
}
|
|
1053
|
+
function speakerId(scope, role) {
|
|
1054
|
+
return role === "user" ? scope.subjectId : scope.agentId ?? DEFAULT_MEMORY_AGENT_KEY;
|
|
1055
|
+
}
|
|
1056
|
+
function ignoredRoles(messages) {
|
|
1057
|
+
const roles = new Set(messages.map((message) => message.role));
|
|
1058
|
+
return [...roles].filter((role) => messages.every((message) => message.role !== role || !message.extract));
|
|
1059
|
+
}
|
|
1060
|
+
var ZepMemoryProvider = class {
|
|
1061
|
+
name = PROVIDER_NAME;
|
|
1062
|
+
#apiKey;
|
|
1063
|
+
#baseUrl;
|
|
1064
|
+
#logger;
|
|
1065
|
+
#fetch;
|
|
1066
|
+
#sleep;
|
|
1067
|
+
#timeoutMs;
|
|
1068
|
+
#maxAttempts;
|
|
1069
|
+
/** Scope key → Zep user uuid; users are never deleted by ingestion. */
|
|
1070
|
+
#userUuids = /* @__PURE__ */ new Map();
|
|
1071
|
+
constructor(options) {
|
|
1072
|
+
this.#apiKey = options.apiKey;
|
|
1073
|
+
this.#baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
1074
|
+
this.#logger = options.logger;
|
|
1075
|
+
this.#fetch = options.fetch ?? fetch;
|
|
1076
|
+
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1077
|
+
this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1078
|
+
this.#maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
1079
|
+
}
|
|
1080
|
+
async ingestExchange(input) {
|
|
1081
|
+
const { scope, exchange } = input;
|
|
1082
|
+
if (exchange.messages.length === 0) {
|
|
1083
|
+
throw new Error(`Exchange ending at turn ${exchange.lastTurnId} has no messages`);
|
|
1084
|
+
}
|
|
1085
|
+
const roles = ignoredRoles(exchange.messages);
|
|
1086
|
+
const body = {
|
|
1087
|
+
messages: exchange.messages.map((message) => ({
|
|
1088
|
+
role: message.role,
|
|
1089
|
+
name: speakerId(scope, message.role),
|
|
1090
|
+
content: message.content,
|
|
1091
|
+
reference_time: message.createdAt,
|
|
1092
|
+
metadata: {
|
|
1093
|
+
session_id: exchange.sessionId,
|
|
1094
|
+
last_turn_id: exchange.lastTurnId,
|
|
1095
|
+
scope: scope.type
|
|
1096
|
+
}
|
|
1097
|
+
})),
|
|
1098
|
+
...roles.length === 0 ? {} : { ignore_roles: roles }
|
|
1099
|
+
};
|
|
1100
|
+
let threadId = input.externalThreadId;
|
|
1101
|
+
try {
|
|
1102
|
+
if (threadId !== null && input.mayAlreadyBeStored && await this.#threadHasExchange(threadId, exchange)) {
|
|
1103
|
+
this.#logger.info("Memory exchange already stored by an earlier attempt; not resending", {
|
|
1104
|
+
provider: PROVIDER_NAME,
|
|
1105
|
+
session_id: exchange.sessionId,
|
|
1106
|
+
last_turn_id: exchange.lastTurnId
|
|
1107
|
+
});
|
|
1108
|
+
return { externalThreadId: threadId };
|
|
1109
|
+
}
|
|
1110
|
+
threadId ??= await this.#createThread(scope);
|
|
1111
|
+
const sent = await this.#addMessages({ threadId, body, allowNotFound: input.externalThreadId !== null });
|
|
1112
|
+
if (sent.status === 404) {
|
|
1113
|
+
threadId = await this.#createThread(scope);
|
|
1114
|
+
await this.#addMessages({ threadId, body, allowNotFound: false });
|
|
1115
|
+
}
|
|
1116
|
+
return { externalThreadId: threadId };
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
throw new MemoryIngestError({
|
|
1119
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1120
|
+
externalThreadId: threadId,
|
|
1121
|
+
cause: error
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Adding messages isn't idempotent, and Zep doesn't deduplicate by metadata. A timeout or 5xx may
|
|
1127
|
+
* have stored them, so it isn't retried here: the caller retries next run, flagged
|
|
1128
|
+
* `mayAlreadyBeStored`, which checks the thread first. A 429 is a rejection and is retried.
|
|
1129
|
+
*/
|
|
1130
|
+
async #addMessages({
|
|
1131
|
+
threadId,
|
|
1132
|
+
body,
|
|
1133
|
+
allowNotFound
|
|
1134
|
+
}) {
|
|
1135
|
+
return await this.#request({
|
|
1136
|
+
operation: "add_messages",
|
|
1137
|
+
path: `/threads/${encodeURIComponent(threadId)}/messages`,
|
|
1138
|
+
body,
|
|
1139
|
+
allowNotFound,
|
|
1140
|
+
retryUnclearFailures: false
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Whether the thread's newest messages already include this exchange, matched by its metadata.
|
|
1145
|
+
* TODO(memory-idempotency): see `IngestExchangeInput.mayAlreadyBeStored`.
|
|
1146
|
+
*/
|
|
1147
|
+
async #threadHasExchange(threadId, exchange) {
|
|
1148
|
+
const query = new URLSearchParams({
|
|
1149
|
+
order_by: "created_at",
|
|
1150
|
+
order: "desc",
|
|
1151
|
+
page_size: String(exchange.messages.length)
|
|
1152
|
+
});
|
|
1153
|
+
const listed = await this.#request({
|
|
1154
|
+
operation: "list_messages",
|
|
1155
|
+
method: "GET",
|
|
1156
|
+
path: `/threads/${encodeURIComponent(threadId)}/messages?${query.toString()}`,
|
|
1157
|
+
allowNotFound: true
|
|
1158
|
+
});
|
|
1159
|
+
if (listed.status === 404) {
|
|
1160
|
+
return false;
|
|
1161
|
+
}
|
|
1162
|
+
return ZepMessagesResponseSchema.parse(listed.body).items.some(
|
|
1163
|
+
({ metadata }) => metadata?.["session_id"] === exchange.sessionId && metadata["last_turn_id"] === exchange.lastTurnId
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
async #createThread(scope) {
|
|
1167
|
+
const userUuid = await this.#userUuid(scope);
|
|
1168
|
+
const created = await this.#request({
|
|
1169
|
+
operation: "create_thread",
|
|
1170
|
+
path: "/threads",
|
|
1171
|
+
body: { user_uuid: userUuid }
|
|
1172
|
+
});
|
|
1173
|
+
return ZepUuidResponseSchema.parse(created.body).uuid;
|
|
1174
|
+
}
|
|
1175
|
+
async #userUuid(scope) {
|
|
1176
|
+
const cached = this.#userUuids.get(scope.key);
|
|
1177
|
+
if (cached !== void 0) {
|
|
1178
|
+
return cached;
|
|
1179
|
+
}
|
|
1180
|
+
const uuid = await this.#lookupUser(scope) ?? await this.#createUser(scope);
|
|
1181
|
+
this.#userUuids.set(scope.key, uuid);
|
|
1182
|
+
return uuid;
|
|
1183
|
+
}
|
|
1184
|
+
async #lookupUser(scope) {
|
|
1185
|
+
const found = await this.#request({
|
|
1186
|
+
operation: "lookup_user",
|
|
1187
|
+
path: "/users/lookup",
|
|
1188
|
+
body: { user_id: scope.key },
|
|
1189
|
+
allowNotFound: true
|
|
1190
|
+
});
|
|
1191
|
+
return found.status === 404 ? void 0 : ZepUuidResponseSchema.parse(found.body).uuid;
|
|
1192
|
+
}
|
|
1193
|
+
async #createUser(scope) {
|
|
1194
|
+
try {
|
|
1195
|
+
const created = await this.#request({
|
|
1196
|
+
operation: "create_user",
|
|
1197
|
+
path: "/users",
|
|
1198
|
+
body: {
|
|
1199
|
+
user_id: scope.key,
|
|
1200
|
+
// An id, never a display name: no person's name reaches Zep.
|
|
1201
|
+
first_name: scope.subjectId,
|
|
1202
|
+
// Maps the Zep user back to its TrueForge user and scope.
|
|
1203
|
+
metadata: {
|
|
1204
|
+
tenant_id: scope.tenantId,
|
|
1205
|
+
subject_id: scope.subjectId,
|
|
1206
|
+
agent_id: scope.agentId,
|
|
1207
|
+
scope_type: scope.type
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
});
|
|
1211
|
+
return ZepUuidResponseSchema.parse(created.body).uuid;
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
if (error instanceof ZepRequestError && (error.status === 400 || error.status === 409)) {
|
|
1214
|
+
const uuid = await this.#lookupUser(scope);
|
|
1215
|
+
if (uuid !== void 0) {
|
|
1216
|
+
return uuid;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
throw error;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
async #request({
|
|
1223
|
+
operation,
|
|
1224
|
+
method = "POST",
|
|
1225
|
+
path: path3,
|
|
1226
|
+
body,
|
|
1227
|
+
allowNotFound = false,
|
|
1228
|
+
retryUnclearFailures = true
|
|
1229
|
+
}) {
|
|
1230
|
+
for (let attempt = 1; ; attempt++) {
|
|
1231
|
+
const startedAt = Date.now();
|
|
1232
|
+
const logFields = (status) => ({
|
|
1233
|
+
provider: PROVIDER_NAME,
|
|
1234
|
+
operation,
|
|
1235
|
+
status,
|
|
1236
|
+
duration_ms: Date.now() - startedAt,
|
|
1237
|
+
attempt
|
|
1238
|
+
});
|
|
1239
|
+
const canRetry = attempt < this.#maxAttempts;
|
|
1240
|
+
const backoffMs = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** (attempt - 1));
|
|
1241
|
+
let response;
|
|
1242
|
+
let text;
|
|
1243
|
+
try {
|
|
1244
|
+
response = await this.#fetch(`${this.#baseUrl}${path3}`, {
|
|
1245
|
+
method,
|
|
1246
|
+
headers: { Authorization: `Api-Key ${this.#apiKey}`, "Content-Type": "application/json" },
|
|
1247
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
1248
|
+
signal: AbortSignal.timeout(this.#timeoutMs)
|
|
1249
|
+
});
|
|
1250
|
+
text = await response.text();
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1253
|
+
if (canRetry && retryUnclearFailures) {
|
|
1254
|
+
this.#logger.warn("Memory provider request failed; retrying", { ...logFields(null), error: message });
|
|
1255
|
+
await this.#sleep(backoffMs);
|
|
1256
|
+
continue;
|
|
1257
|
+
}
|
|
1258
|
+
this.#logger.error("Memory provider request failed", { ...logFields(null), error: message });
|
|
1259
|
+
throw new ZepRequestError({
|
|
1260
|
+
operation,
|
|
1261
|
+
status: null,
|
|
1262
|
+
message: `Zep ${operation} failed: ${message}`,
|
|
1263
|
+
cause: error
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
if (response.ok || allowNotFound && response.status === 404) {
|
|
1267
|
+
this.#logger.debug("Memory provider request", logFields(response.status));
|
|
1268
|
+
return { status: response.status, body: text === "" ? {} : JSON.parse(text) };
|
|
1269
|
+
}
|
|
1270
|
+
const detail = text.slice(0, 500);
|
|
1271
|
+
const retryable = response.status === 429 || retryUnclearFailures && isRetryableStatus(response.status);
|
|
1272
|
+
const waitMs = retryAfterMs(response) ?? backoffMs;
|
|
1273
|
+
if (retryable && canRetry && waitMs <= MAX_BACKOFF_MS) {
|
|
1274
|
+
this.#logger.warn("Memory provider request failed; retrying", logFields(response.status));
|
|
1275
|
+
await this.#sleep(waitMs);
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1278
|
+
this.#logger.error("Memory provider request failed", { ...logFields(response.status), error: detail });
|
|
1279
|
+
throw new ZepRequestError({
|
|
1280
|
+
operation,
|
|
1281
|
+
status: response.status,
|
|
1282
|
+
message: `Zep ${operation} returned ${String(response.status)}: ${detail}`
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
// src/memory/createMemoryProvider.ts
|
|
1289
|
+
function createMemoryProvider({ config, logger }) {
|
|
1290
|
+
switch (config.type) {
|
|
1291
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- one provider today; more get a case here
|
|
1292
|
+
case "zep":
|
|
1293
|
+
return new ZepMemoryProvider({ apiKey: config.apiKey, baseUrl: config.serverUrl, logger });
|
|
1294
|
+
default: {
|
|
1295
|
+
const _exhaustive = config.type;
|
|
1296
|
+
throw new Error(`Unsupported memory provider: ${String(_exhaustive)}`);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// src/memory/exchanges.ts
|
|
1302
|
+
import { ASK_USER_QUESTION_TOOL_NAME } from "@truefoundry/trueforge-core/core";
|
|
1303
|
+
var MAX_MEMORY_MESSAGE_CHARS = 4e3;
|
|
1304
|
+
var TRUNCATION_MARKER = " [truncated]";
|
|
1305
|
+
function hasUserMessage(turn) {
|
|
1306
|
+
return turn.input.some((item) => item.type === "user.message");
|
|
1307
|
+
}
|
|
1308
|
+
function statusAfter(state) {
|
|
1309
|
+
switch (state.status) {
|
|
1310
|
+
case "running":
|
|
1311
|
+
case "paused":
|
|
1312
|
+
return "running";
|
|
1313
|
+
case "done":
|
|
1314
|
+
return state.required_actions.length === 0 ? "closed" : "paused";
|
|
1315
|
+
case "error":
|
|
1316
|
+
case "cancelled":
|
|
1317
|
+
return "closed";
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
function activePath({
|
|
1321
|
+
turns,
|
|
1322
|
+
tipTurnId
|
|
1323
|
+
}) {
|
|
1324
|
+
const byId = new Map(turns.map((turn) => [turn.turn_id, turn]));
|
|
1325
|
+
const path3 = [];
|
|
1326
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1327
|
+
let current = byId.get(tipTurnId);
|
|
1328
|
+
while (current !== void 0 && !seen.has(current.turn_id)) {
|
|
1329
|
+
seen.add(current.turn_id);
|
|
1330
|
+
path3.push(current);
|
|
1331
|
+
current = current.previous_turn_id === null ? void 0 : byId.get(current.previous_turn_id);
|
|
1332
|
+
}
|
|
1333
|
+
return path3.reverse();
|
|
1334
|
+
}
|
|
1335
|
+
function buildExchanges(turns) {
|
|
1336
|
+
const exchanges = [];
|
|
1337
|
+
let current;
|
|
1338
|
+
for (const turn of turns) {
|
|
1339
|
+
if (current !== void 0 && hasUserMessage(turn)) {
|
|
1340
|
+
current.status = "closed";
|
|
1341
|
+
current.completedAt ??= turn.created_at;
|
|
1342
|
+
current = void 0;
|
|
1343
|
+
}
|
|
1344
|
+
if (current === void 0) {
|
|
1345
|
+
current = {
|
|
1346
|
+
turns: [turn],
|
|
1347
|
+
status: statusAfter(turn.state),
|
|
1348
|
+
completedAt: completedAt(turn.state),
|
|
1349
|
+
continuation: !hasUserMessage(turn)
|
|
1350
|
+
};
|
|
1351
|
+
exchanges.push(current);
|
|
1352
|
+
} else {
|
|
1353
|
+
current.turns.push(turn);
|
|
1354
|
+
current.status = statusAfter(turn.state);
|
|
1355
|
+
current.completedAt = completedAt(turn.state);
|
|
1356
|
+
}
|
|
1357
|
+
if (current.status === "closed") {
|
|
1358
|
+
current = void 0;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
return exchanges;
|
|
1362
|
+
}
|
|
1363
|
+
function resumePoint({
|
|
1364
|
+
path: path3,
|
|
1365
|
+
turns,
|
|
1366
|
+
lastIngestedTurnId
|
|
1367
|
+
}) {
|
|
1368
|
+
if (lastIngestedTurnId === null) {
|
|
1369
|
+
return { startIndex: 0, forked: false };
|
|
1370
|
+
}
|
|
1371
|
+
const pathIndex = new Map(path3.map((turn, index) => [turn.turn_id, index]));
|
|
1372
|
+
const ingestedIndex = pathIndex.get(lastIngestedTurnId);
|
|
1373
|
+
if (ingestedIndex !== void 0) {
|
|
1374
|
+
return { startIndex: ingestedIndex + 1, forked: false };
|
|
1375
|
+
}
|
|
1376
|
+
const byId = new Map(turns.map((turn) => [turn.turn_id, turn]));
|
|
1377
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1378
|
+
let forkIndex;
|
|
1379
|
+
let current = byId.get(lastIngestedTurnId);
|
|
1380
|
+
while (current !== void 0 && !seen.has(current.turn_id) && forkIndex === void 0) {
|
|
1381
|
+
seen.add(current.turn_id);
|
|
1382
|
+
current = current.previous_turn_id === null ? void 0 : byId.get(current.previous_turn_id);
|
|
1383
|
+
forkIndex = current === void 0 ? void 0 : pathIndex.get(current.turn_id);
|
|
1384
|
+
}
|
|
1385
|
+
return { startIndex: forkIndex === void 0 ? 0 : forkIndex + 1, forked: true };
|
|
1386
|
+
}
|
|
1387
|
+
function completedAt(state) {
|
|
1388
|
+
return state.status === "done" || state.status === "error" || state.status === "cancelled" ? state.completed_at : null;
|
|
1389
|
+
}
|
|
1390
|
+
function exchangeReadiness({
|
|
1391
|
+
exchange,
|
|
1392
|
+
now: now2,
|
|
1393
|
+
pauseTimeoutMs
|
|
1394
|
+
}) {
|
|
1395
|
+
const finishedAt = exchange.completedAt;
|
|
1396
|
+
if (exchange.status === "running" || finishedAt === null) {
|
|
1397
|
+
return { ready: false };
|
|
1398
|
+
}
|
|
1399
|
+
if (exchange.status === "closed") {
|
|
1400
|
+
return { ready: true, partial: false };
|
|
1401
|
+
}
|
|
1402
|
+
return now2.getTime() - Date.parse(finishedAt) >= pauseTimeoutMs ? { ready: true, partial: true } : { ready: false };
|
|
1403
|
+
}
|
|
1404
|
+
function askUserQuestionsByToolCallId(messages) {
|
|
1405
|
+
const questions = /* @__PURE__ */ new Map();
|
|
1406
|
+
for (const message of messages) {
|
|
1407
|
+
for (const call of message.tool_calls ?? []) {
|
|
1408
|
+
if (call.function.name !== ASK_USER_QUESTION_TOOL_NAME) {
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
const question = parseQuestion(call.function.arguments);
|
|
1412
|
+
if (question !== void 0) {
|
|
1413
|
+
questions.set(call.id, question);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return questions;
|
|
1418
|
+
}
|
|
1419
|
+
function parseQuestion(rawArguments) {
|
|
1420
|
+
try {
|
|
1421
|
+
const parsed = JSON.parse(rawArguments);
|
|
1422
|
+
if (typeof parsed === "object" && parsed !== null && "question" in parsed && typeof parsed.question === "string") {
|
|
1423
|
+
const question = parsed.question.trim();
|
|
1424
|
+
return question === "" ? void 0 : question;
|
|
1425
|
+
}
|
|
1426
|
+
} catch {
|
|
1427
|
+
}
|
|
1428
|
+
return void 0;
|
|
1429
|
+
}
|
|
1430
|
+
function modelMessageText(content) {
|
|
1431
|
+
if (content === void 0 || content === null) {
|
|
1432
|
+
return "";
|
|
1433
|
+
}
|
|
1434
|
+
if (typeof content === "string") {
|
|
1435
|
+
return content.trim();
|
|
1436
|
+
}
|
|
1437
|
+
return content.map((part) => part.type === "text" ? part.text : part.refusal).join("").trim();
|
|
1438
|
+
}
|
|
1439
|
+
function capped(text) {
|
|
1440
|
+
return text.length <= MAX_MEMORY_MESSAGE_CHARS ? text : text.slice(0, MAX_MEMORY_MESSAGE_CHARS - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
1441
|
+
}
|
|
1442
|
+
function renderExchange({
|
|
1443
|
+
exchange,
|
|
1444
|
+
questions
|
|
1445
|
+
}) {
|
|
1446
|
+
const messages = [];
|
|
1447
|
+
const user = (content, createdAt) => {
|
|
1448
|
+
if (content !== "") {
|
|
1449
|
+
messages.push({ role: "user", content: capped(content), createdAt, extract: true });
|
|
1450
|
+
}
|
|
1451
|
+
};
|
|
1452
|
+
for (const turn of exchange.turns) {
|
|
1453
|
+
for (const item of turn.input) {
|
|
1454
|
+
if (item.type === "user.message") {
|
|
1455
|
+
const text = typeof item.content === "string" ? item.content : item.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n");
|
|
1456
|
+
user(text.trim(), turn.created_at);
|
|
1457
|
+
} else if (item.type === "user.tool_response") {
|
|
1458
|
+
const question = questions.get(item.tool_call_id);
|
|
1459
|
+
const answer = item.content.trim();
|
|
1460
|
+
if (question !== void 0 && answer !== "") {
|
|
1461
|
+
user(`(Answering "${question}") ${answer}`, turn.created_at);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
const last = exchange.turns[exchange.turns.length - 1];
|
|
1467
|
+
if (exchange.status === "closed" && last?.state.status === "done" && last.state.output !== null) {
|
|
1468
|
+
const reply = modelMessageText(last.state.output.content);
|
|
1469
|
+
if (reply !== "") {
|
|
1470
|
+
messages.push({
|
|
1471
|
+
role: "assistant",
|
|
1472
|
+
content: capped(reply),
|
|
1473
|
+
createdAt: last.state.completed_at,
|
|
1474
|
+
extract: false
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
return messages;
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
// src/memory/MemorySettings.ts
|
|
1482
|
+
var TenantAllowlistMemorySettings = class {
|
|
1483
|
+
#tenantIds;
|
|
1484
|
+
constructor(options) {
|
|
1485
|
+
this.#tenantIds = options.tenantIds.length === 0 ? void 0 : [...new Set(options.tenantIds)];
|
|
1486
|
+
}
|
|
1487
|
+
listEnabledTenantIds() {
|
|
1488
|
+
return Promise.resolve(this.#tenantIds);
|
|
1489
|
+
}
|
|
1490
|
+
};
|
|
1491
|
+
|
|
1492
|
+
// src/truefoundry/resolveTrueFoundryMemoryProviderConfig.ts
|
|
1493
|
+
import { z as z3 } from "zod";
|
|
1494
|
+
var TrueFoundryMemorySettingsSchema = z3.object({
|
|
1495
|
+
/** Gap between ingest runs. */
|
|
1496
|
+
interval_ms: z3.number().int().positive().default(5 * 60 * 1e3),
|
|
1497
|
+
/** Sessions processed per run. */
|
|
1498
|
+
max_sessions_per_run: z3.number().int().positive().default(50),
|
|
1499
|
+
/** Exchanges sent per session per run. */
|
|
1500
|
+
max_exchanges_per_session: z3.number().int().positive().default(20),
|
|
1501
|
+
/** How far back a session's latest turn is picked up; sessions not ingested by then are dropped. */
|
|
1502
|
+
lookback_ms: z3.number().int().positive().default(2 * 60 * 60 * 1e3),
|
|
1503
|
+
/**
|
|
1504
|
+
* An exchange paused on the user (a question, approval or auth) is sent as-is after this long.
|
|
1505
|
+
* Paused sessions are looked up again in a lookback-wide range this far back.
|
|
1506
|
+
*/
|
|
1507
|
+
pause_timeout_ms: z3.number().int().positive().default(12 * 60 * 60 * 1e3)
|
|
1508
|
+
}).strict();
|
|
1509
|
+
function parseSettingsJson(raw) {
|
|
1510
|
+
if (raw === void 0) {
|
|
1511
|
+
return {};
|
|
1512
|
+
}
|
|
1513
|
+
try {
|
|
1514
|
+
return JSON.parse(raw);
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
throw new Error("TRUEFOUNDRY_MEMORY_SETTINGS must be valid JSON", { cause: error });
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
function resolveTrueFoundryMemoryProviderConfig(config) {
|
|
1520
|
+
if (!config.TRUEFOUNDRY_MEMORY_ENABLED) {
|
|
1521
|
+
return void 0;
|
|
1522
|
+
}
|
|
1523
|
+
const settings = TrueFoundryMemorySettingsSchema.parse(parseSettingsJson(config.TRUEFOUNDRY_MEMORY_SETTINGS));
|
|
1524
|
+
switch (config.TRUEFOUNDRY_MEMORY_PROVIDER) {
|
|
1525
|
+
case "zep": {
|
|
1526
|
+
if (config.TRUEFOUNDRY_MEMORY_API_KEY === void 0) {
|
|
1527
|
+
throw new Error("TRUEFOUNDRY_MEMORY_API_KEY is required when TRUEFOUNDRY_MEMORY_PROVIDER is zep");
|
|
1528
|
+
}
|
|
1529
|
+
return {
|
|
1530
|
+
type: "zep",
|
|
1531
|
+
apiKey: config.TRUEFOUNDRY_MEMORY_API_KEY,
|
|
1532
|
+
serverUrl: config.TRUEFOUNDRY_MEMORY_SERVER_URL ?? ZEP_DEFAULT_BASE_URL,
|
|
1533
|
+
settings
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
case void 0:
|
|
1537
|
+
return void 0;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// src/controller/memoryIngest.ts
|
|
1542
|
+
var MEMORY_INGEST_LOOP_NAME = "memory-ingest";
|
|
1543
|
+
function errorMessage(error) {
|
|
1544
|
+
return error instanceof Error ? error.message : String(error);
|
|
1545
|
+
}
|
|
1546
|
+
function readyExchanges({
|
|
1547
|
+
exchanges,
|
|
1548
|
+
now: now2,
|
|
1549
|
+
config
|
|
1550
|
+
}) {
|
|
1551
|
+
const ready = [];
|
|
1552
|
+
for (const exchange of exchanges) {
|
|
1553
|
+
if (ready.length === config.maxExchangesPerSession || !exchangeReadiness({ exchange, now: now2, pauseTimeoutMs: config.pauseTimeoutMs }).ready) {
|
|
1554
|
+
break;
|
|
1555
|
+
}
|
|
1556
|
+
ready.push(exchange);
|
|
1557
|
+
}
|
|
1558
|
+
return ready;
|
|
1559
|
+
}
|
|
1560
|
+
async function ingestSession({
|
|
1561
|
+
candidate,
|
|
1562
|
+
scope,
|
|
1563
|
+
deps,
|
|
1564
|
+
signal
|
|
1565
|
+
}) {
|
|
1566
|
+
const { store, provider, logger, config, now: now2 } = deps;
|
|
1567
|
+
const { cursor } = candidate;
|
|
1568
|
+
const logFields = {
|
|
1569
|
+
session_id: candidate.session_id,
|
|
1570
|
+
tenant_id: candidate.tenant_id,
|
|
1571
|
+
scope_type: scope.type,
|
|
1572
|
+
agent_id: candidate.agent_id
|
|
1573
|
+
};
|
|
1574
|
+
let threadId = cursor?.external_thread_id ?? null;
|
|
1575
|
+
let lastIngestedTurnId = cursor?.last_ingested_turn_id ?? null;
|
|
1576
|
+
const turns = await store.listSessionTurns({ session_id: candidate.session_id });
|
|
1577
|
+
const path3 = activePath({ turns, tipTurnId: candidate.tip_turn_id });
|
|
1578
|
+
const { startIndex, forked } = resumePoint({ path: path3, turns, lastIngestedTurnId });
|
|
1579
|
+
if (forked) {
|
|
1580
|
+
logger.warn("Memory checkpoint is off the active path; resuming after the fork point", {
|
|
1581
|
+
...logFields,
|
|
1582
|
+
last_ingested_turn_id: lastIngestedTurnId
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
const ready = readyExchanges({ exchanges: buildExchanges(path3.slice(startIndex)), now: now2(), config });
|
|
1586
|
+
if (ready.length === 0) {
|
|
1587
|
+
return { outcome: "not_ready", exchangesSent: 0, exchangesFailed: 0 };
|
|
1588
|
+
}
|
|
1589
|
+
const previous = path3[startIndex - 1];
|
|
1590
|
+
const turnIds = [
|
|
1591
|
+
...previous === void 0 ? [] : [previous.turn_id],
|
|
1592
|
+
...ready.flatMap((e) => e.turns.map((t) => t.turn_id))
|
|
1593
|
+
];
|
|
1594
|
+
const modelMessages = await store.listMainThreadModelMessages({
|
|
1595
|
+
session_id: candidate.session_id,
|
|
1596
|
+
turn_ids: turnIds
|
|
1597
|
+
});
|
|
1598
|
+
const questions = askUserQuestionsByToolCallId(modelMessages.map((entry) => entry.message));
|
|
1599
|
+
let exchangesSent = 0;
|
|
1600
|
+
let mayAlreadyBeStored = cursor !== null && cursor.last_error !== null;
|
|
1601
|
+
for (const exchange of ready) {
|
|
1602
|
+
if (signal.aborted) {
|
|
1603
|
+
break;
|
|
1604
|
+
}
|
|
1605
|
+
const firstTurnId = exchange.turns[0].turn_id;
|
|
1606
|
+
const lastTurnId = exchange.turns[exchange.turns.length - 1]?.turn_id ?? firstTurnId;
|
|
1607
|
+
const messages = renderExchange({ exchange, questions });
|
|
1608
|
+
try {
|
|
1609
|
+
if (messages.length > 0) {
|
|
1610
|
+
const sent = await provider.ingestExchange({
|
|
1611
|
+
scope,
|
|
1612
|
+
exchange: { sessionId: candidate.session_id, lastTurnId, messages },
|
|
1613
|
+
externalThreadId: threadId,
|
|
1614
|
+
mayAlreadyBeStored
|
|
1615
|
+
});
|
|
1616
|
+
threadId = sent.externalThreadId;
|
|
1617
|
+
mayAlreadyBeStored = false;
|
|
1618
|
+
exchangesSent += 1;
|
|
1619
|
+
}
|
|
1620
|
+
} catch (error) {
|
|
1621
|
+
if (error instanceof MemoryIngestError && error.externalThreadId !== null) {
|
|
1622
|
+
threadId = error.externalThreadId;
|
|
1623
|
+
}
|
|
1624
|
+
const lastError = errorMessage(error);
|
|
1625
|
+
logger.error("Memory ingest failed for session", {
|
|
1626
|
+
...logFields,
|
|
1627
|
+
exchanges_sent: exchangesSent,
|
|
1628
|
+
last_error: lastError,
|
|
1629
|
+
reportable_error: { error, extra: { ...logFields, first_turn_id: firstTurnId, last_turn_id: lastTurnId } }
|
|
1630
|
+
});
|
|
1631
|
+
await store.upsertCursor({
|
|
1632
|
+
session_id: candidate.session_id,
|
|
1633
|
+
last_ingested_turn_id: lastIngestedTurnId,
|
|
1634
|
+
external_thread_id: threadId,
|
|
1635
|
+
last_error: lastError.slice(0, 1e3)
|
|
1636
|
+
});
|
|
1637
|
+
return { outcome: "failed", exchangesSent, exchangesFailed: 1 };
|
|
1638
|
+
}
|
|
1639
|
+
lastIngestedTurnId = lastTurnId;
|
|
1640
|
+
await store.upsertCursor({
|
|
1641
|
+
session_id: candidate.session_id,
|
|
1642
|
+
last_ingested_turn_id: lastIngestedTurnId,
|
|
1643
|
+
external_thread_id: threadId,
|
|
1644
|
+
last_error: null
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
logger.debug("Memory ingest session finished", { ...logFields, exchanges_sent: exchangesSent });
|
|
1648
|
+
return { outcome: "ingested", exchangesSent, exchangesFailed: 0 };
|
|
1649
|
+
}
|
|
1650
|
+
async function runMemoryIngestPass({
|
|
1651
|
+
deps,
|
|
1652
|
+
signal
|
|
1653
|
+
}) {
|
|
1654
|
+
const { store, settings, logger, config, now: now2 } = deps;
|
|
1655
|
+
const startedAt = now2();
|
|
1656
|
+
const startedMs = startedAt.getTime();
|
|
1657
|
+
const tenantIds = await settings.listEnabledTenantIds();
|
|
1658
|
+
const listed = tenantIds?.length === 0 ? [] : await store.listCandidateSessions({
|
|
1659
|
+
tenant_ids: tenantIds,
|
|
1660
|
+
recent_since: new Date(startedMs - config.lookbackMs),
|
|
1661
|
+
paused_from: new Date(startedMs - config.pauseTimeoutMs - config.lookbackMs),
|
|
1662
|
+
paused_until: new Date(startedMs - config.pauseTimeoutMs),
|
|
1663
|
+
limit: config.maxSessionsPerRun + 1
|
|
1664
|
+
});
|
|
1665
|
+
const backlog = listed.length > config.maxSessionsPerRun;
|
|
1666
|
+
const candidates = listed.slice(0, config.maxSessionsPerRun);
|
|
1667
|
+
const outcomes = {};
|
|
1668
|
+
let exchangesSent = 0;
|
|
1669
|
+
let exchangesFailed = 0;
|
|
1670
|
+
let sessionsProcessed = 0;
|
|
1671
|
+
for (const candidate of candidates) {
|
|
1672
|
+
if (signal.aborted) {
|
|
1673
|
+
break;
|
|
1674
|
+
}
|
|
1675
|
+
sessionsProcessed += 1;
|
|
1676
|
+
const result = await processCandidate({ candidate, deps, signal });
|
|
1677
|
+
outcomes[result.outcome] = (outcomes[result.outcome] ?? 0) + 1;
|
|
1678
|
+
exchangesSent += result.exchangesSent;
|
|
1679
|
+
exchangesFailed += result.exchangesFailed;
|
|
1680
|
+
}
|
|
1681
|
+
const summary = {
|
|
1682
|
+
sessions: sessionsProcessed,
|
|
1683
|
+
backlog,
|
|
1684
|
+
sessions_by_outcome: outcomes,
|
|
1685
|
+
exchanges_sent: exchangesSent,
|
|
1686
|
+
exchanges_failed: exchangesFailed,
|
|
1687
|
+
duration_ms: now2().getTime() - startedAt.getTime()
|
|
1688
|
+
};
|
|
1689
|
+
if (exchangesSent > 0 || exchangesFailed > 0 || backlog) {
|
|
1690
|
+
logger.info("Memory ingest run finished", summary);
|
|
1691
|
+
} else {
|
|
1692
|
+
logger.debug("Memory ingest run finished", summary);
|
|
1693
|
+
}
|
|
1694
|
+
return summary;
|
|
1695
|
+
}
|
|
1696
|
+
async function processCandidate({
|
|
1697
|
+
candidate,
|
|
1698
|
+
deps,
|
|
1699
|
+
signal
|
|
1700
|
+
}) {
|
|
1701
|
+
const { logger } = deps;
|
|
1702
|
+
const skipped = (outcome) => ({
|
|
1703
|
+
outcome,
|
|
1704
|
+
exchangesSent: 0,
|
|
1705
|
+
exchangesFailed: 0
|
|
1706
|
+
});
|
|
1707
|
+
const scope = resolveMemoryScope({
|
|
1708
|
+
tenantId: candidate.tenant_id,
|
|
1709
|
+
createdBySubject: candidate.created_by_subject,
|
|
1710
|
+
agentId: candidate.agent_id,
|
|
1711
|
+
agentMemoryEnabled: candidate.agent_memory_enabled,
|
|
1712
|
+
tfgSource: candidate.tfg_source,
|
|
1713
|
+
createAgentSession: candidate.create_agent_session
|
|
1714
|
+
});
|
|
1715
|
+
if (scope === void 0) {
|
|
1716
|
+
return skipped("memory_disabled");
|
|
1717
|
+
}
|
|
1718
|
+
try {
|
|
1719
|
+
return await ingestSession({ candidate, scope, deps, signal });
|
|
1720
|
+
} catch (error) {
|
|
1721
|
+
logger.error("Memory ingest failed for session", {
|
|
1722
|
+
session_id: candidate.session_id,
|
|
1723
|
+
tenant_id: candidate.tenant_id,
|
|
1724
|
+
scope_type: scope.type,
|
|
1725
|
+
agent_id: candidate.agent_id,
|
|
1726
|
+
last_error: errorMessage(error),
|
|
1727
|
+
reportable_error: { error, extra: { session_id: candidate.session_id, tenant_id: candidate.tenant_id } }
|
|
1728
|
+
});
|
|
1729
|
+
return skipped("failed");
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
function memoryIngestFromConfig({
|
|
1733
|
+
config,
|
|
1734
|
+
store,
|
|
1735
|
+
logger
|
|
1736
|
+
}) {
|
|
1737
|
+
const providerConfig = resolveTrueFoundryMemoryProviderConfig(config);
|
|
1738
|
+
if (providerConfig === void 0) {
|
|
1739
|
+
return void 0;
|
|
1740
|
+
}
|
|
1741
|
+
const { settings } = providerConfig;
|
|
1742
|
+
return {
|
|
1743
|
+
store,
|
|
1744
|
+
provider: createMemoryProvider({ config: providerConfig, logger }),
|
|
1745
|
+
settings: new TenantAllowlistMemorySettings({ tenantIds: config.TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST }),
|
|
1746
|
+
config: {
|
|
1747
|
+
intervalMs: settings.interval_ms,
|
|
1748
|
+
maxSessionsPerRun: settings.max_sessions_per_run,
|
|
1749
|
+
maxExchangesPerSession: settings.max_exchanges_per_session,
|
|
1750
|
+
lookbackMs: settings.lookback_ms,
|
|
1751
|
+
pauseTimeoutMs: settings.pause_timeout_ms
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
function memoryIngestLoop(deps) {
|
|
1756
|
+
return {
|
|
1757
|
+
name: MEMORY_INGEST_LOOP_NAME,
|
|
1758
|
+
intervalMs: deps.config.intervalMs,
|
|
1759
|
+
async tick(signal) {
|
|
1760
|
+
if (signal.aborted) {
|
|
1761
|
+
return;
|
|
1762
|
+
}
|
|
1763
|
+
await runMemoryIngestPass({ deps, signal });
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
|
|
908
1768
|
// src/controller/sandboxEnvBuild.ts
|
|
909
1769
|
import { TrueForgeApi, TrueForgeError } from "@truefoundry/trueforge-sdk";
|
|
910
1770
|
|
|
@@ -1055,12 +1915,12 @@ function sandboxEnvBuildLoop(params) {
|
|
|
1055
1915
|
import { randomUUID } from "crypto";
|
|
1056
1916
|
|
|
1057
1917
|
// src/schemas/schedule.ts
|
|
1058
|
-
import { z as
|
|
1918
|
+
import { z as z5 } from "@hono/zod-openapi";
|
|
1059
1919
|
import { CreatedBySubjectSchema, TokenPaginationSchema } from "@truefoundry/trueforge-core/agent-session";
|
|
1060
1920
|
|
|
1061
1921
|
// src/schemas/common.ts
|
|
1062
|
-
import { z as
|
|
1063
|
-
var NameSchema =
|
|
1922
|
+
import { z as z4 } from "@hono/zod-openapi";
|
|
1923
|
+
var NameSchema = z4.string().min(2).max(64).regex(
|
|
1064
1924
|
/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/,
|
|
1065
1925
|
"must be 2\u201364 lowercase chars: start with a letter, end with alphanumeric, hyphens only in between"
|
|
1066
1926
|
).openapi("ResourceName");
|
|
@@ -1073,11 +1933,11 @@ var InvalidCronError = class extends Error {
|
|
|
1073
1933
|
this.name = "InvalidCronError";
|
|
1074
1934
|
}
|
|
1075
1935
|
};
|
|
1076
|
-
var CronExpressionSchema =
|
|
1936
|
+
var CronExpressionSchema = z5.string().trim().regex(
|
|
1077
1937
|
new RegExp(`^${CRON_FIELD}(?:\\s+${CRON_FIELD}){4}$`),
|
|
1078
1938
|
"must be a 5-field cron expression: minute hour day-of-month month day-of-week"
|
|
1079
1939
|
).describe("Standard 5-field cron expression, evaluated in `timezone`.").openapi("CronExpression");
|
|
1080
|
-
var TimezoneSchema =
|
|
1940
|
+
var TimezoneSchema = z5.string().trim().min(1).refine((value) => {
|
|
1081
1941
|
try {
|
|
1082
1942
|
new Intl.DateTimeFormat(void 0, { timeZone: value });
|
|
1083
1943
|
return true;
|
|
@@ -1085,19 +1945,19 @@ var TimezoneSchema = z3.string().trim().min(1).refine((value) => {
|
|
|
1085
1945
|
return false;
|
|
1086
1946
|
}
|
|
1087
1947
|
}, 'must be a valid IANA time zone name, e.g. "America/New_York"').describe("IANA time zone the cron expression is evaluated in.").openapi("Timezone");
|
|
1088
|
-
var IsoTimestamp =
|
|
1089
|
-
var NullableIsoTimestamp =
|
|
1090
|
-
var ScheduleTaskSchema =
|
|
1091
|
-
var ScheduleStatusSchema =
|
|
1092
|
-
var ScheduleManifestObjectSchema =
|
|
1948
|
+
var IsoTimestamp = z5.iso.datetime().openapi({ type: "string", format: "date-time" });
|
|
1949
|
+
var NullableIsoTimestamp = z5.iso.datetime().nullable().openapi({ type: ["string", "null"], format: "date-time" });
|
|
1950
|
+
var ScheduleTaskSchema = z5.string().trim().min(1).describe("First user message sent to the agent on every run.");
|
|
1951
|
+
var ScheduleStatusSchema = z5.enum(["active", "paused"]).openapi("ScheduleStatus");
|
|
1952
|
+
var ScheduleManifestObjectSchema = z5.object({
|
|
1093
1953
|
task: ScheduleTaskSchema,
|
|
1094
1954
|
cron: CronExpressionSchema,
|
|
1095
1955
|
timezone: TimezoneSchema.default("UTC"),
|
|
1096
1956
|
status: ScheduleStatusSchema.default("active")
|
|
1097
1957
|
}).strict();
|
|
1098
1958
|
var ScheduleManifestSchema = ScheduleManifestObjectSchema.openapi("ScheduleManifest");
|
|
1099
|
-
var ScheduleSchema =
|
|
1100
|
-
id:
|
|
1959
|
+
var ScheduleSchema = z5.object({
|
|
1960
|
+
id: z5.string(),
|
|
1101
1961
|
agent_name: NameSchema,
|
|
1102
1962
|
name: NameSchema,
|
|
1103
1963
|
manifest: ScheduleManifestSchema,
|
|
@@ -1105,45 +1965,45 @@ var ScheduleSchema = z3.object({
|
|
|
1105
1965
|
created_at: IsoTimestamp,
|
|
1106
1966
|
updated_at: IsoTimestamp
|
|
1107
1967
|
}).strict().openapi("Schedule");
|
|
1108
|
-
var CreateScheduleRequestSchema =
|
|
1968
|
+
var CreateScheduleRequestSchema = z5.object({
|
|
1109
1969
|
agent_name: NameSchema,
|
|
1110
1970
|
name: NameSchema,
|
|
1111
1971
|
manifest: ScheduleManifestSchema
|
|
1112
1972
|
}).strict().openapi("CreateScheduleRequest");
|
|
1113
|
-
var UpdateScheduleRequestSchema =
|
|
1973
|
+
var UpdateScheduleRequestSchema = z5.object({
|
|
1114
1974
|
name: NameSchema,
|
|
1115
1975
|
manifest: ScheduleManifestSchema
|
|
1116
1976
|
}).strict().openapi("UpdateScheduleRequest");
|
|
1117
|
-
var GetScheduleResponseSchema =
|
|
1118
|
-
var ListSchedulesResponseSchema =
|
|
1119
|
-
data:
|
|
1977
|
+
var GetScheduleResponseSchema = z5.object({ data: ScheduleSchema }).openapi("GetScheduleResponse");
|
|
1978
|
+
var ListSchedulesResponseSchema = z5.object({
|
|
1979
|
+
data: z5.array(ScheduleSchema),
|
|
1120
1980
|
pagination: TokenPaginationSchema
|
|
1121
1981
|
}).openapi("ListSchedulesResponse");
|
|
1122
|
-
var DeleteScheduleResponseSchema =
|
|
1123
|
-
var ScheduleRunStatusSchema =
|
|
1124
|
-
var ScheduleRunSchema =
|
|
1125
|
-
id:
|
|
1126
|
-
schedule_id:
|
|
1127
|
-
name:
|
|
1982
|
+
var DeleteScheduleResponseSchema = z5.object({}).openapi("DeleteScheduleResponse");
|
|
1983
|
+
var ScheduleRunStatusSchema = z5.enum(["scheduled", "triggered", "failed"]).openapi("ScheduleRunStatus");
|
|
1984
|
+
var ScheduleRunSchema = z5.object({
|
|
1985
|
+
id: z5.string(),
|
|
1986
|
+
schedule_id: z5.string(),
|
|
1987
|
+
name: z5.string(),
|
|
1128
1988
|
scheduled_for: IsoTimestamp,
|
|
1129
1989
|
status: ScheduleRunStatusSchema,
|
|
1130
1990
|
created_by_subject: CreatedBySubjectSchema,
|
|
1131
1991
|
triggered_at: NullableIsoTimestamp,
|
|
1132
|
-
reason:
|
|
1133
|
-
session_id:
|
|
1992
|
+
reason: z5.string().nullable(),
|
|
1993
|
+
session_id: z5.string().nullable(),
|
|
1134
1994
|
created_at: IsoTimestamp,
|
|
1135
1995
|
updated_at: IsoTimestamp
|
|
1136
1996
|
}).strict().openapi("ScheduleRun");
|
|
1137
|
-
var ListScheduleRunsResponseSchema =
|
|
1138
|
-
data:
|
|
1997
|
+
var ListScheduleRunsResponseSchema = z5.object({
|
|
1998
|
+
data: z5.array(ScheduleRunSchema),
|
|
1139
1999
|
pagination: TokenPaginationSchema
|
|
1140
2000
|
}).openapi("ListScheduleRunsResponse");
|
|
1141
|
-
var CreateScheduleRunRequestSchema =
|
|
1142
|
-
schedule_id:
|
|
2001
|
+
var CreateScheduleRunRequestSchema = z5.object({
|
|
2002
|
+
schedule_id: z5.string().min(1).max(64).describe("Immutable schedule identifier.")
|
|
1143
2003
|
}).strict().describe("Trigger an immediate run for the given schedule. The task is taken from the schedule manifest.").openapi("CreateScheduleRunRequest");
|
|
1144
|
-
var CreateScheduleRunResponseSchema =
|
|
1145
|
-
var ExecuteScheduleRunRequestSchema =
|
|
1146
|
-
schedule_run_id:
|
|
2004
|
+
var CreateScheduleRunResponseSchema = z5.object({ data: ScheduleRunSchema }).openapi("CreateScheduleRunResponse");
|
|
2005
|
+
var ExecuteScheduleRunRequestSchema = z5.object({
|
|
2006
|
+
schedule_run_id: z5.string().min(1).max(64).describe("Immutable schedule run identifier.")
|
|
1147
2007
|
}).strict().openapi("ExecuteScheduleRunRequest");
|
|
1148
2008
|
|
|
1149
2009
|
// src/db/scheduleStore.ts
|
|
@@ -1331,17 +2191,18 @@ function scheduleDispatchLoop(params) {
|
|
|
1331
2191
|
|
|
1332
2192
|
// src/controller.ts
|
|
1333
2193
|
function createController(params) {
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
logger: params.logger
|
|
1344
|
-
}
|
|
2194
|
+
const loops = [
|
|
2195
|
+
scheduleDispatchLoop({
|
|
2196
|
+
scheduleStore: params.scheduleStore,
|
|
2197
|
+
withTransaction: params.withTransaction,
|
|
2198
|
+
logger: params.logger
|
|
2199
|
+
}),
|
|
2200
|
+
sandboxEnvBuildLoop({ logger: params.logger })
|
|
2201
|
+
];
|
|
2202
|
+
if (params.memory !== void 0) {
|
|
2203
|
+
loops.push(memoryIngestLoop({ ...params.memory, logger: params.logger, now: () => /* @__PURE__ */ new Date() }));
|
|
2204
|
+
}
|
|
2205
|
+
return new Controller({ loops, logger: params.logger });
|
|
1345
2206
|
}
|
|
1346
2207
|
function runController(params) {
|
|
1347
2208
|
const { logger, gracefulTimeoutSeconds, onStopped } = params;
|
|
@@ -1442,19 +2303,12 @@ function isUniqueViolation(err) {
|
|
|
1442
2303
|
return isPgErrorCode(err, "23505");
|
|
1443
2304
|
}
|
|
1444
2305
|
|
|
1445
|
-
// src/db/postgres/
|
|
1446
|
-
import {
|
|
1447
|
-
import {
|
|
1448
|
-
decodeOffsetPageToken,
|
|
1449
|
-
paginateOffsetRows
|
|
1450
|
-
} from "@truefoundry/trueforge-core/agent-session/store/OffsetPageToken";
|
|
1451
|
-
import "kysely";
|
|
2306
|
+
// src/db/postgres/memory-ingest-store/PostgresMemoryIngestStore.ts
|
|
2307
|
+
import { MAIN_THREAD_ID } from "@truefoundry/trueforge-core/agent-session";
|
|
2308
|
+
import { sql as sql2 } from "kysely";
|
|
1452
2309
|
|
|
1453
|
-
// src/
|
|
1454
|
-
|
|
1455
|
-
function newId() {
|
|
1456
|
-
return ulid().toLowerCase();
|
|
1457
|
-
}
|
|
2310
|
+
// src/db/memoryIngestStore.ts
|
|
2311
|
+
var AGENT_MEMORY_ENABLED_PATH = ["runtime", "memory", "enabled"];
|
|
1458
2312
|
|
|
1459
2313
|
// src/db/postgres/sqlExpressions.ts
|
|
1460
2314
|
import { sql } from "kysely";
|
|
@@ -1479,6 +2333,110 @@ function whereCreatedByOrAgentIds(query, filter) {
|
|
|
1479
2333
|
);
|
|
1480
2334
|
}
|
|
1481
2335
|
|
|
2336
|
+
// src/db/postgres/memory-ingest-store/PostgresMemoryIngestStore.ts
|
|
2337
|
+
var agentMemoryEnabled = sql2`a.manifest #>> ${sql2.lit(`{${AGENT_MEMORY_ENABLED_PATH.join(",")}}`)}`;
|
|
2338
|
+
var tfgSource = sql2`s.metadata->>'tfg.source'`;
|
|
2339
|
+
var createAgentSession = sql2`COALESCE(s.metadata->>'is_create_agent' = 'true', false)`;
|
|
2340
|
+
var textOnlyInput = sql2`(
|
|
2341
|
+
SELECT COALESCE(jsonb_agg(
|
|
2342
|
+
CASE WHEN jsonb_typeof(item->'content') = 'array' THEN jsonb_set(item, '{content}', COALESCE(
|
|
2343
|
+
(SELECT jsonb_agg(part ORDER BY part_index)
|
|
2344
|
+
FROM jsonb_array_elements(item->'content') WITH ORDINALITY AS p(part, part_index)
|
|
2345
|
+
WHERE part->>'type' = 'text'),
|
|
2346
|
+
'[]'::jsonb))
|
|
2347
|
+
ELSE item END
|
|
2348
|
+
ORDER BY item_index), '[]'::jsonb)
|
|
2349
|
+
FROM jsonb_array_elements(input) WITH ORDINALITY AS i(item, item_index)
|
|
2350
|
+
)`;
|
|
2351
|
+
var tipPaused = sql2`(t.state->>'status' = 'done' AND jsonb_array_length(COALESCE(t.state->'required_actions', '[]'::jsonb)) > 0)`;
|
|
2352
|
+
var PostgresMemoryIngestStore = class {
|
|
2353
|
+
#db;
|
|
2354
|
+
constructor(db) {
|
|
2355
|
+
this.#db = db;
|
|
2356
|
+
}
|
|
2357
|
+
async listCandidateSessions(input) {
|
|
2358
|
+
const query = this.#db.selectFrom("session as s").innerJoin(
|
|
2359
|
+
"turn as t",
|
|
2360
|
+
(join2) => join2.onRef("t.session_id", "=", "s.session_id").on(sql2`t.turn_id = s.last_turn_details->>'id'`)
|
|
2361
|
+
).leftJoin("agent as a", (join2) => join2.onRef("a.id", "=", "s.agent_id").onRef("a.tenant_id", "=", "s.tenant_id")).leftJoin("memory_ingest_cursor as c", "c.session_id", "s.session_id").select([
|
|
2362
|
+
"s.session_id",
|
|
2363
|
+
"s.tenant_id",
|
|
2364
|
+
"s.created_by_subject",
|
|
2365
|
+
"s.agent_id",
|
|
2366
|
+
tfgSource.as("tfg_source"),
|
|
2367
|
+
createAgentSession.as("create_agent_session"),
|
|
2368
|
+
sql2`COALESCE(${agentMemoryEnabled} = 'true', false)`.as("agent_memory_enabled"),
|
|
2369
|
+
"t.turn_id as tip_turn_id",
|
|
2370
|
+
"c.last_ingested_turn_id as cursor_last_ingested_turn_id",
|
|
2371
|
+
"c.external_thread_id as cursor_external_thread_id",
|
|
2372
|
+
"c.last_error as cursor_last_error",
|
|
2373
|
+
"c.updated_at as cursor_updated_at"
|
|
2374
|
+
]).where("s.source", "is", null).where(
|
|
2375
|
+
(eb) => eb.or([
|
|
2376
|
+
eb("s.updated_at", ">=", input.recent_since),
|
|
2377
|
+
eb.and([eb("s.updated_at", ">=", input.paused_from), eb("s.updated_at", "<", input.paused_until), tipPaused])
|
|
2378
|
+
])
|
|
2379
|
+
).where(sql2`NOT (${createAgentSession})`).where(
|
|
2380
|
+
(eb) => eb.or([eb.and([eb("s.agent_id", "is", null), eb(tfgSource, "=", "ui")]), eb(agentMemoryEnabled, "=", "true")])
|
|
2381
|
+
).where(sql2`c.last_ingested_turn_id IS DISTINCT FROM t.turn_id`);
|
|
2382
|
+
const scoped = input.tenant_ids === void 0 ? query : query.where("s.tenant_id", "in", [...input.tenant_ids]);
|
|
2383
|
+
const rows = await scoped.orderBy("s.updated_at", "asc").orderBy("s.session_id", "asc").limit(input.limit).execute();
|
|
2384
|
+
return rows.map((row) => ({
|
|
2385
|
+
session_id: row.session_id,
|
|
2386
|
+
tenant_id: row.tenant_id,
|
|
2387
|
+
created_by_subject: row.created_by_subject,
|
|
2388
|
+
agent_id: row.agent_id,
|
|
2389
|
+
tfg_source: row.tfg_source,
|
|
2390
|
+
create_agent_session: row.create_agent_session,
|
|
2391
|
+
agent_memory_enabled: row.agent_memory_enabled,
|
|
2392
|
+
tip_turn_id: row.tip_turn_id,
|
|
2393
|
+
cursor: row.cursor_updated_at === null ? null : {
|
|
2394
|
+
session_id: row.session_id,
|
|
2395
|
+
last_ingested_turn_id: row.cursor_last_ingested_turn_id,
|
|
2396
|
+
external_thread_id: row.cursor_external_thread_id,
|
|
2397
|
+
last_error: row.cursor_last_error,
|
|
2398
|
+
updated_at: row.cursor_updated_at.toISOString()
|
|
2399
|
+
}
|
|
2400
|
+
}));
|
|
2401
|
+
}
|
|
2402
|
+
async listSessionTurns(input) {
|
|
2403
|
+
const rows = await this.#db.selectFrom("turn").select(["turn_id", "previous_turn_id", textOnlyInput.as("input"), "state", "created_at"]).where("session_id", "=", input.session_id).orderBy("created_at", "asc").orderBy("turn_id", "asc").execute();
|
|
2404
|
+
return rows.map((row) => ({ ...row, created_at: row.created_at.toISOString() }));
|
|
2405
|
+
}
|
|
2406
|
+
async listMainThreadModelMessages(input) {
|
|
2407
|
+
if (input.turn_ids.length === 0) {
|
|
2408
|
+
return [];
|
|
2409
|
+
}
|
|
2410
|
+
const rows = await this.#db.selectFrom("session_event").select(["turn_id", "event"]).where("session_id", "=", input.session_id).where("turn_id", "in", [...input.turn_ids]).where(sql2`event->>'type'`, "=", "model.message").where(sql2`event->>'thread_id'`, "=", MAIN_THREAD_ID).orderBy("turn_id", "asc").orderBy("event_id", "asc").execute();
|
|
2411
|
+
return rows.flatMap(
|
|
2412
|
+
(row) => row.event.type === "model.message" ? [{ turn_id: row.turn_id, message: row.event }] : []
|
|
2413
|
+
);
|
|
2414
|
+
}
|
|
2415
|
+
async upsertCursor(input) {
|
|
2416
|
+
const values = {
|
|
2417
|
+
last_ingested_turn_id: input.last_ingested_turn_id,
|
|
2418
|
+
external_thread_id: input.external_thread_id,
|
|
2419
|
+
last_error: input.last_error,
|
|
2420
|
+
updated_at: now()
|
|
2421
|
+
};
|
|
2422
|
+
await this.#db.insertInto("memory_ingest_cursor").values({ session_id: input.session_id, ...values }).onConflict((oc) => oc.column("session_id").doUpdateSet(values)).execute();
|
|
2423
|
+
}
|
|
2424
|
+
};
|
|
2425
|
+
|
|
2426
|
+
// src/db/postgres/schedule-store/PostgresScheduleStore.ts
|
|
2427
|
+
import { CreatedBySubjectSchema as CreatedBySubjectSchema2 } from "@truefoundry/trueforge-core/agent-session";
|
|
2428
|
+
import {
|
|
2429
|
+
decodeOffsetPageToken,
|
|
2430
|
+
paginateOffsetRows
|
|
2431
|
+
} from "@truefoundry/trueforge-core/agent-session/store/OffsetPageToken";
|
|
2432
|
+
import "kysely";
|
|
2433
|
+
|
|
2434
|
+
// src/utils/id.ts
|
|
2435
|
+
import { ulid } from "ulid";
|
|
2436
|
+
function newId() {
|
|
2437
|
+
return ulid().toLowerCase();
|
|
2438
|
+
}
|
|
2439
|
+
|
|
1482
2440
|
// src/db/postgres/schedule-store/PostgresScheduleStore.ts
|
|
1483
2441
|
function toScheduleRecord(row) {
|
|
1484
2442
|
return {
|
|
@@ -2090,10 +3048,19 @@ try {
|
|
|
2090
3048
|
serverUrl: config_default.SERVER_URL,
|
|
2091
3049
|
mTlsEnabled: config_default.MTLS_ENABLED
|
|
2092
3050
|
});
|
|
3051
|
+
const memory = isTrueFoundryModeEnabled(config_default) ? memoryIngestFromConfig({ config: config_default, store: new PostgresMemoryIngestStore(db), logger }) : void 0;
|
|
3052
|
+
if (memory !== void 0) {
|
|
3053
|
+
logger.info("Memory ingestion enabled", {
|
|
3054
|
+
provider: memory.provider.name,
|
|
3055
|
+
interval_ms: memory.config.intervalMs,
|
|
3056
|
+
max_sessions_per_run: memory.config.maxSessionsPerRun
|
|
3057
|
+
});
|
|
3058
|
+
}
|
|
2093
3059
|
runController({
|
|
2094
3060
|
scheduleStore: new PostgresScheduleStore(db),
|
|
2095
3061
|
withTransaction: (callback) => db.transaction().execute(callback),
|
|
2096
3062
|
logger,
|
|
3063
|
+
memory,
|
|
2097
3064
|
gracefulTimeoutSeconds: config_default.GRACEFUL_TIMEOUT_SECONDS,
|
|
2098
3065
|
onStopped: () => db.destroy()
|
|
2099
3066
|
});
|