@astrale-os/kernel-client 1.0.0-beta.5 → 1.0.0-beta.50

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 (206) hide show
  1. package/dist/auth/authorization.d.ts +10 -5
  2. package/dist/auth/authorization.js +14 -1
  3. package/dist/auth/index.d.ts +1 -0
  4. package/dist/client/admission.js +3 -1
  5. package/dist/client/client.d.ts +70 -4
  6. package/dist/client/client.js +209 -32
  7. package/dist/client/index.d.ts +3 -3
  8. package/dist/client/index.js +2 -2
  9. package/dist/client/level.d.ts +58 -0
  10. package/dist/client/level.js +159 -0
  11. package/dist/client/request.d.ts +7 -2
  12. package/dist/client/request.js +11 -7
  13. package/dist/client/result.d.ts +14 -1
  14. package/dist/client/result.js +19 -8
  15. package/dist/client/routing-control.d.ts +11 -15
  16. package/dist/client/routing-control.js +21 -29
  17. package/dist/errors/index.d.ts +3 -0
  18. package/dist/errors/index.js +3 -0
  19. package/dist/errors/inexpressible-error.d.ts +23 -0
  20. package/dist/errors/inexpressible-error.js +26 -0
  21. package/dist/errors/query-input.d.ts +47 -0
  22. package/dist/errors/query-input.js +85 -0
  23. package/dist/errors/refusal.d.ts +12 -0
  24. package/dist/errors/refusal.js +44 -6
  25. package/dist/errors/response-too-large-error.d.ts +11 -0
  26. package/dist/errors/response-too-large-error.js +15 -0
  27. package/dist/errors/stale-route-error.d.ts +1 -1
  28. package/dist/errors/stale-route-error.js +1 -1
  29. package/dist/{schema → execution}/admission.d.ts +2 -2
  30. package/dist/{schema → execution}/admission.js +2 -2
  31. package/dist/{session/execution.d.ts → execution/contracts.d.ts} +22 -34
  32. package/dist/execution/contracts.js +1 -0
  33. package/dist/execution/deadline.d.ts +18 -0
  34. package/dist/execution/deadline.js +25 -0
  35. package/dist/execution/execution.d.ts +61 -0
  36. package/dist/execution/execution.js +132 -0
  37. package/dist/execution/index.d.ts +4 -0
  38. package/dist/execution/index.js +3 -0
  39. package/dist/graph/domain/binding.d.ts +2 -2
  40. package/dist/graph/domain/binding.js +20 -17
  41. package/dist/graph/domain/conformance.d.ts +12 -0
  42. package/dist/graph/domain/conformance.js +18 -0
  43. package/dist/graph/domain/index.d.ts +1 -0
  44. package/dist/graph/domain/index.js +1 -1
  45. package/dist/graph/domain/provenance.d.ts +0 -2
  46. package/dist/graph/domain/provenance.js +0 -4
  47. package/dist/graph/graph.d.ts +17 -3
  48. package/dist/graph/graph.js +4 -1
  49. package/dist/graph/index.d.ts +3 -3
  50. package/dist/graph/index.js +1 -1
  51. package/dist/graph/page-contract.d.ts +66 -1
  52. package/dist/graph/provenance.d.ts +4 -5
  53. package/dist/graph/provenance.js +5 -6
  54. package/dist/graph/query.d.ts +10 -4
  55. package/dist/graph/query.js +144 -5
  56. package/dist/graph/query.typecheck.d.ts +81 -0
  57. package/dist/graph/query.typecheck.js +34 -0
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +1 -1
  60. package/dist/schema/contracts.d.ts +54 -79
  61. package/dist/schema/index.d.ts +2 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +36 -64
  64. package/dist/schema/installation.js +67 -131
  65. package/dist/schema/schema.d.ts +10 -16
  66. package/dist/schema/schema.js +57 -34
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +36 -32
  70. package/dist/session/content/api.d.ts +20 -2
  71. package/dist/session/content/api.js +17 -7
  72. package/dist/session/content/files.d.ts +12 -0
  73. package/dist/session/content/files.js +47 -0
  74. package/dist/session/content/index.d.ts +1 -1
  75. package/dist/session/content/input.d.ts +13 -2
  76. package/dist/session/content/input.js +25 -4
  77. package/dist/session/content/retry.d.ts +5 -1
  78. package/dist/session/content/retry.js +21 -31
  79. package/dist/session/context/index.d.ts +2 -2
  80. package/dist/session/context/index.js +2 -2
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/context/policy.d.ts +2 -0
  84. package/dist/session/context/policy.js +6 -3
  85. package/dist/session/credential/credentials.d.ts +2 -1
  86. package/dist/session/credential/credentials.js +62 -29
  87. package/dist/session/discovery/bundle.d.ts +13 -4
  88. package/dist/session/discovery/bundle.js +85 -36
  89. package/dist/session/discovery/discovery.d.ts +1 -1
  90. package/dist/session/discovery/discovery.js +8 -11
  91. package/dist/session/discovery/index.d.ts +1 -0
  92. package/dist/session/discovery/index.js +5 -1
  93. package/dist/session/discovery/release.d.ts +2 -0
  94. package/dist/session/discovery/release.js +34 -31
  95. package/dist/session/discovery/response.d.ts +4 -0
  96. package/dist/session/discovery/response.js +10 -6
  97. package/dist/session/discovery/snapshot.d.ts +5 -1
  98. package/dist/session/discovery/transport.d.ts +37 -3
  99. package/dist/session/discovery/transport.js +62 -1
  100. package/dist/session/durable.d.ts +13 -0
  101. package/dist/session/durable.js +39 -0
  102. package/dist/session/exchange/exchange.d.ts +3 -2
  103. package/dist/session/exchange/exchange.js +10 -7
  104. package/dist/session/exchange/index.d.ts +1 -1
  105. package/dist/session/exchange/index.js +1 -1
  106. package/dist/session/exchange/presentation.js +28 -10
  107. package/dist/session/exchange/source.d.ts +7 -7
  108. package/dist/session/exchange/source.js +26 -27
  109. package/dist/session/index.d.ts +5 -4
  110. package/dist/session/index.js +0 -1
  111. package/dist/session/options.d.ts +4 -2
  112. package/dist/session/options.js +3 -3
  113. package/dist/session/reference.d.ts +27 -6
  114. package/dist/session/reference.js +18 -3
  115. package/dist/session/retry.d.ts +12 -0
  116. package/dist/session/retry.js +23 -0
  117. package/dist/session/routing/auth.d.ts +9 -3
  118. package/dist/session/routing/auth.js +4 -3
  119. package/dist/session/routing/cache.d.ts +12 -5
  120. package/dist/session/routing/cache.js +56 -48
  121. package/dist/session/routing/dispatch.d.ts +26 -3
  122. package/dist/session/routing/dispatch.js +112 -69
  123. package/dist/session/routing/envelope.d.ts +3 -3
  124. package/dist/session/routing/index.d.ts +1 -1
  125. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  126. package/dist/session/routing/legacy/release-route.js +6 -0
  127. package/dist/session/routing/recovery.d.ts +3 -6
  128. package/dist/session/routing/recovery.js +3 -14
  129. package/dist/session/routing/request.d.ts +2 -1
  130. package/dist/session/routing/request.js +2 -1
  131. package/dist/session/routing/result.d.ts +1 -1
  132. package/dist/session/routing/result.js +5 -1
  133. package/dist/session/routing/store.js +4 -5
  134. package/dist/session/session.d.ts +31 -5
  135. package/dist/session/session.js +70 -22
  136. package/dist/session/session.typecheck.js +20 -6
  137. package/dist/session/views/index.d.ts +2 -2
  138. package/dist/session/views/index.js +2 -2
  139. package/dist/session/views/kernel.d.ts +31 -0
  140. package/dist/session/views/kernel.js +30 -0
  141. package/dist/session/views/legacy/catalog.d.ts +21 -0
  142. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  143. package/dist/session/views/legacy/index.d.ts +14 -0
  144. package/dist/session/views/legacy/index.js +14 -0
  145. package/dist/session/views/legacy/resolve.d.ts +46 -0
  146. package/dist/session/views/legacy/resolve.js +83 -0
  147. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  148. package/dist/session/views/legacy/unplaced.js +26 -0
  149. package/dist/session/views/read.d.ts +49 -0
  150. package/dist/session/views/read.js +148 -0
  151. package/dist/session/views/view.d.ts +48 -0
  152. package/dist/session/views/view.js +74 -0
  153. package/dist/store/memory.d.ts +1 -3
  154. package/dist/store/memory.js +61 -112
  155. package/dist/store/shape.d.ts +33 -12
  156. package/dist/store/shape.js +125 -16
  157. package/dist/store/store.d.ts +6 -6
  158. package/dist/store/store.js +1 -1
  159. package/dist/transport/auto/decision.d.ts +28 -14
  160. package/dist/transport/auto/decision.js +39 -32
  161. package/dist/transport/auto/fallback.d.ts +1 -1
  162. package/dist/transport/auto/fallback.js +5 -10
  163. package/dist/transport/auto/transport.d.ts +10 -3
  164. package/dist/transport/auto/transport.js +41 -32
  165. package/dist/transport/deadline.d.ts +2 -0
  166. package/dist/transport/deadline.js +18 -0
  167. package/dist/transport/failure.d.ts +28 -1
  168. package/dist/transport/failure.js +63 -1
  169. package/dist/transport/http/admission.js +8 -35
  170. package/dist/transport/http/binary-request.d.ts +44 -0
  171. package/dist/transport/http/binary-request.js +110 -0
  172. package/dist/transport/http/binary.js +3 -3
  173. package/dist/transport/http/byte-stream.d.ts +2 -1
  174. package/dist/transport/http/byte-stream.js +12 -8
  175. package/dist/transport/http/configuration.d.ts +7 -0
  176. package/dist/transport/http/configuration.js +2 -0
  177. package/dist/transport/http/index.d.ts +1 -1
  178. package/dist/transport/http/index.js +1 -1
  179. package/dist/transport/http/response.d.ts +13 -1
  180. package/dist/transport/http/response.js +22 -9
  181. package/dist/transport/http/stream.d.ts +8 -13
  182. package/dist/transport/http/stream.js +34 -81
  183. package/dist/transport/http/transport.d.ts +14 -1
  184. package/dist/transport/http/transport.js +110 -35
  185. package/dist/transport/http/unprocessed.d.ts +5 -0
  186. package/dist/transport/http/unprocessed.js +28 -0
  187. package/dist/transport/index.d.ts +2 -1
  188. package/dist/transport/index.js +2 -1
  189. package/dist/transport/level.d.ts +42 -0
  190. package/dist/transport/level.js +58 -0
  191. package/dist/transport/stream.d.ts +52 -0
  192. package/dist/transport/stream.js +101 -0
  193. package/dist/transport/transport.d.ts +33 -0
  194. package/dist/transport/unary.d.ts +9 -0
  195. package/dist/transport/unary.js +36 -0
  196. package/dist/transport/websocket/connection.d.ts +13 -4
  197. package/dist/transport/websocket/connection.js +123 -96
  198. package/dist/transport/websocket/exchange.d.ts +15 -19
  199. package/dist/transport/websocket/exchange.js +87 -183
  200. package/dist/transport/websocket/transport.d.ts +19 -1
  201. package/dist/transport/websocket/transport.js +50 -21
  202. package/package.json +9 -7
  203. package/dist/session/execution.js +0 -34
  204. package/dist/session/views/catalog.d.ts +0 -19
  205. package/dist/session/views/resolve.d.ts +0 -13
  206. package/dist/session/views/resolve.js +0 -21
@@ -2,14 +2,17 @@ import * as codecs from '@astrale-os/kernel-protocol/codecs';
2
2
  import * as releaseCodec from '@astrale-os/kernel-protocol/release';
3
3
  import { ClientError } from '../../errors/index.js';
4
4
  import { allowEndpoint } from '../context/index.js';
5
- import { boundedResponse, requireExactResponse } from './response.js';
6
- import { runAcquisition } from './transport.js';
5
+ import { fetchDocument } from './transport.js';
7
6
  /**
8
7
  * Conditionally revalidate by release digest. Only an exact 404 means absence;
9
8
  * all other unsuccessful responses and Fetch failures remain errors.
10
9
  */
11
10
  export class ReleaseDiscovery {
12
11
  options;
12
+ hints = new WeakMap();
13
+ hintFor(release) {
14
+ return this.hints.get(release);
15
+ }
13
16
  release;
14
17
  revision = 0;
15
18
  constructor(options) {
@@ -26,7 +29,15 @@ export class ReleaseDiscovery {
26
29
  const discovered = await this.fetch(operation, previous);
27
30
  if (revision !== this.revision)
28
31
  return this.revalidate(operation);
29
- const retained = previous?.digest === discovered.digest ? previous : discovered;
32
+ const retained = previous?.digest === discovered.release.digest ? previous : discovered.release;
33
+ // A 304 updates cached response headers only when the validator actually supplies them.
34
+ if (discovered.link !== undefined) {
35
+ const hint = releaseCodec.compactBundleHint(this.options.kernel, retained.schema.bundle.href, discovered.link);
36
+ if (hint === undefined)
37
+ this.hints.delete(retained);
38
+ else
39
+ this.hints.set(retained, hint);
40
+ }
30
41
  this.release = retained;
31
42
  return retained;
32
43
  }
@@ -37,45 +48,37 @@ export class ReleaseDiscovery {
37
48
  async fetch(operation, previous) {
38
49
  const url = releaseCodec.url(this.options.kernel);
39
50
  allowEndpoint(url, this.options.policy);
40
- const response = await runAcquisition(operation, 'release', 'unknown', 'Kernel release could not be retrieved.', (signal) => this.options.fetch(url, {
41
- headers: {
42
- accept: releaseCodec.MEDIA_TYPE,
43
- ...(previous === undefined ? {} : { 'if-none-match': `"${previous.digest}"` }),
44
- },
45
- redirect: 'manual',
46
- signal,
47
- }));
48
- requireExactResponse(response, url, 'Release discovery');
49
- if (response.status === 404) {
50
- // Cleanup must not hold discovery open on an injected body cancellation.
51
- void response.body?.cancel().catch(() => undefined);
52
- throw new ClientError('Release discovery returned HTTP 404.');
53
- }
54
- if (response.status === 304) {
51
+ const fetched = await fetchDocument(operation, this.options.fetch, {
52
+ resource: 'release',
53
+ label: 'Release discovery',
54
+ url,
55
+ mediaType: releaseCodec.MEDIA_TYPE,
56
+ mediaTypeMismatch: 'Release response media type differs from the DomainRelease v4 media type.',
57
+ maximumBytes: this.options.maximumBytes,
58
+ ...(previous === undefined ? {} : { ifNoneMatch: `"${previous.digest}"` }),
59
+ notModified: true,
60
+ unavailable: [404],
61
+ });
62
+ if (fetched.kind === 'unavailable')
63
+ throw fetched.error;
64
+ if (fetched.kind === 'not-modified') {
55
65
  if (previous === undefined) {
56
66
  throw new ClientError('Release discovery returned an unexpected not-modified response.');
57
67
  }
58
- const etag = response.headers.get('etag');
59
- if (etag !== null && etag !== `"${previous.digest}"`) {
68
+ if (fetched.headers.has('etag') && fetched.headers.get('etag') !== `"${previous.digest}"`) {
60
69
  throw new ClientError('Release not-modified ETag differs from the retained release digest.');
61
70
  }
62
- return previous;
63
- }
64
- if (!response.ok) {
65
- throw new ClientError(`Release discovery returned HTTP ${response.status}.`);
66
- }
67
- if (response.headers.get('content-type') !== releaseCodec.MEDIA_TYPE) {
68
- throw new ClientError('Release response media type differs from the DomainRelease v4 media type.');
71
+ const link = fetched.headers.get('link');
72
+ return link === null ? { release: previous } : { release: previous, link };
69
73
  }
70
- const body = await runAcquisition(operation, 'release', 'receive', 'Kernel release response could not be read.', (signal) => boundedResponse(response, this.options.maximumBytes, signal));
71
- const admitted = releaseCodec.accept(codecs.json.decode(body));
74
+ const admitted = releaseCodec.accept(codecs.json.decode(await fetched.read()));
72
75
  if (admitted.identity.issuer !== this.options.kernel) {
73
76
  throw new ClientError('Release issuer differs from the requested Kernel issuer.');
74
77
  }
75
- const etag = response.headers.get('etag');
78
+ const etag = fetched.headers.get('etag');
76
79
  if (etag !== null && etag !== `"${admitted.digest}"`) {
77
80
  throw new ClientError('Release response ETag differs from its release digest.');
78
81
  }
79
- return admitted;
82
+ return { release: admitted, link: fetched.headers.get('link') };
80
83
  }
81
84
  }
@@ -1,3 +1,7 @@
1
+ import { ClientError } from '../../errors/index.js';
2
+ /** A malformed or oversized artifact response whose alternate can be discarded. */
3
+ export declare class DocumentRepresentationError extends ClientError {
4
+ }
1
5
  /** Read external bytes within one Session operation's byte and lifetime bounds. */
2
6
  export declare function boundedResponse(response: Response, maximum: number, signal: AbortSignal): Promise<Uint8Array>;
3
7
  export declare function requireExactResponse(response: Response, expected: string, label: string): void;
@@ -1,14 +1,18 @@
1
1
  import { ClientError } from '../../errors/index.js';
2
+ /** A malformed or oversized artifact response whose alternate can be discarded. */
3
+ export class DocumentRepresentationError extends ClientError {
4
+ }
2
5
  /** Read external bytes within one Session operation's byte and lifetime bounds. */
3
6
  export async function boundedResponse(response, maximum, signal) {
4
7
  const declared = response.headers.get('content-length');
5
8
  if (declared !== null) {
6
9
  const length = Number(declared);
7
- if (!Number.isSafeInteger(length) || length < 0) {
8
- throw new ClientError('Response Content-Length is invalid.');
10
+ if (!/^\d+$/u.test(declared) || !Number.isSafeInteger(length) || length > maximum) {
11
+ void response.body?.cancel().catch(() => undefined);
12
+ throw new DocumentRepresentationError(length > maximum
13
+ ? 'Response exceeds its byte limit.'
14
+ : 'Response Content-Length is invalid.');
9
15
  }
10
- if (length > maximum)
11
- throw new ClientError('Response exceeds its byte limit.');
12
16
  }
13
17
  if (response.body === null)
14
18
  return new Uint8Array();
@@ -29,8 +33,8 @@ export async function boundedResponse(response, maximum, signal) {
29
33
  break;
30
34
  total += next.value.byteLength;
31
35
  if (total > maximum) {
32
- await reader.cancel('response exceeds byte limit').catch(() => undefined);
33
- throw new ClientError('Response exceeds its byte limit.');
36
+ void reader.cancel('response exceeds byte limit').catch(() => undefined);
37
+ throw new DocumentRepresentationError('Response exceeds its byte limit.');
34
38
  }
35
39
  chunks.push(next.value);
36
40
  }
@@ -1,12 +1,16 @@
1
1
  import type { IssuerId } from '@astrale-os/kernel-core/auth/issuer';
2
2
  import type { bundle } from '@astrale-os/kernel-dsl/v1';
3
- import type { ViewCatalog } from '../views/index.js';
3
+ import type { ViewCatalog } from '../views/legacy/index.js';
4
4
  import type { IntrinsicRelease } from './release.js';
5
5
  /** Coherent public observation acquired through one Client Session at one intrinsic release. */
6
6
  export interface SessionSnapshot {
7
7
  readonly kernel: IssuerId;
8
8
  readonly release: IntrinsicRelease;
9
9
  readonly bundle: bundle.Bundle;
10
+ /**
11
+ * @deprecated The root Domain's Views as its Release binds them, each with its Release digest.
12
+ * Read them with `ClientSession.view({ domain })`.
13
+ */
10
14
  readonly views: ViewCatalog;
11
15
  }
12
16
  export declare function createSessionSnapshot(kernel: IssuerId, release: IntrinsicRelease, artifact: bundle.Bundle, views: ViewCatalog): SessionSnapshot;
@@ -1,4 +1,38 @@
1
- import type { AcquisitionResource, TransportPhase } from '../../errors/index.js';
1
+ import type { AcquisitionResource } from '../../errors/index.js';
2
+ import type { Fetch } from '../../transport/http/index.js';
2
3
  import type { SessionOperation } from '../context/index.js';
3
- /** Normalize only unknown failures from one injected acquisition capability. */
4
- export declare function runAcquisition<Result>(operation: SessionOperation, resource: AcquisitionResource, phase: Extract<TransportPhase, 'receive' | 'unknown'>, message: string, task: (signal: AbortSignal) => Result | PromiseLike<Result>): Promise<Result>;
4
+ import { ClientError } from '../../errors/index.js';
5
+ /** One public Session document requested from an endpoint the Session policy already allows. */
6
+ export interface DocumentRequest<NotModified extends boolean = boolean> {
7
+ readonly resource: AcquisitionResource;
8
+ /** Names the request in status and URL errors, as in `Release discovery returned HTTP 500.` */
9
+ readonly label: string;
10
+ readonly url: string;
11
+ /** Both the `accept` header and the only admitted `content-type`. */
12
+ readonly mediaType: string;
13
+ readonly mediaTypeMismatch: string;
14
+ readonly maximumBytes: number;
15
+ readonly status?: 200;
16
+ readonly ifNoneMatch?: string;
17
+ readonly cache?: 'no-cache';
18
+ /** Whether a 304 answers the request instead of failing it. */
19
+ readonly notModified: NotModified;
20
+ /** Statuses that mean the document is no longer served, as opposed to a failed retrieval. */
21
+ readonly unavailable: readonly number[];
22
+ }
23
+ /** The answer to a public Session document request; 304 answers only a request that admits it. */
24
+ export type DocumentResponse<NotModified extends boolean = boolean> = {
25
+ readonly kind: 'document';
26
+ readonly headers: Headers;
27
+ discard(): void;
28
+ /** Read the body within the request's byte bound. */
29
+ read(): Promise<Uint8Array>;
30
+ } | {
31
+ readonly kind: 'unavailable';
32
+ readonly error: ClientError;
33
+ } | (NotModified extends true ? {
34
+ readonly kind: 'not-modified';
35
+ readonly headers: Headers;
36
+ } : never);
37
+ /** Fetch one public Session document and admit its exact URL, status and media type. */
38
+ export declare function fetchDocument<NotModified extends boolean>(operation: SessionOperation, fetch: Fetch, request: DocumentRequest<NotModified>): Promise<DocumentResponse<NotModified>>;
@@ -1,7 +1,68 @@
1
+ import { canonicalMediaType } from '@astrale-os/kernel-protocol/artifact';
2
+ import { COMPACT_BUNDLE_MEDIA_TYPE } from '@astrale-os/kernel-protocol/release';
1
3
  import { ClientError, TransportError } from '../../errors/index.js';
2
4
  import { runSessionOperation } from '../context/index.js';
5
+ import { boundedResponse, DocumentRepresentationError, requireExactResponse } from './response.js';
6
+ /** Fetch one public Session document and admit its exact URL, status and media type. */
7
+ export async function fetchDocument(operation, fetch, request) {
8
+ const { resource, label, url } = request;
9
+ const response = await runAcquisition(operation, resource, 'unknown', `Kernel ${resource} could not be retrieved.`, (signal) => fetch(url, {
10
+ headers: {
11
+ accept: request.mediaType,
12
+ ...(request.ifNoneMatch === undefined ? {} : { 'if-none-match': request.ifNoneMatch }),
13
+ },
14
+ // Omitting `cache` is the browser default; Workers reject the DOM-only 'default' mode.
15
+ ...(request.cache === undefined ? {} : { cache: request.cache }),
16
+ redirect: 'manual',
17
+ signal,
18
+ }));
19
+ requireExactResponse(response, url, label);
20
+ const status = `${label} returned HTTP ${response.status}.`;
21
+ if (request.unavailable.includes(response.status)) {
22
+ // Cleanup must not hold discovery open on an injected body cancellation.
23
+ void response.body?.cancel().catch(() => undefined);
24
+ return { kind: 'unavailable', error: new ClientError(status) };
25
+ }
26
+ if (request.notModified && response.status === 304) {
27
+ // `notModified` is true here, so the conditional member is present.
28
+ return {
29
+ kind: 'not-modified',
30
+ headers: response.headers,
31
+ };
32
+ }
33
+ if (!response.ok || (request.status !== undefined && response.status !== request.status)) {
34
+ void response.body?.cancel().catch(() => undefined);
35
+ throw new ClientError(status);
36
+ }
37
+ if (!matchesMediaType(response.headers.get('content-type'), request.mediaType)) {
38
+ void response.body?.cancel().catch(() => undefined);
39
+ throw new DocumentRepresentationError(request.mediaTypeMismatch);
40
+ }
41
+ return {
42
+ kind: 'document',
43
+ headers: response.headers,
44
+ discard: () => {
45
+ void response.body?.cancel().catch(() => undefined);
46
+ },
47
+ read: () => runAcquisition(operation, resource, 'receive', `Kernel ${resource} response could not be read.`, (signal) => boundedResponse(response, request.maximumBytes, signal)),
48
+ };
49
+ }
50
+ function matchesMediaType(actual, expected) {
51
+ if (actual === expected)
52
+ return true;
53
+ if (actual === null || expected !== COMPACT_BUNDLE_MEDIA_TYPE)
54
+ return false;
55
+ try {
56
+ return canonicalMediaType(actual) === expected;
57
+ }
58
+ catch (cause) {
59
+ if (cause instanceof TypeError)
60
+ return false;
61
+ throw cause;
62
+ }
63
+ }
3
64
  /** Normalize only unknown failures from one injected acquisition capability. */
4
- export async function runAcquisition(operation, resource, phase, message, task) {
65
+ async function runAcquisition(operation, resource, phase, message, task) {
5
66
  try {
6
67
  return await runSessionOperation(operation, task);
7
68
  }
@@ -0,0 +1,13 @@
1
+ import type { SessionOperation } from './context/index.js';
2
+ import type { SessionRequestOptions } from './routing/index.js';
3
+ /**
4
+ * Options of one typed invocation of a durable callable: the caller's key, or one created for this
5
+ * call. The key names the Execution, so every attempt of the call reaches the same one.
6
+ */
7
+ export declare function durableOptions(options: Readonly<SessionRequestOptions>): Readonly<SessionRequestOptions>;
8
+ /**
9
+ * Send a keyed durable invocation again while its outcome is unknown: a transport failure, sent or
10
+ * not, or the Kernel's `OUTCOME_UNKNOWN`. Its key makes the Kernel answer with the Execution a lost
11
+ * attempt recorded, marked `replayed`, instead of starting another.
12
+ */
13
+ export declare function attemptDurable<Result>(operation: SessionOperation, attempt: () => Promise<Result>): Promise<Result>;
@@ -0,0 +1,39 @@
1
+ import { CODES } from '@astrale-os/kernel-protocol/errors';
2
+ import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
3
+ import { ResponseError, TransportError } from '../errors/index.js';
4
+ import { retrySessionRequest } from './retry.js';
5
+ const FIRST_PAUSE_MS = 200;
6
+ /**
7
+ * Options of one typed invocation of a durable callable: the caller's key, or one created for this
8
+ * call. The key names the Execution, so every attempt of the call reaches the same one.
9
+ */
10
+ export function durableOptions(options) {
11
+ if (options.idempotencyKey !== undefined)
12
+ return options;
13
+ return Object.freeze({
14
+ ...options,
15
+ idempotencyKey: invocationProtocol.acceptIdempotencyKey(crypto.randomUUID()),
16
+ });
17
+ }
18
+ /**
19
+ * Send a keyed durable invocation again while its outcome is unknown: a transport failure, sent or
20
+ * not, or the Kernel's `OUTCOME_UNKNOWN`. Its key makes the Kernel answer with the Execution a lost
21
+ * attempt recorded, marked `replayed`, instead of starting another.
22
+ */
23
+ export function attemptDurable(operation, attempt) {
24
+ return retrySessionRequest(operation, pause, attempt);
25
+ }
26
+ /**
27
+ * The pause after failed attempt `failed`: 200 ms doubled at each attempt, unless the outcome is
28
+ * known or the call's deadline would pass first.
29
+ */
30
+ function pause(cause, failed, operation) {
31
+ if (!unknownOutcome(cause))
32
+ return undefined;
33
+ const ms = FIRST_PAUSE_MS * 2 ** (failed - 1);
34
+ return operation.deadline - Date.now() <= ms ? undefined : ms;
35
+ }
36
+ function unknownOutcome(cause) {
37
+ return ((cause instanceof TransportError && cause.context.kind === 'invocation') ||
38
+ (cause instanceof ResponseError && cause.code === CODES.OUTCOME_UNKNOWN));
39
+ }
@@ -7,6 +7,7 @@ import type { SessionOperation, SessionPolicy } from '../context/index.js';
7
7
  import type { SessionCredential } from '../credential/index.js';
8
8
  import type { EffectiveAuth, SessionAuth } from '../routing/index.js';
9
9
  import type { ExchangeRequest } from './options.js';
10
+ import type { Exhausted } from './source.js';
10
11
  /** Everything an exchange reaches: the Session's source Kernel and authority, and the Domain legs. */
11
12
  export interface ExchangeDependencies {
12
13
  readonly kernel: IssuerId;
@@ -37,9 +38,9 @@ export interface DomainExchangeRequest {
37
38
  }
38
39
  /**
39
40
  * Delegate the source caller to one Domain issuer and redeem that delegation at the issuer's
40
- * advertised endpoint for the Domain's credential to the source Kernel.
41
+ * advertised endpoint for the Domain's credential to the source Kernel, or find the source exhausted.
41
42
  */
42
- export declare function exchangeDomainCredential(dependencies: ExchangeDependencies, source: EffectiveAuth, request: DomainExchangeRequest, operation: SessionOperation): Promise<DomainCredential>;
43
+ export declare function exchangeDomainCredential(dependencies: ExchangeDependencies, source: EffectiveAuth, request: DomainExchangeRequest, operation: SessionOperation): Promise<DomainCredential | Exhausted>;
43
44
  /**
44
45
  * One Domain credential for a named Domain issuer, as `session.exchange` returns it. When the
45
46
  * request asks for more than the Session delegation, the credential covers that delegation, and the
@@ -3,10 +3,10 @@ import { identityApi } from '../../auth/identity.js';
3
3
  import { delegationCoverageMs } from '../credential/index.js';
4
4
  import { resolveAuth } from '../routing/index.js';
5
5
  import { redeem, tokenEndpoint } from './issuer.js';
6
- import { delegationTtl, isAuthority, renewing, sourceCaller, sourceExhausted } from './source.js';
6
+ import { delegationTtl, EXHAUSTED, renewing, sourceCaller, sourceExhausted } from './source.js';
7
7
  /**
8
8
  * Delegate the source caller to one Domain issuer and redeem that delegation at the issuer's
9
- * advertised endpoint for the Domain's credential to the source Kernel.
9
+ * advertised endpoint for the Domain's credential to the source Kernel, or find the source exhausted.
10
10
  */
11
11
  export async function exchangeDomainCredential(dependencies, source, request, operation) {
12
12
  const caller = sourceCaller(dependencies, source, operation);
@@ -16,7 +16,9 @@ export async function exchangeDomainCredential(dependencies, source, request, op
16
16
  .whoami()
17
17
  .then(({ id }) => id),
18
18
  ]);
19
- const ttlSeconds = delegationTtl(source.credential, request.ttlSeconds, request.coverageMs);
19
+ const ttlSeconds = delegationTtl(source, request.ttlSeconds, request.coverageMs);
20
+ if (ttlSeconds === EXHAUSTED)
21
+ return EXHAUSTED;
20
22
  const delegation = await credentialApi(caller.call).delegate(principal, {
21
23
  audience: request.issuer,
22
24
  ttlSeconds,
@@ -24,9 +26,8 @@ export async function exchangeDomainCredential(dependencies, source, request, op
24
26
  const credential = await redeem(dependencies, request.issuer, endpoint, delegation, operation);
25
27
  // A Domain credential never outlives its source, so only a fresher source can lengthen it.
26
28
  const bySource = ttlSeconds < request.ttlSeconds;
27
- if (bySource && credential.expiresAt - Date.now() <= (request.coverageMs ?? 0)) {
28
- throw sourceExhausted();
29
- }
29
+ if (bySource && credential.expiresAt - Date.now() <= (request.coverageMs ?? 0))
30
+ return EXHAUSTED;
30
31
  return Object.freeze({ ...credential, delegation });
31
32
  }
32
33
  /**
@@ -47,8 +48,10 @@ export async function acquireDomainCredential(dependencies, request, operation)
47
48
  ...(request.ttlSeconds * 1_000 > coverageMs ? { coverageMs } : {}),
48
49
  }, operation);
49
50
  const source = await resolveAuth(auth, call, operation);
50
- const exchanged = auth === undefined || !isAuthority(source)
51
+ const exchanged = auth === undefined || source.kind === 'anonymous'
51
52
  ? await exchange(source)
52
53
  : await renewing(auth, call, source, operation, exchange);
54
+ if (exchanged === EXHAUSTED)
55
+ throw sourceExhausted();
53
56
  return Object.freeze({ credential: exchanged.credential, expiresAt: exchanged.expiresAt });
54
57
  }
@@ -2,4 +2,4 @@ export { callableOrigin, installedIssuer } from './domain.js';
2
2
  export { acquireDomainCredential, exchangeDomainCredential, type DomainCredential, type DomainExchangeRequest, type ExchangeDependencies, } from './exchange.js';
3
3
  export { admitExchangeOptions, admitExchangeRequest, type ExchangeRequest, type SessionExchangeOptions, type SessionExchangeRequest, } from './options.js';
4
4
  export { createSessionExchange, type SessionExchange } from './presentation.js';
5
- export { isAuthority } from './source.js';
5
+ export { EXHAUSTED, sourceExhausted, type Exhausted } from './source.js';
@@ -2,4 +2,4 @@ export { callableOrigin, installedIssuer } from './domain.js';
2
2
  export { acquireDomainCredential, exchangeDomainCredential, } from './exchange.js';
3
3
  export { admitExchangeOptions, admitExchangeRequest, } from './options.js';
4
4
  export { createSessionExchange } from './presentation.js';
5
- export { isAuthority } from './source.js';
5
+ export { EXHAUSTED, sourceExhausted } from './source.js';
@@ -1,10 +1,10 @@
1
- import { ClientError } from '../../errors/index.js';
1
+ import { ClientError, ExchangeError } from '../../errors/index.js';
2
2
  import { runSessionOperation } from '../context/index.js';
3
3
  import { credentials, delegationCoverageMs } from '../credential/index.js';
4
4
  import { createInstallations, declaringOrigin, isKernelOrigin } from './domain.js';
5
5
  import { exchangeDomainCredential } from './exchange.js';
6
6
  import { MAXIMUM_EXCHANGE_SOURCES } from './limits.js';
7
- import { isAuthority, renewing } from './source.js';
7
+ import { EXHAUSTED, renewing, sourceExhausted } from './source.js';
8
8
  /**
9
9
  * Present each Call whose callable a remote installed Domain declares with the credential that
10
10
  * Domain exchanged for the Call's source caller.
@@ -20,7 +20,7 @@ export function createSessionExchange(dependencies, options) {
20
20
  const sources = new Map();
21
21
  return Object.freeze({ resolve, clear });
22
22
  async function resolve(call, effective, operation) {
23
- if (!isAuthority(effective))
23
+ if (effective.kind === 'anonymous')
24
24
  return effective;
25
25
  const origin = declaringOrigin(call.target);
26
26
  if (origin === undefined || isKernelOrigin(origin))
@@ -33,8 +33,21 @@ export function createSessionExchange(dependencies, options) {
33
33
  throw new ClientError('Session delegation outlives the Domain credential it would carry.');
34
34
  }
35
35
  const domainCredentials = credentialsFor(source, domain);
36
- const exchanged = await runSessionOperation(operation, (signal) => domainCredentials.acquire(signal));
37
- return Object.freeze({ credential: exchanged.credential, delegate: source.delegate });
36
+ let exchanged;
37
+ try {
38
+ exchanged = await runSessionOperation(operation, (signal) => domainCredentials.acquire(signal));
39
+ }
40
+ catch (error) {
41
+ // Credentials settles a mint by value or rejection, so exhaustion crosses it as the error.
42
+ if (error instanceof ExchangeError && error.failure === 'source-exhausted')
43
+ return EXHAUSTED;
44
+ throw error;
45
+ }
46
+ return Object.freeze({
47
+ kind: 'authenticated',
48
+ credential: exchanged.credential,
49
+ delegate: source.delegate,
50
+ });
38
51
  });
39
52
  }
40
53
  function clear() {
@@ -48,11 +61,16 @@ export function createSessionExchange(dependencies, options) {
48
61
  return known;
49
62
  const domainCredentials = credentials({
50
63
  ttlSeconds: auth.ttlSeconds,
51
- mint: (signal) => exchangeDomainCredential(dependencies, source, {
52
- issuer: domain,
53
- ttlSeconds: options.ttlSeconds,
54
- coverageMs,
55
- }, dependencies.operation(signal)),
64
+ mint: async (signal) => {
65
+ const exchanged = await exchangeDomainCredential(dependencies, source, {
66
+ issuer: domain,
67
+ ttlSeconds: options.ttlSeconds,
68
+ coverageMs,
69
+ }, dependencies.operation(signal));
70
+ if (exchanged === EXHAUSTED)
71
+ throw sourceExhausted();
72
+ return exchanged;
73
+ },
56
74
  });
57
75
  held.set(domain, domainCredentials);
58
76
  return domainCredentials;
@@ -2,19 +2,19 @@ import type { invocation } from '@astrale-os/kernel-protocol';
2
2
  import type { AuthCall } from '../../auth/auth.js';
3
3
  import type { Call, Result } from '../../client/index.js';
4
4
  import type { SessionOperation } from '../context/index.js';
5
- import type { EffectiveAuth, SessionAuth } from '../routing/index.js';
5
+ import type { Authenticated, EffectiveAuth, SessionAuth } from '../routing/index.js';
6
6
  import type { ExchangeDependencies } from './exchange.js';
7
7
  import { ExchangeError } from '../../errors/index.js';
8
- /** A resolved source that carries both a credential and its delegation. */
9
- export type SourceAuthority = Required<EffectiveAuth>;
10
8
  /** Source Kernel syscalls issued as exactly one admitted source caller within one operation. */
11
9
  interface SourceCaller {
12
10
  dispatch(call: Call): Promise<Result>;
13
11
  readonly call: AuthCall;
14
12
  }
15
13
  /** The source credential can no longer grant a delegation that covers what its exchange carries. */
14
+ export declare const EXHAUSTED: unique symbol;
15
+ export type Exhausted = typeof EXHAUSTED;
16
+ /** The public failure of an exhausted source, once no renewal can replace it. */
16
17
  export declare function sourceExhausted(): ExchangeError;
17
- export declare function isAuthority(auth: EffectiveAuth): auth is SourceAuthority;
18
18
  /** The source Kernel conversation of one exchange, acting as exactly the admitted source caller. */
19
19
  export declare function sourceCaller(dependencies: Pick<ExchangeDependencies, 'source'>, auth: EffectiveAuth, operation: SessionOperation): SourceCaller;
20
20
  /**
@@ -23,11 +23,11 @@ export declare function sourceCaller(dependencies: Pick<ExchangeDependencies, 's
23
23
  * transport-held source leaves the bound to the Kernel. A source that cannot grant one second, or
24
24
  * bounds the delegation within `coverageMs`, is exhausted.
25
25
  */
26
- export declare function delegationTtl(credential: string | undefined, ttlSeconds: number, coverageMs?: number): number;
26
+ export declare function delegationTtl(source: EffectiveAuth, ttlSeconds: number, coverageMs?: number): number | Exhausted;
27
27
  /**
28
28
  * Run `attempt` with the resolved source, and once more with a renewed source if that one proved
29
29
  * exhausted. The Session auth is refreshed only while it still resolves the exhausted credential, so
30
- * concurrent Calls share one renewal; an auth that cannot refresh keeps the failure.
30
+ * concurrent Calls share one renewal; an auth that cannot refresh fails as `sourceExhausted`.
31
31
  */
32
- export declare function renewing<T>(auth: SessionAuth, call: invocation.Call, source: SourceAuthority, operation: SessionOperation, attempt: (source: SourceAuthority) => Promise<T>): Promise<T>;
32
+ export declare function renewing<T>(auth: SessionAuth, call: invocation.Call, source: Authenticated, operation: SessionOperation, attempt: (source: Authenticated) => Promise<T | Exhausted>): Promise<T>;
33
33
  export {};
@@ -4,21 +4,20 @@ import { runSessionOperation, sessionTransportOptions } from '../context/index.j
4
4
  import { requireResultKind, resolveAuth } from '../routing/index.js';
5
5
  import { ISSUANCE_MARGIN_SECONDS } from './limits.js';
6
6
  /** The source credential can no longer grant a delegation that covers what its exchange carries. */
7
+ export const EXHAUSTED = Symbol('exhausted');
8
+ /** The public failure of an exhausted source, once no renewal can replace it. */
7
9
  export function sourceExhausted() {
8
10
  return new ExchangeError('The source credential expires too soon for a Domain token exchange.', {
9
11
  failure: 'source-exhausted',
10
12
  });
11
13
  }
12
- export function isAuthority(auth) {
13
- return auth.credential !== undefined && auth.delegate !== undefined;
14
- }
15
14
  /** The source Kernel conversation of one exchange, acting as exactly the admitted source caller. */
16
15
  export function sourceCaller(dependencies, auth, operation) {
17
16
  const client = dependencies.source();
18
- const caller = auth.credential === undefined ? client : client.as(auth.credential);
17
+ const caller = auth.kind === 'anonymous' ? client : client.as(auth.credential);
19
18
  const dispatch = (input) => runSessionOperation(operation, () => caller.dispatch(input, {
20
19
  ...sessionTransportOptions(operation),
21
- ...(auth.delegate === undefined ? {} : { delegate: auth.delegate }),
20
+ ...(auth.kind === 'anonymous' ? {} : { delegate: auth.delegate }),
22
21
  }));
23
22
  const call = async (target, input) => requireResultKind('value', await dispatch({ target, input })).value;
24
23
  return Object.freeze({ dispatch, call });
@@ -29,42 +28,42 @@ export function sourceCaller(dependencies, auth, operation) {
29
28
  * transport-held source leaves the bound to the Kernel. A source that cannot grant one second, or
30
29
  * bounds the delegation within `coverageMs`, is exhausted.
31
30
  */
32
- export function delegationTtl(credential, ttlSeconds, coverageMs = 0) {
33
- const remaining = remainingSeconds(credential);
31
+ export function delegationTtl(source, ttlSeconds, coverageMs = 0) {
32
+ const remaining = source.kind === 'anonymous' ? undefined : remainingSeconds(source.credential);
34
33
  if (remaining === undefined || remaining >= ttlSeconds)
35
34
  return ttlSeconds;
36
35
  if (remaining < 1 || remaining * 1_000 <= coverageMs)
37
- throw sourceExhausted();
36
+ return EXHAUSTED;
38
37
  return remaining;
39
38
  }
40
39
  /**
41
40
  * Run `attempt` with the resolved source, and once more with a renewed source if that one proved
42
41
  * exhausted. The Session auth is refreshed only while it still resolves the exhausted credential, so
43
- * concurrent Calls share one renewal; an auth that cannot refresh keeps the failure.
42
+ * concurrent Calls share one renewal; an auth that cannot refresh fails as `sourceExhausted`.
44
43
  */
45
44
  export async function renewing(auth, call, source, operation, attempt) {
46
- try {
47
- return await attempt(source);
45
+ const first = await attempt(source);
46
+ if (first !== EXHAUSTED)
47
+ return first;
48
+ let renewed = await resolveAuth(auth, call, operation);
49
+ const refresh = auth.refresh;
50
+ if (renewed.kind === 'authenticated' &&
51
+ renewed.credential === source.credential &&
52
+ refresh !== undefined) {
53
+ await runSessionOperation(operation, async (signal) => {
54
+ await refresh(signal);
55
+ });
56
+ renewed = await resolveAuth(auth, call, operation);
48
57
  }
49
- catch (cause) {
50
- if (!(cause instanceof ExchangeError) || cause.failure !== 'source-exhausted')
51
- throw cause;
52
- let renewed = await resolveAuth(auth, call, operation);
53
- if (renewed.credential === source.credential && auth.refresh !== undefined) {
54
- const refresh = auth.refresh;
55
- await runSessionOperation(operation, async (signal) => {
56
- await refresh(signal);
57
- });
58
- renewed = await resolveAuth(auth, call, operation);
59
- }
60
- if (!isAuthority(renewed) || renewed.credential === source.credential)
61
- throw cause;
62
- return attempt(renewed);
58
+ if (renewed.kind === 'anonymous' || renewed.credential === source.credential) {
59
+ throw sourceExhausted();
63
60
  }
61
+ const second = await attempt(renewed);
62
+ if (second === EXHAUSTED)
63
+ throw sourceExhausted();
64
+ return second;
64
65
  }
65
66
  function remainingSeconds(credential) {
66
- if (credential === undefined)
67
- return undefined;
68
67
  let expiresAt;
69
68
  try {
70
69
  expiresAt = inspect(credential).claims.exp;
@@ -1,5 +1,5 @@
1
1
  export type { SessionControlOptions, SessionPolicy } from './context/index.js';
2
- export type { ContentApi, ContentDownload, ContentLocation, ContentRejection, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
2
+ export type { ContentApi, ContentDownload, ContentLocation, ContentReceipt, ContentRejection, ContentSource, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
3
3
  export { bindSession, type BoundClientSession, type BoundSessionControls, type BoundSessionSource, } from './bound.js';
4
4
  export { credentials, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credential/index.js';
5
5
  export type { IntrinsicRelease, SessionSnapshot } from './discovery/index.js';
@@ -7,8 +7,9 @@ export type { SessionExchangeOptions, SessionExchangeRequest } from './exchange/
7
7
  export type { Auth, PersistedRoute, SessionRouteArtifact, SessionRouteStore, SessionAuth, SessionEnvelopeTransport, SessionRequestOptions, SessionRequestOptionsWithBody, } from './routing/index.js';
8
8
  export type { ClientSessionOptions } from './options.js';
9
9
  export { ClientSession, connect, type ConnectOptions } from './session.js';
10
- export type { CallableReference, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
10
+ export type { CallableReference, FileSourcesOf, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
11
11
  export { reference } from './reference.js';
12
- export { execution, type ExecutionOutcome, type ExecutionRef, type DeletedExecutionStatus, type ExecutionNodeStatus, type ExecutionState, type ExecutionStatus, } from './execution.js';
13
- export type { ResolvedView, ViewCatalog } from './views/index.js';
12
+ export type { DeletedExecutionStatus, ExecutionApi, ExecutionFailure, ExecutionNodeStatus, ExecutionOutcome, ExecutionRef, ExecutionState, ExecutionStatus, ExecutionTarget, ExecutionWait, } from '../execution/index.js';
13
+ export type { View, ViewsOf } from './views/index.js';
14
+ export type { ResolvedView, ViewCatalog } from './views/legacy/index.js';
14
15
  export type { DomainBinding } from '../graph/domain/index.js';