@myclaw163/clawclaw-cli 0.8.26 → 0.8.27
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/README.md +3 -0
- package/docs/custom-modules/api-reference.md +43 -1
- package/docs/custom-modules/behavior.md +3 -0
- package/docs/custom-modules/examples/task-reminder.ts +17 -0
- package/docs/custom-modules/perception.md +7 -1
- package/docs/custom-modules/reminders.md +147 -0
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +21 -16
- package/skills/clawclaw/references/BEHAVIORS.md +2 -2
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +3 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +43 -1
- package/skills/clawclaw/references/CUSTOM-MODULES.md +3 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +11 -5
- package/skills/clawclaw/references/CUSTOM-REMINDER-DEVELOPMENT.md +147 -0
- package/skills/clawclaw/references/HUB.md +14 -0
- package/skills/clawclaw/references/TACTICS.md +17 -15
- package/src/cli.ts +2 -14
- package/src/commands/capability.ts +5 -2
- package/src/commands/hub.ts +5 -4
- package/src/commands/load.ts +13 -1
- package/src/lib/capability-cloud-sync.ts +11 -2
- package/src/lib/capability-load-diagnostics.ts +1 -1
- package/src/lib/command-error.ts +22 -0
- package/src/lib/hub-client.ts +26 -2
- package/src/lib/hub-errors.ts +60 -0
- package/src/lib/perception-config.ts +1 -1
- package/src/runtime/clawclaw/owner.ts +3 -1
- package/src/runtime/clawclaw/plugins/assembly.ts +17 -2
- package/src/runtime/clawclaw/plugins/behavior-input-source.ts +10 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +137 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-rules.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +59 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-worker.ts +33 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +7 -3
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +17 -1
- package/src/runtime/clawclaw/reminder-manifest.ts +28 -0
- package/src/runtime/clawclaw/runtime.ts +3 -0
- package/src/runtime/clawclaw-event-catalog.ts +4 -1
- package/src/runtime/framework/events/event-repository.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +14 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +16 -0
- package/src/runtime/framework/events/types.ts +6 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
- package/src/runtime/framework/plugins/contracts.ts +3 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +19 -0
- package/src/runtime/framework/runtime.ts +1 -0
- package/src/sdk/perception-plugin/index.ts +2 -0
- package/src/sdk/perception-plugin/reminder-rules.ts +41 -0
- package/src/sdk/perception-plugin/reminder.ts +40 -0
package/src/lib/hub-client.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { AuthStore } from './auth.js';
|
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { ServerRegistry } from './server-registry.js';
|
|
4
4
|
import { HttpTransport } from './http-transport.js';
|
|
5
|
+
import { isWorkspaceRevisionConflict } from './hub-errors.js';
|
|
5
6
|
|
|
6
7
|
export type ResourceType = 'skill' | 'strategy' | 'persona' | 'perception';
|
|
7
8
|
|
|
@@ -12,6 +13,7 @@ export interface ResourceStats {
|
|
|
12
13
|
}
|
|
13
14
|
|
|
14
15
|
export interface ResourceSummary {
|
|
16
|
+
skillName?: string | null;
|
|
15
17
|
id: string;
|
|
16
18
|
forkedFromResourceId?: string;
|
|
17
19
|
type: ResourceType;
|
|
@@ -61,6 +63,7 @@ export interface ListOptions {
|
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
export interface WorkspaceResourceSummary {
|
|
66
|
+
skillName?: string | null;
|
|
64
67
|
workspaceItemId: string;
|
|
65
68
|
forkedFromResourceId?: string;
|
|
66
69
|
resourceId: string;
|
|
@@ -127,6 +130,7 @@ interface RawVersion {
|
|
|
127
130
|
}
|
|
128
131
|
|
|
129
132
|
interface RawResource {
|
|
133
|
+
skill_name?: string | null;
|
|
130
134
|
id?: string;
|
|
131
135
|
forked_from_resource_id?: string | null;
|
|
132
136
|
resource_id: string;
|
|
@@ -144,6 +148,7 @@ interface RawResource {
|
|
|
144
148
|
}
|
|
145
149
|
|
|
146
150
|
interface RawWorkspaceItem {
|
|
151
|
+
skill_name?: string | null;
|
|
147
152
|
workspace_item_id: string;
|
|
148
153
|
forked_from_resource_id?: string | null;
|
|
149
154
|
resource_id: string;
|
|
@@ -169,6 +174,7 @@ export interface HubUploadedSourceFile {
|
|
|
169
174
|
}
|
|
170
175
|
|
|
171
176
|
export interface HubResourceMutationResult {
|
|
177
|
+
skillName?: string | null;
|
|
172
178
|
resourceId: string;
|
|
173
179
|
versionId: string;
|
|
174
180
|
workspaceItemId?: string;
|
|
@@ -188,6 +194,7 @@ function toSummary(resource: RawResource): ResourceSummary {
|
|
|
188
194
|
id: resource.resource_id ?? resource.id ?? '',
|
|
189
195
|
forkedFromResourceId: resource.forked_from_resource_id ?? undefined,
|
|
190
196
|
type: resource.resource_type,
|
|
197
|
+
skillName: resource.skill_name ?? null,
|
|
191
198
|
title: version.title,
|
|
192
199
|
description: version.description,
|
|
193
200
|
creator: owner.id ?? '',
|
|
@@ -321,6 +328,7 @@ export class HubClient {
|
|
|
321
328
|
forkedFromResourceId: item.forked_from_resource_id ?? undefined,
|
|
322
329
|
resourceId: item.resource_id,
|
|
323
330
|
resourceType: item.resource_type,
|
|
331
|
+
skillName: item.skill_name ?? null,
|
|
324
332
|
title: item.title ?? '',
|
|
325
333
|
versionId: item.version_id,
|
|
326
334
|
equipped: item.is_equipped === true,
|
|
@@ -358,11 +366,23 @@ export class HubClient {
|
|
|
358
366
|
return { updated: response.data.updated, versionId: response.data.version_id };
|
|
359
367
|
}
|
|
360
368
|
|
|
369
|
+
private async updateWorkspace<T>(path: string, body: unknown): Promise<T> {
|
|
370
|
+
try {
|
|
371
|
+
return await this.http.post<T>(path, body);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (!isWorkspaceRevisionConflict(error)) throw error;
|
|
374
|
+
// Refresh once, then retry only this explicit operation. No background
|
|
375
|
+
// replay, extra request fields, or name-conflict replacement is allowed.
|
|
376
|
+
await this.http.get(`${BASE}/workspace/loadout`);
|
|
377
|
+
return this.http.post<T>(path, body);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
361
381
|
async updateWorkspaceEquipment(
|
|
362
382
|
workspaceItemId: string,
|
|
363
383
|
equipped: boolean,
|
|
364
384
|
): Promise<{ workspaceItemId: string; equipped: boolean; revision: number; changed: boolean }> {
|
|
365
|
-
const response = await this.
|
|
385
|
+
const response = await this.updateWorkspace<Envelope<{
|
|
366
386
|
workspace_item_id: string;
|
|
367
387
|
is_equipped: boolean;
|
|
368
388
|
revision: number;
|
|
@@ -387,7 +407,7 @@ export class HubClient {
|
|
|
387
407
|
if (input.strategyItemIds !== undefined) body.strategy_item_ids = input.strategyItemIds;
|
|
388
408
|
if (input.personaItemIds !== undefined) body.persona_item_ids = input.personaItemIds;
|
|
389
409
|
if (input.perceptionItemIds !== undefined) body.perception_item_ids = input.perceptionItemIds;
|
|
390
|
-
const response = await this.
|
|
410
|
+
const response = await this.updateWorkspace<Envelope<{ revision: number; changed: boolean }>>(
|
|
391
411
|
`${BASE}/workspace/loadout/update`,
|
|
392
412
|
body,
|
|
393
413
|
);
|
|
@@ -462,6 +482,7 @@ export class HubClient {
|
|
|
462
482
|
resource_id: string;
|
|
463
483
|
latest_version: { id: string };
|
|
464
484
|
workspace_item_id?: string;
|
|
485
|
+
skill_name?: string | null;
|
|
465
486
|
}>>(`${BASE}/resources/create`, {
|
|
466
487
|
resource_type: input.resourceType,
|
|
467
488
|
version_number: '1.0.0',
|
|
@@ -477,6 +498,7 @@ export class HubClient {
|
|
|
477
498
|
return {
|
|
478
499
|
resourceId: response.data.resource_id,
|
|
479
500
|
versionId: response.data.latest_version.id,
|
|
501
|
+
skillName: response.data.skill_name ?? null,
|
|
480
502
|
...(response.data.workspace_item_id ? { workspaceItemId: response.data.workspace_item_id } : {}),
|
|
481
503
|
};
|
|
482
504
|
}
|
|
@@ -494,6 +516,7 @@ export class HubClient {
|
|
|
494
516
|
const response = await this.http.post<Envelope<{
|
|
495
517
|
resource_id: string;
|
|
496
518
|
latest_version: { id: string };
|
|
519
|
+
skill_name?: string | null;
|
|
497
520
|
}>>(`${BASE}/resources/version/create`, {
|
|
498
521
|
resource_id: input.resourceId,
|
|
499
522
|
base_version_id: input.baseVersionId,
|
|
@@ -509,6 +532,7 @@ export class HubClient {
|
|
|
509
532
|
return {
|
|
510
533
|
resourceId: response.data.resource_id,
|
|
511
534
|
versionId: response.data.latest_version.id,
|
|
535
|
+
skillName: response.data.skill_name ?? null,
|
|
512
536
|
};
|
|
513
537
|
}
|
|
514
538
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ApiError, formatApiError } from './http-transport.js';
|
|
2
|
+
|
|
3
|
+
export interface HubErrorFields {
|
|
4
|
+
status: number;
|
|
5
|
+
code?: string;
|
|
6
|
+
message: string;
|
|
7
|
+
operation: string;
|
|
8
|
+
details?: Record<string, unknown>;
|
|
9
|
+
hint?: string;
|
|
10
|
+
retryable?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
14
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Preserve Hub business errors across direct commands and per-resource sync failures. */
|
|
18
|
+
export function hubErrorFields(error: unknown): HubErrorFields | undefined {
|
|
19
|
+
if (!(error instanceof ApiError) || !error.path.startsWith('/api/v1/hub/')) return undefined;
|
|
20
|
+
let body: unknown;
|
|
21
|
+
try { body = JSON.parse(error.body); } catch { /* retain the original response below */ }
|
|
22
|
+
const payload = record(body) && record(body.error) ? body.error : undefined;
|
|
23
|
+
const code = typeof payload?.code === 'string' ? payload.code : undefined;
|
|
24
|
+
const operation = error.path.split('?')[0]!;
|
|
25
|
+
const equipment = operation === '/api/v1/hub/workspace/equipment/update'
|
|
26
|
+
|| operation === '/api/v1/hub/workspace/loadout/update';
|
|
27
|
+
const create = operation === '/api/v1/hub/resources/create';
|
|
28
|
+
const version = operation === '/api/v1/hub/resources/version/create';
|
|
29
|
+
const result: HubErrorFields = {
|
|
30
|
+
status: error.status,
|
|
31
|
+
...(code ? { code } : {}),
|
|
32
|
+
message: typeof payload?.message === 'string' ? payload.message : formatApiError(error),
|
|
33
|
+
operation,
|
|
34
|
+
...(record(payload?.details) ? { details: payload.details } : {}),
|
|
35
|
+
};
|
|
36
|
+
if ((create || version) && code === 'INVALID_SKILL_NAME') {
|
|
37
|
+
result.hint = '请检查根 SKILL.md 的 UTF-8、YAML frontmatter 和 name,按服务端原因修正后再提交;本地文件已保留。';
|
|
38
|
+
} else if (create && code === 'SKILL_NAME_CONFLICT') {
|
|
39
|
+
result.hint = '你已有同名 Skill。请到 Hub 确认已有资源;更新它需明确选择该资源,新建则需修改新 Skill 的 name。不要按同名自动关联、覆盖或再次 fork。';
|
|
40
|
+
} else if (version && code === 'SKILL_NAME_IMMUTABLE') {
|
|
41
|
+
result.hint = '已有 Skill 不能通过新版本改名。请恢复原 name 后发版,或明确新建另一资源;修改 Hub 标题不能解决。本地文件已保留。';
|
|
42
|
+
} else if (version && code === 'SKILL_NAME_KEY_MISSING') {
|
|
43
|
+
result.hint = '该历史 Skill 尚未完成名称回填,请联系 Hub 运维处理后再发版;不要反复重试,本地修改已保留。';
|
|
44
|
+
} else if (equipment && code === 'SKILL_NAME_CONFLICT') {
|
|
45
|
+
result.hint = '已装配另一件同名 Skill。请用户到 Hub 处理装配冲突,完成后重新运行 ccl load;CCL 不自动卸载或替换任何 Skill,也不要用卸载后重装绕过此提示。';
|
|
46
|
+
} else if (equipment && code === 'INVALID_LOADOUT') {
|
|
47
|
+
result.hint = '装配选择无效,可能是同名 Skill、超出上限或类型不匹配。请按服务端原因到 Hub 修正选择,再运行 ccl load。';
|
|
48
|
+
} else if (equipment && code === 'WORKSPACE_REVISION_CONFLICT') {
|
|
49
|
+
result.hint = 'Workspace 装配正在被并发修改。请刷新最新装配状态后再重试本次明确操作;不要反复重放旧装配。';
|
|
50
|
+
result.retryable = true;
|
|
51
|
+
}
|
|
52
|
+
if (result.hint && result.retryable === undefined) result.retryable = false;
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function isWorkspaceRevisionConflict(error: unknown): boolean {
|
|
57
|
+
const fields = hubErrorFields(error);
|
|
58
|
+
return fields?.status === 409 && fields.code === 'WORKSPACE_REVISION_CONFLICT'
|
|
59
|
+
&& fields.retryable === true;
|
|
60
|
+
}
|
|
@@ -61,7 +61,7 @@ export function readWorkspacePerceptionConfig(
|
|
|
61
61
|
];
|
|
62
62
|
const eventTypes = new Set<string>([
|
|
63
63
|
...CLAWCLAW_VISUAL_EVENT_TYPES,
|
|
64
|
-
...sources.flatMap((source) => [...source.manifest.produces]),
|
|
64
|
+
...sources.filter(source => !source.reminder).flatMap((source) => [...source.manifest.produces]),
|
|
65
65
|
]);
|
|
66
66
|
let maxBackfillVisualFrames: number | undefined;
|
|
67
67
|
if (configuredMaxBackfillVisualFrames !== undefined) {
|
|
@@ -828,6 +828,7 @@ export async function runClawclawOwner(
|
|
|
828
828
|
observability: telemetry,
|
|
829
829
|
runtimeEpochPlugins: epochPlugins,
|
|
830
830
|
visualEventDelivery: perceptionConfig.events.delivery,
|
|
831
|
+
reminderDelivery: true,
|
|
831
832
|
visualEventTypes: assembly.perception.produces.events,
|
|
832
833
|
behaviorEventTypes: assembly.behavior.produces?.events ?? [],
|
|
833
834
|
});
|
|
@@ -957,7 +958,8 @@ export async function runClawclawOwner(
|
|
|
957
958
|
? resolveClawclawResourceMetadata(source, DESKTOP_RESOURCE_LOCALE)
|
|
958
959
|
: null;
|
|
959
960
|
})(),
|
|
960
|
-
perceptions: assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
|
|
961
|
+
perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
|
|
962
|
+
...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE)],
|
|
961
963
|
}),
|
|
962
964
|
eventDescriptors: () => assembly.perception
|
|
963
965
|
.localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { GameClient } from '../../../lib/game-client.js';
|
|
2
|
+
import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
|
|
3
|
+
import { listClawclawPerceptionSources } from './perception/perception-source.js';
|
|
4
|
+
import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
|
|
2
5
|
import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
|
|
3
6
|
import {
|
|
4
7
|
CLAWCLAW_ACTION_PLUGIN_ID,
|
|
@@ -50,6 +53,7 @@ export interface ClawclawPluginAssembly {
|
|
|
50
53
|
action: ClawclawActionPlugin;
|
|
51
54
|
gameQuery: ClawclawGameQueryPlugin;
|
|
52
55
|
perception: ClawclawPerceptionPlugin;
|
|
56
|
+
reminders: ClawclawReminderPlugin;
|
|
53
57
|
trigger: ClawclawTriggerPlugin;
|
|
54
58
|
behavior: ClawclawBehaviorPlugin;
|
|
55
59
|
mailbox: ClawclawMailboxPlugin;
|
|
@@ -83,6 +87,16 @@ export function assembleClawclawPlugins(
|
|
|
83
87
|
if (!plugins.some((plugin) => plugin.id === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID)) {
|
|
84
88
|
plugins.push(new ClawclawDerivedEventPlugin());
|
|
85
89
|
}
|
|
90
|
+
const configuredReminders = plugins.find(plugin => plugin.id === CLAWCLAW_REMINDER_PLUGIN_ID);
|
|
91
|
+
if (configuredReminders && !(configuredReminders instanceof ClawclawReminderPlugin)) {
|
|
92
|
+
throw new Error(`Runtime Plugin ${CLAWCLAW_REMINDER_PLUGIN_ID} is not a ClawclawReminderPlugin.`);
|
|
93
|
+
}
|
|
94
|
+
const selected = new Set(options.perception?.modules ?? DEFAULT_PERCEPTION_MODULES);
|
|
95
|
+
const reminders = configuredReminders as ClawclawReminderPlugin | undefined ?? new ClawclawReminderPlugin({
|
|
96
|
+
sources: (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
|
|
97
|
+
.filter(source => source.reminder && selected.has(source.id)),
|
|
98
|
+
});
|
|
99
|
+
if (!configuredReminders) plugins.push(reminders);
|
|
86
100
|
|
|
87
101
|
const configuredGameQuery = plugins.find((plugin) => plugin.id === CLAWCLAW_GAME_QUERY_PLUGIN_ID);
|
|
88
102
|
if (configuredGameQuery && !(configuredGameQuery instanceof ClawclawGameQueryPlugin)) {
|
|
@@ -123,6 +137,7 @@ export function assembleClawclawPlugins(
|
|
|
123
137
|
after: [
|
|
124
138
|
CLAWCLAW_ACTION_PLUGIN_ID,
|
|
125
139
|
CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
|
|
140
|
+
CLAWCLAW_REMINDER_PLUGIN_ID,
|
|
126
141
|
CLAWCLAW_GAME_QUERY_PLUGIN_ID,
|
|
127
142
|
CLAWCLAW_PERCEPTION_PLUGIN_ID,
|
|
128
143
|
CLAWCLAW_TRIGGER_PLUGIN_ID,
|
|
@@ -146,11 +161,11 @@ export function assembleClawclawPlugins(
|
|
|
146
161
|
}
|
|
147
162
|
const eventProducers = plugins
|
|
148
163
|
.filter((plugin) => plugin.id !== CLAWCLAW_MAILBOX_PLUGIN_ID)
|
|
149
|
-
.filter((plugin) => (plugin.produces?.events?.length ?? 0) > 0)
|
|
164
|
+
.filter((plugin) => (plugin.produces?.events?.length ?? 0) > 0 || (plugin.controlsEventDelivery?.length ?? 0) > 0)
|
|
150
165
|
.map((plugin) => plugin.id);
|
|
151
166
|
const mailbox = configuredMailbox as ClawclawMailboxPlugin | undefined
|
|
152
167
|
?? new ClawclawMailboxPlugin({ after: eventProducers });
|
|
153
168
|
if (!configuredMailbox) plugins.push(mailbox);
|
|
154
169
|
|
|
155
|
-
return { plugins, action, gameQuery, perception, trigger, behavior, mailbox };
|
|
170
|
+
return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox };
|
|
156
171
|
}
|
|
@@ -13,6 +13,16 @@ interface ParsedValue {
|
|
|
13
13
|
|
|
14
14
|
class LiteralParseError extends Error {}
|
|
15
15
|
|
|
16
|
+
/** Shared, non-evaluating parser for a complete module manifest literal. */
|
|
17
|
+
export function parseLiteralModuleManifest(source: string): Record<string, unknown> | null {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = parseValue(source, skipTrivia(source, 0));
|
|
20
|
+
if (skipTrivia(source, parsed.next) !== source.length || !parsed.value
|
|
21
|
+
|| typeof parsed.value !== 'object' || Array.isArray(parsed.value)) return null;
|
|
22
|
+
return parsed.value as Record<string, unknown>;
|
|
23
|
+
} catch { return null; }
|
|
24
|
+
}
|
|
25
|
+
|
|
16
26
|
function skipTrivia(source: string, start: number): number {
|
|
17
27
|
let cursor = start;
|
|
18
28
|
while (cursor < source.length) {
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
|
|
2
|
+
import type { EventDeliveryDecision } from '../../../framework/events/types.js';
|
|
3
|
+
import type { ReminderInput, ReminderResult, ReminderTopic } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
|
|
5
|
+
import { freshClawclawGameState } from '../../runtime-state.js';
|
|
6
|
+
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
7
|
+
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
8
|
+
import { deliveryClass, isReminderMode, REMINDER_CONTROLLED_TYPES, REMINDER_FACT_TYPES, REMINDER_TOPICS } from './reminder-rules.js';
|
|
9
|
+
import { ReminderRunner } from './reminder-runner.js';
|
|
10
|
+
import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
|
|
11
|
+
|
|
12
|
+
export const CLAWCLAW_REMINDER_PLUGIN_ID = 'clawclaw.derived-event.reminders';
|
|
13
|
+
export interface ReminderPluginOptions {
|
|
14
|
+
/** Already selected by the ordinary local/Hub perception loadout. No separate settings. */
|
|
15
|
+
sources?: readonly ResolvedClawclawPerceptionSource[];
|
|
16
|
+
}
|
|
17
|
+
interface Checkpoint {
|
|
18
|
+
gameId?: string;
|
|
19
|
+
previousTick?: number; previousConnectionId?: string;
|
|
20
|
+
states: Partial<Record<ReminderTopic, { provider: string; value: unknown }>>;
|
|
21
|
+
}
|
|
22
|
+
function empty(): Checkpoint { return { states: {} }; }
|
|
23
|
+
function coreTask(payload: Record<string, unknown>): boolean {
|
|
24
|
+
return !['task_state_changed', 'task_assigned'].includes(String(payload.reason));
|
|
25
|
+
}
|
|
26
|
+
export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string, any>> {
|
|
27
|
+
readonly kind = 'epoch' as const;
|
|
28
|
+
readonly id = CLAWCLAW_REMINDER_PLUGIN_ID;
|
|
29
|
+
readonly version = '1';
|
|
30
|
+
readonly after = ['clawclaw.derived-event'];
|
|
31
|
+
readonly consumes = { events: REMINDER_FACT_TYPES };
|
|
32
|
+
readonly produces = { events: [] } as const;
|
|
33
|
+
readonly controlsEventDelivery = REMINDER_CONTROLLED_TYPES;
|
|
34
|
+
readonly catchUp = 'strict_ordered' as const;
|
|
35
|
+
readonly timeoutMs = 3_000;
|
|
36
|
+
private checkpoint: Checkpoint = empty();
|
|
37
|
+
private readonly sources = new Map<ReminderTopic, ResolvedClawclawPerceptionSource[]>();
|
|
38
|
+
private readonly runners = new Map<ReminderTopic, ReminderRunner>();
|
|
39
|
+
private readonly failed = new Set<ReminderTopic>();
|
|
40
|
+
constructor(private readonly options: ReminderPluginOptions = {}) {
|
|
41
|
+
for (const source of options.sources ?? []) {
|
|
42
|
+
if (!source.reminder) continue;
|
|
43
|
+
const selected = this.sources.get(source.reminder.topic) ?? [];
|
|
44
|
+
selected.push(source); this.sources.set(source.reminder.topic, selected);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
|
|
48
|
+
this.checkpoint = empty(); this.failed.clear();
|
|
49
|
+
await Promise.all(REMINDER_TOPICS.map(async topic => {
|
|
50
|
+
const sources = this.sources.get(topic) ?? [];
|
|
51
|
+
if (!sources.length) return;
|
|
52
|
+
try {
|
|
53
|
+
if (sources.length !== 1) throw new Error(`perception_topic_conflict:${topic}:${sources.map(s => s.id).join(',')}`);
|
|
54
|
+
const runner = new ReminderRunner(sources[0]!);
|
|
55
|
+
this.runners.set(topic, runner);
|
|
56
|
+
await runner.start();
|
|
57
|
+
} catch (error) { this.markFailed(topic, context, error); await this.runners.get(topic)?.stop(); }
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
61
|
+
const checkpoint = context.checkpoint() as Checkpoint | undefined;
|
|
62
|
+
if (checkpoint?.states) this.checkpoint = structuredClone({
|
|
63
|
+
gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
|
|
64
|
+
previousConnectionId: checkpoint.previousConnectionId,
|
|
65
|
+
states: checkpoint.states.tasks ? { tasks: checkpoint.states.tasks } : {},
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(r => r.stop())); this.runners.clear(); }
|
|
69
|
+
localizedModuleDescriptors(locale: string) {
|
|
70
|
+
return [...this.sources.entries()].filter(([topic, sources]) => sources.length === 1
|
|
71
|
+
&& this.runners.has(topic) && !this.failed.has(topic)).map(([, [source]]) => (
|
|
72
|
+
resolveClawclawResourceMetadata({ ...source!.manifest, display: source!.display }, locale)
|
|
73
|
+
));
|
|
74
|
+
}
|
|
75
|
+
async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
|
|
76
|
+
const snapshot = freshClawclawGameState(input.frame.state);
|
|
77
|
+
const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
|
|
78
|
+
let next = structuredClone(this.checkpoint);
|
|
79
|
+
if (game && next.gameId !== game.game_id) next = { ...empty(), gameId: game.game_id };
|
|
80
|
+
const frame = new ObservationFrameProjector().project(input.frame);
|
|
81
|
+
if (frame) {
|
|
82
|
+
const delta = next.previousTick === undefined ? null : frame.tick - next.previousTick;
|
|
83
|
+
Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
|
|
84
|
+
&& next.previousConnectionId === input.epoch.connectionId });
|
|
85
|
+
next.previousTick = frame.tick;
|
|
86
|
+
next.previousConnectionId = input.epoch.connectionId;
|
|
87
|
+
} else if (!game) {
|
|
88
|
+
next.previousTick = undefined; next.previousConnectionId = undefined;
|
|
89
|
+
}
|
|
90
|
+
const facts = input.pendingEvents;
|
|
91
|
+
const optional = facts.filter(e => e.type === 'tasks_changed' && !coreTask(e.payload));
|
|
92
|
+
const decisions = new Map<string, EventDeliveryDecision>(optional.map(e => [e.eventId, { eventId: e.eventId, deliveryClass: 'internal_only' }]));
|
|
93
|
+
for (const fact of facts.filter(e => e.type === 'tasks_changed' && coreTask(e.payload))) {
|
|
94
|
+
decisions.set(fact.eventId, { eventId: fact.eventId, deliveryClass: 'monitor_and_events' });
|
|
95
|
+
}
|
|
96
|
+
for (const topic of REMINDER_TOPICS) {
|
|
97
|
+
const selected = this.sources.get(topic)?.[0];
|
|
98
|
+
if (!selected || this.failed.has(topic)) continue;
|
|
99
|
+
const previous = next.states[topic];
|
|
100
|
+
const moduleInput: ReminderInput = {
|
|
101
|
+
scope: input.epoch.scope, frame, gameState: game,
|
|
102
|
+
facts: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type,
|
|
103
|
+
occurredAt: e.occurredAt, producer: e.producer, payload: e.payload })),
|
|
104
|
+
config: selected.reminder!.config ?? {}, state: previous?.provider === selected.id ? previous.value : undefined,
|
|
105
|
+
nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
const result: ReminderResult = await this.runners.get(topic)!.update(moduleInput);
|
|
109
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)
|
|
110
|
+
|| Object.keys(result).some(k => !['state', 'deliveries'].includes(k))
|
|
111
|
+
|| (result.deliveries !== undefined && !Array.isArray(result.deliveries))
|
|
112
|
+
|| Buffer.byteLength(JSON.stringify(result)) > 1024 * 1024) throw new Error('Invalid reminder output.');
|
|
113
|
+
const accepted: EventDeliveryDecision[] = [];
|
|
114
|
+
const ids = new Set<string>();
|
|
115
|
+
for (const decision of result.deliveries ?? []) {
|
|
116
|
+
const fact = optional.find(e => e.eventId === decision.eventId);
|
|
117
|
+
if (!fact || !isReminderMode(decision.mode) || ids.has(decision.eventId)
|
|
118
|
+
|| fact.type !== 'tasks_changed') {
|
|
119
|
+
throw new Error('Reminder attempted to control an unauthorized fact.');
|
|
120
|
+
}
|
|
121
|
+
ids.add(decision.eventId);
|
|
122
|
+
accepted.push({ eventId: fact.eventId, deliveryClass: deliveryClass(decision.mode) });
|
|
123
|
+
}
|
|
124
|
+
for (const decision of accepted) decisions.set(decision.eventId, decision);
|
|
125
|
+
next.states[topic] = { provider: selected.id, value: structuredClone(result.state) };
|
|
126
|
+
} catch (error) { this.markFailed(topic, context, error); }
|
|
127
|
+
}
|
|
128
|
+
this.checkpoint = next;
|
|
129
|
+
return { outcome: 'processed', eventDeliveries: [...decisions.values()], checkpoint: next,
|
|
130
|
+
...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
|
|
131
|
+
}
|
|
132
|
+
private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
|
|
133
|
+
this.failed.add(topic);
|
|
134
|
+
context.diagnostic('reminder.module_failed', { topic, module_ids: this.sources.get(topic)?.map(s => s.id),
|
|
135
|
+
error: error instanceof Error ? error.message : String(error) }, 'error');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../../../../sdk/perception-plugin/reminder-rules.js';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import type { ClawclawReminderManifest, ReminderInput, ReminderResult } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
|
|
5
|
+
import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
|
|
6
|
+
|
|
7
|
+
/** One bounded persistent Worker; module instances themselves are stateless between calls. */
|
|
8
|
+
export class ReminderRunner {
|
|
9
|
+
private worker?: Worker;
|
|
10
|
+
private sequence = 0;
|
|
11
|
+
private pending?: { resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout>; id?: number };
|
|
12
|
+
private failure?: Error;
|
|
13
|
+
constructor(readonly source: ResolvedClawclawPerceptionSource) {
|
|
14
|
+
if (!source.reminder) throw new Error('Not a reminder perception source.');
|
|
15
|
+
}
|
|
16
|
+
async start(): Promise<{ manifest: ClawclawReminderManifest; config: Record<string, unknown> }> {
|
|
17
|
+
const loader = runtimeModuleThreadLoaderConfig();
|
|
18
|
+
const promise = this.wait(8_000);
|
|
19
|
+
this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
|
|
20
|
+
execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 },
|
|
21
|
+
workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.reminder,
|
|
22
|
+
runtimeModuleBootstrap: { hostUrl: new URL('./reminder-worker.ts', import.meta.url).href,
|
|
23
|
+
...loader, esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
|
|
24
|
+
});
|
|
25
|
+
this.worker.stdout?.on('data', () => {});
|
|
26
|
+
this.worker.stderr?.on('data', () => {});
|
|
27
|
+
this.worker.on('error', error => this.fail(error));
|
|
28
|
+
this.worker.on('exit', code => this.fail(new Error(`Reminder worker exited (${code}).`)));
|
|
29
|
+
this.worker.on('message', message => {
|
|
30
|
+
if (!this.pending || (message.id !== undefined && this.pending.id !== message.id)) return;
|
|
31
|
+
if (message.type === 'error') { this.fail(new Error(message.error)); return; }
|
|
32
|
+
clearTimeout(this.pending.timer);
|
|
33
|
+
this.pending.resolve(message.type === 'ready' ? message : message.result);
|
|
34
|
+
this.pending = undefined;
|
|
35
|
+
});
|
|
36
|
+
return promise;
|
|
37
|
+
}
|
|
38
|
+
async update(input: ReminderInput): Promise<ReminderResult> {
|
|
39
|
+
if (this.failure) throw this.failure;
|
|
40
|
+
if (!this.worker) throw new Error('Reminder worker not started.');
|
|
41
|
+
const id = ++this.sequence;
|
|
42
|
+
const promise = this.wait(500, id);
|
|
43
|
+
this.worker.postMessage({ id, input });
|
|
44
|
+
return promise;
|
|
45
|
+
}
|
|
46
|
+
async stop(): Promise<void> { await this.worker?.terminate(); this.worker = undefined; }
|
|
47
|
+
private wait(timeout: number, id?: number): Promise<any> {
|
|
48
|
+
if (this.pending) throw new Error('Concurrent reminder invocation.');
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
this.pending = { id, resolve, reject, timer: setTimeout(() => {
|
|
51
|
+
this.fail(new Error('Reminder worker timeout.')); void this.stop();
|
|
52
|
+
}, timeout) };
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
private fail(error: Error): void {
|
|
56
|
+
this.failure = error;
|
|
57
|
+
if (this.pending) { clearTimeout(this.pending.timer); this.pending.reject(error); this.pending = undefined; }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { ClawclawReminder, type ReminderInput } from '../../../../sdk/perception-plugin/reminder.js';
|
|
4
|
+
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
5
|
+
|
|
6
|
+
function freeze<T>(value: T): T {
|
|
7
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
8
|
+
for (const child of Object.values(value)) freeze(child);
|
|
9
|
+
Object.freeze(value);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const imported = await import(pathToFileURL(workerData.modulePath).href);
|
|
15
|
+
const Module = imported.default;
|
|
16
|
+
if (!(Module?.prototype instanceof ClawclawReminder)) throw new Error('Invalid reminder perception class.');
|
|
17
|
+
const manifest = normalizeReminderManifest(Module.manifest);
|
|
18
|
+
if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('perception_manifest_source_mismatch');
|
|
19
|
+
const config = manifest.config ?? {};
|
|
20
|
+
parentPort!.postMessage({ type: 'ready', manifest, config });
|
|
21
|
+
parentPort!.on('message', async ({ id, input }: { id: number; input: ReminderInput }) => {
|
|
22
|
+
try {
|
|
23
|
+
const result = await new Module().update(freeze({ ...input, config,
|
|
24
|
+
facts: input.facts.filter(fact => manifest.consumes.includes(fact.type)) }));
|
|
25
|
+
if (Buffer.byteLength(JSON.stringify(result) ?? '') > 1024 * 1024) throw new Error('Reminder output exceeds 1 MB.');
|
|
26
|
+
parentPort!.postMessage({ type: 'result', id, result });
|
|
27
|
+
} catch (error) {
|
|
28
|
+
parentPort!.postMessage({ type: 'error', id, error: error instanceof Error ? error.message : String(error) });
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
} catch (error) {
|
|
32
|
+
parentPort!.postMessage({ type: 'error', error: error instanceof Error ? error.message : String(error) });
|
|
33
|
+
}
|
|
@@ -243,7 +243,8 @@ export class AgentMailboxCoordinator {
|
|
|
243
243
|
maxEpochSeq: ready.epochSeq,
|
|
244
244
|
order: 'asc',
|
|
245
245
|
}, this.consumerId, ['details']).filter((row) => (
|
|
246
|
-
|
|
246
|
+
(options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
247
|
+
&& this.selectsEvent(row.event, ready.state.state)
|
|
247
248
|
));
|
|
248
249
|
if (pending.length === 0) {
|
|
249
250
|
const eventIsBeyondReadyBoundary = this.delayWindow?.sessionId === ready.scope.sessionId
|
|
@@ -301,7 +302,8 @@ export class AgentMailboxCoordinator {
|
|
|
301
302
|
maxEpochSeq: ready.epochSeq,
|
|
302
303
|
order: 'desc',
|
|
303
304
|
}, this.consumerId, ['details']).filter((row) => (
|
|
304
|
-
|
|
305
|
+
(options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
306
|
+
&& this.selectsEvent(row.event, ready.state.state)
|
|
305
307
|
));
|
|
306
308
|
if (candidates.length === 0) {
|
|
307
309
|
this.delayWindow = undefined;
|
|
@@ -437,7 +439,7 @@ export class AgentMailboxCoordinator {
|
|
|
437
439
|
observeEvents(events: readonly CanonicalEvent[]): void {
|
|
438
440
|
const first = events
|
|
439
441
|
.filter((event) => (
|
|
440
|
-
event.deliveryClass
|
|
442
|
+
event.deliveryClass === 'monitor_and_events'
|
|
441
443
|
&& this.selectsEvent(event, undefined)
|
|
442
444
|
))
|
|
443
445
|
.sort((left, right) => left.commitSeq - right.commitSeq)[0];
|
|
@@ -460,6 +462,7 @@ export class AgentMailboxCoordinator {
|
|
|
460
462
|
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
|
|
461
463
|
const pending = this.repository.listEvents({
|
|
462
464
|
sessionId: ready.scope.sessionId,
|
|
465
|
+
deliveryClasses: ['monitor_and_events'],
|
|
463
466
|
detailStates: ['pending', 'deferred'],
|
|
464
467
|
maxCommitSeq: ready.eventWatermark,
|
|
465
468
|
maxEpochSeq: ready.epochSeq,
|
|
@@ -486,6 +489,7 @@ export class AgentMailboxCoordinator {
|
|
|
486
489
|
event: CanonicalEvent,
|
|
487
490
|
state: Record<string, any> | null | undefined,
|
|
488
491
|
): boolean {
|
|
492
|
+
if (event.deliveryClass === 'events_only') return true;
|
|
489
493
|
if (this.delegatedMonitorConsumerId && event.deliveryClass !== 'internal_only' && event.wakeAgent === false) return true;
|
|
490
494
|
if (this.eventFilter(event, state)) return true;
|
|
491
495
|
if (!this.delegatedMonitorConsumerId) return false;
|
|
@@ -327,7 +327,7 @@ function createModuleSlots(
|
|
|
327
327
|
const source = sources.get(id);
|
|
328
328
|
if (!source) throw new Error(`Unknown perception module '${id}'.`);
|
|
329
329
|
return source;
|
|
330
|
-
});
|
|
330
|
+
}).filter(source => !source.reminder);
|
|
331
331
|
const reducerPool = selected.length > 0
|
|
332
332
|
? new PerceptionReducerThreadPool({
|
|
333
333
|
modules: selected.map((source) => loader.threadSpec(source)),
|
|
@@ -22,11 +22,14 @@ import type {
|
|
|
22
22
|
} from './contracts.js';
|
|
23
23
|
import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js';
|
|
24
24
|
import { literalPluginApiVersion } from '../plugin-api-version.js';
|
|
25
|
+
import { parseLiteralModuleManifest } from '../behavior-input-source.js';
|
|
26
|
+
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
27
|
+
import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
|
|
25
28
|
|
|
26
29
|
export const MAX_PERCEPTION_FILES = 512;
|
|
27
30
|
const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
28
31
|
const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/;
|
|
29
|
-
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
32
|
+
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
30
33
|
const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
|
|
31
34
|
|
|
32
35
|
export interface ResolvedClawclawPerceptionSource {
|
|
@@ -39,6 +42,8 @@ export interface ResolvedClawclawPerceptionSource {
|
|
|
39
42
|
readonly display?: Readonly<{ name: string; description: string }>;
|
|
40
43
|
readonly description: string;
|
|
41
44
|
readonly manifest: ClawclawPerceptionManifest;
|
|
45
|
+
/** Non-visual execution contract; manifest above is the common resource descriptor. */
|
|
46
|
+
readonly reminder?: ClawclawReminderManifest;
|
|
42
47
|
readonly sourcePath: string;
|
|
43
48
|
readonly sourceRoot: string;
|
|
44
49
|
}
|
|
@@ -343,6 +348,17 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
343
348
|
const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}');
|
|
344
349
|
if (!manifestBlock) return null;
|
|
345
350
|
|
|
351
|
+
if (classMatch[1] === 'ClawclawReminder') {
|
|
352
|
+
try {
|
|
353
|
+
const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
|
|
354
|
+
const { id, description, localizations } = reminder;
|
|
355
|
+
const name = reminder.name ?? id;
|
|
356
|
+
return { apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
|
|
357
|
+
manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations,
|
|
358
|
+
subjectScope: 'self_and_others', produces: [] } };
|
|
359
|
+
} catch { return null; }
|
|
360
|
+
}
|
|
361
|
+
|
|
346
362
|
const apiVersion = literalPluginApiVersion(manifestBlock) ?? null;
|
|
347
363
|
const id = literalProperty(manifestBlock, 'id')?.trim();
|
|
348
364
|
const name = literalProperty(manifestBlock, 'name')?.trim() ?? id;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { REMINDER_PLUGIN_API_VERSION, type ClawclawReminderManifest } from '../../sdk/perception-plugin/reminder.js';
|
|
2
|
+
import { REMINDER_FACT_TYPES } from '../../sdk/perception-plugin/reminder-rules.js';
|
|
3
|
+
import { hasValidClawclawResourceLocalizations } from '../../sdk/resource-metadata.js';
|
|
4
|
+
import { normalizeBehaviorInput, normalizeBehaviorInputFields } from './behavior-input-fields.js';
|
|
5
|
+
|
|
6
|
+
/** Used by both static Perception discovery and the isolated runtime loader. */
|
|
7
|
+
export function normalizeReminderManifest(value: unknown, requireCurrentVersion = true): ClawclawReminderManifest {
|
|
8
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid perception reminder manifest.');
|
|
9
|
+
const m = value as ClawclawReminderManifest;
|
|
10
|
+
if (m.kind !== 'reminder' || !Number.isInteger(m.apiVersion)
|
|
11
|
+
|| (requireCurrentVersion && m.apiVersion !== REMINDER_PLUGIN_API_VERSION)
|
|
12
|
+
|| typeof m.id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(m.id)
|
|
13
|
+
|| typeof m.description !== 'string' || !m.description.trim()
|
|
14
|
+
|| (m.name !== undefined && (typeof m.name !== 'string' || !m.name.trim()))
|
|
15
|
+
|| !hasValidClawclawResourceLocalizations(m.localizations)
|
|
16
|
+
|| m.topic !== 'tasks'
|
|
17
|
+
|| !Array.isArray(m.consumes) || new Set(m.consumes).size !== m.consumes.length
|
|
18
|
+
|| m.consumes.some(type => !(REMINDER_FACT_TYPES as readonly string[]).includes(type))
|
|
19
|
+
|| (m.config !== undefined && (!m.config || typeof m.config !== 'object' || Array.isArray(m.config)))
|
|
20
|
+
|| Object.keys(m).some(key => !['apiVersion', 'kind', 'id', 'name', 'description', 'localizations',
|
|
21
|
+
'topic', 'consumes', 'inputs', 'config'].includes(key))) throw new Error('Invalid perception reminder manifest.');
|
|
22
|
+
const inputs = m.inputs === undefined ? undefined : normalizeBehaviorInputFields(m.inputs);
|
|
23
|
+
const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
|
|
24
|
+
return { apiVersion: m.apiVersion, kind: 'reminder', id: m.id, description: m.description,
|
|
25
|
+
...(m.name === undefined ? {} : { name: m.name }),
|
|
26
|
+
...(m.localizations === undefined ? {} : { localizations: structuredClone(m.localizations) }),
|
|
27
|
+
topic: m.topic, consumes: [...m.consumes], ...(inputs === undefined ? {} : { inputs }), config };
|
|
28
|
+
}
|