@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/main.js CHANGED
@@ -359,6 +359,16 @@ function parsePublicBaseUrl(raw) {
359
359
  const path7 = segments.length === 0 ? "" : `/${segments.join("/")}`;
360
360
  return `${parsed.origin}${path7}`;
361
361
  }
362
+ function parseTrueFoundryMemoryProvider(raw) {
363
+ if (raw === void 0 || raw.trim() === "") {
364
+ return void 0;
365
+ }
366
+ const value = raw.trim();
367
+ if (value === "zep") {
368
+ return value;
369
+ }
370
+ throw new Error(`Environment variable TRUEFOUNDRY_MEMORY_PROVIDER must be "zep", got ${JSON.stringify(raw)}`);
371
+ }
362
372
  function parseTrueFoundrySandboxProvider(raw) {
363
373
  if (raw === void 0 || raw.trim() === "") {
364
374
  return void 0;
@@ -979,7 +989,22 @@ var init_config = __esm({
979
989
  getEnv("TRUEFOUNDRY_WEB_SEARCH_PROVIDER", { required: false })
980
990
  ),
981
991
  TRUEFOUNDRY_AUTH_SERVER_URL: getEnv("TRUEFOUNDRY_AUTH_SERVER_URL", { required: false }),
982
- TRUEFOUNDRY_TENANT_NAME: getEnv("TRUEFOUNDRY_TENANT_NAME", { required: false })
992
+ TRUEFOUNDRY_TENANT_NAME: getEnv("TRUEFOUNDRY_TENANT_NAME", { required: false }),
993
+ TRUEFOUNDRY_MEMORY_ENABLED: parseBoolean({
994
+ envKey: "TRUEFOUNDRY_MEMORY_ENABLED",
995
+ raw: getEnv("TRUEFOUNDRY_MEMORY_ENABLED"),
996
+ defaultValue: false
997
+ }),
998
+ TRUEFOUNDRY_MEMORY_PROVIDER: parseTrueFoundryMemoryProvider(
999
+ getEnv("TRUEFOUNDRY_MEMORY_PROVIDER", { required: false })
1000
+ ),
1001
+ TRUEFOUNDRY_MEMORY_API_KEY: getEnv("TRUEFOUNDRY_MEMORY_API_KEY", { required: false }),
1002
+ TRUEFOUNDRY_MEMORY_SERVER_URL: getEnv("TRUEFOUNDRY_MEMORY_SERVER_URL", { required: false }),
1003
+ TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST: parseJsonStringArrayEnv({
1004
+ envKey: "TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST",
1005
+ raw: getEnv("TRUEFOUNDRY_MEMORY_TENANT_ALLOWLIST")
1006
+ }),
1007
+ TRUEFOUNDRY_MEMORY_SETTINGS: getEnv("TRUEFOUNDRY_MEMORY_SETTINGS", { required: false })
983
1008
  };
984
1009
  TrueForgeAuthMode = /* @__PURE__ */ ((TrueForgeAuthMode3) => {
985
1010
  TrueForgeAuthMode3["Standalone"] = "standalone";
@@ -1023,6 +1048,25 @@ var init_config = __esm({
1023
1048
  );
1024
1049
  }
1025
1050
  }
1051
+ if (configuration.TRUEFOUNDRY_MEMORY_ENABLED) {
1052
+ if (configuration.TRUEFOUNDRY_MEMORY_PROVIDER === void 0) {
1053
+ throw new Error(
1054
+ 'TRUEFOUNDRY_MEMORY_ENABLED is true but TRUEFOUNDRY_MEMORY_PROVIDER is not set. Set TRUEFOUNDRY_MEMORY_PROVIDER to "zep", or set TRUEFOUNDRY_MEMORY_ENABLED=false.'
1055
+ );
1056
+ }
1057
+ if (configuration.TRUEFOUNDRY_MEMORY_API_KEY === void 0) {
1058
+ throw new Error(
1059
+ "TRUEFOUNDRY_MEMORY_PROVIDER=zep requires TRUEFOUNDRY_MEMORY_API_KEY, or set TRUEFOUNDRY_MEMORY_ENABLED=false."
1060
+ );
1061
+ }
1062
+ if (configuration.TRUEFOUNDRY_MEMORY_SETTINGS !== void 0) {
1063
+ try {
1064
+ JSON.parse(configuration.TRUEFOUNDRY_MEMORY_SETTINGS);
1065
+ } catch (error) {
1066
+ throw new Error("TRUEFOUNDRY_MEMORY_SETTINGS must be valid JSON", { cause: error });
1067
+ }
1068
+ }
1069
+ }
1026
1070
  }
1027
1071
  if (!configuration.STANDALONE && configuration.TRUEFORGE_API_KEY.trim() === "") {
1028
1072
  throw new Error("TRUEFORGE_API_KEY must not be empty when STANDALONE=false.");
@@ -8711,12 +8755,15 @@ async function patchMCPServers2(db, input) {
8711
8755
  session_id: input.session_id,
8712
8756
  turn_id: input.turn_id
8713
8757
  };
8714
- const result = await db.updateTable("turn").set(
8715
- sql22`checkpoint['mcp_servers']`,
8716
- sql22`(CASE WHEN jsonb_typeof(checkpoint->'mcp_servers') = 'object'
8758
+ const result = await db.updateTable("turn").set({
8759
+ checkpoint: jsonbSet(
8760
+ sql22`checkpoint`,
8761
+ sql22`'{mcp_servers}'`,
8762
+ sql22`(CASE WHEN jsonb_typeof(checkpoint->'mcp_servers') = 'object'
8717
8763
  THEN checkpoint->'mcp_servers'
8718
8764
  ELSE '{}'::jsonb END) || ${json(serversById)}`
8719
- ).set({ updated_at: sql22`now()` }).where("session_id", "=", keys.session_id).where("turn_id", "=", keys.turn_id).where(sql22`state->>'status' = 'running'`).executeTakeFirst();
8765
+ )
8766
+ }).set({ updated_at: sql22`now()` }).where("session_id", "=", keys.session_id).where("turn_id", "=", keys.turn_id).where(sql22`state->>'status' = 'running'`).executeTakeFirst();
8720
8767
  if (Number(result.numUpdatedRows) === 0) {
8721
8768
  await classifyTurnFenceWriteFailure2(db, keys);
8722
8769
  }
@@ -8726,7 +8773,7 @@ async function patchSandboxInfo2(db, input) {
8726
8773
  session_id: input.session_id,
8727
8774
  turn_id: input.turn_id
8728
8775
  };
8729
- const result = await db.updateTable("turn").set(sql22`checkpoint['sandbox_info']`, json(input.sandbox_info)).set({ updated_at: sql22`now()` }).where("session_id", "=", keys.session_id).where("turn_id", "=", keys.turn_id).where(sql22`state->>'status' = 'running'`).executeTakeFirst();
8776
+ const result = await db.updateTable("turn").set({ checkpoint: jsonbSet(sql22`checkpoint`, sql22`'{sandbox_info}'`, json(input.sandbox_info)) }).set({ updated_at: sql22`now()` }).where("session_id", "=", keys.session_id).where("turn_id", "=", keys.turn_id).where(sql22`state->>'status' = 'running'`).executeTakeFirst();
8730
8777
  if (Number(result.numUpdatedRows) === 0) {
8731
8778
  await classifyTurnFenceWriteFailure2(db, keys);
8732
8779
  }
@@ -21615,6 +21662,473 @@ var Controller = class {
21615
21662
  }
21616
21663
  };
21617
21664
 
21665
+ // src/memory/zep/ZepMemoryProvider.ts
21666
+ import { z as z45 } from "zod";
21667
+
21668
+ // src/memory/MemoryProvider.ts
21669
+ var MemoryIngestError = class extends Error {
21670
+ externalThreadId;
21671
+ constructor({
21672
+ message,
21673
+ externalThreadId,
21674
+ cause
21675
+ }) {
21676
+ super(message, { cause });
21677
+ this.name = "MemoryIngestError";
21678
+ this.externalThreadId = externalThreadId;
21679
+ }
21680
+ };
21681
+
21682
+ // src/memory/scope.ts
21683
+ import { createHash as createHash2 } from "crypto";
21684
+ var DEFAULT_MEMORY_AGENT_KEY = "trueforge";
21685
+ var UI_SESSION_SOURCE = "ui";
21686
+ function memoryScopeKey({
21687
+ tenantId,
21688
+ agentKey,
21689
+ subjectId
21690
+ }) {
21691
+ const digest = createHash2("sha256").update(JSON.stringify([tenantId, agentKey, subjectId])).digest("hex");
21692
+ return `tfg-${digest}`;
21693
+ }
21694
+ function resolveMemoryScope(session) {
21695
+ if (session.createAgentSession) {
21696
+ return void 0;
21697
+ }
21698
+ const tenantId = session.tenantId;
21699
+ const subjectId = session.createdBySubject.subject_id;
21700
+ if (session.agentId !== null) {
21701
+ if (!session.agentMemoryEnabled) {
21702
+ return void 0;
21703
+ }
21704
+ return {
21705
+ type: "agent",
21706
+ tenantId,
21707
+ subjectId,
21708
+ agentId: session.agentId,
21709
+ key: memoryScopeKey({ tenantId, agentKey: session.agentId, subjectId })
21710
+ };
21711
+ }
21712
+ if (session.tfgSource !== UI_SESSION_SOURCE) {
21713
+ return void 0;
21714
+ }
21715
+ return {
21716
+ type: "default",
21717
+ tenantId,
21718
+ subjectId,
21719
+ agentId: null,
21720
+ key: memoryScopeKey({ tenantId, agentKey: DEFAULT_MEMORY_AGENT_KEY, subjectId })
21721
+ };
21722
+ }
21723
+
21724
+ // src/memory/zep/ZepMemoryProvider.ts
21725
+ var ZepUuidResponseSchema = z45.object({ uuid: z45.string().min(1) });
21726
+ var ZepMessagesResponseSchema = z45.object({
21727
+ items: z45.array(z45.object({ metadata: z45.record(z45.string(), z45.unknown()).nullish() }))
21728
+ });
21729
+
21730
+ // src/memory/exchanges.ts
21731
+ import { ASK_USER_QUESTION_TOOL_NAME } from "@truefoundry/trueforge-core/core";
21732
+ var MAX_MEMORY_MESSAGE_CHARS = 4e3;
21733
+ var TRUNCATION_MARKER = " [truncated]";
21734
+ function hasUserMessage(turn) {
21735
+ return turn.input.some((item) => item.type === "user.message");
21736
+ }
21737
+ function statusAfter(state) {
21738
+ switch (state.status) {
21739
+ case "running":
21740
+ case "paused":
21741
+ return "running";
21742
+ case "done":
21743
+ return state.required_actions.length === 0 ? "closed" : "paused";
21744
+ case "error":
21745
+ case "cancelled":
21746
+ return "closed";
21747
+ }
21748
+ }
21749
+ function activePath({
21750
+ turns,
21751
+ tipTurnId
21752
+ }) {
21753
+ const byId = new Map(turns.map((turn) => [turn.turn_id, turn]));
21754
+ const path7 = [];
21755
+ const seen = /* @__PURE__ */ new Set();
21756
+ let current = byId.get(tipTurnId);
21757
+ while (current !== void 0 && !seen.has(current.turn_id)) {
21758
+ seen.add(current.turn_id);
21759
+ path7.push(current);
21760
+ current = current.previous_turn_id === null ? void 0 : byId.get(current.previous_turn_id);
21761
+ }
21762
+ return path7.reverse();
21763
+ }
21764
+ function buildExchanges(turns) {
21765
+ const exchanges = [];
21766
+ let current;
21767
+ for (const turn of turns) {
21768
+ if (current !== void 0 && hasUserMessage(turn)) {
21769
+ current.status = "closed";
21770
+ current.completedAt ??= turn.created_at;
21771
+ current = void 0;
21772
+ }
21773
+ if (current === void 0) {
21774
+ current = {
21775
+ turns: [turn],
21776
+ status: statusAfter(turn.state),
21777
+ completedAt: completedAt(turn.state),
21778
+ continuation: !hasUserMessage(turn)
21779
+ };
21780
+ exchanges.push(current);
21781
+ } else {
21782
+ current.turns.push(turn);
21783
+ current.status = statusAfter(turn.state);
21784
+ current.completedAt = completedAt(turn.state);
21785
+ }
21786
+ if (current.status === "closed") {
21787
+ current = void 0;
21788
+ }
21789
+ }
21790
+ return exchanges;
21791
+ }
21792
+ function resumePoint({
21793
+ path: path7,
21794
+ turns,
21795
+ lastIngestedTurnId
21796
+ }) {
21797
+ if (lastIngestedTurnId === null) {
21798
+ return { startIndex: 0, forked: false };
21799
+ }
21800
+ const pathIndex = new Map(path7.map((turn, index) => [turn.turn_id, index]));
21801
+ const ingestedIndex = pathIndex.get(lastIngestedTurnId);
21802
+ if (ingestedIndex !== void 0) {
21803
+ return { startIndex: ingestedIndex + 1, forked: false };
21804
+ }
21805
+ const byId = new Map(turns.map((turn) => [turn.turn_id, turn]));
21806
+ const seen = /* @__PURE__ */ new Set();
21807
+ let forkIndex;
21808
+ let current = byId.get(lastIngestedTurnId);
21809
+ while (current !== void 0 && !seen.has(current.turn_id) && forkIndex === void 0) {
21810
+ seen.add(current.turn_id);
21811
+ current = current.previous_turn_id === null ? void 0 : byId.get(current.previous_turn_id);
21812
+ forkIndex = current === void 0 ? void 0 : pathIndex.get(current.turn_id);
21813
+ }
21814
+ return { startIndex: forkIndex === void 0 ? 0 : forkIndex + 1, forked: true };
21815
+ }
21816
+ function completedAt(state) {
21817
+ return state.status === "done" || state.status === "error" || state.status === "cancelled" ? state.completed_at : null;
21818
+ }
21819
+ function exchangeReadiness({
21820
+ exchange,
21821
+ now: now2,
21822
+ pauseTimeoutMs
21823
+ }) {
21824
+ const finishedAt = exchange.completedAt;
21825
+ if (exchange.status === "running" || finishedAt === null) {
21826
+ return { ready: false };
21827
+ }
21828
+ if (exchange.status === "closed") {
21829
+ return { ready: true, partial: false };
21830
+ }
21831
+ return now2.getTime() - Date.parse(finishedAt) >= pauseTimeoutMs ? { ready: true, partial: true } : { ready: false };
21832
+ }
21833
+ function askUserQuestionsByToolCallId(messages) {
21834
+ const questions = /* @__PURE__ */ new Map();
21835
+ for (const message of messages) {
21836
+ for (const call of message.tool_calls ?? []) {
21837
+ if (call.function.name !== ASK_USER_QUESTION_TOOL_NAME) {
21838
+ continue;
21839
+ }
21840
+ const question = parseQuestion(call.function.arguments);
21841
+ if (question !== void 0) {
21842
+ questions.set(call.id, question);
21843
+ }
21844
+ }
21845
+ }
21846
+ return questions;
21847
+ }
21848
+ function parseQuestion(rawArguments) {
21849
+ try {
21850
+ const parsed = JSON.parse(rawArguments);
21851
+ if (typeof parsed === "object" && parsed !== null && "question" in parsed && typeof parsed.question === "string") {
21852
+ const question = parsed.question.trim();
21853
+ return question === "" ? void 0 : question;
21854
+ }
21855
+ } catch {
21856
+ }
21857
+ return void 0;
21858
+ }
21859
+ function modelMessageText(content) {
21860
+ if (content === void 0 || content === null) {
21861
+ return "";
21862
+ }
21863
+ if (typeof content === "string") {
21864
+ return content.trim();
21865
+ }
21866
+ return content.map((part) => part.type === "text" ? part.text : part.refusal).join("").trim();
21867
+ }
21868
+ function capped(text) {
21869
+ return text.length <= MAX_MEMORY_MESSAGE_CHARS ? text : text.slice(0, MAX_MEMORY_MESSAGE_CHARS - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
21870
+ }
21871
+ function renderExchange({
21872
+ exchange,
21873
+ questions
21874
+ }) {
21875
+ const messages = [];
21876
+ const user = (content, createdAt) => {
21877
+ if (content !== "") {
21878
+ messages.push({ role: "user", content: capped(content), createdAt, extract: true });
21879
+ }
21880
+ };
21881
+ for (const turn of exchange.turns) {
21882
+ for (const item of turn.input) {
21883
+ if (item.type === "user.message") {
21884
+ const text = typeof item.content === "string" ? item.content : item.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n");
21885
+ user(text.trim(), turn.created_at);
21886
+ } else if (item.type === "user.tool_response") {
21887
+ const question = questions.get(item.tool_call_id);
21888
+ const answer = item.content.trim();
21889
+ if (question !== void 0 && answer !== "") {
21890
+ user(`(Answering "${question}") ${answer}`, turn.created_at);
21891
+ }
21892
+ }
21893
+ }
21894
+ }
21895
+ const last = exchange.turns[exchange.turns.length - 1];
21896
+ if (exchange.status === "closed" && last?.state.status === "done" && last.state.output !== null) {
21897
+ const reply = modelMessageText(last.state.output.content);
21898
+ if (reply !== "") {
21899
+ messages.push({
21900
+ role: "assistant",
21901
+ content: capped(reply),
21902
+ createdAt: last.state.completed_at,
21903
+ extract: false
21904
+ });
21905
+ }
21906
+ }
21907
+ return messages;
21908
+ }
21909
+
21910
+ // src/truefoundry/resolveTrueFoundryMemoryProviderConfig.ts
21911
+ import { z as z46 } from "zod";
21912
+ var TrueFoundryMemorySettingsSchema = z46.object({
21913
+ /** Gap between ingest runs. */
21914
+ interval_ms: z46.number().int().positive().default(5 * 60 * 1e3),
21915
+ /** Sessions processed per run. */
21916
+ max_sessions_per_run: z46.number().int().positive().default(50),
21917
+ /** Exchanges sent per session per run. */
21918
+ max_exchanges_per_session: z46.number().int().positive().default(20),
21919
+ /** How far back a session's latest turn is picked up; sessions not ingested by then are dropped. */
21920
+ lookback_ms: z46.number().int().positive().default(2 * 60 * 60 * 1e3),
21921
+ /**
21922
+ * An exchange paused on the user (a question, approval or auth) is sent as-is after this long.
21923
+ * Paused sessions are looked up again in a lookback-wide range this far back.
21924
+ */
21925
+ pause_timeout_ms: z46.number().int().positive().default(12 * 60 * 60 * 1e3)
21926
+ }).strict();
21927
+
21928
+ // src/controller/memoryIngest.ts
21929
+ var MEMORY_INGEST_LOOP_NAME = "memory-ingest";
21930
+ function errorMessage(error) {
21931
+ return error instanceof Error ? error.message : String(error);
21932
+ }
21933
+ function readyExchanges({
21934
+ exchanges,
21935
+ now: now2,
21936
+ config
21937
+ }) {
21938
+ const ready = [];
21939
+ for (const exchange of exchanges) {
21940
+ if (ready.length === config.maxExchangesPerSession || !exchangeReadiness({ exchange, now: now2, pauseTimeoutMs: config.pauseTimeoutMs }).ready) {
21941
+ break;
21942
+ }
21943
+ ready.push(exchange);
21944
+ }
21945
+ return ready;
21946
+ }
21947
+ async function ingestSession({
21948
+ candidate,
21949
+ scope,
21950
+ deps,
21951
+ signal
21952
+ }) {
21953
+ const { store, provider, logger: logger2, config, now: now2 } = deps;
21954
+ const { cursor } = candidate;
21955
+ const logFields = {
21956
+ session_id: candidate.session_id,
21957
+ tenant_id: candidate.tenant_id,
21958
+ scope_type: scope.type,
21959
+ agent_id: candidate.agent_id
21960
+ };
21961
+ let threadId = cursor?.external_thread_id ?? null;
21962
+ let lastIngestedTurnId = cursor?.last_ingested_turn_id ?? null;
21963
+ const turns = await store.listSessionTurns({ session_id: candidate.session_id });
21964
+ const path7 = activePath({ turns, tipTurnId: candidate.tip_turn_id });
21965
+ const { startIndex, forked } = resumePoint({ path: path7, turns, lastIngestedTurnId });
21966
+ if (forked) {
21967
+ logger2.warn("Memory checkpoint is off the active path; resuming after the fork point", {
21968
+ ...logFields,
21969
+ last_ingested_turn_id: lastIngestedTurnId
21970
+ });
21971
+ }
21972
+ const ready = readyExchanges({ exchanges: buildExchanges(path7.slice(startIndex)), now: now2(), config });
21973
+ if (ready.length === 0) {
21974
+ return { outcome: "not_ready", exchangesSent: 0, exchangesFailed: 0 };
21975
+ }
21976
+ const previous = path7[startIndex - 1];
21977
+ const turnIds = [
21978
+ ...previous === void 0 ? [] : [previous.turn_id],
21979
+ ...ready.flatMap((e) => e.turns.map((t) => t.turn_id))
21980
+ ];
21981
+ const modelMessages = await store.listMainThreadModelMessages({
21982
+ session_id: candidate.session_id,
21983
+ turn_ids: turnIds
21984
+ });
21985
+ const questions = askUserQuestionsByToolCallId(modelMessages.map((entry) => entry.message));
21986
+ let exchangesSent = 0;
21987
+ let mayAlreadyBeStored = cursor !== null && cursor.last_error !== null;
21988
+ for (const exchange of ready) {
21989
+ if (signal.aborted) {
21990
+ break;
21991
+ }
21992
+ const firstTurnId = exchange.turns[0].turn_id;
21993
+ const lastTurnId = exchange.turns[exchange.turns.length - 1]?.turn_id ?? firstTurnId;
21994
+ const messages = renderExchange({ exchange, questions });
21995
+ try {
21996
+ if (messages.length > 0) {
21997
+ const sent = await provider.ingestExchange({
21998
+ scope,
21999
+ exchange: { sessionId: candidate.session_id, lastTurnId, messages },
22000
+ externalThreadId: threadId,
22001
+ mayAlreadyBeStored
22002
+ });
22003
+ threadId = sent.externalThreadId;
22004
+ mayAlreadyBeStored = false;
22005
+ exchangesSent += 1;
22006
+ }
22007
+ } catch (error) {
22008
+ if (error instanceof MemoryIngestError && error.externalThreadId !== null) {
22009
+ threadId = error.externalThreadId;
22010
+ }
22011
+ const lastError = errorMessage(error);
22012
+ logger2.error("Memory ingest failed for session", {
22013
+ ...logFields,
22014
+ exchanges_sent: exchangesSent,
22015
+ last_error: lastError,
22016
+ reportable_error: { error, extra: { ...logFields, first_turn_id: firstTurnId, last_turn_id: lastTurnId } }
22017
+ });
22018
+ await store.upsertCursor({
22019
+ session_id: candidate.session_id,
22020
+ last_ingested_turn_id: lastIngestedTurnId,
22021
+ external_thread_id: threadId,
22022
+ last_error: lastError.slice(0, 1e3)
22023
+ });
22024
+ return { outcome: "failed", exchangesSent, exchangesFailed: 1 };
22025
+ }
22026
+ lastIngestedTurnId = lastTurnId;
22027
+ await store.upsertCursor({
22028
+ session_id: candidate.session_id,
22029
+ last_ingested_turn_id: lastIngestedTurnId,
22030
+ external_thread_id: threadId,
22031
+ last_error: null
22032
+ });
22033
+ }
22034
+ logger2.debug("Memory ingest session finished", { ...logFields, exchanges_sent: exchangesSent });
22035
+ return { outcome: "ingested", exchangesSent, exchangesFailed: 0 };
22036
+ }
22037
+ async function runMemoryIngestPass({
22038
+ deps,
22039
+ signal
22040
+ }) {
22041
+ const { store, settings, logger: logger2, config, now: now2 } = deps;
22042
+ const startedAt = now2();
22043
+ const startedMs = startedAt.getTime();
22044
+ const tenantIds = await settings.listEnabledTenantIds();
22045
+ const listed = tenantIds?.length === 0 ? [] : await store.listCandidateSessions({
22046
+ tenant_ids: tenantIds,
22047
+ recent_since: new Date(startedMs - config.lookbackMs),
22048
+ paused_from: new Date(startedMs - config.pauseTimeoutMs - config.lookbackMs),
22049
+ paused_until: new Date(startedMs - config.pauseTimeoutMs),
22050
+ limit: config.maxSessionsPerRun + 1
22051
+ });
22052
+ const backlog = listed.length > config.maxSessionsPerRun;
22053
+ const candidates = listed.slice(0, config.maxSessionsPerRun);
22054
+ const outcomes = {};
22055
+ let exchangesSent = 0;
22056
+ let exchangesFailed = 0;
22057
+ let sessionsProcessed = 0;
22058
+ for (const candidate of candidates) {
22059
+ if (signal.aborted) {
22060
+ break;
22061
+ }
22062
+ sessionsProcessed += 1;
22063
+ const result = await processCandidate({ candidate, deps, signal });
22064
+ outcomes[result.outcome] = (outcomes[result.outcome] ?? 0) + 1;
22065
+ exchangesSent += result.exchangesSent;
22066
+ exchangesFailed += result.exchangesFailed;
22067
+ }
22068
+ const summary = {
22069
+ sessions: sessionsProcessed,
22070
+ backlog,
22071
+ sessions_by_outcome: outcomes,
22072
+ exchanges_sent: exchangesSent,
22073
+ exchanges_failed: exchangesFailed,
22074
+ duration_ms: now2().getTime() - startedAt.getTime()
22075
+ };
22076
+ if (exchangesSent > 0 || exchangesFailed > 0 || backlog) {
22077
+ logger2.info("Memory ingest run finished", summary);
22078
+ } else {
22079
+ logger2.debug("Memory ingest run finished", summary);
22080
+ }
22081
+ return summary;
22082
+ }
22083
+ async function processCandidate({
22084
+ candidate,
22085
+ deps,
22086
+ signal
22087
+ }) {
22088
+ const { logger: logger2 } = deps;
22089
+ const skipped = (outcome) => ({
22090
+ outcome,
22091
+ exchangesSent: 0,
22092
+ exchangesFailed: 0
22093
+ });
22094
+ const scope = resolveMemoryScope({
22095
+ tenantId: candidate.tenant_id,
22096
+ createdBySubject: candidate.created_by_subject,
22097
+ agentId: candidate.agent_id,
22098
+ agentMemoryEnabled: candidate.agent_memory_enabled,
22099
+ tfgSource: candidate.tfg_source,
22100
+ createAgentSession: candidate.create_agent_session
22101
+ });
22102
+ if (scope === void 0) {
22103
+ return skipped("memory_disabled");
22104
+ }
22105
+ try {
22106
+ return await ingestSession({ candidate, scope, deps, signal });
22107
+ } catch (error) {
22108
+ logger2.error("Memory ingest failed for session", {
22109
+ session_id: candidate.session_id,
22110
+ tenant_id: candidate.tenant_id,
22111
+ scope_type: scope.type,
22112
+ agent_id: candidate.agent_id,
22113
+ last_error: errorMessage(error),
22114
+ reportable_error: { error, extra: { session_id: candidate.session_id, tenant_id: candidate.tenant_id } }
22115
+ });
22116
+ return skipped("failed");
22117
+ }
22118
+ }
22119
+ function memoryIngestLoop(deps) {
22120
+ return {
22121
+ name: MEMORY_INGEST_LOOP_NAME,
22122
+ intervalMs: deps.config.intervalMs,
22123
+ async tick(signal) {
22124
+ if (signal.aborted) {
22125
+ return;
22126
+ }
22127
+ await runMemoryIngestPass({ deps, signal });
22128
+ }
22129
+ };
22130
+ }
22131
+
21618
22132
  // src/controller/sandboxEnvBuild.ts
21619
22133
  import { TrueForgeApi, TrueForgeError } from "@truefoundry/trueforge-sdk";
21620
22134
  var SANDBOX_ENV_BUILD_INTERVAL_MS = 5e3;
@@ -21665,17 +22179,18 @@ function sandboxEnvBuildLoop(params) {
21665
22179
 
21666
22180
  // src/controller.ts
21667
22181
  function createController(params) {
21668
- return new Controller({
21669
- loops: [
21670
- scheduleDispatchLoop({
21671
- scheduleStore: params.scheduleStore,
21672
- withTransaction: params.withTransaction,
21673
- logger: params.logger
21674
- }),
21675
- sandboxEnvBuildLoop({ logger: params.logger })
21676
- ],
21677
- logger: params.logger
21678
- });
22182
+ const loops = [
22183
+ scheduleDispatchLoop({
22184
+ scheduleStore: params.scheduleStore,
22185
+ withTransaction: params.withTransaction,
22186
+ logger: params.logger
22187
+ }),
22188
+ sandboxEnvBuildLoop({ logger: params.logger })
22189
+ ];
22190
+ if (params.memory !== void 0) {
22191
+ loops.push(memoryIngestLoop({ ...params.memory, logger: params.logger, now: () => /* @__PURE__ */ new Date() }));
22192
+ }
22193
+ return new Controller({ loops, logger: params.logger });
21679
22194
  }
21680
22195
 
21681
22196
  // src/db/McpServerWithAuthStore.ts
@@ -22960,11 +23475,11 @@ import {
22960
23475
  toolResultResponse
22961
23476
  } from "@truefoundry/trueforge-core/core";
22962
23477
  import { HTTPException as HTTPException25 } from "hono/http-exception";
22963
- import { z as z45 } from "zod";
23478
+ import { z as z47 } from "zod";
22964
23479
  var X_TFG_TOOLS = "x-tfg-tools";
22965
23480
  var MAX_TFG_TOOLS = 16;
22966
23481
  var MAX_TFG_TOOLS_HEADER_LENGTH = 16e3;
22967
- var InlineToolsHeaderSchema = z45.array(McpToolSchema);
23482
+ var InlineToolsHeaderSchema = z47.array(McpToolSchema);
22968
23483
  function assertTfgToolsHeaderAllowed(input) {
22969
23484
  if (!input.isTrueFoundryMode) {
22970
23485
  throw new HTTPException25(400, { message: `${X_TFG_TOOLS} requires TrueFoundry mode` });
@@ -23061,9 +23576,9 @@ var InlineClientSideTools = class extends ClientSideTool {
23061
23576
 
23062
23577
  // src/truefoundry/perServerMcpHeaders.ts
23063
23578
  import { HTTPException as HTTPException26 } from "hono/http-exception";
23064
- import { z as z46 } from "zod";
23579
+ import { z as z48 } from "zod";
23065
23580
  var X_TFG_MCP_HEADERS = "x-tfg-mcp-headers";
23066
- var PerServerMcpHeadersSchema = z46.record(z46.string().min(1), z46.record(z46.string().min(1), z46.string()));
23581
+ var PerServerMcpHeadersSchema = z48.record(z48.string().min(1), z48.record(z48.string().min(1), z48.string()));
23067
23582
  function parsePerServerMcpHeaders(raw) {
23068
23583
  let decoded;
23069
23584
  try {
@@ -23096,7 +23611,7 @@ import {
23096
23611
  import { HTTPException as HTTPException27 } from "hono/http-exception";
23097
23612
  import { LRUCache } from "lru-cache";
23098
23613
  import { fetch as undiciFetch3 } from "undici";
23099
- import { z as z49 } from "zod";
23614
+ import { z as z51 } from "zod";
23100
23615
 
23101
23616
  // src/truefoundry/internalTls.ts
23102
23617
  function normalizeInternalTlsUrl(input) {
@@ -23110,20 +23625,20 @@ function createInternalTlsDispatcher(options) {
23110
23625
  }
23111
23626
 
23112
23627
  // src/truefoundry/mapSfyAgentSkills.ts
23113
- import { z as z47 } from "zod";
23114
- var SfyRegistryManifestSchema = z47.object({
23628
+ import { z as z49 } from "zod";
23629
+ var SfyRegistryManifestSchema = z49.object({
23115
23630
  // Display label only — not TF ResourceName / DNS-label rules.
23116
- name: z47.string().min(1),
23117
- version: z47.number().int().positive(),
23631
+ name: z49.string().min(1),
23632
+ version: z49.number().int().positive(),
23118
23633
  // SFY field is `ml_repo`; TrueForge wire is `repository_name`.
23119
- ml_repo: z47.string().min(1),
23120
- source: z47.object({
23121
- description: z47.string().min(1).optional()
23634
+ ml_repo: z49.string().min(1),
23635
+ source: z49.object({
23636
+ description: z49.string().min(1).optional()
23122
23637
  }).optional()
23123
23638
  });
23124
- var SfyRegistrySkillSchema = z47.object({
23125
- latest_version: z47.object({
23126
- fqn: z47.string().min(1),
23639
+ var SfyRegistrySkillSchema = z49.object({
23640
+ latest_version: z49.object({
23641
+ fqn: z49.string().min(1),
23127
23642
  manifest: SfyRegistryManifestSchema
23128
23643
  })
23129
23644
  }).transform(({ latest_version }) => ({
@@ -23134,20 +23649,20 @@ var SfyRegistrySkillSchema = z47.object({
23134
23649
  repository_name: latest_version.manifest.ml_repo,
23135
23650
  version: latest_version.manifest.version
23136
23651
  }));
23137
- var SfyRegistrySkillVersionSchema = z47.object({
23138
- agent_skill_id: z47.string().min(1),
23139
- fqn: z47.string().min(1),
23652
+ var SfyRegistrySkillVersionSchema = z49.object({
23653
+ agent_skill_id: z49.string().min(1),
23654
+ fqn: z49.string().min(1),
23140
23655
  manifest: SfyRegistryManifestSchema
23141
23656
  });
23142
- var ResolvedAgentSkillVersionSchema = z47.object({
23143
- fqn: z47.string().min(1),
23144
- name: z47.string().min(1),
23145
- description: z47.string().min(1),
23146
- skill_md_content: z47.string().nullable().optional(),
23147
- presigned_url: z47.string().min(1).optional()
23657
+ var ResolvedAgentSkillVersionSchema = z49.object({
23658
+ fqn: z49.string().min(1),
23659
+ name: z49.string().min(1),
23660
+ description: z49.string().min(1),
23661
+ skill_md_content: z49.string().nullable().optional(),
23662
+ presigned_url: z49.string().min(1).optional()
23148
23663
  });
23149
- var ResolveAgentSkillVersionsResponseSchema = z47.object({
23150
- skills: z47.array(ResolvedAgentSkillVersionSchema)
23664
+ var ResolveAgentSkillVersionsResponseSchema = z49.object({
23665
+ skills: z49.array(ResolvedAgentSkillVersionSchema)
23151
23666
  });
23152
23667
  function mapSfyRegistrySkills(rows) {
23153
23668
  return rows.map((row) => SfyRegistrySkillSchema.parse(row));
@@ -23171,48 +23686,48 @@ function mapResolvedAgentSkillVersions(payload) {
23171
23686
  }
23172
23687
 
23173
23688
  // src/truefoundry/mapSfyMcpServers.ts
23174
- import { z as z48 } from "zod";
23689
+ import { z as z50 } from "zod";
23175
23690
  var MCP_PROXY_BASE_URL_TEMPLATE = "{{mcpProxyBaseURL}}";
23176
- var IsoInstantSchema = z48.union([z48.string().min(1), z48.date()]).transform((value, ctx) => {
23691
+ var IsoInstantSchema = z50.union([z50.string().min(1), z50.date()]).transform((value, ctx) => {
23177
23692
  if (value instanceof Date) {
23178
23693
  if (!Number.isFinite(value.getTime())) {
23179
23694
  ctx.addIssue({ code: "custom", message: "Invalid Date" });
23180
- return z48.NEVER;
23695
+ return z50.NEVER;
23181
23696
  }
23182
23697
  return value.toISOString();
23183
23698
  }
23184
23699
  const ms = Date.parse(value);
23185
23700
  if (!Number.isFinite(ms)) {
23186
23701
  ctx.addIssue({ code: "custom", message: "Invalid ISO timestamp" });
23187
- return z48.NEVER;
23702
+ return z50.NEVER;
23188
23703
  }
23189
23704
  return new Date(ms).toISOString();
23190
23705
  });
23191
- var SfyMcpServerRowSchema = z48.object({
23192
- id: z48.string().min(1),
23193
- name: z48.string().min(1),
23194
- proxyUrl: z48.string().min(1),
23706
+ var SfyMcpServerRowSchema = z50.object({
23707
+ id: z50.string().min(1),
23708
+ name: z50.string().min(1),
23709
+ proxyUrl: z50.string().min(1),
23195
23710
  createdAt: IsoInstantSchema,
23196
23711
  updatedAt: IsoInstantSchema,
23197
- manifest: z48.object({
23198
- description: z48.string().min(1).optional(),
23199
- auth_data: z48.object({
23200
- type: z48.string().min(1).optional()
23712
+ manifest: z50.object({
23713
+ description: z50.string().min(1).optional(),
23714
+ auth_data: z50.object({
23715
+ type: z50.string().min(1).optional()
23201
23716
  }).optional()
23202
23717
  }).optional()
23203
23718
  });
23204
- var SfyMcpAuthStatusAuthenticatedSchema = z48.object({ status: z48.literal("authenticated") });
23205
- var SfyMcpAuthStatusNotRequiredSchema = z48.object({ status: z48.literal("authentication_not_required") });
23206
- var SfyMcpAuthStatusRequiredSchema = z48.object({ status: z48.literal("authentication_required") });
23719
+ var SfyMcpAuthStatusAuthenticatedSchema = z50.object({ status: z50.literal("authenticated") });
23720
+ var SfyMcpAuthStatusNotRequiredSchema = z50.object({ status: z50.literal("authentication_not_required") });
23721
+ var SfyMcpAuthStatusRequiredSchema = z50.object({ status: z50.literal("authentication_required") });
23207
23722
  var SfyMcpAuthorizeRequiredSchema = SfyMcpAuthStatusRequiredSchema.extend({
23208
- authorization_endpoint: z48.url()
23723
+ authorization_endpoint: z50.url()
23209
23724
  });
23210
- var SfyMcpAuthStatusSchema = z48.discriminatedUnion("status", [
23725
+ var SfyMcpAuthStatusSchema = z50.discriminatedUnion("status", [
23211
23726
  SfyMcpAuthStatusAuthenticatedSchema,
23212
23727
  SfyMcpAuthStatusRequiredSchema,
23213
23728
  SfyMcpAuthStatusNotRequiredSchema
23214
23729
  ]);
23215
- var SfyMcpAuthorizeResultSchema = z48.discriminatedUnion("status", [
23730
+ var SfyMcpAuthorizeResultSchema = z50.discriminatedUnion("status", [
23216
23731
  SfyMcpAuthStatusAuthenticatedSchema,
23217
23732
  SfyMcpAuthorizeRequiredSchema,
23218
23733
  SfyMcpAuthStatusNotRequiredSchema
@@ -23286,32 +23801,32 @@ var VEND_TOKEN_PATH = "internal/vend-token";
23286
23801
  var SUBJECTS_PEEK_PATH = "v1/subjects/peek";
23287
23802
  var AGENT_SKILLS_PAGE_SIZE = 100;
23288
23803
  var AGENT_SKILL_RESOLVE_CHUNK_SIZE = 50;
23289
- var SessionSubjectSchema = z49.object({
23290
- subjectId: z49.string().min(1),
23291
- subjectType: z49.string().min(1),
23292
- subjectDisplayName: z49.string().nullable().optional(),
23293
- subjectSlug: z49.string().nullable().optional()
23804
+ var SessionSubjectSchema = z51.object({
23805
+ subjectId: z51.string().min(1),
23806
+ subjectType: z51.string().min(1),
23807
+ subjectDisplayName: z51.string().nullable().optional(),
23808
+ subjectSlug: z51.string().nullable().optional()
23294
23809
  });
23295
- var GetSessionUserSchema = z49.object({
23296
- tenantName: z49.string().min(1),
23297
- roles: z49.array(z49.string()),
23810
+ var GetSessionUserSchema = z51.object({
23811
+ tenantName: z51.string().min(1),
23812
+ roles: z51.array(z51.string()),
23298
23813
  subject: SessionSubjectSchema
23299
23814
  });
23300
- var GetSessionUnauthenticatedSchema = z49.object({
23301
- user: z49.null()
23815
+ var GetSessionUnauthenticatedSchema = z51.object({
23816
+ user: z51.null()
23302
23817
  });
23303
- var GetSessionAuthenticatedSchema = z49.object({
23818
+ var GetSessionAuthenticatedSchema = z51.object({
23304
23819
  user: GetSessionUserSchema
23305
23820
  });
23306
- var GetSessionWireSchema = z49.union([GetSessionUnauthenticatedSchema, GetSessionAuthenticatedSchema]);
23307
- var TenantControlPlaneUrlSchema = z49.object({
23308
- controlPlaneURL: z49.url()
23821
+ var GetSessionWireSchema = z51.union([GetSessionUnauthenticatedSchema, GetSessionAuthenticatedSchema]);
23822
+ var TenantControlPlaneUrlSchema = z51.object({
23823
+ controlPlaneURL: z51.url()
23309
23824
  });
23310
- var ListResponseSchema = z49.union([
23311
- z49.array(z49.unknown()),
23312
- z49.object({
23313
- data: z49.array(z49.unknown()).catch([]),
23314
- pagination: z49.object({ total: z49.number().optional() }).optional()
23825
+ var ListResponseSchema = z51.union([
23826
+ z51.array(z51.unknown()),
23827
+ z51.object({
23828
+ data: z51.array(z51.unknown()).catch([]),
23829
+ pagination: z51.object({ total: z51.number().optional() }).optional()
23315
23830
  })
23316
23831
  ]);
23317
23832
  var SERVICE_FOUNDRY_OPERATIONS = {
@@ -23334,34 +23849,34 @@ var SERVICE_FOUNDRY_OPERATIONS = {
23334
23849
  vendToken: "vend_token",
23335
23850
  peekUsers: "users"
23336
23851
  };
23337
- var ServiceFoundryErrorSchema = z49.object({
23338
- message: z49.union([z49.string(), z49.array(z49.string())]).optional()
23852
+ var ServiceFoundryErrorSchema = z51.object({
23853
+ message: z51.union([z51.string(), z51.array(z51.string())]).optional()
23339
23854
  });
23340
- var PutRemoteAgentResponseSchema = z49.object({
23341
- agentId: z49.string().min(1)
23855
+ var PutRemoteAgentResponseSchema = z51.object({
23856
+ agentId: z51.string().min(1)
23342
23857
  });
23343
- var AgentPermissionSchema = z49.enum(["READ_AGENT", "USE_AGENT", "MANAGE_AGENT", "DELETE_AGENT"]);
23344
- var AgentPermissionsSchema = z49.record(
23345
- z49.string(),
23346
- z49.array(z49.string()).transform(
23858
+ var AgentPermissionSchema = z51.enum(["READ_AGENT", "USE_AGENT", "MANAGE_AGENT", "DELETE_AGENT"]);
23859
+ var AgentPermissionsSchema = z51.record(
23860
+ z51.string(),
23861
+ z51.array(z51.string()).transform(
23347
23862
  (permissions) => permissions.flatMap((permission) => {
23348
23863
  const parsed = AgentPermissionSchema.safeParse(permission);
23349
23864
  return parsed.success ? [parsed.data] : [];
23350
23865
  })
23351
23866
  )
23352
23867
  );
23353
- var VendTokenResponseSchema = z49.object({
23354
- subjectToken: z49.string().min(1),
23355
- actorToken: z49.string().min(1)
23868
+ var VendTokenResponseSchema = z51.object({
23869
+ subjectToken: z51.string().min(1),
23870
+ actorToken: z51.string().min(1)
23356
23871
  });
23357
- var PeekUserSchema = z49.object({
23358
- id: z49.string().min(1),
23359
- name: z49.string().nullish(),
23360
- email: z49.string().min(1)
23872
+ var PeekUserSchema = z51.object({
23873
+ id: z51.string().min(1),
23874
+ name: z51.string().nullish(),
23875
+ email: z51.string().min(1)
23361
23876
  });
23362
- var PeekUsersResponseSchema = z49.object({
23363
- users: z49.array(PeekUserSchema),
23364
- totalUsers: z49.number().int().nonnegative()
23877
+ var PeekUsersResponseSchema = z51.object({
23878
+ users: z51.array(PeekUserSchema),
23879
+ totalUsers: z51.number().int().nonnegative()
23365
23880
  });
23366
23881
  async function readServiceFoundryErrorMessage(response) {
23367
23882
  const body = await response.json().catch(() => void 0);
@@ -23766,7 +24281,7 @@ var TrueFoundryServiceFoundryServerClient = class {
23766
24281
  accessToken: input.accessToken,
23767
24282
  method: "GET"
23768
24283
  });
23769
- const parsed = z49.array(z49.string()).safeParse(payload);
24284
+ const parsed = z51.array(z51.string()).safeParse(payload);
23770
24285
  if (!parsed.success) {
23771
24286
  this.#logger.error("TrueFoundry ServiceFoundry tenant permissions response was malformed", {
23772
24287
  ...extractErrorLogFields8(parsed.error),
@@ -24273,24 +24788,24 @@ init_mcpServerStore();
24273
24788
  init_config();
24274
24789
  import { SUPPORTED_REASONING_EFFORTS as SUPPORTED_REASONING_EFFORTS3 } from "@truefoundry/trueforge-core/core";
24275
24790
  import { HTTPException as HTTPException29 } from "hono/http-exception";
24276
- import { z as z50 } from "zod";
24277
- var ModelParamSchema = z50.object({
24278
- key: z50.string(),
24279
- supportedValues: z50.array(z50.string()).optional()
24791
+ import { z as z52 } from "zod";
24792
+ var ModelParamSchema = z52.object({
24793
+ key: z52.string(),
24794
+ supportedValues: z52.array(z52.string()).optional()
24280
24795
  });
24281
- var MetadataSchema = z50.object({
24282
- limits: z50.object({
24283
- context_window: z50.number().optional(),
24284
- max_input_tokens: z50.number().optional(),
24285
- max_output_tokens: z50.number().optional(),
24286
- max_tokens: z50.number().optional()
24796
+ var MetadataSchema = z52.object({
24797
+ limits: z52.object({
24798
+ context_window: z52.number().optional(),
24799
+ max_input_tokens: z52.number().optional(),
24800
+ max_output_tokens: z52.number().optional(),
24801
+ max_tokens: z52.number().optional()
24287
24802
  }).optional(),
24288
- params: z50.array(ModelParamSchema).optional()
24803
+ params: z52.array(ModelParamSchema).optional()
24289
24804
  });
24290
- var IntegrationSchema = z50.object({
24291
- name: z50.string().min(1),
24292
- manifest: z50.object({ model_types: z50.array(z50.string()).optional() }),
24293
- providerAccount: z50.object({ name: z50.string().min(1) }),
24805
+ var IntegrationSchema = z52.object({
24806
+ name: z52.string().min(1),
24807
+ manifest: z52.object({ model_types: z52.array(z52.string()).optional() }),
24808
+ providerAccount: z52.object({ name: z52.string().min(1) }),
24294
24809
  metadata: MetadataSchema.optional()
24295
24810
  });
24296
24811
  function toReasoningEfforts(params) {
@@ -24348,11 +24863,11 @@ function filterEnvModels(input) {
24348
24863
  const allowed = new Set(allowedAccounts);
24349
24864
  return input.models.filter((model) => allowed.has(model.accountName));
24350
24865
  }
24351
- var InstallationSchema = z50.object({
24352
- isDefault: z50.boolean().optional(),
24353
- manifest: z50.object({ url: z50.string().min(1) })
24866
+ var InstallationSchema = z52.object({
24867
+ isDefault: z52.boolean().optional(),
24868
+ manifest: z52.object({ url: z52.string().min(1) })
24354
24869
  });
24355
- var InstallationsEnvelopeSchema = z50.union([z50.array(z50.unknown()), z50.object({ data: z50.array(z50.unknown()) })]);
24870
+ var InstallationsEnvelopeSchema = z52.union([z52.array(z52.unknown()), z52.object({ data: z52.array(z52.unknown()) })]);
24356
24871
  function resolveDefaultGatewayUrl(payload) {
24357
24872
  const envelope = InstallationsEnvelopeSchema.parse(payload);
24358
24873
  const rows = Array.isArray(envelope) ? envelope : envelope.data;