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AC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,EACzC,MAAM,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,OAAO,EACxC,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAczB;IAED,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAMxB;IAED,OAAO,CAAC,cAAc;IA2CtB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,kBAAkB;YAIZ,OAAO;CAyBrB","sourcesContent":["import type { EventListener, Events, HarnessEvent, HarnessEventType, WatchHandle } from \"./agent-harness.ts\";\nimport type { Context } from \"./context.ts\";\n\ntype UntypedEventListener = (event: HarnessEvent, context: Context) => void | Promise<void>;\ntype ResnapshotCapture<T> = (context: Context, markBoundary: () => void) => Promise<T>;\n\n/** Passive harness event bus with isolated handler failures. */\nexport class HarnessEventBus implements Events {\n\tprivate readonly listeners = new Map<HarnessEventType, Set<UntypedEventListener>>();\n\tprivate readonly watchListeners = new Set<UntypedEventListener>();\n\tprivate deliveryTail: Promise<void> = Promise.resolve();\n\tprivate closedError: Error | undefined;\n\n\ton<TType extends HarnessEventType>(\n\t\ttype: TType,\n\t\tlistener: EventListener<Extract<HarnessEvent, { type: TType }>>,\n\t): () => void {\n\t\tif (this.closedError !== undefined) throw this.closedError;\n\t\tconst wrapped: UntypedEventListener = (event, context) =>\n\t\t\tlistener(event as Extract<HarnessEvent, { type: TType }>, context);\n\t\tlet listeners = this.listeners.get(type);\n\t\tif (listeners === undefined) {\n\t\t\tlisteners = new Set();\n\t\t\tthis.listeners.set(type, listeners);\n\t\t}\n\t\tlisteners.add(wrapped);\n\t\treturn () => listeners?.delete(wrapped);\n\t}\n\n\temit(event: HarnessEvent, context: Context): Promise<void> {\n\t\treturn this.emitBatch([event], context);\n\t}\n\n\t/** Bind current recipients and append one contiguous batch to the global delivery tail. */\n\temitBatch(events: readonly HarnessEvent[], context: Context): Promise<void> {\n\t\tif (this.closedError !== undefined || events.length === 0) return Promise.resolve();\n\t\tconst bound = events.map((event) => {\n\t\t\tconst payload = structuredClone(event);\n\t\t\treturn { payload, recipients: this.snapshotRecipients(payload) };\n\t\t});\n\t\tconst delivery = this.deliveryTail.then(async () => {\n\t\t\tfor (const { payload, recipients } of bound) await this.deliver(payload, recipients, true, context);\n\t\t});\n\t\tthis.deliveryTail = delivery.catch(() => {});\n\t\treturn delivery;\n\t}\n\n\twatch<T>(\n\t\tsnapshot: T,\n\t\tfilter: (event: HarnessEvent) => boolean,\n\t\t_context: Context,\n\t\tresnapshot?: ResnapshotCapture<T>,\n\t): WatchHandle<T> {\n\t\tif (this.closedError !== undefined) throw this.closedError;\n\t\treturn this.installWatcher(snapshot, filter, resnapshot);\n\t}\n\n\tasync watchFromSnapshot<T>(\n\t\tcapture: (context: Context) => Promise<T>,\n\t\tfilter: (event: HarnessEvent) => boolean,\n\t\tcontext: Context,\n\t): Promise<WatchHandle<T>> {\n\t\tif (this.closedError !== undefined) throw this.closedError;\n\t\tconst watcher = this.installWatcher<T>(undefined, filter, async (captureContext, markBoundary) => {\n\t\t\tconst snapshot = await capture(captureContext);\n\t\t\tmarkBoundary();\n\t\t\treturn snapshot;\n\t\t});\n\t\ttry {\n\t\t\twatcher.setSnapshot(await capture(context));\n\t\t\treturn watcher;\n\t\t} catch (error) {\n\t\t\twatcher.unsubscribe();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(error: Error): void {\n\t\tthis.closedError ??= error;\n\t\tvoid this.deliveryTail.finally(() => {\n\t\t\tthis.listeners.clear();\n\t\t\tthis.watchListeners.clear();\n\t\t});\n\t}\n\n\tprivate installWatcher<T>(\n\t\tsnapshot: T | undefined,\n\t\tfilter: (event: HarnessEvent) => boolean,\n\t\tresnapshot: ResnapshotCapture<T> | undefined,\n\t): BufferedEventWatcher<T> {\n\t\tlet watcher!: BufferedEventWatcher<T>;\n\t\tconst capture =\n\t\t\tresnapshot === undefined\n\t\t\t\t? undefined\n\t\t\t\t: async (context: Context) => {\n\t\t\t\t\t\tlet marked = false;\n\t\t\t\t\t\tconst next = await resnapshot(context, () => {\n\t\t\t\t\t\t\tif (marked) throw new Error(\"Resnapshot boundary was already marked\");\n\t\t\t\t\t\t\tmarked = true;\n\t\t\t\t\t\t\tthis.enqueueBarrier(() => watcher.markResnapshotBoundary());\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!marked) throw new Error(\"Resnapshot capture did not mark its boundary\");\n\t\t\t\t\t\treturn next;\n\t\t\t\t\t};\n\t\twatcher = new BufferedEventWatcher(snapshot, capture, async (error, event, context) => {\n\t\t\tif (event.type === \"handler_error\") return;\n\t\t\tconst normalized = error instanceof Error ? error : new Error(String(error));\n\t\t\tconst lane = \"lane\" in event && typeof event.lane === \"string\" ? event.lane : undefined;\n\t\t\tawait this.emit(\n\t\t\t\t{\n\t\t\t\t\ttype: \"handler_error\",\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: normalized.message,\n\t\t\t\t\t...(normalized.stack === undefined ? {} : { stack: normalized.stack }),\n\t\t\t\t\t...(lane === undefined ? {} : { lane }),\n\t\t\t\t},\n\t\t\t\tcontext,\n\t\t\t);\n\t\t});\n\t\tconst watchListener: UntypedEventListener = (event, context) => {\n\t\t\tif (filter(event)) watcher.push(event, context);\n\t\t};\n\t\tthis.watchListeners.add(watchListener);\n\t\twatcher.setUnsubscribe(() => this.watchListeners.delete(watchListener));\n\t\treturn watcher;\n\t}\n\n\tprivate enqueueBarrier(barrier: () => void): void {\n\t\tconst delivery = this.deliveryTail.then(barrier);\n\t\tthis.deliveryTail = delivery.catch(() => {});\n\t}\n\n\tprivate snapshotRecipients(event: HarnessEvent): UntypedEventListener[] {\n\t\treturn [...(this.listeners.get(event.type) ?? []), ...this.watchListeners];\n\t}\n\n\tprivate async deliver(\n\t\tevent: HarnessEvent,\n\t\trecipients: readonly UntypedEventListener[],\n\t\treportErrors: boolean,\n\t\tcontext: Context,\n\t): Promise<void> {\n\t\tfor (const listener of recipients) {\n\t\t\ttry {\n\t\t\t\tawait listener(structuredClone(event), context);\n\t\t\t} catch (error) {\n\t\t\t\tif (!reportErrors || event.type === \"handler_error\") continue;\n\t\t\t\tconst normalized = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tconst lane = \"lane\" in event && typeof event.lane === \"string\" ? event.lane : undefined;\n\t\t\t\tconst handlerError: HarnessEvent = {\n\t\t\t\t\ttype: \"handler_error\",\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: normalized.message,\n\t\t\t\t\t...(normalized.stack === undefined ? {} : { stack: normalized.stack }),\n\t\t\t\t\t...(lane === undefined ? {} : { lane }),\n\t\t\t\t};\n\t\t\t\tawait this.deliver(handlerError, this.snapshotRecipients(handlerError), false, context);\n\t\t\t}\n\t\t}\n\t}\n}\n\nclass BufferedEventWatcher<T> implements WatchHandle<T> {\n\tsnapshot: T;\n\tprivate readonly resnapshotCallback: ((context: Context) => Promise<T>) | undefined;\n\tprivate readonly onError: (error: unknown, event: HarnessEvent, context: Context) => void | Promise<void>;\n\tprivate buffer: Array<{ event: HarnessEvent; context: Context; epoch: number }> = [];\n\tprivate listener: EventListener | undefined;\n\tprivate unsubscribeCallback: (() => void) | undefined;\n\tprivate deliveryTail: Promise<void> = Promise.resolve();\n\tprivate epoch = 0;\n\tprivate resnapshotState:\n\t\t| {\n\t\t\t\tphase: \"dropping\" | \"holding\";\n\t\t\t\theld: Array<{ event: HarnessEvent; context: Context }>;\n\t\t\t\treached: Promise<void>;\n\t\t\t\tresolveReached: () => void;\n\t\t  }\n\t\t| undefined;\n\tprivate state: \"buffering\" | \"started\" | \"unsubscribed\" = \"buffering\";\n\n\tconstructor(\n\t\tsnapshot: T | undefined,\n\t\tresnapshot: ((context: Context) => Promise<T>) | undefined,\n\t\tonError: (error: unknown, event: HarnessEvent, context: Context) => void | Promise<void>,\n\t) {\n\t\tthis.snapshot = snapshot as T;\n\t\tthis.resnapshotCallback = resnapshot;\n\t\tthis.onError = onError;\n\t}\n\n\tsetSnapshot(snapshot: T): void {\n\t\tthis.snapshot = snapshot;\n\t}\n\n\tstart(listener: EventListener): void {\n\t\tif (this.state !== \"buffering\") throw new Error(\"WatchHandle.start() may be called only once\");\n\t\tthis.state = \"started\";\n\t\tthis.listener = listener;\n\t\tconst buffered = this.buffer;\n\t\tthis.buffer = [];\n\t\tfor (const bufferedEvent of buffered) {\n\t\t\tthis.enqueue(bufferedEvent.event, bufferedEvent.context, bufferedEvent.epoch);\n\t\t}\n\t}\n\n\tasync resnapshot(context: Context): Promise<T> {\n\t\tif (this.state === \"unsubscribed\") throw new Error(\"WatchHandle is unsubscribed\");\n\t\tif (this.resnapshotCallback === undefined) throw new Error(\"WatchHandle does not support resnapshot\");\n\t\tif (this.resnapshotState !== undefined) throw new Error(\"WatchHandle resnapshot is already in progress\");\n\t\tlet resolveReached!: () => void;\n\t\tconst reached = new Promise<void>((resolve) => {\n\t\t\tresolveReached = resolve;\n\t\t});\n\t\tconst resnapshotState = {\n\t\t\tphase: \"dropping\" as const,\n\t\t\theld: [] as Array<{ event: HarnessEvent; context: Context }>,\n\t\t\treached,\n\t\t\tresolveReached,\n\t\t};\n\t\tthis.epoch++;\n\t\tthis.resnapshotState = resnapshotState;\n\t\ttry {\n\t\t\tconst snapshot = await this.resnapshotCallback(context);\n\t\t\tawait reached;\n\t\t\tthis.snapshot = snapshot;\n\t\t\tthis.resnapshotState = undefined;\n\t\t\tfor (const held of resnapshotState.held) this.push(held.event, held.context);\n\t\t\treturn snapshot;\n\t\t} catch (error) {\n\t\t\tthis.resnapshotState = undefined;\n\t\t\tfor (const held of resnapshotState.held) this.push(held.event, held.context);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tmarkResnapshotBoundary(): void {\n\t\tconst resnapshot = this.resnapshotState;\n\t\tif (resnapshot === undefined || resnapshot.phase !== \"dropping\") return;\n\t\tresnapshot.phase = \"holding\";\n\t\tresnapshot.resolveReached();\n\t}\n\n\tunsubscribe(): void {\n\t\tif (this.state === \"unsubscribed\") return;\n\t\tthis.state = \"unsubscribed\";\n\t\tthis.buffer = [];\n\t\tthis.listener = undefined;\n\t\tthis.unsubscribeCallback?.();\n\t\tthis.unsubscribeCallback = undefined;\n\t}\n\n\tpush(event: HarnessEvent, context: Context): void {\n\t\tif (this.state === \"unsubscribed\") return;\n\t\tif (this.resnapshotState?.phase === \"dropping\") return;\n\t\tif (this.resnapshotState?.phase === \"holding\") {\n\t\t\tthis.resnapshotState.held.push({ event, context });\n\t\t\treturn;\n\t\t}\n\t\tif (this.state === \"buffering\") {\n\t\t\tthis.buffer.push({ event, context, epoch: this.epoch });\n\t\t\treturn;\n\t\t}\n\t\tthis.enqueue(event, context, this.epoch);\n\t}\n\n\tsetUnsubscribe(callback: () => void): void {\n\t\tthis.unsubscribeCallback = callback;\n\t}\n\n\tprivate enqueue(event: HarnessEvent, context: Context, epoch: number): void {\n\t\tconst listener = this.listener;\n\t\tif (listener === undefined) return;\n\t\tthis.deliveryTail = this.deliveryTail\n\t\t\t.then(async () => {\n\t\t\t\tif (this.state === \"started\" && epoch === this.epoch) await listener(event, context);\n\t\t\t})\n\t\t\t.catch(async (error) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.onError(error, event, context);\n\t\t\t\t} catch {}\n\t\t\t});\n\t}\n}\n"]}