@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/dist/client.js CHANGED
@@ -37,23 +37,7 @@ var __importStar = (this && this.__importStar) || (function () {
37
37
  })();
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.HivemindClient = exports.HivemindError = void 0;
40
- // Re-export all types for consumers
41
40
  __exportStar(require("./types"), exports);
42
- /**
43
- * Error thrown when an API request fails.
44
- * Contains the HTTP status code and the raw response body for inspection.
45
- *
46
- * @example
47
- * ```typescript
48
- * try {
49
- * await client.query("my-org", { query: "hello" });
50
- * } catch (err) {
51
- * if (err instanceof HivemindError) {
52
- * console.error(`HTTP ${err.statusCode}:`, err.detail);
53
- * }
54
- * }
55
- * ```
56
- */
57
41
  class HivemindError extends Error {
58
42
  statusCode;
59
43
  detail;
@@ -87,9 +71,6 @@ class HivemindClient {
87
71
  this.baseUrl = this.config.baseUrl;
88
72
  this.prefix = this.config.apiPrefix ?? "/v1";
89
73
  }
90
- // -----------------------------------------------------------------------
91
- // Generic HTTP helpers
92
- // -----------------------------------------------------------------------
93
74
  async request(method, path, opts = {}) {
94
75
  const url = new URL(`${this.prefix}${path}`, this.baseUrl);
95
76
  return this.performRequest(url, method, opts);
@@ -100,15 +81,16 @@ class HivemindClient {
100
81
  }
101
82
  async performRequest(url, method, opts = {}) {
102
83
  if (opts.query) {
103
- for (const [k, v] of Object.entries(opts.query)) {
104
- if (v !== undefined && v !== null)
105
- url.searchParams.set(k, v);
84
+ for (const [key, value] of Object.entries(opts.query)) {
85
+ if (value !== undefined && value !== null) {
86
+ url.searchParams.set(key, String(value));
87
+ }
106
88
  }
107
89
  }
108
90
  const headers = { ...opts.headers };
109
91
  const apiKey = opts.apiKey ?? this.config.apiKey;
110
92
  if (apiKey) {
111
- headers["Authorization"] = `Bearer ${apiKey}`;
93
+ headers.Authorization = `Bearer ${apiKey}`;
112
94
  }
113
95
  if (this.config.adminKey) {
114
96
  headers["X-Admin-Key"] = this.config.adminKey;
@@ -116,42 +98,38 @@ class HivemindClient {
116
98
  if (this.config.webhookSecret) {
117
99
  headers["X-Webhook-Secret"] = this.config.webhookSecret;
118
100
  }
119
- if (this.config.employeeId) {
120
- headers["X-Employee-Id"] = this.config.employeeId;
121
- }
122
- let bodyPayload;
101
+ let body;
123
102
  if (opts.formData) {
124
- bodyPayload = opts.formData;
103
+ body = opts.formData;
125
104
  }
126
105
  else if (opts.body !== undefined) {
127
106
  headers["Content-Type"] = "application/json";
128
- bodyPayload = JSON.stringify(opts.body);
107
+ body = JSON.stringify(opts.body);
129
108
  }
130
109
  const controller = new AbortController();
131
110
  const timeoutId = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 30_000);
132
111
  try {
133
- const fetchOpts = {
112
+ const res = await fetch(url.toString(), {
134
113
  method,
135
114
  headers,
136
- body: bodyPayload,
115
+ body: body,
137
116
  signal: controller.signal,
138
- };
139
- const res = await fetch(url.toString(), fetchOpts);
140
- if (res.status === 204)
117
+ });
118
+ if (res.status === 204) {
141
119
  return undefined;
120
+ }
142
121
  const text = await res.text();
143
- let json;
122
+ let parsed;
144
123
  try {
145
- json = JSON.parse(text);
124
+ parsed = JSON.parse(text);
146
125
  }
147
126
  catch {
148
- json = text;
127
+ parsed = text;
149
128
  }
150
- const envelope = this.asEnvelope(json);
129
+ const envelope = this.asEnvelope(parsed);
151
130
  if (envelope) {
152
131
  if (!envelope.success) {
153
- const message = envelope.message || this.extractErrorMessage(envelope.data) || undefined;
154
- throw new HivemindError(envelope.statusCode, envelope.data, message);
132
+ throw new HivemindError(envelope.statusCode, envelope.data, envelope.message || this.extractErrorMessage(envelope.data) || undefined);
155
133
  }
156
134
  if (envelope.statusCode === 204 || envelope.data === null) {
157
135
  return undefined;
@@ -159,48 +137,39 @@ class HivemindClient {
159
137
  return envelope.data;
160
138
  }
161
139
  if (!res.ok) {
162
- const message = this.extractErrorMessage(json) || undefined;
163
- throw new HivemindError(res.status, json, message);
140
+ throw new HivemindError(res.status, parsed, this.extractErrorMessage(parsed) || undefined);
164
141
  }
165
- return json;
142
+ return parsed;
166
143
  }
167
144
  finally {
168
145
  clearTimeout(timeoutId);
169
146
  }
170
147
  }
171
- /**
172
- * Build the same request a normal REST call would, but return the full
173
- * envelope instead of unwrapping `.data`. Useful when callers need
174
- * `message` or `statusCode` directly.
175
- */
176
148
  async requestEnvelope(method, path, opts = {}) {
177
149
  const url = new URL(`${this.prefix}${path}`, this.baseUrl);
178
150
  if (opts.query) {
179
- for (const [k, v] of Object.entries(opts.query)) {
180
- if (v !== undefined && v !== null)
181
- url.searchParams.set(k, v);
151
+ for (const [key, value] of Object.entries(opts.query)) {
152
+ if (value !== undefined && value !== null) {
153
+ url.searchParams.set(key, String(value));
154
+ }
182
155
  }
183
156
  }
184
157
  const headers = { ...opts.headers };
185
158
  const apiKey = opts.apiKey ?? this.config.apiKey;
186
159
  if (apiKey)
187
- headers["Authorization"] = `Bearer ${apiKey}`;
160
+ headers.Authorization = `Bearer ${apiKey}`;
188
161
  if (this.config.adminKey)
189
162
  headers["X-Admin-Key"] = this.config.adminKey;
190
163
  if (this.config.webhookSecret)
191
164
  headers["X-Webhook-Secret"] = this.config.webhookSecret;
192
- if (this.config.employeeId)
193
- headers["X-Employee-Id"] = this.config.employeeId;
194
- if (opts.body !== undefined) {
165
+ if (opts.body !== undefined)
195
166
  headers["Content-Type"] = "application/json";
196
- }
197
167
  const res = await fetch(url.toString(), {
198
168
  method,
199
169
  headers,
200
170
  body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
201
171
  });
202
- const json = await res.json();
203
- return json;
172
+ return await res.json();
204
173
  }
205
174
  asEnvelope(payload) {
206
175
  if (payload &&
@@ -218,21 +187,17 @@ class HivemindClient {
218
187
  if (!detail || typeof detail !== "object")
219
188
  return null;
220
189
  const record = detail;
221
- const directMessage = record.message;
222
- if (typeof directMessage === "string")
223
- return directMessage;
224
- const nestedDetail = record.detail;
225
- if (typeof nestedDetail === "string")
226
- return nestedDetail;
227
- if (Array.isArray(nestedDetail)) {
228
- const parts = nestedDetail
190
+ if (typeof record.message === "string")
191
+ return record.message;
192
+ if (typeof record.detail === "string")
193
+ return record.detail;
194
+ if (Array.isArray(record.detail)) {
195
+ const parts = record.detail
229
196
  .map((item) => {
230
197
  if (typeof item === "string")
231
198
  return item;
232
- if (item && typeof item === "object") {
233
- const nestedMessage = item.msg;
234
- if (typeof nestedMessage === "string")
235
- return nestedMessage;
199
+ if (item && typeof item === "object" && typeof item.msg === "string") {
200
+ return item.msg;
236
201
  }
237
202
  return null;
238
203
  })
@@ -241,814 +206,185 @@ class HivemindClient {
241
206
  }
242
207
  return null;
243
208
  }
244
- isOrganizationAlreadyExistsError(err, orgId) {
245
- if (!(err instanceof HivemindError))
246
- return false;
247
- if (err.statusCode !== 400 && err.statusCode !== 409)
248
- return false;
249
- const message = this.extractErrorMessage(err.detail)?.toLowerCase() ?? "";
250
- const normalizedOrgId = orgId.toLowerCase();
251
- return message.includes("already exists") && (message.includes("organization") || message.includes(normalizedOrgId));
252
- }
253
209
  get(path, query, options) {
254
210
  return this.request("GET", path, { query, apiKey: options?.apiKey });
255
211
  }
256
212
  post(path, body, options) {
257
213
  return this.request("POST", path, { body, apiKey: options?.apiKey });
258
214
  }
259
- del(path, options) {
260
- return this.request("DELETE", path, { apiKey: options?.apiKey });
261
- }
262
215
  put(path, body, options) {
263
216
  return this.request("PUT", path, { body, apiKey: options?.apiKey });
264
217
  }
265
218
  patch(path, body, options) {
266
219
  return this.request("PATCH", path, { body, apiKey: options?.apiKey });
267
220
  }
268
- // -----------------------------------------------------------------------
269
- // Health
270
- // -----------------------------------------------------------------------
271
- /**
272
- * Fetch the unauthenticated service root metadata payload.
273
- *
274
- * @returns Service name plus relative health/docs entrypoints.
275
- *
276
- * **Endpoint:** `GET /`
277
- */
221
+ del(path, options) {
222
+ return this.request("DELETE", path, { apiKey: options?.apiKey });
223
+ }
278
224
  root() {
279
225
  return this.requestUnprefixed("GET", "/");
280
226
  }
281
- /**
282
- * Check service health status. No authentication required.
283
- *
284
- * @returns Service name, version, status, and aggregate statistics.
285
- *
286
- * **Endpoint:** `GET /v1/health`
287
- *
288
- * @example
289
- * ```typescript
290
- * const health = await client.health();
291
- * console.log(health.status); // "ok"
292
- * console.log(health.stats); // { organizations: 12, documents: 450, total_chunks: 3200 }
293
- * ```
294
- */
295
227
  health() {
296
228
  return this.get("/health");
297
229
  }
298
- // -----------------------------------------------------------------------
299
- // Admin auth
300
- // -----------------------------------------------------------------------
301
- /**
302
- * Exchange the bootstrap admin key for a signed session token.
303
- * The token can be used as `Authorization: Bearer <token>` for admin endpoints
304
- * instead of sending the raw admin key on every request.
305
- *
306
- * @param params - Object containing the `admin_key`.
307
- * @returns Signed session token with type and expiry.
308
- * @throws {@link HivemindError} 400 if admin key is not configured on the server.
309
- * @throws {@link HivemindError} 401 if the admin key is invalid.
310
- *
311
- * **Endpoint:** `POST /v1/admin/login`
312
- *
313
- * @example
314
- * ```typescript
315
- * const { access_token, expires_in_seconds } = await client.adminLogin({
316
- * admin_key: "your-bootstrap-admin-key",
317
- * });
318
- * // Use access_token as Bearer token for subsequent admin requests
319
- * ```
320
- */
321
230
  adminLogin(params) {
322
231
  return this.post("/admin/login", params);
323
232
  }
324
- async createOrganization(params, options) {
325
- const allowExisting = options?.allowExisting !== false;
326
- try {
327
- const created = await this.post("/organizations", params);
328
- if (allowExisting) {
329
- return { ...created, created: true };
330
- }
331
- return created;
332
- }
333
- catch (err) {
334
- if (!allowExisting || !this.isOrganizationAlreadyExistsError(err, params.org_id)) {
335
- throw err;
336
- }
337
- const organization = await this.getAdminOrganization(params.org_id);
338
- return {
339
- created: false,
340
- organization,
341
- api_key: null,
342
- };
343
- }
233
+ issueApiKey(params = {}) {
234
+ return this.post("/api-keys", params);
235
+ }
236
+ getCurrentScope(options) {
237
+ return this.get("/api-key", undefined, options);
344
238
  }
345
- /**
346
- * Ensure an organization exists without throwing when it has already been provisioned.
347
- *
348
- * **Auth:** Requires `adminKey` in client config.
349
- *
350
- * @param params - Organization creation parameters.
351
- * @returns A discriminated result describing whether the org was created or already existed.
352
- */
353
- ensureOrganization(params) {
354
- return this.createOrganization(params, { allowExisting: true });
355
- }
356
- /**
357
- * Retrieve organization details including tier, status, and settings.
358
- *
359
- * **Auth:** Requires org-scoped API key (via config or `options.apiKey`).
360
- *
361
- * @param orgId - Organization identifier.
362
- * @param options - Optional per-request overrides (e.g. `{ apiKey }`).
363
- * @returns Full organization entity.
364
- * @throws {@link HivemindError} 401 if API key is missing or invalid.
365
- * @throws {@link HivemindError} 403 if the API key belongs to a different org.
366
- * @throws {@link HivemindError} 404 if the organization does not exist.
367
- *
368
- * **Endpoint:** `GET /v1/organizations/{orgId}`
369
- */
370
- getOrganization(orgId, options) {
371
- return this.get(`/organizations/${orgId}`, undefined, options);
372
- }
373
- /**
374
- * Rotate the API key for an organization. The previous key remains valid
375
- * for a 24-hour grace period.
376
- *
377
- * **Auth:** Requires `adminKey` in client config.
378
- *
379
- * @param orgId - Organization identifier.
380
- * @param options - Optional per-request overrides.
381
- * @returns New API key and grace period expiry for the previous key.
382
- * @throws {@link HivemindError} 401 if admin credentials are invalid.
383
- * @throws {@link HivemindError} 404 if the organization does not exist.
384
- *
385
- * **Endpoint:** `POST /v1/organizations/{orgId}/api-keys/rotate`
386
- */
387
- rotateApiKey(orgId, options) {
388
- return this.post(`/organizations/${orgId}/api-keys/rotate`, undefined, options);
389
- }
390
- /**
391
- * Suspend an organization, blocking all API key access until reactivated.
392
- *
393
- * **Auth:** Requires `adminKey` in client config.
394
- *
395
- * @param orgId - Organization identifier.
396
- * @param options - Optional per-request overrides.
397
- * @returns Updated organization status.
398
- * @throws {@link HivemindError} 401 if admin credentials are invalid.
399
- * @throws {@link HivemindError} 404 if the organization does not exist.
400
- *
401
- * **Endpoint:** `POST /v1/organizations/{orgId}/suspend`
402
- */
403
- suspendOrganization(orgId, options) {
404
- return this.post(`/organizations/${orgId}/suspend`, undefined, options);
405
- }
406
- /**
407
- * Reactivate a suspended organization, restoring API key access.
408
- *
409
- * **Auth:** Requires `adminKey` in client config.
410
- *
411
- * @param orgId - Organization identifier.
412
- * @param options - Optional per-request overrides.
413
- * @returns Updated organization status.
414
- * @throws {@link HivemindError} 401 if admin credentials are invalid.
415
- * @throws {@link HivemindError} 404 if the organization does not exist.
416
- *
417
- * **Endpoint:** `POST /v1/organizations/{orgId}/reactivate`
418
- */
419
- reactivateOrganization(orgId, options) {
420
- return this.post(`/organizations/${orgId}/reactivate`, undefined, options);
421
- }
422
- /**
423
- * Permanently delete an organization and all associated data.
424
- * This action is irreversible.
425
- *
426
- * **Auth:** Requires `adminKey` in client config.
427
- *
428
- * @param orgId - Organization identifier.
429
- * @param options - Optional per-request overrides.
430
- * @throws {@link HivemindError} 401 if admin credentials are invalid.
431
- * @throws {@link HivemindError} 404 if the organization does not exist.
432
- *
433
- * **Endpoint:** `DELETE /v1/organizations/{orgId}`
434
- */
435
- deleteOrganization(orgId, options) {
436
- return this.del(`/organizations/${orgId}`, options);
437
- }
438
- // -----------------------------------------------------------------------
439
- // Documents
440
- // -----------------------------------------------------------------------
441
- /**
442
- * Upload and ingest a document file (PDF, TXT, DOCX, etc.).
443
- * The document is stored in GCS, split into chunks, and embedded for RAG retrieval.
444
- *
445
- * **Auth:** Requires org-scoped API key.
446
- *
447
- * @param orgId - Organization identifier.
448
- * @param file - Document content as a `Blob` or `Buffer`.
449
- * @param filename - Original filename (e.g. `"report.pdf"`).
450
- * @param options - Optional per-request overrides (e.g. `{ apiKey }`).
451
- * @returns Upload result with document ID, chunk count, and status.
452
- * @throws {@link HivemindError} 400 if the file exceeds the maximum upload size (default 25 MB).
453
- * @throws {@link HivemindError} 401 if API key is missing or invalid.
454
- * @throws {@link HivemindError} 429 if rate limit is exceeded.
455
- *
456
- * **Endpoint:** `POST /v1/organizations/{orgId}/documents/upload`
457
- * **Content-Type:** `multipart/form-data`
458
- *
459
- * @example
460
- * ```typescript
461
- * import { readFileSync } from "fs";
462
- * const file = readFileSync("./report.pdf");
463
- * const result = await client.uploadDocument("acme-corp", file, "report.pdf");
464
- * console.log(`Uploaded: ${result.document_id}, ${result.chunks} chunks`);
465
- * ```
466
- */
467
- async uploadDocument(orgId, file, filename, options) {
239
+ rotateApiKey(options) {
240
+ return this.post("/api-key/rotate", undefined, options);
241
+ }
242
+ async uploadDocument(file, filename, options) {
468
243
  const form = new FormData();
469
244
  const blob = file instanceof Blob ? file : new Blob([file], { type: "application/octet-stream" });
470
245
  form.append("file", blob, filename);
471
- return this.request("POST", `/organizations/${orgId}/documents/upload`, { formData: form, apiKey: options?.apiKey });
472
- }
473
- // -----------------------------------------------------------------------
474
- // Query (RAG)
475
- // -----------------------------------------------------------------------
476
- /**
477
- * Query the organization's document knowledge base using RAG
478
- * (Retrieval-Augmented Generation). Retrieves relevant document chunks,
479
- * then generates a response with citations.
480
- *
481
- * **Auth:** Requires org-scoped API key.
482
- *
483
- * @param orgId - Organization identifier.
484
- * @param params - Query parameters (query text, model, temperature, strategy).
485
- * @param options - Optional per-request overrides (e.g. `{ apiKey }`).
486
- * @returns Generated answer with source citations, confidence, and processing time.
487
- * @throws {@link HivemindError} 401 if API key is missing or invalid.
488
- * @throws {@link HivemindError} 403 if cross-organization access is attempted.
489
- * @throws {@link HivemindError} 429 if rate limit or token quota is exceeded.
490
- *
491
- * **Endpoint:** `POST /v1/organizations/{orgId}/query`
492
- *
493
- * @example
494
- * ```typescript
495
- * const result = await client.query("acme-corp", {
496
- * query: "What are the key findings in Q4?",
497
- * temperature: 0.2,
498
- * retrieval_strategy: "hybrid",
499
- * });
500
- * console.log(result.answer);
501
- * console.log(result.sources); // citations with doc_id, chunk_id, score, snippet
502
- * ```
503
- */
504
- query(orgId, params, options) {
505
- return this.post(`/organizations/${orgId}/query`, params, options);
506
- }
507
- /**
508
- * Search indexed sources for source discovery.
509
- *
510
- * **Auth:** Requires org-scoped API key.
511
- *
512
- * **Endpoint:** `POST /v1/organizations/{orgId}/search`
513
- */
514
- search(orgId, params, options) {
515
- return this.post(`/organizations/${orgId}/search`, params, options);
516
- }
517
- // -----------------------------------------------------------------------
518
- // Content Creator
519
- // -----------------------------------------------------------------------
520
- createProject(orgId, params, options) {
521
- return this.post(`/organizations/${orgId}/projects`, params, options);
522
- }
523
- listProjects(orgId, options) {
524
- return this.get(`/organizations/${orgId}/projects`, undefined, options);
525
- }
526
- getProject(orgId, projectId, options) {
527
- return this.get(`/organizations/${orgId}/projects/${projectId}`, undefined, options);
528
- }
529
- updateProject(orgId, projectId, params, options) {
530
- return this.patch(`/organizations/${orgId}/projects/${projectId}`, params, options);
531
- }
532
- deleteProject(orgId, projectId, options) {
533
- return this.del(`/organizations/${orgId}/projects/${projectId}`, options);
534
- }
535
- chatProject(orgId, projectId, params, options) {
536
- return this.post(`/organizations/${orgId}/projects/${projectId}/chat`, params, options);
537
- }
538
- getProjectChatHistory(orgId, projectId, userId, options) {
539
- return this.get(`/organizations/${orgId}/projects/${projectId}/chat`, { user_id: userId }, options);
540
- }
541
- createContentItem(orgId, projectId, params, options) {
542
- return this.post(`/organizations/${orgId}/projects/${projectId}/content`, params, options);
543
- }
544
- listContentItems(orgId, projectId, options) {
545
- return this.get(`/organizations/${orgId}/projects/${projectId}/content`, undefined, options);
546
- }
547
- getContentItem(orgId, projectId, contentId, options) {
548
- return this.get(`/organizations/${orgId}/projects/${projectId}/content/${contentId}`, undefined, options);
549
- }
550
- updateContentItem(orgId, projectId, contentId, params, options) {
551
- return this.patch(`/organizations/${orgId}/projects/${projectId}/content/${contentId}`, params, options);
552
- }
553
- deleteContentItem(orgId, projectId, contentId, options) {
554
- return this.del(`/organizations/${orgId}/projects/${projectId}/content/${contentId}`, options);
555
- }
556
- createProjectSource(orgId, projectId, params, options) {
557
- return this.post(`/organizations/${orgId}/projects/${projectId}/sources`, params, options);
558
- }
559
- /**
560
- * Scrape external URLs and save the normalized results as project sources.
561
- *
562
- * **Auth:** Requires org-scoped API key.
563
- *
564
- * **Endpoint:** `POST /v1/organizations/{orgId}/projects/{projectId}/sources/scrape`
565
- */
566
- scrapeProjectSources(orgId, projectId, params, options) {
567
- return this.post(`/organizations/${orgId}/projects/${projectId}/sources/scrape`, params, options);
568
- }
569
- listProjectSources(orgId, projectId, options) {
570
- return this.get(`/organizations/${orgId}/projects/${projectId}/sources`, undefined, options);
571
- }
572
- getProjectSource(orgId, projectId, sourceId, options) {
573
- return this.get(`/organizations/${orgId}/projects/${projectId}/sources/${sourceId}`, undefined, options);
574
- }
575
- updateProjectSource(orgId, projectId, sourceId, params, options) {
576
- return this.patch(`/organizations/${orgId}/projects/${projectId}/sources/${sourceId}`, params, options);
577
- }
578
- deleteProjectSource(orgId, projectId, sourceId, options) {
579
- return this.del(`/organizations/${orgId}/projects/${projectId}/sources/${sourceId}`, options);
580
- }
581
- /**
582
- * Create a publish schedule for an existing content item.
583
- *
584
- * **Auth:** Requires org-scoped API key.
585
- *
586
- * **Endpoint:** `POST /v1/organizations/{orgId}/projects/{projectId}/schedules`
587
- */
588
- createPublishSchedule(orgId, projectId, params, options) {
589
- return this.post(`/organizations/${orgId}/projects/${projectId}/schedules`, params, options);
590
- }
591
- /**
592
- * List publish schedules for a project.
593
- *
594
- * **Auth:** Requires org-scoped API key.
595
- *
596
- * **Endpoint:** `GET /v1/organizations/{orgId}/projects/{projectId}/schedules`
597
- */
598
- listPublishSchedules(orgId, projectId, options) {
599
- return this.get(`/organizations/${orgId}/projects/${projectId}/schedules`, undefined, options);
600
- }
601
- /**
602
- * Get a single publish schedule.
603
- *
604
- * **Auth:** Requires org-scoped API key.
605
- *
606
- * **Endpoint:** `GET /v1/organizations/{orgId}/projects/{projectId}/schedules/{scheduleId}`
607
- */
608
- getPublishSchedule(orgId, projectId, scheduleId, options) {
609
- return this.get(`/organizations/${orgId}/projects/${projectId}/schedules/${scheduleId}`, undefined, options);
610
- }
611
- /**
612
- * Update a publish schedule.
613
- *
614
- * **Auth:** Requires org-scoped API key.
615
- *
616
- * **Endpoint:** `PATCH /v1/organizations/{orgId}/projects/{projectId}/schedules/{scheduleId}`
617
- */
618
- updatePublishSchedule(orgId, projectId, scheduleId, params, options) {
619
- return this.patch(`/organizations/${orgId}/projects/${projectId}/schedules/${scheduleId}`, params, options);
620
- }
621
- /**
622
- * Delete a publish schedule.
623
- *
624
- * **Auth:** Requires org-scoped API key.
625
- *
626
- * **Endpoint:** `DELETE /v1/organizations/{orgId}/projects/{projectId}/schedules/{scheduleId}`
627
- */
628
- deletePublishSchedule(orgId, projectId, scheduleId, options) {
629
- return this.del(`/organizations/${orgId}/projects/${projectId}/schedules/${scheduleId}`, options);
630
- }
631
- /**
632
- * Manually run due Content Creator schedules immediately.
633
- *
634
- * This is primarily an admin fallback or operational tool. In normal
635
- * deployments, due schedules are processed automatically by the backend's
636
- * background content schedule runner.
637
- *
638
- * **Auth:** Requires admin key.
639
- *
640
- * **Endpoint:** `POST /v1/admin/content-creator/schedules/run-due`
641
- */
246
+ return this.request("POST", "/documents/upload", {
247
+ formData: form,
248
+ apiKey: options?.apiKey,
249
+ });
250
+ }
251
+ query(params, options) {
252
+ return this.post("/query", params, options);
253
+ }
254
+ search(params, options) {
255
+ return this.post("/search", params, options);
256
+ }
257
+ createProject(params, options) {
258
+ return this.post("/projects", params, options);
259
+ }
260
+ listProjects(options) {
261
+ return this.get("/projects", undefined, options);
262
+ }
263
+ getProject(projectId, options) {
264
+ return this.get(`/projects/${projectId}`, undefined, options);
265
+ }
266
+ updateProject(projectId, params, options) {
267
+ return this.patch(`/projects/${projectId}`, params, options);
268
+ }
269
+ deleteProject(projectId, options) {
270
+ return this.del(`/projects/${projectId}`, options);
271
+ }
272
+ chatProject(projectId, params, options) {
273
+ return this.post(`/projects/${projectId}/chat`, params, options);
274
+ }
275
+ getProjectChatHistory(projectId, userId, options) {
276
+ return this.get(`/projects/${projectId}/chat`, { user_id: userId }, options);
277
+ }
278
+ createContentItem(projectId, params, options) {
279
+ return this.post(`/projects/${projectId}/content`, params, options);
280
+ }
281
+ listContentItems(projectId, options) {
282
+ return this.get(`/projects/${projectId}/content`, undefined, options);
283
+ }
284
+ getContentItem(projectId, contentId, options) {
285
+ return this.get(`/projects/${projectId}/content/${contentId}`, undefined, options);
286
+ }
287
+ updateContentItem(projectId, contentId, params, options) {
288
+ return this.patch(`/projects/${projectId}/content/${contentId}`, params, options);
289
+ }
290
+ deleteContentItem(projectId, contentId, options) {
291
+ return this.del(`/projects/${projectId}/content/${contentId}`, options);
292
+ }
293
+ createProjectSource(projectId, params, options) {
294
+ return this.post(`/projects/${projectId}/sources`, params, options);
295
+ }
296
+ scrapeProjectSources(projectId, params, options) {
297
+ return this.post(`/projects/${projectId}/sources/scrape`, params, options);
298
+ }
299
+ listProjectSources(projectId, options) {
300
+ return this.get(`/projects/${projectId}/sources`, undefined, options);
301
+ }
302
+ getProjectSource(projectId, sourceId, options) {
303
+ return this.get(`/projects/${projectId}/sources/${sourceId}`, undefined, options);
304
+ }
305
+ updateProjectSource(projectId, sourceId, params, options) {
306
+ return this.patch(`/projects/${projectId}/sources/${sourceId}`, params, options);
307
+ }
308
+ deleteProjectSource(projectId, sourceId, options) {
309
+ return this.del(`/projects/${projectId}/sources/${sourceId}`, options);
310
+ }
311
+ createPublishSchedule(projectId, params, options) {
312
+ return this.post(`/projects/${projectId}/schedules`, params, options);
313
+ }
314
+ listPublishSchedules(projectId, options) {
315
+ return this.get(`/projects/${projectId}/schedules`, undefined, options);
316
+ }
317
+ getPublishSchedule(projectId, scheduleId, options) {
318
+ return this.get(`/projects/${projectId}/schedules/${scheduleId}`, undefined, options);
319
+ }
320
+ updatePublishSchedule(projectId, scheduleId, params, options) {
321
+ return this.patch(`/projects/${projectId}/schedules/${scheduleId}`, params, options);
322
+ }
323
+ deletePublishSchedule(projectId, scheduleId, options) {
324
+ return this.del(`/projects/${projectId}/schedules/${scheduleId}`, options);
325
+ }
642
326
  runDueSchedules() {
643
327
  return this.post("/admin/content-creator/schedules/run-due");
644
328
  }
645
- // -----------------------------------------------------------------------
646
- // Generation
647
- // -----------------------------------------------------------------------
648
- /**
649
- * Start an asynchronous video generation job using Vertex AI Veo.
650
- * Returns a job ID — poll with `getJob()` or `waitForJob()` for results.
651
- *
652
- * **Auth:** Requires org-scoped API key.
653
- *
654
- * @param orgId - Organization identifier.
655
- * @param params - Video generation parameters (prompt, duration, aspect_ratio, style).
656
- * @param options - Optional per-request overrides.
657
- * @returns Job ID and estimated processing time (HTTP 202).
658
- * @throws {@link HivemindError} 429 if rate limit, video quota, or concurrent job limit is exceeded.
659
- *
660
- * **Endpoint:** `POST /v1/organizations/{orgId}/generate/video`
661
- *
662
- * @example
663
- * ```typescript
664
- * const job = await client.generateVideo("acme-corp", {
665
- * prompt: "A drone flyover of a mountain lake at sunset",
666
- * duration: 8,
667
- * aspect_ratio: "16:9",
668
- * style: "cinematic",
669
- * });
670
- * const result = await client.waitForJob("acme-corp", job.job_id);
671
- * console.log(result.result); // { output_url, signed_url }
672
- * ```
673
- */
674
- generateVideo(orgId, params, options) {
675
- return this.post(`/organizations/${orgId}/generate/video`, params, options);
676
- }
677
- /**
678
- * Start an asynchronous image generation job using Vertex AI Imagen.
679
- * Returns a job ID — poll with `getJob()` or `waitForJob()` for results.
680
- *
681
- * **Auth:** Requires org-scoped API key.
682
- *
683
- * @param orgId - Organization identifier.
684
- * @param params - Image generation parameters (prompt, aspect_ratio, style, num_images).
685
- * @param options - Optional per-request overrides.
686
- * @returns Job ID and estimated processing time (HTTP 202).
687
- * @throws {@link HivemindError} 429 if rate limit, image quota, or concurrent job limit is exceeded.
688
- *
689
- * **Endpoint:** `POST /v1/organizations/{orgId}/generate/image`
690
- *
691
- * @example
692
- * ```typescript
693
- * const job = await client.generateImage("acme-corp", {
694
- * prompt: "A futuristic city skyline at dusk",
695
- * aspect_ratio: "16:9",
696
- * style: "digital art",
697
- * num_images: 4,
698
- * });
699
- * const result = await client.waitForJob("acme-corp", job.job_id);
700
- * ```
701
- */
702
- generateImage(orgId, params, options) {
703
- return this.post(`/organizations/${orgId}/generate/image`, params, options);
704
- }
705
- /**
706
- * Start an asynchronous music generation job.
707
- * Returns a job ID — poll with `getJob()` or `waitForJob()` for results.
708
- *
709
- * **Auth:** Requires org-scoped API key.
710
- *
711
- * **Endpoint:** `POST /v1/organizations/{orgId}/generate/music`
712
- */
713
- generateMusic(orgId, params, options) {
714
- return this.post(`/organizations/${orgId}/generate/music`, params, options);
715
- }
716
- // -----------------------------------------------------------------------
717
- // Jobs
718
- // -----------------------------------------------------------------------
719
- /**
720
- * Check the status of an asynchronous job (video or image generation).
721
- *
722
- * **Auth:** Requires org-scoped API key.
723
- *
724
- * @param orgId - Organization identifier.
725
- * @param jobId - Job identifier (from `generateVideo()` or `generateImage()`).
726
- * @param options - Optional per-request overrides.
727
- * @returns Job status, result URLs (when completed), or error details (when failed).
728
- * @throws {@link HivemindError} 404 if the job does not exist.
729
- *
730
- * **Endpoint:** `GET /v1/organizations/{orgId}/jobs/{jobId}`
731
- */
732
- getJob(orgId, jobId, options) {
733
- return this.get(`/organizations/${orgId}/jobs/${jobId}`, undefined, options);
734
- }
735
- /**
736
- * Poll a job until it reaches a terminal status (`completed`, `failed`, or `cancelled`).
737
- *
738
- * @param orgId - Organization identifier.
739
- * @param jobId - Job identifier.
740
- * @param intervalMs - Polling interval in milliseconds. @default 2000
741
- * @param maxWaitMs - Maximum wait time in milliseconds. @default 300000 (5 min)
742
- * @param options - Optional per-request overrides.
743
- * @returns Final job status with result or error.
744
- * @throws Error if the job does not complete within `maxWaitMs`.
745
- *
746
- * @example
747
- * ```typescript
748
- * const job = await client.generateVideo("acme-corp", { prompt: "..." });
749
- * const result = await client.waitForJob("acme-corp", job.job_id, 3000, 600_000);
750
- * if (result.status === "completed") console.log(result.result);
751
- * ```
752
- */
753
- async waitForJob(orgId, jobId, intervalMs = 2000, maxWaitMs = 300_000, options) {
329
+ generateVideo(params, options) {
330
+ return this.post("/generate/video", params, options);
331
+ }
332
+ generateImage(params, options) {
333
+ return this.post("/generate/image", params, options);
334
+ }
335
+ generateMusic(params, options) {
336
+ return this.post("/generate/music", params, options);
337
+ }
338
+ getJob(jobId, options) {
339
+ return this.get(`/jobs/${jobId}`, undefined, options);
340
+ }
341
+ async waitForJob(jobId, intervalMs = 2000, maxWaitMs = 300_000, options) {
754
342
  const start = Date.now();
755
343
  while (Date.now() - start < maxWaitMs) {
756
- const job = await this.getJob(orgId, jobId, options);
344
+ const job = await this.getJob(jobId, options);
757
345
  if (["completed", "failed", "cancelled"].includes(job.status)) {
758
346
  return job;
759
347
  }
760
- await new Promise((r) => setTimeout(r, intervalMs));
348
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
761
349
  }
762
350
  throw new Error(`Job ${jobId} did not complete within ${maxWaitMs}ms`);
763
351
  }
764
- // -----------------------------------------------------------------------
765
- // Data chat
766
- // -----------------------------------------------------------------------
767
- /**
768
- * Ask a natural-language question over BigQuery datasets.
769
- * Gemini generates SQL from the question, executes it, and returns formatted results.
770
- *
771
- * **Auth:** Requires org-scoped API key.
772
- *
773
- * @param orgId - Organization identifier.
774
- * @param params - Question and optional user ID.
775
- * @param options - Optional per-request overrides.
776
- * @returns Generated SQL, natural-language answer, and result rows.
777
- * @throws {@link HivemindError} 429 if rate limit or token quota is exceeded.
778
- *
779
- * **Endpoint:** `POST /v1/organizations/{orgId}/data-chat`
780
- *
781
- * @example
782
- * ```typescript
783
- * const result = await client.dataChat("acme-corp", {
784
- * question: "How many active users this month?",
785
- * });
786
- * console.log(result.answer); // "There are 1,247 active users this month."
787
- * console.log(result.sql); // Generated SQL
788
- * console.log(result.rows); // [{ active_users: 1247 }]
789
- * ```
790
- */
791
- dataChat(orgId, params, options) {
792
- return this.post(`/organizations/${orgId}/data-chat`, params, options);
793
- }
794
- // -----------------------------------------------------------------------
795
- // Agents
796
- // -----------------------------------------------------------------------
797
- /**
798
- * Create a custom AI agent template with system instructions and optional tool bindings.
799
- *
800
- * **Auth:** Requires org-scoped API key.
801
- *
802
- * @param orgId - Organization identifier.
803
- * @param params - Agent name, instructions, and optional tools.
804
- * @param options - Optional per-request overrides.
805
- * @returns Created agent with ID, name, and enabled tools.
806
- *
807
- * **Endpoint:** `POST /v1/organizations/{orgId}/agents/custom`
808
- *
809
- * @example
810
- * ```typescript
811
- * const agent = await client.createAgent("acme-corp", {
812
- * name: "Support Bot",
813
- * instructions: "You are a helpful customer support agent.",
814
- * tools: ["rag_search", "ticket_create"],
815
- * });
816
- * console.log(agent.agent_id);
817
- * ```
818
- */
819
- createAgent(orgId, params, options) {
820
- return this.post(`/organizations/${orgId}/agents/custom`, params, options);
821
- }
822
- /**
823
- * Send a query to an AI agent. Routes to the specified agent type or auto-selects.
824
- *
825
- * **Auth:** Requires org-scoped API key.
826
- *
827
- * @param orgId - Organization identifier.
828
- * @param params - Query text, user ID, and optional agent type.
829
- * @param options - Optional per-request overrides.
830
- * @returns Agent response text, agent type, and any tool calls made.
831
- * @throws {@link HivemindError} 429 if rate limit or token quota is exceeded.
832
- *
833
- * **Endpoint:** `POST /v1/organizations/{orgId}/agents/query`
834
- */
835
- queryAgent(orgId, params, options) {
836
- return this.post(`/organizations/${orgId}/agents/query`, params, options);
837
- }
838
- // -----------------------------------------------------------------------
839
- // Audio
840
- // -----------------------------------------------------------------------
841
- /**
842
- * Transcribe audio content to text (speech-to-text).
843
- *
844
- * **Auth:** Requires org-scoped API key.
845
- *
846
- * @param orgId - Organization identifier.
847
- * @param params - Audio content and optional BCP-47 language code.
848
- * @param options - Optional per-request overrides.
849
- * @returns Transcription result with transcript text, confidence, and language.
850
- * @throws {@link HivemindError} 429 if rate limit is exceeded.
851
- *
852
- * **Endpoint:** `POST /v1/organizations/{orgId}/audio/transcribe`
853
- */
854
- transcribeAudio(orgId, params, options) {
855
- return this.post(`/organizations/${orgId}/audio/transcribe`, params, options);
856
- }
857
- /**
858
- * Convert text to speech (text-to-speech synthesis).
859
- * Returns a signed URL to the generated audio file.
860
- *
861
- * **Auth:** Requires org-scoped API key.
862
- *
863
- * @param orgId - Organization identifier.
864
- * @param params - Text to synthesize and optional voice name.
865
- * @param options - Optional per-request overrides.
866
- * @returns Audio URL, duration, and voice used.
867
- * @throws {@link HivemindError} 429 if rate limit is exceeded.
868
- *
869
- * **Endpoint:** `POST /v1/organizations/{orgId}/audio/synthesize`
870
- */
871
- synthesizeAudio(orgId, params, options) {
872
- return this.post(`/organizations/${orgId}/audio/synthesize`, params, options);
873
- }
874
- // -----------------------------------------------------------------------
875
- // Analytics / ML
876
- // -----------------------------------------------------------------------
877
- /**
878
- * Train a predictive model on tabular data.
879
- *
880
- * **Auth:** Requires org-scoped API key.
881
- *
882
- * @param orgId - Organization identifier.
883
- * @param params - Target column, feature columns, and training data rows.
884
- * @param options - Optional per-request overrides.
885
- * @returns Deployed model ID and status.
886
- *
887
- * **Endpoint:** `POST /v1/organizations/{orgId}/analytics/train`
888
- *
889
- * @example
890
- * ```typescript
891
- * const model = await client.trainModel("acme-corp", {
892
- * target_column: "churn",
893
- * feature_columns: ["tenure", "monthly_charges", "total_charges"],
894
- * rows: [
895
- * { tenure: 12, monthly_charges: 50, total_charges: 600, churn: 0 },
896
- * { tenure: 2, monthly_charges: 80, total_charges: 160, churn: 1 },
897
- * ],
898
- * });
899
- * console.log(model.model_id); // Use with predict()
900
- * ```
901
- */
902
- trainModel(orgId, params, options) {
903
- return this.post(`/organizations/${orgId}/analytics/train`, params, options);
904
- }
905
- /**
906
- * Run predictions using a previously trained model.
907
- *
908
- * **Auth:** Requires org-scoped API key.
909
- *
910
- * @param orgId - Organization identifier.
911
- * @param params - Model ID and data instances to predict on.
912
- * @param options - Optional per-request overrides.
913
- * @returns Predictions for each input instance.
914
- * @throws {@link HivemindError} 404 if the model does not exist.
915
- *
916
- * **Endpoint:** `POST /v1/organizations/{orgId}/analytics/predict`
917
- */
918
- predict(orgId, params, options) {
919
- return this.post(`/organizations/${orgId}/analytics/predict`, params, options);
920
- }
921
- /**
922
- * Generate a time-series forecast from historical data using ARIMA-based modeling.
923
- *
924
- * **Auth:** Requires org-scoped API key.
925
- *
926
- * @param orgId - Organization identifier.
927
- * @param params - Historical series values and optional forecast horizon (1–365).
928
- * @param options - Optional per-request overrides.
929
- * @returns Predicted future values.
930
- *
931
- * **Endpoint:** `POST /v1/organizations/{orgId}/analytics/forecast`
932
- */
933
- forecast(orgId, params, options) {
934
- return this.post(`/organizations/${orgId}/analytics/forecast`, params, options);
935
- }
936
- // -----------------------------------------------------------------------
937
- // Billing
938
- // -----------------------------------------------------------------------
939
- /**
940
- * Get the monthly usage summary for an organization.
941
- * Includes token, image, video, storage, and compute usage against tier limits.
942
- *
943
- * **Auth:** Requires org-scoped API key.
944
- *
945
- * @param orgId - Organization identifier.
946
- * @param month - Month in `YYYY-MM` format. Defaults to current month.
947
- * @param options - Optional per-request overrides.
948
- * @returns Usage counters, tier limits, and quota status.
949
- *
950
- * **Endpoint:** `GET /v1/organizations/{orgId}/usage?month={month}`
951
- */
952
- getUsage(orgId, month, options) {
953
- const query = month ? { month } : undefined;
954
- return this.get(`/organizations/${orgId}/usage`, query, options);
955
- }
956
- /**
957
- * Get the monthly invoice with detailed cost breakdown by resource type.
958
- *
959
- * **Auth:** Requires org-scoped API key.
960
- *
961
- * @param orgId - Organization identifier.
962
- * @param month - Month in `YYYY-MM` format. Defaults to current month.
963
- * @param options - Optional per-request overrides.
964
- * @returns Invoice with itemized costs and total in USD.
965
- *
966
- * **Endpoint:** `GET /v1/organizations/{orgId}/invoice?month={month}`
967
- */
968
- getInvoice(orgId, month, options) {
969
- const query = month ? { month } : undefined;
970
- return this.get(`/organizations/${orgId}/invoice`, query, options);
971
- }
972
- // -----------------------------------------------------------------------
973
- // Audit
974
- // -----------------------------------------------------------------------
975
- /**
976
- * Retrieve audit log records for an organization.
977
- *
978
- * **Auth:** Requires org-scoped API key.
979
- *
980
- * @param orgId - Organization identifier.
981
- * @param options - Optional per-request overrides.
982
- * @returns Audit log entries with timestamps, actions, and metadata.
983
- *
984
- * **Endpoint:** `GET /v1/organizations/{orgId}/audit`
985
- */
986
- getAuditLogs(orgId, options) {
987
- return this.get(`/organizations/${orgId}/audit`, undefined, options);
988
- }
989
- // -----------------------------------------------------------------------
990
- // Scraping
991
- // -----------------------------------------------------------------------
992
- /**
993
- * Get the current scraping runtime configuration.
994
- *
995
- * **Auth:** None required.
996
- *
997
- * @returns Execution mode, Cloud Run status, and cache statistics.
998
- *
999
- * **Endpoint:** `GET /v1/scraping/config`
1000
- */
352
+ dataChat(params, options) {
353
+ return this.post("/data-chat", params, options);
354
+ }
355
+ createAgent(params, options) {
356
+ return this.post("/agents/custom", params, options);
357
+ }
358
+ queryAgent(params, options) {
359
+ return this.post("/agents/query", params, options);
360
+ }
361
+ transcribeAudio(params, options) {
362
+ return this.post("/audio/transcribe", params, options);
363
+ }
364
+ synthesizeAudio(params, options) {
365
+ return this.post("/audio/synthesize", params, options);
366
+ }
367
+ trainModel(params, options) {
368
+ return this.post("/analytics/train", params, options);
369
+ }
370
+ predict(params, options) {
371
+ return this.post("/analytics/predict", params, options);
372
+ }
373
+ forecast(params, options) {
374
+ return this.post("/analytics/forecast", params, options);
375
+ }
376
+ getAuditLogs(options) {
377
+ return this.get("/audit", undefined, options);
378
+ }
1001
379
  getScrapingConfig() {
1002
380
  return this.get("/scraping/config");
1003
381
  }
1004
- /**
1005
- * Submit URLs for scraping. JS-heavy sites (Reddit, Twitter, LinkedIn)
1006
- * are auto-routed to Selenium.
1007
- *
1008
- * **Auth:** None required.
1009
- *
1010
- * @param params - Object containing the `urls` array.
1011
- * @returns Task ID and submission status.
1012
- *
1013
- * **Endpoint:** `POST /v1/scraping/scrape`
1014
- */
1015
382
  scrape(params) {
1016
383
  return this.post("/scraping/scrape", params);
1017
384
  }
1018
- /**
1019
- * Check the status and results of a scrape task.
1020
- *
1021
- * **Auth:** None required.
1022
- *
1023
- * @param taskId - Task identifier (from `scrape()`).
1024
- * @returns Task status and scraped results (empty while pending).
1025
- *
1026
- * **Endpoint:** `GET /v1/scraping/status/{taskId}`
1027
- */
1028
385
  getScrapeStatus(taskId) {
1029
386
  return this.get(`/scraping/status/${taskId}`);
1030
387
  }
1031
- /**
1032
- * Submit a scrape job and poll until results are ready.
1033
- *
1034
- * @param urls - URLs to scrape.
1035
- * @param intervalMs - Polling interval in milliseconds. @default 2000
1036
- * @param maxWaitMs - Maximum wait time in milliseconds. @default 120000 (2 min)
1037
- * @returns Final scrape status with results.
1038
- * @throws Error if the task does not complete within `maxWaitMs`.
1039
- *
1040
- * @example
1041
- * ```typescript
1042
- * const result = await client.scrapeAndWait(
1043
- * ["https://example.com", "https://example.org"],
1044
- * 2000,
1045
- * 60_000,
1046
- * );
1047
- * for (const item of result.result) {
1048
- * console.log(item.title, item.full_text?.substring(0, 200));
1049
- * }
1050
- * ```
1051
- */
1052
388
  async scrapeAndWait(urls, intervalMs = 2000, maxWaitMs = 120_000) {
1053
389
  const { task_id } = await this.scrape({ urls });
1054
390
  const start = Date.now();
@@ -1057,679 +393,158 @@ class HivemindClient {
1057
393
  if (["SUCCESS", "FAILURE", "completed"].includes(status.status)) {
1058
394
  return status;
1059
395
  }
1060
- await new Promise((r) => setTimeout(r, intervalMs));
396
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
1061
397
  }
1062
398
  throw new Error(`Scrape ${task_id} did not complete within ${maxWaitMs}ms`);
1063
399
  }
1064
- // -----------------------------------------------------------------------
1065
- // Webhooks
1066
- // -----------------------------------------------------------------------
1067
- /**
1068
- * Send a video generation completion webhook notification.
1069
- *
1070
- * **Auth:** Requires `webhookSecret` in client config (sends `X-Webhook-Secret` header).
1071
- *
1072
- * @param payload - Webhook payload with job_id, org_id, status, and optional metadata.
1073
- * @returns `{ received: true }` on success.
1074
- * @throws {@link HivemindError} 401 if the webhook secret is invalid.
1075
- *
1076
- * **Endpoint:** `POST /v1/webhook/video-complete`
1077
- */
1078
400
  sendVideoCompleteWebhook(payload) {
1079
401
  return this.post("/webhook/video-complete", payload);
1080
402
  }
1081
- /**
1082
- * Send a document processing completion webhook notification.
1083
- *
1084
- * **Auth:** Requires `webhookSecret` in client config (sends `X-Webhook-Secret` header).
1085
- *
1086
- * @param payload - Webhook payload with document_id, org_id, status, and optional metadata.
1087
- * @returns `{ received: true }` on success.
1088
- * @throws {@link HivemindError} 401 if the webhook secret is invalid.
1089
- *
1090
- * **Endpoint:** `POST /v1/webhook/document-processed`
1091
- */
1092
403
  sendDocumentProcessedWebhook(payload) {
1093
404
  return this.post("/webhook/document-processed", payload);
1094
405
  }
1095
- // -----------------------------------------------------------------------
1096
- // Admin — Configuration
1097
- // -----------------------------------------------------------------------
1098
- /**
1099
- * Get full service configuration overview.
1100
- *
1101
- * **Auth:** Requires `adminKey` in client config.
1102
- *
1103
- * **Endpoint:** `GET /v1/admin/config`
1104
- */
1105
406
  getAdminConfig() {
1106
407
  return this.get("/admin/config");
1107
408
  }
1108
- /**
1109
- * Get runtime setting overrides.
1110
- *
1111
- * **Auth:** Requires `adminKey` in client config.
1112
- *
1113
- * **Endpoint:** `GET /v1/admin/config/overrides`
1114
- */
1115
409
  getAdminConfigOverrides() {
1116
410
  return this.get("/admin/config/overrides");
1117
411
  }
1118
- /**
1119
- * Update a mutable runtime setting (e.g. log_level, debug, cors_allow_origins).
1120
- *
1121
- * **Auth:** Requires `adminKey` in client config.
1122
- *
1123
- * @param params - Setting key and new value.
1124
- *
1125
- * **Endpoint:** `PUT /v1/admin/settings`
1126
- */
1127
412
  updateAdminSetting(params) {
1128
413
  return this.put("/admin/settings", params);
1129
414
  }
1130
- // -----------------------------------------------------------------------
1131
- // Admin — Logging
1132
- // -----------------------------------------------------------------------
1133
- /**
1134
- * Get the current application log level.
1135
- *
1136
- * **Auth:** Requires `adminKey` in client config.
1137
- *
1138
- * **Endpoint:** `GET /v1/admin/logging/level`
1139
- */
1140
415
  getLogLevel() {
1141
416
  return this.get("/admin/logging/level");
1142
417
  }
1143
- /**
1144
- * Change the application log level.
1145
- *
1146
- * **Auth:** Requires `adminKey` in client config.
1147
- *
1148
- * @param params - The new log level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
1149
- *
1150
- * **Endpoint:** `PUT /v1/admin/logging/level`
1151
- */
1152
418
  setLogLevel(params) {
1153
419
  return this.put("/admin/logging/level", params);
1154
420
  }
1155
- /**
1156
- * List all loggers with their levels and handlers.
1157
- *
1158
- * **Auth:** Requires `adminKey` in client config.
1159
- *
1160
- * **Endpoint:** `GET /v1/admin/logging/loggers`
1161
- */
1162
421
  getLoggers() {
1163
422
  return this.get("/admin/logging/loggers");
1164
423
  }
1165
- // -----------------------------------------------------------------------
1166
- // Admin — Traffic & Monitoring
1167
- // -----------------------------------------------------------------------
1168
- /**
1169
- * Get inbound traffic statistics.
1170
- *
1171
- * **Auth:** Requires `adminKey` in client config.
1172
- *
1173
- * **Endpoint:** `GET /v1/admin/traffic/inbound`
1174
- */
1175
424
  getInboundTraffic() {
1176
425
  return this.get("/admin/traffic/inbound");
1177
426
  }
1178
- /**
1179
- * Reset inbound traffic counters.
1180
- *
1181
- * **Auth:** Requires `adminKey` in client config.
1182
- *
1183
- * **Endpoint:** `POST /v1/admin/traffic/inbound/reset`
1184
- */
1185
427
  resetInboundTraffic() {
1186
428
  return this.post("/admin/traffic/inbound/reset");
1187
429
  }
1188
- /**
1189
- * Check health of outbound dependencies (GCP, Vertex, BigQuery, Redis).
1190
- *
1191
- * **Auth:** Requires `adminKey` in client config.
1192
- *
1193
- * **Endpoint:** `GET /v1/admin/traffic/outbound`
1194
- */
1195
430
  getOutboundStatus() {
1196
431
  return this.get("/admin/traffic/outbound");
1197
432
  }
1198
- // -----------------------------------------------------------------------
1199
- // Admin — CORS
1200
- // -----------------------------------------------------------------------
1201
- /**
1202
- * Get the current CORS allowed origins.
1203
- *
1204
- * **Auth:** Requires `adminKey` in client config.
1205
- *
1206
- * **Endpoint:** `GET /v1/admin/cors`
1207
- */
1208
433
  getCors() {
1209
434
  return this.get("/admin/cors");
1210
435
  }
1211
- /**
1212
- * Update the CORS allowed origins.
1213
- *
1214
- * **Auth:** Requires `adminKey` in client config.
1215
- *
1216
- * @param allowOrigins - Comma-separated origins or `"*"`.
1217
- *
1218
- * **Endpoint:** `PUT /v1/admin/cors`
1219
- */
1220
436
  setCors(allowOrigins) {
1221
437
  return this.put("/admin/cors", { allow_origins: allowOrigins });
1222
438
  }
1223
- // -----------------------------------------------------------------------
1224
- // Admin — Rate Limiting
1225
- // -----------------------------------------------------------------------
1226
- /**
1227
- * List all rate-limit entries.
1228
- *
1229
- * **Auth:** Requires `adminKey` in client config.
1230
- *
1231
- * **Endpoint:** `GET /v1/admin/rate-limits`
1232
- */
1233
439
  getRateLimits() {
1234
440
  return this.get("/admin/rate-limits");
1235
441
  }
1236
- /**
1237
- * Reset the rate-limit counter for an organization.
1238
- *
1239
- * **Auth:** Requires `adminKey` in client config.
1240
- *
1241
- * @param orgId - Organization identifier.
1242
- *
1243
- * **Endpoint:** `POST /v1/admin/rate-limits/reset/{orgId}`
1244
- */
1245
- resetRateLimit(orgId) {
1246
- return this.post(`/admin/rate-limits/reset/${orgId}`);
1247
- }
1248
- // -----------------------------------------------------------------------
1249
- // Admin — Organization & Job listing
1250
- // -----------------------------------------------------------------------
1251
- /**
1252
- * List all organizations (admin view).
1253
- *
1254
- * **Auth:** Requires `adminKey` in client config.
1255
- *
1256
- * @param limit - Maximum number of organizations to return (1–1000, default 100).
1257
- *
1258
- * **Endpoint:** `GET /v1/admin/organizations`
1259
- */
1260
- listOrganizations(limit) {
1261
- const query = limit !== undefined ? { limit: String(limit) } : undefined;
1262
- return this.get("/admin/organizations", query);
1263
- }
1264
- /**
1265
- * Get a single organization (admin view).
1266
- *
1267
- * **Auth:** Requires `adminKey` in client config.
1268
- *
1269
- * @param orgId - Organization identifier.
1270
- *
1271
- * **Endpoint:** `GET /v1/admin/organizations/{orgId}`
1272
- */
1273
- getAdminOrganization(orgId) {
1274
- return this.get(`/admin/organizations/${orgId}`);
1275
- }
1276
- /**
1277
- * List recent jobs across all organizations (admin view).
1278
- *
1279
- * **Auth:** Requires `adminKey` in client config.
1280
- *
1281
- * @param limit - Maximum number of jobs to return (1–500, default 50).
1282
- *
1283
- * **Endpoint:** `GET /v1/admin/jobs`
1284
- */
442
+ resetRateLimit(scopeId) {
443
+ return this.post(`/admin/rate-limits/reset/${scopeId}`);
444
+ }
1285
445
  listJobs(limit) {
1286
- const query = limit !== undefined ? { limit: String(limit) } : undefined;
446
+ const query = limit !== undefined ? { limit } : undefined;
1287
447
  return this.get("/admin/jobs", query);
1288
448
  }
1289
- // -----------------------------------------------------------------------
1290
- // Admin — Feature Flags
1291
- // -----------------------------------------------------------------------
1292
- /**
1293
- * Get all feature flags.
1294
- *
1295
- * **Auth:** Requires `adminKey` in client config.
1296
- *
1297
- * **Endpoint:** `GET /v1/admin/feature-flags`
1298
- */
1299
449
  getFeatureFlags() {
1300
450
  return this.get("/admin/feature-flags");
1301
451
  }
1302
- /**
1303
- * Get a single feature flag by key.
1304
- *
1305
- * **Auth:** Requires `adminKey` in client config.
1306
- *
1307
- * @param key - Feature flag key.
1308
- *
1309
- * **Endpoint:** `GET /v1/admin/feature-flags/{key}`
1310
- */
1311
452
  getFeatureFlag(key) {
1312
453
  return this.get(`/admin/feature-flags/${key}`);
1313
454
  }
1314
- /**
1315
- * Create or update a feature flag.
1316
- *
1317
- * **Auth:** Requires `adminKey` in client config.
1318
- *
1319
- * @param params - Flag key and enabled status.
1320
- *
1321
- * **Endpoint:** `PUT /v1/admin/feature-flags`
1322
- */
1323
455
  setFeatureFlag(params) {
1324
456
  return this.put("/admin/feature-flags", params);
1325
457
  }
1326
- /**
1327
- * Delete a feature flag.
1328
- *
1329
- * **Auth:** Requires `adminKey` in client config.
1330
- *
1331
- * @param key - Feature flag key to delete.
1332
- *
1333
- * **Endpoint:** `DELETE /v1/admin/feature-flags/{key}`
1334
- */
1335
458
  deleteFeatureFlag(key) {
1336
459
  return this.del(`/admin/feature-flags/${key}`);
1337
460
  }
1338
- // -----------------------------------------------------------------------
1339
- // Admin — Maintenance Mode
1340
- // -----------------------------------------------------------------------
1341
- /**
1342
- * Get current maintenance mode state.
1343
- *
1344
- * **Auth:** Requires `adminKey` in client config.
1345
- *
1346
- * **Endpoint:** `GET /v1/admin/maintenance`
1347
- */
1348
461
  getMaintenanceMode() {
1349
462
  return this.get("/admin/maintenance");
1350
463
  }
1351
- /**
1352
- * Enable or disable maintenance mode.
1353
- *
1354
- * **Auth:** Requires `adminKey` in client config.
1355
- *
1356
- * @param params - Enabled flag and optional message.
1357
- *
1358
- * **Endpoint:** `PUT /v1/admin/maintenance`
1359
- */
1360
464
  setMaintenanceMode(params) {
1361
465
  return this.put("/admin/maintenance", params);
1362
466
  }
1363
- // -----------------------------------------------------------------------
1364
- // Admin — Cache
1365
- // -----------------------------------------------------------------------
1366
- /**
1367
- * Get cache statistics.
1368
- *
1369
- * **Auth:** Requires `adminKey` in client config.
1370
- *
1371
- * **Endpoint:** `GET /v1/admin/cache`
1372
- */
1373
467
  getCacheStats() {
1374
468
  return this.get("/admin/cache");
1375
469
  }
1376
- /**
1377
- * Flush all caches.
1378
- *
1379
- * **Auth:** Requires `adminKey` in client config.
1380
- *
1381
- * **Endpoint:** `POST /v1/admin/cache/flush`
1382
- */
1383
470
  flushCache() {
1384
471
  return this.post("/admin/cache/flush");
1385
472
  }
1386
- // -----------------------------------------------------------------------
1387
- // Admin — Tiers & Pricing
1388
- // -----------------------------------------------------------------------
1389
- /**
1390
- * Get all tier configurations.
1391
- *
1392
- * **Auth:** Requires `adminKey` in client config.
1393
- *
1394
- * **Endpoint:** `GET /v1/admin/tiers`
1395
- */
1396
- getTiers() {
1397
- return this.get("/admin/tiers");
1398
- }
1399
- /**
1400
- * Get current pricing configuration.
1401
- *
1402
- * **Auth:** Requires `adminKey` in client config.
1403
- *
1404
- * **Endpoint:** `GET /v1/admin/pricing`
1405
- */
1406
- getPricing() {
1407
- return this.get("/admin/pricing");
1408
- }
1409
- // -----------------------------------------------------------------------
1410
- // Admin — Audit & System
1411
- // -----------------------------------------------------------------------
1412
- /**
1413
- * Get admin-level audit log entries.
1414
- *
1415
- * **Auth:** Requires `adminKey` in client config.
1416
- *
1417
- * @param limit - Maximum entries to return (1–1000, default 100).
1418
- *
1419
- * **Endpoint:** `GET /v1/admin/audit`
1420
- */
1421
473
  getAdminAudit(limit) {
1422
- const query = limit !== undefined ? { limit: String(limit) } : undefined;
474
+ const query = limit !== undefined ? { limit } : undefined;
1423
475
  return this.get("/admin/audit", query);
1424
476
  }
1425
- /**
1426
- * Get system information (Python version, platform, architecture, PID, etc.).
1427
- *
1428
- * **Auth:** Requires `adminKey` in client config.
1429
- *
1430
- * **Endpoint:** `GET /v1/admin/system`
1431
- */
1432
477
  getSystemInfo() {
1433
478
  return this.get("/admin/system");
1434
479
  }
1435
- // -----------------------------------------------------------------------
1436
- // Jira Integration
1437
- // -----------------------------------------------------------------------
1438
- /**
1439
- * Connect a Jira Cloud site using an API token.
1440
- * Validates credentials, registers a webhook, and stores the encrypted token.
1441
- *
1442
- * **Auth:** Requires org-scoped API key.
1443
- *
1444
- * @param orgId - Organization identifier.
1445
- * @param params - Jira connection details (site_url, email, api_token).
1446
- * @param options - Optional per-request overrides.
1447
- *
1448
- * **Endpoint:** `POST /v1/organizations/{orgId}/integrations/jira/connect`
1449
- */
1450
- connectJira(orgId, params, options) {
1451
- return this.post(`/organizations/${orgId}/integrations/jira/connect`, params, options);
1452
- }
1453
- /**
1454
- * Get the current Jira integration status for an organization.
1455
- *
1456
- * **Auth:** Requires org-scoped API key.
1457
- *
1458
- * @param orgId - Organization identifier.
1459
- * @param options - Optional per-request overrides.
1460
- *
1461
- * **Endpoint:** `GET /v1/organizations/{orgId}/integrations/jira/status`
1462
- */
1463
- getJiraStatus(orgId, options) {
1464
- return this.get(`/organizations/${orgId}/integrations/jira/status`, undefined, options);
1465
- }
1466
- /**
1467
- * Disconnect (unlink) an organization's Jira integration.
1468
- * Deregisters the webhook and deletes stored credentials.
1469
- *
1470
- * **Auth:** Requires org-scoped API key.
1471
- *
1472
- * @param orgId - Organization identifier.
1473
- * @param options - Optional per-request overrides.
1474
- *
1475
- * **Endpoint:** `DELETE /v1/organizations/{orgId}/integrations/jira`
1476
- */
1477
- disconnectJira(orgId, options) {
1478
- return this.del(`/organizations/${orgId}/integrations/jira`, options);
1479
- }
1480
- /**
1481
- * Trigger a bulk sync of Jira issues from specified projects into the
1482
- * document store for RAG retrieval.
1483
- *
1484
- * **Auth:** Requires org-scoped API key.
1485
- *
1486
- * @param orgId - Organization identifier.
1487
- * @param params - Object containing `project_keys` array.
1488
- * @param options - Optional per-request overrides.
1489
- *
1490
- * **Endpoint:** `POST /v1/organizations/{orgId}/integrations/jira/sync`
1491
- */
1492
- syncJira(orgId, params, options) {
1493
- return this.post(`/organizations/${orgId}/integrations/jira/sync`, params, options);
1494
- }
1495
- /**
1496
- * Send a Jira webhook event manually.
1497
- *
1498
- * **Auth:** Requires `webhookSecret` in client config.
1499
- *
1500
- * @param payload - Jira webhook payload (issue, webhookEvent, etc.).
1501
- *
1502
- * **Endpoint:** `POST /v1/webhook/jira`
1503
- */
480
+ connectJira(params, options) {
481
+ return this.post("/integrations/jira/connect", params, options);
482
+ }
483
+ getJiraStatus(options) {
484
+ return this.get("/integrations/jira/status", undefined, options);
485
+ }
486
+ disconnectJira(options) {
487
+ return this.del("/integrations/jira", options);
488
+ }
489
+ syncJira(params, options) {
490
+ return this.post("/integrations/jira/sync", params, options);
491
+ }
1504
492
  sendJiraWebhook(payload) {
1505
493
  return this.post("/webhook/jira", payload);
1506
494
  }
1507
- // ---------------------------------------------------------------------------
1508
- // Blueprint Management
1509
- // ---------------------------------------------------------------------------
1510
- /**
1511
- * Create a new document blueprint (template).
1512
- *
1513
- * **Auth:** Requires org-scoped API key.
1514
- *
1515
- * @param orgId - Organization ID.
1516
- * @param params - Blueprint details (name, sections, workflow_config, etc.).
1517
- *
1518
- * **Endpoint:** `POST /v1/organizations/{orgId}/blueprints`
1519
- */
1520
- createBlueprint(orgId, params, options) {
1521
- return this.post(`/organizations/${orgId}/blueprints`, params, options);
1522
- }
1523
- /**
1524
- * List all blueprints for an organization.
1525
- *
1526
- * **Auth:** Requires org-scoped API key.
1527
- *
1528
- * @param orgId - Organization ID.
1529
- *
1530
- * **Endpoint:** `GET /v1/organizations/{orgId}/blueprints`
1531
- */
1532
- listBlueprints(orgId, options) {
1533
- return this.get(`/organizations/${orgId}/blueprints`, undefined, options);
1534
- }
1535
- /**
1536
- * Get a single blueprint by ID.
1537
- *
1538
- * **Auth:** Requires org-scoped API key.
1539
- *
1540
- * @param orgId - Organization ID.
1541
- * @param blueprintId - Blueprint ID.
1542
- *
1543
- * **Endpoint:** `GET /v1/organizations/{orgId}/blueprints/{blueprintId}`
1544
- */
1545
- getBlueprint(orgId, blueprintId, options) {
1546
- return this.get(`/organizations/${orgId}/blueprints/${blueprintId}`, undefined, options);
1547
- }
1548
- /**
1549
- * Update an existing blueprint. Only provided fields are changed.
1550
- *
1551
- * **Auth:** Requires org-scoped API key.
1552
- *
1553
- * @param orgId - Organization ID.
1554
- * @param blueprintId - Blueprint ID.
1555
- * @param params - Fields to update.
1556
- *
1557
- * **Endpoint:** `PUT /v1/organizations/{orgId}/blueprints/{blueprintId}`
1558
- */
1559
- updateBlueprint(orgId, blueprintId, params, options) {
1560
- return this.put(`/organizations/${orgId}/blueprints/${blueprintId}`, params, options);
1561
- }
1562
- /**
1563
- * Publish a blueprint, making it available for document creation.
1564
- *
1565
- * **Auth:** Requires org-scoped API key.
1566
- *
1567
- * @param orgId - Organization ID.
1568
- * @param blueprintId - Blueprint ID.
1569
- *
1570
- * **Endpoint:** `POST /v1/organizations/{orgId}/blueprints/{blueprintId}/publish`
1571
- */
1572
- publishBlueprint(orgId, blueprintId, options) {
1573
- return this.post(`/organizations/${orgId}/blueprints/${blueprintId}/publish`, {}, options);
1574
- }
1575
- /**
1576
- * Archive a blueprint, preventing new documents from being created from it.
1577
- *
1578
- * **Auth:** Requires org-scoped API key.
1579
- *
1580
- * @param orgId - Organization ID.
1581
- * @param blueprintId - Blueprint ID.
1582
- *
1583
- * **Endpoint:** `POST /v1/organizations/{orgId}/blueprints/{blueprintId}/archive`
1584
- */
1585
- archiveBlueprint(orgId, blueprintId, options) {
1586
- return this.post(`/organizations/${orgId}/blueprints/${blueprintId}/archive`, {}, options);
1587
- }
1588
- /**
1589
- * Permanently delete a blueprint.
1590
- *
1591
- * **Auth:** Requires org-scoped API key.
1592
- *
1593
- * @param orgId - Organization ID.
1594
- * @param blueprintId - Blueprint ID.
1595
- *
1596
- * **Endpoint:** `DELETE /v1/organizations/{orgId}/blueprints/{blueprintId}`
1597
- */
1598
- deleteBlueprint(orgId, blueprintId, options) {
1599
- return this.del(`/organizations/${orgId}/blueprints/${blueprintId}`, options);
1600
- }
1601
- // ---------------------------------------------------------------------------
1602
- // Managed Documents
1603
- // ---------------------------------------------------------------------------
1604
- /**
1605
- * Create a new managed document from a published blueprint.
1606
- *
1607
- * **Auth:** Requires org-scoped API key.
1608
- *
1609
- * @param orgId - Organization ID.
1610
- * @param params - Document details (blueprint_id, title, sections, etc.).
1611
- *
1612
- * **Endpoint:** `POST /v1/organizations/{orgId}/documents/create`
1613
- */
1614
- createDocumentFromBlueprint(orgId, params, options) {
1615
- return this.post(`/organizations/${orgId}/documents/create`, params, options);
1616
- }
1617
- /**
1618
- * List all managed documents for an organization.
1619
- *
1620
- * **Auth:** Requires org-scoped API key.
1621
- *
1622
- * @param orgId - Organization ID.
1623
- *
1624
- * **Endpoint:** `GET /v1/organizations/{orgId}/documents/managed`
1625
- */
1626
- listManagedDocuments(orgId, options) {
1627
- return this.get(`/organizations/${orgId}/documents/managed`, undefined, options);
1628
- }
1629
- /**
1630
- * Get a single managed document by ID.
1631
- *
1632
- * **Auth:** Requires org-scoped API key.
1633
- *
1634
- * @param orgId - Organization ID.
1635
- * @param documentId - Document ID.
1636
- *
1637
- * **Endpoint:** `GET /v1/organizations/{orgId}/documents/managed/{documentId}`
1638
- */
1639
- getManagedDocument(orgId, documentId, options) {
1640
- return this.get(`/organizations/${orgId}/documents/managed/${documentId}`, undefined, options);
1641
- }
1642
- /**
1643
- * Update the content of a document section. Only allowed in draft/revision status.
1644
- *
1645
- * **Auth:** Requires org-scoped API key.
1646
- *
1647
- * @param orgId - Organization ID.
1648
- * @param documentId - Document ID.
1649
- * @param params - Section ID and new content.
1650
- *
1651
- * **Endpoint:** `PATCH /v1/organizations/{orgId}/documents/managed/{documentId}/sections`
1652
- */
1653
- updateDocumentSection(orgId, documentId, params, options) {
1654
- return this.patch(`/organizations/${orgId}/documents/managed/${documentId}/sections`, params, options);
1655
- }
1656
- /**
1657
- * Perform a workflow action on a managed document.
1658
- *
1659
- * Actions: submit, approve, reject, request_changes, seal.
1660
- *
1661
- * **Auth:** Requires org-scoped API key.
1662
- *
1663
- * @param orgId - Organization ID.
1664
- * @param documentId - Document ID.
1665
- * @param params - Action type and optional comment.
1666
- *
1667
- * **Endpoint:** `POST /v1/organizations/{orgId}/documents/managed/{documentId}/workflow`
1668
- */
1669
- performDocumentWorkflow(orgId, documentId, params, options) {
1670
- return this.post(`/organizations/${orgId}/documents/managed/${documentId}/workflow`, params, options);
1671
- }
1672
- /**
1673
- * Permanently delete a managed document.
1674
- *
1675
- * **Auth:** Requires org-scoped API key.
1676
- *
1677
- * @param orgId - Organization ID.
1678
- * @param documentId - Document ID.
1679
- *
1680
- * **Endpoint:** `DELETE /v1/organizations/{orgId}/documents/managed/{documentId}`
1681
- */
1682
- deleteManagedDocument(orgId, documentId, options) {
1683
- return this.del(`/organizations/${orgId}/documents/managed/${documentId}`, options);
1684
- }
1685
- /**
1686
- * AI-generate content for a document section using the blueprint's AI rules.
1687
- *
1688
- * **Auth:** Requires org-scoped API key.
1689
- *
1690
- * @param orgId - Organization ID.
1691
- * @param documentId - Document ID.
1692
- * @param params - Section ID and optional context for generation.
1693
- *
1694
- * **Endpoint:** `POST /v1/organizations/{orgId}/documents/managed/{documentId}/generate`
1695
- */
1696
- generateDocumentSection(orgId, documentId, params, options) {
1697
- return this.post(`/organizations/${orgId}/documents/managed/${documentId}/generate`, params, options);
1698
- }
1699
- // -----------------------------------------------------------------------
1700
- // Streaming — SSE
1701
- // -----------------------------------------------------------------------
1702
- /**
1703
- * Chat inside a content project using Server-Sent Events.
1704
- * Returns an async iterator of typed {@link ChatStreamEvent} objects.
1705
- *
1706
- * **Auth:** Requires org-scoped API key.
1707
- *
1708
- * **Endpoint:** `POST /v1/organizations/{orgId}/projects/{projectId}/chat/stream`
1709
- *
1710
- * @example
1711
- * ```typescript
1712
- * for await (const evt of client.chatProjectSse("acme", "proj-1", {
1713
- * message: "Summarize our sources",
1714
- * user_id: "u1",
1715
- * })) {
1716
- * if (evt.event === "done") console.log(evt.data.answer);
1717
- * }
1718
- * ```
1719
- */
1720
- async *chatProjectSse(orgId, projectId, params, options) {
1721
- const url = new URL(`${this.prefix}/organizations/${orgId}/projects/${projectId}/chat/stream`, this.baseUrl);
495
+ createBlueprint(params, options) {
496
+ return this.post("/blueprints", params, options);
497
+ }
498
+ listBlueprints(options) {
499
+ return this.get("/blueprints", undefined, options);
500
+ }
501
+ getBlueprint(blueprintId, options) {
502
+ return this.get(`/blueprints/${blueprintId}`, undefined, options);
503
+ }
504
+ updateBlueprint(blueprintId, params, options) {
505
+ return this.put(`/blueprints/${blueprintId}`, params, options);
506
+ }
507
+ publishBlueprint(blueprintId, options) {
508
+ return this.post(`/blueprints/${blueprintId}/publish`, {}, options);
509
+ }
510
+ archiveBlueprint(blueprintId, options) {
511
+ return this.post(`/blueprints/${blueprintId}/archive`, {}, options);
512
+ }
513
+ deleteBlueprint(blueprintId, options) {
514
+ return this.del(`/blueprints/${blueprintId}`, options);
515
+ }
516
+ createDocumentFromBlueprint(params, options) {
517
+ return this.post("/documents/create", params, options);
518
+ }
519
+ listManagedDocuments(options) {
520
+ return this.get("/documents/managed", undefined, options);
521
+ }
522
+ getManagedDocument(documentId, options) {
523
+ return this.get(`/documents/managed/${documentId}`, undefined, options);
524
+ }
525
+ updateDocumentSection(documentId, params, options) {
526
+ return this.patch(`/documents/managed/${documentId}/sections`, params, options);
527
+ }
528
+ performDocumentWorkflow(documentId, params, options) {
529
+ return this.post(`/documents/managed/${documentId}/workflow`, params, options);
530
+ }
531
+ deleteManagedDocument(documentId, options) {
532
+ return this.del(`/documents/managed/${documentId}`, options);
533
+ }
534
+ generateDocumentSection(documentId, params, options) {
535
+ return this.post(`/documents/managed/${documentId}/generate`, params, options);
536
+ }
537
+ async *chatProjectSse(projectId, params, options) {
538
+ const url = new URL(`${this.prefix}/projects/${projectId}/chat/stream`, this.baseUrl);
1722
539
  const headers = {
1723
540
  "Content-Type": "application/json",
1724
541
  Accept: "text/event-stream",
1725
542
  };
1726
543
  const apiKey = options?.apiKey ?? this.config.apiKey;
1727
544
  if (apiKey)
1728
- headers["Authorization"] = `Bearer ${apiKey}`;
545
+ headers.Authorization = `Bearer ${apiKey}`;
1729
546
  if (this.config.adminKey)
1730
547
  headers["X-Admin-Key"] = this.config.adminKey;
1731
- if (this.config.employeeId)
1732
- headers["X-Employee-Id"] = this.config.employeeId;
1733
548
  const res = await fetch(url.toString(), {
1734
549
  method: "POST",
1735
550
  headers,
@@ -1758,27 +573,8 @@ class HivemindClient {
1758
573
  yield { event: raw.event, data };
1759
574
  }
1760
575
  }
1761
- // -----------------------------------------------------------------------
1762
- // Streaming WebSocket
1763
- // -----------------------------------------------------------------------
1764
- /**
1765
- * Open a WebSocket to the project chat endpoint and return a
1766
- * convenience handle for sending commands and receiving frames.
1767
- *
1768
- * **Auth:** API key is sent as `?api_key=` query param (browser-safe).
1769
- *
1770
- * **Endpoint:** `WS /v1/organizations/{orgId}/projects/{projectId}/chat/ws`
1771
- *
1772
- * @example
1773
- * ```typescript
1774
- * const ws = await client.chatProjectWebSocket("acme", "proj-1");
1775
- * const frame = await ws.chat({ message: "Hello", user_id: "u1" });
1776
- * if (frame.type === "result") console.log(frame.payload.answer);
1777
- * ws.close();
1778
- * ```
1779
- */
1780
- async chatProjectWebSocket(orgId, projectId, options) {
1781
- const httpUrl = new URL(`${this.prefix}/organizations/${orgId}/projects/${projectId}/chat/ws`, this.baseUrl);
576
+ async chatProjectWebSocket(projectId, options) {
577
+ const httpUrl = new URL(`${this.prefix}/projects/${projectId}/chat/ws`, this.baseUrl);
1782
578
  const wsUrl = httpUrl.toString().replace(/^http/, "ws");
1783
579
  const apiKey = options?.apiKey ?? this.config.apiKey;
1784
580
  const { openHivemindWebSocket, sendChatCommand } = await Promise.resolve().then(() => __importStar(require("./ws")));
@@ -1787,13 +583,10 @@ class HivemindClient {
1787
583
  signal: options?.signal,
1788
584
  });
1789
585
  return {
1790
- /** The underlying WebSocket instance. */
1791
586
  raw: ws,
1792
- /** Send a chat command and wait for the server response frame. */
1793
587
  chat(params) {
1794
588
  return sendChatCommand(ws, { type: "chat", ...params });
1795
589
  },
1796
- /** Gracefully close the connection. */
1797
590
  close(code, reason) {
1798
591
  ws.close(code ?? 1000, reason);
1799
592
  },