@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
@@ -0,0 +1,22 @@
1
+ import { ApiError, formatApiError } from './http-transport.js';
2
+ import { invalidAccountMessage } from './account-guidance.js';
3
+ import { hubErrorFields } from './hub-errors.js';
4
+
5
+ export class CommandOutputError extends Error {
6
+ constructor(message: string, public readonly output: Record<string, unknown>) {
7
+ super(message);
8
+ this.name = 'CommandOutputError';
9
+ }
10
+ }
11
+
12
+ export function formatCommandError(error: unknown): string {
13
+ if (error instanceof CommandOutputError) return JSON.stringify(error.output, null, 2);
14
+ if (error instanceof ApiError && error.status === 401) return invalidAccountMessage();
15
+ const hub = hubErrorFields(error);
16
+ if (hub) return JSON.stringify({ error: 'api_error', ...hub }, null, 2);
17
+ if (error instanceof ApiError) {
18
+ // HTTP 422 is a validation failure, not evidence of a malformed API key.
19
+ return formatApiError(error);
20
+ }
21
+ return error instanceof Error ? error.message : String(error);
22
+ }
@@ -2,6 +2,7 @@ import { AuthStore } from './auth.js';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { ServerRegistry } from './server-registry.js';
4
4
  import { HttpTransport } from './http-transport.js';
5
+ import { isWorkspaceRevisionConflict } from './hub-errors.js';
5
6
 
6
7
  export type ResourceType = 'skill' | 'strategy' | 'persona' | 'perception';
7
8
 
@@ -12,6 +13,7 @@ export interface ResourceStats {
12
13
  }
13
14
 
14
15
  export interface ResourceSummary {
16
+ skillName?: string | null;
15
17
  id: string;
16
18
  forkedFromResourceId?: string;
17
19
  type: ResourceType;
@@ -61,6 +63,7 @@ export interface ListOptions {
61
63
  }
62
64
 
63
65
  export interface WorkspaceResourceSummary {
66
+ skillName?: string | null;
64
67
  workspaceItemId: string;
65
68
  forkedFromResourceId?: string;
66
69
  resourceId: string;
@@ -127,6 +130,7 @@ interface RawVersion {
127
130
  }
128
131
 
129
132
  interface RawResource {
133
+ skill_name?: string | null;
130
134
  id?: string;
131
135
  forked_from_resource_id?: string | null;
132
136
  resource_id: string;
@@ -144,6 +148,7 @@ interface RawResource {
144
148
  }
145
149
 
146
150
  interface RawWorkspaceItem {
151
+ skill_name?: string | null;
147
152
  workspace_item_id: string;
148
153
  forked_from_resource_id?: string | null;
149
154
  resource_id: string;
@@ -169,6 +174,7 @@ export interface HubUploadedSourceFile {
169
174
  }
170
175
 
171
176
  export interface HubResourceMutationResult {
177
+ skillName?: string | null;
172
178
  resourceId: string;
173
179
  versionId: string;
174
180
  workspaceItemId?: string;
@@ -188,6 +194,7 @@ function toSummary(resource: RawResource): ResourceSummary {
188
194
  id: resource.resource_id ?? resource.id ?? '',
189
195
  forkedFromResourceId: resource.forked_from_resource_id ?? undefined,
190
196
  type: resource.resource_type,
197
+ skillName: resource.skill_name ?? null,
191
198
  title: version.title,
192
199
  description: version.description,
193
200
  creator: owner.id ?? '',
@@ -321,6 +328,7 @@ export class HubClient {
321
328
  forkedFromResourceId: item.forked_from_resource_id ?? undefined,
322
329
  resourceId: item.resource_id,
323
330
  resourceType: item.resource_type,
331
+ skillName: item.skill_name ?? null,
324
332
  title: item.title ?? '',
325
333
  versionId: item.version_id,
326
334
  equipped: item.is_equipped === true,
@@ -358,11 +366,23 @@ export class HubClient {
358
366
  return { updated: response.data.updated, versionId: response.data.version_id };
359
367
  }
360
368
 
369
+ private async updateWorkspace<T>(path: string, body: unknown): Promise<T> {
370
+ try {
371
+ return await this.http.post<T>(path, body);
372
+ } catch (error) {
373
+ if (!isWorkspaceRevisionConflict(error)) throw error;
374
+ // Refresh once, then retry only this explicit operation. No background
375
+ // replay, extra request fields, or name-conflict replacement is allowed.
376
+ await this.http.get(`${BASE}/workspace/loadout`);
377
+ return this.http.post<T>(path, body);
378
+ }
379
+ }
380
+
361
381
  async updateWorkspaceEquipment(
362
382
  workspaceItemId: string,
363
383
  equipped: boolean,
364
384
  ): Promise<{ workspaceItemId: string; equipped: boolean; revision: number; changed: boolean }> {
365
- const response = await this.http.post<Envelope<{
385
+ const response = await this.updateWorkspace<Envelope<{
366
386
  workspace_item_id: string;
367
387
  is_equipped: boolean;
368
388
  revision: number;
@@ -387,7 +407,7 @@ export class HubClient {
387
407
  if (input.strategyItemIds !== undefined) body.strategy_item_ids = input.strategyItemIds;
388
408
  if (input.personaItemIds !== undefined) body.persona_item_ids = input.personaItemIds;
389
409
  if (input.perceptionItemIds !== undefined) body.perception_item_ids = input.perceptionItemIds;
390
- const response = await this.http.post<Envelope<{ revision: number; changed: boolean }>>(
410
+ const response = await this.updateWorkspace<Envelope<{ revision: number; changed: boolean }>>(
391
411
  `${BASE}/workspace/loadout/update`,
392
412
  body,
393
413
  );
@@ -462,6 +482,7 @@ export class HubClient {
462
482
  resource_id: string;
463
483
  latest_version: { id: string };
464
484
  workspace_item_id?: string;
485
+ skill_name?: string | null;
465
486
  }>>(`${BASE}/resources/create`, {
466
487
  resource_type: input.resourceType,
467
488
  version_number: '1.0.0',
@@ -477,6 +498,7 @@ export class HubClient {
477
498
  return {
478
499
  resourceId: response.data.resource_id,
479
500
  versionId: response.data.latest_version.id,
501
+ skillName: response.data.skill_name ?? null,
480
502
  ...(response.data.workspace_item_id ? { workspaceItemId: response.data.workspace_item_id } : {}),
481
503
  };
482
504
  }
@@ -494,6 +516,7 @@ export class HubClient {
494
516
  const response = await this.http.post<Envelope<{
495
517
  resource_id: string;
496
518
  latest_version: { id: string };
519
+ skill_name?: string | null;
497
520
  }>>(`${BASE}/resources/version/create`, {
498
521
  resource_id: input.resourceId,
499
522
  base_version_id: input.baseVersionId,
@@ -509,6 +532,7 @@ export class HubClient {
509
532
  return {
510
533
  resourceId: response.data.resource_id,
511
534
  versionId: response.data.latest_version.id,
535
+ skillName: response.data.skill_name ?? null,
512
536
  };
513
537
  }
514
538
  }
@@ -0,0 +1,60 @@
1
+ import { ApiError, formatApiError } from './http-transport.js';
2
+
3
+ export interface HubErrorFields {
4
+ status: number;
5
+ code?: string;
6
+ message: string;
7
+ operation: string;
8
+ details?: Record<string, unknown>;
9
+ hint?: string;
10
+ retryable?: boolean;
11
+ }
12
+
13
+ function record(value: unknown): value is Record<string, unknown> {
14
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
15
+ }
16
+
17
+ /** Preserve Hub business errors across direct commands and per-resource sync failures. */
18
+ export function hubErrorFields(error: unknown): HubErrorFields | undefined {
19
+ if (!(error instanceof ApiError) || !error.path.startsWith('/api/v1/hub/')) return undefined;
20
+ let body: unknown;
21
+ try { body = JSON.parse(error.body); } catch { /* retain the original response below */ }
22
+ const payload = record(body) && record(body.error) ? body.error : undefined;
23
+ const code = typeof payload?.code === 'string' ? payload.code : undefined;
24
+ const operation = error.path.split('?')[0]!;
25
+ const equipment = operation === '/api/v1/hub/workspace/equipment/update'
26
+ || operation === '/api/v1/hub/workspace/loadout/update';
27
+ const create = operation === '/api/v1/hub/resources/create';
28
+ const version = operation === '/api/v1/hub/resources/version/create';
29
+ const result: HubErrorFields = {
30
+ status: error.status,
31
+ ...(code ? { code } : {}),
32
+ message: typeof payload?.message === 'string' ? payload.message : formatApiError(error),
33
+ operation,
34
+ ...(record(payload?.details) ? { details: payload.details } : {}),
35
+ };
36
+ if ((create || version) && code === 'INVALID_SKILL_NAME') {
37
+ result.hint = '请检查根 SKILL.md 的 UTF-8、YAML frontmatter 和 name,按服务端原因修正后再提交;本地文件已保留。';
38
+ } else if (create && code === 'SKILL_NAME_CONFLICT') {
39
+ result.hint = '你已有同名 Skill。请到 Hub 确认已有资源;更新它需明确选择该资源,新建则需修改新 Skill 的 name。不要按同名自动关联、覆盖或再次 fork。';
40
+ } else if (version && code === 'SKILL_NAME_IMMUTABLE') {
41
+ result.hint = '已有 Skill 不能通过新版本改名。请恢复原 name 后发版,或明确新建另一资源;修改 Hub 标题不能解决。本地文件已保留。';
42
+ } else if (version && code === 'SKILL_NAME_KEY_MISSING') {
43
+ result.hint = '该历史 Skill 尚未完成名称回填,请联系 Hub 运维处理后再发版;不要反复重试,本地修改已保留。';
44
+ } else if (equipment && code === 'SKILL_NAME_CONFLICT') {
45
+ result.hint = '已装配另一件同名 Skill。请用户到 Hub 处理装配冲突,完成后重新运行 ccl load;CCL 不自动卸载或替换任何 Skill,也不要用卸载后重装绕过此提示。';
46
+ } else if (equipment && code === 'INVALID_LOADOUT') {
47
+ result.hint = '装配选择无效,可能是同名 Skill、超出上限或类型不匹配。请按服务端原因到 Hub 修正选择,再运行 ccl load。';
48
+ } else if (equipment && code === 'WORKSPACE_REVISION_CONFLICT') {
49
+ result.hint = 'Workspace 装配正在被并发修改。请刷新最新装配状态后再重试本次明确操作;不要反复重放旧装配。';
50
+ result.retryable = true;
51
+ }
52
+ if (result.hint && result.retryable === undefined) result.retryable = false;
53
+ return result;
54
+ }
55
+
56
+ export function isWorkspaceRevisionConflict(error: unknown): boolean {
57
+ const fields = hubErrorFields(error);
58
+ return fields?.status === 409 && fields.code === 'WORKSPACE_REVISION_CONFLICT'
59
+ && fields.retryable === true;
60
+ }
@@ -61,7 +61,7 @@ export function readWorkspacePerceptionConfig(
61
61
  ];
62
62
  const eventTypes = new Set<string>([
63
63
  ...CLAWCLAW_VISUAL_EVENT_TYPES,
64
- ...sources.flatMap((source) => [...source.manifest.produces]),
64
+ ...sources.filter(source => !source.reminder).flatMap((source) => [...source.manifest.produces]),
65
65
  ]);
66
66
  let maxBackfillVisualFrames: number | undefined;
67
67
  if (configuredMaxBackfillVisualFrames !== undefined) {
@@ -416,6 +416,8 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
416
416
  const cooldownText = cooldown === undefined ? '' : `;共享冷却剩余${cooldown}秒`;
417
417
  return `破坏任务“${firstString(event, ['task_name'])}”因紧急任务开始而中断,任务未消耗${cooldownText}。`;
418
418
  }
419
+ case 'reminder.task':
420
+ return firstString(event, ['text'], '任务提醒。');
419
421
  case 'tasks_changed':
420
422
  return `任务列表已更新(${firstString(event, ['reason'])})。`;
421
423
  case 'players_changed':
@@ -957,7 +957,8 @@ export async function runClawclawOwner(
957
957
  ? resolveClawclawResourceMetadata(source, DESKTOP_RESOURCE_LOCALE)
958
958
  : null;
959
959
  })(),
960
- perceptions: assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
960
+ perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
961
+ ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE)],
961
962
  }),
962
963
  eventDescriptors: () => assembly.perception
963
964
  .localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
@@ -1,4 +1,7 @@
1
1
  import type { GameClient } from '../../../lib/game-client.js';
2
+ import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
3
+ import { listClawclawPerceptionSources } from './perception/perception-source.js';
4
+ import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
2
5
  import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
3
6
  import {
4
7
  CLAWCLAW_ACTION_PLUGIN_ID,
@@ -50,6 +53,7 @@ export interface ClawclawPluginAssembly {
50
53
  action: ClawclawActionPlugin;
51
54
  gameQuery: ClawclawGameQueryPlugin;
52
55
  perception: ClawclawPerceptionPlugin;
56
+ reminders: ClawclawReminderPlugin;
53
57
  trigger: ClawclawTriggerPlugin;
54
58
  behavior: ClawclawBehaviorPlugin;
55
59
  mailbox: ClawclawMailboxPlugin;
@@ -83,6 +87,16 @@ export function assembleClawclawPlugins(
83
87
  if (!plugins.some((plugin) => plugin.id === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID)) {
84
88
  plugins.push(new ClawclawDerivedEventPlugin());
85
89
  }
90
+ const configuredReminders = plugins.find(plugin => plugin.id === CLAWCLAW_REMINDER_PLUGIN_ID);
91
+ if (configuredReminders && !(configuredReminders instanceof ClawclawReminderPlugin)) {
92
+ throw new Error(`Runtime Plugin ${CLAWCLAW_REMINDER_PLUGIN_ID} is not a ClawclawReminderPlugin.`);
93
+ }
94
+ const selected = new Set(options.perception?.modules ?? DEFAULT_PERCEPTION_MODULES);
95
+ const reminders = configuredReminders as ClawclawReminderPlugin | undefined ?? new ClawclawReminderPlugin({
96
+ sources: (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
97
+ .filter(source => source.reminder && selected.has(source.id)),
98
+ });
99
+ if (!configuredReminders) plugins.push(reminders);
86
100
 
87
101
  const configuredGameQuery = plugins.find((plugin) => plugin.id === CLAWCLAW_GAME_QUERY_PLUGIN_ID);
88
102
  if (configuredGameQuery && !(configuredGameQuery instanceof ClawclawGameQueryPlugin)) {
@@ -123,6 +137,7 @@ export function assembleClawclawPlugins(
123
137
  after: [
124
138
  CLAWCLAW_ACTION_PLUGIN_ID,
125
139
  CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
140
+ CLAWCLAW_REMINDER_PLUGIN_ID,
126
141
  CLAWCLAW_GAME_QUERY_PLUGIN_ID,
127
142
  CLAWCLAW_PERCEPTION_PLUGIN_ID,
128
143
  CLAWCLAW_TRIGGER_PLUGIN_ID,
@@ -146,11 +161,11 @@ export function assembleClawclawPlugins(
146
161
  }
147
162
  const eventProducers = plugins
148
163
  .filter((plugin) => plugin.id !== CLAWCLAW_MAILBOX_PLUGIN_ID)
149
- .filter((plugin) => (plugin.produces?.events?.length ?? 0) > 0)
164
+ .filter((plugin) => (plugin.produces?.events?.length ?? 0) > 0 || (plugin.controlsEventDelivery?.length ?? 0) > 0)
150
165
  .map((plugin) => plugin.id);
151
166
  const mailbox = configuredMailbox as ClawclawMailboxPlugin | undefined
152
167
  ?? new ClawclawMailboxPlugin({ after: eventProducers });
153
168
  if (!configuredMailbox) plugins.push(mailbox);
154
169
 
155
- return { plugins, action, gameQuery, perception, trigger, behavior, mailbox };
170
+ return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox };
156
171
  }
@@ -13,6 +13,16 @@ interface ParsedValue {
13
13
 
14
14
  class LiteralParseError extends Error {}
15
15
 
16
+ /** Shared, non-evaluating parser for a complete module manifest literal. */
17
+ export function parseLiteralModuleManifest(source: string): Record<string, unknown> | null {
18
+ try {
19
+ const parsed = parseValue(source, skipTrivia(source, 0));
20
+ if (skipTrivia(source, parsed.next) !== source.length || !parsed.value
21
+ || typeof parsed.value !== 'object' || Array.isArray(parsed.value)) return null;
22
+ return parsed.value as Record<string, unknown>;
23
+ } catch { return null; }
24
+ }
25
+
16
26
  function skipTrivia(source: string, start: number): number {
17
27
  let cursor = start;
18
28
  while (cursor < source.length) {
@@ -0,0 +1,146 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
2
+ import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
+ import type { ReminderInput, ReminderResult, ReminderTopic, ReminderTaskChange } 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 { REMINDER_EVENT_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
+ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string, any>> {
24
+ readonly kind = 'epoch' as const;
25
+ readonly id = CLAWCLAW_REMINDER_PLUGIN_ID;
26
+ readonly version = '2';
27
+ readonly after = ['clawclaw.derived-event'];
28
+ readonly consumes = { events: REMINDER_FACT_TYPES };
29
+ readonly produces = { events: REMINDER_EVENT_TYPES } as const;
30
+ readonly catchUp = 'strict_ordered' as const;
31
+ readonly timeoutMs = 3_000;
32
+ private checkpoint: Checkpoint = empty();
33
+ private readonly sources = new Map<ReminderTopic, ResolvedClawclawPerceptionSource[]>();
34
+ private readonly runners = new Map<ReminderTopic, ReminderRunner>();
35
+ private readonly failed = new Set<ReminderTopic>();
36
+ constructor(private readonly options: ReminderPluginOptions = {}) {
37
+ for (const source of options.sources ?? []) {
38
+ if (!source.reminder) continue;
39
+ const selected = this.sources.get(source.reminder.topic) ?? [];
40
+ selected.push(source); this.sources.set(source.reminder.topic, selected);
41
+ }
42
+ }
43
+ async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
44
+ this.checkpoint = empty(); this.failed.clear();
45
+ await Promise.all(REMINDER_TOPICS.map(async topic => {
46
+ const sources = this.sources.get(topic) ?? [];
47
+ if (!sources.length) return;
48
+ try {
49
+ if (sources.length !== 1) throw new Error(`perception_topic_conflict:${topic}:${sources.map(s => s.id).join(',')}`);
50
+ const runner = new ReminderRunner(sources[0]!);
51
+ this.runners.set(topic, runner);
52
+ await runner.start();
53
+ } catch (error) { this.markFailed(topic, context, error); await this.runners.get(topic)?.stop(); }
54
+ }));
55
+ }
56
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
57
+ const checkpoint = context.checkpoint() as Checkpoint | undefined;
58
+ if (checkpoint?.states) this.checkpoint = structuredClone({
59
+ gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
60
+ previousConnectionId: checkpoint.previousConnectionId,
61
+ states: checkpoint.states.tasks ? { tasks: checkpoint.states.tasks } : {},
62
+ });
63
+ }
64
+ async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(r => r.stop())); this.runners.clear(); }
65
+ localizedModuleDescriptors(locale: string) {
66
+ return [...this.sources.entries()].filter(([topic, sources]) => sources.length === 1
67
+ && this.runners.has(topic) && !this.failed.has(topic)).map(([, [source]]) => (
68
+ resolveClawclawResourceMetadata({ ...source!.manifest, display: source!.display }, locale)
69
+ ));
70
+ }
71
+ async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
72
+ const snapshot = freshClawclawGameState(input.frame.state);
73
+ const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
74
+ let next = structuredClone(this.checkpoint);
75
+ const initial = !!game && next.gameId !== game.game_id;
76
+ const boundary = initial ? 'initial' as const
77
+ : (next.previousConnectionId !== undefined && next.previousConnectionId !== input.epoch.connectionId)
78
+ || input.epochEvents.some(e => e.type === 'game_stream_reconnected')
79
+ ? 'recovery' as const : null;
80
+ if (initial) next = { ...empty(), gameId: game!.game_id };
81
+ const frame = new ObservationFrameProjector().project(input.frame);
82
+ if (frame) {
83
+ const delta = next.previousTick === undefined ? null : frame.tick - next.previousTick;
84
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
85
+ && next.previousConnectionId === input.epoch.connectionId });
86
+ next.previousTick = frame.tick;
87
+ next.previousConnectionId = input.epoch.connectionId;
88
+ } else if (!game) {
89
+ next.previousTick = undefined; next.previousConnectionId = undefined;
90
+ }
91
+ next.previousConnectionId = input.epoch.connectionId;
92
+ const facts = input.pendingEvents;
93
+ const events: RuntimeEventProposal[] = [];
94
+ const taskChanges: ReminderTaskChange[] = facts.filter(e => e.type === 'tasks_changed').flatMap(e => {
95
+ const delta = Array.isArray(e.payload.delta) ? e.payload.delta : [];
96
+ return delta.map((change, index) => ({ ...change, key: `change:${e.eventId}:${index}`,
97
+ eventId: e.eventId, epochId: e.epochSeq,
98
+ baseline: e.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(e.payload.reason)),
99
+ } as ReminderTaskChange));
100
+ });
101
+ for (const topic of REMINDER_TOPICS) {
102
+ const selected = this.sources.get(topic)?.[0];
103
+ if (!selected || this.failed.has(topic)) continue;
104
+ const previous = next.states[topic];
105
+ const moduleInput: ReminderInput = {
106
+ scope: input.epoch.scope, frame, gameState: game, taskChanges, boundary,
107
+ facts: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type,
108
+ occurredAt: e.occurredAt, producer: e.producer, payload: e.payload })),
109
+ config: selected.reminder!.config ?? {}, state: previous?.provider === selected.id ? previous.value : undefined,
110
+ nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
111
+ };
112
+ try {
113
+ const result: ReminderResult = await this.runners.get(topic)!.update(moduleInput);
114
+ if (!result || typeof result !== 'object' || Array.isArray(result)
115
+ || Object.keys(result).some(k => !['state', 'events'].includes(k))
116
+ || (result.events !== undefined && !Array.isArray(result.events))
117
+ || Buffer.byteLength(JSON.stringify(result)) > 1024 * 1024) throw new Error('Invalid reminder output.');
118
+ const accepted: RuntimeEventProposal[] = [];
119
+ const keys = new Set<string>();
120
+ for (const event of result.events ?? []) {
121
+ if (!event || event.type !== 'reminder.task' || typeof event.key !== 'string'
122
+ || !event.key.trim() || event.key.length > 512 || keys.has(event.key)
123
+ || typeof event.wakeAgent !== 'boolean' || !event.payload || Array.isArray(event.payload)
124
+ || typeof event.payload.text !== 'string' || !event.payload.text.trim()) {
125
+ throw new Error('Invalid task reminder event.');
126
+ }
127
+ keys.add(event.key);
128
+ accepted.push({ type: event.type, dedupeKey: JSON.stringify([selected.id, event.key]),
129
+ dedupeScope: 'segment', wakeAgent: event.wakeAgent, payload: { ...event.payload },
130
+ occurredAt: new Date(moduleInput.nowMs).toISOString() });
131
+ }
132
+ // Recovery/initial snapshots establish private state, never replay notices.
133
+ if (!boundary && game) events.push(...accepted);
134
+ next.states[topic] = { provider: selected.id, value: structuredClone(result.state) };
135
+ } catch (error) { this.markFailed(topic, context, error); }
136
+ }
137
+ this.checkpoint = next;
138
+ return { outcome: 'processed', events, checkpoint: next,
139
+ ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
140
+ }
141
+ private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
142
+ this.failed.add(topic);
143
+ context.diagnostic('reminder.module_failed', { topic, module_ids: this.sources.get(topic)?.map(s => s.id),
144
+ error: error instanceof Error ? error.message : String(error) }, 'error');
145
+ }
146
+ }
@@ -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
- this.selectsEvent(row.event, ready.state.state)
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
- this.selectsEvent(row.event, ready.state.state)
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 !== 'internal_only'
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;
@@ -18,9 +18,6 @@ export const CLAWCLAW_DETAIL_EVENT_TYPES = new Set<string>([
18
18
  'game_started',
19
19
  'role_assigned',
20
20
  'players_changed',
21
- 'tasks_changed',
22
- 'task_completed',
23
- 'task_sabotaged',
24
21
  'meeting_briefing',
25
22
  'exile',
26
23
  'no_exile',
@@ -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)),