@artieeez/cf-client 0.0.0-stage → 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.
- package/README.md +4 -2
- package/dist/index.d.ts +339 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +356 -0
- package/dist/index.js.map +1 -0
- package/dist/schema.gen.d.ts +3805 -0
- package/dist/schema.gen.d.ts.map +1 -0
- package/dist/schema.gen.js +2 -0
- package/dist/schema.gen.js.map +1 -0
- package/package.json +32 -3
- package/src/index.ts +515 -0
- package/src/schema.gen.ts +3805 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
import type { CfEvent, ErrorBody, ErrorCode, Manifest, Me, Provenance, Role, WorkerEventType, WorkerMode } from '@artieeez/cf-core';
|
|
2
|
+
import createFetch from 'openapi-fetch';
|
|
3
|
+
import type { components, paths } from './schema.gen.ts';
|
|
4
|
+
|
|
5
|
+
export class ApiError extends Error {
|
|
6
|
+
readonly status: number;
|
|
7
|
+
readonly code: ErrorCode;
|
|
8
|
+
/** `agent_account_unavailable`: the earliest cooldown end as ISO, or null (agent-accounts) */
|
|
9
|
+
readonly retryAt: string | null | undefined;
|
|
10
|
+
/** `forbidden`: the role the route needs (oidc-login AC 16) */
|
|
11
|
+
readonly role: Role | undefined;
|
|
12
|
+
constructor(status: number, code: ErrorCode, message: string, retryAt?: string | null, role?: Role) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'ApiError';
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.retryAt = retryAt;
|
|
18
|
+
this.role = role;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The server could not be reached (refused, reset, DNS). */
|
|
23
|
+
export class ConnectionError extends Error {
|
|
24
|
+
readonly url: string;
|
|
25
|
+
constructor(url: string, cause: unknown) {
|
|
26
|
+
super(`cannot reach server at ${url}`, { cause });
|
|
27
|
+
this.name = 'ConnectionError';
|
|
28
|
+
this.url = url;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The answers' types come from the server's OpenAPI document (AD-046): `pnpm gen:api`.
|
|
33
|
+
type S = components['schemas'];
|
|
34
|
+
export type RunInfo = S['RunInfo_Output'];
|
|
35
|
+
/** A run's link (AD-085). */
|
|
36
|
+
export type RunLink = S['RunLink_Output'];
|
|
37
|
+
export type InterventionInfo = S['InterventionInfo_Output'];
|
|
38
|
+
export type AnswerResult = S['AnswerResultResponse_Output'];
|
|
39
|
+
/** What pause, resume and stop answer. */
|
|
40
|
+
export type RunControl = S['RunControlResponse_Output'];
|
|
41
|
+
export type WorkflowInfo = S['WorkflowInfo_Output'];
|
|
42
|
+
/** What a factory or workflow pause or resume answers: the scope's state after it (AD-088). */
|
|
43
|
+
export type ScopeControl = S['ScopeControl_Output'];
|
|
44
|
+
/** The factory pause and each paused workflow (`GET /api/controls`, AD-088). */
|
|
45
|
+
export type Controls = S['Controls_Output'];
|
|
46
|
+
/** A workflow's slots and settings for its latest version, with where each value comes from (AD-087). */
|
|
47
|
+
export type WorkflowConfigInfo = S['WorkflowConfigInfo_Output'];
|
|
48
|
+
/** What `updateWorkflowConfig` sets: each named slot or setting; `null` clears the dashboard's value. */
|
|
49
|
+
export type WorkflowConfigPatch = S['UpdateWorkflowConfigRequest'];
|
|
50
|
+
/** One process of a worker: a session registered with its token (worker-tokens door 4). */
|
|
51
|
+
export type WorkerReplica = Omit<S['WorkerReplica_Output'], 'provenance'> & {
|
|
52
|
+
provenance: Provenance | null;
|
|
53
|
+
};
|
|
54
|
+
/** One worker as `GET /api/workers` lists it: a token and its replicas (AD-063). */
|
|
55
|
+
export type WorkerInfo = Omit<S['WorkerInfo_Output'], 'replicas'> & { replicas: WorkerReplica[] };
|
|
56
|
+
/** What `createWorker` answers: the worker and its token, shown once (worker-tokens door 2). */
|
|
57
|
+
export type CreatedWorker = S['CreatedWorkerResponse_Output'];
|
|
58
|
+
export type NewWorker = S['CreateWorkerRequest'];
|
|
59
|
+
/** One plugin instance and its last check on the server (`GET /api/plugins`, health-ready door 8). */
|
|
60
|
+
export type PluginInfo = S['PluginInfo_Output'];
|
|
61
|
+
/** One plugin this server ships and its instances (`GET /api/integrations`, integration-setup S1). */
|
|
62
|
+
export type IntegrationInfo = S['IntegrationInfo_Output'];
|
|
63
|
+
/** The whole catalog: each plugin, and whether `CF_PUBLIC_URL` is set (GitHub setup needs it, integration-setup AC 14). */
|
|
64
|
+
export type IntegrationCatalog = S['IntegrationListResponse_Output'];
|
|
65
|
+
/** One plugin instance as Integrations lists it: env or dashboard, its config, secret fingerprints and webhook URL. */
|
|
66
|
+
export type IntegrationInstance = S['IntegrationInstanceInfo_Output'];
|
|
67
|
+
/** "Create on GitHub": the manifest and GitHub's new-App page to post it to (AC 7). */
|
|
68
|
+
export type GithubManifestSetup = S['StartGithubSetupResponse_Output'];
|
|
69
|
+
export type NewGithubManifest = S['StartGithubSetupRequest'];
|
|
70
|
+
/** An instance from credentials: an existing GitHub App, or a Linear key and team (AC 15, 18). */
|
|
71
|
+
export type NewIntegrationInstance = S['CreateInstanceRequest'];
|
|
72
|
+
export type LinearTeam = S['LinearTeam_Output'];
|
|
73
|
+
export type InstallationRepository = S['InstallationRepository_Output'];
|
|
74
|
+
/** One entry of an instance's log (`GET /api/integrations/instances/:instance/log`, ART-238): metadata only, never a body. */
|
|
75
|
+
export type InstanceLogEntry = S['InstanceLogEntry_Output'];
|
|
76
|
+
/** A page of an instance log: newest first, and the `before` of the next page or null. */
|
|
77
|
+
export type InstanceLogPage = S['InstanceLogResponse_Output'];
|
|
78
|
+
/** The filters and page of an instance log; `since` and `until` are ISO times. */
|
|
79
|
+
export interface InstanceLogQuery {
|
|
80
|
+
kind?: InstanceLogEntry['kind'][];
|
|
81
|
+
status?: InstanceLogEntry['status'];
|
|
82
|
+
since?: string;
|
|
83
|
+
until?: string;
|
|
84
|
+
before?: string;
|
|
85
|
+
limit?: number;
|
|
86
|
+
}
|
|
87
|
+
/** A run's status as `POST /w/workspaces/check` answers it: `missing` when the server has no such run. */
|
|
88
|
+
export type WorkspaceStatus = S['CheckWorkspacesResponse_Output']['statuses'][string];
|
|
89
|
+
/** What `POST /w/workspaces/check` answers: each run's status, and its ISO end time or null (ART-226). */
|
|
90
|
+
export type WorkspaceCheck = S['CheckWorkspacesResponse_Output'];
|
|
91
|
+
/** One run as `POST /w/drain` answers it: its status and how far its pause has got (ART-234). */
|
|
92
|
+
export type DrainedRun = S['DrainSessionResponse_Output']['runs'][number];
|
|
93
|
+
/** One run folder a worker reports (`POST /w/workspaces/report`, ART-226). */
|
|
94
|
+
export type WorkspaceFolder = S['WorkspaceFolder'];
|
|
95
|
+
/** One workflow version's readiness on a worker, as `POST /w/health` takes it (health-ready door 1). */
|
|
96
|
+
export interface WorkflowHealth {
|
|
97
|
+
workflow: string;
|
|
98
|
+
version: string;
|
|
99
|
+
ready: boolean;
|
|
100
|
+
problems: string[];
|
|
101
|
+
}
|
|
102
|
+
/** One registered version of a workflow, with its manifest as registered. */
|
|
103
|
+
export type WorkflowVersionInfo = Omit<S['WorkflowVersionInfoResponse_Output'], 'manifest'> & { manifest: Manifest };
|
|
104
|
+
export type LeasedUnit = S['LeasedUnitResponse_Output'];
|
|
105
|
+
/** One resolved `about` ref (waivers door 3). */
|
|
106
|
+
export type AboutEntry = NonNullable<InterventionInfo['about']>[number];
|
|
107
|
+
/** What a replica is doing, from its last call and its leases (workers-panel door 3). */
|
|
108
|
+
export type WorkerStatus = WorkerReplica['status'];
|
|
109
|
+
/** One artifact a run's units stored, oldest first (`GET /api/runs/:id/artifacts`). */
|
|
110
|
+
export type RunArtifact = S['RunArtifactListResponse_Output']['artifacts'][number];
|
|
111
|
+
/** One agent account as `GET /api/agent-accounts` lists it, never with its secret (agent-accounts door 1). */
|
|
112
|
+
export type AgentAccountView = S['AgentAccountView_Output'];
|
|
113
|
+
export type NewAgentAccount = S['CreateAccountRequest'];
|
|
114
|
+
export type AgentAccountPatch = S['UpdateAccountRequest'];
|
|
115
|
+
/** An account granted for one agent session (agent-accounts door 4). */
|
|
116
|
+
export type AccountGrantInfo = S['AcquireAccountResponse_Output'];
|
|
117
|
+
export type AccountRelease = S['ReleaseAccountRequest'];
|
|
118
|
+
/** Where a manual dispatch came from (dashboard-dispatch door 4). */
|
|
119
|
+
export type DispatchVia = NonNullable<S['DispatchRunRequest']['via']>;
|
|
120
|
+
|
|
121
|
+
export interface InterventionFilter {
|
|
122
|
+
run?: string;
|
|
123
|
+
/** `open` when left out */
|
|
124
|
+
status?: 'open' | 'answered' | 'voided' | 'all';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface RunFilter {
|
|
128
|
+
workflow?: string;
|
|
129
|
+
status?: string;
|
|
130
|
+
limit?: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface WorkerEvent {
|
|
134
|
+
/** a worker event type, or a domain type the workflow declares (artifact-store door 5) */
|
|
135
|
+
type: WorkerEventType | `${string}.${string}`;
|
|
136
|
+
time: string;
|
|
137
|
+
data: Record<string, unknown>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export type CompleteBody =
|
|
141
|
+
| { outcome: string; output?: unknown; pause?: { reason: string }; events: WorkerEvent[] }
|
|
142
|
+
/** `ctx.pause` in `beforeUnit`: the unit goes back to the queue and the run pauses (boss-sdd-gaps door 7) */
|
|
143
|
+
| { yield: { reason: string }; events: WorkerEvent[] }
|
|
144
|
+
| { error: { message: string; kind?: 'hook'; hook?: 'preInit' | 'beforeUnit' }; events: WorkerEvent[] };
|
|
145
|
+
|
|
146
|
+
/** The server `pnpm dev:server` starts in the main checkout; a worktree's comes in `CF_SERVER`. */
|
|
147
|
+
export const DEFAULT_SERVER_URL = 'http://127.0.0.1:4400';
|
|
148
|
+
|
|
149
|
+
export interface ClientOptions {
|
|
150
|
+
baseUrl: string;
|
|
151
|
+
fetch?: typeof fetch;
|
|
152
|
+
/** a CLI token (`cfp_…`, oidc-login): sent as the bearer of every call that sets no `authorization` of its own */
|
|
153
|
+
token?: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** What `POST /auth/cli/token` answers (oidc-login door 3). */
|
|
157
|
+
export interface CliTokenInfo {
|
|
158
|
+
token: string;
|
|
159
|
+
expiresAt: string;
|
|
160
|
+
user: { email: string; name: string; role: Role };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** An `ApiError` from a refusal's body, or `HTTP <status>` when the body is not one. */
|
|
164
|
+
function apiError(status: number, body: unknown): ApiError {
|
|
165
|
+
const error = (body as Partial<ErrorBody> | null)?.error;
|
|
166
|
+
return new ApiError(status, error?.code ?? 'code_factory/not_found', error?.message ?? `HTTP ${status}`, error?.retryAt, error?.role);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function createClient(opts: ClientOptions) {
|
|
170
|
+
const base = opts.baseUrl.replace(/\/$/, '');
|
|
171
|
+
const f = opts.fetch ?? fetch;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Every request goes through here: an unreachable server and a refusal both throw. The token is
|
|
175
|
+
* the bearer unless the call brings its own (a worker's session); a write carries `x-cf-csrf`,
|
|
176
|
+
* which a signed-in browser needs and a cross-site form cannot send (oidc-login door 4).
|
|
177
|
+
*/
|
|
178
|
+
async function send(url: string, init: RequestInit = {}): Promise<Response> {
|
|
179
|
+
const headers: Record<string, string> = init.headers instanceof Headers ? Object.fromEntries(init.headers) : { ...(init.headers as Record<string, string> | undefined) };
|
|
180
|
+
const has = (name: string) => Object.keys(headers).some((k) => k.toLowerCase() === name);
|
|
181
|
+
if (opts.token !== undefined && !has('authorization')) headers['authorization'] = `Bearer ${opts.token}`;
|
|
182
|
+
const method = (init.method ?? 'GET').toUpperCase();
|
|
183
|
+
if (method !== 'GET' && method !== 'HEAD') headers['x-cf-csrf'] = '1';
|
|
184
|
+
let res: Response;
|
|
185
|
+
try {
|
|
186
|
+
res = await f(url, { ...init, headers });
|
|
187
|
+
} catch (err) {
|
|
188
|
+
if (init.signal?.aborted) throw err;
|
|
189
|
+
throw new ConnectionError(base, err);
|
|
190
|
+
}
|
|
191
|
+
if (res.status >= 400) throw apiError(res.status, await res.json().catch(() => null));
|
|
192
|
+
return res;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// openapi-fetch hands a Request; the caller's fetch keeps taking (url, init)
|
|
196
|
+
const api = createFetch<paths>({
|
|
197
|
+
baseUrl: base,
|
|
198
|
+
fetch: async (req) => {
|
|
199
|
+
const body = req.method === 'GET' || req.method === 'HEAD' ? '' : await req.text();
|
|
200
|
+
const headers = Object.fromEntries(req.headers);
|
|
201
|
+
return send(req.url, { method: req.method, headers, signal: req.signal, ...(body !== '' ? { body } : {}) });
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
/** The answer's body; a refusal has already thrown in `send`. */
|
|
206
|
+
const ok = async <T>(call: Promise<{ data?: T }>): Promise<T> => (await call).data as T;
|
|
207
|
+
const bearer = (token: string) => ({ authorization: `Bearer ${token}` });
|
|
208
|
+
const leased = (session: string, leaseToken: string) => ({ ...bearer(session), 'x-cf-lease': leaseToken });
|
|
209
|
+
const path = (id: string) => ({ params: { path: { id } } });
|
|
210
|
+
const reasonBody = (reason?: string) => (reason === undefined ? {} : { reason });
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
baseUrl: base,
|
|
214
|
+
|
|
215
|
+
// people's sign-in (oidc-login)
|
|
216
|
+
/** Who is signed in; with auth off, the local admin. A 401 throws. */
|
|
217
|
+
me: async (): Promise<Me> => (await send(`${base}/auth/me`)).json() as Promise<Me>,
|
|
218
|
+
/** Ends this client's session: the browser cookie or the CLI token. */
|
|
219
|
+
async logout(): Promise<void> {
|
|
220
|
+
await send(`${base}/auth/logout`, { method: 'POST' });
|
|
221
|
+
},
|
|
222
|
+
/** `cf login`'s exchange of the browser's one-time code and the PKCE verifier for a CLI token. */
|
|
223
|
+
async cliToken(code: string, verifier: string): Promise<CliTokenInfo> {
|
|
224
|
+
const res = await send(`${base}/auth/cli/token`, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: { 'content-type': 'application/json' },
|
|
227
|
+
body: JSON.stringify({ code, verifier }),
|
|
228
|
+
});
|
|
229
|
+
return (await res.json()) as CliTokenInfo;
|
|
230
|
+
},
|
|
231
|
+
|
|
232
|
+
// control API
|
|
233
|
+
dispatch(workflow: string, input: unknown = {}, o?: { via?: DispatchVia }): Promise<{ runId: string }> {
|
|
234
|
+
return ok(api.POST('/api/runs', { body: o?.via !== undefined ? { workflow, input, via: o.via } : { workflow, input } }));
|
|
235
|
+
},
|
|
236
|
+
getRun: (id: string): Promise<RunInfo> => ok(api.GET('/api/runs/{id}', path(id))),
|
|
237
|
+
async listRuns(filter: RunFilter = {}): Promise<RunInfo[]> {
|
|
238
|
+
const { limit, ...rest } = filter;
|
|
239
|
+
const query = { ...rest, ...(limit !== undefined ? { limit: String(limit) } : {}) } as { limit?: string };
|
|
240
|
+
return (await ok(api.GET('/api/runs', { params: { query } }))).runs;
|
|
241
|
+
},
|
|
242
|
+
listWorkflows: async (): Promise<WorkflowInfo[]> => (await ok(api.GET('/api/workflows'))).workflows,
|
|
243
|
+
async getWorkflowVersion(id: string, version: string): Promise<WorkflowVersionInfo> {
|
|
244
|
+
const params = { path: { id, version } };
|
|
245
|
+
return (await ok(api.GET('/api/workflows/{id}/versions/{version}', { params }))) as WorkflowVersionInfo;
|
|
246
|
+
},
|
|
247
|
+
/** The latest version's slots and settings, their values and sources (`GET /api/workflows/:id/config`). */
|
|
248
|
+
getWorkflowConfig: (id: string): Promise<WorkflowConfigInfo> => ok(api.GET('/api/workflows/{id}/config', path(id))),
|
|
249
|
+
/** Sets or clears dashboard bindings and settings (admin, `PUT /api/workflows/:id/config`); answers the config. */
|
|
250
|
+
updateWorkflowConfig(id: string, body: WorkflowConfigPatch): Promise<WorkflowConfigInfo> {
|
|
251
|
+
return ok(api.PUT('/api/workflows/{id}/config', { ...path(id), body }));
|
|
252
|
+
},
|
|
253
|
+
pauseRun(id: string, reason?: string): Promise<RunControl> {
|
|
254
|
+
return ok(api.POST('/api/runs/{id}/pause', { ...path(id), body: reasonBody(reason) }));
|
|
255
|
+
},
|
|
256
|
+
resumeRun: (id: string): Promise<RunControl> => ok(api.POST('/api/runs/{id}/resume', path(id))),
|
|
257
|
+
stopRun(id: string, reason?: string): Promise<RunControl> {
|
|
258
|
+
return ok(api.POST('/api/runs/{id}/stop', { ...path(id), body: reasonBody(reason) }));
|
|
259
|
+
},
|
|
260
|
+
async listInterventions(filter: InterventionFilter = {}): Promise<InterventionInfo[]> {
|
|
261
|
+
return (await ok(api.GET('/api/interventions', { params: { query: filter } }))).interventions;
|
|
262
|
+
},
|
|
263
|
+
getIntervention: (id: string): Promise<InterventionInfo> => ok(api.GET('/api/interventions/{id}', path(id))),
|
|
264
|
+
answerIntervention(id: string, outcome: string, data?: Record<string, unknown>): Promise<AnswerResult> {
|
|
265
|
+
const body = data === undefined ? { outcome } : { outcome, data };
|
|
266
|
+
return ok(api.POST('/api/interventions/{id}/answer', { ...path(id), body }));
|
|
267
|
+
},
|
|
268
|
+
async readArtifact(runId: string, sha256: string): Promise<string> {
|
|
269
|
+
return (await send(`${base}/api/runs/${encodeURIComponent(runId)}/artifacts/${encodeURIComponent(sha256)}`)).text();
|
|
270
|
+
},
|
|
271
|
+
async listArtifacts(runId: string): Promise<RunArtifact[]> {
|
|
272
|
+
return (await ok(api.GET('/api/runs/{id}/artifacts', path(runId)))).artifacts;
|
|
273
|
+
},
|
|
274
|
+
/** An artifact's bytes, as stored. */
|
|
275
|
+
async downloadArtifact(runId: string, sha256: string): Promise<Uint8Array> {
|
|
276
|
+
const res = await send(`${base}/api/runs/${encodeURIComponent(runId)}/artifacts/${encodeURIComponent(sha256)}`);
|
|
277
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
278
|
+
},
|
|
279
|
+
async events(id: string, after = 0): Promise<CfEvent[]> {
|
|
280
|
+
const params = { path: { id }, query: { after: String(after) } };
|
|
281
|
+
return (await ok(api.GET('/api/runs/{id}/events', { params }))).events;
|
|
282
|
+
},
|
|
283
|
+
/** Every event after `after`, then live ones; ends after `run.completed` or when the server closes. */
|
|
284
|
+
async *stream(id: string, after = 0, signal?: AbortSignal): AsyncGenerator<CfEvent> {
|
|
285
|
+
const res = await send(`${base}/api/runs/${encodeURIComponent(id)}/events/stream?after=${after}`, {
|
|
286
|
+
headers: { accept: 'text/event-stream' },
|
|
287
|
+
...(signal ? { signal } : {}),
|
|
288
|
+
});
|
|
289
|
+
if (res.body === null) return;
|
|
290
|
+
const decoder = new TextDecoder();
|
|
291
|
+
let buffer = '';
|
|
292
|
+
// a reader, not `for await` over the body: browsers without async-iterable streams use it too
|
|
293
|
+
const reader = res.body.getReader();
|
|
294
|
+
for (;;) {
|
|
295
|
+
const { done, value: chunk } = await reader.read();
|
|
296
|
+
if (done) break;
|
|
297
|
+
buffer += decoder.decode(chunk as Uint8Array, { stream: true });
|
|
298
|
+
let cut: number;
|
|
299
|
+
while ((cut = buffer.indexOf('\n\n')) >= 0) {
|
|
300
|
+
const frame = buffer.slice(0, cut);
|
|
301
|
+
buffer = buffer.slice(cut + 2);
|
|
302
|
+
const data = frame
|
|
303
|
+
.split('\n')
|
|
304
|
+
.filter((l) => l.startsWith('data:'))
|
|
305
|
+
.map((l) => l.slice(5).trimStart())
|
|
306
|
+
.join('\n');
|
|
307
|
+
if (data !== '') yield JSON.parse(data) as CfEvent;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
},
|
|
311
|
+
/** The factory and workflow pauses (AD-088); a run's own pause is `pauseRun`. */
|
|
312
|
+
controls: {
|
|
313
|
+
list: (): Promise<Controls> => ok(api.GET('/api/controls')),
|
|
314
|
+
},
|
|
315
|
+
factory: {
|
|
316
|
+
/** Holds every queued unit of every running run until resume (operator, `POST /api/factory/pause`). */
|
|
317
|
+
pause: (reason?: string): Promise<ScopeControl> => ok(api.POST('/api/factory/pause', { body: reasonBody(reason) })),
|
|
318
|
+
resume: (): Promise<ScopeControl> => ok(api.POST('/api/factory/resume')),
|
|
319
|
+
},
|
|
320
|
+
workflows: {
|
|
321
|
+
/** Holds the queued units of every version of the workflow until resume (operator). */
|
|
322
|
+
pause(id: string, reason?: string): Promise<ScopeControl> {
|
|
323
|
+
return ok(api.POST('/api/workflows/{id}/pause', { ...path(id), body: reasonBody(reason) }));
|
|
324
|
+
},
|
|
325
|
+
resume: (id: string): Promise<ScopeControl> => ok(api.POST('/api/workflows/{id}/resume', path(id))),
|
|
326
|
+
},
|
|
327
|
+
workers: {
|
|
328
|
+
/** Every unrevoked worker with its replicas, newest seen first (`GET /api/workers`). */
|
|
329
|
+
list: async (): Promise<WorkerInfo[]> => (await ok(api.GET('/api/workers'))).workers as WorkerInfo[],
|
|
330
|
+
/** Asks the worker's online sessions on `host` to delete these run folders on their next round (admin, ART-226). */
|
|
331
|
+
async deleteWorkspaces(id: string, host: string | null, runs: string[]): Promise<void> {
|
|
332
|
+
await ok(api.POST('/api/workers/{id}/workspaces/delete', { params: { path: { id } }, body: { host, runs } }));
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
plugins: {
|
|
336
|
+
/** Each plugin instance with its last check on the server (`GET /api/plugins`). */
|
|
337
|
+
list: async (): Promise<PluginInfo[]> => (await ok(api.GET('/api/plugins'))).plugins,
|
|
338
|
+
},
|
|
339
|
+
integrations: {
|
|
340
|
+
/** Each plugin this server ships with its instances, their last check and bound workflows (`GET /api/integrations`). */
|
|
341
|
+
list: async (): Promise<IntegrationInfo[]> => (await ok(api.GET('/api/integrations'))).integrations,
|
|
342
|
+
/** The catalog and whether `CF_PUBLIC_URL` is set (`GET /api/integrations`). */
|
|
343
|
+
catalog: (): Promise<IntegrationCatalog> => ok(api.GET('/api/integrations')),
|
|
344
|
+
/** "Create on GitHub" (`POST /api/integrations/github/manifest`): the browser then posts `manifest` to `action`. */
|
|
345
|
+
startGithub: (body: NewGithubManifest): Promise<GithubManifestSetup> => ok(api.POST('/api/integrations/github/manifest', { body })),
|
|
346
|
+
/** An instance from credentials (`POST /api/integrations`). */
|
|
347
|
+
create: (body: NewIntegrationInstance): Promise<IntegrationInstance> => ok(api.POST('/api/integrations', { body })),
|
|
348
|
+
/** The teams a Linear key sees (`POST /api/integrations/linear/teams`). */
|
|
349
|
+
linearTeams: async (apiKey: string): Promise<LinearTeam[]> => (await ok(api.POST('/api/integrations/linear/teams', { body: { apiKey } }))).teams,
|
|
350
|
+
/** The repositories a GitHub instance's installation reaches (`GET /api/integrations/:name/github/repositories`). */
|
|
351
|
+
githubRepositories: async (name: string): Promise<InstallationRepository[]> =>
|
|
352
|
+
(await ok(api.GET('/api/integrations/{name}/github/repositories', { params: { path: { name } } }))).repositories,
|
|
353
|
+
/** Which repos a GitHub instance covers (`PATCH /api/integrations/:name`). */
|
|
354
|
+
updateRepos: (name: string, repos: string[]): Promise<IntegrationInstance> => ok(api.PATCH('/api/integrations/{name}', { params: { path: { name } }, body: { repos } })),
|
|
355
|
+
/** Removes a dashboard instance (`DELETE /api/integrations/:name`): what could not be cleaned up in `warnings`. */
|
|
356
|
+
remove: (name: string): Promise<{ removed: string; warnings: string[] }> => ok(api.DELETE('/api/integrations/{name}', { params: { path: { name } } })),
|
|
357
|
+
/** What passed through one instance, newest first (`GET /api/integrations/instances/:instance/log`). */
|
|
358
|
+
log(instance: string, q: InstanceLogQuery = {}): Promise<InstanceLogPage> {
|
|
359
|
+
const { limit, kind, ...rest } = q;
|
|
360
|
+
const query = { ...rest, ...(kind !== undefined && kind.length > 0 ? { kind } : {}), ...(limit !== undefined ? { limit: String(limit) } : {}) };
|
|
361
|
+
return ok(api.GET('/api/integrations/instances/{instance}/log', { params: { path: { instance }, query } }));
|
|
362
|
+
},
|
|
363
|
+
},
|
|
364
|
+
/** Coding agent accounts the server holds (agent-accounts door 1); a secret is write-only. */
|
|
365
|
+
agentAccounts: {
|
|
366
|
+
list: async (): Promise<AgentAccountView[]> => (await ok(api.GET('/api/agent-accounts'))).accounts,
|
|
367
|
+
create: (body: NewAgentAccount): Promise<AgentAccountView> => ok(api.POST('/api/agent-accounts', { body })),
|
|
368
|
+
update(name: string, body: AgentAccountPatch): Promise<AgentAccountView> {
|
|
369
|
+
return ok(api.PATCH('/api/agent-accounts/{name}', { params: { path: { name } }, body }));
|
|
370
|
+
},
|
|
371
|
+
async remove(name: string): Promise<void> {
|
|
372
|
+
await api.DELETE('/api/agent-accounts/{name}', { params: { path: { name } } });
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
/** A worker token any number of processes can use (AD-063); `workflows` left out: any workflow. */
|
|
376
|
+
createWorker(body: NewWorker): Promise<CreatedWorker> {
|
|
377
|
+
return ok(api.POST('/api/workers', { body }));
|
|
378
|
+
},
|
|
379
|
+
/** Its next register and every call of a session it holds answer 401. */
|
|
380
|
+
async revokeWorker(id: string): Promise<void> {
|
|
381
|
+
await ok(api.POST('/api/workers/{id}/revoke', { params: { path: { id } } }));
|
|
382
|
+
},
|
|
383
|
+
|
|
384
|
+
// worker API
|
|
385
|
+
register(
|
|
386
|
+
credential: string,
|
|
387
|
+
manifests: Manifest[],
|
|
388
|
+
provenance?: Provenance,
|
|
389
|
+
/** units the process runs at once and its tenancy (multi-slot-workers doors 1, 4); server defaults 1, multi */
|
|
390
|
+
capacity: { slots?: number; mode?: WorkerMode } = {},
|
|
391
|
+
): Promise<{ workerId: string; sessionToken: string; expiresAt: string }> {
|
|
392
|
+
const body = {
|
|
393
|
+
manifests,
|
|
394
|
+
...(provenance === undefined ? {} : { provenance }),
|
|
395
|
+
...(capacity.slots === undefined ? {} : { slots: capacity.slots }),
|
|
396
|
+
...(capacity.mode === undefined ? {} : { mode: capacity.mode }),
|
|
397
|
+
};
|
|
398
|
+
return ok(api.POST('/w/register', { body, headers: bearer(credential) }));
|
|
399
|
+
},
|
|
400
|
+
/** The session's readiness per workflow version (health-ready door 1): every version once. */
|
|
401
|
+
async reportHealth(session: string, workflows: WorkflowHealth[]): Promise<void> {
|
|
402
|
+
await api.POST('/w/health', { body: { workflows }, headers: bearer(session) });
|
|
403
|
+
},
|
|
404
|
+
/** null when the long-poll ended with no work (204). */
|
|
405
|
+
async lease(session: string, signal?: AbortSignal): Promise<LeasedUnit | null> {
|
|
406
|
+
const { data, response } = await api.POST('/w/lease', { headers: bearer(session), ...(signal ? { signal } : {}) });
|
|
407
|
+
return response.status === 204 ? null : (data as LeasedUnit);
|
|
408
|
+
},
|
|
409
|
+
heartbeat(session: string, unitId: string, leaseToken: string, events: WorkerEvent[]): Promise<{ leaseExpiresAt: string }> {
|
|
410
|
+
const params = { path: { id: unitId } };
|
|
411
|
+
return ok(api.POST('/w/units/{id}/heartbeat', { params, body: { events }, headers: leased(session, leaseToken) }));
|
|
412
|
+
},
|
|
413
|
+
async complete(session: string, unitId: string, leaseToken: string, body: CompleteBody): Promise<void> {
|
|
414
|
+
const params = { path: { id: unitId } };
|
|
415
|
+
await api.POST('/w/units/{id}/complete', { params, body, headers: leased(session, leaseToken) });
|
|
416
|
+
},
|
|
417
|
+
/** The worker artifact routes (artifact-store door 2), authorised by the session and a unit's lease. */
|
|
418
|
+
worker: {
|
|
419
|
+
/**
|
|
420
|
+
* The session got a stop and drains (ART-234, AD-090): the server pauses `by: 'shutdown'` the
|
|
421
|
+
* runs it is finishing a unit of, and answers each run's state; 1 to WORKER_SLOTS_MAX run ids.
|
|
422
|
+
*/
|
|
423
|
+
async drain(session: string, runs: string[]): Promise<DrainedRun[]> {
|
|
424
|
+
return (await ok(api.POST('/w/drain', { body: { runs }, headers: bearer(session) }))).runs;
|
|
425
|
+
},
|
|
426
|
+
workspaces: {
|
|
427
|
+
/** Each run's status and end time, for the worker's run folders (run-affinity door 5): 1 to 500 run ids. */
|
|
428
|
+
async check(session: string, runs: string[]): Promise<WorkspaceCheck> {
|
|
429
|
+
return ok(api.POST('/w/workspaces/check', { body: { runs }, headers: bearer(session) }));
|
|
430
|
+
},
|
|
431
|
+
/** The run folders left after a collect round; answers the run ids an admin asked to delete (ART-226). */
|
|
432
|
+
async report(session: string, folders: WorkspaceFolder[]): Promise<{ delete: string[] }> {
|
|
433
|
+
return ok(api.POST('/w/workspaces/report', { body: { folders }, headers: bearer(session) }));
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
units: {
|
|
437
|
+
/** One plugin action the server runs for the unit's lease holder (AD-048): one request, never retried. */
|
|
438
|
+
async action(
|
|
439
|
+
session: string,
|
|
440
|
+
unitId: string,
|
|
441
|
+
leaseToken: string,
|
|
442
|
+
body: { slot: string; action: string; args: unknown[] },
|
|
443
|
+
): Promise<unknown> {
|
|
444
|
+
const params = { path: { id: unitId } };
|
|
445
|
+
const r = await ok(api.POST('/w/units/{id}/actions', { params, body, headers: leased(session, leaseToken) }));
|
|
446
|
+
return r.result;
|
|
447
|
+
},
|
|
448
|
+
/** One more key for the unit's run (github-pr-review door 4, AD-074); 409 `key_taken` throws `ApiError`. */
|
|
449
|
+
async claimKey(session: string, unitId: string, leaseToken: string, key: string): Promise<{ key: string; claimed: boolean }> {
|
|
450
|
+
const params = { path: { id: unitId } };
|
|
451
|
+
return ok(api.POST('/w/units/{id}/keys', { params, body: { key }, headers: leased(session, leaseToken) }));
|
|
452
|
+
},
|
|
453
|
+
/**
|
|
454
|
+
* The title and links of the unit's run (AD-085): `title` replaces the run's, `links` are added
|
|
455
|
+
* but for urls it holds; answers the run's title and links after the call and the links it added.
|
|
456
|
+
*/
|
|
457
|
+
async setRunMeta(
|
|
458
|
+
session: string,
|
|
459
|
+
unitId: string,
|
|
460
|
+
leaseToken: string,
|
|
461
|
+
body: { title?: string; links?: RunLink[] },
|
|
462
|
+
): Promise<{ title: string | null; links: RunLink[]; added: RunLink[] }> {
|
|
463
|
+
const params = { path: { id: unitId } };
|
|
464
|
+
return ok(api.POST('/w/units/{id}/run', { params, body, headers: leased(session, leaseToken) }));
|
|
465
|
+
},
|
|
466
|
+
/**
|
|
467
|
+
* An agent account for one session (agent-accounts door 4); null on 204 (none scoped: the
|
|
468
|
+
* worker's own login). A 503 throws `ApiError` with `retryAt`.
|
|
469
|
+
*/
|
|
470
|
+
async acquireAccount(
|
|
471
|
+
session: string,
|
|
472
|
+
unitId: string,
|
|
473
|
+
leaseToken: string,
|
|
474
|
+
body: { harness: 'claude-code'; model?: string; exclude?: string[] },
|
|
475
|
+
): Promise<AccountGrantInfo | null> {
|
|
476
|
+
const params = { path: { id: unitId } };
|
|
477
|
+
const { data, response } = await api.POST('/w/units/{id}/agent-accounts', { params, body, headers: leased(session, leaseToken) });
|
|
478
|
+
return response.status === 204 ? null : (data as AccountGrantInfo);
|
|
479
|
+
},
|
|
480
|
+
async releaseAccount(session: string, unitId: string, leaseToken: string, grant: string, body: AccountRelease): Promise<void> {
|
|
481
|
+
const params = { path: { id: unitId, grant } };
|
|
482
|
+
await api.POST('/w/units/{id}/agent-accounts/{grant}/release', { params, body, headers: leased(session, leaseToken) });
|
|
483
|
+
},
|
|
484
|
+
},
|
|
485
|
+
artifacts: {
|
|
486
|
+
async put(session: string, leaseToken: string, sha256: string, bytes: Uint8Array): Promise<{ sha256: string; size: number }> {
|
|
487
|
+
const res = await send(`${base}/w/artifacts/${sha256}`, {
|
|
488
|
+
method: 'PUT',
|
|
489
|
+
headers: { 'content-type': 'application/octet-stream', ...leased(session, leaseToken) },
|
|
490
|
+
body: bytes as Uint8Array<ArrayBuffer>,
|
|
491
|
+
});
|
|
492
|
+
return (await res.json()) as { sha256: string; size: number };
|
|
493
|
+
},
|
|
494
|
+
async get(session: string, leaseToken: string, sha256: string): Promise<Uint8Array> {
|
|
495
|
+
return (await this.read(session, leaseToken, sha256)).bytes;
|
|
496
|
+
},
|
|
497
|
+
/** The bytes, and the path and media type the run last recorded them under (`null` when none did). */
|
|
498
|
+
async read(
|
|
499
|
+
session: string,
|
|
500
|
+
leaseToken: string,
|
|
501
|
+
sha256: string,
|
|
502
|
+
): Promise<{ bytes: Uint8Array; path: string | null; mediaType: string | null }> {
|
|
503
|
+
const res = await send(`${base}/w/artifacts/${sha256}`, { method: 'GET', headers: leased(session, leaseToken) });
|
|
504
|
+
return {
|
|
505
|
+
bytes: new Uint8Array(await res.arrayBuffer()),
|
|
506
|
+
path: res.headers.get('x-cf-artifact-path'),
|
|
507
|
+
mediaType: res.headers.get('x-cf-artifact-media-type'),
|
|
508
|
+
};
|
|
509
|
+
},
|
|
510
|
+
},
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export type Client = ReturnType<typeof createClient>;
|