@socialseal/cli 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+ - Document public base URL and CLI error output.
5
+ - Add request timeouts, verbose error output, and OSS-safe tool discovery behavior.
6
+
7
+ ## 0.1.0
8
+ - Initial CLI with agent streaming, tools calls, and provisional data exports.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # SocialSeal CLI
2
+
3
+ ## Setup
4
+ - Requires Node 18+
5
+ - Global install: `npm install -g @socialseal/cli`
6
+ - Dev install: `npm install`
7
+
8
+ ## Configuration
9
+ Environment variables:
10
+ - `SOCIALSEAL_API_KEY`
11
+ - `SOCIALSEAL_API_BASE` (default `https://api.socialseal.co`)
12
+ - `SOCIALSEAL_TIMEOUT_MS` (optional request timeout override)
13
+
14
+ Optional config file:
15
+ - `~/.config/socialseal/config.json`
16
+
17
+ ```json
18
+ {
19
+ "apiKey": "ss_cli_...",
20
+ "apiBase": "https://api.socialseal.co",
21
+ "timeoutMs": 30000
22
+ }
23
+ ```
24
+
25
+ ## Commands
26
+ - Agent (non-interactive, streaming):
27
+ - `socialseal agent run --message "..." --api-base https://api.socialseal.co --api-key <key> [--workspace-id <uuid>]`
28
+ - `socialseal agent run --message "..." --timeout 60000`
29
+
30
+ - Tools list (limited):
31
+ - `socialseal tools list`
32
+ - `socialseal tools list --json`
33
+
34
+ - Tools (direct edge function call):
35
+ - `socialseal tools call --function <tool> --body @payload.json --api-base https://api.socialseal.co --api-key <key>`
36
+ - `socialseal tools call --function <tool> --body @payload.json --json`
37
+
38
+ - Data exports (provisional):
39
+ - `socialseal data export-tracking --group-id 123 --time-period 30d --out out.csv`
40
+ - `socialseal data export-report --report-type keyword_universe --format csv --payload @payload.json --out out.csv`
41
+
42
+ ## Notes
43
+ - `export-report` and `export_tracking_data` are provisional until CLI export specs are finalized.
44
+ - `tools list` does not enumerate internal endpoints in the OSS build. Refer to official docs for supported tool names.
45
+ - Use `--timeout <ms>` to override the default 30s timeout for network calls.
46
+
47
+ ## Errors and exit codes
48
+ - Exit codes: `2` (usage), `3` (auth), `4` (not found), `5` (server), `1` (unknown)
49
+ - Add `--json` to `tools call` or `data` commands to emit machine-readable errors.
50
+ - Add `--verbose` to print error details (suppressed by default).
51
+
52
+ ## Smoke Test (manual)
53
+ 1. `SOCIALSEAL_API_KEY=... socialseal agent run --message "ping"`
54
+ 2. `SOCIALSEAL_API_KEY=... socialseal tools call --function <tool> --body @payload.json`
55
+
56
+ ## Maintainers
57
+ - The public CLI base (`api.socialseal.co`) must route to the CLI gateway service.
package/SECURITY.md ADDED
@@ -0,0 +1,7 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ If you discover a security issue, please email security@socialseal.co with details and reproduction steps.
6
+
7
+ We aim to acknowledge reports within 72 hours and will coordinate a fix and disclosure timeline.
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@socialseal/cli",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "SocialSeal CLI (non-interactive)",
7
+ "keywords": [
8
+ "socialseal",
9
+ "cli",
10
+ "analytics",
11
+ "video"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/OpenSealAI/socialseal-cli.git"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/OpenSealAI/socialseal-cli/issues"
20
+ },
21
+ "homepage": "https://github.com/OpenSealAI/socialseal-cli#readme",
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE",
30
+ "SECURITY.md"
31
+ ],
32
+ "bin": {
33
+ "socialseal": "src/index.js"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test test/*.test.js"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "commander": "^11.1.0",
43
+ "ws": "^8.16.0"
44
+ }
45
+ }
package/src/index.js ADDED
@@ -0,0 +1,703 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import WebSocket from 'ws';
8
+
9
+ const DEFAULT_CONFIG_PATH = path.join(os.homedir(), '.config', 'socialseal', 'config.json');
10
+ const DEFAULT_API_BASE = 'https://api.socialseal.co';
11
+ const CLI_KEY_HEADER = 'X-CLI-Key';
12
+ const WORKSPACE_HEADER = 'X-Workspace-Id';
13
+ const DEFAULT_TIMEOUT_MS = 30000;
14
+ const MAX_TIMEOUT_MS = 300000;
15
+ const LEGACY_ENABLED = process.env.SOCIALSEAL_ENABLE_LEGACY === '1';
16
+ const EXIT_CODES = {
17
+ OK: 0,
18
+ UNKNOWN: 1,
19
+ USAGE: 2,
20
+ AUTH: 3,
21
+ NOT_FOUND: 4,
22
+ SERVER: 5,
23
+ };
24
+ const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
25
+ const KNOWN_TOOLS = [];
26
+
27
+ function loadConfig() {
28
+ const configPath = process.env.SOCIALSEAL_CONFIG || DEFAULT_CONFIG_PATH;
29
+ try {
30
+ if (!fs.existsSync(configPath)) return {};
31
+ const raw = fs.readFileSync(configPath, 'utf8');
32
+ return JSON.parse(raw);
33
+ } catch (err) {
34
+ console.error('[socialseal] Failed to read config:', err.message || err);
35
+ return {};
36
+ }
37
+ }
38
+
39
+ function resolveApiKey(opts, config) {
40
+ return opts.apiKey || process.env.SOCIALSEAL_API_KEY || config.apiKey;
41
+ }
42
+
43
+ function resolveApiBase(opts, config) {
44
+ return opts.apiBase || process.env.SOCIALSEAL_API_BASE || config.apiBase || null;
45
+ }
46
+
47
+ function resolveAgentUrl(opts, config) {
48
+ return opts.agentUrl || process.env.SOCIALSEAL_AGENT_URL || config.agentUrl;
49
+ }
50
+
51
+ function resolveSupabaseUrl(opts, config) {
52
+ return opts.supabaseUrl || process.env.SOCIALSEAL_SUPABASE_URL || config.supabaseUrl;
53
+ }
54
+
55
+ class CliError extends Error {
56
+ constructor(message, { code = 'CLI_ERROR', exitCode = EXIT_CODES.UNKNOWN, status, hint, details } = {}) {
57
+ super(message);
58
+ this.name = 'CliError';
59
+ this.code = code;
60
+ this.exitCode = exitCode;
61
+ this.status = status;
62
+ this.hint = hint;
63
+ this.details = details;
64
+ }
65
+ }
66
+
67
+ function normalizeMethod(method) {
68
+ const normalized = String(method || 'POST').trim().toUpperCase();
69
+ if (!HTTP_METHODS.has(normalized)) {
70
+ throw new CliError(`Unsupported HTTP method: ${method}`, {
71
+ code: 'INVALID_METHOD',
72
+ exitCode: EXIT_CODES.USAGE,
73
+ hint: `Use one of: ${Array.from(HTTP_METHODS).join(', ')}.`,
74
+ });
75
+ }
76
+ return normalized;
77
+ }
78
+
79
+ function resolveTimeoutMs(opts, config) {
80
+ const raw = opts.timeout ?? process.env.SOCIALSEAL_TIMEOUT_MS ?? config.timeoutMs;
81
+ if (raw == null || raw === '') return DEFAULT_TIMEOUT_MS;
82
+ const parsed = Number(raw);
83
+ if (!Number.isFinite(parsed) || parsed <= 0) {
84
+ throw new CliError('Invalid timeout value. Use a positive number of milliseconds.', {
85
+ code: 'INVALID_TIMEOUT',
86
+ exitCode: EXIT_CODES.USAGE,
87
+ });
88
+ }
89
+ return Math.min(parsed, MAX_TIMEOUT_MS);
90
+ }
91
+
92
+ function resolveLegacyUrl(value, label) {
93
+ if (!value) return null;
94
+ if (!LEGACY_ENABLED) {
95
+ throw new CliError(`Legacy URL override (${label}) is disabled.`, {
96
+ code: 'LEGACY_DISABLED',
97
+ exitCode: EXIT_CODES.USAGE,
98
+ hint: 'Remove the legacy URL or set SOCIALSEAL_ENABLE_LEGACY=1.',
99
+ });
100
+ }
101
+ return value;
102
+ }
103
+
104
+ function parseJsonInput(value, { label = 'payload', allowString = false } = {}) {
105
+ if (!value) return null;
106
+ if (value.startsWith('@')) {
107
+ const filePath = value.slice(1);
108
+ if (!fs.existsSync(filePath)) {
109
+ throw new CliError(`File not found: ${filePath}`, {
110
+ code: 'FILE_NOT_FOUND',
111
+ exitCode: EXIT_CODES.USAGE,
112
+ hint: `Use --${label} @path.json or --${label} '{"key":"value"}'.`,
113
+ });
114
+ }
115
+ const raw = fs.readFileSync(filePath, 'utf8');
116
+ try {
117
+ return JSON.parse(raw);
118
+ } catch (err) {
119
+ throw new CliError(`Invalid JSON in ${filePath}`, {
120
+ code: 'INVALID_JSON',
121
+ exitCode: EXIT_CODES.USAGE,
122
+ hint: `Fix ${filePath} or pass --${label} with valid JSON.`,
123
+ details: err instanceof Error ? err.message : String(err),
124
+ });
125
+ }
126
+ }
127
+ try {
128
+ return JSON.parse(value);
129
+ } catch (err) {
130
+ if (allowString) return value;
131
+ throw new CliError(`Invalid ${label} JSON`, {
132
+ code: 'INVALID_JSON',
133
+ exitCode: EXIT_CODES.USAGE,
134
+ hint: `Use --${label} @path.json or --${label} '{"key":"value"}'.`,
135
+ details: err instanceof Error ? err.message : String(err),
136
+ });
137
+ }
138
+ }
139
+
140
+ function ensureJsonObject(value, label) {
141
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
142
+ throw new CliError(`Invalid ${label}: expected a JSON object`, {
143
+ code: 'INVALID_PAYLOAD',
144
+ exitCode: EXIT_CODES.USAGE,
145
+ hint: `Use --${label} '{"key":"value"}' or --${label} @payload.json.`,
146
+ });
147
+ }
148
+ return value;
149
+ }
150
+
151
+ function mapStatusToExitCode(status) {
152
+ if (status === 401 || status === 403) return EXIT_CODES.AUTH;
153
+ if (status === 404) return EXIT_CODES.NOT_FOUND;
154
+ if (status >= 500) return EXIT_CODES.SERVER;
155
+ if (status >= 400) return EXIT_CODES.USAGE;
156
+ return EXIT_CODES.UNKNOWN;
157
+ }
158
+
159
+ function buildStatusHint(status, context = {}) {
160
+ switch (status) {
161
+ case 401:
162
+ case 403:
163
+ return 'Check your CLI key and workspace access.';
164
+ case 404:
165
+ if (context.functionName) {
166
+ return `Unknown function "${context.functionName}". Double-check the name and API base.`;
167
+ }
168
+ return 'Check the API base URL and endpoint path.';
169
+ case 405:
170
+ return `Method not allowed. Try --method GET or ensure the endpoint supports ${context.method || 'this method'}.`;
171
+ case 422:
172
+ return 'Validation error. Review the JSON payload schema.';
173
+ default:
174
+ return null;
175
+ }
176
+ }
177
+
178
+ function truncateDetails(value, limit = 2000) {
179
+ if (value == null) return value;
180
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
181
+ if (text.length <= limit) return value;
182
+ return `${text.slice(0, limit)}…`;
183
+ }
184
+
185
+ async function buildHttpError(res, context = {}) {
186
+ const status = res.status;
187
+ const contentType = res.headers.get('content-type') || '';
188
+ const raw = await res.text();
189
+ let details = raw || null;
190
+ if (raw && contentType.includes('application/json')) {
191
+ try {
192
+ details = JSON.parse(raw);
193
+ } catch {
194
+ details = raw;
195
+ }
196
+ }
197
+
198
+ const label = context.label || 'Request';
199
+ const statusText = res.statusText ? ` ${res.statusText}` : '';
200
+ const hint = context.hint || buildStatusHint(status, context);
201
+
202
+ return new CliError(`${label} failed: ${status}${statusText}`.trim(), {
203
+ code: 'HTTP_ERROR',
204
+ exitCode: mapStatusToExitCode(status),
205
+ status,
206
+ hint,
207
+ details: truncateDetails(details),
208
+ });
209
+ }
210
+
211
+ function emitError(err, opts = {}) {
212
+ const showDetails = opts.json || opts.verbose;
213
+ const payload = {
214
+ type: 'error',
215
+ error: {
216
+ code: err.code || 'CLI_ERROR',
217
+ message: err.message || 'Unknown error',
218
+ status: err.status ?? null,
219
+ hint: err.hint ?? null,
220
+ details: showDetails ? (err.details ?? null) : null,
221
+ },
222
+ };
223
+
224
+ if (opts.json) {
225
+ process.stderr.write(`${JSON.stringify(payload)}\n`);
226
+ return;
227
+ }
228
+
229
+ process.stderr.write(`[socialseal] ${payload.error.message}\n`);
230
+ if (payload.error.hint) {
231
+ process.stderr.write(`[socialseal] ${payload.error.hint}\n`);
232
+ }
233
+ if (showDetails && payload.error.details) {
234
+ process.stderr.write(`[socialseal] Details: ${payload.error.details}\n`);
235
+ } else if (!showDetails && err.details) {
236
+ process.stderr.write('[socialseal] Use --verbose to see error details.\n');
237
+ }
238
+ }
239
+
240
+ function coerceCliError(err, fallbackMessage = 'Command failed') {
241
+ if (err instanceof CliError) return err;
242
+ if (err instanceof Error) {
243
+ return new CliError(err.message || fallbackMessage, {
244
+ code: 'CLI_ERROR',
245
+ exitCode: EXIT_CODES.UNKNOWN,
246
+ });
247
+ }
248
+ return new CliError(fallbackMessage, {
249
+ code: 'CLI_ERROR',
250
+ exitCode: EXIT_CODES.UNKNOWN,
251
+ details: String(err),
252
+ });
253
+ }
254
+
255
+ function requireApiKey(opts, config) {
256
+ const apiKey = resolveApiKey(opts, config);
257
+ if (!apiKey) {
258
+ throw new CliError('Missing API key. Set SOCIALSEAL_API_KEY or --api-key.', {
259
+ code: 'MISSING_API_KEY',
260
+ exitCode: EXIT_CODES.USAGE,
261
+ });
262
+ }
263
+ return apiKey;
264
+ }
265
+
266
+ function resolveApiTarget({ apiBase, legacyUrl }) {
267
+ const resolvedApiBase = apiBase || (!legacyUrl ? DEFAULT_API_BASE : null);
268
+ if (!resolvedApiBase && !legacyUrl) {
269
+ throw new CliError('Missing API base. Set SOCIALSEAL_API_BASE or --api-base.', {
270
+ code: 'MISSING_API_BASE',
271
+ exitCode: EXIT_CODES.USAGE,
272
+ });
273
+ }
274
+ return { resolvedApiBase, legacyUrl, useGateway: !!resolvedApiBase };
275
+ }
276
+
277
+ async function runCommand(handler, opts) {
278
+ try {
279
+ await handler(opts);
280
+ } catch (err) {
281
+ const cliError = coerceCliError(err);
282
+ emitError(cliError, opts);
283
+ process.exitCode = cliError.exitCode ?? EXIT_CODES.UNKNOWN;
284
+ }
285
+ }
286
+
287
+ async function fetchWithTimeout(url, options, timeoutMs) {
288
+ const controller = new AbortController();
289
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
290
+ try {
291
+ return await fetch(url, { ...options, signal: controller.signal });
292
+ } catch (err) {
293
+ if (err instanceof Error && err.name === 'AbortError') {
294
+ throw new CliError('Request timed out.', {
295
+ code: 'TIMEOUT',
296
+ exitCode: EXIT_CODES.SERVER,
297
+ hint: 'Increase the timeout with --timeout <ms>.',
298
+ });
299
+ }
300
+ throw err;
301
+ } finally {
302
+ clearTimeout(timer);
303
+ }
304
+ }
305
+
306
+ async function callApi({ apiBase, apiKey, path, method = 'POST', body, workspaceId, timeoutMs }) {
307
+ if (!apiBase) {
308
+ throw new CliError('Missing API base. Set SOCIALSEAL_API_BASE or --api-base.', {
309
+ code: 'MISSING_API_BASE',
310
+ exitCode: EXIT_CODES.USAGE,
311
+ });
312
+ }
313
+ const normalizedMethod = normalizeMethod(method);
314
+ const url = `${apiBase.replace(/\/$/, '')}${path.startsWith('/') ? path : `/${path}`}`;
315
+ const headers = {
316
+ Accept: 'application/json',
317
+ [CLI_KEY_HEADER]: apiKey,
318
+ };
319
+ if (workspaceId) headers[WORKSPACE_HEADER] = workspaceId;
320
+ const hasBody = body !== undefined && normalizedMethod !== 'GET' && normalizedMethod !== 'HEAD';
321
+ if (hasBody) {
322
+ headers['Content-Type'] = 'application/json';
323
+ }
324
+ const res = await fetchWithTimeout(url, {
325
+ method: normalizedMethod,
326
+ headers,
327
+ body: hasBody ? JSON.stringify(body ?? {}) : undefined,
328
+ }, timeoutMs ?? DEFAULT_TIMEOUT_MS);
329
+ return res;
330
+ }
331
+
332
+ async function handleAgentRun(opts) {
333
+ const config = loadConfig();
334
+ const apiKey = requireApiKey(opts, config);
335
+ const apiBase = resolveApiBase(opts, config);
336
+ const agentUrl = resolveLegacyUrl(resolveAgentUrl(opts, config), 'SOCIALSEAL_AGENT_URL');
337
+ const { resolvedApiBase, legacyUrl } = resolveApiTarget({ apiBase, legacyUrl: agentUrl });
338
+ const timeoutMs = resolveTimeoutMs(opts, config);
339
+
340
+ const headers = {
341
+ 'Content-Type': 'application/json',
342
+ [CLI_KEY_HEADER]: apiKey,
343
+ };
344
+ if (opts.workspaceId) headers[WORKSPACE_HEADER] = opts.workspaceId;
345
+
346
+ const sessionUrl = resolvedApiBase
347
+ ? `${resolvedApiBase.replace(/\/$/, '')}/cli/agent/session`
348
+ : `${legacyUrl.replace(/\/$/, '')}/api/agent/session`;
349
+
350
+ const sessionRes = await fetchWithTimeout(sessionUrl, {
351
+ method: 'POST',
352
+ headers,
353
+ body: JSON.stringify({
354
+ conversationId: opts.conversationId || undefined,
355
+ createNew: !!opts.createNew,
356
+ }),
357
+ }, timeoutMs);
358
+
359
+ if (!sessionRes.ok) {
360
+ throw await buildHttpError(sessionRes, { label: 'Agent session creation' });
361
+ }
362
+
363
+ const sessionData = await sessionRes.json();
364
+ const wsUrl = sessionData?.data?.websocketUrl;
365
+ if (!wsUrl) {
366
+ throw new CliError('Missing websocketUrl in session response.', {
367
+ code: 'INVALID_RESPONSE',
368
+ exitCode: EXIT_CODES.SERVER,
369
+ });
370
+ }
371
+
372
+ const context = parseJsonInput(opts.context, { label: 'context', allowString: true });
373
+ const message = opts.message;
374
+
375
+ await new Promise((resolve, reject) => {
376
+ const ws = new WebSocket(wsUrl);
377
+ let finished = false;
378
+ let inactivityTimer = null;
379
+
380
+ const resetInactivity = () => {
381
+ if (!timeoutMs) return;
382
+ if (inactivityTimer) clearTimeout(inactivityTimer);
383
+ inactivityTimer = setTimeout(() => {
384
+ try {
385
+ ws.terminate();
386
+ } catch {
387
+ // ignore
388
+ }
389
+ reject(new CliError('WebSocket timed out waiting for agent response.', {
390
+ code: 'WEBSOCKET_TIMEOUT',
391
+ exitCode: EXIT_CODES.SERVER,
392
+ hint: 'Increase the timeout with --timeout <ms>.',
393
+ }));
394
+ }, timeoutMs);
395
+ };
396
+
397
+ ws.on('open', () => {
398
+ resetInactivity();
399
+ const payload = {
400
+ type: 'user_message',
401
+ payload: { content: message, context: context || undefined },
402
+ timestamp: Date.now(),
403
+ };
404
+ ws.send(JSON.stringify(payload));
405
+ });
406
+
407
+ ws.on('message', (data) => {
408
+ try {
409
+ resetInactivity();
410
+ const msg = JSON.parse(data.toString());
411
+ if (opts.json) {
412
+ process.stdout.write(JSON.stringify(msg) + '\n');
413
+ if (msg.type === 'assistant_chunk' && msg.payload?.done) {
414
+ finished = true;
415
+ ws.close(1000, 'done');
416
+ }
417
+ return;
418
+ }
419
+ if (msg.type === 'assistant_chunk') {
420
+ const chunk = msg.payload?.chunk ?? '';
421
+ if (chunk) process.stdout.write(chunk);
422
+ if (msg.payload?.done) {
423
+ finished = true;
424
+ process.stdout.write('\n');
425
+ ws.close(1000, 'done');
426
+ }
427
+ } else if (msg.type === 'error') {
428
+ process.stderr.write(`\n[socialseal] Agent error: ${msg.payload?.message || 'unknown'}\n`);
429
+ }
430
+ } catch (err) {
431
+ process.stderr.write(`\n[socialseal] Failed to parse agent message: ${err.message || err}\n`);
432
+ }
433
+ });
434
+
435
+ ws.on('close', () => {
436
+ if (inactivityTimer) clearTimeout(inactivityTimer);
437
+ if (!finished) {
438
+ reject(new CliError('WebSocket closed before completion.', {
439
+ code: 'WEBSOCKET_CLOSED',
440
+ exitCode: EXIT_CODES.SERVER,
441
+ }));
442
+ } else {
443
+ resolve();
444
+ }
445
+ });
446
+
447
+ ws.on('error', (err) => {
448
+ if (inactivityTimer) clearTimeout(inactivityTimer);
449
+ reject(err);
450
+ });
451
+ });
452
+ }
453
+
454
+ async function handleToolsCall(opts) {
455
+ const config = loadConfig();
456
+ const apiKey = requireApiKey(opts, config);
457
+ const apiBase = resolveApiBase(opts, config);
458
+ const supabaseUrl = resolveLegacyUrl(resolveSupabaseUrl(opts, config), 'SOCIALSEAL_SUPABASE_URL');
459
+ const { resolvedApiBase, legacyUrl, useGateway } = resolveApiTarget({ apiBase, legacyUrl: supabaseUrl });
460
+ const timeoutMs = resolveTimeoutMs(opts, config);
461
+
462
+ const payload = parseJsonInput(opts.body, { label: 'body' }) ?? {};
463
+ const method = normalizeMethod(opts.method);
464
+ const res = await callApi({
465
+ apiBase: useGateway ? resolvedApiBase : legacyUrl,
466
+ apiKey,
467
+ path: useGateway ? `/cli/tools/${opts.function}` : `/functions/v1/${opts.function}`,
468
+ method,
469
+ body: payload,
470
+ workspaceId: opts.workspaceId,
471
+ timeoutMs,
472
+ });
473
+
474
+ if (!res.ok) {
475
+ throw await buildHttpError(res, {
476
+ label: 'Tool call',
477
+ functionName: opts.function,
478
+ method,
479
+ });
480
+ }
481
+
482
+ const contentType = res.headers.get('content-type') || '';
483
+ if (contentType.includes('application/json')) {
484
+ const data = await res.json();
485
+ process.stdout.write(JSON.stringify(data, null, opts.pretty ? 2 : 0) + '\n');
486
+ return;
487
+ }
488
+
489
+ const text = await res.text();
490
+ process.stdout.write(text);
491
+ }
492
+
493
+ function handleToolsList(opts) {
494
+ const payload = {
495
+ tools: KNOWN_TOOLS,
496
+ note: 'Tool discovery is disabled in the OSS CLI. Refer to official docs for supported tool names.',
497
+ };
498
+
499
+ if (opts.json) {
500
+ process.stdout.write(JSON.stringify(payload, null, opts.pretty ? 2 : 0) + '\n');
501
+ return;
502
+ }
503
+
504
+ process.stdout.write('[socialseal] Tool discovery is disabled in the OSS CLI.\n');
505
+ process.stdout.write(`[socialseal] ${payload.note}\n`);
506
+ }
507
+
508
+ async function handleDataExportTracking(opts) {
509
+ const config = loadConfig();
510
+ const apiKey = requireApiKey(opts, config);
511
+ const apiBase = resolveApiBase(opts, config);
512
+ const supabaseUrl = resolveLegacyUrl(resolveSupabaseUrl(opts, config), 'SOCIALSEAL_SUPABASE_URL');
513
+ const { resolvedApiBase, legacyUrl, useGateway } = resolveApiTarget({ apiBase, legacyUrl: supabaseUrl });
514
+ const timeoutMs = resolveTimeoutMs(opts, config);
515
+
516
+ if (!opts.groupId && !opts.itemId) {
517
+ throw new CliError('Provide --group-id or --item-id.', {
518
+ code: 'MISSING_ARGUMENT',
519
+ exitCode: EXIT_CODES.USAGE,
520
+ });
521
+ }
522
+
523
+ const payload = {
524
+ tracking_item_id: opts.itemId || undefined,
525
+ group_id: opts.groupId || undefined,
526
+ time_period: opts.timePeriod,
527
+ };
528
+
529
+ const res = await callApi({
530
+ apiBase: useGateway ? resolvedApiBase : legacyUrl,
531
+ apiKey,
532
+ path: useGateway ? '/cli/tools/export_tracking_data' : '/functions/v1/export_tracking_data',
533
+ method: 'POST',
534
+ body: payload,
535
+ workspaceId: opts.workspaceId,
536
+ timeoutMs,
537
+ });
538
+
539
+ if (!res.ok) {
540
+ throw await buildHttpError(res, { label: 'Tracking export' });
541
+ }
542
+
543
+ const outPath = opts.stdout ? null : (opts.out || 'tracking_export.csv');
544
+ if (outPath) {
545
+ await pipeline(res.body, fs.createWriteStream(outPath));
546
+ process.stderr.write(`[socialseal] CSV written to ${outPath}\n`);
547
+ } else {
548
+ await pipeline(res.body, process.stdout);
549
+ }
550
+ }
551
+
552
+ async function handleDataExportReport(opts) {
553
+ const config = loadConfig();
554
+ const apiKey = requireApiKey(opts, config);
555
+ const apiBase = resolveApiBase(opts, config);
556
+ const supabaseUrl = resolveLegacyUrl(resolveSupabaseUrl(opts, config), 'SOCIALSEAL_SUPABASE_URL');
557
+ const { resolvedApiBase, legacyUrl, useGateway } = resolveApiTarget({ apiBase, legacyUrl: supabaseUrl });
558
+ const timeoutMs = resolveTimeoutMs(opts, config);
559
+
560
+ const payload = ensureJsonObject(parseJsonInput(opts.payload, { label: 'payload' }), 'payload');
561
+
562
+ const res = await callApi({
563
+ apiBase: useGateway ? resolvedApiBase : legacyUrl,
564
+ apiKey,
565
+ path: useGateway ? '/cli/tools/export-report' : '/functions/v1/export-report',
566
+ method: 'POST',
567
+ body: {
568
+ reportType: opts.reportType,
569
+ format: opts.format,
570
+ payload,
571
+ },
572
+ workspaceId: opts.workspaceId,
573
+ timeoutMs,
574
+ });
575
+
576
+ if (!res.ok) {
577
+ throw await buildHttpError(res, { label: 'Report export' });
578
+ }
579
+
580
+ const json = await res.json();
581
+ if (!json?.artifact) {
582
+ process.stdout.write(JSON.stringify(json, null, opts.pretty ? 2 : 0) + '\n');
583
+ return;
584
+ }
585
+
586
+ const artifact = json.artifact;
587
+ if (artifact.contentBase64) {
588
+ const buffer = Buffer.from(artifact.contentBase64, 'base64');
589
+ const outPath = opts.stdout ? null : (opts.out || artifact.filename || 'export.bin');
590
+ if (outPath) {
591
+ fs.writeFileSync(outPath, buffer);
592
+ process.stderr.write(`[socialseal] Export written to ${outPath}\n`);
593
+ } else {
594
+ process.stdout.write(buffer);
595
+ }
596
+ return;
597
+ }
598
+
599
+ if (artifact.contentJson) {
600
+ const outPath = opts.stdout ? null : (opts.out || artifact.filename || 'export.json');
601
+ const jsonText = JSON.stringify(artifact.contentJson, null, opts.pretty ? 2 : 0);
602
+ if (outPath) {
603
+ fs.writeFileSync(outPath, jsonText);
604
+ process.stderr.write(`[socialseal] Export written to ${outPath}\n`);
605
+ } else {
606
+ process.stdout.write(jsonText + '\n');
607
+ }
608
+ return;
609
+ }
610
+
611
+ process.stdout.write(JSON.stringify(json, null, opts.pretty ? 2 : 0) + '\n');
612
+ }
613
+
614
+ const program = new Command();
615
+ program
616
+ .name('socialseal')
617
+ .description('SocialSeal CLI (non-interactive)')
618
+ .version('0.1.0');
619
+
620
+ if (typeof program.showHelpAfterError === 'function') {
621
+ program.showHelpAfterError(true);
622
+ }
623
+ if (typeof program.showSuggestionAfterError === 'function') {
624
+ program.showSuggestionAfterError(true);
625
+ }
626
+ program.addHelpText('after', `\nExamples:\n socialseal agent run --message \"ping\"\n socialseal tools list\n socialseal tools call --function <tool> --body @payload.json\n socialseal data export-tracking --group-id 123 --time-period 30d\n`);
627
+
628
+ program
629
+ .command('agent')
630
+ .description('Agent operations')
631
+ .command('run')
632
+ .requiredOption('-m, --message <text>', 'Message to send to the agent')
633
+ .option('--context <jsonOrFile>', 'Context JSON or @file.json')
634
+ .option('--api-base <url>', 'API base URL (default https://api.socialseal.co)')
635
+ .option('--api-key <key>', 'CLI API key')
636
+ .option('--workspace-id <id>', 'Workspace id (for scoped keys)')
637
+ .option('--conversation-id <id>', 'Conversation id to resume')
638
+ .option('--create-new', 'Create a new conversation')
639
+ .option('--json', 'Emit NDJSON events')
640
+ .option('--timeout <ms>', 'Request timeout in milliseconds')
641
+ .option('--verbose', 'Show error details')
642
+ .action((opts) => runCommand(handleAgentRun, opts));
643
+
644
+ const tools = program.command('tools').description('Call edge functions directly (tool backends)');
645
+
646
+ tools
647
+ .command('list')
648
+ .description('List tools (discovery disabled in OSS build)')
649
+ .option('--json', 'Emit machine-readable output')
650
+ .option('--pretty', 'Pretty-print JSON')
651
+ .option('--verbose', 'Show error details')
652
+ .action((opts) => runCommand(handleToolsList, opts));
653
+
654
+ tools
655
+ .command('call')
656
+ .requiredOption('--function <name>', 'Tool name (see official docs)')
657
+ .option('--method <method>', 'HTTP method', 'POST')
658
+ .option('--body <jsonOrFile>', 'JSON body or @file.json')
659
+ .option('--api-base <url>', 'API base URL (default https://api.socialseal.co)')
660
+ .option('--api-key <key>', 'CLI API key')
661
+ .option('--workspace-id <id>', 'Workspace id (for scoped keys)')
662
+ .option('--pretty', 'Pretty-print JSON')
663
+ .option('--json', 'Emit machine-readable errors')
664
+ .option('--timeout <ms>', 'Request timeout in milliseconds')
665
+ .option('--verbose', 'Show error details')
666
+ .action((opts) => runCommand(handleToolsCall, opts));
667
+
668
+ const data = program.command('data').description('Data exports (provisional)');
669
+
670
+ data
671
+ .command('export-tracking')
672
+ .description('Export tracking data as CSV')
673
+ .option('--group-id <id>', 'Tracking group id')
674
+ .option('--item-id <id>', 'Tracking item id')
675
+ .requiredOption('--time-period <value>', '7d|30d|90d|180d|365d|mtd')
676
+ .option('--out <path>', 'Output file path')
677
+ .option('--stdout', 'Write to stdout')
678
+ .option('--api-base <url>', 'API base URL (default https://api.socialseal.co)')
679
+ .option('--api-key <key>', 'CLI API key')
680
+ .option('--workspace-id <id>', 'Workspace id (for scoped keys)')
681
+ .option('--json', 'Emit machine-readable errors')
682
+ .option('--timeout <ms>', 'Request timeout in milliseconds')
683
+ .option('--verbose', 'Show error details')
684
+ .action((opts) => runCommand(handleDataExportTracking, opts));
685
+
686
+ data
687
+ .command('export-report')
688
+ .description('Export report data via export-report (provisional)')
689
+ .requiredOption('--report-type <type>', 'keyword_universe|cluster_insights|creator_signatures|post_publish|quick_audit')
690
+ .option('--format <format>', 'csv|json|markdown|html|excel_data', 'csv')
691
+ .requiredOption('--payload <jsonOrFile>', 'Payload JSON or @file.json')
692
+ .option('--out <path>', 'Output file path')
693
+ .option('--stdout', 'Write to stdout')
694
+ .option('--api-base <url>', 'API base URL (default https://api.socialseal.co)')
695
+ .option('--api-key <key>', 'CLI API key')
696
+ .option('--workspace-id <id>', 'Workspace id (for scoped keys)')
697
+ .option('--pretty', 'Pretty-print JSON')
698
+ .option('--json', 'Emit machine-readable errors')
699
+ .option('--timeout <ms>', 'Request timeout in milliseconds')
700
+ .option('--verbose', 'Show error details')
701
+ .action((opts) => runCommand(handleDataExportReport, opts));
702
+
703
+ program.parseAsync(process.argv);