@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -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,337 +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
- | 'perception_update'
37
- | 'perception_status'
38
- | 'behavior_watch'
39
- | 'behavior_unwatch'
40
- | 'behavior_update'
41
- | 'behavior_start'
42
- | 'behavior_status'
43
- | 'behavior_cancel'
44
- | 'behavior_fallback'
45
- | 'behavior_idle'
46
- | 'trigger_configure'
47
- | 'intent_start'
48
- | 'intent_status'
49
- | 'intent_cancel';
50
-
51
- export type HostRelayOwnerControlType =
52
- | 'mailbox_claim'
53
- | 'mailbox_ack'
54
- | 'mailbox_nack';
55
-
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';
56
13
  export type OwnerControlType = MasterOwnerControlType;
57
-
58
- export interface OwnerControlInfo {
59
- kind: 'node-net-socket';
60
- path: string;
61
- }
62
-
63
- export interface OwnerControlRequest {
64
- token?: string;
65
- relay_token?: string;
66
- type?: OwnerControlType;
67
- strategy?: string;
68
- args?: string[];
69
- [key: string]: any;
70
- }
71
-
72
- export interface OwnerControlResponse {
73
- ok: boolean;
74
- type?: string;
75
- error?: string;
76
- message?: string;
77
- [key: string]: any;
14
+ export interface OwnerControlRequest extends CoreRequest {
15
+ type?: OwnerControlType;
78
16
  }
79
-
80
- export type OwnerControlRequestContext =
81
- | { principal: 'master' }
82
- | { principal: 'host_relay' };
83
-
84
- export interface OwnerControlServerOptions {
85
- observability?: TelemetryRecorder;
86
- }
87
-
88
- export interface OwnerControlServer {
89
- control: OwnerControlInfo;
90
- /** Master authority for short CLI commands only. Never pass this to workers. */
91
- token: string;
92
- /** Narrow Mailbox-only authority for disposable Host Relays. */
93
- relayToken: string;
94
- close: () => Promise<void>;
95
- }
96
-
97
17
  export function gameStartRuntimePath(stateDir: string): string {
98
- return join(stateDir, GAME_START_RUNTIME_FILE);
18
+ return join(stateDir, GAME_START_RUNTIME_FILE);
99
19
  }
100
-
101
20
  export function readGameStartRuntime(stateDir: string): Record<string, any> | null {
102
- const runtimePath = gameStartRuntimePath(stateDir);
103
- if (!existsSync(runtimePath)) return null;
104
- try {
105
- return SAFE_JSON_PARSE(readFileSync(runtimePath, 'utf8'));
106
- } catch {}
107
- return null;
108
- }
109
-
110
- function ownerControlPath(stateDir: string, pid: number, nonce: string): string {
111
- const hash = createHash('sha1').update(stateDir).digest('hex').slice(0, 12);
112
- if (process.platform === 'win32') return `\\\\.\\pipe\\clawclaw-${hash}-${pid}-${nonce}`;
113
- const userId = typeof process.getuid === 'function' ? String(process.getuid()) : hash;
114
- const dir = join(tmpdir(), `clawclaw-${userId}`);
115
- mkdirSync(dir, { recursive: true, mode: 0o700 });
116
- try { chmodSync(dir, 0o700); } catch {}
117
- 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'] });
118
32
  }
119
-
120
- function safeRequest(request: OwnerControlRequest): OwnerControlRequest {
121
- const {
122
- token: _token,
123
- relay_token: _relayToken,
124
- ...rest
125
- } = request;
126
- return rest;
127
- }
128
-
129
- function sendLine(socket: import('net').Socket, value: OwnerControlResponse): void {
130
- socket.end(`${SAFE_JSON_STRINGIFY(value)}\n`);
131
- }
132
-
133
- export async function startOwnerControlServer(
134
- stateDir: string,
135
- onRequest: (
136
- request: OwnerControlRequest,
137
- context: OwnerControlRequestContext,
138
- ) => Promise<OwnerControlResponse> | OwnerControlResponse,
139
- options: OwnerControlServerOptions = {},
140
- ): Promise<OwnerControlServer> {
141
- const token = randomBytes(24).toString('hex');
142
- const relayToken = randomBytes(24).toString('hex');
143
- const path = ownerControlPath(stateDir, process.pid, randomBytes(8).toString('hex'));
144
- if (process.platform !== 'win32') {
145
- try { unlinkSync(path); } catch {}
146
- }
147
-
148
- const sockets = new Set<Socket>();
149
- const server: Server = createServer((socket) => {
150
- sockets.add(socket);
151
- socket.on('error', () => {});
152
- socket.once('close', () => sockets.delete(socket));
153
- socket.setTimeout(OWNER_CONTROL_TIMEOUT_MS, () => socket.destroy());
154
- let buffer = '';
155
- let handled = false;
156
- const respond = (value: OwnerControlResponse): void => {
157
- sendLine(socket, value);
158
- };
159
- socket.setEncoding('utf8');
160
- socket.on('data', (chunk) => {
161
- if (handled) return;
162
- buffer += chunk;
163
- if (Buffer.byteLength(buffer, 'utf8') > MAX_CONTROL_REQUEST_BYTES) {
164
- handled = true;
165
- respond({ ok: false, error: 'owner_control_request_too_large' });
166
- return;
167
- }
168
- const nl = buffer.indexOf('\n');
169
- if (nl < 0) return;
170
- handled = true;
171
- socket.setTimeout(0);
172
- const line = buffer.slice(0, nl);
173
- void (async () => {
174
- try {
175
- const request = SAFE_JSON_PARSE(line) as OwnerControlRequest;
176
- if (request.token === token) {
177
- const response = await onRequest(safeRequest(request), { principal: 'master' });
178
- respond(response);
179
- return;
180
- }
181
- if (request.relay_token === relayToken) {
182
- if (!['mailbox_claim', 'mailbox_ack', 'mailbox_nack'].includes(String(request.type ?? ''))) {
183
- respond({ ok: false, error: 'host_relay_request_not_allowed' });
184
- return;
185
- }
186
- const response = await onRequest(safeRequest(request), { principal: 'host_relay' });
187
- respond(response);
188
- return;
189
- }
190
- respond({ ok: false, error: 'invalid_token' });
191
- } catch (err: any) {
192
- respond({ ok: false, error: err?.message ?? String(err) });
193
- }
194
- })();
195
- });
196
- });
197
- server.maxConnections = MAX_CONTROL_CONNECTIONS;
198
- await new Promise<void>((resolve, reject) => {
199
- server.once('error', reject);
200
- server.listen(path, () => {
201
- server.off('error', reject);
202
- resolve();
203
- });
204
- });
205
- if (process.platform !== 'win32') {
206
- try { chmodSync(path, 0o600); } catch {}
207
- }
208
-
209
- const control: OwnerControlInfo = { kind: 'node-net-socket', path };
210
- options.observability?.log('info', 'owner.control.started', {
211
- transport: control.kind,
212
- }, { component: 'runtime.owner_control' });
213
- let closed = false;
214
- return {
215
- control,
216
- token,
217
- relayToken,
218
- close: async () => {
219
- if (closed) return;
220
- closed = true;
221
- await new Promise<void>((resolve) => {
222
- server.close(() => resolve());
223
- for (const socket of sockets) socket.destroy();
224
- });
225
- if (process.platform !== 'win32') {
226
- try { unlinkSync(path); } catch {}
227
- }
228
- options.observability?.log('info', 'owner.control.stopped', {}, {
229
- component: 'runtime.owner_control',
230
- });
231
- },
232
- };
233
- }
234
-
235
- function sendControlRequest(
236
- path: string,
237
- request: OwnerControlRequest,
238
- timeoutMs: number,
239
- ): Promise<OwnerControlResponse | null> {
240
- return new Promise((resolve, reject) => {
241
- const socket = connect(path);
242
- let buffer = '';
243
- let settled = false;
244
- const finishResolve = (value: OwnerControlResponse | null): void => {
245
- if (settled) return;
246
- settled = true;
247
- clearTimeout(timer);
248
- resolve(value);
249
- };
250
- const finishReject = (error: unknown): void => {
251
- if (settled) return;
252
- settled = true;
253
- clearTimeout(timer);
254
- reject(error);
255
- };
256
- const timer = setTimeout(() => {
257
- socket.destroy();
258
- finishReject(new Error('owner_control_timeout'));
259
- }, timeoutMs);
260
- socket.setEncoding('utf8');
261
- socket.on('connect', () => {
262
- socket.write(`${SAFE_JSON_STRINGIFY(request)}\n`);
263
- });
264
- socket.on('data', (chunk) => {
265
- buffer += chunk;
266
- const nl = buffer.indexOf('\n');
267
- if (nl < 0) return;
268
- socket.end();
269
- try {
270
- finishResolve(SAFE_JSON_PARSE(buffer.slice(0, nl)));
271
- } catch (err) {
272
- finishReject(err);
273
- }
274
- });
275
- socket.on('error', finishReject);
276
- socket.on('close', () => {
277
- if (!buffer) finishResolve(null);
278
- });
279
- });
280
- }
281
-
282
33
  /** Master/short-command path. This is the only helper that reads game-start.json. */
283
- export function sendOwnerControlRequest(
284
- stateDir: string,
285
- type: OwnerControlType,
286
- payload: Record<string, any> = {},
287
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
288
- ): Promise<OwnerControlResponse | null> {
289
- const info = readGameStartRuntime(stateDir);
290
- 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);
291
37
  }
292
-
293
38
  /** Use a captured endpoint when replacing an owner; do not re-read a newer pointer. */
294
- export function sendOwnerControlRequestTo(
295
- info: Record<string, any> | null,
296
- type: OwnerControlType,
297
- payload: Record<string, any> = {},
298
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
299
- ): Promise<OwnerControlResponse | null> {
300
- const path = typeof info?.control?.path === 'string' ? info.control.path : '';
301
- const token = typeof info?.control_token === 'string' ? info.control_token : '';
302
- if (!path || !token) return Promise.resolve(null);
303
- 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);
304
45
  }
305
-
306
46
  /** Narrow Host Relay path; this authority cannot execute actions or lifecycle commands. */
307
- export function sendOwnerRelayControlRequest(
308
- stateDir: string,
309
- type: HostRelayOwnerControlType,
310
- payload: Record<string, any> = {},
311
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
312
- ): Promise<OwnerControlResponse | null> {
313
- const info = readGameStartRuntime(stateDir);
314
- const path = typeof info?.control?.path === 'string' ? info.control.path : '';
315
- const relayToken = typeof info?.relay_token === 'string' ? info.relay_token : '';
316
- if (!path || !relayToken) return Promise.resolve(null);
317
- return sendControlRequest(path, {
318
- ...payload,
319
- relay_token: relayToken,
320
- type,
321
- }, 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);
322
58
  }
323
-
324
59
  /** Stable owner-control lookup for Agent-facing short commands. */
325
- export function sendProfileOwnerControlRequest(
326
- profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
327
- type: OwnerControlType,
328
- payload: Record<string, any> = {},
329
- timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
330
- ): Promise<OwnerControlResponse | null> {
331
- return sendOwnerControlRequest(
332
- getProfileRuntimeStateDir(profile),
333
- type,
334
- payload,
335
- timeoutMs,
336
- );
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);
337
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';