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