@astrale-os/kernel-client 1.0.0-beta.4 → 1.0.0-beta.40

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 (194) hide show
  1. package/dist/auth/index.d.ts +1 -0
  2. package/dist/client/admission.js +3 -1
  3. package/dist/client/client.d.ts +19 -2
  4. package/dist/client/client.js +62 -30
  5. package/dist/client/index.d.ts +3 -3
  6. package/dist/client/index.js +2 -2
  7. package/dist/client/request.d.ts +8 -2
  8. package/dist/client/request.js +28 -7
  9. package/dist/client/result.d.ts +10 -1
  10. package/dist/client/result.js +10 -4
  11. package/dist/client/routing-control.d.ts +11 -15
  12. package/dist/client/routing-control.js +21 -29
  13. package/dist/errors/index.d.ts +3 -0
  14. package/dist/errors/index.js +3 -0
  15. package/dist/errors/query-input.d.ts +47 -0
  16. package/dist/errors/query-input.js +85 -0
  17. package/dist/errors/refusal.d.ts +24 -0
  18. package/dist/errors/refusal.js +78 -0
  19. package/dist/errors/response-too-large-error.d.ts +11 -0
  20. package/dist/errors/response-too-large-error.js +15 -0
  21. package/dist/errors/stale-route-error.d.ts +1 -1
  22. package/dist/errors/stale-route-error.js +1 -1
  23. package/dist/{schema → execution}/admission.d.ts +2 -2
  24. package/dist/{schema → execution}/admission.js +3 -3
  25. package/dist/execution/contracts.d.ts +76 -0
  26. package/dist/execution/contracts.js +1 -0
  27. package/dist/execution/deadline.d.ts +18 -0
  28. package/dist/execution/deadline.js +25 -0
  29. package/dist/execution/execution.d.ts +61 -0
  30. package/dist/execution/execution.js +132 -0
  31. package/dist/execution/index.d.ts +4 -0
  32. package/dist/execution/index.js +3 -0
  33. package/dist/graph/domain/binding.d.ts +2 -2
  34. package/dist/graph/domain/binding.js +24 -17
  35. package/dist/graph/domain/conformance.d.ts +12 -0
  36. package/dist/graph/domain/conformance.js +18 -0
  37. package/dist/graph/domain/index.d.ts +1 -0
  38. package/dist/graph/domain/index.js +1 -1
  39. package/dist/graph/domain/provenance.d.ts +0 -2
  40. package/dist/graph/domain/provenance.js +0 -4
  41. package/dist/graph/graph.d.ts +17 -3
  42. package/dist/graph/graph.js +4 -1
  43. package/dist/graph/index.d.ts +3 -3
  44. package/dist/graph/index.js +1 -1
  45. package/dist/graph/page-contract.d.ts +66 -1
  46. package/dist/graph/provenance.d.ts +4 -5
  47. package/dist/graph/provenance.js +5 -6
  48. package/dist/graph/query.d.ts +10 -4
  49. package/dist/graph/query.js +149 -7
  50. package/dist/graph/query.typecheck.d.ts +79 -0
  51. package/dist/graph/query.typecheck.js +34 -0
  52. package/dist/pacer/index.d.ts +1 -1
  53. package/dist/pacer/index.js +1 -1
  54. package/dist/pacer/retry/index.d.ts +1 -0
  55. package/dist/pacer/retry/index.js +1 -0
  56. package/dist/pacer/retry/refusals.d.ts +7 -0
  57. package/dist/pacer/retry/refusals.js +10 -0
  58. package/dist/pacer/retry/retry.d.ts +2 -0
  59. package/dist/pacer/retry/retry.js +33 -1
  60. package/dist/schema/contracts.d.ts +77 -9
  61. package/dist/schema/index.d.ts +3 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +76 -0
  64. package/dist/schema/installation.js +82 -0
  65. package/dist/schema/schema.d.ts +22 -13
  66. package/dist/schema/schema.js +67 -48
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +66 -20
  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 +1 -1
  80. package/dist/session/context/index.js +1 -1
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/credential/credentials.js +43 -28
  84. package/dist/session/discovery/bundle.d.ts +9 -4
  85. package/dist/session/discovery/bundle.js +28 -35
  86. package/dist/session/discovery/discovery.d.ts +1 -1
  87. package/dist/session/discovery/discovery.js +8 -11
  88. package/dist/session/discovery/release.js +18 -28
  89. package/dist/session/discovery/snapshot.d.ts +5 -1
  90. package/dist/session/discovery/transport.d.ts +35 -3
  91. package/dist/session/discovery/transport.js +40 -1
  92. package/dist/session/durable.d.ts +13 -0
  93. package/dist/session/durable.js +39 -0
  94. package/dist/session/exchange/exchange.d.ts +3 -2
  95. package/dist/session/exchange/exchange.js +10 -7
  96. package/dist/session/exchange/index.d.ts +1 -1
  97. package/dist/session/exchange/index.js +1 -1
  98. package/dist/session/exchange/presentation.js +28 -10
  99. package/dist/session/exchange/source.d.ts +7 -7
  100. package/dist/session/exchange/source.js +26 -27
  101. package/dist/session/index.d.ts +5 -4
  102. package/dist/session/index.js +0 -1
  103. package/dist/session/options.d.ts +0 -2
  104. package/dist/session/options.js +0 -3
  105. package/dist/session/reference.d.ts +27 -6
  106. package/dist/session/reference.js +18 -3
  107. package/dist/session/retry.d.ts +12 -0
  108. package/dist/session/retry.js +23 -0
  109. package/dist/session/routing/auth.d.ts +9 -3
  110. package/dist/session/routing/auth.js +4 -3
  111. package/dist/session/routing/cache.d.ts +12 -5
  112. package/dist/session/routing/cache.js +56 -48
  113. package/dist/session/routing/dispatch.d.ts +26 -3
  114. package/dist/session/routing/dispatch.js +112 -67
  115. package/dist/session/routing/envelope.d.ts +3 -3
  116. package/dist/session/routing/index.d.ts +1 -1
  117. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  118. package/dist/session/routing/legacy/release-route.js +6 -0
  119. package/dist/session/routing/recovery.d.ts +3 -6
  120. package/dist/session/routing/recovery.js +3 -14
  121. package/dist/session/routing/request.d.ts +6 -1
  122. package/dist/session/routing/request.js +13 -2
  123. package/dist/session/routing/result.d.ts +1 -1
  124. package/dist/session/routing/result.js +5 -1
  125. package/dist/session/routing/store.js +4 -5
  126. package/dist/session/session.d.ts +31 -5
  127. package/dist/session/session.js +67 -20
  128. package/dist/session/session.typecheck.js +20 -6
  129. package/dist/session/views/index.d.ts +2 -2
  130. package/dist/session/views/index.js +2 -2
  131. package/dist/session/views/kernel.d.ts +31 -0
  132. package/dist/session/views/kernel.js +30 -0
  133. package/dist/session/views/legacy/catalog.d.ts +21 -0
  134. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  135. package/dist/session/views/legacy/index.d.ts +14 -0
  136. package/dist/session/views/legacy/index.js +14 -0
  137. package/dist/session/views/legacy/resolve.d.ts +46 -0
  138. package/dist/session/views/legacy/resolve.js +83 -0
  139. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  140. package/dist/session/views/legacy/unplaced.js +26 -0
  141. package/dist/session/views/read.d.ts +49 -0
  142. package/dist/session/views/read.js +148 -0
  143. package/dist/session/views/view.d.ts +48 -0
  144. package/dist/session/views/view.js +74 -0
  145. package/dist/store/memory.d.ts +1 -3
  146. package/dist/store/memory.js +73 -105
  147. package/dist/store/shape.d.ts +33 -12
  148. package/dist/store/shape.js +125 -16
  149. package/dist/store/store.d.ts +6 -6
  150. package/dist/store/store.js +1 -1
  151. package/dist/transport/auto/decision.d.ts +26 -14
  152. package/dist/transport/auto/decision.js +35 -32
  153. package/dist/transport/auto/fallback.d.ts +1 -1
  154. package/dist/transport/auto/fallback.js +5 -10
  155. package/dist/transport/auto/transport.d.ts +0 -2
  156. package/dist/transport/auto/transport.js +24 -32
  157. package/dist/transport/deadline.d.ts +2 -0
  158. package/dist/transport/deadline.js +18 -0
  159. package/dist/transport/failure.d.ts +28 -1
  160. package/dist/transport/failure.js +63 -1
  161. package/dist/transport/http/admission.js +7 -34
  162. package/dist/transport/http/binary-request.d.ts +44 -0
  163. package/dist/transport/http/binary-request.js +110 -0
  164. package/dist/transport/http/binary.js +3 -3
  165. package/dist/transport/http/byte-stream.d.ts +2 -1
  166. package/dist/transport/http/byte-stream.js +12 -8
  167. package/dist/transport/http/index.d.ts +1 -1
  168. package/dist/transport/http/index.js +1 -1
  169. package/dist/transport/http/response.d.ts +3 -1
  170. package/dist/transport/http/response.js +7 -9
  171. package/dist/transport/http/stream.d.ts +8 -13
  172. package/dist/transport/http/stream.js +34 -81
  173. package/dist/transport/http/transport.d.ts +10 -0
  174. package/dist/transport/http/transport.js +87 -32
  175. package/dist/transport/http/unprocessed.d.ts +5 -0
  176. package/dist/transport/http/unprocessed.js +28 -0
  177. package/dist/transport/index.d.ts +1 -1
  178. package/dist/transport/index.js +1 -1
  179. package/dist/transport/stream.d.ts +52 -0
  180. package/dist/transport/stream.js +101 -0
  181. package/dist/transport/transport.d.ts +10 -0
  182. package/dist/transport/unary.d.ts +8 -0
  183. package/dist/transport/unary.js +34 -0
  184. package/dist/transport/websocket/connection.d.ts +7 -3
  185. package/dist/transport/websocket/connection.js +103 -92
  186. package/dist/transport/websocket/exchange.d.ts +12 -19
  187. package/dist/transport/websocket/exchange.js +86 -184
  188. package/dist/transport/websocket/transport.js +11 -19
  189. package/package.json +9 -7
  190. package/dist/session/execution.d.ts +0 -65
  191. package/dist/session/execution.js +0 -34
  192. package/dist/session/views/catalog.d.ts +0 -19
  193. package/dist/session/views/resolve.d.ts +0 -13
  194. package/dist/session/views/resolve.js +0 -21
@@ -31,13 +31,14 @@ export function credentials(source) {
31
31
  const notify = options.onChange?.bind(options);
32
32
  // The threshold is the coverage the caller already declared, never a separate guessed constant.
33
33
  const marginMs = delegationCoverageMs(ttlSeconds);
34
- let current = options.initial === undefined ? undefined : admitInitial(options.initial);
35
- let state = Object.freeze(current === undefined
34
+ const initial = options.initial === undefined ? undefined : admitInitial(options.initial);
35
+ let state = Object.freeze(initial === undefined
36
36
  ? { status: 'empty' }
37
- : { status: 'valid', credential: current });
38
- let inflight;
39
- let controller;
37
+ : { status: 'valid', credential: initial });
38
+ let minting;
40
39
  let waiting = 0;
40
+ /** A caller without a signal keeps the mint in flight alive; anticipation does not. */
41
+ let unsignalled = false;
41
42
  let anticipating = false;
42
43
  let refreshTimer;
43
44
  let expiryTimer;
@@ -54,7 +55,12 @@ export function credentials(source) {
54
55
  async function resolve(_call, signal) {
55
56
  return { credential: (await acquire(signal)).credential };
56
57
  }
58
+ /** The credential the published state holds, if any. */
59
+ function held() {
60
+ return 'credential' in state ? state.credential : undefined;
61
+ }
57
62
  function acquire(signal) {
63
+ const current = held();
58
64
  if (current !== undefined && covers(current))
59
65
  return Promise.resolve(current);
60
66
  return share(signal);
@@ -75,9 +81,11 @@ export function credentials(source) {
75
81
  function share(signal) {
76
82
  if (signal?.aborted === true)
77
83
  return Promise.reject(signal.reason);
78
- const pending = inflight ?? begin();
79
- if (signal === undefined)
80
- return pending;
84
+ const flight = minting ?? begin();
85
+ if (signal === undefined) {
86
+ unsignalled = true;
87
+ return flight.promise;
88
+ }
81
89
  waiting += 1;
82
90
  let settled = false;
83
91
  return new Promise((complete, fail) => {
@@ -88,8 +96,8 @@ export function credentials(source) {
88
96
  waiting -= 1;
89
97
  signal.removeEventListener('abort', cancel);
90
98
  // Nobody is waiting and nobody is anticipating: the mint has no beneficiary left.
91
- if (waiting === 0 && !anticipating)
92
- controller?.abort(signal.reason);
99
+ if (waiting === 0 && !anticipating && !unsignalled)
100
+ minting?.controller.abort(signal.reason);
93
101
  };
94
102
  const cancel = () => {
95
103
  const reason = signal.reason;
@@ -97,7 +105,7 @@ export function credentials(source) {
97
105
  fail(reason);
98
106
  };
99
107
  signal.addEventListener('abort', cancel, { once: true });
100
- pending.then((credential) => {
108
+ flight.promise.then((credential) => {
101
109
  if (settled)
102
110
  return;
103
111
  settled = true;
@@ -114,21 +122,28 @@ export function credentials(source) {
114
122
  });
115
123
  });
116
124
  }
125
+ /** Begin a mint; without a mint capability, the returned one has already failed and is not held. */
117
126
  function begin() {
127
+ const controller = new AbortController();
118
128
  if (mint === undefined) {
119
129
  const error = new ClientError('Session credential needs renewal, but no mint was supplied.');
120
130
  settleFailure(error);
121
- return Promise.reject(error);
131
+ return { promise: Promise.reject(error), controller };
122
132
  }
123
133
  const renew = mint;
134
+ const current = held();
124
135
  publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
125
- const owned = new AbortController();
126
- controller = owned;
127
- const signal = AbortSignal.any([owned.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
128
- const pending = (async () => {
136
+ unsignalled = false;
137
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
138
+ const promise = (async () => {
129
139
  try {
130
- const minted = admitMinted(await renew(signal));
131
- current = minted;
140
+ // A mint that throws instead of rejecting fails this attempt alike: the executor turns the
141
+ // throw into a rejection, so the attempt settles only after it yields, once `minting`
142
+ // holds it, and the cleanup below releases it for the next acquisition.
143
+ const returned = new Promise((complete) => {
144
+ complete(renew(signal));
145
+ });
146
+ const minted = admitMinted(await returned);
132
147
  attempt = 0;
133
148
  publish({ status: 'valid', credential: minted });
134
149
  if (anticipating)
@@ -140,21 +155,20 @@ export function credentials(source) {
140
155
  throw error;
141
156
  }
142
157
  finally {
143
- inflight = undefined;
144
- controller = undefined;
158
+ minting = undefined;
145
159
  }
146
160
  })();
147
- inflight = pending;
161
+ minting = { promise, controller };
148
162
  // A rejection reaches every waiter; keep an unattached one from surfacing as unhandled.
149
- pending.catch(() => undefined);
150
- return pending;
163
+ promise.catch(() => undefined);
164
+ return minting;
151
165
  }
152
166
  function settleFailure(error) {
167
+ const current = held();
153
168
  if (current !== undefined && current.expiresAt > Date.now()) {
154
169
  publish({ status: 'degraded', credential: current, error });
155
170
  }
156
171
  else {
157
- current = undefined;
158
172
  publish({ status: 'expired', error });
159
173
  }
160
174
  if (anticipating)
@@ -165,8 +179,9 @@ export function credentials(source) {
165
179
  clearTimers();
166
180
  if (!anticipating)
167
181
  return;
182
+ const current = held();
168
183
  if (current === undefined) {
169
- void share().catch(() => undefined);
184
+ void (minting ?? begin()).promise.catch(() => undefined);
170
185
  return;
171
186
  }
172
187
  // The threshold itself, with no extra lead: chained providers sharing this rule must not
@@ -177,6 +192,7 @@ export function credentials(source) {
177
192
  function retry() {
178
193
  if (refreshTimer !== undefined)
179
194
  return;
195
+ const current = held();
180
196
  if (current !== undefined)
181
197
  armExpiry(current);
182
198
  // Without a mint nothing can replace the held credential; only its expiry remains to report.
@@ -189,7 +205,7 @@ export function credentials(source) {
189
205
  function armRefresh(delay) {
190
206
  refreshTimer = setTimeout(() => {
191
207
  refreshTimer = undefined;
192
- void share().catch(() => undefined);
208
+ void (minting ?? begin()).promise.catch(() => undefined);
193
209
  }, delay);
194
210
  }
195
211
  function armExpiry(credential) {
@@ -197,9 +213,8 @@ export function credentials(source) {
197
213
  clearTimeout(expiryTimer);
198
214
  expiryTimer = setTimeout(() => {
199
215
  expiryTimer = undefined;
200
- if (!anticipating || current !== credential)
216
+ if (!anticipating || held() !== credential)
201
217
  return;
202
- current = undefined;
203
218
  publish({ status: 'expired', error: new ClientError('Session credential expired.') });
204
219
  }, clamp(credential.expiresAt - Date.now()));
205
220
  }
@@ -8,14 +8,19 @@ interface BundleDiscoveryOptions {
8
8
  readonly policy: Readonly<SessionPolicy>;
9
9
  readonly maximumBytes: number;
10
10
  }
11
- /** Internal evidence that a selected immutable artifact is no longer served. */
12
- export declare class BundleUnavailableError extends ClientError {
13
- }
11
+ /** A Release's Bundle, or evidence that its digest-addressed artifact is no longer served. */
12
+ export type BundleRead = {
13
+ readonly kind: 'bundle';
14
+ readonly bundle: bundle.Bundle;
15
+ } | {
16
+ readonly kind: 'unavailable';
17
+ readonly error: ClientError;
18
+ };
14
19
  export declare class BundleDiscovery {
15
20
  private readonly options;
16
21
  private retained?;
17
22
  constructor(options: BundleDiscoveryOptions);
18
- get(release: DomainRelease, operation: SessionOperation): Promise<bundle.Bundle>;
23
+ get(release: DomainRelease, operation: SessionOperation): Promise<BundleRead>;
19
24
  clear(): void;
20
25
  private fetch;
21
26
  }
@@ -1,11 +1,7 @@
1
1
  import { bundleUrl, decodeBundle } from '@astrale-os/kernel-protocol/release';
2
2
  import { ClientError } from '../../errors/index.js';
3
3
  import { allowEndpoint } from '../context/index.js';
4
- import { boundedResponse, requireExactResponse } from './response.js';
5
- import { runAcquisition } from './transport.js';
6
- /** Internal evidence that a selected immutable artifact is no longer served. */
7
- export class BundleUnavailableError extends ClientError {
8
- }
4
+ import { fetchDocument } from './transport.js';
9
5
  export class BundleDiscovery {
10
6
  options;
11
7
  retained;
@@ -16,47 +12,44 @@ export class BundleDiscovery {
16
12
  const key = bundleKey(release);
17
13
  allowEndpoint(release.schema.bundle.href, this.options.policy);
18
14
  if (this.retained?.key === key)
19
- return this.retained.value;
20
- const value = await this.fetch(release, operation);
21
- this.retained = { key, value };
22
- return value;
15
+ return { kind: 'bundle', bundle: this.retained.value };
16
+ const read = await this.fetch(release, operation);
17
+ if (read.kind === 'bundle')
18
+ this.retained = { key, value: read.bundle };
19
+ return read;
23
20
  }
24
21
  clear() {
25
22
  this.retained = undefined;
26
23
  }
27
24
  async fetch(release, operation) {
28
- if (release.schema.bundle.ref.size > this.options.maximumBytes) {
25
+ const { href, ref } = release.schema.bundle;
26
+ if (ref.size > this.options.maximumBytes) {
29
27
  throw new ClientError('Bundle artifact exceeds its byte limit.');
30
28
  }
31
- const href = release.schema.bundle.href;
32
- const immutable = href === bundleUrl(release.identity.issuer, release.schema.bundle.ref);
33
- const response = await runAcquisition(operation, 'bundle', 'unknown', 'Kernel bundle could not be retrieved.', (signal) => this.options.fetch(href, {
34
- headers: { accept: release.schema.bundle.ref.mediaType },
35
- // Omitting `cache` is the browser default; Workers reject the DOM-only 'default' mode.
36
- cache: immutable ? undefined : 'no-cache',
37
- redirect: 'manual',
38
- signal,
39
- }));
40
- requireExactResponse(response, href, 'Bundle retrieval');
41
- if (immutable && (response.status === 404 || response.status === 410)) {
42
- // Cleanup must not hold discovery open on an injected body cancellation.
43
- void response.body?.cancel().catch(() => undefined);
44
- throw new BundleUnavailableError(`Bundle retrieval returned HTTP ${response.status}.`);
45
- }
46
- if (!response.ok)
47
- throw new ClientError(`Bundle retrieval returned HTTP ${response.status}.`);
48
- if (response.headers.get('content-type') !== release.schema.bundle.ref.mediaType) {
49
- throw new ClientError('Bundle artifact media type differs from its descriptor.');
50
- }
51
- const etag = response.headers.get('etag');
52
- if (etag !== null && etag !== `"${release.schema.bundle.ref.digest}"`) {
29
+ const immutable = href === bundleUrl(release.identity.issuer, ref);
30
+ const fetched = await fetchDocument(operation, this.options.fetch, {
31
+ resource: 'bundle',
32
+ label: 'Bundle retrieval',
33
+ url: href,
34
+ mediaType: ref.mediaType,
35
+ mediaTypeMismatch: 'Bundle artifact media type differs from its descriptor.',
36
+ maximumBytes: ref.size,
37
+ ...(immutable ? {} : { cache: 'no-cache' }),
38
+ notModified: false,
39
+ // Only a digest-addressed artifact can be retired by a Release change.
40
+ unavailable: immutable ? [404, 410] : [],
41
+ });
42
+ if (fetched.kind !== 'document')
43
+ return fetched;
44
+ const etag = fetched.headers.get('etag');
45
+ if (etag !== null && etag !== `"${ref.digest}"`) {
53
46
  throw new ClientError('Bundle response ETag differs from its descriptor.');
54
47
  }
55
- const bytes = await runAcquisition(operation, 'bundle', 'receive', 'Kernel bundle response could not be read.', (signal) => boundedResponse(response, release.schema.bundle.ref.size, signal));
56
- if (bytes.byteLength !== release.schema.bundle.ref.size) {
48
+ const bytes = await fetched.read();
49
+ if (bytes.byteLength !== ref.size) {
57
50
  throw new ClientError('Bundle artifact size differs from its descriptor.');
58
51
  }
59
- return decodeBundle(release, bytes);
52
+ return { kind: 'bundle', bundle: decodeBundle(release, bytes) };
60
53
  }
61
54
  }
62
55
  function bundleKey(release) {
@@ -1,8 +1,8 @@
1
1
  import type { IssuerId } from '@astrale-os/kernel-core/auth/issuer';
2
2
  import type { SessionOperation, SessionPolicy } from '../context/index.js';
3
+ import type { BundleDiscovery } from './bundle.js';
3
4
  import type { IntrinsicRelease } from './release.js';
4
5
  import type { SessionSnapshot } from './snapshot.js';
5
- import { type BundleDiscovery } from './bundle.js';
6
6
  /** Revalidating reader of the source Kernel's intrinsic release. */
7
7
  interface IntrinsicReleases {
8
8
  revalidate(operation: SessionOperation): Promise<IntrinsicRelease>;
@@ -1,6 +1,5 @@
1
1
  import { runSessionOperation } from '../context/index.js';
2
- import { rootViewCatalog } from '../views/index.js';
3
- import { BundleUnavailableError } from './bundle.js';
2
+ import { rootViewCatalog } from '../views/legacy/index.js';
4
3
  import { createSessionSnapshot } from './snapshot.js';
5
4
  export class SessionDiscovery {
6
5
  kernel;
@@ -60,19 +59,17 @@ export class SessionDiscovery {
60
59
  }
61
60
  async acquireSnapshot(operation) {
62
61
  let release = await this.release(operation);
63
- let artifact;
64
- try {
65
- artifact = await this.bundles.get(release, operation);
66
- }
67
- catch (cause) {
68
- if (!(cause instanceof BundleUnavailableError))
69
- throw cause;
62
+ let read = await this.bundles.get(release, operation);
63
+ if (read.kind === 'unavailable') {
70
64
  const current = await this.release(operation);
71
65
  if (current.digest === release.digest)
72
- throw cause;
66
+ throw read.error;
73
67
  release = current;
74
- artifact = await this.bundles.get(release, operation);
68
+ read = await this.bundles.get(release, operation);
69
+ if (read.kind === 'unavailable')
70
+ throw read.error;
75
71
  }
72
+ const artifact = read.bundle;
76
73
  this.requireOpen();
77
74
  if (this.retained !== undefined && this.retained.release.digest === release.digest) {
78
75
  return this.retained;
@@ -2,8 +2,7 @@ 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.
@@ -37,42 +36,33 @@ export class ReleaseDiscovery {
37
36
  async fetch(operation, previous) {
38
37
  const url = releaseCodec.url(this.options.kernel);
39
38
  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) {
39
+ const fetched = await fetchDocument(operation, this.options.fetch, {
40
+ resource: 'release',
41
+ label: 'Release discovery',
42
+ url,
43
+ mediaType: releaseCodec.MEDIA_TYPE,
44
+ mediaTypeMismatch: 'Release response media type differs from the DomainRelease v4 media type.',
45
+ maximumBytes: this.options.maximumBytes,
46
+ ...(previous === undefined ? {} : { ifNoneMatch: `"${previous.digest}"` }),
47
+ notModified: true,
48
+ unavailable: [404],
49
+ });
50
+ if (fetched.kind === 'unavailable')
51
+ throw fetched.error;
52
+ if (fetched.kind === 'not-modified') {
55
53
  if (previous === undefined) {
56
54
  throw new ClientError('Release discovery returned an unexpected not-modified response.');
57
55
  }
58
- const etag = response.headers.get('etag');
59
- if (etag !== null && etag !== `"${previous.digest}"`) {
56
+ if (fetched.etag !== null && fetched.etag !== `"${previous.digest}"`) {
60
57
  throw new ClientError('Release not-modified ETag differs from the retained release digest.');
61
58
  }
62
59
  return previous;
63
60
  }
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.');
69
- }
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));
61
+ const admitted = releaseCodec.accept(codecs.json.decode(await fetched.read()));
72
62
  if (admitted.identity.issuer !== this.options.kernel) {
73
63
  throw new ClientError('Release issuer differs from the requested Kernel issuer.');
74
64
  }
75
- const etag = response.headers.get('etag');
65
+ const etag = fetched.headers.get('etag');
76
66
  if (etag !== null && etag !== `"${admitted.digest}"`) {
77
67
  throw new ClientError('Release response ETag differs from its release digest.');
78
68
  }
@@ -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,36 @@
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 ifNoneMatch?: string;
16
+ readonly cache?: 'no-cache';
17
+ /** Whether a 304 answers the request instead of failing it. */
18
+ readonly notModified: NotModified;
19
+ /** Statuses that mean the document is no longer served, as opposed to a failed retrieval. */
20
+ readonly unavailable: readonly number[];
21
+ }
22
+ /** The answer to a public Session document request; 304 answers only a request that admits it. */
23
+ export type DocumentResponse<NotModified extends boolean = boolean> = {
24
+ readonly kind: 'document';
25
+ readonly headers: Headers;
26
+ /** Read the body within the request's byte bound. */
27
+ read(): Promise<Uint8Array>;
28
+ } | {
29
+ readonly kind: 'unavailable';
30
+ readonly error: ClientError;
31
+ } | (NotModified extends true ? {
32
+ readonly kind: 'not-modified';
33
+ readonly etag: string | null;
34
+ } : never);
35
+ /** Fetch one public Session document and admit its exact URL, status and media type. */
36
+ export declare function fetchDocument<NotModified extends boolean>(operation: SessionOperation, fetch: Fetch, request: DocumentRequest<NotModified>): Promise<DocumentResponse<NotModified>>;
@@ -1,7 +1,46 @@
1
1
  import { ClientError, TransportError } from '../../errors/index.js';
2
2
  import { runSessionOperation } from '../context/index.js';
3
+ import { boundedResponse, requireExactResponse } from './response.js';
4
+ /** Fetch one public Session document and admit its exact URL, status and media type. */
5
+ export async function fetchDocument(operation, fetch, request) {
6
+ const { resource, label, url } = request;
7
+ const response = await runAcquisition(operation, resource, 'unknown', `Kernel ${resource} could not be retrieved.`, (signal) => fetch(url, {
8
+ headers: {
9
+ accept: request.mediaType,
10
+ ...(request.ifNoneMatch === undefined ? {} : { 'if-none-match': request.ifNoneMatch }),
11
+ },
12
+ // Omitting `cache` is the browser default; Workers reject the DOM-only 'default' mode.
13
+ ...(request.cache === undefined ? {} : { cache: request.cache }),
14
+ redirect: 'manual',
15
+ signal,
16
+ }));
17
+ requireExactResponse(response, url, label);
18
+ const status = `${label} returned HTTP ${response.status}.`;
19
+ if (request.unavailable.includes(response.status)) {
20
+ // Cleanup must not hold discovery open on an injected body cancellation.
21
+ void response.body?.cancel().catch(() => undefined);
22
+ return { kind: 'unavailable', error: new ClientError(status) };
23
+ }
24
+ if (request.notModified && response.status === 304) {
25
+ // `notModified` is true here, so the conditional member is present.
26
+ return {
27
+ kind: 'not-modified',
28
+ etag: response.headers.get('etag'),
29
+ };
30
+ }
31
+ if (!response.ok)
32
+ throw new ClientError(status);
33
+ if (response.headers.get('content-type') !== request.mediaType) {
34
+ throw new ClientError(request.mediaTypeMismatch);
35
+ }
36
+ return {
37
+ kind: 'document',
38
+ headers: response.headers,
39
+ read: () => runAcquisition(operation, resource, 'receive', `Kernel ${resource} response could not be read.`, (signal) => boundedResponse(response, request.maximumBytes, signal)),
40
+ };
41
+ }
3
42
  /** Normalize only unknown failures from one injected acquisition capability. */
4
- export async function runAcquisition(operation, resource, phase, message, task) {
43
+ async function runAcquisition(operation, resource, phase, message, task) {
5
44
  try {
6
45
  return await runSessionOperation(operation, task);
7
46
  }
@@ -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';