@onesi/genesis 0.0.1-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +29 -0
  2. package/dist/auto.d.ts +1010 -0
  3. package/dist/auto.js +125 -0
  4. package/dist/beacons.d.ts +145 -0
  5. package/dist/beacons.js +148 -0
  6. package/dist/blinds-owner-enrollment.d.ts +280 -0
  7. package/dist/blinds-owner-enrollment.js +169 -0
  8. package/dist/client.d.ts +52 -0
  9. package/dist/client.js +384 -0
  10. package/dist/context.d.ts +50 -0
  11. package/dist/context.js +153 -0
  12. package/dist/dials.d.ts +299 -0
  13. package/dist/dials.js +100 -0
  14. package/dist/errors.d.ts +35 -0
  15. package/dist/errors.js +66 -0
  16. package/dist/flares.d.ts +202 -0
  17. package/dist/flares.js +61 -0
  18. package/dist/fleets.d.ts +218 -0
  19. package/dist/fleets.js +189 -0
  20. package/dist/flocks.d.ts +439 -0
  21. package/dist/flocks.js +98 -0
  22. package/dist/foundry-billing.d.ts +97 -0
  23. package/dist/foundry-billing.js +107 -0
  24. package/dist/foundry.d.ts +424 -0
  25. package/dist/foundry.js +133 -0
  26. package/dist/garden.d.ts +754 -0
  27. package/dist/garden.js +76 -0
  28. package/dist/gateway.d.ts +365 -0
  29. package/dist/gateway.js +82 -0
  30. package/dist/gears.d.ts +226 -0
  31. package/dist/gears.js +42 -0
  32. package/dist/generated/operations.d.ts +4 -0
  33. package/dist/generated/operations.js +65134 -0
  34. package/dist/generated/schema.d.ts +87658 -0
  35. package/dist/generated/schema.js +1 -0
  36. package/dist/genesis.d.ts +9574 -0
  37. package/dist/genesis.js +271 -0
  38. package/dist/genesis.openapi.json +128522 -0
  39. package/dist/henry.d.ts +369 -0
  40. package/dist/henry.js +268 -0
  41. package/dist/hives-cells.d.ts +127 -0
  42. package/dist/hives-cells.js +151 -0
  43. package/dist/hives-environment.d.ts +37 -0
  44. package/dist/hives-environment.js +80 -0
  45. package/dist/hives-functions.d.ts +36 -0
  46. package/dist/hives-functions.js +185 -0
  47. package/dist/hives-marketplace.d.ts +128 -0
  48. package/dist/hives-marketplace.js +187 -0
  49. package/dist/hives-node.d.ts +9 -0
  50. package/dist/hives-node.js +155 -0
  51. package/dist/hives-operations.d.ts +451 -0
  52. package/dist/hives-operations.js +43 -0
  53. package/dist/hives-platform.d.ts +149 -0
  54. package/dist/hives-platform.js +183 -0
  55. package/dist/hives-queue-consumer.d.ts +56 -0
  56. package/dist/hives-queue-consumer.js +95 -0
  57. package/dist/hives-queue-funding.d.ts +28 -0
  58. package/dist/hives-queue-funding.js +81 -0
  59. package/dist/hives-queues.d.ts +137 -0
  60. package/dist/hives-queues.js +143 -0
  61. package/dist/hives-resources-transport.d.ts +23 -0
  62. package/dist/hives-resources-transport.js +204 -0
  63. package/dist/hives-response.d.ts +2 -0
  64. package/dist/hives-response.js +32 -0
  65. package/dist/hives-runtimes.d.ts +34 -0
  66. package/dist/hives-runtimes.js +32 -0
  67. package/dist/hives-sse.d.ts +24 -0
  68. package/dist/hives-sse.js +111 -0
  69. package/dist/hives-topics.d.ts +51 -0
  70. package/dist/hives-topics.js +79 -0
  71. package/dist/hives-upload.d.ts +9 -0
  72. package/dist/hives-upload.js +23 -0
  73. package/dist/hives-volumes.d.ts +64 -0
  74. package/dist/hives-volumes.js +117 -0
  75. package/dist/iam-directory.d.ts +8 -0
  76. package/dist/iam-directory.js +23 -0
  77. package/dist/iam.d.ts +391 -0
  78. package/dist/iam.js +92 -0
  79. package/dist/idempotency.d.ts +7 -0
  80. package/dist/idempotency.js +39 -0
  81. package/dist/index.d.ts +47 -0
  82. package/dist/index.js +37 -0
  83. package/dist/instances.d.ts +200 -0
  84. package/dist/instances.js +43 -0
  85. package/dist/lanes.d.ts +267 -0
  86. package/dist/lanes.js +41 -0
  87. package/dist/minds-agent.d.ts +88 -0
  88. package/dist/minds-agent.js +233 -0
  89. package/dist/minds-engine.d.ts +394 -0
  90. package/dist/minds-engine.js +555 -0
  91. package/dist/minds-owner.d.ts +110 -0
  92. package/dist/minds-owner.js +226 -0
  93. package/dist/minds.d.ts +377 -0
  94. package/dist/minds.js +228 -0
  95. package/dist/orgs.d.ts +405 -0
  96. package/dist/orgs.js +63 -0
  97. package/dist/relays-enrollment.d.ts +33 -0
  98. package/dist/relays-enrollment.js +115 -0
  99. package/dist/runner-grant.d.ts +10 -0
  100. package/dist/runner-grant.js +133 -0
  101. package/dist/runner.d.ts +72 -0
  102. package/dist/runner.js +117 -0
  103. package/dist/scopes.d.ts +310 -0
  104. package/dist/scopes.js +40 -0
  105. package/dist/taps.d.ts +118 -0
  106. package/dist/taps.js +45 -0
  107. package/dist/traces.d.ts +574 -0
  108. package/dist/traces.js +97 -0
  109. package/dist/types.d.ts +98 -0
  110. package/dist/types.js +1 -0
  111. package/dist/urls.d.ts +6 -0
  112. package/dist/urls.js +31 -0
  113. package/package.json +49 -1
package/dist/client.js ADDED
@@ -0,0 +1,384 @@
1
+ import { isHivesQueueFundingOperation, hivesQueueOperationError } from './hives-queue-funding.js';
2
+ import { isMindsOperation, mindsTransport } from './minds.js';
3
+ import { isMindsAgentOperation, mindsAgentTransport } from './minds-agent.js';
4
+ import { isMindsOwnerOperation, mindsOwnerTransport } from './minds-owner.js';
5
+ import { isFoundryBillingOperation, foundryBillingTransport } from './foundry-billing.js';
6
+ import { isRelaysEnrollmentOperation, relaysEnrollmentTransport } from './relays-enrollment.js';
7
+ import { blindsOperationKey, blindsOwnerTransport, isBlindsOwnerOperation } from './blinds-owner-enrollment.js';
8
+ import { isHivesObjectUpload, hivesObjectBody, hivesContentType, isHivesResourceOperation, resourceError, resourceErrorFromResponse } from './hives-resources-transport.js';
9
+ import { operationTable, services } from './generated/operations.js';
10
+ import { GenesisError } from './errors.js';
11
+ import { requireSecureUrl } from './urls.js';
12
+ import { iamDirectoryFailure, isIamDirectoryOperation } from './iam-directory.js';
13
+ import { validateHivesInvocation, hivesFunctionResponseHeaders, hivesFunctionMetadata, hivesOperationError } from './hives-functions.js';
14
+ import { validateHivesEnvironment, validateHivesEnvironmentNames, hivesEnvironmentSetNames, hivesEnvironmentMetadata, hivesEnvironmentReveal } from './hives-environment.js';
15
+ import { RUNNER_SELF_GRANT_OPERATION, snapshotRunnerSelfGrant, runnerGrantResponse, runnerGrantTransportError } from './runner-grant.js';
16
+ /** The Genesis API gateway. `https://console.life.one/api` remains an alias for the same gateway. */
17
+ export const DEFAULT_BASE_URL = 'https://os.one.ml/api';
18
+ const env = globalThis.process?.env ?? {};
19
+ /** Endless Server-Sent Events streams and the bounded reader for each; request() refuses these and any operation generated with `stream: true`. */
20
+ const ENDLESS_STREAMS = {
21
+ hives_stream_logs: 'genesis.hives.logs.stream() or genesis.hives.logs.window()',
22
+ hives_stream_deployment_logs: 'hivesSseWindow(await genesis.raw(...))',
23
+ };
24
+ export class GenesisClient {
25
+ baseUrl;
26
+ routing;
27
+ opts;
28
+ fetchImpl;
29
+ get contextFetch() { return this.fetchImpl; }
30
+ constructor(opts = {}) {
31
+ this.opts = opts;
32
+ this.baseUrl = requireSecureUrl(opts.baseUrl ?? env.GENESIS_BASE_URL ?? DEFAULT_BASE_URL, 'baseUrl').replace(/\/+$/, '');
33
+ this.routing = opts.routing ?? (env.GENESIS_ROUTING === 'direct' ? 'direct' : 'gateway');
34
+ const f = opts.fetch ?? globalThis.fetch;
35
+ if (!f)
36
+ throw new Error('No fetch available; pass options.fetch');
37
+ this.fetchImpl = f.bind(globalThis);
38
+ }
39
+ static operations = operationTable;
40
+ static services = services;
41
+ /** Resolve the credential: explicit apiKey > token > env GENESIS_API_KEY > GENESIS_TOKEN > provider. */
42
+ async credential() {
43
+ return this.opts.apiKey ?? this.opts.token ?? env.GENESIS_API_KEY ?? env.GENESIS_TOKEN ?? (await this.opts.credentials?.());
44
+ }
45
+ /** Build the URL for an operation (exposed for tests and `--dry-run`). */
46
+ url(operationId, input = {}) {
47
+ const op = operationTable[operationId];
48
+ if (!op)
49
+ throw new Error(`Unknown Genesis operation: ${operationId}`);
50
+ const fill = (tpl) => tpl.replace(/\{([^}]+)\}/g, (_, k) => {
51
+ const v = input[k];
52
+ if (v === undefined || v === null || v === '')
53
+ throw new GenesisError({ status: 0, type: 'invalid_request', message: `Missing required path parameter "${k}" for ${operationId}`, operationId });
54
+ if (!op.tailParams?.includes(k))
55
+ return encodeURIComponent(String(v));
56
+ const segments = String(v).split('/');
57
+ if (segments.some(s => s === '' || s === '.' || s === '..' || s.includes('\\')))
58
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId,
59
+ message: `Path parameter "${k}" for ${operationId} must be "/"-separated segments with no empty, "." or ".." segment and no backslash` });
60
+ return segments.map(encodeURIComponent).join('/');
61
+ });
62
+ let base;
63
+ let p;
64
+ if (this.routing === 'direct') {
65
+ if (op.service === 'gateway')
66
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId, message: 'Gateway operations are answered by the Genesis gateway itself and have no direct upstream.' });
67
+ base = (this.opts.upstreams?.[op.service] ?? op.upstream.base).replace(/\/+$/, '');
68
+ p = fill(op.upstream.path);
69
+ }
70
+ else {
71
+ base = this.baseUrl;
72
+ p = fill(op.path);
73
+ }
74
+ const qs = new URLSearchParams();
75
+ for (const q of op.queryParams) {
76
+ const v = input[q];
77
+ if (v === undefined || v === null)
78
+ continue;
79
+ if (Array.isArray(v))
80
+ v.forEach((x) => qs.append(q, String(x)));
81
+ else
82
+ qs.set(q, String(v));
83
+ }
84
+ const s = qs.toString();
85
+ return `${base}${p}${s ? `?${s}` : ''}`;
86
+ }
87
+ /** Call any Genesis operation by id, fully typed from the merged spec. */
88
+ async request(operationId, input, init = {}) {
89
+ // An endless SSE body never completes, so buffering it would hang: refuse before any request is sent.
90
+ // Finite SSE reads (for example traces_streamRun) are not marked and still use request().
91
+ const endless = ENDLESS_STREAMS[operationId]
92
+ ?? (operationTable[operationId]?.stream === true ? 'hivesSseWindow(await genesis.raw(...))' : undefined);
93
+ if (endless)
94
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId,
95
+ message: `${String(operationId)} is an endless Server-Sent Events stream. Read a bounded window with ${endless} instead of request().` });
96
+ const res = await this.raw(operationId, (input ?? {}), init);
97
+ if (operationTable[operationId].rawResponse)
98
+ return res;
99
+ // DELETE /env answers 200 with an empty body.
100
+ if (operationId === 'hives_delete_project_env') {
101
+ void res.body?.cancel().catch(() => { });
102
+ return undefined;
103
+ }
104
+ if (operationId === 'hives_stop_deployment' && res.status !== 200) {
105
+ void res.body?.cancel().catch(() => { });
106
+ throw new GenesisError({ status: 0, type: 'invalid_response', operationId, message: 'Hives did not confirm this deployment stopped. Read its current state before explicitly reconciling stop.' });
107
+ }
108
+ if (res.status === 204)
109
+ return undefined;
110
+ const ct = res.headers.get('content-type') ?? '';
111
+ let value;
112
+ try {
113
+ value = ct.includes('json') ? await res.json() : await res.text();
114
+ }
115
+ catch (error) {
116
+ if (String(operationId).startsWith('hives_') && /_project_env(?:ironment)?$/.test(operationId))
117
+ throw new Error('Hives returned invalid environment data.');
118
+ if (String(operationId).startsWith('hives_') && /_functions?$/.test(operationId))
119
+ throw new Error('Hives returned invalid function metadata.');
120
+ throw error;
121
+ }
122
+ if (operationId === 'hives_stop_deployment') {
123
+ const requested = input;
124
+ if (!value || value.id !== requested.deployment_id || value.project_id !== requested.project_id || value.status !== 'cancelled') {
125
+ throw new GenesisError({ status: 0, type: 'invalid_response', operationId, message: 'Hives did not confirm this deployment stopped. Read its current state before explicitly reconciling stop.' });
126
+ }
127
+ }
128
+ if (operationId === 'hives_list_functions') {
129
+ if (!value || !Array.isArray(value.data) || !value.pagination)
130
+ throw new Error('Hives returned invalid function list metadata.');
131
+ const pagination = Object.fromEntries(['page', 'per_page', 'total', 'total_pages', 'has_next', 'has_prev'].map((key) => [key, value.pagination[key]]));
132
+ return { data: value.data.map((row) => hivesFunctionMetadata(row, input?.project_id)), pagination };
133
+ }
134
+ if (['hives_get_function', 'hives_create_function', 'hives_update_function'].includes(operationId)) {
135
+ return hivesFunctionMetadata(value, input?.project_id, operationId === 'hives_create_function' ? undefined : input?.function_id);
136
+ }
137
+ if (operationId === 'hives_list_project_environment' || operationId === 'hives_update_project_environment') {
138
+ return hivesEnvironmentMetadata(value, input?.project_id, operationId === 'hives_update_project_environment');
139
+ }
140
+ if (operationId === 'hives_set_project_env') {
141
+ return hivesEnvironmentSetNames(value, input?.project_id, input?.body);
142
+ }
143
+ if (operationId === 'hives_reveal_project_environment') {
144
+ return hivesEnvironmentReveal(value, input?.key);
145
+ }
146
+ return value;
147
+ }
148
+ /** Raw Response. Completed Hives guest responses retain their actual status, including non-2xx. */
149
+ async raw(operationId, input = {}, init = {}) {
150
+ if (!isIamDirectoryOperation(operationId))
151
+ return this.dispatch(operationId, input, init);
152
+ // The gateway binds the organization context itself. A refusal is only explained here; the client never changes a session or its context.
153
+ try {
154
+ return await this.dispatch(operationId, input, init);
155
+ }
156
+ catch (e) {
157
+ throw iamDirectoryFailure(e, typeof input.org_id === 'string' ? input.org_id : '', operationId);
158
+ }
159
+ }
160
+ async dispatch(operationId, input, init) {
161
+ if (isMindsOwnerOperation(operationId))
162
+ return mindsOwnerTransport({ operationId, input, headers: init.headers, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
163
+ if (isMindsAgentOperation(operationId))
164
+ return mindsAgentTransport({ operationId, input, headers: init.headers, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
165
+ if (isMindsOperation(operationId))
166
+ return mindsTransport({ operationId, input, headers: init.headers, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
167
+ if (isFoundryBillingOperation(operationId))
168
+ return foundryBillingTransport({ operationId, input, headers: init.headers, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
169
+ if (isRelaysEnrollmentOperation(operationId))
170
+ return relaysEnrollmentTransport({ operationId, input, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
171
+ if (isBlindsOwnerOperation(operationId))
172
+ return blindsOwnerTransport({ operationId, input, routing: this.routing, url: this.url(operationId, input), credential: () => this.credential(), fetch: this.fetchImpl, signal: init.signal });
173
+ const runnerGrant = operationId === RUNNER_SELF_GRANT_OPERATION ? snapshotRunnerSelfGrant(input, this.routing) : undefined;
174
+ if (runnerGrant)
175
+ input = { body: runnerGrant };
176
+ const op = operationTable[operationId];
177
+ if (op.rawResponse && op.service === 'hives')
178
+ validateHivesInvocation(input.body);
179
+ const flocksNative = ['flocks_exchangeJoinToken', 'flocks_activateNode', 'flocks_rotateNodeCredential'].includes(operationId);
180
+ if (flocksNative && this.routing === 'direct')
181
+ throw new GenesisError({ status: 0, type: 'invalid_request', message: 'Native Flocks credentials are brokered only through the Genesis gateway.', operationId });
182
+ if (operationId === 'hives_update_project_environment' || operationId === 'hives_set_project_env')
183
+ input = { ...input, body: validateHivesEnvironment(input.body) };
184
+ if (operationId === 'hives_delete_project_env')
185
+ input = { ...input, body: validateHivesEnvironmentNames(input.body) };
186
+ const objectBody = isHivesObjectUpload(operationId) ? await hivesObjectBody(input.body) : undefined;
187
+ const url = this.url(operationId, input);
188
+ const headers = {
189
+ accept: 'application/json',
190
+ 'user-agent': this.opts.userAgent ?? '@onesi/genesis/0.2.0',
191
+ ...this.opts.headers, ...init.headers,
192
+ };
193
+ if (op.service === 'blinds' && !['GET', 'HEAD', 'OPTIONS'].includes(op.method))
194
+ blindsOperationKey(operationId, input, headers);
195
+ if (isHivesQueueFundingOperation(operationId)) {
196
+ const keys = Object.keys(headers).filter(name => name.toLowerCase() === 'idempotency-key');
197
+ if (keys.length > 1 || keys.some(name => !/^[ -~]{1,128}$/.test(headers[name])))
198
+ throw resourceError(0, operationId);
199
+ }
200
+ if (runnerGrant) {
201
+ for (const key of Object.keys(headers))
202
+ if (!['accept', 'user-agent'].includes(key.toLowerCase()))
203
+ delete headers[key];
204
+ headers['x-request-id'] = runnerGrant.requestId;
205
+ headers['idempotency-key'] = runnerGrant.operationId;
206
+ }
207
+ if (operationId === 'flocks_exchangeJoinToken') {
208
+ for (const key of Object.keys(headers))
209
+ if (!['accept', 'user-agent'].includes(key.toLowerCase()))
210
+ delete headers[key];
211
+ }
212
+ if (!op.public) {
213
+ const cred = await this.credential();
214
+ // Direct mode: let the upstream decide (some, like Foundry's model list, are public).
215
+ if (!cred && this.routing !== 'direct')
216
+ throw new GenesisError({ status: 401, type: 'unauthorized', message: 'No Genesis credential. Run `genesis login`, or set GENESIS_API_KEY.', operationId });
217
+ if (cred)
218
+ headers.authorization = `Bearer ${cred}`;
219
+ }
220
+ // A timed-out credential provider must not dispatch a later resource mutation.
221
+ if (init.signal?.aborted && isHivesResourceOperation(operationId))
222
+ throw resourceError(0, operationId);
223
+ let body;
224
+ if (op.hasBody && input.body !== undefined) {
225
+ // Fetch owns multipart boundary generation. Never serialize a File/Blob as JSON.
226
+ for (const key of Object.keys(headers))
227
+ if (key.toLowerCase() === 'content-type')
228
+ delete headers[key];
229
+ if (objectBody !== undefined && op.requestContentType === 'application/octet-stream') {
230
+ headers['content-type'] = hivesContentType(input.content_type);
231
+ headers['content-length'] = String(objectBody.byteLength);
232
+ body = objectBody;
233
+ }
234
+ else if (op.requestContentType === 'multipart/form-data') {
235
+ if (!(input.body instanceof FormData))
236
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId,
237
+ message: 'This operation requires a FormData body containing a real binary file.' });
238
+ body = input.body;
239
+ }
240
+ else {
241
+ if (input.body instanceof FormData || input.body instanceof Blob || input.body instanceof ArrayBuffer || ArrayBuffer.isView(input.body)) {
242
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId, message: 'This operation requires a JSON body.' });
243
+ }
244
+ headers['content-type'] = 'application/json';
245
+ body = JSON.stringify(input.body);
246
+ }
247
+ }
248
+ const environmentOperation = op.service === 'hives' && /_project_env(?:ironment)?$/.test(operationId);
249
+ const secretOperation = op.service === 'hives' && (/_secrets?$/.test(operationId) || environmentOperation);
250
+ const functionOperation = op.service === 'hives' && (op.rawResponse || /_function(?:s|_async)?$/.test(operationId));
251
+ let res;
252
+ try {
253
+ res = await this.fetchImpl(url, { method: op.method, headers, body, signal: init.signal,
254
+ ...(op.service === 'hives' || op.service === 'flocks' || runnerGrant ? { cache: 'no-store', redirect: op.rawResponse && !runnerGrant ? 'manual' : 'error' } : {}) });
255
+ }
256
+ catch (error) {
257
+ if (runnerGrant)
258
+ throw runnerGrantTransportError();
259
+ if (functionOperation)
260
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
261
+ message: 'Hives function transport failed. Keep the original invocation key and reconcile its operation before retrying.' });
262
+ if (!secretOperation)
263
+ throw error;
264
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
265
+ message: 'Hives secret transport failed. Redirects are refused; check the service address and retry.' });
266
+ }
267
+ if (runnerGrant)
268
+ return runnerGrantResponse(res, runnerGrant);
269
+ // A raw (binary) answer outside Hives, e.g. a Panes screenshot: a success is the bytes; a
270
+ // failure takes the ordinary error path below.
271
+ if (op.rawResponse && op.service !== 'hives' && res.ok)
272
+ return res;
273
+ if (op.rawResponse && /^exec_[a-f0-9]{32}$/.test(res.headers.get('x-execution-id') ?? '')) {
274
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers: hivesFunctionResponseHeaders(res.headers) });
275
+ }
276
+ if (op.rawResponse && op.service === 'hives' && res.headers.has('x-hives-operation-id')) {
277
+ // 5xx stays invalid_response below: its outcome is uncertain, so keep the key and reconcile.
278
+ const copy = res.status >= 400 && res.status < 500 ? res.clone() : undefined;
279
+ const error = await hivesOperationError(res);
280
+ if (error) {
281
+ void copy?.body?.cancel().catch(() => { });
282
+ throw error;
283
+ }
284
+ // A refusal envelope that is not an operation receipt keeps its own status, code and request id (finding G2).
285
+ const detail = copy ? await hivesErrorDetail(copy) : {};
286
+ if (detail.code !== undefined) {
287
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, operationId, code: detail.code,
288
+ message: detail.message ?? `Hives refused this invocation (${res.status}). Keep the original idempotency key and read its operation status before retrying.`,
289
+ requestId: res.headers.get('x-request-id') ?? detail.requestId });
290
+ }
291
+ throw new GenesisError({ status: res.status, type: 'invalid_response', operationId,
292
+ message: 'Hives operation status was not confirmed. Keep the original idempotency key and reconcile its operation.' });
293
+ }
294
+ if (op.rawResponse && res.ok)
295
+ throw new GenesisError({ status: res.status, type: 'invalid_response', operationId,
296
+ message: 'Hives did not confirm a completed guest execution. Keep the original invocation key and reconcile its operation.' });
297
+ if (functionOperation && !res.ok) {
298
+ // Keep the service's own refusal code and text (findings G3, G4); the fixed texts are fallbacks only.
299
+ const detail = await hivesErrorDetail(res);
300
+ const invocation = op.rawResponse === true;
301
+ const scope = detail.code === undefined || /scope/i.test(detail.code);
302
+ const message = detail.code !== undefined && detail.message !== undefined && !(res.status === 403 && scope) ? detail.message
303
+ : res.status === 401 ? 'Genesis credential rejected. Sign in again.'
304
+ : res.status === 403 ? (scope ? 'Missing the authorized Hives scope for this function action.' : `Hives refused this ${invocation ? 'invocation' : 'function action'} (${detail.code}).`)
305
+ : res.status === 404 ? 'Function/deployment, project or artifact not found in the authenticated organization and project.'
306
+ : res.status === 409 ? (invocation ? `Hives refused this invocation as a conflict${detail.code ? ` (${detail.code})` : ''}. Read the target's current state before retrying.` : 'Function mutation conflicted. Refresh its metadata before retrying.')
307
+ : res.status === 400 || res.status === 422 ? 'Invalid function request. Check artifact, resource bounds and guest request syntax.'
308
+ : res.status === 413 ? 'Function request exceeds a body or serialized guest envelope limit.'
309
+ : res.status >= 300 && res.status < 400 ? 'Unexpected function service redirect. No redirect was followed.'
310
+ : `Hives function operation failed (${res.status}). Refresh and retry.`;
311
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, operationId, message, code: detail.code,
312
+ requestId: res.headers.get('x-request-id') ?? detail.requestId });
313
+ }
314
+ if (!res.ok && secretOperation) {
315
+ const message = res.status === 401 ? 'Genesis credential rejected. Sign in again.'
316
+ : res.status === 403 ? 'Missing the authorized Hives scope for this action (hives:read or hives:write).'
317
+ : res.status === 404 ? 'Secret or project not found in your authenticated organization.'
318
+ : res.status === 409 ? 'A secret with this name already exists. Update it instead.'
319
+ : res.status === 400 || res.status === 422 ? 'Invalid secret request. Check names and UTF-8 value size.'
320
+ : res.status === 413 ? 'Secret request too large. Use a smaller batch.'
321
+ : res.status === 429 ? 'Too many requests. Wait briefly before retrying.'
322
+ : res.status === 503 ? 'Hives customer encryption is unavailable or stored secrets require protected migration.'
323
+ : `Hives secret operation failed (${res.status}). Refresh metadata and retry.`;
324
+ // Validation/provider bodies may reflect submitted plaintext. Never retain or log them.
325
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, message, operationId,
326
+ requestId: environmentOperation ? undefined : res.headers.get('x-request-id') ?? undefined });
327
+ }
328
+ if (!res.ok && isHivesQueueFundingOperation(operationId)) {
329
+ const receipt = await hivesQueueOperationError(res, input.operation_id);
330
+ if (receipt)
331
+ throw receipt;
332
+ }
333
+ if (!res.ok && isHivesResourceOperation(operationId))
334
+ throw await resourceErrorFromResponse(res, operationId);
335
+ if (!res.ok)
336
+ throw await GenesisError.fromResponse(res, operationId);
337
+ return res;
338
+ }
339
+ }
340
+ /**
341
+ * The refusal code, short message and request id of a Hives function/invocation error body. Reads at most
342
+ * 8 KiB and keeps nothing else: a body without a platform code may reflect guest request data.
343
+ */
344
+ async function hivesErrorDetail(res) {
345
+ if (!res.body)
346
+ return {};
347
+ const reader = res.body.getReader();
348
+ const chunks = [];
349
+ let size = 0;
350
+ try {
351
+ for (;;) {
352
+ const { value, done } = await reader.read();
353
+ if (done)
354
+ break;
355
+ size += value.length;
356
+ if (size > 8192) {
357
+ await reader.cancel().catch(() => { });
358
+ return {};
359
+ }
360
+ chunks.push(value);
361
+ }
362
+ const bytes = new Uint8Array(size);
363
+ let offset = 0;
364
+ for (const chunk of chunks) {
365
+ bytes.set(chunk, offset);
366
+ offset += chunk.length;
367
+ }
368
+ const body = JSON.parse(new TextDecoder().decode(bytes));
369
+ const e = body && typeof body === 'object' ? body.error : undefined;
370
+ // Only an error envelope: a top-level `code` belongs to an operation receipt, never to a refusal.
371
+ const raw = e && typeof e === 'object' ? e.code : typeof e === 'string' ? e : undefined;
372
+ const code = typeof raw === 'string' && /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/.test(raw) ? raw : undefined;
373
+ const text = e && typeof e === 'object' ? e.message : undefined;
374
+ const message = code && typeof text === 'string' && text.length <= 300 && !/[\u0000-\u001f\u007f]/.test(text) ? text : undefined;
375
+ const id = (e && typeof e === 'object' ? e.request_id : undefined) ?? body?.request_id;
376
+ return { code, message, requestId: typeof id === 'string' && /^[A-Za-z0-9_.:-]{1,128}$/.test(id) ? id : undefined };
377
+ }
378
+ catch {
379
+ return {};
380
+ }
381
+ finally {
382
+ reader.releaseLock();
383
+ }
384
+ }
@@ -0,0 +1,50 @@
1
+ export type GenesisContextSelection = {
2
+ organizationId: string;
3
+ } | {
4
+ organizationId: string;
5
+ projectId: string;
6
+ platformId: 'pf_console';
7
+ workspaceId: string;
8
+ fleetId: null;
9
+ environmentId: 'sandbox';
10
+ };
11
+ export interface GenesisContextSession {
12
+ principal: {
13
+ id: string;
14
+ kind: 'human';
15
+ email?: string;
16
+ };
17
+ session: {
18
+ id: string;
19
+ principalKind: 'human';
20
+ accessToken: string;
21
+ issuer: string;
22
+ audience: string;
23
+ issuedAt: string;
24
+ expiresAt: string;
25
+ organizationId: string;
26
+ tenantId?: string;
27
+ projectId?: string | null;
28
+ platformId?: string | null;
29
+ workspaceId?: string | null;
30
+ fleetId?: string | null;
31
+ resourceEnvironment?: string | null;
32
+ };
33
+ tenant: {
34
+ organizationId: string;
35
+ projectId?: string | null;
36
+ platformId?: string | null;
37
+ workspaceId?: string | null;
38
+ fleetId?: string | null;
39
+ environmentId?: string | null;
40
+ };
41
+ refresh_token: string;
42
+ }
43
+ /** Response consistency only: Auth verifies credentials, membership and IAM. */
44
+ export declare function checkedGenesisContextSession(value: unknown, priorToken: string, selection: GenesisContextSelection, now?: number): GenesisContextSession;
45
+ /** One authoritative tenant-context remint. Persist both returned tokens together before using the selection. No org header or local grant is created. */
46
+ export declare function selectGenesisContext(selection: GenesisContextSelection, options: {
47
+ credential: () => Promise<string | undefined>;
48
+ fetch?: typeof fetch;
49
+ signal?: AbortSignal;
50
+ }): Promise<GenesisContextSession>;
@@ -0,0 +1,153 @@
1
+ import { GenesisError } from './errors.js';
2
+ const AUTH = 'https://auth.life.one';
3
+ const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
4
+ const id = (v, prefix) => typeof v === 'string' && new RegExp('^' + prefix + '_[A-Za-z0-9_-]{1,128}$').exec(v)?.[0] === v;
5
+ const secret = (v) => typeof v === 'string' && v.length > 0 && v.length <= 16_384 && !/[\s,\x00-\x1f\x7f]/.test(v);
6
+ function fail(status = 0) { throw new GenesisError({ status, type: 'context_unconfirmed', message: 'One account did not confirm this context. No automatic retry was made.' }); }
7
+ function claims(token) {
8
+ if (!secret(token))
9
+ return fail();
10
+ try {
11
+ const parts = token.split('.');
12
+ if (parts.length !== 3 || parts.some(p => !p || /[^A-Za-z0-9_-]/.test(p)))
13
+ return fail();
14
+ const json = atob(parts[1].replaceAll('-', '+').replaceAll('_', '/'));
15
+ const value = object(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(json, c => c.charCodeAt(0)))));
16
+ if (!value)
17
+ return fail();
18
+ return value;
19
+ }
20
+ catch {
21
+ return fail();
22
+ }
23
+ }
24
+ function audiences(value) {
25
+ const values = Array.isArray(value) ? value : [value];
26
+ return values.length && values.every(v => typeof v === 'string' && v.length > 0 && v.length <= 256) ? values : fail();
27
+ }
28
+ function human(token, now) {
29
+ const c = claims(token);
30
+ if (c.iss !== AUTH || c.kind !== 'human' || !id(c.sub, 'h') || c.tid !== c.sub || !id(c.sid, 'sess')
31
+ || !Number.isSafeInteger(c.exp) || c.exp <= now || c.cnf !== undefined || c.cap !== undefined || c.obo !== undefined)
32
+ return fail(401);
33
+ return c;
34
+ }
35
+ /** Response consistency only: Auth verifies credentials, membership and IAM. */
36
+ export function checkedGenesisContextSession(value, priorToken, selection, now = Date.now() / 1000) {
37
+ const prior = human(priorToken, now), root = object(value), p = object(root?.principal), s = object(root?.session), t = object(root?.tenant);
38
+ if (!root || !p || !s || !t || p.kind !== 'human' || p.id !== prior.sub || s.principalKind !== 'human' || !id(s.id, 'sess')
39
+ || s.issuer !== AUTH || !secret(s.accessToken) || !secret(root.refresh_token) || s.organizationId !== selection.organizationId
40
+ || t.organizationId !== selection.organizationId || typeof s.audience !== 'string' || typeof s.issuedAt !== 'string' || typeof s.expiresAt !== 'string')
41
+ return fail();
42
+ const next = human(s.accessToken, now), aud = audiences(next.aud), previousAud = audiences(prior.aud);
43
+ if (s.id === prior.sid || next.sub !== prior.sub || next.sid !== s.id || next.org !== selection.organizationId || !aud.includes(s.audience) || !previousAud.includes(s.audience)
44
+ || !Number.isFinite(Date.parse(s.issuedAt)) || !Number.isFinite(Date.parse(s.expiresAt)) || Date.parse(s.issuedAt) / 1000 > now + 60
45
+ || Date.parse(s.expiresAt) / 1000 <= now || Date.parse(s.expiresAt) <= Date.parse(s.issuedAt)
46
+ || (s.tenantId !== undefined && s.tenantId !== null && s.tenantId !== prior.sub))
47
+ return fail();
48
+ // Validate optional projections even for an organization-only remint. Never
49
+ // cast unvalidated provider fields into a public selected-context result.
50
+ const fields = [['projectId', 'pid', 'pr'], ['platformId', 'pfid', 'pf'], ['workspaceId', 'wid', 'w'], ['fleetId', 'flid', 'fl']];
51
+ for (const [name, claim, prefix] of fields) {
52
+ if ([s[name], t[name], next[claim]].some(v => v !== undefined && v !== null && !id(v, prefix))
53
+ || (s[name] ?? null) !== (t[name] ?? null) || (s[name] ?? null) !== (next[claim] ?? null))
54
+ return fail();
55
+ }
56
+ if (![undefined, null, 'sandbox', 'live'].includes(s.resourceEnvironment)
57
+ || (s.resourceEnvironment ?? null) !== (t.environmentId ?? null))
58
+ return fail();
59
+ if ('projectId' in selection) {
60
+ for (const [name, claim] of [['projectId', 'pid'], ['platformId', 'pfid'], ['workspaceId', 'wid'], ['fleetId', 'flid']]) {
61
+ if ((s[name] ?? null) !== selection[name] || (t[name] ?? null) !== selection[name] || (next[claim] ?? null) !== selection[name])
62
+ return fail();
63
+ }
64
+ if (s.resourceEnvironment !== selection.environmentId || t.environmentId !== selection.environmentId)
65
+ return fail();
66
+ }
67
+ return { principal: { id: p.id, kind: 'human', ...(typeof p.email === 'string' ? { email: p.email } : {}) },
68
+ session: { id: s.id, principalKind: 'human', accessToken: s.accessToken, issuer: AUTH, audience: s.audience, issuedAt: s.issuedAt, expiresAt: s.expiresAt,
69
+ organizationId: s.organizationId, tenantId: prior.sub, projectId: s.projectId,
70
+ platformId: s.platformId, workspaceId: s.workspaceId,
71
+ fleetId: s.fleetId, resourceEnvironment: s.resourceEnvironment },
72
+ tenant: { organizationId: t.organizationId, projectId: t.projectId, platformId: t.platformId,
73
+ workspaceId: t.workspaceId, fleetId: t.fleetId, environmentId: t.environmentId },
74
+ refresh_token: root.refresh_token };
75
+ }
76
+ /** One authoritative tenant-context remint. Persist both returned tokens together before using the selection. No org header or local grant is created. */
77
+ export async function selectGenesisContext(selection, options) {
78
+ const requested = { ...selection };
79
+ const keys = Object.keys(requested), full = 'projectId' in requested;
80
+ if (!id(requested.organizationId, 'o') || keys.some(k => !(full ? ['organizationId', 'projectId', 'platformId', 'workspaceId', 'fleetId', 'environmentId'] : ['organizationId']).includes(k))
81
+ || (full && (!id(requested.projectId, 'pr') || !id(requested.workspaceId, 'w') || requested.platformId !== 'pf_console' || requested.fleetId !== null || requested.environmentId !== 'sandbox')))
82
+ return fail(400);
83
+ const controller = new AbortController(), cancel = () => controller.abort();
84
+ options.signal?.addEventListener('abort', cancel, { once: true });
85
+ if (options.signal?.aborted)
86
+ cancel();
87
+ const timer = setTimeout(cancel, 30_000);
88
+ let reader;
89
+ const stopped = new Promise((_, reject) => controller.signal.addEventListener('abort', () => { void reader?.cancel().catch(() => { }); reject(new Error('cancelled')); }, { once: true }));
90
+ try {
91
+ controller.signal.throwIfAborted();
92
+ const token = await Promise.race([options.credential(), stopped]);
93
+ if (!token)
94
+ return fail(401);
95
+ human(token, Date.now() / 1000);
96
+ controller.signal.throwIfAborted();
97
+ const response = await Promise.race([(options.fetch ?? fetch)(AUTH + '/v4/auth/tenant-context', { method: 'POST', headers: { authorization: 'Bearer ' + token, accept: 'application/json', 'content-type': 'application/json' },
98
+ body: JSON.stringify(requested), signal: controller.signal, redirect: 'error', cache: 'no-store' }).then(value => {
99
+ if (controller.signal.aborted) {
100
+ void value.body?.cancel().catch(() => { });
101
+ throw new Error('cancelled');
102
+ }
103
+ return value;
104
+ }), stopped]);
105
+ if (!response.ok) {
106
+ void response.body?.cancel().catch(() => { });
107
+ return fail(response.status);
108
+ }
109
+ if (!/^application\/json(?:;|$)/i.test(response.headers.get('content-type') ?? '')) {
110
+ void response.body?.cancel().catch(() => { });
111
+ return fail();
112
+ }
113
+ reader = response.body?.getReader();
114
+ if (!reader)
115
+ return fail();
116
+ const parts = [];
117
+ let size = 0;
118
+ for (;;) {
119
+ const next = await Promise.race([reader.read(), stopped]);
120
+ if (next.done)
121
+ break;
122
+ size += next.value.length;
123
+ if (size > 65536)
124
+ return fail();
125
+ parts.push(next.value);
126
+ }
127
+ const bytes = new Uint8Array(size);
128
+ let at = 0;
129
+ for (const part of parts) {
130
+ bytes.set(part, at);
131
+ at += part.length;
132
+ }
133
+ controller.signal.throwIfAborted();
134
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
135
+ return checkedGenesisContextSession(value, token, requested);
136
+ }
137
+ catch (error) {
138
+ if (error instanceof GenesisError)
139
+ throw error;
140
+ return fail();
141
+ }
142
+ finally {
143
+ clearTimeout(timer);
144
+ options.signal?.removeEventListener('abort', cancel);
145
+ if (reader) {
146
+ void reader.cancel().catch(() => { });
147
+ try {
148
+ reader.releaseLock();
149
+ }
150
+ catch { /* cancelled pending read */ }
151
+ }
152
+ }
153
+ }