@astrale-os/kernel-client 0.6.0-beta.88 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/client/index.d.ts +1 -1
  2. package/dist/client/request.d.ts +1 -0
  3. package/dist/client/request.js +17 -0
  4. package/dist/client/result.d.ts +4 -1
  5. package/dist/client/result.js +10 -4
  6. package/dist/errors/index.d.ts +1 -0
  7. package/dist/errors/index.js +1 -0
  8. package/dist/errors/refusal.d.ts +12 -0
  9. package/dist/errors/refusal.js +40 -0
  10. package/dist/graph/domain/binding.js +4 -0
  11. package/dist/graph/page-contract.d.ts +6 -0
  12. package/dist/graph/query.js +10 -2
  13. package/dist/pacer/index.d.ts +1 -1
  14. package/dist/pacer/index.js +1 -1
  15. package/dist/pacer/retry/index.d.ts +1 -0
  16. package/dist/pacer/retry/index.js +1 -0
  17. package/dist/pacer/retry/refusals.d.ts +7 -0
  18. package/dist/pacer/retry/refusals.js +10 -0
  19. package/dist/pacer/retry/retry.d.ts +2 -0
  20. package/dist/pacer/retry/retry.js +33 -1
  21. package/dist/schema/admission.d.ts +1 -1
  22. package/dist/schema/admission.js +2 -2
  23. package/dist/schema/contracts.d.ts +95 -2
  24. package/dist/schema/index.d.ts +2 -1
  25. package/dist/schema/installation.d.ts +104 -0
  26. package/dist/schema/installation.js +144 -0
  27. package/dist/schema/schema.d.ts +18 -3
  28. package/dist/schema/schema.js +31 -35
  29. package/dist/session/bound.js +42 -0
  30. package/dist/session/credential/{provider.d.ts → credentials.d.ts} +21 -12
  31. package/dist/session/credential/{provider.js → credentials.js} +75 -15
  32. package/dist/session/credential/index.d.ts +1 -1
  33. package/dist/session/credential/index.js +1 -1
  34. package/dist/session/credential/limits.d.ts +2 -0
  35. package/dist/session/credential/limits.js +2 -0
  36. package/dist/session/exchange/presentation.js +7 -7
  37. package/dist/session/execution.d.ts +24 -1
  38. package/dist/session/index.d.ts +2 -2
  39. package/dist/session/index.js +1 -1
  40. package/dist/session/reference.d.ts +8 -4
  41. package/dist/session/reference.js +7 -2
  42. package/dist/session/routing/dispatch.js +2 -0
  43. package/dist/session/routing/request.d.ts +4 -0
  44. package/dist/session/routing/request.js +11 -1
  45. package/dist/session/routing/result.d.ts +1 -1
  46. package/dist/session/routing/result.js +5 -1
  47. package/dist/session/session.d.ts +1 -1
  48. package/dist/session/session.js +11 -8
  49. package/dist/session/session.typecheck.js +12 -9
  50. package/dist/store/memory.js +20 -1
  51. package/dist/transport/http/admission.js +3 -0
  52. package/dist/transport/transport.d.ts +10 -0
  53. package/dist/transport/websocket/exchange.js +8 -0
  54. package/package.json +5 -5
@@ -0,0 +1,144 @@
1
+ import { Path } from '@astrale-os/kernel-core/path';
2
+ import { abortSignal, commandSignal, executionOutcome, executionStatus, uninstallOutput, } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
+ import { execution as methods } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
4
+ import { MethodKey } from '@astrale-os/kernel-dsl/v1/addressing';
5
+ import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
6
+ import { call as invocation } from '../client/index.js';
7
+ import { ResponseError, TransportError } from '../errors/index.js';
8
+ import { RETRY_REFUSALS, retry } from '../pacer/index.js';
9
+ import { acceptOutput } from './admission.js';
10
+ /** Attempts of one effect-free Execution read; the wait's deadline bounds them too. */
11
+ const READ_ATTEMPTS = 8;
12
+ /** A pending answer sooner than this did not wait: the Kernel answers now, so waiting ends. */
13
+ const LAPSED_WAIT_MS = 1_000;
14
+ /** No wait starts with less time left than this before its deadline. */
15
+ const MINIMUM_WAIT_MS = 1_000;
16
+ /** The `K.Execution` Methods of one Execution, over one call capability; package-private. */
17
+ export function executionMethods(call, options) {
18
+ const value = async (id, method, input, request) => {
19
+ const target = Path.instanceMethod(Path.id(id), MethodKey.of(method.owner, method.name));
20
+ const result = await call(invocation(target, input), options(request));
21
+ if (result.kind !== 'value')
22
+ throw new TypeError('Execution Method returned a non-value result.');
23
+ return result.value;
24
+ };
25
+ /**
26
+ * An Execution read has no effect: one a process refused with a retry delay, or a gap with no
27
+ * process on the port failed, is sent again through the pacer, each attempt within `deadline`.
28
+ */
29
+ const read = (deadline, request, work) => retry(() => work({ ...request, timeoutMs: Math.max(1, deadline - Date.now()) }), {
30
+ maxAttempts: READ_ATTEMPTS,
31
+ shouldRetry: (error, attempt) => Date.now() < deadline &&
32
+ (error instanceof TransportError || RETRY_REFUSALS.shouldRetry(error, attempt)),
33
+ retryAfter: RETRY_REFUSALS.retryAfter,
34
+ });
35
+ const status = async (id, accept, answer) => {
36
+ const admitted = acceptOutput(executionStatus, await answer, 'Execution status');
37
+ if (admitted.id !== id)
38
+ throw new TypeError('Kernel returned the status of another Execution.');
39
+ const outcome = admitted.outcome === undefined ? undefined : outcomeOf(admitted.outcome, accept);
40
+ // A deleted Execution carries the outcome its lifecycle record keeps, whatever its kind.
41
+ if (admitted.state !== 'deleted' &&
42
+ (admitted.state === 'completed') !== (outcome?.kind === 'completed')) {
43
+ throw new TypeError('Execution status and outcome disagree.');
44
+ }
45
+ if (admitted.state === 'deleted')
46
+ return Object.freeze({ id, state: 'deleted', outcome: outcome });
47
+ const { outcome: _outcome, ...rest } = admitted;
48
+ return Object.freeze({ ...rest, ...(outcome === undefined ? {} : { outcome }) });
49
+ };
50
+ return Object.freeze({
51
+ status: (id, accept, request) => status(id, accept, value(id, methods.status, {}, request)),
52
+ async result(id, accept, wait = {}, request) {
53
+ const answer = await value(id, methods.result, { ...wait }, request);
54
+ return outcomeOf(acceptOutput(executionOutcome, answer, 'Execution outcome'), accept);
55
+ },
56
+ async signal(id, name, signalled, request) {
57
+ await value(id, methods.signal, { name, value: signalled }, request);
58
+ },
59
+ cancel: (id, accept, input, request) => status(id, accept, value(id, methods.cancel, { ...input }, request)),
60
+ resume: (id, accept, request) => status(id, accept, value(id, methods.resume, {}, request)),
61
+ async delete(id, request) {
62
+ await value(id, methods.delete, {}, request);
63
+ },
64
+ /** Admit what a durable call answers at once: the Execution it created or recovered. */
65
+ async start(path, input, request) {
66
+ const result = await call(invocation(path, input), options(request));
67
+ if (result.kind !== 'execution')
68
+ throw new TypeError('Schema syscall did not answer with an Execution.');
69
+ return result.execution;
70
+ },
71
+ /**
72
+ * Wait within the request deadline for the outcome. A wait that lapsed after waiting, while
73
+ * time remains, waits again; a wait a closing process or a gap with no process failed is sent
74
+ * again. Every other end of the wait, or its deadline, leaves the Execution as it is: its
75
+ * status, read next, says where it is, so the caller never loses the Execution.
76
+ */
77
+ async settle(id, request) {
78
+ const deadline = Date.now() + (options(request).timeoutMs ?? 0);
79
+ while (deadline - Date.now() >= MINIMUM_WAIT_MS) {
80
+ const started = Date.now();
81
+ try {
82
+ await read(deadline, request, (attempt) => value(id, methods.result, { waitMs: attempt.timeoutMs }, attempt));
83
+ return;
84
+ }
85
+ catch (error) {
86
+ const pending = error instanceof ResponseError && error.reason?.code === 'EXECUTION_PENDING';
87
+ if (!pending || Date.now() - started < LAPSED_WAIT_MS)
88
+ return;
89
+ }
90
+ }
91
+ },
92
+ /** The status after a wait, read again as `settle` sends its wait again, within the deadline. */
93
+ observe(id, accept, request) {
94
+ const deadline = Date.now() + (options(request).timeoutMs ?? 0);
95
+ return read(deadline, request, (attempt) => status(id, accept, value(id, methods.status, {}, attempt)));
96
+ },
97
+ });
98
+ }
99
+ /** The install Methods: a completed outcome carries the result its Protocol owner admits. */
100
+ export function createInstallation(executions) {
101
+ const accept = (input) => {
102
+ if (uninstallOutput.safeParse(input).success) {
103
+ throw new TypeError('The Execution is an uninstall: read it through SchemaApi.uninstallation.');
104
+ }
105
+ return protocolSchema.installation.acceptResult(input);
106
+ };
107
+ return Object.freeze({
108
+ status: (execution, request) => executions.status(execution, accept, request),
109
+ result: (execution, wait, request) => executions.result(execution, accept, wait, request),
110
+ apply: async (execution, command, request) => executions.signal(execution, commandSignal(ordinal(command.index)), Object.freeze({
111
+ kind: 'apply',
112
+ ...(command.validation === undefined ? {} : { validation: command.validation }),
113
+ }), request),
114
+ abort: async (execution, attempt, request) => executions.signal(execution, abortSignal(ordinal(attempt)), Object.freeze({ kind: 'abort' }), request),
115
+ cancel: (execution, input = {}, request) => executions.cancel(execution, accept, input, request),
116
+ resume: (execution, request) => executions.resume(execution, accept, request),
117
+ delete: (execution, request) => executions.delete(execution, request),
118
+ });
119
+ }
120
+ /** The uninstall Methods: a completed outcome carries the receipt Core's contract admits. */
121
+ export function createUninstallation(executions) {
122
+ const accept = acceptUninstallReceipt;
123
+ return Object.freeze({
124
+ status: (execution, request) => executions.status(execution, accept, request),
125
+ result: (execution, wait, request) => executions.result(execution, accept, wait, request),
126
+ cancel: (execution, input = {}, request) => executions.cancel(execution, accept, input, request),
127
+ resume: (execution, request) => executions.resume(execution, accept, request),
128
+ delete: (execution, request) => executions.delete(execution, request),
129
+ });
130
+ }
131
+ export function acceptUninstallReceipt(input) {
132
+ return acceptOutput(uninstallOutput, input, 'uninstall receipt');
133
+ }
134
+ function outcomeOf(outcome, accept) {
135
+ if (outcome.kind !== 'completed')
136
+ return outcome;
137
+ return Object.freeze({ kind: 'completed', value: accept(outcome.value) });
138
+ }
139
+ function ordinal(input) {
140
+ if (!Number.isSafeInteger(input) || input < 1) {
141
+ throw new TypeError('A session signal index is a positive integer.');
142
+ }
143
+ return input;
144
+ }
@@ -2,7 +2,8 @@ import type { Key } from '@astrale-os/kernel-dsl/v1';
2
2
  import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
3
3
  import type { Call, Result } from '../client/index.js';
4
4
  import type { RequestOptions } from '../transport/index.js';
5
- import type { InstallRequest, UninstallReceipt, UninstallRequest } from './contracts.js';
5
+ import type { Installation, InstallRequest, Uninstallation, UninstallRequest } from './contracts.js';
6
+ import { type InstallationApi, type UninstallationApi } from './installation.js';
6
7
  export type SchemaCall = (call: Call, options?: RequestOptions) => Promise<Result>;
7
8
  export interface SchemaOptions extends protocolSchema.installation.introspection.Limits {
8
9
  readonly lifecycleTimeoutMs?: number;
@@ -14,8 +15,22 @@ export type InstalledRelease = protocolSchema.installation.introspection.Install
14
15
  export type InstalledPin = protocolSchema.installation.introspection.InstalledPin;
15
16
  export type InstallResult = protocolSchema.installation.InstallResult;
16
17
  export interface SchemaApi {
17
- install(request: InstallRequest, options?: RequestOptions): Promise<InstallResult>;
18
- uninstall(request: UninstallRequest, options?: RequestOptions): Promise<UninstallReceipt>;
18
+ /**
19
+ * Install Domains: start the durable Execution the install is, then, unless `wait` is false or
20
+ * the mode is `maintenance`, wait within the request deadline for its outcome. The answer names
21
+ * the Execution with its status; `result` is present once it completed. A rejected install is a
22
+ * terminal `failed` status, never a failed call.
23
+ */
24
+ install(request: InstallRequest, options?: RequestOptions): Promise<Installation>;
25
+ /** The install executions and repair sessions, through their `K.Execution` Methods. */
26
+ readonly installation: InstallationApi;
27
+ /**
28
+ * Uninstall Domains: start the durable Execution the uninstall is and wait within the request
29
+ * deadline for its outcome. `result` is the receipt once it completed.
30
+ */
31
+ uninstall(request: UninstallRequest, options?: RequestOptions): Promise<Uninstallation>;
32
+ /** The uninstall executions, through their `K.Execution` Methods. */
33
+ readonly uninstallation: UninstallationApi;
19
34
  inspect(origin: Key.Origin, options?: RequestOptions): Promise<DomainInfo>;
20
35
  bundle(origin: Key.Origin, options?: RequestOptions): Promise<DomainBundle>;
21
36
  dependencies(origin: Key.Origin, options?: RequestOptions): Promise<DomainDependencies>;
@@ -1,9 +1,7 @@
1
1
  import { Path } from '@astrale-os/kernel-core/path';
2
- import { uninstallOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
2
  import { install, uninstall } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
4
3
  import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
5
- import { call as invocation } from '../client/index.js';
6
- import { acceptOutput } from './admission.js';
4
+ import { acceptUninstallReceipt, createInstallation, createUninstallation, executionMethods, } from './installation.js';
7
5
  import { introspect } from './introspection.js';
8
6
  const INSTALL_PATH = Path.project(install).raw;
9
7
  const UNINSTALL_PATH = Path.project(uninstall).raw;
@@ -13,34 +11,33 @@ export function createSchema(call, limits) {
13
11
  if (typeof call !== 'function')
14
12
  throw new TypeError('Schema call capability is invalid.');
15
13
  const admittedLimits = admitLimits(limits);
14
+ const executions = executionMethods(call, (options) => lifecycleOptions(options, admittedLimits.lifecycleTimeoutMs));
15
+ const installation = createInstallation(executions);
16
+ const uninstallation = createUninstallation(executions);
16
17
  return Object.freeze({
17
18
  async install(request, options) {
18
- const result = await call(invocation(INSTALL_PATH, request), lifecycleOptions(options, admittedLimits.lifecycleTimeoutMs));
19
- if (result.kind !== 'binary') {
20
- throw new TypeError('Schema install returned a non-binary result.');
19
+ // `wait` is the Client's own: it never reaches the Kernel, so it is no part of the intent.
20
+ const { wait, ...input } = request;
21
+ const execution = await executions.start(INSTALL_PATH, input, options);
22
+ // A maintenance session awaits Root's commands: its outcome is not the call's to wait for.
23
+ if (wait !== false && input.mode !== 'maintenance') {
24
+ await executions.settle(execution, options);
21
25
  }
22
- const { mediaType } = result.value;
23
- const decode = mediaType === protocolSchema.installation.MEDIA_TYPE
24
- ? protocolSchema.installation.decode
25
- : undefined;
26
- if (decode === undefined) {
27
- throw new TypeError('Schema install returned an unsupported media type.');
28
- }
29
- if (!(result.value.body instanceof Uint8Array)) {
30
- await result.value.body[Symbol.asyncIterator]().return?.();
31
- throw new TypeError('Schema install returned a streaming binary result.');
32
- }
33
- const decoded = await decode(result.value.body, installationResultLimit(admittedLimits.maximumReleaseBytes, request.domains.length));
34
- proveInstallResult(request, decoded);
35
- return decoded;
26
+ const status = await executions.observe(execution, protocolSchema.installation.acceptResult, options);
27
+ return admitInstallation(request, execution, status);
36
28
  },
29
+ installation,
37
30
  async uninstall(request, options) {
38
31
  const snapshot = snapshotUninstallRequest(request);
39
- const output = value(await call(invocation(UNINSTALL_PATH, snapshot), lifecycleOptions(options, admittedLimits.lifecycleTimeoutMs)));
40
- const receipt = acceptOutput(uninstallOutput, output);
41
- proveUninstallReceipt(snapshot, receipt);
42
- return receipt;
32
+ const execution = await executions.start(UNINSTALL_PATH, snapshot, options);
33
+ await executions.settle(execution, options);
34
+ const status = await executions.observe(execution, acceptUninstallReceipt, options);
35
+ if (status.outcome?.kind !== 'completed')
36
+ return Object.freeze({ execution, status });
37
+ proveUninstallReceipt(snapshot, status.outcome.value);
38
+ return Object.freeze({ execution, status, result: status.outcome.value });
43
39
  },
40
+ uninstallation,
44
41
  async inspect(origin, options) {
45
42
  return introspect(call, admittedLimits, { kind: 'inspect', origin }, options);
46
43
  },
@@ -75,12 +72,16 @@ function proveUninstallReceipt(request, receipt) {
75
72
  function compare(left, right) {
76
73
  return left < right ? -1 : left > right ? 1 : 0;
77
74
  }
78
- function installationResultLimit(maximumDomainBytes, roots) {
79
- const perDomain = maximumDomainBytes + 4_096;
80
- if (roots > Math.floor((Number.MAX_SAFE_INTEGER - 4_096) / perDomain)) {
81
- return Number.MAX_SAFE_INTEGER;
82
- }
83
- return perDomain * roots + 4_096;
75
+ /**
76
+ * The answer of one install, proved against its request: a completed status carries the result of
77
+ * exactly this operation, admitted by its Protocol owner.
78
+ */
79
+ function admitInstallation(request, execution, status) {
80
+ if (status.outcome?.kind !== 'completed')
81
+ return Object.freeze({ execution, status });
82
+ const result = status.outcome.value;
83
+ proveInstallResult(request, result);
84
+ return Object.freeze({ execution, status, result });
84
85
  }
85
86
  function proveInstallResult(request, result) {
86
87
  if (result.changed) {
@@ -96,11 +97,6 @@ function proveInstallResult(request, result) {
96
97
  throw new TypeError('Schema unchanged result does not match the requested Domain count.');
97
98
  }
98
99
  }
99
- function value(result) {
100
- if (result.kind !== 'value')
101
- throw new TypeError('Schema syscall returned a non-value result.');
102
- return result.value;
103
- }
104
100
  function admitLimits(input) {
105
101
  const lifecycleTimeoutMs = input?.lifecycleTimeoutMs ?? DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS;
106
102
  if (input === null ||
@@ -36,9 +36,29 @@ export function bindSession(source, controls) {
36
36
  const bundle = (origin, options) => schemaSource.bundle(origin, controlOptions(options, admittedControls));
37
37
  const dependencies = (origin, options) => schemaSource.dependencies(origin, controlOptions(options, admittedControls));
38
38
  const installed = (options) => schemaSource.installed(controlOptions(options, admittedControls));
39
+ const installs = schemaSource.installation;
40
+ const installation = Object.freeze({
41
+ status: (execution, options) => installs.status(execution, controlOptions(options, admittedControls)),
42
+ result: (execution, wait, options) => installs.result(execution, wait, controlOptions(options, admittedControls)),
43
+ apply: (execution, command, options) => installs.apply(execution, command, controlOptions(options, admittedControls)),
44
+ abort: (execution, attempt, options) => installs.abort(execution, attempt, controlOptions(options, admittedControls)),
45
+ cancel: (execution, input, options) => installs.cancel(execution, input, controlOptions(options, admittedControls)),
46
+ resume: (execution, options) => installs.resume(execution, controlOptions(options, admittedControls)),
47
+ delete: (execution, options) => installs.delete(execution, controlOptions(options, admittedControls)),
48
+ });
49
+ const uninstalls = schemaSource.uninstallation;
50
+ const uninstallation = Object.freeze({
51
+ status: (execution, options) => uninstalls.status(execution, controlOptions(options, admittedControls)),
52
+ result: (execution, wait, options) => uninstalls.result(execution, wait, controlOptions(options, admittedControls)),
53
+ cancel: (execution, input, options) => uninstalls.cancel(execution, input, controlOptions(options, admittedControls)),
54
+ resume: (execution, options) => uninstalls.resume(execution, controlOptions(options, admittedControls)),
55
+ delete: (execution, options) => uninstalls.delete(execution, controlOptions(options, admittedControls)),
56
+ });
39
57
  const schema = Object.freeze({
40
58
  install,
59
+ installation,
41
60
  uninstall,
61
+ uninstallation,
42
62
  inspect,
43
63
  bundle,
44
64
  dependencies,
@@ -106,9 +126,31 @@ function capture(source, key) {
106
126
  function captureSchema(input) {
107
127
  if (input === null || typeof input !== 'object')
108
128
  invalid();
129
+ const installation = input.installation;
130
+ if (installation === null || typeof installation !== 'object')
131
+ invalid();
132
+ const uninstallation = input.uninstallation;
133
+ if (uninstallation === null || typeof uninstallation !== 'object')
134
+ invalid();
109
135
  return Object.freeze({
110
136
  install: capture(input, 'install'),
137
+ installation: Object.freeze({
138
+ status: capture(installation, 'status'),
139
+ result: capture(installation, 'result'),
140
+ apply: capture(installation, 'apply'),
141
+ abort: capture(installation, 'abort'),
142
+ cancel: capture(installation, 'cancel'),
143
+ resume: capture(installation, 'resume'),
144
+ delete: capture(installation, 'delete'),
145
+ }),
111
146
  uninstall: capture(input, 'uninstall'),
147
+ uninstallation: Object.freeze({
148
+ status: capture(uninstallation, 'status'),
149
+ result: capture(uninstallation, 'result'),
150
+ cancel: capture(uninstallation, 'cancel'),
151
+ resume: capture(uninstallation, 'resume'),
152
+ delete: capture(uninstallation, 'delete'),
153
+ }),
112
154
  inspect: capture(input, 'inspect'),
113
155
  bundle: capture(input, 'bundle'),
114
156
  dependencies: capture(input, 'dependencies'),
@@ -5,8 +5,8 @@ export interface SessionCredential {
5
5
  /** Absolute Unix time in milliseconds. */
6
6
  readonly expiresAt: number;
7
7
  }
8
- /** Observable lifecycle of the single credential one provider owns. */
9
- export type SessionCredentialState = {
8
+ /** Observable lifecycle of the single credential one Credentials owns. */
9
+ export type CredentialsState = {
10
10
  readonly status: 'empty';
11
11
  } | {
12
12
  readonly status: 'valid';
@@ -22,23 +22,28 @@ export type SessionCredentialState = {
22
22
  readonly status: 'expired';
23
23
  readonly error: unknown;
24
24
  };
25
- export interface SessionCredentialProviderOptions {
25
+ /**
26
+ * Acquire one fresh credential: a compact JWT, whose `exp` claim is its expiry, or an explicit
27
+ * credential and expiry. The supplied signal is owned by Credentials.
28
+ */
29
+ export type CredentialsMint = (signal: AbortSignal) => string | SessionCredential | PromiseLike<string | SessionCredential>;
30
+ export interface CredentialsOptions {
26
31
  /** Delegation TTL every served credential must still cover; also the SessionAuth TTL. */
27
- readonly ttlSeconds: number;
28
- /** Acquire one fresh credential; the supplied signal is owned by the provider. */
29
- mint(signal: AbortSignal): Promise<SessionCredential>;
32
+ readonly ttlSeconds?: number;
33
+ /** Renew the credential. Without it, the initial credential is served until it stops covering. */
34
+ readonly mint?: CredentialsMint;
30
35
  /** Caller-held credential admitted as the initial entry; it need only be unexpired. */
31
- readonly initial?: SessionCredential;
32
- readonly onChange?: (state: SessionCredentialState) => void;
36
+ readonly initial?: string | SessionCredential;
37
+ readonly onChange?: (state: CredentialsState) => void;
33
38
  }
34
39
  /**
35
40
  * Caller-owned source credential with a derived refresh threshold and shared minting.
36
41
  *
37
- * The provider is a SessionAuth, so a ClientSession consumes it directly. Anticipation is opt-in:
42
+ * Credentials is a SessionAuth, so a ClientSession consumes it directly. Anticipation is opt-in:
38
43
  * an ephemeral process or a request-scoped worker never holds a pending timer it did not ask for.
39
44
  */
40
- export interface SessionCredentialProvider extends SessionAuth {
41
- state(): SessionCredentialState;
45
+ export interface Credentials extends SessionAuth {
46
+ state(): CredentialsState;
42
47
  /** Serve a credential that still covers the delegation TTL; concurrent callers share one mint. */
43
48
  acquire(signal?: AbortSignal): Promise<SessionCredential>;
44
49
  /** Mint regardless of the current credential, joining a mint already in flight. */
@@ -53,4 +58,8 @@ export interface SessionCredentialProvider extends SessionAuth {
53
58
  * plus the settlement skew, so it cannot expire between admission and delivery.
54
59
  */
55
60
  export declare function delegationCoverageMs(ttlSeconds: number): number;
56
- export declare function createSessionCredentialProvider(options: SessionCredentialProviderOptions): SessionCredentialProvider;
61
+ /**
62
+ * Hold one source credential for a Session: a fixed credential, a mint that renews it on demand,
63
+ * or options that also seed it, observe it, or change the delegation TTL it must cover.
64
+ */
65
+ export declare function credentials(source: string | CredentialsMint | CredentialsOptions): Credentials;
@@ -1,5 +1,6 @@
1
+ import { inspect } from '@astrale-os/kernel-core/auth/credential';
1
2
  import { ClientError } from '../../errors/index.js';
2
- import { BACKOFF_MS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS } from './limits.js';
3
+ import { BACKOFF_MS, DEFAULT_TTL_SECONDS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS, } from './limits.js';
3
4
  /**
4
5
  * Remaining lifetime a credential must exceed to carry a delegation of `ttlSeconds`: the TTL itself
5
6
  * plus the settlement skew, so it cannot expire between admission and delivery.
@@ -7,21 +8,26 @@ import { BACKOFF_MS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS } fr
7
8
  export function delegationCoverageMs(ttlSeconds) {
8
9
  return ttlSeconds * 1_000 + SETTLEMENT_SKEW_MS;
9
10
  }
10
- export function createSessionCredentialProvider(options) {
11
- if (options === null || typeof options !== 'object') {
12
- throw new TypeError('Session credential provider options are invalid.');
13
- }
14
- if (typeof options.mint !== 'function') {
11
+ /**
12
+ * Hold one source credential for a Session: a fixed credential, a mint that renews it on demand,
13
+ * or options that also seed it, observe it, or change the delegation TTL it must cover.
14
+ */
15
+ export function credentials(source) {
16
+ const options = admitSource(source);
17
+ if (options.mint !== undefined && typeof options.mint !== 'function') {
15
18
  throw new TypeError('Session credential mint capability is invalid.');
16
19
  }
17
- if (!Number.isSafeInteger(options.ttlSeconds) || options.ttlSeconds < 1) {
20
+ if (options.mint === undefined && options.initial === undefined) {
21
+ throw new TypeError('Session credentials need a mint or an initial credential.');
22
+ }
23
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
24
+ if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 1) {
18
25
  throw new TypeError('Session credential ttlSeconds must be a positive safe integer.');
19
26
  }
20
27
  if (options.onChange !== undefined && typeof options.onChange !== 'function') {
21
28
  throw new TypeError('Session credential change observer is invalid.');
22
29
  }
23
- const { ttlSeconds } = options;
24
- const mint = options.mint.bind(options);
30
+ const mint = options.mint?.bind(options);
25
31
  const notify = options.onChange?.bind(options);
26
32
  // The threshold is the coverage the caller already declared, never a separate guessed constant.
27
33
  const marginMs = delegationCoverageMs(ttlSeconds);
@@ -109,13 +115,19 @@ export function createSessionCredentialProvider(options) {
109
115
  });
110
116
  }
111
117
  function begin() {
118
+ if (mint === undefined) {
119
+ const error = new ClientError('Session credential needs renewal, but no mint was supplied.');
120
+ settleFailure(error);
121
+ return Promise.reject(error);
122
+ }
123
+ const renew = mint;
112
124
  publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
113
125
  const owned = new AbortController();
114
126
  controller = owned;
115
127
  const signal = AbortSignal.any([owned.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
116
128
  const pending = (async () => {
117
129
  try {
118
- const minted = admitMinted(await mint(signal));
130
+ const minted = admitMinted(await renew(signal));
119
131
  current = minted;
120
132
  attempt = 0;
121
133
  publish({ status: 'valid', credential: minted });
@@ -165,11 +177,14 @@ export function createSessionCredentialProvider(options) {
165
177
  function retry() {
166
178
  if (refreshTimer !== undefined)
167
179
  return;
180
+ if (current !== undefined)
181
+ armExpiry(current);
182
+ // Without a mint nothing can replace the held credential; only its expiry remains to report.
183
+ if (mint === undefined)
184
+ return;
168
185
  const backoff = BACKOFF_MS[attempt];
169
186
  attempt = Math.min(attempt + 1, BACKOFF_MS.length);
170
187
  armRefresh(backoff ?? RETRY_INTERVAL_MS);
171
- if (current !== undefined)
172
- armExpiry(current);
173
188
  }
174
189
  function armRefresh(delay) {
175
190
  refreshTimer = setTimeout(() => {
@@ -204,22 +219,67 @@ export function createSessionCredentialProvider(options) {
204
219
  notify?.(state);
205
220
  }
206
221
  function admitMinted(input) {
222
+ if (typeof input === 'string') {
223
+ const credential = fromCompactJwt(input);
224
+ if (credential === undefined) {
225
+ throw new ClientError('Minted session credential carries no expiry; return { credential, expiresAt }.');
226
+ }
227
+ return admitCovering(credential);
228
+ }
207
229
  const credential = admitShape(input);
208
230
  if (credential === undefined)
209
231
  throw new ClientError('Minted session credential is invalid.');
232
+ return admitCovering(credential);
233
+ }
234
+ function admitCovering(credential) {
210
235
  if (!covers(credential)) {
211
236
  throw new ClientError('Minted session credential cannot cover the delegation TTL.');
212
237
  }
213
238
  return credential;
214
239
  }
215
240
  }
241
+ /** A bare credential is fixed, a function mints; anything else must already be options. */
242
+ function admitSource(source) {
243
+ if (source === undefined || source === null || source === '') {
244
+ throw new TypeError('Session credential is missing.');
245
+ }
246
+ if (typeof source === 'string')
247
+ return { initial: source };
248
+ if (typeof source === 'function')
249
+ return { mint: source };
250
+ if (typeof source !== 'object')
251
+ throw new TypeError('Session credentials source is invalid.');
252
+ return source;
253
+ }
216
254
  function admitInitial(input) {
217
- const credential = admitShape(input);
218
- if (credential === undefined || credential.expiresAt <= Date.now()) {
219
- throw new TypeError('Initial session credential is invalid.');
255
+ const credential = typeof input === 'string' ? fromCompactJwt(input) : admitShape(input);
256
+ if (credential === undefined) {
257
+ throw new TypeError(typeof input === 'string'
258
+ ? 'Session credential carries no expiry; supply { credential, expiresAt }.'
259
+ : 'Initial session credential is invalid.');
260
+ }
261
+ if (credential.expiresAt <= Date.now()) {
262
+ throw new TypeError('Initial session credential has expired.');
220
263
  }
221
264
  return credential;
222
265
  }
266
+ /** Read the expiry a compact JWT declares; an opaque or expiry-less credential yields none. */
267
+ function fromCompactJwt(input) {
268
+ if (input.length === 0)
269
+ return undefined;
270
+ let exp;
271
+ try {
272
+ exp = inspect(input).claims.exp;
273
+ }
274
+ catch {
275
+ return undefined;
276
+ }
277
+ if (typeof exp !== 'number' || !Number.isSafeInteger(exp) || exp < 1)
278
+ return undefined;
279
+ if (!Number.isSafeInteger(exp * 1_000))
280
+ return undefined;
281
+ return Object.freeze({ credential: input, expiresAt: exp * 1_000 });
282
+ }
223
283
  function admitShape(input) {
224
284
  if (input === null ||
225
285
  typeof input !== 'object' ||
@@ -1 +1 @@
1
- export { createSessionCredentialProvider, delegationCoverageMs, type SessionCredential, type SessionCredentialProvider, type SessionCredentialProviderOptions, type SessionCredentialState, } from './provider.js';
1
+ export { credentials, delegationCoverageMs, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credentials.js';
@@ -1 +1 @@
1
- export { createSessionCredentialProvider, delegationCoverageMs, } from './provider.js';
1
+ export { credentials, delegationCoverageMs, } from './credentials.js';
@@ -1,3 +1,5 @@
1
+ /** Delegation TTL a Credentials serves when its caller declares none. */
2
+ export declare const DEFAULT_TTL_SECONDS = 60;
1
3
  /**
2
4
  * Settlement allowance added to the declared delegation TTL to form the refresh threshold. It
3
5
  * matches the destination-credential skew routing already applies to a warm entry, so a credential
@@ -1,3 +1,5 @@
1
+ /** Delegation TTL a Credentials serves when its caller declares none. */
2
+ export const DEFAULT_TTL_SECONDS = 60;
1
3
  /**
2
4
  * Settlement allowance added to the declared delegation TTL to form the refresh threshold. It
3
5
  * matches the destination-credential skew routing already applies to a warm entry, so a credential
@@ -1,6 +1,6 @@
1
1
  import { ClientError } from '../../errors/index.js';
2
2
  import { runSessionOperation } from '../context/index.js';
3
- import { createSessionCredentialProvider, delegationCoverageMs } from '../credential/index.js';
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';
@@ -32,8 +32,8 @@ export function createSessionExchange(dependencies, options) {
32
32
  if (source.delegate.ttlSeconds > auth.ttlSeconds) {
33
33
  throw new ClientError('Session delegation outlives the Domain credential it would carry.');
34
34
  }
35
- const provider = providerFor(source, domain);
36
- const exchanged = await runSessionOperation(operation, (signal) => provider.acquire(signal));
35
+ const domainCredentials = credentialsFor(source, domain);
36
+ const exchanged = await runSessionOperation(operation, (signal) => domainCredentials.acquire(signal));
37
37
  return Object.freeze({ credential: exchanged.credential, delegate: source.delegate });
38
38
  });
39
39
  }
@@ -41,12 +41,12 @@ export function createSessionExchange(dependencies, options) {
41
41
  installations.clear();
42
42
  sources.clear();
43
43
  }
44
- function providerFor(source, domain) {
44
+ function credentialsFor(source, domain) {
45
45
  const held = heldFor(source.credential);
46
46
  const known = held.get(domain);
47
47
  if (known !== undefined)
48
48
  return known;
49
- const provider = createSessionCredentialProvider({
49
+ const domainCredentials = credentials({
50
50
  ttlSeconds: auth.ttlSeconds,
51
51
  mint: (signal) => exchangeDomainCredential(dependencies, source, {
52
52
  issuer: domain,
@@ -54,8 +54,8 @@ export function createSessionExchange(dependencies, options) {
54
54
  coverageMs,
55
55
  }, dependencies.operation(signal)),
56
56
  });
57
- held.set(domain, provider);
58
- return provider;
57
+ held.set(domain, domainCredentials);
58
+ return domainCredentials;
59
59
  }
60
60
  /** Domain credentials never cross source credentials; the oldest source is forgotten first. */
61
61
  function heldFor(credential) {