import { o as createSubsystemLogger } from "./entry.js";
import "./auth-profiles-D11Xw15i.js";
import "./exec-CzwIUObA.js";
import "./agent-scope-C-Jte08L.js";
import "./model-selection-CMx1evaF.js";
import "./file-lock-DrmXX3vL.js";
import "./agent-paths-DryQawbH.js";
import "./pi-auth-json-mn8xSJKs.js";
import "./model-B4Btg-Q6.js";
import "./pi-model-discovery-EgBaDO8n.js";
import "./frontmatter-PrEWR41G.js";
import "./skills-cLBEdkqu.js";
import "./manifest-registry-CVLmi8rz.js";
import "./config-D7TcU4qN.js";
import "./shell-env-CTYaxUs_.js";
import "./client-BOd5o3Kp.js";
import "./call-DTshgdlW.js";
import "./message-channel-DXToSaWK.js";
import "./pairing-token-B-OTYROz.js";
import { T as runAgentTurn } from "./subagent-registry-CVhLz4p3.js";
import "./sessions-Dn6VXn4p.js";
import "./plugins-BsEhWvLn.js";
import "./send-Dq252-bi.js";
import "./with-timeout-B9GM8DPj.js";
import "./deliver-DIK2emIV.js";
import "./diagnostic-IdKKvrDQ.js";
import "./diagnostic-session-state-CIjIGxEE.js";
import "./pi-embedded-helpers-BQjRftRI.js";
import "./sandbox-DjKcZavm.js";
import "./chrome-D1eO2jfe.js";
import "./tailscale-FeJ1M0mP.js";
import "./auth-pHRwjgkx.js";
import "./server-context-DrAh6Cgw.js";
import "./routes-wLkmjLj9.js";
import "./redact-Dj3r1_tS.js";
import "./errors-BmdGLmRC.js";
import "./fs-safe-D0xrTzGw.js";
import "./paths-8yCI1Car.js";
import "./ssrf-BZFvPKEu.js";
import "./image-ops-FPBHTBd0.js";
import "./ports-uA7P2qIK.js";
import "./trash-Bx4LIudf.js";
import "./dock-DZ6SgvTh.js";
import "./paths-DtiEyjsC.js";
import "./thinking-BZDIJMl_.js";
import "./model-auth-Byr7Gic_.js";
import "./github-copilot-token-B5y4__YM.js";
import "./models-config-CiR_RUxw.js";
import "./reply-prefix-DV3KhOhL.js";
import "./memory-C02Znuee.js";
import "./manager-DH00nlW8.js";
import "./sqlite-9jF_eajd.js";
import "./chunk-B2lBXhR0.js";
import "./markdown-tables-BEdkErjm.js";
import "./fetch-guard-3_W2W6u_.js";
import "./local-roots-Bm30yHHs.js";
import "./commands-BiW8npr7.js";
import "./commands-registry-D8LQ9fss.js";
import "./tool-display-DxbOx1Kx.js";
import "./tokens-CC6jvm1-.js";
import "./skills-remote-DSGpkPJE.js";
import "./redact-identifier-BOxAUdff.js";
import "./workspace-dirs-wlRR65M3.js";
import "./model-catalog-CzKsiNZA.js";
import "./session-utils-Zpe3t68b.js";
import "./skill-commands-BXP2zJNy.js";
import "./pairing-store-C4KBIVqJ.js";
import "./exec-approvals-DEjIocmZ.js";
import "./nodes-screen-_JvT4DjZ.js";
import "./session-cost-usage-CJWHHY-C.js";
import "./breakdown-Cszrv-Lf.js";
import "./control-service-CG6l_Yap.js";
import "./stagger-DUVGiPYV.js";
import "./channel-selection-CmU8iVio.js";
import "./delivery-queue-B2oigbh4.js";
import "./bindings-BRZBH7eX.js";
import "./resolve-route-BVJ4-d9c.js";
import "./links-Dnmd-RS-.js";
import "./cli-utils-DXfA5936.js";
import "./help-format-Dbp8yEhl.js";
import "./progress-CI19Xh3z.js";
import "./memory-cli-083UJtVJ.js";
import "./logging-UO6tk8Em.js";
import "./replies-CLREUzzB.js";
import "./pi-tools.policy-06k__URR.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 };