@animalabs/agent-framework 0.8.0 → 0.10.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/src/agent.d.ts +11 -1
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +33 -3
- package/dist/src/agent.js.map +1 -1
- package/dist/src/framework.d.ts +184 -18
- package/dist/src/framework.d.ts.map +1 -1
- package/dist/src/framework.js +1323 -246
- package/dist/src/framework.js.map +1 -1
- package/dist/src/gate/event-gate.d.ts +73 -7
- package/dist/src/gate/event-gate.d.ts.map +1 -1
- package/dist/src/gate/event-gate.js +399 -22
- package/dist/src/gate/event-gate.js.map +1 -1
- package/dist/src/gate/types.d.ts +56 -0
- package/dist/src/gate/types.d.ts.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcpl/capability-grant.d.ts +115 -0
- package/dist/src/mcpl/capability-grant.d.ts.map +1 -0
- package/dist/src/mcpl/capability-grant.js +291 -0
- package/dist/src/mcpl/capability-grant.js.map +1 -0
- package/dist/src/mcpl/capability-mask.d.ts +51 -0
- package/dist/src/mcpl/capability-mask.d.ts.map +1 -0
- package/dist/src/mcpl/capability-mask.js +190 -0
- package/dist/src/mcpl/capability-mask.js.map +1 -0
- package/dist/src/mcpl/channel-registry.d.ts +3 -1
- package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
- package/dist/src/mcpl/channel-registry.js +163 -36
- package/dist/src/mcpl/channel-registry.js.map +1 -1
- package/dist/src/mcpl/checkpoint-manager.d.ts +8 -3
- package/dist/src/mcpl/checkpoint-manager.d.ts.map +1 -1
- package/dist/src/mcpl/checkpoint-manager.js +28 -8
- package/dist/src/mcpl/checkpoint-manager.js.map +1 -1
- package/dist/src/mcpl/errors.d.ts +6 -0
- package/dist/src/mcpl/errors.d.ts.map +1 -1
- package/dist/src/mcpl/errors.js +6 -0
- package/dist/src/mcpl/errors.js.map +1 -1
- package/dist/src/mcpl/feature-set-manager.d.ts +10 -1
- package/dist/src/mcpl/feature-set-manager.d.ts.map +1 -1
- package/dist/src/mcpl/feature-set-manager.js +45 -4
- package/dist/src/mcpl/feature-set-manager.js.map +1 -1
- package/dist/src/mcpl/hook-orchestrator.d.ts +10 -14
- package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
- package/dist/src/mcpl/hook-orchestrator.js +58 -67
- package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
- package/dist/src/mcpl/index.d.ts +1 -1
- package/dist/src/mcpl/index.d.ts.map +1 -1
- package/dist/src/mcpl/index.js.map +1 -1
- package/dist/src/mcpl/prose-grammar.d.ts +11 -0
- package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
- package/dist/src/mcpl/prose-grammar.js +21 -0
- package/dist/src/mcpl/prose-grammar.js.map +1 -1
- package/dist/src/mcpl/prose-stream-router.d.ts +11 -2
- package/dist/src/mcpl/prose-stream-router.d.ts.map +1 -1
- package/dist/src/mcpl/prose-stream-router.js +73 -13
- package/dist/src/mcpl/prose-stream-router.js.map +1 -1
- package/dist/src/mcpl/push-handler.d.ts.map +1 -1
- package/dist/src/mcpl/push-handler.js +20 -2
- package/dist/src/mcpl/push-handler.js.map +1 -1
- package/dist/src/mcpl/server-connection.d.ts +93 -9
- package/dist/src/mcpl/server-connection.d.ts.map +1 -1
- package/dist/src/mcpl/server-connection.js +231 -32
- package/dist/src/mcpl/server-connection.js.map +1 -1
- package/dist/src/mcpl/server-registry.d.ts.map +1 -1
- package/dist/src/mcpl/server-registry.js +4 -3
- package/dist/src/mcpl/server-registry.js.map +1 -1
- package/dist/src/mcpl/tags.d.ts +24 -0
- package/dist/src/mcpl/tags.d.ts.map +1 -0
- package/dist/src/mcpl/tags.js +52 -0
- package/dist/src/mcpl/tags.js.map +1 -0
- package/dist/src/mcpl/transport.d.ts.map +1 -1
- package/dist/src/mcpl/transport.js +10 -0
- package/dist/src/mcpl/transport.js.map +1 -1
- package/dist/src/mcpl/types.d.ts +159 -64
- package/dist/src/mcpl/types.d.ts.map +1 -1
- package/dist/src/mcpl/types.js +16 -2
- package/dist/src/mcpl/types.js.map +1 -1
- package/dist/src/modules/workspace/index.d.ts +23 -0
- package/dist/src/modules/workspace/index.d.ts.map +1 -1
- package/dist/src/modules/workspace/index.js +48 -0
- package/dist/src/modules/workspace/index.js.map +1 -1
- package/dist/src/modules/workspace/sync.d.ts +11 -2
- package/dist/src/modules/workspace/sync.d.ts.map +1 -1
- package/dist/src/modules/workspace/sync.js +18 -8
- package/dist/src/modules/workspace/sync.js.map +1 -1
- package/dist/src/refusal-reactions.d.ts +27 -0
- package/dist/src/refusal-reactions.d.ts.map +1 -0
- package/dist/src/refusal-reactions.js +35 -0
- package/dist/src/refusal-reactions.js.map +1 -0
- package/dist/src/tool-result-history.d.ts +20 -0
- package/dist/src/tool-result-history.d.ts.map +1 -1
- package/dist/src/tool-result-history.js +26 -5
- package/dist/src/tool-result-history.js.map +1 -1
- package/dist/src/types/agent.d.ts +39 -1
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/framework.d.ts +16 -0
- package/dist/src/types/framework.d.ts.map +1 -1
- package/dist/src/types/trace.d.ts +24 -0
- package/dist/src/types/trace.d.ts.map +1 -1
- package/dist/test/channel-registry-routing.test.js +38 -10
- package/dist/test/channel-registry-routing.test.js.map +1 -1
- package/dist/test/channel-registry-typing.test.js +10 -1
- package/dist/test/channel-registry-typing.test.js.map +1 -1
- package/dist/test/checkpoint-attribution.test.js +168 -8
- package/dist/test/checkpoint-attribution.test.js.map +1 -1
- package/dist/test/conversation-fork-injection-scoping.test.js +8 -3
- package/dist/test/conversation-fork-injection-scoping.test.js.map +1 -1
- package/dist/test/event-gate-passthrough.test.d.ts +15 -0
- package/dist/test/event-gate-passthrough.test.d.ts.map +1 -0
- package/dist/test/event-gate-passthrough.test.js +289 -0
- package/dist/test/event-gate-passthrough.test.js.map +1 -0
- package/dist/test/event-gate-selfwake.test.d.ts +15 -0
- package/dist/test/event-gate-selfwake.test.d.ts.map +1 -0
- package/dist/test/event-gate-selfwake.test.js +125 -0
- package/dist/test/event-gate-selfwake.test.js.map +1 -0
- package/dist/test/explicit-prose-routing.test.js +137 -7
- package/dist/test/explicit-prose-routing.test.js.map +1 -1
- package/dist/test/fixtures/awareness-barrier-mcpl-server.mjs +276 -0
- package/dist/test/fixtures/flaky-mcpl-server.mjs +41 -0
- package/dist/test/machine-close-provenance.test.js +6 -0
- package/dist/test/machine-close-provenance.test.js.map +1 -1
- package/dist/test/mcpl-awareness-barrier.test.js +10 -0
- package/dist/test/mcpl-awareness-barrier.test.js.map +1 -1
- package/dist/test/mcpl-capability-grant.test.d.ts +10 -0
- package/dist/test/mcpl-capability-grant.test.d.ts.map +1 -0
- package/dist/test/mcpl-capability-grant.test.js +109 -0
- package/dist/test/mcpl-capability-grant.test.js.map +1 -0
- package/dist/test/mcpl-capability-scoping.test.d.ts +2 -0
- package/dist/test/mcpl-capability-scoping.test.d.ts.map +1 -0
- package/dist/test/mcpl-capability-scoping.test.js +266 -0
- package/dist/test/mcpl-capability-scoping.test.js.map +1 -0
- package/dist/test/mcpl-gate-roundtrip.test.js +13 -0
- package/dist/test/mcpl-gate-roundtrip.test.js.map +1 -1
- package/dist/test/mcpl-list-status.test.d.ts +2 -0
- package/dist/test/mcpl-list-status.test.d.ts.map +1 -0
- package/dist/test/mcpl-list-status.test.js +78 -0
- package/dist/test/mcpl-list-status.test.js.map +1 -0
- package/dist/test/mcpl-manifest-changed.test.d.ts +2 -0
- package/dist/test/mcpl-manifest-changed.test.d.ts.map +1 -0
- package/dist/test/mcpl-manifest-changed.test.js +177 -0
- package/dist/test/mcpl-manifest-changed.test.js.map +1 -0
- package/dist/test/mcpl-reconnect-events.test.js +27 -2
- package/dist/test/mcpl-reconnect-events.test.js.map +1 -1
- package/dist/test/mcpl-reconnect-reregistration.test.js +53 -17
- package/dist/test/mcpl-reconnect-reregistration.test.js.map +1 -1
- package/dist/test/mcpl-request-timeout.test.js +1 -1
- package/dist/test/mcpl-request-timeout.test.js.map +1 -1
- package/dist/test/physical-window-restart.test.d.ts +14 -0
- package/dist/test/physical-window-restart.test.d.ts.map +1 -0
- package/dist/test/physical-window-restart.test.js +222 -0
- package/dist/test/physical-window-restart.test.js.map +1 -0
- package/dist/test/present-while-acting.test.js +199 -1
- package/dist/test/present-while-acting.test.js.map +1 -1
- package/dist/test/prose-stream-router.test.js +43 -0
- package/dist/test/prose-stream-router.test.js.map +1 -1
- package/dist/test/refusal-reaction-baseline.test.d.ts +2 -0
- package/dist/test/refusal-reaction-baseline.test.d.ts.map +1 -0
- package/dist/test/refusal-reaction-baseline.test.js +74 -0
- package/dist/test/refusal-reaction-baseline.test.js.map +1 -0
- package/dist/test/state-scaling-e2e.test.js +7 -1
- package/dist/test/state-scaling-e2e.test.js.map +1 -1
- package/dist/test/state-scaling.test.js +9 -1
- package/dist/test/state-scaling.test.js.map +1 -1
- package/dist/test/tool-result-spill.test.d.ts +13 -0
- package/dist/test/tool-result-spill.test.d.ts.map +1 -0
- package/dist/test/tool-result-spill.test.js +472 -0
- package/dist/test/tool-result-spill.test.js.map +1 -0
- package/dist/test/trunk-channel-routing.test.js +45 -0
- package/dist/test/trunk-channel-routing.test.js.map +1 -1
- package/dist/test/xml-round-persist.test.d.ts +19 -0
- package/dist/test/xml-round-persist.test.d.ts.map +1 -0
- package/dist/test/xml-round-persist.test.js +235 -0
- package/dist/test/xml-round-persist.test.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -4
- package/src/agent.ts +38 -4
- package/src/framework.ts +1488 -272
- package/src/gate/event-gate.ts +427 -24
- package/src/gate/types.ts +58 -0
- package/src/index.ts +1 -0
- package/src/mcpl/capability-grant.ts +319 -0
- package/src/mcpl/capability-mask.ts +228 -0
- package/src/mcpl/channel-registry.ts +167 -39
- package/src/mcpl/checkpoint-manager.ts +28 -8
- package/src/mcpl/errors.ts +7 -0
- package/src/mcpl/feature-set-manager.ts +50 -5
- package/src/mcpl/hook-orchestrator.ts +64 -86
- package/src/mcpl/index.ts +0 -2
- package/src/mcpl/prose-grammar.ts +21 -0
- package/src/mcpl/prose-stream-router.ts +65 -14
- package/src/mcpl/push-handler.ts +18 -2
- package/src/mcpl/server-connection.ts +262 -34
- package/src/mcpl/server-registry.ts +4 -3
- package/src/mcpl/tags.ts +50 -0
- package/src/mcpl/transport.ts +11 -0
- package/src/mcpl/types.ts +176 -78
- package/src/modules/workspace/index.ts +48 -0
- package/src/modules/workspace/sync.ts +30 -7
- package/src/refusal-reactions.ts +37 -0
- package/src/tool-result-history.ts +27 -5
- package/src/types/agent.ts +40 -1
- package/src/types/framework.ts +17 -0
- package/src/types/trace.ts +22 -0
|
@@ -238,12 +238,138 @@ function validatePolicy(raw) {
|
|
|
238
238
|
if (names.length > 0)
|
|
239
239
|
resets = names;
|
|
240
240
|
}
|
|
241
|
+
// Validate passthrough — only meaningful on the counting behaviors, where
|
|
242
|
+
// "matched but didn't fire" is a distinct outcome that can fall through.
|
|
243
|
+
// On always/defer/skip/debounce the flag would be a no-op at best and a
|
|
244
|
+
// misleading promise at worst, so reject it loudly instead of ignoring it.
|
|
245
|
+
let passthrough;
|
|
246
|
+
if (obj.passthrough !== undefined) {
|
|
247
|
+
if (typeof obj.passthrough !== 'boolean') {
|
|
248
|
+
throw new Error(`Policy "${obj.name}": passthrough must be a boolean`);
|
|
249
|
+
}
|
|
250
|
+
if (obj.passthrough) {
|
|
251
|
+
const counting = typeof behavior === 'object'
|
|
252
|
+
&& ('rate_limit' in behavior || 'passive_sample' in behavior);
|
|
253
|
+
if (!counting) {
|
|
254
|
+
throw new Error(`Policy "${obj.name}": passthrough is only valid with rate_limit or `
|
|
255
|
+
+ `passive_sample behaviors — for "${formatBehavior(behavior)}" there is `
|
|
256
|
+
+ 'no non-firing match to fall through on');
|
|
257
|
+
}
|
|
258
|
+
passthrough = true;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
241
261
|
const policy = { name: obj.name, match, behavior };
|
|
242
262
|
if (resets)
|
|
243
263
|
policy.resets = resets;
|
|
264
|
+
if (passthrough)
|
|
265
|
+
policy.passthrough = passthrough;
|
|
244
266
|
return policy;
|
|
245
267
|
}
|
|
246
268
|
// ---------------------------------------------------------------------------
|
|
269
|
+
// Shadow lint — prove (conservatively) when rule ordering makes a rule dead
|
|
270
|
+
// ---------------------------------------------------------------------------
|
|
271
|
+
/** Set-inclusion helper for exact-string lists. */
|
|
272
|
+
function subsetOf(a, b) {
|
|
273
|
+
return a.every((x) => b.includes(x));
|
|
274
|
+
}
|
|
275
|
+
/** A glob field on the EARLIER rule is at least as broad as the LATER rule's
|
|
276
|
+
* when it's absent, the universal "*", or literally identical. Anything
|
|
277
|
+
* cleverer (real glob subsumption) is out of conservative scope. */
|
|
278
|
+
function globAtLeastAsBroad(earlier, later) {
|
|
279
|
+
if (earlier === undefined || earlier === '*')
|
|
280
|
+
return true;
|
|
281
|
+
return earlier === later;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Event types for which `earlier` provably matches EVERY event that `later`
|
|
285
|
+
* would match — i.e. the types for which `later` is unreachable when
|
|
286
|
+
* `earlier` sits before it and consumes its matches. Returns null when
|
|
287
|
+
* subsumption can't be proven (which is not proof of safety — the lint is
|
|
288
|
+
* deliberately one-sided so every warning it emits is true).
|
|
289
|
+
*/
|
|
290
|
+
function subsumedEventTypes(earlier, later) {
|
|
291
|
+
const e = earlier.match;
|
|
292
|
+
const l = later.match;
|
|
293
|
+
// Scope: which of `later`'s event types does `earlier` cover?
|
|
294
|
+
let covered;
|
|
295
|
+
if (!e.scope || e.scope.length === 0) {
|
|
296
|
+
covered = l.scope && l.scope.length > 0 ? l.scope : 'all';
|
|
297
|
+
}
|
|
298
|
+
else if (!l.scope || l.scope.length === 0) {
|
|
299
|
+
// `later` matches all types; `earlier` only consumes its own scope, so
|
|
300
|
+
// the shadow is partial — exactly those types.
|
|
301
|
+
covered = e.scope;
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
const overlap = l.scope.filter((t) => e.scope.includes(t));
|
|
305
|
+
if (overlap.length === 0)
|
|
306
|
+
return null;
|
|
307
|
+
covered = overlap;
|
|
308
|
+
}
|
|
309
|
+
// Every remaining discriminator on `earlier` must be at least as broad as
|
|
310
|
+
// `later`'s, otherwise some `later` events slip past `earlier`.
|
|
311
|
+
if (!globAtLeastAsBroad(e.source, l.source))
|
|
312
|
+
return null;
|
|
313
|
+
if (!globAtLeastAsBroad(e.channel, l.channel))
|
|
314
|
+
return null;
|
|
315
|
+
if (!globAtLeastAsBroad(e.mount, l.mount))
|
|
316
|
+
return null;
|
|
317
|
+
if (!globAtLeastAsBroad(e.pathGlob, l.pathGlob))
|
|
318
|
+
return null;
|
|
319
|
+
if (e.filter) {
|
|
320
|
+
if (!l.filter || e.filter.type !== l.filter.type || e.filter.pattern !== l.filter.pattern) {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
// metadataTrue / tagsAny are OR-lists: earlier subsumes when later's list
|
|
325
|
+
// is a subset of earlier's (any event satisfying later then satisfies
|
|
326
|
+
// earlier too). tagsAll / tagsNone are AND/NOT constraints: earlier
|
|
327
|
+
// subsumes when its constraints are a subset of later's.
|
|
328
|
+
if (e.metadataTrue && e.metadataTrue.length > 0) {
|
|
329
|
+
if (!l.metadataTrue || !subsetOf(l.metadataTrue, e.metadataTrue))
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
if (e.tagsAny && e.tagsAny.length > 0) {
|
|
333
|
+
if (!l.tagsAny || !subsetOf(l.tagsAny, e.tagsAny))
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
if (e.tagsAll && !subsetOf(e.tagsAll, l.tagsAll ?? []))
|
|
337
|
+
return null;
|
|
338
|
+
if (e.tagsNone && !subsetOf(e.tagsNone, l.tagsNone ?? []))
|
|
339
|
+
return null;
|
|
340
|
+
return covered;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Find rules made unreachable by earlier, broader rules (first match wins).
|
|
344
|
+
* The 2026-08-08 Mythos incident is the canonical catch: a prepended
|
|
345
|
+
* `{scope:[mcpl:channel-incoming]}` sampler silently made the
|
|
346
|
+
* direct-address and mention rules dead for the whole incoming lane.
|
|
347
|
+
* `passthrough` observers shadow nothing — non-firing matches fall through.
|
|
348
|
+
*/
|
|
349
|
+
export function findShadowedPolicies(policies) {
|
|
350
|
+
const out = [];
|
|
351
|
+
for (let i = 0; i < policies.length; i++) {
|
|
352
|
+
const earlier = policies[i];
|
|
353
|
+
if (earlier.passthrough)
|
|
354
|
+
continue;
|
|
355
|
+
for (let j = i + 1; j < policies.length; j++) {
|
|
356
|
+
const covered = subsumedEventTypes(earlier, policies[j]);
|
|
357
|
+
if (covered) {
|
|
358
|
+
out.push({ earlier: earlier.name, later: policies[j].name, eventTypes: covered });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
/** Human-readable one-liner for a ShadowWarning, used in tool results,
|
|
365
|
+
* traces, and gate_status alike so the same hazard reads the same way
|
|
366
|
+
* everywhere. */
|
|
367
|
+
export function formatShadowWarning(w) {
|
|
368
|
+
const types = w.eventTypes === 'all' ? 'ALL event types' : w.eventTypes.join(', ');
|
|
369
|
+
return `rule "${w.earlier}" makes "${w.later}" unreachable for ${types} `
|
|
370
|
+
+ `(first match wins — every event "${w.later}" would match is consumed by "${w.earlier}" first)`;
|
|
371
|
+
}
|
|
372
|
+
// ---------------------------------------------------------------------------
|
|
247
373
|
// EventGate
|
|
248
374
|
// ---------------------------------------------------------------------------
|
|
249
375
|
export class EventGate {
|
|
@@ -271,6 +397,10 @@ export class EventGate {
|
|
|
271
397
|
inferenceBuffer = [];
|
|
272
398
|
// Per-policy stats
|
|
273
399
|
stats = new Map();
|
|
400
|
+
// Shadow-lint cache (see refreshShadowWarnings) — recomputed on every
|
|
401
|
+
// config change, fingerprinted so an unchanged hazard set doesn't re-trace.
|
|
402
|
+
shadowWarningsCache = [];
|
|
403
|
+
shadowWarningsFingerprint = '[]';
|
|
274
404
|
// Observability counters for events that didn't match any policy
|
|
275
405
|
totalEvaluations = 0;
|
|
276
406
|
defaultTriggered = 0;
|
|
@@ -286,6 +416,12 @@ export class EventGate {
|
|
|
286
416
|
sleepSuppressed = 0;
|
|
287
417
|
sleepTimer = null;
|
|
288
418
|
sleepAgent;
|
|
419
|
+
// Self-wake timers per agent (skip_reply's wake_in_seconds). Unlike sleep,
|
|
420
|
+
// a self-wake suppresses NOTHING — it means "if nothing else wakes me by
|
|
421
|
+
// then, wake me". Any turn start for the agent cancels its pending
|
|
422
|
+
// self-wake (an external wake supersedes it; the timer would otherwise
|
|
423
|
+
// land as a redundant empty wake right after the turn).
|
|
424
|
+
selfWakeTimers = new Map();
|
|
289
425
|
// Privileged users who may wake the agent through sleep. Hot-reloaded from
|
|
290
426
|
// privilegedUsersPath on change.
|
|
291
427
|
privilegedUsersPath;
|
|
@@ -354,6 +490,7 @@ export class EventGate {
|
|
|
354
490
|
// Load config
|
|
355
491
|
this.config = this.loadConfig() ?? opts.initialConfig ?? { ...DEFAULT_CONFIG };
|
|
356
492
|
this.compiledPolicies = this.compilePolicies(this.config);
|
|
493
|
+
this.refreshShadowWarnings('startup');
|
|
357
494
|
// Programmable gate: an optional agent-authored `gate.js` next to gate.json.
|
|
358
495
|
// Absent ⇒ inactive (zero overhead beyond a throttled stat check).
|
|
359
496
|
this.gateScript = new GateScript(join(dirname(this.configPath), 'gate.js'), opts.scriptTimeoutMs ?? 50, this.now);
|
|
@@ -464,6 +601,7 @@ export class EventGate {
|
|
|
464
601
|
this.config = newConfig;
|
|
465
602
|
this.compiledPolicies = this.compilePolicies(newConfig);
|
|
466
603
|
this.lastReloadTimestamp = now;
|
|
604
|
+
this.refreshShadowWarnings('reload');
|
|
467
605
|
this.emitTrace({
|
|
468
606
|
type: 'gate:config-reloaded',
|
|
469
607
|
configPath: this.configPath,
|
|
@@ -491,24 +629,42 @@ export class EventGate {
|
|
|
491
629
|
* without waiting for the throttled mtime reload.
|
|
492
630
|
*
|
|
493
631
|
* The freshest on-disk config is re-read first, so a concurrent operator edit
|
|
494
|
-
* isn't clobbered. A policy with the same `name` is replaced IN PLACE
|
|
495
|
-
* preserved);
|
|
496
|
-
* —
|
|
497
|
-
*
|
|
632
|
+
* isn't clobbered. A policy with the same `name` is replaced IN PLACE when no
|
|
633
|
+
* `position` is given (order preserved); WITH a `position` it is moved there
|
|
634
|
+
* — so re-issuing a rule is also how you reposition it. New policies append
|
|
635
|
+
* by default; `'prepend'` puts one at the very front (ahead of EVERYTHING,
|
|
636
|
+
* including addressed-message wake rules — see the shadow lint), and the
|
|
637
|
+
* anchored forms `{before: name}` / `{after: name}` insert relative to an
|
|
638
|
+
* existing rule, which is almost always the safer way to order a sampler
|
|
639
|
+
* or debounce against a specific catch-all.
|
|
498
640
|
*/
|
|
499
641
|
addPolicy(rawPolicy, options) {
|
|
500
642
|
const policy = validatePolicy(rawPolicy);
|
|
501
643
|
const current = this.loadConfig() ?? this.config;
|
|
502
644
|
const policies = [...current.policies];
|
|
503
645
|
const idx = policies.findIndex((p) => p.name === policy.name);
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
else if (options?.position === 'prepend') {
|
|
508
|
-
policies.unshift(policy);
|
|
646
|
+
const position = options?.position;
|
|
647
|
+
if (idx >= 0 && position === undefined) {
|
|
648
|
+
policies[idx] = policy; // replace in place, order preserved
|
|
509
649
|
}
|
|
510
650
|
else {
|
|
511
|
-
|
|
651
|
+
if (idx >= 0)
|
|
652
|
+
policies.splice(idx, 1); // repositioning a known rule
|
|
653
|
+
if (position === 'prepend') {
|
|
654
|
+
policies.unshift(policy);
|
|
655
|
+
}
|
|
656
|
+
else if (position !== undefined && typeof position === 'object') {
|
|
657
|
+
const anchorName = 'before' in position ? position.before : position.after;
|
|
658
|
+
const anchorIdx = policies.findIndex((p) => p.name === anchorName);
|
|
659
|
+
if (anchorIdx < 0) {
|
|
660
|
+
throw new Error(`addPolicy: no policy named "${anchorName}" to anchor on — `
|
|
661
|
+
+ `have: [${policies.map((p) => p.name).join(', ')}]`);
|
|
662
|
+
}
|
|
663
|
+
policies.splice('before' in position ? anchorIdx : anchorIdx + 1, 0, policy);
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
policies.push(policy);
|
|
667
|
+
}
|
|
512
668
|
}
|
|
513
669
|
this.writeConfig({ ...current, policies });
|
|
514
670
|
this.emitTrace({
|
|
@@ -564,6 +720,7 @@ export class EventGate {
|
|
|
564
720
|
writeFileSync(this.configPath, JSON.stringify(config, null, 2) + '\n');
|
|
565
721
|
this.config = config;
|
|
566
722
|
this.compiledPolicies = this.compilePolicies(config);
|
|
723
|
+
this.refreshShadowWarnings('policy-mutation');
|
|
567
724
|
this.configSource = 'file';
|
|
568
725
|
this.configErrors = [];
|
|
569
726
|
this.lastReloadTimestamp = Date.now();
|
|
@@ -575,16 +732,9 @@ export class EventGate {
|
|
|
575
732
|
}
|
|
576
733
|
}
|
|
577
734
|
// =========================================================================
|
|
578
|
-
// Policy matching — first match wins
|
|
735
|
+
// Policy matching — first match wins (passthrough observers excepted; the
|
|
736
|
+
// match/decide loop lives inline in evaluate() and probe())
|
|
579
737
|
// =========================================================================
|
|
580
|
-
matchPolicy(info) {
|
|
581
|
-
for (const compiled of this.compiledPolicies) {
|
|
582
|
-
if (this.compiledMatches(compiled, info)) {
|
|
583
|
-
return compiled.policy;
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
return null;
|
|
587
|
-
}
|
|
588
738
|
compiledMatches(compiled, info) {
|
|
589
739
|
const match = compiled.policy.match;
|
|
590
740
|
// Scope check
|
|
@@ -688,11 +838,33 @@ export class EventGate {
|
|
|
688
838
|
// Programmable gate (gate.js) takes precedence when present and returns a
|
|
689
839
|
// behavior; null/undefined (inactive, error, or a deliberate pass) falls
|
|
690
840
|
// through to the declarative gate.json policies below.
|
|
841
|
+
//
|
|
842
|
+
// Declarative policies: first match wins — EXCEPT `passthrough` observers,
|
|
843
|
+
// which consume the event only when their counting behavior actually
|
|
844
|
+
// fires. A passthrough policy that matched-but-didn't-fire records its
|
|
845
|
+
// count and evaluation continues, so a density sampler placed early can
|
|
846
|
+
// no longer swallow the addressed-message rules behind it.
|
|
691
847
|
const scripted = this.gateScript.evaluate(info);
|
|
692
|
-
|
|
693
|
-
const
|
|
848
|
+
let decision = null;
|
|
849
|
+
const observed = [];
|
|
850
|
+
if (scripted != null) {
|
|
851
|
+
decision = this.computeDecision({ name: 'gate.js', match: {}, behavior: scripted }, info);
|
|
852
|
+
}
|
|
853
|
+
else {
|
|
854
|
+
for (const compiled of this.compiledPolicies) {
|
|
855
|
+
if (!this.compiledMatches(compiled, info))
|
|
856
|
+
continue;
|
|
857
|
+
const candidate = this.computeDecision(compiled.policy, info);
|
|
858
|
+
if (candidate.trigger || !compiled.policy.passthrough) {
|
|
859
|
+
decision = candidate;
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
observed.push(compiled.policy.name); // counted, didn't fire, fell through
|
|
863
|
+
}
|
|
864
|
+
}
|
|
694
865
|
this.totalEvaluations++;
|
|
695
|
-
if (!
|
|
866
|
+
if (!decision) {
|
|
867
|
+
decision = this.computeDecision(null, info);
|
|
696
868
|
const bucket = this.defaultByEventType.get(info.eventType)
|
|
697
869
|
?? { triggered: 0, skipped: 0 };
|
|
698
870
|
if (decision.trigger) {
|
|
@@ -705,6 +877,8 @@ export class EventGate {
|
|
|
705
877
|
}
|
|
706
878
|
this.defaultByEventType.set(info.eventType, bucket);
|
|
707
879
|
}
|
|
880
|
+
if (observed.length > 0)
|
|
881
|
+
decision.observed = observed;
|
|
708
882
|
this.emitTrace({
|
|
709
883
|
type: 'gate:decision',
|
|
710
884
|
eventType: info.eventType,
|
|
@@ -713,6 +887,7 @@ export class EventGate {
|
|
|
713
887
|
matchedPolicy: decision.policyName,
|
|
714
888
|
trigger: decision.trigger,
|
|
715
889
|
behavior: formatBehavior(decision.behavior),
|
|
890
|
+
...(observed.length > 0 ? { observed } : {}),
|
|
716
891
|
timestamp: this.now(),
|
|
717
892
|
});
|
|
718
893
|
return decision;
|
|
@@ -860,6 +1035,147 @@ export class EventGate {
|
|
|
860
1035
|
this.passiveSampleFires.delete(name);
|
|
861
1036
|
}
|
|
862
1037
|
// =========================================================================
|
|
1038
|
+
// Dry-run probes — side-effect-free "what would this event do right now"
|
|
1039
|
+
// =========================================================================
|
|
1040
|
+
/**
|
|
1041
|
+
* Non-mutating twin of the behavior decision: would this policy trigger for
|
|
1042
|
+
* this event, given CURRENT counter/bucket state? Reads state, never writes
|
|
1043
|
+
* it — no stats, no traces, no counter increments, no debounce batching.
|
|
1044
|
+
*/
|
|
1045
|
+
wouldTrigger(policy, info) {
|
|
1046
|
+
const b = policy.behavior;
|
|
1047
|
+
if (b === 'always')
|
|
1048
|
+
return true;
|
|
1049
|
+
if (b === 'defer' || b === 'skip')
|
|
1050
|
+
return false;
|
|
1051
|
+
if (typeof b === 'object') {
|
|
1052
|
+
if ('debounce' in b)
|
|
1053
|
+
return false; // batches; never triggers inline
|
|
1054
|
+
if ('rate_limit' in b) {
|
|
1055
|
+
const cfg = b.rate_limit;
|
|
1056
|
+
const key = this.resolveKey(info.metadata, cfg.keyBy);
|
|
1057
|
+
const bucket = this.rateLimitBuckets.get(policy.name)?.get(key);
|
|
1058
|
+
if (!bucket)
|
|
1059
|
+
return true; // fresh bucket starts full
|
|
1060
|
+
let tokens = bucket.tokens;
|
|
1061
|
+
if (tokens < cfg.tokens) {
|
|
1062
|
+
const elapsed = Math.max(0, this.now() - bucket.lastRefill);
|
|
1063
|
+
tokens = Math.min(cfg.tokens, tokens + Math.floor(elapsed / cfg.refillIntervalMs));
|
|
1064
|
+
}
|
|
1065
|
+
return tokens > 0;
|
|
1066
|
+
}
|
|
1067
|
+
if ('passive_sample' in b) {
|
|
1068
|
+
const cfg = b.passive_sample;
|
|
1069
|
+
const key = this.resolveKey(info.metadata, cfg.keyBy);
|
|
1070
|
+
const count = this.passiveSampleCounters.get(policy.name)?.get(key) ?? 0;
|
|
1071
|
+
return count + 1 >= cfg.every;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return false;
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Evaluate an event against the declarative policy table WITHOUT side
|
|
1078
|
+
* effects: no counters advance, no debounce batches form, no stats or
|
|
1079
|
+
* traces are recorded, and sleep suppression is ignored (a probe asks
|
|
1080
|
+
* about the table, not the moment). gate.js is not consulted — a script
|
|
1081
|
+
* may be stateful, and a probe must never perturb state.
|
|
1082
|
+
*/
|
|
1083
|
+
probe(info) {
|
|
1084
|
+
for (const compiled of this.compiledPolicies) {
|
|
1085
|
+
if (!this.compiledMatches(compiled, info))
|
|
1086
|
+
continue;
|
|
1087
|
+
const trigger = this.wouldTrigger(compiled.policy, info);
|
|
1088
|
+
if (trigger || !compiled.policy.passthrough) {
|
|
1089
|
+
return { trigger, policyName: compiled.policy.name, behavior: compiled.policy.behavior };
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
const trigger = (this.config.default ?? 'always') === 'always';
|
|
1093
|
+
return { trigger, policyName: null, behavior: this.config.default ?? 'always' };
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Probe a canonical set of synthetic chat/heartbeat events and report which
|
|
1097
|
+
* rule wins each and whether it would wake. Backs the before/after table in
|
|
1098
|
+
* the wake_add_rule result — the point where a rule change's real semantics
|
|
1099
|
+
* must become legible (af#105; the Mythos stand-back-density incident would
|
|
1100
|
+
* have been visible as `dm: discord-direct-address → stand-back-density`).
|
|
1101
|
+
* Probes are representative shapes, not an exhaustive event space — rules
|
|
1102
|
+
* keyed on specific channels/mounts may not match any probe.
|
|
1103
|
+
*/
|
|
1104
|
+
probeTable() {
|
|
1105
|
+
const chat = (label, eventType, metadata, tags) => ({
|
|
1106
|
+
label,
|
|
1107
|
+
info: {
|
|
1108
|
+
content: `[probe] ${label}`,
|
|
1109
|
+
eventType,
|
|
1110
|
+
serverId: 'discord',
|
|
1111
|
+
channelId: '',
|
|
1112
|
+
metadata: { ...metadata, eventType },
|
|
1113
|
+
tags,
|
|
1114
|
+
},
|
|
1115
|
+
});
|
|
1116
|
+
const probes = [
|
|
1117
|
+
chat('dm (open channel)', 'mcpl:channel-incoming', { isDM: true, isMention: true }, ['chat:dm', 'chat:private', 'chat:addressed', 'chat:from-human']),
|
|
1118
|
+
chat('dm (closed channel)', 'mcpl:push-event', { isDM: true, isMention: true }, ['chat:dm', 'chat:private', 'chat:addressed', 'chat:from-human']),
|
|
1119
|
+
chat('explicit mention (open channel)', 'mcpl:channel-incoming', { isMention: true, isExplicitMention: true }, ['chat:mention', 'chat:addressed', 'chat:from-human']),
|
|
1120
|
+
chat('explicit mention (closed channel)', 'mcpl:push-event', { isMention: true, isExplicitMention: true }, ['chat:mention', 'chat:addressed', 'chat:from-human']),
|
|
1121
|
+
chat('reply to you', 'mcpl:channel-incoming', { isMention: true, isReplyToBot: true }, ['chat:reply', 'chat:addressed', 'chat:from-human']),
|
|
1122
|
+
chat('ambient (human)', 'mcpl:channel-incoming', {}, ['chat:ambient', 'chat:from-human']),
|
|
1123
|
+
chat('ambient (bot)', 'mcpl:channel-incoming', { isBot: true }, ['chat:ambient', 'chat:from-bot']),
|
|
1124
|
+
{
|
|
1125
|
+
label: 'heartbeat',
|
|
1126
|
+
info: {
|
|
1127
|
+
content: '[probe] heartbeat',
|
|
1128
|
+
eventType: 'mcpl:push-event',
|
|
1129
|
+
serverId: 'heartbeat',
|
|
1130
|
+
channelId: '',
|
|
1131
|
+
metadata: { source: 'heartbeat', eventType: 'mcpl:push-event' },
|
|
1132
|
+
},
|
|
1133
|
+
},
|
|
1134
|
+
];
|
|
1135
|
+
return probes.map(({ label, info }) => {
|
|
1136
|
+
const d = this.probe(info);
|
|
1137
|
+
return {
|
|
1138
|
+
probe: label,
|
|
1139
|
+
eventType: info.eventType,
|
|
1140
|
+
policy: d.policyName,
|
|
1141
|
+
behavior: d.policyName === null
|
|
1142
|
+
? `default:${formatBehavior(d.behavior)}`
|
|
1143
|
+
: formatBehavior(d.behavior),
|
|
1144
|
+
wouldWake: d.trigger,
|
|
1145
|
+
};
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
// =========================================================================
|
|
1149
|
+
// Shadow lint surface
|
|
1150
|
+
// =========================================================================
|
|
1151
|
+
/** Current shadow-lint findings for the live policy order. Fresh compute —
|
|
1152
|
+
* cheap (policy lists are tens of entries at most). */
|
|
1153
|
+
lintShadows() {
|
|
1154
|
+
return findShadowedPolicies(this.config.policies);
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* Recompute shadow warnings and, when the set changed and is non-empty,
|
|
1158
|
+
* emit a `gate:shadow-warnings` trace so the hazard lands in ops
|
|
1159
|
+
* observability at the moment the order changed — not at the next missed
|
|
1160
|
+
* DM. Called from writeConfig and reloadIfChanged.
|
|
1161
|
+
*/
|
|
1162
|
+
refreshShadowWarnings(reason) {
|
|
1163
|
+
const warnings = this.lintShadows();
|
|
1164
|
+
const fingerprint = JSON.stringify(warnings);
|
|
1165
|
+
if (fingerprint === this.shadowWarningsFingerprint)
|
|
1166
|
+
return;
|
|
1167
|
+
this.shadowWarningsFingerprint = fingerprint;
|
|
1168
|
+
this.shadowWarningsCache = warnings;
|
|
1169
|
+
if (warnings.length > 0) {
|
|
1170
|
+
this.emitTrace({
|
|
1171
|
+
type: 'gate:shadow-warnings',
|
|
1172
|
+
reason,
|
|
1173
|
+
warnings: warnings.map(formatShadowWarning),
|
|
1174
|
+
timestamp: this.now(),
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
// =========================================================================
|
|
863
1179
|
// shouldTriggerInference callback adapter
|
|
864
1180
|
// =========================================================================
|
|
865
1181
|
/**
|
|
@@ -978,6 +1294,14 @@ export class EventGate {
|
|
|
978
1294
|
// =========================================================================
|
|
979
1295
|
onInferenceStarted(agentName) {
|
|
980
1296
|
this.inferring.add(agentName);
|
|
1297
|
+
// A turn is starting — whatever caused it supersedes any pending
|
|
1298
|
+
// self-wake. (Arming happens MID-turn via skip_reply, i.e. after this
|
|
1299
|
+
// ran for the arming turn, so a fresh arm always survives its own turn.)
|
|
1300
|
+
const selfWake = this.selfWakeTimers.get(agentName);
|
|
1301
|
+
if (selfWake) {
|
|
1302
|
+
clearTimeout(selfWake);
|
|
1303
|
+
this.selfWakeTimers.delete(agentName);
|
|
1304
|
+
}
|
|
981
1305
|
}
|
|
982
1306
|
onInferenceEnded(agentName) {
|
|
983
1307
|
this.inferring.delete(agentName);
|
|
@@ -1041,6 +1365,54 @@ export class EventGate {
|
|
|
1041
1365
|
});
|
|
1042
1366
|
return { until: this.sleepUntil };
|
|
1043
1367
|
}
|
|
1368
|
+
// =========================================================================
|
|
1369
|
+
// Self-wake (skip_reply wake_in_seconds)
|
|
1370
|
+
// =========================================================================
|
|
1371
|
+
/**
|
|
1372
|
+
* Arm a one-shot self-wake for `agentName` in `seconds` (clamped to
|
|
1373
|
+
* [1, 3600]). Fires a normal inference request when it elapses — no
|
|
1374
|
+
* suppression window, unlike sleep. Re-arming replaces the pending timer.
|
|
1375
|
+
* Cancelled by the agent's next turn start (see onInferenceStarted):
|
|
1376
|
+
* the semantics are "if nothing else wakes me by then, wake me".
|
|
1377
|
+
*/
|
|
1378
|
+
armSelfWake(agentName, seconds, source = 'skip_reply') {
|
|
1379
|
+
const ms = Math.max(1_000, Math.min(3_600_000, Math.floor(seconds * 1000)));
|
|
1380
|
+
const prev = this.selfWakeTimers.get(agentName);
|
|
1381
|
+
if (prev)
|
|
1382
|
+
clearTimeout(prev);
|
|
1383
|
+
const timer = setTimeout(() => {
|
|
1384
|
+
this.selfWakeTimers.delete(agentName);
|
|
1385
|
+
this.emitTrace({
|
|
1386
|
+
type: 'gate:decision',
|
|
1387
|
+
eventType: 'selfwake:fired',
|
|
1388
|
+
matchedPolicy: 'self-wake',
|
|
1389
|
+
trigger: true,
|
|
1390
|
+
behavior: 'always',
|
|
1391
|
+
timestamp: this.now(),
|
|
1392
|
+
});
|
|
1393
|
+
// Compact in-window notice: without it the wake turn contains nothing
|
|
1394
|
+
// new, so the agent can't tell WHAT woke it (its own timer vs. a
|
|
1395
|
+
// heartbeat) or WHEN. One line, timestamped to the second. Added
|
|
1396
|
+
// before the inference request so it rides the wake turn (addMessage's
|
|
1397
|
+
// turn-alive guard defers it to that turn's start if needed).
|
|
1398
|
+
const nowIso = new Date(this.now()).toISOString().slice(0, 19) + 'Z';
|
|
1399
|
+
this.addMessageFn('user', [{
|
|
1400
|
+
type: 'text',
|
|
1401
|
+
text: `[self-wake] your ${source} timer (${Math.round(ms / 1000)}s) elapsed — now ${nowIso}`,
|
|
1402
|
+
}], { source: 'gate:self-wake' });
|
|
1403
|
+
this.requestInferenceFn(agentName, `self-scheduled wake (${source}, ${Math.round(ms / 1000)}s)`, 'self-wake');
|
|
1404
|
+
}, ms);
|
|
1405
|
+
this.selfWakeTimers.set(agentName, timer);
|
|
1406
|
+
this.emitTrace({
|
|
1407
|
+
type: 'gate:decision',
|
|
1408
|
+
eventType: 'selfwake:set',
|
|
1409
|
+
matchedPolicy: 'self-wake',
|
|
1410
|
+
trigger: false,
|
|
1411
|
+
behavior: 'skip',
|
|
1412
|
+
timestamp: this.now(),
|
|
1413
|
+
});
|
|
1414
|
+
return { inMs: ms };
|
|
1415
|
+
}
|
|
1044
1416
|
/** End sleep immediately. Returns true if the agent was asleep. */
|
|
1045
1417
|
clearSleep() {
|
|
1046
1418
|
const wasAsleep = this.sleepUntil > this.now();
|
|
@@ -1207,6 +1579,7 @@ export class EventGate {
|
|
|
1207
1579
|
script: this.gateScript.status(),
|
|
1208
1580
|
policies,
|
|
1209
1581
|
errors: [...this.configErrors],
|
|
1582
|
+
shadowWarnings: this.shadowWarningsCache.map(formatShadowWarning),
|
|
1210
1583
|
totalEvaluations: this.totalEvaluations,
|
|
1211
1584
|
defaultDecisions: {
|
|
1212
1585
|
triggered: this.defaultTriggered,
|
|
@@ -1224,6 +1597,10 @@ export class EventGate {
|
|
|
1224
1597
|
clearTimeout(state.timer);
|
|
1225
1598
|
}
|
|
1226
1599
|
this.debounceTimers.clear();
|
|
1600
|
+
for (const timer of this.selfWakeTimers.values()) {
|
|
1601
|
+
clearTimeout(timer);
|
|
1602
|
+
}
|
|
1603
|
+
this.selfWakeTimers.clear();
|
|
1227
1604
|
this.rateLimitBuckets.clear();
|
|
1228
1605
|
this.passiveSampleCounters.clear();
|
|
1229
1606
|
this.rateLimitDenied.clear();
|