@myclaw163/clawclaw-cli 0.8.21 → 0.8.22
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/docs/custom-modules/api-reference.md +2 -0
- package/docs/custom-modules/perception.md +25 -0
- package/docs/runtime/official-perception-modules.md +23 -0
- package/package.json +1 -1
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +2 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +25 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +7 -0
- package/src/runtime/clawclaw/owner.ts +16 -10
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +18 -11
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +2 -0
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +10 -1
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +17 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +5 -2
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +46 -15
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +2 -1
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +4 -0
- package/src/runtime/framework/events/event-ingress.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +5 -4
- package/src/runtime/framework/events/sqlite-event-repository.ts +36 -9
- package/src/runtime/framework/events/types.ts +4 -0
- package/src/runtime/framework/mailbox/types.ts +4 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -0
- package/src/runtime/framework/runtime.ts +1 -0
- package/src/runtime/mailbox-host-relay.ts +13 -12
- package/src/sdk/perception-plugin/index.ts +4 -0
|
@@ -440,6 +440,7 @@ interface PerceptionApi {
|
|
|
440
440
|
|
|
441
441
|
```ts
|
|
442
442
|
interface PerceptionEventProposal {
|
|
443
|
+
wakeAgent?: boolean; // 覆盖 Manifest 默认值;省略时继承,最终默认 true
|
|
443
444
|
readonly type: string;
|
|
444
445
|
readonly dedupeKey: string;
|
|
445
446
|
readonly dedupeScope?: 'segment' | 'session';
|
|
@@ -492,6 +493,7 @@ debugSnapshot?(): unknown;
|
|
|
492
493
|
| `localizations` | object,可选 | 本地化资源文本 |
|
|
493
494
|
| `subjectScope` | `'others' \| 'self_and_others' \| 'visible_pairs' \| 'corpses'` | 描述 Event 主体范围 |
|
|
494
495
|
| `produces` | `string[]` | 允许输出的 Event type |
|
|
496
|
+
| `wakeAgent` | boolean,可选 | 模块默认是否主动唤醒 Agent,省略为 true;单条 proposal 可覆盖 |
|
|
495
497
|
| `eventMetadata` | object,可选 | 每种 Event 的名称、说明和本地化 |
|
|
496
498
|
| `execution` | `'parallel_analysis'`,可选 | 启用 `analyze/commit` 接口 |
|
|
497
499
|
| `boundaryBaseline` | `'current_only'`,可选 | 声明边界重建能力 |
|
|
@@ -80,6 +80,7 @@ export default class MyPerception extends ClawclawPerception {
|
|
|
80
80
|
| `localizations` | 可选的本地化名称与说明 |
|
|
81
81
|
| `subjectScope` | Event 描述其他玩家、自身与他人、玩家对,还是尸体 |
|
|
82
82
|
| `produces` | 这个模块可能发布的 Event type |
|
|
83
|
+
| `wakeAgent` | 可选布尔值;模块默认是否主动唤醒 Agent,省略为 `true` |
|
|
83
84
|
| `eventMetadata` | 可选,为 `produces` 中的 Event 提供展示名称、说明与本地化 |
|
|
84
85
|
| `execution` | 可选;耗时分析模块写 `parallel_analysis` |
|
|
85
86
|
| `boundaryBaseline` | 可选;声明并行 reducer 能否仅用当前帧安全建立边界基线 |
|
|
@@ -226,11 +227,35 @@ Perception 只能返回 Event proposal:
|
|
|
226
227
|
| `payload` | 结构化业务事实 |
|
|
227
228
|
| `dedupeScope` | 可选,`segment` 或 `session` |
|
|
228
229
|
| `occurredAt` | 可选的事实发生时间 |
|
|
230
|
+
| `wakeAgent` | 可选布尔值,覆盖模块默认唤醒策略 |
|
|
229
231
|
|
|
230
232
|
`dedupeKey` 不会自动阻止模块在后续 frame 再次发布同类事实。需要“只发布一次”时,应像最小示例一样在实例或 reducer 中维护状态。
|
|
231
233
|
|
|
232
234
|
Perception 不能返回 Action、Behavior Status 或 GameState patch。
|
|
233
235
|
|
|
236
|
+
|
|
237
|
+
## 是否主动唤醒 Agent
|
|
238
|
+
|
|
239
|
+
Manifest 可声明 `wakeAgent: false`,让模块默认只积累感知。省略时默认 `true`,保持已有模块行为。单条 `PerceptionEventProposal.wakeAgent` 可以覆盖模块默认值;仅接受布尔值。
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
static readonly manifest = {
|
|
243
|
+
apiVersion: 2,
|
|
244
|
+
id: 'visual.first_sighting',
|
|
245
|
+
name: '第一次看见玩家',
|
|
246
|
+
description: '记录首次目击,随下一次通知交付。',
|
|
247
|
+
subjectScope: 'others',
|
|
248
|
+
produces: ['visual.first_sighting'],
|
|
249
|
+
wakeAgent: false,
|
|
250
|
+
} as const;
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
静默 Event 仍立即持久化并供 Behavior 消费。只有待交付批次中存在允许唤醒的 Event 时,Mailbox 才主动推送,并携带已积累的静默感知;`ccl events` 主动查询可直接读取。定时 flush、预算恢复、重连和 Runtime 重启都不会单独释放静默积压。该选项不改变视觉事实、Event type、去重身份或 Trigger 的输入。
|
|
254
|
+
|
|
255
|
+
Monitor 沿用既有预算、视觉限频和溢出提示规则。可唤醒感知的投递优先级为 50,静默感知为 40;普通名额选择、积压提示锚点和同批拆包投递优先保留较高优先级。同优先级保留原有类别与时间规则。其他事件维持原优先级,80 及以上的直推保护不变,感知不会仅因允许唤醒而绕过普通预算。只有静默感知时不生成积压提醒。Monitor 成功推出通知时,该 Ready 批次涵盖的感知就向服务器上报,包括被积压提醒覆盖的感知,无需等待 `ccl events`;Channels/Desktop 则随批次交付确认上报。上报保持 best-effort,不参与 Agent ACK。
|
|
256
|
+
|
|
257
|
+
官方模块仅尸体与跟随可唤醒。跟随在 12 个有效 tick 后确认并静默输出,累计有效跟随证据严格超过 30 tick(3 秒)时补发一次可唤醒的 `visual.following`。之后的查询快照不重复唤醒;达到阈值的关系结束可唤醒,短关系结束保持静默。短暂不满足条件的 tick 不计入有效证据。
|
|
258
|
+
|
|
234
259
|
## 怎样保存跨帧信息
|
|
235
260
|
|
|
236
261
|
普通 `update()` 模式会在同一个实例上按帧调用,因此可以用类字段保存轨迹状态。状态应只描述当前连续视觉片段。
|
|
@@ -345,3 +345,26 @@ ccl perception --enable visual.follow
|
|
|
345
345
|
## 实现真值
|
|
346
346
|
|
|
347
347
|
本文的官方清单对应 `src/runtime/clawclaw/plugins/perception/official-module-ids.ts` 和 `official-modules.ts` 的闭合注册表。判断某个模块是否属于当前发布的官方资源,以该注册表、模块 manifest 和 `ccl perception --list` 的静态目录为准;判断某一局是否实际加载成功,还要看当次 Runtime 启动和诊断。仅存在设计稿、测试辅助模块或 Event Catalog 条目,不代表它已被官方默认装载。
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
## 是否主动唤醒 Agent
|
|
351
|
+
|
|
352
|
+
Manifest 可声明 `wakeAgent: false`,让模块默认只积累感知。省略时默认 `true`,保持已有模块行为。单条 `PerceptionEventProposal.wakeAgent` 可以覆盖模块默认值;仅接受布尔值。
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
static readonly manifest = {
|
|
356
|
+
apiVersion: 2,
|
|
357
|
+
id: 'visual.first_sighting',
|
|
358
|
+
name: '第一次看见玩家',
|
|
359
|
+
description: '记录首次目击,随下一次通知交付。',
|
|
360
|
+
subjectScope: 'others',
|
|
361
|
+
produces: ['visual.first_sighting'],
|
|
362
|
+
wakeAgent: false,
|
|
363
|
+
} as const;
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
静默 Event 仍立即持久化并供 Behavior 消费。只有待交付批次中存在允许唤醒的 Event 时,Mailbox 才主动推送,并携带已积累的静默感知;`ccl events` 主动查询可直接读取。定时 flush、预算恢复、重连和 Runtime 重启都不会单独释放静默积压。该选项不改变视觉事实、Event type、去重身份或 Trigger 的输入。
|
|
367
|
+
|
|
368
|
+
Monitor 沿用既有预算、视觉限频和溢出提示规则。只有静默感知时不生成积压提醒。Monitor 成功推出通知时,该 Ready 批次涵盖的感知就向服务器上报,包括被积压提醒覆盖的感知,无需等待 `ccl events`;Channels/Desktop 则随批次交付确认上报。上报保持 best-effort,不参与 Agent ACK。
|
|
369
|
+
|
|
370
|
+
官方模块仅尸体与跟随可唤醒。跟随在 12 个有效 tick 后确认并静默输出,累计有效跟随证据严格超过 30 tick(3 秒)时补发一次可唤醒的 `visual.following`。之后的查询快照不重复唤醒;达到阈值的关系结束可唤醒,短关系结束保持静默。短暂不满足条件的 tick 不计入有效证据。
|
package/package.json
CHANGED
|
@@ -436,6 +436,7 @@ interface PerceptionApi {
|
|
|
436
436
|
|
|
437
437
|
```ts
|
|
438
438
|
interface PerceptionEventProposal {
|
|
439
|
+
wakeAgent?: boolean; // 覆盖 Manifest 默认值;省略时继承,最终默认 true
|
|
439
440
|
readonly type: string;
|
|
440
441
|
readonly dedupeKey: string;
|
|
441
442
|
readonly dedupeScope?: 'segment' | 'session';
|
|
@@ -488,6 +489,7 @@ debugSnapshot?(): unknown;
|
|
|
488
489
|
| `localizations` | object,可选 | 本地化资源文本 |
|
|
489
490
|
| `subjectScope` | `'others' \| 'self_and_others' \| 'visible_pairs' \| 'corpses'` | 描述 Event 主体范围 |
|
|
490
491
|
| `produces` | `string[]` | 允许输出的 Event type |
|
|
492
|
+
| `wakeAgent` | boolean,可选 | 模块默认是否主动唤醒 Agent,省略为 true;单条 proposal 可覆盖 |
|
|
491
493
|
| `eventMetadata` | object,可选 | 每种 Event 的名称、说明和本地化 |
|
|
492
494
|
| `execution` | `'parallel_analysis'`,可选 | 启用 `analyze/commit` 接口 |
|
|
493
495
|
| `boundaryBaseline` | `'current_only'`,可选 | 声明边界重建能力 |
|
|
@@ -80,6 +80,7 @@ export default class MyPerception extends ClawclawPerception {
|
|
|
80
80
|
| `localizations` | 可选的本地化名称与说明 |
|
|
81
81
|
| `subjectScope` | Event 描述其他玩家、自身与他人、玩家对,还是尸体 |
|
|
82
82
|
| `produces` | 这个模块可能发布的 Event type |
|
|
83
|
+
| `wakeAgent` | 可选布尔值;模块默认是否主动唤醒 Agent,省略为 `true` |
|
|
83
84
|
| `eventMetadata` | 可选,为 `produces` 中的 Event 提供展示名称、说明与本地化 |
|
|
84
85
|
| `execution` | 可选;耗时分析模块写 `parallel_analysis` |
|
|
85
86
|
| `boundaryBaseline` | 可选;声明并行 reducer 能否仅用当前帧安全建立边界基线 |
|
|
@@ -226,11 +227,35 @@ Perception 只能返回 Event proposal:
|
|
|
226
227
|
| `payload` | 结构化业务事实 |
|
|
227
228
|
| `dedupeScope` | 可选,`segment` 或 `session` |
|
|
228
229
|
| `occurredAt` | 可选的事实发生时间 |
|
|
230
|
+
| `wakeAgent` | 可选布尔值,覆盖模块默认唤醒策略 |
|
|
229
231
|
|
|
230
232
|
`dedupeKey` 不会自动阻止模块在后续 frame 再次发布同类事实。需要“只发布一次”时,应像最小示例一样在实例或 reducer 中维护状态。
|
|
231
233
|
|
|
232
234
|
Perception 不能返回 Action、Behavior Status 或 GameState patch。
|
|
233
235
|
|
|
236
|
+
|
|
237
|
+
## 是否主动唤醒 Agent
|
|
238
|
+
|
|
239
|
+
Manifest 可声明 `wakeAgent: false`,让模块默认只积累感知。省略时默认 `true`,保持已有模块行为。单条 `PerceptionEventProposal.wakeAgent` 可以覆盖模块默认值;仅接受布尔值。
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
static readonly manifest = {
|
|
243
|
+
apiVersion: 2,
|
|
244
|
+
id: 'visual.first_sighting',
|
|
245
|
+
name: '第一次看见玩家',
|
|
246
|
+
description: '记录首次目击,随下一次通知交付。',
|
|
247
|
+
subjectScope: 'others',
|
|
248
|
+
produces: ['visual.first_sighting'],
|
|
249
|
+
wakeAgent: false,
|
|
250
|
+
} as const;
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
静默 Event 仍立即持久化并供 Behavior 消费。只有待交付批次中存在允许唤醒的 Event 时,Mailbox 才主动推送,并携带已积累的静默感知;`ccl events` 主动查询可直接读取。定时 flush、预算恢复、重连和 Runtime 重启都不会单独释放静默积压。该选项不改变视觉事实、Event type、去重身份或 Trigger 的输入。
|
|
254
|
+
|
|
255
|
+
Monitor 沿用既有预算、视觉限频和溢出提示规则。可唤醒感知的投递优先级为 50,静默感知为 40;普通名额选择、积压提示锚点和同批拆包投递优先保留较高优先级。同优先级保留原有类别与时间规则。其他事件维持原优先级,80 及以上的直推保护不变,感知不会仅因允许唤醒而绕过普通预算。只有静默感知时不生成积压提醒。Monitor 成功推出通知时,该 Ready 批次涵盖的感知就向服务器上报,包括被积压提醒覆盖的感知,无需等待 `ccl events`;Channels/Desktop 则随批次交付确认上报。上报保持 best-effort,不参与 Agent ACK。
|
|
256
|
+
|
|
257
|
+
官方模块仅尸体与跟随可唤醒。跟随在 12 个有效 tick 后确认并静默输出,累计有效跟随证据严格超过 30 tick(3 秒)时补发一次可唤醒的 `visual.following`。之后的查询快照不重复唤醒;达到阈值的关系结束可唤醒,短关系结束保持静默。短暂不满足条件的 tick 不计入有效证据。
|
|
258
|
+
|
|
234
259
|
## 怎样保存跨帧信息
|
|
235
260
|
|
|
236
261
|
普通 `update()` 模式会在同一个实例上按帧调用,因此可以用类字段保存轨迹状态。状态应只描述当前连续视觉片段。
|
|
@@ -46,6 +46,13 @@ export function clawclawMonitorPriority(type: string): number {
|
|
|
46
46
|
return CLAWCLAW_MONITOR_EVENT_PRIORITY[type] ?? DEFAULT_MONITOR_PRIORITY;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** Resolved per-event priority; wake policy only changes visual Event ranking. */
|
|
50
|
+
export function clawclawMonitorEventPriority(event: { type: string; wakeAgent?: boolean }): number {
|
|
51
|
+
return event.type.startsWith('visual.')
|
|
52
|
+
? event.wakeAgent === false ? 40 : 50
|
|
53
|
+
: clawclawMonitorPriority(event.type);
|
|
54
|
+
}
|
|
55
|
+
|
|
49
56
|
export function clawclawMonitorDelayMs(type: string): number {
|
|
50
57
|
return CLAWCLAW_MONITOR_DELAY_MS[type] ?? 0;
|
|
51
58
|
}
|
|
@@ -897,9 +897,19 @@ export async function runClawclawOwner(
|
|
|
897
897
|
throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
|
|
898
898
|
}
|
|
899
899
|
const mailboxRepository = runtime.repository;
|
|
900
|
+
const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
|
|
901
|
+
producerPluginId: assembly.perception.id,
|
|
902
|
+
descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
|
|
903
|
+
eventType,
|
|
904
|
+
client.gameSyncLocale,
|
|
905
|
+
),
|
|
906
|
+
send: (reports) => client.reportGameSyncPerceptions(reports),
|
|
907
|
+
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
908
|
+
});
|
|
900
909
|
cclEventsMailbox = new AgentMailboxCoordinator({
|
|
901
910
|
repository: mailboxRepository,
|
|
902
911
|
readyView: () => runtime!.readReadyView(0, 1),
|
|
912
|
+
onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
|
|
903
913
|
presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents),
|
|
904
914
|
compactState: compactStateForEvents,
|
|
905
915
|
eventFilter: clawclawEventRequiresDetails,
|
|
@@ -921,24 +931,15 @@ export async function runClawclawOwner(
|
|
|
921
931
|
monitorEnabled: !!options.notificationHost,
|
|
922
932
|
diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity),
|
|
923
933
|
});
|
|
924
|
-
const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
|
|
925
|
-
producerPluginId: assembly.perception.id,
|
|
926
|
-
descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
|
|
927
|
-
eventType,
|
|
928
|
-
client.gameSyncLocale,
|
|
929
|
-
),
|
|
930
|
-
send: (reports) => client.reportGameSyncPerceptions(reports),
|
|
931
|
-
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
932
|
-
});
|
|
933
934
|
const mailboxDrivers: ClawclawMailboxDriver[] = [
|
|
934
935
|
mailboxService,
|
|
935
936
|
cclEventsMailbox,
|
|
936
|
-
perceptionReportAdapter,
|
|
937
937
|
];
|
|
938
938
|
if (options.desktopEvents) {
|
|
939
939
|
desktopMailbox = new AgentMailboxCoordinator({
|
|
940
940
|
repository: mailboxRepository,
|
|
941
941
|
readyView: () => runtime!.readReadyView(0, 1),
|
|
942
|
+
onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
|
|
942
943
|
presentEvent: ownerAgentEventPresenter('desktop_ipc', true),
|
|
943
944
|
compactState: compactStateForEvents,
|
|
944
945
|
consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
|
|
@@ -993,6 +994,7 @@ export async function runClawclawOwner(
|
|
|
993
994
|
assembly.behavior.attachDriver(createClawclawBehaviorControlDriver(runtime));
|
|
994
995
|
if (channelPolicy.enabled) {
|
|
995
996
|
channelAdapter = new ClaudeChannelMailboxAdapter({
|
|
997
|
+
onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
|
|
996
998
|
repository: mailboxRepository,
|
|
997
999
|
readyView: () => runtime!.readReadyView(0, 1),
|
|
998
1000
|
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
@@ -1080,6 +1082,10 @@ export async function runClawclawOwner(
|
|
|
1080
1082
|
mailboxRepository,
|
|
1081
1083
|
'short',
|
|
1082
1084
|
MONITOR_MAILBOX_CONSUMER_ID,
|
|
1085
|
+
undefined,
|
|
1086
|
+
(eventIds) => {
|
|
1087
|
+
perceptionReportAdapter.reportDelivered(mailboxService!.monitorDeliveredEvents(eventIds));
|
|
1088
|
+
},
|
|
1083
1089
|
);
|
|
1084
1090
|
relayAbort = new AbortController();
|
|
1085
1091
|
relayAlive = true;
|
|
@@ -705,7 +705,13 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
705
705
|
computation: Readonly<RuntimeEpochPluginResult>,
|
|
706
706
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
707
707
|
): Promise<RuntimeEpochPluginResult> {
|
|
708
|
-
return this.enqueueControl(() =>
|
|
708
|
+
return this.enqueueControl(async () => {
|
|
709
|
+
const result = await this.commitOrdered(input, proposal(computation.proposal), context);
|
|
710
|
+
// Report the final activation after this epoch's advances, finishes and
|
|
711
|
+
// boundary transitions, rather than the activation it started with.
|
|
712
|
+
this.refreshBackendStrategyReport(input, context);
|
|
713
|
+
return result;
|
|
714
|
+
});
|
|
709
715
|
}
|
|
710
716
|
|
|
711
717
|
async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
|
|
@@ -797,7 +803,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
797
803
|
const runtimeState = input.epoch.state;
|
|
798
804
|
|
|
799
805
|
await this.syncRoleFallback(frameForClock, now);
|
|
800
|
-
this.refreshBackendStrategyReport(input, context);
|
|
801
806
|
|
|
802
807
|
await this.applyTransitions(this.manager.advance(now));
|
|
803
808
|
const currentForFrame = this.manager.current();
|
|
@@ -1344,17 +1349,19 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1344
1349
|
|
|
1345
1350
|
/**
|
|
1346
1351
|
* The backend still calls this display-only field a Strategy. Report the
|
|
1347
|
-
*
|
|
1352
|
+
* current activation, including short/reflex overrides. A configured fallback
|
|
1353
|
+
* or suspended long is not active until the manager gives it control.
|
|
1348
1354
|
*/
|
|
1349
1355
|
private backendStrategyDescriptor(): ClawclawResolvedResourceMetadata | undefined {
|
|
1350
|
-
const
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1356
|
+
const current = this.manager.current();
|
|
1357
|
+
if (!current) return {
|
|
1358
|
+
// The backend requires non-empty display text and has no clear action.
|
|
1359
|
+
id: 'clawclaw:no-active-behavior',
|
|
1360
|
+
name: '无策略在运行',
|
|
1361
|
+
description: '当前没有活跃的策略。',
|
|
1362
|
+
};
|
|
1363
|
+
const prepared = this.runtimes.get(current.activationId)?.prepared;
|
|
1364
|
+
if (!prepared || prepared.manifest.id !== current.behaviorId) return undefined;
|
|
1358
1365
|
return resolveClawclawResourceMetadata({
|
|
1359
1366
|
id: prepared.manifest.id,
|
|
1360
1367
|
name: prepared.manifest.name,
|
|
@@ -15,6 +15,7 @@ export const CLAUDE_CHANNEL_CONSUMER_ID = CLAUDE_CHANNEL_MAILBOX_CONSUMER_ID;
|
|
|
15
15
|
export const CLAUDE_CHANNEL_COALESCE_MS = 220;
|
|
16
16
|
|
|
17
17
|
export interface ClaudeChannelMailboxAdapterOptions {
|
|
18
|
+
onDelivered?: (events: readonly CanonicalEvent[]) => void;
|
|
18
19
|
repository: EventRepository;
|
|
19
20
|
readyView: () => RuntimeReadyView;
|
|
20
21
|
consumerId?: string;
|
|
@@ -39,6 +40,7 @@ export class ClaudeChannelMailboxAdapter implements ClawclawMailboxDriver {
|
|
|
39
40
|
consumerId: this.consumerId,
|
|
40
41
|
};
|
|
41
42
|
this.coordinator = new AgentMailboxCoordinator({
|
|
43
|
+
onDelivered: options.onDelivered,
|
|
42
44
|
repository: options.repository,
|
|
43
45
|
readyView: options.readyView,
|
|
44
46
|
presentEvent: presentCanonicalEventForChannel,
|
package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts
CHANGED
|
@@ -56,14 +56,22 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
private stopped = false;
|
|
59
|
+
private sessionId?: string;
|
|
60
|
+
private readonly reported = new Set<string>();
|
|
59
61
|
|
|
60
62
|
constructor(private readonly options: GameSyncPerceptionReportAdapterOptions) {}
|
|
61
63
|
|
|
62
|
-
|
|
64
|
+
/** Called only at Agent delivery, including Monitor backlog notification. */
|
|
65
|
+
reportDelivered(events: readonly CanonicalEvent[]): void {
|
|
63
66
|
if (this.stopped) return;
|
|
64
67
|
let skipped = 0;
|
|
65
68
|
const reports: GameSyncPerceptionReport[] = [];
|
|
66
69
|
for (const event of events) {
|
|
70
|
+
if (this.sessionId !== event.sessionId) {
|
|
71
|
+
this.sessionId = event.sessionId;
|
|
72
|
+
this.reported.clear();
|
|
73
|
+
}
|
|
74
|
+
if (this.reported.has(event.eventId)) continue;
|
|
67
75
|
if (
|
|
68
76
|
event.producerPluginId !== this.options.producerPluginId
|
|
69
77
|
|| event.deliveryClass === 'internal_only'
|
|
@@ -75,6 +83,7 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
|
|
|
75
83
|
skipped += 1;
|
|
76
84
|
continue;
|
|
77
85
|
}
|
|
86
|
+
this.reported.add(event.eventId);
|
|
78
87
|
reports.push({
|
|
79
88
|
id: uuidForEvent(event),
|
|
80
89
|
name: descriptor.name.trim(),
|
|
@@ -51,6 +51,8 @@ export interface AgentMailboxCoordinatorOptions {
|
|
|
51
51
|
state: Record<string, any> | null | undefined,
|
|
52
52
|
events?: Array<Record<string, any>>,
|
|
53
53
|
) => Record<string, any> | null;
|
|
54
|
+
/** Best-effort observer after this consumer accepts a batch. */
|
|
55
|
+
onDelivered?: (events: readonly CanonicalEvent[]) => void;
|
|
54
56
|
/** Adapter-specific selection; omitted adapters receive every Agent-visible Event. */
|
|
55
57
|
eventFilter?: (
|
|
56
58
|
event: CanonicalEvent,
|
|
@@ -164,6 +166,7 @@ function compactBehaviorStateForAgent(
|
|
|
164
166
|
*/
|
|
165
167
|
export class AgentMailboxCoordinator {
|
|
166
168
|
readonly adapter?: ClawclawMailboxAdapterDescriptor;
|
|
169
|
+
private readonly onDelivered?: AgentMailboxCoordinatorOptions['onDelivered'];
|
|
167
170
|
private readonly repository: EventRepository;
|
|
168
171
|
private readonly readyView: () => RuntimeReadyView;
|
|
169
172
|
private readonly presentEvent: AgentMailboxCoordinatorOptions['presentEvent'];
|
|
@@ -183,6 +186,7 @@ export class AgentMailboxCoordinator {
|
|
|
183
186
|
private stopped = false;
|
|
184
187
|
|
|
185
188
|
constructor(options: AgentMailboxCoordinatorOptions) {
|
|
189
|
+
this.onDelivered = options.onDelivered;
|
|
186
190
|
this.repository = options.repository;
|
|
187
191
|
this.readyView = options.readyView;
|
|
188
192
|
this.presentEvent = options.presentEvent;
|
|
@@ -255,6 +259,11 @@ export class AgentMailboxCoordinator {
|
|
|
255
259
|
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
256
260
|
}
|
|
257
261
|
|
|
262
|
+
if (!options.bypassDelay && !pending.some(({ event }) => event.wakeAgent !== false)) {
|
|
263
|
+
this.delayWindow = undefined;
|
|
264
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
265
|
+
}
|
|
266
|
+
|
|
258
267
|
if (this.delayWindow?.sessionId !== ready.scope.sessionId) {
|
|
259
268
|
this.delayWindow = {
|
|
260
269
|
sessionId: ready.scope.sessionId,
|
|
@@ -375,6 +384,12 @@ export class AgentMailboxCoordinator {
|
|
|
375
384
|
} as Parameters<EventRepository['transitionDetails']>[0];
|
|
376
385
|
const changed = this.repository.transitionDetails(transition);
|
|
377
386
|
if (changed !== prepared.eventIds.length) return false;
|
|
387
|
+
try {
|
|
388
|
+
this.onDelivered?.(prepared.eventIds.flatMap((id) => {
|
|
389
|
+
const event = this.repository.eventById(id);
|
|
390
|
+
return event ? [event] : [];
|
|
391
|
+
}));
|
|
392
|
+
} catch { /* Display reporting must not affect delivery ACK. */ }
|
|
378
393
|
this.prepared.delete(deliveryToken);
|
|
379
394
|
this.repository.releaseLease(prepared.lease);
|
|
380
395
|
this.notifyPreparedSlotAvailable();
|
|
@@ -452,7 +467,7 @@ export class AgentMailboxCoordinator {
|
|
|
452
467
|
}, this.consumerId, ['details']).filter((row) => (
|
|
453
468
|
this.selectsEvent(row.event, ready.state.state)
|
|
454
469
|
));
|
|
455
|
-
if (pending.
|
|
470
|
+
if (!pending.some(({ event }) => event.wakeAgent !== false) && this.prepared.size === 0) return true;
|
|
456
471
|
await new Promise<void>((resolve) => {
|
|
457
472
|
const timer = setTimeout(resolve, READY_VIEW_RETRY_MS);
|
|
458
473
|
timer.unref?.();
|
|
@@ -471,6 +486,7 @@ export class AgentMailboxCoordinator {
|
|
|
471
486
|
event: CanonicalEvent,
|
|
472
487
|
state: Record<string, any> | null | undefined,
|
|
473
488
|
): boolean {
|
|
489
|
+
if (this.delegatedMonitorConsumerId && event.deliveryClass !== 'internal_only' && event.wakeAgent === false) return true;
|
|
474
490
|
if (this.eventFilter(event, state)) return true;
|
|
475
491
|
if (!this.delegatedMonitorConsumerId) return false;
|
|
476
492
|
return this.repository.delivery(event.eventId, this.delegatedMonitorConsumerId)
|
|
@@ -7,6 +7,7 @@ import type { CanonicalEvent } from '../../../framework/events/index.js';
|
|
|
7
7
|
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
8
8
|
import {
|
|
9
9
|
clawclawMonitorPriority,
|
|
10
|
+
clawclawMonitorEventPriority,
|
|
10
11
|
} from '../../agent-event-policy.js';
|
|
11
12
|
import { isRoomMode } from '../../../../lib/room.js';
|
|
12
13
|
|
|
@@ -31,6 +32,7 @@ export const CLAWCLAW_DETAIL_EVENT_TYPES = new Set<string>([
|
|
|
31
32
|
export interface ClawclawMonitorItemPayload extends Record<string, unknown> {
|
|
32
33
|
schema: 'clawclaw.monitor-item.v1';
|
|
33
34
|
event_id: string;
|
|
35
|
+
monitor_priority?: number;
|
|
34
36
|
ready: {
|
|
35
37
|
epoch_seq: number;
|
|
36
38
|
frame_seq: number;
|
|
@@ -92,6 +94,7 @@ export function monitorItemPayload(
|
|
|
92
94
|
const fullMessage = fullMonitorMessage(presented, ready.state.state);
|
|
93
95
|
return {
|
|
94
96
|
schema: 'clawclaw.monitor-item.v1',
|
|
97
|
+
monitor_priority: clawclawMonitorEventPriority(event),
|
|
95
98
|
event_id: event.eventId,
|
|
96
99
|
ready: {
|
|
97
100
|
epoch_seq: ready.epochSeq,
|
|
@@ -111,8 +114,8 @@ function orderedItems(items: readonly ClawclawMonitorItemPayload[]): ClawclawMon
|
|
|
111
114
|
return items
|
|
112
115
|
.map((item, index) => ({ item, index }))
|
|
113
116
|
.sort((left, right) => (
|
|
114
|
-
clawclawMonitorPriority(String(right.item.event.type ?? ''))
|
|
115
|
-
- clawclawMonitorPriority(String(left.item.event.type ?? ''))
|
|
117
|
+
(right.item.monitor_priority ?? clawclawMonitorPriority(String(right.item.event.type ?? '')))
|
|
118
|
+
- (left.item.monitor_priority ?? clawclawMonitorPriority(String(left.item.event.type ?? '')))
|
|
116
119
|
|| left.index - right.index
|
|
117
120
|
))
|
|
118
121
|
.map(({ item }) => item);
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
} from '../../../framework/mailbox/index.js';
|
|
14
14
|
import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contracts.js';
|
|
15
15
|
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
16
|
-
import {
|
|
16
|
+
import { clawclawMonitorEventPriority } from '../../agent-event-policy.js';
|
|
17
17
|
import { AgentMailboxCoordinator } from './agent-mailbox-coordinator.js';
|
|
18
18
|
import type {
|
|
19
19
|
ClawclawMailboxAdapterDescriptor,
|
|
@@ -59,15 +59,15 @@ const MONITOR_NOISY_VISUAL_EVENT_TYPES = new Set([
|
|
|
59
59
|
'visual.players_moving_together',
|
|
60
60
|
]);
|
|
61
61
|
|
|
62
|
-
function monitorEventMustRemainDirect(event: Pick<CanonicalEvent, 'type'>): boolean {
|
|
62
|
+
function monitorEventMustRemainDirect(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
|
|
63
63
|
return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
|
|
64
|
-
||
|
|
64
|
+
|| clawclawMonitorEventPriority(event) >= MONITOR_PROTECTED_PRIORITY;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
function monitorDirectAdmissionPriority(event: Pick<CanonicalEvent, 'type'>): number {
|
|
67
|
+
function monitorDirectAdmissionPriority(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): number {
|
|
68
68
|
return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
|
|
69
69
|
? Number.MAX_SAFE_INTEGER
|
|
70
|
-
:
|
|
70
|
+
: clawclawMonitorEventPriority(event);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
function ordinaryMonitorRetentionRank(event: Pick<CanonicalEvent, 'type' | 'commitSeq'>): number {
|
|
@@ -77,7 +77,7 @@ function ordinaryMonitorRetentionRank(event: Pick<CanonicalEvent, 'type' | 'comm
|
|
|
77
77
|
return event.type.startsWith('visual.') ? 1 : 0;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
function monitorEventIsNoisyVisual(event: Pick<CanonicalEvent, 'type'>): boolean {
|
|
80
|
+
function monitorEventIsNoisyVisual(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
|
|
81
81
|
return MONITOR_NOISY_VISUAL_EVENT_TYPES.has(event.type);
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -340,7 +340,7 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
340
340
|
row.event.eventId,
|
|
341
341
|
'short',
|
|
342
342
|
));
|
|
343
|
-
if (unprojected.length === 0) return 0;
|
|
343
|
+
if (unprojected.length === 0 || !unprojected.some(({ event }) => event.wakeAgent !== false)) return 0;
|
|
344
344
|
|
|
345
345
|
const nowMs = this.now();
|
|
346
346
|
this.pruneMonitorAdmissionWindows(nowMs);
|
|
@@ -414,15 +414,19 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
414
414
|
const noisyVisualEvents = allOrdinaryEvents
|
|
415
415
|
.filter((row) => monitorEventIsNoisyVisual(row.event))
|
|
416
416
|
.sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
417
|
-
const directVisualCandidate = visualAdmissionAvailable ? noisyVisualEvents.
|
|
417
|
+
const directVisualCandidate = visualAdmissionAvailable ? [...noisyVisualEvents].sort((left, right) => (
|
|
418
|
+
clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
|
|
419
|
+
|| right.event.commitSeq - left.event.commitSeq
|
|
420
|
+
))[0] : undefined;
|
|
418
421
|
const coalescedVisualOverflow = directVisualCandidate
|
|
419
|
-
? noisyVisualEvents.
|
|
422
|
+
? noisyVisualEvents.filter((row) => row !== directVisualCandidate)
|
|
420
423
|
: noisyVisualEvents;
|
|
421
424
|
const ordinaryEvents = allOrdinaryEvents
|
|
422
425
|
.filter((row) => !monitorEventIsNoisyVisual(row.event))
|
|
423
426
|
.concat(directVisualCandidate ? [directVisualCandidate] : [])
|
|
424
427
|
.sort((left, right) => (
|
|
425
|
-
|
|
428
|
+
clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
|
|
429
|
+
|| ordinaryMonitorRetentionRank(left.event) - ordinaryMonitorRetentionRank(right.event)
|
|
426
430
|
|| left.event.commitSeq - right.event.commitSeq
|
|
427
431
|
));
|
|
428
432
|
const ordinaryDirectAdmissionCount = Math.min(
|
|
@@ -438,7 +442,10 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
438
442
|
...coalescedVisualOverflow,
|
|
439
443
|
].sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
440
444
|
let direct = [...directProtected, ...directOrdinary]
|
|
441
|
-
.sort((left, right) =>
|
|
445
|
+
.sort((left, right) => (
|
|
446
|
+
monitorDirectAdmissionPriority(right.event) - monitorDirectAdmissionPriority(left.event)
|
|
447
|
+
|| left.event.commitSeq - right.event.commitSeq
|
|
448
|
+
));
|
|
442
449
|
let dedicatedBacklogHintEventId: string | undefined;
|
|
443
450
|
// A full ordinary queue still needs one durable signal. Use the first new
|
|
444
451
|
// Event as that signal's factual anchor and allow one separately-budgeted
|
|
@@ -454,16 +461,18 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
454
461
|
)
|
|
455
462
|
&& (overflow.length > 1 || (overflow.length > 0 && delegatedUnreadBefore > 0))
|
|
456
463
|
) {
|
|
457
|
-
const
|
|
464
|
+
const highestPriority = Math.max(...overflow.map(({ event }) => clawclawMonitorEventPriority(event)));
|
|
465
|
+
const preferred = overflow.filter(({ event }) => clawclawMonitorEventPriority(event) === highestPriority);
|
|
466
|
+
const firstNonVisualIndex = preferred.findIndex((row) => (
|
|
458
467
|
!row.event.type.startsWith('visual.')
|
|
459
468
|
));
|
|
460
469
|
const hintAnchorIndex = firstNonVisualIndex >= 0
|
|
461
470
|
? firstNonVisualIndex
|
|
462
|
-
:
|
|
463
|
-
const hintAnchor =
|
|
471
|
+
: preferred.length - 1;
|
|
472
|
+
const hintAnchor = preferred[hintAnchorIndex]!;
|
|
464
473
|
direct = [hintAnchor];
|
|
465
474
|
dedicatedBacklogHintEventId = hintAnchor.event.eventId;
|
|
466
|
-
overflow = overflow.filter((
|
|
475
|
+
overflow = overflow.filter((row) => row !== hintAnchor);
|
|
467
476
|
}
|
|
468
477
|
if (direct.length === 0 && overflow.length === 0) return 0;
|
|
469
478
|
// With only one newly blocked Event there is no factual anchor plus
|
|
@@ -511,6 +520,9 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
511
520
|
return { coalesceKey, payload, row };
|
|
512
521
|
});
|
|
513
522
|
});
|
|
523
|
+
// Reassign only delivery slots within this batch; canonical sequence is unchanged.
|
|
524
|
+
const slots = entries.map(({ row }) => row.event.commitSeq).sort((a, b) => a - b);
|
|
525
|
+
const deliveryOrder = new Map(entries.map((entry, index) => [entry.row.event.eventId, slots[index]!]));
|
|
514
526
|
const enqueue = (entry: typeof entries[number]) => {
|
|
515
527
|
const event = entry.row.event;
|
|
516
528
|
return this.repository.enqueueMailboxItem<Record<string, unknown>>({
|
|
@@ -527,6 +539,7 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
527
539
|
segmentId: event.segmentId,
|
|
528
540
|
eventId: event.eventId,
|
|
529
541
|
eventCommitSeq: event.commitSeq,
|
|
542
|
+
deliveryOrder: deliveryOrder.get(event.eventId),
|
|
530
543
|
mode: 'short',
|
|
531
544
|
coalesceKey: entry.coalesceKey,
|
|
532
545
|
payload: entry.payload,
|
|
@@ -623,6 +636,24 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
|
623
636
|
return inserted;
|
|
624
637
|
}
|
|
625
638
|
|
|
639
|
+
/** Monitor delivery reports every perception covered by the accepted Ready batch.
|
|
640
|
+
* A backlog hint counts as delivery for display; detail ACK is independent.
|
|
641
|
+
*/
|
|
642
|
+
monitorDeliveredEvents(eventIds: readonly string[]): CanonicalEvent[] {
|
|
643
|
+
const bounds = new Map<string, number>();
|
|
644
|
+
for (const id of eventIds) {
|
|
645
|
+
const item = this.repository.mailboxItemForEvent<Record<string, any>>(this.consumerId, id, 'short');
|
|
646
|
+
if (!item || item.state !== 'accepted') continue;
|
|
647
|
+
const through = Number(item.payload.ready?.event_commit_seq ?? item.eventCommitSeq);
|
|
648
|
+
bounds.set(item.sessionId, Math.max(bounds.get(item.sessionId) ?? 0, through));
|
|
649
|
+
}
|
|
650
|
+
const events: CanonicalEvent[] = [];
|
|
651
|
+
for (const [sessionId, through] of bounds) {
|
|
652
|
+
events.push(...this.repository.listCommittedEvents({ sessionId, maxCommitSeq: through, order: 'asc' }));
|
|
653
|
+
}
|
|
654
|
+
return events;
|
|
655
|
+
}
|
|
656
|
+
|
|
626
657
|
composeMonitor(values: readonly Record<string, unknown>[]): Record<string, unknown> {
|
|
627
658
|
const hasBacklog = values.some((value) => (
|
|
628
659
|
!!value.backlog && typeof value.backlog === 'object'
|
|
@@ -17,13 +17,14 @@ export function normalizePerceptionEvents(
|
|
|
17
17
|
!event
|
|
18
18
|
|| typeof event !== 'object'
|
|
19
19
|
|| !declared.has(event.type)
|
|
20
|
+
|| (event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean')
|
|
20
21
|
|| typeof event.dedupeKey !== 'string'
|
|
21
22
|
|| !event.dedupeKey
|
|
22
23
|
|| !event.payload
|
|
23
24
|
|| typeof event.payload !== 'object'
|
|
24
25
|
|| Array.isArray(event.payload)
|
|
25
26
|
) throw new Error(`perception_event_invalid:${index}`);
|
|
26
|
-
return structuredClone(event);
|
|
27
|
+
return structuredClone({ ...event, wakeAgent: event.wakeAgent ?? manifest.wakeAgent ?? true });
|
|
27
28
|
});
|
|
28
29
|
assertRuntimeModuleOutputSize(events, 'perception_event_output');
|
|
29
30
|
return events;
|
|
@@ -232,6 +232,7 @@ function perceptionLifecycle(frame: Readonly<PerceptionFrame>): string {
|
|
|
232
232
|
}
|
|
233
233
|
|
|
234
234
|
function hasValidPerceptionEventMetadata(manifest: ClawclawPerceptionManifest): boolean {
|
|
235
|
+
if (manifest.wakeAgent !== undefined && typeof manifest.wakeAgent !== 'boolean') return false;
|
|
235
236
|
const metadata = manifest.eventMetadata;
|
|
236
237
|
if (metadata === undefined) return true;
|
|
237
238
|
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false;
|
|
@@ -352,6 +352,9 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
352
352
|
const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
|
|
353
353
|
const localizations = literalLocalizations(manifestBlock);
|
|
354
354
|
const eventMetadata = literalEventMetadata(manifestBlock);
|
|
355
|
+
const hasWakePolicy = /\bwakeAgent\s*:/.test(manifestBlock);
|
|
356
|
+
const wakeValue = /\bwakeAgent\s*:\s*(true|false)\b\s*(?=,|}|\n|\/\/|\/\*)/.exec(manifestBlock)?.[1];
|
|
357
|
+
if (hasWakePolicy && wakeValue === undefined) return null;
|
|
355
358
|
const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
|
|
356
359
|
if (
|
|
357
360
|
!id
|
|
@@ -388,6 +391,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
388
391
|
name,
|
|
389
392
|
description,
|
|
390
393
|
...(localizations === undefined ? {} : { localizations }),
|
|
394
|
+
...(wakeValue === undefined ? {} : { wakeAgent: wakeValue === 'true' }),
|
|
391
395
|
subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
|
|
392
396
|
produces,
|
|
393
397
|
...(eventMetadata === undefined ? {} : { eventMetadata }),
|
|
@@ -73,6 +73,7 @@ export class EventIngress {
|
|
|
73
73
|
...(input.producerOutputIndex === undefined
|
|
74
74
|
? {}
|
|
75
75
|
: { producerOutputIndex: input.producerOutputIndex }),
|
|
76
|
+
...(input.wakeAgent === undefined ? {} : { wakeAgent: input.wakeAgent }),
|
|
76
77
|
deliveryClass: policy.deliveryClass,
|
|
77
78
|
occurredAt: input.occurredAt ?? receivedAt,
|
|
78
79
|
receivedAt,
|
|
@@ -642,6 +642,7 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
642
642
|
segmentId: request.segmentId,
|
|
643
643
|
eventId: request.eventId,
|
|
644
644
|
eventCommitSeq: request.eventCommitSeq,
|
|
645
|
+
...(request.deliveryOrder === undefined ? {} : { deliveryOrder: request.deliveryOrder }),
|
|
645
646
|
mode: request.mode,
|
|
646
647
|
coalesceKey: request.coalesceKey,
|
|
647
648
|
payload: cloneRecord(request.payload),
|
|
@@ -688,9 +689,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
688
689
|
rows.sort((a, b) => {
|
|
689
690
|
const direction = filter.order === 'desc' ? -1 : 1;
|
|
690
691
|
return direction * (
|
|
691
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
692
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
692
693
|
? a.itemId.localeCompare(b.itemId)
|
|
693
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
694
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
694
695
|
);
|
|
695
696
|
});
|
|
696
697
|
const limit = filter.limit === undefined
|
|
@@ -713,9 +714,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
713
714
|
&& (item.state === 'pending' || item.state === 'claimed')
|
|
714
715
|
))
|
|
715
716
|
.sort((a, b) => (
|
|
716
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
717
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
717
718
|
? a.itemId.localeCompare(b.itemId)
|
|
718
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
719
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
719
720
|
));
|
|
720
721
|
const activeRows: MailboxItem[] = [];
|
|
721
722
|
for (const item of rows) {
|
|
@@ -158,6 +158,7 @@ function segmentFromRow(row: Record<string, unknown>): EventSegmentRecord {
|
|
|
158
158
|
function eventFromRow(row: Record<string, unknown>): CanonicalEvent {
|
|
159
159
|
const payload = JSON.parse(String(row.payload_json)) as Record<string, unknown>;
|
|
160
160
|
return {
|
|
161
|
+
...(row.wake_agent === null || row.wake_agent === undefined ? {} : { wakeAgent: numberValue(row.wake_agent) !== 0 }),
|
|
161
162
|
commitSeq: numberValue(row.commit_seq),
|
|
162
163
|
...(row.epoch_seq === null || row.epoch_seq === undefined
|
|
163
164
|
? {}
|
|
@@ -223,6 +224,7 @@ function mailboxItemFromRow<T = unknown>(row: Record<string, unknown>): MailboxI
|
|
|
223
224
|
segmentId: String(row.segment_id),
|
|
224
225
|
eventId: String(row.event_id),
|
|
225
226
|
eventCommitSeq: numberValue(row.event_commit_seq),
|
|
227
|
+
...(row.delivery_order == null ? {} : { deliveryOrder: numberValue(row.delivery_order) }),
|
|
226
228
|
// New runtime code only creates short notifications. The SQLite schema
|
|
227
229
|
// still accepts historical full rows so existing ledgers open in place.
|
|
228
230
|
mode: 'short',
|
|
@@ -572,8 +574,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
572
574
|
event_id, epoch_seq, session_id, segment_id, type, producer,
|
|
573
575
|
producer_plugin_id, producer_output_index, delivery_class,
|
|
574
576
|
occurred_at, received_at, payload_json, source_id, source_event_id,
|
|
575
|
-
source_sequence, connection_id, replayed
|
|
576
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
|
+
source_sequence, connection_id, replayed, wake_agent
|
|
578
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
579
|
`).run(
|
|
578
580
|
request.event.eventId,
|
|
579
581
|
request.event.epochSeq ?? null,
|
|
@@ -592,6 +594,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
592
594
|
request.event.sourceSequence ?? null,
|
|
593
595
|
request.event.connectionId ?? null,
|
|
594
596
|
booleanInt(request.event.replayed),
|
|
597
|
+
request.event.wakeAgent === undefined ? null : booleanInt(request.event.wakeAgent),
|
|
595
598
|
);
|
|
596
599
|
const event: CanonicalEvent = {
|
|
597
600
|
...cloneRecord(request.event),
|
|
@@ -948,8 +951,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
948
951
|
INSERT INTO mailbox_items(
|
|
949
952
|
item_id, schema_version, formatter_version, consumer_id, session_id,
|
|
950
953
|
segment_id, event_id, event_commit_seq, mode, coalesce_key,
|
|
951
|
-
payload_json, state, attempt_count, available_at, created_at, updated_at
|
|
952
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
|
|
954
|
+
payload_json, state, attempt_count, available_at, created_at, updated_at, delivery_order
|
|
955
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
|
|
953
956
|
`).run(
|
|
954
957
|
request.itemId,
|
|
955
958
|
request.schemaVersion ?? 1,
|
|
@@ -966,6 +969,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
966
969
|
request.availableAtMs ?? 0,
|
|
967
970
|
createdAt,
|
|
968
971
|
createdAt,
|
|
972
|
+
request.deliveryOrder ?? null,
|
|
969
973
|
);
|
|
970
974
|
const inserted = this.db.prepare('SELECT * FROM mailbox_items WHERE item_id = ?')
|
|
971
975
|
.get(request.itemId);
|
|
@@ -1012,7 +1016,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1012
1016
|
return this.db.prepare(`
|
|
1013
1017
|
SELECT * FROM mailbox_items
|
|
1014
1018
|
WHERE ${clauses.join(' AND ')}
|
|
1015
|
-
ORDER BY event_commit_seq ${order}, item_id ${order}${limit}
|
|
1019
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ${order}, item_id ${order}${limit}
|
|
1016
1020
|
`).all(...params).map((row) => mailboxItemFromRow<T>(row));
|
|
1017
1021
|
}
|
|
1018
1022
|
|
|
@@ -1032,7 +1036,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1032
1036
|
AND m.segment_id = ?
|
|
1033
1037
|
AND m.mode = ?
|
|
1034
1038
|
AND m.state IN ('pending', 'claimed')
|
|
1035
|
-
ORDER BY m.event_commit_seq ASC, m.item_id ASC
|
|
1039
|
+
ORDER BY COALESCE(m.delivery_order, m.event_commit_seq) ASC, m.item_id ASC
|
|
1036
1040
|
`).all(request.consumerId, request.sessionId, request.segmentId, request.mode);
|
|
1037
1041
|
|
|
1038
1042
|
const activeRows: Array<Record<string, unknown>> = [];
|
|
@@ -1098,7 +1102,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1098
1102
|
const claimedRows = this.db.prepare(`
|
|
1099
1103
|
SELECT * FROM mailbox_items
|
|
1100
1104
|
WHERE item_id IN (${placeholders(itemIds.length)})
|
|
1101
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1105
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1102
1106
|
`).all(...itemIds);
|
|
1103
1107
|
return {
|
|
1104
1108
|
ownerId: request.ownerId,
|
|
@@ -1115,7 +1119,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1115
1119
|
const rows = this.db.prepare(`
|
|
1116
1120
|
SELECT * FROM mailbox_items
|
|
1117
1121
|
WHERE claim_owner = ? AND claim_token = ?
|
|
1118
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1122
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1119
1123
|
`).all(request.ownerId, request.claimToken);
|
|
1120
1124
|
if (rows.length === 0) return { status: 'claim_lost', itemIds: [], eventIds: [] };
|
|
1121
1125
|
const itemIds = rows.map((row) => String(row.item_id));
|
|
@@ -1158,7 +1162,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1158
1162
|
const rows = this.db.prepare(`
|
|
1159
1163
|
SELECT * FROM mailbox_items
|
|
1160
1164
|
WHERE claim_owner = ? AND claim_token = ? AND state = 'claimed'
|
|
1161
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1165
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1162
1166
|
`).all(request.ownerId, request.claimToken);
|
|
1163
1167
|
if (
|
|
1164
1168
|
rows.length === 0
|
|
@@ -1669,6 +1673,29 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1669
1673
|
`).run(new Date().toISOString());
|
|
1670
1674
|
});
|
|
1671
1675
|
}
|
|
1676
|
+
const wakeMigration = this.db.prepare('SELECT version FROM schema_migrations WHERE version = 11').get();
|
|
1677
|
+
if (!wakeMigration) {
|
|
1678
|
+
this.transaction(() => {
|
|
1679
|
+
const columns = this.db.prepare('PRAGMA table_info(events)').all();
|
|
1680
|
+
if (!columns.some((row) => row.name === 'wake_agent')) {
|
|
1681
|
+
this.db.exec('ALTER TABLE events ADD COLUMN wake_agent INTEGER CHECK(wake_agent IN (0, 1))');
|
|
1682
|
+
}
|
|
1683
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (11, ?)')
|
|
1684
|
+
.run(new Date().toISOString());
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
if (!this.db.prepare('SELECT version FROM schema_migrations WHERE version = 12').get()) {
|
|
1689
|
+
this.transaction(() => {
|
|
1690
|
+
const columns = this.db.prepare('PRAGMA table_info(mailbox_items)').all();
|
|
1691
|
+
if (!columns.some((row) => row.name === 'delivery_order')) {
|
|
1692
|
+
this.db.exec('ALTER TABLE mailbox_items ADD COLUMN delivery_order INTEGER');
|
|
1693
|
+
}
|
|
1694
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (12, ?)')
|
|
1695
|
+
.run(new Date().toISOString());
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1672
1699
|
}
|
|
1673
1700
|
|
|
1674
1701
|
/**
|
|
@@ -85,6 +85,8 @@ export interface EventSourceRef {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
export interface PublishEventInput {
|
|
88
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
89
|
+
readonly wakeAgent?: boolean;
|
|
88
90
|
/** Runtime epoch that admitted or derived this Event. */
|
|
89
91
|
epochSeq?: number;
|
|
90
92
|
type: string;
|
|
@@ -103,6 +105,8 @@ export interface PublishEventInput {
|
|
|
103
105
|
}
|
|
104
106
|
|
|
105
107
|
export interface CanonicalEvent {
|
|
108
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
109
|
+
readonly wakeAgent?: boolean;
|
|
106
110
|
commitSeq: number;
|
|
107
111
|
/** Absent only for records written before the epoch runtime migration. */
|
|
108
112
|
epochSeq?: number;
|
|
@@ -24,6 +24,8 @@ export interface MailboxItem<T = unknown> {
|
|
|
24
24
|
segmentId: string;
|
|
25
25
|
eventId: string;
|
|
26
26
|
eventCommitSeq: number;
|
|
27
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
28
|
+
deliveryOrder?: number;
|
|
27
29
|
mode: MailboxDeliveryMode;
|
|
28
30
|
coalesceKey: string;
|
|
29
31
|
payload: T;
|
|
@@ -51,6 +53,8 @@ export interface EnqueueMailboxItem<T = unknown> {
|
|
|
51
53
|
segmentId: string;
|
|
52
54
|
eventId: string;
|
|
53
55
|
eventCommitSeq: number;
|
|
56
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
57
|
+
deliveryOrder?: number;
|
|
54
58
|
mode: MailboxDeliveryMode;
|
|
55
59
|
coalesceKey: string;
|
|
56
60
|
payload: T;
|
|
@@ -115,6 +115,8 @@ export interface RuntimeStateProposal<T = unknown> {
|
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
export interface RuntimeEventProposal {
|
|
118
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
119
|
+
readonly wakeAgent?: boolean;
|
|
118
120
|
readonly type: string;
|
|
119
121
|
readonly dedupeKey: string;
|
|
120
122
|
readonly dedupeScope?: 'segment' | 'session';
|
|
@@ -1258,6 +1258,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1258
1258
|
producerOutputIndex: proposalIndex,
|
|
1259
1259
|
sessionId: epoch.scope.sessionId,
|
|
1260
1260
|
segmentId: epoch.scope.segmentId,
|
|
1261
|
+
wakeAgent: proposal.wakeAgent,
|
|
1261
1262
|
payload: proposal.payload,
|
|
1262
1263
|
occurredAt: proposal.occurredAt,
|
|
1263
1264
|
receivedAt: new Date().toISOString(),
|
|
@@ -62,6 +62,7 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
62
62
|
readonly mode: MailboxDeliveryMode,
|
|
63
63
|
private readonly consumerId = DEFAULT_EVENT_CONSUMER_ID,
|
|
64
64
|
private readonly maxItems = DEFAULT_RELAY_BATCH_SIZE,
|
|
65
|
+
private readonly onDelivered?: (eventIds: readonly string[]) => void,
|
|
65
66
|
) {}
|
|
66
67
|
|
|
67
68
|
handle(request: OwnerControlRequest): OwnerControlResponse | undefined {
|
|
@@ -123,18 +124,18 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
123
124
|
const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
124
125
|
if (!claimToken) return { ok: false, error: 'invalid_mailbox_claim_token' };
|
|
125
126
|
if (request.type === 'mailbox_ack') {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
};
|
|
127
|
+
const result = this.repository.ackMailboxClaim({
|
|
128
|
+
ownerId: relayId,
|
|
129
|
+
claimToken,
|
|
130
|
+
acceptedAt: typeof request.accepted_at === 'string'
|
|
131
|
+
? request.accepted_at
|
|
132
|
+
: undefined,
|
|
133
|
+
acceptanceLevel: 'sink_emitted',
|
|
134
|
+
});
|
|
135
|
+
if (result.status !== 'claim_lost') {
|
|
136
|
+
try { this.onDelivered?.(result.eventIds); } catch { /* Best-effort display only. */ }
|
|
137
|
+
}
|
|
138
|
+
return { ok: true, type: 'mailbox_ack', result };
|
|
138
139
|
}
|
|
139
140
|
return {
|
|
140
141
|
ok: true,
|
|
@@ -107,6 +107,8 @@ export interface PerceptionBoundary {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
export interface PerceptionEventProposal {
|
|
110
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
111
|
+
readonly wakeAgent?: boolean;
|
|
110
112
|
readonly type: string;
|
|
111
113
|
/** Stable identity of this semantic slice within the current segment. */
|
|
112
114
|
readonly dedupeKey: string;
|
|
@@ -116,6 +118,8 @@ export interface PerceptionEventProposal {
|
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
export interface ClawclawPerceptionManifest {
|
|
121
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
122
|
+
readonly wakeAgent?: boolean;
|
|
119
123
|
readonly apiVersion: typeof PERCEPTION_PLUGIN_API_VERSION;
|
|
120
124
|
readonly id: string;
|
|
121
125
|
readonly name: string;
|