@myclaw163/clawclaw-cli 0.8.13 → 0.8.15

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 (68) hide show
  1. package/docs/custom-modules/perception.md +4 -4
  2. package/docs/runtime/README.md +1 -1
  3. package/docs/runtime/behavior-runtime.md +1 -1
  4. package/docs/runtime/official-perception-modules.md +23 -30
  5. package/docs/runtime/perception-replay.md +1 -1
  6. package/package.json +1 -1
  7. package/skills/clawclaw/SKILL.md +8 -4
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CHANNELS.md +1 -1
  10. package/skills/clawclaw/references/COMMANDS.md +2 -2
  11. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  13. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  14. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  15. package/skills/clawclaw/references/STREAM.md +4 -2
  16. package/src/lib/game-client.ts +12 -4
  17. package/src/pipeline/event-format.ts +5 -0
  18. package/src/pipeline/event-hints.ts +10 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  20. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  21. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  22. package/src/runtime/clawclaw/owner.ts +64 -1
  23. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  24. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  25. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
  32. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
  33. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  34. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  35. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  36. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
  37. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  38. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  39. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
  40. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  42. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  43. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  44. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  45. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  46. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  49. package/src/runtime/clawclaw/runtime.ts +31 -3
  50. package/src/runtime/clawclaw-event-catalog.ts +3 -0
  51. package/src/runtime/framework/events/event-repository.ts +1 -1
  52. package/src/runtime/framework/events/memory-event-repository.ts +71 -1
  53. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  54. package/src/runtime/framework/mailbox/types.ts +2 -0
  55. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  56. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  57. package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
  58. package/src/runtime/framework/plugins/contracts.ts +5 -2
  59. package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
  60. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
  61. package/src/runtime/framework/runtime.ts +75 -4
  62. package/src/runtime/framework/state/history/contracts.ts +9 -1
  63. package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
  64. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  65. package/src/runtime/observability/redaction.ts +28 -1
  66. package/src/sdk/behavior-plugin/index.ts +5 -24
  67. package/src/sdk/module-input/index.ts +47 -0
  68. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -12,6 +12,7 @@ import {
12
12
  } from '../clawclaw-event-catalog.js';
13
13
  import type { ClawclawPosition } from '../clawclaw-position.js';
14
14
  import { Runtime, type RuntimeOptions } from '../framework/runtime.js';
15
+ import { createMemoryFirstPersistence } from '../framework/persistence/memory-first-persistence.js';
15
16
  import {
16
17
  AtomicJsonAgentStateSnapshotStore,
17
18
  DurableAgentStateSnapshotObserver,
@@ -108,6 +109,25 @@ export function createClawclawRuntime(
108
109
  : configuredSnapshot ?? new AtomicJsonAgentStateSnapshotStore<Record<string, any>>(
109
110
  durableAgentStateSnapshotPath(getProfileRuntimeStateDir(profile)),
110
111
  );
112
+ const useDefaultPersistence = !runtimeOptions.eventRepository
113
+ && !runtimeOptions.stateHistoryRepository
114
+ && !runtimeOptions.inputJournal;
115
+ const persistence = useDefaultPersistence
116
+ ? createMemoryFirstPersistence<ClawclawPosition>({
117
+ eventLedgerPath: getProfileEventLedgerPath(profile),
118
+ stateHistoryPath: getProfileStateHistoryPath(profile),
119
+ inputJournalPath: getProfileInputJournalPath(profile),
120
+ onDegraded: (error, health) => runtimeOptions.observability?.error(
121
+ 'runtime.persistence.async_degraded',
122
+ error,
123
+ {
124
+ pending_operations: health.pendingOperations,
125
+ dropped_operations: health.droppedOperations,
126
+ },
127
+ { component: 'runtime.persistence' },
128
+ ),
129
+ })
130
+ : null;
111
131
 
112
132
  return new Runtime<ClawclawPosition>({
113
133
  ...runtimeOptions,
@@ -121,9 +141,17 @@ export function createClawclawRuntime(
121
141
  // Mailbox ACK adapters own independent durable lanes. Disabled and
122
142
  // acknowledgement:none adapters must not leave an unowned delivery row.
123
143
  initialEventConsumerIds: [],
124
- eventLedgerPath: getProfileEventLedgerPath(profile),
125
- stateHistoryPath: getProfileStateHistoryPath(profile),
126
- inputJournalPath: getProfileInputJournalPath(profile),
144
+ ...(persistence
145
+ ? {
146
+ eventRepository: persistence.eventRepository,
147
+ stateHistoryRepository: persistence.stateHistoryRepository,
148
+ inputJournal: persistence.inputJournal,
149
+ }
150
+ : {
151
+ eventLedgerPath: getProfileEventLedgerPath(profile),
152
+ stateHistoryPath: getProfileStateHistoryPath(profile),
153
+ inputJournalPath: getProfileInputJournalPath(profile),
154
+ }),
127
155
  currentStateFromRuntimeState: projectClawclawCurrentState,
128
156
  stateFreshnessPolicy,
129
157
  stateFreshnessPolicyResolver,
@@ -12,6 +12,7 @@ export const CLAWCLAW_VISUAL_EVENT_TYPES = [
12
12
  'visual.player_motion_changed',
13
13
  'visual.player_stopped',
14
14
  'visual.player_resumed',
15
+ 'visual.player_stop_ended',
15
16
  'visual.no_significant_stop',
16
17
  'visual.player_area_changed',
17
18
  'visual.player_position_changed',
@@ -153,6 +154,8 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
153
154
  'poll_error',
154
155
  'error',
155
156
  'game_start_failed',
157
+ 'game_over_recovered',
158
+ 'game_terminal_missing',
156
159
  'game_stream_disconnected',
157
160
  'game_stream_reconnected',
158
161
  'stop_requested',
@@ -57,7 +57,7 @@ export interface EventRepository {
57
57
  releaseLease(lease: ConsumerLease): boolean;
58
58
 
59
59
  sourceCheckpoint(sourceId: string): SourceCheckpointRecord | null;
60
- close?(): void;
60
+ close?(): void | Promise<void>;
61
61
  }
62
62
 
63
63
  export class DeliveryLeaseLostError extends Error {
@@ -44,6 +44,17 @@ import {
44
44
  validateDetailDeliveryVia,
45
45
  } from './types.js';
46
46
 
47
+ export interface EventRepositorySnapshot {
48
+ sessions: PlaySessionRecord[];
49
+ segments: EventSegmentRecord[];
50
+ events: CanonicalEvent[];
51
+ deliveries: EventDeliveryRecord[];
52
+ checkpoints: SourceCheckpointRecord[];
53
+ leases: ConsumerLease[];
54
+ mailboxItems: MailboxItem[];
55
+ nextCommitSeq: number;
56
+ }
57
+
47
58
  function deliveryKey(eventId: string, consumerId: string): string {
48
59
  return `${eventId}\u0000${consumerId}`;
49
60
  }
@@ -82,8 +93,67 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
82
93
  private readonly remoteSequences = new Map<string, string>();
83
94
  private readonly mailboxItems = new Map<string, MailboxItem>();
84
95
  private readonly mailboxUniqueItems = new Map<string, string>();
96
+
97
+ diagnosticCounts(): Readonly<Record<string, number>> {
98
+ return {
99
+ sessions: this.sessions.size,
100
+ segments: this.segments.size,
101
+ events: this.events.size,
102
+ deliveries: this.deliveries.size,
103
+ checkpoints: this.checkpoints.size,
104
+ leases: this.leases.size,
105
+ mailbox_items: this.mailboxItems.size,
106
+ };
107
+ }
85
108
  private nextCommitSeq = 1;
86
109
 
110
+ constructor(snapshot?: EventRepositorySnapshot) {
111
+ if (snapshot) this.restore(snapshot);
112
+ }
113
+
114
+ snapshot(): EventRepositorySnapshot {
115
+ return cloneRecord({
116
+ sessions: [...this.sessions.values()],
117
+ segments: [...this.segments.values()],
118
+ events: this.eventOrder.map((eventId) => this.events.get(eventId)!),
119
+ deliveries: [...this.deliveries.values()],
120
+ checkpoints: [...this.checkpoints.values()],
121
+ leases: [...this.leases.values()],
122
+ mailboxItems: [...this.mailboxItems.values()],
123
+ nextCommitSeq: this.nextCommitSeq,
124
+ });
125
+ }
126
+
127
+ private restore(snapshot: EventRepositorySnapshot): void {
128
+ for (const session of snapshot.sessions) this.sessions.set(session.sessionId, cloneRecord(session));
129
+ for (const segment of snapshot.segments) this.segments.set(segment.segmentId, cloneRecord(segment));
130
+ for (const event of snapshot.events) {
131
+ this.events.set(event.eventId, cloneRecord(event));
132
+ this.eventOrder.push(event.eventId);
133
+ if (event.sourceEventId) this.remoteEventIds.set(sourceEventKey(event.sourceId, event.sourceEventId), event.eventId);
134
+ if (event.sourceSequence) {
135
+ this.remoteSequences.set(
136
+ sourceSequenceKey(event.sourceId, event.sessionId, event.segmentId, event.sourceSequence),
137
+ event.eventId,
138
+ );
139
+ }
140
+ }
141
+ for (const delivery of snapshot.deliveries) {
142
+ this.deliveries.set(deliveryKey(delivery.eventId, delivery.consumerId), cloneRecord(delivery));
143
+ }
144
+ for (const checkpoint of snapshot.checkpoints) {
145
+ this.checkpoints.set(checkpoint.sourceId, cloneRecord(checkpoint));
146
+ }
147
+ for (const lease of snapshot.leases) {
148
+ this.leases.set(leaseKey(lease.consumerId, lease.channel), cloneRecord(lease));
149
+ }
150
+ for (const item of snapshot.mailboxItems) {
151
+ this.mailboxItems.set(item.itemId, cloneRecord(item));
152
+ this.mailboxUniqueItems.set(mailboxUniqueKey(item.consumerId, item.eventId, item.mode), item.itemId);
153
+ }
154
+ this.nextCommitSeq = Math.max(snapshot.nextCommitSeq, 1);
155
+ }
156
+
87
157
  saveSession(session: PlaySessionRecord): void {
88
158
  const existingSession = this.sessions.get(session.sessionId);
89
159
  if (existingSession?.isCurrent && !session.isCurrent) {
@@ -657,7 +727,7 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
657
727
  selected.push(item);
658
728
  }
659
729
 
660
- const claimToken = randomUUID();
730
+ const claimToken = request.claimToken ?? randomUUID();
661
731
  const claimExpiresAtMs = nowMs + Math.max(1, request.leaseTtlMs);
662
732
  const attemptedAt = new Date(nowMs).toISOString();
663
733
  const claimed = selected.map((item) => {
@@ -4,6 +4,7 @@ import { mkdirSync } from 'fs';
4
4
  import { dirname } from 'path';
5
5
  import { loadNodeSqliteModule } from '../load-node-sqlite.js';
6
6
  import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
7
+ import type { EventRepositorySnapshot } from './memory-event-repository.js';
7
8
  import type {
8
9
  AckMailboxClaimRequest,
9
10
  AckMailboxClaimResult,
@@ -294,6 +295,27 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
294
295
  this.db.close();
295
296
  }
296
297
 
298
+ /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
299
+ snapshot(): EventRepositorySnapshot {
300
+ const events = this.db.prepare('SELECT * FROM events ORDER BY commit_seq ASC')
301
+ .all().map(eventFromRow);
302
+ return {
303
+ sessions: this.db.prepare('SELECT * FROM play_sessions').all().map(sessionFromRow),
304
+ segments: this.db.prepare('SELECT * FROM event_segments').all().map(segmentFromRow),
305
+ events,
306
+ deliveries: this.db.prepare('SELECT * FROM event_deliveries').all().map(deliveryFromRow),
307
+ checkpoints: this.db.prepare('SELECT * FROM source_checkpoints').all().map(checkpointFromRow),
308
+ leases: this.db.prepare('SELECT * FROM consumer_leases').all().map((row) => ({
309
+ consumerId: String(row.consumer_id),
310
+ channel: row.channel as ConsumerLease['channel'],
311
+ ownerId: String(row.owner_id),
312
+ expiresAt: numberValue(row.expires_at),
313
+ })),
314
+ mailboxItems: this.db.prepare('SELECT * FROM mailbox_items').all().map(mailboxItemFromRow),
315
+ nextCommitSeq: (events.at(-1)?.commitSeq ?? 0) + 1,
316
+ };
317
+ }
318
+
297
319
  schemaVersion(): number {
298
320
  const row = this.db.prepare('SELECT MAX(version) AS version FROM schema_migrations').get();
299
321
  return numberValue(row?.version);
@@ -1024,7 +1046,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
1024
1046
  }
1025
1047
  const itemIds = selected.map((row) => String(row.item_id));
1026
1048
  const eventIds = selected.map((row) => String(row.event_id));
1027
- const claimToken = randomUUID();
1049
+ const claimToken = request.claimToken ?? randomUUID();
1028
1050
  const claimExpiresAtMs = nowMs + Math.max(1, request.leaseTtlMs);
1029
1051
  const attemptedAt = new Date(nowMs).toISOString();
1030
1052
  this.db.prepare(`
@@ -88,6 +88,8 @@ export interface ClaimMailboxItemsRequest {
88
88
  * coalesceKey matches, so batching never lets a later topic overtake one.
89
89
  */
90
90
  maxItems?: number;
91
+ /** Internal deterministic token used by mirrored persistence stores. */
92
+ claimToken?: string;
91
93
  }
92
94
 
93
95
  export interface MailboxClaim<T = unknown> {
@@ -0,0 +1,24 @@
1
+ import { serialize } from 'node:v8';
2
+
3
+ export const MAX_RUNTIME_MODULE_OUTPUT_BYTES = 1024 * 1024;
4
+
5
+ export interface RuntimeModuleOutputSize {
6
+ readonly bytes: number;
7
+ readonly limitBytes: number;
8
+ }
9
+
10
+ /** Bounds cloneable external-module output before it is copied into the Owner. */
11
+ export function assertRuntimeModuleOutputSize(
12
+ value: unknown,
13
+ code: string,
14
+ limitBytes = MAX_RUNTIME_MODULE_OUTPUT_BYTES,
15
+ ): RuntimeModuleOutputSize {
16
+ let bytes: number;
17
+ try {
18
+ bytes = serialize(value).byteLength;
19
+ } catch {
20
+ throw new Error(`${code}_not_serializable`);
21
+ }
22
+ if (bytes > limitBytes) throw new Error(`${code}_too_large:${bytes}:${limitBytes}`);
23
+ return { bytes, limitBytes };
24
+ }
@@ -0,0 +1,58 @@
1
+ import { parentPort, workerData } from 'worker_threads';
2
+ import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
3
+ import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
4
+ import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
5
+
6
+ interface WorkerPaths {
7
+ eventLedgerPath: string;
8
+ stateHistoryPath: string;
9
+ inputJournalPath: string;
10
+ }
11
+
12
+ interface PersistenceOperation {
13
+ store: 'events' | 'history' | 'input';
14
+ method: string;
15
+ args: unknown[];
16
+ }
17
+
18
+ const paths = workerData as WorkerPaths;
19
+ const opened = SqliteEventRepository.open(paths.eventLedgerPath);
20
+ if (!opened.ok) throw new Error(`${opened.unavailable.code}: ${opened.unavailable.message}`);
21
+ const stores = {
22
+ events: opened.repository,
23
+ history: new SqliteStateHistoryRepository(paths.stateHistoryPath),
24
+ input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
25
+ };
26
+
27
+ parentPort?.on('message', (message: {
28
+ type: 'batch' | 'barrier' | 'close';
29
+ id: number;
30
+ operations?: PersistenceOperation[];
31
+ }) => {
32
+ try {
33
+ if (message.type === 'batch') {
34
+ for (const operation of message.operations ?? []) {
35
+ const store = stores[operation.store] as unknown as Record<string, (...args: unknown[]) => unknown>;
36
+ const method = store[operation.method];
37
+ if (typeof method !== 'function') throw new Error(`Unknown persistence operation: ${operation.store}.${operation.method}`);
38
+ method.apply(store, operation.args);
39
+ }
40
+ parentPort?.postMessage({ type: 'ack', id: message.id });
41
+ return;
42
+ }
43
+ if (message.type === 'barrier') {
44
+ parentPort?.postMessage({ type: 'barrier', id: message.id });
45
+ return;
46
+ }
47
+ stores.history.close();
48
+ stores.input.close();
49
+ stores.events.close();
50
+ parentPort?.postMessage({ type: 'closed', id: message.id });
51
+ } catch (error) {
52
+ parentPort?.postMessage({
53
+ type: 'error',
54
+ id: message.id,
55
+ error: error instanceof Error ? error.message : String(error),
56
+ });
57
+ }
58
+ });