@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.
- package/QUICKSTART.md +1 -1
- package/QUICKSTART_OTHER.md +13 -12
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +27 -101
- package/docs/custom-modules/README.md +23 -35
- package/docs/custom-modules/api-reference.md +95 -273
- package/docs/custom-modules/behavior.md +94 -78
- package/docs/custom-modules/examples/auto-escape.ts +5 -5
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +42 -603
- package/docs/custom-modules/skill.md +12 -10
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +16 -17
- package/docs/runtime/agent-notifications.md +42 -12
- package/docs/runtime/behavior-runtime.md +47 -46
- package/docs/runtime/components-and-boundaries.md +70 -28
- package/docs/runtime/events-and-state.md +41 -18
- package/docs/runtime/framework-package.md +73 -0
- package/docs/runtime/official-perception-modules.md +5 -5
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +8 -9
- package/docs/user-guide/README.md +10 -7
- package/docs/user-guide/api-reference.md +81 -164
- package/docs/user-guide/behavior.md +84 -68
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +42 -586
- package/docs/user-guide/skill.md +12 -10
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +20 -23
- package/scripts/enable_ccl_permissions.cjs +4 -0
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/postinstall.mjs +1 -1
- package/scripts/qa-install.mjs +105 -0
- package/scripts/sync-bundled-skill.mjs +35 -28
- package/skills/clawclaw/SKILL.md +53 -57
- package/skills/clawclaw/references/BEHAVIORS.md +43 -83
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +62 -103
- package/skills/clawclaw/references/HUB.md +2 -2
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/skills/clawclaw-creator/SKILL.md +82 -0
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
- package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
- package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
- package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
- package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
- package/src/channel/claude-channel-ipc-server.ts +1 -0
- package/src/cli.ts +4 -2
- package/src/commands/behavior.ts +26 -10
- package/src/commands/capability.ts +17 -14
- package/src/commands/load.ts +5 -3
- package/src/commands/perception.ts +5 -0
- package/src/commands/skill.ts +34 -29
- package/src/commands/strategy.ts +2 -0
- package/src/commands/upgrade.ts +2 -2
- package/src/lib/agent-workspace-skills.ts +20 -13
- package/src/lib/capability-cloud-sync.ts +2 -1
- package/src/lib/capability-discovery.ts +2 -1
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/capability-workspace.ts +2 -1
- package/src/lib/game-client.ts +7 -1
- package/src/lib/package-skills.ts +4 -0
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/skill-host.ts +1 -1
- package/src/lib/workspace-runtime-lock.ts +3 -46
- package/src/pipeline/canonical-event-presentation.ts +23 -124
- package/src/pipeline/event-format.ts +12 -21
- package/src/pipeline/event-hints.ts +6 -6
- package/src/pipeline/game-sync-event-normalization.ts +57 -63
- package/src/runtime/clawclaw/behavior-decision.ts +7 -3
- package/src/runtime/clawclaw/behavior-input.ts +8 -4
- package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
- package/src/runtime/clawclaw/notification-policy.ts +42 -0
- package/src/runtime/clawclaw/notification-turn.ts +19 -0
- package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
- package/src/runtime/clawclaw/owner.ts +47 -9
- package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
- package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
- package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
- package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
- package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
- package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
- package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
- package/src/runtime/clawclaw/runtime-state.ts +11 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
- package/src/runtime/clawclaw/strategy-memory.ts +1 -77
- package/src/runtime/clawclaw-event-catalog.ts +12 -12
- package/src/runtime/framework/action-diagnostics.ts +3 -83
- package/src/runtime/framework/capability-registry.ts +2 -395
- package/src/runtime/framework/contracts.ts +2 -144
- package/src/runtime/framework/control/control-scheduler.ts +2 -1268
- package/src/runtime/framework/control/domain-set.ts +2 -81
- package/src/runtime/framework/control/index.ts +1 -3
- package/src/runtime/framework/control/types.ts +2 -191
- package/src/runtime/framework/control-coordinator.ts +2 -11
- package/src/runtime/framework/events/event-catalog.ts +2 -74
- package/src/runtime/framework/events/event-delivery-service.ts +2 -200
- package/src/runtime/framework/events/event-ingress.ts +2 -99
- package/src/runtime/framework/events/event-repository.ts +2 -82
- package/src/runtime/framework/events/index.ts +2 -7
- package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
- package/src/runtime/framework/events/runtime-resume.ts +2 -20
- package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
- package/src/runtime/framework/events/test-helpers.ts +1 -1
- package/src/runtime/framework/events/types.ts +2 -312
- package/src/runtime/framework/index.ts +3 -7
- package/src/runtime/framework/load-node-sqlite.ts +2 -17
- package/src/runtime/framework/mailbox/coalescer.ts +2 -83
- package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
- package/src/runtime/framework/mailbox/identity.ts +2 -38
- package/src/runtime/framework/mailbox/index.ts +1 -7
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
- package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
- package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
- package/src/runtime/framework/mailbox/types.ts +2 -145
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
- package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
- package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
- package/src/runtime/framework/participation-manager.ts +2 -253
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
- package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
- package/src/runtime/framework/plugins/contracts.ts +2 -396
- package/src/runtime/framework/plugins/index.ts +1 -4
- package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
- package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
- package/src/runtime/framework/runtime.ts +5 -1843
- package/src/runtime/framework/serial-task-queue.ts +2 -14
- package/src/runtime/framework/state/contracts.ts +2 -49
- package/src/runtime/framework/state/current-state-store.ts +2 -184
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
- package/src/runtime/framework/state/freshness.ts +2 -72
- package/src/runtime/framework/state/history/contracts.ts +2 -158
- package/src/runtime/framework/state/history/history-writer.ts +2 -194
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
- package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
- package/src/runtime/framework/state/index.ts +1 -13
- package/src/runtime/framework/state/state-ingress.ts +2 -95
- package/src/runtime/framework/state/state-provider.ts +2 -62
- package/src/runtime/framework/state/types.ts +2 -155
- package/src/runtime/game-sync-ingress-protocol.ts +3 -2
- package/src/runtime/game-sync-ingress-worker.ts +7 -1
- package/src/runtime/game-sync-protocol.ts +64 -4
- package/src/runtime/host-monitor-rate-gate.ts +1 -123
- package/src/runtime/mailbox-host-relay.ts +1 -326
- package/src/runtime/observability/detail-capture.ts +4 -108
- package/src/runtime/observability/process-timing.ts +2 -59
- package/src/runtime/observability/recorder.ts +2 -238
- package/src/runtime/observability/redaction.ts +2 -181
- package/src/runtime/observability/reporter.ts +2 -154
- package/src/runtime/observability/sinks.ts +2 -135
- package/src/runtime/observability/types.ts +2 -92
- package/src/runtime/owner-control.ts +45 -320
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/runtime/threaded-ws-client.ts +11 -2
- package/src/runtime/ws-client.ts +6 -0
- package/src/sdk/behavior-plugin/index.ts +9 -3
- package/src/sdk/index.ts +40 -2
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +3 -1
- package/src/sdk/perception-plugin/module.ts +12 -2
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
- package/src/sdk/strategy-memory.ts +1 -12
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +1 -0
- package/docs/custom-modules/trigger.md +0 -295
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
|
@@ -1,72 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { readFileSync, readlinkSync } from 'node:fs';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
|
|
5
|
-
export interface ProcessIdentity {
|
|
6
|
-
/** OS process creation value, never the time the lock file was written. */
|
|
7
|
-
birth: string;
|
|
8
|
-
startedAtMs: number;
|
|
9
|
-
executable: string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function inspectProcessIdentity(pid: number): ProcessIdentity | null {
|
|
13
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
14
|
-
try {
|
|
15
|
-
if (process.platform === 'win32') {
|
|
16
|
-
const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
|
|
17
|
-
const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
|
|
18
|
-
+ '$t=$p.StartTime.ToUniversalTime(); '
|
|
19
|
-
+ '@{birth=$t.Ticks.ToString();startedAtMs=([DateTimeOffset]$t).ToUnixTimeMilliseconds();executable=$p.ProcessName} | ConvertTo-Json -Compress';
|
|
20
|
-
const output = execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
21
|
-
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
|
|
22
|
-
{ encoding: 'utf8', windowsHide: true, timeout: 5_000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
23
|
-
return JSON.parse(output) as ProcessIdentity;
|
|
24
|
-
}
|
|
25
|
-
if (process.platform === 'linux') {
|
|
26
|
-
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
27
|
-
const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
|
|
28
|
-
const boot = Number(/^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]);
|
|
29
|
-
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2_000 }));
|
|
30
|
-
return { birth: `${boot}:${ticks}`, startedAtMs: (boot + ticks / hz) * 1_000,
|
|
31
|
-
executable: readlinkSync(`/proc/${pid}/exe`) };
|
|
32
|
-
}
|
|
33
|
-
if (process.platform === 'darwin') {
|
|
34
|
-
const options = { encoding: 'utf8' as const, timeout: 2_000, env: { ...process.env, LC_ALL: 'C' } };
|
|
35
|
-
const birth = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'lstart='], options).trim();
|
|
36
|
-
const executable = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'comm='], options).trim();
|
|
37
|
-
const startedAtMs = Date.parse(birth);
|
|
38
|
-
return birth && executable && Number.isFinite(startedAtMs) ? { birth, startedAtMs, executable } : null;
|
|
39
|
-
}
|
|
40
|
-
} catch {}
|
|
41
|
-
return null;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function sameProcessIdentity(a: ProcessIdentity | null, b: ProcessIdentity | null): boolean {
|
|
45
|
-
return !!a && !!b && a.birth === b.birth && a.executable === b.executable;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** Recheck immediately before signalling; a PID alone never authorizes a kill. */
|
|
49
|
-
export function terminateVerifiedProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void {
|
|
50
|
-
if (pid === process.pid || !sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
|
|
51
|
-
throw new Error(`Refusing to terminate an unverified ClawClaw runtime (pid ${pid}).`);
|
|
52
|
-
}
|
|
53
|
-
if (process.platform === 'win32') {
|
|
54
|
-
const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
|
|
55
|
-
if (!/^\d+$/.test(identity.birth)) throw new Error('Invalid Windows process creation identity.');
|
|
56
|
-
// Retain the kernel handle before validating creation time. Killing via that
|
|
57
|
-
// Process object cannot target a later process that happens to reuse the PID.
|
|
58
|
-
// Runtime computation workers are threads of this process, so they exit too.
|
|
59
|
-
const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
|
|
60
|
-
+ `try { $null=$p.Handle; if ($p.StartTime.ToUniversalTime().Ticks.ToString() -ne '${identity.birth}') `
|
|
61
|
-
+ "{ throw 'runtime_identity_changed' }; $p.Kill(); } finally { $p.Dispose() }";
|
|
62
|
-
execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
63
|
-
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
|
|
64
|
-
{ stdio: 'ignore', windowsHide: true, timeout: 5_000 });
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
if (sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
|
|
68
|
-
try { process.kill(pid, signal); } catch (error) {
|
|
69
|
-
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
}
|
|
1
|
+
export * from '@myclaw163/game-agent-runtime/owner/process-identity.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Worker } from 'node:worker_threads';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
3
|
import { WsConnectionState } from '../sdk/types.js';
|
|
4
|
-
import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from './game-sync-protocol.js';
|
|
4
|
+
import { gameSyncPerceptionReportMessage, gameSyncRuntimeReportMessage, type GameSyncPerceptionReport, type GameSyncRuntimeReport } from './game-sync-protocol.js';
|
|
5
5
|
import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
|
|
6
6
|
import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
|
|
7
7
|
|
|
@@ -155,7 +155,16 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
|
|
|
155
155
|
const message = gameSyncPerceptionReportMessage(perceptions);
|
|
156
156
|
if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
|
|
157
157
|
this.pendingReports++;
|
|
158
|
-
this.post({ type: 'report', perceptions });
|
|
158
|
+
this.post({ type: 'report', perceptions: message.data.perceptions, connectionId: this.connectionId });
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
reportRuntime(report: GameSyncRuntimeReport): boolean {
|
|
163
|
+
if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
|
|
164
|
+
const message = gameSyncRuntimeReportMessage(report);
|
|
165
|
+
if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
|
|
166
|
+
this.pendingReports++;
|
|
167
|
+
this.post({ type: 'runtime_report', report: message.data, connectionId: this.connectionId });
|
|
159
168
|
return true;
|
|
160
169
|
}
|
|
161
170
|
|
package/src/runtime/ws-client.ts
CHANGED
|
@@ -13,6 +13,8 @@ import {
|
|
|
13
13
|
parseGameSyncMessage,
|
|
14
14
|
type GameSyncErrorData,
|
|
15
15
|
type GameSyncPerceptionReport,
|
|
16
|
+
gameSyncRuntimeReportMessage,
|
|
17
|
+
type GameSyncRuntimeReport,
|
|
16
18
|
} from './game-sync-protocol.js';
|
|
17
19
|
|
|
18
20
|
export interface GameSyncResumeState {
|
|
@@ -194,6 +196,10 @@ export class WsClient {
|
|
|
194
196
|
return this.send(gameSyncPerceptionReportMessage(perceptions));
|
|
195
197
|
}
|
|
196
198
|
|
|
199
|
+
reportRuntime(report: GameSyncRuntimeReport): boolean {
|
|
200
|
+
return this.send(gameSyncRuntimeReportMessage(report));
|
|
201
|
+
}
|
|
202
|
+
|
|
197
203
|
/**
|
|
198
204
|
* Advance the resume/ACK watermark after the consumer has accepted the frame.
|
|
199
205
|
* The threaded consumer retains it in memory before ACK; this is not a disk flush.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Strategy } from '@myclaw163/game-agent-runtime/sdk/strategy.js';
|
|
1
2
|
import type {
|
|
2
3
|
BehaviorInput,
|
|
3
4
|
BehaviorDecisionAction,
|
|
@@ -217,6 +218,10 @@ export interface BehaviorDelegation {
|
|
|
217
218
|
readonly behavior: string;
|
|
218
219
|
readonly input?: Readonly<Record<string, unknown>>;
|
|
219
220
|
}
|
|
221
|
+
export interface StrategyDelegation {
|
|
222
|
+
readonly strategy: string;
|
|
223
|
+
readonly input?: Readonly<Record<string, unknown>>;
|
|
224
|
+
}
|
|
220
225
|
|
|
221
226
|
/** All semantic effects of one Behavior decision. */
|
|
222
227
|
export interface BehaviorDecision {
|
|
@@ -224,7 +229,7 @@ export interface BehaviorDecision {
|
|
|
224
229
|
readonly status?: Readonly<BehaviorStatus>;
|
|
225
230
|
readonly events?: readonly Readonly<BehaviorEventProposal>[];
|
|
226
231
|
/** Suspends this long Activation and starts one validated short Activation. */
|
|
227
|
-
readonly delegate?: Readonly<BehaviorDelegation>;
|
|
232
|
+
readonly delegate?: Readonly<BehaviorDelegation | StrategyDelegation>;
|
|
228
233
|
/** Ends this Activation after the Decision's preceding effects are committed. */
|
|
229
234
|
readonly finish?: Readonly<BehaviorFinish>;
|
|
230
235
|
}
|
|
@@ -268,7 +273,7 @@ export interface ClawclawBehaviorManifest {
|
|
|
268
273
|
readonly inputs: readonly BehaviorInputFieldSpec[];
|
|
269
274
|
/** Omitted means isolated parallel decide(); serial retains one Activation instance. */
|
|
270
275
|
readonly execution?: BehaviorExecution;
|
|
271
|
-
/**
|
|
276
|
+
/** Legacy input-driven cadence. The fixed-cadence Owner does not use this as a decision gate. */
|
|
272
277
|
readonly everyTicks?: number;
|
|
273
278
|
/** Event types this Behavior may propose. Omit when it produces no custom Events. */
|
|
274
279
|
readonly produces?: readonly string[];
|
|
@@ -308,7 +313,7 @@ export interface BehaviorNormalizationApi {
|
|
|
308
313
|
*/
|
|
309
314
|
export abstract class ClawclawBehavior<
|
|
310
315
|
TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
|
|
311
|
-
> {
|
|
316
|
+
> extends Strategy<BehaviorInput<TInput>, BehaviorReadApi, BehaviorDecision> {
|
|
312
317
|
static readonly manifest?: ClawclawBehaviorManifest;
|
|
313
318
|
|
|
314
319
|
/** Optional one-time normalization. Schema defaults and validation run first. */
|
|
@@ -333,3 +338,4 @@ export interface ClawclawBehaviorClass<
|
|
|
333
338
|
readonly manifest?: ClawclawBehaviorManifest;
|
|
334
339
|
new(): ClawclawBehavior<TInput>;
|
|
335
340
|
}
|
|
341
|
+
export type { ProcessingCycleInfo } from '../module-input/index.js';
|
package/src/sdk/index.ts
CHANGED
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
* · MapRoom / GameResult / WsConnectionState / ActionErrorCode(客户端类型)
|
|
18
18
|
*
|
|
19
19
|
* 自定义模块的基类也可以从根入口导入;希望依赖更小的模块面时,从
|
|
20
|
-
* `
|
|
21
|
-
* `
|
|
20
|
+
* `strategy-plugin` 或 `perception-plugin` 导入。Strategy 使用
|
|
21
|
+
* `StrategyInput`;感知通过 `PerceptionModuleInput` 读取 `ObservationFrame` / `GameState`
|
|
22
22
|
* 数据边界。包内 `src/...` 深路径仍不是公开 API。
|
|
23
23
|
*
|
|
24
24
|
* 新增 / 删除本文件的 export 必须走 minor / major 版本号;字段语义变更同理。
|
|
@@ -96,3 +96,41 @@ export type {
|
|
|
96
96
|
MapRoom, GameResult,
|
|
97
97
|
WsConnectionState, ActionErrorCode,
|
|
98
98
|
} from './types.js';
|
|
99
|
+
|
|
100
|
+
export { ClawclawStrategy, STRATEGY_PLUGIN_API_VERSION } from './strategy-plugin/index.js';
|
|
101
|
+
export type {
|
|
102
|
+
StrategyActivationLayer,
|
|
103
|
+
StrategyBooleanInputField,
|
|
104
|
+
StrategyContinuation,
|
|
105
|
+
StrategyDecide,
|
|
106
|
+
StrategyDecision,
|
|
107
|
+
StrategyDecisionAction,
|
|
108
|
+
StrategyDecisionFrame,
|
|
109
|
+
StrategyDecisionFrameStatus,
|
|
110
|
+
StrategyDelegatedStrategyResult,
|
|
111
|
+
StrategyDelegation,
|
|
112
|
+
StrategyEnumInputField,
|
|
113
|
+
StrategyEventProposal,
|
|
114
|
+
StrategyExecution,
|
|
115
|
+
StrategyFinish,
|
|
116
|
+
StrategyInput,
|
|
117
|
+
StrategyInputFieldSpec,
|
|
118
|
+
StrategyNormalizationApi,
|
|
119
|
+
StrategyNumberInputField,
|
|
120
|
+
StrategyPathQuery,
|
|
121
|
+
StrategyPlayerSeatInputField,
|
|
122
|
+
StrategyPlayerSeatsInputField,
|
|
123
|
+
StrategyReadApi,
|
|
124
|
+
StrategyRuntimeDefaults,
|
|
125
|
+
StrategyScope,
|
|
126
|
+
StrategyStateMode,
|
|
127
|
+
StrategyStatus,
|
|
128
|
+
StrategyStringInputField,
|
|
129
|
+
StrategyStringListInputField,
|
|
130
|
+
StrategyTiming,
|
|
131
|
+
ClawclawStrategyClass,
|
|
132
|
+
ClawclawStrategyManifest,
|
|
133
|
+
FiniteStrategyDecision,
|
|
134
|
+
} from './strategy-plugin/index.js';
|
|
135
|
+
|
|
136
|
+
export type { PerceptionStrategyBinding, PerceptionStrategyActivation } from './perception-plugin/module.js';
|
|
@@ -288,6 +288,8 @@ export interface BehaviorDecisionFrame {
|
|
|
288
288
|
export interface BehaviorInput<
|
|
289
289
|
TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
|
|
290
290
|
> {
|
|
291
|
+
/** Local cadence metadata; backend tick and observation age remain authoritative. */
|
|
292
|
+
readonly cycle?: ProcessingCycleInfo;
|
|
291
293
|
readonly epochId: number;
|
|
292
294
|
readonly scope: Readonly<BehaviorScope>;
|
|
293
295
|
/** Runtime-observed time for this accepted input, suitable for deterministic logic. */
|
|
@@ -303,3 +305,6 @@ export interface BehaviorInput<
|
|
|
303
305
|
/** Present for the first committed decision after delegated short work ends. */
|
|
304
306
|
readonly continuation?: Readonly<BehaviorContinuation>;
|
|
305
307
|
}
|
|
308
|
+
/** Local call timing and the provenance of the latest backend observation; not a State-history API. */
|
|
309
|
+
export type ProcessingCycleInfo = Readonly<Pick<import('../../runtime/framework/plugins/contracts.js').RuntimeCycleInfo,
|
|
310
|
+
'id' | 'intervalMs' | 'nowMs' | 'hasNewState' | 'stateVersion' | 'stateReceivedAtMs' | 'stateAgeMs' | 'connectionState'>>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
|
|
2
2
|
export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
|
|
3
3
|
export * from './module.js';
|
|
4
|
+
import { Perception } from '@myclaw163/game-agent-runtime/sdk/perception.js';
|
|
4
5
|
import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleApi } from './module.js';
|
|
5
6
|
export { ClawclawReaction } from './reaction.js';
|
|
6
7
|
export type { ClawclawReactionManifest, ReactionBehaviorBinding, ReactionActivation, ReactionInput, ReactionResult, ReactionEvent, ReactionFact } from './reaction.js';
|
|
@@ -169,7 +170,7 @@ export interface ClawclawPerceptionManifest {
|
|
|
169
170
|
* retains its original persistent reducer semantics on the compatibility path.
|
|
170
171
|
* A slow call can be terminated without blocking the Runtime Owner.
|
|
171
172
|
*/
|
|
172
|
-
export abstract class ClawclawPerception {
|
|
173
|
+
export abstract class ClawclawPerception extends Perception<PerceptionModuleInput, PerceptionModuleApi, PerceptionModuleResult> {
|
|
173
174
|
static readonly manifest?: ClawclawPerceptionManifest | PerceptionModuleManifest;
|
|
174
175
|
|
|
175
176
|
/** API v3 combines observation, notification and fixed Behavior activation. */
|
|
@@ -246,3 +247,4 @@ export interface ClawclawPerceptionClass {
|
|
|
246
247
|
readonly manifest?: ClawclawPerceptionManifest;
|
|
247
248
|
new(): ClawclawPerception;
|
|
248
249
|
}
|
|
250
|
+
export type { ProcessingCycleInfo } from '../module-input/index.js';
|
|
@@ -7,6 +7,12 @@ import type { StrategyMemory } from '../strategy-memory.js';
|
|
|
7
7
|
|
|
8
8
|
/** Unified perception contract with optional fixed Reflex bindings. */
|
|
9
9
|
export const PERCEPTION_MODULE_API_VERSION = 3 as const;
|
|
10
|
+
export type PerceptionStrategyBinding = ReactionBehaviorBinding;
|
|
11
|
+
export interface PerceptionStrategyActivation {
|
|
12
|
+
readonly strategy: string;
|
|
13
|
+
readonly input?: Readonly<Record<string, unknown>>;
|
|
14
|
+
readonly reason?: string;
|
|
15
|
+
}
|
|
10
16
|
export interface PerceptionModuleManifest {
|
|
11
17
|
readonly apiVersion: typeof PERCEPTION_MODULE_API_VERSION;
|
|
12
18
|
readonly id: string;
|
|
@@ -17,15 +23,18 @@ export interface PerceptionModuleManifest {
|
|
|
17
23
|
readonly produces?: readonly string[];
|
|
18
24
|
readonly inputs?: readonly BehaviorInputFieldSpec[];
|
|
19
25
|
readonly config?: Readonly<Record<string, unknown>>;
|
|
26
|
+
readonly strategies?: Readonly<Record<string, PerceptionStrategyBinding>>;
|
|
20
27
|
readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
|
|
21
28
|
}
|
|
22
29
|
export interface PerceptionModuleInput {
|
|
30
|
+
readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
|
|
23
31
|
readonly moduleId: string;
|
|
24
32
|
readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
|
|
25
33
|
readonly gameState: Readonly<GameState> | null;
|
|
26
34
|
readonly frame: Readonly<ObservationFrame> | null;
|
|
27
|
-
/** Source/backend
|
|
35
|
+
/** Original Source/backend facts only; never another perception's output or a forwarded copy. */
|
|
28
36
|
readonly events: readonly Readonly<ReminderFact>[];
|
|
37
|
+
/** Compared independently against this module's own durable task baseline. */
|
|
29
38
|
readonly taskChanges: readonly ReminderTaskChange[];
|
|
30
39
|
readonly boundary: 'initial' | 'recovery' | null;
|
|
31
40
|
readonly nowMs: number;
|
|
@@ -34,6 +43,7 @@ export interface PerceptionModuleInput {
|
|
|
34
43
|
/** Equipped, loadable dependencies; independent of the automatic-activation switch. */
|
|
35
44
|
readonly availableBindings?: readonly string[];
|
|
36
45
|
readonly availableBehaviors?: readonly string[];
|
|
46
|
+
readonly availableStrategies?: readonly string[];
|
|
37
47
|
readonly enabledBindings?: readonly string[];
|
|
38
48
|
}
|
|
39
49
|
export interface PerceptionModuleApi {
|
|
@@ -51,5 +61,5 @@ export interface PerceptionModuleResult {
|
|
|
51
61
|
readonly state?: unknown;
|
|
52
62
|
readonly events?: readonly PerceptionModuleEvent[];
|
|
53
63
|
/** Keys in manifest.behaviors; never arbitrary strategy names or executable Actions. */
|
|
54
|
-
readonly activations?: readonly ReactionActivation[];
|
|
64
|
+
readonly activations?: readonly (PerceptionStrategyActivation | ReactionActivation)[];
|
|
55
65
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic,
|
|
1
|
+
import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic, ReminderEvent } from './reminder.js';
|
|
2
2
|
|
|
3
|
-
export const
|
|
4
|
-
'ability.ready', 'ability.remaining_uses_changed', 'ability.exhausted', 'tasks_changed',
|
|
3
|
+
export const TASK_LIFECYCLE_FACT_TYPES = [
|
|
5
4
|
'task_started', 'task_progress', 'task_assigned', 'task_completed', 'task_interrupted', 'task_sabotaged',
|
|
5
|
+
] as const;
|
|
6
|
+
export const TASK_REMINDER_FACT_TYPES = [
|
|
7
|
+
...TASK_LIFECYCLE_FACT_TYPES,
|
|
6
8
|
'role_assigned', 'emergency_started', 'emergency_resolved', 'emergency_interrupted', 'meeting_briefing',
|
|
7
9
|
] as const;
|
|
8
10
|
export const REMINDER_FACT_TYPES_BY_TOPIC = {
|
|
@@ -18,6 +20,7 @@ export function isReminderMode(value: unknown): value is ReminderMode {
|
|
|
18
20
|
}
|
|
19
21
|
export function defaultConfig(topic: ReminderTopic): Record<string, ReminderMode> {
|
|
20
22
|
if (topic !== 'tasks') throw new Error('Unsupported reminder topic; countdown and ability notifications are owned by CCL.');
|
|
23
|
+
// removed/updated remain accepted for existing installed v2 configs; this helper does not emit them.
|
|
21
24
|
return { started: 'state_only', progress: 'state_only', added: 'silent', completed: 'silent',
|
|
22
25
|
interrupted: 'wake', sabotaged: 'wake', removed: 'silent', updated: 'silent' };
|
|
23
26
|
}
|
|
@@ -36,37 +39,6 @@ const labels: Record<string, string> = { started: '开始任务', progress: '任
|
|
|
36
39
|
function record(value: unknown): Record<string, unknown> {
|
|
37
40
|
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
38
41
|
}
|
|
39
|
-
function ownFact(fact: ReminderFact, input: ReminderInput): boolean {
|
|
40
|
-
const actor = record(fact.payload.actor);
|
|
41
|
-
const seat = actor.seat ?? fact.payload.actor_seat;
|
|
42
|
-
const name = actor.name ?? fact.payload.actor_name;
|
|
43
|
-
const self = input.gameState?.you?.player;
|
|
44
|
-
if (seat !== undefined && self?.seat !== undefined) return seat === self.seat;
|
|
45
|
-
if (name !== undefined && self?.name !== undefined) return name === self.name;
|
|
46
|
-
return seat === undefined && name === undefined;
|
|
47
|
-
}
|
|
48
|
-
function matches(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
|
|
49
|
-
if (fact.epochId !== change.epochId || (fact.type.startsWith('task_') && !ownFact(fact, input))) return false;
|
|
50
|
-
const p = fact.payload;
|
|
51
|
-
if (p.task_id && change.task.task_id) return p.task_id === change.task.task_id;
|
|
52
|
-
const name = p.task_name;
|
|
53
|
-
if (!name || name !== change.task.name) return false;
|
|
54
|
-
if (p.room && change.task.room && p.room !== change.task.room) return false;
|
|
55
|
-
// Without IDs, only correlate an unambiguous task in this physical frame.
|
|
56
|
-
return input.taskChanges.filter(c => c.epochId === change.epochId && c.task.name === name
|
|
57
|
-
&& (!p.room || !c.task.room || c.task.room === p.room)).length === 1;
|
|
58
|
-
}
|
|
59
|
-
function explained(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
|
|
60
|
-
if (!matches(fact, change, input)) return false;
|
|
61
|
-
if (change.change === 'added') return fact.type === 'task_assigned' || fact.type === 'emergency_started';
|
|
62
|
-
if (change.change === 'removed') return ['task_completed', 'task_sabotaged', 'emergency_resolved', 'emergency_interrupted'].includes(fact.type);
|
|
63
|
-
if (change.change === 'status_changed') {
|
|
64
|
-
if (change.to_status === 'completed') return ['task_completed', 'task_sabotaged'].includes(fact.type);
|
|
65
|
-
if (change.to_status === 'in_progress') return fact.type === 'task_started';
|
|
66
|
-
if (change.from_status === 'in_progress' && change.to_status === 'normal') return fact.type === 'task_interrupted';
|
|
67
|
-
}
|
|
68
|
-
return false;
|
|
69
|
-
}
|
|
70
42
|
/** Nearby speech is a backend fact; only its Agent notification is optional. */
|
|
71
43
|
export function speechReminder(input: ReminderInput): ReminderResult {
|
|
72
44
|
if (Object.keys(input.config).some(key => key !== 'receive')
|
|
@@ -111,13 +83,7 @@ export function defaultReminder(topic: ReminderTopic, input: ReminderInput): Rem
|
|
|
111
83
|
const kind = kinds[fact.type];
|
|
112
84
|
if (kind) emit(kind, `fact:${fact.eventId}`, { ...fact.payload }, fact.eventId);
|
|
113
85
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const kind = change.change === 'added' ? 'added' : change.change === 'removed' ? 'removed'
|
|
117
|
-
: change.change === 'status_changed' && change.to_status === 'in_progress' ? 'started'
|
|
118
|
-
: change.change === 'status_changed' && change.to_status === 'completed' ? 'completed' : 'updated';
|
|
119
|
-
emit(kind, change.key, { ...change.task, change: change.change,
|
|
120
|
-
from_status: change.from_status, to_status: change.to_status }, change.eventId);
|
|
121
|
-
}
|
|
86
|
+
// Task lifecycle facts belong to this helper. State-only list changes stay
|
|
87
|
+
// available as input; emergency lifecycle notifications belong to emergency perception.
|
|
122
88
|
return { events };
|
|
123
89
|
}
|
|
@@ -22,11 +22,12 @@ export interface ReminderTaskChange {
|
|
|
22
22
|
readonly baseline: boolean;
|
|
23
23
|
}
|
|
24
24
|
export interface ReminderInput {
|
|
25
|
+
readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
|
|
25
26
|
readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
|
|
26
27
|
readonly frame: Readonly<ObservationFrame> | null;
|
|
27
28
|
readonly gameState: Readonly<GameState> | null;
|
|
28
29
|
readonly facts: readonly Readonly<ReminderFact>[];
|
|
29
|
-
/**
|
|
30
|
+
/** Module-local comparison of consecutive task snapshots; no cross-perception dependency. */
|
|
30
31
|
readonly taskChanges: readonly ReminderTaskChange[];
|
|
31
32
|
/** Establish private baselines without replaying notifications. */
|
|
32
33
|
readonly boundary: 'initial' | 'recovery' | null;
|
|
@@ -0,0 +1,258 @@
|
|
|
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
|
+
* Each perception owns its comparison baseline. This pure helper publishes no shared Event.
|
|
212
|
+
*/
|
|
213
|
+
export function nextTaskProjection(input: {
|
|
214
|
+
previous: readonly TaskSnapshot[];
|
|
215
|
+
initialized: boolean;
|
|
216
|
+
summary?: Record<string, any> | null;
|
|
217
|
+
events?: readonly Record<string, any>[];
|
|
218
|
+
selfName?: string;
|
|
219
|
+
selfSeat?: number;
|
|
220
|
+
allowUntickedInitialRole?: boolean;
|
|
221
|
+
}): TaskProjectionUpdate {
|
|
222
|
+
const current = tasksFromState(input.summary);
|
|
223
|
+
if (!current) {
|
|
224
|
+
return {
|
|
225
|
+
projection: [...input.previous].map((task) => structuredClone(task)),
|
|
226
|
+
initialized: input.initialized,
|
|
227
|
+
payload: null,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const delta = taskDelta(input.previous, current);
|
|
231
|
+
if (input.initialized && delta.length === 0) {
|
|
232
|
+
return { projection: current, initialized: true, payload: null };
|
|
233
|
+
}
|
|
234
|
+
const selfSeat = input.selfSeat ?? (Number.isInteger(input.summary?.you?.player?.seat)
|
|
235
|
+
? Number(input.summary!.you.player.seat)
|
|
236
|
+
: undefined);
|
|
237
|
+
const selfName = input.selfName ?? nonEmptyString(input.summary?.you?.player?.name);
|
|
238
|
+
const tick = finiteNumber(input.summary?.tick);
|
|
239
|
+
const reason = updateReason(
|
|
240
|
+
input.initialized,
|
|
241
|
+
input.events ?? [],
|
|
242
|
+
selfName,
|
|
243
|
+
selfSeat,
|
|
244
|
+
tick,
|
|
245
|
+
input.allowUntickedInitialRole === true,
|
|
246
|
+
);
|
|
247
|
+
return {
|
|
248
|
+
projection: current,
|
|
249
|
+
initialized: true,
|
|
250
|
+
payload: {
|
|
251
|
+
baseline: !input.initialized,
|
|
252
|
+
...(tick === undefined ? {} : { tick }),
|
|
253
|
+
reason: reason.reason,
|
|
254
|
+
delta,
|
|
255
|
+
tasks: current.map((task) => structuredClone(task)),
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|