import "./paths-CE7eVGHg.js";
import "./registry-C-JddWwo.js";
import "./agent-scope-B1Ina6jV.js";
import { t as createSubsystemLogger } from "./subsystem-DzRUKS9f.js";
import "./workspace-CsaDUuDn.js";
import { t as runAgentTurn } from "./unified-runner-O3qR5Iie.js";
import "./auth-profiles-BSw0aQND.js";
import "./model-selection-BqshlIZc.js";
import "./deliver-BiWlR84Y.js";
import "./ssrf-DNhyFMRW.js";
import "./boolean-BsqeuxE6.js";
import "./shell-env-B1lDWz4t.js";
import "./manifest-registry-BGJu2aC-.js";
import "./chrome-OTJg3QKn.js";
import "./frontmatter-CJEX1BrH.js";
import "./skills-Dm4gX4Tl.js";
import "./redact-CSGZUFxa.js";
import "./errors-C89ppfp9.js";
import "./local-roots-C7fBKoOI.js";
import "./thinking-h_Lv1OKF.js";
import "./chunk-BkYIP_hB.js";
import "./plugins-B06cTFHC.js";
import "./send-C75uSv6p.js";
import "./paths-BsT3BvfH.js";
import "./tokens-D_vCJSzF.js";
import "./diagnostic-BALvP9wI.js";
import "./diagnostic-session-state-BDfanaOY.js";
import "./manager-DbVMwpDc.js";
import "./github-copilot-token-uhEBNQfj.js";
import "./pi-auth-json-DCGR3yfh.js";
import "./reply-prefix-D0NzzC4I.js";
import "./sqlite-CmMv0ans.js";
import "./markdown-tables-CGqX2WvO.js";
import "./commands-registry-7vX6rnw_.js";
import "./skill-commands-lyuYvLis.js";
import "./pi-model-discovery-Rgm3jE5N.js";
import "./resolve-route-CDsQda0z.js";
import "./replies-D0FYSIJg.js";

//#region src/memory/synthesis.ts
const log = createSubsystemLogger("memory/synthesis");
const SYNTH_TIMEOUT_MS = 6e4;
const MAX_CLUSTER_CHARS = 4e3;
const SYNTH_KINDS = [
	"belief",
	"preference",
	"fact",
	"lesson",
	"identity"
];
/**
* Build a SynthesizeFn that wraps runAgentTurn for L3 stage 4.
*
* Each invocation:
*   1. Concatenates the cluster's source texts (capped to keep the prompt bounded)
*   2. Calls runAgentTurn with tools disabled and a constrained output format
*   3. Parses the response into { kind, text }
*   4. Returns null on any failure — stage 4 treats null as "skip this cluster"
*
* Caller controls provider/model via the current agent's config. On local
* model setups the cost is free so every cluster gets a turn; on remote
* setups callers can bound frequency via `runL3CycleIfDue`'s minInterval.
*/
function createSynthesizer(params) {
	return async (cluster) => {
		if (cluster.sources.length === 0) return null;
		const prompt = buildSynthesisPrompt(formatClusterObservations(cluster.sources));
		const sessionId = `l3-synth-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
		try {
			const result = await runAgentTurn({
				sessionId,
				sessionKey: `temp:l3-synthesis:${params.agentId}`,
				workspaceDir: params.workspaceDir,
				config: params.cfg,
				prompt,
				modelId: params.modelId,
				provider: params.provider,
				timeoutMs: params.timeoutMs ?? SYNTH_TIMEOUT_MS,
				disableTools: true,
				disableMessageTool: true
			});
			if (!result.text) return null;
			const parsed = parseSynthesisOutput(result.text);
			if (!parsed) {
				log.debug("synthesis: unparseable output", { preview: result.text.slice(0, 200) });
				return null;
			}
			return parsed;
		} catch (err) {
			log.warn(`synthesis: runAgentTurn failed: ${String(err)}`);
			return null;
		}
	};
}
function formatClusterObservations(sources) {
	const lines = [];
	let chars = 0;
	for (const source of sources) {
		const body = source.text.trim().replace(/\s+/g, " ");
		if (!body) continue;
		const entry = `- ${body}`;
		if (chars + entry.length > MAX_CLUSTER_CHARS) break;
		lines.push(entry);
		chars += entry.length + 1;
	}
	return lines.join("\n");
}
function buildSynthesisPrompt(observations) {
	return `You are synthesizing long-term memory for Symi. Below are several related observations that appeared repeatedly across past sessions with this user. Collapse them into ONE durable statement that captures what is consistently true.

OBSERVATIONS:
${observations}

OUTPUT RULES (strict):
- First line: "KIND: <one of: belief | preference | fact | lesson | identity>"
- Remaining lines: the single durable statement, one to three sentences.
- No hedging ("maybe", "perhaps", "might"). If uncertain, reply with the single word SKIP.
- No meta-commentary. No quoting the observations back. No headings.
- Prefer concrete, specific language. Retain names, tools, numbers, dates.

Choose KIND by:
- identity — who Symi is to this user, the relationship itself
- preference — user's style, cadence, taste, communication preferences
- fact — stable fact about the user or their world
- lesson — "what goes wrong / what works" patterns learned from past work
- belief — any other durable synthesized truth`;
}
/**
* Parse "KIND: <k>\n<text>" responses. Returns null on malformed output,
* or when the model chose to skip.
*/
function parseSynthesisOutput(raw) {
	const trimmed = raw.trim();
	if (!trimmed) return null;
	if (/^skip\b/i.test(trimmed)) return null;
	const match = trimmed.match(/^KIND:\s*([a-z]+)\s*\n([\s\S]+)$/i);
	if (!match) return null;
	const kindRaw = match[1]?.toLowerCase().trim() ?? "";
	const textRaw = match[2]?.trim() ?? "";
	if (!textRaw) return null;
	const kind = SYNTH_KINDS.find((k) => k === kindRaw);
	if (!kind) return null;
	const text = textRaw.replace(/```[a-z]*\n?|\n?```/g, "").replace(/^\s*[-*]\s+/, "").trim();
	if (text.length < 10) return null;
	return {
		text,
		kind
	};
}

//#endregion
export { createSynthesizer, parseSynthesisOutput };