@ai2aim.ai/hivemind-sdk 1.0.15 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,858 +1,334 @@
1
- # @hivemind/sdk
1
+ # @ai2aim.ai/hivemind-sdk
2
2
 
3
- Node.js / TypeScript SDK for the **Hivemind** API.
4
- Covers every endpoint — organizations, RAG queries, generation, scraping, analytics, billing, audio, agents, admin, Jira integration, and more.
5
- Includes a **CLI** (`hivemind`) for init, config, health, helper utilities, query, search, org creation, music generation, scraping, and manual schedule execution.
3
+ Node.js / TypeScript SDK for the API-key-scoped Hivemind API.
6
4
 
7
- ## Install
5
+ The SDK tracks the current backend contract:
6
+ - no public organization id in request paths
7
+ - no public billing endpoints
8
+ - no public tier or employee-id surface
9
+ - API keys scope their own data
8
10
 
9
- **From this repo (local):**
11
+ ## Install
10
12
 
11
13
  ```bash
12
14
  cd sdk
13
15
  npm install
14
16
  npm run build
15
-
16
- # Then in your other project:
17
- npm install ../path-to/VERTEX-AI/sdk
18
17
  ```
19
18
 
20
- **Or publish to a private registry and install normally:**
19
+ Then from another project:
21
20
 
22
21
  ```bash
23
- npm install @hivemind/sdk
22
+ npm install ../path-to/VERTEX-AI/sdk
24
23
  ```
25
24
 
26
- ## Quick start
27
-
28
- Set **HIVEMIND_BASE_URL** (or HIVEMIND_API_URL) in your environment once. Then create clients with only the overrides you need (e.g. `adminKey`, `apiKey`); baseUrl is read from env when omitted.
25
+ ## Quick Start
29
26
 
30
- ```typescript
31
- import { HivemindClient } from "@hivemind/sdk";
27
+ ```ts
28
+ import { HivemindClient } from "@ai2aim.ai/hivemind-sdk";
32
29
 
33
30
  const client = new HivemindClient({
34
- apiKey: "vtx_myorg_abc123...", // or pass per-request via options
31
+ baseUrl: process.env.HIVEMIND_BASE_URL!,
32
+ apiKey: process.env.HIVEMIND_API_KEY!,
35
33
  });
36
34
 
37
35
  const health = await client.health();
38
- const result = await client.query("my-org", { query: "What is the return policy?" });
36
+ const result = await client.query({
37
+ query: "Summarize the indexed knowledge base.",
38
+ });
39
+
40
+ console.log(health.status);
39
41
  console.log(result.answer);
40
42
  ```
41
43
 
42
- ## Content Creator Scheduling
44
+ ## Bootstrap A New API Key Scope
45
+
46
+ ```ts
47
+ import { HivemindClient } from "@ai2aim.ai/hivemind-sdk";
48
+
49
+ const admin = new HivemindClient({
50
+ baseUrl: process.env.HIVEMIND_BASE_URL!,
51
+ adminKey: process.env.HIVEMIND_ADMIN_KEY!,
52
+ });
53
+
54
+ const issued = await admin.issueApiKey({
55
+ name: "Acme Marketing",
56
+ settings: { timezone: "UTC", brand_voice: "playful" },
57
+ });
43
58
 
44
- The SDK also exposes the Content Creator project, content, source, and publish schedule routes.
59
+ console.log(issued.api_key);
60
+ console.log(issued.scope.name);
61
+ ```
45
62
 
46
- ```typescript
47
- import { HivemindClient } from "@hivemind/sdk";
63
+ ## Content Creator Example
48
64
 
49
- const client = new HivemindClient({ baseUrl: process.env.HIVEMIND_BASE_URL });
50
- const apiKey = await getOrgApiKeyFromDb(orgId);
65
+ ```ts
66
+ const client = new HivemindClient({
67
+ baseUrl: process.env.HIVEMIND_BASE_URL!,
68
+ apiKey: process.env.HIVEMIND_API_KEY!,
69
+ });
51
70
 
52
- const project = await client.createProject(orgId, {
71
+ const project = await client.createProject({
53
72
  name: "Launch Campaign",
54
- description: "Q4 rollout",
55
- }, { apiKey });
73
+ description: "Q4 rollout workspace",
74
+ });
56
75
 
57
- const item = await client.createContentItem(orgId, project.project_id, {
76
+ const item = await client.createContentItem(project.project_id, {
58
77
  item_type: "article",
59
78
  title: "Launch Post",
60
79
  content: "We are launching this quarter.",
61
80
  status: "ready",
62
- }, { apiKey });
81
+ });
63
82
 
64
- const schedule = await client.createPublishSchedule(orgId, project.project_id, {
83
+ const schedule = await client.createPublishSchedule(project.project_id, {
65
84
  content_id: item.content_id,
66
85
  target_platforms: ["linkedin", "x"],
67
86
  publish_at: "2026-03-17T12:00:00Z",
68
- }, { apiKey });
69
-
70
- console.log(schedule.status); // "scheduled"
71
- ```
72
-
73
- In normal deployments, the backend processes due schedules automatically with its background content schedule runner. The manual admin fallback is:
74
-
75
- ```typescript
76
- const admin = new HivemindClient({
77
- baseUrl: process.env.HIVEMIND_BASE_URL,
78
- adminKey: process.env.HIVEMIND_ADMIN_KEY,
79
87
  });
80
88
 
81
- const result = await admin.runDueSchedules();
82
- console.log(result.published);
89
+ console.log(schedule.status);
83
90
  ```
84
91
 
85
92
  ## Configuration
86
93
 
87
94
  | Option | Required | Description |
88
95
  |---|---|---|
89
- | `baseUrl` | No* | API base URL; defaults to **HIVEMIND_BASE_URL** or **HIVEMIND_API_URL** |
90
- | `apiPrefix` | No | Path prefix (default `/v1`) |
91
- | `apiKey` | No | Org API key; or pass per-request (see below) |
92
- | `adminKey` | No | Bootstrap admin key for admin endpoints |
93
- | `webhookSecret` | No | Secret for webhook endpoints |
96
+ | `baseUrl` | No* | API base URL. Defaults to `HIVEMIND_BASE_URL` or `HIVEMIND_API_URL`. |
97
+ | `apiPrefix` | No | Path prefix. Defaults to `/v1`. |
98
+ | `apiKey` | No | Bearer API key for API-key-scoped routes. |
99
+ | `adminKey` | No | Bootstrap admin key for admin routes and `issueApiKey()`. |
100
+ | `webhookSecret` | No | Secret for webhook receiver routes. |
101
+ | `timeoutMs` | No | Request timeout in ms. Defaults to `30000`. |
102
+ | `insecure` | No | Reserved for self-signed TLS workflows. |
94
103
 
95
- \* Required: either pass in config or set the env var.
96
- | `employeeId` | No | Employee ID header for RBAC |
97
- | `timeoutMs` | No | Request timeout in ms (default 30 000) |
98
- | `insecure` | No | Skip TLS verification for self-signed certs |
104
+ \* Required unless already present in env.
99
105
 
100
- ### API key from your database or cache
106
+ ## Main Methods
101
107
 
102
- You do **not** need to put the org API key in the client config. Store it in **your system’s database or cache** (e.g. per tenant/org) and pass it per request via the optional `options` parameter.
108
+ ### Core
103
109
 
104
- Set **HIVEMIND_BASE_URL** (or HIVEMIND_API_URL) in your environment. Then create one shared client with no API key; pass the key from your store on each org-scoped call:
105
-
106
- ```typescript
107
- import { HivemindClient } from "@hivemind/sdk";
108
-
109
- // One shared client — no API key in config
110
- const client = new HivemindClient({});
110
+ ```ts
111
+ client.root();
112
+ client.health();
113
+ client.adminLogin({ admin_key });
114
+ ```
111
115
 
112
- // In your app: load API key from your DB/cache for the current org
113
- const apiKey = await getOrgApiKeyFromDb(orgId); // your function
116
+ ### API key scope
114
117
 
115
- const result = await client.query(orgId, { query: "What is the return policy?" }, { apiKey });
118
+ ```ts
119
+ client.issueApiKey({ name, settings });
120
+ client.getCurrentScope();
121
+ client.rotateApiKey();
116
122
  ```
117
123
 
118
- All org-scoped methods accept an optional last argument `options?: RequestOptions` with `{ apiKey?: string }`. Use it to pass the key from your store instead of setting it on the client.
124
+ ### Documents and knowledge
119
125
 
120
- ### CLI config
126
+ ```ts
127
+ client.uploadDocument(file, "handbook.pdf");
128
+ client.query({ query: "What is our refund policy?" });
129
+ client.search({ query: "best B2B onboarding examples", num: 5 });
130
+ client.getAuditLogs();
131
+ ```
121
132
 
122
- The CLI reads config from **environment variables** and optionally **`.hivemindrc.json`** in the current directory. Env overrides file.
133
+ ### Projects
134
+
135
+ ```ts
136
+ client.createProject({ name, description });
137
+ client.listProjects();
138
+ client.getProject(projectId);
139
+ client.updateProject(projectId, { status: "archived" });
140
+ client.deleteProject(projectId);
141
+
142
+ client.chatProject(projectId, { message, user_id });
143
+ client.getProjectChatHistory(projectId, userId);
144
+
145
+ client.createContentItem(projectId, params);
146
+ client.listContentItems(projectId);
147
+ client.getContentItem(projectId, contentId);
148
+ client.updateContentItem(projectId, contentId, params);
149
+ client.deleteContentItem(projectId, contentId);
150
+
151
+ client.createProjectSource(projectId, params);
152
+ client.scrapeProjectSources(projectId, { urls });
153
+ client.listProjectSources(projectId);
154
+ client.getProjectSource(projectId, sourceId);
155
+ client.updateProjectSource(projectId, sourceId, params);
156
+ client.deleteProjectSource(projectId, sourceId);
157
+
158
+ client.createPublishSchedule(projectId, params);
159
+ client.listPublishSchedules(projectId);
160
+ client.getPublishSchedule(projectId, scheduleId);
161
+ client.updatePublishSchedule(projectId, scheduleId, params);
162
+ client.deletePublishSchedule(projectId, scheduleId);
163
+ ```
123
164
 
124
- | Env | Description |
125
- |---|---|
126
- | `HIVEMIND_BASE_URL` | API base URL (required) |
127
- | `HIVEMIND_API_KEY` | Org API key (for org-scoped commands) |
128
- | `HIVEMIND_ADMIN_KEY` | Admin key for org:create and schedule:run-due |
129
- | `HIVEMIND_API_PREFIX` | Path prefix (default `/v1`) |
130
- | `HIVEMIND_INSECURE` | Set to `true` to skip TLS verification |
131
- | `HIVEMIND_TIMEOUT_MS` | Request timeout in ms |
165
+ ### Generation and jobs
132
166
 
133
- You can also set `apiKey` on the client for single-tenant use.
167
+ ```ts
168
+ const job = await client.generateImage({ prompt: "Studio product photo" });
169
+ const status = await client.getJob(job.job_id);
170
+ const final = await client.waitForJob(job.job_id);
171
+ ```
134
172
 
135
- ### Admin endpoints
173
+ Also available:
174
+
175
+ ```ts
176
+ client.generateVideo(params);
177
+ client.generateMusic(params);
178
+ client.dataChat(params);
179
+ client.createAgent(params);
180
+ client.queryAgent(params);
181
+ client.transcribeAudio(params);
182
+ client.synthesizeAudio(params);
183
+ client.trainModel(params);
184
+ client.predict(params);
185
+ client.forecast(params);
186
+ ```
136
187
 
137
- If base URL is already in env, pass only `adminKey`:
188
+ ### Jira and blueprints
189
+
190
+ ```ts
191
+ client.connectJira(params);
192
+ client.getJiraStatus();
193
+ client.syncJira(params);
194
+ client.disconnectJira();
195
+
196
+ client.createBlueprint(params);
197
+ client.listBlueprints();
198
+ client.getBlueprint(blueprintId);
199
+ client.updateBlueprint(blueprintId, params);
200
+ client.publishBlueprint(blueprintId);
201
+ client.archiveBlueprint(blueprintId);
202
+ client.deleteBlueprint(blueprintId);
203
+
204
+ client.createDocumentFromBlueprint(params);
205
+ client.listManagedDocuments();
206
+ client.getManagedDocument(documentId);
207
+ client.updateDocumentSection(documentId, params);
208
+ client.performDocumentWorkflow(documentId, params);
209
+ client.generateDocumentSection(documentId, params);
210
+ client.deleteManagedDocument(documentId);
211
+ ```
138
212
 
139
- ```typescript
140
- const admin = new HivemindClient({
141
- adminKey: "your-bootstrap-admin-key",
142
- });
213
+ ### Scraping
143
214
 
144
- // Create a new organization, or reuse it if it already exists
145
- const ensured = await admin.createOrganization({
146
- org_id: "acme",
147
- name: "Acme Corp",
148
- tier: "premium",
149
- });
215
+ ```ts
216
+ client.getScrapingConfig();
217
+ client.scrape({ urls: ["https://example.com"] });
218
+ client.getScrapeStatus(taskId);
219
+ client.scrapeAndWait(["https://example.com"]);
220
+ ```
150
221
 
151
- if (ensured.created) {
152
- console.log("API Key:", ensured.api_key);
153
- } else {
154
- console.log("Already existed:", ensured.organization.org_id);
155
- }
222
+ ### Admin
223
+
224
+ ```ts
225
+ client.getAdminConfig();
226
+ client.getAdminConfigOverrides();
227
+ client.updateAdminSetting({ key, value });
228
+ client.getLogLevel();
229
+ client.setLogLevel({ level: "DEBUG" });
230
+ client.getLoggers();
231
+ client.getInboundTraffic();
232
+ client.resetInboundTraffic();
233
+ client.getOutboundStatus();
234
+ client.getCors();
235
+ client.setCors("*");
236
+ client.getRateLimits();
237
+ client.resetRateLimit(scopeId);
238
+ client.listJobs();
239
+ client.getFeatureFlags();
240
+ client.getFeatureFlag(key);
241
+ client.setFeatureFlag({ key, enabled: true });
242
+ client.deleteFeatureFlag(key);
243
+ client.getMaintenanceMode();
244
+ client.setMaintenanceMode({ enabled: true, message: "Maintenance" });
245
+ client.getCacheStats();
246
+ client.flushCache();
247
+ client.getAdminAudit();
248
+ client.getSystemInfo();
249
+ client.runDueSchedules();
156
250
  ```
157
251
 
158
252
  ## CLI
159
253
 
160
- After install, the `hivemind` binary is available (`npx hivemind` or via `npm exec hivemind` if installed globally).
254
+ After building, the `hivemind` binary is available.
161
255
 
162
256
  ### Commands
163
257
 
164
- | Command | Description |
165
- |---|---|
166
- | `hivemind init` | Create `.hivemindrc.json` and `.env.example` in the current directory |
167
- | `hivemind config` | Print resolved config (secrets masked) |
168
- | `hivemind health` | Call the API health endpoint |
169
- | `hivemind helper validate` | Validate config and test connection |
170
- | `hivemind helper env` | Print env var template for copy-paste |
171
- | `hivemind query <org_id> <question>` | Run a RAG query (needs API key) |
172
- | `hivemind search <org_id> <query>` | Run source discovery search (needs API key) |
173
- | `hivemind org:create <org_id> <name>` | Create an organization (needs admin key) |
174
- | `hivemind music <org_id> <genre> <mood>` | Start music generation (needs API key) |
175
- | `hivemind scrape <url...>` | Submit URLs to scrape |
176
- | `hivemind scrape:status <task_id>` | Get scrape task status and result |
177
- | `hivemind schedule:run-due` | Manually process due Content Creator schedules (needs admin key) |
178
-
179
- ### Examples
180
-
181
258
  ```bash
182
- # Initialize config in current directory
183
259
  hivemind init
184
-
185
- # Only create .env.example
186
- hivemind init --env-only
187
-
188
- # Check connection
189
- export HIVEMIND_BASE_URL=https://your-api.com
260
+ hivemind config
190
261
  hivemind health
191
-
192
- # Validate config and ping API
193
262
  hivemind helper validate
194
-
195
- # Print env template
196
263
  hivemind helper env
197
-
198
- # Run a RAG query (requires HIVEMIND_API_KEY)
199
- hivemind query my-org "What is the return policy?"
200
-
201
- # Run source discovery search
202
- hivemind search my-org "content marketing 2026" --type news --num 10
203
-
204
- # Create org (requires HIVEMIND_ADMIN_KEY)
205
- hivemind org:create acme "Acme Corp" --tier premium
206
-
207
- # Generate music and wait for completion
208
- hivemind music my-org ambient uplifting --duration 30 --wait
209
-
210
- # Scrape URLs and wait for results
211
- hivemind scrape https://example.com https://example.org --wait
212
-
213
- # Manually run due Content Creator schedules
264
+ hivemind query "What is our refund policy?"
265
+ hivemind search "content marketing trends 2026"
266
+ hivemind api-key:issue "Acme Marketing"
267
+ hivemind api-key:scope
268
+ hivemind api-key:rotate
269
+ hivemind music ambient uplifting --wait
270
+ hivemind scrape https://example.com --wait
271
+ hivemind scrape:status <task_id>
214
272
  hivemind schedule:run-due
273
+ hivemind start-web
215
274
  ```
216
275
 
217
- ### Options
218
-
219
- - **`-d, --dir <path>`** (for init, config, health, helper, query, search, org:create, music, scrape, schedule:run-due): Directory to use for `.hivemindrc.json` (default: current directory).
220
- - **`-u, --url <url>`** (health): Override base URL for a one-off health check.
221
- - **`--skip-ping`** (helper validate): Validate config only, do not call the API.
276
+ ## Streaming
222
277
 
223
- ### Search, music, and schedules
224
-
225
- ```typescript
226
- const search = await client.search("my-org", {
227
- query: "best B2B content strategy",
228
- type: "news",
229
- num: 10,
230
- });
231
-
232
- const musicJob = await client.generateMusic("my-org", {
233
- genre: "ambient",
234
- mood: "uplifting",
235
- duration: 30,
236
- });
237
-
238
- const music = await client.waitForJob("my-org", musicJob.job_id);
239
-
240
- const schedules = await client.listPublishSchedules("my-org", "proj_123", { apiKey });
241
- ```
242
-
243
- ## All methods
244
-
245
- All org-scoped methods accept an optional last argument `options?: RequestOptions` where you can pass `{ apiKey: string }` from your database or cache.
246
-
247
- **Authentication types:**
248
- - **Admin** — Set `adminKey` in client config. Sends `X-Admin-Key` header.
249
- - **API Key** — Set `apiKey` in config or pass per-request via `options.apiKey`. Sent as `Authorization: Bearer <key>`.
250
- - **Webhook** — Set `webhookSecret` in client config. Sends `X-Webhook-Secret` header.
251
- - **None** — No authentication required.
252
-
253
- All responses are wrapped in the standard envelope:
254
- ```json
255
- { "success": true, "statusCode": 200, "data": { ... }, "message": "Request successful" }
256
- ```
257
- The SDK returns the **`data`** payload directly (unwrapped). If you need the full envelope (e.g. `message`, `statusCode`), use `client.requestEnvelope<T>(method, path, opts)`.
258
-
259
- The envelope types `ApiEnvelope<T>` and `ApiErrorBody` are exported from the SDK for use in your own code.
260
-
261
- ### Health
262
-
263
- | Method | Auth | Description |
264
- |---|---|---|
265
- | `health()` | None | Service health check |
266
-
267
- **Returns** `HealthResponse`:
268
-
269
- | Field | Type | Description |
270
- |-----------|--------|-------------------------------------------------------|
271
- | `service` | string | Service name |
272
- | `version` | string | Service version |
273
- | `status` | string | Health status (`"ok"`) |
274
- | `stats` | object | `{ organizations, documents, total_chunks }` |
275
-
276
- ### Admin auth
277
-
278
- | Method | Auth | Description |
279
- |---|---|---|
280
- | `adminLogin({ admin_key })` | None | Exchange admin key for a signed session token |
281
-
282
- **Parameters** (`AdminLoginParams`):
283
-
284
- | Field | Type | Required | Description |
285
- |-------------|--------|----------|----------------------------|
286
- | `admin_key` | string | Yes | The bootstrap admin key |
287
-
288
- **Returns** `AdminLoginResponse`:
289
-
290
- | Field | Type | Description |
291
- |----------------------|--------|------------------------------------------|
292
- | `access_token` | string | Signed JWT session token |
293
- | `token_type` | string | Always `"bearer"` |
294
- | `expires_in_seconds` | number | Token validity (default 28800 = 8 hours) |
295
-
296
- ```typescript
297
- const { access_token } = await client.adminLogin({ admin_key: "your-admin-key" });
298
- ```
299
-
300
- ### Organizations
301
-
302
- | Method | Auth | Description |
303
- |---|---|---|
304
- | `createOrganization(params, options?)` | Admin | Create org idempotently; returns existing org instead of throwing on duplicates |
305
- | `ensureOrganization(params)` | Admin | Create org if missing, or return existing org without throwing |
306
- | `getAdminOrganization(orgId)` | Admin | Get org details with admin credentials |
307
- | `getOrganization(orgId, options?)` | API Key | Get org details |
308
- | `rotateApiKey(orgId, options?)` | Admin | Rotate org API key (24h grace period for old key) |
309
- | `suspendOrganization(orgId, options?)` | Admin | Suspend an org (blocks API access) |
310
- | `reactivateOrganization(orgId, options?)` | Admin | Reactivate a suspended org |
311
- | `deleteOrganization(orgId, options?)` | Admin | Permanently delete an org (irreversible) |
312
-
313
- **`createOrganization` parameters** (`OrgCreateParams`):
314
-
315
- | Field | Type | Required | Default | Description |
316
- |------------|--------|----------|--------------|------------------------------------------------|
317
- | `org_id` | string | Yes | — | Unique org identifier (2–64 chars) |
318
- | `name` | string | Yes | — | Display name (2–128 chars) |
319
- | `tier` | string | No | `"standard"` | `"free"`, `"standard"`, `"premium"`, `"enterprise"` |
320
- | `settings` | object | No | `{}` | Custom org settings |
321
-
322
- **Returns** `OrgEnsureResponse` by default:
323
-
324
- | Field | Type | Description |
325
- |----------------|----------------------|-----------------------------------------------|
326
- | `created` | `true \| false` | Whether this call created the org |
327
- | `organization` | Organization | Full organization entity |
328
- | `api_key` | `string \| null` | Generated API key, or `null` if org existed |
329
-
330
- ```typescript
331
- const ensured = await admin.createOrganization({
332
- org_id: "acme-corp",
333
- name: "Acme Corporation",
334
- tier: "premium",
335
- });
336
-
337
- if (ensured.created) {
338
- console.log("New API key:", ensured.api_key);
339
- } else {
340
- console.log("Organization already existed:", ensured.organization.org_id);
341
- }
342
- ```
343
-
344
- If you want strict create-only behavior and prefer duplicate orgs to throw:
345
-
346
- ```typescript
347
- const created = await admin.createOrganization(
348
- {
349
- org_id: "acme-corp",
350
- name: "Acme Corporation",
351
- tier: "premium",
352
- },
353
- { allowExisting: false },
354
- );
355
- console.log("New API key:", created.api_key);
356
- ```
357
-
358
- ### Documents
359
-
360
- | Method | Auth | Description |
361
- |---|---|---|
362
- | `uploadDocument(orgId, file, filename, options?)` | API Key | Upload a document (Buffer or Blob) |
363
-
364
- **Parameters:**
365
-
366
- | Param | Type | Required | Description |
367
- |------------|----------------|----------|---------------------------------------|
368
- | `orgId` | string | Yes | Organization identifier |
369
- | `file` | Blob \| Buffer | Yes | Document content |
370
- | `filename` | string | Yes | Original filename (e.g. `"report.pdf"`) |
371
-
372
- **Returns** `DocumentUploadResponse`:
373
-
374
- | Field | Type | Description |
375
- |---------------|--------|-------------------------------------------|
376
- | `document_id` | string | Unique document identifier |
377
- | `org_id` | string | Organization ID |
378
- | `filename` | string | Original filename |
379
- | `chunks` | number | Number of text chunks created |
380
- | `status` | string | Processing status (e.g. `"processed"`) |
381
-
382
- ```typescript
383
- import { readFileSync } from "fs";
384
- const file = readFileSync("./report.pdf");
385
- const result = await client.uploadDocument("acme-corp", file, "report.pdf");
386
- console.log(`${result.chunks} chunks created`);
387
- ```
388
-
389
- ### Query (RAG)
390
-
391
- | Method | Auth | Description |
392
- |---|---|---|
393
- | `query(orgId, params, options?)` | API Key | RAG query with retrieval and generation |
394
-
395
- **Parameters** (`QueryParams`):
396
-
397
- | Field | Type | Required | Default | Description |
398
- |----------------------|--------|----------|--------------|-------------------------------------------|
399
- | `query` | string | Yes | — | Query text |
400
- | `user_id` | string | No | `null` | User identifier for tracking |
401
- | `model_type` | string | No | `"gemini-pro"` | Gemini model for generation |
402
- | `temperature` | number | No | `0.2` | Sampling temperature (0.0–1.0) |
403
- | `retrieval_strategy` | string | No | `"hybrid"` | `"hybrid"`, `"dense"`, or `"sparse"` |
404
-
405
- **Returns** `QueryResponse`:
406
-
407
- | Field | Type | Description |
408
- |--------------|----------|-------------------------------------------------|
409
- | `answer` | string | Generated answer text |
410
- | `sources` | object[] | Source citations (doc_id, chunk_id, score, snippet) |
411
- | `model_type` | string | Model used |
412
-
413
- ```typescript
414
- const result = await client.query("acme-corp", {
415
- query: "What are the key findings in Q4?",
416
- temperature: 0.2,
417
- });
418
- console.log(result.answer);
419
- result.sources.forEach(s => console.log(s.doc_id, s.score));
420
- ```
421
-
422
- ### Generation
423
-
424
- | Method | Auth | Description |
425
- |---|---|---|
426
- | `generateVideo(orgId, params, options?)` | API Key | Start async video generation (Vertex AI Veo) |
427
- | `generateImage(orgId, params, options?)` | API Key | Start async image generation (Vertex AI Imagen) |
428
-
429
- **`generateVideo` parameters** (`GenerateVideoParams`):
430
-
431
- | Field | Type | Required | Default | Description |
432
- |----------------|--------|----------|----------|------------------------------------|
433
- | `prompt` | string | Yes | — | Video generation prompt |
434
- | `duration` | number | No | `8` | Duration: `4`, `6`, or `8` seconds |
435
- | `aspect_ratio` | string | No | `"16:9"` | Aspect ratio |
436
- | `style` | string | No | `null` | Visual style hint |
437
- | `user_id` | string | No | `null` | User identifier |
438
-
439
- **`generateImage` parameters** (`GenerateImageParams`):
440
-
441
- | Field | Type | Required | Default | Description |
442
- |----------------|--------|----------|---------|-------------------------------|
443
- | `prompt` | string | Yes | — | Image generation prompt |
444
- | `aspect_ratio` | string | No | `"1:1"` | Aspect ratio |
445
- | `style` | string | No | `null` | Visual style hint |
446
- | `num_images` | number | No | `1` | Number of images (1–8) |
447
- | `user_id` | string | No | `null` | User identifier |
448
-
449
- **Both return** `JobAcceptedResponse` (HTTP 202):
450
-
451
- | Field | Type | Description |
452
- |------------------|--------|-----------------------------------------------|
453
- | `job_id` | string | Job ID — use with `getJob()` / `waitForJob()` |
454
- | `status` | string | Always `"processing"` |
455
- | `estimated_time` | number | Estimated processing time in seconds |
456
-
457
- ```typescript
458
- const job = await client.generateVideo("acme-corp", {
459
- prompt: "A drone flyover of a mountain lake at sunset",
460
- duration: 8,
461
- style: "cinematic",
462
- });
463
- const result = await client.waitForJob("acme-corp", job.job_id);
464
- console.log(result.result); // { output_url, signed_url }
465
- ```
278
+ ### SSE
466
279
 
467
- ### Jobs
468
-
469
- | Method | Auth | Description |
470
- |---|---|---|
471
- | `getJob(orgId, jobId, options?)` | API Key | Get job status |
472
- | `waitForJob(orgId, jobId, intervalMs?, maxWaitMs?, options?)` | API Key | Poll until job reaches terminal status |
473
-
474
- **Returns** `JobStatusResponse`:
475
-
476
- | Field | Type | Description |
477
- |----------|----------------|------------------------------------------------------|
478
- | `job_id` | string | Job identifier |
479
- | `status` | string | `"processing"`, `"completed"`, `"failed"`, `"cancelled"` |
480
- | `result` | object \| null | Result payload when completed (e.g. `{ output_url, signed_url }`) |
481
- | `error` | string \| null | Error message if failed |
482
-
483
- **`waitForJob` parameters:**
484
-
485
- | Param | Type | Default | Description |
486
- |--------------|--------|-----------|-----------------------------|
487
- | `intervalMs` | number | `2000` | Polling interval (ms) |
488
- | `maxWaitMs` | number | `300000` | Maximum wait time (ms) |
489
-
490
- ### Data chat
491
-
492
- | Method | Auth | Description |
493
- |---|---|---|
494
- | `dataChat(orgId, params, options?)` | API Key | Natural-language questions over BigQuery |
495
-
496
- **Parameters** (`DataChatParams`):
497
-
498
- | Field | Type | Required | Description |
499
- |------------|--------|----------|--------------------------------|
500
- | `question` | string | Yes | Natural-language question |
501
- | `user_id` | string | No | User identifier for tracking |
502
-
503
- **Returns** `DataChatResponse`:
504
-
505
- | Field | Type | Description |
506
- |-------------|----------|------------------------------------------|
507
- | `answer` | string | Natural-language answer |
508
- | `sql` | string | Generated SQL query |
509
- | `data` | object[] | Result rows returned by the query |
510
- | `row_count` | number | Number of rows returned |
511
- | `tool_used` | string | Backend tool used (e.g. `"alloydb"`) |
512
-
513
- ```typescript
514
- const result = await client.dataChat("acme-corp", {
515
- question: "How many active users this month?",
516
- });
517
- console.log(result.answer); // "There are 1,247 active users."
518
- console.log(result.sql); // "SELECT COUNT(DISTINCT user_id) FROM ..."
519
- ```
520
-
521
- ### Agents
522
-
523
- | Method | Auth | Description |
524
- |---|---|---|
525
- | `createAgent(orgId, params, options?)` | API Key | Create a custom AI agent template |
526
- | `queryAgent(orgId, params, options?)` | API Key | Query an AI agent |
527
-
528
- **`createAgent` parameters** (`AgentCreateParams`):
529
-
530
- | Field | Type | Required | Default | Description |
531
- |----------------|----------|----------|---------|---------------------------------|
532
- | `name` | string | Yes | — | Agent name (2–64 chars) |
533
- | `instructions` | string | Yes | — | System instructions (min 4 chars) |
534
- | `tools` | string[] | No | `[]` | Tool identifiers to enable |
535
-
536
- **`queryAgent` parameters** (`AgentQueryParams`):
537
-
538
- | Field | Type | Required | Default | Description |
539
- |--------------|--------|----------|----------|--------------------------|
540
- | `query` | string | Yes | — | User query |
541
- | `user_id` | string | Yes | — | User identifier |
542
- | `agent_type` | string | No | `"auto"` | Agent type to route to |
543
-
544
- ### Audio
545
-
546
- | Method | Auth | Description |
547
- |---|---|---|
548
- | `transcribeAudio(orgId, params, options?)` | API Key | Speech-to-text transcription |
549
- | `synthesizeAudio(orgId, params, options?)` | API Key | Text-to-speech synthesis |
550
-
551
- **`transcribeAudio` parameters** (`AudioTranscribeParams`):
552
-
553
- | Field | Type | Required | Default | Description |
554
- |-----------------|--------|----------|------------|---------------------------|
555
- | `audio_text` | string | No | — | Legacy text fallback |
556
- | `audio_url` | string | No | — | Audio URL for Scribe |
557
- | `language_code` | string | No | `"en-US"` | BCP-47 language code |
558
- | `model_id` | string | No | `"scribe_v2"` | STT model override |
559
-
560
- **`synthesizeAudio` parameters** (`AudioSynthesizeParams`):
561
-
562
- | Field | Type | Required | Default | Description |
563
- |------------------|--------|----------|----------------------|--------------------------------|
564
- | `text` | string | Yes | — | Text to synthesize |
565
- | `voice_name` | string | No | `"en-US-Neural2-J"` | Voice identifier / voice ID |
566
- | `model_id` | string | No | backend default | ElevenLabs TTS model override |
567
- | `output_format` | string | No | backend default | Output format override |
568
- | `language_code` | string | No | — | ISO 639-1 language code |
569
- | `seed` | number | No | — | Deterministic synthesis seed |
570
- | `voice_settings` | object | No | backend default | Per-request voice settings |
571
-
572
- ### Analytics / ML
573
-
574
- | Method | Auth | Description |
575
- |---|---|---|
576
- | `trainModel(orgId, params, options?)` | API Key | Train a predictive model on tabular data |
577
- | `predict(orgId, params, options?)` | API Key | Run predictions with a trained model |
578
- | `forecast(orgId, params, options?)` | API Key | Time-series forecast (ARIMA-based) |
579
-
580
- **`trainModel` parameters** (`TrainModelParams`):
581
-
582
- | Field | Type | Required | Description |
583
- |-------------------|----------|----------|-----------------------------|
584
- | `target_column` | string | Yes | Column to predict |
585
- | `feature_columns` | string[] | Yes | Feature column names |
586
- | `rows` | object[] | Yes | Training data rows |
587
-
588
- **`predict` parameters** (`PredictParams`):
589
-
590
- | Field | Type | Required | Description |
591
- |-------------|----------|----------|------------------------------|
592
- | `model_id` | string | Yes | Trained model ID |
593
- | `instances` | object[] | Yes | Data instances to predict on |
594
-
595
- **`forecast` parameters** (`ForecastParams`):
596
-
597
- | Field | Type | Required | Default | Description |
598
- |-----------|----------|----------|---------|--------------------------------|
599
- | `series` | number[] | Yes | — | Historical time-series values |
600
- | `horizon` | number | No | `30` | Forecast horizon (1–365) |
601
-
602
- ```typescript
603
- // Train
604
- const model = await client.trainModel("acme-corp", {
605
- target_column: "churn",
606
- feature_columns: ["tenure", "monthly_charges"],
607
- rows: [{ tenure: 12, monthly_charges: 50, churn: 0 }],
608
- });
609
-
610
- // Predict
611
- const { predictions } = await client.predict("acme-corp", {
612
- model_id: model.model_id,
613
- instances: [{ tenure: 6, monthly_charges: 65 }],
614
- });
615
- ```
616
-
617
- ### Billing
618
-
619
- | Method | Auth | Description |
620
- |---|---|---|
621
- | `getUsage(orgId, month?, options?)` | API Key | Monthly usage summary with tier limits |
622
- | `getInvoice(orgId, month?, options?)` | API Key | Monthly invoice with cost breakdown |
623
-
624
- **Optional `month` parameter:** `YYYY-MM` format. Defaults to current month.
625
-
626
- **`getUsage` returns** `UsageSummaryResponse`:
627
-
628
- | Field | Type | Description |
629
- |-------------------|----------|------------------------------------------------|
630
- | `org_id` | string | Organization ID |
631
- | `month` | string | Month (`YYYY-MM`) |
632
- | `usage` | object | `{ tokens_used, images_generated, videos_generated, storage_bytes, compute_hours }` |
633
- | `limits` | object | Tier limits |
634
- | `within_quota` | boolean | Whether all metrics are within quota |
635
- | `exceeded_limits` | string[] | List of exceeded metric names |
636
-
637
- **`getInvoice` returns** `InvoiceResponse`:
638
-
639
- | Field | Type | Description |
640
- |------------|--------|---------------------------------------|
641
- | `org_id` | string | Organization ID |
642
- | `month` | string | Month (`YYYY-MM`) |
643
- | `usage` | object | Usage counters for the billing period |
644
- | `costs` | object | Cost breakdown by resource type |
645
- | `total` | number | Total cost for the period |
646
- | `currency` | string | Currency code (e.g. `"USD"`) |
647
-
648
- ### Audit
649
-
650
- | Method | Auth | Description |
651
- |---|---|---|
652
- | `getAuditLogs(orgId, options?)` | API Key | List audit log records |
653
-
654
- **Returns** `AuditLogResponse`:
655
-
656
- | Field | Type | Description |
657
- |-----------|----------------|--------------------|
658
- | `org_id` | string | Organization ID |
659
- | `records` | AuditRecord[] | Audit log entries |
660
-
661
- Each `AuditRecord`:
662
-
663
- | Field | Type | Description |
664
- |------------|----------------|-----------------------------------------|
665
- | `timestamp`| string | ISO 8601 timestamp |
666
- | `action` | string | Action (e.g. `"query.execute"`) |
667
- | `resource` | string | Resource path |
668
- | `status` | string | `"success"` or `"failure"` |
669
- | `user_id` | string \| null | User who performed the action |
670
- | `metadata` | object | Additional context |
671
-
672
- ### Scraping
673
-
674
- | Method | Auth | Description |
675
- |---|---|---|
676
- | `getScrapingConfig()` | None | Runtime scraping configuration |
677
- | `scrape({ urls })` | None | Submit URLs for scraping |
678
- | `getScrapeStatus(taskId)` | None | Check scrape task status and results |
679
- | `scrapeAndWait(urls, intervalMs?, maxWaitMs?)` | None | Submit + poll until results are ready |
680
-
681
- **`scrape` parameters** (`ScrapeParams`):
682
-
683
- | Field | Type | Required | Description |
684
- |--------|----------|----------|---------------------------------|
685
- | `urls` | string[] | Yes | URLs to scrape |
686
-
687
- **`getScrapeStatus` returns** `ScrapeStatusResponse`:
688
-
689
- | Field | Type | Description |
690
- |-----------|-------------------|----------------------------------------------------|
691
- | `task_id` | string | Task identifier |
692
- | `status` | string | `"PENDING"`, `"SUCCESS"`, `"FAILURE"`, `"completed"` |
693
- | `result` | ScrapeResultItem[] | Scraped results (each with url, title, full_text) |
694
-
695
- ```typescript
696
- const result = await client.scrapeAndWait(["https://example.com"]);
697
- for (const page of result.result) {
698
- console.log(page.title, page.full_text?.substring(0, 200));
699
- }
700
- ```
701
-
702
- ### Webhooks
703
-
704
- | Method | Auth | Description |
705
- |---|---|---|
706
- | `sendVideoCompleteWebhook(payload)` | Webhook | Send video completion notification |
707
- | `sendDocumentProcessedWebhook(payload)` | Webhook | Send document processing notification |
708
-
709
- **`VideoCompleteWebhook` payload:**
710
-
711
- | Field | Type | Required | Description |
712
- |------------|--------|----------|-------------------------------------|
713
- | `job_id` | string | Yes | Job identifier |
714
- | `org_id` | string | Yes | Organization identifier |
715
- | `status` | string | Yes | Completion status |
716
- | `metadata` | object | No | Additional data (e.g. `{ output_uri }`) |
717
-
718
- **`DocumentProcessedWebhook` payload:**
719
-
720
- | Field | Type | Required | Description |
721
- |---------------|--------|----------|-------------------------------------|
722
- | `document_id` | string | Yes | Document identifier |
723
- | `org_id` | string | Yes | Organization identifier |
724
- | `status` | string | Yes | Processing status |
725
- | `metadata` | object | No | Additional data (e.g. `{ chunks }`) |
726
-
727
- ## Real-time transports
728
-
729
- In addition to standard REST, the SDK supports **Server-Sent Events (SSE)** and **WebSocket** for streaming endpoints. Currently, project chat is the first endpoint to support these transports; additional endpoints can be added using the same primitives.
730
-
731
- ### SSE (Server-Sent Events)
732
-
733
- Use `chatProjectSse()` to receive chat results as a stream of typed events:
734
-
735
- ```typescript
736
- for await (const evt of client.chatProjectSse("acme", "proj-1", {
737
- message: "Summarize our sources",
738
- user_id: "u1",
280
+ ```ts
281
+ for await (const evt of client.chatProjectSse("proj_123", {
282
+ message: "Summarize our saved sources.",
283
+ user_id: "sdk-user",
739
284
  })) {
740
- switch (evt.event) {
741
- case "start":
742
- console.log("Stream started for", evt.data.project_id);
743
- break;
744
- case "done":
745
- console.log("Answer:", evt.data.answer);
746
- break;
747
- case "error":
748
- console.error("Error:", evt.data.message);
749
- break;
285
+ if (evt.event === "done") {
286
+ console.log(evt.data.answer);
750
287
  }
751
288
  }
752
289
  ```
753
290
 
754
- **Endpoint:** `POST /v1/organizations/{orgId}/projects/{projectId}/chat/stream`
755
-
756
- **Event types:**
757
-
758
- | Event | Data shape | Description |
759
- |---------|----------------------------------|------------------------------------|
760
- | `start` | `{ org_id, project_id }` | Stream has started |
761
- | `done` | `QueryResponse` | Final result (same shape as REST) |
762
- | `error` | `{ message: string }` | An error occurred |
763
-
764
- The SSE parser is also available standalone for custom use:
765
-
766
- ```typescript
767
- import { parseSseStream } from "@ai2aim.ai/hivemind-sdk";
768
-
769
- const res = await fetch(url, { method: "POST", body, headers });
770
- for await (const event of parseSseStream(res.body!)) {
771
- console.log(event.event, event.data);
772
- }
773
- ```
774
-
775
291
  ### WebSocket
776
292
 
777
- Use `chatProjectWebSocket()` to open a persistent connection for interactive chat:
778
-
779
- ```typescript
780
- const ws = await client.chatProjectWebSocket("acme", "proj-1", {
781
- apiKey: "vtx_...",
782
- });
293
+ ```ts
294
+ const ws = await client.chatProjectWebSocket("proj_123");
783
295
 
784
296
  const frame = await ws.chat({
785
- message: "What are our top sources?",
786
- user_id: "u1",
297
+ message: "What are our strongest sources?",
298
+ user_id: "sdk-user",
787
299
  });
788
300
 
789
301
  if (frame.type === "result") {
790
302
  console.log(frame.payload.answer);
791
- } else {
792
- console.error(frame.message);
793
303
  }
794
304
 
795
305
  ws.close();
796
306
  ```
797
307
 
798
- **Endpoint:** `WS /v1/organizations/{orgId}/projects/{projectId}/chat/ws?api_key=...`
799
-
800
- **Authentication:** The API key is sent as a `?api_key=` query parameter (browser-safe; `Authorization` headers are not available for browser WebSocket connections).
801
-
802
- **Client command frame:**
803
-
804
- ```json
805
- { "type": "chat", "message": "...", "user_id": "...", "temperature": 0.2 }
806
- ```
807
-
808
- **Server response frames:**
308
+ ## Dashboard
809
309
 
810
- | `type` | Shape | Description |
811
- |----------|--------------------------------------|--------------------------------------|
812
- | `result` | `{ type: "result", payload: QueryResponse }` | Successful chat result |
813
- | `error` | `{ type: "error", message: string }` | An error occurred |
310
+ `hivemind start-web` launches a local browser dashboard with:
311
+ - connection settings
312
+ - API key issuance and rotation
313
+ - query and search
314
+ - document upload
315
+ - project creation and chat
316
+ - generation jobs
317
+ - scraping
318
+ - manual request runner
814
319
 
815
- ### Node.js vs browser
320
+ ## Error Handling
816
321
 
817
- - **SSE** uses the standard `fetch` API (`ReadableStream`), available in all modern browsers and Node 18+.
818
- - **WebSocket** uses `globalThis.WebSocket`. Browsers have this natively. Node 22+ includes a built-in `WebSocket`. For Node 18–21, install the [`ws`](https://www.npmjs.com/package/ws) package and assign `globalThis.WebSocket = require("ws")` before using WebSocket methods.
819
- - The `signal` option on `chatProjectWebSocket()` allows you to use an `AbortController` to close the connection from the outside.
322
+ All API failures throw `HivemindError`.
820
323
 
821
- ## Error handling
822
-
823
- All API errors throw `HivemindError`:
824
-
825
- ```typescript
826
- import { HivemindClient, HivemindError } from "@hivemind/sdk";
324
+ ```ts
325
+ import { HivemindClient, HivemindError } from "@ai2aim.ai/hivemind-sdk";
827
326
 
828
327
  try {
829
- await client.query("my-org", { query: "hello" });
328
+ await client.query({ query: "hello" });
830
329
  } catch (err) {
831
330
  if (err instanceof HivemindError) {
832
331
  console.error(err.statusCode, err.detail);
833
332
  }
834
333
  }
835
334
  ```
836
-
837
- `createOrganization(params)` and `ensureOrganization(params)` are idempotent for
838
- duplicate organizations by default. Pass `createOrganization(params, { allowExisting: false })`
839
- if you want duplicate-org responses to throw `HivemindError`.
840
-
841
- ## Vercel / Next.js example
842
-
843
- ```typescript
844
- // app/api/query/route.ts (Next.js App Router)
845
- import { HivemindClient } from "@hivemind/sdk";
846
- import { NextResponse } from "next/server";
847
-
848
- // With HIVEMIND_API_URL set in env
849
- const client = new HivemindClient({
850
- apiKey: process.env.HIVEMIND_API_KEY!,
851
- });
852
-
853
- export async function POST(req: Request) {
854
- const { query } = await req.json();
855
- const result = await client.query("my-org", { query });
856
- return NextResponse.json(result);
857
- }
858
- ```