-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.js
More file actions
477 lines (410 loc) Β· 22.3 KB
/
cli.js
File metadata and controls
477 lines (410 loc) Β· 22.3 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#!/usr/bin/env node
const { program } = require('commander');
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const readline = require('readline');
const notifier = require('node-notifier');
const express = require('express');
const nacl = require('tweetnacl');
const { ClinchCore, NegotiationState } = require('clinch-core');
const CONFIG_DIR = path.join(os.homedir(), '.clinch');
const VAULT_FILE = path.join(CONFIG_DIR, 'vault.enc');
const STATE_FILE = path.join(CONFIG_DIR, 'state.json');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
// ============================================================================
// SECURE VAULT
// ============================================================================
class SecureVault {
static _deriveKey(passphrase) {
return crypto.scryptSync(passphrase, 'clinch-protocol-salt-v1', 32, { N: 16384, r: 8, p: 1 });
}
static async getPassphrase(isDirect) {
if (process.env.CLINCH_PASSPHRASE) return process.env.CLINCH_PASSPHRASE;
if (isDirect) throw new Error("Running in --direct mode requires CLINCH_PASSPHRASE env var.");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => {
rl.question('\nπ Enter Clinch Vault Passphrase: ', ans => {
rl.close(); resolve(ans.trim());
});
});
}
static async unlock(isDirect = false) {
if (!fs.existsSync(VAULT_FILE)) return null;
const pass = await this.getPassphrase(isDirect);
const key = this._deriveKey(pass);
try {
const enc = JSON.parse(fs.readFileSync(VAULT_FILE, 'utf8'));
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(enc.iv, 'hex'));
decipher.setAuthTag(Buffer.from(enc.tag, 'hex'));
let dec = decipher.update(enc.data, 'hex', 'utf8');
dec += decipher.final('utf8');
const parsed = JSON.parse(dec);
if (!parsed.blindKeys) parsed.blindKeys = {};
return { parsed, pass };
} catch (e) {
console.error(isDirect ? JSON.stringify({ error: "Invalid passphrase" }) : "β Decryption failed.");
process.exit(1);
}
}
static async save(passphrase, keysData) {
const key = this._deriveKey(passphrase);
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let data = cipher.update(JSON.stringify(keysData), 'utf8', 'hex');
data += cipher.final('hex');
const tag = cipher.getAuthTag().toString('hex');
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(VAULT_FILE, JSON.stringify({ iv: iv.toString('hex'), data, tag: tag }), { mode: 0o600 });
}
}
// ============================================================================
// UTILS & SETUP
// ============================================================================
function loadConfig() {
return fs.existsSync(CONFIG_FILE) ? JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')) : { mode: 'buyer' };
}
function saveConfig(cfg) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2));
}
function getRawSessions() {
if (!fs.existsSync(STATE_FILE)) return {};
return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
}
function syncState(core, shouldWatch = false) {
let isWriting = false;
const load = () => {
if (!isWriting && fs.existsSync(STATE_FILE)) {
core.importSessions(getRawSessions());
}
};
load(); // Initial load
// π Watch only if explicitly told to (daemon mode), preventing short-lived CLI tools from hanging the event loop
if (shouldWatch) {
fs.watchFile(STATE_FILE, { interval: 1000 }, (curr, prev) => {
if (curr.mtimeMs !== prev.mtimeMs) {
load();
}
});
}
const save = () => {
isWriting = true;
fs.writeFileSync(STATE_FILE, JSON.stringify(core.exportSessions(), null, 2));
setTimeout(() => { isWriting = false; }, 1500);
};
core.on('counter_received', save);
core.on('approval_required', save);
core.on('deal_signed', save);
core.on('session_cancelled', save);
return save;
}
async function getInitializedCore(vaultData, isDirect) {
const cfg = loadConfig();
const core = new ClinchCore({
privateKeyHex: vaultData.privateKeyHex,
blindKeys: vaultData.blindKeys
});
if (!isDirect) console.log("β³ Connecting to Registry...");
await core.initialize(cfg.token);
if (core.jwtToken && core.jwtToken !== cfg.token) {
cfg.token = core.jwtToken;
saveConfig(cfg);
}
return core;
}
async function extractConstraints(intentText, isDirect) {
if (intentText.trim().startsWith('{')) return JSON.parse(intentText);
if (!isDirect) console.log("π§ Analyzing constraint intent...");
const prompt = `Output ONLY valid JSON matching exactly:\n{"intent": "purchase|schedule|service", "item": "string", "max_budget": number | null, "terms": {"key": "value"}}\nExtract from: "${intentText}"`;
try {
const res = await fetch('http://127.0.0.1:11434/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'llama3', prompt, stream: false, format: 'json' }) });
const data = await res.json();
return JSON.parse(data.response);
} catch(e) { return { intent: "purchase", item: intentText, max_budget: null, terms: {} }; }
}
// ============================================================================
// CLI COMMANDS
// ============================================================================
program.name('clinch').description('Clinch Protocol Command Line').version('0.2.1');
program.command('config').description('Set CLI configuration')
.option('--mode <mode>', 'buyer | seller | both')
.option('--webhook <url>', 'OpenClaw webhook URL')
.action((opts) => {
const cfg = loadConfig();
if (opts.mode) cfg.mode = opts.mode;
if (opts.webhook) cfg.openClawWebhook = opts.webhook;
saveConfig(cfg);
console.log(`β Config updated.`);
});
program.command('init').description('Initialize cryptographic identity')
.option('--key <hex>', 'Import an official private key')
.action(async (opts) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const pass = await new Promise(resolve => rl.question('Enter strong vault passphrase: ', ans => { rl.close(); resolve(ans); }));
let secretKeyHex;
if (opts.key) {
secretKeyHex = opts.key.trim();
console.log(`\nπ₯ Importing official dashboard private key...`);
} else {
const seed = crypto.randomBytes(32);
const keyPair = nacl.sign.keyPair.fromSeed(seed);
secretKeyHex = Buffer.from(keyPair.secretKey).toString('hex');
console.log(`\nπ‘ Note: Generated generic buyer identity.`);
}
await SecureVault.save(pass, { privateKeyHex: secretKeyHex, blindKeys: {} });
console.log(`π Identity configured and vault locked.`);
});
program.command('key').description('Manage third-party API credentials')
.option('--set <domain>', 'Set a new key for a domain')
.option('--value <key>', 'The actual secret key value')
.option('--list', 'List registered domains')
.option('--remove <domain>', 'Delete a credential')
.action(async (opts) => {
const vaultRes = await SecureVault.unlock(false);
if (!vaultRes) return console.log("Run 'clinch init' first.");
if (opts.list) {
console.log("\nπ Registered Blind Keys:");
Object.keys(vaultRes.parsed.blindKeys).forEach(d => console.log(` - ${d}`));
console.log("");
} else if (opts.remove) {
delete vaultRes.parsed.blindKeys[opts.remove];
await SecureVault.save(vaultRes.pass, vaultRes.parsed);
console.log(`β Removed blind key for ${opts.remove}`);
} else if (opts.set && opts.value) {
vaultRes.parsed.blindKeys[opts.set] = opts.value;
await SecureVault.save(vaultRes.pass, vaultRes.parsed);
console.log(`β Key registered!`);
} else {
console.log("Provide --list, or --set <domain> --value <key>");
}
});
program.command('start').description('Start the listener daemon')
.action(async () => {
const cfg = loadConfig();
const vaultRes = await SecureVault.unlock(false);
if (!vaultRes) return console.log("Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, false);
syncState(core, true); // <--- Watch enabled for background daemon
console.log("π’ Clinch Daemon active. Listening for events...");
core.on('approval_required', async (s) => {
const msg = `Approval Required: ${s.targetId} agreed to $${s.lastPrice} for ${s.constraints.item}`;
console.log(`\nβ οΈ ${msg}\n Run: clinch approve ${s.sessionId}`);
notifier.notify({ title: 'Clinch Protocol', message: msg });
if (cfg.openClawWebhook) {
await fetch(cfg.openClawWebhook, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event: 'approval_required', session: s })
}).catch(()=>{});
}
});
core.on('counter_received', async (s) => {
console.log(`\n㪠Counter from ${s.targetId}: $${s.lastPrice}`);
if (s.lastMessage) console.log(` [Message]: ${s.lastMessage}`);
if (cfg.openClawWebhook) {
await fetch(cfg.openClawWebhook, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event: 'counter_received', session: s })
}).catch(()=>{});
}
});
core.connectDaemonStream();
process.on('SIGINT', () => { console.log('\nπ Shutting down daemon...'); process.exit(0); });
process.on('SIGTERM', () => { console.log('\nπ Shutting down daemon...'); process.exit(0); });
});
program.command('discover <category>').description('Browse registered sellers')
.option('--direct', 'JSON output mode')
.action(async (category, opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const results = await core.discover(category);
if (opts.direct) return console.log(JSON.stringify(results));
if (!results.length) {
console.log(`\nπ No sellers found for "${category}".`);
return;
}
console.log(`\nπ Sellers for "${category}" (${results.length} found):\n`);
results.forEach((r, i) => {
const name = r.display_name || `${r.agent_id}`;
const official = r.official_node ? ' β Official' : '';
console.log(` [${i + 1}] ${name}${official}`);
console.log(` Domain ID : ${r.agent_id}`);
console.log(` Capabilities : ${(r.capabilities || []).join(', ')}`);
console.log('');
});
});
program.command('status').description('List active negotiations')
.option('--direct', 'JSON output mode')
.action((opts) => {
const data = getRawSessions();
const sessions = Object.values(data).filter(s => s.state !== 'SIGNED' && s.state !== 'CANCELLED');
if (opts.direct) return console.log(JSON.stringify(sessions));
console.log("\nπ Active Negotiations:");
if (!sessions.length) console.log(" None.");
sessions.forEach(s => console.log(` [${s.state}] ID: ${s.sessionId} | Target: ${s.targetId} | Last Price: $${s.lastPrice}`));
console.log("");
});
program.command('deals').description('List signed deals')
.option('--direct', 'JSON output mode')
.action((opts) => {
const data = getRawSessions();
const deals = Object.values(data).filter(s => s.state === 'SIGNED' && s.artifact !== null).map(s => s.artifact);
if (opts.direct) return console.log(JSON.stringify(deals));
console.log("\nπ Signed Deals:");
if (!deals.length) console.log(" None.");
deals.forEach(d => console.log(` ID: ${d.sessionId} | Item: ${d.item} | Price: $${d.price}`));
console.log("");
});
program.command('negotiate <intent>').description('Initialize a negotiation')
.option('--target <domain>', 'Target seller domain')
.option('--direct', 'JSON output mode')
.action(async (intent, opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const save = syncState(core, false); // <--- No watch for short-lived run
const constraints = await extractConstraints(intent, opts.direct);
let target = opts.target || (await core.discover(constraints.item))[0]?.agent_id;
if (!target) return console.log(opts.direct ? JSON.stringify({ error: "No sellers found" }) : "β No sellers found.");
const session = await core.proposeDeal(target, constraints);
save();
if (session.state === NegotiationState.CANCELLED) {
if (opts.direct) console.log(JSON.stringify({ status: "CANCELLED", session }));
else console.log(`\nβ Seller rejected the proposal.\nSession ID: ${session.sessionId}\n`);
} else {
if (opts.direct) console.log(JSON.stringify({ status: "SUCCESS", session }));
else console.log(`\nβ Proposal sent to ${target}.\nSession ID: ${session.sessionId}\n`);
}
});
program.command('counter <sessionId> <price>').description('Counter an offer')
.option('--reason <msg>', 'Reason for counter', 'Counter offer')
.option('--direct', 'JSON output mode')
.action(async (sessionId, price, opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const save = syncState(core, false); // <--- No watch for short-lived run
try {
const session = await core.counter(sessionId, parseFloat(price), opts.reason);
save();
if (session.state === NegotiationState.CANCELLED) {
if (opts.direct) console.log(JSON.stringify({ status: "CANCELLED", session }));
else console.log(`\nβ Seller cancelled the negotiation.\nSession ID: ${session.sessionId}\n`);
} else {
if (opts.direct) console.log(JSON.stringify({ status: "COUNTERED", session }));
else console.log(`β Counter of $${price} sent for ${sessionId}`);
}
} catch (e) { console.log(opts.direct ? JSON.stringify({ error: e.message }) : `β Error: ${e.message}`); }
});
program.command('cancel <sessionId>').description('Cleanly exit a negotiation')
.option('--direct', 'JSON output mode')
.action(async (sessionId, opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const save = syncState(core, false); // <--- No watch for short-lived run
try {
const session = await core.cancelSession(sessionId);
save();
if (opts.direct) console.log(JSON.stringify({ status: "CANCELLED", session }));
else console.log(`β Session ${sessionId} cleanly cancelled.`);
} catch (e) { console.log(opts.direct ? JSON.stringify({ error: e.message }) : `β Error: ${e.message}`); }
});
program.command('approve <sessionId>').description('Cryptographically sign a CONFIRMED deal')
.option('--direct', 'JSON output mode')
.action(async (sessionId, opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const save = syncState(core, false); // <--- No watch for short-lived run
try {
const artifact = await core.approveAndSign(sessionId);
save();
if (opts.direct) console.log(JSON.stringify({ status: "SIGNED", artifact }));
else console.log(`\nπ DEAL SIGNED AND COMMITTED!\nArtifact ID: ${artifact.sessionId}\n`);
} catch (e) { console.log(opts.direct ? JSON.stringify({ error: e.message }) : `\nβ Approval Failed: ${e.message}\n`); }
});
const nodeCmd = program.command('node').description('Node management commands');
nodeCmd.command('register <agentId> <endpoint>').description('Bind your dashboard .anp domain to your server endpoint')
.option('--categories <list>', 'Comma separated categories', 'general')
.option('--capabilities <list>', 'Comma separated capabilities', 'http-webhook')
.option('--modes <list>', 'Supported protocol modes', 'ANP/C')
.action(async (agentId, endpoint, opts) => {
const vaultRes = await SecureVault.unlock(false);
if (!vaultRes) return console.log("Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, false);
const categories = opts.categories ? opts.categories.split(',').map(c => c.trim()) : ['general'];
const capabilities = opts.capabilities ? opts.capabilities.split(',').map(c => c.trim()) : ['http-webhook'];
const modes = opts.modes ? opts.modes.split(',').map(m => m.trim()) : ['ANP/C'];
try {
await core.registerNode(agentId, endpoint, categories, capabilities, { supported_modes: modes });
console.log(`\nβ Endpoint successfully bound!`);
} catch (e) {
console.log(`\nβ Registration Failed: ${e.message}\n`);
}
});
program.command('serve').description('Start Seller HTTP server')
.option('--port <p>', 'Port to listen on', 8080)
.option('--config <file>', 'Path to seller config JSON')
.option('--direct', 'JSON output mode for background agent handling')
.action(async (opts) => {
const vaultRes = await SecureVault.unlock(opts.direct);
if (!vaultRes) return console.log(opts.direct ? JSON.stringify({ error: "Vault Locked" }) : "β Run 'clinch init' first.");
const core = await getInitializedCore(vaultRes.parsed, opts.direct);
const save = syncState(core, true); // <--- Server needs watching
const sellerCfg = opts.config && fs.existsSync(opts.config)
? JSON.parse(fs.readFileSync(opts.config))
: { defaultFloor: 45, defaultApprove: 100, maxTurns: 5 };
const app = express();
app.use(express.json());
app.post('/handshake', async (req, res) => {
const { session_id, constraints, buyer_pub_key } = req.body;
core.registerIncomingSession(session_id, buyer_pub_key, constraints);
const categoryCfg = sellerCfg;
if (constraints.max_budget !== null && constraints.max_budget >= categoryCfg.defaultApprove) {
core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, categoryCfg.defaultApprove, 1);
res.json({ type: 'CONFIRM', price: categoryCfg.defaultApprove });
} else {
const counter = Math.max(categoryCfg.defaultFloor, (categoryCfg.defaultFloor + categoryCfg.defaultApprove) / 2);
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, counter, 2);
res.json({ type: 'COUNTER', price: counter, turn: 2 });
}
save();
});
app.post('/counter', async (req, res) => {
const { session_id, price, turn } = req.body;
const categoryCfg = sellerCfg;
const currentTurn = turn || 2;
const nextTurn = currentTurn + 1;
const maxTurns = categoryCfg.maxTurns || 5;
if (price >= categoryCfg.defaultApprove) {
core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, price, currentTurn);
res.json({ type: 'CONFIRM', price });
} else if (currentTurn >= maxTurns) {
if (price >= categoryCfg.defaultFloor) {
core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, price, currentTurn);
res.json({ type: 'CONFIRM', price });
} else {
core.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, price, currentTurn);
res.json({ type: 'CANCEL', reason: "Max turns reached without meeting floor." });
}
} else {
const counter = Math.max(categoryCfg.defaultFloor, (categoryCfg.defaultFloor + categoryCfg.defaultApprove) / 2);
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, counter, nextTurn);
res.json({ type: 'COUNTER', price: counter, turn: nextTurn });
}
save();
});
app.post('/sign_request', (req, res) => {
try { res.json({ sellerSignature: core.signAsSeller(req.body.artifact) }); }
catch (e) { res.status(400).json({ error: e.message }); }
});
app.listen(opts.port, () => { if (!opts.direct) console.log(`\nπ Seller Node active on port ${opts.port}`); });
process.on('SIGINT', () => { console.log('\nπ Shutting down seller node...'); process.exit(0); });
process.on('SIGTERM', () => { console.log('\nπ Shutting down seller node...'); process.exit(0); });
});
program.parse();