deepsearch-so 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/dist/index.js +1076 -0
  4. package/package.json +54 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RELOAD TEKNOLOJI LIMITED SIRKETI
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 CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # Deep Search CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official command-line client for the [Deep Search](https://deepsearch.so) Developer
4
+ API, the people-search product at **deepsearch.so**, published by
5
+ RELOAD TEKNOLOJI LIMITED SIRKETI. It is a single self-contained package with no runtime dependencies
6
+ and shares the same scopes, wallet metering, and sandbox behavior as the REST API.
7
+
8
+ - Product: <https://deepsearch.so>
9
+ - API overview: <https://deepsearch.so/api>
10
+ - API reference: <https://deepsearch.so/api/docs>
11
+ - OpenAPI 3.1 spec: <https://deepsearch.so/openapi.json>
12
+ - Hosted MCP server: `https://deepsearch.so/api/mcp`
13
+
14
+ ```bash
15
+ npx deepsearch-so search "Ada Lovelace" --sandbox
16
+ ```
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install -g deepsearch-so # then: deepsearch --help
22
+ # or run without installing:
23
+ npx deepsearch-so --help
24
+ ```
25
+
26
+ Requires Node.js ≥ 20.9.
27
+
28
+ ## Authentication
29
+
30
+ The CLI resolves your API key in this order (highest priority first):
31
+
32
+ 1. `--api-key dsk_...`
33
+ 2. `DEEPSEARCH_API_KEY` environment variable
34
+ 3. `~/.deepsearch/config.json` (written by `deepsearch login`)
35
+
36
+ Create a key at <https://deepsearch.so/developers>, then store it once:
37
+
38
+ ```bash
39
+ deepsearch login # prompts for the key (hidden) and base URL
40
+ deepsearch login --api-key dsk_... --base-url https://deepsearch.so
41
+ ```
42
+
43
+ The config file is written with `0600` permissions. `deepsearch config get` masks the key.
44
+
45
+ The base URL resolves the same way (`--base-url` › `DEEPSEARCH_BASE_URL` › config › `https://deepsearch.so`).
46
+
47
+ ## Commands
48
+
49
+ | Command | Description |
50
+ | --- | --- |
51
+ | `search <query>` | Find people by `name`, `phone`, `email`, or `username` |
52
+ | `dossier <name>` | Build or replay a public-footprint dossier |
53
+ | `chat <name> <message...>` | Ask a follow-up question about a person |
54
+ | `jobs create <op>` | Queue an async job (`search`, `dossier`, or `chat`) |
55
+ | `jobs list` | List recent async jobs |
56
+ | `jobs get <id>` | Fetch one job by id |
57
+ | `jobs events <id>` | Replay a job's stored SSE event stream |
58
+ | `status` | Show developer API availability (no key required) |
59
+ | `login` | Save an API key and base URL to config |
60
+ | `config <get\|set\|path>` | Inspect or edit stored config |
61
+
62
+ ### Common options
63
+
64
+ | Flag | Effect |
65
+ | --- | --- |
66
+ | `--json` | Print the raw JSON envelope instead of formatted output |
67
+ | `--sandbox` | Use deterministic, unmetered Ada Lovelace fixtures |
68
+ | `--stream` | Stream live SSE events (`search`, `dossier`, `chat`) |
69
+ | `--api-key <key>` | Override the API key for one call |
70
+ | `--base-url <url>` | Override the API base URL |
71
+ | `-h, --help` / `-v, --version` | Help / version |
72
+
73
+ ## Examples
74
+
75
+ ```bash
76
+ # Name search, formatted
77
+ deepsearch search "Ada Lovelace" --sandbox
78
+
79
+ # Username search scoped to platforms, raw JSON
80
+ deepsearch search ada --type username --platforms linkedin,github --json
81
+
82
+ # Dossier, streaming progress as it scans
83
+ deepsearch dossier "Ada Lovelace" --stream
84
+
85
+ # Ask a question
86
+ deepsearch chat "Ada Lovelace" "Summarize the public sources" --sandbox
87
+
88
+ # Async job from a payload file, with idempotency
89
+ deepsearch jobs create dossier --input @job.json --idempotency-key demo-1
90
+ deepsearch jobs get job_123 --json
91
+
92
+ # Pipe a payload in
93
+ echo '{"query":"Grace Hopper","type":"name","format":"json"}' \
94
+ | deepsearch jobs create search --input -
95
+
96
+ # One-off key without storing anything
97
+ DEEPSEARCH_API_KEY=dsk_... deepsearch search "Grace Hopper"
98
+ ```
99
+
100
+ ## Output & exit codes
101
+
102
+ - Default output is human-formatted; usage/metering is printed to **stderr** so `--json`-free
103
+ output stays pipe-friendly. Add `--json` for the full typed envelope on **stdout**.
104
+ - Exit codes: `0` success, `1` runtime/API error (a `DeepSearchError` prints status, code, and
105
+ request id), `2` usage error (bad flags or missing arguments).
106
+
107
+ Use `--sandbox` while integrating: it requires a valid scoped key but returns deterministic
108
+ fixtures and never consumes usage.
109
+
110
+ Requests made with your API key send `X-DeepSearch-Client: deepsearch-cli/<version>`, the
111
+ version `deepsearch --version` prints. The value is self-reported and used only for aggregate
112
+ client analytics; it never affects authentication, rate limits or billing.
113
+
114
+ ## Not to be confused with
115
+
116
+ "Deep Search" is a contested name. This CLI talks to the people-search API at
117
+ **deepsearch.so** only. It is unrelated to xAI's Deep Search research feature and
118
+ to the Korean market-data API published on `deepsearch.com`. The `homepage` field
119
+ of this package is the check that settles it.
120
+
121
+ ## More commands
122
+
123
+ ```bash
124
+ deepsearch companies Northwind --sandbox --json
125
+ deepsearch company Northwind --sandbox --json
126
+ deepsearch reverse-image https://example.com/photo.jpg --sandbox --json
127
+ deepsearch vin 1HGCM82633A004352 --sandbox --json
128
+ deepsearch address "350 5th Ave, New York, NY 10118" --sandbox --json
129
+ deepsearch batch --input @operations.json --idempotency-key batch-1 --json
130
+ deepsearch jobs list --limit 25 --cursor '<next_cursor>' --json
131
+ deepsearch jobs events '<id>' --follow --after '<event-id>' --json
132
+ deepsearch jobs cancel '<id>' --json
133
+ deepsearch jobs result '<id>' --json
134
+ ```
135
+
136
+ Job operation IDs are `search`, `dossier`, `chat`, `entity_search`, `entity_dossier`, `reverse_image`, `vin` and `address`. `address` builds a property & place report for a street address; it never names the people who live there. `--timeout` is in seconds. `--idempotency-key` also applies to ordinary JSON operations. Streams never restart automatically. Public sandbox jobs return completed fixtures immediately.
package/dist/index.js ADDED
@@ -0,0 +1,1076 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { parseArgs } from "node:util";
5
+ import { readFileSync as readFileSync2 } from "node:fs";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { stdin, stdout } from "node:process";
8
+
9
+ // ../typescript/dist/version.generated.js
10
+ var SDK_VERSION = "0.1.1";
11
+
12
+ // ../typescript/dist/index.js
13
+ var CLIENT_HEADER = "X-DeepSearch-Client";
14
+ var DeepSearchError = class extends Error {
15
+ status;
16
+ code;
17
+ requestId;
18
+ body;
19
+ headers;
20
+ constructor(message, input) {
21
+ super(message);
22
+ this.name = "DeepSearchError";
23
+ this.status = input.status;
24
+ this.code = input.code;
25
+ this.requestId = input.requestId;
26
+ this.body = input.body;
27
+ this.headers = input.headers ?? new Headers();
28
+ }
29
+ };
30
+ var uniqueKey = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
31
+ var retriable = /* @__PURE__ */ new Set([429, 502, 503, 504]);
32
+ var delay = (ms, signal) => new Promise((resolve, reject) => {
33
+ const timer = setTimeout(done, ms);
34
+ function done() {
35
+ signal.removeEventListener("abort", abort);
36
+ resolve();
37
+ }
38
+ function abort() {
39
+ clearTimeout(timer);
40
+ signal.removeEventListener("abort", abort);
41
+ reject(signal.reason);
42
+ }
43
+ signal.addEventListener("abort", abort, { once: true });
44
+ if (signal.aborted)
45
+ abort();
46
+ });
47
+ var DeepSearchClient = class {
48
+ config;
49
+ baseUrl;
50
+ fetchImpl;
51
+ constructor(options) {
52
+ if (!options.apiKey)
53
+ throw new Error("Deep Search API key is required.");
54
+ this.config = options;
55
+ this.baseUrl = (options.baseUrl ?? "https://deepsearch.so").replace(/\/$/, "");
56
+ this.fetchImpl = options.fetch ?? fetch;
57
+ }
58
+ search(input, options) {
59
+ return this.json("/api/v1/search", { ...input, format: "json" }, options);
60
+ }
61
+ dossier(input, options) {
62
+ return this.json("/api/v1/dossier", { ...input, format: "json" }, options);
63
+ }
64
+ chat(input, options) {
65
+ return this.json("/api/v1/chat", { ...input, format: "json" }, options);
66
+ }
67
+ searchCompanies(input, options) {
68
+ return this.json("/api/v1/entity/search", { ...input, format: "json" }, options);
69
+ }
70
+ companyDossier(input, options) {
71
+ return this.json("/api/v1/entity/dossier", { ...input, format: "json" }, options);
72
+ }
73
+ reverseImage(input, options) {
74
+ return this.json("/api/v1/reverse-image", { ...input, format: "json" }, options);
75
+ }
76
+ vin(input, options) {
77
+ return this.json("/api/v1/vin", { ...input, format: "json" }, options);
78
+ }
79
+ /** A property & place report for one street address. It describes the place and never names the people who live there. Every call is a fresh, metered build. */
80
+ address(input, options) {
81
+ return this.json("/api/v1/address", { ...input, format: "json" }, options);
82
+ }
83
+ /** Cited deep research on a public topic, company or vehicle. Runs take minutes; prefer createJob for long-lived work. */
84
+ research(input, options) {
85
+ return this.json("/api/v1/research", { ...input, format: "json" }, options);
86
+ }
87
+ searchStream(input, options) {
88
+ return this.stream("/api/v1/search", { ...input, format: "sse" }, options);
89
+ }
90
+ dossierStream(input, options) {
91
+ return this.stream("/api/v1/dossier", { ...input, format: "sse" }, options);
92
+ }
93
+ chatStream(input, options) {
94
+ return this.stream("/api/v1/chat", { ...input, format: "sse" }, options);
95
+ }
96
+ companySearchStream(input, options) {
97
+ return this.stream("/api/v1/entity/search", { ...input, format: "sse" }, options);
98
+ }
99
+ companyDossierStream(input, options) {
100
+ return this.stream("/api/v1/entity/dossier", { ...input, format: "sse" }, options);
101
+ }
102
+ reverseImageStream(input, options) {
103
+ return this.stream("/api/v1/reverse-image", { ...input, format: "sse" }, options);
104
+ }
105
+ vinStream(input, options) {
106
+ return this.stream("/api/v1/vin", { ...input, format: "sse" }, options);
107
+ }
108
+ addressStream(input, options) {
109
+ return this.stream("/api/v1/address", { ...input, format: "sse" }, options);
110
+ }
111
+ researchStream(input, options) {
112
+ return this.stream("/api/v1/research", { ...input, format: "sse" }, options);
113
+ }
114
+ batch(operations, options) {
115
+ return this.json("/api/v1/batch", { operations }, options);
116
+ }
117
+ createJob(input, options) {
118
+ return this.json("/api/v1/jobs", { ...input }, options);
119
+ }
120
+ listJobs(options) {
121
+ const query = new URLSearchParams();
122
+ if (options?.limit)
123
+ query.set("limit", String(options.limit));
124
+ if (options?.cursor)
125
+ query.set("cursor", options.cursor);
126
+ return this.json(`/api/v1/jobs?${query}`, void 0, options);
127
+ }
128
+ getJob(id, options) {
129
+ return this.json(`/api/v1/jobs/${encodeURIComponent(id)}`, void 0, options);
130
+ }
131
+ cancelJob(id, options) {
132
+ return this.json(`/api/v1/jobs/${encodeURIComponent(id)}/cancel`, {}, options);
133
+ }
134
+ async jobResult(id, options) {
135
+ const { job } = await this.getJob(id, options);
136
+ if (job.status !== "succeeded")
137
+ throw new DeepSearchError(job.error ?? "Job result is not ready.", { status: 409, code: "job_not_succeeded", body: job });
138
+ return job.result;
139
+ }
140
+ jobEvents(id, options) {
141
+ const query = new URLSearchParams();
142
+ if (options?.after !== void 0)
143
+ query.set("after", String(options.after));
144
+ if (options?.follow)
145
+ query.set("follow", "1");
146
+ return this.stream(`/api/v1/jobs/${encodeURIComponent(id)}/events?${query}`, void 0, options);
147
+ }
148
+ async *allJobs(options) {
149
+ let cursor;
150
+ do {
151
+ const page = await this.listJobs({ ...options, cursor });
152
+ yield* page.jobs;
153
+ cursor = page.has_more ? page.next_cursor ?? void 0 : void 0;
154
+ } while (cursor);
155
+ }
156
+ connection(options = {}) {
157
+ const controller = new AbortController(), signal = options.signal;
158
+ const abort = () => controller.abort(signal?.reason);
159
+ signal?.addEventListener("abort", abort, { once: true });
160
+ if (signal?.aborted)
161
+ abort();
162
+ const timeout = options.timeoutMs ?? this.config.timeoutMs ?? 12e4;
163
+ const timer = timeout > 0 ? setTimeout(() => controller.abort(new Error("Deep Search request timed out.")), timeout) : void 0;
164
+ return { signal: controller.signal, cleanup: () => {
165
+ clearTimeout(timer);
166
+ signal?.removeEventListener("abort", abort);
167
+ } };
168
+ }
169
+ headers(options) {
170
+ return { ...identify(this.config.defaultHeaders), Authorization: `Bearer ${this.config.apiKey}`, "Content-Type": "application/json", ...options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}, ...options?.requestId ? { "X-Request-Id": options.requestId } : {}, ...options?.sandbox ? { "X-DeepSearch-Sandbox": "true" } : {} };
171
+ }
172
+ async json(path, body, options = {}) {
173
+ const opts = { ...options, ...body ? { idempotencyKey: options.idempotencyKey ?? uniqueKey() } : {} }, connection = this.connection(opts), retries = Math.max(0, Math.min(5, options.maxRetries ?? this.config.maxRetries ?? 2));
174
+ try {
175
+ for (let attempt = 0; ; attempt++) {
176
+ let res;
177
+ try {
178
+ res = await this.fetchImpl(`${this.baseUrl}${path}`, { method: body ? "POST" : "GET", headers: this.headers(opts), body: body ? JSON.stringify({ ...body, sandbox: opts.sandbox ?? body.sandbox }) : void 0, signal: connection.signal });
179
+ } catch (error) {
180
+ if (attempt >= retries || connection.signal.aborted)
181
+ throw error;
182
+ await delay(250 * 2 ** attempt, connection.signal);
183
+ continue;
184
+ }
185
+ options.onResponse?.({ status: res.status, requestId: res.headers.get("x-request-id"), headers: new Headers(res.headers) });
186
+ if (attempt < retries && (retriable.has(res.status) || res.status === 409 && res.headers.has("retry-after"))) {
187
+ const wait = retryDelay(res, attempt);
188
+ await res.body?.cancel();
189
+ await delay(wait, connection.signal);
190
+ continue;
191
+ }
192
+ const parsed = await safeJson(res);
193
+ if (!res.ok)
194
+ throw toError(res, parsed);
195
+ return parsed;
196
+ }
197
+ } finally {
198
+ connection.cleanup();
199
+ }
200
+ }
201
+ async *stream(path, body, options = {}) {
202
+ const connection = this.connection(options);
203
+ try {
204
+ const res = await this.fetchImpl(`${this.baseUrl}${path}`, { method: body ? "POST" : "GET", headers: { ...this.headers(options), Accept: "text/event-stream" }, body: body ? JSON.stringify({ ...body, sandbox: options.sandbox ?? body.sandbox }) : void 0, signal: connection.signal });
205
+ options.onResponse?.({ status: res.status, requestId: res.headers.get("x-request-id"), headers: new Headers(res.headers) });
206
+ yield* parseEventStream(res, { requireTerminal: !path.includes("/events") });
207
+ } finally {
208
+ connection.cleanup();
209
+ }
210
+ }
211
+ };
212
+ function identify(defaults = {}) {
213
+ const named = Object.keys(defaults).filter((key) => key.toLowerCase() === CLIENT_HEADER.toLowerCase());
214
+ if (!named.length)
215
+ return { [CLIENT_HEADER]: `deepsearch-typescript/${SDK_VERSION}`, ...defaults };
216
+ return Object.fromEntries(Object.entries(defaults).filter(([key, value]) => !named.includes(key) || String(value ?? "").trim() !== ""));
217
+ }
218
+ function retryDelay(res, attempt) {
219
+ const raw = res.headers.get("retry-after"), seconds = raw ? Number(raw) : NaN;
220
+ const ms = Number.isFinite(seconds) ? seconds * 1e3 : raw ? Date.parse(raw) - Date.now() : 250 * 2 ** attempt;
221
+ return Math.max(100, Number.isFinite(ms) ? ms : 250);
222
+ }
223
+ async function safeJson(res) {
224
+ const text = await res.text();
225
+ if (!text)
226
+ return null;
227
+ try {
228
+ return JSON.parse(text);
229
+ } catch {
230
+ return { error: { message: text } };
231
+ }
232
+ }
233
+ function toError(res, body) {
234
+ const error = body?.error;
235
+ return new DeepSearchError(error?.message ?? `Deep Search request failed with ${res.status}`, { status: res.status, code: error?.code, requestId: res.headers.get("x-request-id"), body, headers: new Headers(res.headers) });
236
+ }
237
+ async function* parseEventStream(res, options = {}) {
238
+ if (!res.ok)
239
+ throw toError(res, await safeJson(res));
240
+ if (!res.body)
241
+ throw new DeepSearchError("Stream has no body.", { status: res.status, code: "invalid_stream", body: null });
242
+ if (!res.headers.get("content-type")?.includes("text/event-stream"))
243
+ throw new DeepSearchError("Expected an SSE response.", { status: res.status, code: "invalid_stream", body: null });
244
+ const reader = res.body.getReader(), decoder = new TextDecoder("utf-8", { fatal: true });
245
+ let buffer = "", data = [], id, finished = false, terminal = false;
246
+ function frame() {
247
+ const payload = data.join("\n");
248
+ data = [];
249
+ if (!payload)
250
+ return null;
251
+ if (payload === "[DONE]") {
252
+ terminal = true;
253
+ return null;
254
+ }
255
+ let event;
256
+ try {
257
+ event = JSON.parse(payload);
258
+ } catch {
259
+ throw new DeepSearchError("Malformed SSE JSON.", { status: res.status, code: "invalid_stream_payload", body: payload });
260
+ }
261
+ if (!event || typeof event !== "object" || typeof event.type !== "string")
262
+ throw new DeepSearchError("Invalid SSE event.", { status: res.status, code: "invalid_stream_payload", body: event });
263
+ if (event.type === "error")
264
+ throw new DeepSearchError(String(event.message ?? "Stream failed."), { status: res.status, code: typeof event.code === "string" ? event.code : "stream_error", requestId: res.headers.get("x-request-id"), body: event });
265
+ if (event.type === "done" || event.type === "job_status" && ["succeeded", "failed", "cancelled"].includes(String(event.status)))
266
+ terminal = true;
267
+ return { ...event, ...id ? { event_id: id } : {} };
268
+ }
269
+ try {
270
+ while (true) {
271
+ const part = await reader.read();
272
+ try {
273
+ buffer += decoder.decode(part.value, { stream: !part.done });
274
+ } catch {
275
+ throw new DeepSearchError("Malformed UTF-8 in SSE.", { status: res.status, code: "invalid_stream_payload", body: null });
276
+ }
277
+ let match;
278
+ while (match = /\r\n|\n|\r/.exec(buffer)) {
279
+ if (match[0] === "\r" && match.index === buffer.length - 1 && !part.done)
280
+ break;
281
+ const line = buffer.slice(0, match.index);
282
+ buffer = buffer.slice(match.index + match[0].length);
283
+ if (!line) {
284
+ const event = frame();
285
+ if (event)
286
+ yield event;
287
+ continue;
288
+ }
289
+ if (line.startsWith(":"))
290
+ continue;
291
+ const colon = line.indexOf(":"), key = colon < 0 ? line : line.slice(0, colon), value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
292
+ if (key === "data")
293
+ data.push(value);
294
+ else if (key === "id" && !value.includes("\0"))
295
+ id = value;
296
+ }
297
+ if (buffer.length + data.join("\n").length > 1048576)
298
+ throw new DeepSearchError("SSE frame is too large.", { status: res.status, code: "invalid_stream_payload", body: null });
299
+ if (part.done) {
300
+ finished = true;
301
+ if (buffer || data.length)
302
+ throw new DeepSearchError("Stream disconnected mid-frame.", { status: res.status, code: "stream_disconnected", body: null });
303
+ break;
304
+ }
305
+ }
306
+ if (!terminal && options.requireTerminal !== false)
307
+ throw new DeepSearchError("Stream ended before completion.", { status: res.status, code: "stream_disconnected", body: null });
308
+ } finally {
309
+ if (!finished)
310
+ await reader.cancel().catch(() => {
311
+ });
312
+ reader.releaseLock();
313
+ }
314
+ }
315
+
316
+ // src/config.ts
317
+ import { homedir } from "node:os";
318
+ import { join } from "node:path";
319
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
320
+ var DEFAULT_BASE_URL = "https://deepsearch.so";
321
+ function configDir() {
322
+ return process.env.DEEPSEARCH_CONFIG_DIR ?? join(homedir(), ".deepsearch");
323
+ }
324
+ function configPath() {
325
+ return join(configDir(), "config.json");
326
+ }
327
+ function readConfig() {
328
+ try {
329
+ const raw = readFileSync(configPath(), "utf8");
330
+ const parsed = JSON.parse(raw);
331
+ return parsed && typeof parsed === "object" ? parsed : {};
332
+ } catch {
333
+ return {};
334
+ }
335
+ }
336
+ function writeConfig(next) {
337
+ const dir = configDir();
338
+ mkdirSync(dir, { recursive: true, mode: 448 });
339
+ const path = configPath();
340
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}
341
+ `, { mode: 384 });
342
+ chmodSync(path, 384);
343
+ }
344
+ function resolveBaseUrl(overrides = {}, config = readConfig()) {
345
+ const baseUrl = overrides.baseUrl ?? process.env.DEEPSEARCH_BASE_URL ?? config.baseUrl ?? DEFAULT_BASE_URL;
346
+ return baseUrl.replace(/\/$/, "");
347
+ }
348
+ function resolveAuth(overrides = {}) {
349
+ const config = readConfig();
350
+ const apiKey = overrides.apiKey ?? process.env.DEEPSEARCH_API_KEY ?? config.apiKey;
351
+ const baseUrl = resolveBaseUrl(overrides, config);
352
+ if (!apiKey) {
353
+ throw new MissingApiKeyError();
354
+ }
355
+ return { apiKey, baseUrl };
356
+ }
357
+ var MissingApiKeyError = class extends Error {
358
+ constructor() {
359
+ super(
360
+ [
361
+ "No Deep Search API key found.",
362
+ "",
363
+ "Provide one with any of:",
364
+ " \u2022 deepsearch login (stores it in ~/.deepsearch/config.json)",
365
+ " \u2022 export DEEPSEARCH_API_KEY=dsk_...",
366
+ " \u2022 --api-key dsk_...",
367
+ "",
368
+ "Create a key at https://deepsearch.so/developers"
369
+ ].join("\n")
370
+ );
371
+ this.name = "MissingApiKeyError";
372
+ }
373
+ };
374
+
375
+ // src/render.ts
376
+ var useColor = process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb" && process.stdout.isTTY === true;
377
+ function paint(code, text) {
378
+ return useColor ? `\x1B[${code}m${text}\x1B[0m` : text;
379
+ }
380
+ var c = {
381
+ bold: (t) => paint(1, t),
382
+ dim: (t) => paint(2, t),
383
+ red: (t) => paint(31, t),
384
+ green: (t) => paint(32, t),
385
+ yellow: (t) => paint(33, t),
386
+ blue: (t) => paint(34, t),
387
+ cyan: (t) => paint(36, t)
388
+ };
389
+ function printJson(value) {
390
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
391
+ `);
392
+ }
393
+ function asString(value) {
394
+ return typeof value === "string" && value.length > 0 ? value : void 0;
395
+ }
396
+ function asNumber(value) {
397
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
398
+ }
399
+ function renderHits(hits) {
400
+ if (hits.length === 0) {
401
+ process.stdout.write(`${c.dim("No matches found.")}
402
+ `);
403
+ return;
404
+ }
405
+ hits.forEach((hit, index) => {
406
+ const name = asString(hit.name) ?? asString(hit.id) ?? "(unnamed)";
407
+ const confidence = asNumber(hit.confidence);
408
+ const id = asString(hit.id);
409
+ const tags = Array.isArray(hit.tags) ? hit.tags.filter((t) => typeof t === "string") : [];
410
+ const headline = asString(hit.headline) ?? asString(hit.title) ?? asString(hit.summary);
411
+ const conf = confidence !== void 0 ? c.dim(` ${confidence}% confidence`) : "";
412
+ process.stdout.write(`${c.bold(`${index + 1}. ${name}`)}${conf}
413
+ `);
414
+ if (headline) process.stdout.write(` ${headline}
415
+ `);
416
+ if (tags.length > 0) process.stdout.write(` ${c.cyan(tags.join(" \xB7 "))}
417
+ `);
418
+ if (id) process.stdout.write(` ${c.dim(`id: ${id}`)}
419
+ `);
420
+ process.stdout.write("\n");
421
+ });
422
+ }
423
+ function renderDossier(dossier) {
424
+ if (dossier.summary) {
425
+ process.stdout.write(`${c.bold("Summary")}
426
+ ${dossier.summary}
427
+
428
+ `);
429
+ }
430
+ const sectionEntries = Object.entries(dossier.sections ?? {});
431
+ for (const [key, value] of sectionEntries) {
432
+ process.stdout.write(`${c.bold(titleCase(key))}
433
+ `);
434
+ process.stdout.write(`${renderSectionValue(value)}
435
+
436
+ `);
437
+ }
438
+ const sources = dossier.sources ?? [];
439
+ if (sources.length > 0) {
440
+ process.stdout.write(`${c.bold(`Sources (${sources.length})`)}
441
+ `);
442
+ for (const source of sources) {
443
+ const label = asString(source.title) ?? asString(source.name) ?? asString(source.label) ?? "source";
444
+ const url = asString(source.url) ?? asString(source.href);
445
+ process.stdout.write(` \u2022 ${label}${url ? c.dim(` ${url}`) : ""}
446
+ `);
447
+ }
448
+ process.stdout.write("\n");
449
+ }
450
+ }
451
+ function renderChat(answer, related) {
452
+ process.stdout.write(`${answer}
453
+ `);
454
+ if (related.length > 0) {
455
+ process.stdout.write(`
456
+ ${c.bold("Related questions")}
457
+ `);
458
+ for (const q of related) process.stdout.write(` \u2022 ${q}
459
+ `);
460
+ }
461
+ }
462
+ function renderUsage(usage) {
463
+ const parts = [];
464
+ if (usage.sandbox) parts.push("sandbox");
465
+ if (usage.cached) parts.push("cached");
466
+ if (usage.metered === false) parts.push("not metered");
467
+ else if (usage.percentageCharged !== void 0) {
468
+ parts.push(`${usage.percentageCharged}% charged`);
469
+ } else if (usage.credits !== void 0) {
470
+ parts.push(`${usage.credits} compatibility credit${usage.credits === 1 ? "" : "s"}`);
471
+ }
472
+ if (usage.remainingPercent !== void 0) parts.push(`${usage.remainingPercent}% remaining`);
473
+ if (usage.resetAt) parts.push(`resets ${new Date(usage.resetAt).toLocaleDateString()}`);
474
+ if (usage.source) parts.push(`via ${usage.source}`);
475
+ else if (usage.allowanceSource) parts.push(`via ${usage.allowanceSource}`);
476
+ if (parts.length > 0) process.stderr.write(`${c.dim(parts.join(" \xB7 "))}
477
+ `);
478
+ }
479
+ function renderEvent(event) {
480
+ switch (event.type) {
481
+ case "status":
482
+ process.stderr.write(`${c.dim(`\u2026 ${asString(event.label) ?? "working"}`)}
483
+ `);
484
+ break;
485
+ case "hit": {
486
+ const hit = event.hit ?? {};
487
+ process.stdout.write(`${c.green("\u2713")} ${asString(hit.name) ?? asString(hit.id) ?? "hit"}
488
+ `);
489
+ break;
490
+ }
491
+ case "token":
492
+ case "delta": {
493
+ const text = asString(event.text) ?? asString(event.content) ?? asString(event.delta);
494
+ if (text) process.stdout.write(text);
495
+ break;
496
+ }
497
+ case "error":
498
+ process.stderr.write(`${c.red("error")} ${asString(event.message) ?? JSON.stringify(event)}
499
+ `);
500
+ break;
501
+ case "done":
502
+ break;
503
+ default:
504
+ process.stderr.write(`${c.dim(JSON.stringify(event))}
505
+ `);
506
+ }
507
+ }
508
+ function renderSectionValue(value, indent = " ") {
509
+ if (value == null) return `${indent}${c.dim("\u2014")}`;
510
+ if (typeof value === "string") return `${indent}${value}`;
511
+ if (typeof value === "number" || typeof value === "boolean") return `${indent}${String(value)}`;
512
+ if (Array.isArray(value)) {
513
+ return value.map((item) => `${indent}\u2022 ${flatten(item)}`).join("\n");
514
+ }
515
+ if (typeof value === "object") {
516
+ return Object.entries(value).map(([k, v]) => `${indent}${c.dim(`${titleCase(k)}:`)} ${flatten(v)}`).join("\n");
517
+ }
518
+ return `${indent}${String(value)}`;
519
+ }
520
+ function flatten(value) {
521
+ if (value == null) return "";
522
+ if (typeof value === "string") return value;
523
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
524
+ return JSON.stringify(value);
525
+ }
526
+ function titleCase(key) {
527
+ return key.replace(/[_-]+/g, " ").replace(/\b\w/g, (m) => m.toUpperCase()).trim();
528
+ }
529
+
530
+ // src/index.ts
531
+ var interruptController = new AbortController();
532
+ process.once("SIGINT", () => interruptController.abort(new Error("Interrupted.")));
533
+ var VERSION = readPackageVersion();
534
+ var HELP = `${c.bold("deepsearch")} \u2014 command-line client for the Deep Search Developer API
535
+
536
+ ${c.bold("Usage")}
537
+ deepsearch <command> [arguments] [options]
538
+
539
+ ${c.bold("Commands")}
540
+ search <query> Find people by name, phone, email, or username
541
+ dossier <name> Build or replay a public-footprint dossier
542
+ chat <name> <message...> Ask a question about a person
543
+ companies <query> Search companies
544
+ company <name> Build a company dossier
545
+ reverse-image <url> Find public image appearances
546
+ vin <vin> Decode a vehicle VIN
547
+ address <address> Property & place report (never names residents)
548
+ batch --input <json> Run up to ten operations
549
+ jobs create <op> Queue any lookup operation
550
+ jobs list List recent async jobs
551
+ jobs get <id> Fetch one job by id
552
+ jobs events <id> Replay progress (--follow, --after <event-id>)
553
+ jobs cancel <id> Cancel a queued or running job
554
+ jobs result <id> Get a completed result
555
+ status Show developer API availability
556
+ login Save an API key (and base URL) to config
557
+ config <get|set|path> Inspect or edit stored config
558
+ help [command] Show help
559
+
560
+ ${c.bold("Common options")}
561
+ --json Print the raw JSON envelope instead of formatted output
562
+ --sandbox Use deterministic, unmetered Ada Lovelace fixtures
563
+ --stream Stream SSE events for any lookup
564
+ --api-key <key> Override the API key for this call
565
+ --base-url <url> Override the API base URL (default https://deepsearch.so)
566
+ -h, --help Show help
567
+ -v, --version Show version
568
+
569
+ ${c.bold("Search options")}
570
+ -t, --type <type> name | phone | email | username (default: name)
571
+ --platforms <a,b> Comma-separated platform focus for username searches
572
+
573
+ ${c.bold("Dossier options")}
574
+ --person <json> Full PersonHit JSON (defaults to { name })
575
+ --refresh Bypass the dossier cache and run a fresh scan
576
+
577
+ ${c.bold("Chat options")}
578
+ --context <text> Extra context to ground the answer
579
+ --direct Answer directly without an extra research pass
580
+
581
+ ${c.bold("Job options")}
582
+ --input <json|@file|-> Job input payload (file path or - for stdin)
583
+ --idempotency-key <k> Protect requests against duplicates
584
+ --metadata <json> Arbitrary metadata to attach to the job
585
+
586
+ ${c.bold("Examples")}
587
+ deepsearch search "Ada Lovelace" --sandbox
588
+ deepsearch search ada --type username --platforms linkedin,github
589
+ deepsearch dossier "Ada Lovelace" --sandbox --refresh
590
+ deepsearch chat "Ada Lovelace" "Summarize the public sources" --sandbox
591
+ deepsearch jobs create dossier --input @job.json --idempotency-key demo-1
592
+ DEEPSEARCH_API_KEY=dsk_... deepsearch search "Grace Hopper"
593
+
594
+ Create an API key at https://deepsearch.so/developers
595
+ `;
596
+ async function main(argv) {
597
+ let parsed;
598
+ try {
599
+ parsed = parseArgs({
600
+ args: argv,
601
+ allowPositionals: true,
602
+ strict: true,
603
+ options: {
604
+ json: { type: "boolean" },
605
+ sandbox: { type: "boolean" },
606
+ stream: { type: "boolean" },
607
+ help: { type: "boolean", short: "h" },
608
+ version: { type: "boolean", short: "v" },
609
+ "api-key": { type: "string" },
610
+ "base-url": { type: "string" },
611
+ type: { type: "string", short: "t" },
612
+ platforms: { type: "string" },
613
+ refresh: { type: "boolean" },
614
+ person: { type: "string" },
615
+ context: { type: "string" },
616
+ direct: { type: "boolean" },
617
+ input: { type: "string" },
618
+ "idempotency-key": { type: "string" },
619
+ metadata: { type: "string" },
620
+ timeout: { type: "string" },
621
+ limit: { type: "string" },
622
+ cursor: { type: "string" },
623
+ follow: { type: "boolean" },
624
+ after: { type: "string" },
625
+ company: { type: "string" }
626
+ }
627
+ });
628
+ } catch (error) {
629
+ process.stderr.write(`${c.red("error")} ${error.message}
630
+ `);
631
+ return 2;
632
+ }
633
+ const { values, positionals } = parsed;
634
+ const command = positionals[0];
635
+ if (values.version) {
636
+ stdout.write(`${VERSION}
637
+ `);
638
+ return 0;
639
+ }
640
+ if (values.help || !command || command === "help") {
641
+ stdout.write(`${HELP}
642
+ `);
643
+ return 0;
644
+ }
645
+ const overrides = {
646
+ apiKey: values["api-key"],
647
+ baseUrl: values["base-url"]
648
+ };
649
+ const asJson = values.json === true;
650
+ const sandbox = values.sandbox === true;
651
+ const stream = values.stream === true;
652
+ switch (command) {
653
+ case "search":
654
+ return runSearch(positionals.slice(1), values, overrides, { asJson, sandbox, stream });
655
+ case "dossier":
656
+ return runDossier(positionals.slice(1), values, overrides, { asJson, sandbox, stream });
657
+ case "chat":
658
+ return runChat(positionals.slice(1), values, overrides, { asJson, sandbox, stream });
659
+ case "companies":
660
+ case "company":
661
+ case "reverse-image":
662
+ case "vin":
663
+ case "address":
664
+ case "batch":
665
+ return runExtended(command, positionals.slice(1), values, overrides, { asJson, sandbox, stream });
666
+ case "jobs":
667
+ return runJobs(positionals.slice(1), values, overrides, { asJson, sandbox });
668
+ case "status":
669
+ return runStatus(overrides, asJson);
670
+ case "login":
671
+ return runLogin(overrides);
672
+ case "config":
673
+ return runConfig(positionals.slice(1));
674
+ default:
675
+ process.stderr.write(`${c.red("error")} unknown command "${command}". Run "deepsearch help".
676
+ `);
677
+ return 2;
678
+ }
679
+ }
680
+ function makeClient(overrides, values = {}) {
681
+ const { apiKey, baseUrl } = resolveAuth(overrides);
682
+ const timeoutMs = values.timeout === void 0 ? void 0 : Number(values.timeout) * 1e3;
683
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new Error("--timeout must be a positive number of seconds");
684
+ return new DeepSearchClient({ apiKey, baseUrl, timeoutMs, defaultHeaders: { [CLIENT_HEADER]: `deepsearch-cli/${VERSION}` } });
685
+ }
686
+ async function runSearch(args, values, overrides, flags) {
687
+ const query = args.join(" ").trim();
688
+ if (!query) {
689
+ process.stderr.write(`${c.red("error")} a search query is required.
690
+ `);
691
+ return 2;
692
+ }
693
+ const type = values.type ?? "name";
694
+ const platformsRaw = values.platforms;
695
+ const platforms = platformsRaw ? platformsRaw.split(",").map((p) => p.trim()).filter(Boolean) : void 0;
696
+ const client = makeClient(overrides, values);
697
+ const input = { query, type, platforms };
698
+ if (flags.stream) {
699
+ for await (const event of client.searchStream(input, requestOptions(values, flags))) {
700
+ renderEvent(event);
701
+ }
702
+ return 0;
703
+ }
704
+ const result = await client.search(input, requestOptions(values, flags));
705
+ if (flags.asJson) {
706
+ printJson(result);
707
+ } else {
708
+ renderHits(result.hits);
709
+ renderUsage(result.usage);
710
+ }
711
+ return 0;
712
+ }
713
+ async function runDossier(args, values, overrides, flags) {
714
+ const person = resolvePerson(args.join(" ").trim(), values.person);
715
+ if (!person) {
716
+ process.stderr.write(`${c.red("error")} a person name or --person JSON is required.
717
+ `);
718
+ return 2;
719
+ }
720
+ const refresh = values.refresh === true;
721
+ const client = makeClient(overrides, values);
722
+ const input = { person, refresh };
723
+ if (flags.stream) {
724
+ for await (const event of client.dossierStream(input, requestOptions(values, flags))) {
725
+ renderEvent(event);
726
+ }
727
+ return 0;
728
+ }
729
+ const result = await client.dossier(input, requestOptions(values, flags));
730
+ if (flags.asJson) {
731
+ printJson(result);
732
+ } else {
733
+ renderDossier(result.dossier);
734
+ renderUsage({ ...result.usage, cached: result.cached });
735
+ }
736
+ return 0;
737
+ }
738
+ async function runChat(args, values, overrides, flags) {
739
+ const [name, ...rest] = args;
740
+ const message = rest.join(" ").trim();
741
+ if (!name || !message) {
742
+ process.stderr.write(`${c.red("error")} usage: deepsearch chat "<name>" "<message>"
743
+ `);
744
+ return 2;
745
+ }
746
+ const client = makeClient(overrides, values);
747
+ const input = {
748
+ person: { name },
749
+ messages: [{ role: "user", content: message }],
750
+ context: values.context,
751
+ direct: values.direct === true
752
+ };
753
+ if (flags.stream) {
754
+ for await (const event of client.chatStream(input, requestOptions(values, flags))) {
755
+ renderEvent(event);
756
+ }
757
+ stdout.write("\n");
758
+ return 0;
759
+ }
760
+ const result = await client.chat(input, requestOptions(values, flags));
761
+ if (flags.asJson) {
762
+ printJson(result);
763
+ } else {
764
+ renderChat(result.answer, result.related_questions ?? []);
765
+ renderUsage(result.usage);
766
+ }
767
+ return 0;
768
+ }
769
+ async function runJobs(args, values, overrides, flags) {
770
+ const sub = args[0];
771
+ const client = makeClient(overrides, values);
772
+ switch (sub) {
773
+ case "create": {
774
+ const operation = args[1];
775
+ if (!["search", "dossier", "chat", "entity_search", "entity_dossier", "reverse_image", "vin", "address"].includes(operation ?? "")) {
776
+ process.stderr.write(`${c.red("error")} usage: deepsearch jobs create <search|dossier|chat> --input <json>
777
+ `);
778
+ return 2;
779
+ }
780
+ const input = await readPayload(values.input);
781
+ if (input === void 0) {
782
+ process.stderr.write(`${c.red("error")} --input <json|@file|-> is required for jobs create.
783
+ `);
784
+ return 2;
785
+ }
786
+ const metadataRaw = values.metadata;
787
+ const metadata = metadataRaw ? JSON.parse(metadataRaw) : void 0;
788
+ const { job } = await client.createJob(
789
+ { operation, input, sandbox: flags.sandbox, metadata },
790
+ requestOptions(values, flags)
791
+ );
792
+ if (flags.asJson) printJson(job);
793
+ else printJobSummary(job);
794
+ return 0;
795
+ }
796
+ case "list": {
797
+ const page = await client.listJobs({ ...requestOptions(values, flags), cursor: values.cursor, limit: values.limit === void 0 ? void 0 : Number(values.limit) });
798
+ const { jobs } = page;
799
+ if (flags.asJson) {
800
+ printJson(page);
801
+ } else if (jobs.length === 0) {
802
+ stdout.write(`${c.dim("No jobs yet.")}
803
+ `);
804
+ } else {
805
+ for (const job of jobs) printJobSummary(job);
806
+ }
807
+ return 0;
808
+ }
809
+ case "get": {
810
+ const id = args[1];
811
+ if (!id) {
812
+ process.stderr.write(`${c.red("error")} usage: deepsearch jobs get <id>
813
+ `);
814
+ return 2;
815
+ }
816
+ const { job } = await client.getJob(id, requestOptions(values, flags));
817
+ if (flags.asJson) printJson(job);
818
+ else printJobSummary(job);
819
+ return 0;
820
+ }
821
+ case "cancel":
822
+ case "result": {
823
+ if (!args[1]) throw new Error("A job id is required");
824
+ printJson(sub === "cancel" ? await client.cancelJob(args[1], requestOptions(values, flags)) : await client.jobResult(args[1], requestOptions(values, flags)));
825
+ return 0;
826
+ }
827
+ case "events": {
828
+ const id = args[1];
829
+ if (!id) {
830
+ process.stderr.write(`${c.red("error")} usage: deepsearch jobs events <id>
831
+ `);
832
+ return 2;
833
+ }
834
+ for await (const event of client.jobEvents(id, { ...requestOptions(values, flags), follow: values.follow === true, after: values.after })) {
835
+ if (flags.asJson) printJson(event);
836
+ else renderEvent(event);
837
+ }
838
+ return 0;
839
+ }
840
+ default:
841
+ process.stderr.write(`${c.red("error")} usage: deepsearch jobs <create|list|get|events>
842
+ `);
843
+ return 2;
844
+ }
845
+ }
846
+ async function runStatus(overrides, asJson) {
847
+ const baseUrl = resolveBaseUrl(overrides);
848
+ const res = await fetch(`${baseUrl}/api/developer/status`);
849
+ const body = await res.json();
850
+ if (asJson) {
851
+ printJson(body);
852
+ return res.ok ? 0 : 1;
853
+ }
854
+ const enabled = body.enabled === true;
855
+ const str = (v) => typeof v === "string" && v ? v : void 0;
856
+ const mcpUrl = str(body.mcp) ?? (body.mcp && typeof body.mcp === "object" ? str(body.mcp.url) : void 0);
857
+ stdout.write(`${c.bold("Deep Search Developer API")}
858
+ `);
859
+ stdout.write(` endpoint ${baseUrl}
860
+ `);
861
+ stdout.write(` enabled ${enabled ? c.green("yes") : c.red("no")}
862
+ `);
863
+ if (str(body.status)) stdout.write(` status ${body.status}
864
+ `);
865
+ if (str(body.base_url)) stdout.write(` v1 base ${body.base_url}
866
+ `);
867
+ if (mcpUrl) stdout.write(` mcp ${mcpUrl}
868
+ `);
869
+ if (str(body.openapi_url)) stdout.write(` openapi ${body.openapi_url}
870
+ `);
871
+ if (str(body.docs_url)) stdout.write(` docs ${body.docs_url}
872
+ `);
873
+ const features = Array.isArray(body.features) ? body.features : [];
874
+ if (features.length > 0) {
875
+ stdout.write(` features ${features.map((f) => f && typeof f === "object" ? str(f.label) : str(f)).filter(Boolean).join(", ")}
876
+ `);
877
+ }
878
+ return res.ok && enabled ? 0 : 1;
879
+ }
880
+ async function runLogin(overrides) {
881
+ const config = readConfig();
882
+ const apiKey = overrides.apiKey ?? await prompt("Deep Search API key (dsk_...): ", { secret: true });
883
+ if (!apiKey) {
884
+ process.stderr.write(`${c.red("error")} no API key provided.
885
+ `);
886
+ return 2;
887
+ }
888
+ const baseUrl = overrides.baseUrl ?? config.baseUrl ?? await prompt("Base URL [https://deepsearch.so]: ");
889
+ const next = { ...config, apiKey: apiKey.trim() };
890
+ if (baseUrl && baseUrl.trim()) next.baseUrl = baseUrl.trim().replace(/\/$/, "");
891
+ writeConfig(next);
892
+ stdout.write(`${c.green("\u2713")} Saved credentials to ${configPath()}
893
+ `);
894
+ return 0;
895
+ }
896
+ function runConfig(args) {
897
+ const sub = args[0];
898
+ const config = readConfig();
899
+ switch (sub) {
900
+ case "path":
901
+ stdout.write(`${configPath()}
902
+ `);
903
+ return 0;
904
+ case "get": {
905
+ const key = args[1];
906
+ if (!key) {
907
+ printJson(redact(config));
908
+ return 0;
909
+ }
910
+ const value = config[key];
911
+ stdout.write(`${value === void 0 ? "" : key === "apiKey" ? maskKey(String(value)) : String(value)}
912
+ `);
913
+ return 0;
914
+ }
915
+ case "set": {
916
+ const key = args[1];
917
+ const value = args[2];
918
+ if (!key || value === void 0) {
919
+ process.stderr.write(`${c.red("error")} usage: deepsearch config set <apiKey|baseUrl> <value>
920
+ `);
921
+ return 2;
922
+ }
923
+ writeConfig({ ...config, [key]: value });
924
+ stdout.write(`${c.green("\u2713")} ${key} updated in ${configPath()}
925
+ `);
926
+ return 0;
927
+ }
928
+ default:
929
+ process.stderr.write(`${c.red("error")} usage: deepsearch config <get|set|path>
930
+ `);
931
+ return 2;
932
+ }
933
+ }
934
+ function resolvePerson(name, personJson) {
935
+ if (personJson) {
936
+ const parsed = JSON.parse(personJson);
937
+ if (typeof parsed.name !== "string") throw new Error('--person JSON must include a "name" string.');
938
+ return parsed;
939
+ }
940
+ if (!name) return null;
941
+ return { name };
942
+ }
943
+ async function readPayload(spec) {
944
+ if (spec === void 0) return void 0;
945
+ let text = spec;
946
+ if (spec === "-") {
947
+ text = await readStdin();
948
+ } else if (spec.startsWith("@")) {
949
+ text = readFileSync2(spec.slice(1), "utf8");
950
+ }
951
+ return JSON.parse(text);
952
+ }
953
+ function readStdin() {
954
+ return new Promise((resolve, reject) => {
955
+ let data = "";
956
+ stdin.setEncoding("utf8");
957
+ stdin.on("data", (chunk) => data += chunk);
958
+ stdin.on("end", () => resolve(data));
959
+ stdin.on("error", reject);
960
+ });
961
+ }
962
+ async function prompt(question, opts = {}) {
963
+ if (opts.secret && stdin.isTTY) {
964
+ return readSecret(question);
965
+ }
966
+ const rl = createInterface({ input: stdin, output: stdout });
967
+ try {
968
+ return (await rl.question(question)).trim();
969
+ } finally {
970
+ rl.close();
971
+ }
972
+ }
973
+ function readSecret(question) {
974
+ return new Promise((resolve) => {
975
+ stdout.write(question);
976
+ stdin.setRawMode?.(true);
977
+ stdin.resume();
978
+ stdin.setEncoding("utf8");
979
+ let value = "";
980
+ const onData = (char) => {
981
+ for (const ch of char) {
982
+ const code = ch.charCodeAt(0);
983
+ if (code === 10 || code === 13 || code === 4) {
984
+ stdin.setRawMode?.(false);
985
+ stdin.pause();
986
+ stdin.removeListener("data", onData);
987
+ stdout.write("\n");
988
+ resolve(value);
989
+ return;
990
+ }
991
+ if (code === 3) {
992
+ stdin.setRawMode?.(false);
993
+ stdout.write("\n");
994
+ process.exit(130);
995
+ } else if (code === 127 || code === 8) {
996
+ value = value.slice(0, -1);
997
+ } else if (code >= 32) {
998
+ value += ch;
999
+ }
1000
+ }
1001
+ };
1002
+ stdin.on("data", onData);
1003
+ });
1004
+ }
1005
+ function printJobSummary(job) {
1006
+ const color = job.status === "succeeded" ? c.green : job.status === "failed" ? c.red : c.yellow;
1007
+ stdout.write(`${color(job.status.padEnd(9))} ${c.bold(job.operation.padEnd(8))} ${c.dim(job.id)}
1008
+ `);
1009
+ if (job.error) stdout.write(` ${c.red(job.error)}
1010
+ `);
1011
+ }
1012
+ function redact(config) {
1013
+ const copy = { ...config };
1014
+ if (typeof copy.apiKey === "string") copy.apiKey = maskKey(copy.apiKey);
1015
+ return copy;
1016
+ }
1017
+ function maskKey(key) {
1018
+ if (key.length <= 8) return "\u2022\u2022\u2022\u2022";
1019
+ return `${key.slice(0, 6)}\u2026${key.slice(-4)}`;
1020
+ }
1021
+ function readPackageVersion() {
1022
+ try {
1023
+ const url = new URL("../package.json", import.meta.url);
1024
+ const pkg = JSON.parse(readFileSync2(url, "utf8"));
1025
+ return pkg.version ?? "0.0.0";
1026
+ } catch {
1027
+ return "0.0.0";
1028
+ }
1029
+ }
1030
+ main(process.argv.slice(2)).then((code) => process.exit(code)).catch((error) => {
1031
+ if (interruptController.signal.aborted) {
1032
+ process.stderr.write("Interrupted.\n");
1033
+ process.exit(130);
1034
+ }
1035
+ if (error instanceof MissingApiKeyError) {
1036
+ process.stderr.write(`${error.message}
1037
+ `);
1038
+ process.exit(1);
1039
+ }
1040
+ if (error instanceof DeepSearchError) {
1041
+ const code = error.code ? ` (${error.code})` : "";
1042
+ process.stderr.write(`${c.red(`error ${error.status}`)}${code} ${error.message}
1043
+ `);
1044
+ if (error.requestId) process.stderr.write(`${c.dim(`request id: ${error.requestId}`)}
1045
+ `);
1046
+ process.exit(1);
1047
+ }
1048
+ process.stderr.write(`${c.red("error")} ${error.message ?? String(error)}
1049
+ `);
1050
+ process.exit(1);
1051
+ });
1052
+ function requestOptions(values, flags) {
1053
+ return { signal: interruptController.signal, sandbox: flags.sandbox, idempotencyKey: values["idempotency-key"] };
1054
+ }
1055
+ async function runExtended(command, args, values, overrides, flags) {
1056
+ const client = makeClient(overrides, values), options = requestOptions(values, flags);
1057
+ if (command === "batch") {
1058
+ const input = await readPayload(values.input);
1059
+ if (!Array.isArray(input)) throw new Error("--input must contain an array of batch operations");
1060
+ printJson(await client.batch(input, options));
1061
+ return 0;
1062
+ }
1063
+ const text = args.join(" ").trim();
1064
+ if (!text) throw new Error("A query, name, image URL, VIN or street address is required");
1065
+ if (flags.stream) {
1066
+ const events = command === "companies" ? client.companySearchStream({ query: text }, options) : command === "company" ? client.companyDossierStream({ company: { name: text }, refresh: values.refresh === true }, options) : command === "reverse-image" ? client.reverseImageStream({ imageUrl: text }, options) : command === "address" ? client.addressStream({ address: text }, options) : client.vinStream({ vin: text, refresh: values.refresh === true }, options);
1067
+ for await (const event of events) {
1068
+ if (flags.asJson) printJson(event);
1069
+ else renderEvent(event);
1070
+ }
1071
+ } else {
1072
+ const result = command === "companies" ? await client.searchCompanies({ query: text }, options) : command === "company" ? await client.companyDossier({ company: { name: text }, refresh: values.refresh === true }, options) : command === "reverse-image" ? await client.reverseImage({ imageUrl: text }, options) : command === "address" ? await client.address({ address: text }, options) : await client.vin({ vin: text, refresh: values.refresh === true }, options);
1073
+ printJson(result);
1074
+ }
1075
+ return 0;
1076
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "deepsearch-so",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Official command-line interface for Deep Search (deepsearch.so) - look a person up by name, phone, email, or username and build a sourced public-footprint dossier from your terminal.",
5
+ "type": "module",
6
+ "bin": {
7
+ "deepsearch": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc --noEmit -p tsconfig.json && esbuild src/index.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/index.js",
15
+ "postbuild": "chmod +x dist/index.js",
16
+ "prepublishOnly": "npm run build",
17
+ "dev": "node src/index.ts"
18
+ },
19
+ "keywords": [
20
+ "deepsearch",
21
+ "deepsearch.so",
22
+ "people-search",
23
+ "people-search-api",
24
+ "reverse-phone-lookup",
25
+ "reverse-email-lookup",
26
+ "username-search",
27
+ "osint",
28
+ "public-records",
29
+ "cli",
30
+ "api",
31
+ "ai-agent",
32
+ "mcp"
33
+ ],
34
+ "license": "MIT",
35
+ "engines": {
36
+ "node": ">=20.9.0"
37
+ },
38
+ "author": {
39
+ "name": "RELOAD TEKNOLOJI LIMITED SIRKETI",
40
+ "email": "support@deepsearch.so",
41
+ "url": "https://deepsearch.so"
42
+ },
43
+ "homepage": "https://deepsearch.so",
44
+ "bugs": {
45
+ "email": "support@deepsearch.so"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "devDependencies": {
51
+ "deepsearch-so-client": "^0.1.1",
52
+ "@types/node": "^20.19.43",
53
+ "esbuild": "^0.28.2",
54
+ "typescript": "7.0.2"
55
+ }
56
+ }