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