import { c as createSseStream, S as SSE_HEADERS, a as encodeStreamEvent } from './http-CoxxIFTY.js';
import { g as getTaskAccessor } from './data-accessor-CVbz8X_7.js';
import { l as listTasks } from './list-DfOyEStk.js';
import { c as resolveGatewayBaseUrl } from './_dispatch-ncuRztUQ.js';
import './paths-2M_UxD_H.js';
import 'node:fs';
import 'node:path';
import 'node:os';
import 'node:events';
import 'node:diagnostics_channel';
import 'fs';
import 'events';
import 'util';
import 'path';
import 'assert';
import 'worker_threads';
import 'module';
import 'node:url';
import 'url';
import 'buffer';
import 'node:module';
import 'node:child_process';
import 'node:crypto';
import 'node:process';
import 'node:async_hooks';
import './dist4-CiQ5cizO.js';
import './dual-scope-db-ATrwq0LH.js';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './adapters-D2gEs_5L.js';
import './registry2-BSyCTA3q.js';
import './tasks-CnwUAUXf.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './chunk-DDP5xfzh.js';
import './sqlite-Dsbe0wec.js';
import './memory-schema-Bi7cChwo.js';
import './agent-registry-BtE5uhMO.js';
import './nexus-sqlite2-DgTuv9BQ.js';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'constants';
import 'stream';
import 'node:fs/promises';
import 'jsonc-parser';
import '@cleocode/cant';
import 'node:util';
import 'node:buffer';
import 'child_process';
import './branch-lock-qP1EkZ7p.js';
import './src2-DK8DKufK.js';
import 'llmtxt/identity';
import './sessions-j73dkbCI.js';
import './index-Ca4C2M45.js';
import './mvi-helpers-BNsJ8ZpQ.js';
import './session-store-OwQWMSf_.js';
import './session-manifest-ZHrj54LR.js';
import './storage-B9UA3BHR.js';
import './config-B0nEjgSh.js';
import './json-DXl7iDYg.js';
import './data-safety-central-vmfu_Y4J.js';
import './sqlite-data-accessor-C59wZ0zp.js';
import './cross-db-cleanup-C_FLyd-6.js';
import './query-ops-BDMaTdYw.js';
import 'node:net';
import './src3-CMSGYxDI.js';
import './local-model-fit2-J1xCIhC_.js';
import './credential-pool-B04qO8at.js';
import './catalog-model-resolver2-Cexk2TN0.js';
import './role-resolver-DF9BQ_U6.js';
import './identity2-DeAB5RXE.js';
import './role-executor-C4-3bmgC.js';
import 'node:stream';
import 'crypto';
import 'os';
import 'node:http2';
import 'fs/promises';
import './models-catalog-DG3aPok8.js';
import './catalog-resolver2-c0qfF34B.js';
import './providers-CmIcBfg-.js';
import './brain-maintenance-bSR6GwAG.js';
import './graph-auto-populate2-DYsUNGSL.js';
import './temporal-supersession-BZ46j30w.js';
import './typed-query-l1D_QElt.js';
import './llm-backend-resolver-BPbvttS4.js';
import '@ai-sdk/provider-utils';
import './observer-reflector2-D8nxuglX.js';
import './learnings2-2m2p7lzT.js';
import './memory-accessor2-BzlgmY-Z.js';
import './quality-scoring-CCPuRQmJ.js';
import './patterns2-DYKfsbwN.js';
import './graph-memory-bridge2-C7Y32Mk4.js';
import './sigil2-DftKm7Um.js';
import './services-Dlf3Gefq.js';
import './audit4-S87oN-BC.js';
import 'process';

//#region src/routes/api/tasks/subscribe/+server.ts
/** Poll cadence (ms) for the Studio-local board-change detector fallback. */
var POLL_INTERVAL_MS = 2e3;
/** Connect timeout (ms) for the gateway proxy attempt before falling back. */
var GATEWAY_CONNECT_TIMEOUT_MS = 1500;
/**
* Attempt to proxy the gateway `GET /v1/tasks/subscribe` SSE. Returns the
* upstream `Response` (its `text/event-stream` body) on success, or `null` when
* the daemon listener is unreachable (so the caller falls back to the local
* board-change detector).
*
* @param baseUrl - The resolved gateway base URL.
* @param root - Optional saga/parent scope forwarded as `?root=`.
* @param signal - Abort signal tied to the client disconnect.
* @returns The upstream SSE response, or `null` when unreachable.
*/
async function tryProxyGatewayStream(baseUrl, root, signal) {
	const url = `${baseUrl}/v1/tasks/subscribe${root ? `?root=${encodeURIComponent(root)}` : ""}`;
	const connectCtl = new AbortController();
	const timer = setTimeout(() => connectCtl.abort(), GATEWAY_CONNECT_TIMEOUT_MS);
	const onClientAbort = () => connectCtl.abort();
	signal.addEventListener("abort", onClientAbort);
	try {
		const res = await fetch(url, {
			headers: { accept: "text/event-stream" },
			signal: connectCtl.signal
		});
		clearTimeout(timer);
		signal.removeEventListener("abort", onClientAbort);
		if (!res.ok || res.body === null) return null;
		return res;
	} catch {
		clearTimeout(timer);
		signal.removeEventListener("abort", onClientAbort);
		return null;
	}
}
var GET = async ({ locals, url, request }) => {
	const ctx = locals.projectCtx;
	const root = url.searchParams.get("root");
	const upstream = await tryProxyGatewayStream(resolveGatewayBaseUrl(), root, request.signal);
	if (upstream?.body) return new Response(upstream.body, {
		status: 200,
		headers: {
			"Content-Type": "text/event-stream",
			"Cache-Control": "no-cache",
			Connection: "keep-alive",
			"X-Accel-Buffering": "no"
		}
	});
	const requestId = `studio-${Date.now().toString(36)}`;
	const projectPath = ctx.projectPath;
	const stream = createSseStream((emitter) => {
		let seq = 0;
		let lastUpdated = "";
		let lastCount = -1;
		/** Guards against overlapping ticks when a probe outlives its interval. */
		let probing = false;
		/** Emit one canonical board-event `data` frame (dropped after close). */
		function emit(event) {
			const frame = {
				kind: "data",
				seq,
				data: {
					scope: "tasks.board",
					root: root ?? null,
					event,
					ts: (/* @__PURE__ */ new Date()).toISOString()
				},
				requestId
			};
			emitter.sendRaw(encodeStreamEvent(frame));
			seq += 1;
		}
		/**
		* Derive the board-change signal through the `@cleocode/core` facade: the
		* latest `updatedAt` + the non-archived task count. CORE-first — the same
		* projection `/api/tasks` GET reads, never raw SQL.
		*/
		async function probe() {
			const result = await listTasks({
				excludeArchived: true,
				limit: 1e3
			}, projectPath, await getTaskAccessor(projectPath));
			let latest = "";
			for (const t of result.tasks) {
				const u = t.updatedAt ?? t.createdAt;
				if (typeof u === "string" && u > latest) latest = u;
			}
			return {
				latest,
				count: result.tasks.length
			};
		}
		emit("connected");
		const interval = setInterval(() => {
			if (emitter.closed) {
				clearInterval(interval);
				return;
			}
			if (probing) return;
			probing = true;
			probe().then(({ latest, count }) => {
				if (emitter.closed) return;
				if (lastCount === -1) {
					lastUpdated = latest;
					lastCount = count;
					emit("heartbeat");
					return;
				}
				if (latest !== lastUpdated || count !== lastCount) {
					lastUpdated = latest;
					lastCount = count;
					emit("updated");
				} else emit("heartbeat");
			}).catch(() => {}).finally(() => {
				probing = false;
			});
		}, POLL_INTERVAL_MS);
		return () => clearInterval(interval);
	}, request.signal);
	return new Response(stream, { headers: { ...SSE_HEADERS } });
};

export { GET };
//# sourceMappingURL=_server.ts-971ZW7lt.js.map
