@myclaw163/clawclaw-cli 0.8.25 → 0.8.27
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/docs/configuration.md +1 -1
- package/docs/custom-modules/README.md +7 -0
- package/docs/custom-modules/api-reference.md +43 -1
- package/docs/custom-modules/behavior.md +3 -0
- package/docs/custom-modules/examples/task-reminder.ts +17 -0
- package/docs/custom-modules/perception.md +7 -1
- package/docs/custom-modules/reminders.md +147 -0
- package/docs/custom-modules/skill.md +67 -0
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +25 -17
- package/skills/clawclaw/references/BEHAVIORS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +2 -0
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +3 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +43 -1
- package/skills/clawclaw/references/CUSTOM-MODULES.md +7 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +11 -5
- package/skills/clawclaw/references/CUSTOM-REMINDER-DEVELOPMENT.md +147 -0
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +67 -0
- package/skills/clawclaw/references/HUB.md +14 -0
- package/skills/clawclaw/references/TACTICS.md +17 -15
- package/src/cli.ts +2 -14
- package/src/commands/capability.ts +21 -8
- package/src/commands/hub.ts +5 -4
- package/src/commands/load.ts +16 -3
- package/src/lib/agent-workspace-skills.ts +24 -3
- package/src/lib/capability-cloud-sync.ts +11 -2
- package/src/lib/capability-load-diagnostics.ts +1 -1
- package/src/lib/command-error.ts +22 -0
- package/src/lib/hub-client.ts +26 -2
- package/src/lib/hub-errors.ts +60 -0
- package/src/lib/perception-config.ts +1 -1
- package/src/lib/skill-host.ts +26 -0
- package/src/runtime/clawclaw/owner.ts +3 -1
- package/src/runtime/clawclaw/plugins/assembly.ts +17 -2
- package/src/runtime/clawclaw/plugins/behavior-input-source.ts +10 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +137 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-rules.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +59 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-worker.ts +33 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +7 -3
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +17 -1
- package/src/runtime/clawclaw/reminder-manifest.ts +28 -0
- package/src/runtime/clawclaw/runtime.ts +3 -0
- package/src/runtime/clawclaw-event-catalog.ts +4 -1
- package/src/runtime/framework/events/event-repository.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +14 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +16 -0
- package/src/runtime/framework/events/types.ts +6 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
- package/src/runtime/framework/plugins/contracts.ts +3 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +19 -0
- package/src/runtime/framework/runtime.ts +1 -0
- package/src/sdk/perception-plugin/index.ts +2 -0
- package/src/sdk/perception-plugin/reminder-rules.ts +41 -0
- package/src/sdk/perception-plugin/reminder.ts +40 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
|
|
2
|
+
import type { EventDeliveryDecision } from '../../../framework/events/types.js';
|
|
3
|
+
import type { ReminderInput, ReminderResult, ReminderTopic } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
|
|
5
|
+
import { freshClawclawGameState } from '../../runtime-state.js';
|
|
6
|
+
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
7
|
+
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
8
|
+
import { deliveryClass, isReminderMode, REMINDER_CONTROLLED_TYPES, REMINDER_FACT_TYPES, REMINDER_TOPICS } from './reminder-rules.js';
|
|
9
|
+
import { ReminderRunner } from './reminder-runner.js';
|
|
10
|
+
import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
|
|
11
|
+
|
|
12
|
+
export const CLAWCLAW_REMINDER_PLUGIN_ID = 'clawclaw.derived-event.reminders';
|
|
13
|
+
export interface ReminderPluginOptions {
|
|
14
|
+
/** Already selected by the ordinary local/Hub perception loadout. No separate settings. */
|
|
15
|
+
sources?: readonly ResolvedClawclawPerceptionSource[];
|
|
16
|
+
}
|
|
17
|
+
interface Checkpoint {
|
|
18
|
+
gameId?: string;
|
|
19
|
+
previousTick?: number; previousConnectionId?: string;
|
|
20
|
+
states: Partial<Record<ReminderTopic, { provider: string; value: unknown }>>;
|
|
21
|
+
}
|
|
22
|
+
function empty(): Checkpoint { return { states: {} }; }
|
|
23
|
+
function coreTask(payload: Record<string, unknown>): boolean {
|
|
24
|
+
return !['task_state_changed', 'task_assigned'].includes(String(payload.reason));
|
|
25
|
+
}
|
|
26
|
+
export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string, any>> {
|
|
27
|
+
readonly kind = 'epoch' as const;
|
|
28
|
+
readonly id = CLAWCLAW_REMINDER_PLUGIN_ID;
|
|
29
|
+
readonly version = '1';
|
|
30
|
+
readonly after = ['clawclaw.derived-event'];
|
|
31
|
+
readonly consumes = { events: REMINDER_FACT_TYPES };
|
|
32
|
+
readonly produces = { events: [] } as const;
|
|
33
|
+
readonly controlsEventDelivery = REMINDER_CONTROLLED_TYPES;
|
|
34
|
+
readonly catchUp = 'strict_ordered' as const;
|
|
35
|
+
readonly timeoutMs = 3_000;
|
|
36
|
+
private checkpoint: Checkpoint = empty();
|
|
37
|
+
private readonly sources = new Map<ReminderTopic, ResolvedClawclawPerceptionSource[]>();
|
|
38
|
+
private readonly runners = new Map<ReminderTopic, ReminderRunner>();
|
|
39
|
+
private readonly failed = new Set<ReminderTopic>();
|
|
40
|
+
constructor(private readonly options: ReminderPluginOptions = {}) {
|
|
41
|
+
for (const source of options.sources ?? []) {
|
|
42
|
+
if (!source.reminder) continue;
|
|
43
|
+
const selected = this.sources.get(source.reminder.topic) ?? [];
|
|
44
|
+
selected.push(source); this.sources.set(source.reminder.topic, selected);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
|
|
48
|
+
this.checkpoint = empty(); this.failed.clear();
|
|
49
|
+
await Promise.all(REMINDER_TOPICS.map(async topic => {
|
|
50
|
+
const sources = this.sources.get(topic) ?? [];
|
|
51
|
+
if (!sources.length) return;
|
|
52
|
+
try {
|
|
53
|
+
if (sources.length !== 1) throw new Error(`perception_topic_conflict:${topic}:${sources.map(s => s.id).join(',')}`);
|
|
54
|
+
const runner = new ReminderRunner(sources[0]!);
|
|
55
|
+
this.runners.set(topic, runner);
|
|
56
|
+
await runner.start();
|
|
57
|
+
} catch (error) { this.markFailed(topic, context, error); await this.runners.get(topic)?.stop(); }
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
61
|
+
const checkpoint = context.checkpoint() as Checkpoint | undefined;
|
|
62
|
+
if (checkpoint?.states) this.checkpoint = structuredClone({
|
|
63
|
+
gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
|
|
64
|
+
previousConnectionId: checkpoint.previousConnectionId,
|
|
65
|
+
states: checkpoint.states.tasks ? { tasks: checkpoint.states.tasks } : {},
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(r => r.stop())); this.runners.clear(); }
|
|
69
|
+
localizedModuleDescriptors(locale: string) {
|
|
70
|
+
return [...this.sources.entries()].filter(([topic, sources]) => sources.length === 1
|
|
71
|
+
&& this.runners.has(topic) && !this.failed.has(topic)).map(([, [source]]) => (
|
|
72
|
+
resolveClawclawResourceMetadata({ ...source!.manifest, display: source!.display }, locale)
|
|
73
|
+
));
|
|
74
|
+
}
|
|
75
|
+
async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
|
|
76
|
+
const snapshot = freshClawclawGameState(input.frame.state);
|
|
77
|
+
const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
|
|
78
|
+
let next = structuredClone(this.checkpoint);
|
|
79
|
+
if (game && next.gameId !== game.game_id) next = { ...empty(), gameId: game.game_id };
|
|
80
|
+
const frame = new ObservationFrameProjector().project(input.frame);
|
|
81
|
+
if (frame) {
|
|
82
|
+
const delta = next.previousTick === undefined ? null : frame.tick - next.previousTick;
|
|
83
|
+
Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
|
|
84
|
+
&& next.previousConnectionId === input.epoch.connectionId });
|
|
85
|
+
next.previousTick = frame.tick;
|
|
86
|
+
next.previousConnectionId = input.epoch.connectionId;
|
|
87
|
+
} else if (!game) {
|
|
88
|
+
next.previousTick = undefined; next.previousConnectionId = undefined;
|
|
89
|
+
}
|
|
90
|
+
const facts = input.pendingEvents;
|
|
91
|
+
const optional = facts.filter(e => e.type === 'tasks_changed' && !coreTask(e.payload));
|
|
92
|
+
const decisions = new Map<string, EventDeliveryDecision>(optional.map(e => [e.eventId, { eventId: e.eventId, deliveryClass: 'internal_only' }]));
|
|
93
|
+
for (const fact of facts.filter(e => e.type === 'tasks_changed' && coreTask(e.payload))) {
|
|
94
|
+
decisions.set(fact.eventId, { eventId: fact.eventId, deliveryClass: 'monitor_and_events' });
|
|
95
|
+
}
|
|
96
|
+
for (const topic of REMINDER_TOPICS) {
|
|
97
|
+
const selected = this.sources.get(topic)?.[0];
|
|
98
|
+
if (!selected || this.failed.has(topic)) continue;
|
|
99
|
+
const previous = next.states[topic];
|
|
100
|
+
const moduleInput: ReminderInput = {
|
|
101
|
+
scope: input.epoch.scope, frame, gameState: game,
|
|
102
|
+
facts: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type,
|
|
103
|
+
occurredAt: e.occurredAt, producer: e.producer, payload: e.payload })),
|
|
104
|
+
config: selected.reminder!.config ?? {}, state: previous?.provider === selected.id ? previous.value : undefined,
|
|
105
|
+
nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
const result: ReminderResult = await this.runners.get(topic)!.update(moduleInput);
|
|
109
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)
|
|
110
|
+
|| Object.keys(result).some(k => !['state', 'deliveries'].includes(k))
|
|
111
|
+
|| (result.deliveries !== undefined && !Array.isArray(result.deliveries))
|
|
112
|
+
|| Buffer.byteLength(JSON.stringify(result)) > 1024 * 1024) throw new Error('Invalid reminder output.');
|
|
113
|
+
const accepted: EventDeliveryDecision[] = [];
|
|
114
|
+
const ids = new Set<string>();
|
|
115
|
+
for (const decision of result.deliveries ?? []) {
|
|
116
|
+
const fact = optional.find(e => e.eventId === decision.eventId);
|
|
117
|
+
if (!fact || !isReminderMode(decision.mode) || ids.has(decision.eventId)
|
|
118
|
+
|| fact.type !== 'tasks_changed') {
|
|
119
|
+
throw new Error('Reminder attempted to control an unauthorized fact.');
|
|
120
|
+
}
|
|
121
|
+
ids.add(decision.eventId);
|
|
122
|
+
accepted.push({ eventId: fact.eventId, deliveryClass: deliveryClass(decision.mode) });
|
|
123
|
+
}
|
|
124
|
+
for (const decision of accepted) decisions.set(decision.eventId, decision);
|
|
125
|
+
next.states[topic] = { provider: selected.id, value: structuredClone(result.state) };
|
|
126
|
+
} catch (error) { this.markFailed(topic, context, error); }
|
|
127
|
+
}
|
|
128
|
+
this.checkpoint = next;
|
|
129
|
+
return { outcome: 'processed', eventDeliveries: [...decisions.values()], checkpoint: next,
|
|
130
|
+
...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
|
|
131
|
+
}
|
|
132
|
+
private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
|
|
133
|
+
this.failed.add(topic);
|
|
134
|
+
context.diagnostic('reminder.module_failed', { topic, module_ids: this.sources.get(topic)?.map(s => s.id),
|
|
135
|
+
error: error instanceof Error ? error.message : String(error) }, 'error');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../../../../sdk/perception-plugin/reminder-rules.js';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import type { ClawclawReminderManifest, ReminderInput, ReminderResult } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
|
|
5
|
+
import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
|
|
6
|
+
|
|
7
|
+
/** One bounded persistent Worker; module instances themselves are stateless between calls. */
|
|
8
|
+
export class ReminderRunner {
|
|
9
|
+
private worker?: Worker;
|
|
10
|
+
private sequence = 0;
|
|
11
|
+
private pending?: { resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout>; id?: number };
|
|
12
|
+
private failure?: Error;
|
|
13
|
+
constructor(readonly source: ResolvedClawclawPerceptionSource) {
|
|
14
|
+
if (!source.reminder) throw new Error('Not a reminder perception source.');
|
|
15
|
+
}
|
|
16
|
+
async start(): Promise<{ manifest: ClawclawReminderManifest; config: Record<string, unknown> }> {
|
|
17
|
+
const loader = runtimeModuleThreadLoaderConfig();
|
|
18
|
+
const promise = this.wait(8_000);
|
|
19
|
+
this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
|
|
20
|
+
execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 },
|
|
21
|
+
workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.reminder,
|
|
22
|
+
runtimeModuleBootstrap: { hostUrl: new URL('./reminder-worker.ts', import.meta.url).href,
|
|
23
|
+
...loader, esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
|
|
24
|
+
});
|
|
25
|
+
this.worker.stdout?.on('data', () => {});
|
|
26
|
+
this.worker.stderr?.on('data', () => {});
|
|
27
|
+
this.worker.on('error', error => this.fail(error));
|
|
28
|
+
this.worker.on('exit', code => this.fail(new Error(`Reminder worker exited (${code}).`)));
|
|
29
|
+
this.worker.on('message', message => {
|
|
30
|
+
if (!this.pending || (message.id !== undefined && this.pending.id !== message.id)) return;
|
|
31
|
+
if (message.type === 'error') { this.fail(new Error(message.error)); return; }
|
|
32
|
+
clearTimeout(this.pending.timer);
|
|
33
|
+
this.pending.resolve(message.type === 'ready' ? message : message.result);
|
|
34
|
+
this.pending = undefined;
|
|
35
|
+
});
|
|
36
|
+
return promise;
|
|
37
|
+
}
|
|
38
|
+
async update(input: ReminderInput): Promise<ReminderResult> {
|
|
39
|
+
if (this.failure) throw this.failure;
|
|
40
|
+
if (!this.worker) throw new Error('Reminder worker not started.');
|
|
41
|
+
const id = ++this.sequence;
|
|
42
|
+
const promise = this.wait(500, id);
|
|
43
|
+
this.worker.postMessage({ id, input });
|
|
44
|
+
return promise;
|
|
45
|
+
}
|
|
46
|
+
async stop(): Promise<void> { await this.worker?.terminate(); this.worker = undefined; }
|
|
47
|
+
private wait(timeout: number, id?: number): Promise<any> {
|
|
48
|
+
if (this.pending) throw new Error('Concurrent reminder invocation.');
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
this.pending = { id, resolve, reject, timer: setTimeout(() => {
|
|
51
|
+
this.fail(new Error('Reminder worker timeout.')); void this.stop();
|
|
52
|
+
}, timeout) };
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
private fail(error: Error): void {
|
|
56
|
+
this.failure = error;
|
|
57
|
+
if (this.pending) { clearTimeout(this.pending.timer); this.pending.reject(error); this.pending = undefined; }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { ClawclawReminder, type ReminderInput } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
5
|
+
|
|
6
|
+
function freeze<T>(value: T): T {
|
|
7
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
8
|
+
for (const child of Object.values(value)) freeze(child);
|
|
9
|
+
Object.freeze(value);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const imported = await import(pathToFileURL(workerData.modulePath).href);
|
|
15
|
+
const Module = imported.default;
|
|
16
|
+
if (!(Module?.prototype instanceof ClawclawReminder)) throw new Error('Invalid reminder perception class.');
|
|
17
|
+
const manifest = normalizeReminderManifest(Module.manifest);
|
|
18
|
+
if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('perception_manifest_source_mismatch');
|
|
19
|
+
const config = manifest.config ?? {};
|
|
20
|
+
parentPort!.postMessage({ type: 'ready', manifest, config });
|
|
21
|
+
parentPort!.on('message', async ({ id, input }: { id: number; input: ReminderInput }) => {
|
|
22
|
+
try {
|
|
23
|
+
const result = await new Module().update(freeze({ ...input, config,
|
|
24
|
+
facts: input.facts.filter(fact => manifest.consumes.includes(fact.type)) }));
|
|
25
|
+
if (Buffer.byteLength(JSON.stringify(result) ?? '') > 1024 * 1024) throw new Error('Reminder output exceeds 1 MB.');
|
|
26
|
+
parentPort!.postMessage({ type: 'result', id, result });
|
|
27
|
+
} catch (error) {
|
|
28
|
+
parentPort!.postMessage({ type: 'error', id, error: error instanceof Error ? error.message : String(error) });
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
} catch (error) {
|
|
32
|
+
parentPort!.postMessage({ type: 'error', error: error instanceof Error ? error.message : String(error) });
|
|
33
|
+
}
|
|
@@ -243,7 +243,8 @@ export class AgentMailboxCoordinator {
|
|
|
243
243
|
maxEpochSeq: ready.epochSeq,
|
|
244
244
|
order: 'asc',
|
|
245
245
|
}, this.consumerId, ['details']).filter((row) => (
|
|
246
|
-
|
|
246
|
+
(options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
247
|
+
&& this.selectsEvent(row.event, ready.state.state)
|
|
247
248
|
));
|
|
248
249
|
if (pending.length === 0) {
|
|
249
250
|
const eventIsBeyondReadyBoundary = this.delayWindow?.sessionId === ready.scope.sessionId
|
|
@@ -301,7 +302,8 @@ export class AgentMailboxCoordinator {
|
|
|
301
302
|
maxEpochSeq: ready.epochSeq,
|
|
302
303
|
order: 'desc',
|
|
303
304
|
}, this.consumerId, ['details']).filter((row) => (
|
|
304
|
-
|
|
305
|
+
(options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
306
|
+
&& this.selectsEvent(row.event, ready.state.state)
|
|
305
307
|
));
|
|
306
308
|
if (candidates.length === 0) {
|
|
307
309
|
this.delayWindow = undefined;
|
|
@@ -437,7 +439,7 @@ export class AgentMailboxCoordinator {
|
|
|
437
439
|
observeEvents(events: readonly CanonicalEvent[]): void {
|
|
438
440
|
const first = events
|
|
439
441
|
.filter((event) => (
|
|
440
|
-
event.deliveryClass
|
|
442
|
+
event.deliveryClass === 'monitor_and_events'
|
|
441
443
|
&& this.selectsEvent(event, undefined)
|
|
442
444
|
))
|
|
443
445
|
.sort((left, right) => left.commitSeq - right.commitSeq)[0];
|
|
@@ -460,6 +462,7 @@ export class AgentMailboxCoordinator {
|
|
|
460
462
|
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
|
|
461
463
|
const pending = this.repository.listEvents({
|
|
462
464
|
sessionId: ready.scope.sessionId,
|
|
465
|
+
deliveryClasses: ['monitor_and_events'],
|
|
463
466
|
detailStates: ['pending', 'deferred'],
|
|
464
467
|
maxCommitSeq: ready.eventWatermark,
|
|
465
468
|
maxEpochSeq: ready.epochSeq,
|
|
@@ -486,6 +489,7 @@ export class AgentMailboxCoordinator {
|
|
|
486
489
|
event: CanonicalEvent,
|
|
487
490
|
state: Record<string, any> | null | undefined,
|
|
488
491
|
): boolean {
|
|
492
|
+
if (event.deliveryClass === 'events_only') return true;
|
|
489
493
|
if (this.delegatedMonitorConsumerId && event.deliveryClass !== 'internal_only' && event.wakeAgent === false) return true;
|
|
490
494
|
if (this.eventFilter(event, state)) return true;
|
|
491
495
|
if (!this.delegatedMonitorConsumerId) return false;
|
|
@@ -327,7 +327,7 @@ function createModuleSlots(
|
|
|
327
327
|
const source = sources.get(id);
|
|
328
328
|
if (!source) throw new Error(`Unknown perception module '${id}'.`);
|
|
329
329
|
return source;
|
|
330
|
-
});
|
|
330
|
+
}).filter(source => !source.reminder);
|
|
331
331
|
const reducerPool = selected.length > 0
|
|
332
332
|
? new PerceptionReducerThreadPool({
|
|
333
333
|
modules: selected.map((source) => loader.threadSpec(source)),
|
|
@@ -22,11 +22,14 @@ import type {
|
|
|
22
22
|
} from './contracts.js';
|
|
23
23
|
import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js';
|
|
24
24
|
import { literalPluginApiVersion } from '../plugin-api-version.js';
|
|
25
|
+
import { parseLiteralModuleManifest } from '../behavior-input-source.js';
|
|
26
|
+
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
27
|
+
import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
|
|
25
28
|
|
|
26
29
|
export const MAX_PERCEPTION_FILES = 512;
|
|
27
30
|
const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
28
31
|
const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/;
|
|
29
|
-
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
32
|
+
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
30
33
|
const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
|
|
31
34
|
|
|
32
35
|
export interface ResolvedClawclawPerceptionSource {
|
|
@@ -39,6 +42,8 @@ export interface ResolvedClawclawPerceptionSource {
|
|
|
39
42
|
readonly display?: Readonly<{ name: string; description: string }>;
|
|
40
43
|
readonly description: string;
|
|
41
44
|
readonly manifest: ClawclawPerceptionManifest;
|
|
45
|
+
/** Non-visual execution contract; manifest above is the common resource descriptor. */
|
|
46
|
+
readonly reminder?: ClawclawReminderManifest;
|
|
42
47
|
readonly sourcePath: string;
|
|
43
48
|
readonly sourceRoot: string;
|
|
44
49
|
}
|
|
@@ -343,6 +348,17 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
343
348
|
const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}');
|
|
344
349
|
if (!manifestBlock) return null;
|
|
345
350
|
|
|
351
|
+
if (classMatch[1] === 'ClawclawReminder') {
|
|
352
|
+
try {
|
|
353
|
+
const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
|
|
354
|
+
const { id, description, localizations } = reminder;
|
|
355
|
+
const name = reminder.name ?? id;
|
|
356
|
+
return { apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
|
|
357
|
+
manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations,
|
|
358
|
+
subjectScope: 'self_and_others', produces: [] } };
|
|
359
|
+
} catch { return null; }
|
|
360
|
+
}
|
|
361
|
+
|
|
346
362
|
const apiVersion = literalPluginApiVersion(manifestBlock) ?? null;
|
|
347
363
|
const id = literalProperty(manifestBlock, 'id')?.trim();
|
|
348
364
|
const name = literalProperty(manifestBlock, 'name')?.trim() ?? id;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { REMINDER_PLUGIN_API_VERSION, type ClawclawReminderManifest } from '../../sdk/perception-plugin/reminder.js';
|
|
2
|
+
import { REMINDER_FACT_TYPES } from '../../sdk/perception-plugin/reminder-rules.js';
|
|
3
|
+
import { hasValidClawclawResourceLocalizations } from '../../sdk/resource-metadata.js';
|
|
4
|
+
import { normalizeBehaviorInput, normalizeBehaviorInputFields } from './behavior-input-fields.js';
|
|
5
|
+
|
|
6
|
+
/** Used by both static Perception discovery and the isolated runtime loader. */
|
|
7
|
+
export function normalizeReminderManifest(value: unknown, requireCurrentVersion = true): ClawclawReminderManifest {
|
|
8
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid perception reminder manifest.');
|
|
9
|
+
const m = value as ClawclawReminderManifest;
|
|
10
|
+
if (m.kind !== 'reminder' || !Number.isInteger(m.apiVersion)
|
|
11
|
+
|| (requireCurrentVersion && m.apiVersion !== REMINDER_PLUGIN_API_VERSION)
|
|
12
|
+
|| typeof m.id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(m.id)
|
|
13
|
+
|| typeof m.description !== 'string' || !m.description.trim()
|
|
14
|
+
|| (m.name !== undefined && (typeof m.name !== 'string' || !m.name.trim()))
|
|
15
|
+
|| !hasValidClawclawResourceLocalizations(m.localizations)
|
|
16
|
+
|| m.topic !== 'tasks'
|
|
17
|
+
|| !Array.isArray(m.consumes) || new Set(m.consumes).size !== m.consumes.length
|
|
18
|
+
|| m.consumes.some(type => !(REMINDER_FACT_TYPES as readonly string[]).includes(type))
|
|
19
|
+
|| (m.config !== undefined && (!m.config || typeof m.config !== 'object' || Array.isArray(m.config)))
|
|
20
|
+
|| Object.keys(m).some(key => !['apiVersion', 'kind', 'id', 'name', 'description', 'localizations',
|
|
21
|
+
'topic', 'consumes', 'inputs', 'config'].includes(key))) throw new Error('Invalid perception reminder manifest.');
|
|
22
|
+
const inputs = m.inputs === undefined ? undefined : normalizeBehaviorInputFields(m.inputs);
|
|
23
|
+
const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
|
|
24
|
+
return { apiVersion: m.apiVersion, kind: 'reminder', id: m.id, description: m.description,
|
|
25
|
+
...(m.name === undefined ? {} : { name: m.name }),
|
|
26
|
+
...(m.localizations === undefined ? {} : { localizations: structuredClone(m.localizations) }),
|
|
27
|
+
topic: m.topic, consumes: [...m.consumes], ...(inputs === undefined ? {} : { inputs }), config };
|
|
28
|
+
}
|
|
@@ -46,6 +46,7 @@ export type ClawclawRuntimeOptions = Omit<
|
|
|
46
46
|
durableStateSnapshot?: AtomicJsonAgentStateSnapshotStore<Record<string, any>> | false;
|
|
47
47
|
/** Frozen delivery policy for visual Events produced by Perception. */
|
|
48
48
|
visualEventDelivery?: ClawclawVisualEventDelivery;
|
|
49
|
+
reminderDelivery?: boolean;
|
|
49
50
|
/** Visual Event types declared by the selected perception modules. */
|
|
50
51
|
visualEventTypes?: readonly string[];
|
|
51
52
|
/** Event types declared by enabled Intent and Strategy modules at startup. */
|
|
@@ -95,6 +96,7 @@ export function createClawclawRuntime(
|
|
|
95
96
|
stateFreshnessPolicy: configuredFreshness = {},
|
|
96
97
|
stateFreshnessPolicyResolver: configuredResolver,
|
|
97
98
|
visualEventDelivery,
|
|
99
|
+
reminderDelivery,
|
|
98
100
|
visualEventTypes,
|
|
99
101
|
behaviorEventTypes,
|
|
100
102
|
...runtimeOptions
|
|
@@ -143,6 +145,7 @@ export function createClawclawRuntime(
|
|
|
143
145
|
accountId: getRuntimeAccountId(profile),
|
|
144
146
|
eventCatalog: createClawclawEventCatalog({
|
|
145
147
|
visualEventDelivery,
|
|
148
|
+
reminderDelivery,
|
|
146
149
|
visualEventTypes,
|
|
147
150
|
behaviorEventTypes,
|
|
148
151
|
}),
|
|
@@ -30,6 +30,8 @@ export type ClawclawVisualEventDelivery = EventDeliveryClass
|
|
|
30
30
|
| Readonly<Partial<Record<string, EventDeliveryClass>>>;
|
|
31
31
|
|
|
32
32
|
export interface ClawclawEventCatalogOptions {
|
|
33
|
+
/** Task changes start hidden until their ordered reminder rule resolves delivery. */
|
|
34
|
+
reminderDelivery?: boolean;
|
|
33
35
|
/** Defaults to monitor_and_events so visual facts wake the default Agent surface. */
|
|
34
36
|
visualEventDelivery?: ClawclawVisualEventDelivery;
|
|
35
37
|
/** Additional visual Event types declared by selected user perception modules. */
|
|
@@ -267,7 +269,8 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
|
|
|
267
269
|
...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.map((type) => ({
|
|
268
270
|
type,
|
|
269
271
|
producer: 'local_synth' as const,
|
|
270
|
-
deliveryClass: '
|
|
272
|
+
deliveryClass: options.reminderDelivery && type === 'tasks_changed'
|
|
273
|
+
? 'internal_only' as const : 'monitor_and_events' as const,
|
|
271
274
|
})),
|
|
272
275
|
...CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES.map((type) => ({
|
|
273
276
|
type,
|
|
@@ -28,6 +28,7 @@ export interface EventRepository {
|
|
|
28
28
|
latestScope(account: EventAccountScope, options?: LatestEventScopeOptions): CurrentEventScope | null;
|
|
29
29
|
|
|
30
30
|
commitEvent(request: CommitEventRequest): CommitEventResult;
|
|
31
|
+
resolveEventDelivery(decision: import('./types.js').EventDeliveryDecision): void;
|
|
31
32
|
eventById(eventId: string): CanonicalEvent | null;
|
|
32
33
|
latestEventByType(sessionId: string, type: string, segmentId?: string): CanonicalEvent | null;
|
|
33
34
|
highWaterCommitSeq(sessionId: string, segmentId?: string): number;
|
|
@@ -292,6 +292,20 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
292
292
|
return segment ? { session: cloneRecord(session), segment: cloneRecord(segment) } : null;
|
|
293
293
|
}
|
|
294
294
|
|
|
295
|
+
resolveEventDelivery(decision: import('./types.js').EventDeliveryDecision): void {
|
|
296
|
+
const event = this.events.get(decision.eventId);
|
|
297
|
+
if (!event) throw new Error('Unknown delivery decision Event.');
|
|
298
|
+
if (event.deliveryClass === decision.deliveryClass) return;
|
|
299
|
+
const rows = [...this.deliveries.entries()].filter(([, row]) => row.eventId === event.eventId);
|
|
300
|
+
if (rows.some(([, row]) => row.monitorAttemptCount > 0 || row.monitorState === 'notified'
|
|
301
|
+
|| row.detailState === 'delivered')
|
|
302
|
+
|| [...this.mailboxItems.values()].some(row => row.eventId === event.eventId)) {
|
|
303
|
+
throw new Error('Cannot change delivery after admission.');
|
|
304
|
+
}
|
|
305
|
+
event.deliveryClass = decision.deliveryClass;
|
|
306
|
+
for (const [key, row] of rows) this.deliveries.set(key, this.initialDelivery(event, row.consumerId));
|
|
307
|
+
}
|
|
308
|
+
|
|
295
309
|
commitEvent(request: CommitEventRequest): CommitEventResult {
|
|
296
310
|
const draft = cloneRecord(request.event);
|
|
297
311
|
if (!this.sessions.has(draft.sessionId)) {
|
|
@@ -542,6 +542,22 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
542
542
|
return segmentRow ? { session, segment: segmentFromRow(segmentRow) } : null;
|
|
543
543
|
}
|
|
544
544
|
|
|
545
|
+
resolveEventDelivery(decision: import('./types.js').EventDeliveryDecision): void {
|
|
546
|
+
this.transaction(() => {
|
|
547
|
+
const event = this.eventById(decision.eventId);
|
|
548
|
+
if (!event) throw new Error('Unknown delivery decision Event.');
|
|
549
|
+
if (event.deliveryClass === decision.deliveryClass) return;
|
|
550
|
+
const delivered = this.db.prepare(`SELECT 1 FROM event_deliveries WHERE event_id = ?
|
|
551
|
+
AND (monitor_attempt_count > 0 OR monitor_state = 'notified' OR detail_state = 'delivered')`).get(event.eventId);
|
|
552
|
+
const admitted = this.db.prepare('SELECT 1 FROM mailbox_items WHERE event_id = ?').get(event.eventId);
|
|
553
|
+
if (delivered || admitted) throw new Error('Cannot change delivery after admission.');
|
|
554
|
+
const consumers = this.db.prepare('SELECT consumer_id FROM event_deliveries WHERE event_id = ?').all(event.eventId);
|
|
555
|
+
this.db.prepare('UPDATE events SET delivery_class = ? WHERE event_id = ?').run(decision.deliveryClass, event.eventId);
|
|
556
|
+
this.db.prepare('DELETE FROM event_deliveries WHERE event_id = ?').run(event.eventId);
|
|
557
|
+
for (const row of consumers) this.insertInitialDelivery({ ...event, deliveryClass: decision.deliveryClass }, String(row.consumer_id));
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
545
561
|
commitEvent(request: CommitEventRequest): CommitEventResult {
|
|
546
562
|
return this.transaction(() => {
|
|
547
563
|
const duplicateById = request.event.sourceEventId
|
|
@@ -7,6 +7,12 @@ export type EventDeliveryClass =
|
|
|
7
7
|
| 'events_only'
|
|
8
8
|
| 'internal_only';
|
|
9
9
|
|
|
10
|
+
/** Delivery metadata may be resolved before Ready; factual identity/payload never change. */
|
|
11
|
+
export interface EventDeliveryDecision {
|
|
12
|
+
eventId: string;
|
|
13
|
+
deliveryClass: EventDeliveryClass;
|
|
14
|
+
}
|
|
15
|
+
|
|
10
16
|
export type MonitorDeliveryState =
|
|
11
17
|
| 'not_applicable'
|
|
12
18
|
| 'pending'
|
|
@@ -272,6 +272,9 @@ class MemoryFirstEventRepository extends MirroredStore implements EventRepositor
|
|
|
272
272
|
currentScope(account?: EventAccountScope) { return this.memory.currentScope(account); }
|
|
273
273
|
latestScope(account: EventAccountScope, options?: LatestEventScopeOptions) { return this.memory.latestScope(account, options); }
|
|
274
274
|
commitEvent(value: CommitEventRequest) { const result = this.memory.commitEvent(value); this.persist('events', 'commitEvent', value); return result; }
|
|
275
|
+
resolveEventDelivery(value: import('../events/types.js').EventDeliveryDecision) {
|
|
276
|
+
this.memory.resolveEventDelivery(value); this.persist('events', 'resolveEventDelivery', value);
|
|
277
|
+
}
|
|
275
278
|
eventById(eventId: string) { return this.memory.eventById(eventId); }
|
|
276
279
|
latestEventByType(sessionId: string, type: string, segmentId?: string) { return this.memory.latestEventByType(sessionId, type, segmentId); }
|
|
277
280
|
highWaterCommitSeq(sessionId: string, segmentId?: string) { return this.memory.highWaterCommitSeq(sessionId, segmentId); }
|
|
@@ -128,6 +128,7 @@ export type RuntimeEpochPluginOutcome = 'processed' | 'noop' | 'failed' | 'coale
|
|
|
128
128
|
export type RuntimeDiagnosticSeverity = 'debug' | 'info' | 'warn' | 'error';
|
|
129
129
|
|
|
130
130
|
export interface RuntimeEpochPluginResult {
|
|
131
|
+
readonly eventDeliveries?: readonly import('../events/types.js').EventDeliveryDecision[];
|
|
131
132
|
readonly outcome: 'processed' | 'noop';
|
|
132
133
|
readonly reason?: string;
|
|
133
134
|
/**
|
|
@@ -184,6 +185,8 @@ export interface RuntimeEpochPluginInput<
|
|
|
184
185
|
|
|
185
186
|
export interface RuntimeEpochPlugin<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
|
|
186
187
|
extends RuntimePluginIdentity<'epoch'> {
|
|
188
|
+
/** Only these existing Event types may have their pre-Ready delivery metadata resolved. */
|
|
189
|
+
readonly controlsEventDelivery?: readonly string[];
|
|
187
190
|
readonly consumes?: {
|
|
188
191
|
readonly states?: readonly string[];
|
|
189
192
|
readonly events?: readonly string[];
|
|
@@ -62,6 +62,7 @@ export interface RuntimePluginSchedulerOptions<
|
|
|
62
62
|
types?: readonly string[];
|
|
63
63
|
}): CanonicalEvent[];
|
|
64
64
|
highWaterCommitSeq(scope: RuntimeScope): number;
|
|
65
|
+
resolveEventDelivery?(decision: import('../events/types.js').EventDeliveryDecision): void;
|
|
65
66
|
currentSegment?: RuntimeEpochPluginContext<TState>['currentSegment'];
|
|
66
67
|
capabilitiesFor?(
|
|
67
68
|
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
@@ -401,6 +402,7 @@ function validateComputationResult(
|
|
|
401
402
|
}
|
|
402
403
|
if (
|
|
403
404
|
result.states !== undefined
|
|
405
|
+
|| result.eventDeliveries !== undefined
|
|
404
406
|
|| result.events !== undefined
|
|
405
407
|
|| result.checkpoint !== undefined
|
|
406
408
|
|| result.consumeEventsThroughCommitSeq !== undefined
|
|
@@ -478,6 +480,7 @@ export class RuntimePluginScheduler<
|
|
|
478
480
|
private readonly stateHistory: StateFrameHistoryReader<TState>;
|
|
479
481
|
private readonly commitInputEvents: RuntimePluginSchedulerOptions<TState, TEvent>['commitInputEvents'];
|
|
480
482
|
private readonly publishEvent: RuntimePluginSchedulerOptions<TState, TEvent>['publishEvent'];
|
|
483
|
+
private readonly resolveEventDelivery: RuntimePluginSchedulerOptions<TState, TEvent>['resolveEventDelivery'];
|
|
481
484
|
private readonly listEvents: RuntimePluginSchedulerOptions<TState, TEvent>['listEvents'];
|
|
482
485
|
private readonly highWaterCommitSeq: RuntimePluginSchedulerOptions<TState, TEvent>['highWaterCommitSeq'];
|
|
483
486
|
private readonly currentSegment: RuntimeEpochPluginContext<TState>['currentSegment'];
|
|
@@ -517,6 +520,7 @@ export class RuntimePluginScheduler<
|
|
|
517
520
|
this.stateHistory = options.stateHistory;
|
|
518
521
|
this.commitInputEvents = options.commitInputEvents;
|
|
519
522
|
this.publishEvent = options.publishEvent;
|
|
523
|
+
this.resolveEventDelivery = options.resolveEventDelivery;
|
|
520
524
|
this.listEvents = options.listEvents;
|
|
521
525
|
this.highWaterCommitSeq = options.highWaterCommitSeq;
|
|
522
526
|
this.currentSegment = options.currentSegment ?? (() => ({ kind: 'unknown' }));
|
|
@@ -1222,6 +1226,21 @@ export class RuntimePluginScheduler<
|
|
|
1222
1226
|
topic: state.topic,
|
|
1223
1227
|
value: cloneCanonical(state.value),
|
|
1224
1228
|
}));
|
|
1229
|
+
const deliveryFacts = result.eventDeliveries?.length ? this.listEvents({
|
|
1230
|
+
scope: work.epoch.scope, afterCommitSeq: invocation.cursorBefore,
|
|
1231
|
+
maxCommitSeq: invocation.maxEventWatermark, maxEpochSeq: work.epoch.epochSeq,
|
|
1232
|
+
}) : [];
|
|
1233
|
+
for (const decision of result.eventDeliveries ?? []) {
|
|
1234
|
+
const fact = deliveryFacts.find(event => event.eventId === decision.eventId);
|
|
1235
|
+
if (!fact || !plugin.controlsEventDelivery?.includes(fact.type)
|
|
1236
|
+
|| !['monitor_and_events', 'events_only', 'internal_only'].includes(decision.deliveryClass)) {
|
|
1237
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} returned an unauthorized delivery decision.`);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
for (const decision of result.eventDeliveries ?? []) {
|
|
1241
|
+
if (!this.resolveEventDelivery) throw new Error('Event delivery decisions are unsupported.');
|
|
1242
|
+
this.resolveEventDelivery(decision);
|
|
1243
|
+
}
|
|
1225
1244
|
for (const [proposalIndex, proposal] of (result.events ?? []).entries()) {
|
|
1226
1245
|
await this.publishEvent(plugin.id, work.epoch, proposal, proposalIndex);
|
|
1227
1246
|
eventCount += 1;
|
|
@@ -466,6 +466,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
466
466
|
publishEvent: (pluginId, epoch, proposal, proposalIndex) => this.eventIngress.publish(
|
|
467
467
|
this.pluginEventInput(pluginId, epoch, proposal, proposalIndex),
|
|
468
468
|
),
|
|
469
|
+
resolveEventDelivery: (decision) => this.repository.resolveEventDelivery(decision),
|
|
469
470
|
highWaterCommitSeq: (scope) => this.repository.highWaterCommitSeq(
|
|
470
471
|
scope.sessionId,
|
|
471
472
|
),
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic } from './reminder.js';
|
|
2
|
+
|
|
3
|
+
export const REMINDER_FACT_TYPES = [
|
|
4
|
+
'ability.ready', 'ability.remaining_uses_changed', 'ability.exhausted', 'tasks_changed',
|
|
5
|
+
'task_started', 'task_progress', 'task_assigned', 'task_completed', 'task_interrupted', 'task_sabotaged',
|
|
6
|
+
'role_assigned', 'emergency_started', 'emergency_resolved', 'emergency_interrupted', 'meeting_briefing',
|
|
7
|
+
] as const;
|
|
8
|
+
// The four fixed countdown/ability events remain entirely CCL-owned.
|
|
9
|
+
export const REMINDER_CONTROLLED_TYPES = ['tasks_changed'] as const;
|
|
10
|
+
export const REMINDER_TOPICS: readonly ReminderTopic[] = ['tasks'];
|
|
11
|
+
export function deliveryClass(mode: ReminderMode) {
|
|
12
|
+
return mode === 'notify' ? 'monitor_and_events' : mode === 'query' ? 'events_only' : 'internal_only';
|
|
13
|
+
}
|
|
14
|
+
export function isReminderMode(value: unknown): value is ReminderMode {
|
|
15
|
+
return value === 'notify' || value === 'query' || value === 'off';
|
|
16
|
+
}
|
|
17
|
+
export function defaultConfig(topic: ReminderTopic): Record<string, unknown> {
|
|
18
|
+
if (topic !== 'tasks') throw new Error('Unsupported reminder topic; countdown and ability notifications are owned by CCL.');
|
|
19
|
+
return { started: 'off', added: 'notify', updated: 'notify' };
|
|
20
|
+
}
|
|
21
|
+
export function validateDefaultConfig(topic: ReminderTopic, input: unknown): Record<string, unknown> {
|
|
22
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Reminder config must be an object.');
|
|
23
|
+
const defaults = defaultConfig(topic);
|
|
24
|
+
for (const key of Object.keys(input)) if (!Object.hasOwn(defaults, key)) throw new Error('Unknown reminder option: ' + key);
|
|
25
|
+
const value = { ...defaults, ...input };
|
|
26
|
+
if (!Object.values(value).every(isReminderMode)) throw new Error('Reminder mode must be notify, query, or off.');
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
export function taskChangeMode(payload: Record<string, unknown>, config: Record<string, unknown>): ReminderMode {
|
|
30
|
+
const delta = Array.isArray(payload.delta) ? payload.delta as Record<string, unknown>[] : [];
|
|
31
|
+
const modes = delta.map(change => change.change === 'status_changed' && change.from_status === 'normal'
|
|
32
|
+
&& change.to_status === 'in_progress' ? config.started : change.change === 'added' ? config.added : config.updated);
|
|
33
|
+
return modes.includes('notify') ? 'notify' : modes.includes('query') ? 'query' : 'off';
|
|
34
|
+
}
|
|
35
|
+
export function defaultReminder(topic: ReminderTopic, input: ReminderInput): ReminderResult {
|
|
36
|
+
const config = validateDefaultConfig(topic, input.config);
|
|
37
|
+
return { deliveries: input.facts.filter(f => f.type === 'tasks_changed'
|
|
38
|
+
&& ['task_state_changed', 'task_assigned'].includes(String(f.payload.reason))).map(f => ({
|
|
39
|
+
eventId: f.eventId, mode: taskChangeMode(f.payload as Record<string, unknown>, config),
|
|
40
|
+
})) };
|
|
41
|
+
}
|