@quartal/messages-client 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.js ADDED
@@ -0,0 +1,968 @@
1
+ import { FsError } from "@quartal/core";
2
+ //#region src/idFormat.ts
3
+ /**
4
+ * Stable user-given id format shared by `models`, `tools`,
5
+ * `agents`, and `channels`. Mirrors the CHECK constraint on each table:
6
+ *
7
+ * ^[a-z0-9][a-z0-9._\-]*$ AND length ≤ 80
8
+ *
9
+ * Lowercase letters/digits to start; rest may include `_`, `.`, `-`.
10
+ * Wide enough to fit provider model ids ("gpt-5.4-pro") and route slugs
11
+ * ("payroll", "all-companies"); narrow enough to be URL- and JSON-safe.
12
+ *
13
+ * Validation lives in the API client so the same rule fires on every save
14
+ * regardless of who calls it (Vue UI, server script, future REST surface).
15
+ */
16
+ /** Human-readable description of the id format, suitable for error messages. */
17
+ const ID_FORMAT_PATTERN = "^[a-z0-9][a-z0-9._\\-]*$ (lowercase, ≤ 80 chars)";
18
+ const ID_REGEX = /^[a-z0-9][a-z0-9._\-]*$/;
19
+ /** True when `id` is a non-empty string ≤ 80 chars matching {@linkcode ID_REGEX}. */
20
+ function isValidId(id) {
21
+ if (typeof id !== "string") return false;
22
+ if (id.length === 0 || id.length > 80) return false;
23
+ return ID_REGEX.test(id);
24
+ }
25
+ //#endregion
26
+ //#region src/config/ClientConfig.ts
27
+ /** Default scopes: profile plus the IAM API and Messages API audiences. */
28
+ const DEFAULT_SCOPE = "openid profile email iam-api quartal-hub-test";
29
+ /** The values given with {@link configureClient}; null when the app uses `import.meta.env` only. */
30
+ let configured = null;
31
+ /**
32
+ * Sets the configuration at runtime, over `import.meta.env`: for an app that is not built with the
33
+ * `VITE_*` variables, such as a channel plugin's page that learns the API's address from the Hub.
34
+ * Such an app needs only what it uses: {@link loadClientConfig} then requires `messagesApiUrl` alone.
35
+ * @param config The values to use; a later call adds to and overrides the earlier ones.
36
+ */
37
+ function configureClient(config) {
38
+ configured = {
39
+ ...configured,
40
+ ...config
41
+ };
42
+ }
43
+ /**
44
+ * Reads `ClientConfig` from `import.meta.env` and the values given with {@link configureClient}.
45
+ * Throws when a required value is missing so the failure surfaces at app startup, not at the first
46
+ * call.
47
+ */
48
+ function loadClientConfig() {
49
+ const env = import.meta.env ?? {};
50
+ const config = {
51
+ messagesApiUrl: env.VITE_MESSAGES_API_URL ?? "",
52
+ oidcAuthority: env.VITE_OIDC_AUTHORITY ?? "",
53
+ oidcClientId: env.VITE_OIDC_CLIENT_ID ?? "",
54
+ oidcScope: env.VITE_OIDC_SCOPE || DEFAULT_SCOPE,
55
+ iamApiUrl: env.VITE_IAM_API_URL ?? "",
56
+ ...configured
57
+ };
58
+ if (configured) {
59
+ if (!config.messagesApiUrl) throw new Error("configureClient() was called without messagesApiUrl.");
60
+ return config;
61
+ }
62
+ const missing = Object.entries(config).filter(([, v]) => !v).map(([k]) => k);
63
+ if (missing.length) throw new Error(`Missing ${missing.join(", ")} (VITE_MESSAGES_API_URL, VITE_OIDC_AUTHORITY, VITE_OIDC_CLIENT_ID, VITE_IAM_API_URL). Copy .env.example to .env at the repo root and fill in the values.`);
64
+ return config;
65
+ }
66
+ //#endregion
67
+ //#region src/http.ts
68
+ /** A failed API call: the HTTP status, the API's `error` text and, for file errors, its `code`. */
69
+ var ApiError = class extends Error {
70
+ /** HTTP status of the response (0 when the request did not reach the API). */
71
+ status;
72
+ /** The API's error code when it sends one: the `FsErrorCode` of a file operation (`ENOENT`, `ECONFLICT`, …). */
73
+ code;
74
+ /**
75
+ * @param status HTTP status of the response.
76
+ * @param message The API's `error` text, or the status text.
77
+ * @param code The API's error code, if any.
78
+ */
79
+ constructor(status, message, code) {
80
+ super(message);
81
+ this.name = "ApiError";
82
+ this.status = status;
83
+ this.code = code;
84
+ }
85
+ };
86
+ /** A minimal JSON client for the Messages API. */
87
+ var HttpClient = class {
88
+ /**
89
+ * @param baseUrl The API origin, e.g. `http://localhost:8002`.
90
+ * @param getToken Supplies the bearer token for each request.
91
+ */
92
+ constructor(baseUrl, getToken) {
93
+ this.baseUrl = baseUrl;
94
+ this.getToken = getToken;
95
+ }
96
+ /** GET `path`; resolves to the parsed JSON body. */
97
+ get(path, options = {}) {
98
+ return this.request("GET", path, options);
99
+ }
100
+ /** POST `path` with a JSON body. */
101
+ post(path, body = {}, options = {}) {
102
+ return this.request("POST", path, {
103
+ ...options,
104
+ body
105
+ });
106
+ }
107
+ /** PUT `path` with a JSON body. */
108
+ put(path, body = {}, options = {}) {
109
+ return this.request("PUT", path, {
110
+ ...options,
111
+ body
112
+ });
113
+ }
114
+ /** DELETE `path`. */
115
+ delete(path, options = {}) {
116
+ return this.request("DELETE", path, options);
117
+ }
118
+ /** Sends one request. Throws {@link ApiError} on a non-2xx response or a network failure. */
119
+ async request(method, path, options = {}) {
120
+ const url = new URL(path, this.baseUrl);
121
+ for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
122
+ const token = await this.getToken();
123
+ const headers = {};
124
+ if (token) headers.authorization = `Bearer ${token}`;
125
+ if (options.body !== void 0) headers["content-type"] = "application/json";
126
+ let res;
127
+ try {
128
+ res = await fetch(url, {
129
+ method,
130
+ headers,
131
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
132
+ signal: options.signal
133
+ });
134
+ } catch (err) {
135
+ throw new ApiError(0, err.message);
136
+ }
137
+ const text = await res.text();
138
+ const json = text ? safeJson(text) : void 0;
139
+ if (!res.ok) {
140
+ const body = json;
141
+ throw new ApiError(res.status, body?.error ?? (text || res.statusText), body?.code);
142
+ }
143
+ return json;
144
+ }
145
+ /** The current token (for the event stream). */
146
+ token() {
147
+ return Promise.resolve(this.getToken());
148
+ }
149
+ };
150
+ /** Encodes one path segment. */
151
+ function seg(value) {
152
+ return encodeURIComponent(value);
153
+ }
154
+ function safeJson(text) {
155
+ try {
156
+ return JSON.parse(text);
157
+ } catch {
158
+ return;
159
+ }
160
+ }
161
+ //#endregion
162
+ //#region src/files/filesSource.ts
163
+ const CODES = [
164
+ "ENOENT",
165
+ "EEXIST",
166
+ "ENOTDIR",
167
+ "EISDIR",
168
+ "ENOTEMPTY",
169
+ "EPERM",
170
+ "ENOTSUP",
171
+ "ECONFLICT",
172
+ "EINVAL",
173
+ "EQUOTA"
174
+ ];
175
+ /** The code of an API error, from its `code` or else from its status. */
176
+ function codeOf(e) {
177
+ if (CODES.includes(e.code)) return e.code;
178
+ if (e.status === 404) return "ENOENT";
179
+ if (e.status === 403) return "EPERM";
180
+ if (e.status === 400) return "EINVAL";
181
+ return "EUNKNOWN";
182
+ }
183
+ /** An API error as an {@link FsError}, so components branch on codes, not statuses. Anything else as is. */
184
+ function toFsError(e, address) {
185
+ return e instanceof ApiError ? new FsError(codeOf(e), e.message, address) : e;
186
+ }
187
+ /** Bytes as base64 (chunked, so large files do not overflow the call stack). */
188
+ function bytesToBase64(bytes) {
189
+ let binary = "";
190
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
191
+ return btoa(binary);
192
+ }
193
+ /** Base64 as bytes. */
194
+ function base64ToBytes(base64) {
195
+ const binary = atob(base64);
196
+ const bytes = new Uint8Array(binary.length);
197
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
198
+ return bytes;
199
+ }
200
+ /** A blob's bytes as base64. */
201
+ async function blobToBase64(blob) {
202
+ return bytesToBase64(new Uint8Array(await blob.arrayBuffer()));
203
+ }
204
+ /**
205
+ * The files of one owner (a company id, or `system`) as a {@link QFsSource}, the filesystem the
206
+ * file components of `@quartal/ui-core` work on. Every failure is an {@link FsError}. The API has no
207
+ * `watch` or `glob` yet, so the components fall back to a refresh button and to searching the loaded
208
+ * folders.
209
+ * @param files The files resource of the API client.
210
+ * @param owner The owner: a company id, or `system`.
211
+ */
212
+ function filesSource(files, owner) {
213
+ const wrap = async (address, call) => {
214
+ try {
215
+ return await call();
216
+ } catch (e) {
217
+ throw toFsError(e, address);
218
+ }
219
+ };
220
+ return {
221
+ list: (a, o) => wrap(a, () => files.list(owner, a, o)),
222
+ stat: (a) => wrap(a, () => files.stat(owner, a)),
223
+ read: (a) => wrap(a, () => files.read(owner, a)),
224
+ write: (a, content, o) => wrap(a, () => typeof content === "string" ? files.write(owner, a, content, { ifMatch: o?.ifMatch }) : files.write(owner, a, bytesToBase64(content), {
225
+ ifMatch: o?.ifMatch,
226
+ encoding: "base64"
227
+ })),
228
+ mkdir: (a, o) => wrap(a, async () => {
229
+ if (o?.ifNotExists) {
230
+ const existing = await files.stat(owner, a).catch(() => null);
231
+ if (existing?.isFolder) return existing;
232
+ }
233
+ return files.mkdir(owner, a);
234
+ }),
235
+ remove: (a, o) => wrap(a, () => files.delete(owner, a, o)),
236
+ move: (from, to, o) => wrap(from, () => files.move(owner, from, to, o)),
237
+ copy: (from, to, o) => wrap(from, () => files.copy(owner, from, to, { overwrite: o?.overwrite }))
238
+ };
239
+ }
240
+ //#endregion
241
+ //#region src/events.ts
242
+ /** One shared SSE connection with fan-out to handlers. */
243
+ var LiveEvents = class {
244
+ handlers = /* @__PURE__ */ new Set();
245
+ controller = null;
246
+ retry = 0;
247
+ /** @param http The client whose base URL and token the stream uses. */
248
+ constructor(http) {
249
+ this.http = http;
250
+ }
251
+ /** Calls `handler` for every change until the returned function is called. */
252
+ subscribe(handler) {
253
+ this.handlers.add(handler);
254
+ if (!this.controller) this.connect();
255
+ return () => {
256
+ this.handlers.delete(handler);
257
+ if (this.handlers.size === 0) this.close();
258
+ };
259
+ }
260
+ /** Closes the connection (it reopens on the next subscription). */
261
+ close() {
262
+ this.controller?.abort();
263
+ this.controller = null;
264
+ }
265
+ async connect() {
266
+ const controller = new AbortController();
267
+ this.controller = controller;
268
+ try {
269
+ const token = await this.http.token();
270
+ if (!token) throw new Error("signed out");
271
+ const res = await fetch(new URL("/events", this.http.baseUrl), {
272
+ method: "POST",
273
+ headers: { authorization: `Bearer ${token}` },
274
+ signal: controller.signal
275
+ });
276
+ if (!res.ok || !res.body) throw new Error(`events: ${res.status}`);
277
+ this.retry = 0;
278
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
279
+ let buffer = "";
280
+ for (;;) {
281
+ const { value, done } = await reader.read();
282
+ if (done) break;
283
+ buffer += value;
284
+ let end;
285
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
286
+ this.dispatch(buffer.slice(0, end));
287
+ buffer = buffer.slice(end + 2);
288
+ }
289
+ }
290
+ } catch (err) {
291
+ if (controller.signal.aborted) return;
292
+ console.warn("[messages] event stream interrupted:", err.message);
293
+ }
294
+ if (this.controller !== controller || this.handlers.size === 0) return;
295
+ const delay = Math.min(3e4, 1e3 * 2 ** this.retry++);
296
+ setTimeout(() => {
297
+ if (this.controller === controller && this.handlers.size > 0) this.connect();
298
+ }, delay);
299
+ }
300
+ dispatch(block) {
301
+ const name = /^event: (.*)$/m.exec(block)?.[1];
302
+ const data = /^data: (.*)$/m.exec(block)?.[1];
303
+ if (name !== "change" || !data) return;
304
+ let event;
305
+ try {
306
+ event = JSON.parse(data);
307
+ } catch {
308
+ return;
309
+ }
310
+ for (const handler of this.handlers) try {
311
+ handler(event);
312
+ } catch (err) {
313
+ console.error("[messages] live event handler failed:", err);
314
+ }
315
+ }
316
+ };
317
+ //#endregion
318
+ //#region src/agents/AgentsApi.ts
319
+ /**
320
+ * The agents over the Messages API (`/api/agents`). Every agent is defined in a plugin; it gets its
321
+ * row when a channel definition first names it.
322
+ */
323
+ var AgentsApi = class {
324
+ /** @param http The Messages API client. */
325
+ constructor(http) {
326
+ this.http = http;
327
+ }
328
+ /** The live agents, by name; optionally only those a plugin defines. */
329
+ async list(filter = {}) {
330
+ return (await this.http.get("/api/agents", { query: {
331
+ name: filter.name,
332
+ pluginId: filter.pluginId
333
+ } })).agents;
334
+ }
335
+ /** One agent by id; rejects with a 404 `ApiError` when it is not visible. */
336
+ get(id) {
337
+ return this.http.get(`/api/agents/${seg(id)}`);
338
+ }
339
+ /**
340
+ * The agents an organization can attach to its channels: those its own plugins define, then those
341
+ * of the catalog's plugins.
342
+ */
343
+ async available(owner) {
344
+ return (await this.http.get("/api/agents/available", { query: { owner } })).agents;
345
+ }
346
+ /** Changes how an agent is shown. */
347
+ update(id, patch) {
348
+ return this.http.put(`/api/agents/${seg(id)}`, patch);
349
+ }
350
+ /** Archives an agent: it no longer answers. */
351
+ async archive(id) {
352
+ await this.http.delete(`/api/agents/${seg(id)}`);
353
+ }
354
+ };
355
+ //#endregion
356
+ //#region src/channels/ChannelsApi.ts
357
+ /**
358
+ * Channels over the Messages API (`/api/channels`). Visibility comes from the API's access rules. `getBlank` and `validate` run locally; the API validates again on write.
359
+ */
360
+ var ChannelsApi = class {
361
+ /** Resource type name. */
362
+ type = "channel";
363
+ /** @param http The Messages API client. */
364
+ constructor(http) {
365
+ this.http = http;
366
+ }
367
+ getBlank() {
368
+ const now = (/* @__PURE__ */ new Date()).toISOString();
369
+ return {
370
+ id: "",
371
+ owner: "",
372
+ name: "",
373
+ statuses: [],
374
+ pluginId: "",
375
+ definition: {
376
+ title: "",
377
+ statuses: [],
378
+ agents: []
379
+ },
380
+ definitionCommit: "",
381
+ definitionReadAt: now,
382
+ createdAt: now,
383
+ updatedAt: now,
384
+ archivedAt: null
385
+ };
386
+ }
387
+ /** Validate a new channel; requires `id` (valid format) and `owner`. */
388
+ validate(item) {
389
+ const errors = [];
390
+ if (!item.id?.trim()) errors.push({
391
+ code: "channel.id.required",
392
+ field: "id",
393
+ type: "required",
394
+ message: "id is required"
395
+ });
396
+ else if (!isValidId(item.id)) errors.push({
397
+ code: "channel.id.format",
398
+ field: "id",
399
+ type: "invalid",
400
+ message: `id must match ${ID_FORMAT_PATTERN}`
401
+ });
402
+ if (!item.owner) errors.push({
403
+ code: "channel.owner.required",
404
+ field: "owner",
405
+ type: "required",
406
+ message: "owner is required"
407
+ });
408
+ const hasMissing = errors.some((e) => e.type === "required");
409
+ return {
410
+ isValid: errors.length === 0,
411
+ hasAllRequiredFields: !hasMissing,
412
+ errors
413
+ };
414
+ }
415
+ /** One channel by id; rejects with a 404 `ApiError` when it is not visible. */
416
+ findById(id) {
417
+ return this.http.get(`/api/channels/${seg(id)}`);
418
+ }
419
+ /** The channels matching `query.$filter` (the API decides the order). */
420
+ async getOData(query) {
421
+ const f = query.$filter ?? {};
422
+ return { value: (await this.http.get("/api/channels", { query: {
423
+ owner: f.owner,
424
+ name: f.name,
425
+ company: f.company
426
+ } })).channels };
427
+ }
428
+ /** Paging is not offered: every list returns all matching rows. */
429
+ getNextPage(_nextLink) {
430
+ return Promise.reject(/* @__PURE__ */ new Error("Paging is not supported: lists return every matching row."));
431
+ }
432
+ /**
433
+ * Creates a channel with a new definition titled with the item's name (its id when empty). A
434
+ * channel's name and look are its definition's: change them with {@link saveDefinition}.
435
+ */
436
+ save(item) {
437
+ return this.create({
438
+ id: item.id,
439
+ owner: item.owner,
440
+ newDefinition: { title: item.name || item.id }
441
+ });
442
+ }
443
+ /** Creates a channel and its plugin: a new definition, or a copy of a catalog channel plugin. */
444
+ create(input) {
445
+ return this.http.post("/api/channels", input);
446
+ }
447
+ /** Commits the channel plugin's files on the plugin host and moves the channel to that commit. */
448
+ refresh(id) {
449
+ return this.http.post("/api/channels/refresh", { id });
450
+ }
451
+ /** The definitions an organization can make channels from: its own channel plugins, then the catalog's. */
452
+ async definitions(owner) {
453
+ return (await this.http.get("/api/channels/definitions", { query: { owner } })).definitions;
454
+ }
455
+ /** Writes a definition into its plugin on the organization's plugin host, commits it and moves its channels to it. */
456
+ saveDefinition(owner, pluginId, definition) {
457
+ return this.http.post("/api/channels/save-definition", {
458
+ owner,
459
+ pluginId,
460
+ definition
461
+ });
462
+ }
463
+ /** Moves every channel made from a definition to its plugin's latest state, after its files changed. */
464
+ refreshDefinition(owner, pluginId) {
465
+ return this.http.post("/api/channels/refresh-definition", {
466
+ owner,
467
+ pluginId
468
+ });
469
+ }
470
+ /**
471
+ * Syncs the organization's channels with the definitions on its plugin host, without pulling:
472
+ * a definition in `channels/` with no channel gets one, a channel whose plugin is gone is
473
+ * archived, every other channel moves to its plugin's latest commit.
474
+ */
475
+ sync(owner) {
476
+ return this.http.post("/api/channels/sync", { owner });
477
+ }
478
+ /** Statistics of the visible channels: listed companies and threads per status. */
479
+ stats() {
480
+ return this.http.get("/api/channels/stats");
481
+ }
482
+ /** Archives the channel. */
483
+ async delete(id) {
484
+ await this.http.delete(`/api/channels/${seg(id)}`);
485
+ }
486
+ };
487
+ //#endregion
488
+ //#region src/models/ModelsApi.ts
489
+ /**
490
+ * The models agents can use over the Messages API (`/api/models`): OpenCode Zen's catalog with the
491
+ * product's settings from Git. Read only.
492
+ */
493
+ var ModelsApi = class {
494
+ /** Resource type name. */
495
+ type = "model";
496
+ /** @param http The Messages API client. */
497
+ constructor(http) {
498
+ this.http = http;
499
+ }
500
+ /** One model by id; rejects with a 404 `ApiError` when the catalog does not have it. */
501
+ findById(id) {
502
+ return this.http.get(`/api/models/${seg(id)}`);
503
+ }
504
+ /** The models matching the filter, the default first (enabled ones unless `includeDisabled`). */
505
+ async list(filter = {}) {
506
+ return (await this.http.get("/api/models", { query: {
507
+ includeDisabled: filter.includeDisabled,
508
+ provider: filter.provider,
509
+ name: filter.name
510
+ } })).models;
511
+ }
512
+ /** The gateway the agents' models are called through (OpenCode Zen or Amazon Bedrock). */
513
+ gateway() {
514
+ return this.http.get("/api/models/gateway");
515
+ }
516
+ /** Reads the catalog again from OpenCode Zen (the API otherwise reads it once a day). */
517
+ refresh() {
518
+ return this.http.post("/api/models/refresh", {});
519
+ }
520
+ };
521
+ //#endregion
522
+ //#region src/MessagesApi.ts
523
+ /** Every Messages API resource behind one client. */
524
+ var MessagesApi = class {
525
+ /** The underlying HTTP client. */
526
+ http;
527
+ /** Channels (CRUD). */
528
+ channels;
529
+ /** The model catalog (CRUD + default/disabled). */
530
+ models;
531
+ /** The agents: those attached to channels, and the ones plugins offer. */
532
+ agents;
533
+ /** The shared live event stream. */
534
+ events;
535
+ /**
536
+ * @param baseUrl The API origin, e.g. `http://localhost:8002`.
537
+ * @param getToken Supplies the signed-in user's access token.
538
+ */
539
+ constructor(baseUrl, getToken) {
540
+ this.http = new HttpClient(baseUrl, getToken);
541
+ this.channels = new ChannelsApi(this.http);
542
+ this.models = new ModelsApi(this.http);
543
+ this.agents = new AgentsApi(this.http);
544
+ this.events = new LiveEvents(this.http);
545
+ }
546
+ /** The signed-in user: profile, the companies they can act for, and roles. */
547
+ me() {
548
+ return this.http.get("/api/me");
549
+ }
550
+ /** The companies the user can see (their own, and those of the channels they see), by name. */
551
+ async companies() {
552
+ return (await this.http.get("/api/companies")).companies;
553
+ }
554
+ /** Counts per company the user sees (channels, threads, messages, people, last activity); `ids` limits them. */
555
+ async companyStats(ids) {
556
+ const query = ids?.length ? { ids: ids.join(",") } : {};
557
+ return (await this.http.get("/api/companies/stats", { query })).companies;
558
+ }
559
+ /**
560
+ * The Hub configuration of an organization (its skin), kept in Git as `hub-configuration.json`
561
+ * at the root of its plugin repository: read by its members, changed (and committed) by its admins.
562
+ */
563
+ hubConfiguration = {
564
+ get: (companyId) => this.http.get(`/api/hub-configuration/${seg(companyId)}`),
565
+ update: (companyId, configuration) => this.http.put(`/api/hub-configuration/${seg(companyId)}`, { configuration })
566
+ };
567
+ /** The Quartal Hub plugin catalog. */
568
+ plugins = {
569
+ list: async () => (await this.http.get("/api/plugins")).plugins,
570
+ get: (id) => this.http.get(`/api/plugins/${seg(id)}`),
571
+ sync: async () => (await this.http.post("/api/plugins/sync", {})).results,
572
+ lastSync: async () => (await this.http.get("/api/plugins/last-sync")).sync,
573
+ repository: () => this.http.get("/api/plugins/repository"),
574
+ getFile: async (url) => (await this.http.get("/api/plugins/file", { query: { url } })).content,
575
+ saveContent: (id, plugin) => this.http.post("/api/plugins/save-content", {
576
+ id,
577
+ plugin
578
+ }),
579
+ gitStatus: () => this.http.get("/api/plugins/git-status"),
580
+ push: (message) => this.http.post("/api/plugins/push", { message })
581
+ };
582
+ /**
583
+ * The catalog plugins an organization uses as they are, from where they run. The list is kept in
584
+ * the organization's plugin repository. For the organization's direct members.
585
+ */
586
+ externalPlugins = {
587
+ list: async (owner) => (await this.http.get("/api/external-plugins", { query: { owner } })).plugins,
588
+ create: (owner, pluginId) => this.http.post("/api/external-plugins", {
589
+ owner,
590
+ pluginId
591
+ }),
592
+ delete: async (owner, id) => {
593
+ await this.http.delete(`/api/external-plugins/${seg(id)}`, { query: { owner } });
594
+ }
595
+ };
596
+ /**
597
+ * The organization's own plugins on its plugin host: Quartal Plugin projects in the host's Git
598
+ * repository, each built and served on its own subdomain. For the organization's direct members.
599
+ */
600
+ hostedPlugins = {
601
+ host: (owner) => this.http.get("/api/hosted-plugins/host", { query: { owner } }),
602
+ list: async (owner) => (await this.http.get("/api/hosted-plugins", { query: { owner } })).plugins,
603
+ get: (owner, id) => this.http.get(`/api/hosted-plugins/${seg(id)}`, { query: { owner } }),
604
+ create: (owner, plugin) => this.http.post("/api/hosted-plugins", {
605
+ owner,
606
+ ...plugin
607
+ }),
608
+ copy: (owner, pluginId, id, mode) => this.http.post("/api/hosted-plugins/copy", {
609
+ owner,
610
+ pluginId,
611
+ id,
612
+ mode
613
+ }),
614
+ content: (owner, id) => this.http.get(`/api/hosted-plugins/content/${seg(id)}`, { query: { owner } }),
615
+ saveContent: (owner, id, plugin) => this.http.post("/api/hosted-plugins/save-content", {
616
+ owner,
617
+ id,
618
+ plugin
619
+ }),
620
+ delete: async (owner, id) => {
621
+ await this.http.delete(`/api/hosted-plugins/${seg(id)}`, { query: { owner } });
622
+ },
623
+ build: (owner, id) => this.http.post("/api/hosted-plugins/build", {
624
+ owner,
625
+ id
626
+ }),
627
+ restart: (owner, id) => this.http.post("/api/hosted-plugins/restart", {
628
+ owner,
629
+ id
630
+ }),
631
+ setDev: (owner, id, enabled) => this.http.post("/api/hosted-plugins/set-dev", {
632
+ owner,
633
+ id,
634
+ enabled
635
+ }),
636
+ logs: async (owner, id, lines) => (await this.http.get(`/api/hosted-plugins/logs/${seg(id)}`, { query: {
637
+ owner,
638
+ lines
639
+ } })).text,
640
+ secrets: async (owner, id) => (await this.http.get(`/api/hosted-plugins/secrets/${seg(id)}`, { query: { owner } })).names,
641
+ setSecrets: async (owner, id, values) => (await this.http.post("/api/hosted-plugins/set-secrets", {
642
+ owner,
643
+ id,
644
+ values
645
+ })).names
646
+ };
647
+ /**
648
+ * The coding chats: sessions of the plugin host's coding agent, each in one of the organization's
649
+ * plugins (docs/code-agent.md). The host rebuilds a plugin when the agent changes it. Read a chat
650
+ * again while it is `busy`.
651
+ */
652
+ pluginCoding = {
653
+ uiUrl: async (owner, path) => (await this.http.post("/api/plugin-coding/open-ui", {
654
+ owner,
655
+ path
656
+ })).url,
657
+ chats: async (owner) => (await this.http.get("/api/plugin-coding/chats", { query: { owner } })).chats,
658
+ startChat: (owner, input) => this.http.post("/api/plugin-coding/start-chat", {
659
+ owner,
660
+ ...input
661
+ }),
662
+ chat: (owner, sessionId) => this.http.get("/api/plugin-coding/chat", { query: {
663
+ owner,
664
+ sessionId
665
+ } }),
666
+ continueChat: (owner, sessionId, input) => this.http.post("/api/plugin-coding/continue-chat", {
667
+ owner,
668
+ sessionId,
669
+ ...input
670
+ }),
671
+ stopChat: (owner, sessionId) => this.http.post("/api/plugin-coding/stop-chat", {
672
+ owner,
673
+ sessionId
674
+ }),
675
+ deleteChat: async (owner, sessionId) => {
676
+ await this.http.delete("/api/plugin-coding/chat", { query: {
677
+ owner,
678
+ sessionId
679
+ } });
680
+ }
681
+ };
682
+ /** The files of the organization's hosted plugins, addressed as `/{plugin id}/{path}`. */
683
+ hostedPluginFiles = {
684
+ list: async (owner, path, options = {}) => (await this.http.get("/api/hosted-plugin-files", { query: {
685
+ owner,
686
+ path,
687
+ recursive: options.recursive
688
+ } })).entries,
689
+ stat: (owner, path) => this.http.get("/api/hosted-plugin-files/entry", { query: {
690
+ owner,
691
+ path
692
+ } }),
693
+ read: (owner, path) => this.http.get("/api/hosted-plugin-files/content", { query: {
694
+ owner,
695
+ path
696
+ } }),
697
+ write: (owner, path, content, options = {}) => this.http.post("/api/hosted-plugin-files/write", {
698
+ owner,
699
+ path,
700
+ content,
701
+ ...options
702
+ }),
703
+ mkdir: (owner, path) => this.http.post("/api/hosted-plugin-files/mkdir", {
704
+ owner,
705
+ path
706
+ }),
707
+ move: (owner, from, to, options = {}) => this.http.post("/api/hosted-plugin-files/move", {
708
+ owner,
709
+ from,
710
+ to,
711
+ ...options
712
+ }),
713
+ copy: (owner, from, to, options = {}) => this.http.post("/api/hosted-plugin-files/copy", {
714
+ owner,
715
+ from,
716
+ to,
717
+ ...options
718
+ }),
719
+ delete: async (owner, path, options = {}) => {
720
+ await this.http.delete("/api/hosted-plugin-files", { query: {
721
+ owner,
722
+ path,
723
+ recursive: options.recursive
724
+ } });
725
+ },
726
+ forOwner: (owner) => filesSource(this.hostedPluginFiles, owner)
727
+ };
728
+ /** The Git repository behind the organization's plugin host. */
729
+ pluginHostGit = {
730
+ status: (owner) => this.http.get("/api/plugin-host-git/status", { query: { owner } }),
731
+ log: async (owner) => (await this.http.get("/api/plugin-host-git/log", { query: { owner } })).commits,
732
+ file: (owner, commit, path, from) => this.http.get("/api/plugin-host-git/file", { query: {
733
+ owner,
734
+ commit,
735
+ path,
736
+ from
737
+ } }),
738
+ reset: (owner, commit, mode) => this.http.post("/api/plugin-host-git/reset", {
739
+ owner,
740
+ commit,
741
+ mode
742
+ }),
743
+ discard: (owner, scope) => this.http.post("/api/plugin-host-git/discard", {
744
+ owner,
745
+ scope
746
+ }),
747
+ pull: (owner) => this.http.post("/api/plugin-host-git/pull", { owner }),
748
+ push: (owner, message) => this.http.post("/api/plugin-host-git/push", {
749
+ owner,
750
+ message
751
+ })
752
+ };
753
+ /**
754
+ * Files of a company (`owner`: a company id, or `system` for the read-only product data), addressed
755
+ * as `/{drive}/{path}`. A company's own people use them, and so do the people of an advisory that
756
+ * has it as a customer.
757
+ */
758
+ files = {
759
+ list: async (owner, path, options = {}) => (await this.http.get("/api/files", { query: {
760
+ owner,
761
+ path,
762
+ recursive: options.recursive
763
+ } })).entries,
764
+ stat: (owner, path) => this.http.get("/api/files/entry", { query: {
765
+ owner,
766
+ path
767
+ } }),
768
+ read: (owner, path) => this.http.get("/api/files/content", { query: {
769
+ owner,
770
+ path
771
+ } }),
772
+ write: (owner, path, content, options = {}) => this.http.post("/api/files/write", {
773
+ owner,
774
+ path,
775
+ content,
776
+ ...options
777
+ }),
778
+ mkdir: (owner, path) => this.http.post("/api/files/mkdir", {
779
+ owner,
780
+ path
781
+ }),
782
+ move: (owner, from, to, options = {}) => this.http.post("/api/files/move", {
783
+ owner,
784
+ from,
785
+ to,
786
+ ...options
787
+ }),
788
+ copy: (owner, from, to, options = {}) => this.http.post("/api/files/copy", {
789
+ owner,
790
+ from,
791
+ to,
792
+ ...options
793
+ }),
794
+ delete: async (owner, path, options = {}) => {
795
+ await this.http.delete("/api/files", { query: {
796
+ owner,
797
+ path,
798
+ recursive: options.recursive
799
+ } });
800
+ },
801
+ createDemo: (owner) => this.http.post("/api/files/demo", { owner }),
802
+ forOwner: (owner) => filesSource(this.files, owner)
803
+ };
804
+ /** Thread operations. */
805
+ threads = {
806
+ list: async (channelId) => (await this.http.get("/api/threads", { query: { channelId } })).threads,
807
+ recent: async (owner, limit = 50) => (await this.http.get("/api/threads/recent", { query: {
808
+ owner,
809
+ limit
810
+ } })).threads,
811
+ get: (id) => this.http.get(`/api/threads/${seg(id)}`),
812
+ create: (channelId, subject, owner) => this.http.post("/api/threads", {
813
+ channelId,
814
+ subject,
815
+ owner
816
+ }),
817
+ update: (id, patch) => this.http.put(`/api/threads/${seg(id)}`, patch),
818
+ archive: async (id) => {
819
+ await this.http.delete(`/api/threads/${seg(id)}`);
820
+ }
821
+ };
822
+ /** Message operations. */
823
+ messages = {
824
+ list: async (threadId) => (await this.http.get("/api/messages", { query: { threadId } })).messages,
825
+ get: (id) => this.http.get(`/api/messages/${seg(id)}`),
826
+ approveToolCall: (messageId, toolCallId, approved, reason) => this.http.post("/api/messages/approve-tool-call", {
827
+ messageId,
828
+ toolCallId,
829
+ approved,
830
+ ...reason ? { reason } : {}
831
+ }),
832
+ answerToolCall: (messageId, toolCallId, answer) => this.http.post("/api/messages/answer-tool-call", {
833
+ messageId,
834
+ toolCallId,
835
+ ...answer
836
+ }),
837
+ create: (threadId, parts, options = {}) => this.http.post("/api/messages", {
838
+ threadId,
839
+ parts,
840
+ ...options
841
+ }),
842
+ uploadFile: async (threadId, file) => this.http.post("/api/messages/upload-file", {
843
+ threadId,
844
+ filename: file.name || "file",
845
+ mediaType: file.type || void 0,
846
+ content: await blobToBase64(file)
847
+ }),
848
+ files: async (channelId) => (await this.http.get("/api/messages/files", { query: { channelId } })).files,
849
+ usage: async (threadId) => (await this.http.get("/api/messages/usage", { query: { threadId } })).usage,
850
+ getFile: (messageId, partId) => this.http.get("/api/messages/file", { query: {
851
+ messageId,
852
+ partId
853
+ } }),
854
+ getFileBlob: async (messageId, partId) => {
855
+ const file = await this.http.get("/api/messages/file", { query: {
856
+ messageId,
857
+ partId
858
+ } });
859
+ return new Blob([base64ToBytes(file.content)], { type: file.mediaType });
860
+ }
861
+ };
862
+ /** Widgets of tool calls in messages: MCP Apps served by the plugins agents use. */
863
+ widgets = {
864
+ get: (messageId, toolCallId) => this.http.get("/api/widgets", { query: {
865
+ messageId,
866
+ toolCallId
867
+ } }),
868
+ callTool: (messageId, toolCallId, name, args = {}) => this.http.post("/api/widgets/call-tool", {
869
+ messageId,
870
+ toolCallId,
871
+ name,
872
+ args
873
+ }),
874
+ updateContext: (messageId, toolCallId, context) => this.http.put("/api/widgets/context", {
875
+ messageId,
876
+ toolCallId,
877
+ ...context
878
+ })
879
+ };
880
+ /** The companies listed on a channel. */
881
+ channelCompanies = {
882
+ list: async (channelId) => (await this.http.get("/api/channel-companies", { query: { channelId } })).companies,
883
+ candidates: async (channelId) => (await this.http.get("/api/channel-companies/candidates", { query: { channelId } })).companies,
884
+ add: (channelId, companyId) => this.http.post("/api/channel-companies", {
885
+ channelId,
886
+ companyId
887
+ }),
888
+ end: async (id) => {
889
+ await this.http.delete(`/api/channel-companies/${seg(id)}`);
890
+ }
891
+ };
892
+ /** Channel agent operations. */
893
+ channelAgents = {
894
+ list: async (channelId) => (await this.http.get("/api/channel-agents", { query: { channelId } })).agents,
895
+ attach: (channelId, pluginId, agentName) => this.http.post("/api/channel-agents", {
896
+ channelId,
897
+ pluginId,
898
+ agentName
899
+ }),
900
+ update: (channelId, agentId, patch) => this.http.put("/api/channel-agents", {
901
+ channelId,
902
+ agentId,
903
+ ...patch
904
+ }),
905
+ detach: async (channelId, agentId) => {
906
+ await this.http.delete("/api/channel-agents", { query: {
907
+ channelId,
908
+ agentId
909
+ } });
910
+ },
911
+ runSchedule: async (channelId, agentId, scheduleId) => {
912
+ await this.http.post("/api/channel-agents/run-schedule", {
913
+ channelId,
914
+ agentId,
915
+ scheduleId
916
+ });
917
+ }
918
+ };
919
+ /**
920
+ * Tests of the plugins a channel's agents use, as one of the channel's customers: the API calls
921
+ * them with the agent's token for that company, as in a scheduled run.
922
+ */
923
+ pluginTests = {
924
+ createToken: (subject) => this.http.post("/api/plugin-tests/token", subject),
925
+ listTools: (subject) => this.http.get("/api/plugin-tests/tools", { query: { ...subject } }),
926
+ callTool: (subject, pluginId, name, args = {}, forWidget = false) => this.http.post("/api/plugin-tests/call-tool", {
927
+ ...subject,
928
+ pluginId,
929
+ name,
930
+ args,
931
+ forWidget
932
+ }),
933
+ getWidget: (subject, pluginId, uri) => this.http.get("/api/plugin-tests/widget", { query: {
934
+ ...subject,
935
+ pluginId,
936
+ uri
937
+ } })
938
+ };
939
+ /**
940
+ * The views of the Hub's front page besides the chats: the saved dashboards of the dashboards
941
+ * plugins the organization's channels use, each shown with its plugin's widget as the person.
942
+ */
943
+ homeViews = {
944
+ list: (owner, language) => this.http.get("/api/home-views/views", { query: {
945
+ owner,
946
+ language
947
+ } }),
948
+ show: (owner, pluginId, name, language) => this.http.post("/api/home-views/show-view", {
949
+ owner,
950
+ pluginId,
951
+ name,
952
+ language
953
+ }),
954
+ getWidget: (owner, pluginId, uri) => this.http.get("/api/home-views/widget", { query: {
955
+ owner,
956
+ pluginId,
957
+ uri
958
+ } }),
959
+ callTool: (owner, pluginId, name, args = {}) => this.http.post("/api/home-views/call-tool", {
960
+ owner,
961
+ pluginId,
962
+ name,
963
+ args
964
+ })
965
+ };
966
+ };
967
+ //#endregion
968
+ export { AgentsApi, ApiError, ChannelsApi, HttpClient, ID_FORMAT_PATTERN, LiveEvents, MessagesApi, ModelsApi, base64ToBytes, blobToBase64, bytesToBase64, configureClient, filesSource, isValidId, loadClientConfig, toFsError };