@nordsym/apiclaw 1.5.17 → 1.5.19

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.
Files changed (228) hide show
  1. package/convex/http.js.map +1 -1
  2. package/convex/http.ts +516 -0
  3. package/dist/analytics.d.ts +0 -4
  4. package/dist/analytics.d.ts.map +1 -1
  5. package/dist/analytics.js +0 -1
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/bin.js +1 -1
  8. package/dist/cli/commands/mcp-install.d.ts.map +1 -1
  9. package/dist/cli/commands/mcp-install.js +8 -87
  10. package/dist/cli/commands/mcp-install.js.map +1 -1
  11. package/dist/cli/index.js +0 -7
  12. package/dist/credentials.d.ts.map +1 -1
  13. package/dist/credentials.js +38 -43
  14. package/dist/credentials.js.map +1 -1
  15. package/dist/discovery.d.ts.map +1 -1
  16. package/dist/discovery.js +82 -191
  17. package/dist/discovery.js.map +1 -1
  18. package/dist/http-api.d.ts.map +1 -1
  19. package/dist/http-api.js +33 -17
  20. package/dist/http-api.js.map +1 -1
  21. package/dist/proxy.js +1 -1
  22. package/dist/proxy.js.map +1 -1
  23. package/landing/next-env.d.ts +0 -1
  24. package/landing/src/app/api/auth/magic-link/route.ts +1 -1
  25. package/landing/src/app/auth/verify/page.tsx +0 -6
  26. package/landing/src/app/dashboard/verify/page.tsx +0 -6
  27. package/landing/src/app/join/page.tsx +0 -6
  28. package/landing/src/app/layout.tsx +2 -2
  29. package/landing/src/app/login/page.tsx +1 -1
  30. package/landing/src/app/mou/[partnerId]/page.tsx +0 -6
  31. package/landing/src/app/page.tsx +18 -39
  32. package/landing/src/app/providers/dashboard/[apiId]/actions/[actionId]/edit/page.tsx +0 -6
  33. package/landing/src/app/providers/dashboard/[apiId]/actions/new/page.tsx +0 -5
  34. package/landing/src/app/providers/dashboard/[apiId]/actions/page.tsx +0 -5
  35. package/landing/src/app/providers/dashboard/[apiId]/direct-call/page.tsx +1 -6
  36. package/landing/src/app/providers/dashboard/[apiId]/page.tsx +0 -5
  37. package/landing/src/app/providers/dashboard/[apiId]/test/page.tsx +0 -5
  38. package/landing/src/app/providers/dashboard/layout.tsx +6 -6
  39. package/landing/src/app/providers/dashboard/login/page.tsx +1 -1
  40. package/landing/src/app/providers/dashboard/page.tsx +1 -1
  41. package/landing/src/app/providers/dashboard/verify/page.tsx +0 -6
  42. package/landing/src/app/providers/layout.tsx +1 -1
  43. package/landing/src/app/upgrade/page.tsx +0 -6
  44. package/landing/src/app/workspace/page.tsx +0 -6
  45. package/landing/src/components/HeroTabs.tsx +2 -2
  46. package/landing/src/components/{Workspace.tsx → ProviderDashboard.tsx} +2 -2
  47. package/landing/src/components/VideoDemo.tsx +10 -21
  48. package/landing/src/lib/mock-data.ts +1 -1
  49. package/landing/src/lib/stats.json +1 -1
  50. package/package.json +3 -8
  51. package/src/analytics.ts +0 -5
  52. package/src/bin.ts +1 -1
  53. package/src/cli/commands/mcp-install.ts +8 -90
  54. package/src/cli/index.ts +0 -8
  55. package/src/credentials.ts +39 -44
  56. package/src/discovery.ts +82 -191
  57. package/src/http-api.ts +34 -18
  58. package/src/proxy.ts +1 -1
  59. package/APILAYER_STATUS_2026-03-24.md +0 -38
  60. package/CHANGELOG-WHITELIST-V2.md +0 -269
  61. package/HIVR-WHITELIST-STATUS.md +0 -205
  62. package/HIVR-WHITELIST.md +0 -148
  63. package/TERMINOLOGY-AUDIT.md +0 -99
  64. package/TERMINOLOGY-FIXED.md +0 -74
  65. package/VIDEO-DEMO-GUIDE.md +0 -82
  66. package/WHITELIST-ARCHITECTURE.md +0 -379
  67. package/api/discover.ts +0 -71
  68. package/api/health.ts +0 -20
  69. package/convex/adminActivate.d.ts +0 -3
  70. package/convex/adminActivate.js +0 -47
  71. package/convex/adminStats.d.ts +0 -3
  72. package/convex/adminStats.js +0 -42
  73. package/convex/agents.d.ts +0 -54
  74. package/convex/agents.js +0 -499
  75. package/convex/analytics.d.ts +0 -5
  76. package/convex/analytics.js +0 -166
  77. package/convex/billing.d.ts +0 -88
  78. package/convex/billing.js +0 -655
  79. package/convex/capabilities.d.ts +0 -9
  80. package/convex/capabilities.js +0 -145
  81. package/convex/chains.d.ts +0 -67
  82. package/convex/chains.js +0 -1042
  83. package/convex/credits.d.ts +0 -25
  84. package/convex/credits.js +0 -186
  85. package/convex/crons.d.ts +0 -3
  86. package/convex/crons.js +0 -17
  87. package/convex/directCall.d.ts +0 -72
  88. package/convex/directCall.js +0 -627
  89. package/convex/earnProgress.d.ts +0 -58
  90. package/convex/earnProgress.js +0 -649
  91. package/convex/email.d.ts +0 -14
  92. package/convex/email.js +0 -300
  93. package/convex/feedback.d.ts +0 -7
  94. package/convex/feedback.js +0 -227
  95. package/convex/http.d.ts +0 -3
  96. package/convex/http.js +0 -910
  97. package/convex/logs.d.ts +0 -38
  98. package/convex/logs.js +0 -487
  99. package/convex/mou.d.ts +0 -6
  100. package/convex/mou.js +0 -82
  101. package/convex/providerKeys.d.ts +0 -31
  102. package/convex/providerKeys.js +0 -257
  103. package/convex/providers.d.ts +0 -29
  104. package/convex/providers.js +0 -756
  105. package/convex/purchases.d.ts +0 -7
  106. package/convex/purchases.js +0 -157
  107. package/convex/ratelimit.d.ts +0 -4
  108. package/convex/ratelimit.js +0 -91
  109. package/convex/searchLogs.d.ts +0 -4
  110. package/convex/searchLogs.js +0 -129
  111. package/convex/spendAlerts.d.ts +0 -36
  112. package/convex/spendAlerts.js +0 -380
  113. package/convex/stripeActions.d.ts +0 -19
  114. package/convex/stripeActions.js +0 -411
  115. package/convex/teams.d.ts +0 -21
  116. package/convex/teams.js +0 -215
  117. package/convex/telemetry.d.ts +0 -4
  118. package/convex/telemetry.js +0 -74
  119. package/convex/usage.d.ts +0 -27
  120. package/convex/usage.js +0 -229
  121. package/convex/waitlist.d.ts +0 -4
  122. package/convex/waitlist.js +0 -49
  123. package/convex/webhooks.d.ts +0 -12
  124. package/convex/webhooks.js +0 -410
  125. package/convex/workspaces.d.ts +0 -29
  126. package/convex/workspaces.js +0 -880
  127. package/direct-test.mjs +0 -51
  128. package/dist/access-control.d.ts +0 -45
  129. package/dist/access-control.d.ts.map +0 -1
  130. package/dist/access-control.js +0 -142
  131. package/dist/access-control.js.map +0 -1
  132. package/dist/chain-types.d.ts +0 -187
  133. package/dist/chain-types.d.ts.map +0 -1
  134. package/dist/chain-types.js +0 -33
  135. package/dist/chain-types.js.map +0 -1
  136. package/dist/convex/adminActivate.js +0 -46
  137. package/dist/convex/adminStats.js +0 -41
  138. package/dist/convex/agents.js +0 -498
  139. package/dist/convex/analytics.js +0 -165
  140. package/dist/convex/billing.js +0 -654
  141. package/dist/convex/capabilities.js +0 -144
  142. package/dist/convex/chains.js +0 -1041
  143. package/dist/convex/credits.js +0 -185
  144. package/dist/convex/crons.js +0 -16
  145. package/dist/convex/directCall.js +0 -626
  146. package/dist/convex/earnProgress.js +0 -648
  147. package/dist/convex/email.js +0 -299
  148. package/dist/convex/feedback.js +0 -226
  149. package/dist/convex/http.js +0 -909
  150. package/dist/convex/logs.js +0 -486
  151. package/dist/convex/mou.js +0 -81
  152. package/dist/convex/providerKeys.js +0 -256
  153. package/dist/convex/providers.js +0 -755
  154. package/dist/convex/purchases.js +0 -156
  155. package/dist/convex/ratelimit.js +0 -90
  156. package/dist/convex/schema.js +0 -709
  157. package/dist/convex/searchLogs.js +0 -128
  158. package/dist/convex/spendAlerts.js +0 -379
  159. package/dist/convex/stripeActions.js +0 -410
  160. package/dist/convex/teams.js +0 -214
  161. package/dist/convex/telemetry.js +0 -73
  162. package/dist/convex/usage.js +0 -228
  163. package/dist/convex/waitlist.js +0 -48
  164. package/dist/convex/webhooks.js +0 -409
  165. package/dist/convex/workspaces.js +0 -879
  166. package/dist/hivr-whitelist.d.ts +0 -18
  167. package/dist/hivr-whitelist.d.ts.map +0 -1
  168. package/dist/hivr-whitelist.js +0 -95
  169. package/dist/hivr-whitelist.js.map +0 -1
  170. package/dist/http-server-minimal.d.ts +0 -7
  171. package/dist/http-server-minimal.d.ts.map +0 -1
  172. package/dist/http-server-minimal.js +0 -126
  173. package/dist/http-server-minimal.js.map +0 -1
  174. package/dist/product-whitelist.d.ts +0 -37
  175. package/dist/product-whitelist.d.ts.map +0 -1
  176. package/dist/product-whitelist.js +0 -203
  177. package/dist/product-whitelist.js.map +0 -1
  178. package/dist/src/analytics.js +0 -129
  179. package/dist/src/bin.js +0 -17
  180. package/dist/src/capability-router.js +0 -240
  181. package/dist/src/chainExecutor.js +0 -451
  182. package/dist/src/chainResolver.js +0 -518
  183. package/dist/src/cli/commands/doctor.js +0 -324
  184. package/dist/src/cli/commands/mcp-install.js +0 -255
  185. package/dist/src/cli/commands/restore.js +0 -259
  186. package/dist/src/cli/commands/setup.js +0 -205
  187. package/dist/src/cli/commands/uninstall.js +0 -188
  188. package/dist/src/cli/index.js +0 -111
  189. package/dist/src/cli.js +0 -302
  190. package/dist/src/confirmation.js +0 -240
  191. package/dist/src/credentials.js +0 -357
  192. package/dist/src/credits.js +0 -260
  193. package/dist/src/crypto.js +0 -66
  194. package/dist/src/discovery.js +0 -504
  195. package/dist/src/enterprise/env.js +0 -123
  196. package/dist/src/enterprise/script-generator.js +0 -460
  197. package/dist/src/execute-dynamic.js +0 -473
  198. package/dist/src/execute.js +0 -1727
  199. package/dist/src/index.js +0 -2062
  200. package/dist/src/metered.js +0 -80
  201. package/dist/src/open-apis.js +0 -276
  202. package/dist/src/proxy.js +0 -28
  203. package/dist/src/session.js +0 -86
  204. package/dist/src/stripe.js +0 -407
  205. package/dist/src/telemetry.js +0 -49
  206. package/dist/src/types.js +0 -2
  207. package/dist/src/utils/backup.js +0 -181
  208. package/dist/src/utils/config.js +0 -220
  209. package/dist/src/utils/os.js +0 -105
  210. package/dist/src/utils/paths.js +0 -159
  211. package/landing/pages/api/discover.ts +0 -43
  212. package/landing/pages/api/health.ts +0 -20
  213. package/scripts/test-whitelist-v2.sh +0 -128
  214. package/src/access-control.ts +0 -174
  215. package/src/hivr-whitelist.ts +0 -110
  216. package/src/http-server-minimal.ts +0 -154
  217. package/src/product-whitelist.ts +0 -246
  218. package/test-actual-handlers.ts +0 -92
  219. package/test-apilayer-all-14.ts +0 -249
  220. package/test-apilayer-fixed.ts +0 -248
  221. package/test-direct-endpoints.ts +0 -174
  222. package/test-exact-endpoints.ts +0 -144
  223. package/test-final.ts +0 -83
  224. package/test-full-routing.ts +0 -100
  225. package/test-handlers-correct.ts +0 -217
  226. package/test-numverify-key.ts +0 -41
  227. package/test-via-handlers.ts +0 -92
  228. package/test-worldnews.mjs +0 -26
@@ -1,111 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * APIClaw MCP Auto-Setup CLI
4
- * Enterprise-grade, platform-agnostic configuration tool
5
- */
6
- import { Command } from 'commander';
7
- import { writeFileSync } from 'fs';
8
- import { setupCommand } from './commands/setup.js';
9
- import { mcpInstallCommand } from './commands/mcp-install.js';
10
- import { doctorCommand } from './commands/doctor.js';
11
- import { restoreCommand } from './commands/restore.js';
12
- import { uninstallCommand } from './commands/uninstall.js';
13
- import { generateScript } from '../enterprise/script-generator.js';
14
- const VERSION = '1.0.0';
15
- const program = new Command();
16
- program
17
- .name('apiclaw')
18
- .description('APIClaw MCP Auto-Setup - Configure APIClaw across all your AI coding assistants')
19
- .version(VERSION);
20
- // Setup command - main entry point
21
- program
22
- .command('setup')
23
- .description('Configure APIClaw for MCP clients')
24
- .option('-c, --client <client>', 'Target specific client (claude-desktop, cursor, windsurf, cline, continue)')
25
- .option('--config <path>', 'Custom config file path')
26
- .option('-w, --workspace <id>', 'Pre-link APIClaw workspace ID')
27
- .option('--dry-run', 'Show what would happen without making changes')
28
- .option('-f, --force', 'Overwrite existing APIClaw configuration')
29
- .option('--wizard', 'Interactive setup wizard')
30
- .option('--all', 'Configure all detected clients')
31
- .option('-v, --verbose', 'Verbose output')
32
- .option('--enterprise', 'Generate enterprise deployment script')
33
- .option('--output <file>', 'Output file for enterprise script')
34
- .option('--script-type <type>', 'Script type: bash or powershell (default: auto)')
35
- .action(async (options) => {
36
- // Enterprise script generation mode
37
- if (options.enterprise) {
38
- const scriptType = options.scriptType || 'auto';
39
- const result = generateScript(scriptType, {
40
- workspace: options.workspace,
41
- verbose: options.verbose,
42
- });
43
- if (options.output) {
44
- writeFileSync(options.output, result.script);
45
- console.log(`\n✓ Enterprise script written to: ${options.output}`);
46
- console.log(` Type: ${result.platform}`);
47
- console.log(`\nUsage:`);
48
- if (result.platform === 'bash') {
49
- console.log(` chmod +x ${options.output}`);
50
- console.log(` ./${options.output}`);
51
- }
52
- else {
53
- console.log(` powershell -ExecutionPolicy Bypass -File ${options.output}`);
54
- }
55
- console.log('');
56
- }
57
- else {
58
- console.log(result.script);
59
- }
60
- return;
61
- }
62
- // Normal setup
63
- await setupCommand(options);
64
- });
65
- // MCP Install command - simple focused installation
66
- program
67
- .command('mcp-install')
68
- .description('Install APIClaw into Claude Desktop or Claude Code MCP config')
69
- .option('-c, --client <client>', 'Target specific client (claude-desktop, claude-code)')
70
- .option('--dry-run', 'Show what would happen without making changes')
71
- .action(mcpInstallCommand);
72
- // Doctor command - health check
73
- program
74
- .command('doctor')
75
- .description('Diagnose APIClaw setup and connectivity')
76
- .option('--server-name <name>', 'Server name to check (default: apiclaw)')
77
- .option('--json', 'Output as JSON')
78
- .action(doctorCommand);
79
- // Restore command - rollback from backup
80
- program
81
- .command('restore')
82
- .description('Restore config from backup')
83
- .option('-c, --client <client>', 'Target specific client')
84
- .option('-l, --list', 'List available backups')
85
- .option('-b, --backup <file>', 'Specific backup file to restore')
86
- .option('--dry-run', 'Show what would be done without making changes')
87
- .action(restoreCommand);
88
- // Uninstall command - remove APIClaw
89
- program
90
- .command('uninstall')
91
- .description('Remove APIClaw from all configured clients')
92
- .option('-c, --client <client>', 'Target specific client')
93
- .option('--all', 'Remove from all clients')
94
- .option('--server-name <name>', 'Server name to remove (default: apiclaw)')
95
- .option('--no-backup', 'Skip backup creation')
96
- .option('--dry-run', 'Show what would be done without making changes')
97
- .option('-f, --force', 'Remove even if not configured')
98
- .action(uninstallCommand);
99
- // MCP Uninstall alias - same as uninstall but for consistency with mcp-install
100
- program
101
- .command('mcp-uninstall')
102
- .description('Remove APIClaw from Claude Desktop or Claude Code MCP config')
103
- .option('-c, --client <client>', 'Target specific client (claude-desktop, claude-code)')
104
- .option('--dry-run', 'Show what would be done without making changes')
105
- .action(uninstallCommand);
106
- // Parse and execute
107
- program.parse();
108
- // Show help if no command provided
109
- if (!process.argv.slice(2).length) {
110
- program.outputHelp();
111
- }
package/dist/src/cli.js DELETED
@@ -1,302 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * APIClaw Interactive CLI
4
- * Run with: npx @nordsym/apiclaw --cli
5
- */
6
- import * as readline from 'readline';
7
- import { ConvexHttpClient } from 'convex/browser';
8
- import { discoverAPIs } from './discovery.js';
9
- import { executeAPICall, getConnectedProviders } from './execute.js';
10
- import { readSession, writeSession, clearSession, getMachineFingerprint } from './session.js';
11
- const CONVEX_URL = process.env.CONVEX_URL || 'https://adventurous-avocet-799.convex.cloud';
12
- const convex = new ConvexHttpClient(CONVEX_URL);
13
- // Colors for terminal
14
- const colors = {
15
- reset: '\x1b[0m',
16
- bright: '\x1b[1m',
17
- red: '\x1b[31m',
18
- green: '\x1b[32m',
19
- yellow: '\x1b[33m',
20
- blue: '\x1b[34m',
21
- magenta: '\x1b[35m',
22
- cyan: '\x1b[36m',
23
- };
24
- function log(msg) {
25
- console.log(msg);
26
- }
27
- function success(msg) {
28
- console.log(`${colors.green}✓${colors.reset} ${msg}`);
29
- }
30
- function error(msg) {
31
- console.log(`${colors.red}✗${colors.reset} ${msg}`);
32
- }
33
- function info(msg) {
34
- console.log(`${colors.cyan}ℹ${colors.reset} ${msg}`);
35
- }
36
- let workspaceContext = null;
37
- async function validateSession() {
38
- const session = readSession();
39
- if (!session)
40
- return false;
41
- try {
42
- const result = await convex.query("workspaces:getWorkspaceStatus", {
43
- sessionToken: session.sessionToken,
44
- });
45
- if (!result?.authenticated || result?.status !== 'active') {
46
- clearSession();
47
- return false;
48
- }
49
- workspaceContext = {
50
- sessionToken: session.sessionToken,
51
- workspaceId: session.workspaceId,
52
- email: result.email ?? '',
53
- tier: result.tier ?? 'free',
54
- usageRemaining: result.usageRemaining ?? 0,
55
- };
56
- return true;
57
- }
58
- catch {
59
- return false;
60
- }
61
- }
62
- async function registerOwner(email) {
63
- info(`Sending magic link to ${email}...`);
64
- try {
65
- const fingerprint = getMachineFingerprint();
66
- // Use HTTP endpoint for magic link
67
- const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/magic-link`, {
68
- method: 'POST',
69
- headers: { 'Content-Type': 'application/json' },
70
- body: JSON.stringify({ email, fingerprint }),
71
- });
72
- const result = await response.json();
73
- if (result?.success && result?.token) {
74
- success(`Magic link sent to ${email}`);
75
- log(`\n📧 Check your email and click the link to authenticate.`);
76
- // Start polling for verification
77
- log(`\n⏳ Waiting for you to click the link...`);
78
- log(` (Press Ctrl+C to cancel)\n`);
79
- await pollForVerification(result.token, fingerprint);
80
- }
81
- else {
82
- error(`Failed: ${result?.error || 'Unknown error'}`);
83
- }
84
- }
85
- catch (err) {
86
- error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
87
- }
88
- }
89
- async function pollForVerification(token, fingerprint) {
90
- const maxAttempts = 60; // 5 minutes
91
- for (let i = 0; i < maxAttempts; i++) {
92
- await new Promise(r => setTimeout(r, 5000)); // Poll every 5 seconds
93
- try {
94
- const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/poll?token=${token}`);
95
- const result = await response.json();
96
- if (result?.verified && result?.sessionToken) {
97
- // Save the real session
98
- writeSession(result.sessionToken, result.workspaceId || '', result.email || '');
99
- success(`Authenticated as ${result.email}!`);
100
- // Reload workspace context
101
- await validateSession();
102
- return;
103
- }
104
- }
105
- catch {
106
- // Continue polling
107
- }
108
- // Show progress dot
109
- process.stdout.write('.');
110
- }
111
- log('\n');
112
- error('Verification timed out. Please try again.');
113
- }
114
- async function showStatus() {
115
- const valid = await validateSession();
116
- log(`\n${colors.bright}APIClaw Status${colors.reset}`);
117
- log(`${'─'.repeat(40)}`);
118
- if (valid && workspaceContext) {
119
- success(`Authenticated as ${workspaceContext.email}`);
120
- log(` Tier: ${workspaceContext.tier}`);
121
- log(` Remaining calls: ${workspaceContext.usageRemaining}`);
122
- }
123
- else {
124
- error(`Not authenticated`);
125
- log(` Run: ${colors.cyan}register <email>${colors.reset}`);
126
- }
127
- log('');
128
- }
129
- async function discover(query) {
130
- info(`Searching for: "${query}"`);
131
- try {
132
- const results = discoverAPIs(query, { maxResults: 5 });
133
- if (!results || results.length === 0) {
134
- log(`No APIs found for "${query}"`);
135
- return;
136
- }
137
- log(`\n${colors.bright}Found ${results.length} APIs:${colors.reset}\n`);
138
- // Get connected providers for Direct Call detection
139
- const connected = getConnectedProviders().map(p => p.provider.toLowerCase());
140
- for (const result of results) {
141
- const api = result.provider;
142
- const isDirectCall = connected.includes(api.id?.toLowerCase() || api.name.toLowerCase().replace(/\s+/g, '_'));
143
- const directCallBadge = isDirectCall ? `${colors.green}[Direct Call]${colors.reset}` : '';
144
- log(`${colors.cyan}${api.name}${colors.reset} ${directCallBadge}`);
145
- log(` ${api.description}`);
146
- log(` Category: ${api.category}`);
147
- log(` Pricing: ${api.pricing?.model || 'See docs'}`);
148
- log('');
149
- }
150
- }
151
- catch (err) {
152
- error(`Search failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
153
- }
154
- }
155
- async function listConnected() {
156
- try {
157
- const providers = getConnectedProviders();
158
- log(`\n${colors.bright}Direct Call Providers (no API key needed):${colors.reset}\n`);
159
- for (const p of providers) {
160
- log(`${colors.cyan}${p.provider}${colors.reset}`);
161
- log(` Actions: ${p.actions?.join(', ') || 'See docs'}`);
162
- log('');
163
- }
164
- }
165
- catch (err) {
166
- error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
167
- }
168
- }
169
- async function callApi(provider, action, params) {
170
- if (!workspaceContext) {
171
- error('Not authenticated. Run: register <email>');
172
- return;
173
- }
174
- info(`Calling ${provider}.${action}...`);
175
- try {
176
- const result = await executeAPICall(provider, action, params, workspaceContext.workspaceId);
177
- log(`\n${colors.bright}Result:${colors.reset}\n`);
178
- log(JSON.stringify(result, null, 2));
179
- log('');
180
- }
181
- catch (err) {
182
- error(`Call failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
183
- }
184
- }
185
- function showHelp() {
186
- log(`
187
- ${colors.bright}🦞 APIClaw CLI${colors.reset}
188
-
189
- ${colors.cyan}Commands:${colors.reset}
190
- register <email> Send magic link to authenticate
191
- status Check authentication status
192
- discover <query> Search for APIs by capability
193
- list Show Direct Call providers
194
- call <provider> <action> <json-params>
195
- Call an API (e.g., call brave_search search {"q":"test"})
196
- help Show this help
197
- exit Quit
198
-
199
- ${colors.cyan}Examples:${colors.reset}
200
- discover send SMS
201
- discover image generation
202
- list
203
- call brave_search search {"q":"hello world"}
204
- `);
205
- }
206
- function parseCallCommand(args) {
207
- // Format: provider action {json}
208
- const match = args.match(/^(\S+)\s+(\S+)\s+(.+)$/);
209
- if (!match)
210
- return null;
211
- try {
212
- const params = JSON.parse(match[3]);
213
- return { provider: match[1], action: match[2], params };
214
- }
215
- catch {
216
- return null;
217
- }
218
- }
219
- export async function startCLI() {
220
- log(`
221
- ${colors.bright}🦞 APIClaw CLI v1.1.5${colors.reset}
222
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
223
-
224
- Type ${colors.cyan}help${colors.reset} for commands, ${colors.cyan}exit${colors.reset} to quit.
225
- `);
226
- // Check session on startup
227
- const valid = await validateSession();
228
- if (valid && workspaceContext) {
229
- success(`Authenticated as ${workspaceContext.email}`);
230
- }
231
- else {
232
- info(`Not authenticated. Run: ${colors.cyan}register <email>${colors.reset}`);
233
- }
234
- log('');
235
- const rl = readline.createInterface({
236
- input: process.stdin,
237
- output: process.stdout,
238
- prompt: `${colors.red}apiclaw${colors.reset}> `,
239
- });
240
- rl.prompt();
241
- rl.on('line', async (line) => {
242
- const input = line.trim();
243
- const [cmd, ...args] = input.split(/\s+/);
244
- const argsStr = args.join(' ');
245
- switch (cmd.toLowerCase()) {
246
- case '':
247
- break;
248
- case 'help':
249
- case '?':
250
- showHelp();
251
- break;
252
- case 'exit':
253
- case 'quit':
254
- case 'q':
255
- log('Bye! 🦞');
256
- process.exit(0);
257
- break;
258
- case 'register':
259
- if (!argsStr) {
260
- error('Usage: register <email>');
261
- }
262
- else {
263
- await registerOwner(argsStr);
264
- }
265
- break;
266
- case 'status':
267
- await showStatus();
268
- break;
269
- case 'discover':
270
- case 'search':
271
- if (!argsStr) {
272
- error('Usage: discover <query>');
273
- }
274
- else {
275
- await discover(argsStr);
276
- }
277
- break;
278
- case 'list':
279
- case 'connected':
280
- await listConnected();
281
- break;
282
- case 'call':
283
- const parsed = parseCallCommand(argsStr);
284
- if (!parsed) {
285
- error('Usage: call <provider> <action> {"param":"value"}');
286
- log('Example: call brave_search search {"q":"hello"}');
287
- }
288
- else {
289
- await callApi(parsed.provider, parsed.action, parsed.params);
290
- }
291
- break;
292
- default:
293
- error(`Unknown command: ${cmd}`);
294
- log(`Type ${colors.cyan}help${colors.reset} for available commands.`);
295
- }
296
- rl.prompt();
297
- });
298
- rl.on('close', () => {
299
- log('\nBye! 🦞');
300
- process.exit(0);
301
- });
302
- }
@@ -1,240 +0,0 @@
1
- /**
2
- * APIClaw Confirmation System
3
- * For actions that cost money or have side effects
4
- *
5
- * Flow:
6
- * 1. Agent calls action → gets preview + token
7
- * 2. Agent shows preview to user
8
- * 3. User confirms → agent calls confirm with token
9
- * 4. APIClaw executes the actual action
10
- */
11
- import { randomBytes } from 'crypto';
12
- // In-memory store for pending confirmations (in production, use Redis)
13
- const pendingActions = new Map();
14
- // Actions that require confirmation before execution
15
- export const CONFIRMATION_REQUIRED = {
16
- // Invoicing - costs money per send
17
- coaccept: ['send_invoice', 'send_reminder'],
18
- // SMS - costs money per message
19
- '46elks': ['send_sms'],
20
- twilio: ['send_sms'],
21
- // Email sends (less critical but still good to confirm)
22
- resend: ['send_email'],
23
- };
24
- // Token expiry time (5 minutes)
25
- const TOKEN_EXPIRY_MS = 5 * 60 * 1000;
26
- /**
27
- * Check if an action requires confirmation (hardcoded list only)
28
- * For dynamic providers, use requiresConfirmationAsync
29
- */
30
- export function requiresConfirmation(provider, action) {
31
- const actions = CONFIRMATION_REQUIRED[provider];
32
- return actions?.includes(action) ?? false;
33
- }
34
- /**
35
- * Check if a dynamic provider action requires confirmation
36
- * This is imported dynamically to avoid circular deps
37
- */
38
- export async function requiresConfirmationAsync(provider, action) {
39
- // First check hardcoded list
40
- if (requiresConfirmation(provider, action)) {
41
- return { required: true, isDynamic: false };
42
- }
43
- // Then check dynamic provider config
44
- try {
45
- const { getDynamicConfirmationConfig } = await import('./execute-dynamic.js');
46
- const config = await getDynamicConfirmationConfig(provider, action);
47
- if (config.required) {
48
- return {
49
- required: true,
50
- estimatedCost: config.estimatedCost,
51
- isDynamic: true
52
- };
53
- }
54
- }
55
- catch (e) {
56
- // Dynamic config not available, that's ok
57
- }
58
- return { required: false };
59
- }
60
- /**
61
- * Generate a confirmation token and store the pending action
62
- */
63
- export function createPendingAction(provider, action, params, preview, userId) {
64
- // Clean up expired tokens
65
- cleanupExpired();
66
- const token = randomBytes(16).toString('hex');
67
- const now = Date.now();
68
- const pending = {
69
- token,
70
- provider,
71
- action,
72
- params,
73
- preview,
74
- createdAt: now,
75
- expiresAt: now + TOKEN_EXPIRY_MS,
76
- userId,
77
- };
78
- pendingActions.set(token, pending);
79
- return pending;
80
- }
81
- /**
82
- * Get a pending action by token (and validate it)
83
- */
84
- export function getPendingAction(token) {
85
- const pending = pendingActions.get(token);
86
- if (!pending) {
87
- return null;
88
- }
89
- if (Date.now() > pending.expiresAt) {
90
- pendingActions.delete(token);
91
- return null;
92
- }
93
- return pending;
94
- }
95
- /**
96
- * Consume a pending action (use it and remove from store)
97
- */
98
- export function consumePendingAction(token) {
99
- const pending = getPendingAction(token);
100
- if (pending) {
101
- pendingActions.delete(token);
102
- }
103
- return pending;
104
- }
105
- /**
106
- * Clean up expired tokens
107
- */
108
- function cleanupExpired() {
109
- const now = Date.now();
110
- for (const [token, pending] of pendingActions.entries()) {
111
- if (now > pending.expiresAt) {
112
- pendingActions.delete(token);
113
- }
114
- }
115
- }
116
- /**
117
- * Generate a human-readable preview for an action
118
- */
119
- export function generatePreview(provider, action, params) {
120
- // Provider-specific preview generators
121
- switch (provider) {
122
- case 'coaccept':
123
- return generateCoAcceptPreview(action, params);
124
- case '46elks':
125
- case 'twilio':
126
- return generateSMSPreview(params);
127
- case 'resend':
128
- return generateEmailPreview(params);
129
- default:
130
- return { action, params };
131
- }
132
- }
133
- function generateCoAcceptPreview(action, params) {
134
- if (action === 'send_invoice') {
135
- const items = params.items || [];
136
- const totalAmount = items.reduce((sum, item) => sum + (item.amount || 0), 0);
137
- return {
138
- type: 'invoice',
139
- recipient: {
140
- name: params.recipient_name,
141
- email: params.recipient_email,
142
- org_number: params.recipient_org_nr,
143
- },
144
- amount: {
145
- subtotal: totalAmount,
146
- vat_rate: params.vat_rate || 25,
147
- vat_amount: totalAmount * ((params.vat_rate || 25) / 100),
148
- total: totalAmount * (1 + (params.vat_rate || 25) / 100),
149
- currency: params.currency || 'SEK',
150
- },
151
- due_date: params.due_date,
152
- items: items.map((item) => ({
153
- description: item.description,
154
- quantity: item.quantity || 1,
155
- unit_price: item.unit_price || item.amount,
156
- amount: item.amount,
157
- })),
158
- payment_method: 'SMS + Swish/Card (CoAccept)',
159
- estimated_cost: '~2-5 SEK per invoice',
160
- };
161
- }
162
- return { action, params };
163
- }
164
- function generateSMSPreview(params) {
165
- const messageLength = (params.message || '').length;
166
- const segments = Math.ceil(messageLength / 160);
167
- return {
168
- type: 'sms',
169
- to: params.to,
170
- from: params.from || 'NordSym',
171
- message: params.message,
172
- message_length: messageLength,
173
- segments,
174
- estimated_cost: `~${(segments * 0.35).toFixed(2)} SEK`,
175
- };
176
- }
177
- function generateEmailPreview(params) {
178
- return {
179
- type: 'email',
180
- to: params.to,
181
- from: params.from || 'noreply@nordsym.com',
182
- subject: params.subject,
183
- preview: (params.message || params.html || '').substring(0, 200) + '...',
184
- };
185
- }
186
- /**
187
- * Validate params before creating preview
188
- * Returns { valid: true } or { valid: false, errors: [...] }
189
- */
190
- export function validateParams(provider, action, params) {
191
- const errors = [];
192
- switch (provider) {
193
- case 'coaccept':
194
- if (action === 'send_invoice') {
195
- if (!params.recipient_name)
196
- errors.push('Missing: recipient_name');
197
- if (!params.recipient_email)
198
- errors.push('Missing: recipient_email');
199
- if (!params.items || !Array.isArray(params.items) || params.items.length === 0) {
200
- errors.push('Missing: items (at least one invoice item required)');
201
- }
202
- if (!params.due_date)
203
- errors.push('Missing: due_date (YYYY-MM-DD)');
204
- // Validate email format
205
- if (params.recipient_email && !params.recipient_email.includes('@')) {
206
- errors.push('Invalid: recipient_email format');
207
- }
208
- // Validate due date is not in past
209
- if (params.due_date) {
210
- const dueDate = new Date(params.due_date);
211
- const today = new Date();
212
- today.setHours(0, 0, 0, 0);
213
- if (dueDate < today) {
214
- errors.push('Invalid: due_date cannot be in the past');
215
- }
216
- }
217
- }
218
- break;
219
- case '46elks':
220
- case 'twilio':
221
- if (!params.to)
222
- errors.push('Missing: to (phone number)');
223
- if (!params.message)
224
- errors.push('Missing: message');
225
- // Validate phone format (basic check)
226
- if (params.to && !params.to.startsWith('+')) {
227
- errors.push('Invalid: phone number must start with + (e.g., +46701234567)');
228
- }
229
- break;
230
- case 'resend':
231
- if (!params.to)
232
- errors.push('Missing: to (email address)');
233
- if (!params.subject)
234
- errors.push('Missing: subject');
235
- if (!params.message && !params.html)
236
- errors.push('Missing: message or html content');
237
- break;
238
- }
239
- return errors.length > 0 ? { valid: false, errors } : { valid: true };
240
- }