-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathsetup.js
More file actions
365 lines (329 loc) · 13.7 KB
/
setup.js
File metadata and controls
365 lines (329 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env node
/**
* Setup script for OpenClaw Billing Proxy
*
* Auto-detects OpenClaw configuration, scans for sessions_* tools,
* and generates sanitization + reverse mapping rules.
*
* Usage: node setup.js
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
// Default counts for display (must match proxy.js)
const DEFAULT_REPLACEMENTS_COUNT = 30;
const DEFAULT_TOOL_RENAMES_COUNT = 28;
const homeDir = os.homedir();
console.log('\n OpenClaw Billing Proxy Setup');
console.log(' ---------------------------\n');
// Step 1: Check Claude Code auth
console.log('1. Checking Claude Code authentication...');
const credsPaths = [
path.join(homeDir, '.claude', '.credentials.json'),
path.join(homeDir, '.claude', 'credentials.json')
];
let credsPath = null;
let creds = null;
// Check file-based credentials
for (const p of credsPaths) {
if (fs.existsSync(p)) {
const stat = fs.statSync(p);
if (stat.size > 0) {
try {
const parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
if (parsed.claudeAiOauth && parsed.claudeAiOauth.accessToken) {
credsPath = p;
creds = parsed;
break;
}
} catch (e) { /* invalid JSON, skip */ }
}
}
}
// If no file-based credentials, try macOS Keychain
if (!creds && process.platform === 'darwin') {
console.log(' File credentials not found, checking macOS Keychain...');
const { execSync } = require('child_process');
// Try common Keychain service names
const keychainNames = ['Claude Code-credentials', 'claude-code', 'claude', 'com.anthropic.claude-code'];
let keychainToken = null;
for (const svc of keychainNames) {
try {
keychainToken = execSync('security find-generic-password -s "' + svc + '" -w 2>/dev/null', { encoding: 'utf8' }).trim();
if (keychainToken) {
console.log(' Found token in macOS Keychain (service: ' + svc + ')');
break;
}
} catch (e) { /* not found, try next */ }
}
if (keychainToken) {
// The Keychain might store the full JSON or just the token
try {
const parsed = JSON.parse(keychainToken);
if (parsed.claudeAiOauth && parsed.claudeAiOauth.accessToken) {
creds = parsed;
}
} catch (e) {
// Raw token string -- wrap in expected structure
if (keychainToken.startsWith('sk-ant-')) {
creds = {
claudeAiOauth: {
accessToken: keychainToken,
expiresAt: Date.now() + 86400000, // assume 24h -- will be refreshed
subscriptionType: 'unknown'
}
};
console.log(' Extracted raw token from Keychain');
}
}
if (creds) {
// Write credentials to file so the proxy can read them
credsPath = path.join(homeDir, '.claude', '.credentials.json');
const claudeDir = path.join(homeDir, '.claude');
if (!fs.existsSync(claudeDir)) { fs.mkdirSync(claudeDir, { recursive: true }); }
fs.writeFileSync(credsPath, JSON.stringify(creds));
console.log(' Written Keychain credentials to: ' + credsPath);
console.log(' NOTE: You may need to re-run this after token refresh (every ~24h)');
}
}
}
// If still no credentials, try forcing a credential write via claude CLI
if (!creds) {
console.log(' No credentials found. Attempting to trigger credential write...');
const { execSync } = require('child_process');
try {
execSync('claude -p "ping" --max-turns 1 --no-session-persistence --output-format json 2>/dev/null', {
timeout: 30000,
stdio: 'pipe'
});
// Re-check files after the CLI call
for (const p of credsPaths) {
if (fs.existsSync(p) && fs.statSync(p).size > 0) {
try {
const parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
if (parsed.claudeAiOauth && parsed.claudeAiOauth.accessToken) {
credsPath = p;
creds = parsed;
console.log(' Credential write triggered successfully: ' + p);
break;
}
} catch (e) { /* skip */ }
}
}
} catch (e) {
// CLI not available or failed
}
}
if (!creds) {
console.error(' CREDENTIALS NOT FOUND.');
console.error('');
console.error(' Claude Code CLI must be installed and authenticated:');
console.error('');
console.error(' npm install -g @anthropic-ai/claude-code');
console.error(' claude auth login');
console.error('');
console.error(' This opens a browser to sign in with your Claude Max/Pro account.');
console.error(' After authenticating, run this setup script again.');
console.error('');
console.error(' Searched for credentials at:');
for (const p of credsPaths) { console.error(' ' + p); }
if (process.platform === 'darwin') {
console.error(' macOS Keychain (Claude Code-credentials, claude-code, claude, com.anthropic.claude-code)');
}
console.error('');
console.error(' If claude auth status shows you are logged in but no file exists,');
console.error(' your Claude Code version stores tokens in the macOS Keychain.');
console.error(' Run: claude -p "test" --max-turns 1 --no-session-persistence');
console.error(' Then try this setup again.');
process.exit(1);
}
const expiresIn = ((creds.claudeAiOauth.expiresAt - Date.now()) / 3600000).toFixed(1);
console.log(' OK: ' + (creds.claudeAiOauth.subscriptionType || 'unknown') + ' subscription, token expires in ' + expiresIn + 'h');
// Step 2: Find OpenClaw config
console.log('\n2. Finding OpenClaw configuration...');
const oclawPaths = [
path.join(homeDir, '.openclaw', 'openclaw.json'),
'/etc/openclaw/openclaw.json'
];
let oclawPath = null;
for (const p of oclawPaths) {
if (fs.existsSync(p)) { oclawPath = p; break; }
}
// Build replacement and reverse map lists
const replacements = [
['OpenClaw', 'OCPlatform'],
['openclaw', 'ocplatform'],
['HEARTBEAT_OK', 'HB_ACK'],
['running inside', 'running on']
];
const reverseMap = [
['OCPlatform', 'OpenClaw'],
['ocplatform', 'openclaw'],
['HB_ACK', 'HEARTBEAT_OK']
];
// Step 3: Scan for sessions_* tools
console.log('\n3. Scanning for session management tools...');
if (oclawPath) {
console.log(' Found: ' + oclawPath);
const oclawConfig = JSON.parse(fs.readFileSync(oclawPath, 'utf8'));
const baseUrl = (oclawConfig.models && oclawConfig.models.providers &&
oclawConfig.models.providers.anthropic && oclawConfig.models.providers.anthropic.baseUrl) || 'unknown';
console.log(' Current baseUrl: ' + baseUrl);
// Scan OpenClaw source for DEFAULT_TOOL_ALLOW to find all sessions_* tools
const oclawDir = path.dirname(oclawPath);
const distDir = path.join(oclawDir, '..', 'node_modules', 'openclaw', 'dist');
const globalDist = '/usr/lib/node_modules/openclaw/dist';
const npmGlobalDist = path.join(homeDir, '.npm-global', 'lib', 'node_modules', 'openclaw', 'dist');
const distPaths = [distDir, globalDist, npmGlobalDist];
// Also check npm global on Windows
if (process.platform === 'win32') {
distPaths.push(path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'openclaw', 'dist'));
}
// Check NVM install paths
const nvmDir = path.join(homeDir, '.nvm', 'versions', 'node');
if (fs.existsSync(nvmDir)) {
try {
const versions = fs.readdirSync(nvmDir);
for (const v of versions) {
distPaths.push(path.join(nvmDir, v, 'lib', 'node_modules', 'openclaw', 'dist'));
}
} catch (e) { /* skip */ }
}
let sessionTools = [];
for (const dp of distPaths) {
if (!fs.existsSync(dp)) continue;
try {
const files = fs.readdirSync(dp).filter(function(f) { return f.endsWith('.js'); });
for (const f of files) {
const content = fs.readFileSync(path.join(dp, f), 'utf8');
const matches = content.match(/sessions_[a-z_]+/g);
if (matches) {
for (const m of matches) {
if (sessionTools.indexOf(m) === -1) sessionTools.push(m);
}
}
}
if (sessionTools.length > 0) {
console.log(' Found OpenClaw dist at: ' + dp);
break;
}
} catch (e) { /* skip */ }
}
if (sessionTools.length === 0) {
// Fallback: use known sessions_* tools
sessionTools = ['sessions_spawn', 'sessions_list', 'sessions_history', 'sessions_send', 'sessions_yield_interrupt', 'sessions_yield', 'sessions_store'];
console.log(' Using default sessions_* tool list (could not scan source)');
} else {
console.log(' Detected sessions_* tools: ' + sessionTools.join(', '));
}
// Generate replacement pairs for each sessions_* tool
const sessionReplacements = {
'sessions_spawn': 'create_task',
'sessions_list': 'list_tasks',
'sessions_history': 'get_history',
'sessions_send': 'send_to_task',
'sessions_yield_interrupt': 'task_yield_interrupt',
'sessions_yield': 'yield_task',
'sessions_store': 'task_store'
};
for (const tool of sessionTools) {
const replacement = sessionReplacements[tool] || tool.replace('sessions_', 'task_');
replacements.push([tool, replacement]);
reverseMap.push([replacement, tool]);
console.log(' ' + tool + ' -> ' + replacement);
}
// Detect assistant name from workspace files
const workspaceDir = (oclawConfig.agents && oclawConfig.agents.defaults &&
oclawConfig.agents.defaults.workspace) || null;
if (workspaceDir) {
const identityFiles = ['SOUL.md', 'USER.md', 'AGENTS.md'];
for (const f of identityFiles) {
const fPath = path.join(workspaceDir, f);
if (fs.existsSync(fPath)) {
const content = fs.readFileSync(fPath, 'utf8');
const nameMatch = content.match(/(?:name|assistant|bot)\s*[:=]\s*["']?(\w+)/i);
if (nameMatch && nameMatch[1].length > 2 && ['the', 'you', 'your', 'this'].indexOf(nameMatch[1].toLowerCase()) === -1) {
console.log('\n Detected assistant name: ' + nameMatch[1]);
console.log(' Note: Assistant names are usually NOT blocked by Anthropic.');
console.log(' If requests fail, try adding it to replacements as a test.');
break;
}
}
}
}
// Check for clawhub/clawd references in the OpenClaw source
for (const dp of distPaths) {
if (!fs.existsSync(dp)) continue;
try {
const indexFile = fs.readdirSync(dp).find(function(f) { return f.startsWith('index'); });
if (indexFile) {
const content = fs.readFileSync(path.join(dp, indexFile), 'utf8');
if (content.includes('clawhub')) {
replacements.push(['clawhub.com', 'skillhub.example.com']);
replacements.push(['clawhub', 'skillhub']);
reverseMap.push(['skillhub.example.com', 'clawhub.com']);
reverseMap.push(['skillhub', 'clawhub']);
console.log(' Added clawhub sanitization');
}
if (content.includes('clawd')) {
replacements.push(['clawd', 'agentd']);
reverseMap.push(['agentd', 'clawd']);
console.log(' Added clawd sanitization');
}
}
break;
} catch (e) { /* skip */ }
}
} else {
console.log(' OpenClaw config not found (using defaults)');
// Default sessions_* tools
const defaults = [
['sessions_spawn', 'create_task'],
['sessions_list', 'list_tasks'],
['sessions_history', 'get_history'],
['sessions_send', 'send_to_task'],
['sessions_yield', 'yield_task']
];
for (const [tool, repl] of defaults) {
replacements.push([tool, repl]);
reverseMap.push([repl, tool]);
}
}
// Step 4: Generate config
console.log('\n4. Generating configuration...');
// Only write port and credentialsPath to config.json.
// Pattern arrays (replacements, reverseMap, toolRenames, propRenames) are NOT
// written — they use the defaults from proxy.js which stay current across
// updates. Users can add custom patterns to config.json and they'll be MERGED
// with defaults automatically. (see issue #24)
const config = {
port: 18801,
credentialsPath: credsPath,
_comment: 'Pattern arrays use proxy.js defaults. Add custom entries to replacements/reverseMap/toolRenames and they will be merged with defaults automatically.'
};
const configPath = path.join(process.cwd(), 'config.json');
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
console.log(' Written: ' + configPath);
console.log(' Default sanitization: ' + DEFAULT_REPLACEMENTS_COUNT + ' string + ' + DEFAULT_TOOL_RENAMES_COUNT + ' tool renames (from proxy.js)');
console.log(' Custom patterns can be added to config.json and will be merged with defaults.');
// Step 5: Instructions
console.log('\n5. Setup complete!\n');
console.log(' Next steps:');
console.log(' -----------');
console.log(' a) Start the proxy: node proxy.js');
console.log(' b) Update OpenClaw: Set baseUrl to http://127.0.0.1:' + config.port + ' in openclaw.json');
console.log(' c) Restart gateway: Restart your OpenClaw gateway');
console.log(' d) Test: Send your assistant a message\n');
if (oclawPath) {
console.log(' To update baseUrl automatically:');
if (process.platform === 'win32') {
console.log(' powershell -c "(gc \'' + oclawPath + '\') -replace \'\\\"baseUrl\\\":\\s*\\\"[^\\\"]*\\\"\', \'\\\"baseUrl\\\": \\\"http://127.0.0.1:' + config.port + '\\\"\' | sc \'' + oclawPath + '\'"');
} else {
console.log(' sed -i \'s|"baseUrl": "[^"]*"|"baseUrl": "http://127.0.0.1:' + config.port + '"|\' \'' + oclawPath + '\'');
}
}
console.log('\n Troubleshooting:');
console.log(' - If requests fail with "extra usage" errors, check proxy console for 400 status codes');
console.log(' - Add any new sessions_* tools to both replacements and reverseMap in config.json');
console.log(' - If your assistant name is blocked (rare), add it to replacements and reverseMap');
console.log(' - Token refreshes when you open Claude Code CLI -- do this every 24h\n');