-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
766 lines (650 loc) Β· 28.6 KB
/
cli.js
File metadata and controls
766 lines (650 loc) Β· 28.6 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
#!/usr/bin/env node
// ============================================================
// clinch-cli β Clinch Protocol Command Line Client
// Usage: clinch <command> [options]
// ============================================================
const { program } = require('commander');
const fs = require('fs');
const path = require('path');
const os = require('os');
const readline = require('readline');
const crypto = require('crypto');
const https = require('https');
const CONFIG_DIR = path.join(os.homedir(), '.clinch');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
const SESSIONS_FILE = path.join(CONFIG_DIR, 'sessions.json');
const DEALS_FILE = path.join(CONFIG_DIR, 'deals.json');
const SECRETS_FILE = path.join(CONFIG_DIR, 'secrets.json');
// ββ Cryptographic Key Vault Helpers (Blind Key Pass) βββββββββ
function getEncryptionKey() {
const salt = 'clinch-local-secret-salt-398457';
const machineId = os.hostname() + os.arch() + os.platform() + os.userInfo().username;
return crypto.pbkdf2Sync(machineId, salt, 10000, 32, 'sha256');
}
function encrypt(text) {
const key = getEncryptionKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
return JSON.stringify({ iv: iv.toString('hex'), data: encrypted, tag: authTag });
}
function decrypt(encJson) {
try {
const key = getEncryptionKey();
const { iv, data, tag } = JSON.parse(encJson);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'hex'));
decipher.setAuthTag(Buffer.from(tag, 'hex'));
let decrypted = decipher.update(data, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (e) {
return null;
}
}
function loadSecrets() {
if (!fs.existsSync(SECRETS_FILE)) return {};
try {
const encryptedRaw = JSON.parse(fs.readFileSync(SECRETS_FILE, 'utf8'));
const decrypted = {};
for (const [domain, payload] of Object.entries(encryptedRaw)) {
const decryptedValue = decrypt(payload.encValue);
if (decryptedValue) {
decrypted[domain] = { key: decryptedValue, name: payload.name };
}
}
return decrypted;
} catch {
return {};
}
}
function saveSecrets(secrets) {
const encryptedRaw = {};
for (const [domain, payload] of Object.entries(secrets)) {
encryptedRaw[domain] = {
name: payload.name,
encValue: encrypt(payload.key)
};
}
fs.writeFileSync(SECRETS_FILE, JSON.stringify(encryptedRaw, null, 2), { mode: 0o600 });
}
// ββ Config & Session Persistence Helpers ββββββββββββββββββββββ
function loadConfig() {
if (!fs.existsSync(CONFIG_FILE)) return null;
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
}
function saveConfig(config) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
}
function loadSessions() {
if (!fs.existsSync(SESSIONS_FILE)) return {};
return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8'));
}
function saveSessionState(sessionId, core) {
try {
const serialized = core.exportSessionState(sessionId);
const sessions = loadSessions();
sessions[sessionId] = {
updatedAt: new Date().toISOString(),
state: serialized
};
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 2));
} catch (e) {
// Ignore gracefully
}
}
function requireConfig() {
const cfg = loadConfig();
if (!cfg) {
console.error(c.red('Not initialized. Run: clinch init'));
process.exit(1);
}
return cfg;
}
function getClinchCore(cfg) {
let ClinchCoreModule;
try { ClinchCoreModule = require('clinch-core'); }
catch {
console.error(c.red('clinch-core not found. Ensure it is linked or installed.'));
process.exit(1);
}
const { ClinchCore } = ClinchCoreModule;
const core = new ClinchCore({ registryUrl: cfg.registryUrl });
const secrets = loadSecrets();
for (const [domain, s] of Object.entries(secrets)) {
core.registerSecret(domain, s.key, s.name);
}
core.on('log', msg => console.log(msg));
core.on('error', err => console.error(c.red('Error:'), err.message));
return core;
}
function prompt(question) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => {
rl.question(question, answer => { rl.close(); resolve(answer.trim()); });
});
}
// ββ AI Engine Orchestration (Ollama vs GGUF) ββββββββββββββββββ
async function ensureAIEngine(cfg) {
if (cfg.engine) return cfg;
console.log(c.bold("\nπ€ Local AI Engine Setup"));
console.log(c.dim("Agent Q requires a local AI to parse intents and auto-negotiate."));
const choice = await prompt("Which engine would you like to use?\n 1) Ollama (Recommended - Requires Ollama running locally)\n 2) Standalone GGUF (Downloads ~1.1GB model)\nπ (1/2): ");
if (choice === '1') {
cfg.engine = 'ollama';
const model = await prompt("π Enter Ollama model name (default: llama3): ");
cfg.ollamaModel = model || 'llama3';
} else {
cfg.engine = 'gguf';
const dl = await prompt("π Download default Qwen 1.5B model? (Y/n): ");
if (dl.toLowerCase() !== 'n') {
cfg.ggufUrl = "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf";
} else {
cfg.ggufUrl = await prompt("π Enter custom GGUF download URL: ");
}
}
saveConfig(cfg);
return cfg;
}
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
const request = (currentUrl) => {
https.get(currentUrl, (response) => {
if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
return request(response.headers.location);
}
if (response.statusCode !== 200) {
return reject(new Error(`Download failed: ${response.statusCode}`));
}
const total = parseInt(response.headers['content-length'], 10);
let downloaded = 0;
response.on('data', (chunk) => {
downloaded += chunk.length;
const msg = total ? `${((downloaded / total) * 100).toFixed(1)}%` : `${(downloaded / 1024 / 1024).toFixed(1)} MB`;
process.stdout.write(`\r${c.yellow('Downloading model...')} ${msg}`);
});
response.pipe(file);
file.on('finish', () => {
console.log(c.green("\nβ Download complete!"));
file.close(resolve);
});
}).on('error', (err) => {
fs.unlink(dest, () => reject(err));
});
};
request(url);
});
}
// Global cache to prevent reloading the 1.1GB model on every chat turn
let cachedLlamaModel = null;
let cachedLlamaContext = null;
async function promptAI(systemPrompt, userText, cfg) {
if (cfg.engine === 'ollama') {
try {
const res = await fetch('http://127.0.0.1:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: cfg.ollamaModel || 'llama3',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userText }
],
stream: false
})
});
if (!res.ok) throw new Error(`Ollama returned status ${res.status}`);
const data = await res.json();
return data.message.content;
} catch (e) {
console.error(c.red(`\n[!] Ollama request failed: ${e.message}`));
console.error(c.dim(`Please ensure Ollama is running (http://127.0.0.1:11434) and the model is pulled.`));
process.exit(1);
}
} else {
// GGUF Execution
const resolvedPath = path.resolve(cfg.modelPath || path.join(CONFIG_DIR, 'model.gguf'));
if (!fs.existsSync(resolvedPath)) {
console.log(c.yellow(`\nModel not found at ${resolvedPath}`));
await downloadFile(cfg.ggufUrl || "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf", resolvedPath);
}
let nodeLlama;
try { nodeLlama = await import('node-llama-cpp'); }
catch (e) {
console.error(c.red("\nError: 'node-llama-cpp' is required for GGUF execution."));
console.error("Run: npm install -g node-llama-cpp");
process.exit(1);
}
if (!cachedLlamaModel) {
const threads = Math.max(2, os.cpus().length - 1);
console.log(c.dim(`\n[Agent Q] Loading GGUF model into memory using ${threads} threads (this may take a few seconds)...`));
const llama = await nodeLlama.getLlama();
cachedLlamaModel = await llama.loadModel({ modelPath: resolvedPath });
cachedLlamaContext = await cachedLlamaModel.createContext({ contextSize: 2048, threads: threads });
console.log(c.dim(`[Agent Q] Model loaded. Analyzing...`));
}
const session = new nodeLlama.LlamaChatSession({
contextSequence: cachedLlamaContext.getSequence(),
systemPrompt: systemPrompt,
chatWrapper: new nodeLlama.ChatMLChatWrapper()
});
let responseText = "";
await session.prompt(userText, { maxTokens: 1500, onTextChunk: (chunk) => { responseText += chunk; } });
return responseText;
}
}
async function parseIntentWithLLM(userInput, cfg) {
const systemPrompt = `You are a structured data extractor for a smart network agent.
Analyze the user's input. They might want to purchase an item, schedule a P2P service, book something, or query a node.
If the user says a greeting (like "hi" or "hello") or their request is too vague to act on, output EXACTLY this JSON:
{"error": "Please specify what you want to do (e.g. 'Get me a laptop under $500', or 'Schedule a call with @algeru on ginger')."}
If they DO specify a clear intent (purchase, scheduling, booking, data retrieval), output EXACTLY this JSON schema:
{
"intent": "string (e.g. purchase, schedule, booking)",
"category": "string (e.g. electronics, scheduling, p2p_services, domain_names)",
"item": "string (the actual item, target, or service requested)",
"max_budget": number (integer representing max budget. If none mentioned, use 0)
}
Your response MUST be ONLY valid JSON. Do not include conversational text.`;
try {
const rawRes = await promptAI(systemPrompt, userInput, cfg);
const cleanJson = rawRes.replace(/```json|```/g, "").trim();
const parsed = JSON.parse(cleanJson);
// Allow the loop to catch errors and reprompt the user interactively
if (parsed.error) {
return { error: parsed.error };
}
if (!parsed.item) {
return { error: "I couldn't figure out the exact item or service you want. Please be specific!" };
}
return parsed;
} catch (e) {
return { error: "Failed to parse intent correctly. Please try formatting your request more simply." };
}
}
// ββ Color & Banner helpers ββββββββββββββββββββββββββββββββββββ
const c = {
green: s => `\x1b[32m${s}\x1b[0m`,
yellow: s => `\x1b[33m${s}\x1b[0m`,
red: s => `\x1b[31m${s}\x1b[0m`,
cyan: s => `\x1b[36m${s}\x1b[0m`,
bold: s => `\x1b[1m${s}\x1b[0m`,
dim: s => `\x1b[2m${s}\x1b[0m`,
};
function banner() {
console.log(c.cyan(c.bold(`
ββββββββββ βββββββ βββ ββββββββββ βββ
βββββββββββ ββββββββ ββββββββββββββ βββ
βββ βββ βββββββββ ββββββ ββββββββ
βββ βββ ββββββββββββββββ ββββββββ
ββββββββββββββββββββββ βββββββββββββββββ βββ
βββββββββββββββββββββ βββββ ββββββββββ βββ
`)));
console.log(c.dim(' Agent Negotiation Protocol β v0.1.0\n'));
}
// ============================================================
// COMMANDS
// ============================================================
program
.command('init')
.description('Initialize your Clinch buyer agent')
.option('--registry <url>', 'Custom registry URL')
.action(async (opts) => {
banner();
console.log(c.bold('Setting up your Clinch agent...\n'));
let config = loadConfig() || {};
if (config.pubKey) {
const overwrite = await prompt('Config already exists. Overwrite network identity? (y/N): ');
if (overwrite.toLowerCase() !== 'y') { console.log('Aborted.'); process.exit(0); }
}
config.registryUrl = opts.registry || 'https://everydaytok-agentq-core-logics.hf.space';
config.modelPath = path.join(CONFIG_DIR, 'model.gguf');
config = await ensureAIEngine(config);
console.log(c.yellow('\nConnecting to registry and completing PoW handshake...'));
const core = getClinchCore(config);
await core.initialize();
config.pubKey = core.identityPubKey;
config.token = core.jwtToken;
config.mode = 'ANP/A';
config.createdAt = new Date().toISOString();
saveConfig(config);
core.disconnect();
console.log('\n' + c.green('β Agent initialized successfully'));
console.log(c.dim(` Public key: ${config.pubKey.substring(0,16)}...`));
console.log('\n' + c.bold('π Next Steps:'));
console.log(` 1. Start a natural language negotiation: ${c.cyan('clinch negotiate')}`);
console.log(` 2. Search the network for sellers: ${c.cyan('clinch query "electronics"')}`);
console.log(` 3. Manage blind API key vaults: ${c.cyan('clinch key')}`);
process.exit(0);
});
program
.command('query')
.description('Search for seller agents on the network')
.argument('<category>', 'Category to search')
.option('--mode <mode>', 'Filter by protocol mode')
.action(async (category, opts) => {
const cfg = requireConfig();
const core = getClinchCore(cfg);
console.log(c.cyan(`\nSearching for ${c.bold(category)} sellers...\n`));
await core.initialize(cfg.token);
const results = await core.search(category, opts.mode);
core.disconnect();
const sellers = results.results || [];
if (!sellers.length) {
console.log(c.yellow('No sellers found for this category.'));
process.exit(0);
}
console.log(c.bold(`Found ${sellers.length} seller(s):\n`));
sellers.forEach((s, i) => {
const tier = s.verification_tier === 'verified' ? c.green('β Verified') : c.dim('Unverified');
console.log(` ${c.bold((i+1) + '.')} ${c.cyan(s.agent_id)} (${tier})`);
console.log(` ANP address: ${c.yellow('ANP/C.' + s.agent_id)}`);
console.log(` Modes: ${(s.supported_modes || []).join(', ')}`);
});
process.exit(0);
});
program
.command('negotiate')
.description('Start a negotiation with a seller agent')
.argument('[address]', 'ANP address β format: MODE.domain.anp (e.g. ANP/C.amazon.anp)')
.option('--budget <n>', 'Max budget (USD)')
.option('--item <name>', 'Specific item to negotiate')
.option('--category <name>', 'Market category (Triggers cascade negotiation across matching sellers)')
.option('--squeeze <n>', 'Number of sellers to sequentially squeeze', '3')
.option('--parallel <n>', 'Number of sellers to negotiate with simultaneously')
.option('--auto', 'Run CLI-driven LLM auto-negotiation')
.action(async (address, opts) => {
let cfg = requireConfig();
let targetAddress = address;
let budget = opts.budget;
let constraints = {};
// ββ WIZARD MODE ββ
if (!targetAddress && !opts.category && !budget) {
banner();
console.log(c.bold("π¬ Clinch Onboarding Wizard β Tell me what you're looking for.\n"));
cfg = await ensureAIEngine(cfg);
let naturalIntent = await prompt("π Describe what you want to negotiate\n" +
c.dim(" (e.g., 'Get me the domain cartpost.shop under 80 dollars')\n\nπ¬: "));
// Conversational loop: keeps asking until a valid intent is parsed
while (true) {
if (!naturalIntent) process.exit(1);
const parsed = await parseIntentWithLLM(naturalIntent, cfg);
if (!parsed) {
naturalIntent = await prompt(c.yellow("\n[Agent Q] Something went wrong. Let's try again. What are you looking for?\nπ¬: "));
continue;
}
if (parsed.error) {
naturalIntent = await prompt(c.yellow(`\n[Agent Q] ${parsed.error}\nπ¬: `));
continue;
}
console.log(c.bold("\nπ Extracted Intention Context:"));
console.log(` - Intent: ${c.cyan(parsed.intent || 'purchase')}`);
console.log(` - Category: ${c.cyan(parsed.category)}`);
console.log(` - Target Item: ${c.cyan(parsed.item)}`);
console.log(` - Max Budget: ${c.green("$" + parsed.max_budget)}\n`);
const confirm = await prompt("π Is this correct? (Y/n): ");
if (confirm.toLowerCase() === 'n') {
naturalIntent = await prompt(c.yellow("\n[Agent Q] Got it. Let's try again. What are you looking for?\nπ¬: "));
continue;
}
constraints = parsed;
budget = parsed.max_budget;
break; // Exit loop on confirmation
}
console.log(c.dim(`\n[Network] Querying registry for category "${constraints.category}"...`));
const coreDiscovery = getClinchCore(cfg);
await coreDiscovery.initialize(cfg.token);
const results = await coreDiscovery.search(constraints.category);
coreDiscovery.disconnect();
const sellers = results.results || [];
if (sellers.length === 0) {
console.log(c.yellow(`\nNo sellers found for "${constraints.category}".`));
targetAddress = await prompt("π Enter address manually (e.g. ANP/C.amazon.anp): ");
} else {
console.log(c.bold(`\nAvailable sellers:`));
sellers.forEach((s, idx) => console.log(` ${idx + 1}. ${c.cyan(s.agent_id)}`));
const selection = await prompt(`\nπ Select a seller (1-${sellers.length}): `);
targetAddress = `ANP/C.${sellers[parseInt(selection) - 1].agent_id}`;
}
} else {
constraints = { intent: 'purchase', item: opts.item || 'Item', max_budget: parseFloat(budget || 100) };
if (opts.category) constraints.category = opts.category;
}
let runAuto = opts.auto;
if (runAuto === undefined) {
const autoInput = await prompt("\nπ Let Agent Q negotiate autonomously? (Y/n): ");
runAuto = autoInput.toLowerCase() !== 'n';
}
if (runAuto) {
cfg = await ensureAIEngine(cfg);
}
const core = getClinchCore(cfg);
// ββ CLI AUTO-NEGOTIATION HOOK ββ
if (runAuto) {
console.log(c.yellow(`\nπ€ Auto-mode initialized. Routing inference through: ${c.bold(cfg.engine)}`));
core.on('callback_received', async ({ sessionId, payload }) => {
const session = core.getSession(sessionId);
if (!session) return;
session.currentTurn++;
const incomingMessage = payload.message || JSON.stringify(payload);
const priceMatch = incomingMessage.match(/price\s*:\s*\$?(\d+(?:\.\d{2})?)/i);
if (priceMatch) session.lastKnownPrice = parseFloat(priceMatch[1]);
if (session.lastKnownPrice > 0 && session.lastKnownPrice <= session.constraints.max_budget) {
console.log(c.green(`\nπ [Agent Q] Target met constraints! Securing deal.`));
await core.sendCounter(sessionId, session.lastKnownPrice, "I accept this offer.");
return;
}
if (session.currentTurn > 6) {
console.log(c.red(`\nπ [Agent Q] Max turns reached. Exiting.`));
await core.exitSession(sessionId);
return;
}
const promptStr = core.buildAgentPrompt(sessionId, incomingMessage);
console.log(c.dim(`\n[Agent Q] Evaluating turn ${session.currentTurn}...`));
const aiResponse = await promptAI(promptStr, incomingMessage, cfg);
let price = null;
let msg = "Counter offer / Clarification requested";
try {
const clean = aiResponse.replace(/```json|```/g, "").trim();
const parsed = JSON.parse(clean);
if (parsed.price) price = parsed.price;
if (parsed.message) msg = parsed.message;
} catch(e) {
const fallback = aiResponse.match(/"price"\s*:\s*(\d+(?:\.\d{2})?)/i);
if (fallback) price = parseFloat(fallback[1]);
}
if (price) {
await core.sendCounter(sessionId, Math.min(price, session.constraints.max_budget), msg);
} else {
console.log(c.yellow(`[Agent Q] Sending safe fallback response.`));
await core.sendCounter(sessionId, session.lastKnownPrice * 0.9 || 0, "Can you provide more details?");
}
});
}
// ββ CASCADING ITERATIVE CASCADE TRIGGER ββ
if (!targetAddress && opts.category) {
let maxSellers = 3;
let strategy = 'sequential';
if (opts.parallel && !opts.squeeze) {
maxSellers = parseInt(opts.parallel);
strategy = 'parallel';
console.log(c.yellow(`π€ Parallel Mode: Handshaking concurrently with top ${maxSellers} nodes for "${opts.category}"...\n`));
} else {
maxSellers = parseInt(opts.squeeze || '3');
strategy = 'sequential';
console.log(c.yellow(`π€ Squeeze Mode: Sequentially communicating across top ${maxSellers} nodes for "${opts.category}"...\n`));
}
await core.initialize(cfg.token);
const bestDeal = await core.negotiateCascade(opts.category, constraints, maxSellers, strategy);
if (bestDeal) {
console.log(c.green(c.bold(`\nπ CASCADE COMPLETE: Secured optimal agreement with ${bestDeal.sellerId} at $${bestDeal.finalPrice}!`)));
} else {
console.log(c.red(`\nβ Cascade completed without any successful agreements.`));
}
process.exit(0);
}
// ββ STANDARD ONE-ON-ONE HANDSHAKE ββ
if (targetAddress && !targetAddress.startsWith('ANP/')) {
console.error(c.red(`\nβ Invalid Address: ${targetAddress}`));
console.error(" Address MUST include the protocol mode prefix.");
console.error(" Example: ANP/C.amazon.anp\n");
process.exit(1);
}
await core.initialize(cfg.token);
core.on('session_started', ({ sessionId }) => {
console.log(c.green(`\nβ Session started: ${c.bold(sessionId)}`));
saveSessionState(sessionId, core);
});
if (!runAuto) {
core.on('callback_received', ({ sessionId, payload }) => {
saveSessionState(sessionId, core);
console.log(c.cyan(`\n㪠Node says:`), payload);
console.log(c.dim(`\nType a price/response to counter, or "exit" / "accept":`));
});
}
core.on('session_closed', ({ sessionId, outcome, finalPrice }) => {
saveSessionState(sessionId, core);
if (outcome === 'deal') {
console.log(c.green(c.bold(`\nπ AGREEMENT SECURED at $${finalPrice}`)));
process.exit(0);
}
});
core.on('status_changed', status => {
if (status === 'STALEMATE') {
console.log(c.red('\nβ Stalemate. Exiting.'));
process.exit(0);
}
});
const sessionId = await core.negotiate(targetAddress, constraints);
if (!runAuto) {
console.log(c.bold('\nManual mode β await response, then type a counter-offer, or "exit" / "accept".\n'));
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', async (cmd) => {
if (cmd === 'exit') {
await core.exitSession(sessionId);
saveSessionState(sessionId, core);
process.exit(0);
}
else if (cmd === 'accept') { console.log(c.green(`Accepting...`)); }
else {
const price = parseFloat(cmd);
if (!isNaN(price)) {
await core.sendCounter(sessionId, price, 'Counter offer');
saveSessionState(sessionId, core);
} else {
// Allows sending non-numeric replies if needed
await core.sendCounter(sessionId, 0, cmd);
saveSessionState(sessionId, core);
}
}
});
}
});
program
.command('sessions')
.description('List saved negotiation sessions')
.action(() => {
const sessions = loadSessions();
const ids = Object.keys(sessions);
if (ids.length === 0) {
console.log(c.yellow('No saved sessions found.'));
process.exit(0);
}
console.log(c.bold(`Found ${ids.length} session(s):\n`));
ids.forEach(id => {
const s = JSON.parse(sessions[id].state);
console.log(` ${c.cyan(id)} - Target: ${s.sellerId} | Status: ${c.bold(s.status)} | Turn: ${s.currentTurn}`);
});
process.exit(0);
});
program
.command('resume')
.description('Resume a dropped or asynchronous negotiation session')
.argument('<sessionId>', 'The session ID to resume')
.option('--auto', 'Resume with auto-negotiation')
.action(async (sessionId, opts) => {
let cfg = requireConfig();
const sessions = loadSessions();
if (!sessions[sessionId]) {
console.error(c.red(`Session ${sessionId} not found in local store.`));
process.exit(1);
}
console.log(c.yellow(`\nRehydrating Session ${c.bold(sessionId)}...\n`));
if (opts.auto) {
cfg = await ensureAIEngine(cfg);
}
const core = getClinchCore(cfg);
await core.initialize(cfg.token);
core.importSessionState(sessions[sessionId].state);
core.on('callback_received', ({ id }) => saveSessionState(id, core));
core.on('session_closed', ({ outcome, finalPrice }) => {
saveSessionState(sessionId, core);
if (outcome === 'deal') console.log(c.green(c.bold(`\nπ AGREEMENT SECURED at $${finalPrice}`)));
process.exit(0);
});
console.log(c.green('β State rehydrated. Listening for webhooks/callbacks...\n'));
if (!opts.auto) {
console.log(c.dim('Awaiting remote updates. Press Ctrl+C to detach.'));
}
});
// ββ KEY VAULT COMMANDS (Blind Key Pass Management) βββββββββββ
program
.command('key')
.description('Manage third-party API credentials (Blind Key Pass vault)')
.option('--set', 'Interactively save a new API key credential')
.option('--list', 'List domains with registered local credentials')
.option('--remove <domain>', 'Delete a credential from your local vault')
.option('--show', 'Display the raw API keys when listing')
.action(async (opts) => {
const cfg = requireConfig();
const secrets = loadSecrets();
if (opts.remove) {
const domain = opts.remove.toLowerCase().trim();
if (secrets[domain]) {
delete secrets[domain];
saveSecrets(secrets);
console.log(c.green(`β Credential vault cleared for domain: ${domain}`));
} else {
console.log(c.yellow(`No credential found for domain: ${domain}`));
}
process.exit(0);
}
if (opts.list) {
const entries = Object.entries(secrets);
if (entries.length === 0) {
console.log(c.yellow('Your Blind Key Pass vault is empty.'));
process.exit(0);
}
console.log(c.bold('\nπ Registered Blind Key Credentials:\n'));
entries.forEach(([domain, s]) => {
if (opts.show) {
console.log(` - ${c.cyan(domain)} (${c.dim(s.name || 'unnamed')}) -> ${c.yellow(s.key)}`);
} else {
console.log(` - ${c.cyan(domain)} (${c.dim(s.name || 'unnamed')}) -> ${c.dim('β’β’β’β’β’β’β’β’β’β’β’β’')}`);
}
});
console.log(c.dim(opts.show ? '' : '\n(Run with --show to view raw keys)'));
process.exit(0);
}
// Default: Interactive configuration
console.log(c.bold('\nπ Register a local Blind Key Pass credential'));
console.log(c.dim(' Your credentials are AES-GCM encrypted and bound to this hardware locally.\n'));
const domain = await prompt('π Target Domain (e.g. apify.anp): ');
if (!domain) process.exit(0);
const normalizedDomain = domain.toLowerCase().trim();
const name = await prompt('π Key Label (e.g. Apify Production Token): ');
const value = await prompt('π Secret Value / API Key: ');
if (!value) process.exit(0);
secrets[normalizedDomain] = { key: value, name: name || 'Unnamed Key' };
saveSecrets(secrets);
console.log(c.green(`\nβ Key registered! Handshakes targeting ${normalizedDomain} will silently inject this token.`));
process.exit(0);
});
program
.name('clinch')
.description('Clinch Protocol β Agent Negotiation CLI')
.version('0.1.0');
program.parse();