agent-clinch 0.1.0

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.
@@ -0,0 +1,29 @@
1
+ name: Publish Clinch Core to NPM
2
+
3
+ on:
4
+ workflow_dispatch: # Allows you to trigger this manually from the GitHub UI
5
+
6
+ jobs:
7
+ build-and-publish:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - name: Checkout Source Code
11
+ uses: actions/checkout@v4
12
+
13
+ - name: Setup Node.js
14
+ uses: actions/setup-node@v4
15
+ with:
16
+ node-version: '20.x'
17
+ registry-url: 'https://registry.npmjs.org'
18
+
19
+ - name: Install Dependencies
20
+ # Ubuntu has all C++ compilers, so node-llama-cpp will install perfectly here
21
+ run: npm install
22
+
23
+ #- name: Build TypeScript
24
+ # run: npm run build
25
+
26
+ - name: Publish to NPM
27
+ run: npm publish
28
+ env:
29
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 publicstringapps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # Agent Clinch (`agent-clinch`)
2
+
3
+ > **Agent Negotiation Protocol β€” Terminal Client & Autonomous Agent Q**
4
+
5
+ The Clinch CLI is the official reference implementation of a Clinch Protocol buyer agent. It allows you to discover sellers, negotiate deals interactively, or dispatch an autonomous local AI agent ("Agent Q") to haggle on your behalfβ€”right from your terminal.
6
+
7
+ By keeping the execution edge-first, all cryptographic keys, session transcripts, downloaded models, and deal artifacts are stored strictly on your local machine.
8
+
9
+ ---
10
+
11
+ ## πŸ“¦ Installation
12
+
13
+ Install the CLI globally via NPM:
14
+
15
+ ```bash
16
+ npm install -g agent-clinch
17
+ ```
18
+
19
+ *Note: To use the conversational wizard or the `--auto` flag (which allows the local LLM to parse your intent and negotiate autonomously), you must have `node-llama-cpp` installed globally or in your environment:*
20
+ ```bash
21
+ npm install -g node-llama-cpp
22
+ ```
23
+
24
+ ---
25
+
26
+ ## πŸš€ Getting Started
27
+
28
+ ### 1. Initialize your Agent
29
+ Before you can negotiate, you need to generate your cryptographic identity and register with the network via Proof-of-Work (PoW).
30
+
31
+ ```bash
32
+ clinch init
33
+ ```
34
+ This command:
35
+ 1. Generates a permanent Ed25519 identity keypair.
36
+ 2. Solves the network PoW challenge (taking ~1-2 seconds of CPU).
37
+ 3. Retrieves a long-lived JWT access token.
38
+ 4. Saves your configuration to `~/.clinch/config.json`.
39
+
40
+ ### 2. The Conversational Wizard (Agent Q)
41
+ The easiest way to use Clinch is to simply type:
42
+
43
+ ```bash
44
+ clinch negotiate
45
+ ```
46
+
47
+ Instead of memorizing flags and seller domains, the CLI boots a local LLM to ask what you want in plain English.
48
+
49
+ ```text
50
+ πŸ’¬ Clinch Onboarding Wizard β€” Tell me what you're looking for.
51
+
52
+ πŸ‘‰ Describe what you want to negotiate
53
+ (e.g., 'Get me the domain cartpost.shop under 80 dollars, must have WHOIS privacy')
54
+
55
+ πŸ’¬: I need a high-speed blender under 100 dollars, make sure it has a warranty and fast shipping
56
+
57
+ [Agent Q] Booting local parser model to analyze your request...
58
+
59
+ πŸ“Š Extracted Intention Context:
60
+ - Category: kitchen_appliance
61
+ - Target Item: high-speed blender
62
+ - Max Budget: $100
63
+ - Must Haves: warranty, fast shipping
64
+ ```
65
+
66
+ Agent Q parses your natural language into a strict JSON `ConstraintVector`, queries the Clinch Registry to find matching sellers, and lets you select your target. It then seamlessly transitions into the negotiation phase.
67
+
68
+ ### 3. Explicit Negotiation (Manual or Auto Mode)
69
+ If you already know the seller's address and want to bypass the wizard, you can pass arguments directly:
70
+
71
+ **Manual Mode:** Open an interactive terminal where you manually input counter-offers.
72
+ ```bash
73
+ clinch negotiate ANP/A.amazon.anp --category "electronics" --item "Ninja Blender" --budget 85.00
74
+ ```
75
+ * Type a number (e.g., `45.50`) to send a counter-offer.
76
+ * Type `accept` to seal the deal.
77
+ * Type `exit` to terminate and issue a callback token to the seller.
78
+
79
+ **Auto Mode:** Add the `--auto` flag to hand control over to the local LLM Sandbox (Qwen 2.5 1.5B). The agent will evaluate the seller's offers and negotiate autonomously up to your strict max budget.
80
+ ```bash
81
+ clinch negotiate ANP/A.cloudflare.anp --category "domain" --item "my-startup.io" --budget 50.00 --auto
82
+ ```
83
+
84
+ ---
85
+
86
+ ## πŸ›  Command Reference
87
+
88
+ ### `clinch init [options]`
89
+ Initializes the agent and performs network registration.
90
+ * `--registry <url>`: Override the default dynamic router.
91
+ * `--model <path>`: Specify a custom path for the `.gguf` model file.
92
+
93
+ ### `clinch query <category> [options]`
94
+ Queries the registry for seller nodes.
95
+ * `--mode <mode>`: Filter by agent protocol mode (e.g., `ANP/A`, `ANP/C`).
96
+ * `--json`: Output raw JSON for scripting.
97
+
98
+ ### `clinch negotiate [address] [options]`
99
+ Opens a session with a target seller address. If `address` or `--budget` are omitted, launches the conversational wizard.
100
+ * `--budget <n>`: Your absolute maximum budget in USD.
101
+ * `--item <name>`: The specific item being negotiated.
102
+ * `--category <name>`: The market category.
103
+ * `--intent <intent>`: e.g., `purchase`, `lease`.
104
+ * `--auto`: Delegates turn-based negotiation to the local AI sandbox.
105
+
106
+ ### `clinch sessions [options]`
107
+ Lists historical and active negotiation sessions.
108
+ * `--last <n>`: Number of recent sessions to show (Default: 20).
109
+ * `--outcome <s>`: Filter by `ACTIVE`, `CONVERGED`, or `STALEMATE`.
110
+
111
+ ### `clinch deals [options]`
112
+ Lists successfully converged, cryptographically signed deal artifacts.
113
+ * `--verify <id>`: Fetches the deal artifact from the network and validates the cryptographic chain, Registry signature, and Seller signature.
114
+
115
+ ### `clinch callbacks [options]`
116
+ Connects to the WebSocket queue and listens for incoming, asynchronous counter-offers from sellers you previously `exit`ed on.
117
+ * `--pending`: Only show unread callbacks.
118
+
119
+ ### `clinch config [options]`
120
+ View or update your agent's local configuration variables.
121
+ * `--mode <mode>`: Update default handshake mode.
122
+ * `--registry <url>`: Point CLI to a new registry network.
123
+ * `--local-only <bool>`: Opt-out of anonymous session reporting.
124
+
125
+ ### `clinch status`
126
+ Pings the active Registry network to check health and latency.
127
+
128
+ ---
129
+
130
+ ## πŸ“‚ Local Storage & Privacy
131
+
132
+ The Clinch CLI operates on a strict zero-trust, edge-first model. Your data never leaves your machine unless explicitly sent as a constraint during a session.
133
+
134
+ All state is stored locally in your home directory (`~/.clinch/`):
135
+ * `config.json`: Your identity keys, JWT token, and preferences. **Do not share this file.**
136
+ * `sessions.json`: Local transcripts of your negotiations.
137
+ * `deals.json`: Your cryptographic deal artifacts.
package/cli.js ADDED
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ============================================================
4
+ // clinch-cli β€” Clinch Protocol Command Line Client
5
+ // Usage: clinch <command> [options]
6
+ // ============================================================
7
+ const { program } = require('commander');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const os = require('os');
11
+ const readline = require('readline');
12
+
13
+ const CONFIG_DIR = path.join(os.homedir(), '.clinch');
14
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
15
+ const SESSIONS_FILE = path.join(CONFIG_DIR, 'sessions.json');
16
+ const DEALS_FILE = path.join(CONFIG_DIR, 'deals.json');
17
+
18
+ // ── Config helpers ────────────────────────────────────────────
19
+ function loadConfig() {
20
+ if (!fs.existsSync(CONFIG_FILE)) return null;
21
+ return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
22
+ }
23
+
24
+ function saveConfig(config) {
25
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
26
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
27
+ }
28
+
29
+ function loadSessions() {
30
+ if (!fs.existsSync(SESSIONS_FILE)) return [];
31
+ return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8'));
32
+ }
33
+
34
+ function saveSessions(sessions) {
35
+ fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 2));
36
+ }
37
+
38
+ function requireConfig() {
39
+ const cfg = loadConfig();
40
+ if (!cfg) {
41
+ console.error('Not initialized. Run: clinch init');
42
+ process.exit(1);
43
+ }
44
+ return cfg;
45
+ }
46
+
47
+ function getClinchCore(cfg) {
48
+ let ClinchCoreModule;
49
+ try {
50
+ ClinchCoreModule = require('clinch-core');
51
+ } catch {
52
+ console.error('clinch-core not found. Ensure it is linked or installed.');
53
+ process.exit(1);
54
+ }
55
+ const { ClinchCore } = ClinchCoreModule;
56
+ const core = new ClinchCore({ registryUrl: cfg.registryUrl });
57
+
58
+ core.on('log', msg => console.log(msg));
59
+ core.on('error', err => console.error('Error:', err.message));
60
+ core.on('status_changed', s => process.stdout.write(`\r[${s}] \r`));
61
+
62
+ return core;
63
+ }
64
+
65
+ // ── Prompt helper ─────────────────────────────────────────────
66
+ function prompt(question) {
67
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
68
+ return new Promise(resolve => {
69
+ rl.question(question, answer => { rl.close(); resolve(answer.trim()); });
70
+ });
71
+ }
72
+
73
+ // ── Conversational AI Intent Parser (CLI Layer) ───────────────
74
+ async function parseIntentWithLLM(userInput, modelPath) {
75
+ console.log(c.dim("\n[Agent Q] Booting local parser model to analyze your request..."));
76
+
77
+ let nodeLlama;
78
+ try {
79
+ nodeLlama = await import('node-llama-cpp');
80
+ } catch (e) {
81
+ console.error(c.red("\nError: node-llama-cpp is required for conversational parsing."));
82
+ console.error("Please run: npm install -g node-llama-cpp\n");
83
+ process.exit(1);
84
+ }
85
+
86
+ const resolvedPath = path.resolve(modelPath);
87
+ if (!fs.existsSync(resolvedPath)) {
88
+ console.error(c.red(`\nError: Model not found at ${resolvedPath}`));
89
+ console.error("Please run 'clinch init' again or specify the model path.\n");
90
+ process.exit(1);
91
+ }
92
+
93
+ const llama = await nodeLlama.getLlama();
94
+ const model = await llama.loadModel({ modelPath: resolvedPath });
95
+ const context = await model.createContext({
96
+ contextSize: 2048,
97
+ threads: Math.max(1, os.cpus().length - 1)
98
+ });
99
+
100
+ const systemPrompt = `You are a structured data extractor. Convert the user's conversational intent into a strict JSON schema.
101
+ Your response MUST be ONLY valid JSON matching this schema exactly. Do not output conversational text.
102
+
103
+ JSON Schema:
104
+ {
105
+ "intent": "purchase",
106
+ "category": "string (e.g. domain_name, electronics, kitchen_appliance)",
107
+ "item": "string (the exact item, website, or product they want)",
108
+ "max_budget": number (extract budget numeric value),
109
+ "must_haves": ["array", "of", "strings", "representing", "conditions", "like", "WHOIS privacy", "warranty"]
110
+ }`;
111
+
112
+ const session = new nodeLlama.LlamaChatSession({
113
+ contextSequence: context.getSequence(),
114
+ systemPrompt: systemPrompt,
115
+ chatWrapper: new nodeLlama.ChatMLChatWrapper()
116
+ });
117
+
118
+ let responseText = "";
119
+ await session.prompt(userInput, {
120
+ maxTokens: 1500,
121
+ onTextChunk: (chunk) => { responseText += chunk; }
122
+ });
123
+
124
+ try {
125
+ const cleanJson = responseText.replace(/```json|```/g, "").trim();
126
+ return JSON.parse(cleanJson);
127
+ } catch (e) {
128
+ console.error(c.red("Failed to parse intent. Falling back to manual entry."));
129
+ return null;
130
+ }
131
+ }
132
+
133
+ // ── Color & Banner helpers ────────────────────────────────────
134
+ const c = {
135
+ green: s => `\x1b[32m${s}\x1b[0m`,
136
+ yellow: s => `\x1b[33m${s}\x1b[0m`,
137
+ red: s => `\x1b[31m${s}\x1b[0m`,
138
+ cyan: s => `\x1b[36m${s}\x1b[0m`,
139
+ bold: s => `\x1b[1m${s}\x1b[0m`,
140
+ dim: s => `\x1b[2m${s}\x1b[0m`,
141
+ };
142
+
143
+ function banner() {
144
+ console.log(c.cyan(c.bold(`
145
+ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—
146
+ β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘
147
+ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘
148
+ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘
149
+ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘
150
+ β•šβ•β•β•β•β•β•β•šβ•β•β•β•β•β•β•β•šβ•β•β•šβ•β• β•šβ•β•β•β• β•šβ•β•β•β•β•β•β•šβ•β• β•šβ•β•
151
+ `)));
152
+ console.log(c.dim(' Agent Negotiation Protocol β€” v0.1.0\n'));
153
+ }
154
+
155
+ // ============================================================
156
+ // COMMANDS
157
+ // ============================================================
158
+
159
+ program
160
+ .command('init')
161
+ .description('Initialize your Clinch buyer agent')
162
+ .option('--registry <url>', 'Custom registry URL')
163
+ .option('--model <path>', 'Path to custom GGUF model')
164
+ .action(async (opts) => {
165
+ banner();
166
+ console.log(c.bold('Setting up your Clinch agent...\n'));
167
+
168
+ const existing = loadConfig();
169
+ if (existing) {
170
+ const overwrite = await prompt('Config already exists. Overwrite? (y/N): ');
171
+ if (overwrite.toLowerCase() !== 'y') {
172
+ console.log('Aborted.'); return;
173
+ }
174
+ }
175
+
176
+ const registryUrl = opts.registry || 'https://everydaytok-agentq-core-logics.hf.space';
177
+ const modelPath = opts.model || path.join(CONFIG_DIR, 'model.gguf');
178
+
179
+ console.log(c.yellow('Connecting to registry and completing PoW handshake...'));
180
+
181
+ const core = getClinchCore({ registryUrl });
182
+ await core.initialize();
183
+
184
+ const config = {
185
+ registryUrl,
186
+ modelPath,
187
+ pubKey: core.identityPubKey,
188
+ token: core.jwtToken,
189
+ mode: 'ANP/A',
190
+ localOnly: false,
191
+ createdAt: new Date().toISOString()
192
+ };
193
+
194
+ saveConfig(config);
195
+ core.disconnect();
196
+
197
+ console.log('\n' + c.green('βœ“ Agent initialized successfully'));
198
+ console.log(c.dim(` Public key: ${config.pubKey.substring(0,16)}...`));
199
+ });
200
+
201
+ program
202
+ .command('query')
203
+ .description('Search for seller agents on the network')
204
+ .argument('<category>', 'Category to search')
205
+ .option('--mode <mode>', 'Filter by protocol mode')
206
+ .action(async (category, opts) => {
207
+ const cfg = requireConfig();
208
+ const core = getClinchCore(cfg);
209
+ console.log(c.cyan(`\nSearching for ${c.bold(category)} sellers...\n`));
210
+
211
+ await core.initialize(cfg.token);
212
+ const results = await core.search(category, opts.mode);
213
+ core.disconnect();
214
+
215
+ const sellers = results.results || [];
216
+ if (!sellers.length) return console.log(c.yellow('No sellers found for this category.'));
217
+
218
+ console.log(c.bold(`Found ${sellers.length} seller(s):\n`));
219
+ sellers.forEach((s, i) => {
220
+ const tier = s.verification_tier === 'verified' ? c.green('βœ“ Verified') : c.dim('Unverified');
221
+ console.log(` ${c.bold((i+1) + '.')} ${c.cyan(s.agent_id)} (${tier})`);
222
+ });
223
+ });
224
+
225
+ program
226
+ .command('negotiate')
227
+ .description('Start a negotiation with a seller agent')
228
+ .argument('[address]', 'Seller address (optional, triggers wizard if omitted)')
229
+ .option('--budget <n>', 'Max budget (USD)')
230
+ .option('--auto', 'Run sandbox auto-negotiation')
231
+ .action(async (address, opts) => {
232
+ const cfg = requireConfig();
233
+ let targetAddress = address;
234
+ let budget = opts.budget;
235
+ let constraints = {};
236
+
237
+ // ── WIZARD MODE: Leverage CLI-layer Agent Q ──
238
+ if (!targetAddress || !budget) {
239
+ banner();
240
+ console.log(c.bold("πŸ’¬ Clinch Onboarding Wizard β€” Tell me what you're looking for.\n"));
241
+
242
+ const naturalIntent = await prompt("πŸ‘‰ Describe what you want to negotiate\n" +
243
+ c.dim(" (e.g., 'Get me the domain cartpost.shop under 80 dollars, must have WHOIS privacy')\n\nπŸ’¬: "));
244
+
245
+ if (!naturalIntent) process.exit(1);
246
+
247
+ const parsed = await parseIntentWithLLM(naturalIntent, cfg.modelPath);
248
+
249
+ if (!parsed) {
250
+ console.error(c.red("βœ— Error parsing constraints. Please try manual entry."));
251
+ process.exit(1);
252
+ }
253
+
254
+ console.log(c.bold("\nπŸ“Š Extracted Intention Context:"));
255
+ console.log(` - Category: ${c.cyan(parsed.category)}`);
256
+ console.log(` - Target Item: ${c.cyan(parsed.item)}`);
257
+ console.log(` - Max Budget: ${c.green("$" + parsed.max_budget)}`);
258
+ console.log(` - Must Haves: ${c.yellow(parsed.must_haves.join(', ') || 'none')}\n`);
259
+
260
+ const confirm = await prompt("πŸ‘‰ Is this correct? (Y/n): ");
261
+ if (confirm.toLowerCase() === 'n') process.exit(0);
262
+
263
+ constraints = parsed;
264
+ budget = parsed.max_budget;
265
+
266
+ // ── Seller Discovery ──
267
+ console.log(c.dim(`\nQuerying registry to find compatible sellers for "${parsed.category}"...`));
268
+ const coreDiscovery = getClinchCore(cfg);
269
+ await coreDiscovery.initialize(cfg.token);
270
+ const results = await coreDiscovery.search(parsed.category);
271
+ coreDiscovery.disconnect();
272
+
273
+ const sellers = results.results || [];
274
+ if (sellers.length === 0) {
275
+ console.log(c.yellow(`\nNo certified sellers found on the network for category "${parsed.category}".`));
276
+ targetAddress = await prompt("πŸ‘‰ Please enter a seller address manually (e.g. amazon.anp): ");
277
+ } else {
278
+ console.log(c.bold(`\nAvailable certified sellers on the network:`));
279
+ sellers.forEach((s, idx) => console.log(` ${idx + 1}. ${c.cyan(s.agent_id)} (${s.display_name})`));
280
+ const selection = await prompt(`\nπŸ‘‰ Select a seller to target (1-${sellers.length}): `);
281
+ targetAddress = `ANP/A.${sellers[parseInt(selection) - 1].agent_id}`;
282
+ }
283
+ } else {
284
+ constraints = { intent: 'purchase', item: 'Item', max_budget: parseFloat(budget) };
285
+ }
286
+
287
+ // ── INITIATE CORE PROTOCOL NEGOTIATION ──
288
+ console.log(c.cyan(`\nStarting negotiation with ${c.bold(targetAddress)}...`));
289
+ const core = getClinchCore(cfg);
290
+
291
+ let runAuto = opts.auto;
292
+ if (runAuto === undefined) {
293
+ const autoInput = await prompt("\nπŸ‘‰ Let Agent Q negotiate autonomously? (Y/n): ");
294
+ runAuto = autoInput.toLowerCase() !== 'n';
295
+ }
296
+
297
+ if (runAuto) {
298
+ console.log(c.yellow('πŸ€– Auto-mode: Local LLM sandbox is taking the wheel...\n'));
299
+ await core.sandbox({ modelPath: cfg.modelPath });
300
+ } else {
301
+ await core.initialize(cfg.token);
302
+ }
303
+
304
+ core.on('session_started', ({ sessionId }) => {
305
+ console.log(c.green(`\nβœ“ Session started: ${c.bold(sessionId)}`));
306
+ });
307
+
308
+ core.on('status_changed', status => {
309
+ if (status === 'CONVERGED') console.log(c.green(`\nβœ“ DEAL REACHED at $${core.lastKnownPrice}`));
310
+ if (status === 'STALEMATE') console.log(c.red('\nβœ— No deal reached (stalemate)'));
311
+ });
312
+
313
+ const sessionId = await core.negotiate(targetAddress, constraints);
314
+
315
+ if (!runAuto) {
316
+ console.log(c.bold('\nManual mode β€” type a price to counter, or "exit" / "accept":\n'));
317
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
318
+ rl.on('line', async (cmd) => {
319
+ if (cmd === 'exit') { await core.exitSession(sessionId); process.exit(0); }
320
+ else if (cmd === 'accept') { console.log(c.green(`Accepting...`)); rl.close(); }
321
+ else {
322
+ const price = parseFloat(cmd);
323
+ if (!isNaN(price)) await core.sendCounter(sessionId, price, 'Counter offer');
324
+ }
325
+ });
326
+ }
327
+ });
328
+
329
+ program
330
+ .name('clinch')
331
+ .description('Clinch Protocol β€” Agent Negotiation CLI')
332
+ .version('0.1.0');
333
+
334
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+
3
+ "keywords": [],
4
+ "author": "",
5
+ "license": "ISC",
6
+
7
+
8
+ "name": "agent-clinch",
9
+ "version": "0.1.0",
10
+ "description": "Clinch Protocol CLI β€” agent negotiation from your terminal",
11
+ "main": "cli.js",
12
+ "bin": {
13
+ "clinch": "./cli.js"
14
+ },
15
+ "scripts": {
16
+ "start": "node cli.js"
17
+ },
18
+
19
+ "dependencies": {
20
+ "commander": "^14.0.3",
21
+ "node-llama-cpp": "^3.18.1",
22
+ "clinch-core": "0.1.0"
23
+ }
24
+ }