troxy-cli 1.10.0 → 1.11.1

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/bin/troxy.js CHANGED
@@ -457,8 +457,21 @@ switch (command) {
457
457
  process.exit(1);
458
458
  }
459
459
 
460
+ // Refresh the hosted-agent instructions regardless of whether the package
461
+ // moved. For a cloud agent the package is beside the point: what goes stale
462
+ // is its picture of which checkpoints exist, and that lives on the server.
463
+ // This is a no-op on a machine with an MCP client, which gets a fresh tool
464
+ // list from the MCP handshake every session anyway.
465
+ const { refreshHostedInstructions } = await import('../src/init.js');
466
+ const refresh = async () => {
467
+ try {
468
+ return await refreshHostedInstructions((loadConfig() || {}).apiKey);
469
+ } catch { return false; }
470
+ };
471
+
460
472
  if (current === latest) {
461
- console.log(`already up to date (${current})\n`);
473
+ console.log(`already up to date (${current})`);
474
+ if (!await refresh()) console.log('');
462
475
  break;
463
476
  }
464
477
 
@@ -480,7 +493,8 @@ switch (command) {
480
493
  }
481
494
  // Also refresh the npx cache so MCP servers (e.g. OpenClaw) pick up the new version
482
495
  try { execSync(`npx --yes troxy-cli@${latest} --version`, { stdio: 'pipe' }); } catch { /* non-fatal */ }
483
- console.log(`✓\n\n Updated to ${latest}. Restart your terminal and any MCP clients to use the new version.\n`);
496
+ console.log(`✓\n\n Updated to ${latest}. Restart your terminal and any MCP clients to use the new version.`);
497
+ if (!await refresh()) console.log('');
484
498
  } catch (err) {
485
499
  const stderr = err.stderr?.toString() || err.message || '';
486
500
  if (stderr.includes('EACCES') || stderr.includes('permission')) {
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "troxy-cli",
3
- "version": "1.10.0",
4
- "description": "AI payment control protect your agent's payments with policies",
3
+ "version": "1.11.1",
4
+ "description": "Control layer for AI agents: check payments, emails, logins and destructive actions against your policies",
5
+ "homepage": "https://troxy.io",
6
+ "bugs": {
7
+ "email": "support@troxy.io"
8
+ },
5
9
  "type": "module",
6
10
  "bin": {
7
11
  "troxy": "bin/troxy.js"
package/src/api.js CHANGED
@@ -84,6 +84,11 @@ export const api = {
84
84
  // MCP status (agent API key — no login needed)
85
85
  mcpStatus: (apiKey) => request('GET', '/mcp/status', { apiKey }),
86
86
 
87
+ // Setup instructions for an agent with no MCP client to configure. Fetched
88
+ // rather than hardcoded so a new checkpoint reaches agents without an npm
89
+ // release — a cloud agent runs init once and never upgrades the package.
90
+ agentInstructions: (apiKey) => request('GET', '/agent/instructions', { apiKey }),
91
+
87
92
  // MCP pause / resume / rename via JWT (requires troxy login)
88
93
  pauseToken: (jwt, id) => request('POST', `/tokens/${id}/pause`, { jwt }),
89
94
  resumeToken: (jwt, id) => request('POST', `/tokens/${id}/resume`, { jwt }),
package/src/init.js CHANGED
@@ -12,7 +12,10 @@ import { evaluatePayment, api } from './api.js';
12
12
  // one immediately, so every real consumer — which holds the key via ENV, not config.json —
13
13
  // kept presenting the now-revoked key until the user manually re-ran init. Non-interactive
14
14
  // (no prompts), so it's safe to call from rotate-key with the existing agent name.
15
- export async function reprovisionKeyConsumers(key, agentName) {
15
+ // True when this machine has something that can host an MCP server. When it
16
+ // does not, we are almost certainly inside a hosted agent's own sandbox, and
17
+ // the setup it needs is instructions rather than config files.
18
+ export function detectMcpClients() {
16
19
  const platform = process.platform;
17
20
  const detected = MCP_CLIENTS.filter(c => {
18
21
  const p = c.path[platform] ?? c.path.linux;
@@ -25,11 +28,36 @@ export async function reprovisionKeyConsumers(key, agentName) {
25
28
  hasOpenClaw = true;
26
29
  } catch {}
27
30
 
28
- if (detected.length === 0 && !hasOpenClaw) {
29
- console.log('\n No MCP clients detected (Claude Desktop, Cursor, Windsurf, OpenClaw).');
30
- console.log(' Troxy MCP server config:\n');
31
- console.log(JSON.stringify(mcpEntry(key), null, 4));
32
- console.log('\n Add the above to your MCP client\'s config under "mcpServers".\n');
31
+ return { detected, hasOpenClaw, none: detected.length === 0 && !hasOpenClaw };
32
+ }
33
+
34
+ // `troxy update` on a hosted agent. The npm package is beside the point there:
35
+ // what goes stale is the agent's picture of which checkpoints exist, and that
36
+ // lives on the server. So this re-fetches and reprints even when the package
37
+ // itself is already current, which is the common case for an agent that runs
38
+ // npx and never installs anything.
39
+ export async function refreshHostedInstructions(key) {
40
+ if (!key || !detectMcpClients().none) return false;
41
+ await printHostedAgentSetup(key);
42
+ return true;
43
+ }
44
+
45
+ export async function reprovisionKeyConsumers(key, agentName) {
46
+ const platform = process.platform;
47
+ const { detected, hasOpenClaw, none } = detectMcpClients();
48
+
49
+ if (none) {
50
+ // No MCP client on this machine almost always means a hosted agent running
51
+ // init inside its own sandbox. This branch used to print the mcpServers
52
+ // JSON and say "add this to your MCP client's config" — advice such an
53
+ // agent cannot act on: it has no config file, and it cannot reconfigure the
54
+ // runtime it lives inside. A real Base44 agent hit exactly this, ended up
55
+ // registered and named in the dashboard but with zero tools, and fell back
56
+ // to hand-written curl against whichever endpoints it found in the docs.
57
+ //
58
+ // What it CAN do is read this output, because it just ran the command. So
59
+ // print the instructions instead. One command, no copy-paste, no docs.
60
+ await printHostedAgentSetup(key);
33
61
  } else {
34
62
  console.log('\n MCP clients found:');
35
63
  for (const client of detected) {
@@ -67,6 +95,77 @@ export async function reprovisionKeyConsumers(key, agentName) {
67
95
  }
68
96
  }
69
97
 
98
+ const AGENTS_START = '<!-- troxy:start -->';
99
+ const AGENTS_END = '<!-- troxy:end -->';
100
+
101
+ // The endpoint deliberately does not echo the caller's key back, so the live
102
+ // key is substituted here, on the machine that already has it. Split/join
103
+ // rather than a regex because a key is user-controlled input and would other-
104
+ // wise need escaping to avoid being read as a pattern.
105
+ export function buildHostedInstructions(data, key) {
106
+ const text = String((data && data.instructions) || '');
107
+ if (!text.trim()) throw new Error('empty instructions');
108
+ const placeholder = (data && data.key_placeholder) || 'YOUR_TROXY_KEY';
109
+ return text.split(placeholder).join(key);
110
+ }
111
+
112
+ // Print the setup an agent with no MCP client needs, and persist it where
113
+ // agent runtimes look. Two delivery paths on purpose, because neither is
114
+ // reliable alone: stdout reaches the agent right now but dies with the session,
115
+ // AGENTS.md survives but only matters on platforms that read it.
116
+ async function printHostedAgentSetup(key) {
117
+ console.log('\n No MCP client on this machine, so this looks like a hosted agent.');
118
+ console.log(' Nothing to install. The instructions below are the whole setup.\n');
119
+
120
+ let text;
121
+ try {
122
+ text = buildHostedInstructions(await api.agentInstructions(key), key);
123
+ } catch {
124
+ console.log(' Could not reach the Troxy API to fetch them.');
125
+ console.log(' Re-run this command once you are back online.\n');
126
+ return;
127
+ }
128
+
129
+ const rule = ' ' + '─'.repeat(66);
130
+ console.log(rule);
131
+ console.log(text.split('\n').map(l => ' ' + l).join('\n'));
132
+ console.log(rule);
133
+
134
+ try {
135
+ const written = writeAgentsFile(process.cwd(), text);
136
+ console.log(`\n Saved to ${written}`);
137
+ } catch (err) {
138
+ console.log(`\n Could not write AGENTS.md (${err.message})`);
139
+ }
140
+
141
+ console.log('\n If you are an AI agent reading this: save the block above to your');
142
+ console.log(' own persistent instructions or memory, so it survives a new session.');
143
+ console.log(' Then follow it before you pay, email, log in, or delete anything.\n');
144
+ }
145
+
146
+ // Idempotent, and never clobbers instructions the user wrote themselves: the
147
+ // Troxy section lives between markers, so re-running init (or rotate-key, which
148
+ // changes the key inside the block) replaces only that span.
149
+ export function writeAgentsFile(dir, text) {
150
+ const file = path.join(dir, 'AGENTS.md');
151
+ const block = `${AGENTS_START}\n${text}\n${AGENTS_END}`;
152
+ let existing = '';
153
+ try { existing = fs.readFileSync(file, 'utf8'); } catch {}
154
+
155
+ let next;
156
+ if (existing.includes(AGENTS_START) && existing.includes(AGENTS_END)) {
157
+ const head = existing.slice(0, existing.indexOf(AGENTS_START));
158
+ const tail = existing.slice(existing.indexOf(AGENTS_END) + AGENTS_END.length);
159
+ next = head + block + tail;
160
+ } else if (existing.trim()) {
161
+ next = existing.replace(/\s*$/, '') + '\n\n' + block + '\n';
162
+ } else {
163
+ next = block + '\n';
164
+ }
165
+ fs.writeFileSync(file, next);
166
+ return file;
167
+ }
168
+
70
169
  function prompt(question) {
71
170
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
72
171
  return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans.trim()); }));
@@ -0,0 +1,133 @@
1
+ import { describe, it, beforeEach, afterEach } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import { writeAgentsFile, buildHostedInstructions, refreshHostedInstructions, detectMcpClients } from '../init.js';
8
+
9
+ // `troxy init` on a hosted agent writes the Troxy setup into AGENTS.md, which
10
+ // on most agent platforms is a file the user also writes their own rules into.
11
+ // So the write has to be surgical: re-running init (or rotate-key, which
12
+ // changes the key inside the block) must replace only Troxy's section and leave
13
+ // everything else byte-for-byte intact.
14
+
15
+ let dir;
16
+ beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'troxy-agents-')); });
17
+ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
18
+
19
+ const read = () => fs.readFileSync(path.join(dir, 'AGENTS.md'), 'utf8');
20
+
21
+ describe('writeAgentsFile', () => {
22
+ it('creates the file when there is none', () => {
23
+ writeAgentsFile(dir, '## Troxy\nkey ONE');
24
+ assert.match(read(), /## Troxy\nkey ONE/);
25
+ });
26
+
27
+ it('wraps the block in markers so it can be found again', () => {
28
+ writeAgentsFile(dir, 'BLOCK');
29
+ const out = read();
30
+ assert.ok(out.includes('<!-- troxy:start -->'));
31
+ assert.ok(out.includes('<!-- troxy:end -->'));
32
+ });
33
+
34
+ it('appends to a file the user already wrote, without touching their content', () => {
35
+ const theirs = '# My agent rules\n\nAlways answer in English.\n';
36
+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), theirs);
37
+ writeAgentsFile(dir, 'BLOCK');
38
+ const out = read();
39
+ assert.ok(out.startsWith('# My agent rules'));
40
+ assert.ok(out.includes('Always answer in English.'));
41
+ assert.ok(out.includes('BLOCK'));
42
+ });
43
+
44
+ it('replaces its own block on a re-run instead of stacking duplicates', () => {
45
+ writeAgentsFile(dir, 'key ONE');
46
+ writeAgentsFile(dir, 'key TWO');
47
+ const out = read();
48
+ assert.equal(out.split('<!-- troxy:start -->').length - 1, 1);
49
+ assert.ok(out.includes('key TWO'));
50
+ assert.ok(!out.includes('key ONE'));
51
+ });
52
+
53
+ it('keeps the user content around the block when replacing', () => {
54
+ // The rotate-key case: a stale key must be swapped out without collateral.
55
+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), 'BEFORE\n');
56
+ writeAgentsFile(dir, 'key ONE');
57
+ fs.appendFileSync(path.join(dir, 'AGENTS.md'), '\nAFTER\n');
58
+ writeAgentsFile(dir, 'key TWO');
59
+ const out = read();
60
+ assert.ok(out.includes('BEFORE'));
61
+ assert.ok(out.includes('AFTER'));
62
+ assert.ok(out.includes('key TWO'));
63
+ assert.ok(!out.includes('key ONE'));
64
+ });
65
+
66
+ it('does not add a second block to a file that only has whitespace', () => {
67
+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), ' \n\n');
68
+ writeAgentsFile(dir, 'BLOCK');
69
+ assert.equal(read().split('<!-- troxy:start -->').length - 1, 1);
70
+ });
71
+
72
+ it('returns the path it wrote, so init can report it', () => {
73
+ const written = writeAgentsFile(dir, 'BLOCK');
74
+ assert.equal(written, path.join(dir, 'AGENTS.md'));
75
+ });
76
+ });
77
+
78
+ describe('buildHostedInstructions', () => {
79
+ const KEY = 'txy-live-key-123';
80
+
81
+ it('substitutes the live key for the placeholder', () => {
82
+ const out = buildHostedInstructions(
83
+ { instructions: 'Authorization: Bearer YOUR_TROXY_KEY', key_placeholder: 'YOUR_TROXY_KEY' }, KEY);
84
+ assert.equal(out, `Authorization: Bearer ${KEY}`);
85
+ assert.ok(!out.includes('YOUR_TROXY_KEY'));
86
+ });
87
+
88
+ it('substitutes every occurrence, not just the first', () => {
89
+ const out = buildHostedInstructions(
90
+ { instructions: 'X YOUR_TROXY_KEY Y YOUR_TROXY_KEY', key_placeholder: 'YOUR_TROXY_KEY' }, KEY);
91
+ assert.equal(out.split(KEY).length - 1, 2);
92
+ });
93
+
94
+ it('falls back to the known placeholder if the server omits it', () => {
95
+ const out = buildHostedInstructions({ instructions: 'Bearer YOUR_TROXY_KEY' }, KEY);
96
+ assert.ok(out.includes(KEY));
97
+ });
98
+
99
+ it('treats a key containing regex characters literally', () => {
100
+ // Keys are opaque server-generated strings, but a replace built on a regex
101
+ // would corrupt the output the day that stops being true.
102
+ const weird = 'txy-a$&b.*c';
103
+ const out = buildHostedInstructions(
104
+ { instructions: 'Bearer YOUR_TROXY_KEY', key_placeholder: 'YOUR_TROXY_KEY' }, weird);
105
+ assert.equal(out, `Bearer ${weird}`);
106
+ });
107
+
108
+ it('rejects an empty payload rather than printing a blank setup', () => {
109
+ // Better to fall through to the "could not reach the API" path than to hand
110
+ // an agent an empty block it will treat as complete.
111
+ assert.throws(() => buildHostedInstructions({ instructions: ' ' }, KEY));
112
+ assert.throws(() => buildHostedInstructions({}, KEY));
113
+ assert.throws(() => buildHostedInstructions(null, KEY));
114
+ });
115
+ });
116
+
117
+ describe('refreshHostedInstructions', () => {
118
+ it('does nothing without a saved key', async () => {
119
+ // `troxy update` runs on machines that never ran init. It must not reach
120
+ // for the network, or print a setup block, with no key to authenticate.
121
+ assert.equal(await refreshHostedInstructions(undefined), false);
122
+ assert.equal(await refreshHostedInstructions(''), false);
123
+ });
124
+
125
+ it('reports whether this machine can host an MCP server', () => {
126
+ // The signal that decides between "patch config files" and "print
127
+ // instructions". Shape only — the answer is environment-dependent.
128
+ const r = detectMcpClients();
129
+ assert.ok(Array.isArray(r.detected));
130
+ assert.equal(typeof r.hasOpenClaw, 'boolean');
131
+ assert.equal(r.none, r.detected.length === 0 && !r.hasOpenClaw);
132
+ });
133
+ });