@myclaw163/clawclaw-cli 0.8.16 → 0.8.18

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 +7 -3
  2. package/docs/runtime/owner-lifecycle-and-observability.md +25 -0
  3. package/package.json +1 -1
  4. package/skills/clawclaw/SKILL.md +22 -3
  5. package/skills/clawclaw/references/COMMANDS.md +8 -4
  6. package/src/commands/account.ts +9 -1
  7. package/src/commands/behavior.ts +17 -17
  8. package/src/commands/capability.ts +33 -25
  9. package/src/commands/load.ts +145 -8
  10. package/src/commands/perception.ts +17 -16
  11. package/src/commands/persona.ts +24 -6
  12. package/src/lib/agent-workspace-client.ts +2 -0
  13. package/src/lib/agent-workspace-runtime.ts +10 -2
  14. package/src/lib/agent-workspace-skills.ts +7 -1
  15. package/src/lib/agent-workspace-sync.ts +39 -7
  16. package/src/lib/capability-cloud-presence.ts +179 -0
  17. package/src/lib/capability-cloud-refresh.ts +33 -20
  18. package/src/lib/capability-cloud-sync.ts +94 -7
  19. package/src/lib/capability-selection.ts +62 -0
  20. package/src/lib/capability-workspace.ts +4 -0
  21. package/src/lib/game-client.ts +40 -10
  22. package/src/lib/http-transport.ts +2 -2
  23. package/src/lib/hub-client.ts +75 -0
  24. package/src/lib/persona.ts +14 -1
  25. package/src/pipeline/event-hints.ts +1 -1
  26. package/src/runtime/clawclaw/owner.ts +32 -20
  27. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +33 -6
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -0
  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 +14 -4
  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
@@ -29,6 +29,8 @@ export interface ResourceSummary {
29
29
  isInstalled: boolean;
30
30
  isOfficial: boolean;
31
31
  versionId: string;
32
+ versionNumber?: string;
33
+ versionDescription?: string;
32
34
  }
33
35
 
34
36
  export interface ResourceDetail extends ResourceSummary {
@@ -65,6 +67,13 @@ export interface WorkspaceResourceSummary {
65
67
  versionId: string;
66
68
  equipped: boolean;
67
69
  hasUpdate: boolean;
70
+ kind: 'owned' | 'installed';
71
+ isCreatedByMe: boolean;
72
+ owner: {
73
+ id: string;
74
+ name: string | null;
75
+ isOfficial: boolean;
76
+ };
68
77
  }
69
78
 
70
79
  export interface WorkspaceListResult {
@@ -74,6 +83,13 @@ export interface WorkspaceListResult {
74
83
  limit: number;
75
84
  }
76
85
 
86
+ export interface WorkspaceLoadoutUpdate {
87
+ skillItemIds?: readonly string[];
88
+ strategyItemIds?: readonly string[];
89
+ personaItemIds?: readonly string[];
90
+ perceptionItemIds?: readonly string[];
91
+ }
92
+
77
93
  const BASE = '/api/v1/hub';
78
94
 
79
95
  /** Parse a `<type>/<id>` resource ref. */
@@ -98,6 +114,8 @@ interface RawFileEntry {
98
114
 
99
115
  interface RawVersion {
100
116
  id: string;
117
+ version_number?: string;
118
+ version_description?: string;
101
119
  title: string;
102
120
  description: string;
103
121
  icon_url?: string | null;
@@ -130,6 +148,9 @@ interface RawWorkspaceItem {
130
148
  version_id: string;
131
149
  is_equipped?: boolean;
132
150
  has_update?: boolean;
151
+ kind?: 'owned' | 'installed';
152
+ is_created_by_me?: boolean;
153
+ owner?: { id?: string; name?: string | null; is_official?: boolean };
133
154
  }
134
155
 
135
156
  export interface HubSourceFileUpload {
@@ -181,6 +202,8 @@ function toSummary(resource: RawResource): ResourceSummary {
181
202
  isInstalled: resource.is_installed === true,
182
203
  isOfficial: resource.is_official === true || owner.is_official === true,
183
204
  versionId: version.id,
205
+ versionNumber: version.version_number,
206
+ versionDescription: version.version_description,
184
207
  };
185
208
  }
186
209
 
@@ -296,6 +319,13 @@ export class HubClient {
296
319
  versionId: item.version_id,
297
320
  equipped: item.is_equipped === true,
298
321
  hasUpdate: item.has_update === true,
322
+ kind: item.kind === 'owned' ? 'owned' : 'installed',
323
+ isCreatedByMe: item.is_created_by_me === true,
324
+ owner: {
325
+ id: item.owner?.id ?? '',
326
+ name: item.owner?.name ?? null,
327
+ isOfficial: item.owner?.is_official === true,
328
+ },
299
329
  })),
300
330
  nextCursor: response.data.next_cursor,
301
331
  hasMore: response.data.has_more,
@@ -322,6 +352,42 @@ export class HubClient {
322
352
  return { updated: response.data.updated, versionId: response.data.version_id };
323
353
  }
324
354
 
355
+ async updateWorkspaceEquipment(
356
+ workspaceItemId: string,
357
+ equipped: boolean,
358
+ ): Promise<{ workspaceItemId: string; equipped: boolean; revision: number; changed: boolean }> {
359
+ const response = await this.http.post<Envelope<{
360
+ workspace_item_id: string;
361
+ is_equipped: boolean;
362
+ revision: number;
363
+ changed: boolean;
364
+ }>>(`${BASE}/workspace/equipment/update`, {
365
+ workspace_item_id: workspaceItemId,
366
+ is_equipped: equipped,
367
+ });
368
+ return {
369
+ workspaceItemId: response.data.workspace_item_id,
370
+ equipped: response.data.is_equipped,
371
+ revision: response.data.revision,
372
+ changed: response.data.changed,
373
+ };
374
+ }
375
+
376
+ async updateWorkspaceLoadout(
377
+ input: WorkspaceLoadoutUpdate,
378
+ ): Promise<{ revision: number; changed: boolean }> {
379
+ const body: Record<string, readonly string[]> = {};
380
+ if (input.skillItemIds !== undefined) body.skill_item_ids = input.skillItemIds;
381
+ if (input.strategyItemIds !== undefined) body.strategy_item_ids = input.strategyItemIds;
382
+ if (input.personaItemIds !== undefined) body.persona_item_ids = input.personaItemIds;
383
+ if (input.perceptionItemIds !== undefined) body.perception_item_ids = input.perceptionItemIds;
384
+ const response = await this.http.post<Envelope<{ revision: number; changed: boolean }>>(
385
+ `${BASE}/workspace/loadout/update`,
386
+ body,
387
+ );
388
+ return { revision: response.data.revision, changed: response.data.changed };
389
+ }
390
+
325
391
  async deleteWorkspaceItem(workspaceItemId: string): Promise<void> {
326
392
  await this.http.post(`${BASE}/workspace/delete`, { workspace_item_id: workspaceItemId });
327
393
  }
@@ -384,6 +450,7 @@ export class HubClient {
384
450
  sourceFiles: readonly HubUploadedSourceFile[];
385
451
  packageFileId?: string;
386
452
  forkFromWorkspaceItemId?: string;
453
+ strategyKind?: 'long' | 'short';
387
454
  }): Promise<HubResourceMutationResult> {
388
455
  const response = await this.http.post<Envelope<{
389
456
  resource_id: string;
@@ -391,6 +458,9 @@ export class HubClient {
391
458
  workspace_item_id?: string;
392
459
  }>>(`${BASE}/resources/create`, {
393
460
  resource_type: input.resourceType,
461
+ version_number: '1.0.0',
462
+ version_description: '本地修改同步',
463
+ ...(input.resourceType === 'strategy' ? { strategy_kind: input.strategyKind ?? 'long' } : {}),
394
464
  title: input.title,
395
465
  description: input.description,
396
466
  icon_url: null,
@@ -412,6 +482,8 @@ export class HubClient {
412
482
  description: string;
413
483
  sourceFiles: readonly HubUploadedSourceFile[];
414
484
  packageFileId?: string;
485
+ versionNumber: string;
486
+ strategyKind?: 'long' | 'short';
415
487
  }): Promise<HubResourceMutationResult> {
416
488
  const response = await this.http.post<Envelope<{
417
489
  resource_id: string;
@@ -419,6 +491,9 @@ export class HubClient {
419
491
  }>>(`${BASE}/resources/version/create`, {
420
492
  resource_id: input.resourceId,
421
493
  base_version_id: input.baseVersionId,
494
+ version_number: input.versionNumber,
495
+ version_description: '本地修改同步',
496
+ ...(input.strategyKind ? { strategy_kind: input.strategyKind } : {}),
422
497
  title: input.title,
423
498
  description: input.description,
424
499
  icon_url: null,
@@ -15,6 +15,8 @@ import {
15
15
  resolveLocalAgentWorkspaceWorkingCopyPath,
16
16
  type LocalAgentWorkspaceSnapshot,
17
17
  } from './agent-workspace-sync.js';
18
+ import { filterInactiveAgentWorkspaceSnapshot } from './capability-cloud-presence.js';
19
+ import { capabilityEntryForPath, readCapabilityWorkspaceRegistry, capabilityWorkspacePath } from './capability-workspace.js';
18
20
 
19
21
  export interface PersonaPreset {
20
22
  id: string;
@@ -148,14 +150,25 @@ export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedP
148
150
  if (!profile) throw new Error('Not logged in.');
149
151
  const workspaceDir = getWorkspaceDir();
150
152
  ensureAccountUserDataLayout(workspaceDir, profile);
151
- const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
153
+ const snapshot = filterInactiveAgentWorkspaceSnapshot(
154
+ workspaceDir,
155
+ profile,
156
+ readLocalAgentWorkspaceSnapshot(workspaceDir, profile),
157
+ );
152
158
  const selectedHub = hubPersona(workspaceDir, profile, snapshot);
153
159
  const selection = readPersonaSelection(workspaceDir, profile)
154
160
  ?? (selectedHub ? { source: 'hub' as const } : { source: 'none' as const });
155
161
  if (selection?.source === 'local') {
156
162
  const preset = findPersonaPreset(selection.id, getUserDataAccountPersonasDir(workspaceDir, profile));
163
+ const entry = preset ? capabilityEntryForPath(workspaceDir, profile, 'persona', preset.path) : undefined;
164
+ if (entry?.hub) return selectedHub ?? { path: null, source: 'none' };
165
+ if (entry && entry.selection !== 'equipped') return selectedHub ?? { path: null, source: 'none' };
157
166
  return { path: preset?.path ?? null, source: 'local', id: selection.id };
158
167
  }
168
+ if (selectedHub) return selectedHub;
169
+ const local = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
170
+ .find(entry => entry.type === 'persona' && !entry.hub && entry.selection === 'equipped');
171
+ if (local) return { path: capabilityWorkspacePath(workspaceDir, profile, local), source: 'local', id: local.runtimeId };
159
172
  if (selection?.source === 'none') return { path: null, source: 'none' };
160
173
  return selectedHub ?? { path: null, source: 'none' };
161
174
  }
@@ -104,7 +104,7 @@ function coordPair(x: unknown, y: unknown): string {
104
104
  function roleAssignedHint(event: Record<string, any>): string {
105
105
  const role = text(event.role_display_name ?? event.role_display ?? event.role, '?');
106
106
  const faction = text(event.faction, '?');
107
- return `You are ${role} (${faction}). Read \`references/GAME-MECHANICS.md\` for the exact rules, then tell your user your role, faction, win condition, and first plan.`;
107
+ return `You are ${role} (${faction}). Tell your user your role, faction, win condition, and first plan.`;
108
108
  }
109
109
 
110
110
  function meetingBriefingHint(event: Record<string, any>): string | undefined {
@@ -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,
@@ -93,6 +95,7 @@ import {
93
95
  readLocalAgentWorkspaceSnapshot,
94
96
  resolveLocalAgentWorkspaceSnapshot,
95
97
  } from '../../lib/agent-workspace-sync.js';
98
+ import { filterInactiveAgentWorkspaceSnapshot } from '../../lib/capability-cloud-presence.js';
96
99
  import {
97
100
  listAgentWorkspaceBehaviorSources,
98
101
  listAgentWorkspacePerceptionSources,
@@ -666,7 +669,8 @@ export async function runClawclawOwner(
666
669
  ): Promise<ClawclawSourceCompletion> {
667
670
  let lock: OwnerLock | undefined;
668
671
  let telemetry: ReturnType<typeof createOwnerTelemetryRecorder> | undefined;
669
- let rawWsLog: BufferedRawWsLog | undefined;
672
+ let ingressRawLog: ThreadedWsClientConfig['rawLog'];
673
+ let closeGameSyncTransports: (() => Promise<void>) | undefined;
670
674
  let runtime: ReturnType<typeof createClawclawRuntime> | undefined;
671
675
  let source: ClawclawSourcePlugin | undefined;
672
676
  let mailbox: ClawclawMailboxPlugin | undefined;
@@ -684,6 +688,7 @@ export async function runClawclawOwner(
684
688
  let relayPromise: Promise<void> | undefined;
685
689
  let parentWatch: ParentProcessWatchHandle | undefined;
686
690
  let diagnosticSampleTimer: ReturnType<typeof setInterval> | undefined;
691
+ let processTimingSampler: RuntimeProcessTimingSampler | undefined;
687
692
  let localStopRequested = false;
688
693
  let forceExitTimer: ReturnType<typeof setTimeout> | undefined;
689
694
  const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery);
@@ -704,10 +709,7 @@ export async function runClawclawOwner(
704
709
  const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
705
710
  if (fullDiagnosticsEnabled) {
706
711
  const retention = observabilityRetention();
707
- rawWsLog = new BufferedRawWsLog(
708
- ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)),
709
- retention,
710
- );
712
+ ingressRawLog = { path: ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)), options: retention };
711
713
  telemetry.log('info', 'runtime.raw_ws.capture_started', {
712
714
  max_file_bytes: retention.maxFileBytes,
713
715
  retained_files: retention.retainedFiles,
@@ -718,16 +720,26 @@ export async function runClawclawOwner(
718
720
  apiKey: options.profile.apiKey,
719
721
  agentName: options.profile.agentName,
720
722
  enableWs: true,
721
- 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
+ },
722
729
  });
730
+ closeGameSyncTransports = () => client.closeGameSyncTransports();
723
731
  const workspaceDir = getWorkspaceDir();
724
732
  ensureAccountUserDataLayout(workspaceDir, options.profile);
725
733
  const perceptionConfig = readWorkspacePerceptionConfig();
726
734
  const gameplayConfig = readGameplayConfig(workspaceDir, options.profile);
727
735
  const storedAgentWorkspace = readLocalAgentWorkspaceSnapshot(workspaceDir, options.profile);
728
- const agentWorkspace = storedAgentWorkspace
729
- ? resolveLocalAgentWorkspaceSnapshot(workspaceDir, options.profile, storedAgentWorkspace)
730
- : undefined;
736
+ const agentWorkspace = filterInactiveAgentWorkspaceSnapshot(
737
+ workspaceDir,
738
+ options.profile,
739
+ storedAgentWorkspace
740
+ ? resolveLocalAgentWorkspaceSnapshot(workspaceDir, options.profile, storedAgentWorkspace)
741
+ : undefined,
742
+ );
731
743
  const configurationWarning: ConfigurationWarning = (code, details) => {
732
744
  telemetry?.log('warn', `runtime.configuration.${code}`, details, {
733
745
  component: 'runtime.behavior',
@@ -742,6 +754,7 @@ export async function runClawclawOwner(
742
754
  discoveredLocalCapabilities.behaviors
743
755
  .filter(({ source, entry }) => (
744
756
  entry.selection === 'equipped' && !disabledBehaviors.has(source.id)
757
+ && !agentWorkspace?.items.strategy.some(item => item.resourceId === entry.hub?.resourceId)
745
758
  ))
746
759
  .map(({ source }) => source),
747
760
  agentBehaviorSources,
@@ -774,6 +787,7 @@ export async function runClawclawOwner(
774
787
  const localPerceptionSources = discoveredLocalCapabilities.perceptions
775
788
  .filter(({ source, entry }) => (
776
789
  entry.selection === 'equipped' && !disabledPerceptions.has(source.id)
790
+ && !agentWorkspace?.items.perception.some(item => item.resourceId === entry.hub?.resourceId)
777
791
  ))
778
792
  .map(({ source }) => source);
779
793
  const perceptionSources = mergeAgentWorkspacePerceptionSources(
@@ -818,6 +832,7 @@ export async function runClawclawOwner(
818
832
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
819
833
  });
820
834
  if (fullDiagnosticsEnabled) {
835
+ processTimingSampler = new RuntimeProcessTimingSampler();
821
836
  const sample = (): void => {
822
837
  try {
823
838
  const memory = process.memoryUsage();
@@ -831,6 +846,11 @@ export async function runClawclawOwner(
831
846
  : undefined;
832
847
  telemetry?.log('debug', 'runtime.diagnostics.sample', {
833
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(),
834
854
  process_memory: {
835
855
  rss_bytes: memory.rss,
836
856
  heap_total_bytes: memory.heapTotal,
@@ -1476,6 +1496,7 @@ export async function runClawclawOwner(
1476
1496
  return completion;
1477
1497
  } finally {
1478
1498
  if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer);
1499
+ processTimingSampler?.stop();
1479
1500
  process.off('SIGINT', onSignal);
1480
1501
  process.off('SIGTERM', onSignal);
1481
1502
  if (forceExitTimer) clearTimeout(forceExitTimer);
@@ -1492,16 +1513,7 @@ export async function runClawclawOwner(
1492
1513
  }
1493
1514
  } finally {
1494
1515
  try {
1495
- if (rawWsLog) {
1496
- await rawWsLog.close();
1497
- const stats = rawWsLog.stats();
1498
- telemetry?.log(
1499
- stats.dropped > 0 || stats.failedBatches > 0 ? 'warn' : 'info',
1500
- 'runtime.raw_ws.capture_stopped',
1501
- { ...stats },
1502
- { component: 'runtime.transport' },
1503
- );
1504
- }
1516
+ await closeGameSyncTransports?.();
1505
1517
  await telemetry?.closeWithin(2_000).catch(() => false);
1506
1518
  } finally {
1507
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
@@ -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
@@ -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;
@@ -179,6 +179,7 @@ interface LagSnapshot {
179
179
  }
180
180
 
181
181
  const DEFAULT_PLUGIN_TIMEOUT_MS = 1_000;
182
+ const PLUGIN_START_TIMEOUT_MS = 10_000;
182
183
  const DEFAULT_MAX_CATCH_UP_EPOCHS = 10;
183
184
  const MAX_PLUGIN_IN_FLIGHT = 10;
184
185
  const DEFAULT_RETRY_ATTEMPTS = 3;
@@ -643,9 +644,15 @@ export class RuntimePluginScheduler<
643
644
  for (const layer of this.layers) {
644
645
  await Promise.all(layer.map(async (plugin) => {
645
646
  const startController = new AbortController();
646
- await this.withDeadline(plugin, startController, () => plugin.start?.(
647
- this.context(plugin, scope, startController.signal, 0),
648
- ));
647
+ await this.withDeadline(
648
+ plugin,
649
+ startController,
650
+ () => plugin.start?.(this.context(plugin, scope, startController.signal, 0)),
651
+ undefined,
652
+ false,
653
+ undefined,
654
+ PLUGIN_START_TIMEOUT_MS,
655
+ );
649
656
  const recoverController = new AbortController();
650
657
  await this.withDeadline(
651
658
  plugin,
@@ -754,7 +761,10 @@ export class RuntimePluginScheduler<
754
761
  this.pumpRequested = true;
755
762
  if (this.pumping || this.stopped) return;
756
763
  this.pumping = true;
757
- 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(() => {
758
768
  void this.pump().catch((error) => this.failRuntime(error, 'runtime.scheduler')).finally(() => {
759
769
  this.pumping = false;
760
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 };