@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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 (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -1,114 +1,13 @@
1
+ import { PerceptionRuleRunner } from '../system-perception/rule-runner.js';
1
2
  import { PlayerChangesDerivedEventRule, TaskChangesDerivedEventRule } from './state-change-rules.js';
2
- import type {
3
- RuntimeEpochPlugin,
4
- RuntimeEpochPluginContext,
5
- RuntimeEpochPluginInput,
6
- RuntimeEpochPluginResult,
7
- RuntimeEventProposal,
8
- RuntimeSourceEvent,
9
- } from '../../../framework/plugins/index.js';
10
- import type { StoredStateFrame } from '../../../framework/state/index.js';
11
- import {
12
- AbilityStateDerivedEventRule,
13
- EmergencyCountdownDerivedEventRule,
14
- MeetingStateDerivedEventRule,
15
- RoomReadyDerivedEventRule,
16
- type ClawclawDerivedEventRule,
17
- } from './derived-event-rules.js';
18
-
3
+ import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule,
4
+ MeetingStateDerivedEventRule, RoomReadyDerivedEventRule, type ClawclawDerivedEventRule } from './derived-event-rules.js';
19
5
  export const CLAWCLAW_DERIVED_EVENT_PLUGIN_ID = 'clawclaw.derived-event';
20
-
21
- export class ClawclawDerivedEventPlugin
22
- implements RuntimeEpochPlugin<Record<string, any>> {
23
- readonly kind = 'epoch' as const;
24
- readonly id = CLAWCLAW_DERIVED_EVENT_PLUGIN_ID;
25
- readonly version = '2';
26
- readonly produces: { events: readonly string[] };
27
- readonly consumes: { events: readonly string[] };
28
- // Task/player changes must commit beside the backend facts from that input.
29
- // Coalescing them into a later epoch would split downstream notification causality.
30
- readonly catchUp = 'strict_ordered' as const;
31
- readonly timeoutMs = 1_000;
32
-
33
- private readonly rules: ClawclawDerivedEventRule[];
34
- private lastFrameSeq = 0;
35
-
6
+ /** Legacy rule harness. The production graph uses independent builtin perceptions. */
7
+ export class ClawclawDerivedEventPlugin extends PerceptionRuleRunner {
36
8
  constructor(rules?: readonly ClawclawDerivedEventRule[]) {
37
- this.rules = [...(rules ?? [
38
- new PlayerChangesDerivedEventRule(),
39
- new TaskChangesDerivedEventRule(),
40
- new AbilityStateDerivedEventRule(),
41
- new EmergencyCountdownDerivedEventRule(),
42
- new RoomReadyDerivedEventRule(),
43
- new MeetingStateDerivedEventRule(),
44
- ])].sort((left, right) => left.id.localeCompare(right.id));
45
- this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
46
- this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
47
- }
48
-
49
- start(): void {
50
- this.reset();
51
- }
52
-
53
- recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
54
- const completedThrough = context.progress().completedThroughEpochSeq;
55
- if (completedThrough <= 0) return;
56
- this.scanHistory(context, completedThrough, false);
57
- }
58
-
59
- update(
60
- input: RuntimeEpochPluginInput<Record<string, any>>,
61
- context: RuntimeEpochPluginContext<Record<string, any>>,
62
- ): RuntimeEpochPluginResult {
63
- const events = this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
64
- return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
65
- : { outcome: 'noop' as const, reason: 'no_derived_event' }),
66
- ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
67
- }
68
-
69
- stop(): void {
70
- this.reset();
71
- }
72
-
73
- private scanHistory(
74
- context: RuntimeEpochPluginContext<Record<string, any>>,
75
- throughEpochSeq: number,
76
- collect: boolean,
77
- throughFrameSeq?: number,
78
- currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
79
- ): RuntimeEventProposal[] {
80
- const proposals: RuntimeEventProposal[] = [];
81
- let afterFrameSeq = this.lastFrameSeq;
82
- while (true) {
83
- const page = context.stateHistory.queryStateFrames({
84
- scope: context.scope,
85
- afterFrameSeq,
86
- toEpochSeq: throughEpochSeq,
87
- ...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }),
88
- order: 'asc',
89
- limit: 500,
90
- });
91
- if (page.frames.length === 0) break;
92
- for (const frame of page.frames) {
93
- const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
94
- ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
95
- const frameEvents = this.inspectFrame(frame, facts);
96
- if (collect) proposals.push(...frameEvents);
97
- afterFrameSeq = frame.frameSeq;
98
- }
99
- if (!page.page.hasMore) break;
100
- }
101
- return proposals;
102
- }
103
-
104
- private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
105
- if (frame.frameSeq <= this.lastFrameSeq) return [];
106
- this.lastFrameSeq = frame.frameSeq;
107
- return this.rules.flatMap((rule) => rule.inspect(frame, facts));
108
- }
109
-
110
- private reset(): void {
111
- this.lastFrameSeq = 0;
112
- for (const rule of this.rules) rule.reset();
9
+ super(CLAWCLAW_DERIVED_EVENT_PLUGIN_ID, rules ?? [new PlayerChangesDerivedEventRule(),
10
+ new TaskChangesDerivedEventRule(), new AbilityStateDerivedEventRule(),
11
+ new EmergencyCountdownDerivedEventRule(), new RoomReadyDerivedEventRule(), new MeetingStateDerivedEventRule()]);
113
12
  }
114
13
  }
@@ -43,7 +43,7 @@ function roomSnapshot(
43
43
  frame: StoredStateFrame<Record<string, any>>,
44
44
  ): UnknownRecord | null | undefined {
45
45
  const state = frame.state;
46
- if (!isClawclawRuntimeState(state) || state.cause !== 'room_update') return undefined;
46
+ if (!isClawclawRuntimeState(state) || state.stage !== 'room') return undefined;
47
47
  return record(record(state.room)?.room);
48
48
  }
49
49
 
@@ -116,7 +116,7 @@ function freshGameSnapshot(
116
116
  ): UnknownRecord | null | undefined {
117
117
  const state = frame.state;
118
118
  if (!isClawclawRuntimeState(state)) return record(state);
119
- if (state.game_snapshot.status !== 'fresh') return undefined;
119
+ if ((state.game_snapshot.status !== 'fresh' && state.game_snapshot.status !== 'cached')) return undefined;
120
120
  return record(state.game_snapshot.state);
121
121
  }
122
122
 
@@ -1,8 +1,11 @@
1
+ import { prepareNotificationContent } from '../perception/notification-content.js';
2
+ import { preparePerceptionNotification } from '../perception/report-content.js';
3
+ import { isNotificationTurn } from '../../notification-turn.js';
1
4
  import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
2
5
  import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
- import type { ReminderInput, ReminderResult, ReminderTopic, ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
6
+ import type { ReminderInput, ReminderResult, ReminderTopic } from '../../../../sdk/perception-plugin/reminder.js';
4
7
  import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
5
- import { freshClawclawGameState } from '../../runtime-state.js';
8
+ import { clawclawComputationGameState } from '../../runtime-state.js';
6
9
  import { createCanonicalGameState } from '../../behavior-input.js';
7
10
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
8
11
  import { ObservationFrameProjector } from '../../observation-frame-projector.js';
@@ -10,22 +13,26 @@ import { REMINDER_EVENT_TYPES, REMINDER_EVENT_TYPE_BY_TOPIC, REMINDER_FACT_TYPES
10
13
  import { ReminderRunner } from './reminder-runner.js';
11
14
  import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
12
15
 
16
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js';
17
+
13
18
  export const CLAWCLAW_REMINDER_PLUGIN_ID = 'clawclaw.derived-event.reminders';
14
19
  export interface ReminderPluginOptions {
15
20
  /** Already selected by the ordinary local/Hub perception loadout. No separate settings. */
16
21
  sources?: readonly ResolvedClawclawPerceptionSource[];
17
22
  }
18
23
  interface Checkpoint {
24
+ taskBaseline?: PerceptionTaskBaseline;
19
25
  gameId?: string;
20
26
  previousTick?: number; previousConnectionId?: string;
21
27
  states: Partial<Record<ReminderTopic, { provider: string; value: unknown }>>;
22
28
  }
23
29
  function empty(): Checkpoint { return { states: {} }; }
24
30
  export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string, any>> {
31
+ readonly agentNotificationProducer = true;
25
32
  readonly kind = 'epoch' as const;
26
33
  readonly id = CLAWCLAW_REMINDER_PLUGIN_ID;
27
34
  readonly version = '2';
28
- readonly after = ['clawclaw.derived-event'];
35
+ readonly after: readonly string[] = [];
29
36
  readonly consumes = { events: REMINDER_FACT_TYPES };
30
37
  readonly produces = { events: REMINDER_EVENT_TYPES } as const;
31
38
  readonly catchUp = 'strict_ordered' as const;
@@ -57,7 +64,7 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
57
64
  recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
58
65
  const checkpoint = context.checkpoint() as Checkpoint | undefined;
59
66
  if (checkpoint?.states) this.checkpoint = structuredClone({
60
- gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
67
+ taskBaseline: checkpoint.taskBaseline, gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
61
68
  previousConnectionId: checkpoint.previousConnectionId,
62
69
  states: Object.fromEntries(REMINDER_TOPICS.filter(topic => checkpoint.states[topic])
63
70
  .map(topic => [topic, checkpoint.states[topic]])),
@@ -71,9 +78,10 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
71
78
  ));
72
79
  }
73
80
  async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
81
+ if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
74
82
  if (this.sources.size === 0) return { outcome: 'noop', reason: 'no_reminder_modules',
75
83
  ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
76
- const snapshot = freshClawclawGameState(input.frame.state);
84
+ const snapshot = clawclawComputationGameState(input.frame.state);
77
85
  const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
78
86
  let next = structuredClone(this.checkpoint);
79
87
  const initial = !!game && next.gameId !== game.game_id;
@@ -93,21 +101,19 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
93
101
  next.previousTick = undefined; next.previousConnectionId = undefined;
94
102
  }
95
103
  next.previousConnectionId = input.epoch.connectionId;
96
- const facts = input.pendingEvents.map(event => ({ ...event,
104
+ const facts = input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({ ...event,
97
105
  payload: projectTaskChoiceEventPayload(game, event.type, event.payload) }));
98
106
  const events: RuntimeEventProposal[] = [];
99
- const taskChanges: ReminderTaskChange[] = facts.filter(e => e.type === 'tasks_changed').flatMap(e => {
100
- const delta = Array.isArray(e.payload.delta) ? e.payload.delta : [];
101
- return delta.map((change, index) => ({ ...change, key: `change:${e.eventId}:${index}`,
102
- eventId: e.eventId, epochId: e.epochSeq,
103
- baseline: e.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(e.payload.reason)),
104
- } as ReminderTaskChange));
105
- });
106
- for (const topic of REMINDER_TOPICS) {
107
+ const comparison = comparePerceptionTasks(next.taskBaseline, input, boundary);
108
+ next.taskBaseline = comparison.baseline;
109
+ const taskChanges = comparison.changes;
110
+ const outputs = await Promise.all(REMINDER_TOPICS.map(async topic => {
111
+ const events: RuntimeEventProposal[] = [];
107
112
  const selected = this.sources.get(topic)?.[0];
108
- if (!selected || this.failed.has(topic)) continue;
113
+ if (!selected || this.failed.has(topic)) return events;
109
114
  const previous = next.states[topic];
110
115
  const moduleInput: ReminderInput = {
116
+ ...(input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
111
117
  scope: input.epoch.scope, frame, gameState: game, taskChanges, boundary,
112
118
  facts: facts.filter(e => topic !== 'speech' || !e.replayed)
113
119
  .map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type,
@@ -133,6 +139,7 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
133
139
  keys.add(event.key);
134
140
  accepted.push({ type: event.type, dedupeKey: JSON.stringify([selected.id, event.key]),
135
141
  dedupeScope: 'segment', wakeAgent: event.wakeAgent, payload: { ...event.payload },
142
+ notificationContent: preparePerceptionNotification(event.type, event.payload, game, selected.id, input.frame.backendTick),
136
143
  occurredAt: new Date(moduleInput.nowMs).toISOString() });
137
144
  }
138
145
  // Task snapshots establish baselines. Fresh speech remains an occurrence
@@ -140,9 +147,12 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
140
147
  if (game && (topic === 'speech' || !boundary)) events.push(...accepted);
141
148
  next.states[topic] = { provider: selected.id, value: structuredClone(result.state) };
142
149
  } catch (error) { this.markFailed(topic, context, error); }
143
- }
150
+ return events;
151
+ }));
152
+ events.push(...outputs.flat());
144
153
  this.checkpoint = next;
145
- return { outcome: 'processed', events, checkpoint: next,
154
+ return { outcome: 'processed', events: events.map(event => ({ ...event,
155
+ notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, game, 'custom') })), checkpoint: next,
146
156
  ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
147
157
  }
148
158
  private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
@@ -14,6 +14,7 @@ export class ReminderRunner {
14
14
  if (!source.reminder) throw new Error('Not a reminder perception source.');
15
15
  }
16
16
  async start(): Promise<{ manifest: ClawclawReminderManifest; config: Record<string, unknown> }> {
17
+ if (this.source.compatibilityError) throw new Error(this.source.compatibilityError);
17
18
  const loader = runtimeModuleThreadLoaderConfig();
18
19
  const promise = this.wait(8_000);
19
20
  this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
@@ -2,7 +2,7 @@ import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framewor
2
2
  import type { StoredStateFrame } from '../../../framework/state/index.js';
3
3
  import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
4
4
  import { CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
5
- import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
5
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
6
6
  import type { ClawclawDerivedEventRule } from './derived-event-rules.js';
7
7
  import { nextPlayerProjection, type PlayerSnapshot } from './player-change-tracker.js';
8
8
  import { nextTaskProjection, type TaskSnapshot } from './task-change-tracker.js';
@@ -30,7 +30,7 @@ function trackerFacts(events: readonly RuntimeSourceEvent[]): Array<Record<strin
30
30
  }
31
31
 
32
32
  function gameState(frame: StoredStateFrame<Record<string, any>>): Record<string, any> | null {
33
- const game = freshClawclawGameState(frame.state);
33
+ const game = clawclawComputationGameState(frame.state);
34
34
  if (!game) return null;
35
35
  return { ...game, ...(frame.backendTick === undefined ? {} : { tick: frame.backendTick }) };
36
36
  }
@@ -76,7 +76,7 @@ export class TaskChangesDerivedEventRule implements ClawclawDerivedEventRule {
76
76
  const state = frame.state;
77
77
  const update = nextTaskProjection({ previous: this.projection, initialized: this.initialized, summary: game,
78
78
  events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name,
79
- allowUntickedInitialRole: isClawclawRuntimeState(state) && state.game_snapshot.status === 'fresh'
79
+ allowUntickedInitialRole: isClawclawRuntimeState(state) && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached')
80
80
  && state.game_snapshot.origin === 'update' });
81
81
  this.projection = update.projection; this.initialized = update.initialized;
82
82
  return update.payload ? proposal('tasks_changed', frame, update.payload, events) : [];
@@ -1,259 +1 @@
1
- export interface TaskSnapshot extends Record<string, unknown> {
2
- task_id?: string;
3
- name: string;
4
- room?: string;
5
- x?: number;
6
- y?: number;
7
- status?: string;
8
- is_fake_shrimp?: boolean;
9
- task_note?: string;
10
- faction?: 'lobster' | 'crab';
11
- }
12
-
13
- export interface TaskChangeDetail extends Record<string, unknown> {
14
- change: 'added' | 'removed' | 'status_changed' | 'updated';
15
- task: TaskSnapshot;
16
- before?: TaskSnapshot;
17
- from_status?: string;
18
- to_status?: string;
19
- }
20
-
21
- export interface TasksChangedPayload extends Record<string, unknown> {
22
- baseline: boolean;
23
- tick?: number;
24
- reason:
25
- | 'role_assigned'
26
- | 'task_completed'
27
- | 'task_sabotaged'
28
- | 'task_assigned'
29
- | 'emergency_started'
30
- | 'emergency_resolved'
31
- | 'emergency_interrupted'
32
- | 'meeting_started'
33
- | 'task_state_changed'
34
- | 'tasks_initialized';
35
- delta: TaskChangeDetail[];
36
- tasks: TaskSnapshot[];
37
- }
38
-
39
- export interface TaskProjectionUpdate {
40
- projection: TaskSnapshot[];
41
- initialized: boolean;
42
- payload: TasksChangedPayload | null;
43
- }
44
-
45
- function record(value: unknown): Record<string, any> | null {
46
- return value && typeof value === 'object' && !Array.isArray(value)
47
- ? value as Record<string, any>
48
- : null;
49
- }
50
-
51
- function finiteNumber(value: unknown): number | undefined {
52
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
53
- }
54
-
55
- function nonEmptyString(value: unknown): string | undefined {
56
- return typeof value === 'string' && value.length > 0 ? value : undefined;
57
- }
58
-
59
- function taskSnapshot(value: unknown): TaskSnapshot | null {
60
- const task = record(value);
61
- const name = nonEmptyString(task?.name) ?? nonEmptyString(task?.task_name);
62
- if (!task || !name) return null;
63
- const faction = task.faction === 'lobster' || task.faction === 'crab'
64
- ? task.faction
65
- : undefined;
66
- return {
67
- ...(nonEmptyString(task.task_id) ? { task_id: task.task_id } : {}),
68
- name,
69
- ...(nonEmptyString(task.room) ? { room: task.room } : {}),
70
- ...(finiteNumber(task.x) === undefined ? {} : { x: task.x }),
71
- ...(finiteNumber(task.y) === undefined ? {} : { y: task.y }),
72
- ...(nonEmptyString(task.status) ? { status: task.status } : {}),
73
- ...(typeof task.is_fake_shrimp === 'boolean'
74
- ? { is_fake_shrimp: task.is_fake_shrimp }
75
- : {}),
76
- ...(nonEmptyString(task.task_note) ? { task_note: task.task_note } : {}),
77
- ...(faction ? { faction } : {}),
78
- };
79
- }
80
-
81
- function tasksFromState(summary: Record<string, any> | null | undefined): TaskSnapshot[] | null {
82
- if (!Array.isArray(summary?.you?.tasks)) return null;
83
- return summary.you.tasks
84
- .map((task: unknown) => taskSnapshot(task))
85
- .filter((task: TaskSnapshot | null): task is TaskSnapshot => task !== null);
86
- }
87
-
88
- function taskKey(task: TaskSnapshot): string {
89
- if (task.task_id) return `id:${task.task_id}`;
90
- return JSON.stringify([
91
- task.name,
92
- task.room ?? null,
93
- task.x ?? null,
94
- task.y ?? null,
95
- task.faction ?? null,
96
- task.is_fake_shrimp ?? null,
97
- ]);
98
- }
99
-
100
- function sameTask(left: TaskSnapshot, right: TaskSnapshot): boolean {
101
- return JSON.stringify(left) === JSON.stringify(right);
102
- }
103
-
104
- function taskDelta(
105
- previous: readonly TaskSnapshot[],
106
- current: readonly TaskSnapshot[],
107
- ): TaskChangeDetail[] {
108
- const previousByKey = new Map(previous.map((task) => [taskKey(task), task]));
109
- const currentByKey = new Map(current.map((task) => [taskKey(task), task]));
110
- const delta: TaskChangeDetail[] = [];
111
- for (const task of previous) {
112
- if (!currentByKey.has(taskKey(task))) {
113
- delta.push({ change: 'removed', task: structuredClone(task) });
114
- }
115
- }
116
- for (const task of current) {
117
- const before = previousByKey.get(taskKey(task));
118
- if (!before) {
119
- delta.push({ change: 'added', task: structuredClone(task) });
120
- continue;
121
- }
122
- if (before.status !== task.status) {
123
- delta.push({
124
- change: 'status_changed',
125
- before: structuredClone(before),
126
- task: structuredClone(task),
127
- ...(before.status === undefined ? {} : { from_status: before.status }),
128
- ...(task.status === undefined ? {} : { to_status: task.status }),
129
- });
130
- continue;
131
- }
132
- if (!sameTask(before, task)) {
133
- delta.push({ change: 'updated', task: structuredClone(task), before: structuredClone(before) });
134
- }
135
- }
136
- return delta;
137
- }
138
-
139
- function actorMatches(
140
- event: Record<string, any>,
141
- selfName: string | undefined,
142
- selfSeat: number | undefined,
143
- ): boolean {
144
- const actor = record(event.actor);
145
- const name = nonEmptyString(actor?.name) ?? nonEmptyString(event.actor_name);
146
- const seat = Number.isInteger(actor?.seat)
147
- ? Number(actor!.seat)
148
- : Number.isInteger(event.actor_seat) ? Number(event.actor_seat) : undefined;
149
- if (selfSeat !== undefined && seat !== undefined) return seat === selfSeat;
150
- if (selfName && name) return name === selfName;
151
- return false;
152
- }
153
-
154
- function findLastEventIndex(
155
- events: readonly Record<string, any>[],
156
- predicate: (event: Record<string, any>) => boolean,
157
- ): number {
158
- for (let index = events.length - 1; index >= 0; index -= 1) {
159
- if (predicate(events[index]!)) return index;
160
- }
161
- return -1;
162
- }
163
-
164
- function updateReason(
165
- initialized: boolean,
166
- events: readonly Record<string, any>[],
167
- selfName: string | undefined,
168
- selfSeat: number | undefined,
169
- currentTick: number | undefined,
170
- allowUntickedInitialRole: boolean,
171
- ): Pick<TasksChangedPayload, 'reason'> {
172
- const roleIndex = findLastEventIndex(events, (event) => event.type === 'role_assigned');
173
- const roleTick = roleIndex >= 0 ? finiteNumber(events[roleIndex]?.tick) : undefined;
174
- const currentRole = roleIndex >= 0 && (
175
- (roleTick !== undefined && currentTick !== undefined && roleTick === currentTick)
176
- || (roleTick === undefined && allowUntickedInitialRole)
177
- );
178
- if (currentRole) {
179
- return { reason: 'role_assigned' };
180
- }
181
- // A first snapshot may replay historical task Events. Its current list is
182
- // an initialization fact, not the after-state of any one historical Event.
183
- if (!initialized) return { reason: 'tasks_initialized' };
184
- const visibleReasons = events
185
- .map((event, index) => ({ event, index }))
186
- .filter(({ event }) => (
187
- (event.type === 'task_completed' || event.type === 'task_sabotaged')
188
- ? actorMatches(event, selfName, selfSeat)
189
- : [
190
- 'emergency_started',
191
- 'emergency_resolved',
192
- 'emergency_interrupted',
193
- 'meeting_briefing',
194
- ].includes(event.type)
195
- ));
196
- const visible = visibleReasons[visibleReasons.length - 1];
197
- if (visible) {
198
- const reason = visible.event.type === 'meeting_briefing'
199
- ? 'meeting_started'
200
- : visible.event.type as TasksChangedPayload['reason'];
201
- return { reason };
202
- }
203
- if (events.some((event) => (
204
- event.type === 'task_assigned' && actorMatches(event, selfName, selfSeat)
205
- ))) return { reason: 'task_assigned' };
206
- return { reason: 'task_state_changed' };
207
- }
208
-
209
- /**
210
- * Diff the authoritative task list carried by one complete GameSync State.
211
- * Derived Event emits tasks_changed from the same accepted input, separate from backend facts.
212
- * Reminder scripts own Agent-facing task notifications.
213
- */
214
- export function nextTaskProjection(input: {
215
- previous: readonly TaskSnapshot[];
216
- initialized: boolean;
217
- summary?: Record<string, any> | null;
218
- events?: readonly Record<string, any>[];
219
- selfName?: string;
220
- selfSeat?: number;
221
- allowUntickedInitialRole?: boolean;
222
- }): TaskProjectionUpdate {
223
- const current = tasksFromState(input.summary);
224
- if (!current) {
225
- return {
226
- projection: [...input.previous].map((task) => structuredClone(task)),
227
- initialized: input.initialized,
228
- payload: null,
229
- };
230
- }
231
- const delta = taskDelta(input.previous, current);
232
- if (input.initialized && delta.length === 0) {
233
- return { projection: current, initialized: true, payload: null };
234
- }
235
- const selfSeat = input.selfSeat ?? (Number.isInteger(input.summary?.you?.player?.seat)
236
- ? Number(input.summary!.you.player.seat)
237
- : undefined);
238
- const selfName = input.selfName ?? nonEmptyString(input.summary?.you?.player?.name);
239
- const tick = finiteNumber(input.summary?.tick);
240
- const reason = updateReason(
241
- input.initialized,
242
- input.events ?? [],
243
- selfName,
244
- selfSeat,
245
- tick,
246
- input.allowUntickedInitialRole === true,
247
- );
248
- return {
249
- projection: current,
250
- initialized: true,
251
- payload: {
252
- baseline: !input.initialized,
253
- ...(tick === undefined ? {} : { tick }),
254
- reason: reason.reason,
255
- delta,
256
- tasks: current.map((task) => structuredClone(task)),
257
- },
258
- };
259
- }
1
+ export * from '../../../../sdk/perception-plugin/task-change-tracker.js';
@@ -127,12 +127,12 @@ export class ClawclawGameQueryPlugin implements RuntimeEpochPlugin<Record<string
127
127
  }
128
128
  const snapshot = queryContext.stateFrame;
129
129
  if (!snapshot || !isClawclawRuntimeState(snapshot.state)
130
- || snapshot.state.game_snapshot.status !== 'fresh') {
130
+ || (snapshot.state.game_snapshot.status !== 'fresh' && snapshot.state.game_snapshot.status !== 'cached')) {
131
131
  return { state: null, receivedAt: null };
132
132
  }
133
133
  return {
134
134
  state: snapshot.state.game_snapshot.state,
135
- receivedAt: new Date(snapshot.receivedAtMs).toISOString(),
135
+ receivedAt: new Date(snapshot.state.cycle?.stateReceivedAtMs ?? snapshot.receivedAtMs).toISOString(),
136
136
  };
137
137
  }
138
138
 
@@ -234,9 +234,9 @@ export class ClawclawGameQueryPlugin implements RuntimeEpochPlugin<Record<string
234
234
  }
235
235
  const runtimeState = input.epoch.state;
236
236
  if (isClawclawRuntimeState(runtimeState)
237
- && runtimeState.game_snapshot.status === 'fresh') {
237
+ && (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')) {
238
238
  this.latestFreshGameState = structuredClone(runtimeState.game_snapshot.state);
239
- this.latestFreshReceivedAt = new Date(input.frame.receivedAtMs).toISOString();
239
+ this.latestFreshReceivedAt = new Date(runtimeState.cycle?.stateReceivedAtMs ?? input.frame.receivedAtMs).toISOString();
240
240
  }
241
241
  return { outcome: 'noop', reason: 'query_provider' };
242
242
  }