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

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 (44) 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/execution.d.ts +24 -1
  31. package/dist/session/index.d.ts +1 -1
  32. package/dist/session/reference.d.ts +8 -4
  33. package/dist/session/reference.js +7 -2
  34. package/dist/session/routing/dispatch.js +2 -0
  35. package/dist/session/routing/request.d.ts +4 -0
  36. package/dist/session/routing/request.js +11 -1
  37. package/dist/session/routing/result.d.ts +1 -1
  38. package/dist/session/routing/result.js +5 -1
  39. package/dist/session/session.js +10 -7
  40. package/dist/store/memory.js +20 -1
  41. package/dist/transport/http/admission.js +3 -0
  42. package/dist/transport/transport.d.ts +10 -0
  43. package/dist/transport/websocket/exchange.js +8 -0
  44. package/package.json +4 -4
@@ -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'),
@@ -1,4 +1,5 @@
1
1
  import type { NodeId } from '@astrale-os/kernel-core/graph/node';
2
+ import type { SystemExecutionDetail } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
2
3
  import type { Value } from '@astrale-os/kernel-dsl/value';
3
4
  import type { CallableReference } from './reference.js';
4
5
  declare const EXECUTION_OUTPUT: unique symbol;
@@ -25,14 +26,36 @@ export type ExecutionOutcome<Output = unknown> = {
25
26
  readonly kind: 'cancelled';
26
27
  };
27
28
  export type ExecutionState = 'pending' | 'running' | 'waiting' | 'paused' | 'completed' | 'failed' | 'cancelled' | 'expired';
28
- export interface ExecutionStatus<Output = unknown> {
29
+ /**
30
+ * The status of an Execution: its node's, or what Root reads of a system execution whose node was
31
+ * deleted.
32
+ */
33
+ export type ExecutionStatus<Output = unknown> = ExecutionNodeStatus<Output> | DeletedExecutionStatus<Output>;
34
+ /** The status of an Execution whose node exists, with the engine state of its run. */
35
+ export interface ExecutionNodeStatus<Output = unknown> {
29
36
  readonly id: NodeId;
30
37
  readonly function: NodeId;
31
38
  readonly version: `sha256:${string}`;
32
39
  readonly state: ExecutionState;
33
40
  readonly createdAt: string;
41
+ /** A system execution's step, progress and session state, as Core shapes it. */
42
+ readonly detail?: SystemExecutionDetail;
34
43
  readonly outcome?: ExecutionOutcome<Output>;
35
44
  }
45
+ /**
46
+ * What Root alone reads of a system execution whose node was deleted: the outcome its lifecycle
47
+ * record keeps, under the explicit state `deleted`, never a live state.
48
+ */
49
+ export interface DeletedExecutionStatus<Output = unknown> {
50
+ readonly id: NodeId;
51
+ readonly state: 'deleted';
52
+ readonly outcome: ExecutionOutcome<Output>;
53
+ /** Absent: the node that recorded them is deleted. */
54
+ readonly function?: never;
55
+ readonly version?: never;
56
+ readonly createdAt?: never;
57
+ readonly detail?: never;
58
+ }
36
59
  type Empty = Readonly<Record<string, never>>;
37
60
  type ExecutionLike<Output> = ExecutionRef<Output> | NodeId;
38
61
  /**
@@ -9,6 +9,6 @@ export type { ClientSessionOptions } from './options.js';
9
9
  export { ClientSession, connect, type ConnectOptions } from './session.js';
10
10
  export type { CallableReference, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
11
11
  export { reference } from './reference.js';
12
- export { execution, type ExecutionOutcome, type ExecutionRef, type ExecutionState, type ExecutionStatus, } from './execution.js';
12
+ export { execution, type ExecutionOutcome, type ExecutionRef, type DeletedExecutionStatus, type ExecutionNodeStatus, type ExecutionState, type ExecutionStatus, } from './execution.js';
13
13
  export type { ResolvedView, ViewCatalog } from './views/index.js';
14
14
  export type { DomainBinding } from '../graph/domain/index.js';
@@ -1,10 +1,12 @@
1
1
  import type { Path as PathValue, PathLike } from '@astrale-os/kernel-core/path';
2
- import type { CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod } from '@astrale-os/kernel-dsl/v1';
2
+ import type { CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod, ResolvedMethod } from '@astrale-os/kernel-dsl/v1';
3
3
  import type { MethodAddress } from '@astrale-os/kernel-dsl/v1/addressing';
4
4
  import type { MeaningFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
5
5
  import { type Key as KeyType } from '@astrale-os/kernel-dsl/v1/addressing';
6
- import type { Binary, Input } from '../client/index.js';
6
+ import type { Binary, Input, Result } from '../client/index.js';
7
7
  import type { ExecutionRef } from './execution.js';
8
+ /** Result kind a reference expects: a durable callable answers with its Execution. */
9
+ type OutputMode = Exclude<Result['kind'], 'redirect'>;
8
10
  declare const REFERENCE_INPUT: unique symbol;
9
11
  declare const REFERENCE_INPUT_MODE: unique symbol;
10
12
  declare const REFERENCE_OUTPUT: unique symbol;
@@ -14,7 +16,7 @@ export interface CallableReference<InputValue = Input, Output = unknown, InputMo
14
16
  readonly fingerprint?: MeaningFingerprint;
15
17
  readonly callable: KeyType.Callable;
16
18
  readonly target: PathValue;
17
- readonly outputMode: 'value' | 'stream' | 'binary';
19
+ readonly outputMode: OutputMode;
18
20
  readonly [REFERENCE_INPUT]?: InputValue;
19
21
  readonly [REFERENCE_INPUT_MODE]?: InputMode;
20
22
  readonly [REFERENCE_OUTPUT]?: Output;
@@ -24,7 +26,7 @@ export interface InstanceCallableReference<InputValue = Input, Output = unknown>
24
26
  readonly origin: KeyType.Origin;
25
27
  readonly fingerprint?: MeaningFingerprint;
26
28
  readonly callable: KeyType.Callable;
27
- readonly outputMode: 'value' | 'stream' | 'binary';
29
+ readonly outputMode: OutputMode;
28
30
  }
29
31
  export type InputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer InputValue, unknown> ? InputValue : never;
30
32
  export type OutputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer _Input, infer Output> ? Output : never;
@@ -47,6 +49,8 @@ export declare function reference<const Callable extends ExecutableInstanceMetho
47
49
  * addresses every Kernel syscall. Loading the Session therefore never resolves the Kernel Schema.
48
50
  */
49
51
  export declare function kernelReference(method: MethodAddress): InstanceCallableReference<unknown>;
52
+ /** The result kind invoking this callable yields. */
53
+ export declare function outputModeOf(callable: ResolvedFunction | ResolvedMethod): OutputMode;
50
54
  export declare function admitReference(input: CallableReference<unknown>): CallableReference<unknown>;
51
55
  export declare function matchesCallable(target: PathValue, callable: KeyType.Callable): boolean;
52
56
  export {};
@@ -2,6 +2,7 @@ import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { callableAddress, Key, MethodKey, patterns, } from '@astrale-os/kernel-dsl/v1/addressing';
3
3
  import { callableFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
4
4
  const FINGERPRINT_PATTERN = /^sha256:[0-9a-f]{64}$/u;
5
+ const OUTPUT_MODES = ['value', 'stream', 'binary', 'execution'];
5
6
  export function reference(domain, callable) {
6
7
  if (Key.origin(callable.key) !== domain.origin)
7
8
  invalid();
@@ -11,7 +12,7 @@ export function reference(domain, callable) {
11
12
  origin: domain.origin,
12
13
  fingerprint: callableFingerprint(callable),
13
14
  callable: callable.key,
14
- outputMode: callable.output.mode,
15
+ outputMode: outputModeOf(callable),
15
16
  });
16
17
  if ('owner' in callable && !callable.static) {
17
18
  const bind = (receiver) => admitReference({
@@ -39,6 +40,10 @@ export function kernelReference(method) {
39
40
  const bind = (receiver) => admitReference({ ...common, target: Path.instanceMethod(Path.from(receiver), callable) });
40
41
  return Object.assign(bind, common);
41
42
  }
43
+ /** The result kind invoking this callable yields. */
44
+ export function outputModeOf(callable) {
45
+ return callable.execution?.durable === true ? 'execution' : callable.output.mode;
46
+ }
42
47
  export function admitReference(input) {
43
48
  if (input === null || typeof input !== 'object')
44
49
  invalid();
@@ -47,7 +52,7 @@ export function admitReference(input) {
47
52
  typeof input.callable !== 'string' ||
48
53
  !Key.is(input.callable) ||
49
54
  Key.origin(input.callable) !== input.origin ||
50
- !['value', 'stream', 'binary'].includes(input.outputMode) ||
55
+ !OUTPUT_MODES.includes(input.outputMode) ||
51
56
  (input.fingerprint !== undefined &&
52
57
  (typeof input.fingerprint !== 'string' || !FINGERPRINT_PATTERN.test(input.fingerprint))))
53
58
  invalid();
@@ -62,6 +62,8 @@ export class SessionDispatcher {
62
62
  ...transportOptions(operation, options, streaming),
63
63
  ...(state.auth.delegate === undefined ? {} : { delegate: state.auth.delegate }),
64
64
  ...(routing === undefined ? {} : { routing }),
65
+ // The guard is the source Kernel's: a routed destination request never carries it.
66
+ ...(options.maintenance === undefined ? {} : { maintenance: options.maintenance }),
65
67
  }));
66
68
  }
67
69
  async followSource(result, state, options, operation, streaming) {
@@ -3,6 +3,10 @@ import type { SessionControlOptions } from '../context/index.js';
3
3
  export type SessionEnvelopeTransport = 'auto' | 'http' | 'websocket';
4
4
  export interface SessionRequestOptions extends SessionControlOptions {
5
5
  readonly idempotencyKey?: invocation.IdempotencyKey;
6
+ /** Sent to the source Kernel only; a routed destination never receives it. */
7
+ readonly maintenance?: {
8
+ readonly session: string;
9
+ };
6
10
  readonly body?: never;
7
11
  }
8
12
  export type SessionRequestOptionsWithBody = Omit<SessionRequestOptions, 'body' | 'idempotencyKey'> & {
@@ -23,17 +23,27 @@ export function admitRequestOptions(input = {}) {
23
23
  }
24
24
  const control = admitControlOptions(input);
25
25
  const fields = Reflect.ownKeys(input);
26
- if (fields.some((field) => !['signal', 'timeoutMs', 'idempotencyKey'].includes(String(field)))) {
26
+ if (fields.some((field) => !['signal', 'timeoutMs', 'idempotencyKey', 'maintenance'].includes(String(field)))) {
27
27
  throw new TypeError('Session request options contain unsupported fields.');
28
28
  }
29
29
  const idempotencyKey = input.idempotencyKey === undefined
30
30
  ? undefined
31
31
  : invocationProtocol.acceptIdempotencyKey(input.idempotencyKey, 'request.idempotencyKey');
32
+ const maintenance = input.maintenance === undefined ? undefined : admitMaintenance(input.maintenance);
32
33
  return Object.freeze({
33
34
  ...control,
34
35
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
36
+ ...(maintenance === undefined ? {} : { maintenance }),
35
37
  });
36
38
  }
39
+ function admitMaintenance(input) {
40
+ try {
41
+ return invocationProtocol.acceptMaintenance(input);
42
+ }
43
+ catch (cause) {
44
+ throw new TypeError('Session maintenance guard is invalid.', { cause });
45
+ }
46
+ }
37
47
  export function admitEnvelopeTransport(input) {
38
48
  if (input !== 'auto' && input !== 'http' && input !== 'websocket') {
39
49
  throw new TypeError('Session envelope transport is invalid.');
@@ -1,5 +1,5 @@
1
1
  import type { Result } from '../../client/index.js';
2
2
  /** Narrow a Result to the kind a sugar requires, releasing a live body before rejecting it. */
3
- export declare function requireResultKind<Kind extends 'value' | 'stream' | 'binary'>(expected: Kind, result: Result): Extract<Result, {
3
+ export declare function requireResultKind<Kind extends Exclude<Result['kind'], 'redirect'>>(expected: Kind, result: Result): Extract<Result, {
4
4
  kind: Kind;
5
5
  }>;
@@ -8,5 +8,9 @@ export function requireResultKind(expected, result) {
8
8
  if (result.kind === 'binary' && !(result.value.body instanceof Uint8Array)) {
9
9
  void result.value.body[Symbol.asyncIterator]().return?.();
10
10
  }
11
- throw new ClientError(`Function returned ${result.kind}; ${expected} was required.`);
11
+ // A started Execution is named so its caller never starts it again.
12
+ const returned = result.kind === 'execution'
13
+ ? `Function started Execution ${result.execution}`
14
+ : `Function returned ${result.kind}`;
15
+ throw new ClientError(`${returned}; ${expected} was required.`);
12
16
  }
@@ -12,7 +12,7 @@ import { admitControlOptions, allowEndpoint, createSessionOperation } from './co
12
12
  import { createSessionDiscovery } from './discovery/index.js';
13
13
  import { acquireDomainCredential, admitExchangeRequest, createSessionExchange, } from './exchange/index.js';
14
14
  import { acceptSessionOptions } from './options.js';
15
- import { admitReference } from './reference.js';
15
+ import { admitReference, outputModeOf } from './reference.js';
16
16
  import { admitInvocationOptions, requireResultKind, SessionDispatcher } from './routing/index.js';
17
17
  import { domainViewCatalog, resolveViewsFor } from './views/index.js';
18
18
  const DEFAULT_SESSION_POLICY = Object.freeze({ maximumRouteAgeMs: 60_000 });
@@ -162,11 +162,14 @@ export class ClientSession {
162
162
  ? this.dispatcher.dispatch(call, admitted.options, operation)
163
163
  : this.dispatcher.dispatchHttp(call, admitted.options, operation, admitted.body));
164
164
  const narrowed = requireResultKind(admittedReference.outputMode, result);
165
- return narrowed.kind === 'value'
166
- ? narrowed.value
167
- : narrowed.kind === 'stream'
168
- ? narrowed.stream
169
- : narrowed.value;
165
+ switch (narrowed.kind) {
166
+ case 'stream':
167
+ return narrowed.stream;
168
+ case 'execution':
169
+ return Object.freeze({ id: narrowed.execution });
170
+ default:
171
+ return narrowed.value;
172
+ }
170
173
  }
171
174
  dispatchWith(call, options, requireHttp = false) {
172
175
  const admitted = admitInvocationOptions(options);
@@ -209,7 +212,7 @@ export class ClientSession {
209
212
  fingerprint: callableFingerprint(method),
210
213
  callable: method.key,
211
214
  target: Path.instanceMethod(Path.id(node.id), method.key),
212
- outputMode: method.output.mode,
215
+ outputMode: outputModeOf(method),
213
216
  }, input);
214
217
  }
215
218
  operation(options) {
@@ -4,6 +4,10 @@ import { retainDerivedQueryProvenance } from '../graph/provenance.js';
4
4
  import { EntityIndex } from './entity-index.js';
5
5
  import { OptimisticOverlay } from './optimistic.js';
6
6
  import { COLD_SNAPSHOT, QueryShape } from './shape.js';
7
+ const NO_REFERENCES = Object.freeze({
8
+ nodes: Object.freeze([]),
9
+ edges: Object.freeze([]),
10
+ });
7
11
  export class GraphMemory {
8
12
  options;
9
13
  entities = new EntityIndex();
@@ -60,6 +64,17 @@ export class GraphMemory {
60
64
  this.publish(shape, prior === undefined ? 'cold' : this.overlay.hasAny() ? 'optimistic' : 'stale');
61
65
  return result;
62
66
  }
67
+ // An uncertified read may hold facts the active schema refutes: it stays raw on its own
68
+ // shape and never enters, or is derived from, the shared entity cache.
69
+ if (result.certification === 'uncertified') {
70
+ shape.references = NO_REFERENCES;
71
+ shape.confirmed = result;
72
+ shape.response = result;
73
+ shape.refreshedAt = this.options.now();
74
+ this.touch(shape, shape.refreshedAt);
75
+ this.publish(shape, 'ready');
76
+ return shape.response;
77
+ }
63
78
  const integration = this.entities.integrate(result.result);
64
79
  shape.references = integration.references;
65
80
  shape.confirmed = result;
@@ -127,7 +142,7 @@ export class GraphMemory {
127
142
  }
128
143
  optimistic() {
129
144
  for (const shape of this.shapes.values()) {
130
- if (shape.response === undefined)
145
+ if (shape.response === undefined || shape.confirmed?.certification === 'uncertified')
131
146
  continue;
132
147
  shape.response = this.materialize(shape.confirmed, shape.references);
133
148
  this.publish(shape, 'optimistic');
@@ -195,9 +210,13 @@ export class GraphMemory {
195
210
  this.pending.shift()?.reject(error);
196
211
  }
197
212
  materialize(template, references) {
213
+ // Optimistic overlays and cache refreshes never rewrite an uncertified read.
214
+ if (template.certification === 'uncertified')
215
+ return template;
198
216
  const response = Object.freeze({
199
217
  result: this.materializeResult(template.result, references),
200
218
  page: template.page,
219
+ ...(template.certification === undefined ? {} : { certification: template.certification }),
201
220
  });
202
221
  return retainDerivedQueryProvenance(template, response);
203
222
  }