@tai42/api-client 0.1.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.
Files changed (48) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +28 -0
  3. package/dist/agents.d.ts +265 -0
  4. package/dist/agents.d.ts.map +1 -0
  5. package/dist/agents.js +200 -0
  6. package/dist/agents.js.map +1 -0
  7. package/dist/client.d.ts +1316 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/client.js +468 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/errors.d.ts +43 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +63 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/fleet-report.d.ts +61 -0
  16. package/dist/fleet-report.d.ts.map +1 -0
  17. package/dist/fleet-report.js +42 -0
  18. package/dist/fleet-report.js.map +1 -0
  19. package/dist/http.d.ts +69 -0
  20. package/dist/http.d.ts.map +1 -0
  21. package/dist/http.js +152 -0
  22. package/dist/http.js.map +1 -0
  23. package/dist/index.d.ts +23 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +16 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/schemas.d.ts +5469 -0
  28. package/dist/schemas.d.ts.map +1 -0
  29. package/dist/schemas.js +1103 -0
  30. package/dist/schemas.js.map +1 -0
  31. package/dist/sse.d.ts +27 -0
  32. package/dist/sse.d.ts.map +1 -0
  33. package/dist/sse.js +84 -0
  34. package/dist/sse.js.map +1 -0
  35. package/dist/tool-runs.d.ts +112 -0
  36. package/dist/tool-runs.d.ts.map +1 -0
  37. package/dist/tool-runs.js +70 -0
  38. package/dist/tool-runs.js.map +1 -0
  39. package/package.json +51 -0
  40. package/src/agents.ts +248 -0
  41. package/src/client.ts +837 -0
  42. package/src/errors.ts +67 -0
  43. package/src/fleet-report.ts +94 -0
  44. package/src/http.ts +198 -0
  45. package/src/index.ts +142 -0
  46. package/src/schemas.ts +1341 -0
  47. package/src/sse.ts +90 -0
  48. package/src/tool-runs.ts +103 -0
package/src/client.ts ADDED
@@ -0,0 +1,837 @@
1
+ /**
2
+ * The typed client: one method per endpoint, each validating
3
+ * its response against the matching zod schema. Server state flows through
4
+ * TanStack Query in the features; this client is a plain typed transport with no
5
+ * caching of its own.
6
+ */
7
+ import {
8
+ type ApiConfig,
9
+ type RequestOptions,
10
+ apiDownload,
11
+ apiRequest,
12
+ apiText,
13
+ encodeSegment,
14
+ isUnsafePathSegment,
15
+ } from './http';
16
+ import { ApiError, ApiLoginFailedError, ApiUnauthorizedError } from './errors';
17
+ import { readSseFrames } from './sse';
18
+ import { agentList, streamAgentRun, streamAuthoredAgentRun } from './agents';
19
+ import { getToolRun, listToolRuns, submitToolRun, type SubmitToolRunArgs } from './tool-runs';
20
+ import * as s from './schemas';
21
+
22
+ export interface RunToolArgs {
23
+ readonly tool: string;
24
+ readonly kwargs?: Record<string, unknown>;
25
+ }
26
+
27
+ export interface StartConnectArgs {
28
+ readonly provider_id: string;
29
+ readonly alias: string;
30
+ readonly enabled_sub_services: string[];
31
+ readonly config_values?: Record<string, string>;
32
+ readonly return_url?: string;
33
+ }
34
+
35
+ /** Body for creating or editing an API key (POST/PUT `/api/auth/api-keys`). */
36
+ export interface ApiKeyBody {
37
+ readonly user_id: string;
38
+ readonly description: string;
39
+ readonly scopes: string[];
40
+ // `null` is an explicit clear on edit (PATCH-style PUT): absent preserves the
41
+ // stored policy data, `null` wipes it. Create never sends `null`.
42
+ readonly policy_data?: Record<string, unknown> | null;
43
+ readonly condition?: string | null;
44
+ readonly condition_id?: string | null;
45
+ readonly condition_kwargs?: Record<string, unknown> | null;
46
+ }
47
+
48
+ /**
49
+ * Body for one-time claim-link creation (POST `/api/auth/claim-links`). The
50
+ * `api_key` is a raw key the caller holds (the just-minted key, client-side
51
+ * exactly once); `ttl_seconds` optionally overrides the default lifetime (the
52
+ * server caps it at its ceiling).
53
+ */
54
+ export interface ClaimLinkBody {
55
+ readonly api_key: string;
56
+ readonly ttl_seconds?: number | null;
57
+ }
58
+
59
+ /**
60
+ * Body for the fail-closed jq guard (POST `/api/auth/validate-condition`).
61
+ * `condition` (inline jq) and `condition_id` (named template) are mutually
62
+ * exclusive — send exactly one. `sample_context` is a `JqAuthContext`-shaped
63
+ * sample; when present the guard also evaluates the condition against it and
64
+ * returns the boolean `result` (else `result` is `null`).
65
+ */
66
+ export interface ValidateConditionBody {
67
+ readonly condition?: string;
68
+ readonly condition_id?: string;
69
+ readonly condition_kwargs?: Record<string, unknown>;
70
+ readonly sample_context?: Record<string, unknown>;
71
+ }
72
+
73
+ /**
74
+ * Body for binding a webhook verifier to a topic
75
+ * (PUT `/api/hooks/topics/{topic}/verifier`). `verifier` is a registered verifier
76
+ * NAME, resolved against the live registry at bind time (an unknown name is a loud
77
+ * 400). `config` is that verifier's config object — it carries a `secret_env` name,
78
+ * never a secret value — and defaults to `{}` when omitted.
79
+ */
80
+ export interface TopicVerifierBody {
81
+ readonly verifier: string;
82
+ readonly config?: Record<string, unknown>;
83
+ }
84
+
85
+ /** Body for adding a URL to a scope (POST `/api/auth/scopes`). */
86
+ export interface AddUrlToScopeBody {
87
+ readonly scope_id: string;
88
+ readonly url: string;
89
+ readonly pattern?: string;
90
+ }
91
+
92
+ /**
93
+ * Body for pinning a route public (POST `/api/auth/public-routes`). `pattern` is an
94
+ * optional regex the AC verifier full-matches request paths against, mapping every
95
+ * match to the `url` key (so a mount's whole subtree can be pinned in one call).
96
+ */
97
+ export interface PinRoutePublicBody {
98
+ readonly url: string;
99
+ readonly pattern?: string;
100
+ }
101
+
102
+ /**
103
+ * Body for creating a preset (POST `/api/presets`). `tags` are the preset's
104
+ * categorization labels. `extensions` is the combos list — the create flow OMITS
105
+ * it when there are no combos (the route rejects an explicit `extensions: []`).
106
+ * `output_schema` is the optional author-set output JSON Schema. Each combo
107
+ * element is a bare extension name or a `{ name, config }` mapping.
108
+ */
109
+ export interface CreatePresetBody {
110
+ readonly name: string;
111
+ readonly base_tool: string;
112
+ readonly description?: string;
113
+ readonly fixed_kwargs?: Record<string, unknown>;
114
+ readonly tags?: readonly string[];
115
+ readonly extensions?: readonly s.PresetExtensionElement[][];
116
+ readonly output_schema?: Record<string, unknown> | null;
117
+ }
118
+
119
+ /**
120
+ * Body for saving a new preset version (POST `/api/presets/{name}/versions`). At
121
+ * least one field must be provided (an empty body is a loud 400). Each field's
122
+ * sentinel is uniform: omitted carries the active version's value forward; an
123
+ * explicit `[]` clears `tags`/`extensions`, and an explicit `null` clears
124
+ * `output_schema`.
125
+ */
126
+ export interface SavePresetVersionBody {
127
+ readonly fixed_kwargs?: Record<string, unknown>;
128
+ readonly tags?: readonly string[];
129
+ readonly extensions?: readonly s.PresetExtensionElement[][];
130
+ readonly output_schema?: Record<string, unknown> | null;
131
+ }
132
+
133
+ /**
134
+ * Body for the dry-run validate door (POST `/api/presets/validate`). `name` is
135
+ * required and selects the verdict mode server-side: CREATE when no preset named
136
+ * `name` exists (then `base_tool` is required), VERSION when one does (the version
137
+ * fields are read under save-version semantics). The draft is sent exactly as the
138
+ * matching write would send it.
139
+ */
140
+ export interface ValidatePresetBody {
141
+ readonly name: string;
142
+ readonly base_tool?: string;
143
+ readonly description?: string;
144
+ readonly fixed_kwargs?: Record<string, unknown>;
145
+ readonly tags?: readonly string[];
146
+ readonly extensions?: readonly s.PresetExtensionElement[][];
147
+ readonly output_schema?: Record<string, unknown> | null;
148
+ }
149
+
150
+ /**
151
+ * Body for a storage upload (POST `/api/storage/resources`). Exactly ONE of
152
+ * `content_text` (stored verbatim) or `content_base64` (a base64 string decoded to
153
+ * bytes) supplies the content for `id`; uploading an existing id overwrites it
154
+ * (provider passthrough semantics).
155
+ */
156
+ export interface StorageUploadBody {
157
+ readonly id: string;
158
+ readonly content_text?: string;
159
+ readonly content_base64?: string;
160
+ }
161
+
162
+ /** The observability-metrics window + bucket size (GET query params). */
163
+ export interface MetricsQuery {
164
+ readonly from?: string;
165
+ readonly to?: string;
166
+ readonly granularity?: string;
167
+ }
168
+
169
+ /**
170
+ * The observability runs filter. List/dict-valued params (`tags`) are
171
+ * JSON-encoded into the query string; scalars are sent verbatim. Shared by
172
+ * `listRuns` and the `exportRuns` download.
173
+ */
174
+ export interface RunsQuery {
175
+ readonly from?: string;
176
+ readonly to?: string;
177
+ readonly tags?: string[];
178
+ readonly status?: 'error' | 'success';
179
+ readonly minCost?: number;
180
+ readonly maxCost?: number;
181
+ readonly minTokens?: number;
182
+ readonly maxTokens?: number;
183
+ readonly minLatencyMs?: number;
184
+ readonly maxLatencyMs?: number;
185
+ readonly sort?: string;
186
+ readonly dir?: 'asc' | 'desc';
187
+ readonly page?: number;
188
+ readonly pageSize?: number;
189
+ }
190
+
191
+ /**
192
+ * The marketplace search filter (GET `/api/marketplace/search` query params).
193
+ * `tags` is sent as REPEATED `tags` params, one per value; `page` is supplied
194
+ * per-request by the infinite query, never from the URL. `tier`, `namespace`,
195
+ * `contract`, and `page_size` are accepted by the route but the v1 UI sends none
196
+ * of them (every v1 row is official/tai42; the page size stays the server
197
+ * default) — they exist for contract completeness.
198
+ */
199
+ export interface MarketplaceSearchQuery {
200
+ readonly q?: string;
201
+ readonly kind?: string;
202
+ readonly category?: string;
203
+ readonly tags?: string[];
204
+ readonly namespace?: string;
205
+ readonly tier?: string;
206
+ readonly contract?: string;
207
+ readonly sort?: 'downloads' | 'updated' | 'name' | 'relevance';
208
+ readonly page?: number;
209
+ readonly page_size?: number;
210
+ }
211
+
212
+ /** Body for installing / updating a plugin. `ref` is `namespace/name`. */
213
+ export interface MarketplaceInstallBody {
214
+ readonly ref: string;
215
+ readonly version?: string;
216
+ }
217
+
218
+ /** Body for uninstalling a plugin. */
219
+ export interface MarketplaceUninstallBody {
220
+ readonly ref: string;
221
+ }
222
+
223
+ /**
224
+ * Encode a possibly-nested storage id / directory path for use in a URL path,
225
+ * percent-encoding each segment while preserving the `/` separators. A storage id
226
+ * can be a nested path (e.g. `a/b c.txt`); encoding each segment independently keeps
227
+ * the slashes structural and escapes everything else (spaces, `#`, `?`, …).
228
+ *
229
+ * Dot segments (`.`, `..`), empty segments (a leading/trailing/doubled `/`, or an
230
+ * empty id) are REJECTED loudly rather than encoded: the browser's WHATWG URL parser
231
+ * removes dot-segments from a relative request path before it is sent — collapsing
232
+ * `..` even when percent-encoded — so such an id can never be faithfully transmitted.
233
+ * Left to encode, it would silently retarget the request at an unrelated same-origin
234
+ * route. The server enforces the same relative-path rule; failing fast here keeps a
235
+ * malformed id from ever leaving the client.
236
+ */
237
+ function encodePath(id: string): string {
238
+ const segments = id.split('/');
239
+ if (segments.some(isUnsafePathSegment)) {
240
+ throw new Error("storage path must be a relative path with no empty, '.', or '..' segment");
241
+ }
242
+ return segments.map(encodeURIComponent).join('/');
243
+ }
244
+
245
+ /** Flatten a `RunsQuery` to transport params, JSON-encoding the `tags` list. */
246
+ function runsQueryToParams(query: RunsQuery): Required<RequestOptions>['query'] {
247
+ return {
248
+ from: query.from,
249
+ to: query.to,
250
+ tags: query.tags === undefined ? undefined : JSON.stringify(query.tags),
251
+ status: query.status,
252
+ minCost: query.minCost,
253
+ maxCost: query.maxCost,
254
+ minTokens: query.minTokens,
255
+ maxTokens: query.maxTokens,
256
+ minLatencyMs: query.minLatencyMs,
257
+ maxLatencyMs: query.maxLatencyMs,
258
+ sort: query.sort,
259
+ dir: query.dir,
260
+ page: query.page,
261
+ pageSize: query.pageSize,
262
+ };
263
+ }
264
+
265
+ /**
266
+ * Whether a login-method target is a safe same-origin relative API path. The
267
+ * login screen is the one page where a misconfigured/compromised manifest could
268
+ * redirect CREDENTIALS off-origin, so a `submit_path`/`href` MUST start `/api/`
269
+ * — anything else (absolute URL, protocol-relative `//host`, missing prefix) is
270
+ * rejected. The `/api/` prefix already excludes `//`-prefixed values; the
271
+ * explicit double-slash clause is kept for readability.
272
+ */
273
+ export function isSafeApiPath(path: string): boolean {
274
+ return path.startsWith('/api/') && !path.startsWith('//');
275
+ }
276
+
277
+ /**
278
+ * Map a transport error from a login submission onto an `ApiLoginFailedError`
279
+ * (rendered inline on the login page) or rethrow it unchanged (5xx, schema
280
+ * drift, network — the page's generic failure branch surfaces it loudly).
281
+ *
282
+ * A transport 401 arrives as `ApiUnauthorizedError` before any body is read, so
283
+ * its message is generic by construction; the domain 4xx statuses carry the
284
+ * server's informative envelope text (rate-limit, bootstrap-already-initialized,
285
+ * password-policy, or the claim exchange's uniform "unknown or already used"
286
+ * 404) straight through to the inline surface.
287
+ */
288
+ function asLoginError(error: unknown): never {
289
+ if (error instanceof ApiUnauthorizedError) {
290
+ throw new ApiLoginFailedError('Sign-in failed — check your credentials.', 401);
291
+ }
292
+ if (
293
+ error instanceof ApiError &&
294
+ (error.status === 400 ||
295
+ error.status === 403 ||
296
+ error.status === 404 ||
297
+ error.status === 409 ||
298
+ error.status === 422 ||
299
+ error.status === 429)
300
+ ) {
301
+ throw new ApiLoginFailedError(error.message, error.status);
302
+ }
303
+ throw error;
304
+ }
305
+
306
+ export function createApiClient(config: ApiConfig) {
307
+ const req = <S extends Parameters<typeof apiRequest>[2]>(
308
+ path: string,
309
+ schema: S,
310
+ options?: Parameters<typeof apiRequest>[3],
311
+ ) => apiRequest(config, path, schema, options);
312
+
313
+ return {
314
+ // -- tools ---------------------------------------------------------------
315
+ listTools: (signal?: AbortSignal) => req('/api/tools', s.toolNames, { signal }),
316
+ getToolSchema: (name: string, signal?: AbortSignal) =>
317
+ req(`/api/tools/${encodeSegment(name)}/schema`, s.toolSchema, { signal }),
318
+ getAllToolSchemas: (signal?: AbortSignal) =>
319
+ req('/api/tools-schema', s.allToolSchemas, { signal }),
320
+ runTool: (args: RunToolArgs, signal?: AbortSignal) =>
321
+ req('/api/run-tool', s.runToolResult, {
322
+ method: 'POST',
323
+ // The backend's `/api/run-tool` door reads `{tool_name, arguments}` (the
324
+ // shape `read_tool_call` enforces and the background `/api/tool-runs`
325
+ // submit already sends). The SPA keeps `tool`/`kwargs` as its ergonomic
326
+ // arg names; map them onto the wire fields here.
327
+ body: { tool_name: args.tool, arguments: args.kwargs ?? {} },
328
+ signal,
329
+ }),
330
+
331
+ // -- background tool runs ------------------------------------------------
332
+ submitToolRun: (args: SubmitToolRunArgs, signal?: AbortSignal) =>
333
+ submitToolRun(config, args, signal),
334
+ getToolRun: (runId: string, signal?: AbortSignal) => getToolRun(config, runId, signal),
335
+ listToolRuns: (toolName: string, signal?: AbortSignal) =>
336
+ listToolRuns(config, toolName, signal),
337
+
338
+ // -- tool tags (additive map feeding the ToolPicker tag grouping) --------
339
+ listToolTags: (signal?: AbortSignal) => req('/api/tools/tags', s.toolTags, { signal }),
340
+
341
+ // -- presets -------------------------------------------------------------
342
+ // Every preset is store-backed and versioned; the list is the single
343
+ // management population (the presets plus the conflicted quarantined rows).
344
+ listPresets: (signal?: AbortSignal) => req('/api/presets', s.presetList, { signal }),
345
+ createPreset: (body: CreatePresetBody) =>
346
+ req('/api/presets', s.presetRecord, { method: 'POST', body }),
347
+ getPreset: (name: string, signal?: AbortSignal) =>
348
+ req(`/api/presets/${encodeSegment(name)}`, s.presetDetail, { signal }),
349
+ listPresetVersions: (name: string, signal?: AbortSignal) =>
350
+ req(`/api/presets/${encodeSegment(name)}/versions`, s.presetVersionList, { signal }),
351
+ getPresetVersion: (name: string, version: number, signal?: AbortSignal) =>
352
+ req(
353
+ `/api/presets/${encodeSegment(name)}/versions/${encodeSegment(version)}`,
354
+ s.presetVersion,
355
+ { signal },
356
+ ),
357
+ savePresetVersion: (name: string, body: SavePresetVersionBody) =>
358
+ req(`/api/presets/${encodeSegment(name)}/versions`, s.presetVersion, {
359
+ method: 'POST',
360
+ body,
361
+ }),
362
+ rollbackPreset: (name: string, version: number) =>
363
+ req(`/api/presets/${encodeSegment(name)}/rollback`, s.presetRollback, {
364
+ method: 'POST',
365
+ body: { version },
366
+ }),
367
+ deletePreset: (name: string) =>
368
+ req(`/api/presets/${encodeSegment(name)}`, s.presetDeleted, { method: 'DELETE' }),
369
+ renamePreset: (name: string, newName: string) =>
370
+ req(`/api/presets/${encodeSegment(name)}/rename`, s.presetRenamed, {
371
+ method: 'POST',
372
+ body: { new_name: newName },
373
+ }),
374
+ // The presets whose active composition names this one as a tool — the referees
375
+ // a rename would strand. A rename preflight reads this to warn before the 409.
376
+ getPresetReferees: (name: string, signal?: AbortSignal) =>
377
+ req(`/api/presets/${encodeSegment(name)}/referees`, s.presetReferees, { signal }),
378
+ // The dry-run verdict for a draft (create OR version, mode-resolved server-side):
379
+ // `valid` plus the server's verbatim `error` message. Both verdicts are HTTP 200.
380
+ validatePreset: (body: ValidatePresetBody) =>
381
+ req('/api/presets/validate', s.presetValidation, { method: 'POST', body }),
382
+ // Replace one version's `tags` annotation — labels on an immutable body, so no
383
+ // rebind. Returns the re-annotated identity + new tag list.
384
+ setPresetVersionTags: (name: string, version: number, tags: readonly string[]) =>
385
+ req(
386
+ `/api/presets/${encodeSegment(name)}/versions/${encodeSegment(version)}/tags`,
387
+ s.presetVersionTags,
388
+ { method: 'PUT', body: { tags } },
389
+ ),
390
+
391
+ // -- storage -------------------------------------------------------------
392
+ // The content store a storage-provider plugin exposes. Dead by default:
393
+ // `getStorageInfo` reports `present: false` (a 200 empty state) and every other
394
+ // door answers a loud 501 when no provider is installed. Ids may be nested
395
+ // paths, so each is `encodePath`-encoded (per-segment, `/` preserved).
396
+ getStorageInfo: (signal?: AbortSignal) => req('/api/storage', s.storageInfo, { signal }),
397
+ listStorageResources: (signal?: AbortSignal) =>
398
+ req('/api/storage/resources', s.storageResourceList, { signal }),
399
+ statStorageResource: (id: string, signal?: AbortSignal) =>
400
+ req(`/api/storage/resources/${encodePath(id)}/stat`, s.storageResourceStat, { signal }),
401
+ downloadStorageResource: (id: string, signal?: AbortSignal): Promise<Blob> =>
402
+ apiDownload(config, `/api/storage/resources/${encodePath(id)}/content`, { signal }),
403
+ uploadStorageResource: (body: StorageUploadBody) =>
404
+ req('/api/storage/resources', s.storageResourceStored, { method: 'POST', body }),
405
+ deleteStorageResource: (id: string) =>
406
+ req(`/api/storage/resources/${encodePath(id)}`, s.storageResourceDeleted, {
407
+ method: 'DELETE',
408
+ }),
409
+ deleteStorageDir: (path: string) =>
410
+ req(`/api/storage/dirs/${encodePath(path)}`, s.storageDirDeleted, { method: 'DELETE' }),
411
+
412
+ // -- backend identity + fleet (worker bus) -------------------------------
413
+ // Backend IDENTITY (`getBackendInfo`, kept on `/api/backend`) is distinct from
414
+ // the FLEET doors, which ride the app's worker bus and need no backend at all.
415
+ // `getBackendInfo` reports `present: false` (a 200 empty state) when no backend
416
+ // plugin is registered. `listFleetWorkers` reads the live bus presence census
417
+ // (every subscribed origin, ASGI + backend-runtime) and never fabricates an empty
418
+ // fleet — a census read that fails surfaces as a loud 500.
419
+ getBackendInfo: (signal?: AbortSignal) => req('/api/backend', s.backendInfo, { signal }),
420
+ listFleetWorkers: (signal?: AbortSignal) =>
421
+ req('/api/fleet/workers', s.fleetWorkers, { signal }),
422
+ // Soft-restart the fleet: `targets` names the workers to reload, or `null` for
423
+ // the whole fleet. The serving worker applies locally then broadcasts; a 200
424
+ // response carries the per-origin fleet report, so workers that did not converge
425
+ // are named, not hidden. A failed local apply instead re-raises as a loud error
426
+ // (the transport throws with the failure message), not a returned report.
427
+ reloadFleetConfig: (targets: string[] | null) =>
428
+ req('/api/fleet/reload-config', s.fleetReloadResult, { method: 'POST', body: { targets } }),
429
+
430
+ // -- extensions ----------------------------------------------------------
431
+ listExtensions: (signal?: AbortSignal) => req('/api/extensions', s.extensions, { signal }),
432
+ // A MANIFEST-provided tool's current combos + the extension catalog. (A preset
433
+ // tool's extensions live on the preset spec, read via `getPreset`.)
434
+ getToolExtensions: (name: string, signal?: AbortSignal) =>
435
+ req(`/api/tools/${encodeSegment(name)}/extensions`, s.toolExtensions, { signal }),
436
+ // Author ALL of a MANIFEST tool's combos at once (the full lossless list; `[]`
437
+ // clears). Returns the apply result: the local reload (`status` + `env_keys`) plus
438
+ // the mode-wrapped fleet `fanout` of the reload it broadcast, from which the shared
439
+ // fleet-report handler surfaces any failed propagation.
440
+ setToolExtensions: (name: string, combos: readonly s.PresetExtensionElement[][]) =>
441
+ req(`/api/tools/${encodeSegment(name)}/extensions`, s.toolExtensionsApplyResult, {
442
+ method: 'POST',
443
+ body: { combos },
444
+ }),
445
+
446
+ // -- templates -----------------------------------------------------------
447
+ listTemplates: (signal?: AbortSignal) => req('/api/templates', s.templateNames, { signal }),
448
+ getTemplate: (templateId: string) =>
449
+ req('/api/template', s.templateDetail, { method: 'POST', body: { template_id: templateId } }),
450
+ uploadTemplate: (path: string, content: string) =>
451
+ req('/api/upload-template', s.templateUploaded, { method: 'POST', body: { path, content } }),
452
+ deleteTemplate: (path: string) =>
453
+ req('/api/delete-template', s.templateDeleted, { method: 'POST', body: { path } }),
454
+ renderTemplate: (body: {
455
+ content?: string;
456
+ template_id?: string;
457
+ kwargs?: Record<string, unknown>;
458
+ }) => req('/api/render-template', s.templateRendered, { method: 'POST', body }),
459
+ clearTemplatesCache: () =>
460
+ req('/api/clear-templates-cache', s.templateCacheCleared, { method: 'POST' }),
461
+
462
+ // -- manifest / mcp ------------------------------------------------------
463
+ getManifest: (signal?: AbortSignal) => req('/api/manifest', s.manifestView, { signal }),
464
+ setMcpConfig: (mcp: unknown[]) =>
465
+ req('/api/mcp-config', s.reloadConfigResult, { method: 'POST', body: { mcp } }),
466
+ getMcpStatus: (signal?: AbortSignal) => req('/api/mcp-status', s.mcpStatus, { signal }),
467
+ reloadMcp: (title: string) =>
468
+ req(`/api/mcp-status/${encodeSegment(title)}/reload`, s.mcpReloadResult, {
469
+ method: 'POST',
470
+ }),
471
+
472
+ // -- sub-mcp -------------------------------------------------------------
473
+ listSubMcp: (signal?: AbortSignal) => req('/api/sub-mcp', s.subMcpList, { signal }),
474
+ createSubMcp: (slug: string, tools: string[]) =>
475
+ req('/api/sub-mcp', s.subMcpCreated, { method: 'POST', body: { slug, tools } }),
476
+ deleteSubMcp: (slug: string) =>
477
+ req(`/api/sub-mcp/${encodeSegment(slug)}`, s.subMcpRemoved, { method: 'DELETE' }),
478
+
479
+ // -- config --------------------------------------------------------------
480
+ getEnvConfig: (signal?: AbortSignal) => req('/api/config/env', s.envConfig, { signal }),
481
+ setEnvConfig: (env: Record<string, string>) =>
482
+ req('/api/config/env', s.reloadConfigResult, { method: 'POST', body: env }),
483
+ getConfigMode: (signal?: AbortSignal) => req('/api/config/mode', s.configMode, { signal }),
484
+
485
+ // -- connectors ----------------------------------------------------------
486
+ listProviders: (signal?: AbortSignal) =>
487
+ req('/api/connectors/providers', s.providers, { signal }),
488
+ listConnections: (signal?: AbortSignal) =>
489
+ req('/api/connectors/connections', s.connectionsList, { signal }),
490
+ getConnection: (id: string, signal?: AbortSignal) =>
491
+ req(`/api/connectors/connections/${encodeSegment(id)}`, s.connectionView, { signal }),
492
+ startConnect: (args: StartConnectArgs) =>
493
+ req('/api/connectors/connections/start', s.startConnectResult, {
494
+ method: 'POST',
495
+ body: args,
496
+ }),
497
+ disconnect: (id: string) =>
498
+ req(`/api/connectors/connections/${encodeSegment(id)}`, s.disconnectResult, {
499
+ method: 'DELETE',
500
+ }),
501
+ reconnect: (id: string, enabled_sub_services: string[], return_url?: string) =>
502
+ req(`/api/connectors/connections/${encodeSegment(id)}/reconnect`, s.reconnectResult, {
503
+ method: 'POST',
504
+ body: { enabled_sub_services, return_url },
505
+ }),
506
+ patchSubServices: (id: string, enabled_sub_services: string[], return_url?: string) =>
507
+ req(
508
+ `/api/connectors/connections/${encodeSegment(id)}/sub-services`,
509
+ s.patchSubServicesResult,
510
+ {
511
+ method: 'PATCH',
512
+ body: { enabled_sub_services, return_url },
513
+ },
514
+ ),
515
+ completeOAuth: (state: string, code: string, error?: string) =>
516
+ req('/api/connectors/oauth/complete', s.oauthCompleteResult, {
517
+ method: 'POST',
518
+ body: { state, code, error },
519
+ }),
520
+
521
+ // -- studio plugin registry ---------------------------------------------
522
+ listStudioPlugins: (signal?: AbortSignal) =>
523
+ req('/api/plugins', s.studioPluginRegistry, { signal }),
524
+
525
+ // -- interactions --------------------------------------------------------
526
+ answerInteraction: (interactionId: string, answer: unknown) =>
527
+ req(`/api/interactions/${encodeSegment(interactionId)}/answer`, s.interactionAnswered, {
528
+ method: 'POST',
529
+ body: { answer },
530
+ }),
531
+
532
+ // -- channels --------------------------------------------------------------
533
+ // The installed channel-plugin names (delivery media for ask_user questions).
534
+ listChannels: (signal?: AbortSignal) => req('/api/channels', s.channels, { signal }),
535
+
536
+ // -- notifications ---------------------------------------------------------
537
+ // The internal notifications sink, newest-first — the messages the `notify_user`
538
+ // operation records with no channel, so they surface only in this inbox.
539
+ listNotifications: (signal?: AbortSignal) =>
540
+ req('/api/notifications', s.notifications, { signal }),
541
+
542
+ // -- agents --------------------------------------------------------------
543
+ listAgents: (signal?: AbortSignal) => req('/api/agents', agentList, { signal }),
544
+ // The authorable subset (agents whose `spec_runnable` is true) — the compose
545
+ // UI's base-agent picker. An empty `items` list ⇒ no authoring is possible.
546
+ listSpecRunnableAgents: (signal?: AbortSignal) =>
547
+ req('/api/agents/spec-runnable', agentList, { signal }),
548
+ // The streaming run: opens POST /api/agents/{name}/runs and yields parsed
549
+ // agent events. The auto-form's built value is the POST body.
550
+ streamAgentRun: (name: string, input: unknown, signal?: AbortSignal) =>
551
+ streamAgentRun(config, name, input, signal),
552
+ // The streaming run of an AUTHORED agent (POST /api/agents/authored/{name}/runs).
553
+ // The body carries only the non-baked ToolInput fields; the baked spec is
554
+ // resolved server-side. Reuses the same SSE parser (never EventSource).
555
+ streamAuthoredAgentRun: (name: string, input: unknown, signal?: AbortSignal) =>
556
+ streamAuthoredAgentRun(config, name, input, signal),
557
+
558
+ // -- hooks --------------------------------------------------------
559
+ listHooks: (topic?: string, signal?: AbortSignal) =>
560
+ req('/api/hooks', s.hookList, { signal, query: topic === undefined ? undefined : { topic } }),
561
+ registerHook: (params: s.HookParams) =>
562
+ req('/api/hooks', s.hookRegistered, { method: 'POST', body: params }),
563
+ unregisterHook: (name: string) =>
564
+ req(`/api/hooks/${encodeSegment(name)}`, s.hookRemoved, { method: 'DELETE' }),
565
+ // The registered webhook-verifier catalog — the only source the bind picker
566
+ // reads (names only; an empty registry is a valid empty list).
567
+ listHookVerifiers: (signal?: AbortSignal) =>
568
+ req('/api/hooks/verifiers', s.hookVerifiers, { signal }),
569
+ // Bind a verifier to a topic (locks its otherwise-open public ingress). A PUT
570
+ // replaces any existing binding; an unknown verifier name is a loud 400.
571
+ setTopicVerifier: (topic: string, body: TopicVerifierBody) =>
572
+ req(`/api/hooks/topics/${encodeSegment(topic)}/verifier`, s.topicVerifierSet, {
573
+ method: 'PUT',
574
+ body,
575
+ }),
576
+ // Unbind a topic's verifier (re-opens its public ingress). 404 when no binding.
577
+ deleteTopicVerifier: (topic: string) =>
578
+ req(`/api/hooks/topics/${encodeSegment(topic)}/verifier`, s.topicVerifierRemoved, {
579
+ method: 'DELETE',
580
+ }),
581
+
582
+ // -- mcp config schema (manifest McpTab form) ----------------------------
583
+ getMcpConfigSchema: (signal?: AbortSignal) =>
584
+ req('/api/mcp-config/schema', s.jsonSchema, { signal }),
585
+
586
+ // -- settings schema -----------------------------------------------------
587
+ getSettingsSchema: (signal?: AbortSignal) =>
588
+ req('/api/config/settings-schema', s.settingsSchema, { signal }),
589
+
590
+ // -- auth: scopes --------------------------------------------------------
591
+ listScopes: (signal?: AbortSignal) => req('/api/auth/scopes', s.authScopes, { signal }),
592
+ addUrlToScope: (body: AddUrlToScopeBody) =>
593
+ req('/api/auth/scopes', s.addUrlToScopeResult, { method: 'POST', body }),
594
+ removeUrlFromScope: (body: { url: string }) =>
595
+ req('/api/auth/scopes/urls', s.removeUrlFromScopeResult, { method: 'DELETE', body }),
596
+ removeScope: (scopeId: string) =>
597
+ req(`/api/auth/scopes/${encodeSegment(scopeId)}`, s.removeScopeResult, {
598
+ method: 'DELETE',
599
+ }),
600
+ // The app's HTTP route catalog with each route's current mapping — the only
601
+ // source of the mapper's unassigned-routes bucket (`mapped: null` entries).
602
+ listAuthRoutes: (signal?: AbortSignal) => req('/api/auth/routes', s.authRoutes, { signal }),
603
+ // The urls pinned to the public marker; pinning/unpinning is the dedicated
604
+ // public-routes writer, never the scope machinery.
605
+ listPublicRoutes: (signal?: AbortSignal) =>
606
+ req('/api/auth/public-routes', s.publicRoutes, { signal }),
607
+ pinRoutePublic: (body: PinRoutePublicBody) =>
608
+ req('/api/auth/public-routes', s.pinPublicResult, { method: 'POST', body }),
609
+ // Unpin a public url. A url that is absent or scope-mapped is a loud 404.
610
+ unpinPublicRoute: (url: string) =>
611
+ req('/api/auth/public-routes', s.unpinPublicResult, { method: 'DELETE', body: { url } }),
612
+
613
+ // -- auth: api keys ------------------------------------------------------
614
+ listTokensPayload: (signal?: AbortSignal) =>
615
+ req('/api/auth/tokens-payload', s.tokensPayload, { signal }),
616
+ createApiKey: (body: ApiKeyBody) =>
617
+ req('/api/auth/api-keys', s.createdApiKey, { method: 'POST', body }),
618
+ editApiKey: (userId: string, body: Omit<ApiKeyBody, 'user_id'>) =>
619
+ req(`/api/auth/api-keys/${encodeSegment(userId)}`, s.editApiKeyResult, {
620
+ method: 'PUT',
621
+ body,
622
+ }),
623
+ revokeApiKey: (userId: string) =>
624
+ req(`/api/auth/api-keys/${encodeSegment(userId)}`, s.revokeApiKeyResult, {
625
+ method: 'DELETE',
626
+ }),
627
+ // Mint a one-time claim link carrying a raw key to another device (the QR
628
+ // onboarding leg). The token rides the URL fragment; the server returns a
629
+ // relative `claim_path` and the raw token ONCE.
630
+ createClaimLink: (body: ClaimLinkBody) =>
631
+ req('/api/auth/claim-links', s.claimLinkCreated, { method: 'POST', body }),
632
+
633
+ // -- auth: the caller's capability projection ----------------------------
634
+ // The derived (path, method) surface + tools/agents the caller can reach
635
+ // right now — the projection the Studio filters its nav and pages on.
636
+ getMe: (signal?: AbortSignal) => req('/api/auth/me', s.meProjection, { signal }),
637
+
638
+ // -- login: the public sign-in aggregator --------------------------------
639
+ // PUBLIC by design: `apiRequest` attaches `x-api-key` only when a token
640
+ // exists, so the unauthenticated call carries no auth header — no transport
641
+ // change needed.
642
+ getLoginMethods: (options?: { signal?: AbortSignal }) =>
643
+ req('/api/login/methods', s.loginMethods, { signal: options?.signal }),
644
+ // Submit a `form` method's field VALUES as a flat top-level JSON body (the
645
+ // server's request models take the declared field names top-level). `path`
646
+ // is re-checked with the same relative-`/api/` guard the renderer uses — an
647
+ // off-origin path is a PROGRAMMING error (loud `Error`), not a login failure.
648
+ // A refused credential becomes an inline `ApiLoginFailedError`.
649
+ submitLoginForm: async (path: string, values: Record<string, string>) => {
650
+ if (!isSafeApiPath(path)) {
651
+ throw new Error(
652
+ `login submit_path must be a relative /api/ path; received ${JSON.stringify(path)}`,
653
+ );
654
+ }
655
+ try {
656
+ return await req(path, s.loginResult, { method: 'POST', body: values });
657
+ } catch (error) {
658
+ return asLoginError(error);
659
+ }
660
+ },
661
+ // Exchange a one-time SSO hand-back code for a session (never a token in the
662
+ // URL). An expired/reused code is a login failure, surfaced inline.
663
+ exchangeSsoCode: async (code: string) => {
664
+ try {
665
+ return await req('/api/login/sso/exchange', s.loginResult, {
666
+ method: 'POST',
667
+ body: { code },
668
+ });
669
+ } catch (error) {
670
+ return asLoginError(error);
671
+ }
672
+ },
673
+ // Exchange a one-time claim token (read from the login URL fragment, never a
674
+ // query param) for a session. PUBLIC. The token is single-use and burns
675
+ // server-side; a used/unknown/expired token answers the uniform 404, which —
676
+ // like the SSO leg — maps to an inline `ApiLoginFailedError`, not a global
677
+ // unauthorized redirect. The caller latches the exchange so it fires once.
678
+ claimLogin: async (body: { token: string }) => {
679
+ try {
680
+ return await req('/api/login/claim', s.loginResult, { method: 'POST', body });
681
+ } catch (error) {
682
+ return asLoginError(error);
683
+ }
684
+ },
685
+ // Whether this deployment can mint API keys locally (the settings key-create
686
+ // UI gates on `mintable`). AUTHED.
687
+ getAuthCapabilities: (signal?: AbortSignal) =>
688
+ req('/api/auth/capabilities', s.authCapabilities, { signal }),
689
+
690
+ // -- auth: session logout ------------------------------------------------
691
+ // The single authed logout dispatcher — revokes the caller's accounts
692
+ // session server-side before the shell clears local state. A plain `sk-` key
693
+ // has nothing to revoke and answers 404 (surfaced as an `ApiError`, quiet at
694
+ // the call site); a 5xx/network failure is a real revoke failure the shell
695
+ // surfaces loudly.
696
+ logout: () => req('/api/auth/logout', s.logoutResult, { method: 'POST' }),
697
+
698
+ // -- auth: policy authoring + versioning ---------------------------------
699
+ // The fail-closed jq guard: compiles (and, with `sample_context`, evaluates) a
700
+ // condition without persisting anything, so a broken condition is caught at
701
+ // author time instead of locking a key out at enforcement. A broken condition
702
+ // is a 400 the transport throws — never a false-positive `ok`.
703
+ validateCondition: (body: ValidateConditionBody) =>
704
+ req('/api/auth/validate-condition', s.validateConditionResult, { method: 'POST', body }),
705
+ // The user's append-only policy version history (each row's `is_current`
706
+ // derived from the active pointer). SECRET-ADJACENT — the body carries the raw
707
+ // condition, so its fixtures are hand-authored.
708
+ listPolicyVersions: (userId: string, signal?: AbortSignal) =>
709
+ req(`/api/auth/api-keys/${encodeSegment(userId)}/policy/versions`, s.policyVersionList, {
710
+ signal,
711
+ }),
712
+ // Re-point the enforced policy to a prior version; returns the re-pointed
713
+ // active version. Enforcement follows on cache invalidation.
714
+ rollbackPolicy: (userId: string, version: number) =>
715
+ req(`/api/auth/api-keys/${encodeSegment(userId)}/policy/rollback`, s.policyRollback, {
716
+ method: 'POST',
717
+ body: { version },
718
+ }),
719
+
720
+ // -- backup --------------------------------------------------------------
721
+ listBackupSections: (signal?: AbortSignal) =>
722
+ req('/api/backup/sections', s.backupSections, { signal }),
723
+ exportBackup: (sections: string[], signal?: AbortSignal): Promise<Blob> =>
724
+ apiDownload(config, '/api/backup/export', { method: 'POST', body: { sections }, signal }),
725
+ importBackup: (body: { document: unknown; sections: string[] }) =>
726
+ req('/api/backup/import', s.backupImportReport, { method: 'POST', body }),
727
+
728
+ // -- schedules -----------------------------------------------------------
729
+ listSchedules: (signal?: AbortSignal) => req('/api/schedules', s.scheduleList, { signal }),
730
+ getServerDateTime: (signal?: AbortSignal) =>
731
+ req('/api/schedules/server-datetime', s.serverDateTime, { signal }),
732
+ addSchedule: (body: {
733
+ tool_name: string;
734
+ tool_kwargs: Record<string, unknown>;
735
+ schedule_kwargs: Record<string, unknown>;
736
+ }) => req('/api/schedules', s.jsonValue, { method: 'POST', body }),
737
+ deleteSchedule: (name: string) =>
738
+ req(`/api/schedules/${encodeSegment(name)}`, s.jsonValue, { method: 'DELETE' }),
739
+
740
+ // -- observability -------------------------------------------------------
741
+ // NB: named `getObservabilityMetrics` (not `getMetrics`) — `getMetrics`
742
+ // already serves the Prometheus `/metrics` text endpoint.
743
+ getObservabilityMetrics: (params: MetricsQuery = {}, signal?: AbortSignal) =>
744
+ req('/api/observability/metrics', s.dashboardMetrics, {
745
+ query: { from: params.from, to: params.to, granularity: params.granularity },
746
+ signal,
747
+ }),
748
+ listRuns: (params: RunsQuery = {}, signal?: AbortSignal) =>
749
+ req('/api/observability/runs', s.runsPage, { query: runsQueryToParams(params), signal }),
750
+ getRunTrace: (traceId: string, signal?: AbortSignal) =>
751
+ req(`/api/observability/runs/${encodeSegment(traceId)}/trace`, s.runTrace, { signal }),
752
+ exportTrace: (traceId: string, signal?: AbortSignal): Promise<Blob> =>
753
+ apiDownload(config, `/api/observability/runs/${encodeSegment(traceId)}/trace/export`, {
754
+ signal,
755
+ }),
756
+ exportRuns: (
757
+ params: RunsQuery & { format: 'csv' | 'json' },
758
+ signal?: AbortSignal,
759
+ ): Promise<Blob> =>
760
+ apiDownload(config, '/api/observability/runs/export', {
761
+ query: { ...runsQueryToParams(params), format: params.format },
762
+ signal,
763
+ }),
764
+
765
+ // -- marketplace ---------------------------------------------------------
766
+ // Browse/search proxy the registry through the app (one origin, one auth);
767
+ // install/uninstall/update mutate the RUNNING app (pip install + manifest
768
+ // patch + reload) and return synchronous receipts.
769
+ searchMarketplace: (query: MarketplaceSearchQuery = {}, signal?: AbortSignal) =>
770
+ req('/api/marketplace/search', s.marketplaceSearchPage, {
771
+ query: {
772
+ q: query.q,
773
+ kind: query.kind,
774
+ category: query.category,
775
+ tags: query.tags,
776
+ namespace: query.namespace,
777
+ tier: query.tier,
778
+ contract: query.contract,
779
+ sort: query.sort,
780
+ page: query.page,
781
+ page_size: query.page_size,
782
+ },
783
+ signal,
784
+ }),
785
+ getMarketplacePlugin: (namespace: string, name: string, signal?: AbortSignal) =>
786
+ req(
787
+ `/api/marketplace/plugins/${encodeSegment(namespace)}/${encodeSegment(name)}`,
788
+ s.marketplacePluginDetail,
789
+ { signal },
790
+ ),
791
+ listMarketplaceCategories: (signal?: AbortSignal) =>
792
+ req('/api/marketplace/categories', s.marketplaceCategories, { signal }),
793
+ listInstalledMarketplacePlugins: (signal?: AbortSignal) =>
794
+ req('/api/marketplace/installed', s.marketplaceInstalled, { signal }),
795
+ installMarketplacePlugin: (body: MarketplaceInstallBody) =>
796
+ req('/api/marketplace/install', s.marketplaceInstallResult, { method: 'POST', body }),
797
+ uninstallMarketplacePlugin: (body: MarketplaceUninstallBody) =>
798
+ req('/api/marketplace/uninstall', s.marketplaceUninstallResult, { method: 'POST', body }),
799
+ updateMarketplacePlugin: (body: MarketplaceInstallBody) =>
800
+ req('/api/marketplace/update', s.marketplaceInstallResult, { method: 'POST', body }),
801
+ getMarketplaceAdvisories: (signal?: AbortSignal) =>
802
+ req('/api/marketplace/advisories', s.marketplaceAdvisories, { signal }),
803
+
804
+ // -- system (plain-text ops endpoints) -----------------------------------
805
+ getHealth: (signal?: AbortSignal) => apiText(config, '/health', { signal }),
806
+ getMetrics: (signal?: AbortSignal) => apiText(config, '/metrics', { signal }),
807
+
808
+ // The pluggable-kind status table (`GET /api/system/kinds`) — a JSON `{data}`
809
+ // envelope, one row per kind with its active/default/off state.
810
+ getSystemKinds: (signal?: AbortSignal) =>
811
+ req('/api/system/kinds', s.kindStatusList, { signal }),
812
+
813
+ /**
814
+ * Open the authed interactions SSE stream. The caller drives reconnect +
815
+ * backlog-replay dedup. Returns the raw frame iterator; the interactions
816
+ * feature maps frames to typed events.
817
+ */
818
+ streamInteractions: async (signal?: AbortSignal) => {
819
+ const doFetch = config.fetch ?? globalThis.fetch;
820
+ const token = config.getToken();
821
+ const headers: Record<string, string> = { accept: 'text/event-stream' };
822
+ if (token) headers['x-api-key'] = token;
823
+ const response = await doFetch(`${config.baseUrl ?? ''}/api/interactions/stream`, {
824
+ headers,
825
+ signal,
826
+ });
827
+ if (response.status === 401) throw new ApiUnauthorizedError();
828
+ // A non-ok stream open (5xx/4xx) still carries a body, which would parse to
829
+ // zero frames and look like a silently-empty stream — surface it loudly so
830
+ // the caller shows an error instead of hanging on a reconnect loop.
831
+ if (!response.ok) throw new ApiError(response.statusText || 'stream failed', response.status);
832
+ return readSseFrames(response, signal);
833
+ },
834
+ } as const;
835
+ }
836
+
837
+ export type ApiClient = ReturnType<typeof createApiClient>;