@myclaw163/clawclaw-cli 0.9.1 → 0.10.1

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 (216) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +27 -40
  7. package/docs/custom-modules/api-reference.md +132 -273
  8. package/docs/custom-modules/behavior.md +185 -75
  9. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +46 -806
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +18 -19
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +54 -48
  19. package/docs/runtime/components-and-boundaries.md +87 -137
  20. package/docs/runtime/events-and-state.md +52 -17
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +12 -9
  26. package/docs/user-guide/api-reference.md +132 -180
  27. package/docs/user-guide/behavior.md +175 -65
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +46 -789
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +9 -14
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +50 -48
  37. package/skills/clawclaw/references/BEHAVIORS.md +45 -65
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +65 -87
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +49 -104
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +18 -25
  53. package/src/commands/module-runtime-control.ts +113 -0
  54. package/src/commands/perception.ts +23 -4
  55. package/src/commands/strategy.ts +2 -0
  56. package/src/commands/trigger.ts +1 -1
  57. package/src/lib/capability-load-diagnostics.ts +3 -3
  58. package/src/lib/perception-config.ts +18 -6
  59. package/src/lib/runtime-cadence-config.ts +16 -0
  60. package/src/lib/workspace-runtime-lock.ts +3 -46
  61. package/src/pipeline/canonical-event-presentation.ts +23 -124
  62. package/src/pipeline/event-format.ts +12 -21
  63. package/src/pipeline/event-hints.ts +6 -6
  64. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  65. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  66. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  67. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  68. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  69. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  70. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  71. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  72. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  73. package/src/runtime/clawclaw/owner.ts +67 -8
  74. package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
  75. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  76. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  77. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  78. package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
  79. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  82. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  83. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  84. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
  85. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
  86. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  87. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  88. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  89. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
  90. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
  91. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
  92. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  93. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  94. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  95. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
  96. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  97. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  98. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  99. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  100. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  101. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  102. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  103. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  104. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  105. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  106. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  107. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
  108. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
  109. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
  110. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
  111. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
  112. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  113. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
  114. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  115. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  116. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  117. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  118. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
  119. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  120. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  121. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  122. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  123. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  124. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  125. package/src/runtime/clawclaw/runtime-state.ts +12 -1
  126. package/src/runtime/clawclaw/runtime.ts +11 -3
  127. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
  128. package/src/runtime/clawclaw/strategy-memory.ts +1 -0
  129. package/src/runtime/clawclaw-event-catalog.ts +17 -17
  130. package/src/runtime/framework/action-diagnostics.ts +3 -83
  131. package/src/runtime/framework/capability-registry.ts +2 -395
  132. package/src/runtime/framework/contracts.ts +2 -144
  133. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  134. package/src/runtime/framework/control/domain-set.ts +2 -81
  135. package/src/runtime/framework/control/index.ts +1 -3
  136. package/src/runtime/framework/control/types.ts +2 -191
  137. package/src/runtime/framework/control-coordinator.ts +2 -11
  138. package/src/runtime/framework/events/event-catalog.ts +2 -74
  139. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  140. package/src/runtime/framework/events/event-ingress.ts +2 -99
  141. package/src/runtime/framework/events/event-repository.ts +2 -82
  142. package/src/runtime/framework/events/index.ts +2 -7
  143. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  144. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  145. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  146. package/src/runtime/framework/events/test-helpers.ts +1 -1
  147. package/src/runtime/framework/events/types.ts +2 -312
  148. package/src/runtime/framework/index.ts +3 -7
  149. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  150. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  151. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  152. package/src/runtime/framework/mailbox/identity.ts +2 -38
  153. package/src/runtime/framework/mailbox/index.ts +1 -7
  154. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  155. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  156. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  157. package/src/runtime/framework/mailbox/types.ts +2 -145
  158. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  159. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  160. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  161. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  162. package/src/runtime/framework/participation-manager.ts +2 -253
  163. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  164. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  165. package/src/runtime/framework/plugins/contracts.ts +2 -388
  166. package/src/runtime/framework/plugins/index.ts +1 -4
  167. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  168. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  169. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
  170. package/src/runtime/framework/runtime.ts +5 -1843
  171. package/src/runtime/framework/serial-task-queue.ts +2 -14
  172. package/src/runtime/framework/state/contracts.ts +2 -49
  173. package/src/runtime/framework/state/current-state-store.ts +2 -184
  174. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  175. package/src/runtime/framework/state/freshness.ts +2 -72
  176. package/src/runtime/framework/state/history/contracts.ts +2 -158
  177. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  178. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  179. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  180. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  181. package/src/runtime/framework/state/index.ts +1 -13
  182. package/src/runtime/framework/state/state-ingress.ts +2 -95
  183. package/src/runtime/framework/state/state-provider.ts +2 -62
  184. package/src/runtime/framework/state/types.ts +2 -155
  185. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  186. package/src/runtime/mailbox-host-relay.ts +1 -326
  187. package/src/runtime/observability/detail-capture.ts +4 -108
  188. package/src/runtime/observability/process-timing.ts +2 -59
  189. package/src/runtime/observability/recorder.ts +2 -238
  190. package/src/runtime/observability/redaction.ts +2 -181
  191. package/src/runtime/observability/reporter.ts +2 -154
  192. package/src/runtime/observability/sinks.ts +2 -135
  193. package/src/runtime/observability/types.ts +2 -92
  194. package/src/runtime/owner-control.ts +45 -315
  195. package/src/runtime/parent-process-watch.ts +1 -51
  196. package/src/runtime/process-identity.ts +1 -72
  197. package/src/sdk/behavior-plugin/index.ts +13 -4
  198. package/src/sdk/index.ts +44 -3
  199. package/src/sdk/module-input/index.ts +5 -0
  200. package/src/sdk/perception-plugin/index.ts +9 -5
  201. package/src/sdk/perception-plugin/module.ts +25 -6
  202. package/src/sdk/perception-plugin/reaction.ts +1 -1
  203. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  204. package/src/sdk/perception-plugin/reminder.ts +2 -1
  205. package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
  206. package/src/sdk/strategy-memory.ts +1 -0
  207. package/src/sdk/strategy-plugin/index.ts +36 -0
  208. package/src/sdk/trigger-plugin/index.ts +4 -3
  209. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  210. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  211. package/docs/custom-modules/trigger.md +0 -295
  212. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  213. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
  214. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
  215. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  216. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -1,135 +1,2 @@
1
- import { appendFile, mkdir, readdir, rename, rm, stat } from 'fs/promises';
2
- import { basename, dirname, join } from 'path';
3
- import type { ObservabilityRecord, ObservabilitySink } from './types.js';
4
-
5
- function hasErrorCode(error: unknown, code: string): boolean {
6
- return !!error && typeof error === 'object' && (error as NodeJS.ErrnoException).code === code;
7
- }
8
-
9
- export interface JsonlObservabilitySinkOptions {
10
- maxFileBytes?: number;
11
- retainedFiles?: number;
12
- }
13
-
14
- /** Owner-only local diagnostic journal. Records arrive already redacted. */
15
- export class JsonlObservabilitySink implements ObservabilitySink {
16
- readonly id = 'local-jsonl';
17
- readonly filePath: string;
18
-
19
- private readonly maxFileBytes: number;
20
- private readonly retainedFiles: number;
21
- private operation: Promise<void> = Promise.resolve();
22
- private closed = false;
23
- private retentionPrepared = false;
24
-
25
- constructor(filePath: string, options: JsonlObservabilitySinkOptions = {}) {
26
- this.filePath = filePath;
27
- this.maxFileBytes = Math.max(64 * 1024, options.maxFileBytes ?? 10 * 1024 * 1024);
28
- this.retainedFiles = Math.max(1, options.retainedFiles ?? 5);
29
- }
30
-
31
- write(records: readonly ObservabilityRecord[]): Promise<void> {
32
- if (this.closed) return Promise.reject(new Error('observability_sink_closed'));
33
- if (records.length === 0) return this.operation;
34
- const data = records.map((record) => JSON.stringify(record)).join('\n') + '\n';
35
- const next = this.operation.then(async () => {
36
- await mkdir(dirname(this.filePath), { recursive: true });
37
- if (!this.retentionPrepared) {
38
- await this.pruneExcessHistory();
39
- this.retentionPrepared = true;
40
- }
41
- await this.rotateIfNeeded(Buffer.byteLength(data));
42
- await appendFile(this.filePath, data, { encoding: 'utf8', mode: 0o600 });
43
- });
44
- this.operation = next.catch(() => {});
45
- return next;
46
- }
47
-
48
- async close(): Promise<void> {
49
- this.closed = true;
50
- await this.operation;
51
- }
52
-
53
- private async rotateIfNeeded(incomingBytes: number): Promise<void> {
54
- let size = 0;
55
- try {
56
- size = (await stat(this.filePath)).size;
57
- } catch (error) {
58
- if (!hasErrorCode(error, 'ENOENT')) throw error;
59
- }
60
- if (size === 0 || size + incomingBytes <= this.maxFileBytes) return;
61
- await rm(`${this.filePath}.${this.retainedFiles}`, { force: true });
62
- for (let index = this.retainedFiles - 1; index >= 1; index -= 1) {
63
- try {
64
- await this.renameFile(`${this.filePath}.${index}`, `${this.filePath}.${index + 1}`);
65
- } catch (error) {
66
- // Sparse history is normal. Permission, lock and filesystem errors are
67
- // not: appending after one of those would make retention unbounded.
68
- if (!hasErrorCode(error, 'ENOENT')) throw error;
69
- }
70
- }
71
- // stat() just proved the active file exists. Any failure here must abort
72
- // this write so the reporter can retain/retry the batch instead of growing
73
- // the already-full active file indefinitely.
74
- await this.renameFile(this.filePath, `${this.filePath}.1`);
75
- }
76
-
77
- private async pruneExcessHistory(): Promise<void> {
78
- const directory = dirname(this.filePath);
79
- const prefix = `${basename(this.filePath)}.`;
80
- const entries = await readdir(directory);
81
- await Promise.all(entries.map(async (entry) => {
82
- if (!entry.startsWith(prefix)) return;
83
- const suffix = entry.slice(prefix.length);
84
- if (!/^\d+$/.test(suffix) || Number(suffix) <= this.retainedFiles) return;
85
- await rm(join(directory, entry), { force: true });
86
- }));
87
- }
88
-
89
- /** Protected seam for platform adapters and deterministic failure tests. */
90
- protected renameFile(source: string, destination: string): Promise<void> {
91
- return rename(source, destination);
92
- }
93
- }
94
-
95
- /**
96
- * Fan-out boundary for local storage plus future reporters. A partial sink
97
- * failure does not make a successful durable sink repeat its records.
98
- */
99
- export class CompositeObservabilitySink implements ObservabilitySink {
100
- readonly id = 'composite';
101
- private readonly sinks: ObservabilitySink[];
102
- private readonly onSinkError?: (sinkId: string, error: unknown) => void;
103
-
104
- constructor(
105
- sinks: Iterable<ObservabilitySink>,
106
- options: { onSinkError?: (sinkId: string, error: unknown) => void } = {},
107
- ) {
108
- this.sinks = [...sinks];
109
- if (this.sinks.length === 0) throw new Error('observability_sink_required');
110
- this.onSinkError = options.onSinkError;
111
- }
112
-
113
- async write(records: readonly ObservabilityRecord[]): Promise<void> {
114
- const results = await Promise.allSettled(this.sinks.map(
115
- (sink) => Promise.resolve().then(() => sink.write(records)),
116
- ));
117
- let successes = 0;
118
- results.forEach((result, index) => {
119
- if (result.status === 'fulfilled') successes += 1;
120
- else {
121
- try { this.onSinkError?.(this.sinks[index]!.id, result.reason); } catch {}
122
- }
123
- });
124
- if (successes === 0) throw new AggregateError(
125
- results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map((result) => result.reason),
126
- 'all_observability_sinks_failed',
127
- );
128
- }
129
-
130
- async close(): Promise<void> {
131
- await Promise.allSettled(this.sinks.map(
132
- (sink) => Promise.resolve().then(() => sink.close?.()),
133
- ));
134
- }
135
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/sinks.js';
@@ -1,92 +1,2 @@
1
- export const OBSERVABILITY_SCHEMA = 'ccl.observability.v1' as const;
2
-
3
- export type ObservabilityKind = 'log' | 'metric' | 'error';
4
- export type ObservabilitySeverity = 'debug' | 'info' | 'warn' | 'error';
5
- export type ObservabilityProcessRole = 'owner' | 'cli';
6
-
7
- /** Logical game scope only. Account credentials and player-facing payloads do not belong here. */
8
- export interface ObservabilityScope {
9
- adapterId?: string;
10
- sessionId?: string;
11
- segmentId?: string;
12
- segmentSeq?: number;
13
- connectionId?: string;
14
- }
15
-
16
- export interface ObservabilityCorrelation {
17
- commandId?: string;
18
- requestId?: string;
19
- actionId?: string;
20
- behaviorActivationId?: string;
21
- behaviorActivationGeneration?: number;
22
- traceId?: string;
23
- parentRecordId?: string;
24
- }
25
-
26
- export interface ObservabilityProcess {
27
- role: ObservabilityProcessRole;
28
- pid: number;
29
- }
30
-
31
- export interface ObservabilityMetric {
32
- value: number;
33
- unit?: string;
34
- aggregation?: 'counter' | 'gauge' | 'histogram_sample';
35
- }
36
-
37
- export interface ObservabilityError {
38
- name?: string;
39
- code?: string;
40
- message?: string;
41
- stack?: string;
42
- cause?: unknown;
43
- }
44
-
45
- export interface ObservabilityRecord {
46
- schema: typeof OBSERVABILITY_SCHEMA;
47
- recordId: string;
48
- timestamp: string;
49
- kind: ObservabilityKind;
50
- name: string;
51
- severity: ObservabilitySeverity;
52
- component: string;
53
- process: ObservabilityProcess;
54
- scope?: ObservabilityScope;
55
- correlation?: ObservabilityCorrelation;
56
- attributes: Record<string, unknown>;
57
- metric?: ObservabilityMetric;
58
- error?: ObservabilityError;
59
- }
60
-
61
- export interface RecordTelemetryInput {
62
- kind: ObservabilityKind;
63
- name: string;
64
- severity?: ObservabilitySeverity;
65
- component?: string;
66
- scope?: ObservabilityScope;
67
- correlation?: ObservabilityCorrelation;
68
- attributes?: Record<string, unknown>;
69
- metric?: ObservabilityMetric;
70
- error?: ObservabilityError | Error | unknown;
71
- }
72
-
73
- export interface ObservabilityReporterStats {
74
- accepted: number;
75
- dropped: number;
76
- flushed: number;
77
- failedBatches: number;
78
- queued: number;
79
- }
80
-
81
- export interface ObservabilityReporter {
82
- enqueue(record: ObservabilityRecord): boolean;
83
- flush(): Promise<void>;
84
- close(): Promise<void>;
85
- stats(): ObservabilityReporterStats;
86
- }
87
-
88
- export interface ObservabilitySink {
89
- readonly id: string;
90
- write(records: readonly ObservabilityRecord[]): Promise<void>;
91
- close?(): Promise<void>;
92
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/types.js';
@@ -1,332 +1,62 @@
1
- import { createHash, randomBytes } from 'crypto';
2
- import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync } from 'fs';
3
- import { tmpdir } from 'os';
4
- import { join } from 'path';
5
- import { connect, createServer, type Server, type Socket } from 'net';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
6
3
  import type { AuthProfile } from '../lib/auth.js';
7
4
  import { getProfileRuntimeStateDir } from '../lib/init-command.js';
8
- import type { TelemetryRecorder } from './observability/index.js';
9
-
10
- export const GAME_START_RUNTIME_FILE = 'game-start.json';
11
- export const OWNER_CONTROL_TIMEOUT_MS = 2000;
12
- const MAX_CONTROL_REQUEST_BYTES = 1024 * 1024;
13
- const MAX_CONTROL_CONNECTIONS = 64;
14
- // Capture protocol primitives so runtime modules cannot rewrite authenticated
15
- // owner-control requests by monkey-patching global JSON.
5
+ import { startOwnerControlServer as startControlServer, sendControlRequest, OWNER_CONTROL_TIMEOUT_MS } from '@myclaw163/game-agent-runtime/owner/control-channel.js';
6
+ import type { OwnerControlRequest as CoreRequest, OwnerControlRequestContext, OwnerControlResponse, OwnerControlServerOptions, OwnerControlServer } from '@myclaw163/game-agent-runtime/owner/control-channel.js';
7
+ export { OWNER_CONTROL_TIMEOUT_MS };
8
+ export type { OwnerControlInfo, OwnerControlRequestContext, OwnerControlResponse, OwnerControlServerOptions, OwnerControlServer } from '@myclaw163/game-agent-runtime/owner/control-channel.js';
16
9
  const SAFE_JSON_PARSE = JSON.parse.bind(JSON) as typeof JSON.parse;
17
- const SAFE_JSON_STRINGIFY = JSON.stringify.bind(JSON) as typeof JSON.stringify;
18
-
19
- export type MasterOwnerControlType =
20
- | 'quit'
21
- | 'leave'
22
- | 'stop'
23
- | 'training_mode'
24
- | 'training_role_lock'
25
- | 'training_role_clear'
26
- | 'switch_strategy'
27
- | 'update_strategy_control'
28
- | 'snapshot'
29
- | 'action'
30
- | 'mailbox_claim'
31
- | 'mailbox_ack'
32
- | 'mailbox_nack'
33
- | 'mailbox_events_prepare'
34
- | 'mailbox_events_ack'
35
- | 'mailbox_events_release'
36
- | 'behavior_start'
37
- | 'behavior_status'
38
- | 'behavior_cancel'
39
- | 'behavior_fallback'
40
- | 'behavior_idle'
41
- | 'trigger_configure'
42
- | 'intent_start'
43
- | 'intent_status'
44
- | 'intent_cancel';
45
-
46
- export type HostRelayOwnerControlType =
47
- | 'mailbox_claim'
48
- | 'mailbox_ack'
49
- | 'mailbox_nack';
50
-
10
+ export const GAME_START_RUNTIME_FILE = 'game-start.json';
11
+ export type MasterOwnerControlType = 'quit' | 'leave' | 'stop' | 'training_mode' | 'training_role_lock' | 'training_role_clear' | 'switch_strategy' | 'update_strategy_control' | 'snapshot' | 'action' | 'mailbox_claim' | 'mailbox_ack' | 'mailbox_nack' | 'mailbox_events_prepare' | 'mailbox_events_ack' | 'mailbox_events_release' | 'perception_update' | 'perception_status' | 'behavior_watch' | 'behavior_unwatch' | 'behavior_update' | 'behavior_start' | 'behavior_status' | 'behavior_cancel' | 'behavior_fallback' | 'behavior_idle' | 'trigger_configure' | 'intent_start' | 'intent_status' | 'intent_cancel';
12
+ export type HostRelayOwnerControlType = 'mailbox_claim' | 'mailbox_ack' | 'mailbox_nack';
51
13
  export type OwnerControlType = MasterOwnerControlType;
52
-
53
- export interface OwnerControlInfo {
54
- kind: 'node-net-socket';
55
- path: string;
56
- }
57
-
58
- export interface OwnerControlRequest {
59
- token?: string;
60
- relay_token?: string;
61
- type?: OwnerControlType;
62
- strategy?: string;
63
- args?: string[];
64
- [key: string]: any;
65
- }
66
-
67
- export interface OwnerControlResponse {
68
- ok: boolean;
69
- type?: string;
70
- error?: string;
71
- message?: string;
72
- [key: string]: any;
14
+ export interface OwnerControlRequest extends CoreRequest {
15
+ type?: OwnerControlType;
73
16
  }
74
-
75
- export type OwnerControlRequestContext =
76
- | { principal: 'master' }
77
- | { principal: 'host_relay' };
78
-
79
- export interface OwnerControlServerOptions {
80
- observability?: TelemetryRecorder;
81
- }
82
-
83
- export interface OwnerControlServer {
84
- control: OwnerControlInfo;
85
- /** Master authority for short CLI commands only. Never pass this to workers. */
86
- token: string;
87
- /** Narrow Mailbox-only authority for disposable Host Relays. */
88
- relayToken: string;
89
- close: () => Promise<void>;
90
- }
91
-
92
17
  export function gameStartRuntimePath(stateDir: string): string {
93
- return join(stateDir, GAME_START_RUNTIME_FILE);
18
+ return join(stateDir, GAME_START_RUNTIME_FILE);
94
19
  }
95
-
96
20
  export function readGameStartRuntime(stateDir: string): Record<string, any> | null {
97
- const runtimePath = gameStartRuntimePath(stateDir);
98
- if (!existsSync(runtimePath)) return null;
99
- try {
100
- return SAFE_JSON_PARSE(readFileSync(runtimePath, 'utf8'));
101
- } catch {}
102
- return null;
103
- }
104
-
105
- function ownerControlPath(stateDir: string, pid: number, nonce: string): string {
106
- const hash = createHash('sha1').update(stateDir).digest('hex').slice(0, 12);
107
- if (process.platform === 'win32') return `\\\\.\\pipe\\clawclaw-${hash}-${pid}-${nonce}`;
108
- const userId = typeof process.getuid === 'function' ? String(process.getuid()) : hash;
109
- const dir = join(tmpdir(), `clawclaw-${userId}`);
110
- mkdirSync(dir, { recursive: true, mode: 0o700 });
111
- try { chmodSync(dir, 0o700); } catch {}
112
- return join(dir, `${hash}-${pid}-${nonce}.sock`);
21
+ const runtimePath = gameStartRuntimePath(stateDir);
22
+ if (!existsSync(runtimePath))
23
+ return null;
24
+ try {
25
+ return SAFE_JSON_PARSE(readFileSync(runtimePath, 'utf8'));
26
+ }
27
+ catch { }
28
+ return null;
29
+ }
30
+ export function startOwnerControlServer(stateDir: string, onRequest: (request: OwnerControlRequest, context: OwnerControlRequestContext) => Promise<OwnerControlResponse> | OwnerControlResponse, options: OwnerControlServerOptions = {}): Promise<OwnerControlServer> {
31
+ return startControlServer(stateDir, (request, context) => onRequest(request as OwnerControlRequest, context), { ...options, namespace: 'clawclaw', relayCommands: ['mailbox_claim', 'mailbox_ack', 'mailbox_nack'] });
113
32
  }
114
-
115
- function safeRequest(request: OwnerControlRequest): OwnerControlRequest {
116
- const {
117
- token: _token,
118
- relay_token: _relayToken,
119
- ...rest
120
- } = request;
121
- return rest;
122
- }
123
-
124
- function sendLine(socket: import('net').Socket, value: OwnerControlResponse): void {
125
- socket.end(`${SAFE_JSON_STRINGIFY(value)}\n`);
126
- }
127
-
128
- export async function startOwnerControlServer(
129
- stateDir: string,
130
- onRequest: (
131
- request: OwnerControlRequest,
132
- context: OwnerControlRequestContext,
133
- ) => Promise<OwnerControlResponse> | OwnerControlResponse,
134
- options: OwnerControlServerOptions = {},
135
- ): Promise<OwnerControlServer> {
136
- const token = randomBytes(24).toString('hex');
137
- const relayToken = randomBytes(24).toString('hex');
138
- const path = ownerControlPath(stateDir, process.pid, randomBytes(8).toString('hex'));
139
- if (process.platform !== 'win32') {
140
- try { unlinkSync(path); } catch {}
141
- }
142
-
143
- const sockets = new Set<Socket>();
144
- const server: Server = createServer((socket) => {
145
- sockets.add(socket);
146
- socket.on('error', () => {});
147
- socket.once('close', () => sockets.delete(socket));
148
- socket.setTimeout(OWNER_CONTROL_TIMEOUT_MS, () => socket.destroy());
149
- let buffer = '';
150
- let handled = false;
151
- const respond = (value: OwnerControlResponse): void => {
152
- sendLine(socket, value);
153
- };
154
- socket.setEncoding('utf8');
155
- socket.on('data', (chunk) => {
156
- if (handled) return;
157
- buffer += chunk;
158
- if (Buffer.byteLength(buffer, 'utf8') > MAX_CONTROL_REQUEST_BYTES) {
159
- handled = true;
160
- respond({ ok: false, error: 'owner_control_request_too_large' });
161
- return;
162
- }
163
- const nl = buffer.indexOf('\n');
164
- if (nl < 0) return;
165
- handled = true;
166
- socket.setTimeout(0);
167
- const line = buffer.slice(0, nl);
168
- void (async () => {
169
- try {
170
- const request = SAFE_JSON_PARSE(line) as OwnerControlRequest;
171
- if (request.token === token) {
172
- const response = await onRequest(safeRequest(request), { principal: 'master' });
173
- respond(response);
174
- return;
175
- }
176
- if (request.relay_token === relayToken) {
177
- if (!['mailbox_claim', 'mailbox_ack', 'mailbox_nack'].includes(String(request.type ?? ''))) {
178
- respond({ ok: false, error: 'host_relay_request_not_allowed' });
179
- return;
180
- }
181
- const response = await onRequest(safeRequest(request), { principal: 'host_relay' });
182
- respond(response);
183
- return;
184
- }
185
- respond({ ok: false, error: 'invalid_token' });
186
- } catch (err: any) {
187
- respond({ ok: false, error: err?.message ?? String(err) });
188
- }
189
- })();
190
- });
191
- });
192
- server.maxConnections = MAX_CONTROL_CONNECTIONS;
193
- await new Promise<void>((resolve, reject) => {
194
- server.once('error', reject);
195
- server.listen(path, () => {
196
- server.off('error', reject);
197
- resolve();
198
- });
199
- });
200
- if (process.platform !== 'win32') {
201
- try { chmodSync(path, 0o600); } catch {}
202
- }
203
-
204
- const control: OwnerControlInfo = { kind: 'node-net-socket', path };
205
- options.observability?.log('info', 'owner.control.started', {
206
- transport: control.kind,
207
- }, { component: 'runtime.owner_control' });
208
- let closed = false;
209
- return {
210
- control,
211
- token,
212
- relayToken,
213
- close: async () => {
214
- if (closed) return;
215
- closed = true;
216
- await new Promise<void>((resolve) => {
217
- server.close(() => resolve());
218
- for (const socket of sockets) socket.destroy();
219
- });
220
- if (process.platform !== 'win32') {
221
- try { unlinkSync(path); } catch {}
222
- }
223
- options.observability?.log('info', 'owner.control.stopped', {}, {
224
- component: 'runtime.owner_control',
225
- });
226
- },
227
- };
228
- }
229
-
230
- function sendControlRequest(
231
- path: string,
232
- request: OwnerControlRequest,
233
- timeoutMs: number,
234
- ): Promise<OwnerControlResponse | null> {
235
- return new Promise((resolve, reject) => {
236
- const socket = connect(path);
237
- let buffer = '';
238
- let settled = false;
239
- const finishResolve = (value: OwnerControlResponse | null): void => {
240
- if (settled) return;
241
- settled = true;
242
- clearTimeout(timer);
243
- resolve(value);
244
- };
245
- const finishReject = (error: unknown): void => {
246
- if (settled) return;
247
- settled = true;
248
- clearTimeout(timer);
249
- reject(error);
250
- };
251
- const timer = setTimeout(() => {
252
- socket.destroy();
253
- finishReject(new Error('owner_control_timeout'));
254
- }, timeoutMs);
255
- socket.setEncoding('utf8');
256
- socket.on('connect', () => {
257
- socket.write(`${SAFE_JSON_STRINGIFY(request)}\n`);
258
- });
259
- socket.on('data', (chunk) => {
260
- buffer += chunk;
261
- const nl = buffer.indexOf('\n');
262
- if (nl < 0) return;
263
- socket.end();
264
- try {
265
- finishResolve(SAFE_JSON_PARSE(buffer.slice(0, nl)));
266
- } catch (err) {
267
- finishReject(err);
268
- }
269
- });
270
- socket.on('error', finishReject);
271
- socket.on('close', () => {
272
- if (!buffer) finishResolve(null);
273
- });
274
- });
275
- }
276
-
277
33
  /** Master/short-command path. This is the only helper that reads game-start.json. */
278
- export function sendOwnerControlRequest(
279
- stateDir: string,
280
- type: OwnerControlType,
281
- payload: Record<string, any> = {},
282
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
283
- ): Promise<OwnerControlResponse | null> {
284
- const info = readGameStartRuntime(stateDir);
285
- return sendOwnerControlRequestTo(info, type, payload, timeoutMs);
34
+ export function sendOwnerControlRequest(stateDir: string, type: OwnerControlType, payload: Record<string, any> = {}, timeoutMs = OWNER_CONTROL_TIMEOUT_MS): Promise<OwnerControlResponse | null> {
35
+ const info = readGameStartRuntime(stateDir);
36
+ return sendOwnerControlRequestTo(info, type, payload, timeoutMs);
286
37
  }
287
-
288
38
  /** Use a captured endpoint when replacing an owner; do not re-read a newer pointer. */
289
- export function sendOwnerControlRequestTo(
290
- info: Record<string, any> | null,
291
- type: OwnerControlType,
292
- payload: Record<string, any> = {},
293
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
294
- ): Promise<OwnerControlResponse | null> {
295
- const path = typeof info?.control?.path === 'string' ? info.control.path : '';
296
- const token = typeof info?.control_token === 'string' ? info.control_token : '';
297
- if (!path || !token) return Promise.resolve(null);
298
- return sendControlRequest(path, { ...payload, token, type }, timeoutMs);
39
+ export function sendOwnerControlRequestTo(info: Record<string, any> | null, type: OwnerControlType, payload: Record<string, any> = {}, timeoutMs = OWNER_CONTROL_TIMEOUT_MS): Promise<OwnerControlResponse | null> {
40
+ const path = typeof info?.control?.path === 'string' ? info.control.path : '';
41
+ const token = typeof info?.control_token === 'string' ? info.control_token : '';
42
+ if (!path || !token)
43
+ return Promise.resolve(null);
44
+ return sendControlRequest(path, { ...payload, token, type }, timeoutMs);
299
45
  }
300
-
301
46
  /** Narrow Host Relay path; this authority cannot execute actions or lifecycle commands. */
302
- export function sendOwnerRelayControlRequest(
303
- stateDir: string,
304
- type: HostRelayOwnerControlType,
305
- payload: Record<string, any> = {},
306
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
307
- ): Promise<OwnerControlResponse | null> {
308
- const info = readGameStartRuntime(stateDir);
309
- const path = typeof info?.control?.path === 'string' ? info.control.path : '';
310
- const relayToken = typeof info?.relay_token === 'string' ? info.relay_token : '';
311
- if (!path || !relayToken) return Promise.resolve(null);
312
- return sendControlRequest(path, {
313
- ...payload,
314
- relay_token: relayToken,
315
- type,
316
- }, timeoutMs);
47
+ export function sendOwnerRelayControlRequest(stateDir: string, type: HostRelayOwnerControlType, payload: Record<string, any> = {}, timeoutMs = OWNER_CONTROL_TIMEOUT_MS): Promise<OwnerControlResponse | null> {
48
+ const info = readGameStartRuntime(stateDir);
49
+ const path = typeof info?.control?.path === 'string' ? info.control.path : '';
50
+ const relayToken = typeof info?.relay_token === 'string' ? info.relay_token : '';
51
+ if (!path || !relayToken)
52
+ return Promise.resolve(null);
53
+ return sendControlRequest(path, {
54
+ ...payload,
55
+ relay_token: relayToken,
56
+ type,
57
+ }, timeoutMs);
317
58
  }
318
-
319
59
  /** Stable owner-control lookup for Agent-facing short commands. */
320
- export function sendProfileOwnerControlRequest(
321
- profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
322
- type: OwnerControlType,
323
- payload: Record<string, any> = {},
324
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
325
- ): Promise<OwnerControlResponse | null> {
326
- return sendOwnerControlRequest(
327
- getProfileRuntimeStateDir(profile),
328
- type,
329
- payload,
330
- timeoutMs,
331
- );
60
+ export function sendProfileOwnerControlRequest(profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>, type: OwnerControlType, payload: Record<string, any> = {}, timeoutMs = OWNER_CONTROL_TIMEOUT_MS): Promise<OwnerControlResponse | null> {
61
+ return sendOwnerControlRequest(getProfileRuntimeStateDir(profile), type, payload, timeoutMs);
332
62
  }
@@ -1,51 +1 @@
1
- export interface ParentProcessWatchOptions {
2
- readonly parentPid?: number;
3
- readonly intervalMs?: number;
4
- readonly isAlive?: (pid: number) => boolean;
5
- }
6
-
7
- export interface ParentProcessWatchHandle {
8
- readonly parentPid: number;
9
- stop(): void;
10
- }
11
-
12
- export function processIsAlive(pid: number): boolean {
13
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
14
- try {
15
- process.kill(pid, 0);
16
- return true;
17
- } catch {
18
- return false;
19
- }
20
- }
21
-
22
- /**
23
- * Watches the immediate launcher captured at CCL startup. This is a local
24
- * lifecycle signal only; it never asks the game backend to leave.
25
- */
26
- export function watchParentProcess(
27
- onExit: () => void,
28
- options: ParentProcessWatchOptions = {},
29
- ): ParentProcessWatchHandle {
30
- const parentPid = options.parentPid ?? process.ppid;
31
- const intervalMs = Math.max(100, Math.floor(options.intervalMs ?? 500));
32
- const isAlive = options.isAlive ?? processIsAlive;
33
- let stopped = false;
34
- let notified = false;
35
- const poll = (): void => {
36
- if (stopped || notified || isAlive(parentPid)) return;
37
- notified = true;
38
- onExit();
39
- };
40
- const timer = setInterval(poll, intervalMs);
41
- timer.unref?.();
42
- poll();
43
- return {
44
- parentPid,
45
- stop: () => {
46
- if (stopped) return;
47
- stopped = true;
48
- clearInterval(timer);
49
- },
50
- };
51
- }
1
+ export * from '@myclaw163/game-agent-runtime/owner/parent-process-watch.js';