opencode-apex 0.1.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.
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Apex Advisor — sesión lateral de advisor (una por ÁRBOL de sesiones).
3
+ *
4
+ * Jerarquía: una sesión agente-usuario (raíz) puede invocar subagentes
5
+ * (sesiones agente-agente, con `parentID`). TODAS ellas comparten UNA sola
6
+ * sesión advisor: se resuelve la raíz subiendo por `parentID` y se mapea
7
+ * raíz → sesión advisor.
8
+ *
9
+ * Round-trip: se encola una decisión pendiente (promesa en memoria), se hace
10
+ * `session.prompt` a la sesión advisor y el agente advisor responde llamando a
11
+ * la herramienta `apex_advisor_decide`, que resuelve la promesa.
12
+ *
13
+ * La sesión advisor queda registrada entera → auditoría de cada allow/deny.
14
+ */
15
+
16
+ import { mkdirSync } from "node:fs"
17
+ import { tmpdir } from "node:os"
18
+ import { isAbsolute, join, normalize } from "node:path"
19
+ import { randomUUID } from "node:crypto"
20
+ import { Effect } from "effect"
21
+ import type { Plugin } from "@opencode/plugin/effect"
22
+ import { ADVISOR_AGENT_ID } from "./advisor-agent.js"
23
+
24
+ export interface AdvisorDecision {
25
+ readonly decision: "allow" | "deny"
26
+ readonly reason?: string
27
+ }
28
+
29
+ export interface AdvisorRequest {
30
+ /** Sesión que solicita la ejecución (puede ser un subagente). */
31
+ readonly sessionID: string
32
+ readonly action: string
33
+ readonly resources: readonly string[]
34
+ readonly agent?: string
35
+ readonly metadata?: Record<string, unknown>
36
+ /** true = la decisión se aplica; false = solo se informa al usuario. */
37
+ readonly decisive: boolean
38
+ readonly timeoutMs: number
39
+ readonly template: string
40
+ /** Directorio de la sesión advisor (aislado del proyecto por defecto). */
41
+ readonly location?: string
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Estado en memoria
46
+ // ---------------------------------------------------------------------------
47
+
48
+ /**
49
+ * Estado compartido por PROCESO, no por grafo de módulos.
50
+ *
51
+ * La sesión advisor vive en su propio location (`/tmp/opencode-apex-advisor`, para
52
+ * no heredar el AGENTS.md del repo) y opencode instancia el plugin **una vez por
53
+ * location**: en el log salen dos «[apex] config:», uno por el proyecto y otro por
54
+ * el directorio del advisor. Con el estado en ámbito de módulo, la instancia que
55
+ * registraba la petición y la que ejecutaba `apex_advisor_decide` eran distintas,
56
+ * cada una con su `pending` vacío — la decisión llegaba con `accepted: false` («la
57
+ * solicitud ya no estaba pendiente») y el permiso caducaba por plazo agotado,
58
+ * medido incluso con el advisor respondiendo en 9 s sobre un plazo de 45 s.
59
+ *
60
+ * `Symbol.for` es el único ámbito que coincide con el del recurso: el proceso.
61
+ * La clave lleva versión para que un cambio de forma no choque con una celda vieja.
62
+ */
63
+ interface AdvisorCell {
64
+ /** clave "rootID|location" → advisor sessionID (caché) */
65
+ readonly sessionCache: Map<string, string>
66
+ /** advisor sessionIDs conocidas (guardas anti-recursión) */
67
+ readonly advisorSessions: Set<string>
68
+ /** requestID → resolver de la promesa pendiente */
69
+ readonly pending: Map<string, (decision: AdvisorDecision) => void>
70
+ }
71
+
72
+ const CELL_KEY = Symbol.for("apex.advisor.state.v1")
73
+
74
+ function cell(): AdvisorCell {
75
+ const holder = globalThis as Record<symbol, AdvisorCell | undefined>
76
+ const existing = holder[CELL_KEY]
77
+ if (existing) return existing
78
+ const created: AdvisorCell = {
79
+ sessionCache: new Map(),
80
+ advisorSessions: new Set(),
81
+ pending: new Map(),
82
+ }
83
+ holder[CELL_KEY] = created
84
+ return created
85
+ }
86
+
87
+ const sessionCache = cell().sessionCache
88
+ const advisorSessions = cell().advisorSessions
89
+ const pending = cell().pending
90
+
91
+ const STORAGE_KEY = (rootID: string) => `apex:advisor:session:${rootID}`
92
+ const MAX_DEPTH = 25
93
+
94
+ /**
95
+ * Location por defecto de la sesión advisor: un directorio dedicado FUERA del
96
+ * proyecto. La discovery de instrucciones es por location y solo camina el
97
+ * árbol cuando la sesión está dentro del root del proyecto, así que aquí NO se
98
+ * inyecta el AGENTS.md del repo.
99
+ */
100
+ export const DEFAULT_ADVISOR_LOCATION = join(tmpdir(), "opencode-apex-advisor")
101
+
102
+ /** Guarda: ¿esta sesión es una sesión advisor? (nunca se evalúa a sí misma) */
103
+ export function isAdvisorSession(sessionID: string): boolean {
104
+ return advisorSessions.has(sessionID)
105
+ }
106
+
107
+ /** Llamado por la herramienta del advisor para resolver una decisión pendiente. */
108
+ export function resolvePendingDecision(requestID: string, decision: "allow" | "deny", reason?: string): boolean {
109
+ const resolver = pending.get(requestID)
110
+ if (!resolver) return false
111
+ pending.delete(requestID)
112
+ resolver({ decision, reason })
113
+ return true
114
+ }
115
+
116
+ /** Nº de peticiones pendientes (diagnóstico/tests). */
117
+ export function pendingCount(): number {
118
+ return pending.size
119
+ }
120
+
121
+ // ---------------------------------------------------------------------------
122
+ // Jerarquía de sesiones
123
+ // ---------------------------------------------------------------------------
124
+
125
+ /** Sube por `parentID` hasta la raíz (sesión agente-usuario). */
126
+ export async function resolveRootSessionID(
127
+ ctx: Plugin.Context,
128
+ sessionID: string,
129
+ ): Promise<string> {
130
+ let current = sessionID
131
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
132
+ let info: { parentID?: string } | undefined
133
+ try {
134
+ info = (await Effect.runPromise(ctx.session.get({ sessionID: current as never }))) as { parentID?: string }
135
+ } catch {
136
+ return current
137
+ }
138
+ const parent = info?.parentID
139
+ if (!parent) return current
140
+ current = parent
141
+ }
142
+ return current
143
+ }
144
+
145
+ /** Obtiene (o crea) la ÚNICA sesión advisor del árbol. */
146
+ export async function getOrCreateAdvisorSession(
147
+ ctx: Plugin.Context,
148
+ rootID: string,
149
+ location?: string,
150
+ ): Promise<string> {
151
+ // Directorio aislado: sin AGENTS.md del proyecto (y fuera de $HOME para no
152
+ // caminar la cadena de ancestros del home). Las rutas relativas se resuelven
153
+ // contra el cwd del proceso del servidor.
154
+ const rawDir = location && location.trim().length > 0 ? location.trim() : DEFAULT_ADVISOR_LOCATION
155
+ const directory = isAbsolute(rawDir) ? normalize(rawDir) : join(process.cwd(), rawDir)
156
+ const cacheKey = `${rootID}|${directory}`
157
+
158
+ const cached = sessionCache.get(cacheKey)
159
+ if (cached) return cached
160
+
161
+ // Persistida entre recargas (se valida que siga existiendo, que el agente sea
162
+ // el advisor y que la location coincida; si no, se recrea).
163
+ try {
164
+ const stored = await Effect.runPromise(ctx.storage.get(STORAGE_KEY(rootID)))
165
+ if (typeof stored === "string" && stored.length > 0) {
166
+ const info = (await Effect.runPromise(ctx.session.get({ sessionID: stored as never }))) as
167
+ | { id?: string; agent?: string; metadata?: Record<string, unknown> }
168
+ | undefined
169
+ const storedLocation = info?.metadata?.apexAdvisorLocation
170
+ if (
171
+ info?.id &&
172
+ info.agent === ADVISOR_AGENT_ID &&
173
+ (storedLocation === undefined || storedLocation === directory)
174
+ ) {
175
+ sessionCache.set(cacheKey, stored)
176
+ advisorSessions.add(stored)
177
+ return stored
178
+ }
179
+ }
180
+ } catch {
181
+ // sin sesión persistida válida → se crea
182
+ }
183
+
184
+ try {
185
+ mkdirSync(directory, { recursive: true })
186
+ } catch {
187
+ // si no se puede crear, se intenta crear la sesión igualmente
188
+ }
189
+
190
+ const created = (await Effect.runPromise(
191
+ ctx.session.create({
192
+ agent: ADVISOR_AGENT_ID as never,
193
+ title: "apex advisor",
194
+ metadata: { apexAdvisorFor: rootID, apexAdvisorLocation: directory } as never,
195
+ location: { directory } as never,
196
+ } as never),
197
+ )) as { id: string }
198
+
199
+ const advisorID = created.id
200
+ sessionCache.set(cacheKey, advisorID)
201
+ advisorSessions.add(advisorID)
202
+ await Effect.runPromise(ctx.storage.set(STORAGE_KEY(rootID), advisorID as never))
203
+ return advisorID
204
+ }
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // Round-trip de decisión
208
+ // ---------------------------------------------------------------------------
209
+
210
+ /** Renderiza la petición para el advisor (placeholders de la plantilla). */
211
+ export function renderAdvisorRequest(template: string, input: AdvisorRequest, requestID: string): string {
212
+ const enforcement = input.decisive
213
+ ? "Tu decisión se APLICA automáticamente."
214
+ : "Tu decisión se muestra al usuario, que decide."
215
+
216
+ return template
217
+ .replace(/\{\{requestID\}\}/g, requestID)
218
+ .replace(/\{\{action\}\}/g, input.action)
219
+ .replace(/\{\{resources\}\}/g, input.resources.join(", ") || "(ninguno)")
220
+ .replace(/\{\{sessionID\}\}/g, input.sessionID)
221
+ .replace(/\{\{agent\}\}/g, input.agent ?? "default")
222
+ .replace(/\{\{enforcement\}\}/g, enforcement)
223
+ .replace(/\{\{metadata\.([^}]+)\}\}/g, (_m, path: string) => {
224
+ const value = path
225
+ .split(".")
226
+ .reduce<unknown>((acc, key) => (acc as Record<string, unknown>)?.[key], input.metadata)
227
+ if (value === undefined || value === null) return ""
228
+ return typeof value === "string" ? value : JSON.stringify(value)
229
+ })
230
+ }
231
+
232
+ /** Plantilla por defecto de la petición al advisor. */
233
+ export const DEFAULT_ADVISOR_REQUEST_TEMPLATE = `Solicitud de permiso {{requestID}}
234
+ Herramienta: {{action}}
235
+ Recursos: {{resources}}
236
+ Sesión solicitante: {{sessionID}} · Agente: {{agent}}
237
+ {{enforcement}}
238
+
239
+ Decidí con \`apex_advisor_decide\` (requestID={{requestID}}). Si denegás, incluí un motivo.`
240
+
241
+ /**
242
+ * Pide una decisión al advisor del árbol.
243
+ * Devuelve null si: la sesión solicitante es la del advisor, no hay sesión
244
+ * advisor disponible, o se agota el timeout.
245
+ */
246
+ export async function requestAdvisorDecision(
247
+ ctx: Plugin.Context,
248
+ input: AdvisorRequest,
249
+ ): Promise<AdvisorDecision | null> {
250
+ if (isAdvisorSession(input.sessionID)) return null
251
+
252
+ const rootID = await resolveRootSessionID(ctx, input.sessionID)
253
+ const advisorSessionID = await getOrCreateAdvisorSession(ctx, rootID, input.location)
254
+
255
+ // requestID impredecible: la tool de decisión es visible para todos los
256
+ // agentes del servidor, así que el identificador no debe ser adivinable
257
+ // (un requestID predecible permitiría a otro agente resolver decisiones ajenas).
258
+ const requestID = `req_${randomUUID()}`
259
+
260
+ const decisionPromise = new Promise<AdvisorDecision>((resolve) => {
261
+ pending.set(requestID, resolve)
262
+ })
263
+
264
+ const text = renderAdvisorRequest(input.template, input, requestID)
265
+
266
+ try {
267
+ // Enviar la petición al advisor (steer: se incorpora al turno en curso;
268
+ // resume: despierta la sesión si está ociosa).
269
+ await Effect.runPromise(
270
+ ctx.session.prompt({
271
+ sessionID: advisorSessionID as never,
272
+ text,
273
+ delivery: "steer",
274
+ resume: true,
275
+ } as never),
276
+ )
277
+ } catch (error) {
278
+ pending.delete(requestID)
279
+ console.warn(`[apex.advisor] no se pudo enviar la petición al advisor: ${String(error)}`)
280
+ return null
281
+ }
282
+
283
+ // Esperar la decisión con timeout (sin bloquear indefinidamente la tool).
284
+ const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), input.timeoutMs))
285
+ const decision = await Promise.race([decisionPromise, timeout])
286
+
287
+ if (decision === null) {
288
+ pending.delete(requestID)
289
+ console.warn(`[apex.advisor] timeout esperando decisión para ${input.action} (${input.timeoutMs}ms)`)
290
+ }
291
+ return decision
292
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Apex Advisor — la ÚNICA herramienta que expone el agente advisor.
3
+ *
4
+ * Contrato (el vocabulario es allow/deny, no "consejo"):
5
+ * - Aprobar la ejecución de una tool → decision: "allow"
6
+ * - Denegarla → decision: "deny" + reason (obligatorio)
7
+ *
8
+ * El aspecto decisorio/aconsejador NO lo elige el modelo: lo determina el
9
+ * llamante (config `advisor.decisive`) y se le comunica en la petición. La
10
+ * herramienta solo resuelve la decisión y devuelve qué se hará con ella.
11
+ */
12
+
13
+ import { Effect } from "effect"
14
+ import type { Scope } from "effect"
15
+ import type { Plugin } from "@opencode/plugin/effect"
16
+ import { ADVISOR_TOOL_NAME } from "./advisor-agent.js"
17
+ import { resolvePendingDecision } from "./advisor-session.js"
18
+
19
+ export interface AdvisorDecisionInput {
20
+ readonly requestID: string
21
+ readonly decision: "allow" | "deny"
22
+ readonly reason?: string
23
+ }
24
+
25
+ /** Registra la herramienta de decisión (solo visible para el agente advisor). */
26
+ export function registerAdvisorTool(
27
+ ctx: Plugin.Context,
28
+ ): Effect.Effect<void, never, Scope.Scope> {
29
+ return Effect.gen(function* () {
30
+ yield* ctx.tool.transform((editor) => {
31
+ editor.add({
32
+ name: ADVISOR_TOOL_NAME,
33
+ description:
34
+ 'Resuelve una solicitud de permiso: decision="allow" aprueba la ejecución de la herramienta; ' +
35
+ 'decision="deny" la deniega (reason obligatorio).',
36
+ input: {
37
+ type: "object",
38
+ properties: {
39
+ requestID: { type: "string", description: "Identificador de la solicitud recibida" },
40
+ decision: { type: "string", enum: ["allow", "deny"], description: "allow = aprobar, deny = denegar" },
41
+ reason: { type: "string", description: "Motivo breve (obligatorio cuando decision=deny)" },
42
+ },
43
+ required: ["requestID", "decision"],
44
+ additionalProperties: false,
45
+ },
46
+ output: {
47
+ type: "object",
48
+ properties: {
49
+ accepted: { type: "boolean", description: "true si la solicitud existía y quedó resuelta" },
50
+ decision: { type: "string", enum: ["allow", "deny"] },
51
+ },
52
+ required: ["accepted", "decision"],
53
+ },
54
+ execute: (rawInput: unknown) =>
55
+ Effect.promise(async () => {
56
+ const input = rawInput as AdvisorDecisionInput
57
+ // Validación estricta: un veredicto inválido se RECHAZA (nunca se
58
+ // asume "allow" por defecto — eso sería fail-open).
59
+ if (input.decision !== "allow" && input.decision !== "deny") {
60
+ throw new Error("decision debe ser \"allow\" o \"deny\"")
61
+ }
62
+ const decision = input.decision
63
+ const reason = typeof input.reason === "string" && input.reason.length > 0 ? input.reason : undefined
64
+
65
+ // Regla del contrato: deny exige motivo.
66
+ if (decision === "deny" && !reason) {
67
+ throw new Error("decision=deny requiere 'reason'")
68
+ }
69
+
70
+ const accepted = resolvePendingDecision(input.requestID, decision, reason)
71
+ return { output: { accepted, decision } }
72
+ }),
73
+ })
74
+ })
75
+ })
76
+ }
package/core/bus.ts ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Core bus module for opencode-apex.
3
+ * Provides an in-memory event buffer with optional persistence for inter-module communication.
4
+ */
5
+
6
+ import type { EventDomain } from "@opencode/plugin/promise/event"
7
+ import type { StorageDomain } from "@opencode/plugin/promise/storage"
8
+
9
+ /**
10
+ * Event envelope for the internal event bus.
11
+ */
12
+ export interface BusEvent<T = unknown> {
13
+ /** Unique event ID */
14
+ id: string
15
+ /** Event type/name (e.g., "profiles.changed", "redact.finding") */
16
+ type: string
17
+ /** Event payload */
18
+ payload: T
19
+ /** Timestamp of event creation */
20
+ timestamp: number
21
+ /** Source module that emitted the event */
22
+ source: string
23
+ /** Optional correlation ID for tracing */
24
+ correlationId?: string
25
+ }
26
+
27
+ /** Event handler type */
28
+ export type BusHandler<T = unknown> = (event: BusEvent<T>) => Promise<void> | void
29
+
30
+ /** Subscription handle for cleanup */
31
+ export interface BusSubscription {
32
+ /** Unsubscribe from events */
33
+ unsubscribe: () => void
34
+ }
35
+
36
+ /** Configuration for the event bus */
37
+ export interface BusConfig {
38
+ /** Máximo de eventos en el buffer en memoria */
39
+ maxBufferSize: number
40
+ /** Persistir eventos en storage */
41
+ persist: boolean
42
+ /** Prefijo de storage cuando persist=true */
43
+ storagePrefix: string
44
+ }
45
+
46
+ /** Default bus configuration */
47
+ const DEFAULT_CONFIG: BusConfig = {
48
+ maxBufferSize: 1000,
49
+ persist: false,
50
+ storagePrefix: "apex.bus.events.",
51
+ }
52
+
53
+ /** In-memory event buffer */
54
+ const eventBuffer: BusEvent[] = []
55
+
56
+ /** Event subscribers by type */
57
+ const subscribers: Map<string, Set<BusHandler>> = new Map()
58
+
59
+ /** Generate a unique event ID */
60
+ function generateEventId(): string {
61
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
62
+ }
63
+
64
+ /**
65
+ * Emit an event to all subscribers and buffer it.
66
+ */
67
+ export async function emit<T>(
68
+ type: string,
69
+ payload: T,
70
+ source: string,
71
+ options?: { correlationId?: string; persist?: boolean },
72
+ ): Promise<string> {
73
+ const event: BusEvent<T> = {
74
+ id: generateEventId(),
75
+ type,
76
+ payload,
77
+ timestamp: Date.now(),
78
+ source,
79
+ correlationId: options?.correlationId,
80
+ }
81
+
82
+ // Add to buffer
83
+ eventBuffer.push(event)
84
+ if (eventBuffer.length > DEFAULT_CONFIG.maxBufferSize) {
85
+ eventBuffer.shift()
86
+ }
87
+
88
+ // Notify subscribers
89
+ const handlers = subscribers.get(type)
90
+ if (handlers) {
91
+ await Promise.all(
92
+ Array.from(handlers).map((handler) =>
93
+ Promise.resolve(handler(event)).catch((err) => {
94
+ console.error(`[apex.bus] Handler error for ${type}:`, err)
95
+ }),
96
+ ),
97
+ )
98
+ }
99
+
100
+ // Also notify wildcard subscribers
101
+ const wildcardHandlers = subscribers.get("*")
102
+ if (wildcardHandlers) {
103
+ await Promise.all(
104
+ Array.from(wildcardHandlers).map((handler) =>
105
+ Promise.resolve(handler(event)).catch((err) => {
106
+ console.error(`[apex.bus] Wildcard handler error for ${type}:`, err)
107
+ }),
108
+ ),
109
+ )
110
+ }
111
+
112
+ return event.id
113
+ }
114
+
115
+ /**
116
+ * Subscribe to events of a specific type (or "*" for all).
117
+ */
118
+ export function subscribe<T = unknown>(
119
+ type: string,
120
+ handler: BusHandler<T>,
121
+ ): BusSubscription {
122
+ if (!subscribers.has(type)) {
123
+ subscribers.set(type, new Set())
124
+ }
125
+ subscribers.get(type)!.add(handler as BusHandler)
126
+
127
+ return {
128
+ unsubscribe: () => {
129
+ const set = subscribers.get(type)
130
+ if (set) {
131
+ set.delete(handler as BusHandler)
132
+ if (set.size === 0) {
133
+ subscribers.delete(type)
134
+ }
135
+ }
136
+ },
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Get recent events from buffer (optionally filtered by type).
142
+ */
143
+ export function getRecentEvents<T = unknown>(
144
+ type?: string,
145
+ limit = 100,
146
+ ): BusEvent<T>[] {
147
+ let events = eventBuffer
148
+ if (type) {
149
+ events = eventBuffer.filter((e) => e.type === type)
150
+ }
151
+ return events.slice(-limit) as BusEvent<T>[]
152
+ }
153
+
154
+ /**
155
+ * Clear the event buffer.
156
+ */
157
+ export function clearBuffer(): void {
158
+ eventBuffer.length = 0
159
+ }
160
+
161
+ /**
162
+ * Register bus module.
163
+ * Sets up event subscription bridge to OpenCode's event system.
164
+ * Returns cleanup function that clears subscriptions and buffer.
165
+ */
166
+ export async function register(
167
+ ctx: { event: EventDomain; storage: StorageDomain },
168
+ config: { enabled: boolean },
169
+ ): Promise<() => Promise<void>> {
170
+ if (!config.enabled) {
171
+ return async () => {}
172
+ }
173
+
174
+ // Bridge OpenCode events to internal bus (optional)
175
+ // This allows modules to react to OpenCode events via the bus
176
+ const controller = new AbortController()
177
+
178
+ // Subscribe to all OpenCode events and re-emit on internal bus
179
+ // (In practice, modules would subscribe directly to ctx.event)
180
+ // This is a stub for the bridge pattern
181
+ void (async () => {
182
+ for await (const ev of ctx.event.subscribe({ signal: controller.signal })) {
183
+ await emit(`opencode.${ev.type}`, ev, "opencode-bridge")
184
+ }
185
+ })().catch(() => undefined)
186
+
187
+ return async () => {
188
+ controller.abort()
189
+ subscribers.clear()
190
+ clearBuffer()
191
+ }
192
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Condition evaluation for opencode-apex.
3
+ * Dot-notation field matching used by the events module for subscription filters.
4
+ */
5
+
6
+ /** Condition - evaluates to true/false based on context. */
7
+ export interface RuleCondition {
8
+ /** Field path in context (e.g., "session.id", "tool.name") */
9
+ field: string
10
+ /** Operator: equals, contains, matches, gt, lt, in, notIn */
11
+ operator: "equals" | "contains" | "matches" | "gt" | "lt" | "in" | "notIn" | "exists" | "notExists"
12
+ /** Value to compare against */
13
+ value?: unknown
14
+ /** For regex matches */
15
+ pattern?: string
16
+ }
17
+
18
+ /** Evaluate a single condition against a context object. */
19
+ export function evaluateCondition(condition: RuleCondition, context: Record<string, unknown>): boolean {
20
+ // Get value from context using dot notation
21
+ const getValue = (obj: Record<string, unknown>, path: string): unknown => {
22
+ return path.split(".").reduce((acc: unknown, key: string) => {
23
+ return (acc as Record<string, unknown>)?.[key]
24
+ }, obj)
25
+ }
26
+
27
+ const contextValue = getValue(context, condition.field)
28
+
29
+ switch (condition.operator) {
30
+ case "exists":
31
+ return contextValue !== undefined && contextValue !== null
32
+ case "notExists":
33
+ return contextValue === undefined || contextValue === null
34
+ case "equals":
35
+ return contextValue === condition.value
36
+ case "contains":
37
+ if (typeof contextValue === "string" && typeof condition.value === "string") {
38
+ return contextValue.includes(condition.value)
39
+ }
40
+ if (Array.isArray(contextValue)) {
41
+ return contextValue.includes(condition.value)
42
+ }
43
+ return false
44
+ case "matches":
45
+ if (typeof contextValue === "string" && condition.pattern) {
46
+ return new RegExp(condition.pattern).test(contextValue)
47
+ }
48
+ return false
49
+ case "gt":
50
+ return (contextValue as number) > (condition.value as number)
51
+ case "lt":
52
+ return (contextValue as number) < (condition.value as number)
53
+ case "in":
54
+ if (Array.isArray(condition.value)) {
55
+ return condition.value.includes(contextValue)
56
+ }
57
+ return false
58
+ case "notIn":
59
+ if (Array.isArray(condition.value)) {
60
+ return !condition.value.includes(contextValue)
61
+ }
62
+ return true
63
+ default:
64
+ return false
65
+ }
66
+ }