@myclaw163/clawclaw-cli 0.10.15 → 0.10.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/cli-runtime/cli.js +16 -1
  3. package/cli-runtime/commands/runtime.js +35 -0
  4. package/cli-runtime/lib/account-resource-lock.js +15 -0
  5. package/cli-runtime/lib/agent-workspace-skills.js +3 -1
  6. package/cli-runtime/lib/desktop-mode.js +3 -0
  7. package/cli-runtime/lib/harness-context.js +20 -0
  8. package/cli-runtime/lib/init-command.js +2 -1
  9. package/cli-runtime/lib/lobby-host-context.js +1 -2
  10. package/cli-runtime/lib/skill-host.js +2 -0
  11. package/cli-runtime/lib/user-data.js +4 -2
  12. package/cli-runtime/runtime/clawclaw/behavior-reflex-control.js +27 -36
  13. package/cli-runtime/runtime/clawclaw/behavior-trigger.js +25 -46
  14. package/cli-runtime/runtime/clawclaw/owner-lock.js +2 -1
  15. package/cli-runtime/runtime/clawclaw/owner.js +7 -6
  16. package/cli-runtime/runtime/clawclaw/plugins/assembly.js +8 -7
  17. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-source.js +6 -5
  18. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-plugin.js +5 -2
  19. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-runner.js +2 -1
  20. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.js +7 -1
  21. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  22. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-module-loader.js +7 -17
  23. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-plugin.js +3 -30
  24. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.js +0 -2
  25. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +0 -2
  26. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +58 -1
  27. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +46 -25
  28. package/docs/configuration.md +6 -0
  29. package/docs/custom-modules/README.md +1 -2
  30. package/docs/custom-modules/api-reference.md +8 -10
  31. package/docs/custom-modules/behavior.md +21 -23
  32. package/docs/custom-modules/examples/auto-escape.ts +17 -19
  33. package/docs/custom-modules/perception.md +2 -2
  34. package/docs/runtime/README.md +1 -1
  35. package/docs/runtime/behavior-runtime.md +4 -5
  36. package/docs/runtime/components-and-boundaries.md +4 -5
  37. package/docs/runtime/events-and-state.md +1 -1
  38. package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
  39. package/docs/user-guide/README.md +1 -1
  40. package/docs/user-guide/api-reference.md +8 -10
  41. package/docs/user-guide/behavior.md +21 -23
  42. package/docs/user-guide/perception.md +2 -2
  43. package/package.json +1 -1
  44. package/skills/clawclaw/SKILL.md +3 -3
  45. package/skills/clawclaw/references/BEHAVIORS.md +1 -1
  46. package/skills/clawclaw-creator/SKILL.md +1 -1
  47. package/skills/clawclaw-creator/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +21 -23
  48. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +8 -10
  49. package/skills/clawclaw-creator/references/CUSTOM-MODULES.md +1 -2
  50. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +2 -2
  51. package/src/cli.ts +12 -1
  52. package/src/commands/runtime.ts +26 -0
  53. package/src/lib/account-resource-lock.ts +14 -0
  54. package/src/lib/agent-workspace-skills.ts +3 -2
  55. package/src/lib/desktop-mode.ts +4 -0
  56. package/src/lib/harness-context.ts +21 -0
  57. package/src/lib/init-command.ts +2 -1
  58. package/src/lib/lobby-host-context.ts +2 -2
  59. package/src/lib/skill-host.ts +2 -0
  60. package/src/lib/user-data.ts +5 -2
  61. package/src/runtime/clawclaw/behavior-reflex-control.ts +26 -22
  62. package/src/runtime/clawclaw/behavior-trigger.ts +20 -41
  63. package/src/runtime/clawclaw/owner-lock.ts +2 -1
  64. package/src/runtime/clawclaw/owner.ts +7 -6
  65. package/src/runtime/clawclaw/plugins/assembly.ts +11 -8
  66. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +7 -6
  67. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +6 -2
  68. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +2 -1
  69. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  70. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +1 -0
  71. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +8 -19
  72. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +4 -37
  73. package/src/runtime/clawclaw/plugins/trigger/trigger-source.ts +0 -2
  74. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +0 -2
package/src/cli.ts CHANGED
@@ -23,6 +23,7 @@ const registry = [
23
23
  if (!name || name === 'game') p.addCommand(module.createGameCommand());
24
24
  } },
25
25
  { names: ['account'], register: async (p: Command) => p.addCommand((await import('./commands/account.js')).createAccountCommand()) },
26
+ { names: ['runtime'], register: async (p: Command) => p.addCommand((await import('./commands/runtime.js')).createRuntimeCommand()) },
26
27
  { names: ['auth'], register: async (p: Command) => p.addCommand((await import('./commands/auth.js')).createAuthCommand()) },
27
28
  { names: ['competition'], register: async (p: Command) => p.addCommand((await import('./commands/competition.js')).createCompetitionCommand()) },
28
29
  { names: ['capability', 'cap'], register: async (p: Command) => p.addCommand((await import('./commands/capability.js')).createCapabilityCommand()) },
@@ -81,7 +82,17 @@ try {
81
82
  }
82
83
  startupMark('cli.modules_loaded');
83
84
  startupMark('cli.parse_ready');
84
- await program.parseAsync();
85
+ const context = (await import('./lib/harness-context.js')).harnessContext();
86
+ if (context && !context.session && (name === 'join' || name === 'start' || (name === 'game' && ['start', 's', 'join-room', 'create-room', 'training'].includes(args[1] ?? ''))) && !args.includes('--help')) {
87
+ throw new Error('INVALID_HARNESS_CONTEXT: game launch requires CLAWCLAW_HOST_SESSION_ID.');
88
+ }
89
+ const writesResources = ['prepare', 'capability', 'cap', 'hub', 'skill', 'persona', 'prs', 'memory', 'mem', 'strategy', 'behavior', 'beh', 'perception', 'pcp', 'trigger', 'trg'];
90
+ let guard;
91
+ if (name && writesResources.includes(name) && !args.includes('--help') && !args.includes('-h')) {
92
+ const { acquireAccountResourceLock } = await import('./lib/account-resource-lock.js');
93
+ guard = acquireAccountResourceLock();
94
+ }
95
+ try { await program.parseAsync(); } finally { guard?.release(); }
85
96
  startupMark('cli.complete');
86
97
  } catch (err) {
87
98
  process.stderr.write(`${formatCommandError(err)}\n`);
@@ -0,0 +1,26 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { getWorkspaceDir } from '../lib/init-command.js';
5
+ import { getRuntimeDir } from '../lib/user-data.js';
6
+ import { resolveBundledClawclawSkill } from '../lib/skill-host.js';
7
+
8
+ export function createRuntimeCommand(): Command {
9
+ const command = new Command('runtime').description('Inspect the effective local CCL installation');
10
+ command.command('info').option('--json').action(() => {
11
+ const workspace = getWorkspaceDir();
12
+ const skillDirectory = resolveBundledClawclawSkill();
13
+ const root = dirname(dirname(skillDirectory));
14
+ const {version} = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
15
+ console.log(JSON.stringify({ protocolVersion: 1, version, workspace, runtimeDirectory: getRuntimeDir(workspace),
16
+ skillDirectory, executable: process.execPath, cli: join(root, 'bin', 'clawclaw-cli.mjs') }));
17
+ });
18
+ command.command('skills').option('--json').action(async () => {
19
+ const { AuthStore } = await import('../lib/auth.js');
20
+ const { accountManagedSkillSources } = await import('../lib/agent-workspace-skills.js');
21
+ const profile = new AuthStore().getActive();
22
+ const sources = profile ? accountManagedSkillSources(getWorkspaceDir(), profile) : new Map<string, string>();
23
+ console.log(JSON.stringify(Array.from(sources, ([name, directory]) => ({ name, directory }))));
24
+ });
25
+ return command;
26
+ }
@@ -0,0 +1,14 @@
1
+ import { join } from 'node:path';
2
+ import { tryAcquireRuntimeLock } from '@myclaw163/game-agent-runtime/owner/runtime-lock.js';
3
+ import { AuthStore } from './auth.js';
4
+ import { getWorkspaceDir } from './init-command.js';
5
+ import { getUserDataAccountDir } from './user-data.js';
6
+
7
+ /** 终端与各客户端共用账号资源;进程退出时操作系统释放写锁。 */
8
+ export function acquireAccountResourceLock() {
9
+ const profile = new AuthStore().getActive();
10
+ if (!profile) return;
11
+ const lock = tryAcquireRuntimeLock(join(getUserDataAccountDir(getWorkspaceDir(), profile), '.resource-lock'));
12
+ if (!lock) throw new Error('ACCOUNT_RESOURCES_BUSY: another command is using this account’s resources. Retry after it finishes.');
13
+ return lock;
14
+ }
@@ -1,3 +1,4 @@
1
+ import { harnessContext } from './harness-context.js';
1
2
  import { isPackageManagedSkill, reservedSkillName } from './package-skills.js';
2
3
  import {
3
4
  existsSync,
@@ -216,7 +217,7 @@ export function inspectSkillNameConflicts(
216
217
  });
217
218
  }
218
219
 
219
- function accountManagedSkillSources(
220
+ export function accountManagedSkillSources(
220
221
  workspaceDir: string,
221
222
  profile: Pick<AuthProfile, 'apiKey'>,
222
223
  includeInactive = false,
@@ -262,7 +263,7 @@ export function switchActiveAccountSkillLinks(
262
263
  nextProfile: Pick<AuthProfile, 'apiKey'> | null,
263
264
  dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
264
265
  ): AccountSkillLinkSwitchResult {
265
- if (previousProfile?.apiKey === nextProfile?.apiKey) return { removed: [], linked: [] };
266
+ if (harnessContext() || previousProfile?.apiKey === nextProfile?.apiKey) return { removed: [], linked: [] };
266
267
  const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir);
267
268
  if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
268
269
  guard.release();
@@ -1,4 +1,8 @@
1
+ import { harnessContext } from './harness-context.js';
2
+
1
3
  export function isDesktopMode(env: NodeJS.ProcessEnv = process.env): boolean {
4
+ const mode = harnessContext(env)?.auth;
5
+ if (mode) return mode === 'managed';
2
6
  return env.CLAWCLAW_IS_DESKTOP === 'true';
3
7
  }
4
8
 
@@ -0,0 +1,21 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+
4
+ export function harnessContext(env: NodeJS.ProcessEnv = process.env) {
5
+ const { CLAWCLAW_HOST_KIND: kind, CLAWCLAW_HOST_INSTANCE_ID: instance, CLAWCLAW_HOST_SESSION_ID: session, CLAWCLAW_AUTH_MODE: auth } = env;
6
+ // 已发布的宿主仅传 Lobby 身份。显式声明客户端类型才启用隔离目录。
7
+ if (kind === undefined && auth === undefined) return undefined;
8
+ if (!kind || !/^[a-z][a-z0-9-]{0,63}$/.test(kind) || !instance || !/^[^\s\p{Cc}]{1,128}$/u.test(instance) ||
9
+ (session !== undefined && !/^[^\s\p{Cc}]{1,128}$/u.test(session)) ||
10
+ (auth !== undefined && auth !== 'managed' && auth !== 'standalone')) {
11
+ throw new Error('INVALID_HARNESS_CONTEXT: provide a valid kind, persistent instance ID and optional session/auth mode.');
12
+ }
13
+ return { kind, instance, session, auth };
14
+ }
15
+
16
+ export function stateRoot(workspace: string): string {
17
+ const context = harnessContext();
18
+ if (!context) return workspace;
19
+ const id = createHash('sha256').update(JSON.stringify([context.kind, context.instance])).digest('hex');
20
+ return join(workspace, 'contexts', id);
21
+ }
@@ -1,3 +1,4 @@
1
+ import { stateRoot } from './harness-context.js';
1
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
2
3
  import { isAbsolute, join, resolve, win32 } from 'path';
3
4
  import { homedir } from 'os';
@@ -78,7 +79,7 @@ export function cmdInit(force = false): { created: boolean; path: string } {
78
79
  }
79
80
 
80
81
  export function getAccountDir(accountId: string): string {
81
- return join(getWorkspaceDir(), 'accounts', accountId);
82
+ return join(stateRoot(getWorkspaceDir()), 'accounts', accountId);
82
83
  }
83
84
 
84
85
  export function createAccountDirs(accountId: string): void {
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { isDesktopMode } from './desktop-mode.js';
2
+
3
3
  import { ApiError } from './http-transport.js';
4
4
 
5
5
  /** Participation origin, not an authentication or GameSync session identity. */
@@ -45,7 +45,7 @@ export function validateLobbyHostContext(value: LobbyHostContext): LobbyHostCont
45
45
  export function resolveLobbyHostContext(env: NodeJS.ProcessEnv = process.env): LobbyHostContext {
46
46
  const instanceId = env.CLAWCLAW_HOST_INSTANCE_ID;
47
47
  const sessionId = env.CLAWCLAW_HOST_SESSION_ID;
48
- if (isDesktopMode(env)) {
48
+ if (env.CLAWCLAW_IS_DESKTOP === 'true') {
49
49
  if (!validId(instanceId) || !validId(sessionId)) {
50
50
  throw new InvalidHostContextError('Desktop must provide CLAWCLAW_HOST_INSTANCE_ID and CLAWCLAW_HOST_SESSION_ID (1–128 characters, no whitespace/control characters).');
51
51
  }
@@ -1,3 +1,4 @@
1
+ import { harnessContext } from './harness-context.js';
1
2
  import { spawnSync } from 'node:child_process';
2
3
  import {
3
4
  cpSync,
@@ -100,6 +101,7 @@ function openClawSkillsDir(homeDir: string): string {
100
101
  }
101
102
 
102
103
  export function agentSkillTargets(name: string): string[] {
104
+ if (harnessContext()) return [];
103
105
  const homeDir = homedir();
104
106
  const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homeDir, '.claude');
105
107
  const codexHome = process.env.CODEX_HOME?.trim() || join(homeDir, '.codex');
@@ -1,3 +1,4 @@
1
+ import { harnessContext, stateRoot } from './harness-context.js';
1
2
  import {
2
3
  copyFileSync,
3
4
  existsSync,
@@ -39,11 +40,11 @@ export function getUserDataDir(workspaceDir: string): string {
39
40
  }
40
41
 
41
42
  export function getRuntimeDir(workspaceDir: string): string {
42
- return join(workspaceDir, RUNTIME_DIR);
43
+ return join(stateRoot(workspaceDir), RUNTIME_DIR);
43
44
  }
44
45
 
45
46
  export function getUserDataAuthFile(workspaceDir: string): string {
46
- return join(getUserDataDir(workspaceDir), 'auth.json');
47
+ return join(getUserDataDir(stateRoot(workspaceDir)), 'auth.json');
47
48
  }
48
49
 
49
50
  export function getRuntimeAuthStateFile(workspaceDir: string): string {
@@ -404,6 +405,8 @@ export function ensureUserDataLayout(workspaceDir: string): UserDataMigrationRes
404
405
  ensureDir(getUserDataHubDir(workspaceDir));
405
406
  ensureDir(getRuntimeDir(workspaceDir));
406
407
 
408
+ // 客户端不导入终端已有的凭据。
409
+ if (harnessContext()) return result;
407
410
  const auth = migrateAuth(workspaceDir, result);
408
411
  migrateAccountFiles(workspaceDir, auth, result);
409
412
  writeMigrationMarker(workspaceDir, result);
@@ -1,8 +1,8 @@
1
1
  import { normalizeBehaviorInput } from './behavior-input-fields.js';
2
2
  import type { ClawclawBehaviorCatalog } from './plugins/behavior/behavior-catalog.js';
3
3
  import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js';
4
- import type { ClawclawTriggerPlugin } from './plugins/trigger/trigger-plugin.js';
5
4
  import type { ClawclawPerceptionModulePlugin } from './plugins/perception/perception-module-plugin.js';
5
+ import type { ResolvedClawclawPerceptionSource } from './plugins/perception/perception-source.js';
6
6
 
7
7
  type Scope = Readonly<{ sessionId: string; segmentId: string }>;
8
8
  const same = (a: Scope, b: Scope) => a.sessionId === b.sessionId && a.segmentId === b.segmentId;
@@ -16,21 +16,13 @@ export class BehaviorReflexControl {
16
16
  private readonly behavior: Pick<ClawclawBehaviorPlugin, 'status' | 'updateReflex' | 'configureInput'>,
17
17
  private readonly catalog: Pick<ClawclawBehaviorCatalog, 'list'>,
18
18
  private readonly scope: () => Scope,
19
- private readonly triggers?: Pick<ClawclawTriggerPlugin, 'descriptors' | 'configureEmbedded'>) {}
20
-
21
- private embedded(id?: string) {
22
- return (this.triggers?.descriptors() ?? []).filter(item => item.embedded && (id === undefined || item.behavior === id));
23
- }
19
+ private readonly embedded: readonly ResolvedClawclawPerceptionSource[] = []) {}
24
20
  status(id?: string) {
25
21
  this.refreshScope();
26
22
  const active = this.behavior.status().stack.reflex;
27
- const embedded = this.embedded(id).map(item => ({
28
- source: 'strategy' as const, behavior_id: item.behavior, trigger_id: item.id,
29
- available: true, enabled: item.enabled, waiting_for_input: item.waitingForInput,
30
- armed: item.armed, cooldown_remaining_ms: item.cooldownRemainingMs,
31
- priority: item.reflexPriority, cooldown_ms: item.cooldownMs, rearm: item.rearm, max_runtime_ms: item.maxRuntimeMs,
32
- }));
33
- return [...embedded, ...(this.modules?.bindings(id) ?? [])].map(binding => ({ ...binding,
23
+ return (this.modules?.bindings(id) ?? []).map(binding => ({ ...binding,
24
+ ...(this.embedded.some(source => source.id === binding.perception_id)
25
+ ? { source: 'strategy', behavior_id: binding.id, config: this.modules?.status(binding.perception_id)[0]?.input } : {}),
34
26
  active: active?.triggerId === binding.trigger_id,
35
27
  ...(active?.triggerId === binding.trigger_id ? { activation_id: active.activationId,
36
28
  instance_generation: active.instanceGeneration } : {}), scope: this.currentScope }));
@@ -54,8 +46,7 @@ export class BehaviorReflexControl {
54
46
  if (!guard()) throw Error('stale_runtime_scope');
55
47
  const entry = this.catalog.list().find(entry => entry.id === id);
56
48
  if (!entry) throw Error('behavior_not_found');
57
- const embedded = this.embedded(id)[0];
58
- if (operation !== 'update' && !embedded) {
49
+ if (operation !== 'update') {
59
50
  const bindings = this.modules?.bindings(id) ?? [];
60
51
  if (!bindings.length || operation === 'enable' && !bindings.some(binding => binding.available)) {
61
52
  throw Error('perception_binding_unavailable');
@@ -64,18 +55,31 @@ export class BehaviorReflexControl {
64
55
  let input = this.parameters.get(id) ?? {}, updated = 0;
65
56
  // A detector may inject required targets later; enabling alone does not prepare a Behavior.
66
57
  if (operation === 'update' || Object.keys(patch).length) {
67
- input = normalizeBehaviorInput({ ...input, ...patch },entry.inputs);
68
- updated = await this.behavior.configureInput(id,input,patch,guard,
69
- () => {
58
+ const source = this.embedded.find(source => source.embedded?.strategyId === id);
59
+ const fields = source?.module?.inputs ?? [];
60
+ const detectorPatch: Record<string, unknown> = {};
61
+ const executionPatch: Record<string, unknown> = {};
62
+ for (const [key, value] of Object.entries(patch)) {
63
+ const observed = fields.some(field => field.id === key);
64
+ if (observed) detectorPatch[key] = value;
65
+ if (!observed || entry.inputs.some(field => field.id === key)) executionPatch[key] = value;
66
+ }
67
+ const configureDetector = () => {
68
+ if (source && Object.keys(detectorPatch).length) this.modules?.configure(source.id, detectorPatch, guard);
69
+ };
70
+ if (Object.keys(executionPatch).length || !Object.keys(detectorPatch).length) {
71
+ input = normalizeBehaviorInput({ ...input, ...executionPatch }, entry.inputs);
72
+ updated = await this.behavior.configureInput(id, input, executionPatch, guard, () => {
73
+ configureDetector();
70
74
  this.parameters.set(id, input);
71
- this.triggers?.configureEmbedded(id, { input });
72
75
  this.modules?.behaviorInputChanged(id);
73
76
  });
77
+ } else {
78
+ configureDetector();
79
+ }
74
80
  }
75
81
  if (operation !== 'update') {
76
- if (!guard()) throw Error('stale_runtime_scope');
77
- if (embedded) this.triggers?.configureEmbedded(id, { enabled: operation === 'enable' });
78
- const triggerIds = embedded ? [embedded.id] : this.modules?.setWatch(id,operation === 'enable',guard);
82
+ const triggerIds = this.modules?.setWatch(id,operation === 'enable',guard);
79
83
  if (!triggerIds) throw Error('perception_binding_unavailable');
80
84
  if (operation === 'disable') for (const triggerId of triggerIds) {
81
85
  updated += Number(await this.behavior.updateReflex(triggerId,undefined,guard));
@@ -1,49 +1,28 @@
1
- import {
2
- MAX_TRIGGER_RUNTIME_MS,
3
- TRIGGER_PLUGIN_API_VERSION,
4
- type StrategyTriggerManifest,
5
- } from '../../sdk/trigger-plugin/index.js';
1
+ import { normalizePerceptionModuleManifest } from './perception-module-manifest.js';
6
2
  import type { ResolvedClawclawBehaviorSource } from './plugins/behavior/behavior-source.js';
7
- import type { ResolvedClawclawTriggerSource } from './plugins/trigger/trigger-source.js';
3
+ import type { ResolvedClawclawPerceptionSource } from './plugins/perception/perception-source.js';
8
4
 
9
- const fields = new Set(['apiVersion', 'consumes', 'defaultReflexPriority', 'defaultCooldownMs',
10
- 'defaultRearm', 'defaultMaxRuntimeMs']);
11
-
12
- export function normalizeStrategyTriggerManifest(value: unknown): Required<Omit<StrategyTriggerManifest, 'id'>> {
13
- const manifest = value as StrategyTriggerManifest | undefined;
14
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)
15
- || manifest.apiVersion !== TRIGGER_PLUGIN_API_VERSION
16
- || Object.keys(manifest).some(key => !fields.has(key))) {
17
- throw new Error('strategy_trigger_manifest_invalid');
18
- }
19
- const consumes = manifest.consumes === undefined ? [] : manifest.consumes;
20
- if (!Array.isArray(consumes) || consumes.some(type => typeof type !== 'string'
21
- || !/^(?:\\*|[a-z0-9][a-z0-9._-]*)$/.test(type)) || new Set(consumes).size !== consumes.length) {
22
- throw new Error('strategy_trigger_consumes_invalid');
23
- }
24
- const {
25
- defaultReflexPriority = 0,
26
- defaultCooldownMs = 1_000,
27
- defaultRearm = 'after_clear',
28
- defaultMaxRuntimeMs = 10_000,
29
- } = manifest;
30
- if (!Number.isSafeInteger(defaultReflexPriority)
31
- || !Number.isSafeInteger(defaultCooldownMs) || defaultCooldownMs < 0
32
- || (defaultRearm !== 'after_clear' && defaultRearm !== 'after_cooldown')
33
- || !Number.isSafeInteger(defaultMaxRuntimeMs) || defaultMaxRuntimeMs < 1
34
- || defaultMaxRuntimeMs > MAX_TRIGGER_RUNTIME_MS) {
35
- throw new Error('strategy_trigger_defaults_invalid');
5
+ export function normalizeStrategyPerception(value: unknown, strategyId: string) {
6
+ const manifest = normalizePerceptionModuleManifest(value);
7
+ const bindings = Object.values(manifest.behaviors ?? {});
8
+ if (!bindings.length || bindings.some(binding => binding.name !== strategyId || binding.resourceId !== undefined)) {
9
+ throw Error('strategy_perception_self_binding_required');
36
10
  }
37
- return { apiVersion: TRIGGER_PLUGIN_API_VERSION, consumes: [...consumes],
38
- defaultReflexPriority, defaultCooldownMs, defaultRearm, defaultMaxRuntimeMs };
11
+ return manifest;
39
12
  }
40
13
 
41
- export function strategyTriggerSource(source: ResolvedClawclawBehaviorSource): ResolvedClawclawTriggerSource | undefined {
14
+ /** Route a named perception through the same host as an equipped Hub perception. */
15
+ export function strategyTriggerSource(source: ResolvedClawclawBehaviorSource): ResolvedClawclawPerceptionSource | undefined {
42
16
  if (!source.trigger) return undefined;
43
- const { name, description, sourcePath, sourceRoot, inputs } = source;
44
- const id = 'behavior:' + source.id;
45
17
  const { manifest, sha256 } = source.trigger;
46
- return { apiVersion: manifest.apiVersion, id, name, description, sourcePath, sourceRoot,
47
- embedded: { manifest, sha256 },
48
- manifest: { ...manifest, id, name, description, inputs, defaultBehavior: source.id, defaultBehaviorInput: {} } };
18
+ const id = 'strategy:' + source.id;
19
+ const name = manifest.name ?? manifest.id;
20
+ const behaviors = Object.fromEntries(Object.entries(manifest.behaviors!).map(([key, binding]) =>
21
+ [key, { ...binding, name: source.id }]));
22
+ return { id, name, description: manifest.description, apiVersion: 3,
23
+ sourcePath: source.sourcePath, sourceRoot: source.sourceRoot,
24
+ embedded: { strategyId: source.id, sha256, declaredManifest: manifest },
25
+ module: { ...manifest, behaviors },
26
+ manifest: { apiVersion: 2, id, name, description: manifest.description,
27
+ subjectScope: 'self_and_others', produces: manifest.produces ?? [] } };
49
28
  }
@@ -1,3 +1,4 @@
1
+ import { stateRoot } from '../../lib/harness-context.js';
1
2
  import { timeStartup } from '../../../bin/startup-trace.mjs';
2
3
  import { createHash, randomUUID } from 'node:crypto';
3
4
  import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -47,7 +48,7 @@ export function workspaceOwnerRecordPath(workspaceDir = getWorkspaceDir()): stri
47
48
  return join(getRuntimeDir(workspaceDir), 'owner.json');
48
49
  }
49
50
  export function workspaceOwnerIdentity(workspaceDir = getWorkspaceDir()): string {
50
- const real = realpathSync(workspaceDir);
51
+ const real = realpathSync(stateRoot(workspaceDir));
51
52
  return createHash('sha256').update(process.platform === 'win32' ? real.toLowerCase() : real).digest('hex');
52
53
  }
53
54
  function readOwnerRecord(path: string): OwnerRecord | null {
@@ -638,9 +638,8 @@ export async function runClawclawOwner(
638
638
  behavior_id: source.id, reason: source.triggerError,
639
639
  });
640
640
  const trigger = strategyTriggerSource(source);
641
- return trigger ? [{ source: trigger, enabled: true }] : [];
641
+ return trigger ? [trigger] : [];
642
642
  });
643
- const triggers = [...legacyTriggers, ...embeddedTriggers];
644
643
  const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules);
645
644
  const agentPerceptionSources = agentWorkspace
646
645
  ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace)
@@ -673,7 +672,8 @@ export async function runClawclawOwner(
673
672
  triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
674
673
  fallbackBehaviors,
675
674
  behaviorEventTypes,
676
- triggers,
675
+ triggers: legacyTriggers,
676
+ embeddedPerceptions: embeddedTriggers,
677
677
  });
678
678
  await assembly.behavior.setIdleMs(gameplayConfig.idle_ms);
679
679
  const epochPlugins = assembly.plugins;
@@ -684,7 +684,7 @@ export async function runClawclawOwner(
684
684
  intent,
685
685
  );
686
686
  const reflexControl = new BehaviorReflexControl(assembly.modules,
687
- assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), assembly.trigger);
687
+ assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), embeddedTriggers);
688
688
  const runtimeDone = startupSpan('owner.runtime_init');
689
689
  runtime = createClawclawRuntime(options.profile, {
690
690
  processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()),
@@ -756,7 +756,7 @@ export async function runClawclawOwner(
756
756
  : null,
757
757
  },
758
758
  perception: assembly.perception.diagnosticSnapshot(),
759
- trigger: assembly.trigger.diagnosticSnapshot(),
759
+ trigger: assembly.trigger?.diagnosticSnapshot(),
760
760
  }, {
761
761
  component: 'runtime.diagnostics',
762
762
  scope: runtime?.publicScope(),
@@ -773,7 +773,7 @@ export async function runClawclawOwner(
773
773
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
774
774
  }
775
775
  const mailboxRepository = runtime.repository;
776
- const perceptionSourceById = new Map(perceptionSources.map(source => [source.id, source]));
776
+ const perceptionSourceById = new Map([...perceptionSources, ...embeddedTriggers].map(source => [source.id, source]));
777
777
  const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
778
778
  producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...(assembly.modules ? [assembly.modules.id] : [])],
779
779
  descriptor: id => {
@@ -1358,6 +1358,7 @@ export async function runClawclawOwner(
1358
1358
  if (!currentTriggerSources.some((source) => source.id === request.trigger)) {
1359
1359
  return { ok: false, type: 'trigger_configure', error: 'trigger_source_unavailable' };
1360
1360
  }
1361
+ if (!assembly.trigger) return { ok: false, type: request.type, error: 'trigger_runtime_restart_required' };
1361
1362
  assembly.trigger.configure(triggerRegistrations(
1362
1363
  currentTriggerSources,
1363
1364
  latest,
@@ -1,7 +1,7 @@
1
1
  import type { GameClient } from '../../../lib/game-client.js';
2
2
  import { ClawclawStrategyMemory } from '../strategy-memory.js';
3
3
  import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
4
- import { listClawclawPerceptionSources, isSupportedPerceptionSource } from './perception/perception-source.js';
4
+ import { listClawclawPerceptionSources, isSupportedPerceptionSource, type ResolvedClawclawPerceptionSource } from './perception/perception-source.js';
5
5
  import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
6
6
  import { ClawclawPerceptionModulePlugin, CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID } from './perception/perception-module-plugin.js';
7
7
  import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
@@ -44,6 +44,7 @@ export interface ClawclawPluginAssemblyOptions {
44
44
  triggerDiagnosticsEnabled?: boolean;
45
45
  fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
46
46
  triggers?: readonly ClawclawTriggerRegistration[];
47
+ embeddedPerceptions?: readonly ResolvedClawclawPerceptionSource[];
47
48
  /** All enabled Behavior Event declarations frozen into the startup plugin graph. */
48
49
  behaviorEventTypes?: readonly string[];
49
50
  }
@@ -55,7 +56,7 @@ export interface ClawclawPluginAssembly {
55
56
  gameQuery: ClawclawGameQueryPlugin;
56
57
  perception: ClawclawPerceptionPlugin;
57
58
  reminders: ClawclawReminderPlugin;
58
- trigger: ClawclawTriggerPlugin;
59
+ trigger?: ClawclawTriggerPlugin;
59
60
  behavior: ClawclawBehaviorPlugin;
60
61
  mailbox: ClawclawMailboxPlugin;
61
62
  }
@@ -125,14 +126,16 @@ export function assembleClawclawPlugins(
125
126
  throw new Error(`Runtime Plugin ${CLAWCLAW_TRIGGER_PLUGIN_ID} is not a ClawclawTriggerPlugin.`);
126
127
  }
127
128
  const trigger = configuredTrigger as ClawclawTriggerPlugin | undefined
128
- ?? new ClawclawTriggerPlugin({
129
+ // Compatibility only for previously installed standalone Trigger resources.
130
+ ?? (options.triggers?.length ? new ClawclawTriggerPlugin({
129
131
  after: [],
130
132
  triggers: options.triggers,
131
133
  diagnosticsEnabled: options.triggerDiagnosticsEnabled,
132
- });
133
- if (!configuredTrigger) plugins.push(trigger);
134
+ }) : undefined);
135
+ if (trigger && !configuredTrigger) plugins.push(trigger);
134
136
 
135
- const modules = moduleSources.length ? new ClawclawPerceptionModulePlugin({ sources: moduleSources,
137
+ const sources = [...moduleSources, ...(options.embeddedPerceptions ?? [])];
138
+ const modules = sources.length ? new ClawclawPerceptionModulePlugin({ sources,
136
139
  after: [],
137
140
  behaviors: () => options.behaviorCatalog?.list?.() ?? [],
138
141
  }) : undefined;
@@ -160,11 +163,11 @@ export function assembleClawclawPlugins(
160
163
  if (!configuredBehavior) plugins.push(behavior);
161
164
 
162
165
  const strategyMemory = new ClawclawStrategyMemory();
163
- trigger.attachMemory(strategyMemory);
166
+ trigger?.attachMemory(strategyMemory);
164
167
  behavior.attachMemory(strategyMemory);
165
168
  modules?.attachMemory(strategyMemory);
166
169
  modules?.attachDriver(behavior);
167
- trigger.attachDriver(behavior);
170
+ trigger?.attachDriver(behavior);
168
171
  // Direct Agent/user commands remain ActionPlugin calls this round. Preserve
169
172
  // their original activity timing: mark activity at Action admission, before
170
173
  // the backend request starts, without routing the command through Behavior.
@@ -20,7 +20,7 @@ import {
20
20
  hasValidClawclawResourceLocalizations,
21
21
  } from '../../../../sdk/behavior-plugin/index.js';
22
22
  import { parseLiteralBehaviorInputFields, parseLiteralModuleManifest } from '../behavior-input-source.js';
23
- import { normalizeStrategyTriggerManifest } from '../../behavior-trigger.js';
23
+ import { normalizeStrategyPerception } from '../../behavior-trigger.js';
24
24
  import {
25
25
  behaviorProducesDiagnostic,
26
26
  deepFreezeBehaviorValue,
@@ -32,7 +32,7 @@ const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
32
32
  const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/;
33
33
  const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
34
34
  const NAMED_TRIGGER = /export\s+class\s+Trigger\b/;
35
- const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawTrigger(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
35
+ const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawPerception(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
36
36
  const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/;
37
37
  const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
38
38
  const MANIFEST_FIELDS = new Set([
@@ -80,7 +80,7 @@ export interface ResolvedClawclawBehaviorSource {
80
80
  readonly everyTicks: number;
81
81
  readonly produces?: readonly string[];
82
82
  readonly runtime?: Readonly<BehaviorRuntimeDefaults>;
83
- readonly trigger?: Readonly<{ manifest: ReturnType<typeof normalizeStrategyTriggerManifest>; sha256: string }>;
83
+ readonly trigger?: Readonly<{ manifest: ReturnType<typeof normalizeStrategyPerception>; sha256: string }>;
84
84
  readonly triggerError?: string;
85
85
  /** Host-authenticated origin. It is never parsed from module source. */
86
86
  readonly provenance?: Readonly<ClawclawBehaviorSourceProvenance>;
@@ -598,10 +598,11 @@ export function inspectClawclawBehaviorSource(
598
598
  if (namedTrigger) {
599
599
  try {
600
600
  const match = TRIGGER_CLASS.exec(masked.slice(namedTrigger.index));
601
- if (match) match.index = namedTrigger.index;
602
- const literal = match && classManifest(source, match);
601
+ if (!match) throw Error('strategy_trigger_requires_perception_v3');
602
+ match.index = namedTrigger.index;
603
+ const literal = classManifest(source, match);
603
604
  trigger = {
604
- manifest: normalizeStrategyTriggerManifest(literal && parseLiteralModuleManifest(literal)),
605
+ manifest: normalizeStrategyPerception(literal && parseLiteralModuleManifest(literal), compatible.id),
605
606
  sha256: createHash('sha256').update(source).digest('hex'),
606
607
  };
607
608
  } catch (error) {
@@ -103,10 +103,13 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
103
103
  const { input, game, frame, facts, eventStates, boundary, common } = prepared.value as Prepared;
104
104
  const events = facts.filter(event => source.module.consumes?.includes(event.type));
105
105
  const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
106
+ const embedded = sourceValue(source).embedded;
107
+ const declaredTargets = embedded && bindings.availableBindings.length
108
+ ? Object.values(embedded.declaredManifest.behaviors ?? {}).map(binding => binding.name) : [];
106
109
  const moduleInput: PerceptionModuleInput = { ...common, moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
107
110
  ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
108
111
  events, eventStates: Object.fromEntries(events.map(event => [event.eventId, eventStates[event.eventId]])), nowMs: prepared.nowMs,
109
- state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
112
+ state, config, ...bindings, availableStrategies: [...new Set([...bindings.availableBehaviors, ...declaredTargets])], taskChanges: comparison.changes, boundary };
110
113
  return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
111
114
  evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || !!common.roomState || !!common.queueState
112
115
  || moduleInput.events.length > 0 || !!moduleInput.lifecycle?.length };
@@ -125,6 +128,7 @@ export class ClawclawPerceptionModulePlugin extends PerceptionHost {
125
128
  sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) });
126
129
  }
127
130
  override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
128
- return super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
131
+ const descriptors = super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
132
+ return descriptors.filter(item => !item.id.startsWith('strategy:'));
129
133
  }
130
134
  }
@@ -6,7 +6,8 @@ import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runt
6
6
  import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
7
7
  export class PerceptionModuleRunner extends PerceptionWorker<PerceptionModuleInput, PerceptionModuleResult> {
8
8
  constructor(readonly source: ResolvedClawclawPerceptionSource, bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {
9
- super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.module,
9
+ super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.embedded?.declaredManifest ?? source.module,
10
+ embeddedSha256: source.embedded?.sha256,
10
11
  legacy: !!source.reaction, runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
11
12
  ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(source.sourcePath)).href] } } }, bindMemory);
12
13
  }
@@ -1,3 +1,5 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
1
3
  import { pathToFileURL } from 'node:url';
2
4
  import { runPerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker-host.js';
3
5
  import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
@@ -7,7 +9,11 @@ import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
9
  import { CLAWCLAW_PERCEPTION_SPATIAL_API } from './spatial-facts.js';
8
10
 
9
11
  await runPerceptionWorker<PerceptionModuleInput>(async data => {
10
- const Module = (await import(pathToFileURL(data.modulePath).href)).default;
12
+ if (data.embeddedSha256 && createHash('sha256').update(readFileSync(data.modulePath)).digest('hex') !== data.embeddedSha256) {
13
+ throw Error('strategy_perception_source_changed');
14
+ }
15
+ const exports = await import(pathToFileURL(data.modulePath).href);
16
+ const Module = data.embeddedSha256 ? exports.Trigger : exports.default;
11
17
  if (!(Module?.prototype instanceof (data.legacy ? ClawclawReaction : ClawclawPerception))
12
18
  || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw Error('PERCEPTION_MODULE_CLASS_INVALID');
13
19
  const legacy = data.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
@@ -51,6 +51,7 @@ export interface ResolvedClawclawPerceptionSource {
51
51
  readonly reminder?: ClawclawReminderManifest;
52
52
  readonly module?: PerceptionModuleManifest;
53
53
  readonly reaction?: ClawclawReactionManifest;
54
+ readonly embedded?: Readonly<{ strategyId: string; sha256: string; declaredManifest: PerceptionModuleManifest }>;
54
55
  readonly sourcePath: string;
55
56
  readonly sourceRoot: string;
56
57
  }