@myclaw163/clawclaw-cli 0.10.3 → 0.10.5

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 (45) hide show
  1. package/docs/configuration.md +2 -0
  2. package/docs/custom-modules/perception.md +2 -0
  3. package/docs/custom-modules/skill.md +8 -0
  4. package/docs/user-guide/desktop-auth.md +45 -0
  5. package/docs/user-guide/perception.md +2 -0
  6. package/docs/user-guide/skill.md +8 -0
  7. package/package.json +1 -1
  8. package/skills/clawclaw/SKILL.md +8 -3
  9. package/skills/clawclaw/references/COMMANDS.md +2 -2
  10. package/skills/clawclaw/references/GAME-MECHANICS.md +34 -49
  11. package/src/cli.ts +2 -0
  12. package/src/commands/account.ts +12 -3
  13. package/src/commands/auth.ts +133 -0
  14. package/src/commands/behavior.ts +2 -1
  15. package/src/commands/capability.ts +4 -1
  16. package/src/commands/communication.ts +2 -1
  17. package/src/commands/data.ts +2 -1
  18. package/src/commands/events.ts +2 -1
  19. package/src/commands/load.ts +8 -3
  20. package/src/commands/memory.ts +2 -1
  21. package/src/commands/module-runtime-control.ts +2 -1
  22. package/src/commands/perception.ts +2 -1
  23. package/src/commands/persona.ts +2 -1
  24. package/src/lib/account-guidance.ts +5 -0
  25. package/src/lib/agent-workspace-skills.ts +93 -10
  26. package/src/lib/auth.ts +8 -1
  27. package/src/lib/capability-cloud-refresh.ts +3 -0
  28. package/src/lib/capability-cloud-sync.ts +7 -1
  29. package/src/lib/capability-selection.ts +8 -0
  30. package/src/lib/desktop-auth.ts +40 -0
  31. package/src/lib/desktop-mode.ts +9 -0
  32. package/src/lib/game-client.ts +2 -1
  33. package/src/lib/hub-client.ts +2 -1
  34. package/src/lib/load-context.ts +2 -1
  35. package/src/lib/persona.ts +2 -1
  36. package/src/lib/skill-host.ts +10 -0
  37. package/src/lib/skill-name-conflicts.ts +110 -0
  38. package/src/pipeline/event-format.ts +6 -0
  39. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  40. package/src/runtime/clawclaw/behavior-start-control.ts +79 -0
  41. package/src/runtime/clawclaw/owner-lock.ts +5 -1
  42. package/src/runtime/clawclaw/owner.ts +8 -21
  43. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +53 -0
  44. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +2 -1
  45. package/src/runtime/clawclaw-event-catalog.ts +1 -0
@@ -0,0 +1,110 @@
1
+ import { resolve } from 'node:path';
2
+ import type { AuthProfile } from './auth.js';
3
+ import {
4
+ resolveLocalAgentWorkspacePath,
5
+ type LocalAgentWorkspaceSnapshot,
6
+ } from './agent-workspace-sync.js';
7
+ import {
8
+ capabilitySelectionRef,
9
+ capabilityWorkspacePath,
10
+ readCapabilityWorkspaceRegistry,
11
+ type CapabilityWorkspaceEntry,
12
+ } from './capability-workspace.js';
13
+ import { CommandOutputError } from './command-error.js';
14
+ import { readSkillName } from './skill-host.js';
15
+
16
+ export interface SkillNameCandidate {
17
+ name: string;
18
+ id?: string;
19
+ working_copy_path: string;
20
+ selection_ref?: string;
21
+ resource_id?: string;
22
+ workspace_item_id?: string;
23
+ }
24
+
25
+ export interface SkillNameConflict {
26
+ code: 'SKILL_NAME_CONFLICT';
27
+ name: string;
28
+ blocking: boolean;
29
+ candidates: SkillNameCandidate[];
30
+ active?: SkillNameCandidate;
31
+ unavailable?: SkillNameCandidate[];
32
+ hint: string;
33
+ }
34
+
35
+ export const skillNameKey = (name: string): string => name.toLowerCase();
36
+
37
+ export function skillNameCandidate(
38
+ workspaceDir: string,
39
+ profile: Pick<AuthProfile, 'apiKey'>,
40
+ entry: CapabilityWorkspaceEntry,
41
+ ): SkillNameCandidate {
42
+ const path = capabilityWorkspacePath(workspaceDir, profile, entry);
43
+ return {
44
+ name: readSkillName(path) ?? entry.runtimeId,
45
+ id: entry.runtimeId,
46
+ working_copy_path: path,
47
+ selection_ref: capabilitySelectionRef(entry),
48
+ ...(entry.hub ? { resource_id: entry.hub.resourceId, workspace_item_id: entry.hub.workspaceItemId } : {}),
49
+ };
50
+ }
51
+
52
+ export function sameSkill(left: SkillNameCandidate, right: SkillNameCandidate): boolean {
53
+ // Missing Hub IDs are not an identity. Two local resources must remain distinct.
54
+ if (left.resource_id || right.resource_id) {
55
+ return !!left.resource_id && left.resource_id === right.resource_id;
56
+ }
57
+ return resolve(left.working_copy_path) === resolve(right.working_copy_path);
58
+ }
59
+
60
+ export function skillNameConflicts(candidates: readonly SkillNameCandidate[]): SkillNameConflict[] {
61
+ const groups = new Map<string, SkillNameCandidate[]>();
62
+ for (const candidate of candidates) {
63
+ const name = skillNameKey(candidate.name);
64
+ const group = groups.get(name) ?? [];
65
+ const previous = group.findIndex(other => sameSkill(other, candidate));
66
+ if (previous < 0) group.push(candidate);
67
+ else if (candidate.selection_ref) group[previous] = candidate;
68
+ groups.set(name, group);
69
+ }
70
+ return [...groups].filter(([, group]) => group.length > 1).map(([name, group]) => ({
71
+ code: 'SKILL_NAME_CONFLICT', name, blocking: true, candidates: group,
72
+ hint: 'Only one Skill with this name may be equipped. Choose which resource to keep and unequip the others using their selection_ref (or in Hub), then run ccl load. No Skill is renamed or replaced automatically.',
73
+ }));
74
+ }
75
+
76
+ /** Also freeze old host names if someone edited SKILL.md before the next load. */
77
+ export function skillConflictNames(conflicts: readonly SkillNameConflict[]): Set<string> {
78
+ return new Set(conflicts.flatMap(conflict => [conflict.name,
79
+ ...conflict.candidates.flatMap(candidate => [candidate.name, ...(candidate.id ? [candidate.id] : [])]),
80
+ ]).map(skillNameKey));
81
+ }
82
+
83
+ /** A supplied Hub snapshot is authoritative; local-only choices remain independent. */
84
+ export function selectedSkillNameConflicts(
85
+ workspaceDir: string,
86
+ profile: Pick<AuthProfile, 'apiKey'>,
87
+ snapshot?: LocalAgentWorkspaceSnapshot,
88
+ ): SkillNameConflict[] {
89
+ const candidates: SkillNameCandidate[] = [];
90
+ const selectedIds = new Set(snapshot?.items.skill.map(item => item.resourceId));
91
+ for (const item of snapshot?.items.skill ?? []) {
92
+ if (!item.skillRootPath) continue;
93
+ const path = resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot!, item.skillRootPath);
94
+ const name = readSkillName(path);
95
+ if (name) candidates.push({ name, working_copy_path: path,
96
+ resource_id: item.resourceId, workspace_item_id: item.workspaceItemId });
97
+ }
98
+ for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
99
+ if (entry.type !== 'skill' || entry.selection !== 'equipped' || entry.hub?.cloudStatus) continue;
100
+ if (snapshot && entry.hub && !selectedIds.has(entry.hub.resourceId)) continue;
101
+ candidates.push(skillNameCandidate(workspaceDir, profile, entry));
102
+ }
103
+ return skillNameConflicts(candidates);
104
+ }
105
+
106
+ export function throwSkillNameConflict(conflict: SkillNameConflict): never {
107
+ throw new CommandOutputError(`SKILL_NAME_CONFLICT:${conflict.name}`, {
108
+ error: 'skill_name_conflict', ...conflict, retryable: false,
109
+ });
110
+ }
@@ -469,7 +469,13 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
469
469
  case 'emergency_interrupted':
470
470
  return `你在处理${firstString(event, ['task_name'])}时死亡,紧急任务仍未解除。`;
471
471
  case 'ability.ready':
472
+ if (event.ability_id === 'sabotage') return `蟹阵营共享破坏能力已恢复就绪。${event.phase === 'meeting' ? '当前会议中,结束后可执行。' : ''}`;
472
473
  return `能力“${firstString(event, ['ability_name', 'ability_id'])}”现在可以使用。`;
474
+ case 'ability.unavailable':
475
+ if (event.ability_id === 'sabotage') return event.status === 'emergency_active'
476
+ ? '蟹阵营共享破坏能力暂不可用:紧急任务正在进行。'
477
+ : `蟹阵营共享破坏能力进入冷却${typeof event.cooldown_remaining_secs === 'number' ? `,剩余${event.cooldown_remaining_secs}秒` : ''}。`;
478
+ return `能力“${firstString(event, ['ability_name', 'ability_id'])}”暂不可用。`;
473
479
  case 'ability.remaining_uses_changed':
474
480
  return `能力“${firstString(event, ['ability_name', 'ability_id'])}”剩余${text(event.remaining_uses, '?')}次。`;
475
481
  case 'ability.exhausted':
@@ -10,6 +10,7 @@ export const CLAWCLAW_MONITOR_EVENT_PRIORITY: Readonly<Record<string, number>> =
10
10
  task_interrupted: 95,
11
11
  emergency_countdown_warning: 95,
12
12
  'ability.ready': 80,
13
+ 'ability.unavailable': 80,
13
14
  'ability.remaining_uses_changed': 80,
14
15
  'ability.exhausted': 90,
15
16
  'behavior.completed': 90,
@@ -0,0 +1,79 @@
1
+ import type { Runtime } from '../framework/runtime.js';
2
+ import type { OwnerControlResponse } from '../owner-control.js';
3
+ import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js';
4
+
5
+ type StartRuntime = Pick<Runtime, 'publicScope' | 'currentSegment' | 'readState'>;
6
+ type BehaviorStarter = Pick<ClawclawBehaviorPlugin, 'startLong' | 'startShort'>;
7
+
8
+ interface BehaviorStartRequest {
9
+ expectedScope: Readonly<{ sessionId: string; segmentId: string }>;
10
+ behavior: string;
11
+ layer: 'long' | 'short';
12
+ input: Readonly<Record<string, unknown>>;
13
+ maxRuntimeMs?: number;
14
+ }
15
+
16
+ function startRejection(runtime: StartRuntime, request: BehaviorStartRequest): OwnerControlResponse | undefined {
17
+ const actual = runtime.publicScope();
18
+ const expected = request.expectedScope;
19
+ if (actual.sessionId !== expected.sessionId || actual.segmentId !== expected.segmentId) {
20
+ return { ok: false, type: 'behavior_start', error: 'stale_runtime_scope' };
21
+ }
22
+ if (runtime.currentSegment().kind !== 'game') {
23
+ return { ok: false, type: 'behavior_start', error: 'no_active_game' };
24
+ }
25
+
26
+ // Admission reads accepted Source state, not the potentially older Ready view.
27
+ const { state, stateStatus } = runtime.readState();
28
+ const scope = stateStatus.scope;
29
+ const inScope = scope?.sessionId === expected.sessionId && scope.segmentId === expected.segmentId;
30
+ let code: string;
31
+ let message: string;
32
+ if (inScope && (state?.phase === 'game_over' || state?.phase === 'settling')) {
33
+ code = 'GAME_ENDED';
34
+ message = `The game has ended. Strategy '${request.behavior}' was not started.`;
35
+ } else if (inScope && state?.you?.is_alive === false) {
36
+ code = 'PLAYER_DEAD';
37
+ message = `The player is dead. Strategy '${request.behavior}' was not started.`;
38
+ } else if (!inScope || stateStatus.status !== 'fresh' || state?.you?.is_alive !== true) {
39
+ code = 'GAME_STATE_UNAVAILABLE';
40
+ message = `Current player state is unavailable. Strategy '${request.behavior}' was not started.`;
41
+ } else {
42
+ // A living player's strategy may still wait for a meeting or another layer.
43
+ return undefined;
44
+ }
45
+ return { ok: false, type: 'behavior_start', error: code, code, message };
46
+ }
47
+
48
+ /** Game-specific admission for explicit strategy starts; GAR owns activation mechanics. */
49
+ export async function startOwnerBehavior(
50
+ runtime: StartRuntime,
51
+ behavior: BehaviorStarter,
52
+ request: BehaviorStartRequest,
53
+ ): Promise<OwnerControlResponse> {
54
+ let rejection: OwnerControlResponse | undefined;
55
+ const isCurrent = (): boolean => {
56
+ rejection = startRejection(runtime, request);
57
+ return rejection === undefined;
58
+ };
59
+ if (!isCurrent()) return rejection!;
60
+ try {
61
+ const options = {
62
+ source: 'agent' as const,
63
+ // The existing GAR guard runs in its control queue after async preparation,
64
+ // before an activation is created or an existing strategy is replaced.
65
+ isCurrent,
66
+ ...(request.maxRuntimeMs === undefined ? {} : { maxRuntimeMs: request.maxRuntimeMs }),
67
+ };
68
+ const activation = request.layer === 'long'
69
+ ? await behavior.startLong(request.behavior, request.input, options)
70
+ : await behavior.startShort(request.behavior, request.input, options);
71
+ return { ok: true, type: 'behavior_start', status: 'accepted', activation };
72
+ } catch (error) {
73
+ return rejection ?? {
74
+ ok: false,
75
+ type: 'behavior_start',
76
+ error: error instanceof Error ? error.message : String(error),
77
+ };
78
+ }
79
+ }
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  import type { AuthData, AuthProfile } from '../../lib/auth.js';
5
5
  import { getRuntimeAccountId, getWorkspaceDir } from '../../lib/init-command.js';
6
6
  import { getRuntimeDir, getUserDataAuthFile } from '../../lib/user-data.js';
7
+ import { isDesktopMode } from '../../lib/desktop-mode.js';
7
8
  import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from '../../lib/workspace-runtime-lock.js';
8
9
  import { readGameStartRuntime, sendOwnerControlRequestTo } from '../owner-control.js';
9
10
  import { inspectProcessIdentity, sameProcessIdentity, terminateVerifiedProcess,
@@ -58,6 +59,9 @@ function readOwnerRecord(path: string): OwnerRecord | null {
58
59
  && /^acct_[a-f0-9]{32}$/.test(value.runtime_account_id) ? value : null;
59
60
  } catch { return null; }
60
61
  }
62
+ export function readWorkspaceOwnerRecord(workspaceDir = getWorkspaceDir()): OwnerRecord | null {
63
+ return readOwnerRecord(workspaceOwnerRecordPath(workspaceDir));
64
+ }
61
65
  function validIdentity(value: ProcessIdentity | null): value is ProcessIdentity {
62
66
  return !!value && typeof value.birth === 'string' && value.birth.length > 0
63
67
  && typeof value.executable === 'string' && value.executable.length > 0
@@ -91,7 +95,7 @@ function claimOwner(
91
95
  try { auth = JSON.parse(readFileSync(getUserDataAuthFile(workspaceDir), 'utf8')) as AuthData; } catch (error) {
92
96
  if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
93
97
  }
94
- if (auth && auth.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
98
+ if ((auth || isDesktopMode()) && auth?.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
95
99
  throw new Error('The active ClawClaw account changed during startup. Retry with the current account.');
96
100
  }
97
101
  let released = false;
@@ -5,6 +5,7 @@ import { createClawclawProcessingCadence } from './runtime-cadence.js';
5
5
  import { readRuntimeCycleIntervalMs } from '../../lib/runtime-cadence-config.js';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { BehaviorReflexControl } from './behavior-reflex-control.js';
8
+ import { startOwnerBehavior } from './behavior-start-control.js';
8
9
  import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
9
10
  import { createStartingOwnerControl } from './starting-owner-control.js';
10
11
  export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js';
@@ -1224,27 +1225,13 @@ export async function runClawclawOwner(
1224
1225
  || maxRuntimeMs > 120_000
1225
1226
  ))
1226
1227
  ) return { ok: false, type: 'behavior_start', error: 'invalid_behavior_start_request' };
1227
- if (!ownerScopeIsCurrent(runtime!, expected)) {
1228
- return { ok: false, type: 'behavior_start', error: 'stale_runtime_scope' };
1229
- }
1230
- try {
1231
- const activation = layer === 'long'
1232
- ? await assembly.behavior.startLong(behavior, behaviorInput, {
1233
- source: 'agent',
1234
- ...(maxRuntimeMs === undefined ? {} : { maxRuntimeMs }),
1235
- })
1236
- : await assembly.behavior.startShort(behavior, behaviorInput, {
1237
- source: 'agent',
1238
- ...(maxRuntimeMs === undefined ? {} : { maxRuntimeMs }),
1239
- });
1240
- return { ok: true, type: 'behavior_start', status: 'accepted', activation };
1241
- } catch (error) {
1242
- return {
1243
- ok: false,
1244
- type: 'behavior_start',
1245
- error: error instanceof Error ? error.message : String(error),
1246
- };
1247
- }
1228
+ return startOwnerBehavior(runtime!, assembly.behavior, {
1229
+ expectedScope: expected,
1230
+ behavior,
1231
+ layer,
1232
+ input: behaviorInput,
1233
+ ...(maxRuntimeMs === undefined ? {} : { maxRuntimeMs }),
1234
+ });
1248
1235
  }
1249
1236
  if (request.type === 'behavior_status') {
1250
1237
  return { ok: true, type: 'behavior_status', status: reflexControl.view(typeof request.behavior === 'string' ? request.behavior : undefined) };
@@ -0,0 +1,53 @@
1
+ import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
2
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
3
+ import type { ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
4
+ import { isClawclawRuntimeState } from '../../runtime-state.js';
5
+
6
+ type SabotageStatus = 'ready' | 'cooldown_charged' | 'emergency_active';
7
+
8
+ /** Shared sabotage availability belongs to the game, not to a strategy instance. */
9
+ export class SabotageAvailabilityRule implements ClawclawDerivedEventRule {
10
+ readonly id = 'sabotage-availability';
11
+ readonly eventTypes = ['ability.ready', 'ability.unavailable'] as const;
12
+ private boundary?: string;
13
+ private status?: SabotageStatus;
14
+
15
+ reset(): void { this.boundary = undefined; this.status = undefined; }
16
+
17
+ inspect(frame: StoredStateFrame<Record<string, any>>): RuntimeEventProposal[] {
18
+ const runtime = frame.state;
19
+ if (isClawclawRuntimeState(runtime) && runtime.connection !== 'connected') {
20
+ this.reset();
21
+ return [];
22
+ }
23
+ const game = isClawclawRuntimeState(runtime)
24
+ ? runtime.game_snapshot.status === 'fresh' || runtime.game_snapshot.status === 'cached'
25
+ ? runtime.game_snapshot.state : undefined
26
+ : runtime;
27
+ if (!game) return [];
28
+ const boundary = JSON.stringify([frame.scope.sessionId, frame.scope.segmentId, frame.connectionId, game.game_id]);
29
+ if (this.boundary !== boundary) { this.boundary = boundary; this.status = undefined; }
30
+ const current = game.crab_sabotage?.status;
31
+ if (current !== 'ready' && current !== 'cooldown_charged' && current !== 'emergency_active') return [];
32
+ const previous = this.status;
33
+ this.status = current;
34
+ if (previous === undefined || (previous === 'ready') === (current === 'ready')) return [];
35
+ if (game.you?.is_alive !== true || game.phase === 'game_over') return [];
36
+ if (game.you?.faction !== 'crab' && game.you?.role !== 'crab_generic') return [];
37
+ const remaining = game.crab_sabotage.cooldown_remaining_secs;
38
+ return [{
39
+ type: current === 'ready' ? 'ability.ready' : 'ability.unavailable',
40
+ dedupeKey: `sabotage-availability:${frame.epochSeq ?? frame.frameSeq}:${current}`,
41
+ dedupeScope: 'segment',
42
+ occurredAt: new Date(frame.observedAtMs ?? frame.receivedAtMs).toISOString(),
43
+ payload: {
44
+ ability_id: 'sabotage', ability_name: '破坏', shared: true,
45
+ previous_status: previous, status: current,
46
+ ...(typeof game.tick === 'number' ? { tick: game.tick } : {}),
47
+ ...(typeof game.phase === 'string' ? { phase: game.phase } : {}),
48
+ ...(current === 'cooldown_charged' && typeof remaining === 'number' && Number.isFinite(remaining)
49
+ ? { cooldown_remaining_secs: Math.max(0, remaining) } : {}),
50
+ },
51
+ }];
52
+ }
53
+ }
@@ -10,6 +10,7 @@ import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perc
10
10
  import { clawclawComputationGameState } from '../../runtime-state.js';
11
11
  import { createCanonicalGameState } from '../../behavior-input.js';
12
12
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
+ import { SabotageAvailabilityRule } from './sabotage-availability-rule.js';
13
14
 
14
15
  export const BUILTIN_PERCEPTION_NAMES = {
15
16
  players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
@@ -98,7 +99,7 @@ export function createSystemPerceptions(behaviorEventTypes: readonly string[] =
98
99
  return [
99
100
  new SystemPerceptionPlugin('players', groups.players, [new PlayerChangesDerivedEventRule()]),
100
101
  new SystemPerceptionPlugin('tasks', groups.tasks),
101
- new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule()]),
102
+ new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule(), new SabotageAvailabilityRule()]),
102
103
  new SystemPerceptionPlugin('emergency', groups.emergency, [new EmergencyCountdownDerivedEventRule()]),
103
104
  new SystemPerceptionPlugin('flow', groups.flow, [new RoomReadyDerivedEventRule()]),
104
105
  new SystemPerceptionPlugin('meeting', groups.meeting),
@@ -189,6 +189,7 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
189
189
  'perception.behavior_unavailable',
190
190
  'emergency_countdown_warning',
191
191
  'ability.ready',
192
+ 'ability.unavailable',
192
193
  'ability.remaining_uses_changed',
193
194
  'ability.exhausted',
194
195
  ] as const;