@astrale-os/kernel-client 1.0.0-beta.25 → 1.0.0-beta.27

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 (73) hide show
  1. package/dist/client/admission.js +3 -1
  2. package/dist/client/client.d.ts +16 -3
  3. package/dist/client/client.js +36 -15
  4. package/dist/client/index.d.ts +2 -2
  5. package/dist/client/index.js +1 -1
  6. package/dist/client/routing-control.d.ts +11 -15
  7. package/dist/client/routing-control.js +21 -29
  8. package/dist/errors/query-input.js +2 -1
  9. package/dist/errors/stale-route-error.d.ts +1 -1
  10. package/dist/errors/stale-route-error.js +1 -1
  11. package/dist/graph/page-contract.d.ts +8 -3
  12. package/dist/graph/query.js +10 -4
  13. package/dist/graph/query.typecheck.js +1 -1
  14. package/dist/session/admission.js +4 -2
  15. package/dist/session/credential/credentials.js +32 -28
  16. package/dist/session/discovery/bundle.d.ts +9 -4
  17. package/dist/session/discovery/bundle.js +28 -35
  18. package/dist/session/discovery/discovery.d.ts +1 -1
  19. package/dist/session/discovery/discovery.js +7 -10
  20. package/dist/session/discovery/release.js +18 -28
  21. package/dist/session/discovery/transport.d.ts +35 -3
  22. package/dist/session/discovery/transport.js +40 -1
  23. package/dist/session/exchange/exchange.d.ts +3 -2
  24. package/dist/session/exchange/exchange.js +10 -7
  25. package/dist/session/exchange/index.d.ts +1 -1
  26. package/dist/session/exchange/index.js +1 -1
  27. package/dist/session/exchange/presentation.js +28 -10
  28. package/dist/session/exchange/source.d.ts +7 -7
  29. package/dist/session/exchange/source.js +26 -27
  30. package/dist/session/routing/auth.d.ts +9 -3
  31. package/dist/session/routing/auth.js +4 -3
  32. package/dist/session/routing/cache.d.ts +12 -5
  33. package/dist/session/routing/cache.js +56 -48
  34. package/dist/session/routing/dispatch.d.ts +2 -1
  35. package/dist/session/routing/dispatch.js +83 -61
  36. package/dist/session/routing/index.d.ts +1 -1
  37. package/dist/session/routing/recovery.d.ts +3 -6
  38. package/dist/session/routing/recovery.js +3 -14
  39. package/dist/session/routing/store.js +4 -5
  40. package/dist/session/views/kernel.d.ts +31 -0
  41. package/dist/session/views/kernel.js +30 -0
  42. package/dist/session/views/read.js +5 -10
  43. package/dist/session/views/view.js +1 -6
  44. package/dist/store/memory.d.ts +1 -3
  45. package/dist/store/memory.js +61 -112
  46. package/dist/store/shape.d.ts +33 -12
  47. package/dist/store/shape.js +125 -16
  48. package/dist/store/store.js +1 -1
  49. package/dist/transport/auto/decision.d.ts +26 -14
  50. package/dist/transport/auto/decision.js +35 -32
  51. package/dist/transport/auto/fallback.d.ts +1 -1
  52. package/dist/transport/auto/fallback.js +5 -10
  53. package/dist/transport/auto/transport.d.ts +0 -2
  54. package/dist/transport/auto/transport.js +24 -32
  55. package/dist/transport/failure.d.ts +28 -1
  56. package/dist/transport/failure.js +57 -1
  57. package/dist/transport/http/admission.js +2 -2
  58. package/dist/transport/http/binary.js +1 -1
  59. package/dist/transport/http/byte-stream.d.ts +2 -1
  60. package/dist/transport/http/byte-stream.js +10 -7
  61. package/dist/transport/http/stream.d.ts +8 -13
  62. package/dist/transport/http/stream.js +32 -79
  63. package/dist/transport/http/transport.js +11 -22
  64. package/dist/transport/stream.d.ts +52 -0
  65. package/dist/transport/stream.js +101 -0
  66. package/dist/transport/unary.d.ts +3 -2
  67. package/dist/transport/unary.js +3 -3
  68. package/dist/transport/websocket/connection.d.ts +7 -3
  69. package/dist/transport/websocket/connection.js +102 -85
  70. package/dist/transport/websocket/exchange.d.ts +10 -19
  71. package/dist/transport/websocket/exchange.js +72 -153
  72. package/dist/transport/websocket/transport.js +11 -19
  73. package/package.json +6 -5
@@ -1,6 +1,7 @@
1
1
  import { Target } from '@astrale-os/kernel-core/callable';
2
2
  import { Path } from '@astrale-os/kernel-core/path';
3
3
  import * as portable from '@astrale-os/kernel-dsl/value';
4
+ import { ENVELOPE_LIMITS } from '@astrale-os/kernel-protocol/codecs';
4
5
  /** Parent-private Call acceptance shared by Client and Client Session. */
5
6
  export function acceptCall(input) {
6
7
  if (input === null || typeof input !== 'object' || Array.isArray(input)) {
@@ -25,7 +26,8 @@ function admitPath(input) {
25
26
  }
26
27
  function admitInput(input) {
27
28
  try {
28
- return portable.acceptImmutable(input);
29
+ // As deep as an envelope carries it: a Query document reaches its own nesting bound first.
30
+ return portable.acceptImmutable(input, { limits: ENVELOPE_LIMITS });
29
31
  }
30
32
  catch (cause) {
31
33
  throw new TypeError('Client input must be a portable Value.', { cause });
@@ -4,15 +4,26 @@ import type { Transport } from '../transport/index.js';
4
4
  import type { AuthenticatedClient, RemoteCredential } from './credential.js';
5
5
  import type { Call, ClientDispatchOptions, ClientDispatchOptionsWithBody } from './request.js';
6
6
  import type { BinaryResponse, Result, StreamResult, ValueResult } from './result.js';
7
+ import type { RoutingControl } from './routing-control.js';
7
8
  import { type HttpTransportOptions } from '../transport/http/index.js';
8
9
  export type ClientOptions = HttpTransportOptions | {
9
10
  readonly transport: Transport;
10
11
  };
12
+ /** One package-private send: the Trace of a redirect continuation and an admitted body, if any. */
13
+ export interface InternalDispatch {
14
+ readonly credential?: RemoteCredential;
15
+ readonly call: Call;
16
+ readonly options?: ClientDispatchOptions;
17
+ readonly trace?: protocol.Trace;
18
+ readonly body?: BinaryBody;
19
+ }
11
20
  /**
12
- * Package-private Session routing path: it presents a redirect continuation's Trace and sends an
13
- * admitted body, which may be a one-shot stream. Intentionally absent from the public Client facade.
21
+ * Package-private Session routing path: it presents a redirect continuation's Trace, sends an
22
+ * admitted body, which may be a one-shot stream, and answers routing control as a value.
23
+ * Intentionally absent from the public Client facade. A Client this package did not construct is
24
+ * reached through its public methods, so it never answers routing control.
14
25
  */
15
- export declare function dispatchInternal(client: Client, credential: RemoteCredential | undefined, call: Call, options: ClientDispatchOptions | undefined, trace?: protocol.Trace, body?: BinaryBody): Promise<Result>;
26
+ export declare function dispatchInternal(client: Client, dispatch: InternalDispatch): Promise<Result | RoutingControl>;
16
27
  /** Pure client for the universal remote Function invocation boundary. */
17
28
  export declare class Client implements AuthenticatedClient {
18
29
  private readonly transport;
@@ -27,5 +38,7 @@ export declare class Client implements AuthenticatedClient {
27
38
  binary(call: Call, options?: ClientDispatchOptions): Promise<BinaryResponse>;
28
39
  as(credential: RemoteCredential): AuthenticatedClient;
29
40
  close(): void;
41
+ /** The public path: routing control is reported as the error every Client raises for it. */
30
42
  private dispatchWith;
43
+ private dispatchRouted;
31
44
  }
@@ -4,17 +4,37 @@ import { dispatchBinaryBody, HttpTransport, } from '../transport/http/index.js';
4
4
  import { authenticated, resolveCredential } from './credential.js';
5
5
  import { admitRequest, invocation } from './request.js';
6
6
  import { requireBinary, requireStream, requireValue } from './result.js';
7
- import { admittedDeploymentRetiredError, admittedMissError, admittedStaleRouteError, } from './routing-control.js';
7
+ import { isRoutingControl, raisedRoutingControl, routingControlError } from './routing-control.js';
8
8
  const controlledDispatch = new WeakMap();
9
9
  /**
10
- * Package-private Session routing path: it presents a redirect continuation's Trace and sends an
11
- * admitted body, which may be a one-shot stream. Intentionally absent from the public Client facade.
10
+ * Package-private Session routing path: it presents a redirect continuation's Trace, sends an
11
+ * admitted body, which may be a one-shot stream, and answers routing control as a value.
12
+ * Intentionally absent from the public Client facade. A Client this package did not construct is
13
+ * reached through its public methods, so it never answers routing control.
12
14
  */
13
- export function dispatchInternal(client, credential, call, options, trace, body) {
14
- const dispatch = controlledDispatch.get(client);
15
- if (dispatch === undefined)
15
+ export function dispatchInternal(client, dispatch) {
16
+ const controlled = controlledDispatch.get(client);
17
+ if (controlled !== undefined)
18
+ return controlled(dispatch);
19
+ if (dispatch.trace !== undefined || dispatch.body !== undefined) {
16
20
  throw new TypeError('Internal dispatch requires an owned Client.');
17
- return dispatch(credential, call, options, trace, body);
21
+ }
22
+ return dispatchPublic(client, dispatch);
23
+ }
24
+ /**
25
+ * A caller-supplied pool may wrap a real Client, whose public dispatch raises routing control as
26
+ * an error: only the exact error a Client raised answers its control; any other error propagates.
27
+ */
28
+ async function dispatchPublic(client, { credential, call, options }) {
29
+ try {
30
+ return await (credential === undefined ? client : client.as(credential)).dispatch(call, options);
31
+ }
32
+ catch (cause) {
33
+ const control = raisedRoutingControl(cause);
34
+ if (control === undefined)
35
+ throw cause;
36
+ return control;
37
+ }
18
38
  }
19
39
  /** Pure client for the universal remote Function invocation boundary. */
20
40
  export class Client {
@@ -28,7 +48,7 @@ export class Client {
28
48
  this.transport = Object.hasOwn(options, 'transport')
29
49
  ? admitTransport(options.transport)
30
50
  : new HttpTransport(options);
31
- controlledDispatch.set(this, (credential, call, requestOptions, trace, body) => this.dispatchWith(credential, call, requestOptions, trace, body));
51
+ controlledDispatch.set(this, (dispatch) => this.dispatchRouted(dispatch.credential, dispatch.call, dispatch.options, dispatch.trace, dispatch.body));
32
52
  }
33
53
  dispatch(call, options) {
34
54
  return this.dispatchWith(undefined, call, options);
@@ -53,7 +73,14 @@ export class Client {
53
73
  this.lifecycle.abort(failure);
54
74
  this.transport.close?.();
55
75
  }
56
- async dispatchWith(credential, input, options, trace, body) {
76
+ /** The public path: routing control is reported as the error every Client raises for it. */
77
+ async dispatchWith(credential, input, options) {
78
+ const result = await this.dispatchRouted(credential, input, options);
79
+ if (isRoutingControl(result))
80
+ throw routingControlError(result);
81
+ return result;
82
+ }
83
+ async dispatchRouted(credential, input, options, trace, body) {
57
84
  if (this.closed)
58
85
  throw new ClientError('Client is closed.');
59
86
  const request = admitRequest(input, options, this.lifecycle.signal, body);
@@ -80,12 +107,6 @@ export class Client {
80
107
  cancelUnsent(request.body);
81
108
  throw cause;
82
109
  }
83
- if (result.kind === 'stale')
84
- throw admittedStaleRouteError(result.current, result.invocation);
85
- if (result.kind === 'miss')
86
- throw admittedMissError(result.invocation);
87
- if (result.kind === 'deployment-retired')
88
- throw admittedDeploymentRetiredError(result);
89
110
  return result;
90
111
  }
91
112
  }
@@ -1,6 +1,6 @@
1
- export { Client, dispatchInternal, type ClientOptions } from './client.js';
1
+ export { Client, dispatchInternal, type ClientOptions, type InternalDispatch } from './client.js';
2
2
  export { acceptCall } from './admission.js';
3
3
  export type { AuthenticatedClient, RemoteCredential } from './credential.js';
4
4
  export { call, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, } from './request.js';
5
5
  export type { Binary, BinaryResponse, ExecutionResult, Input, RedirectResult, Result, Stream, StreamResult, ValueResult, } from './result.js';
6
- export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
6
+ export { isRoutingControl, routingControlError, type RoutingControl } from './routing-control.js';
@@ -1,4 +1,4 @@
1
1
  export { Client, dispatchInternal } from './client.js';
2
2
  export { acceptCall } from './admission.js';
3
3
  export { call, } from './request.js';
4
- export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
4
+ export { isRoutingControl, routingControlError } from './routing-control.js';
@@ -1,18 +1,14 @@
1
- import type { invocation as protocol, release } from '@astrale-os/kernel-protocol';
2
- import type { DeploymentRetired } from '../transport/index.js';
1
+ import type { DeploymentRetired, MissControl, StaleControl } from '../transport/index.js';
2
+ import type { Result } from './result.js';
3
3
  import { MissError, ResponseError, StaleRouteError } from '../errors/index.js';
4
- /** Create a private routing witness only after exact reserved-control decoding. */
5
- export declare function admittedMissError(invocation: protocol.InvocationId): MissError;
6
- /** Create a private routing witness only after exact reserved-control decoding. */
7
- export declare function admittedStaleRouteError(current: release.Sha256Digest, invocation: protocol.InvocationId): StaleRouteError;
4
+ /** A reserved pre-handler control the Transport decoded in place of a Function result. */
5
+ export type RoutingControl = StaleControl | MissControl | DeploymentRetired;
6
+ /** Whether a package-private dispatch answered with routing control rather than a result. */
7
+ export declare function isRoutingControl(input: Result | RoutingControl): input is RoutingControl;
8
8
  /**
9
- * Raise one decoded retirement control as the typed error every Client reports for it,
10
- * `ResponseError(3002, DEPLOYMENT_RETIRED)`, privately witnessed for Session recovery.
9
+ * The public error every Client reports for one routing control; a retirement is
10
+ * `ResponseError(3002, DEPLOYMENT_RETIRED)`.
11
11
  */
12
- export declare function admittedDeploymentRetiredError(control: DeploymentRetired): ResponseError;
13
- /** Distinguish decoded routing control from public or caller-supplied lookalike errors. */
14
- export declare function isAdmittedMissError(input: unknown): input is MissError;
15
- /** Distinguish decoded routing control from public or caller-supplied lookalike errors. */
16
- export declare function isAdmittedStaleRouteError(input: unknown): input is StaleRouteError;
17
- /** Distinguish a decoded retirement control from a lookalike `DEPLOYMENT_RETIRED` response. */
18
- export declare function isAdmittedDeploymentRetiredError(input: unknown): input is ResponseError;
12
+ export declare function routingControlError(control: RoutingControl): StaleRouteError | MissError | ResponseError;
13
+ /** The routing control this exact error was raised for; a lookalike error carries none. */
14
+ export declare function raisedRoutingControl(input: unknown): RoutingControl | undefined;
@@ -1,38 +1,30 @@
1
1
  import { CODES } from '@astrale-os/kernel-protocol/errors';
2
2
  import { MissError, ResponseError, StaleRouteError } from '../errors/index.js';
3
- const admittedMisses = new WeakSet();
4
- const admittedStaleRoutes = new WeakSet();
5
- const admittedRetirements = new WeakSet();
6
- /** Create a private routing witness only after exact reserved-control decoding. */
7
- export function admittedMissError(invocation) {
8
- const error = new MissError(invocation);
9
- admittedMisses.add(error);
10
- return error;
11
- }
12
- /** Create a private routing witness only after exact reserved-control decoding. */
13
- export function admittedStaleRouteError(current, invocation) {
14
- const error = new StaleRouteError(current, invocation);
15
- admittedStaleRoutes.add(error);
16
- return error;
3
+ const raised = new WeakMap();
4
+ /** Whether a package-private dispatch answered with routing control rather than a result. */
5
+ export function isRoutingControl(input) {
6
+ return input.kind === 'stale' || input.kind === 'miss' || input.kind === 'deployment-retired';
17
7
  }
18
8
  /**
19
- * Raise one decoded retirement control as the typed error every Client reports for it,
20
- * `ResponseError(3002, DEPLOYMENT_RETIRED)`, privately witnessed for Session recovery.
9
+ * The public error every Client reports for one routing control; a retirement is
10
+ * `ResponseError(3002, DEPLOYMENT_RETIRED)`.
21
11
  */
22
- export function admittedDeploymentRetiredError(control) {
23
- const error = new ResponseError(CODES.NOT_FOUND, control.message, control.invocation, control.reason);
24
- admittedRetirements.add(error);
12
+ export function routingControlError(control) {
13
+ const error = publicError(control);
14
+ raised.set(error, control);
25
15
  return error;
26
16
  }
27
- /** Distinguish decoded routing control from public or caller-supplied lookalike errors. */
28
- export function isAdmittedMissError(input) {
29
- return input instanceof MissError && admittedMisses.has(input);
30
- }
31
- /** Distinguish decoded routing control from public or caller-supplied lookalike errors. */
32
- export function isAdmittedStaleRouteError(input) {
33
- return input instanceof StaleRouteError && admittedStaleRoutes.has(input);
17
+ /** The routing control this exact error was raised for; a lookalike error carries none. */
18
+ export function raisedRoutingControl(input) {
19
+ return typeof input === 'object' && input !== null ? raised.get(input) : undefined;
34
20
  }
35
- /** Distinguish a decoded retirement control from a lookalike `DEPLOYMENT_RETIRED` response. */
36
- export function isAdmittedDeploymentRetiredError(input) {
37
- return input instanceof ResponseError && admittedRetirements.has(input);
21
+ function publicError(control) {
22
+ switch (control.kind) {
23
+ case 'stale':
24
+ return new StaleRouteError(control.current, control.invocation);
25
+ case 'miss':
26
+ return new MissError(control.invocation);
27
+ case 'deployment-retired':
28
+ return new ResponseError(CODES.NOT_FOUND, control.message, control.invocation, control.reason);
29
+ }
38
30
  }
@@ -1,3 +1,4 @@
1
+ import { ENVELOPE_POINTER_LENGTH } from '@astrale-os/kernel-protocol/codecs';
1
2
  import * as errors from '@astrale-os/kernel-protocol/errors';
2
3
  import { ResponseError } from './response-error.js';
3
4
  /**
@@ -68,7 +69,7 @@ function isRefusal(input) {
68
69
  /** An RFC 6901 pointer into the request, as the Kernel bounds it. */
69
70
  function isPointer(input) {
70
71
  return (typeof input === 'string' &&
71
- input.length <= 1_024 &&
72
+ input.length <= ENVELOPE_POINTER_LENGTH &&
72
73
  input.normalize('NFC') === input &&
73
74
  (input === '' || input.startsWith('/')));
74
75
  }
@@ -1,6 +1,6 @@
1
1
  import type { invocation as protocol, release } from '@astrale-os/kernel-protocol';
2
2
  import { ClientError } from './client-error.js';
3
- /** Client-visible stale-route error shape; public instances are not routing-control witnesses. */
3
+ /** Client-visible stale-route error the Client raises for a decoded Stale control. */
4
4
  export declare class StaleRouteError extends ClientError {
5
5
  readonly invocation: protocol.InvocationId;
6
6
  readonly name = "StaleRouteError";
@@ -1,5 +1,5 @@
1
1
  import { ClientError } from './client-error.js';
2
- /** Client-visible stale-route error shape; public instances are not routing-control witnesses. */
2
+ /** Client-visible stale-route error the Client raises for a decoded Stale control. */
3
3
  export class StaleRouteError extends ClientError {
4
4
  invocation;
5
5
  name = 'StaleRouteError';
@@ -1,6 +1,7 @@
1
1
  import type { EdgeKey } from '@astrale-os/kernel-core/graph/edge';
2
2
  import type { FactId } from '@astrale-os/kernel-core/graph/formula';
3
3
  import type { Answer, QueryResult, Undecided, wire } from '@astrale-os/kernel-core/graph/query';
4
+ import type { ClassKey } from '@astrale-os/kernel-dsl/v1/addressing';
4
5
  /** Caller-selected bounds and continuation for one graph query page. */
5
6
  export interface QueryPageRequest {
6
7
  readonly size: number;
@@ -32,9 +33,13 @@ export type QueryPage = {
32
33
  readonly complete: false;
33
34
  readonly cursor: string;
34
35
  });
35
- /** One delivered item: its fact, the Edge its Branch followed, the ends it renders, its Branches. */
36
+ /**
37
+ * One delivered item: its fact, its Class when the fact is a Node, the Edge its Branch followed,
38
+ * the ends it renders, its Branches.
39
+ */
36
40
  export interface QueryItem {
37
41
  readonly fact: FactId;
42
+ readonly class?: ClassKey;
38
43
  readonly edge?: EdgeKey;
39
44
  readonly source?: QueryItem;
40
45
  readonly target?: QueryItem;
@@ -43,7 +48,7 @@ export interface QueryItem {
43
48
  }>>>;
44
49
  }
45
50
  /**
46
- * What a Query answers, by the family of its root fold: a list's Page, the table of the facts it
51
+ * What a Query answers, by its family: a list's Page, the table of the facts it
47
52
  * renders as values, the revision it was read at and whether its cursor came from another (W6);
48
53
  * an `exists`; or a `count`.
49
54
  */
@@ -57,7 +62,7 @@ export type QueryAnswer = {
57
62
  } | Exclude<Answer, {
58
63
  readonly list: unknown;
59
64
  }>;
60
- /** The answer of the family a Query's root fold names. */
65
+ /** The answer of the family a Query names: `list`, `exists` or `count`. */
61
66
  export type QueryAnswerFor<Query extends wire.Document> = Query extends {
62
67
  readonly list: unknown;
63
68
  } ? Extract<QueryAnswer, {
@@ -3,6 +3,7 @@ import { Path, PathError } from '@astrale-os/kernel-core/path';
3
3
  import { queryOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
4
4
  import { query } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
5
5
  import * as portable from '@astrale-os/kernel-dsl/value';
6
+ import { ENVELOPE_LIMITS } from '@astrale-os/kernel-protocol/codecs';
6
7
  import { call as invocation } from '../client/index.js';
7
8
  import { captureExpected } from './expectation.js';
8
9
  import { retainQueryProvenance } from './provenance.js';
@@ -82,7 +83,8 @@ function admitPaging(input) {
82
83
  /** A detached, frozen portable snapshot of one caller value. */
83
84
  function snapshot(input, what) {
84
85
  try {
85
- return portable.acceptImmutable(input);
86
+ // As deep as an envelope carries it: the Kernel refuses a document past its nesting bound.
87
+ return portable.acceptImmutable(input, { limits: ENVELOPE_LIMITS });
86
88
  }
87
89
  catch (cause) {
88
90
  if (!(cause instanceof portable.BoundaryError))
@@ -94,7 +96,7 @@ function invalid(what, detail, cause) {
94
96
  const subject = what === 'query' ? 'Graph query' : 'Graph query paging';
95
97
  throw new TypeError(`${subject} is invalid: ${detail}.`, { cause });
96
98
  }
97
- /** The family a Query's root fold names; undefined unless it names exactly one. */
99
+ /** The family a Query names (`list`, `exists` or `count`); undefined unless it names one. */
98
100
  function familyOf(query) {
99
101
  const families = ['list', 'exists', 'count'].filter((family) => family in query);
100
102
  return families.length === 1 ? families[0] : undefined;
@@ -122,13 +124,17 @@ function decodeAnswer(input, family) {
122
124
  const answer = value;
123
125
  return 'list' in answer && !pagesClosed(answer.list) ? refuse() : answer;
124
126
  }
125
- /** Every Page, its Branches' included, carries a cursor exactly when an item follows it (W3). */
127
+ /**
128
+ * Every Page, its Branches' included, carries a cursor exactly when an item follows it (W3), and
129
+ * only a Node item carries a Class.
130
+ */
126
131
  function pagesClosed(page) {
127
132
  const continued = 'cursor' in page;
128
133
  return page.complete !== continued && page.items.every(itemClosed);
129
134
  }
130
135
  function itemClosed(item) {
131
- return ((item.source === undefined || itemClosed(item.source)) &&
136
+ return ((!('class' in item) || typeof item.fact === 'string') &&
137
+ (item.source === undefined || itemClosed(item.source)) &&
132
138
  (item.target === undefined || itemClosed(item.target)) &&
133
139
  Object.values(item.branches).every((branch) => !('items' in branch) || pagesClosed(branch)));
134
140
  }
@@ -23,7 +23,7 @@ async function refusals() {
23
23
  await graph.query(ast);
24
24
  // @ts-expect-error A Query names the v7 version.
25
25
  await graph.query({ query: 'astrale.query/6', list: { nodes: [Task] } });
26
- // @ts-expect-error A Query's root fold is list, exists or count.
26
+ // @ts-expect-error A Query is a list, an exists or a count.
27
27
  await graph.query({ query: QUERY, nodes: [Task] });
28
28
  // @ts-expect-error A count needs its bound.
29
29
  await graph.query({ query: QUERY, count: { nodes: [Task] } });
@@ -5,7 +5,7 @@ import { function as functions } from '@astrale-os/kernel-core/schema/kernel/sys
5
5
  import { Key } from '@astrale-os/kernel-dsl/v1/addressing';
6
6
  import { ClientError } from '../errors/index.js';
7
7
  import { runSessionOperation, sessionTransportOptions } from './context/index.js';
8
- import { callableOrigin, exchangeDomainCredential, installedIssuer, isAuthority, } from './exchange/index.js';
8
+ import { callableOrigin, exchangeDomainCredential, EXHAUSTED, installedIssuer, sourceExhausted, } from './exchange/index.js';
9
9
  import { matchesCallable } from './reference.js';
10
10
  import { requireResultKind, resolveAuth } from './routing/index.js';
11
11
  const ADMIT = Path.staticMethod(Path.project(functions.admit.owner), functions.admit.name);
@@ -17,7 +17,7 @@ export async function admitFunction(dependencies, call, operation) {
17
17
  throw new ClientError('Function admission requires a Domain-qualified callable target.');
18
18
  }
19
19
  const effective = await resolveAuth(dependencies.auth, call, operation);
20
- if (!isAuthority(effective)) {
20
+ if (effective.kind === 'anonymous') {
21
21
  throw new ClientError('Function admission requires an authenticated session.');
22
22
  }
23
23
  // Resolve once for the intended Call, then retain that exact caller across every helper syscall.
@@ -27,6 +27,8 @@ export async function admitFunction(dependencies, call, operation) {
27
27
  }
28
28
  // The Kernel preserves the session caller when issuing the delegation.
29
29
  const exchanged = await exchangeDomainCredential(dependencies, effective, { issuer: domain, ttlSeconds: effective.delegate.ttlSeconds }, operation);
30
+ if (exchanged === EXHAUSTED)
31
+ throw sourceExhausted();
30
32
  const result = await runSessionOperation(operation, () => dependencies
31
33
  .source()
32
34
  .as(exchanged.credential)
@@ -31,12 +31,11 @@ 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;
41
40
  /** A caller without a signal keeps the mint in flight alive; anticipation does not. */
42
41
  let unsignalled = false;
@@ -56,7 +55,12 @@ export function credentials(source) {
56
55
  async function resolve(_call, signal) {
57
56
  return { credential: (await acquire(signal)).credential };
58
57
  }
58
+ /** The credential the published state holds, if any. */
59
+ function held() {
60
+ return 'credential' in state ? state.credential : undefined;
61
+ }
59
62
  function acquire(signal) {
63
+ const current = held();
60
64
  if (current !== undefined && covers(current))
61
65
  return Promise.resolve(current);
62
66
  return share(signal);
@@ -77,10 +81,10 @@ export function credentials(source) {
77
81
  function share(signal) {
78
82
  if (signal?.aborted === true)
79
83
  return Promise.reject(signal.reason);
80
- const pending = inflight ?? begin();
84
+ const flight = minting ?? begin();
81
85
  if (signal === undefined) {
82
86
  unsignalled = true;
83
- return pending;
87
+ return flight.promise;
84
88
  }
85
89
  waiting += 1;
86
90
  let settled = false;
@@ -93,7 +97,7 @@ export function credentials(source) {
93
97
  signal.removeEventListener('abort', cancel);
94
98
  // Nobody is waiting and nobody is anticipating: the mint has no beneficiary left.
95
99
  if (waiting === 0 && !anticipating && !unsignalled)
96
- controller?.abort(signal.reason);
100
+ minting?.controller.abort(signal.reason);
97
101
  };
98
102
  const cancel = () => {
99
103
  const reason = signal.reason;
@@ -101,7 +105,7 @@ export function credentials(source) {
101
105
  fail(reason);
102
106
  };
103
107
  signal.addEventListener('abort', cancel, { once: true });
104
- pending.then((credential) => {
108
+ flight.promise.then((credential) => {
105
109
  if (settled)
106
110
  return;
107
111
  settled = true;
@@ -118,28 +122,28 @@ export function credentials(source) {
118
122
  });
119
123
  });
120
124
  }
125
+ /** Begin a mint; without a mint capability, the returned one has already failed and is not held. */
121
126
  function begin() {
127
+ const controller = new AbortController();
122
128
  if (mint === undefined) {
123
129
  const error = new ClientError('Session credential needs renewal, but no mint was supplied.');
124
130
  settleFailure(error);
125
- return Promise.reject(error);
131
+ return { promise: Promise.reject(error), controller };
126
132
  }
127
133
  const renew = mint;
134
+ const current = held();
128
135
  publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
129
- const owned = new AbortController();
130
- controller = owned;
131
136
  unsignalled = false;
132
- const signal = AbortSignal.any([owned.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
133
- const pending = (async () => {
137
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
138
+ const promise = (async () => {
134
139
  try {
135
140
  // A mint that throws instead of rejecting fails this attempt alike: the executor turns the
136
- // throw into a rejection, so the attempt settles only after it yields, once `inflight`
141
+ // throw into a rejection, so the attempt settles only after it yields, once `minting`
137
142
  // holds it, and the cleanup below releases it for the next acquisition.
138
- const minting = new Promise((complete) => {
143
+ const returned = new Promise((complete) => {
139
144
  complete(renew(signal));
140
145
  });
141
- const minted = admitMinted(await minting);
142
- current = minted;
146
+ const minted = admitMinted(await returned);
143
147
  attempt = 0;
144
148
  publish({ status: 'valid', credential: minted });
145
149
  if (anticipating)
@@ -151,21 +155,20 @@ export function credentials(source) {
151
155
  throw error;
152
156
  }
153
157
  finally {
154
- inflight = undefined;
155
- controller = undefined;
158
+ minting = undefined;
156
159
  }
157
160
  })();
158
- inflight = pending;
161
+ minting = { promise, controller };
159
162
  // A rejection reaches every waiter; keep an unattached one from surfacing as unhandled.
160
- pending.catch(() => undefined);
161
- return pending;
163
+ promise.catch(() => undefined);
164
+ return minting;
162
165
  }
163
166
  function settleFailure(error) {
167
+ const current = held();
164
168
  if (current !== undefined && current.expiresAt > Date.now()) {
165
169
  publish({ status: 'degraded', credential: current, error });
166
170
  }
167
171
  else {
168
- current = undefined;
169
172
  publish({ status: 'expired', error });
170
173
  }
171
174
  if (anticipating)
@@ -176,8 +179,9 @@ export function credentials(source) {
176
179
  clearTimers();
177
180
  if (!anticipating)
178
181
  return;
182
+ const current = held();
179
183
  if (current === undefined) {
180
- void (inflight ?? begin()).catch(() => undefined);
184
+ void (minting ?? begin()).promise.catch(() => undefined);
181
185
  return;
182
186
  }
183
187
  // The threshold itself, with no extra lead: chained providers sharing this rule must not
@@ -188,6 +192,7 @@ export function credentials(source) {
188
192
  function retry() {
189
193
  if (refreshTimer !== undefined)
190
194
  return;
195
+ const current = held();
191
196
  if (current !== undefined)
192
197
  armExpiry(current);
193
198
  // Without a mint nothing can replace the held credential; only its expiry remains to report.
@@ -200,7 +205,7 @@ export function credentials(source) {
200
205
  function armRefresh(delay) {
201
206
  refreshTimer = setTimeout(() => {
202
207
  refreshTimer = undefined;
203
- void (inflight ?? begin()).catch(() => undefined);
208
+ void (minting ?? begin()).promise.catch(() => undefined);
204
209
  }, delay);
205
210
  }
206
211
  function armExpiry(credential) {
@@ -208,9 +213,8 @@ export function credentials(source) {
208
213
  clearTimeout(expiryTimer);
209
214
  expiryTimer = setTimeout(() => {
210
215
  expiryTimer = undefined;
211
- if (!anticipating || current !== credential)
216
+ if (!anticipating || held() !== credential)
212
217
  return;
213
- current = undefined;
214
218
  publish({ status: 'expired', error: new ClientError('Session credential expired.') });
215
219
  }, clamp(credential.expiresAt - Date.now()));
216
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
  }