@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.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 (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +244 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +58 -0
  127. package/dist/mailbox/mailbox-plugin.js +128 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +338 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,121 @@
1
+ import { appendFile, mkdir, readdir, rename, rm, stat } from 'fs/promises';
2
+ import { basename, dirname, join } from 'path';
3
+ function hasErrorCode(error, code) {
4
+ return !!error && typeof error === 'object' && error.code === code;
5
+ }
6
+ /** Owner-only local diagnostic journal. Records arrive already redacted. */
7
+ export class JsonlObservabilitySink {
8
+ id = 'local-jsonl';
9
+ filePath;
10
+ maxFileBytes;
11
+ retainedFiles;
12
+ operation = Promise.resolve();
13
+ closed = false;
14
+ retentionPrepared = false;
15
+ constructor(filePath, options = {}) {
16
+ this.filePath = filePath;
17
+ this.maxFileBytes = Math.max(64 * 1024, options.maxFileBytes ?? 10 * 1024 * 1024);
18
+ this.retainedFiles = Math.max(1, options.retainedFiles ?? 5);
19
+ }
20
+ write(records) {
21
+ if (this.closed)
22
+ return Promise.reject(new Error('observability_sink_closed'));
23
+ if (records.length === 0)
24
+ return this.operation;
25
+ const data = records.map((record) => JSON.stringify(record)).join('\n') + '\n';
26
+ const next = this.operation.then(async () => {
27
+ await mkdir(dirname(this.filePath), { recursive: true });
28
+ if (!this.retentionPrepared) {
29
+ await this.pruneExcessHistory();
30
+ this.retentionPrepared = true;
31
+ }
32
+ await this.rotateIfNeeded(Buffer.byteLength(data));
33
+ await appendFile(this.filePath, data, { encoding: 'utf8', mode: 0o600 });
34
+ });
35
+ this.operation = next.catch(() => { });
36
+ return next;
37
+ }
38
+ async close() {
39
+ this.closed = true;
40
+ await this.operation;
41
+ }
42
+ async rotateIfNeeded(incomingBytes) {
43
+ let size = 0;
44
+ try {
45
+ size = (await stat(this.filePath)).size;
46
+ }
47
+ catch (error) {
48
+ if (!hasErrorCode(error, 'ENOENT'))
49
+ throw error;
50
+ }
51
+ if (size === 0 || size + incomingBytes <= this.maxFileBytes)
52
+ return;
53
+ await rm(`${this.filePath}.${this.retainedFiles}`, { force: true });
54
+ for (let index = this.retainedFiles - 1; index >= 1; index -= 1) {
55
+ try {
56
+ await this.renameFile(`${this.filePath}.${index}`, `${this.filePath}.${index + 1}`);
57
+ }
58
+ catch (error) {
59
+ // Sparse history is normal. Permission, lock and filesystem errors are
60
+ // not: appending after one of those would make retention unbounded.
61
+ if (!hasErrorCode(error, 'ENOENT'))
62
+ throw error;
63
+ }
64
+ }
65
+ // stat() just proved the active file exists. Any failure here must abort
66
+ // this write so the reporter can retain/retry the batch instead of growing
67
+ // the already-full active file indefinitely.
68
+ await this.renameFile(this.filePath, `${this.filePath}.1`);
69
+ }
70
+ async pruneExcessHistory() {
71
+ const directory = dirname(this.filePath);
72
+ const prefix = `${basename(this.filePath)}.`;
73
+ const entries = await readdir(directory);
74
+ await Promise.all(entries.map(async (entry) => {
75
+ if (!entry.startsWith(prefix))
76
+ return;
77
+ const suffix = entry.slice(prefix.length);
78
+ if (!/^\d+$/.test(suffix) || Number(suffix) <= this.retainedFiles)
79
+ return;
80
+ await rm(join(directory, entry), { force: true });
81
+ }));
82
+ }
83
+ /** Protected seam for platform adapters and deterministic failure tests. */
84
+ renameFile(source, destination) {
85
+ return rename(source, destination);
86
+ }
87
+ }
88
+ /**
89
+ * Fan-out boundary for local storage plus future reporters. A partial sink
90
+ * failure does not make a successful durable sink repeat its records.
91
+ */
92
+ export class CompositeObservabilitySink {
93
+ id = 'composite';
94
+ sinks;
95
+ onSinkError;
96
+ constructor(sinks, options = {}) {
97
+ this.sinks = [...sinks];
98
+ if (this.sinks.length === 0)
99
+ throw new Error('observability_sink_required');
100
+ this.onSinkError = options.onSinkError;
101
+ }
102
+ async write(records) {
103
+ const results = await Promise.allSettled(this.sinks.map((sink) => Promise.resolve().then(() => sink.write(records))));
104
+ let successes = 0;
105
+ results.forEach((result, index) => {
106
+ if (result.status === 'fulfilled')
107
+ successes += 1;
108
+ else {
109
+ try {
110
+ this.onSinkError?.(this.sinks[index].id, result.reason);
111
+ }
112
+ catch { }
113
+ }
114
+ });
115
+ if (successes === 0)
116
+ throw new AggregateError(results.filter((result) => result.status === 'rejected').map((result) => result.reason), 'all_observability_sinks_failed');
117
+ }
118
+ async close() {
119
+ await Promise.allSettled(this.sinks.map((sink) => Promise.resolve().then(() => sink.close?.())));
120
+ }
121
+ }
@@ -0,0 +1,81 @@
1
+ export declare const OBSERVABILITY_SCHEMA: "ccl.observability.v1";
2
+ export type ObservabilityKind = 'log' | 'metric' | 'error';
3
+ export type ObservabilitySeverity = 'debug' | 'info' | 'warn' | 'error';
4
+ export type ObservabilityProcessRole = 'owner' | 'cli';
5
+ /** Logical game scope only. Account credentials and player-facing payloads do not belong here. */
6
+ export interface ObservabilityScope {
7
+ adapterId?: string;
8
+ sessionId?: string;
9
+ segmentId?: string;
10
+ segmentSeq?: number;
11
+ connectionId?: string;
12
+ }
13
+ export interface ObservabilityCorrelation {
14
+ commandId?: string;
15
+ requestId?: string;
16
+ actionId?: string;
17
+ behaviorActivationId?: string;
18
+ behaviorActivationGeneration?: number;
19
+ traceId?: string;
20
+ parentRecordId?: string;
21
+ }
22
+ export interface ObservabilityProcess {
23
+ role: ObservabilityProcessRole;
24
+ pid: number;
25
+ }
26
+ export interface ObservabilityMetric {
27
+ value: number;
28
+ unit?: string;
29
+ aggregation?: 'counter' | 'gauge' | 'histogram_sample';
30
+ }
31
+ export interface ObservabilityError {
32
+ name?: string;
33
+ code?: string;
34
+ message?: string;
35
+ stack?: string;
36
+ cause?: unknown;
37
+ }
38
+ export interface ObservabilityRecord {
39
+ schema: typeof OBSERVABILITY_SCHEMA;
40
+ recordId: string;
41
+ timestamp: string;
42
+ kind: ObservabilityKind;
43
+ name: string;
44
+ severity: ObservabilitySeverity;
45
+ component: string;
46
+ process: ObservabilityProcess;
47
+ scope?: ObservabilityScope;
48
+ correlation?: ObservabilityCorrelation;
49
+ attributes: Record<string, unknown>;
50
+ metric?: ObservabilityMetric;
51
+ error?: ObservabilityError;
52
+ }
53
+ export interface RecordTelemetryInput {
54
+ kind: ObservabilityKind;
55
+ name: string;
56
+ severity?: ObservabilitySeverity;
57
+ component?: string;
58
+ scope?: ObservabilityScope;
59
+ correlation?: ObservabilityCorrelation;
60
+ attributes?: Record<string, unknown>;
61
+ metric?: ObservabilityMetric;
62
+ error?: ObservabilityError | Error | unknown;
63
+ }
64
+ export interface ObservabilityReporterStats {
65
+ accepted: number;
66
+ dropped: number;
67
+ flushed: number;
68
+ failedBatches: number;
69
+ queued: number;
70
+ }
71
+ export interface ObservabilityReporter {
72
+ enqueue(record: ObservabilityRecord): boolean;
73
+ flush(): Promise<void>;
74
+ close(): Promise<void>;
75
+ stats(): ObservabilityReporterStats;
76
+ }
77
+ export interface ObservabilitySink {
78
+ readonly id: string;
79
+ write(records: readonly ObservabilityRecord[]): Promise<void>;
80
+ close?(): Promise<void>;
81
+ }
@@ -0,0 +1 @@
1
+ export const OBSERVABILITY_SCHEMA = 'ccl.observability.v1';
@@ -0,0 +1,42 @@
1
+ import type { TelemetryRecorder } from '../observability/index.js';
2
+ export declare const OWNER_CONTROL_TIMEOUT_MS = 2000;
3
+ export type OwnerControlType = string;
4
+ export interface OwnerControlInfo {
5
+ kind: 'node-net-socket';
6
+ path: string;
7
+ }
8
+ export interface OwnerControlRequest {
9
+ token?: string;
10
+ relay_token?: string;
11
+ type?: OwnerControlType;
12
+ strategy?: string;
13
+ args?: string[];
14
+ [key: string]: any;
15
+ }
16
+ export interface OwnerControlResponse {
17
+ ok: boolean;
18
+ type?: string;
19
+ error?: string;
20
+ message?: string;
21
+ [key: string]: any;
22
+ }
23
+ export type OwnerControlRequestContext = {
24
+ principal: 'master';
25
+ } | {
26
+ principal: 'host_relay';
27
+ };
28
+ export interface OwnerControlServerOptions {
29
+ observability?: TelemetryRecorder;
30
+ namespace?: string;
31
+ relayCommands?: readonly string[];
32
+ }
33
+ export interface OwnerControlServer {
34
+ control: OwnerControlInfo;
35
+ /** Master authority for short CLI commands only. Never pass this to workers. */
36
+ token: string;
37
+ /** Narrow Mailbox-only authority for disposable Host Relays. */
38
+ relayToken: string;
39
+ close: () => Promise<void>;
40
+ }
41
+ export declare function startOwnerControlServer(stateDir: string, onRequest: (request: OwnerControlRequest, context: OwnerControlRequestContext) => Promise<OwnerControlResponse> | OwnerControlResponse, options?: OwnerControlServerOptions): Promise<OwnerControlServer>;
42
+ export declare function sendControlRequest(path: string, request: OwnerControlRequest, timeoutMs: number): Promise<OwnerControlResponse | null>;
@@ -0,0 +1,188 @@
1
+ import { createHash, randomBytes } from 'crypto';
2
+ import { chmodSync, mkdirSync, unlinkSync } from 'fs';
3
+ import { tmpdir } from 'os';
4
+ import { join } from 'path';
5
+ import { connect, createServer } from 'net';
6
+ export const OWNER_CONTROL_TIMEOUT_MS = 2000;
7
+ const MAX_CONTROL_REQUEST_BYTES = 1024 * 1024;
8
+ const MAX_CONTROL_CONNECTIONS = 64;
9
+ // Capture protocol primitives so runtime modules cannot rewrite authenticated
10
+ // owner-control requests by monkey-patching global JSON.
11
+ const SAFE_JSON_PARSE = JSON.parse.bind(JSON);
12
+ const SAFE_JSON_STRINGIFY = JSON.stringify.bind(JSON);
13
+ function ownerControlPath(stateDir, pid, nonce, namespace) {
14
+ const hash = createHash('sha1').update(stateDir).digest('hex').slice(0, 12);
15
+ if (process.platform === 'win32')
16
+ return `\\\\.\\pipe\\${namespace}-${hash}-${pid}-${nonce}`;
17
+ const userId = typeof process.getuid === 'function' ? String(process.getuid()) : hash;
18
+ const dir = join(tmpdir(), `${namespace}-${userId}`);
19
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
20
+ try {
21
+ chmodSync(dir, 0o700);
22
+ }
23
+ catch { }
24
+ return join(dir, `${hash}-${pid}-${nonce}.sock`);
25
+ }
26
+ function safeRequest(request) {
27
+ const { token: _token, relay_token: _relayToken, ...rest } = request;
28
+ return rest;
29
+ }
30
+ function sendLine(socket, value) {
31
+ socket.end(`${SAFE_JSON_STRINGIFY(value)}\n`);
32
+ }
33
+ export async function startOwnerControlServer(stateDir, onRequest, options = {}) {
34
+ const token = randomBytes(24).toString('hex');
35
+ const relayToken = randomBytes(24).toString('hex');
36
+ const namespace = options.namespace ?? 'agent-runtime';
37
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(namespace))
38
+ throw Error('owner_namespace_invalid');
39
+ const path = ownerControlPath(stateDir, process.pid, randomBytes(8).toString('hex'), namespace);
40
+ if (process.platform !== 'win32') {
41
+ try {
42
+ unlinkSync(path);
43
+ }
44
+ catch { }
45
+ }
46
+ const sockets = new Set();
47
+ const server = createServer((socket) => {
48
+ sockets.add(socket);
49
+ socket.on('error', () => { });
50
+ socket.once('close', () => sockets.delete(socket));
51
+ socket.setTimeout(OWNER_CONTROL_TIMEOUT_MS, () => socket.destroy());
52
+ let buffer = '';
53
+ let handled = false;
54
+ const respond = (value) => {
55
+ sendLine(socket, value);
56
+ };
57
+ socket.setEncoding('utf8');
58
+ socket.on('data', (chunk) => {
59
+ if (handled)
60
+ return;
61
+ buffer += chunk;
62
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_CONTROL_REQUEST_BYTES) {
63
+ handled = true;
64
+ respond({ ok: false, error: 'owner_control_request_too_large' });
65
+ return;
66
+ }
67
+ const nl = buffer.indexOf('\n');
68
+ if (nl < 0)
69
+ return;
70
+ handled = true;
71
+ socket.setTimeout(0);
72
+ const line = buffer.slice(0, nl);
73
+ void (async () => {
74
+ try {
75
+ const request = SAFE_JSON_PARSE(line);
76
+ if (request.token === token) {
77
+ const response = await onRequest(safeRequest(request), { principal: 'master' });
78
+ respond(response);
79
+ return;
80
+ }
81
+ if (request.relay_token === relayToken) {
82
+ if (!(options.relayCommands ?? []).includes(String(request.type ?? ''))) {
83
+ respond({ ok: false, error: 'host_relay_request_not_allowed' });
84
+ return;
85
+ }
86
+ const response = await onRequest(safeRequest(request), { principal: 'host_relay' });
87
+ respond(response);
88
+ return;
89
+ }
90
+ respond({ ok: false, error: 'invalid_token' });
91
+ }
92
+ catch (err) {
93
+ respond({ ok: false, error: err?.message ?? String(err) });
94
+ }
95
+ })();
96
+ });
97
+ });
98
+ server.maxConnections = MAX_CONTROL_CONNECTIONS;
99
+ await new Promise((resolve, reject) => {
100
+ server.once('error', reject);
101
+ server.listen(path, () => {
102
+ server.off('error', reject);
103
+ resolve();
104
+ });
105
+ });
106
+ if (process.platform !== 'win32') {
107
+ try {
108
+ chmodSync(path, 0o600);
109
+ }
110
+ catch { }
111
+ }
112
+ const control = { kind: 'node-net-socket', path };
113
+ options.observability?.log('info', 'owner.control.started', {
114
+ transport: control.kind,
115
+ }, { component: 'runtime.owner_control' });
116
+ let closed = false;
117
+ return {
118
+ control,
119
+ token,
120
+ relayToken,
121
+ close: async () => {
122
+ if (closed)
123
+ return;
124
+ closed = true;
125
+ await new Promise((resolve) => {
126
+ server.close(() => resolve());
127
+ for (const socket of sockets)
128
+ socket.destroy();
129
+ });
130
+ if (process.platform !== 'win32') {
131
+ try {
132
+ unlinkSync(path);
133
+ }
134
+ catch { }
135
+ }
136
+ options.observability?.log('info', 'owner.control.stopped', {}, {
137
+ component: 'runtime.owner_control',
138
+ });
139
+ },
140
+ };
141
+ }
142
+ export function sendControlRequest(path, request, timeoutMs) {
143
+ return new Promise((resolve, reject) => {
144
+ const socket = connect(path);
145
+ let buffer = '';
146
+ let settled = false;
147
+ const finishResolve = (value) => {
148
+ if (settled)
149
+ return;
150
+ settled = true;
151
+ clearTimeout(timer);
152
+ resolve(value);
153
+ };
154
+ const finishReject = (error) => {
155
+ if (settled)
156
+ return;
157
+ settled = true;
158
+ clearTimeout(timer);
159
+ reject(error);
160
+ };
161
+ const timer = setTimeout(() => {
162
+ socket.destroy();
163
+ finishReject(new Error('owner_control_timeout'));
164
+ }, timeoutMs);
165
+ socket.setEncoding('utf8');
166
+ socket.on('connect', () => {
167
+ socket.write(`${SAFE_JSON_STRINGIFY(request)}\n`);
168
+ });
169
+ socket.on('data', (chunk) => {
170
+ buffer += chunk;
171
+ const nl = buffer.indexOf('\n');
172
+ if (nl < 0)
173
+ return;
174
+ socket.end();
175
+ try {
176
+ finishResolve(SAFE_JSON_PARSE(buffer.slice(0, nl)));
177
+ }
178
+ catch (err) {
179
+ finishReject(err);
180
+ }
181
+ });
182
+ socket.on('error', finishReject);
183
+ socket.on('close', () => {
184
+ if (!buffer)
185
+ finishResolve(null);
186
+ });
187
+ });
188
+ }
@@ -0,0 +1,15 @@
1
+ export interface ParentProcessWatchOptions {
2
+ readonly parentPid?: number;
3
+ readonly intervalMs?: number;
4
+ readonly isAlive?: (pid: number) => boolean;
5
+ }
6
+ export interface ParentProcessWatchHandle {
7
+ readonly parentPid: number;
8
+ stop(): void;
9
+ }
10
+ export declare function processIsAlive(pid: number): boolean;
11
+ /**
12
+ * Watches the immediate launcher captured at CCL startup. This is a local
13
+ * lifecycle signal only; it never asks the game backend to leave.
14
+ */
15
+ export declare function watchParentProcess(onExit: () => void, options?: ParentProcessWatchOptions): ParentProcessWatchHandle;
@@ -0,0 +1,40 @@
1
+ export function processIsAlive(pid) {
2
+ if (!Number.isSafeInteger(pid) || pid <= 0)
3
+ return false;
4
+ try {
5
+ process.kill(pid, 0);
6
+ return true;
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ /**
13
+ * Watches the immediate launcher captured at CCL startup. This is a local
14
+ * lifecycle signal only; it never asks the game backend to leave.
15
+ */
16
+ export function watchParentProcess(onExit, options = {}) {
17
+ const parentPid = options.parentPid ?? process.ppid;
18
+ const intervalMs = Math.max(100, Math.floor(options.intervalMs ?? 500));
19
+ const isAlive = options.isAlive ?? processIsAlive;
20
+ let stopped = false;
21
+ let notified = false;
22
+ const poll = () => {
23
+ if (stopped || notified || isAlive(parentPid))
24
+ return;
25
+ notified = true;
26
+ onExit();
27
+ };
28
+ const timer = setInterval(poll, intervalMs);
29
+ timer.unref?.();
30
+ poll();
31
+ return {
32
+ parentPid,
33
+ stop: () => {
34
+ if (stopped)
35
+ return;
36
+ stopped = true;
37
+ clearInterval(timer);
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,10 @@
1
+ export interface ProcessIdentity {
2
+ /** OS process creation value, never the time the lock file was written. */
3
+ birth: string;
4
+ startedAtMs: number;
5
+ executable: string;
6
+ }
7
+ export declare function inspectProcessIdentity(pid: number): ProcessIdentity | null;
8
+ export declare function sameProcessIdentity(a: ProcessIdentity | null, b: ProcessIdentity | null): boolean;
9
+ /** Recheck immediately before signalling; a PID alone never authorizes a kill. */
10
+ export declare function terminateVerifiedProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void;
@@ -0,0 +1,65 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync, readlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ export function inspectProcessIdentity(pid) {
5
+ if (!Number.isSafeInteger(pid) || pid <= 0)
6
+ return null;
7
+ try {
8
+ if (process.platform === 'win32') {
9
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
10
+ const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
11
+ + '$t=$p.StartTime.ToUniversalTime(); '
12
+ + '@{birth=$t.Ticks.ToString();startedAtMs=([DateTimeOffset]$t).ToUnixTimeMilliseconds();executable=$p.ProcessName} | ConvertTo-Json -Compress';
13
+ const output = execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true, timeout: 5_000, stdio: ['ignore', 'pipe', 'ignore'] });
14
+ return JSON.parse(output);
15
+ }
16
+ if (process.platform === 'linux') {
17
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
18
+ const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
19
+ const boot = Number(/^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]);
20
+ const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2_000 }));
21
+ return { birth: `${boot}:${ticks}`, startedAtMs: (boot + ticks / hz) * 1_000,
22
+ executable: readlinkSync(`/proc/${pid}/exe`) };
23
+ }
24
+ if (process.platform === 'darwin') {
25
+ const options = { encoding: 'utf8', timeout: 2_000, env: { ...process.env, LC_ALL: 'C' } };
26
+ const birth = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'lstart='], options).trim();
27
+ const executable = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'comm='], options).trim();
28
+ const startedAtMs = Date.parse(birth);
29
+ return birth && executable && Number.isFinite(startedAtMs) ? { birth, startedAtMs, executable } : null;
30
+ }
31
+ }
32
+ catch { }
33
+ return null;
34
+ }
35
+ export function sameProcessIdentity(a, b) {
36
+ return !!a && !!b && a.birth === b.birth && a.executable === b.executable;
37
+ }
38
+ /** Recheck immediately before signalling; a PID alone never authorizes a kill. */
39
+ export function terminateVerifiedProcess(pid, identity, signal) {
40
+ if (pid === process.pid || !sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
41
+ throw new Error(`Refusing to terminate an unverified ClawClaw runtime (pid ${pid}).`);
42
+ }
43
+ if (process.platform === 'win32') {
44
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
45
+ if (!/^\d+$/.test(identity.birth))
46
+ throw new Error('Invalid Windows process creation identity.');
47
+ // Retain the kernel handle before validating creation time. Killing via that
48
+ // Process object cannot target a later process that happens to reuse the PID.
49
+ // Runtime computation workers are threads of this process, so they exit too.
50
+ const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
51
+ + `try { $null=$p.Handle; if ($p.StartTime.ToUniversalTime().Ticks.ToString() -ne '${identity.birth}') `
52
+ + "{ throw 'runtime_identity_changed' }; $p.Kill(); } finally { $p.Dispose() }";
53
+ execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], { stdio: 'ignore', windowsHide: true, timeout: 5_000 });
54
+ return;
55
+ }
56
+ if (sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
57
+ try {
58
+ process.kill(pid, signal);
59
+ }
60
+ catch (error) {
61
+ if (error.code !== 'ESRCH')
62
+ throw error;
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,5 @@
1
+ export interface WorkspaceRuntimeLock {
2
+ release(): void;
3
+ }
4
+ /** The inode must remain in place: unlinking a locked file permits two owners. */
5
+ export declare function tryAcquireRuntimeLock(directory: string): WorkspaceRuntimeLock | null;
@@ -0,0 +1,47 @@
1
+ import { closeSync, mkdirSync, openSync, realpathSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ const require = createRequire(import.meta.url);
5
+ let nativeLocks;
6
+ const held = new Set();
7
+ /** The inode must remain in place: unlinking a locked file permits two owners. */
8
+ export function tryAcquireRuntimeLock(directory) {
9
+ mkdirSync(directory, { recursive: true });
10
+ const path = join(realpathSync(directory), 'owner.lock');
11
+ const key = process.platform === 'win32' ? path.toLowerCase() : path;
12
+ if (held.has(key))
13
+ return null;
14
+ // Load only for lifecycle operations; help/schema/short commands need no addon.
15
+ const locks = nativeLocks ??= require('fs-native-extensions');
16
+ const fd = openSync(path, 'a+', 0o600);
17
+ let acquired = false;
18
+ try {
19
+ acquired = locks.tryLock(fd);
20
+ if (!acquired)
21
+ return null;
22
+ held.add(key);
23
+ let released = false;
24
+ return {
25
+ release() {
26
+ if (released)
27
+ return;
28
+ released = true;
29
+ try {
30
+ locks.unlock(fd);
31
+ }
32
+ finally {
33
+ try {
34
+ closeSync(fd);
35
+ }
36
+ finally {
37
+ held.delete(key);
38
+ }
39
+ }
40
+ },
41
+ };
42
+ }
43
+ finally {
44
+ if (!acquired)
45
+ closeSync(fd);
46
+ }
47
+ }
@@ -0,0 +1,9 @@
1
+ import type { PerceptionBinding as ReactionBehaviorBinding } from './contracts.js';
2
+ export interface ReactionBehaviorCandidate {
3
+ readonly id: string;
4
+ readonly declaredId?: string;
5
+ readonly resourceId?: string;
6
+ readonly loadable: boolean;
7
+ }
8
+ /** Shared by load diagnostics and the live activation path. Never selects disabled/unloaded entries. */
9
+ export declare function resolveReactionBehavior(binding: ReactionBehaviorBinding, candidates: readonly ReactionBehaviorCandidate[]): string | undefined;
@@ -0,0 +1,14 @@
1
+ /** Shared by load diagnostics and the live activation path. Never selects disabled/unloaded entries. */
2
+ export function resolveReactionBehavior(binding, candidates) {
3
+ const available = candidates.filter(candidate => candidate.loadable);
4
+ const compare = (a, b) => Number(b.id === binding.name) - Number(a.id === binding.name)
5
+ || a.id.localeCompare(b.id, 'en', { numeric: true }) || String(a.resourceId).localeCompare(String(b.resourceId));
6
+ const preferred = binding.resourceId && available.filter(candidate => candidate.resourceId === binding.resourceId).sort(compare)[0];
7
+ if (preferred)
8
+ return preferred.id;
9
+ // Declared source identity distinguishes real duplicate aliases from an unrelated literal escape_1.
10
+ const named = available.filter(candidate => candidate.id === binding.name || candidate.declaredId === binding.name
11
+ || candidate.declaredId === undefined && candidate.id.startsWith(`${binding.name}_`)
12
+ && /^[1-9][0-9]*$/.test(candidate.id.slice(binding.name.length + 1))).sort(compare);
13
+ return named[0]?.id;
14
+ }