import { t as runAgentTurn } from "./unified-runner-4O0ifBsI.js";
import "./registry-Sbac4a4z.js";
import "./paths-By0XjHBk.js";
import "./utils-CTPsqyE_.js";
import { t as createSubsystemLogger } from "./subsystem-CHbO_DkH.js";
import "./auth-profiles-Ce7R_25e.js";
import "./exec-DuYbft0z.js";
import "./agent-scope-DOrZjOnW.js";
import "./model-selection-7wdmO-Iw.js";
import "./file-lock-BVUYnlQv.js";
import "./agent-paths-BbZSGrUA.js";
import "./pi-embedded-helpers-D-OFjhdI.js";
import "./config-B4jkreCN.js";
import "./boolean-CbZoNRMn.js";
import "./env-BRnPI9sO.js";
import "./shell-env-Dc3iU7HK.js";
import "./manifest-registry-D1MLZEjS.js";
import "./sandbox-BkznAPKO.js";
import "./chrome-DJChpTwP.js";
import "./tailscale-DpKBMIvx.js";
import "./auth-Bkx-QuRN.js";
import "./server-context-ChcbJgNo.js";
import "./frontmatter-B_jqcova.js";
import "./skills-BwDmcZdt.js";
import "./routes-ivqbutvM.js";
import "./redact-B3O-RBO1.js";
import "./errors-bI7Tdx75.js";
import "./fs-safe-BdejYjW8.js";
import "./paths-DObzwe08.js";
import "./ssrf-DOZRI5XH.js";
import "./image-ops-L70xVnpG.js";
import "./ports-gxLM5ahL.js";
import "./trash-_YhavPQI.js";
import "./sessions-Dxf5Kjig.js";
import "./dock-hF45sewN.js";
import "./message-channel-DgjXWzf-.js";
import "./plugins-CF5skkHh.js";
import "./send-B0jHSNMF.js";
import "./paths-BtvQ7JvU.js";
import "./thinking-COroyVA5.js";
import "./tokens-0yh2UnJq.js";
import "./deliver-lTZLIQqf.js";
import "./diagnostic-DbT9t0Sh.js";
import "./diagnostic-session-state-DnkpMfCl.js";
import "./model-auth-1EAQvYRv.js";
import "./github-copilot-token-D-FdDfee.js";
import "./models-config-B5Xxy-c-.js";
import "./pi-auth-json-Db8XJVGL.js";
import "./session-cost-usage-D3mgssM_.js";
import "./session-utils-Cs1jlD-q.js";
import "./with-timeout-DPR4A2dx.js";
import "./reply-prefix-BFNeXT65.js";
import "./memory-BZ24UkLW.js";
import "./manager-Cw7IJGbB.js";
import "./sqlite-Cod7C5ba.js";
import "./chunk-BxfKjCUx.js";
import "./markdown-tables-CS1Tvb3z.js";
import "./fetch-guard-JHxT9355.js";
import "./local-roots-CgDCgCuM.js";
import "./commands-DUzLGgEZ.js";
import "./commands-registry-Ca5hh7nh.js";
import "./client-DH75FlQF.js";
import "./call-AZ9vNhST.js";
import "./pairing-token-Dcy37-4s.js";
import "./tool-display-DFOL6UQ9.js";
import "./skills-remote-bz71Bstn.js";
import "./workspace-dirs-jKFQf7of.js";
import "./pi-model-discovery-ClQLvlCW.js";
import "./model-catalog-IWi6-nY9.js";
import "./skill-commands-DDGGlq68.js";
import "./pairing-store-BNhJOnWn.js";
import "./exec-approvals-DioSaIeH.js";
import "./nodes-screen-De9ma6e1.js";
import "./breakdown-B_Dhhm3K.js";
import "./control-service-D8kKOts5.js";
import "./stagger-DQs772BN.js";
import "./channel-selection-H1qOf0q-.js";
import "./delivery-queue-OAc7hsIs.js";
import "./bindings-DIhsYGa_.js";
import "./resolve-route-C1IIA6kH.js";
import "./links-Bqr0FxXx.js";
import "./cli-utils-CuyGL3rq.js";
import "./help-format-7hFcsqss.js";
import "./progress-swt2y17x.js";
import "./memory-cli-0HHYm-B8.js";
import "./logging-BWknayJl.js";
import "./replies-CbXXjn9X.js";
import "./pi-tools.policy-H2t-Xkfc.js";
import "./model-MUMSB_7d.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 };