import { isMemorySubsystemEnabled, shouldInjectMemoryPrefetchThisTurn } from "./memory-config.js";
import { extractAgentUserPlainText } from "./user-message-text.js";
import { injectPrefetchIntoUserMessage } from "./inject-prefetch.js";
//#region src/agent/memory/prefetch-coordinator.ts
var MemoryPrefetchCoordinator = class {
	opts;
	/** Per-session user-message index, incremented before each `applyPrefetch` call. */
	prefetchUserTurn = /* @__PURE__ */ new Map();
	constructor(opts) {
		this.opts = opts;
	}
	/** Forget a session entirely (called when AgentManager removes the agent). */
	forgetSession(sessionKey) {
		this.prefetchUserTurn.delete(sessionKey);
	}
	/** Tear down all per-session state (process stop / hot reload). */
	clear() {
		this.prefetchUserTurn.clear();
	}
	/**
	* Prepend the prefetched memory fence to the user turn when the cadence
	* config says we should. Returns the original message untouched otherwise.
	*/
	async applyToUserMessage(userMessage, sessionKey) {
		const cfg = this.opts.getConfig();
		if (!isMemorySubsystemEnabled(cfg)) return userMessage;
		const plain = extractAgentUserPlainText(userMessage);
		const turn = (this.prefetchUserTurn.get(sessionKey) ?? 0) + 1;
		this.prefetchUserTurn.set(sessionKey, turn);
		if (!shouldInjectMemoryPrefetchThisTurn(cfg, turn)) return userMessage;
		return injectPrefetchIntoUserMessage(this.opts.getMemoryManagerForSession(sessionKey), sessionKey, userMessage, plain);
	}
	/** Post-turn: push the latest exchange to external providers + warm next prefetch. */
	afterTurn(sessionKey, userPlainText) {
		if (!isMemorySubsystemEnabled(this.opts.getConfig())) return;
		const assistant = this.opts.getLastAssistantContent(sessionKey) ?? "";
		const mm = this.opts.getMemoryManagerForSession(sessionKey);
		mm.syncAll(userPlainText, assistant, { sessionId: sessionKey });
		mm.queuePrefetchAll(userPlainText, { sessionId: sessionKey });
	}
};
//#endregion
export { MemoryPrefetchCoordinator };

//# sourceMappingURL=prefetch-coordinator.js.map