@myclaw163/clawclaw-cli 0.10.4 → 0.10.6
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/configuration.md +2 -0
- package/docs/user-guide/desktop-auth.md +45 -0
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +21 -6
- package/skills/clawclaw/references/COMMANDS.md +3 -3
- package/skills/clawclaw/references/GAME-MECHANICS.md +46 -59
- package/skills/clawclaw/references/TACTICS.md +413 -29
- package/src/cli.ts +2 -0
- package/src/commands/account.ts +12 -3
- package/src/commands/auth.ts +133 -0
- package/src/commands/behavior.ts +2 -1
- package/src/commands/capability.ts +2 -1
- package/src/commands/communication.ts +2 -1
- package/src/commands/data.ts +2 -1
- package/src/commands/events.ts +2 -1
- package/src/commands/memory.ts +2 -1
- package/src/commands/module-runtime-control.ts +2 -1
- package/src/commands/perception.ts +2 -1
- package/src/commands/persona.ts +2 -1
- package/src/lib/account-guidance.ts +5 -0
- package/src/lib/agent-workspace-skills.ts +3 -3
- package/src/lib/auth.ts +8 -1
- package/src/lib/desktop-auth.ts +40 -0
- package/src/lib/desktop-mode.ts +9 -0
- package/src/lib/game-client.ts +2 -1
- package/src/lib/hub-client.ts +2 -1
- package/src/lib/load-context.ts +2 -1
- package/src/lib/persona.ts +2 -1
- package/src/runtime/clawclaw/owner-lock.ts +5 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { AuthStore } from '../lib/auth.js';
|
|
3
|
+
import { GameClient } from '../lib/game-client.js';
|
|
4
|
+
import { isDesktopMode } from '../lib/desktop-mode.js';
|
|
5
|
+
import { stopDesktopRuntime } from '../lib/desktop-auth.js';
|
|
6
|
+
import { createProfileDirs, getWorkspaceDir } from '../lib/init-command.js';
|
|
7
|
+
import { switchActiveAccountSkillLinks } from '../lib/agent-workspace-skills.js';
|
|
8
|
+
import { ResponseClassifier } from '../short-command/classifier.js';
|
|
9
|
+
import { createProcessCommandIo } from '../short-command/process-io.js';
|
|
10
|
+
import { ShortCommandRunner, type CommandIo, type ShortCommandOperationResult } from '../short-command/runner.js';
|
|
11
|
+
import { extractBackendAccountId, extractServerAccountName, LOGIN_CONTRACT } from './account.js';
|
|
12
|
+
|
|
13
|
+
const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw';
|
|
14
|
+
|
|
15
|
+
async function readStdin(): Promise<string> {
|
|
16
|
+
if (process.stdin.isTTY) throw new Error('Pass the client credentials as JSON on stdin.');
|
|
17
|
+
const chunks: Buffer[] = [];
|
|
18
|
+
let bytes = 0;
|
|
19
|
+
for await (const chunk of process.stdin) {
|
|
20
|
+
const buffer = Buffer.from(chunk);
|
|
21
|
+
bytes += buffer.length;
|
|
22
|
+
if (bytes > 65_536) throw new Error('Auth input exceeds 64 KiB.');
|
|
23
|
+
chunks.push(buffer);
|
|
24
|
+
}
|
|
25
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function failure(code: string, message: string): ShortCommandOperationResult {
|
|
29
|
+
return { kind: 'local_failure', source: 'local', error: { code, message } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function status(store: AuthStore): ShortCommandOperationResult {
|
|
33
|
+
const profile = store.getActive();
|
|
34
|
+
return { kind: 'local_success', source: 'local', value: {
|
|
35
|
+
success: true,
|
|
36
|
+
data: {
|
|
37
|
+
mode: isDesktopMode() ? 'desktop' : 'standalone',
|
|
38
|
+
logged_in: profile !== null,
|
|
39
|
+
account: profile ? { id: profile.runtimeAccountId, name: profile.agentName } : null,
|
|
40
|
+
},
|
|
41
|
+
} };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createAuthCommand(options: {
|
|
45
|
+
io?: CommandIo;
|
|
46
|
+
readStdin?: () => Promise<string>;
|
|
47
|
+
stopRuntime?: () => Promise<void>;
|
|
48
|
+
switchSkillLinks?: typeof switchActiveAccountSkillLinks;
|
|
49
|
+
} = {}): Command {
|
|
50
|
+
const auth = new Command('auth').description('Client-managed game login');
|
|
51
|
+
const runner = new ShortCommandRunner();
|
|
52
|
+
const io = options.io ?? createProcessCommandIo();
|
|
53
|
+
|
|
54
|
+
auth.command('status').description('Show local login state without credentials')
|
|
55
|
+
.option('--json', 'Return JSON (the default)')
|
|
56
|
+
.action(async () => {
|
|
57
|
+
const secrets: string[] = [];
|
|
58
|
+
await runner.run({ descriptor: { command: 'ccl auth status',
|
|
59
|
+
sensitivePolicy: { sensitiveValues: secrets } }, io,
|
|
60
|
+
operation: () => {
|
|
61
|
+
const store = new AuthStore();
|
|
62
|
+
const profile = store.getActive();
|
|
63
|
+
if (profile) secrets.push(profile.apiKey);
|
|
64
|
+
return status(store);
|
|
65
|
+
} });
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
auth.command('bind').description('Bind the game account provided by Desktop')
|
|
69
|
+
.requiredOption('--stdin', 'Read {"clawkey":"...","serverUrl":"..."} JSON from stdin; serverUrl is optional')
|
|
70
|
+
.action(async () => {
|
|
71
|
+
const secrets: string[] = [];
|
|
72
|
+
await runner.run({ descriptor: { command: 'ccl auth bind',
|
|
73
|
+
sensitivePolicy: { sensitiveValues: secrets } }, io,
|
|
74
|
+
operation: async () => {
|
|
75
|
+
if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth bind requires CLAWCLAW_IS_DESKTOP=true.');
|
|
76
|
+
let input: unknown;
|
|
77
|
+
try { input = JSON.parse(await (options.readStdin ?? readStdin)()); }
|
|
78
|
+
catch { return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.'); }
|
|
79
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
80
|
+
return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.');
|
|
81
|
+
}
|
|
82
|
+
const value = input as Record<string, unknown>;
|
|
83
|
+
const apiKey = typeof value.clawkey === 'string' ? value.clawkey.trim() : '';
|
|
84
|
+
if (!apiKey) return failure('INVALID_AUTH_INPUT', 'clawkey must be a non-empty string.');
|
|
85
|
+
secrets.push(apiKey);
|
|
86
|
+
if (value.serverUrl !== undefined && typeof value.serverUrl !== 'string') {
|
|
87
|
+
return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL.');
|
|
88
|
+
}
|
|
89
|
+
const serverUrl = (value.serverUrl as string | undefined)?.trim()
|
|
90
|
+
|| process.env.CLAWCLAW_SERVER_URL?.trim() || DEFAULT_SERVER_URL;
|
|
91
|
+
try {
|
|
92
|
+
const url = new URL(serverUrl);
|
|
93
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error();
|
|
94
|
+
} catch { return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL without credentials, query or fragment.'); }
|
|
95
|
+
const client = new GameClient({ lobbyUrl: serverUrl, apiKey: '' });
|
|
96
|
+
const response = await client.requestRaw('POST', '/api/v1/agents/login', { api_key: apiKey });
|
|
97
|
+
const result = new ResponseClassifier().classify(response, LOGIN_CONTRACT);
|
|
98
|
+
if (result.kind !== 'success') return { kind: 'backend', response, contract: LOGIN_CONTRACT };
|
|
99
|
+
const agentName = extractServerAccountName(result.upstreamRoot);
|
|
100
|
+
if (typeof agentName !== 'string' || !agentName.trim()) {
|
|
101
|
+
return failure('INVALID_LOGIN_RESPONSE', 'Login response did not contain an account name.');
|
|
102
|
+
}
|
|
103
|
+
const store = new AuthStore();
|
|
104
|
+
const previous = store.getActive();
|
|
105
|
+
if (previous) secrets.push(previous.apiKey);
|
|
106
|
+
if (previous?.apiKey !== apiKey || previous.serverUrl !== serverUrl) {
|
|
107
|
+
await (options.stopRuntime ?? stopDesktopRuntime)();
|
|
108
|
+
}
|
|
109
|
+
const profile = { agentName, apiKey, serverUrl,
|
|
110
|
+
backendAccountId: extractBackendAccountId(result.upstreamRoot) };
|
|
111
|
+
(options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), previous, profile);
|
|
112
|
+
if (previous && previous.serverUrl !== serverUrl) store.updateGameServerUrl(undefined);
|
|
113
|
+
createProfileDirs(profile);
|
|
114
|
+
// The client provides one account. Do not keep fallback credentials.
|
|
115
|
+
store.addProfile(profile, { replaceExisting: true });
|
|
116
|
+
return status(store);
|
|
117
|
+
} });
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
auth.command('unbind').description('Stop the local runtime and clear login; keep account resources and memory')
|
|
121
|
+
.action(async () => {
|
|
122
|
+
await runner.run({ descriptor: { command: 'ccl auth unbind' }, io,
|
|
123
|
+
operation: async () => {
|
|
124
|
+
if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth unbind requires CLAWCLAW_IS_DESKTOP=true.');
|
|
125
|
+
const store = new AuthStore();
|
|
126
|
+
await (options.stopRuntime ?? stopDesktopRuntime)();
|
|
127
|
+
(options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), store.getActive(), null);
|
|
128
|
+
store.clear();
|
|
129
|
+
return status(store);
|
|
130
|
+
} });
|
|
131
|
+
});
|
|
132
|
+
return auth;
|
|
133
|
+
}
|
package/src/commands/behavior.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { runOwnerCommand } from './module-runtime-control.js';
|
|
2
3
|
import { Command, InvalidArgumentError, Option } from 'commander';
|
|
3
4
|
import { AuthStore, type AuthProfile } from '../lib/auth.js';
|
|
@@ -180,7 +181,7 @@ async function tryApplyRuntimeConfig(
|
|
|
180
181
|
|
|
181
182
|
function activeProfile(dependencies: BehaviorCommandDependencies): AuthProfile {
|
|
182
183
|
const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
|
|
183
|
-
if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
|
|
184
|
+
if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
|
|
184
185
|
return profile;
|
|
185
186
|
}
|
|
186
187
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { isPackageManagedSkill } from '../lib/package-skills.js';
|
|
2
3
|
import { Command, InvalidArgumentError } from 'commander';
|
|
3
4
|
import { AuthStore, type AuthProfile } from '../lib/auth.js';
|
|
@@ -133,7 +134,7 @@ function cloudSkillStage(archive: Buffer): { root: string; stage: string; digest
|
|
|
133
134
|
|
|
134
135
|
function activeProfile(): AuthProfile {
|
|
135
136
|
const profile = new AuthStore().getActive();
|
|
136
|
-
if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
|
|
137
|
+
if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
|
|
137
138
|
return profile;
|
|
138
139
|
}
|
|
139
140
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { Command } from 'commander';
|
|
2
3
|
import { extname, resolve } from 'path';
|
|
3
4
|
import { Action } from '../sdk/action.js';
|
|
@@ -189,7 +190,7 @@ async function submitCommunicationAction(
|
|
|
189
190
|
return {
|
|
190
191
|
kind: 'local_failure',
|
|
191
192
|
source: 'local',
|
|
192
|
-
error: { code: 'NO_ACTIVE_ACCOUNT', message: 'No active account. Run `ccl account register` or switch accounts first.' },
|
|
193
|
+
error: { code: 'NO_ACTIVE_ACCOUNT', message: accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.') },
|
|
193
194
|
};
|
|
194
195
|
}
|
|
195
196
|
|
package/src/commands/data.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { Command } from 'commander';
|
|
2
3
|
import { resolve } from 'path';
|
|
3
4
|
import { AuthStore, type AuthProfile } from '../lib/auth.js';
|
|
@@ -63,7 +64,7 @@ export function createDataCommand(dependencies: DataCommandDependencies = {}): C
|
|
|
63
64
|
throw new Error('Choose exactly one export scope: --game-id <id> or --all.');
|
|
64
65
|
}
|
|
65
66
|
const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
|
|
66
|
-
if (!profile) throw new Error('Not logged in. Run: ccl account register');
|
|
67
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in. Run: ccl account register'));
|
|
67
68
|
const now = (dependencies.now ?? (() => new Date()))();
|
|
68
69
|
const output = resolve(
|
|
69
70
|
(dependencies.cwd ?? (() => process.cwd()))(),
|
package/src/commands/events.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { existsSync } from 'node:fs';
|
|
3
4
|
import { Command } from 'commander';
|
|
@@ -335,7 +336,7 @@ export function formatVisualBoardEvent(event: CanonicalEvent): string {
|
|
|
335
336
|
|
|
336
337
|
async function runVisualBoard(): Promise<void> {
|
|
337
338
|
const profile = new AuthStore().getActive();
|
|
338
|
-
if (!profile) throw new Error('Not logged in. Run: ccl account register');
|
|
339
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in. Run: ccl account register'));
|
|
339
340
|
const opened = SqliteEventRepository.open(getProfileEventLedgerPath(profile));
|
|
340
341
|
if (!opened.ok) throw new Error('The local Event Ledger is unavailable.');
|
|
341
342
|
const repository = opened.repository;
|
package/src/commands/memory.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { existsSync, writeFileSync } from 'fs';
|
|
2
3
|
import { Command } from 'commander';
|
|
3
4
|
import { AuthStore } from '../lib/auth.js';
|
|
@@ -6,7 +7,7 @@ import { loadMemorySnapshot } from '../lib/load-context.js';
|
|
|
6
7
|
|
|
7
8
|
function getMemoryFile(): string {
|
|
8
9
|
const profile = new AuthStore().getActive();
|
|
9
|
-
if (!profile) throw new Error('Not logged in.');
|
|
10
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
|
|
10
11
|
return getProfileMemoryFile(profile);
|
|
11
12
|
}
|
|
12
13
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { AuthStore, type AuthProfile } from '../lib/auth.js';
|
|
2
3
|
import { InvalidArgumentError } from 'commander';
|
|
3
4
|
import { sendProfileOwnerControlRequest, type OwnerControlResponse, type OwnerControlType } from '../runtime/owner-control.js';
|
|
@@ -62,7 +63,7 @@ export async function runOwnerCommand(
|
|
|
62
63
|
source: 'local',
|
|
63
64
|
error: {
|
|
64
65
|
code: 'NO_ACTIVE_ACCOUNT',
|
|
65
|
-
message: 'No active account. Run `ccl account register` or switch accounts first.',
|
|
66
|
+
message: accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'),
|
|
66
67
|
},
|
|
67
68
|
};
|
|
68
69
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { BUILTIN_PERCEPTION_NAMES } from '../runtime/clawclaw/plugins/system-perception/system-perceptions.js';
|
|
2
3
|
import { BUILTIN_PERCEPTION_PREFIX } from '../runtime/clawclaw/notification-policy.js';
|
|
3
4
|
import { runOwnerCommand, parseModuleInput, type ModuleRuntimeCommandDependencies } from './module-runtime-control.js';
|
|
@@ -30,7 +31,7 @@ export interface PerceptionCommandDependencies extends ModuleRuntimeCommandDepen
|
|
|
30
31
|
|
|
31
32
|
function activeProfile(dependencies: PerceptionCommandDependencies): AuthProfile {
|
|
32
33
|
const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
|
|
33
|
-
if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
|
|
34
|
+
if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
|
|
34
35
|
return profile;
|
|
35
36
|
}
|
|
36
37
|
|
package/src/commands/persona.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from '../lib/desktop-mode.js';
|
|
1
2
|
import { Command } from 'commander';
|
|
2
3
|
import { existsSync } from 'node:fs';
|
|
3
4
|
import { AuthStore } from '../lib/auth.js';
|
|
@@ -24,7 +25,7 @@ import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-r
|
|
|
24
25
|
|
|
25
26
|
function context() {
|
|
26
27
|
const profile = new AuthStore().getActive();
|
|
27
|
-
if (!profile) throw new Error('Not logged in.');
|
|
28
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
|
|
28
29
|
const workspaceDir = getWorkspaceDir();
|
|
29
30
|
ensureAccountUserDataLayout(workspaceDir, profile);
|
|
30
31
|
return {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { DESKTOP_LOGIN_MESSAGE, isDesktopMode } from './desktop-mode.js';
|
|
2
|
+
|
|
1
3
|
export const OFFICIAL_URL = 'https://myclaw.163.com/';
|
|
2
4
|
export const REGISTER_COMMAND = 'ccl account register [--name <name>] [--invite-code <code>]';
|
|
3
5
|
export const REGISTRATION_CHECK_COMMAND = 'ccl account register --check';
|
|
@@ -69,6 +71,7 @@ export function missingInviteCodeMessage(): string {
|
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
export function noAccountMessage(action: NoAccountAction): string {
|
|
74
|
+
if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
|
|
72
75
|
const firstLine = action === 'gameStart'
|
|
73
76
|
? 'Cannot start matchmaking: no local ClawClaw account is configured.'
|
|
74
77
|
: action === 'accountInfo'
|
|
@@ -82,6 +85,7 @@ export function noAccountMessage(action: NoAccountAction): string {
|
|
|
82
85
|
}
|
|
83
86
|
|
|
84
87
|
export function invalidAccountMessage(): string {
|
|
88
|
+
if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
|
|
85
89
|
return [
|
|
86
90
|
'Account not found or API key expired.',
|
|
87
91
|
REGISTRATION_PROMPT,
|
|
@@ -90,6 +94,7 @@ export function invalidAccountMessage(): string {
|
|
|
90
94
|
}
|
|
91
95
|
|
|
92
96
|
export function malformedApiKeyMessage(): string {
|
|
97
|
+
if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
|
|
93
98
|
return [
|
|
94
99
|
'API key is missing or malformed.',
|
|
95
100
|
REGISTRATION_PROMPT,
|
|
@@ -255,10 +255,10 @@ function accountManagedSkillSources(
|
|
|
255
255
|
export function switchActiveAccountSkillLinks(
|
|
256
256
|
workspaceDir: string,
|
|
257
257
|
previousProfile: Pick<AuthProfile, 'apiKey'> | null,
|
|
258
|
-
nextProfile: Pick<AuthProfile, 'apiKey'
|
|
258
|
+
nextProfile: Pick<AuthProfile, 'apiKey'> | null,
|
|
259
259
|
dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
|
|
260
260
|
): AccountSkillLinkSwitchResult {
|
|
261
|
-
if (previousProfile?.apiKey === nextProfile
|
|
261
|
+
if (previousProfile?.apiKey === nextProfile?.apiKey) return { removed: [], linked: [] };
|
|
262
262
|
const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir);
|
|
263
263
|
if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
|
|
264
264
|
guard.release();
|
|
@@ -268,7 +268,7 @@ export function switchActiveAccountSkillLinks(
|
|
|
268
268
|
const previous = previousProfile
|
|
269
269
|
? accountManagedSkillSources(workspaceDir, previousProfile, true)
|
|
270
270
|
: new Map<string, string>();
|
|
271
|
-
const next = accountManagedSkillSources(workspaceDir, nextProfile);
|
|
271
|
+
const next = nextProfile ? accountManagedSkillSources(workspaceDir, nextProfile) : new Map<string, string>();
|
|
272
272
|
|
|
273
273
|
for (const [name, source] of next) {
|
|
274
274
|
if (!existsSync(source) || readSkillName(source) !== name) {
|
package/src/lib/auth.ts
CHANGED
|
@@ -149,10 +149,11 @@ export class AuthStore {
|
|
|
149
149
|
if (changed) writeRuntimeAuthState(this.runtimeAuthStateFile, current);
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
addProfile(profile: AuthProfile): string {
|
|
152
|
+
addProfile(profile: AuthProfile, options: { replaceExisting?: boolean } = {}): string {
|
|
153
153
|
const data = this.load();
|
|
154
154
|
const key = profileKeyFor(data, profile);
|
|
155
155
|
const existing = data.profiles[key];
|
|
156
|
+
if (options.replaceExisting) data.profiles = {};
|
|
156
157
|
data.profiles[key] = {
|
|
157
158
|
...profile,
|
|
158
159
|
runtimeAccountId: RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? '')
|
|
@@ -165,6 +166,12 @@ export class AuthStore {
|
|
|
165
166
|
return key;
|
|
166
167
|
}
|
|
167
168
|
|
|
169
|
+
/** Forget credentials and routing, without deleting account resources or memory. */
|
|
170
|
+
clear(): void {
|
|
171
|
+
this.save({ activeProfile: '', profiles: {} });
|
|
172
|
+
writeRuntimeAuthState(this.runtimeAuthStateFile, { profiles: {} });
|
|
173
|
+
}
|
|
174
|
+
|
|
168
175
|
removeProfile(name: string): void {
|
|
169
176
|
this.removeProfileByKey(name);
|
|
170
177
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { getWorkspaceDir } from './init-command.js';
|
|
4
|
+
import { getRuntimeDir } from './user-data.js';
|
|
5
|
+
import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js';
|
|
6
|
+
import { readWorkspaceOwnerRecord, workspaceOwnerIdentity } from '../runtime/clawclaw/owner-lock.js';
|
|
7
|
+
import { readGameStartRuntime, sendOwnerControlRequestTo } from '../runtime/owner-control.js';
|
|
8
|
+
|
|
9
|
+
/** Stop locally only: never leave the backend game or claim its control again. */
|
|
10
|
+
export async function stopDesktopRuntime(timeoutMs = 10_000): Promise<void> {
|
|
11
|
+
const workspace = getWorkspaceDir();
|
|
12
|
+
const deadline = Date.now() + timeoutMs;
|
|
13
|
+
let target: string | undefined;
|
|
14
|
+
let stopSent = false;
|
|
15
|
+
do {
|
|
16
|
+
const guard = tryAcquireWorkspaceRuntimeLock(workspace);
|
|
17
|
+
if (guard) {
|
|
18
|
+
guard.release();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const owner = readWorkspaceOwnerRecord(workspace);
|
|
22
|
+
if (owner) {
|
|
23
|
+
if (owner.workspace_id !== workspaceOwnerIdentity(workspace)
|
|
24
|
+
|| (target !== undefined && target !== owner.instance_id)) {
|
|
25
|
+
throw new Error('Runtime changed while logging out. Retry from the client.');
|
|
26
|
+
}
|
|
27
|
+
target = owner.instance_id;
|
|
28
|
+
if (!stopSent) {
|
|
29
|
+
const pointer = readGameStartRuntime(join(getRuntimeDir(workspace), 'accounts', owner.runtime_account_id));
|
|
30
|
+
if (pointer?.instance_id === target && pointer.owner_pid === owner.pid) {
|
|
31
|
+
const response = await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: target },
|
|
32
|
+
Math.max(1, Math.min(1_000, deadline - Date.now())));
|
|
33
|
+
stopSent = response?.ok === true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
await delay(50);
|
|
38
|
+
} while (Date.now() < deadline);
|
|
39
|
+
throw new Error('Runtime did not stop in time. Login binding was retained; retry from the client.');
|
|
40
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function isDesktopMode(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
2
|
+
return env.CLAWCLAW_IS_DESKTOP === 'true';
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export const DESKTOP_LOGIN_MESSAGE = '请在客户端登录游戏账号。CCL 的登录账号由客户端管理。';
|
|
6
|
+
|
|
7
|
+
export function accountRequiredMessage(standaloneMessage: string): string {
|
|
8
|
+
return isDesktopMode() ? DESKTOP_LOGIN_MESSAGE : standaloneMessage;
|
|
9
|
+
}
|
package/src/lib/game-client.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from './desktop-mode.js';
|
|
1
2
|
// src/lib/game-client.ts
|
|
2
3
|
import { WsConnectionState } from '../sdk/types.js';
|
|
3
4
|
import { AuthStore } from './auth.js';
|
|
@@ -142,7 +143,7 @@ export class GameClient {
|
|
|
142
143
|
const profile = store.getActive();
|
|
143
144
|
|
|
144
145
|
if (!profile) {
|
|
145
|
-
throw new Error('No active auth profile. Run: clawclaw-cli account register');
|
|
146
|
+
throw new Error(accountRequiredMessage('No active auth profile. Run: clawclaw-cli account register'));
|
|
146
147
|
}
|
|
147
148
|
|
|
148
149
|
return new GameClient({
|
package/src/lib/hub-client.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from './desktop-mode.js';
|
|
1
2
|
import { AuthStore } from './auth.js';
|
|
2
3
|
import { createHash } from 'node:crypto';
|
|
3
4
|
import { ServerRegistry } from './server-registry.js';
|
|
@@ -238,7 +239,7 @@ export class HubClient {
|
|
|
238
239
|
static fromAuth(opts?: { authStore?: AuthStore }): HubClient {
|
|
239
240
|
const store = opts?.authStore ?? new AuthStore();
|
|
240
241
|
const profile = store.getActive();
|
|
241
|
-
if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
|
|
242
|
+
if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
|
|
242
243
|
return HubClient.fromProfile(profile);
|
|
243
244
|
}
|
|
244
245
|
|
package/src/lib/load-context.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from './desktop-mode.js';
|
|
1
2
|
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
2
3
|
import { AuthStore } from './auth.js';
|
|
3
4
|
import { getProfileMemoryFile } from './init-command.js';
|
|
@@ -44,7 +45,7 @@ export function loadPersonaSnapshot(authStore = new AuthStore()): LoadedFileSnap
|
|
|
44
45
|
|
|
45
46
|
export function loadMemorySnapshot(authStore = new AuthStore()): LoadedFileSnapshot {
|
|
46
47
|
const profile = authStore.getActive();
|
|
47
|
-
if (!profile) throw new Error('Not logged in.');
|
|
48
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
|
|
48
49
|
const path = getProfileMemoryFile(profile);
|
|
49
50
|
ensureMemoryFile(path);
|
|
50
51
|
const exists = existsSync(path);
|
package/src/lib/persona.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { accountRequiredMessage } from './desktop-mode.js';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';
|
|
3
4
|
import { dirname, join, basename } from 'path';
|
|
@@ -155,7 +156,7 @@ function hubPersona(
|
|
|
155
156
|
|
|
156
157
|
export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedPersonaFile {
|
|
157
158
|
const profile = authStore.getActive();
|
|
158
|
-
if (!profile) throw new Error('Not logged in.');
|
|
159
|
+
if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
|
|
159
160
|
const workspaceDir = getWorkspaceDir();
|
|
160
161
|
ensureAccountUserDataLayout(workspaceDir, profile);
|
|
161
162
|
const snapshot = filterInactiveAgentWorkspaceSnapshot(
|
|
@@ -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
|
|
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;
|