@myclaw163/clawclaw-cli 0.8.17 → 0.8.19

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 (39) hide show
  1. package/docs/configuration.md +1 -1
  2. package/docs/runtime/owner-lifecycle-and-observability.md +25 -0
  3. package/package.json +1 -1
  4. package/skills/clawclaw/SKILL.md +3 -1
  5. package/skills/clawclaw/references/BEHAVIORS.md +2 -2
  6. package/skills/clawclaw/references/COMMANDS.md +2 -0
  7. package/src/commands/behavior.ts +3 -0
  8. package/src/commands/load.ts +14 -9
  9. package/src/commands/perception.ts +5 -1
  10. package/src/commands/persona.ts +29 -9
  11. package/src/lib/agent-workspace-runtime.ts +33 -4
  12. package/src/lib/capability-cloud-sync.ts +3 -3
  13. package/src/lib/capability-discovery.ts +6 -1
  14. package/src/lib/capability-operation-name.ts +14 -0
  15. package/src/lib/capability-workspace.ts +14 -1
  16. package/src/lib/game-client.ts +40 -10
  17. package/src/lib/http-transport.ts +2 -2
  18. package/src/lib/persona.ts +13 -2
  19. package/src/runtime/clawclaw/owner.ts +22 -17
  20. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +33 -6
  21. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +4 -2
  22. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -0
  23. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +3 -0
  24. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +1 -1
  25. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +10 -0
  26. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +10 -3
  27. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +1 -1
  28. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +5 -6
  29. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +25 -0
  30. package/src/runtime/framework/capability-registry.ts +31 -1
  31. package/src/runtime/framework/plugins/contracts.ts +2 -0
  32. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +4 -1
  33. package/src/runtime/framework/runtime.ts +5 -0
  34. package/src/runtime/game-sync-ingress-protocol.ts +34 -0
  35. package/src/runtime/game-sync-ingress-worker.ts +153 -0
  36. package/src/runtime/observability/factory.ts +2 -1
  37. package/src/runtime/observability/process-timing.ts +59 -0
  38. package/src/runtime/threaded-ws-client.ts +196 -0
  39. package/src/runtime/ws-client.ts +48 -1
@@ -11,6 +11,7 @@ import {
11
11
  } from 'node:fs';
12
12
  import { join } from 'node:path';
13
13
  import { getHeapStatistics } from 'node:v8';
14
+ import { RuntimeProcessTimingSampler } from '../observability/process-timing.js';
14
15
  import type { AuthProfile } from '../../lib/auth.js';
15
16
  import { GameClient } from '../../lib/game-client.js';
16
17
  import { getProfileRuntimeStateDir, getWorkspaceDir } from '../../lib/init-command.js';
@@ -55,7 +56,8 @@ import {
55
56
  watchParentProcess,
56
57
  type ParentProcessWatchHandle,
57
58
  } from '../parent-process-watch.js';
58
- import { BufferedRawWsLog, ownerRawWsLogPath } from '../raw-ws-log.js';
59
+ import { ownerRawWsLogPath } from '../raw-ws-log.js';
60
+ import type { ThreadedWsClientConfig } from '../threaded-ws-client.js';
59
61
  import {
60
62
  presentCanonicalEventForCclEvents,
61
63
  presentCanonicalEventForDesktop,
@@ -667,7 +669,8 @@ export async function runClawclawOwner(
667
669
  ): Promise<ClawclawSourceCompletion> {
668
670
  let lock: OwnerLock | undefined;
669
671
  let telemetry: ReturnType<typeof createOwnerTelemetryRecorder> | undefined;
670
- let rawWsLog: BufferedRawWsLog | undefined;
672
+ let ingressRawLog: ThreadedWsClientConfig['rawLog'];
673
+ let closeGameSyncTransports: (() => Promise<void>) | undefined;
671
674
  let runtime: ReturnType<typeof createClawclawRuntime> | undefined;
672
675
  let source: ClawclawSourcePlugin | undefined;
673
676
  let mailbox: ClawclawMailboxPlugin | undefined;
@@ -685,6 +688,7 @@ export async function runClawclawOwner(
685
688
  let relayPromise: Promise<void> | undefined;
686
689
  let parentWatch: ParentProcessWatchHandle | undefined;
687
690
  let diagnosticSampleTimer: ReturnType<typeof setInterval> | undefined;
691
+ let processTimingSampler: RuntimeProcessTimingSampler | undefined;
688
692
  let localStopRequested = false;
689
693
  let forceExitTimer: ReturnType<typeof setTimeout> | undefined;
690
694
  const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery);
@@ -705,10 +709,7 @@ export async function runClawclawOwner(
705
709
  const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
706
710
  if (fullDiagnosticsEnabled) {
707
711
  const retention = observabilityRetention();
708
- rawWsLog = new BufferedRawWsLog(
709
- ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)),
710
- retention,
711
- );
712
+ ingressRawLog = { path: ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)), options: retention };
712
713
  telemetry.log('info', 'runtime.raw_ws.capture_started', {
713
714
  max_file_bytes: retention.maxFileBytes,
714
715
  retained_files: retention.retainedFiles,
@@ -719,8 +720,14 @@ export async function runClawclawOwner(
719
720
  apiKey: options.profile.apiKey,
720
721
  agentName: options.profile.agentName,
721
722
  enableWs: true,
722
- rawWsMessageSink: rawWsLog,
723
+ gameSyncIngress: {
724
+ rawLog: ingressRawLog,
725
+ diagnostic: (name, attributes, severity = 'debug') => telemetry?.log(severity, name, attributes, {
726
+ component: 'runtime.transport', scope: runtime?.publicScope(),
727
+ }),
728
+ },
723
729
  });
730
+ closeGameSyncTransports = () => client.closeGameSyncTransports();
724
731
  const workspaceDir = getWorkspaceDir();
725
732
  ensureAccountUserDataLayout(workspaceDir, options.profile);
726
733
  const perceptionConfig = readWorkspacePerceptionConfig();
@@ -825,6 +832,7 @@ export async function runClawclawOwner(
825
832
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
826
833
  });
827
834
  if (fullDiagnosticsEnabled) {
835
+ processTimingSampler = new RuntimeProcessTimingSampler();
828
836
  const sample = (): void => {
829
837
  try {
830
838
  const memory = process.memoryUsage();
@@ -838,6 +846,11 @@ export async function runClawclawOwner(
838
846
  : undefined;
839
847
  telemetry?.log('debug', 'runtime.diagnostics.sample', {
840
848
  sample_interval_ms: FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS,
849
+ node_version: process.version,
850
+ process_platform: process.platform,
851
+ process_arch: process.arch,
852
+ process_uptime_seconds: Math.round(process.uptime()),
853
+ process_timing: processTimingSampler?.sample(),
841
854
  process_memory: {
842
855
  rss_bytes: memory.rss,
843
856
  heap_total_bytes: memory.heapTotal,
@@ -1483,6 +1496,7 @@ export async function runClawclawOwner(
1483
1496
  return completion;
1484
1497
  } finally {
1485
1498
  if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer);
1499
+ processTimingSampler?.stop();
1486
1500
  process.off('SIGINT', onSignal);
1487
1501
  process.off('SIGTERM', onSignal);
1488
1502
  if (forceExitTimer) clearTimeout(forceExitTimer);
@@ -1499,16 +1513,7 @@ export async function runClawclawOwner(
1499
1513
  }
1500
1514
  } finally {
1501
1515
  try {
1502
- if (rawWsLog) {
1503
- await rawWsLog.close();
1504
- const stats = rawWsLog.stats();
1505
- telemetry?.log(
1506
- stats.dropped > 0 || stats.failedBatches > 0 ? 'warn' : 'info',
1507
- 'runtime.raw_ws.capture_stopped',
1508
- { ...stats },
1509
- { component: 'runtime.transport' },
1510
- );
1511
- }
1516
+ await closeGameSyncTransports?.();
1512
1517
  await telemetry?.closeWithin(2_000).catch(() => false);
1513
1518
  } finally {
1514
1519
  lock?.release();
@@ -125,6 +125,17 @@ function deferredAtCommitBoundary(
125
125
  return authority.status === 'deferred' ? authority.result : undefined;
126
126
  }
127
127
 
128
+ /** Release the Action even if preparation or a provider ignores cancellation. */
129
+ function untilAborted<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
130
+ return new Promise<T>((resolve, reject) => {
131
+ const abort = (): void => reject(signal.reason ?? new Error('ACTION_CANCELLED'));
132
+ const cleanup = (): void => signal.removeEventListener('abort', abort);
133
+ operation.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); });
134
+ if (signal.aborted) abort();
135
+ else signal.addEventListener('abort', abort, { once: true });
136
+ });
137
+ }
138
+
128
139
  type AutomatedActionCaller = Extract<ActionCaller, { kind: 'behavior' }>;
129
140
 
130
141
  function isAutomatedCaller(caller: ActionCaller): caller is AutomatedActionCaller {
@@ -559,12 +570,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
559
570
  let actionEndpointStarted = false;
560
571
  const action = { ...admitted.action };
561
572
  try {
573
+ context.signal.throwIfAborted();
562
574
  if (request.audioFile) {
563
- const uploaded = await this.client.uploadAudio(
575
+ const uploaded = await untilAborted(this.client.uploadAudio(
564
576
  request.audioFile.path,
565
577
  undefined,
566
578
  request.audioFile.contentType,
567
- );
579
+ ), context.signal);
568
580
  action.audio_url = uploaded.audio_url;
569
581
  const rejected = this.commitBoundaryRejection(
570
582
  request, scope, admitted.actionId, caller, context,
@@ -582,20 +594,35 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
582
594
  return acknowledgedActionResult(
583
595
  scope,
584
596
  admitted.actionId,
585
- await pending,
597
+ await untilAborted(pending, context.signal),
586
598
  );
587
599
  }
588
- const preparedAction = await this.client.prepareActionForConfirmedSubmission(action as any);
600
+ const preparedAction = await untilAborted(this.client.prepareActionForConfirmedSubmission(action as any), context.signal);
601
+ context.signal.throwIfAborted();
589
602
  const rejected = this.commitBoundaryRejection(
590
603
  request, scope, admitted.actionId, caller, context,
591
604
  );
592
605
  if (rejected) return rejected;
593
- const pending = this.client.submitPreparedActionConfirmed(preparedAction);
606
+ const pending = this.client.submitPreparedActionConfirmed(preparedAction, context.signal);
594
607
  actionEndpointStarted = true;
595
608
  markProviderStartedOrSkipped(true);
596
- const response = await pending;
609
+ const response = await untilAborted(pending, context.signal);
597
610
  return acknowledgedActionResult(scope, admitted.actionId, response);
598
611
  } catch (error) {
612
+ if (context.signal.aborted) {
613
+ if (!actionEndpointStarted) {
614
+ const rejected = deferredAtCommitBoundary(context);
615
+ if (rejected) return rejected;
616
+ }
617
+ const reason = context.signal.reason;
618
+ const code = reason instanceof Error && ['GAME_ENDED', 'ACTION_SCOPE_ENDED'].includes(reason.message)
619
+ ? reason.message : 'ACTION_CANCELLED';
620
+ return actionResult(scope, admitted.actionId, 'failure', undefined, {
621
+ error: { code, message: actionEndpointStarted
622
+ ? 'Action wait cancelled; the backend execution outcome is unknown.'
623
+ : 'Action cancelled before submission.' },
624
+ }, { source: 'local', actionOutcome: actionEndpointStarted ? 'unknown' : 'not_submitted' });
625
+ }
599
626
  return actionResult(scope, admitted.actionId, 'failure', undefined, backendError(error), {
600
627
  source: error instanceof ApiError ? 'backend' : 'transport',
601
628
  actionOutcome: actionEndpointStarted
@@ -95,7 +95,7 @@ function assertSourceParity(
95
95
  manifest: Readonly<ClawclawBehaviorManifest>,
96
96
  source: ResolvedClawclawBehaviorSource,
97
97
  ): void {
98
- if (manifest.id !== source.id) throw new Error('behavior_id_source_mismatch');
98
+ if (manifest.id !== (source.declaredId ?? source.id)) throw new Error('behavior_id_source_mismatch');
99
99
  if (manifest.name !== source.name) throw new Error('behavior_name_source_mismatch');
100
100
  if (manifest.description !== source.description) {
101
101
  throw new Error('behavior_description_source_mismatch');
@@ -143,9 +143,11 @@ export function validateClawclawBehaviorModule(
143
143
  allowReservedProduces: source?.allowReservedProduces,
144
144
  });
145
145
  if (source) assertSourceParity(manifest, source);
146
+ const effectiveManifest = source && source.id !== manifest.id
147
+ ? Object.freeze({ ...manifest, id: source.id }) : manifest;
146
148
  return Object.freeze({
147
149
  BehaviorClass,
148
- manifest,
150
+ manifest: effectiveManifest,
149
151
  ...(source === undefined ? {} : { source }),
150
152
  });
151
153
  }
@@ -833,6 +833,14 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
833
833
  }
834
834
 
835
835
  const current = this.manager.current();
836
+ if (!current) {
837
+ const stack = this.manager.snapshot();
838
+ // An empty host has no activation that will consume this batch later.
839
+ // Drain only this plugin's cursor; canonical Events remain available to
840
+ // other consumers. A suspended long waiting for hand-back still owns
841
+ // its pending Events, even though current() temporarily returns nothing.
842
+ if (!stack.long && !stack.short && !stack.reflex) return this.output(cursor);
843
+ }
836
844
  if (
837
845
  !current
838
846
  || computed.activationId !== current.activationId
@@ -60,6 +60,9 @@ export interface ResolvedClawclawBehaviorSource {
60
60
  /** Optional so a statically identifiable legacy module remains reportable. */
61
61
  readonly apiVersion?: number;
62
62
  readonly id: string;
63
+ /** Host-assigned operation names never change the ID in the source file. */
64
+ readonly declaredId?: string;
65
+ readonly workingCopyPath?: string;
63
66
  readonly name: string;
64
67
  readonly description: string;
65
68
  readonly localizations?: ClawclawResourceLocalizations;
@@ -164,7 +164,7 @@ for (const spec of data.modules) {
164
164
  const manifest = (ModuleClass as any).manifest;
165
165
  if (
166
166
  manifest?.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
167
- || manifest.id !== moduleId
167
+ || manifest.id !== (spec.declaredId ?? moduleId)
168
168
  || manifest.execution !== 'parallel_analysis'
169
169
  ) {
170
170
  throw new Error('perception_analysis_worker_manifest_mismatch');
@@ -14,6 +14,7 @@ import { assertPluginApiVersion } from '../plugin-api-version.js';
14
14
 
15
15
  export interface PerceptionThreadModuleSpec {
16
16
  readonly moduleId: string;
17
+ readonly declaredId?: string;
17
18
  readonly sourceUrl: string;
18
19
  readonly manifest: ResolvedClawclawPerceptionSource['manifest'];
19
20
  }
@@ -40,6 +41,7 @@ export class PerceptionModuleLoader {
40
41
  );
41
42
  return {
42
43
  moduleId: source.id,
44
+ declaredId: source.declaredId,
43
45
  sourceUrl: this.sourceUrl(source),
44
46
  manifest: structuredClone(source.manifest),
45
47
  };
@@ -67,6 +69,14 @@ export class PerceptionModuleLoader {
67
69
  PERCEPTION_PLUGIN_API_VERSION,
68
70
  ModuleClass.manifest?.apiVersion,
69
71
  );
72
+ if (ModuleClass.manifest?.id !== (source.declaredId ?? source.id)) {
73
+ throw new Error('perception_id_source_mismatch');
74
+ }
75
+ if (source.id !== ModuleClass.manifest!.id) {
76
+ const Aliased = class extends (ModuleClass as any) {};
77
+ Object.defineProperty(Aliased, 'manifest', { value: { ...ModuleClass.manifest, id: source.id } });
78
+ return Aliased as unknown as ClawclawPerceptionClass;
79
+ }
70
80
  return ModuleClass;
71
81
  });
72
82
  this.loaded.set(source.id, pending);
@@ -1423,9 +1423,16 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1423
1423
  this.recordModuleTimings(operation, timings);
1424
1424
  this.flushModuleTimingWindows(diagnostic);
1425
1425
  }
1426
- return results.flatMap((result) => (
1427
- result.status === 'fulfilled' ? proposals(result.value) : []
1428
- ));
1426
+ return results.flatMap((result, index) => {
1427
+ if (result.status !== 'fulfilled') return [];
1428
+ const module = modules[index]!;
1429
+ const values = proposals(result.value);
1430
+ // Aliased copies may emit the same source-level dedupe key. Keep their
1431
+ // outputs separate without renaming any public Event type or payload.
1432
+ return module.source?.declaredId && module.source.declaredId !== module.manifest.id
1433
+ ? values.map(value => ({ ...value, dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` }))
1434
+ : values;
1435
+ });
1429
1436
  }
1430
1437
 
1431
1438
  private recordModuleTimings(
@@ -95,7 +95,7 @@ function validateClass(
95
95
  if (
96
96
  !manifest
97
97
  || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
98
- || manifest.id !== spec.moduleId
98
+ || manifest.id !== (spec.declaredId ?? spec.moduleId)
99
99
  || (manifest.execution ?? 'ordered_update')
100
100
  !== (spec.manifest.execution ?? 'ordered_update')
101
101
  || JSON.stringify(manifest.produces) !== JSON.stringify(spec.manifest.produces)
@@ -33,6 +33,8 @@ export interface ResolvedClawclawPerceptionSource {
33
33
  /** Literal source declaration; retained so the loader can diagnose unsupported modules. */
34
34
  readonly apiVersion?: number;
35
35
  readonly id: string;
36
+ readonly declaredId?: string;
37
+ readonly workingCopyPath?: string;
36
38
  readonly name: string;
37
39
  readonly description: string;
38
40
  readonly manifest: ClawclawPerceptionManifest;
@@ -425,20 +427,17 @@ export function listClawclawPerceptionSourcesInDirectory(
425
427
  return [];
426
428
  }
427
429
 
428
- const sources = new Map<string, ResolvedClawclawPerceptionSource>();
430
+ const sources: ResolvedClawclawPerceptionSource[] = [];
429
431
  for (const file of files) {
430
432
  try {
431
433
  const sourcePath = realpathSync(join(root, file));
432
434
  if (!pathInside(root, sourcePath) || dirname(sourcePath) !== root) continue;
433
435
  const source = parseSource(sourcePath, root);
434
436
  if (!source) continue;
435
- // Match Strategy discovery: sorted filenames are deterministic and the
436
- // last declaration wins. Duplicate entries stay recoverable and never
437
- // make Owner terminal.
438
- sources.set(source.id, source);
437
+ sources.push(source);
439
438
  } catch {}
440
439
  }
441
- return [...sources.values()];
440
+ return sources;
442
441
  }
443
442
 
444
443
  /** Lists installed workspace perception classes by reading static manifests only. */
@@ -1453,6 +1453,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1453
1453
  }
1454
1454
 
1455
1455
  private async acceptGameFrame(frame: WsInputFrame): Promise<ClawclawGameTransportStopReason | void> {
1456
+ const sourceStartedAtMs = Date.now();
1456
1457
  const segment = this.requireRuntime().currentSegment();
1457
1458
  if (
1458
1459
  frame.meta.origin === 'snapshot'
@@ -1659,6 +1660,24 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1659
1660
  }
1660
1661
  });
1661
1662
  if (!acceptance) return;
1663
+ const ingress = frame.meta.ingress;
1664
+ if (ingress) {
1665
+ const acceptedAtMs = Date.now();
1666
+ this.diagnostic('runtime.source.frame_admitted', {
1667
+ epoch_seq: acceptance.epoch.epochSeq, source_seq: frame.meta.sourceSeq, domain_tick: frame.meta.domainTick,
1668
+ transport_generation: ingress.transportGeneration,
1669
+ socket_received_at_ms: ingress.socketReceivedAtMs, decoded_at_ms: ingress.decodedAtMs,
1670
+ worker_posted_at_ms: ingress.workerPostedAtMs, owner_received_at_ms: ingress.ownerReceivedAtMs,
1671
+ source_started_at_ms: sourceStartedAtMs, source_accepted_at_ms: acceptedAtMs,
1672
+ decode_ms: ingress.decodeDurationMs,
1673
+ worker_handoff_ms: ingress.ownerReceivedAtMs === undefined || ingress.workerPostedAtMs === undefined
1674
+ ? undefined : Math.max(0, ingress.ownerReceivedAtMs - ingress.workerPostedAtMs),
1675
+ source_queue_ms: ingress.ownerReceivedAtMs === undefined ? undefined : Math.max(0, sourceStartedAtMs - ingress.ownerReceivedAtMs),
1676
+ source_admission_ms: Math.max(0, acceptedAtMs - sourceStartedAtMs),
1677
+ receive_to_admitted_ms: Math.max(0, acceptedAtMs - ingress.socketReceivedAtMs),
1678
+ outstanding_frames: ingress.outstandingFrames, outstanding_bytes: ingress.outstandingBytes,
1679
+ });
1680
+ }
1662
1681
  if (typeof frame.meta.sourceSeq !== 'number') {
1663
1682
  throw new TypeError('GameSync frame sourceSeq must be numeric.');
1664
1683
  }
@@ -2410,6 +2429,12 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2410
2429
  ...(crossedActionSafetyBoundary ? { coalescing: 'forbidden' as const } : {}),
2411
2430
  };
2412
2431
  const acceptance = await this.requireRuntime().acceptInputBatch(acceptedBatch);
2432
+ if (isClawclawRuntimeState(acceptedBatch.state) && acceptedBatch.state.stage === 'ended') {
2433
+ this.requireRuntime().closeActionScope(
2434
+ acceptedBatch.scope,
2435
+ acceptedBatch.sourceId === CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId ? 'ACTION_SCOPE_ENDED' : 'GAME_ENDED',
2436
+ );
2437
+ }
2413
2438
  this.sourceCoalescingBoundaryState = nextBoundaryState;
2414
2439
  this.actionSafetyGeneration = actionSafetyGeneration;
2415
2440
  if (acceptedBatch.state.stage === 'ended') {
@@ -173,6 +173,7 @@ export class ActionRegistry {
173
173
  /** Public lifecycle facade used by the unified Behavior Host. */
174
174
  readonly controls = new ControlCoordinator();
175
175
  private readonly abortController = new AbortController();
176
+ private readonly scopeControllers = new Map<string, AbortController>();
176
177
  private readonly inFlight = new Set<Promise<unknown>>();
177
178
  /** Provider-owned settlements no longer hold a control domain, but shutdown still drains them. */
178
179
  private readonly detachedSettlements = new Set<Promise<unknown>>();
@@ -199,6 +200,31 @@ export class ActionRegistry {
199
200
  this.controls.activateScope(scope);
200
201
  }
201
202
 
203
+ private scopeController(scope: ScopeRef): AbortController {
204
+ const key = JSON.stringify([scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId]);
205
+ let controller = this.scopeControllers.get(key);
206
+ if (!controller) {
207
+ controller = new AbortController();
208
+ this.scopeControllers.set(key, controller);
209
+ }
210
+ return controller;
211
+ }
212
+
213
+ /** Fence this scope permanently; a subsequent game/room scope gets its own signal. */
214
+ closeScope(scope: ScopeRef, reason: string): void {
215
+ this.scopeController(scope).abort(new Error(reason));
216
+ }
217
+
218
+ private closedScopeResult<R>(scope: ScopeRef): ActionResult<R> | undefined {
219
+ const signal = this.scopeController(scope).signal;
220
+ if (!signal.aborted) return undefined;
221
+ return {
222
+ scope, actionId: randomUUID(), status: 'failure', source: 'local',
223
+ actionOutcome: 'not_submitted',
224
+ error: { code: signal.reason.message, message: 'This scope has ended; the Action was not submitted.' },
225
+ };
226
+ }
227
+
202
228
  releaseController(controllerId: string, reason = 'released'): void {
203
229
  this.controls.release(controllerId, { reason });
204
230
  }
@@ -215,6 +241,8 @@ export class ActionRegistry {
215
241
  options: ActionAdmissionOptions = {},
216
242
  ): Promise<ActionResult<R>> {
217
243
  if (this.stopping) throw new Error('Action registry is stopping.');
244
+ const closed = this.closedScopeResult<R>(scope);
245
+ if (closed) return closed;
218
246
  const service = this.services.get(capability);
219
247
  if (!service) throw new Error(`Action capability is not available: ${capability}`);
220
248
  const descriptor = service.describeControl?.(action, scope, caller);
@@ -286,6 +314,8 @@ export class ActionRegistry {
286
314
  handoffWaitMs: descriptor?.handoffTimeoutMs,
287
315
  execute: async (controlContext) => {
288
316
  const revalidate = (): ActionExecutionRevalidation => {
317
+ const closed = this.closedScopeResult<never>(scope);
318
+ if (closed) return { status: 'deferred', result: closed };
289
319
  if (options.isAuthorized && !options.isAuthorized()) {
290
320
  this.controls.release(controllerId, { reason: 'worker_authority_revoked' });
291
321
  return {
@@ -310,7 +340,7 @@ export class ActionRegistry {
310
340
  scope,
311
341
  caller,
312
342
  {
313
- signal: this.abortController.signal,
343
+ signal: AbortSignal.any([this.abortController.signal, this.scopeController(scope).signal]),
314
344
  revalidate,
315
345
  latestAcceptedState: options.latestAcceptedState ?? (() => null),
316
346
  },
@@ -254,6 +254,8 @@ export interface RuntimeSourceContext<
254
254
  TEvent = Record<string, unknown>,
255
255
  > extends RuntimeInputSink<TState, TEvent> {
256
256
  currentSegment(): RuntimeSourceSegment;
257
+ /** A Source-confirmed terminal scope revokes Actions without stopping queries or event delivery. */
258
+ closeActionScope(scope: RuntimeScope, reason: string): void;
257
259
  activateSegment(kind: string, identity?: string): Promise<RuntimeScope>;
258
260
  adoptResumeKey(resumeKey: string): RuntimeScope;
259
261
  updateMode(mode: string): RuntimeScope;
@@ -761,7 +761,10 @@ export class RuntimePluginScheduler<
761
761
  this.pumpRequested = true;
762
762
  if (this.pumping || this.stopped) return;
763
763
  this.pumping = true;
764
- queueMicrotask(() => {
764
+ // Yield to transport/Worker message delivery before launching more CPU work.
765
+ // A self-renewing microtask pump can otherwise prevent newly received State
766
+ // from reaching admission, hiding the backlog from bounded catch-up.
767
+ setImmediate(() => {
765
768
  void this.pump().catch((error) => this.failRuntime(error, 'runtime.scheduler')).finally(() => {
766
769
  this.pumping = false;
767
770
  if (this.pumpRequested && !this.stopped && !this.fatalError) this.requestPump();
@@ -672,6 +672,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
672
672
  this.sourcePlugins.set(plugin.id, { plugin, handle });
673
673
  }
674
674
 
675
+ closeActionScope(scope: RuntimeScope, reason: string): void {
676
+ this.actions.closeScope(scope, reason);
677
+ }
678
+
675
679
  async activateSegment(kind: string, identity?: string): Promise<RuntimeScope> {
676
680
  this.assertOpen();
677
681
  const previous = this.scope();
@@ -1504,6 +1508,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1504
1508
  event_watermark: result.eventWatermark,
1505
1509
  current_scope: isCurrentScope,
1506
1510
  total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
1511
+ received_to_ready_ms: Math.max(0, Date.now() - (milliseconds(epoch.receivedAt) ?? Date.now())),
1507
1512
  intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
1508
1513
  scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
1509
1514
  ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
@@ -0,0 +1,34 @@
1
+ import type { GameSyncPerceptionReport } from './game-sync-protocol.js';
2
+ import type { BufferedRawWsLogOptions, RawWsLogStats } from './raw-ws-log.js';
3
+ import type { WsConnectionState } from '../sdk/types.js';
4
+ import type { GameSyncResumeState, WsCloseInfo, WsInputFrame, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
5
+
6
+ export interface GameSyncIngressConfig {
7
+ url: string;
8
+ apiKey: string;
9
+ resumeState?: GameSyncResumeState;
10
+ reconnectMaxMs?: number;
11
+ ackIntervalMs?: number;
12
+ maxPendingFrames: number;
13
+ maxPendingBytes: number;
14
+ rawLog?: { path: string; options?: BufferedRawWsLogOptions };
15
+ }
16
+
17
+ export type IngressCommand =
18
+ | { type: 'ack'; token: string; immediate: boolean }
19
+ | { type: 'report'; perceptions: readonly GameSyncPerceptionReport[] }
20
+ | { type: 'telemetry_ack' }
21
+ | { type: 'stop' };
22
+
23
+ export type IngressEvent =
24
+ | { type: 'frame'; frame: WsInputFrame }
25
+ | { type: 'opened'; connectionId: string }
26
+ | { type: 'state'; state: WsConnectionState }
27
+ | { type: 'close'; connectionId: string; info: WsCloseInfo }
28
+ | { type: 'protocol'; info: WsProtocolErrorInfo }
29
+ | { type: 'recovery'; info: WsRecoveryStartedInfo }
30
+ | { type: 'connected' }
31
+ | { type: 'failed'; code: string }
32
+ | { type: 'report_done' }
33
+ | { type: 'telemetry'; attributes: Record<string, unknown> }
34
+ | { type: 'stopped'; rawStats?: RawWsLogStats };