@directive-run/core 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs.map +1 -1
- package/dist/adapter-utils.d.cts +1 -1
- package/dist/adapter-utils.d.ts +1 -1
- package/dist/adapter-utils.js.map +1 -1
- package/dist/index.cjs +19 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -6
- package/dist/index.d.ts +13 -6
- package/dist/index.js +19 -19
- package/dist/index.js.map +1 -1
- package/dist/migration.cjs.map +1 -1
- package/dist/migration.js.map +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +103 -23
- package/dist/plugins/index.d.ts +103 -23
- package/dist/plugins/index.js +2 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-KKRG7lDP.d.cts → plugins-cDWoL7A7.d.cts} +146 -47
- package/dist/{plugins-KKRG7lDP.d.ts → plugins-cDWoL7A7.d.ts} +146 -47
- package/dist/testing.cjs +3 -3
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +3 -3
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +3 -3
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/plugins/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as ModuleSchema, P as Plugin, J as System } from '../plugins-
|
|
1
|
+
import { M as ModuleSchema, P as Plugin, J as System } from '../plugins-cDWoL7A7.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Logging Plugin - Console logging for Directive events
|
|
@@ -27,59 +27,139 @@ interface LoggingPluginOptions {
|
|
|
27
27
|
*/
|
|
28
28
|
declare function loggingPlugin<M extends ModuleSchema = ModuleSchema>(options?: LoggingPluginOptions): Plugin<M>;
|
|
29
29
|
|
|
30
|
-
/**
|
|
31
|
-
* Devtools Plugin - Browser devtools integration
|
|
32
|
-
*
|
|
33
|
-
* Exposes the system to browser devtools via window.__DIRECTIVE__
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
30
|
interface DevtoolsPluginOptions {
|
|
37
31
|
/** Name for this system in devtools */
|
|
38
32
|
name?: string;
|
|
39
33
|
/** Enable trace logging */
|
|
40
34
|
trace?: boolean;
|
|
35
|
+
/** Maximum number of trace events to retain (default: 1000) */
|
|
36
|
+
maxEvents?: number;
|
|
37
|
+
/** Show floating debug panel (dev mode only, requires browser) */
|
|
38
|
+
panel?: boolean;
|
|
39
|
+
/** Panel position */
|
|
40
|
+
position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
|
|
41
|
+
/** Start panel open */
|
|
42
|
+
defaultOpen?: boolean;
|
|
41
43
|
}
|
|
42
|
-
interface
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
interface TraceEvent {
|
|
45
|
+
timestamp: number;
|
|
46
|
+
type: string;
|
|
47
|
+
data: unknown;
|
|
48
|
+
}
|
|
49
|
+
declare class CircularBuffer<T> {
|
|
50
|
+
private capacity;
|
|
51
|
+
private buf;
|
|
52
|
+
private head;
|
|
53
|
+
private _size;
|
|
54
|
+
constructor(capacity: number);
|
|
55
|
+
get size(): number;
|
|
56
|
+
push(item: T): void;
|
|
57
|
+
toArray(): T[];
|
|
58
|
+
clear(): void;
|
|
59
|
+
}
|
|
60
|
+
type DevtoolsSubscriber = (event: TraceEvent) => void;
|
|
61
|
+
interface DevtoolsState {
|
|
62
|
+
system: System<ModuleSchema> | null;
|
|
63
|
+
events: CircularBuffer<TraceEvent>;
|
|
49
64
|
maxEvents: number;
|
|
65
|
+
subscribers: Set<DevtoolsSubscriber>;
|
|
66
|
+
resolverStats: Map<string, {
|
|
67
|
+
count: number;
|
|
68
|
+
totalMs: number;
|
|
69
|
+
errors: number;
|
|
70
|
+
}>;
|
|
50
71
|
}
|
|
51
72
|
declare global {
|
|
52
73
|
interface Window {
|
|
53
74
|
__DIRECTIVE__?: {
|
|
54
|
-
systems: Map<string, DevtoolsState
|
|
75
|
+
systems: Map<string, DevtoolsState>;
|
|
55
76
|
getSystem(name?: string): System<ModuleSchema> | null;
|
|
56
77
|
getSystems(): string[];
|
|
57
78
|
inspect(name?: string): unknown;
|
|
58
|
-
getEvents(name?: string):
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
79
|
+
getEvents(name?: string): TraceEvent[];
|
|
80
|
+
explain(requirementId: string, name?: string): string | null;
|
|
81
|
+
exportSession(name?: string): string | null;
|
|
82
|
+
importSession(json: string, name?: string): boolean;
|
|
83
|
+
clearEvents(name?: string): void;
|
|
84
|
+
/** Subscribe to trace events. Returns unsubscribe function. */
|
|
85
|
+
subscribe(callback: DevtoolsSubscriber, systemName?: string): () => void;
|
|
63
86
|
};
|
|
64
87
|
}
|
|
65
88
|
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Devtools Plugin - Browser devtools integration
|
|
92
|
+
*
|
|
93
|
+
* Exposes the system to browser devtools via window.__DIRECTIVE__
|
|
94
|
+
* and optionally renders a floating debug panel with:
|
|
95
|
+
* - Facts & derivations tables (live updates with flash animation)
|
|
96
|
+
* - Inflight/unmet requirements
|
|
97
|
+
* - Performance metrics (reconcile time, resolver latency)
|
|
98
|
+
* - Time-travel controls (undo/redo/snapshot index)
|
|
99
|
+
* - Full dependency graph (facts→derivations→constraints→requirements→resolvers)
|
|
100
|
+
* - Timeline/flamechart waterfall of resolver execution
|
|
101
|
+
* - Event log (when trace: true)
|
|
102
|
+
* - Record & replay sessions (export/import JSON)
|
|
103
|
+
*
|
|
104
|
+
* Split into submodules:
|
|
105
|
+
* - devtools-types.ts — types, constants, pure helpers
|
|
106
|
+
* - devtools-panel.ts — floating panel DOM creation and update helpers
|
|
107
|
+
* - devtools-graph.ts — dependency graph and timeline SVG rendering
|
|
108
|
+
*/
|
|
109
|
+
|
|
66
110
|
/**
|
|
67
111
|
* Create a devtools plugin.
|
|
68
112
|
*
|
|
69
113
|
* @example
|
|
70
114
|
* ```ts
|
|
71
115
|
* const system = createSystem({
|
|
72
|
-
*
|
|
73
|
-
* plugins: [devtoolsPlugin({ name: "my-app" })],
|
|
116
|
+
* module: myModule,
|
|
117
|
+
* plugins: [devtoolsPlugin({ name: "my-app", panel: true, trace: true })],
|
|
74
118
|
* });
|
|
75
119
|
*
|
|
76
120
|
* // In browser console:
|
|
77
121
|
* // __DIRECTIVE__.inspect()
|
|
78
122
|
* // __DIRECTIVE__.getEvents()
|
|
123
|
+
* // __DIRECTIVE__.exportSession()
|
|
79
124
|
* ```
|
|
80
125
|
*/
|
|
81
126
|
declare function devtoolsPlugin<M extends ModuleSchema = ModuleSchema>(options?: DevtoolsPluginOptions): Plugin<M>;
|
|
82
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Client-Side AI Event Bridge for DevTools
|
|
130
|
+
*
|
|
131
|
+
* Dispatches AI debug events (guardrail checks, agent lifecycle, etc.) via
|
|
132
|
+
* CustomEvent so that DevTools AI tabs populate without requiring a server-side
|
|
133
|
+
* SSE stream.
|
|
134
|
+
*
|
|
135
|
+
* Usage:
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { emitDevToolsEvent } from '@directive-run/core/plugins'
|
|
138
|
+
*
|
|
139
|
+
* const result = detectPII(text)
|
|
140
|
+
* emitDevToolsEvent({
|
|
141
|
+
* type: 'guardrail_check',
|
|
142
|
+
* guardrailName: 'pii-detection',
|
|
143
|
+
* guardrailType: 'input',
|
|
144
|
+
* passed: !result.detected,
|
|
145
|
+
* })
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
/** The CustomEvent name that DevTools listens for. */
|
|
149
|
+
declare const DEVTOOLS_EVENT_NAME = "directive-devtools-event";
|
|
150
|
+
/**
|
|
151
|
+
* Emit a single AI debug event into DevTools via the client-side bridge.
|
|
152
|
+
*
|
|
153
|
+
* The event is dispatched as a CustomEvent on `window`. The DevTools
|
|
154
|
+
* `useDevToolsStream` hook listens for these and pushes them into the
|
|
155
|
+
* connection module's event array — the same path as SSE events.
|
|
156
|
+
*
|
|
157
|
+
* Fields `id`, `timestamp`, and `snapshotId` are auto-assigned if not provided.
|
|
158
|
+
*/
|
|
159
|
+
declare function emitDevToolsEvent(event: Record<string, unknown> & {
|
|
160
|
+
type: string;
|
|
161
|
+
}): void;
|
|
162
|
+
|
|
83
163
|
/**
|
|
84
164
|
* Persistence Plugin - Save/restore facts to storage
|
|
85
165
|
*/
|
|
@@ -694,4 +774,4 @@ declare class CircuitBreakerOpenError extends Error {
|
|
|
694
774
|
*/
|
|
695
775
|
declare function createCircuitBreaker(config?: CircuitBreakerConfig): CircuitBreaker;
|
|
696
776
|
|
|
697
|
-
export { type AggregatedMetric, type AlertConfig, type AlertEvent, type CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitBreakerStats, type CircuitState, type ConstraintMetrics, type DashboardData, type DevtoolsPluginOptions, type EffectMetrics, type HistogramBucket, type LoggingPluginOptions, type MetricDataPoint, type MetricType, type OTLPExporter, type OTLPExporterConfig, type ObservabilityConfig, type ObservabilityInstance, type PerformancePluginOptions, type PerformanceSnapshot, type PersistencePluginOptions, type ReconcileMetrics, type ResolverMetrics, type TraceSpan, createAgentMetrics, createCircuitBreaker, createOTLPExporter, createObservability, devtoolsPlugin, loggingPlugin, performancePlugin, persistencePlugin };
|
|
777
|
+
export { type AggregatedMetric, type AlertConfig, type AlertEvent, type CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitBreakerStats, type CircuitState, type ConstraintMetrics, DEVTOOLS_EVENT_NAME, type DashboardData, type DevtoolsPluginOptions, type EffectMetrics, type HistogramBucket, type LoggingPluginOptions, type MetricDataPoint, type MetricType, type OTLPExporter, type OTLPExporterConfig, type ObservabilityConfig, type ObservabilityInstance, type PerformancePluginOptions, type PerformanceSnapshot, type PersistencePluginOptions, type ReconcileMetrics, type ResolverMetrics, type TraceEvent, type TraceSpan, createAgentMetrics, createCircuitBreaker, createOTLPExporter, createObservability, devtoolsPlugin, emitDevToolsEvent, loggingPlugin, performancePlugin, persistencePlugin };
|
package/dist/plugins/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as ModuleSchema, P as Plugin, J as System } from '../plugins-
|
|
1
|
+
import { M as ModuleSchema, P as Plugin, J as System } from '../plugins-cDWoL7A7.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Logging Plugin - Console logging for Directive events
|
|
@@ -27,59 +27,139 @@ interface LoggingPluginOptions {
|
|
|
27
27
|
*/
|
|
28
28
|
declare function loggingPlugin<M extends ModuleSchema = ModuleSchema>(options?: LoggingPluginOptions): Plugin<M>;
|
|
29
29
|
|
|
30
|
-
/**
|
|
31
|
-
* Devtools Plugin - Browser devtools integration
|
|
32
|
-
*
|
|
33
|
-
* Exposes the system to browser devtools via window.__DIRECTIVE__
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
30
|
interface DevtoolsPluginOptions {
|
|
37
31
|
/** Name for this system in devtools */
|
|
38
32
|
name?: string;
|
|
39
33
|
/** Enable trace logging */
|
|
40
34
|
trace?: boolean;
|
|
35
|
+
/** Maximum number of trace events to retain (default: 1000) */
|
|
36
|
+
maxEvents?: number;
|
|
37
|
+
/** Show floating debug panel (dev mode only, requires browser) */
|
|
38
|
+
panel?: boolean;
|
|
39
|
+
/** Panel position */
|
|
40
|
+
position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
|
|
41
|
+
/** Start panel open */
|
|
42
|
+
defaultOpen?: boolean;
|
|
41
43
|
}
|
|
42
|
-
interface
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
interface TraceEvent {
|
|
45
|
+
timestamp: number;
|
|
46
|
+
type: string;
|
|
47
|
+
data: unknown;
|
|
48
|
+
}
|
|
49
|
+
declare class CircularBuffer<T> {
|
|
50
|
+
private capacity;
|
|
51
|
+
private buf;
|
|
52
|
+
private head;
|
|
53
|
+
private _size;
|
|
54
|
+
constructor(capacity: number);
|
|
55
|
+
get size(): number;
|
|
56
|
+
push(item: T): void;
|
|
57
|
+
toArray(): T[];
|
|
58
|
+
clear(): void;
|
|
59
|
+
}
|
|
60
|
+
type DevtoolsSubscriber = (event: TraceEvent) => void;
|
|
61
|
+
interface DevtoolsState {
|
|
62
|
+
system: System<ModuleSchema> | null;
|
|
63
|
+
events: CircularBuffer<TraceEvent>;
|
|
49
64
|
maxEvents: number;
|
|
65
|
+
subscribers: Set<DevtoolsSubscriber>;
|
|
66
|
+
resolverStats: Map<string, {
|
|
67
|
+
count: number;
|
|
68
|
+
totalMs: number;
|
|
69
|
+
errors: number;
|
|
70
|
+
}>;
|
|
50
71
|
}
|
|
51
72
|
declare global {
|
|
52
73
|
interface Window {
|
|
53
74
|
__DIRECTIVE__?: {
|
|
54
|
-
systems: Map<string, DevtoolsState
|
|
75
|
+
systems: Map<string, DevtoolsState>;
|
|
55
76
|
getSystem(name?: string): System<ModuleSchema> | null;
|
|
56
77
|
getSystems(): string[];
|
|
57
78
|
inspect(name?: string): unknown;
|
|
58
|
-
getEvents(name?: string):
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
79
|
+
getEvents(name?: string): TraceEvent[];
|
|
80
|
+
explain(requirementId: string, name?: string): string | null;
|
|
81
|
+
exportSession(name?: string): string | null;
|
|
82
|
+
importSession(json: string, name?: string): boolean;
|
|
83
|
+
clearEvents(name?: string): void;
|
|
84
|
+
/** Subscribe to trace events. Returns unsubscribe function. */
|
|
85
|
+
subscribe(callback: DevtoolsSubscriber, systemName?: string): () => void;
|
|
63
86
|
};
|
|
64
87
|
}
|
|
65
88
|
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Devtools Plugin - Browser devtools integration
|
|
92
|
+
*
|
|
93
|
+
* Exposes the system to browser devtools via window.__DIRECTIVE__
|
|
94
|
+
* and optionally renders a floating debug panel with:
|
|
95
|
+
* - Facts & derivations tables (live updates with flash animation)
|
|
96
|
+
* - Inflight/unmet requirements
|
|
97
|
+
* - Performance metrics (reconcile time, resolver latency)
|
|
98
|
+
* - Time-travel controls (undo/redo/snapshot index)
|
|
99
|
+
* - Full dependency graph (facts→derivations→constraints→requirements→resolvers)
|
|
100
|
+
* - Timeline/flamechart waterfall of resolver execution
|
|
101
|
+
* - Event log (when trace: true)
|
|
102
|
+
* - Record & replay sessions (export/import JSON)
|
|
103
|
+
*
|
|
104
|
+
* Split into submodules:
|
|
105
|
+
* - devtools-types.ts — types, constants, pure helpers
|
|
106
|
+
* - devtools-panel.ts — floating panel DOM creation and update helpers
|
|
107
|
+
* - devtools-graph.ts — dependency graph and timeline SVG rendering
|
|
108
|
+
*/
|
|
109
|
+
|
|
66
110
|
/**
|
|
67
111
|
* Create a devtools plugin.
|
|
68
112
|
*
|
|
69
113
|
* @example
|
|
70
114
|
* ```ts
|
|
71
115
|
* const system = createSystem({
|
|
72
|
-
*
|
|
73
|
-
* plugins: [devtoolsPlugin({ name: "my-app" })],
|
|
116
|
+
* module: myModule,
|
|
117
|
+
* plugins: [devtoolsPlugin({ name: "my-app", panel: true, trace: true })],
|
|
74
118
|
* });
|
|
75
119
|
*
|
|
76
120
|
* // In browser console:
|
|
77
121
|
* // __DIRECTIVE__.inspect()
|
|
78
122
|
* // __DIRECTIVE__.getEvents()
|
|
123
|
+
* // __DIRECTIVE__.exportSession()
|
|
79
124
|
* ```
|
|
80
125
|
*/
|
|
81
126
|
declare function devtoolsPlugin<M extends ModuleSchema = ModuleSchema>(options?: DevtoolsPluginOptions): Plugin<M>;
|
|
82
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Client-Side AI Event Bridge for DevTools
|
|
130
|
+
*
|
|
131
|
+
* Dispatches AI debug events (guardrail checks, agent lifecycle, etc.) via
|
|
132
|
+
* CustomEvent so that DevTools AI tabs populate without requiring a server-side
|
|
133
|
+
* SSE stream.
|
|
134
|
+
*
|
|
135
|
+
* Usage:
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { emitDevToolsEvent } from '@directive-run/core/plugins'
|
|
138
|
+
*
|
|
139
|
+
* const result = detectPII(text)
|
|
140
|
+
* emitDevToolsEvent({
|
|
141
|
+
* type: 'guardrail_check',
|
|
142
|
+
* guardrailName: 'pii-detection',
|
|
143
|
+
* guardrailType: 'input',
|
|
144
|
+
* passed: !result.detected,
|
|
145
|
+
* })
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
/** The CustomEvent name that DevTools listens for. */
|
|
149
|
+
declare const DEVTOOLS_EVENT_NAME = "directive-devtools-event";
|
|
150
|
+
/**
|
|
151
|
+
* Emit a single AI debug event into DevTools via the client-side bridge.
|
|
152
|
+
*
|
|
153
|
+
* The event is dispatched as a CustomEvent on `window`. The DevTools
|
|
154
|
+
* `useDevToolsStream` hook listens for these and pushes them into the
|
|
155
|
+
* connection module's event array — the same path as SSE events.
|
|
156
|
+
*
|
|
157
|
+
* Fields `id`, `timestamp`, and `snapshotId` are auto-assigned if not provided.
|
|
158
|
+
*/
|
|
159
|
+
declare function emitDevToolsEvent(event: Record<string, unknown> & {
|
|
160
|
+
type: string;
|
|
161
|
+
}): void;
|
|
162
|
+
|
|
83
163
|
/**
|
|
84
164
|
* Persistence Plugin - Save/restore facts to storage
|
|
85
165
|
*/
|
|
@@ -694,4 +774,4 @@ declare class CircuitBreakerOpenError extends Error {
|
|
|
694
774
|
*/
|
|
695
775
|
declare function createCircuitBreaker(config?: CircuitBreakerConfig): CircuitBreaker;
|
|
696
776
|
|
|
697
|
-
export { type AggregatedMetric, type AlertConfig, type AlertEvent, type CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitBreakerStats, type CircuitState, type ConstraintMetrics, type DashboardData, type DevtoolsPluginOptions, type EffectMetrics, type HistogramBucket, type LoggingPluginOptions, type MetricDataPoint, type MetricType, type OTLPExporter, type OTLPExporterConfig, type ObservabilityConfig, type ObservabilityInstance, type PerformancePluginOptions, type PerformanceSnapshot, type PersistencePluginOptions, type ReconcileMetrics, type ResolverMetrics, type TraceSpan, createAgentMetrics, createCircuitBreaker, createOTLPExporter, createObservability, devtoolsPlugin, loggingPlugin, performancePlugin, persistencePlugin };
|
|
777
|
+
export { type AggregatedMetric, type AlertConfig, type AlertEvent, type CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitBreakerStats, type CircuitState, type ConstraintMetrics, DEVTOOLS_EVENT_NAME, type DashboardData, type DevtoolsPluginOptions, type EffectMetrics, type HistogramBucket, type LoggingPluginOptions, type MetricDataPoint, type MetricType, type OTLPExporter, type OTLPExporterConfig, type ObservabilityConfig, type ObservabilityInstance, type PerformancePluginOptions, type PerformanceSnapshot, type PersistencePluginOptions, type ReconcileMetrics, type ResolverMetrics, type TraceEvent, type TraceSpan, createAgentMetrics, createCircuitBreaker, createOTLPExporter, createObservability, devtoolsPlugin, emitDevToolsEvent, loggingPlugin, performancePlugin, persistencePlugin };
|
package/dist/plugins/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var U={debug:0,info:1,warn:2,error:3};function W(s={}){let{level:l="info",filter:a=()=>true,logger:o=console,prefix:c="[Directive]"}=s,i=U[l],t=(e,r,...f)=>{U[e]<i||a(r)&&o[e](`${c} ${r}`,...f);};return {name:"logging",onInit:()=>t("debug","init"),onStart:()=>t("info","start"),onStop:()=>t("info","stop"),onDestroy:()=>t("debug","destroy"),onFactSet:(e,r,f)=>{t("debug","fact.set",{key:e,value:r,prev:f});},onFactDelete:(e,r)=>{t("debug","fact.delete",{key:e,prev:r});},onFactsBatch:e=>{t("debug","facts.batch",{count:e.length,changes:e});},onDerivationCompute:(e,r,f)=>{t("debug","derivation.compute",{id:e,value:r,deps:f});},onDerivationInvalidate:e=>{t("debug","derivation.invalidate",{id:e});},onReconcileStart:()=>{t("debug","reconcile.start");},onReconcileEnd:e=>{t("debug","reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length,completed:e.completed.length,canceled:e.canceled.length});},onConstraintEvaluate:(e,r)=>{t("debug","constraint.evaluate",{id:e,active:r});},onConstraintError:(e,r)=>{t("error","constraint.error",{id:e,error:r});},onRequirementCreated:e=>{t("debug","requirement.created",{id:e.id,type:e.requirement.type});},onRequirementMet:(e,r)=>{t("info","requirement.met",{id:e.id,byResolver:r});},onRequirementCanceled:e=>{t("debug","requirement.canceled",{id:e.id});},onResolverStart:(e,r)=>{t("debug","resolver.start",{resolver:e,requirementId:r.id});},onResolverComplete:(e,r,f)=>{t("info","resolver.complete",{resolver:e,requirementId:r.id,duration:f});},onResolverError:(e,r,f)=>{t("error","resolver.error",{resolver:e,requirementId:r.id,error:f});},onResolverRetry:(e,r,f)=>{t("warn","resolver.retry",{resolver:e,requirementId:r.id,attempt:f});},onResolverCancel:(e,r)=>{t("debug","resolver.cancel",{resolver:e,requirementId:r.id});},onEffectRun:e=>{t("debug","effect.run",{id:e});},onEffectError:(e,r)=>{t("error","effect.error",{id:e,error:r});},onSnapshot:e=>{t("debug","timetravel.snapshot",{id:e.id,trigger:e.trigger});},onTimeTravel:(e,r)=>{t("info","timetravel.jump",{from:e,to:r});},onError:e=>{t("error","error",{source:e.source,sourceId:e.sourceId,message:e.message});},onErrorRecovery:(e,r)=>{t("warn","error.recovery",{source:e.source,sourceId:e.sourceId,strategy:r});}}}function J(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[]};if(!window.__DIRECTIVE__){let s=new Map;window.__DIRECTIVE__={systems:s,getSystem(l){return l?s.get(l)?.system??null:s.values().next().value?.system??null},getSystems(){return [...s.keys()]},inspect(l){return this.getSystem(l)?.inspect()??null},getEvents(l){return l?s.get(l)?.events??[]:s.values().next().value?.events??[]}};}return window.__DIRECTIVE__}function G(s={}){let{name:l="default",trace:a=false}=s,o=J(),c={system:null,events:[],maxEvents:1e3};o.systems.set(l,c);let i=(t,e)=>{a&&(c.events.push({timestamp:Date.now(),type:t,data:e}),c.events.length>c.maxEvents&&c.events.shift());};return {name:"devtools",onInit:t=>{c.system=t,i("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${l}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit");},onStart:()=>i("start",{}),onStop:()=>i("stop",{}),onDestroy:()=>{i("destroy",{}),o.systems.delete(l);},onFactSet:(t,e,r)=>{i("fact.set",{key:t,value:e,prev:r});},onFactsBatch:t=>{i("facts.batch",{changes:t});},onReconcileStart:()=>{i("reconcile.start",{});},onReconcileEnd:t=>{i("reconcile.end",t);},onConstraintEvaluate:(t,e)=>{i("constraint.evaluate",{id:t,active:e});},onRequirementCreated:t=>{i("requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,e)=>{i("requirement.met",{id:t.id,byResolver:e});},onResolverStart:(t,e)=>{i("resolver.start",{resolver:t,requirementId:e.id});},onResolverComplete:(t,e,r)=>{i("resolver.complete",{resolver:t,requirementId:e.id,duration:r});},onResolverError:(t,e,r)=>{i("resolver.error",{resolver:t,requirementId:e.id,error:String(r)});},onSnapshot:t=>{i("timetravel.snapshot",{id:t.id,trigger:t.trigger});},onTimeTravel:(t,e)=>{i("timetravel.jump",{from:t,to:e});},onError:t=>{i("error",{source:t.source,sourceId:t.sourceId,message:t.message});}}}function j(s,l=50){let a=new Set(["__proto__","constructor","prototype"]),o=new WeakSet;function c(i,t){if(t>l)return false;if(i==null||typeof i!="object")return true;let e=i;if(o.has(e))return true;if(o.add(e),Array.isArray(e)){for(let r of e)if(!c(r,t+1))return o.delete(e),false;return o.delete(e),true}for(let r of Object.keys(e))if(a.has(r)||!c(e[r],t+1))return o.delete(e),false;return o.delete(e),true}return c(s,0)}function z(s){let{storage:l,key:a,include:o,exclude:c=[],debounce:i=100,onRestore:t,onSave:e,onError:r}=s,f=null,b=null,y=new Set,T=n=>c.includes(n)?false:o?o.includes(n):true,E=()=>{try{let n=l.getItem(a);if(!n)return null;let g=JSON.parse(n);return typeof g!="object"||g===null?null:j(g)?g:(r?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(n){return r?.(n instanceof Error?n:new Error(String(n))),null}},D=()=>{if(b)try{let n={};for(let g of y)T(g)&&(n[g]=b.facts[g]);l.setItem(a,JSON.stringify(n)),e?.(n);}catch(n){r?.(n instanceof Error?n:new Error(String(n)));}},S=()=>{f&&clearTimeout(f),f=setTimeout(D,i);};return {name:"persistence",onInit:n=>{b=n;let g=E();g&&(b.facts.$store.batch(()=>{for(let[v,p]of Object.entries(g))T(v)&&(b.facts[v]=p,y.add(v));}),t?.(g));},onDestroy:()=>{f&&clearTimeout(f),D();},onFactSet:n=>{y.add(n),T(n)&&S();},onFactDelete:n=>{y.delete(n),T(n)&&S();},onFactsBatch:n=>{let g=false;for(let v of n)v.type==="set"?y.add(v.key):y.delete(v.key),T(v.key)&&(g=true);g&&S();}}}function K(s={}){let{onSlowConstraint:l,onSlowResolver:a,slowConstraintThresholdMs:o=16,slowResolverThresholdMs:c=1e3}=s,i=new Map,t=new Map,e=new Map,r={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},f=0,b=0,y=0;function T(n){let g=i.get(n);return g||(g={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},i.set(n,g)),g}function E(n){let g=t.get(n);return g||(g={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},t.set(n,g)),g}function D(n){let g=e.get(n);return g||(g={runs:0,errors:0,lastRunAt:0},e.set(n,g)),g}return {name:"performance",onStart(){f=Date.now();},onConstraintEvaluate(n,g){let v=performance.now(),p=T(n);if(p.evaluations++,p.lastEvaluatedAt=Date.now(),y>0){let h=v-y;p.totalDurationMs+=h;let A=p.evaluations;p.avgDurationMs=p.totalDurationMs/A,h>p.maxDurationMs&&(p.maxDurationMs=h),h>o&&l?.(n,h);}y=v;},onResolverStart(n,g){let v=E(n);v.starts++;},onResolverComplete(n,g,v){let p=E(n);p.completions++,p.totalDurationMs+=v,p.avgDurationMs=p.totalDurationMs/p.completions,v>p.maxDurationMs&&(p.maxDurationMs=v),p.lastCompletedAt=Date.now(),v>c&&a?.(n,v);},onResolverError(n,g,v){E(n).errors++;},onResolverRetry(n,g,v){E(n).retries++;},onResolverCancel(n,g){E(n).cancellations++;},onEffectRun(n){let g=D(n);g.runs++,g.lastRunAt=Date.now();},onEffectError(n,g){D(n).errors++;},onReconcileStart(){b=performance.now(),y=0;},onReconcileEnd(){let n=performance.now()-b;r.runs++,r.totalDurationMs+=n,r.avgDurationMs=r.totalDurationMs/r.runs,n>r.maxDurationMs&&(r.maxDurationMs=n);},getSnapshot(){let n={};for(let[p,h]of i)n[p]={...h};let g={};for(let[p,h]of t)g[p]={...h};let v={};for(let[p,h]of e)v[p]={...h};return {constraints:n,resolvers:g,effects:v,reconcile:{...r},uptime:f?Date.now()-f:0}},reset(){i.clear(),t.clear(),e.clear(),r.runs=0,r.totalDurationMs=0,r.avgDurationMs=0,r.maxDurationMs=0,y=0;}}}function F(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function H(s,l){if(s.length===0)return 0;let a=[...s].sort((c,i)=>c-i),o=Math.ceil(l/100*a.length)-1;return a[Math.max(0,o)]??0}function Q(s={}){let{serviceName:l="directive-agents",metrics:a={},tracing:o={},alerts:c=[],summaryMetrics:i={},events:t={}}=s,e={requests:i.requests??"agent.requests",errors:i.errors??"agent.errors",latency:i.latency??"agent.latency",tokens:i.tokens??"agent.tokens",cost:i.cost??"agent.cost"},{enabled:r=true,exportInterval:f,exporter:b,maxDataPoints:y=1e3}=a,{enabled:T=true,sampleRate:E=1,maxSpans:D=1e3,exporter:S}=o,n=Date.now(),g=new Map,v=new Map,p=[],h=[],A=new Map,w=new Map,_;f&&(b||S)&&(_=setInterval(async()=>{try{if(b&&r&&await b(Array.from(w.values())),S&&T){let u=p.splice(0,100);u.length>0&&await S(u);}}catch(u){console.error("[Directive Observability] Export error:",u);}},f));function L(u){if(!r)return;let d=`${u.name}:${JSON.stringify(Object.fromEntries(Object.entries(u.labels).sort()))}`,m=g.get(d);m||(m=[],g.set(d,m)),m.push(u),m.length>y&&m.shift(),B(u.name,m),t.onMetricRecorded?.(u),M(u.name);}function B(u,d){if(d.length===0)return;let m=d.map(C=>C.value),x=m.reduce((C,R)=>C+R,0),P=d[0],O=m[m.length-1],I={name:u,type:P.type,count:d.length,sum:x,min:Math.min(...m),max:Math.max(...m),avg:x/d.length,lastValue:O,lastUpdated:Date.now()};w.set(u,I);}function M(u){for(let d of c){if(d.metric!==u)continue;let m=w.get(u);if(!m)continue;let x=`${d.metric}:${d.threshold}`,P=A.get(x),O=d.cooldownMs??6e4;if(P&&Date.now()-P<O)continue;let I=d.operator??">",C=m.lastValue,R=d.threshold,N=false;switch(I){case ">":N=C>R;break;case "<":N=C<R;break;case ">=":N=C>=R;break;case "<=":N=C<=R;break;case "==":N=C===R;break}if(N){let V={alertId:F(),metric:u,currentValue:C,threshold:R,operator:I,action:d.action,timestamp:Date.now(),message:`Alert: ${u} ${I} ${R} (current: ${C})`};switch(h.push(V),h.length>1e3&&h.splice(0,h.length-1e3),A.set(x,Date.now()),t.onAlert?.(V),d.action){case "log":console.log(`[Observability] ${V.message}`);break;case "warn":console.warn(`[Observability] ${V.message}`);break;case "alert":console.error(`[Observability ALERT] ${V.message}`);break;case "callback":d.callback?.(m,R);break}}}}function k(u){let d=[];for(let[m,x]of g)if(m.startsWith(`${u}:`))for(let P of x)d.push(P.value);return d.length===0?{}:{p50:H(d,50),p90:H(d,90),p99:H(d,99)}}return {incrementCounter(u,d={},m=1){L({name:u,type:"counter",value:m,labels:d,timestamp:Date.now()});},setGauge(u,d,m={}){L({name:u,type:"gauge",value:d,labels:m,timestamp:Date.now()});},observeHistogram(u,d,m={}){L({name:u,type:"histogram",value:d,labels:m,timestamp:Date.now()});},startSpan(u,d){if(Math.random()>E)return {traceId:"sampled-out",spanId:"sampled-out",operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};let m={traceId:d?v.get(d)?.traceId??F():F(),spanId:F(),parentSpanId:d,operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};return T&&(v.set(m.spanId,m),t.onSpanStart?.(m)),m},endSpan(u,d="ok"){if(u==="sampled-out")return;let m=v.get(u);if(m){for(m.endTime=Date.now(),m.duration=m.endTime-m.startTime,m.status=d,v.delete(u),p.push(m);p.length>D;)p.shift();L({name:`${m.operationName}.latency`,type:"histogram",value:m.duration,labels:{},timestamp:Date.now()}),d==="error"&&L({name:`${m.operationName}.errors`,type:"counter",value:1,labels:{},timestamp:Date.now()}),t.onSpanEnd?.(m);}},addSpanLog(u,d,m="info"){if(u==="sampled-out")return;let x=v.get(u);x&&x.logs.push({timestamp:Date.now(),message:d,level:m});},addSpanTag(u,d,m){if(u==="sampled-out")return;let x=v.get(u);x&&(x.tags[d]=m);},getDashboard(){let u=w.get(e.requests),d=w.get(e.errors),m=w.get(e.latency),x=w.get(e.tokens),P=w.get(e.cost),O=u?.sum??0,I=d?.sum??0,C=O>0?I/O:0,R=m?k(e.latency):{};return {service:{name:l,uptime:Date.now()-n,startTime:n},metrics:Object.fromEntries(w),traces:[...p].slice(-100),alerts:[...h].slice(-50),summary:{totalRequests:O,totalErrors:I,errorRate:C,avgLatency:m?.avg??0,p99Latency:R.p99??0,activeSpans:v.size,totalTokens:x?.sum??0,totalCost:P?.sum??0}}},getMetric(u){let d=w.get(u);if(!d)return;let m=k(u);return {...d,...m}},getTraces(u=100){return [...p].slice(-u)},getAlerts(){return [...h]},export(){return {metrics:Array.from(w.values()),traces:[...p],alerts:[...h]}},clear(){g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},async dispose(){_&&(clearInterval(_),_=void 0);try{b&&r&&w.size>0&&await b(Array.from(w.values())),S&&T&&p.length>0&&await S([...p]);}catch(u){console.error("[Directive Observability] Error flushing data during dispose:",u);}g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},getHealthStatus(){let u=w.get(e.requests),d=w.get(e.errors),m=u?.sum??0,x=d?.sum??0,P=m>0?x/m:0,O=h.filter(I=>Date.now()-I.timestamp<3e5).length;return {healthy:P<.1&&O===0,uptime:Date.now()-n,errorRate:P,activeAlerts:O}}}}function X(s){return {trackRun(l,a){let o={agent:l};s.incrementCounter("agent.requests",o),a.success||s.incrementCounter("agent.errors",o),s.observeHistogram("agent.latency",a.latencyMs,o),a.inputTokens!==void 0&&(s.incrementCounter("agent.tokens.input",o,a.inputTokens),s.incrementCounter("agent.tokens",o,a.inputTokens)),a.outputTokens!==void 0&&(s.incrementCounter("agent.tokens.output",o,a.outputTokens),s.incrementCounter("agent.tokens",o,a.outputTokens)),a.cost!==void 0&&s.incrementCounter("agent.cost",o,a.cost),a.toolCalls!==void 0&&s.incrementCounter("agent.tool_calls",o,a.toolCalls);},trackGuardrail(l,a){let o={guardrail:l};s.incrementCounter("guardrail.checks",o),a.passed||s.incrementCounter("guardrail.failures",o),a.blocked&&s.incrementCounter("guardrail.blocks",o),s.observeHistogram("guardrail.latency",a.latencyMs,o);},trackApproval(l,a){let o={tool:l};s.incrementCounter("approval.requests",o),a.approved?s.incrementCounter("approval.approved",o):s.incrementCounter("approval.rejected",o),a.timedOut&&s.incrementCounter("approval.timeouts",o),s.observeHistogram("approval.wait_time",a.waitTimeMs,o);},trackHandoff(l,a,o){s.incrementCounter("handoff.count",{from:l,to:a}),s.observeHistogram("handoff.latency",o);}}}function Y(s){let l=[{key:"service.name",value:{stringValue:s.serviceName??"directive-agents"}}];if(s.serviceVersion&&l.push({key:"service.version",value:{stringValue:s.serviceVersion}}),s.resourceAttributes)for(let[a,o]of Object.entries(s.resourceAttributes))l.push({key:a,value:{stringValue:o}});return {attributes:l}}function $(s){return `${BigInt(s)*BigInt(1e6)}`}function Z(s){switch(s){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function ee(s,l,a){let o=s.map(c=>{let i=c.lastUpdated-6e4,t=[{asInt:c.type==="counter"?c.sum:void 0,asDouble:c.type!=="counter"?c.lastValue:void 0,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],e=Z(c.type),r={name:c.name,unit:""};return e==="sum"?r.sum={dataPoints:t,aggregationTemporality:2,isMonotonic:true}:e==="histogram"?r.histogram={dataPoints:[{count:c.count,sum:c.sum,min:c.min,max:c.max,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],aggregationTemporality:2}:r.gauge={dataPoints:t},r});return {resourceMetrics:[{resource:l,scopeMetrics:[{scope:{name:"directive",version:a},metrics:o}]}]}}function te(s,l,a){let o=s.map(c=>{let i=c.logs.map(r=>({timeUnixNano:$(r.timestamp),name:r.level,attributes:[{key:"message",value:{stringValue:r.message}},{key:"level",value:{stringValue:r.level}}]})),t=Object.entries(c.tags).map(([r,f])=>({key:r,value:typeof f=="string"?{stringValue:f}:typeof f=="number"?{intValue:`${f}`}:{boolValue:f}})),e=c.status==="ok"?1:c.status==="error"?2:0;return {traceId:c.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:c.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:c.parentSpanId?c.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:c.operationName,kind:1,startTimeUnixNano:$(c.startTime),endTimeUnixNano:c.endTime?$(c.endTime):$(c.startTime),attributes:t,events:i,status:{code:e}}});return {resourceSpans:[{resource:l,scopeSpans:[{scope:{name:"directive",version:a},spans:o}]}]}}function re(s){let{endpoint:l,headers:a={},scopeVersion:o="0.1.0",timeoutMs:c=1e4,fetch:i=globalThis.fetch,onError:t}=s;try{let f=new URL(l);if(f.protocol!=="http:"&&f.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(f){throw new Error(`[Directive OTLP] Invalid endpoint URL "${l}": ${f instanceof Error?f.message:String(f)}`)}if(/\/v1\/(metrics|traces)/.test(l)&&console.warn(`[Directive OTLP] Endpoint "${l}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),c<=0||!Number.isFinite(c))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${c}`);let e=Y(s);async function r(f,b,y){let T=`${l.replace(/\/$/,"")}${f}`,E=new AbortController,D=setTimeout(()=>E.abort(),c);try{let S=await i(T,{method:"POST",headers:{"Content-Type":"application/json",...a},body:JSON.stringify(b),signal:E.signal});if(!S.ok)throw new Error(`OTLP export failed: ${S.status} ${S.statusText}`)}catch(S){let n=S instanceof Error?S:new Error(String(S));t?t(n,y):console.error(`[Directive OTLP] Export ${y} error:`,n.message);}finally{clearTimeout(D);}}return {async exportMetrics(f){if(f.length===0)return;let b=ee(f,e,o);await r("/v1/metrics",b,"metrics");},async exportTraces(f){if(f.length===0)return;let b=te(f,e,o);await r("/v1/traces",b,"traces");}}}var q=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(l,a,o="OPEN",c){let i=c?`[Directive CircuitBreaker] Circuit "${l}" is ${o}. ${c}`:`[Directive CircuitBreaker] Circuit "${l}" is ${o}. Request rejected. Try again in ${Math.ceil(a/1e3)}s.`;super(i),this.name="CircuitBreakerOpenError",this.retryAfterMs=a,this.state=o;}};function ne(s={}){let{failureThreshold:l=5,recoveryTimeMs:a=3e4,halfOpenMaxRequests:o=3,failureWindowMs:c=6e4,observability:i,metricPrefix:t="circuit_breaker",name:e="default",isFailure:r=()=>true,onStateChange:f}=s;if(l<1||!Number.isFinite(l))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${l}`);if(a<=0||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${a}`);if(o<1||!Number.isFinite(o))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${o}`);if(c<=0||!Number.isFinite(c))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${c}`);let b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null;function w(M){if(b===M)return;let k=b;b=M,D=Date.now(),M==="OPEN"&&(S=Date.now()),M==="HALF_OPEN"&&(T=0,E=0),f?.(k,M),i&&i.incrementCounter(`${t}.state_change`,{name:e,from:k,to:M});}function _(){let M=Date.now()-c;return y=y.filter(k=>k>M),y.length}function L(){v++,A=Date.now(),i&&i.incrementCounter(`${t}.success`,{name:e}),b==="HALF_OPEN"&&(E++,E>=o&&(w("CLOSED"),y=[]));}function B(M){if(!r(M)){L();return}g++,h=Date.now(),y.push(Date.now());let k=l*2;if(y.length>k&&(y=y.slice(-k)),i&&i.incrementCounter(`${t}.failure`,{name:e}),b==="HALF_OPEN"){w("OPEN");return}b==="CLOSED"&&_()>=l&&w("OPEN");}return {async execute(M){if(n++,i&&i.incrementCounter(`${t}.requests`,{name:e}),b==="OPEN")if(Date.now()-S>=a)w("HALF_OPEN");else throw p++,i&&i.incrementCounter(`${t}.rejected`,{name:e}),new q(e,a-(Date.now()-S));if(b==="HALF_OPEN"){if(T>=o)throw p++,new q(e,a,"HALF_OPEN",`Max trial requests (${o}) reached.`);T++;}let k=Date.now();try{let u=await M();return L(),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}catch(u){let d=u instanceof Error?u:new Error(String(u));throw B(d),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}},getState(){return b==="OPEN"&&Date.now()-S>=a&&w("HALF_OPEN"),b},getStats(){return {state:this.getState(),totalRequests:n,totalFailures:g,totalSuccesses:v,totalRejected:p,recentFailures:_(),lastFailureTime:h,lastSuccessTime:A,lastStateChange:D}},forceState(M){w(M);},reset(){let M=b;b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null,M!=="CLOSED"&&f?.(M,"CLOSED");},isAllowed(){return b==="CLOSED"?true:b==="OPEN"?Date.now()-S>=a:T<o}}}
|
|
2
|
-
export{
|
|
1
|
+
var De={debug:0,info:1,warn:2,error:3};function Ke(e={}){let{level:s="info",filter:o=()=>true,logger:r=console,prefix:a="[Directive]"}=e,d=De[s],c=(n,i,...l)=>{De[n]<d||o(i)&&r[n](`${a} ${i}`,...l);};return {name:"logging",onInit:()=>c("debug","init"),onStart:()=>c("info","start"),onStop:()=>c("info","stop"),onDestroy:()=>c("debug","destroy"),onFactSet:(n,i,l)=>{c("debug","fact.set",{key:n,value:i,prev:l});},onFactDelete:(n,i)=>{c("debug","fact.delete",{key:n,prev:i});},onFactsBatch:n=>{c("debug","facts.batch",{count:n.length,changes:n});},onDerivationCompute:(n,i,l)=>{c("debug","derivation.compute",{id:n,value:i,deps:l});},onDerivationInvalidate:n=>{c("debug","derivation.invalidate",{id:n});},onReconcileStart:()=>{c("debug","reconcile.start");},onReconcileEnd:n=>{c("debug","reconcile.end",{unmet:n.unmet.length,inflight:n.inflight.length,completed:n.completed.length,canceled:n.canceled.length});},onConstraintEvaluate:(n,i)=>{c("debug","constraint.evaluate",{id:n,active:i});},onConstraintError:(n,i)=>{c("error","constraint.error",{id:n,error:i});},onRequirementCreated:n=>{c("debug","requirement.created",{id:n.id,type:n.requirement.type});},onRequirementMet:(n,i)=>{c("info","requirement.met",{id:n.id,byResolver:i});},onRequirementCanceled:n=>{c("debug","requirement.canceled",{id:n.id});},onResolverStart:(n,i)=>{c("debug","resolver.start",{resolver:n,requirementId:i.id});},onResolverComplete:(n,i,l)=>{c("info","resolver.complete",{resolver:n,requirementId:i.id,duration:l});},onResolverError:(n,i,l)=>{c("error","resolver.error",{resolver:n,requirementId:i.id,error:l});},onResolverRetry:(n,i,l)=>{c("warn","resolver.retry",{resolver:n,requirementId:i.id,attempt:l});},onResolverCancel:(n,i)=>{c("debug","resolver.cancel",{resolver:n,requirementId:i.id});},onEffectRun:n=>{c("debug","effect.run",{id:n});},onEffectError:(n,i)=>{c("error","effect.error",{id:n,error:i});},onSnapshot:n=>{c("debug","timetravel.snapshot",{id:n.id,trigger:n.trigger});},onTimeTravel:(n,i)=>{c("info","timetravel.jump",{from:n,to:i});},onError:n=>{c("error","error",{source:n.source,sourceId:n.sourceId,message:n.message});},onErrorRecovery:(n,i)=>{c("warn","error.recovery",{source:n.source,sourceId:n.sourceId,strategy:i});}}}var ie=class{constructor(s){this.capacity=s;this.buf=new Array(s);}buf;head=0;_size=0;get size(){return this._size}push(s){this.buf[this.head]=s,this.head=(this.head+1)%this.capacity,this._size<this.capacity&&this._size++;}toArray(){return this._size===0?[]:this._size<this.capacity?this.buf.slice(0,this._size):[...this.buf.slice(this.head),...this.buf.slice(0,this.head)]}clear(){this.buf=new Array(this.capacity),this.head=0,this._size=0;}};function le(){try{if(typeof process<"u"&&process.env?.NODE_ENV==="production")return !1}catch{}try{if(typeof import.meta<"u"&&import.meta.env?.MODE==="production")return !1}catch{}return true}function ge(e){try{if(e===void 0)return "undefined";if(e===null)return "null";if(typeof e=="bigint")return String(e)+"n";if(typeof e=="symbol")return String(e);if(typeof e=="object"){let s=JSON.stringify(e,(o,r)=>typeof r=="bigint"?String(r)+"n":typeof r=="symbol"?String(r):r);return s.length>120?s.slice(0,117)+"...":s}return String(e)}catch{return "<error>"}}function K(e,s){return e.length<=s?e:e.slice(0,s-3)+"..."}function te(e){try{return e.inspect()}catch{return null}}function Re(e){try{return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}catch{return null}}function ke(e){return e===void 0?1e3:!Number.isFinite(e)||e<1?(le()&&console.warn(`[directive:devtools] Invalid maxEvents value (${e}), using default 1000`),1e3):Math.floor(e)}function Le(){return {reconcileCount:0,reconcileTotalMs:0,resolverStats:new Map,effectRunCount:0,effectErrorCount:0,lastReconcileStartMs:0}}var Je=200,ne=340,re=16,oe=80,fe=2,be=["#8b9aff","#4ade80","#fbbf24","#c084fc","#f472b6","#22d3ee"];function Oe(){return {entries:new ie(Je),inflight:new Map}}function Pe(){return {derivationDeps:new Map,activeConstraints:new Set,recentlyChangedFacts:new Set,recentlyComputedDerivations:new Set,recentlyActiveConstraints:new Set,animationTimer:null}}var Ie=1e4,_e=100;function Ne(){return {isRecording:false,recordedEvents:[],snapshots:[]}}var $e=50,ye=200,b={bg:"#1a1a2e",text:"#e0e0e0",accent:"#8b9aff",muted:"#b0b0d0",border:"#333",rowBorder:"#2a2a4a",green:"#4ade80",yellow:"#fbbf24",red:"#f87171",closeBtn:"#aaa",font:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},j={nodeW:90,nodeH:16,nodeGap:6,startY:16,colGap:20,fontSize:10,labelMaxChars:11};function Be(e,s,o,r){let a=false,d={position:"fixed",zIndex:"99999",...s.includes("bottom")?{bottom:"12px"}:{top:"12px"},...s.includes("right")?{right:"12px"}:{left:"12px"}},c=document.createElement("style");c.textContent=`[data-directive-devtools] summary:focus-visible{outline:2px solid ${b.accent};outline-offset:2px;border-radius:2px}[data-directive-devtools] button:focus-visible{outline:2px solid ${b.accent};outline-offset:2px}`,document.head.appendChild(c);let n=document.createElement("button");n.setAttribute("aria-label","Open Directive DevTools"),n.setAttribute("aria-expanded",String(o)),n.title="Ctrl+Shift+D to toggle",Object.assign(n.style,{...d,background:b.bg,color:b.text,border:`1px solid ${b.border}`,borderRadius:"6px",padding:"10px 14px",minWidth:"44px",minHeight:"44px",cursor:"pointer",fontFamily:b.font,fontSize:"12px",display:o?"none":"block"}),n.textContent="Directive";let i=document.createElement("div");i.setAttribute("role","region"),i.setAttribute("aria-label","Directive DevTools"),i.setAttribute("data-directive-devtools",""),i.tabIndex=-1,Object.assign(i.style,{...d,background:b.bg,color:b.text,border:`1px solid ${b.border}`,borderRadius:"8px",padding:"12px",fontFamily:b.font,fontSize:"11px",maxWidth:"min(380px, calc(100vw - 24px))",maxHeight:"min(500px, calc(100vh - 24px))",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)",display:o?"block":"none"});let l=document.createElement("div");Object.assign(l.style,{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"});let g=document.createElement("strong");g.style.color=b.accent,g.textContent=e==="default"?"Directive DevTools":`DevTools (${e})`;let h=document.createElement("button");h.setAttribute("aria-label","Close DevTools"),Object.assign(h.style,{background:"none",border:"none",color:b.closeBtn,cursor:"pointer",fontSize:"16px",padding:"8px 12px",minWidth:"44px",minHeight:"44px",lineHeight:"1",display:"flex",alignItems:"center",justifyContent:"center"}),h.textContent="\xD7",l.appendChild(g),l.appendChild(h),i.appendChild(l);let k=document.createElement("div");k.style.marginBottom="6px",k.setAttribute("aria-live","polite");let _=document.createElement("span");_.style.color=b.green,_.textContent="Settled",k.appendChild(_),i.appendChild(k);let C=document.createElement("div");Object.assign(C.style,{display:"none",marginBottom:"8px",padding:"4px 8px",background:"#252545",borderRadius:"4px",alignItems:"center",gap:"6px"});let T=document.createElement("button");Object.assign(T.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:b.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),T.textContent="\u25C0 Undo",T.disabled=true;let u=document.createElement("button");Object.assign(u.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:b.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),u.textContent="Redo \u25B6",u.disabled=true;let f=document.createElement("span");f.style.color=b.muted,f.style.fontSize="10px",C.appendChild(T),C.appendChild(u),C.appendChild(f),i.appendChild(C);function A(q,X){let U=document.createElement("details");X&&(U.open=true),U.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${q} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",U.appendChild(Y);let Q=document.createElement("table");Object.assign(Q.style,{width:"100%",borderCollapse:"collapse",fontSize:"11px"});let Te=document.createElement("thead"),Me=document.createElement("tr");for(let Ye of ["Key","Value"]){let ce=document.createElement("th");ce.scope="col",Object.assign(ce.style,{textAlign:"left",padding:"2px 4px",color:b.accent}),ce.textContent=Ye,Me.appendChild(ce);}Te.appendChild(Me),Q.appendChild(Te);let Ae=document.createElement("tbody");return Q.appendChild(Ae),U.appendChild(Q),{details:U,tbody:Ae,countSpan:ee}}function w(q,X){let U=document.createElement("details");U.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:X,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${q} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",U.appendChild(Y);let Q=document.createElement("ul");return Object.assign(Q.style,{margin:"0",paddingLeft:"16px"}),U.appendChild(Q),{details:U,list:Q,countSpan:ee}}let L=A("Facts",true);i.appendChild(L.details);let B=A("Derivations",false);i.appendChild(B.details);let D=w("Inflight",b.yellow);i.appendChild(D.details);let V=w("Unmet",b.red);i.appendChild(V.details);let O=document.createElement("details");O.style.marginBottom="4px";let H=document.createElement("summary");Object.assign(H.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),H.textContent="Performance",O.appendChild(H);let P=document.createElement("div");P.style.fontSize="10px",P.style.color=b.muted,P.textContent="No data yet",O.appendChild(P),i.appendChild(O);let $=document.createElement("details");$.style.marginBottom="4px";let S=document.createElement("summary");Object.assign(S.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),S.textContent="Dependency Graph",$.appendChild(S);let x=document.createElementNS("http://www.w3.org/2000/svg","svg");x.setAttribute("width","100%"),x.setAttribute("height","120"),x.setAttribute("role","img"),x.setAttribute("aria-label","System dependency graph"),x.style.display="block",x.setAttribute("viewBox","0 0 460 120"),x.setAttribute("preserveAspectRatio","xMinYMin meet"),$.appendChild(x),i.appendChild($);let E=document.createElement("details");E.style.marginBottom="4px";let N=document.createElement("summary");Object.assign(N.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),N.textContent="Timeline",E.appendChild(N);let I=document.createElementNS("http://www.w3.org/2000/svg","svg");I.setAttribute("width","100%"),I.setAttribute("height","60"),I.setAttribute("role","img"),I.setAttribute("aria-label","Resolver execution timeline"),I.style.display="block",I.setAttribute("viewBox",`0 0 ${ne} 60`),I.setAttribute("preserveAspectRatio","xMinYMin meet");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x",String(ne/2)),m.setAttribute("y","30"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",b.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",b.font),m.textContent="No resolver activity yet",I.appendChild(m),E.appendChild(I),i.appendChild(E);let v,y,t,p;if(r){let q=document.createElement("details");q.style.marginBottom="4px";let X=document.createElement("summary");Object.assign(X.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),t=document.createElement("span"),t.textContent="0",X.textContent="Events (",X.appendChild(t),X.appendChild(document.createTextNode(")")),q.appendChild(X),y=document.createElement("div"),Object.assign(y.style,{maxHeight:"150px",overflow:"auto",fontSize:"10px"}),y.setAttribute("role","log"),y.setAttribute("aria-live","polite"),y.tabIndex=0;let U=document.createElement("div");U.style.color=b.muted,U.style.padding="4px",U.textContent="Waiting for events...",U.className="dt-events-empty",y.appendChild(U),q.appendChild(y),i.appendChild(q),v=q,p=document.createElement("div");}else v=document.createElement("details"),y=document.createElement("div"),t=document.createElement("span"),p=document.createElement("div"),p.style.fontSize="10px",p.style.color=b.muted,p.style.marginTop="4px",p.style.fontStyle="italic",p.textContent="Enable trace: true for event log",i.appendChild(p);let M=document.createElement("div");Object.assign(M.style,{display:"flex",gap:"6px",marginTop:"6px"});let R=document.createElement("button");Object.assign(R.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:b.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),R.textContent="\u23FA Record";let z=document.createElement("button");Object.assign(z.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:b.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),z.textContent="\u2913 Export",M.appendChild(R),M.appendChild(z),i.appendChild(M),i.addEventListener("wheel",q=>{let X=i,U=X.scrollTop===0&&q.deltaY<0,Y=X.scrollTop+X.clientHeight>=X.scrollHeight&&q.deltaY>0;(U||Y)&&q.preventDefault();},{passive:false});let F=o,W=new Set;function G(){F=true,i.style.display="block",n.style.display="none",n.setAttribute("aria-expanded","true"),h.focus();}function J(){F=false,i.style.display="none",n.style.display="block",n.setAttribute("aria-expanded","false"),n.focus();}n.addEventListener("click",G),h.addEventListener("click",J);function we(q){q.key==="Escape"&&F&&J();}i.addEventListener("keydown",we);function Ce(q){q.key==="d"&&q.shiftKey&&(q.ctrlKey||q.metaKey)&&(q.preventDefault(),F?J():G());}document.addEventListener("keydown",Ce);function pe(){a||(document.body.appendChild(n),document.body.appendChild(i));}document.body?pe():document.addEventListener("DOMContentLoaded",pe,{once:true});function Xe(){a=true,n.removeEventListener("click",G),h.removeEventListener("click",J),i.removeEventListener("keydown",we),document.removeEventListener("keydown",Ce),document.removeEventListener("DOMContentLoaded",pe);for(let q of W)clearTimeout(q);W.clear(),n.remove(),i.remove(),c.remove();}return {refs:{container:i,toggleBtn:n,titleEl:g,statusEl:_,factsBody:L.tbody,factsCount:L.countSpan,derivBody:B.tbody,derivCount:B.countSpan,derivSection:B.details,inflightList:D.list,inflightSection:D.details,inflightCount:D.countSpan,unmetList:V.list,unmetSection:V.details,unmetCount:V.countSpan,perfSection:O,perfBody:P,timeTravelSection:C,timeTravelLabel:f,undoBtn:T,redoBtn:u,flowSection:$,flowSvg:x,timelineSection:E,timelineSvg:I,eventsSection:v,eventsList:y,eventsCount:t,traceHint:p,recordBtn:R,exportBtn:z},destroy:Xe,isOpen:()=>F,flashTimers:W}}function se(e,s,o,r,a,d){let c=ge(r),n=e.get(o);if(n){let i=n.cells;if(i[1]&&(i[1].textContent=c,a&&d)){let l=i[1];l.style.background="rgba(139, 154, 255, 0.25)";let g=setTimeout(()=>{l.style.background="",d.delete(g);},300);d.add(g);}}else {n=document.createElement("tr"),n.style.borderBottom=`1px solid ${b.rowBorder}`;let i=document.createElement("td");Object.assign(i.style,{padding:"2px 4px",color:b.muted}),i.textContent=o;let l=document.createElement("td");l.style.padding="2px 4px",l.textContent=c,n.appendChild(i),n.appendChild(l),s.appendChild(n),e.set(o,n);}}function He(e,s){let o=e.get(s);o&&(o.remove(),e.delete(s));}function ue(e,s,o){if(e.inflightList.replaceChildren(),e.inflightCount.textContent=String(s.length),s.length>0)for(let r of s){let a=document.createElement("li");a.style.fontSize="11px",a.textContent=`${r.resolverId} (${r.id})`,e.inflightList.appendChild(a);}else {let r=document.createElement("li");r.style.fontSize="10px",r.style.color=b.muted,r.textContent="None",e.inflightList.appendChild(r);}if(e.unmetList.replaceChildren(),e.unmetCount.textContent=String(o.length),o.length>0)for(let r of o){let a=document.createElement("li");a.style.fontSize="11px",a.textContent=`${r.requirement.type} from ${r.fromConstraint}`,e.unmetList.appendChild(a);}else {let r=document.createElement("li");r.style.fontSize="10px",r.style.color=b.muted,r.textContent="None",e.unmetList.appendChild(r);}}function de(e,s,o){let r=s===0&&o===0;e.statusEl.style.color=r?b.green:b.yellow,e.statusEl.textContent=r?"Settled":"Working...",e.toggleBtn.textContent=r?"Directive":"Directive...",e.toggleBtn.setAttribute("aria-label",`Open Directive DevTools${r?"":" (system working)"}`);}function ve(e,s,o,r){let a=Object.keys(o.derive);if(e.derivCount.textContent=String(a.length),a.length===0){s.clear(),e.derivBody.replaceChildren();let c=document.createElement("tr"),n=document.createElement("td");n.colSpan=2,n.style.color=b.muted,n.style.fontSize="10px",n.textContent="No derivations defined",c.appendChild(n),e.derivBody.appendChild(c);return}let d=new Set(a);for(let[c,n]of s)d.has(c)||(n.remove(),s.delete(c));for(let c of a){let n;try{n=ge(o.read(c));}catch{n="<error>";}se(s,e.derivBody,c,n,true,r);}}function Ve(e,s,o,r){let a=e.eventsList.querySelector(".dt-events-empty");a&&a.remove();let d=document.createElement("div");Object.assign(d.style,{padding:"2px 4px",borderBottom:`1px solid ${b.rowBorder}`,fontFamily:"inherit"});let c=new Date,n=`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}:${String(c.getSeconds()).padStart(2,"0")}.${String(c.getMilliseconds()).padStart(3,"0")}`,i;try{let k=JSON.stringify(o);i=K(k,60);}catch{i="{}";}let l=document.createElement("span");l.style.color=b.closeBtn,l.textContent=n;let g=document.createElement("span");g.style.color=b.accent,g.textContent=` ${s} `;let h=document.createElement("span");for(h.style.color=b.muted,h.textContent=i,d.appendChild(l),d.appendChild(g),d.appendChild(h),e.eventsList.prepend(d);e.eventsList.childElementCount>$e;)e.eventsList.lastElementChild?.remove();e.eventsCount.textContent=String(r);}function je(e,s){e.perfBody.replaceChildren();let o=s.reconcileCount>0?(s.reconcileTotalMs/s.reconcileCount).toFixed(1):"\u2014",r=[`Reconciles: ${s.reconcileCount} (avg ${o}ms)`,`Effects: ${s.effectRunCount} run, ${s.effectErrorCount} errors`];for(let a of r){let d=document.createElement("div");d.style.marginBottom="2px",d.textContent=a,e.perfBody.appendChild(d);}if(s.resolverStats.size>0){let a=document.createElement("div");a.style.marginTop="4px",a.style.marginBottom="2px",a.style.color=b.accent,a.textContent="Resolvers:",e.perfBody.appendChild(a);let d=[...s.resolverStats.entries()].sort((c,n)=>n[1].totalMs-c[1].totalMs);for(let[c,n]of d){let i=n.count>0?(n.totalMs/n.count).toFixed(1):"0",l=document.createElement("div");l.style.paddingLeft="8px",l.textContent=`${c}: ${n.count}x, avg ${i}ms${n.errors>0?`, ${n.errors} err`:""}`,n.errors>0&&(l.style.color=b.red),e.perfBody.appendChild(l);}}}function he(e,s){let o=s.debug;if(!o){e.timeTravelSection.style.display="none";return}e.timeTravelSection.style.display="flex";let r=o.currentIndex,a=o.snapshots.length;e.timeTravelLabel.textContent=a>0?`${r+1} / ${a}`:"0 snapshots";let d=r>0,c=r<a-1;e.undoBtn.disabled=!d,e.undoBtn.style.opacity=d?"1":"0.4",e.redoBtn.disabled=!c,e.redoBtn.style.opacity=c?"1":"0.4";}function Fe(e,s){e.undoBtn.addEventListener("click",()=>{s.debug&&s.debug.currentIndex>0&&s.debug.goBack(1);}),e.redoBtn.addEventListener("click",()=>{s.debug&&s.debug.currentIndex<s.debug.snapshots.length-1&&s.debug.goForward(1);});}var Se=new WeakMap;function Qe(e,s,o,r,a,d){return [e.join(","),s.join(","),o.map(c=>`${c.id}:${c.active}`).join(","),[...r.entries()].map(([c,n])=>`${c}:${n.status}:${n.type}`).join(","),a.join(","),d.join(",")].join("|")}function Ze(e,s,o,r,a){for(let d of o){let c=e.nodes.get(`0:${d}`);if(!c)continue;let n=s.recentlyChangedFacts.has(d);c.rect.setAttribute("fill",n?b.text+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}for(let d of r){let c=e.nodes.get(`1:${d}`);if(!c)continue;let n=s.recentlyComputedDerivations.has(d);c.rect.setAttribute("fill",n?b.accent+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}for(let d of a){let c=e.nodes.get(`2:${d}`);if(!c)continue;let n=s.recentlyActiveConstraints.has(d),i=c.rect.getAttribute("stroke")??b.muted;c.rect.setAttribute("fill",n?i+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}}function xe(e,s,o){let r=te(s);if(!r)return;let a;try{a=Object.keys(s.facts.$store.toObject());}catch{a=[];}let d=Object.keys(s.derive),c=r.constraints,n=r.unmet,i=r.inflight,l=Object.keys(r.resolvers),g=new Map;for(let m of n)g.set(m.id,{type:m.requirement.type,fromConstraint:m.fromConstraint,status:"unmet"});for(let m of i)g.set(m.id,{type:m.resolverId,fromConstraint:"",status:"inflight"});if(a.length===0&&d.length===0&&c.length===0&&l.length===0){Se.delete(e.flowSvg),e.flowSvg.replaceChildren(),e.flowSvg.setAttribute("viewBox","0 0 460 40");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x","230"),m.setAttribute("y","24"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",b.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",b.font),m.textContent="No system topology",e.flowSvg.appendChild(m);return}let h=i.map(m=>m.resolverId).sort(),k=Qe(a,d,c,g,l,h),_=Se.get(e.flowSvg);if(_&&_.fingerprint===k){Ze(_,o,a,d,c.map(m=>m.id));return}let C=j.nodeW+j.colGap,T=[5,5+C,5+C*2,5+C*3,5+C*4],u=T[4]+j.nodeW+5;function f(m){let v=j.startY+12;return m.map(y=>{let t={...y,y:v};return v+=j.nodeH+j.nodeGap,t})}let A=f(a.map(m=>({id:m,label:K(m,j.labelMaxChars)}))),w=f(d.map(m=>({id:m,label:K(m,j.labelMaxChars)}))),L=f(c.map(m=>({id:m.id,label:K(m.id,j.labelMaxChars),active:m.active,priority:m.priority}))),B=f([...g.entries()].map(([m,v])=>({id:m,type:v.type,fromConstraint:v.fromConstraint,status:v.status}))),D=f(l.map(m=>({id:m,label:K(m,j.labelMaxChars)}))),V=Math.max(A.length,w.length,L.length,B.length,D.length,1),O=j.startY+12+V*(j.nodeH+j.nodeGap)+8;e.flowSvg.replaceChildren(),e.flowSvg.setAttribute("viewBox",`0 0 ${u} ${O}`),e.flowSvg.setAttribute("aria-label",`Dependency graph: ${a.length} facts, ${d.length} derivations, ${c.length} constraints, ${g.size} requirements, ${l.length} resolvers`);let H=["Facts","Derivations","Constraints","Reqs","Resolvers"];for(let[m,v]of H.entries()){let y=document.createElementNS("http://www.w3.org/2000/svg","text");y.setAttribute("x",String(T[m]??0)),y.setAttribute("y","10"),y.setAttribute("fill",b.accent),y.setAttribute("font-size",String(j.fontSize)),y.setAttribute("font-family",b.font),y.textContent=v,e.flowSvg.appendChild(y);}let P={fingerprint:k,nodes:new Map};function $(m,v,y,t,p,M,R,z){let F=document.createElementNS("http://www.w3.org/2000/svg","g"),W=document.createElementNS("http://www.w3.org/2000/svg","rect");W.setAttribute("x",String(v)),W.setAttribute("y",String(y-6)),W.setAttribute("width",String(j.nodeW)),W.setAttribute("height",String(j.nodeH)),W.setAttribute("rx","3"),W.setAttribute("fill",z?M+"33":"none"),W.setAttribute("stroke",M),W.setAttribute("stroke-width",z?"2":"1"),W.setAttribute("opacity",R?"0.35":"1"),F.appendChild(W);let G=document.createElementNS("http://www.w3.org/2000/svg","text");return G.setAttribute("x",String(v+4)),G.setAttribute("y",String(y+4)),G.setAttribute("fill",M),G.setAttribute("font-size",String(j.fontSize)),G.setAttribute("font-family",b.font),G.setAttribute("opacity",R?"0.35":"1"),G.textContent=p,F.appendChild(G),e.flowSvg.appendChild(F),P.nodes.set(`${m}:${t}`,{g:F,rect:W,text:G}),{midX:v+j.nodeW/2,midY:y}}function S(m,v,y,t,p,M){let R=document.createElementNS("http://www.w3.org/2000/svg","line");R.setAttribute("x1",String(m)),R.setAttribute("y1",String(v)),R.setAttribute("x2",String(y)),R.setAttribute("y2",String(t)),R.setAttribute("stroke",p),R.setAttribute("stroke-width","1"),R.setAttribute("stroke-dasharray","3,2"),R.setAttribute("opacity","0.7"),e.flowSvg.appendChild(R);}let x=new Map,E=new Map,N=new Map,I=new Map;for(let m of A){let v=o.recentlyChangedFacts.has(m.id),y=$(0,T[0],m.y,m.id,m.label,b.text,false,v);x.set(m.id,y);}for(let m of w){let v=o.recentlyComputedDerivations.has(m.id),y=$(1,T[1],m.y,m.id,m.label,b.accent,false,v);E.set(m.id,y);}for(let m of L){let v=o.recentlyActiveConstraints.has(m.id),y=$(2,T[2],m.y,m.id,m.label,m.active?b.yellow:b.muted,!m.active,v);N.set(m.id,y);}for(let m of B){let v=m.status==="unmet"?b.red:b.yellow,y=$(3,T[3],m.y,m.id,K(m.type,j.labelMaxChars),v,false,false);I.set(m.id,y);}for(let m of D){let v=i.some(y=>y.resolverId===m.id);$(4,T[4],m.y,m.id,m.label,v?b.green:b.muted,!v,false);}for(let m of w){let v=o.derivationDeps.get(m.id),y=E.get(m.id);if(v&&y)for(let t of v){let p=x.get(t);p&&S(p.midX+j.nodeW/2,p.midY,y.midX-j.nodeW/2,y.midY,b.accent);}}for(let m of B){let v=N.get(m.fromConstraint),y=I.get(m.id);v&&y&&S(v.midX+j.nodeW/2,v.midY,y.midX-j.nodeW/2,y.midY,b.muted);}for(let m of i){let v=I.get(m.id);if(v){let y=D.find(t=>t.id===m.resolverId);y&&S(v.midX+j.nodeW/2,v.midY,T[4],y.y,b.green);}}Se.set(e.flowSvg,P);}function qe(e){e.animationTimer&&clearTimeout(e.animationTimer),e.animationTimer=setTimeout(()=>{e.recentlyChangedFacts.clear(),e.recentlyComputedDerivations.clear(),e.recentlyActiveConstraints.clear(),e.animationTimer=null;},600);}function ze(e,s){let o=s.entries.toArray();if(o.length===0)return;e.timelineSvg.replaceChildren();let r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let C of o)C.startMs<r&&(r=C.startMs),C.endMs>a&&(a=C.endMs);let d=performance.now();for(let C of s.inflight.values())C<r&&(r=C),d>a&&(a=d);let c=a-r||1,n=ne-oe-10,i=[],l=new Set;for(let C of o)l.has(C.resolver)||(l.add(C.resolver),i.push(C.resolver));for(let C of s.inflight.keys())l.has(C)||(l.add(C),i.push(C));let h=i.slice(-12),k=re*h.length+20;e.timelineSvg.setAttribute("viewBox",`0 0 ${ne} ${k}`),e.timelineSvg.setAttribute("height",String(Math.min(k,200)));let _=5;for(let C=0;C<=_;C++){let T=oe+n*C/_,u=c*C/_,f=document.createElementNS("http://www.w3.org/2000/svg","text");f.setAttribute("x",String(T)),f.setAttribute("y","8"),f.setAttribute("fill",b.muted),f.setAttribute("font-size","6"),f.setAttribute("font-family",b.font),f.setAttribute("text-anchor","middle"),f.textContent=u<1e3?`${u.toFixed(0)}ms`:`${(u/1e3).toFixed(1)}s`,e.timelineSvg.appendChild(f);let A=document.createElementNS("http://www.w3.org/2000/svg","line");A.setAttribute("x1",String(T)),A.setAttribute("y1","10"),A.setAttribute("x2",String(T)),A.setAttribute("y2",String(k)),A.setAttribute("stroke",b.border),A.setAttribute("stroke-width","0.5"),e.timelineSvg.appendChild(A);}for(let C=0;C<h.length;C++){let T=h[C],u=12+C*re,f=C%be.length,A=be[f],w=document.createElementNS("http://www.w3.org/2000/svg","text");w.setAttribute("x",String(oe-4)),w.setAttribute("y",String(u+re/2+3)),w.setAttribute("fill",b.muted),w.setAttribute("font-size","7"),w.setAttribute("font-family",b.font),w.setAttribute("text-anchor","end"),w.textContent=K(T,12),e.timelineSvg.appendChild(w);let L=o.filter(D=>D.resolver===T);for(let D of L){let V=oe+(D.startMs-r)/c*n,O=Math.max((D.endMs-D.startMs)/c*n,fe),H=document.createElementNS("http://www.w3.org/2000/svg","rect");H.setAttribute("x",String(V)),H.setAttribute("y",String(u+2)),H.setAttribute("width",String(O)),H.setAttribute("height",String(re-4)),H.setAttribute("rx","2"),H.setAttribute("fill",D.error?b.red:A),H.setAttribute("opacity","0.8");let P=document.createElementNS("http://www.w3.org/2000/svg","title"),$=D.endMs-D.startMs;P.textContent=`${T}: ${$.toFixed(1)}ms${D.error?" (error)":""}`,H.appendChild(P),e.timelineSvg.appendChild(H);}let B=s.inflight.get(T);if(B!==void 0){let D=oe+(B-r)/c*n,V=Math.max((d-B)/c*n,fe),O=document.createElementNS("http://www.w3.org/2000/svg","rect");O.setAttribute("x",String(D)),O.setAttribute("y",String(u+2)),O.setAttribute("width",String(V)),O.setAttribute("height",String(re-4)),O.setAttribute("rx","2"),O.setAttribute("fill",A),O.setAttribute("opacity","0.4"),O.setAttribute("stroke",A),O.setAttribute("stroke-width","1"),O.setAttribute("stroke-dasharray","3,2");let H=document.createElementNS("http://www.w3.org/2000/svg","title");H.textContent=`${T}: inflight ${(d-B).toFixed(0)}ms`,O.appendChild(H),e.timelineSvg.appendChild(O);}}e.timelineSvg.setAttribute("aria-label",`Timeline: ${o.length} resolver executions across ${h.length} resolvers`);}function et(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[],explain:()=>null,exportSession:()=>null,importSession:()=>false,clearEvents:()=>{},subscribe:()=>()=>{}};if(!window.__DIRECTIVE__){let e=new Map,s={systems:e,getSystem(o){return o?e.get(o)?.system??null:e.values().next().value?.system??null},getSystems(){return [...e.keys()]},inspect(o){let r=this.getSystem(o),a=o?e.get(o):e.values().next().value,d=r?.inspect()??null;return d&&a&&(d.resolverStats=a.resolverStats?Object.fromEntries(a.resolverStats):{}),d},getEvents(o){return o?e.get(o)?.events.toArray()??[]:e.values().next().value?.events.toArray()??[]},explain(o,r){return this.getSystem(r)?.explain(o)??null},subscribe(o,r){let a=r?e.get(r):e.values().next().value;if(!a){let d=false,n=setInterval(()=>{let l=r?e.get(r):e.values().next().value;l&&!d&&(d=true,l.subscribers.add(o));},100),i=setTimeout(()=>clearInterval(n),1e4);return ()=>{clearInterval(n),clearTimeout(i);for(let l of e.values())l.subscribers.delete(o);}}return a.subscribers.add(o),()=>{a.subscribers.delete(o);}},exportSession(o){let r=o?e.get(o):e.values().next().value;return r?JSON.stringify({version:1,name:o??e.keys().next().value??"default",exportedAt:Date.now(),events:r.events.toArray()}):null},importSession(o,r){try{if(o.length>10*1024*1024)return !1;let a=JSON.parse(o);if(!a||typeof a!="object"||Array.isArray(a)||!Array.isArray(a.events))return !1;let d=r?e.get(r):e.values().next().value;if(!d)return !1;let c=d.maxEvents,n=a.events,i=n.length>c?n.length-c:0;d.events.clear();for(let l=i;l<n.length;l++){let g=n[l];g&&typeof g=="object"&&!Array.isArray(g)&&typeof g.timestamp=="number"&&typeof g.type=="string"&&g.type!=="__proto__"&&g.type!=="constructor"&&g.type!=="prototype"&&d.events.push({timestamp:g.timestamp,type:g.type,data:g.data??null});}return !0}catch{return false}},clearEvents(o){let r=o?e.get(o):e.values().next().value;r&&r.events.clear();}};return Object.defineProperty(window,"__DIRECTIVE__",{value:s,writable:false,configurable:le(),enumerable:true}),s}return window.__DIRECTIVE__}function tt(e={}){let{name:s="default",trace:o=false,maxEvents:r,panel:a=false,position:d="bottom-right",defaultOpen:c=false}=e,n=ke(r),i=et(),l={system:null,events:new ie(n),maxEvents:n,subscribers:new Set,resolverStats:new Map};i.systems.set(s,l);let g=(t,p)=>{let M={timestamp:Date.now(),type:t,data:p};o&&l.events.push(M);for(let R of l.subscribers)try{R(M);}catch{}},h=null,k=new Map,_=new Map,C=Le(),T=Pe(),u=Ne(),f=Oe(),A=a&&typeof window<"u"&&typeof document<"u"&&le(),w=null,L=0,B=1,D=2,V=4,O=8,H=16,P=32,$=64,S=128,x=new Map,E=new Set,N=null;function I(t){L|=t,w===null&&typeof requestAnimationFrame<"u"&&(w=requestAnimationFrame(m));}function m(){if(w=null,!h||!l.system){L=0;return}let t=h.refs,p=l.system,M=L;if(L=0,M&B){for(let R of E)He(k,R);E.clear();for(let[R,{value:z,flash:F}]of x)se(k,t.factsBody,R,z,F,h.flashTimers);x.clear(),t.factsCount.textContent=String(k.size);}if(M&D&&ve(t,_,p,h.flashTimers),M&O)if(N)de(t,N.inflight.length,N.unmet.length);else {let R=te(p);R&&de(t,R.inflight.length,R.unmet.length);}if(M&V)if(N)ue(t,N.inflight,N.unmet);else {let R=te(p);R&&ue(t,R.inflight,R.unmet);}M&H&&je(t,C),M&P&&xe(t,p,T),M&$&&he(t,p),M&S&&ze(t,f);}function v(t,p){h&&o&&Ve(h.refs,t,p,l.events.size);}function y(t,p){u.isRecording&&u.recordedEvents.length<Ie&&u.recordedEvents.push({timestamp:Date.now(),type:t,data:Re(p)});}return {name:"devtools",onInit:t=>{if(l.system=t,g("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${s}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit"),A){let p=l.system;h=Be(s,d,c,o);let M=h.refs;try{let z=p.facts.$store.toObject();for(let[F,W]of Object.entries(z))se(k,M.factsBody,F,W,!1);M.factsCount.textContent=String(Object.keys(z).length);}catch{}ve(M,_,p);let R=te(p);R&&(de(M,R.inflight.length,R.unmet.length),ue(M,R.inflight,R.unmet)),he(M,p),Fe(M,p),xe(M,p,T),M.recordBtn.addEventListener("click",()=>{if(u.isRecording=!u.isRecording,M.recordBtn.textContent=u.isRecording?"\u23F9 Stop":"\u23FA Record",M.recordBtn.style.color=u.isRecording?b.red:b.text,u.isRecording){u.recordedEvents=[],u.snapshots=[];try{u.snapshots.push({timestamp:Date.now(),facts:p.facts.$store.toObject()});}catch{}}}),M.exportBtn.addEventListener("click",()=>{let z=u.recordedEvents.length>0?u.recordedEvents:l.events.toArray(),F=JSON.stringify({version:1,name:s,exportedAt:Date.now(),events:z,snapshots:u.snapshots},null,2),W=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(W),J=document.createElement("a");J.href=G,J.download=`directive-session-${s}-${Date.now()}.json`,J.click(),URL.revokeObjectURL(G);});}},onStart:t=>{g("start",{}),v("start",{}),y("start",{});},onStop:t=>{g("stop",{}),v("stop",{}),y("stop",{});},onDestroy:t=>{g("destroy",{}),i.systems.delete(s),w!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(w),w=null),T.animationTimer&&clearTimeout(T.animationTimer),h&&(h.destroy(),h=null,k.clear(),_.clear());},onFactSet:(t,p,M)=>{g("fact.set",{key:t,value:p,prev:M}),y("fact.set",{key:t,value:p,prev:M}),T.recentlyChangedFacts.add(t),h&&l.system&&(x.set(t,{value:p,flash:true}),E.delete(t),I(B),v("fact.set",{key:t,value:p}));},onFactDelete:(t,p)=>{g("fact.delete",{key:t,prev:p}),y("fact.delete",{key:t,prev:p}),h&&(E.add(t),x.delete(t),I(B),v("fact.delete",{key:t}));},onFactsBatch:t=>{if(g("facts.batch",{changes:t}),y("facts.batch",{count:t.length}),h&&l.system){for(let p of t)p.type==="delete"?(E.add(p.key),x.delete(p.key)):(T.recentlyChangedFacts.add(p.key),x.set(p.key,{value:p.value,flash:true}),E.delete(p.key));I(B),v("facts.batch",{count:t.length});}},onDerivationCompute:(t,p,M)=>{g("derivation.compute",{id:t,value:p,deps:M}),y("derivation.compute",{id:t,deps:M}),T.derivationDeps.set(t,M),T.recentlyComputedDerivations.add(t),v("derivation.compute",{id:t,deps:M});},onDerivationInvalidate:t=>{g("derivation.invalidate",{id:t}),v("derivation.invalidate",{id:t});},onReconcileStart:t=>{g("reconcile.start",{}),C.lastReconcileStartMs=performance.now(),v("reconcile.start",{}),y("reconcile.start",{});},onReconcileEnd:t=>{if(g("reconcile.end",t),y("reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length,completed:t.completed.length}),C.lastReconcileStartMs>0){let p=performance.now()-C.lastReconcileStartMs;C.reconcileCount++,C.reconcileTotalMs+=p,C.lastReconcileStartMs=0;}if(u.isRecording&&l.system&&u.snapshots.length<_e)try{u.snapshots.push({timestamp:Date.now(),facts:l.system.facts.$store.toObject()});}catch{}h&&l.system&&(N=t,qe(T),I(D|O|V|H|P|$),v("reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length}));},onConstraintEvaluate:(t,p)=>{g("constraint.evaluate",{id:t,active:p}),y("constraint.evaluate",{id:t,active:p}),p?(T.activeConstraints.add(t),T.recentlyActiveConstraints.add(t)):T.activeConstraints.delete(t),v("constraint.evaluate",{id:t,active:p});},onConstraintError:(t,p)=>{g("constraint.error",{id:t,error:String(p)}),v("constraint.error",{id:t,error:String(p)});},onRequirementCreated:t=>{g("requirement.created",{id:t.id,type:t.requirement.type}),y("requirement.created",{id:t.id,type:t.requirement.type}),v("requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,p)=>{g("requirement.met",{id:t.id,byResolver:p}),y("requirement.met",{id:t.id,byResolver:p}),v("requirement.met",{id:t.id,byResolver:p});},onRequirementCanceled:t=>{g("requirement.canceled",{id:t.id}),y("requirement.canceled",{id:t.id}),v("requirement.canceled",{id:t.id});},onResolverStart:(t,p)=>{g("resolver.start",{resolver:t,requirementId:p.id}),y("resolver.start",{resolver:t,requirementId:p.id}),f.inflight.set(t,performance.now()),h&&l.system&&(I(V|O|S),v("resolver.start",{resolver:t,requirementId:p.id}));},onResolverComplete:(t,p,M)=>{g("resolver.complete",{resolver:t,requirementId:p.id,duration:M}),y("resolver.complete",{resolver:t,requirementId:p.id,duration:M});let R=l.resolverStats.get(t)??{count:0,totalMs:0,errors:0};if(R.count++,R.totalMs+=M,l.resolverStats.set(t,R),l.resolverStats.size>ye){let F=l.resolverStats.keys().next().value;F!==void 0&&l.resolverStats.delete(F);}C.resolverStats.set(t,{...R});let z=f.inflight.get(t);f.inflight.delete(t),z!==void 0&&f.entries.push({resolver:t,startMs:z,endMs:performance.now(),error:false}),h&&l.system&&(I(V|O|H|S),v("resolver.complete",{resolver:t,duration:M}));},onResolverError:(t,p,M)=>{g("resolver.error",{resolver:t,requirementId:p.id,error:String(M)}),y("resolver.error",{resolver:t,requirementId:p.id,error:String(M)});let R=l.resolverStats.get(t)??{count:0,totalMs:0,errors:0};if(R.errors++,l.resolverStats.set(t,R),l.resolverStats.size>ye){let F=l.resolverStats.keys().next().value;F!==void 0&&l.resolverStats.delete(F);}C.resolverStats.set(t,{...R});let z=f.inflight.get(t);f.inflight.delete(t),z!==void 0&&f.entries.push({resolver:t,startMs:z,endMs:performance.now(),error:true}),h&&l.system&&(I(V|O|H|S),v("resolver.error",{resolver:t,error:String(M)}));},onResolverRetry:(t,p,M)=>{g("resolver.retry",{resolver:t,requirementId:p.id,attempt:M}),y("resolver.retry",{resolver:t,requirementId:p.id,attempt:M}),v("resolver.retry",{resolver:t,attempt:M});},onResolverCancel:(t,p)=>{g("resolver.cancel",{resolver:t,requirementId:p.id}),y("resolver.cancel",{resolver:t,requirementId:p.id}),f.inflight.delete(t),v("resolver.cancel",{resolver:t});},onEffectRun:t=>{g("effect.run",{id:t}),y("effect.run",{id:t}),C.effectRunCount++,v("effect.run",{id:t});},onEffectError:(t,p)=>{g("effect.error",{id:t,error:String(p)}),C.effectErrorCount++,v("effect.error",{id:t,error:String(p)});},onSnapshot:t=>{g("timetravel.snapshot",{id:t.id,trigger:t.trigger}),h&&l.system&&I($),v("timetravel.snapshot",{id:t.id,trigger:t.trigger});},onTimeTravel:(t,p)=>{if(g("timetravel.jump",{from:t,to:p}),y("timetravel.jump",{from:t,to:p}),h&&l.system){let M=l.system;try{let R=M.facts.$store.toObject();k.clear(),h.refs.factsBody.replaceChildren();for(let[z,F]of Object.entries(R))se(k,h.refs.factsBody,z,F,!1);h.refs.factsCount.textContent=String(Object.keys(R).length);}catch{}_.clear(),T.derivationDeps.clear(),h.refs.derivBody.replaceChildren(),N=null,I(D|O|V|P|$),v("timetravel.jump",{from:t,to:p});}},onError:t=>{g("error",{source:t.source,sourceId:t.sourceId,message:t.message}),y("error",{source:t.source,message:t.message}),v("error",{source:t.source,message:t.message});},onErrorRecovery:(t,p)=>{g("error.recovery",{source:t.source,sourceId:t.sourceId,strategy:p}),v("error.recovery",{source:t.source,strategy:p});},onRunComplete:t=>{g("run.complete",{id:t.id,status:t.status,facts:t.factChanges.length,constraints:t.constraintsHit.length,requirements:t.requirementsAdded.length,resolvers:t.resolversStarted.length,effects:t.effectsRun.length}),v("run.complete",{id:t.id});}}}var Ue="directive-devtools-event",We=new Set(["__proto__","constructor","prototype"]),nt=Math.random().toString(36).slice(2,8);function rt(){if(typeof window<"u"){let e=`__DIRECTIVE_BRIDGE_ID_${nt}__`,s=window,o=s[e]??0;return s[e]=o+1,o+1}return 1}function ot(e){let s=false;for(let r of We)if(r in e){s=true;break}if(!s)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))We.has(r)||(o[r]=a);return o}function it(e){if(!(typeof window>"u"))try{let s=ot(e),o={id:rt(),timestamp:Date.now(),snapshotId:null,...s};window.dispatchEvent(new CustomEvent(Ue,{detail:o}));}catch{}}function Ge(e,s=50){let o=new Set(["__proto__","constructor","prototype"]),r=new WeakSet;function a(d,c){if(c>s)return false;if(d==null||typeof d!="object")return true;let n=d;if(r.has(n))return true;if(r.add(n),Array.isArray(n)){for(let i of n)if(!a(i,c+1))return r.delete(n),false;return r.delete(n),true}for(let i of Object.keys(n))if(o.has(i)||!a(n[i],c+1))return r.delete(n),false;return r.delete(n),true}return a(e,0)}function st(e){let{storage:s,key:o,include:r,exclude:a=[],debounce:d=100,onRestore:c,onSave:n,onError:i}=e,l=null,g=null,h=new Set,k=u=>a.includes(u)?false:r?r.includes(u):true,_=()=>{try{let u=s.getItem(o);if(!u)return null;let f=JSON.parse(u);return typeof f!="object"||f===null?null:Ge(f)?f:(i?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(u){return i?.(u instanceof Error?u:new Error(String(u))),null}},C=()=>{if(g)try{let u={};for(let f of h)k(f)&&(u[f]=g.facts[f]);s.setItem(o,JSON.stringify(u)),n?.(u);}catch(u){i?.(u instanceof Error?u:new Error(String(u)));}},T=()=>{l&&clearTimeout(l),l=setTimeout(C,d);};return {name:"persistence",onInit:u=>{g=u;let f=_();f&&(g.facts.$store.batch(()=>{for(let[A,w]of Object.entries(f))k(A)&&(g.facts[A]=w,h.add(A));}),c?.(f));},onDestroy:()=>{l&&clearTimeout(l),C();},onFactSet:u=>{h.add(u),k(u)&&T();},onFactDelete:u=>{h.delete(u),k(u)&&T();},onFactsBatch:u=>{let f=false;for(let A of u)A.type==="set"?h.add(A.key):h.delete(A.key),k(A.key)&&(f=true);f&&T();}}}function at(e={}){let{onSlowConstraint:s,onSlowResolver:o,slowConstraintThresholdMs:r=16,slowResolverThresholdMs:a=1e3}=e,d=new Map,c=new Map,n=new Map,i={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},l=0,g=0,h=0;function k(u){let f=d.get(u);return f||(f={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},d.set(u,f)),f}function _(u){let f=c.get(u);return f||(f={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},c.set(u,f)),f}function C(u){let f=n.get(u);return f||(f={runs:0,errors:0,lastRunAt:0},n.set(u,f)),f}return {name:"performance",onStart(){l=Date.now();},onConstraintEvaluate(u,f){let A=performance.now(),w=k(u);if(w.evaluations++,w.lastEvaluatedAt=Date.now(),h>0){let L=A-h;w.totalDurationMs+=L;let B=w.evaluations;w.avgDurationMs=w.totalDurationMs/B,L>w.maxDurationMs&&(w.maxDurationMs=L),L>r&&s?.(u,L);}h=A;},onResolverStart(u,f){let A=_(u);A.starts++;},onResolverComplete(u,f,A){let w=_(u);w.completions++,w.totalDurationMs+=A,w.avgDurationMs=w.totalDurationMs/w.completions,A>w.maxDurationMs&&(w.maxDurationMs=A),w.lastCompletedAt=Date.now(),A>a&&o?.(u,A);},onResolverError(u,f,A){_(u).errors++;},onResolverRetry(u,f,A){_(u).retries++;},onResolverCancel(u,f){_(u).cancellations++;},onEffectRun(u){let f=C(u);f.runs++,f.lastRunAt=Date.now();},onEffectError(u,f){C(u).errors++;},onReconcileStart(){g=performance.now(),h=0;},onReconcileEnd(){let u=performance.now()-g;i.runs++,i.totalDurationMs+=u,i.avgDurationMs=i.totalDurationMs/i.runs,u>i.maxDurationMs&&(i.maxDurationMs=u);},getSnapshot(){let u={};for(let[w,L]of d)u[w]={...L};let f={};for(let[w,L]of c)f[w]={...L};let A={};for(let[w,L]of n)A[w]={...L};return {constraints:u,resolvers:f,effects:A,reconcile:{...i},uptime:l?Date.now()-l:0}},reset(){d.clear(),c.clear(),n.clear(),i.runs=0,i.totalDurationMs=0,i.avgDurationMs=0,i.maxDurationMs=0,h=0;}}}function me(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function Ee(e,s){if(e.length===0)return 0;let o=[...e].sort((a,d)=>a-d),r=Math.ceil(s/100*o.length)-1;return o[Math.max(0,r)]??0}function ct(e={}){let{serviceName:s="directive-agents",metrics:o={},tracing:r={},alerts:a=[],summaryMetrics:d={},events:c={}}=e,n={requests:d.requests??"agent.requests",errors:d.errors??"agent.errors",latency:d.latency??"agent.latency",tokens:d.tokens??"agent.tokens",cost:d.cost??"agent.cost"},{enabled:i=true,exportInterval:l,exporter:g,maxDataPoints:h=1e3}=o,{enabled:k=true,sampleRate:_=1,maxSpans:C=1e3,exporter:T}=r,u=Date.now(),f=new Map,A=new Map,w=[],L=[],B=new Map,D=new Map,V;l&&(g||T)&&(V=setInterval(async()=>{try{if(g&&i&&await g(Array.from(D.values())),T&&k){let S=w.splice(0,100);S.length>0&&await T(S);}}catch(S){console.error("[Directive Observability] Export error:",S);}},l));function O(S){if(!i)return;let x=`${S.name}:${JSON.stringify(Object.fromEntries(Object.entries(S.labels).sort()))}`,E=f.get(x);E||(E=[],f.set(x,E)),E.push(S),E.length>h&&E.shift(),H(S.name,E),c.onMetricRecorded?.(S),P(S.name);}function H(S,x){if(x.length===0)return;let E=x.map(y=>y.value),N=E.reduce((y,t)=>y+t,0),I=x[0],m=E[E.length-1],v={name:S,type:I.type,count:x.length,sum:N,min:Math.min(...E),max:Math.max(...E),avg:N/x.length,lastValue:m,lastUpdated:Date.now()};D.set(S,v);}function P(S){for(let x of a){if(x.metric!==S)continue;let E=D.get(S);if(!E)continue;let N=`${x.metric}:${x.threshold}`,I=B.get(N),m=x.cooldownMs??6e4;if(I&&Date.now()-I<m)continue;let v=x.operator??">",y=E.lastValue,t=x.threshold,p=false;switch(v){case ">":p=y>t;break;case "<":p=y<t;break;case ">=":p=y>=t;break;case "<=":p=y<=t;break;case "==":p=y===t;break}if(p){let M={alertId:me(),metric:S,currentValue:y,threshold:t,operator:v,action:x.action,timestamp:Date.now(),message:`Alert: ${S} ${v} ${t} (current: ${y})`};switch(L.push(M),L.length>1e3&&L.splice(0,L.length-1e3),B.set(N,Date.now()),c.onAlert?.(M),x.action){case "log":console.log(`[Observability] ${M.message}`);break;case "warn":console.warn(`[Observability] ${M.message}`);break;case "alert":console.error(`[Observability ALERT] ${M.message}`);break;case "callback":x.callback?.(E,t);break}}}}function $(S){let x=[];for(let[E,N]of f)if(E.startsWith(`${S}:`))for(let I of N)x.push(I.value);return x.length===0?{}:{p50:Ee(x,50),p90:Ee(x,90),p99:Ee(x,99)}}return {incrementCounter(S,x={},E=1){O({name:S,type:"counter",value:E,labels:x,timestamp:Date.now()});},setGauge(S,x,E={}){O({name:S,type:"gauge",value:x,labels:E,timestamp:Date.now()});},observeHistogram(S,x,E={}){O({name:S,type:"histogram",value:x,labels:E,timestamp:Date.now()});},startSpan(S,x){if(Math.random()>_)return {traceId:"sampled-out",spanId:"sampled-out",operationName:S,serviceName:s,startTime:Date.now(),status:"ok",tags:{},logs:[]};let E={traceId:x?A.get(x)?.traceId??me():me(),spanId:me(),parentSpanId:x,operationName:S,serviceName:s,startTime:Date.now(),status:"ok",tags:{},logs:[]};return k&&(A.set(E.spanId,E),c.onSpanStart?.(E)),E},endSpan(S,x="ok"){if(S==="sampled-out")return;let E=A.get(S);if(E){for(E.endTime=Date.now(),E.duration=E.endTime-E.startTime,E.status=x,A.delete(S),w.push(E);w.length>C;)w.shift();O({name:`${E.operationName}.latency`,type:"histogram",value:E.duration,labels:{},timestamp:Date.now()}),x==="error"&&O({name:`${E.operationName}.errors`,type:"counter",value:1,labels:{},timestamp:Date.now()}),c.onSpanEnd?.(E);}},addSpanLog(S,x,E="info"){if(S==="sampled-out")return;let N=A.get(S);N&&N.logs.push({timestamp:Date.now(),message:x,level:E});},addSpanTag(S,x,E){if(S==="sampled-out")return;let N=A.get(S);N&&(N.tags[x]=E);},getDashboard(){let S=D.get(n.requests),x=D.get(n.errors),E=D.get(n.latency),N=D.get(n.tokens),I=D.get(n.cost),m=S?.sum??0,v=x?.sum??0,y=m>0?v/m:0,t=E?$(n.latency):{};return {service:{name:s,uptime:Date.now()-u,startTime:u},metrics:Object.fromEntries(D),traces:[...w].slice(-100),alerts:[...L].slice(-50),summary:{totalRequests:m,totalErrors:v,errorRate:y,avgLatency:E?.avg??0,p99Latency:t.p99??0,activeSpans:A.size,totalTokens:N?.sum??0,totalCost:I?.sum??0}}},getMetric(S){let x=D.get(S);if(!x)return;let E=$(S);return {...x,...E}},getTraces(S=100){return [...w].slice(-S)},getAlerts(){return [...L]},export(){return {metrics:Array.from(D.values()),traces:[...w],alerts:[...L]}},clear(){f.clear(),D.clear(),A.clear(),w.length=0,L.length=0,B.clear();},async dispose(){V&&(clearInterval(V),V=void 0);try{g&&i&&D.size>0&&await g(Array.from(D.values())),T&&k&&w.length>0&&await T([...w]);}catch(S){console.error("[Directive Observability] Error flushing data during dispose:",S);}f.clear(),D.clear(),A.clear(),w.length=0,L.length=0,B.clear();},getHealthStatus(){let S=D.get(n.requests),x=D.get(n.errors),E=S?.sum??0,N=x?.sum??0,I=E>0?N/E:0,m=L.filter(v=>Date.now()-v.timestamp<3e5).length;return {healthy:I<.1&&m===0,uptime:Date.now()-u,errorRate:I,activeAlerts:m}}}}function lt(e){return {trackRun(s,o){let r={agent:s};e.incrementCounter("agent.requests",r),o.success||e.incrementCounter("agent.errors",r),e.observeHistogram("agent.latency",o.latencyMs,r),o.inputTokens!==void 0&&(e.incrementCounter("agent.tokens.input",r,o.inputTokens),e.incrementCounter("agent.tokens",r,o.inputTokens)),o.outputTokens!==void 0&&(e.incrementCounter("agent.tokens.output",r,o.outputTokens),e.incrementCounter("agent.tokens",r,o.outputTokens)),o.cost!==void 0&&e.incrementCounter("agent.cost",r,o.cost),o.toolCalls!==void 0&&e.incrementCounter("agent.tool_calls",r,o.toolCalls);},trackGuardrail(s,o){let r={guardrail:s};e.incrementCounter("guardrail.checks",r),o.passed||e.incrementCounter("guardrail.failures",r),o.blocked&&e.incrementCounter("guardrail.blocks",r),e.observeHistogram("guardrail.latency",o.latencyMs,r);},trackApproval(s,o){let r={tool:s};e.incrementCounter("approval.requests",r),o.approved?e.incrementCounter("approval.approved",r):e.incrementCounter("approval.rejected",r),o.timedOut&&e.incrementCounter("approval.timeouts",r),e.observeHistogram("approval.wait_time",o.waitTimeMs,r);},trackHandoff(s,o,r){e.incrementCounter("handoff.count",{from:s,to:o}),e.observeHistogram("handoff.latency",r);}}}function ut(e){let s=[{key:"service.name",value:{stringValue:e.serviceName??"directive-agents"}}];if(e.serviceVersion&&s.push({key:"service.version",value:{stringValue:e.serviceVersion}}),e.resourceAttributes)for(let[o,r]of Object.entries(e.resourceAttributes))s.push({key:o,value:{stringValue:r}});return {attributes:s}}function Z(e){return `${BigInt(e)*BigInt(1e6)}`}function dt(e){switch(e){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function mt(e,s,o){let r=e.map(a=>{let d=a.lastUpdated-6e4,c=[{asInt:a.type==="counter"?a.sum:void 0,asDouble:a.type!=="counter"?a.lastValue:void 0,timeUnixNano:Z(a.lastUpdated),startTimeUnixNano:Z(d),attributes:[]}],n=dt(a.type),i={name:a.name,unit:""};return n==="sum"?i.sum={dataPoints:c,aggregationTemporality:2,isMonotonic:true}:n==="histogram"?i.histogram={dataPoints:[{count:a.count,sum:a.sum,min:a.min,max:a.max,timeUnixNano:Z(a.lastUpdated),startTimeUnixNano:Z(d),attributes:[]}],aggregationTemporality:2}:i.gauge={dataPoints:c},i});return {resourceMetrics:[{resource:s,scopeMetrics:[{scope:{name:"directive",version:o},metrics:r}]}]}}function pt(e,s,o){let r=e.map(a=>{let d=a.logs.map(i=>({timeUnixNano:Z(i.timestamp),name:i.level,attributes:[{key:"message",value:{stringValue:i.message}},{key:"level",value:{stringValue:i.level}}]})),c=Object.entries(a.tags).map(([i,l])=>({key:i,value:typeof l=="string"?{stringValue:l}:typeof l=="number"?{intValue:`${l}`}:{boolValue:l}})),n=a.status==="ok"?1:a.status==="error"?2:0;return {traceId:a.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:a.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:a.parentSpanId?a.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:a.operationName,kind:1,startTimeUnixNano:Z(a.startTime),endTimeUnixNano:a.endTime?Z(a.endTime):Z(a.startTime),attributes:c,events:d,status:{code:n}}});return {resourceSpans:[{resource:s,scopeSpans:[{scope:{name:"directive",version:o},spans:r}]}]}}function gt(e){let{endpoint:s,headers:o={},scopeVersion:r="0.1.0",timeoutMs:a=1e4,fetch:d=globalThis.fetch,onError:c}=e;try{let l=new URL(s);if(l.protocol!=="http:"&&l.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(l){throw new Error(`[Directive OTLP] Invalid endpoint URL "${s}": ${l instanceof Error?l.message:String(l)}`)}if(/\/v1\/(metrics|traces)/.test(s)&&console.warn(`[Directive OTLP] Endpoint "${s}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),a<=0||!Number.isFinite(a))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${a}`);let n=ut(e);async function i(l,g,h){let k=`${s.replace(/\/$/,"")}${l}`,_=new AbortController,C=setTimeout(()=>_.abort(),a);try{let T=await d(k,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify(g),signal:_.signal});if(!T.ok)throw new Error(`OTLP export failed: ${T.status} ${T.statusText}`)}catch(T){let u=T instanceof Error?T:new Error(String(T));c?c(u,h):console.error(`[Directive OTLP] Export ${h} error:`,u.message);}finally{clearTimeout(C);}}return {async exportMetrics(l){if(l.length===0)return;let g=mt(l,n,r);await i("/v1/metrics",g,"metrics");},async exportTraces(l){if(l.length===0)return;let g=pt(l,n,r);await i("/v1/traces",g,"traces");}}}var ae=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(s,o,r="OPEN",a){let d=a?`[Directive CircuitBreaker] Circuit "${s}" is ${r}. ${a}`:`[Directive CircuitBreaker] Circuit "${s}" is ${r}. Request rejected. Try again in ${Math.ceil(o/1e3)}s.`;super(d),this.name="CircuitBreakerOpenError",this.retryAfterMs=o,this.state=r;}};function ft(e={}){let{failureThreshold:s=5,recoveryTimeMs:o=3e4,halfOpenMaxRequests:r=3,failureWindowMs:a=6e4,observability:d,metricPrefix:c="circuit_breaker",name:n="default",isFailure:i=()=>true,onStateChange:l}=e;if(s<1||!Number.isFinite(s))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${s}`);if(o<=0||!Number.isFinite(o))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${o}`);if(r<1||!Number.isFinite(r))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${r}`);if(a<=0||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${a}`);let g="CLOSED",h=[],k=0,_=0,C=Date.now(),T=0,u=0,f=0,A=0,w=0,L=null,B=null;function D(P){if(g===P)return;let $=g;g=P,C=Date.now(),P==="OPEN"&&(T=Date.now()),P==="HALF_OPEN"&&(k=0,_=0),l?.($,P),d&&d.incrementCounter(`${c}.state_change`,{name:n,from:$,to:P});}function V(){let P=Date.now()-a;return h=h.filter($=>$>P),h.length}function O(){A++,B=Date.now(),d&&d.incrementCounter(`${c}.success`,{name:n}),g==="HALF_OPEN"&&(_++,_>=r&&(D("CLOSED"),h=[]));}function H(P){if(!i(P)){O();return}f++,L=Date.now(),h.push(Date.now());let $=s*2;if(h.length>$&&(h=h.slice(-$)),d&&d.incrementCounter(`${c}.failure`,{name:n}),g==="HALF_OPEN"){D("OPEN");return}g==="CLOSED"&&V()>=s&&D("OPEN");}return {async execute(P){if(u++,d&&d.incrementCounter(`${c}.requests`,{name:n}),g==="OPEN")if(Date.now()-T>=o)D("HALF_OPEN");else throw w++,d&&d.incrementCounter(`${c}.rejected`,{name:n}),new ae(n,o-(Date.now()-T));if(g==="HALF_OPEN"){if(k>=r)throw w++,new ae(n,o,"HALF_OPEN",`Max trial requests (${r}) reached.`);k++;}let $=Date.now();try{let S=await P();return O(),d&&d.observeHistogram(`${c}.latency`,Date.now()-$,{name:n}),S}catch(S){let x=S instanceof Error?S:new Error(String(S));throw H(x),d&&d.observeHistogram(`${c}.latency`,Date.now()-$,{name:n}),S}},getState(){return g==="OPEN"&&Date.now()-T>=o&&D("HALF_OPEN"),g},getStats(){return {state:this.getState(),totalRequests:u,totalFailures:f,totalSuccesses:A,totalRejected:w,recentFailures:V(),lastFailureTime:L,lastSuccessTime:B,lastStateChange:C}},forceState(P){D(P);},reset(){let P=g;g="CLOSED",h=[],k=0,_=0,C=Date.now(),T=0,u=0,f=0,A=0,w=0,L=null,B=null,P!=="CLOSED"&&l?.(P,"CLOSED");},isAllowed(){return g==="CLOSED"?true:g==="OPEN"?Date.now()-T>=o:k<r}}}
|
|
2
|
+
export{ae as CircuitBreakerOpenError,Ue as DEVTOOLS_EVENT_NAME,lt as createAgentMetrics,ft as createCircuitBreaker,gt as createOTLPExporter,ct as createObservability,tt as devtoolsPlugin,it as emitDevToolsEvent,Ke as loggingPlugin,at as performancePlugin,st as persistencePlugin};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|