@myclaw163/game-agent-runtime 0.1.1 → 0.1.3
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.
- package/README.md +2 -0
- package/dist/framework/events/sqlite-event-repository.js +1 -1
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +13 -0
- package/dist/framework/persistence/sqlite-maintenance.d.ts +26 -0
- package/dist/framework/persistence/sqlite-maintenance.js +177 -0
- package/dist/framework/plugins/runtime-input-journal.js +1 -1
- package/dist/framework/state/history/sqlite-state-history-repository.js +2 -2
- package/dist/perception/contracts.d.ts +9 -2
- package/dist/perception/perception-host.d.ts +8 -0
- package/dist/perception/perception-host.js +72 -31
- package/dist/strategy/activation-manager.d.ts +2 -0
- package/dist/strategy/activation-manager.js +11 -0
- package/dist/strategy/contracts.d.ts +2 -0
- package/dist/strategy/strategy-host.d.ts +14 -1
- package/dist/strategy/strategy-host.js +265 -77
- package/dist/strategy/strategy-script-runner.d.ts +3 -1
- package/dist/strategy/strategy-script-runner.js +5 -1
- package/dist/strategy/strategy-worker-host.d.ts +1 -0
- package/dist/strategy/strategy-worker-host.js +7 -1
- package/dist/strategy/thread-strategy-executor.d.ts +19 -1
- package/dist/strategy/thread-strategy-executor.js +78 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -47,6 +47,8 @@ import { createGridGame } from '@myclaw163/game-agent-runtime/examples/grid-game
|
|
|
47
47
|
|
|
48
48
|
## 接入自己的游戏
|
|
49
49
|
|
|
50
|
+
离线数据库维护通过 `framework/persistence/sqlite-maintenance.js` 的 `tryAcquireRuntimeSqliteMaintenance(runtimeDirectory)` 使用。它与 Owner 共用系统锁,Owner 运行时返回 `null`;成功后可调用 `inspect(paths)`、`remove(paths, scopes, { inactiveBefore })` 和 `compact(paths)`,最后必须 `close()`。删除覆盖事件、投递、Mailbox、State 历史和插件 epoch 的关联记录,并保留全局自增序号。默认拒绝未关闭或最近活动的 scope;接入方确认过期异常退出数据后可显式设置 `allowInactiveOpenScopes`。保留时间、容量上限、整局分组和中断重试由接入方管理,GAR 不规定业务清理策略。
|
|
51
|
+
|
|
50
52
|
1. 用 Source 接入权威 State 和 Event,并保留输入时间及来源。
|
|
51
53
|
2. 实现感知/策略适配器:整理脚本输入、游戏执行条件和 SDK。
|
|
52
54
|
3. 注册 Action 和只读 Query,连接游戏后端。
|
|
@@ -241,7 +241,7 @@ export class SqliteEventRepository {
|
|
|
241
241
|
})),
|
|
242
242
|
mailboxItems: this.db.prepare(`SELECT * FROM mailbox_items${where}`).all(...params).map(mailboxItemFromRow),
|
|
243
243
|
// The mirror uses SQLite's global sequence, not the selected session's last row.
|
|
244
|
-
nextCommitSeq: numberValue(this.db.prepare(
|
|
244
|
+
nextCommitSeq: numberValue(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='events' UNION ALL SELECT MAX(commit_seq) FROM events)").get()?.seq) + 1,
|
|
245
245
|
};
|
|
246
246
|
}
|
|
247
247
|
schemaVersion() {
|
|
@@ -96,6 +96,19 @@ export function resolve(specifier, context, nextResolve) {
|
|
|
96
96
|
url: target,
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
|
+
// A retained Strategy Worker evaluates validation and execution in separate
|
|
100
|
+
// module graphs. Carry the validation key through the local dependency tree.
|
|
101
|
+
if (context.parentURL?.includes('gar_strategy_prepare=1') && (specifier.startsWith('./') || specifier.startsWith('../'))) {
|
|
102
|
+
const parent = new URL(context.parentURL);
|
|
103
|
+
parent.searchParams.delete('gar_strategy_prepare');
|
|
104
|
+
const result = resolve(specifier, { ...context, parentURL: parent.href }, nextResolve);
|
|
105
|
+
const target = new URL(result.url);
|
|
106
|
+
if ([...esmModuleRoots].some(root => target.href.startsWith(root))) {
|
|
107
|
+
target.searchParams.set('gar_strategy_prepare', '1');
|
|
108
|
+
return { ...result, url: target.href, shortCircuit: true };
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
99
112
|
// The CLI registers tsx before this hook. Letting tsx resolve a queried
|
|
100
113
|
// user .ts/.tsx entry can percent-encode the query into a CommonJS virtual
|
|
101
114
|
// URL, which then turns public SDK imports into unresolved require() calls.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface RuntimeSqlitePaths {
|
|
2
|
+
eventLedger: string;
|
|
3
|
+
stateHistory: string;
|
|
4
|
+
inputJournal: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ArchivedScope {
|
|
7
|
+
sessionId: string;
|
|
8
|
+
segmentId: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
identity: string | null;
|
|
11
|
+
openedAt: string | null;
|
|
12
|
+
closedAt: string | null;
|
|
13
|
+
lastActivityAt: string | null;
|
|
14
|
+
open: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface RuntimeSqliteMaintenance {
|
|
17
|
+
inspect(paths: RuntimeSqlitePaths): ArchivedScope[];
|
|
18
|
+
remove(paths: RuntimeSqlitePaths, scopes: readonly Pick<ArchivedScope, 'sessionId' | 'segmentId'>[], options: {
|
|
19
|
+
inactiveBefore: string;
|
|
20
|
+
allowInactiveOpenScopes?: boolean;
|
|
21
|
+
}): void;
|
|
22
|
+
compact(paths: RuntimeSqlitePaths): void;
|
|
23
|
+
close(): void;
|
|
24
|
+
}
|
|
25
|
+
/** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
|
|
26
|
+
export declare function tryAcquireRuntimeSqliteMaintenance(directory: string): RuntimeSqliteMaintenance | null;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
+
import { tryAcquireRuntimeLock } from '../../owner/runtime-lock.js';
|
|
5
|
+
import { loadNodeSqliteModule } from '../load-node-sqlite.js';
|
|
6
|
+
/** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
|
|
7
|
+
export function tryAcquireRuntimeSqliteMaintenance(directory) {
|
|
8
|
+
const lease = tryAcquireRuntimeLock(directory);
|
|
9
|
+
if (!lease)
|
|
10
|
+
return null;
|
|
11
|
+
let root;
|
|
12
|
+
let closed = false;
|
|
13
|
+
let module;
|
|
14
|
+
try {
|
|
15
|
+
root = realpathSync(directory);
|
|
16
|
+
module = loadNodeSqliteModule(createRequire(import.meta.url));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
lease.release();
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
const connection = (paths) => {
|
|
23
|
+
if (closed)
|
|
24
|
+
throw Error('runtime_maintenance_closed');
|
|
25
|
+
const db = new module.DatabaseSync(':memory:');
|
|
26
|
+
try {
|
|
27
|
+
db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=1000');
|
|
28
|
+
for (const [alias, path] of [['eventsdb', paths.eventLedger], ['historydb', paths.stateHistory], ['epochsdb', paths.inputJournal]]) {
|
|
29
|
+
if (!existsSync(path))
|
|
30
|
+
continue;
|
|
31
|
+
const target = realpathSync(path);
|
|
32
|
+
const child = relative(root, target);
|
|
33
|
+
if (!child || isAbsolute(child) || child === '..' || child.startsWith('../') || child.startsWith('..\\')) {
|
|
34
|
+
throw Error('runtime_maintenance_path_outside_lock');
|
|
35
|
+
}
|
|
36
|
+
db.prepare(`ATTACH DATABASE ? AS ${alias}`).run(resolve(target));
|
|
37
|
+
}
|
|
38
|
+
return db;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
db.close();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const table = (db, alias, name) => {
|
|
46
|
+
if (!db.prepare('PRAGMA database_list').all().some(row => row.name === alias))
|
|
47
|
+
return false;
|
|
48
|
+
return !!db.prepare(`SELECT 1 FROM ${alias}.sqlite_schema WHERE type='table' AND name=?`).get(name);
|
|
49
|
+
};
|
|
50
|
+
const inspect = (db) => {
|
|
51
|
+
const scopes = new Map();
|
|
52
|
+
const merge = (sessionId, segmentId, at) => {
|
|
53
|
+
const key = JSON.stringify([sessionId, segmentId]);
|
|
54
|
+
let scope = scopes.get(key);
|
|
55
|
+
if (!scope) {
|
|
56
|
+
scope = { sessionId, segmentId, kind: 'unknown', identity: null, openedAt: null, closedAt: null, lastActivityAt: null, open: false };
|
|
57
|
+
scopes.set(key, scope);
|
|
58
|
+
}
|
|
59
|
+
if (at && Number.isFinite(Date.parse(at)) && (!scope.lastActivityAt || Date.parse(at) > Date.parse(scope.lastActivityAt)))
|
|
60
|
+
scope.lastActivityAt = at;
|
|
61
|
+
return scope;
|
|
62
|
+
};
|
|
63
|
+
if (table(db, 'eventsdb', 'event_segments')) {
|
|
64
|
+
for (const row of db.prepare('SELECT * FROM eventsdb.event_segments').all()) {
|
|
65
|
+
const scope = merge(row.session_id, row.segment_id, row.closed_at ?? row.opened_at);
|
|
66
|
+
Object.assign(scope, { kind: row.kind, identity: row.scope_ref ?? null, openedAt: row.opened_at,
|
|
67
|
+
closedAt: row.closed_at ?? null, open: row.status === 'open' || row.is_current === 1 });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const [alias, name, time] of [
|
|
71
|
+
['eventsdb', 'events', 'MAX(received_at)'],
|
|
72
|
+
['epochsdb', 'runtime_epochs', 'MAX(received_at)'],
|
|
73
|
+
['epochsdb', 'runtime_plugin_progress', 'MAX(updated_at)'],
|
|
74
|
+
])
|
|
75
|
+
if (table(db, alias, name)) {
|
|
76
|
+
for (const row of db.prepare(`SELECT session_id,segment_id,${time} AS at FROM ${alias}.${name} GROUP BY session_id,segment_id`).all()) {
|
|
77
|
+
merge(row.session_id, row.segment_id, row.at);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (table(db, 'historydb', 'history_scopes')) {
|
|
81
|
+
for (const row of db.prepare('SELECT * FROM historydb.history_scopes').all()) {
|
|
82
|
+
const scope = merge(row.session_id, row.segment_id, new Date(row.sealed_at_ms ?? row.opened_at_ms).toISOString());
|
|
83
|
+
scope.open ||= row.status === 'OPEN';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const name of ['state_frames', 'trajectory_records'])
|
|
87
|
+
if (table(db, 'historydb', name)) {
|
|
88
|
+
for (const row of db.prepare(`SELECT session_id,segment_id,MAX(received_at_ms) AS at FROM historydb.${name} GROUP BY session_id,segment_id`).all()) {
|
|
89
|
+
merge(row.session_id, row.segment_id, Number.isFinite(Number(row.at)) ? new Date(Number(row.at)).toISOString() : null);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return [...scopes.values()];
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
inspect(paths) { const db = connection(paths); try {
|
|
96
|
+
return inspect(db);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
db.close();
|
|
100
|
+
} },
|
|
101
|
+
remove(paths, selected, options) {
|
|
102
|
+
const cutoff = Date.parse(options.inactiveBefore);
|
|
103
|
+
if (!Number.isFinite(cutoff))
|
|
104
|
+
throw Error('runtime_maintenance_invalid_cutoff');
|
|
105
|
+
const db = connection(paths);
|
|
106
|
+
try {
|
|
107
|
+
db.exec('BEGIN IMMEDIATE');
|
|
108
|
+
const current = inspect(db);
|
|
109
|
+
for (const scope of selected) {
|
|
110
|
+
const actual = current.find(row => row.sessionId === scope.sessionId && row.segmentId === scope.segmentId);
|
|
111
|
+
if (actual && (!actual.lastActivityAt || Date.parse(actual.lastActivityAt) >= cutoff
|
|
112
|
+
|| actual.open && !options.allowInactiveOpenScopes))
|
|
113
|
+
throw Error('runtime_maintenance_scope_protected');
|
|
114
|
+
}
|
|
115
|
+
const remove = (alias, name, where, args) => {
|
|
116
|
+
if (table(db, alias, name))
|
|
117
|
+
db.prepare(`DELETE FROM ${alias}.${name} WHERE ${where}`).run(...args);
|
|
118
|
+
};
|
|
119
|
+
for (const scope of selected) {
|
|
120
|
+
const args = [scope.sessionId, scope.segmentId];
|
|
121
|
+
const eventIds = 'SELECT event_id FROM eventsdb.events WHERE session_id=? AND segment_id=?';
|
|
122
|
+
if (table(db, 'eventsdb', 'events')) {
|
|
123
|
+
remove('eventsdb', 'mailbox_items', 'session_id=? AND segment_id=?', args);
|
|
124
|
+
remove('eventsdb', 'event_deliveries', `event_id IN (${eventIds})`, args);
|
|
125
|
+
remove('eventsdb', 'source_checkpoints', `event_id IN (${eventIds})`, args);
|
|
126
|
+
remove('eventsdb', 'events', 'session_id=? AND segment_id=?', args);
|
|
127
|
+
}
|
|
128
|
+
remove('eventsdb', 'event_segments', 'session_id=? AND segment_id=?', args);
|
|
129
|
+
for (const name of ['trajectory_records', 'state_frames', 'history_scopes'])
|
|
130
|
+
remove('historydb', name, 'session_id=? AND segment_id=?', args);
|
|
131
|
+
if (table(db, 'epochsdb', 'runtime_epochs')) {
|
|
132
|
+
for (const name of ['runtime_plugin_outcomes', 'runtime_plugin_states']) {
|
|
133
|
+
remove('epochsdb', name, 'epoch_seq IN (SELECT epoch_seq FROM epochsdb.runtime_epochs WHERE session_id=? AND segment_id=?)', args);
|
|
134
|
+
}
|
|
135
|
+
remove('epochsdb', 'runtime_epochs', 'session_id=? AND segment_id=?', args);
|
|
136
|
+
}
|
|
137
|
+
remove('epochsdb', 'runtime_plugin_progress', 'session_id=? AND segment_id=?', args);
|
|
138
|
+
}
|
|
139
|
+
if (table(db, 'eventsdb', 'play_sessions')) {
|
|
140
|
+
for (const sessionId of new Set(selected.map(scope => scope.sessionId))) {
|
|
141
|
+
remove('eventsdb', 'play_sessions', 'session_id=? AND NOT EXISTS (SELECT 1 FROM eventsdb.event_segments s WHERE s.session_id=play_sessions.session_id)', [sessionId]);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
db.exec('COMMIT');
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
try {
|
|
148
|
+
db.exec('ROLLBACK');
|
|
149
|
+
}
|
|
150
|
+
catch { }
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
db.close();
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
compact(paths) {
|
|
158
|
+
const db = connection(paths);
|
|
159
|
+
try {
|
|
160
|
+
for (const row of db.prepare('PRAGMA database_list').all()) {
|
|
161
|
+
if (!['eventsdb', 'historydb', 'epochsdb'].includes(row.name))
|
|
162
|
+
continue;
|
|
163
|
+
db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
|
|
164
|
+
db.exec(`VACUUM ${row.name}`);
|
|
165
|
+
db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
db.close();
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
close() { if (!closed) {
|
|
173
|
+
closed = true;
|
|
174
|
+
lease.release();
|
|
175
|
+
} },
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -579,7 +579,7 @@ export class SqliteRuntimeInputJournal {
|
|
|
579
579
|
pluginProgress,
|
|
580
580
|
pluginRecords,
|
|
581
581
|
states,
|
|
582
|
-
nextEpochSeq: numberValue(this.db.prepare(
|
|
582
|
+
nextEpochSeq: numberValue(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='runtime_epochs' UNION ALL SELECT MAX(epoch_seq) FROM runtime_epochs)").get()?.seq) + 1,
|
|
583
583
|
};
|
|
584
584
|
}
|
|
585
585
|
findByIdentity(scope, sourceId, sourceKey) {
|
|
@@ -280,8 +280,8 @@ export class SqliteStateHistoryRepository {
|
|
|
280
280
|
scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
|
|
281
281
|
stateFrames,
|
|
282
282
|
records,
|
|
283
|
-
nextFrameSeq: Number(this.db.prepare(
|
|
284
|
-
nextRecordSeq: Number(this.db.prepare(
|
|
283
|
+
nextFrameSeq: Number(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='state_frames' UNION ALL SELECT MAX(frame_seq) FROM state_frames)").get()?.seq ?? 0) + 1,
|
|
284
|
+
nextRecordSeq: Number(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='trajectory_records' UNION ALL SELECT MAX(record_seq) FROM trajectory_records)").get()?.seq ?? 0) + 1,
|
|
285
285
|
};
|
|
286
286
|
}
|
|
287
287
|
rememberStateFrame(frame) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RuntimeEpochPluginInput, RuntimeEventProposal } from '../framework/plugins/contracts.js';
|
|
1
|
+
import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext, RuntimeEventProposal } from '../framework/plugins/contracts.js';
|
|
2
2
|
import type { EventNotificationContent } from '../framework/events/types.js';
|
|
3
3
|
import type { StrategyMemory } from '../memory/contracts.js';
|
|
4
4
|
export interface PerceptionBinding {
|
|
@@ -35,6 +35,10 @@ export interface PerceptionResult {
|
|
|
35
35
|
readonly key: string;
|
|
36
36
|
readonly wakeAgent?: boolean;
|
|
37
37
|
readonly payload: Readonly<Record<string, unknown>>;
|
|
38
|
+
readonly occurredAt?: string;
|
|
39
|
+
}[];
|
|
40
|
+
readonly forwards?: readonly {
|
|
41
|
+
readonly eventId: string;
|
|
38
42
|
}[];
|
|
39
43
|
readonly activations?: readonly (PerceptionActivation | {
|
|
40
44
|
readonly strategy: string;
|
|
@@ -58,11 +62,13 @@ export interface PerceptionBoundary {
|
|
|
58
62
|
readonly state: unknown;
|
|
59
63
|
readonly identity?: string;
|
|
60
64
|
readonly resetModules: boolean;
|
|
65
|
+
readonly resetBindings?: boolean;
|
|
61
66
|
readonly resetScope: boolean;
|
|
62
67
|
readonly notificationOnly: boolean;
|
|
63
68
|
readonly nowMs: number;
|
|
64
69
|
readonly reflexAllowed: boolean;
|
|
65
70
|
readonly value: unknown;
|
|
71
|
+
readonly consumeEventsThroughCommitSeq?: number;
|
|
66
72
|
}
|
|
67
73
|
export interface PerceptionBindingInput {
|
|
68
74
|
readonly availableBehaviors: readonly string[];
|
|
@@ -72,7 +78,8 @@ export interface PerceptionBindingInput {
|
|
|
72
78
|
export interface PerceptionAdapter {
|
|
73
79
|
reset(): void;
|
|
74
80
|
recover(checkpoint: unknown): unknown;
|
|
75
|
-
prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown): PerceptionBoundary;
|
|
81
|
+
prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown, context?: RuntimeEpochPluginContext<Record<string, any>>): PerceptionBoundary;
|
|
82
|
+
forward?(eventId: string, boundary: PerceptionBoundary, source: PerceptionSource): RuntimeEventProposal;
|
|
76
83
|
input(source: PerceptionSource, boundary: PerceptionBoundary, inputState: unknown, state: unknown, config: Readonly<Record<string, unknown>>, bindings: PerceptionBindingInput): {
|
|
77
84
|
invocation: PerceptionInvocation;
|
|
78
85
|
inputState: unknown;
|
|
@@ -10,6 +10,12 @@ export interface PerceptionHostOptions {
|
|
|
10
10
|
after: readonly string[];
|
|
11
11
|
behaviors?: () => readonly ReactionBehaviorCandidate[];
|
|
12
12
|
adapter: PerceptionAdapter;
|
|
13
|
+
notificationRelay?: RuntimeEpochPlugin['notificationRelay'];
|
|
14
|
+
/** Registration-owned budgets; script manifests cannot change these. */
|
|
15
|
+
resultLimits?: {
|
|
16
|
+
events?: number;
|
|
17
|
+
bytes?: number;
|
|
18
|
+
};
|
|
13
19
|
}
|
|
14
20
|
/** Observing and notifications remain active independently of fixed Reflex admission. */
|
|
15
21
|
export declare class PerceptionHost implements RuntimeEpochPlugin<Record<string, any>> {
|
|
@@ -27,9 +33,11 @@ export declare class PerceptionHost implements RuntimeEpochPlugin<Record<string,
|
|
|
27
33
|
readonly produces: {
|
|
28
34
|
events: readonly string[];
|
|
29
35
|
};
|
|
36
|
+
readonly notificationRelay?: RuntimeEpochPlugin['notificationRelay'];
|
|
30
37
|
private readonly sources;
|
|
31
38
|
private readonly runners;
|
|
32
39
|
private readonly failed;
|
|
40
|
+
private readonly reflexWarnings;
|
|
33
41
|
private checkpoint;
|
|
34
42
|
constructor(options: PerceptionHostOptions);
|
|
35
43
|
private driver?;
|
|
@@ -16,13 +16,16 @@ export class PerceptionHost {
|
|
|
16
16
|
after;
|
|
17
17
|
consumes;
|
|
18
18
|
produces;
|
|
19
|
+
notificationRelay;
|
|
19
20
|
sources;
|
|
20
21
|
runners = new Map();
|
|
21
22
|
failed = new Set();
|
|
23
|
+
reflexWarnings = [];
|
|
22
24
|
checkpoint = { modules: {}, failures: [] };
|
|
23
25
|
constructor(options) {
|
|
24
26
|
this.options = options;
|
|
25
27
|
this.id = options.id;
|
|
28
|
+
this.notificationRelay = options.notificationRelay;
|
|
26
29
|
this.sources = options.sources.filter(s => s.module).map(source => ({ ...source, module: normalizePerceptionManifestNames(source.module) })).sort((a, b) => a.id.localeCompare(b.id));
|
|
27
30
|
this.after = options.after;
|
|
28
31
|
this.consumes = { events: [...new Set(this.sources.flatMap(source => [...(source.module.consumes ?? [])]))] };
|
|
@@ -116,6 +119,7 @@ export class PerceptionHost {
|
|
|
116
119
|
this.watches.clear();
|
|
117
120
|
this.configs.clear();
|
|
118
121
|
this.checkpoint = { modules: {}, failures: [] };
|
|
122
|
+
this.reflexWarnings.length = 0;
|
|
119
123
|
this.failed.clear();
|
|
120
124
|
this.options.adapter.reset();
|
|
121
125
|
await Promise.all(this.sources.map(async (source, index) => {
|
|
@@ -158,26 +162,29 @@ export class PerceptionHost {
|
|
|
158
162
|
return this.sources.filter(source => !this.failed.has(source.id)).map(source => this.options.adapter.describe(source, locale));
|
|
159
163
|
}
|
|
160
164
|
async update(input, context) {
|
|
161
|
-
const prepared = this.options.adapter.prepare(input, this.checkpoint.adapterState);
|
|
165
|
+
const prepared = this.options.adapter.prepare(input, this.checkpoint.adapterState, context);
|
|
162
166
|
if (prepared.notificationOnly)
|
|
163
167
|
return { outcome: 'noop', reason: 'notification_only' };
|
|
164
168
|
this.scope = { ...input.epoch.scope };
|
|
165
169
|
if (prepared.resetScope)
|
|
166
170
|
this.checkpoint = { modules: {}, failures: [] };
|
|
167
|
-
|
|
168
|
-
|
|
171
|
+
for (const state of Object.values(this.checkpoint.modules)) {
|
|
172
|
+
if (prepared.resetModules)
|
|
169
173
|
state.value = undefined;
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
174
|
+
if (!(prepared.resetBindings ?? prepared.resetModules))
|
|
175
|
+
continue;
|
|
176
|
+
for (const binding of Object.values(state.bindings)) {
|
|
177
|
+
binding.armed = true;
|
|
178
|
+
binding.lastAcceptedAt = undefined;
|
|
179
|
+
binding.failedAttempt = undefined;
|
|
175
180
|
}
|
|
181
|
+
}
|
|
176
182
|
this.checkpoint.adapterState = prepared.state;
|
|
177
183
|
const nowMs = prepared.nowMs;
|
|
178
184
|
this.lastNow = nowMs;
|
|
179
185
|
const candidates = this.options.behaviors?.() ?? [];
|
|
180
|
-
const events =
|
|
186
|
+
const events = this.reflexWarnings.splice(0)
|
|
187
|
+
.filter(warning => warning.current()).map(warning => warning.event);
|
|
181
188
|
const requests = [];
|
|
182
189
|
const results = await mapConcurrent(this.sources, 4, async (source) => {
|
|
183
190
|
const events = [];
|
|
@@ -213,7 +220,11 @@ export class PerceptionHost {
|
|
|
213
220
|
for (const event of result.events ?? []) {
|
|
214
221
|
const proposal = { type: event.type,
|
|
215
222
|
dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
|
|
216
|
-
payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() };
|
|
223
|
+
payload: { ...event.payload }, occurredAt: event.occurredAt ?? new Date(nowMs).toISOString() };
|
|
224
|
+
events.push({ ...proposal, notificationContent: this.options.adapter.notification(proposal, prepared, source) });
|
|
225
|
+
}
|
|
226
|
+
for (const forward of result.forwards ?? []) {
|
|
227
|
+
const proposal = this.options.adapter.forward(forward.eventId, prepared, source);
|
|
217
228
|
events.push({ ...proposal, notificationContent: this.options.adapter.notification(proposal, prepared, source) });
|
|
218
229
|
}
|
|
219
230
|
const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
|
|
@@ -270,6 +281,8 @@ export class PerceptionHost {
|
|
|
270
281
|
const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
|
|
271
282
|
if (state.failedAttempt === attempt)
|
|
272
283
|
continue;
|
|
284
|
+
const current = () => !this.stopped && !context.signal.aborted && generation === this.generation
|
|
285
|
+
&& !!behavior && this.watches.has(behavior) && this.sameScope(input.epoch.scope);
|
|
273
286
|
let result = { accepted: false, reason: 'behavior_not_loaded' };
|
|
274
287
|
if (behavior && this.watches.has(behavior)) {
|
|
275
288
|
try {
|
|
@@ -278,53 +291,81 @@ export class PerceptionHost {
|
|
|
278
291
|
epochId: input.epoch.epochSeq, configGeneration: generation, behavior,
|
|
279
292
|
behaviorInput: { ...binding.input, ...activation.input }, reflexPriority: binding.reflexPriority ?? 0,
|
|
280
293
|
maxRuntimeMs: binding.maxRuntimeMs ?? 10_000,
|
|
281
|
-
reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` }, { isCurrent:
|
|
282
|
-
&& this.watches.has(behavior) && this.sameScope(input.epoch.scope) })
|
|
294
|
+
reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` }, { isCurrent: current })
|
|
283
295
|
?? { accepted: false, reason: 'activation_unavailable' };
|
|
284
296
|
}
|
|
285
297
|
catch {
|
|
286
298
|
result = { accepted: false, reason: 'activation_unavailable' };
|
|
287
299
|
}
|
|
288
300
|
}
|
|
289
|
-
|
|
301
|
+
const accept = (acceptedAt) => {
|
|
290
302
|
state.armed = false;
|
|
291
|
-
state.lastAcceptedAt =
|
|
303
|
+
state.lastAcceptedAt = acceptedAt;
|
|
292
304
|
state.warning = undefined;
|
|
293
305
|
state.failedAttempt = undefined;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
const reason = result.reason ?? 'activation_unavailable';
|
|
306
|
+
};
|
|
307
|
+
const reject = (reason) => {
|
|
297
308
|
state.failedAttempt = attempt;
|
|
298
|
-
if (state.warning
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
309
|
+
if (state.warning === reason)
|
|
310
|
+
return undefined;
|
|
311
|
+
state.warning = reason;
|
|
312
|
+
state.warningSequence++;
|
|
313
|
+
return { type: 'perception.behavior_unavailable', wakeAgent: true,
|
|
314
|
+
dedupeKey: JSON.stringify([prepared.identity, source.id, activation.behavior, state.warningSequence]),
|
|
315
|
+
payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
|
|
316
|
+
...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
|
|
317
|
+
...(behavior ? { behavior_id: behavior } : {}), reason,
|
|
318
|
+
text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } };
|
|
319
|
+
};
|
|
320
|
+
if (result.accepted && result.ready) {
|
|
321
|
+
void result.ready.then(outcome => {
|
|
322
|
+
if (!current())
|
|
323
|
+
return;
|
|
324
|
+
if (outcome === 'ready')
|
|
325
|
+
accept(this.lastNow ?? nowMs);
|
|
326
|
+
if (outcome === 'invalid') {
|
|
327
|
+
const event = reject('binding_invalid');
|
|
328
|
+
if (event)
|
|
329
|
+
this.reflexWarnings.push({ event, current });
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
else if (result.accepted) {
|
|
334
|
+
accept(nowMs);
|
|
335
|
+
}
|
|
336
|
+
else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason)) {
|
|
337
|
+
const event = reject(result.reason);
|
|
338
|
+
if (event)
|
|
339
|
+
events.push(event);
|
|
308
340
|
}
|
|
309
341
|
}
|
|
310
342
|
return { outcome: 'processed', events: events.map(event => ({ ...event,
|
|
311
343
|
notificationContent: event.notificationContent ?? this.options.adapter.notification(event, prepared) })), checkpoint: structuredClone(this.checkpoint),
|
|
312
|
-
...(
|
|
344
|
+
...(prepared.consumeEventsThroughCommitSeq !== undefined
|
|
345
|
+
? { consumeEventsThroughCommitSeq: prepared.consumeEventsThroughCommitSeq }
|
|
346
|
+
: input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1).commitSeq } : {}) };
|
|
313
347
|
}
|
|
314
348
|
validate(result, source) {
|
|
315
|
-
if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
|
|
349
|
+
if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'forwards', 'activations'].includes(key))
|
|
316
350
|
|| result.events !== undefined && !Array.isArray(result.events)
|
|
317
351
|
|| result.activations !== undefined && !Array.isArray(result.activations)
|
|
318
|
-
||
|
|
319
|
-
||
|
|
352
|
+
|| result.forwards !== undefined && (!this.notificationRelay || !this.options.adapter.forward || !Array.isArray(result.forwards))
|
|
353
|
+
|| (result.events?.length ?? 0) > (this.options.resultLimits?.events ?? 32) || (result.activations?.length ?? 0) > 16
|
|
354
|
+
|| Buffer.byteLength(JSON.stringify(result)) > (this.options.resultLimits?.bytes ?? 128_000))
|
|
320
355
|
throw new Error('REACTION_OUTPUT_INVALID');
|
|
321
356
|
for (const event of result.events ?? []) {
|
|
322
357
|
if (!record(event) || !source.module.produces?.includes(event.type)
|
|
323
358
|
|| typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
|
|
324
359
|
|| event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
|
|
360
|
+
|| event.occurredAt !== undefined && (typeof event.occurredAt !== 'string' || !Number.isFinite(Date.parse(event.occurredAt)))
|
|
325
361
|
|| !record(event.payload))
|
|
326
362
|
throw new Error('REACTION_EVENT_INVALID');
|
|
327
363
|
}
|
|
364
|
+
for (const forward of result.forwards ?? []) {
|
|
365
|
+
if (!record(forward) || typeof forward.eventId !== 'string' || !forward.eventId
|
|
366
|
+
|| Object.keys(forward).some(key => key !== 'eventId'))
|
|
367
|
+
throw Error('PERCEPTION_FORWARD_INVALID');
|
|
368
|
+
}
|
|
328
369
|
const bindings = new Set();
|
|
329
370
|
for (const activation of result.activations ?? []) {
|
|
330
371
|
if (!record(activation) || typeof activation.behavior !== 'string' || !Object.hasOwn(source.module.behaviors ?? {}, activation.behavior)
|
|
@@ -83,6 +83,8 @@ export declare class BehaviorActivationManager {
|
|
|
83
83
|
cancel(activationId: string, reason: string, now: number): readonly BehaviorActivationTransition[];
|
|
84
84
|
advance(now: number): readonly BehaviorActivationTransition[];
|
|
85
85
|
current(): BehaviorActivationSnapshot | undefined;
|
|
86
|
+
/** Install normalized input before an asynchronously prepared activation gets control. */
|
|
87
|
+
setPreparedInput(activationId: string, generation: number, input: Readonly<Record<string, unknown>>, now: number): void;
|
|
86
88
|
/** New immutable input, same activation and deadline; old decision generations expire. */
|
|
87
89
|
updateInput(activationId: string, input: Readonly<Record<string, unknown>>, now: number): readonly BehaviorActivationTransition[];
|
|
88
90
|
updateFallbackInput(behaviorId: string, input: Readonly<Record<string, unknown>>): void;
|
|
@@ -255,6 +255,17 @@ export class BehaviorActivationManager {
|
|
|
255
255
|
current() {
|
|
256
256
|
return this.snapshotActivation(this.reflex ?? this.short ?? (this.long?.state === 'running' ? this.long : undefined));
|
|
257
257
|
}
|
|
258
|
+
/** Install normalized input before an asynchronously prepared activation gets control. */
|
|
259
|
+
setPreparedInput(activationId, generation, input, now) {
|
|
260
|
+
const layer = this.findLayer(activationId);
|
|
261
|
+
const activation = layer ? this[layer] : undefined;
|
|
262
|
+
if (!activation || activation.instanceGeneration !== generation)
|
|
263
|
+
return;
|
|
264
|
+
activation.spec = { ...activation.spec, input: cloneInput(input) };
|
|
265
|
+
activation.startedAt = now;
|
|
266
|
+
if (activation.spec.maxRuntimeMs !== undefined)
|
|
267
|
+
activation.deadlineAt = now + activation.spec.maxRuntimeMs;
|
|
268
|
+
}
|
|
258
269
|
/** New immutable input, same activation and deadline; old decision generations expire. */
|
|
259
270
|
updateInput(activationId, input, now) {
|
|
260
271
|
const active = [this.long, this.short, this.reflex].find(entry => entry?.spec.activationId === activationId);
|
|
@@ -99,6 +99,7 @@ export interface PreparedStrategy {
|
|
|
99
99
|
readonly createModule?: () => object;
|
|
100
100
|
readonly source?: unknown;
|
|
101
101
|
readonly value: unknown;
|
|
102
|
+
readonly discardWorker?: () => void;
|
|
102
103
|
}
|
|
103
104
|
export interface StrategyObservation {
|
|
104
105
|
readonly revision: number;
|
|
@@ -178,6 +179,7 @@ export type ReflexResult = Readonly<{
|
|
|
178
179
|
accepted: true;
|
|
179
180
|
activationId: string;
|
|
180
181
|
replacedActivationId?: string;
|
|
182
|
+
ready?: Promise<'ready' | 'invalid' | 'cancelled'>;
|
|
181
183
|
}> | Readonly<{
|
|
182
184
|
accepted: false;
|
|
183
185
|
reason: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StrategyMemoryStore } from '../memory/strategy-memory.js';
|
|
2
|
-
import type { RuntimeEpochCatchUp, RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../framework/plugins/contracts.js';
|
|
2
|
+
import type { RuntimeEpochCatchUp, RuntimeEpochFlushReason, RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../framework/plugins/contracts.js';
|
|
3
3
|
import { BehaviorActivationManager, type BehaviorActivationSnapshot, type BehaviorActivationSource } from './activation-manager.js';
|
|
4
4
|
import type { StrategyControlDriver } from './control-driver.js';
|
|
5
5
|
import type { StrategyAdapter, PreparedStrategy, ReflexDriver, ReflexRequest, ReflexResult } from './contracts.js';
|
|
@@ -19,6 +19,7 @@ export interface StrategyHostOptions {
|
|
|
19
19
|
readonly catalog: {
|
|
20
20
|
has(id: string): boolean;
|
|
21
21
|
prepare(id: string, input: Readonly<Record<string, unknown>>): PreparedStrategy | Promise<PreparedStrategy>;
|
|
22
|
+
prepareForActivation?(id: string, input: Readonly<Record<string, unknown>>): Promise<PreparedStrategy>;
|
|
22
23
|
};
|
|
23
24
|
readonly fallbackBehaviors?: StrategyFallbackBindings;
|
|
24
25
|
readonly manager?: BehaviorActivationManager;
|
|
@@ -85,8 +86,13 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
|
|
|
85
86
|
private readonly pendingLifecycleEvents;
|
|
86
87
|
private readonly decisionControllers;
|
|
87
88
|
private controlTail;
|
|
89
|
+
private readonly startRequests;
|
|
90
|
+
private readonly deferredDelegations;
|
|
91
|
+
private readonly deferredReflexes;
|
|
92
|
+
private pendingPreparations;
|
|
88
93
|
private driver?;
|
|
89
94
|
private scope?;
|
|
95
|
+
private scopeClosing;
|
|
90
96
|
private diagnostic?;
|
|
91
97
|
private boundaryActive;
|
|
92
98
|
private stopped;
|
|
@@ -133,16 +139,22 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
|
|
|
133
139
|
}>): Promise<ReflexResult>;
|
|
134
140
|
update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult>;
|
|
135
141
|
commit(input: RuntimeEpochPluginInput<Record<string, any>>, computation: Readonly<RuntimeEpochPluginResult>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult>;
|
|
142
|
+
flush(reason: RuntimeEpochFlushReason): void;
|
|
136
143
|
stop(reason: 'segment_ending' | 'shutdown'): Promise<void>;
|
|
137
144
|
private startLayer;
|
|
145
|
+
private sameScope;
|
|
146
|
+
private activateLayer;
|
|
138
147
|
private commitOrdered;
|
|
139
148
|
private applyDecision;
|
|
149
|
+
private deferDelegation;
|
|
140
150
|
private prepareDelegatedShort;
|
|
141
151
|
private startDelegatedShort;
|
|
142
152
|
private finishCurrent;
|
|
143
153
|
private failCurrent;
|
|
144
154
|
private applyTransitions;
|
|
145
155
|
private captureDelegationResults;
|
|
156
|
+
private deferRunner;
|
|
157
|
+
private acquireControl;
|
|
146
158
|
private ensureRuntime;
|
|
147
159
|
private syncRoleFallback;
|
|
148
160
|
/**
|
|
@@ -161,5 +173,6 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
|
|
|
161
173
|
private output;
|
|
162
174
|
private withDecisionTimeout;
|
|
163
175
|
private interruptDecisions;
|
|
176
|
+
private inBackground;
|
|
164
177
|
private enqueueControl;
|
|
165
178
|
}
|