@lifesi/genesis 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,179 @@
1
+ import { operationTable, services } from './generated/operations.js';
2
+ import { GenesisError } from './errors.js';
3
+ import { validateHivesInvocation, hivesFunctionResponseHeaders, hivesFunctionMetadata } from './hives-functions.js';
4
+ export const DEFAULT_BASE_URL = 'https://console.life.one/api';
5
+ const env = globalThis.process?.env ?? {};
6
+ export class GenesisClient {
7
+ baseUrl;
8
+ routing;
9
+ opts;
10
+ fetchImpl;
11
+ constructor(opts = {}) {
12
+ this.opts = opts;
13
+ this.baseUrl = (opts.baseUrl ?? env.GENESIS_BASE_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
14
+ this.routing = opts.routing ?? (env.GENESIS_ROUTING === 'direct' ? 'direct' : 'gateway');
15
+ const f = opts.fetch ?? globalThis.fetch;
16
+ if (!f)
17
+ throw new Error('No fetch available; pass options.fetch');
18
+ this.fetchImpl = f.bind(globalThis);
19
+ }
20
+ static operations = operationTable;
21
+ static services = services;
22
+ /** Resolve the credential: explicit apiKey > token > env GENESIS_API_KEY > GENESIS_TOKEN > provider. */
23
+ async credential() {
24
+ return this.opts.apiKey ?? this.opts.token ?? env.GENESIS_API_KEY ?? env.GENESIS_TOKEN ?? (await this.opts.credentials?.());
25
+ }
26
+ /** Build the URL for an operation (exposed for tests and `--dry-run`). */
27
+ url(operationId, input = {}) {
28
+ const op = operationTable[operationId];
29
+ if (!op)
30
+ throw new Error(`Unknown Genesis operation: ${operationId}`);
31
+ const fill = (tpl) => tpl.replace(/\{([^}]+)\}/g, (_, k) => {
32
+ const v = input[k];
33
+ if (v === undefined || v === null || v === '')
34
+ throw new GenesisError({ status: 0, type: 'invalid_request', message: `Missing required path parameter "${k}" for ${operationId}`, operationId });
35
+ return encodeURIComponent(String(v));
36
+ });
37
+ let base;
38
+ let p;
39
+ if (this.routing === 'direct') {
40
+ base = (this.opts.upstreams?.[op.service] ?? op.upstream.base).replace(/\/+$/, '');
41
+ p = fill(op.upstream.path);
42
+ }
43
+ else {
44
+ base = this.baseUrl;
45
+ p = fill(op.path);
46
+ }
47
+ const qs = new URLSearchParams();
48
+ for (const q of op.queryParams) {
49
+ const v = input[q];
50
+ if (v === undefined || v === null)
51
+ continue;
52
+ if (Array.isArray(v))
53
+ v.forEach((x) => qs.append(q, String(x)));
54
+ else
55
+ qs.set(q, String(v));
56
+ }
57
+ const s = qs.toString();
58
+ return `${base}${p}${s ? `?${s}` : ''}`;
59
+ }
60
+ /** Call any Genesis operation by id, fully typed from the merged spec. */
61
+ async request(operationId, input, init = {}) {
62
+ const res = await this.raw(operationId, (input ?? {}), init);
63
+ if (operationTable[operationId].rawResponse)
64
+ return res;
65
+ if (res.status === 204)
66
+ return undefined;
67
+ const ct = res.headers.get('content-type') ?? '';
68
+ let value;
69
+ try {
70
+ value = ct.includes('json') ? await res.json() : await res.text();
71
+ }
72
+ catch (error) {
73
+ if (String(operationId).startsWith('hives_') && /_functions?$/.test(operationId))
74
+ throw new Error('Hives returned invalid function metadata.');
75
+ throw error;
76
+ }
77
+ if (operationId === 'hives_list_functions') {
78
+ if (!value || !Array.isArray(value.data) || !value.pagination)
79
+ throw new Error('Hives returned invalid function list metadata.');
80
+ const pagination = Object.fromEntries(['page', 'per_page', 'total', 'total_pages', 'has_next', 'has_prev'].map((key) => [key, value.pagination[key]]));
81
+ return { data: value.data.map((row) => hivesFunctionMetadata(row, input?.project_id)), pagination };
82
+ }
83
+ if (['hives_get_function', 'hives_create_function', 'hives_update_function'].includes(operationId)) {
84
+ return hivesFunctionMetadata(value, input?.project_id);
85
+ }
86
+ return value;
87
+ }
88
+ /** Raw Response. Completed Hives guest responses retain their actual status, including non-2xx. */
89
+ async raw(operationId, input = {}, init = {}) {
90
+ const op = operationTable[operationId];
91
+ if (op.rawResponse && op.service === 'hives')
92
+ validateHivesInvocation(input.body);
93
+ const url = this.url(operationId, input);
94
+ const headers = {
95
+ accept: 'application/json',
96
+ 'user-agent': this.opts.userAgent ?? '@lifesi/genesis/0.1.0',
97
+ ...this.opts.headers, ...init.headers,
98
+ };
99
+ if (!op.public) {
100
+ const cred = await this.credential();
101
+ // Direct mode: let the upstream decide (some, like Foundry's model list, are public).
102
+ if (!cred && this.routing !== 'direct')
103
+ throw new GenesisError({ status: 401, type: 'unauthorized', message: 'No Genesis credential. Run `genesis login`, or set GENESIS_API_KEY.', operationId });
104
+ if (cred)
105
+ headers.authorization = `Bearer ${cred}`;
106
+ }
107
+ let body;
108
+ if (op.hasBody && input.body !== undefined) {
109
+ // Fetch owns multipart boundary generation. Never serialize a File/Blob as JSON.
110
+ for (const key of Object.keys(headers))
111
+ if (key.toLowerCase() === 'content-type')
112
+ delete headers[key];
113
+ if (op.requestContentType === 'multipart/form-data') {
114
+ if (!(input.body instanceof FormData))
115
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId,
116
+ message: 'This operation requires a FormData body containing a real binary file.' });
117
+ body = input.body;
118
+ }
119
+ else {
120
+ if (input.body instanceof FormData || input.body instanceof Blob || input.body instanceof ArrayBuffer || ArrayBuffer.isView(input.body)) {
121
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId, message: 'This operation requires a JSON body.' });
122
+ }
123
+ headers['content-type'] = 'application/json';
124
+ body = JSON.stringify(input.body);
125
+ }
126
+ }
127
+ const secretOperation = op.service === 'hives' && /_secrets?$/.test(operationId);
128
+ const functionOperation = op.service === 'hives' && (op.rawResponse || /_function(?:s|_async)?$/.test(operationId));
129
+ let res;
130
+ try {
131
+ res = await this.fetchImpl(url, { method: op.method, headers, body, signal: init.signal,
132
+ ...(op.service === 'hives' ? { cache: 'no-store', redirect: op.rawResponse ? 'manual' : 'error' } : {}) });
133
+ }
134
+ catch (error) {
135
+ if (functionOperation)
136
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
137
+ message: 'Hives function transport failed. No redirects are followed; check the service address and retry.' });
138
+ if (!secretOperation)
139
+ throw error;
140
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
141
+ message: 'Hives secret transport failed. Redirects are refused; check the service address and retry.' });
142
+ }
143
+ if (op.rawResponse && /^exec_[a-f0-9]{32}$/.test(res.headers.get('x-execution-id') ?? '')) {
144
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers: hivesFunctionResponseHeaders(res.headers) });
145
+ }
146
+ if (op.rawResponse && res.ok)
147
+ throw new GenesisError({ status: res.status, type: 'invalid_response', operationId,
148
+ message: 'Hives did not confirm a completed guest execution. Refresh the resource and retry.' });
149
+ if (functionOperation && !res.ok) {
150
+ const message = res.status === 401 ? 'Genesis credential rejected. Sign in again.'
151
+ : res.status === 403 ? 'Missing the authorized Hives scope for this function action.'
152
+ : res.status === 404 ? 'Function/deployment, project or artifact not found in the authenticated organization and project.'
153
+ : res.status === 409 ? 'Function mutation conflicted. Refresh its metadata before retrying.'
154
+ : res.status === 400 || res.status === 422 ? 'Invalid function request. Check artifact, resource bounds and guest request syntax.'
155
+ : res.status === 413 ? 'Function request exceeds a body or serialized guest envelope limit.'
156
+ : res.status >= 300 && res.status < 400 ? 'Unexpected function service redirect. No redirect was followed.'
157
+ : `Hives function operation failed (${res.status}). Refresh and retry.`;
158
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, operationId, message,
159
+ requestId: res.headers.get('x-request-id') ?? undefined });
160
+ }
161
+ if (!res.ok && secretOperation) {
162
+ const message = res.status === 401 ? 'Genesis credential rejected. Sign in again.'
163
+ : res.status === 403 ? 'Missing the authorized Hives scope for this action (hives:read or hives:write).'
164
+ : res.status === 404 ? 'Secret or project not found in your authenticated organization.'
165
+ : res.status === 409 ? 'A secret with this name already exists. Update it instead.'
166
+ : res.status === 400 || res.status === 422 ? 'Invalid secret request. Check names and UTF-8 value size.'
167
+ : res.status === 413 ? 'Secret request too large. Use a smaller batch.'
168
+ : res.status === 429 ? 'Too many requests. Wait briefly before retrying.'
169
+ : res.status === 503 ? 'Hives customer encryption is unavailable or stored secrets require protected migration.'
170
+ : `Hives secret operation failed (${res.status}). Refresh metadata and retry.`;
171
+ // Validation/provider bodies may reflect submitted plaintext. Never retain or log them.
172
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, message, operationId,
173
+ requestId: res.headers.get('x-request-id') ?? undefined });
174
+ }
175
+ if (!res.ok)
176
+ throw await GenesisError.fromResponse(res, operationId);
177
+ return res;
178
+ }
179
+ }
@@ -0,0 +1,129 @@
1
+ import type { GenesisClient } from './client.js';
2
+ import type { OperationInput } from './types.js';
3
+ import type { components } from './generated/schema.js';
4
+ export type DialsScope = components['schemas']['Dials.Scope'];
5
+ export type DialsCallControl = components['schemas']['Dials.CallControl'];
6
+ /** The public call contract requires customer-selected behavior for every caller. */
7
+ export type DialsOutboundCall = components['schemas']['Dials.OutboundCall'];
8
+ export type DialsEmergencyAddress = components['schemas']['Dials.RegisterEmergencyAddress'];
9
+ /** Scope is selection only; the Dials backend verifies its org against signed identity. */
10
+ export declare function dialsModule(client: GenesisClient): {
11
+ overview: {
12
+ summary: (scope: DialsScope) => Promise<{
13
+ ok: boolean;
14
+ scope: components["schemas"]["Dials.Scope"];
15
+ calls: {
16
+ total: number;
17
+ queued: number;
18
+ active: number;
19
+ completed: number;
20
+ failed: number;
21
+ };
22
+ dispatch: {
23
+ total: number;
24
+ pending: number;
25
+ claimed: number;
26
+ dispatched: number;
27
+ failed: number;
28
+ };
29
+ people: {
30
+ deployed: number;
31
+ };
32
+ agents: {
33
+ deployed: number;
34
+ };
35
+ routes: {
36
+ deployed: number;
37
+ };
38
+ numbers: {
39
+ deployed: number;
40
+ };
41
+ voice: {
42
+ deployed: number;
43
+ };
44
+ messages: {
45
+ total: number;
46
+ queued: number;
47
+ delivered: number;
48
+ failed: number;
49
+ };
50
+ usage: {
51
+ total: number;
52
+ quantity: number;
53
+ lastMetric: string | null;
54
+ lastResourceId: string | null;
55
+ };
56
+ }>;
57
+ operatingSurface: (scope: DialsScope) => Promise<{
58
+ ok: boolean;
59
+ scope: components["schemas"]["Dials.Scope"];
60
+ summary: components["schemas"]["Dials.ConsoleSummary"];
61
+ surfaces: components["schemas"]["Dials.OperatingSurfaceCard"][];
62
+ } & {
63
+ [key: string]: unknown;
64
+ }>;
65
+ };
66
+ numbers: {
67
+ reconciliations: (scope: DialsScope) => Promise<{
68
+ ok: boolean;
69
+ reconciliations: components["schemas"]["Dials.InventoryReconciliation"][];
70
+ }>;
71
+ drift: (scope: DialsScope) => Promise<{
72
+ ok: boolean;
73
+ drift: components["schemas"]["Dials.InventoryDrift"][];
74
+ }>;
75
+ updateCallerName: (body: OperationInput<"dials_updateNumberCallerName">["body"]) => Promise<{
76
+ ok: boolean;
77
+ number: components["schemas"]["Dials.Number"];
78
+ auditId: string;
79
+ next: string;
80
+ }>;
81
+ reconcile: (body: OperationInput<"dials_reconcileNumberInventory">["body"]) => Promise<{
82
+ ok: boolean;
83
+ reconciliations: components["schemas"]["Dials.InventoryReconciliation"][];
84
+ drift: components["schemas"]["Dials.InventoryDrift"][];
85
+ orphanCount: number;
86
+ auditId: string;
87
+ next: string;
88
+ }>;
89
+ list: (scope: DialsScope) => Promise<{
90
+ ok: boolean;
91
+ numbers: components["schemas"]["Dials.Number"][];
92
+ }>;
93
+ search: (scope: DialsScope, query?: Omit<OperationInput<"dials_searchNumbers">, keyof DialsScope>) => Promise<{
94
+ ok: boolean;
95
+ numbers: components["schemas"]["Dials.AvailableNumber"][];
96
+ }>;
97
+ provision: (body: OperationInput<"dials_provisionNumber">["body"]) => Promise<{
98
+ [key: string]: unknown;
99
+ }>;
100
+ assign: (body: OperationInput<"dials_assignNumber">["body"]) => Promise<{
101
+ [key: string]: unknown;
102
+ }>;
103
+ release: (body: OperationInput<"dials_releaseNumber">["body"]) => Promise<{
104
+ [key: string]: unknown;
105
+ }>;
106
+ registerEmergencyAddress: (body: DialsEmergencyAddress) => Promise<{
107
+ ok: boolean;
108
+ number: components["schemas"]["Dials.Number"];
109
+ address: components["schemas"]["Dials.EmergencyAddress"];
110
+ auditId: string;
111
+ next: string;
112
+ }>;
113
+ };
114
+ calls: {
115
+ list: (scope: DialsScope) => Promise<{
116
+ ok: boolean;
117
+ calls: components["schemas"]["Dials.Call"][];
118
+ }>;
119
+ validate: (body: DialsOutboundCall) => Promise<{
120
+ [key: string]: unknown;
121
+ }>;
122
+ create: (body: DialsOutboundCall) => Promise<{
123
+ [key: string]: unknown;
124
+ }>;
125
+ };
126
+ };
127
+ export type DialsEmergencyAddressFeedback = components['schemas']['Dials.EmergencyAddressFeedback'];
128
+ /** Read bounded, typed advisory feedback from the existing Genesis error. Never auto-apply it. */
129
+ export declare function dialsEmergencyAddressFeedback(error: unknown): DialsEmergencyAddressFeedback | undefined;
package/dist/dials.js ADDED
@@ -0,0 +1,59 @@
1
+ import { GenesisError } from './errors.js';
2
+ /** Scope is selection only; the Dials backend verifies its org against signed identity. */
3
+ export function dialsModule(client) {
4
+ return {
5
+ overview: {
6
+ summary: (scope) => client.request('dials_getConsoleSummary', scope),
7
+ operatingSurface: (scope) => client.request('dials_getOperatingSurface', scope),
8
+ },
9
+ numbers: {
10
+ reconciliations: (scope) => client.request('dials_listNumberReconciliations', scope),
11
+ drift: (scope) => client.request('dials_listNumberDrift', scope),
12
+ updateCallerName: (body) => client.request('dials_updateNumberCallerName', { body }),
13
+ reconcile: (body) => client.request('dials_reconcileNumberInventory', { body }),
14
+ list: (scope) => client.request('dials_listNumbers', scope),
15
+ search: (scope, query = {}) => client.request('dials_searchNumbers', { ...query, ...scope }),
16
+ provision: (body) => client.request('dials_provisionNumber', { body }),
17
+ assign: (body) => client.request('dials_assignNumber', { body }),
18
+ release: (body) => client.request('dials_releaseNumber', { body }),
19
+ registerEmergencyAddress: (body) => client.request('dials_registerEmergencyAddress', { body }),
20
+ },
21
+ calls: {
22
+ list: (scope) => client.request('dials_listCalls', scope),
23
+ validate: (body) => client.request('dials_validateOutboundCall', { body }),
24
+ create: (body) => client.request('dials_createOutboundCall', { body }),
25
+ },
26
+ };
27
+ }
28
+ const fields = { streetNumber: 'Review the street number.', streetName: 'Review the street name.', addressLine2: 'Review the suite or unit type and number.', city: 'Review the city.', region: 'Review the state.', postalCode: 'Review the postal code.', country: 'Review the country.', address: 'The carrier could not validate this address. Review the address and any suggestions.' };
29
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
30
+ const addressText = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max && /^[\p{L}\p{N} .,'#/-]+$/u.test(value) && !/(bearer|basic |sk_|api_key|authorization|secret|token=)/i.test(value);
31
+ /** Read bounded, typed advisory feedback from the existing Genesis error. Never auto-apply it. */
32
+ export function dialsEmergencyAddressFeedback(error) {
33
+ if (!(error instanceof GenesisError) || error.status !== 422 || error.operationId !== 'dials_registerEmergencyAddress')
34
+ return;
35
+ const body = error.body;
36
+ if (!object(body) || body.error !== 'carrier_rejected' || body.automaticCorrection !== false || !Array.isArray(body.fieldErrors) || !body.fieldErrors.length || body.fieldErrors.length > 8 || !Array.isArray(body.candidates) || body.candidates.length > 5)
37
+ return;
38
+ const fieldErrors = [];
39
+ for (const value of body.fieldErrors) {
40
+ if (!object(value) || typeof value.field !== 'string' || !Object.hasOwn(fields, value.field) || !['required', 'invalid', 'not_found', 'ambiguous', 'not_validated'].includes(String(value.code)))
41
+ return;
42
+ const field = value.field;
43
+ fieldErrors.push({ field, code: value.code, message: fields[field] });
44
+ }
45
+ const candidates = [];
46
+ for (const value of body.candidates) {
47
+ if (!object(value) || !addressText(value.streetNumber, 32) || !addressText(value.streetName, 128) || !addressText(value.city, 80) || typeof value.region !== 'string' || !/^[A-Za-z]{2}$/.test(value.region) || typeof value.postalCode !== 'string' || !/^\d{5}(?:-\d{4})?$/.test(value.postalCode))
48
+ return;
49
+ const extra = {};
50
+ if (value.addressType !== undefined || value.addressNumber !== undefined) {
51
+ if (!['Apartment', 'Basement', 'Building', 'Department', 'Floor', 'Office', 'Penthouse', 'Suite', 'Trailer', 'Unit'].includes(String(value.addressType)) || !addressText(value.addressNumber, 32))
52
+ return;
53
+ extra.addressType = value.addressType;
54
+ extra.addressNumber = value.addressNumber;
55
+ }
56
+ candidates.push({ streetNumber: value.streetNumber, streetName: value.streetName, city: value.city, region: value.region, postalCode: value.postalCode, ...extra });
57
+ }
58
+ return { automaticCorrection: false, fieldErrors, candidates };
59
+ }
@@ -0,0 +1,19 @@
1
+ /** Normalized error for every Genesis service (gateway `{error:{type,message}}`, IAM `{error,error_description}`, Relays `{error}`, Foundry/OpenAI shape). */
2
+ export declare class GenesisError extends Error {
3
+ readonly status: number;
4
+ readonly type: string;
5
+ readonly code?: string;
6
+ readonly requestId?: string;
7
+ readonly operationId?: string;
8
+ readonly body: unknown;
9
+ constructor(init: {
10
+ status: number;
11
+ type: string;
12
+ message: string;
13
+ code?: string;
14
+ requestId?: string;
15
+ operationId?: string;
16
+ body?: unknown;
17
+ });
18
+ static fromResponse(res: Response, operationId?: string): Promise<GenesisError>;
19
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,35 @@
1
+ /** Normalized error for every Genesis service (gateway `{error:{type,message}}`, IAM `{error,error_description}`, Relays `{error}`, Foundry/OpenAI shape). */
2
+ export class GenesisError extends Error {
3
+ status;
4
+ type;
5
+ code;
6
+ requestId;
7
+ operationId;
8
+ body;
9
+ constructor(init) {
10
+ super(init.message);
11
+ this.name = 'GenesisError';
12
+ Object.assign(this, init);
13
+ this.status = init.status;
14
+ this.type = init.type;
15
+ this.body = init.body;
16
+ }
17
+ static async fromResponse(res, operationId) {
18
+ const text = await res.text().catch(() => '');
19
+ let body = text;
20
+ try {
21
+ body = text ? JSON.parse(text) : undefined;
22
+ }
23
+ catch { /* keep text */ }
24
+ const e = body?.error;
25
+ const type = typeof e === 'object' && e ? (e.type ?? e.code ?? 'error') : typeof e === 'string' ? e : statusType(res.status);
26
+ const message = (typeof e === 'object' && e?.message) || body?.error_description || body?.message ||
27
+ (typeof e === 'string' && e) || (typeof body === 'string' && body) || `${res.status} ${res.statusText}`;
28
+ return new GenesisError({
29
+ status: res.status, type, message, code: typeof e === 'object' ? e?.code : undefined,
30
+ requestId: res.headers.get('x-request-id') ?? (typeof e === 'object' ? e?.request_id : undefined) ?? body?.request_id,
31
+ operationId, body,
32
+ });
33
+ }
34
+ }
35
+ const statusType = (s) => s === 401 ? 'unauthorized' : s === 403 ? 'forbidden' : s === 404 ? 'not_found' : s === 429 ? 'rate_limited' : s >= 500 ? 'upstream_error' : 'error';
@@ -0,0 +1,71 @@
1
+ import type { GenesisClient } from './client.js';
2
+ import type { OperationInput } from './types.js';
3
+ type TaskInput = NonNullable<OperationInput<'fleets_submitTask'>['body']>;
4
+ /** Managed agent tasks, always scoped to the credential's verified organization. */
5
+ export declare function fleetsModule(client: GenesisClient): {
6
+ connection: {
7
+ get: () => Promise<{
8
+ connected: boolean;
9
+ model: string;
10
+ updated_at?: number;
11
+ }>;
12
+ set: (api_key: string) => Promise<{
13
+ connected: boolean;
14
+ model: string;
15
+ updated_at?: number;
16
+ }>;
17
+ delete: () => Promise<{
18
+ connected: boolean;
19
+ model: string;
20
+ updated_at?: number;
21
+ }>;
22
+ };
23
+ tasks: {
24
+ list: (query?: OperationInput<"fleets_listTasks">) => Promise<{
25
+ tasks: import("./index.js").components["schemas"]["Fleets.Summary"][];
26
+ next_before: string | null;
27
+ }>;
28
+ submit: (body: TaskInput) => Promise<{
29
+ task_id: string;
30
+ status: import("./index.js").components["schemas"]["Fleets.Status"];
31
+ submitted_at: string;
32
+ started_at?: string | null;
33
+ completed_at?: string | null;
34
+ }>;
35
+ get: (task_id: string) => Promise<{
36
+ task_id: string;
37
+ status: import("./index.js").components["schemas"]["Fleets.Status"];
38
+ submitted_at: string;
39
+ started_at?: string | null;
40
+ completed_at?: string | null;
41
+ }>;
42
+ cancel: (task_id: string) => Promise<{
43
+ task_id: string;
44
+ status: import("./index.js").components["schemas"]["Fleets.Status"];
45
+ }>;
46
+ receipt: (task_id: string) => Promise<{
47
+ task_id: string;
48
+ status: import("./index.js").components["schemas"]["Fleets.Status"];
49
+ submitted_at: string;
50
+ started_at?: string | null;
51
+ completed_at?: string | null;
52
+ } & {
53
+ tenant: string;
54
+ principal: string;
55
+ idempotency_key: string | null;
56
+ request_fingerprint: string;
57
+ timeout_seconds: number;
58
+ exit_code: number | null;
59
+ exit_signal: number | null;
60
+ cleanup_result: {
61
+ process_group_gone?: boolean;
62
+ workdir_removed?: boolean;
63
+ sigkill_sent?: boolean;
64
+ } | null;
65
+ henry_receipt?: {
66
+ [key: string]: unknown;
67
+ };
68
+ }>;
69
+ };
70
+ };
71
+ export {};
package/dist/fleets.js ADDED
@@ -0,0 +1,44 @@
1
+ import { GenesisError } from './errors.js';
2
+ const byteLength = (value) => new TextEncoder().encode(value).byteLength;
3
+ const invalid = (operationId, message) => new GenesisError({
4
+ status: 0, type: 'invalid_request', operationId, message,
5
+ });
6
+ function validateTask(body) {
7
+ if (typeof body?.input !== 'string' || !body.input || byteLength(body.input) > 65536 || body.input.includes('\0')) {
8
+ throw invalid('fleets_submitTask', 'Task input must contain 1–65536 UTF-8 bytes without NUL.');
9
+ }
10
+ if (body.timeout_seconds !== undefined && (!Number.isInteger(body.timeout_seconds) || body.timeout_seconds < 1 || body.timeout_seconds > 3600)) {
11
+ throw invalid('fleets_submitTask', 'Timeout must be 1–3600 seconds.');
12
+ }
13
+ if (body.idempotency_key !== undefined && (typeof body.idempotency_key !== 'string' || !/^[!-~]{1,128}$/.test(body.idempotency_key))) {
14
+ throw invalid('fleets_submitTask', 'Idempotency key must contain 1–128 visible ASCII characters.');
15
+ }
16
+ }
17
+ function validateKey(apiKey) {
18
+ if (typeof apiKey !== 'string' || !apiKey || byteLength(apiKey) > 4096 || /[\r\n\0]/.test(apiKey)) {
19
+ throw invalid('fleets_setConnection', 'Foundry key must contain 1–4096 UTF-8 bytes without CR, LF or NUL.');
20
+ }
21
+ }
22
+ /** Managed agent tasks, always scoped to the credential's verified organization. */
23
+ export function fleetsModule(client) {
24
+ return {
25
+ connection: {
26
+ get: () => client.request('fleets_getConnection', {}),
27
+ set: async (api_key) => {
28
+ validateKey(api_key);
29
+ return client.request('fleets_setConnection', { body: { api_key } });
30
+ },
31
+ delete: () => client.request('fleets_deleteConnection', {}),
32
+ },
33
+ tasks: {
34
+ list: (query = {}) => client.request('fleets_listTasks', query),
35
+ submit: async (body) => {
36
+ validateTask(body);
37
+ return client.request('fleets_submitTask', { body });
38
+ },
39
+ get: (task_id) => client.request('fleets_getTask', { task_id }),
40
+ cancel: (task_id) => client.request('fleets_cancelTask', { task_id }),
41
+ receipt: (task_id) => client.request('fleets_getTaskReceipt', { task_id }),
42
+ },
43
+ };
44
+ }