@myclaw163/clawclaw-cli 0.8.26 → 0.8.28

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.
Files changed (58) hide show
  1. package/docs/custom-modules/README.md +3 -0
  2. package/docs/custom-modules/api-reference.md +43 -1
  3. package/docs/custom-modules/behavior.md +3 -0
  4. package/docs/custom-modules/examples/task-reminder.ts +19 -0
  5. package/docs/custom-modules/perception.md +7 -1
  6. package/docs/custom-modules/reminders.md +143 -0
  7. package/docs/runtime/agent-notifications.md +2 -2
  8. package/docs/runtime/events-and-state.md +1 -1
  9. package/package.json +1 -1
  10. package/skills/clawclaw/SKILL.md +23 -18
  11. package/skills/clawclaw/references/BEHAVIORS.md +2 -2
  12. package/skills/clawclaw/references/CHANNELS.md +1 -1
  13. package/skills/clawclaw/references/COMMANDS.md +1 -1
  14. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +3 -0
  15. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +43 -1
  16. package/skills/clawclaw/references/CUSTOM-MODULES.md +3 -0
  17. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +11 -5
  18. package/skills/clawclaw/references/CUSTOM-REMINDER-DEVELOPMENT.md +143 -0
  19. package/skills/clawclaw/references/HUB.md +14 -0
  20. package/skills/clawclaw/references/STREAM.md +2 -2
  21. package/skills/clawclaw/references/TACTICS.md +17 -15
  22. package/src/cli.ts +2 -14
  23. package/src/commands/capability.ts +5 -2
  24. package/src/commands/hub.ts +5 -4
  25. package/src/commands/load.ts +13 -1
  26. package/src/lib/capability-cloud-sync.ts +11 -2
  27. package/src/lib/capability-load-diagnostics.ts +1 -1
  28. package/src/lib/command-error.ts +22 -0
  29. package/src/lib/hub-client.ts +26 -2
  30. package/src/lib/hub-errors.ts +60 -0
  31. package/src/lib/perception-config.ts +1 -1
  32. package/src/pipeline/event-format.ts +2 -0
  33. package/src/runtime/clawclaw/owner.ts +2 -1
  34. package/src/runtime/clawclaw/plugins/assembly.ts +17 -2
  35. package/src/runtime/clawclaw/plugins/behavior-input-source.ts +10 -0
  36. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +146 -0
  37. package/src/runtime/clawclaw/plugins/derived-event/reminder-rules.ts +1 -0
  38. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +59 -0
  39. package/src/runtime/clawclaw/plugins/derived-event/reminder-worker.ts +33 -0
  40. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +7 -3
  41. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +0 -3
  42. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  43. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +17 -1
  44. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -26
  45. package/src/runtime/clawclaw/plugins/source/task-change-tracker.ts +10 -10
  46. package/src/runtime/clawclaw/reminder-manifest.ts +28 -0
  47. package/src/runtime/clawclaw-event-catalog.ts +5 -4
  48. package/src/runtime/framework/events/event-repository.ts +1 -0
  49. package/src/runtime/framework/events/memory-event-repository.ts +14 -0
  50. package/src/runtime/framework/events/sqlite-event-repository.ts +16 -0
  51. package/src/runtime/framework/events/types.ts +6 -0
  52. package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
  53. package/src/runtime/framework/plugins/contracts.ts +3 -0
  54. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +19 -0
  55. package/src/runtime/framework/runtime.ts +1 -0
  56. package/src/sdk/perception-plugin/index.ts +2 -0
  57. package/src/sdk/perception-plugin/reminder-rules.ts +94 -0
  58. package/src/sdk/perception-plugin/reminder.ts +63 -0
@@ -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;
@@ -1537,32 +1537,8 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1537
1537
  selfName: this.profile.agentName,
1538
1538
  allowUntickedInitialRole: frame.meta.origin === 'update',
1539
1539
  });
1540
- let taskPayloadAttached = false;
1541
1540
  const backendEvents = this.sourceEvents(
1542
- frame.events,
1543
- frame.meta,
1544
- CLAWCLAW_GAME_WS_SOURCE.sourceId,
1545
- (event, sourceEventIndex) => {
1546
- if (
1547
- !taskUpdate.payload
1548
- || taskPayloadAttached
1549
- || sourceEventIndex !== taskUpdate.attachToEventIndex
1550
- ) return event;
1551
- taskPayloadAttached = true;
1552
- const clonedTaskPayload = structuredClone(taskUpdate.payload);
1553
- const { reason: _taskReason, ...taskPayloadWithoutReason } = clonedTaskPayload;
1554
- const taskPayload = event.payload.reason === undefined
1555
- ? clonedTaskPayload
1556
- : taskPayloadWithoutReason;
1557
- return {
1558
- ...event,
1559
- payload: {
1560
- ...event.payload,
1561
- ...taskPayload,
1562
- },
1563
- };
1564
- },
1565
- gameState,
1541
+ frame.events, frame.meta, CLAWCLAW_GAME_WS_SOURCE.sourceId, undefined, gameState,
1566
1542
  );
1567
1543
  const recoveryIdentity = `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:${frame.meta.connectionId}`;
1568
1544
  const recoveryEvents = frame.meta.origin === 'resume' || frame.meta.snapshotFallback
@@ -1590,7 +1566,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1590
1566
  `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1591
1567
  )]
1592
1568
  : []),
1593
- ...(taskUpdate.payload && !taskPayloadAttached
1569
+ ...(taskUpdate.payload
1594
1570
  ? [this.tasksChangedEvent(
1595
1571
  taskUpdate.payload,
1596
1572
  frame.meta.receivedAt,
@@ -13,11 +13,13 @@ export interface TaskSnapshot extends Record<string, unknown> {
13
13
  export interface TaskChangeDetail extends Record<string, unknown> {
14
14
  change: 'added' | 'removed' | 'status_changed' | 'updated';
15
15
  task: TaskSnapshot;
16
+ before?: TaskSnapshot;
16
17
  from_status?: string;
17
18
  to_status?: string;
18
19
  }
19
20
 
20
21
  export interface TasksChangedPayload extends Record<string, unknown> {
22
+ baseline: boolean;
21
23
  tick?: number;
22
24
  reason:
23
25
  | 'role_assigned'
@@ -38,7 +40,6 @@ export interface TaskProjectionUpdate {
38
40
  projection: TaskSnapshot[];
39
41
  initialized: boolean;
40
42
  payload: TasksChangedPayload | null;
41
- attachToEventIndex?: number;
42
43
  }
43
44
 
44
45
  function record(value: unknown): Record<string, any> | null {
@@ -121,6 +122,7 @@ function taskDelta(
121
122
  if (before.status !== task.status) {
122
123
  delta.push({
123
124
  change: 'status_changed',
125
+ before: structuredClone(before),
124
126
  task: structuredClone(task),
125
127
  ...(before.status === undefined ? {} : { from_status: before.status }),
126
128
  ...(task.status === undefined ? {} : { to_status: task.status }),
@@ -128,7 +130,7 @@ function taskDelta(
128
130
  continue;
129
131
  }
130
132
  if (!sameTask(before, task)) {
131
- delta.push({ change: 'updated', task: structuredClone(task) });
133
+ delta.push({ change: 'updated', task: structuredClone(task), before: structuredClone(before) });
132
134
  }
133
135
  }
134
136
  return delta;
@@ -166,7 +168,7 @@ function updateReason(
166
168
  selfSeat: number | undefined,
167
169
  currentTick: number | undefined,
168
170
  allowUntickedInitialRole: boolean,
169
- ): Pick<TasksChangedPayload, 'reason'> & Pick<TaskProjectionUpdate, 'attachToEventIndex'> {
171
+ ): Pick<TasksChangedPayload, 'reason'> {
170
172
  const roleIndex = findLastEventIndex(events, (event) => event.type === 'role_assigned');
171
173
  const roleTick = roleIndex >= 0 ? finiteNumber(events[roleIndex]?.tick) : undefined;
172
174
  const currentRole = roleIndex >= 0 && (
@@ -174,7 +176,7 @@ function updateReason(
174
176
  || (roleTick === undefined && allowUntickedInitialRole)
175
177
  );
176
178
  if (currentRole) {
177
- return { reason: 'role_assigned', attachToEventIndex: roleIndex };
179
+ return { reason: 'role_assigned' };
178
180
  }
179
181
  // A first snapshot may replay historical task Events. Its current list is
180
182
  // an initialization fact, not the after-state of any one historical Event.
@@ -196,7 +198,7 @@ function updateReason(
196
198
  const reason = visible.event.type === 'meeting_briefing'
197
199
  ? 'meeting_started'
198
200
  : visible.event.type as TasksChangedPayload['reason'];
199
- return { reason, attachToEventIndex: visible.index };
201
+ return { reason };
200
202
  }
201
203
  if (events.some((event) => (
202
204
  event.type === 'task_assigned' && actorMatches(event, selfName, selfSeat)
@@ -206,8 +208,8 @@ function updateReason(
206
208
 
207
209
  /**
208
210
  * Diff the authoritative task list carried by one complete GameSync State.
209
- * The resulting payload is attached to the factual backend Event when one is
210
- * Agent-visible; otherwise Source emits one local tasks_changed Event.
211
+ * Source emits a private tasks_changed input, separate from backend facts.
212
+ * Reminder scripts own Agent-facing task notifications.
211
213
  */
212
214
  export function nextTaskProjection(input: {
213
215
  previous: readonly TaskSnapshot[];
@@ -247,13 +249,11 @@ export function nextTaskProjection(input: {
247
249
  projection: current,
248
250
  initialized: true,
249
251
  payload: {
252
+ baseline: !input.initialized,
250
253
  ...(tick === undefined ? {} : { tick }),
251
254
  reason: reason.reason,
252
255
  delta,
253
256
  tasks: current.map((task) => structuredClone(task)),
254
257
  },
255
- ...(reason.attachToEventIndex === undefined
256
- ? {}
257
- : { attachToEventIndex: reason.attachToEventIndex }),
258
258
  };
259
259
  }
@@ -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
+ }
@@ -101,9 +101,6 @@ export const CLAWCLAW_BACKEND_AGENT_EVENT_TYPES = [
101
101
  'killed',
102
102
  'murder_witnessed',
103
103
  'warrior_shrimp_self_destruct',
104
- 'task_completed',
105
- 'task_interrupted',
106
- 'task_sabotaged',
107
104
  'body_dropped',
108
105
  'corpse_spotted',
109
106
  'octopus_time_start',
@@ -183,7 +180,7 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
183
180
  'behavior.cancelled',
184
181
  'behavior.replaced',
185
182
  'players_changed',
186
- 'tasks_changed',
183
+ 'reminder.task',
187
184
  'emergency_countdown_warning',
188
185
  'ability.ready',
189
186
  'ability.remaining_uses_changed',
@@ -192,6 +189,9 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
192
189
 
193
190
  /** Durable inputs used by projectors, but never sent directly to the Agent. */
194
191
  export const CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES = [
192
+ 'task_completed',
193
+ 'task_interrupted',
194
+ 'task_sabotaged',
195
195
  'enter_room',
196
196
  'move_start',
197
197
  'move_end',
@@ -211,6 +211,7 @@ export const CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES = [
211
211
  ] as const;
212
212
 
213
213
  export const CLAWCLAW_INTERNAL_LOCAL_EVENT_TYPES = [
214
+ 'tasks_changed',
214
215
  'meeting_state',
215
216
  'runtime_started',
216
217
  'runtime_stopped',
@@ -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
  ),
@@ -1,4 +1,6 @@
1
1
  export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
2
+ export * from './reminder.js';
3
+ export { defaultReminder as evaluateReminder } from './reminder-rules.js';
2
4
 
3
5
  export {
4
6
  hasValidClawclawResourceLocalizations,
@@ -0,0 +1,94 @@
1
+ import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic, ReminderFact, ReminderTaskChange, ReminderEvent } 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
+ export const REMINDER_EVENT_TYPES = ['reminder.task'] as const;
9
+ export const REMINDER_TOPICS: readonly ReminderTopic[] = ['tasks'];
10
+ export function isReminderMode(value: unknown): value is ReminderMode {
11
+ return value === 'wake' || value === 'silent' || value === 'state_only';
12
+ }
13
+ export function defaultConfig(topic: ReminderTopic): Record<string, ReminderMode> {
14
+ if (topic !== 'tasks') throw new Error('Unsupported reminder topic; countdown and ability notifications are owned by CCL.');
15
+ return { started: 'state_only', progress: 'state_only', added: 'wake', completed: 'wake',
16
+ interrupted: 'wake', sabotaged: 'wake', removed: 'wake', updated: 'silent' };
17
+ }
18
+ export function validateDefaultConfig(topic: ReminderTopic, input: unknown): Record<string, ReminderMode> {
19
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Reminder config must be an object.');
20
+ const defaults = defaultConfig(topic);
21
+ for (const key of Object.keys(input)) if (!Object.hasOwn(defaults, key)) throw new Error('Unknown reminder option: ' + key);
22
+ const value = { ...defaults, ...input };
23
+ if (!Object.values(value).every(isReminderMode)) throw new Error('Reminder mode must be wake, silent, or state_only.');
24
+ return value;
25
+ }
26
+ const kinds: Record<string, string> = { task_started: 'started', task_progress: 'progress', task_assigned: 'added',
27
+ task_completed: 'completed', task_interrupted: 'interrupted', task_sabotaged: 'sabotaged' };
28
+ const labels: Record<string, string> = { started: '开始任务', progress: '任务进度变化', added: '新增任务',
29
+ completed: '任务完成', interrupted: '任务中断', sabotaged: '破坏任务完成', removed: '任务不再出现在列表', updated: '任务信息变化' };
30
+ function record(value: unknown): Record<string, unknown> {
31
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
32
+ }
33
+ function ownFact(fact: ReminderFact, input: ReminderInput): boolean {
34
+ const actor = record(fact.payload.actor);
35
+ const seat = actor.seat ?? fact.payload.actor_seat;
36
+ const name = actor.name ?? fact.payload.actor_name;
37
+ const self = input.gameState?.you?.player;
38
+ if (seat !== undefined && self?.seat !== undefined) return seat === self.seat;
39
+ if (name !== undefined && self?.name !== undefined) return name === self.name;
40
+ return seat === undefined && name === undefined;
41
+ }
42
+ function matches(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
43
+ if (fact.epochId !== change.epochId || (fact.type.startsWith('task_') && !ownFact(fact, input))) return false;
44
+ const p = fact.payload;
45
+ if (p.task_id && change.task.task_id) return p.task_id === change.task.task_id;
46
+ const name = p.task_name;
47
+ if (!name || name !== change.task.name) return false;
48
+ if (p.room && change.task.room && p.room !== change.task.room) return false;
49
+ // Without IDs, only correlate an unambiguous task in this physical frame.
50
+ return input.taskChanges.filter(c => c.epochId === change.epochId && c.task.name === name
51
+ && (!p.room || !c.task.room || c.task.room === p.room)).length === 1;
52
+ }
53
+ function explained(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
54
+ if (!matches(fact, change, input)) return false;
55
+ if (change.change === 'added') return fact.type === 'task_assigned' || fact.type === 'emergency_started';
56
+ if (change.change === 'removed') return ['task_completed', 'task_sabotaged', 'emergency_resolved', 'emergency_interrupted'].includes(fact.type);
57
+ if (change.change === 'status_changed') {
58
+ if (change.to_status === 'completed') return ['task_completed', 'task_sabotaged'].includes(fact.type);
59
+ if (change.to_status === 'in_progress') return fact.type === 'task_started';
60
+ if (change.from_status === 'in_progress' && change.to_status === 'normal') return fact.type === 'task_interrupted';
61
+ }
62
+ return false;
63
+ }
64
+ /** Optional task policy: classify individual changes, never re-deliver the whole raw fact. */
65
+ export function defaultReminder(topic: ReminderTopic, input: ReminderInput): ReminderResult {
66
+ const config = validateDefaultConfig(topic, input.config);
67
+ const events: ReminderEvent[] = [];
68
+ if (input.boundary) return { events };
69
+ const emit = (kind: string, key: string, data: Record<string, unknown>, eventId: string) => {
70
+ const mode = config[kind];
71
+ if (mode === 'state_only') return;
72
+ const { tasks: _tasks, delta: _delta, newly_assigned_task: _assigned, ...detail } = data;
73
+ const name = String(detail.task_name ?? detail.name ?? '');
74
+ const actor = record(detail.actor);
75
+ const seat = actor.seat ?? detail.actor_seat;
76
+ const who = seat !== undefined && seat !== input.gameState?.you?.player?.seat ? `${seat}号玩家:` : '';
77
+ const room = detail.room ? `(${String(detail.room)})` : '';
78
+ events.push({ type: 'reminder.task', key, wakeAgent: mode === 'wake',
79
+ payload: { ...detail, kind, source_event_id: eventId, text: `${who}${labels[kind]}:${name}${room}。` } });
80
+ };
81
+ for (const fact of input.facts) {
82
+ const kind = kinds[fact.type];
83
+ if (kind) emit(kind, `fact:${fact.eventId}`, { ...fact.payload }, fact.eventId);
84
+ }
85
+ for (const change of input.taskChanges) {
86
+ if (change.baseline || input.facts.some(f => explained(f, change, input))) continue;
87
+ const kind = change.change === 'added' ? 'added' : change.change === 'removed' ? 'removed'
88
+ : change.change === 'status_changed' && change.to_status === 'in_progress' ? 'started'
89
+ : change.change === 'status_changed' && change.to_status === 'completed' ? 'completed' : 'updated';
90
+ emit(kind, change.key, { ...change.task, change: change.change,
91
+ from_status: change.from_status, to_status: change.to_status }, change.eventId);
92
+ }
93
+ return { events };
94
+ }
@@ -0,0 +1,63 @@
1
+ import type { GameEvent, GameState, ObservationFrame } from '../module-input/index.js';
2
+ import type { BehaviorInputFieldSpec } from '../behavior-plugin/index.js';
3
+
4
+ /** Reminder classes use the same public Perception API version and resource lifecycle. */
5
+ export const REMINDER_PLUGIN_API_VERSION = 2 as const;
6
+ export type ReminderTopic = 'tasks';
7
+ export type ReminderMode = 'wake' | 'silent' | 'state_only';
8
+ export interface ReminderFact extends GameEvent { readonly producer: 'backend_push' | 'local_synth' }
9
+ /** Structural task changes, not Agent notifications or inferred completion facts. */
10
+ export interface ReminderTaskChange {
11
+ readonly key: string;
12
+ readonly eventId: string;
13
+ readonly epochId?: number;
14
+ readonly change: 'added' | 'removed' | 'status_changed' | 'updated';
15
+ readonly task: Readonly<Record<string, unknown>>;
16
+ readonly before?: Readonly<Record<string, unknown>>;
17
+ readonly from_status?: string;
18
+ readonly to_status?: string;
19
+ readonly baseline: boolean;
20
+ }
21
+ export interface ReminderInput {
22
+ readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
23
+ readonly frame: Readonly<ObservationFrame> | null;
24
+ readonly gameState: Readonly<GameState> | null;
25
+ readonly facts: readonly Readonly<ReminderFact>[];
26
+ /** Reuses Source task comparison; independent of the facts subscription. */
27
+ readonly taskChanges: readonly ReminderTaskChange[];
28
+ /** Establish private baselines without replaying notifications. */
29
+ readonly boundary: 'initial' | 'recovery' | null;
30
+ readonly config: Readonly<Record<string, unknown>>;
31
+ /** Host-persisted state from the previous completed update; never use instance fields for recovery. */
32
+ readonly state: unknown;
33
+ readonly nowMs: number;
34
+ }
35
+ export interface ReminderResult {
36
+ readonly state?: unknown;
37
+ readonly events?: readonly ReminderEvent[];
38
+ }
39
+ export interface ReminderEvent {
40
+ readonly type: 'reminder.task';
41
+ /** Stable per occurrence, retained across retry/recovery. */
42
+ readonly key: string;
43
+ readonly wakeAgent: boolean;
44
+ readonly payload: Readonly<Record<string, unknown>> & { readonly text: string };
45
+ }
46
+ export interface ClawclawReminderManifest {
47
+ readonly apiVersion: typeof REMINDER_PLUGIN_API_VERSION;
48
+ readonly kind: 'reminder';
49
+ readonly id: string;
50
+ readonly description: string;
51
+ readonly name?: string;
52
+ readonly localizations?: import('../resource-metadata.js').ClawclawResourceLocalizations;
53
+ readonly topic: ReminderTopic;
54
+ readonly consumes: readonly string[];
55
+ /** Optional validation schema for parameters carried in this module's own manifest. */
56
+ readonly inputs?: readonly BehaviorInputFieldSpec[];
57
+ readonly config?: Readonly<Record<string, unknown>>;
58
+ }
59
+ /** Non-visual perception rule. Runtime supplies durable state and bounds the Worker. */
60
+ export abstract class ClawclawReminder {
61
+ static readonly manifest?: ClawclawReminderManifest;
62
+ abstract update(input: Readonly<ReminderInput>): ReminderResult | Promise<ReminderResult>;
63
+ }