import { AsyncLocalStorage } from "node:async_hooks";

//#region src/context.ts
var SessionContext = class {
	sessionId;
	traceId;
	userId;
	agentId;
	parentAgentId;
	env;
	customerOrgId;
	agentVersion;
	description;
	context;
	groups;
	tags;
	idleTimeoutMinutes;
	deviceId;
	browserSessionId;
	amplitude;
	trackerManaged;
	skipAutoUserTracking;
	_nextTurnIdFn;
	constructor(options) {
		this.sessionId = options.sessionId;
		this.traceId = options.traceId ?? null;
		this.userId = options.userId ?? null;
		this.agentId = options.agentId ?? null;
		let parentAgentId = options.parentAgentId ?? null;
		if (parentAgentId == null) {
			const enclosing = _sessionStorage.getStore();
			if (enclosing != null && enclosing.agentId != null) parentAgentId = enclosing.agentId;
		}
		this.parentAgentId = parentAgentId;
		this.env = options.env ?? null;
		this.customerOrgId = options.customerOrgId ?? null;
		this.agentVersion = options.agentVersion ?? null;
		this.description = options.description ?? null;
		this.context = options.context ?? null;
		this.groups = options.groups ?? null;
		this.tags = options.tags ?? null;
		this.idleTimeoutMinutes = options.idleTimeoutMinutes ?? null;
		this.deviceId = options.deviceId ?? null;
		this.browserSessionId = options.browserSessionId ?? null;
		this.amplitude = options.amplitude ?? null;
		this.trackerManaged = options.trackerManaged ?? false;
		this.skipAutoUserTracking = options.skipAutoUserTracking ?? false;
		this._nextTurnIdFn = options.nextTurnIdFn ?? null;
	}
	nextTurnId() {
		if (this._nextTurnIdFn != null) return this._nextTurnIdFn();
		return null;
	}
};
const _sessionStorage = new AsyncLocalStorage();
function getActiveContext() {
	return _sessionStorage.getStore() ?? null;
}
/**
* Return `true` when a higher-level tracker (e.g. `AgentAnalyticsTracker`)
* owns event emission for this context.
*
* `patch()` provider wrappers check this to avoid duplicate events.
*/
function isTrackerManaged() {
	const ctx = _sessionStorage.getStore();
	return ctx != null && ctx.trackerManaged;
}
function runWithContext(ctx, fn) {
	return _sessionStorage.run(ctx, fn);
}
function runWithContextAsync(ctx, fn) {
	return _sessionStorage.run(ctx, fn);
}
/**
* Set the active SessionContext for the current async scope.
*
* Returns a cleanup function that restores the previous context.
* Use this in middleware or interceptors where the context must outlive
* the call frame that created it.
*
* For scoped usage, prefer `agent.session()` (callback-based) or
* `runWithContext()`.
*/
function pushContext(ctx) {
	const previous = _sessionStorage.getStore() ?? null;
	_sessionStorage.enterWith(ctx);
	return () => {
		_sessionStorage.enterWith(previous);
	};
}

//#endregion
export { SessionContext, _sessionStorage, getActiveContext, isTrackerManaged, pushContext, runWithContext, runWithContextAsync };
//# sourceMappingURL=context.js.map