コンテンツにスキップ

@alneas/eaos-server API

Import Contract
@alneas/eaos-server/db/local-first-sqlite-adapter Typed public export
@alneas/eaos-server/db Typed public export
@alneas/eaos-server/db/migration/aggregator Typed public export
@alneas/eaos-server/db/migration Typed public export
@alneas/eaos-server/lifecycle-engine/backend-migration Typed public export
@alneas/eaos-server/lifecycle-engine Typed public export
@alneas/eaos-server/platform/artifacts Typed public export
@alneas/eaos-server/platform/control-plane Typed public export
@alneas/eaos-server/platform/database-router Typed public export
@alneas/eaos-server/platform/deployment-placements Typed public export
@alneas/eaos-server/platform/deployment Typed public export
@alneas/eaos-server/platform Typed public export
@alneas/eaos-server/platform/runtime Typed public export
@alneas/eaos-server/platform/site-publication Typed public export
@alneas/eaos-server/platform/user-directory Typed public export
@alneas/eaos-server/lifecycle-engine/baseline Typed public export
@alneas/eaos-server/storage Typed public export
@alneas/eaos-server/storage/s3-compatible Typed public export
@alneas/eaos-server/agentic/agent-jobs Typed public export
@alneas/eaos-server/agentic/agent-node Typed public export
@alneas/eaos-server/agentic/agent-runner Typed public export
@alneas/eaos-server/agentic/ai-broker Typed public export
@alneas/eaos-server/agentic/atomic-checkpointer Typed public export
@alneas/eaos-server/agentic/autonomous-worker Typed public export
@alneas/eaos-server/agentic/event-bridge Typed public export
@alneas/eaos-server/agentic/executor Typed public export
@alneas/eaos-server/agentic/graph-projection Typed public export
@alneas/eaos-server/agentic/graph Typed public export
@alneas/eaos-server/agentic Typed public export
@alneas/eaos-server/agentic/local-runner Typed public export
@alneas/eaos-server/agentic/remote-executor Typed public export
@alneas/eaos-server/agentic/types Typed public export
@alneas/eaos-server/agentic/workflow-catalog Typed public export
@alneas/eaos-server/agentic/workflow-compiler Typed public export
@alneas/eaos-server/agentic/workflow-coordinator Typed public export
@alneas/eaos-server/agentic/workflow-manager Typed public export
@alneas/eaos-server/agentic/workflow-registry Typed public export
@alneas/eaos-server/auth-hooks/api-key Typed public export
@alneas/eaos-server/auth-hooks Typed public export
@alneas/eaos-server/browser-auth/account-memberships Typed public export
@alneas/eaos-server/browser-auth Typed public export
@alneas/eaos-server/browser-auth/kratos-session Typed public export
@alneas/eaos-server/browser-auth/platform-session Typed public export
@alneas/eaos-server/browser-auth/public-memberships Typed public export
@alneas/eaos-server/cache Typed public export
@alneas/eaos-server/engine Typed public export
@alneas/eaos-server/execution Typed public export
@alneas/eaos-server/extensions Typed public export
@alneas/eaos-server/health Typed public export
@alneas/eaos-server Typed public export
@alneas/eaos-server/lifecycle Typed public export
@alneas/eaos-server/mcp Typed public export
@alneas/eaos-server/middleware/auth Typed public export
@alneas/eaos-server/middleware/error-handler Typed public export
@alneas/eaos-server/middleware/module-guard Typed public export
@alneas/eaos-server/platform-admin Typed public export
@alneas/eaos-server/platform-admin/store Typed public export
@alneas/eaos-server/plugin-data/annotations Typed public export
@alneas/eaos-server/plugin-data/atomic-context Typed public export
@alneas/eaos-server/plugin-data/atomic Typed public export
@alneas/eaos-server/plugin-data/audit Typed public export
@alneas/eaos-server/plugin-data/commands Typed public export
@alneas/eaos-server/plugin-data/composite Typed public export
@alneas/eaos-server/plugin-data/delivery Typed public export
@alneas/eaos-server/plugin-data Typed public export
@alneas/eaos-server/plugin-data/json-documents Typed public export
@alneas/eaos-server/plugin-data/outbox Typed public export
@alneas/eaos-server/plugin-data/scoped-records Typed public export
@alneas/eaos-server/sql-lifecycle Typed public export
@alneas/eaos-server/tenant Typed public export
@alneas/eaos-server/workspace-context Typed public export
@alneas/eaos-server/entitlements Typed public export
@alneas/eaos-server/plugin-sdk Typed public export

Per-table local counters used to rank adaptive synchronization candidates.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

interface AccessFrequencyRecord {
table_name: string;
read_count: number;
write_count: number;
last_accessed_at: string;
}
Name Type Required Description
table_name string Yes Tracked collection identifier.
read_count number Yes Accumulated read count.
write_count number Yes Accumulated write count.
last_accessed_at string Yes ISO timestamp of the most recently recorded access.

Type declaration; no runtime value.

LocalFirstSqliteAdapter.recordAccess.

Tracked collection identifier.

Accumulated read count.

Accumulated write count.

ISO timestamp of the most recently recorded access.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-authorized provider administration used by account membership operations.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

interface AccountAdminPort {
read(identityId: string): Promise<ManagedIdentity>;
write(identity: ManagedIdentity, metadata: Record<string, unknown>, field: AccountMetadataField): Promise<void>;
}
Name Type Required Description
read Promise<ManagedIdentity> Yes Reads the authoritative current provider identity, including both metadata fields.
write Promise<void> Yes Writes selected metadata while preserving unrelated identity fields.

Type declaration; no runtime value.

publishAccountMemberships.

Reads the authoritative current provider identity, including both metadata fields.

Parameters:

  • identityId: Provider identity ID.

Returns: Current identity snapshot used for lifecycle and hash checks.

Provider errors propagate and retain any acquired durable lock.

Example:

import type { AccountAdminPort } from "@alneas/eaos-server/browser-auth";
export async function readAuthoritativeIdentity(admin: AccountAdminPort, identityId: string) {
// The host supplies an authorized provider-admin connection.
const identity = await admin.read(identityId);
return { id: identity.id, state: identity.state };
}

Writes selected metadata while preserving unrelated identity fields.

Parameters:

  • identity: Authoritative identity snapshot; publication supplies both changed metadata fields and requires the port to PUT both in one provider request.
  • metadata: Complete replacement value for the selected metadata field.
  • field: Selected destination field.

Returns: No value; resolves when the provider acknowledges the write, before independent readback verification.

Provider failures propagate; the provider outcome may be uncertain and the durable lock must remain held.

Example:

import type { AccountAdminPort } from "@alneas/eaos-server/browser-auth";
export async function writeReviewedIdentityMetadata(
admin: AccountAdminPort,
currentIdentity: Parameters<AccountAdminPort["write"]>[0],
reviewedMetadata: Parameters<AccountAdminPort["write"]>[1],
reviewedField: Parameters<AccountAdminPort["write"]>[2],
) {
// Host workflow acquires the mutation lock and checks the reviewed snapshot first.
await admin.write(currentIdentity, reviewedMetadata, reviewedField);
// Read back through admin.read before recording durable mutation completion.
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-verified tenant membership used for authorization, separate from business person records.

Account membership is authorization data; business people do not grant access.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

interface AccountMembership {
tenantId: string;
role: string;
active: boolean;
}
Name Type Required Description
tenantId string Yes Concrete tenant ID, at most 50 supported identifier characters.
role string Yes Tenant-scoped role, at most 50 characters; platform-global role names are forbidden.
active boolean Yes Whether the membership currently grants tenant admission.

Type declaration; no runtime value.

parseAccountMemberships for canonical integration usage.

Concrete tenant ID, at most 50 supported identifier characters.

Tenant-scoped role, at most 50 characters; platform-global role names are forbidden.

Whether the membership currently grants tenant admission.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Validated tenant memberships with optional explicit active default selection.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

interface AccountMemberships {
memberships: readonly AccountMembership[];
defaultTenantId?: string;
}
Name Type Required Description
memberships readonly AccountMembership[] Yes At most 1000 distinct tenant grants; empty means no tenant access.
defaultTenantId string No Optional tenant among active memberships; omitted requires selection when multiple are active.

Type declaration; no runtime value.

parseAccountMemberships for canonical integration usage.

At most 1000 distinct tenant grants; empty means no tenant access.

Optional tenant among active memberships; omitted requires selection when multiple are active.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Provider metadata field updated by a membership migration; public metadata is visible to its account holder.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

type AccountMetadataField = 'metadata_public' | 'metadata_admin';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

applyAccountMembershipChange.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable mutation lock and audit boundary for account metadata updates.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

interface AccountMutationStore {
acquire(identityId: string, token: string, actor: string): Promise<void>;
complete(identityId: string, token: string, actor: string, beforeHash: string, afterHash: string): Promise<void>;
}
Name Type Required Description
acquire Promise<void> Yes Acquires an exclusive durable mutation lock before provider reads/writes.
complete Promise<void> Yes Records verified completion and finalizes the durable lock/audit state.

Type declaration; no runtime value.

A failed or uncertain update retains its lock. The host must reconcile it rather than auto-expire or blindly retry.

applyAccountMembershipChange.

Acquires an exclusive durable mutation lock before provider reads/writes.

Parameters:

  • identityId: Provider identity being changed.
  • token: Fresh mutation token generated for this attempt.
  • actor: Nonblank authenticated operator identity.

Returns: No value; resolves only when the lock is held.

Rejects conflicting or unavailable persistence; provider work will not start.

Example:

import type { AccountMutationStore } from "@alneas/eaos-server/browser-auth";
export async function lockReviewedIdentity(
store: AccountMutationStore, identityId: string, freshMutationToken: string, authenticatedActor: string,
) {
await store.acquire(identityId, freshMutationToken, authenticatedActor);
// Keep the token until verified completion; uncertain writes require reconciliation.
}

Records verified completion and finalizes the durable lock/audit state.

Parameters:

  • identityId: Changed provider identity.
  • token: Token acquired for this attempt; enforce ownership in the host store.
  • actor: Authenticated operator identity.
  • beforeHash: Reviewed pre-change snapshot hash.
  • afterHash: Hash read back and verified after the update.

Returns: No value; resolves when completion is durably recorded.

Persistence errors propagate after the provider may already have changed.

Example:

import type { AccountMutationStore } from "@alneas/eaos-server/browser-auth";
export async function finishVerifiedIdentityMutation(
store: AccountMutationStore, identityId: string, ownedToken: string, authenticatedActor: string,
reviewedBeforeHash: string, verifiedAfterHash: string,
) {
// Call only after reading back and verifying the actual provider metadata update.
await store.complete(identityId, ownedToken, authenticatedActor, reviewedBeforeHash, verifiedAfterHash);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

EAOS workflow runtime backed by the official LangGraph StateGraph. EAOS remains responsible for authorization, approval bindings and side effects.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

declare class AgentGraphEngine {
constructor(checkpointerOrOptions?: BaseCheckpointSaver | AgentGraphEngineOptions, options?: AgentGraphEngineOptions);
addNode(name: string, handler: GraphNodeHandler, options?: GraphNodeOptions): this;
addSubgraph(name: string, subgraph: GraphSubgraph, options?: GraphSubgraphOptions): this;
addEdge(from: string, to: string, options?: GraphEdgeOptions): this;
addConditionalEdges(from: string, router: GraphRouter, destinations: string[], options?: GraphConditionalEdgeOptions): this;
setEntryPoint(nodeName: string): this;
getNextNode(fromNode: string): string | undefined;
describe(): WorkflowGraphDescription;
describeRuntime(state: AgentGraphState): WorkflowGraphRuntimeSnapshot;
getVisualization(sessionId: string): Promise<WorkflowGraphVisualization>;
getCheckpoint(sessionId: string): Promise<AgentGraphState | null>;
runStep(initialState: AgentGraphState): Promise<AgentGraphState>;
resumeAfterApproval(input: {
sessionId: string;
approvalId?: string;
bindingHash?: string;
approved: boolean;
approverId: string;
approverRole: string;
comment?: string;
authorizeResume?: AgentGraphEngineOptions['authorizeResume'];
}): Promise<{
resumed: boolean;
state?: AgentGraphState;
error?: string;
}>;
}
Name Type Required Description
checkpointerOrOptions BaseCheckpointSaver | AgentGraphEngineOptions No LangGraph saver or options; omission uses an independent MemorySaver.
options AgentGraphEngineOptions No Additional options used only when the first argument is a saver; otherwise ignored.

AgentGraphEngine

The default MemorySaver is process-local/test storage. Production hosts must supply durable, tenant-scoped checkpoint persistence, verified initial identity, live resume authorization, and writer serialization. This class does not serialize concurrent calls for the same session or implement transactional side effects. Mutating topology invalidates the compiled graph; configure it before starting workflow sessions.

Registers or replaces a named handler and invalidates compiled topology.

Parameters:

  • name: Nonblank node name; eaos_approval is reserved. Names are retained without trimming.
  • handler: Async callback receiving a cloned state and resolving partial state updates.
  • options: Optional LangGraph retry policy and serializable display metadata.

Returns: This builder for chaining.

For blank/reserved names; handler failures occur later during execution.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
graph.addNode("finish", async () => ({ isComplete: true }));

Mount a plugin-owned compiled LangGraph as one parent-graph node. Input/output mapping is explicit so plugin state does not silently leak into the EAOS state, while the nested graph still gets its own checkpoint thread.

Parameters:

  • name: Parent node identifier, subject to addNode validation.
  • subgraph: Compiled graph with invoke and optional state/resume capabilities.
  • options: Input/output mapping and child-thread identity; defaults pass state/output through and use sessionId:name as thread ID.

Returns: This graph builder.

Child config uses checkpoint_ns=name. A mapped interrupt stores resume metadata in context; host mappings must preserve tenant boundaries and avoid leaking child state.

If subgraph lacks invoke or the name is invalid. Execution propagates mapping/subgraph errors except recognized interrupts handled by mapInterrupted.

Example:

import { AgentGraphEngine, type GraphSubgraph } from "@alneas/eaos-server/agentic/graph";
export function nested(subgraph: GraphSubgraph) {
return new AgentGraphEngine().addSubgraph("start", subgraph, { mapOutput: output => ({ context: { child: output } }) });
}

Adds a declared edge and its display metadata.

Parameters:

  • from: Nonblank source node name.
  • to: Nonblank destination node name.
  • options: Optional serializable display metadata, cloned on insertion.

Returns: This graph builder.

Without conditional routing, execution follows only the first declared outgoing edge; describe may list additional declared edges.

For blank endpoints or uncloneable display metadata. Missing node references can fail compilation later.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
graph.addNode("finish", async () => ({}));
graph.addEdge("start", "finish");

Sets a source node’s conditional router and complete allowed destination set.

Parameters:

  • from: Nonblank source node name.
  • router: Called synchronously after the node with a state clone; must return one declared destination.
  • destinations: Nonempty list of nonblank destination names; duplicates are collapsed.
  • options: Cloned optional edge metadata and destination labels.

Returns: This graph builder.

A pending approval overrides conditional routing and enters the approval node. This replaces an existing conditional route for from.

For invalid source/destinations or uncloneable options; runtime routing rejects undeclared destinations and callback errors.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
graph.addNode("finish", async () => ({}));
graph.addConditionalEdges("start", () => "finish", ["finish"]);

Selects the registered node where future graph execution starts.

Parameters:

  • nodeName: Nonblank node name; existence is checked on deferred compilation.

Returns: This builder after invalidating compiled topology.

For a blank name; missing entry registration fails later on compilation.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
graph.setEntryPoint("start");

Reads the first statically declared outgoing edge without evaluating conditional routing.

Parameters:

  • fromNode: Exact source node identifier.

Returns: First declared destination, or undefined when no static edge exists.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
console.log(graph.getNextNode("start")); // undefined

Return a serializable graph description for UI/API/diagram consumers. Handlers and router functions are intentionally omitted: this is metadata, not a remotely executable workflow definition.

Returns: A structured clone of versioned node/edge display metadata in insertion order; may describe an incomplete graph before compilation.

If retained metadata has become uncloneable.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
console.log(graph.describe().nodes.length); // 1

Extracts runtime status and approval display metadata without history, context, or approval args.

Parameters:

  • state: Authorized checkpoint state to summarize.

Returns: Status prioritized as waiting_approval, failed, completed, running, then idle, plus current node/revision and optional error/approval display details.

Reasons and errors remain visible; the host must control their content and authorize access to this overlay.

Example:

import { AgentGraphEngine, type AgentGraphState } from "@alneas/eaos-server/agentic/graph";
export function overlay(state: AgentGraphState) {
return new AgentGraphEngine().describeRuntime(state);
}

Reads a session checkpoint and combines its display overlay with the current static graph.

Parameters:

  • sessionId: Authorized host session/thread identifier.

Returns: Graph description and runtime overlay when a checkpoint exists, or only graph metadata otherwise.

This method does not authenticate the caller or authorize session access.

Rejects compilation, saver, or description failures.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
const visualization = await graph.getVisualization("example-session");
console.log(visualization.graph.nodes.length);

Reads the current saved state for one graph session.

Parameters:

  • sessionId: Authorized LangGraph thread ID.

Returns: A structured clone of persisted state, or null when no session state exists.

The host authorizes tenant/session access; sessionId alone is not an authentication claim.

Rejects deferred compilation, saver, or clone failures.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
console.log(await graph.getCheckpoint("example-session")); // null

Runs the graph until completion or a LangGraph approval interrupt.

Parameters:

  • initialState: Verified host session/tenant/user state; a nonblank sessionId is required. Existing pendingApproval returns an immediate clone without invoking the graph.

Returns: Latest checkpoint state after execution, interrupted approval state, or the supplied initial state when no checkpoint is available.

This method runs multiple nodes, despite its name. The host must serialize writers and make retried handlers safe for side effects. It installs no timeout or cancellation itself.

Rejects invalid sessionId, compilation, handler/retry, saver, binding, or clone errors except recognized approval interrupts.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
const state = await graph.runStep({ sessionId: "example-session", tenantId: "example", userId: "example-user", currentStep: "start", history: [], isComplete: false });
console.log(state.isComplete); // true

Validates a pending approval binding and host authority before resuming its LangGraph thread.

Parameters:

  • input: Session ID, verified approver ID/role, boolean decision, optional comment, optional expected approvalId/bindingHash, and optional live authorizer overriding constructor settings.

Returns: Resumed state on success, or resumed:false with an error for absent/mismatched approval, denied authorization, or normalized invocation failure. A denial decision completes the graph as rejected.

An approved decision requires a live authorizer returning exactly true; a supplied authorizer also checks rejection decisions. Host writer serialization is required: this method does not acquire an independent lock or compare-and-swap checkpoint revisions. Missing optional expected IDs skip those comparisons. Resume failures can follow side effects; no rollback or automatic retry occurs.

Can reject saver/compilation errors, live authorizer rejection, or post-resume checkpoint failures.

Example:

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
export async function decide(graph: AgentGraphEngine, input: Parameters<AgentGraphEngine["resumeAfterApproval"]>[0]) {
// Authenticate the approver and supply live authorization before approving.
return graph.resumeAfterApproval(input);
}

True when verification/resumption reaches a readable checkpoint, including a resumed rejection decision; false on normalized failures and not proof that no side effect occurred.

Graph state loaded after resumption when available; may represent completion, rejection or another pending interrupt rather than final workflow success.

Optional explanation for a missing/mismatched approval, denied authority, invocation failure or disappeared checkpoint; some saver/authorizer errors reject instead.

LangGraph thread/session identity whose saved pending approval is loaded and resumed.

Optional expected ticket identity; when truthy it must equal the saved pending ticket, while omission skips this comparison.

Optional expected request/contract binding hash; when truthy it must match the saved binding, while omission skips this comparison.

Verified review decision; true requires live authorization returning exactly true, while false resumes the graph as rejected.

Nonblank host-verified reviewer identity supplied to the live authorizer and recorded in lastApproval.

Nonblank host-verified reviewer role supplied to the live authorizer and recorded in lastApproval.

Optional reviewer comment retained in the graph decision; the host owns content/privacy policy.

Optional live reviewer-authority callback overriding the constructor authorizer for this resume attempt.

Uses AgentGraphEngineOptions.authorizeResume: receives a cloned checkpoint and reviewer/decision metadata, resolves exactly true to permit resumption, and may reject. Required from either source for approved=true; when supplied it also checks rejected decisions. Omission uses the constructor callback.

AgentGraphEngineOptions.authorizeResume

import { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
const graph = new AgentGraphEngine();
graph.addNode("start", async () => ({ isComplete: true }));
console.log(graph.describe().entryNode); // "start"

Checkpoint persistence, live approval authority, and workflow metadata for AgentGraphEngine.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface AgentGraphEngineOptions {
authorizeResume?: (state: AgentGraphState, input: {
approverId: string;
approverRole: string;
approved: boolean;
}) => Promise<boolean>;
checkpointer?: BaseCheckpointSaver;
workflowId?: string;
workflowVersion?: string;
}
Name Type Required Description
authorizeResume (state: AgentGraphState, input: { approverId: string; approverRole: string; approved: boolean; }) => Promise<boolean> No Host-owned live membership/lifecycle/resource re-check at resume time.
checkpointer BaseCheckpointSaver No Official LangGraph checkpointer. MemorySaver is local/test-only when omitted.
workflowId string No Stable identity shown by workflow viewers and exported graph documents.
workflowVersion string No Optional workflow version included in graph descriptions.

Type declaration; no runtime value.

Host-owned live membership/lifecycle/resource re-check at resume time.

Nonblank authenticated approver identifier supplied by the host.

Nonblank verified role associated with this human decision.

True requests continuation and requires a current authorizer; false rejects the workflow but is also checked when an authorizer exists.

Official LangGraph checkpointer. MemorySaver is local/test-only when omitted.

Stable identity shown by workflow viewers and exported graph documents.

Optional workflow version included in graph descriptions.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Serializable workflow identity, history, context, and approval state persisted by the graph checkpointer.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface AgentGraphState {
sessionId: string;
tenantId: string;
userId: string;
currentStep: string;
history: Array<{
role: string;
content: string;
timestamp: string;
}>;
context?: Record<string, unknown>;
citations?: Array<{
title: string;
source: string;
score: number;
}>;
pendingApproval?: {
approvalId?: string;
toolName: string;
approvalLevel: ApprovalLevel;
riskLevel: string;
reason: string;
args: Record<string, unknown>;
binding?: ApprovalBinding;
target?: {
type: string;
id: string;
revision?: number;
};
contractVersion?: string;
permission?: string;
};
checkpointRevision?: number;
lastApproval?: GraphApprovalDecision & {
approvalId: string;
bindingHash: string;
decidedAt: string;
};
isComplete: boolean;
error?: string;
}
Name Type Required Description
sessionId string Yes Host-authorized checkpoint thread ID.
tenantId string Yes Verified tenant that owns this workflow.
userId string Yes Verified requesting user, bound into generated approvals.
currentStep string Yes Current node identifier used for display and approval continuation.
history Array<{ role: string; content: string; timestamp: string; }> Yes Ordered conversation/history entries; returned history replaces rather than appends automatically.
context Record<string, unknown> No Optional domain state merged by key; reserved __eaos keys belong to runtime internals.
citations Array<{ title: string; source: string; score: number; }> No Optional supporting source metadata carried through state.
pendingApproval { approvalId?: string; toolName: string; approvalLevel: ApprovalLevel; riskLevel: string; reason: string; args: Record<string, unknown>; binding?: ApprovalBinding; target?: { type: string; id: string; revision?: number; }; contractVersion?: string; permission?: string; } No Optional pending human decision, bound to tenant/user/operation before checkpointing.
checkpointRevision number No Optional host checkpoint revision metadata; this engine does not increment it itself.
lastApproval GraphApprovalDecision & { approvalId: string; bindingHash: string; decidedAt: string; } No Optional last decision plus approval ID, binding hash, and ISO decision timestamp.
isComplete boolean Yes True when execution has completed or a decision rejected the workflow.
error string No Optional domain/runtime failure description included in runtime display overlays.

Type declaration; no runtime value.

AgentGraphEngine.runStep for a complete usage example.

Host-authorized checkpoint thread ID.

Verified tenant that owns this workflow.

Verified requesting user, bound into generated approvals.

Current node identifier used for display and approval continuation.

Ordered conversation/history entries; returned history replaces rather than appends automatically.

Speaker/category label supplied by the host or runtime.

Human-readable history text.

ISO timestamp for runtime-generated entries; host entries are not validated here.

Optional domain state merged by key; reserved __eaos keys belong to runtime internals.

Optional supporting source metadata carried through state.

Display title supplied by the citing node.

Source identifier or URL supplied by the node.

Host/model relevance score; this engine imposes no numeric range.

Optional pending human decision, bound to tenant/user/operation before checkpointing.

Optional ticket ID; generated when absent during binding.

Operation name bound to the approval and requested permission by default.

Required human-approval level for the operation.

Risk label; generated binding normalizes unknown labels to high.

Human-readable approval justification, visible in runtime overlays.

Operation input used to construct the approval binding.

Optional prebuilt binding validated against workflow tenant/user/operation.

Optional resource identity and revision included in generated binding.

Resource category included in the approval binding.

Resource identifier included in the approval binding.

Optional expected resource revision for host approval/admission.

Optional generated binding contract version; defaults to 1.0.0.

Optional generated binding permission; defaults to toolName.

Optional host checkpoint revision metadata; this engine does not increment it itself.

Optional last decision plus approval ID, binding hash, and ISO decision timestamp.

Identity of the pending review ticket consumed by this completed approval decision.

Exact approved request/contract binding hash copied from the consumed pending approval.

ISO timestamp generated when the graph processes the resumed review decision.

True when execution has completed or a decision rejected the workflow.

Optional domain/runtime failure description included in runtime display overlays.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Optional eligibility constraints for durable queue claims; omitted fields impose no restriction.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

interface AgentJobClaimFilter {
dispatchMode?: ServerAgentDispatchMode;
routeIds?: readonly string[];
runnerId?: string;
userId?: string;
}
Name Type Required Description
dispatchMode ServerAgentDispatchMode No Delivery mode; legacy jobs without a mode are treated as server-queue by the atomic implementation.
routeIds readonly string[] No Eligible registered route IDs; jobs without a matching route are excluded.
runnerId string No Verified runner ID; jobs with a different explicit runner binding are excluded, unbound jobs remain eligible.
userId string No Verified owning user ID to require.

Type declaration; no runtime value.

AgentJobStore.claim.

Delivery mode; legacy jobs without a mode are treated as server-queue by the atomic implementation.

Eligible registered route IDs; jobs without a matching route are excluded.

Verified runner ID; jobs with a different explicit runner binding are excluded, unbound jobs remain eligible.

Verified owning user ID to require.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host queue/worker and one-pass retry policy for DurableAgentJobDispatcher.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

interface AgentJobDispatcherOptions {
store: AgentJobStore;
worker: ServerAutonomousWorker;
batchSize?: number;
maxAttempts?: number;
baseDelayMs?: number;
maxDelayMs?: number;
now?: () => Date;
onCompleted?: (job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: ServerAgentTaskResult) => Promise<void>;
}
Name Type Required Description
store AgentJobStore Yes Durable queue enforcing claim leases and tenant admission.
worker ServerAutonomousWorker Yes Worker executing each cloned claimed task.
batchSize number No Jobs requested per pass, safe integer 1–100; defaults to 1.
maxAttempts number No Dispatcher attempt ceiling, safe integer 1–100; defaults to 5 and is combined with each job ceiling.
baseDelayMs number No Finite nonnegative initial exponential retry delay in milliseconds; defaults to 1000.
maxDelayMs number No Finite retry delay ceiling at least baseDelayMs; defaults to 60000 milliseconds.
now () => Date No Clock for claims, transitions, and retry availability; defaults to fresh Date.
onCompleted (job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: ServerAgentTaskResult) => Promise<void> No Resume a LangGraph thread or publish a domain event after a successful agent result.

Type declaration; no runtime value.

Durable queue enforcing claim leases and tenant admission.

Worker executing each cloned claimed task.

Jobs requested per pass, safe integer 1–100; defaults to 1.

Dispatcher attempt ceiling, safe integer 1–100; defaults to 5 and is combined with each job ceiling.

Finite nonnegative initial exponential retry delay in milliseconds; defaults to 1000.

Finite retry delay ceiling at least baseDelayMs; defaults to 60000 milliseconds.

Clock for claims, transitions, and retry availability; defaults to fresh Date.

Resume a LangGraph thread or publish a domain event after a successful agent result.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Counts of one dispatcher pass; jobs missing lease tokens increment failed without a store transition.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

interface AgentJobDispatchResult {
claimed: number;
succeeded: number;
waitingApproval: number;
retried: number;
failed: number;
}
Name Type Required Description
claimed number Yes Number of rows returned by the claim.
succeeded number Yes Jobs whose completion callback and completed transition succeeded.
waitingApproval number Yes Jobs transitioned to waiting_approval.
retried number Yes Jobs scheduled for a later retry.
failed number Yes Jobs marked terminal failure plus claimed jobs missing a lease token.

Type declaration; no runtime value.

DurableAgentJobDispatcher.runOnce.

Number of rows returned by the claim.

Jobs whose completion callback and completed transition succeeded.

Jobs transitioned to waiting_approval.

Jobs scheduled for a later retry.

Jobs marked terminal failure plus claimed jobs missing a lease token.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host durable queue boundary with atomic claims and lease-checked transitions.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

interface AgentJobStore {
claim(now: Date, limit: number, filter?: AgentJobClaimFilter): Promise<readonly AgentJobRecord<ServerAgentTaskRequest>[]>;
markCompleted(jobId: string, leaseToken: string, result: ServerAgentTaskResult, now: Date): Promise<void>;
markWaitingApproval(jobId: string, leaseToken: string, result: ServerAgentTaskResult, now: Date): Promise<void>;
markRetryable(jobId: string, leaseToken: string, error: string, failureCode: string | undefined, retryAt: Date, now: Date): Promise<void>;
markFailed(jobId: string, leaseToken: string, error: string, failureCode: string | undefined, now: Date): Promise<void>;
}
Name Type Required Description
claim Promise<readonly AgentJobRecord<ServerAgentTaskRequest>[]> Yes Claims due/recoverable jobs using durable transaction/lease exclusion.
markCompleted Promise<void> Yes Transitions the leased job to succeeded and persists its result.
markWaitingApproval Promise<void> Yes Transitions the leased job to waiting_approval and persists approval result data.
markRetryable Promise<void> Yes Releases the lease and schedules the job for a later attempt.
markFailed Promise<void> Yes Releases the lease and marks a terminal failed result.

Type declaration; no runtime value.

createAtomicAgentJobStore for the canonical implementation.

Claims due/recoverable jobs using durable transaction/lease exclusion.

Parameters:

  • now: Claim clock used for due and stale checks.
  • limit: Maximum job count, validated by the implementation.
  • filter: Optional dispatch/user/runner/route eligibility.

Returns: Leased jobs, or an empty array.

Queue persistence or admission failures propagate.

Example:

import type { AgentJobStore } from "@alneas/eaos-server";
export async function claimHostJobs(
store: AgentJobStore, eligibility: Parameters<AgentJobStore["claim"]>[2],
) {
// Supply a store already scoped to verified tenant admission.
return await store.claim(new Date(), 10, eligibility);
}

Transitions the leased job to succeeded and persists its result.

Parameters:

  • jobId: Stored job ID.
  • leaseToken: Current claim token; stale tokens must be rejected.
  • result: Normalized task outcome to persist.
  • now: Transition clock; the atomic implementation uses its configured clock instead.

Returns: No value; resolves after the durable transition.

Lease/integrity/admission or persistence failures propagate.

Example:

import type { AgentJobStore } from "@alneas/eaos-server";
export async function completeClaimedJob(
store: AgentJobStore, jobId: string, currentLeaseToken: string,
verifiedResult: Parameters<AgentJobStore["markCompleted"]>[2],
) {
await store.markCompleted(jobId, currentLeaseToken, verifiedResult, new Date());
// Completion is durable under the host store contract; stale leases reject.
}

Transitions the leased job to waiting_approval and persists approval result data.

Parameters:

  • jobId: Stored job ID.
  • leaseToken: Current claim token; stale tokens must be rejected.
  • result: Normalized task outcome to persist.
  • now: Transition clock; the atomic implementation uses its configured clock instead.

Returns: No value; resolves after the durable transition.

Lease/integrity/admission or persistence failures propagate.

Example:

import type { AgentJobStore } from "@alneas/eaos-server";
export async function deferClaimedJobForReview(
store: AgentJobStore, jobId: string, currentLeaseToken: string,
approvalResult: Parameters<AgentJobStore["markWaitingApproval"]>[2],
) {
await store.markWaitingApproval(jobId, currentLeaseToken, approvalResult, new Date());
// This records pending review; it does not approve or execute the proposed action.
}

Releases the lease and schedules the job for a later attempt.

Parameters:

  • jobId: Stored job ID.
  • leaseToken: Current claim token; stale tokens must be rejected.
  • error: Persisted failure description.
  • failureCode: Optional stable runtime classification.
  • retryAt: Earliest eligible next-claim timestamp.
  • now: Transition clock; the atomic implementation uses its configured clock instead.

Returns: No value; resolves after the durable transition.

Lease/integrity/admission or persistence failures propagate.

Example:

import type { AgentJobStore } from "@alneas/eaos-server";
export async function rescheduleClaimedJob(
store: AgentJobStore, jobId: string, currentLeaseToken: string,
sanitizedError: string, failureCode: string | undefined, reviewedRetryAt: Date,
) {
// Reconcile any uncertain external effect before deciding a retry is safe.
await store.markRetryable(
jobId, currentLeaseToken, sanitizedError, failureCode, reviewedRetryAt, new Date(),
);
}

Releases the lease and marks a terminal failed result.

Parameters:

  • jobId: Stored job ID.
  • leaseToken: Current claim token; stale tokens must be rejected.
  • error: Persisted failure description.
  • failureCode: Optional stable runtime classification.
  • now: Transition clock; the atomic implementation uses its configured clock instead.

Returns: No value; resolves after the durable transition.

Lease/integrity/admission or persistence failures propagate.

Example:

import type { AgentJobStore } from "@alneas/eaos-server";
export async function failClaimedJob(
store: AgentJobStore, jobId: string, currentLeaseToken: string,
sanitizedError: string, failureCode: string | undefined,
) {
await store.markFailed(jobId, currentLeaseToken, sanitizedError, failureCode, new Date());
// The host persisted terminal failure; no automatic retry is requested.
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Selected runtime decision and unpersisted or saved queue job.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/ai-broker.

interface AIJobPlan {
decision: AIExecutionDecision;
job: AgentJobRecord<ServerAgentTaskRequest>;
}
Name Type Required Description
decision AIExecutionDecision Yes Current selector decision, even when enqueue returns an existing deduplicated job.
job AgentJobRecord<ServerAgentTaskRequest> Yes Created or deduplicated queue record with persisted runtime routing.

Type declaration; no runtime value.

DurableAIExecutionBroker.enqueue.

Current selector decision, even when enqueue returns an existing deduplicated job.

Created or deduplicated queue record with persisted runtime routing.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified routing request, task, and queue deduplication/retry metadata.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/ai-broker.

interface AIJobSubmission {
routing: AIExecutionRequest;
task: AIJobTaskInput;
kind: AgentJobKind;
workflowInstanceId?: string;
correlationId?: string;
idempotencyKey?: string;
maxAttempts?: number;
}
Name Type Required Description
routing AIExecutionRequest Yes Core execution requirements and verified context used for route allocation.
task AIJobTaskInput Yes Verified task before worker/routing binding.
kind AgentJobKind Yes Queue job kind and idempotency partition.
workflowInstanceId string No Optional associated workflow instance.
correlationId string No Optional queue correlation ID; defaults to routing.context.operation.
idempotencyKey string No Optional durable deduplication key; absent uses task execution key then task.id.
maxAttempts number No Optional job attempt ceiling; defaults to 5 through createAgentJob.

Type declaration; no runtime value.

DurableAIExecutionBroker.plan.

Core execution requirements and verified context used for route allocation.

Verified task before worker/routing binding.

Queue job kind and idempotency partition.

Optional associated workflow instance.

Optional queue correlation ID; defaults to routing.context.operation.

Optional durable deduplication key; absent uses task execution key then task.id.

Optional job attempt ceiling; defaults to 5 through createAgentJob.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified task input before the broker chooses immutable runtime routing fields.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/ai-broker.

interface AIJobTaskInput {
id: string;
tenantId: string;
userId: string;
title: string;
instructions: string;
context?: Record<string, unknown>;
executionContext?: ServerAgentExecutionContext;
timeoutMs?: number;
}
Name Type Required Description
id string Yes Stable task identifier.
tenantId string Yes Verified tenant, required to match routing context.
userId string Yes Verified user, required to match routing context.
title string Yes Human task label forwarded to runtime.
instructions string Yes Runtime instructions forwarded without domain validation here.
context Record<string, unknown> No Optional domain execution context.
executionContext ServerAgentExecutionContext No Optional workflow/tool context; broker-owned routing fields are replaced.
timeoutMs number No Optional runtime timeout in milliseconds, forwarded for executor validation.

Type declaration; no runtime value.

DurableAIExecutionBroker.plan.

Stable task identifier.

Verified tenant, required to match routing context.

Verified user, required to match routing context.

Human task label forwarded to runtime.

Runtime instructions forwarded without domain validation here.

Optional domain execution context.

Optional workflow/tool context; broker-owned routing fields are replaced.

Optional runtime timeout in milliseconds, forwarded for executor validation.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported reader annotation operation names; this list itself grants no document access.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/annotations.

declare const annotationOperations: readonly [
"get_annotations",
"set_check",
"add_comment",
"resolve_comment"
];
Name Type Required Description
— — — No call parameters.

Declared constant value.

documentAnnotations for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compose closed annotation operation schemas from the owning document’s trusted target fields.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/annotations.

declare function annotationSchemas(target: Record<string, unknown>): {
get_annotations: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
[x: string]: unknown;
};
};
set_check: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
[x: string]: unknown;
};
};
add_comment: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
[x: string]: unknown;
};
};
resolve_comment: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
[x: string]: unknown;
};
};
};
Name Type Required Description
target Record<string, unknown> Yes Trusted JSON Schema property map for the owning document identity; those keys are required on every operation.

{ get_annotations: { type: string; additionalProperties: boolean; required: string[]; properties: { [x: string]: unknown; }; }; set_check: { type: string; additionalProperties: boolean; required: string[]; properties: { [x: string]: unknown; }; }; add_comment: { type: string; additionalProperties: boolean; required: string[]; properties: { [x: string]: unknown; }; }; resolve_comment: { type: string; additionalProperties: boolean; required: string[]; properties: { [x: string]: unknown; }; }; }

Schemas for get_annotations, set_check, add_comment and resolve_comment.

Schema generation does not authorize or execute annotations; the owner validates input and pins the exact document before transaction work.

import { annotationSchemas } from '@alneas/eaos-server/plugin-data'
const schemas = annotationSchemas({ documentId: { type: 'string', minLength: 1 } })

Pinned owning-document scope hash and admitted anchor/check IDs; authorization is supplied by its owner.

The owning plugin authorizes and pins the document before entering this transaction.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/annotations.

interface AnnotationTarget {
scope: string;
anchorIds: readonly string[];
checkIds: readonly string[];
}
Name Type Required Description
scope string Yes Trusted 64-character document-scope hash pinned by the owning plugin.
anchorIds readonly string[] Yes Exact anchor IDs valid for newly created reader comments.
checkIds readonly string[] Yes Exact reading-check IDs admitted for this pinned document.

Type declaration; no runtime value.

documentAnnotations for canonical host integration.

Trusted 64-character document-scope hash pinned by the owning plugin.

Exact anchor IDs valid for newly created reader comments.

Exact reading-check IDs admitted for this pinned document.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host persistence lookup for resolveApiKey; records must retain hashed credentials and lifecycle state.

Imports: @alneas/eaos-server/auth-hooks, @alneas/eaos-server/auth-hooks/api-key.

interface ApiKeyLookup {
findByPrefix(prefix: string): Promise<ApiKeyRecord | null>;
}
Name Type Required Description
findByPrefix Promise<ApiKeyRecord | null> Yes Reads a key record by its 12-character public prefix.

Type declaration; no runtime value.

Reads a key record by its 12-character public prefix.

Parameters:

  • prefix: Prefix extracted from an eaos_ credential; never the full secret.

Returns: The stored record, or null if absent.

Persistence errors propagate to resolveApiKey callers.

Example:

import type { ApiKeyLookup } from "@alneas/eaos-server/auth-hooks";
export async function findStoredApiKey(lookup: ApiKeyLookup, parsedPrefix: string) {
const record = await lookup.findByPrefix(parsedPrefix);
return record; // A record match still requires secret, scope and lifecycle verification.
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Append a hash-linked immutable audit event and CAS-update its head in the current transaction.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/audit.

declare function appendAtomicAudit(tx: AtomicSession, p: PluginPrincipal, operation: string, input: unknown, result: unknown, commandKey?: string | null): Promise<{
hash: string;
version: 1;
tenantId: string;
sequence: number;
operation: string;
actorId: string;
at: string;
inputHash: string;
resultHash: string;
commandKey: string | null;
previousHash: string | null;
}>;
Name Type Required Description
tx AtomicSession Yes Live atomic session shared with the domain command.
p PluginPrincipal Yes Verified tenant/user principal.
operation string Yes Trusted nonempty operation label of at most 240 characters.
input unknown Yes Input whose JSON-normalized hash is recorded; payload bytes are not stored in the audit event.
result unknown Yes Result whose JSON-normalized hash is recorded; undefined is normalized to null.
commandKey string | null No Optional command/ receipt key linking command input/result evidence; defaults to null.

Promise<{ hash: string; version: 1; tenantId: string; sequence: number; operation: string; actorId: string; at: string; inputHash: string; resultHash: string; commandKey: string \| null; previousHash: string \| null; }>

The appended version-1 event with sequence and integrity hash.

Requires the caller’s existing transaction and current authorization. Hash continuity is not an external trust anchor; real business payloads remain outside audit events.

Rejects invalid principals/labels/receipt keys, corrupt head/previous event, sequence capacity or transaction failures.

import { appendAtomicAudit } from '@alneas/eaos-server/plugin-data'
export function audit(tx: Parameters<typeof appendAtomicAudit>[0], p: Parameters<typeof appendAtomicAudit>[1], input: unknown, result: unknown) { return appendAtomicAudit(tx, p, 'example-operation', input, result) }

Replaces membership fields under a durable lock and verifies provider readback before recording completion.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

declare function applyAccountMembershipChange(plan: MembershipMigrationPlan, actor: string, store: AccountMutationStore, admin: AccountAdminPort): Promise<void>;
Name Type Required Description
plan MembershipMigrationPlan Yes Reviewed target claims, metadata field, and expected pre-change field hash.
actor string Yes Nonblank authenticated operator identity; authorization is host-owned.
store AccountMutationStore Yes Durable exclusive lock and completion audit implementation.
admin AccountAdminPort Yes Trusted provider read/write implementation.

Promise<void>

No value; resolves after verified provider update and durable completion. Unrelated metadata keys are retained and absent defaultTenantId is written as null.

A failed/uncertain mutation retains its durable lock. Reconcile; never auto-expire or blindly retry. This function does not roll back provider changes. Defaults to metadata_admin; explicitly selecting metadata_public exposes claims to the account holder.

Rejects invalid actor/metadata field/claims, stale or inactive identity, failed readback, or propagated lock/provider/completion errors.

import { applyAccountMembershipChange, type MembershipMigrationPlan, type AccountMutationStore, type AccountAdminPort } from "@alneas/eaos-server/browser-auth/account-memberships";
export async function applyReviewedPlan(plan: MembershipMigrationPlan, actor: string, store: AccountMutationStore, admin: AccountAdminPort) {
await applyAccountMembershipChange(plan, actor, store, admin);
}

Coordinates durable approved publication/withdrawal jobs with channel ownership and resumable idempotent host effects.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

declare class ArtifactDeliveryService {
constructor(options: {
repository: AtomicRepository;
ports: DeliveryPorts;
authorize(p: PluginPrincipal, operation: string, input: unknown, resource?: unknown): Promise<boolean>;
});
execute(p: PluginPrincipal, op: string, a: {
jobId: string;
revision?: number;
commandId?: string;
} & Partial<DeliveryRequest>): Promise<any>;
}
Name Type Required Description
options { repository: AtomicRepository; ports: DeliveryPorts; authorize(p: PluginPrincipal, operation: string, input: unknown, resource?: unknown): Promise<boolean>; } Yes Real atomic repository, idempotent host delivery ports and current operation/resource authorization; construction does not validate or execute those ports.

ArtifactDeliveryService

Requires a real atomic repository and host public-approval/build/channel/purge ports. Channel locks serialize unfinished jobs per tenant/repository. External build/activate/purge/cancel run outside database transactions; a failed reply can follow a completed external effect. Ports must deduplicate by stable jobId. Recovery requires proof that previous workers drained, never an elapsed lease alone.

Real atomic delivery ledger used for jobs, channel ownership and enqueue command receipts.

Host public-approval, artifact, channel, purge and recovery adapters with stable jobId idempotency.

Live operation/resource permission callback; exactly true admits, false denies; schema validation follows initial admission.

Parameters:

  • p: Verified current tenant/user principal.
  • operation: Declared operation name.
  • input: Operation input to validate and authorize at the owning service boundary.
  • resource: Optional current delivery job/resource when available.

Returns: Exactly true to admit the current operation; false denies.

Rejects underlying service, authorization or persistence failures.

Example:

import type { ArtifactDeliveryService, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function canEnqueue(options: ConstructorParameters<typeof ArtifactDeliveryService>[0], principal: PluginPrincipal, input: unknown) {
return await options.authorize(principal, "enqueue_delivery", input) === true;
}

Enqueues, reads, runs, cancels or explicitly recovers one durable approved delivery job.

Parameters:

  • p: Verified current tenant principal; operation/resource admission is rechecked before transitions.
  • op: One of deliveryOperations; each input is checked by its closed schema.
  • a: jobId for every operation; enqueue additionally needs commandId/channel/kind/target/contentHash/approvalRequestId, and recovery needs the exact running job revision.

Returns: The durable AtomicRow, possibly an existing identical enqueue receipt or already terminal job; query get_delivery for current state after receipt replay.

Publish starts at build, withdrawal at activate; completion follows successful purge. Cancellation requires a reconciliation port and never removes a newer host version. Completed jobs require a new withdrawal job instead of cancellation. Recovery requires exact revision and drained(old token), marks failed and clears ownership for retry. Failure retains the last durable phase and a sanitized error, while the original host error may reject the call.

Rejects invalid principal/input (401/400), denied live/public approval (403), absent job (404), busy channel/worker, stale recovery or unavailable cancellation port (409), invalid built artifact and propagated repository/port failures; effects may already have occurred.

Example:

import { ArtifactDeliveryService, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export function readDelivery(service: ArtifactDeliveryService, principal: PluginPrincipal, jobId: string) { return service.execute(principal, 'get_delivery', { jobId }); }

Stable job ID required by every delivery operation; 1–80 letters/digits/underscore/hyphen characters.

Exact current positive running-job revision required only for explicit drained-worker recovery.

Stable enqueue idempotency ID; identical input replays the original receipt and conflicting reuse rejects.

import { ArtifactDeliveryService } from '@alneas/eaos-server/plugin-data';
export function connectDelivery(options: ConstructorParameters<typeof ArtifactDeliveryService>[0]) { return new ArtifactDeliveryService(options); }

Validates matching verification and a source-retaining cutover receipt for the target backend.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

declare function assertBackendMigrationCutover(plan: BackendMigrationPlan, report: BackendMigrationVerificationReport, cutover: BackendMigrationCutover): BackendMigrationCutover;
Name Type Required Description
plan BackendMigrationPlan Yes Reviewed backend migration plan.
report BackendMigrationVerificationReport Yes Passed host verification matching the plan.
cutover BackendMigrationCutover Yes Host routing receipt with nonnegative routing revision and parseable cutover timestamp.

BackendMigrationCutover

The original cutover object; no routing mutation occurs.

This is evidence shape validation, not independent copy verification or authority to switch a tenant.

Error for invalid verification, mismatched target/migration, missing source-retention claim or invalid revision/time.

import { assertBackendMigrationCutover, type BackendMigrationPlan, type BackendMigrationVerificationReport, type BackendMigrationCutover } from '@alneas/eaos-server/lifecycle-engine/backend-migration';
export function inspectCutover(plan: BackendMigrationPlan, report: BackendMigrationVerificationReport, receipt: BackendMigrationCutover) { return assertBackendMigrationCutover(plan, report, receipt); }

[FUNCTION] assertBackendMigrationVerification

Section titled “[FUNCTION] assertBackendMigrationVerification”

Checks that a reported migration verification matches its plan and contains only matched in-scope records.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

declare function assertBackendMigrationVerification(plan: BackendMigrationPlan, report: BackendMigrationVerificationReport): BackendMigrationVerificationReport;
Name Type Required Description
plan BackendMigrationPlan Yes Reviewed backend migration plan.
report BackendMigrationVerificationReport Yes Host report claiming passed verification for the plan’s source and target.

BackendMigrationVerificationReport

The original report when accepted; it is neither cloned nor independently measured.

Validates nonempty records and nonnegative revisions, but does not prove exhaustive tenant/plugin coverage or equal source/target revision numbers. The host owns verification completeness and truth.

Error for mismatched identities, invalid timestamp/revisions, out-of-scope records or unpassed/unmatched evidence.

import { assertBackendMigrationVerification, type BackendMigrationPlan, type BackendMigrationVerificationReport } from '@alneas/eaos-server/lifecycle-engine/backend-migration';
export function inspectVerification(plan: BackendMigrationPlan, report: BackendMigrationVerificationReport) { return assertBackendMigrationVerification(plan, report); }

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function assertDataContractBinding(catalog: DataContractCatalog, binding: DataContractBinding): void;
Name Type Required Description
catalog DataContractCatalog Yes See the upstream owning declaration.
binding DataContractBinding Yes See the upstream owning declaration.

void

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function assertJsonDocumentContracts(documents: readonly JsonDocumentContract[], tables: ReadonlyMap<string, Record<string, unknown>>): void;
Name Type Required Description
documents readonly JsonDocumentContract[] Yes See the upstream owning declaration.
tables ReadonlyMap<string, Record<string, unknown>> Yes See the upstream owning declaration.

void

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Check the structural presence of a nonblank tenant/user identity and string role list.

Imports: @alneas/eaos-server/plugin-data.

declare function assertPrincipal(p: PluginPrincipal): void;
Name Type Required Description
p PluginPrincipal Yes Principal from a trusted authentication resolver.

void

No value; normal completion means the principal has the required shape.

Shape validation is not authentication, membership verification or resource authorization.

Throws PluginError 401 for malformed principal fields.

import { assertPrincipal } from '@alneas/eaos-server/plugin-data'
assertPrincipal({ tenantId: 'example-tenant', userId: 'example-user', roles: [] })

Tenant-scoped CAS persistence, lease timing, admission, and transactional completion hook.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

interface AtomicAgentJobStoreOptions {
repository: AtomicRepository;
principal: PluginPrincipal;
staleAfterMs?: number;
leaseMs?: number;
now?: () => Date;
verifyCurrent?: () => Promise<void>;
onCompleted?: (tx: AtomicSession, job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: Readonly<ServerAgentTaskResult>) => Promise<void>;
}
Name Type Required Description
repository AtomicRepository Yes Host atomic repository enforcing durable CAS and tenant isolation.
principal PluginPrincipal Yes Verified tenant/plugin/user repository scope, retained by reference.
staleAfterMs number No Additional stale grace after lease expiry in milliseconds; finite and at least 1000, defaults to 300000.
leaseMs number No Lease duration in milliseconds; finite and at least 1000, defaults to 900000.
now () => Date No Clock for state transitions; defaults to fresh Date.
verifyCurrent () => Promise<void> No Current host admission is checked before and after durable mutations.
onCompleted (tx: AtomicSession, job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: Readonly<ServerAgentTaskResult>) => Promise<void> No Persist the domain result in the same transaction as the succeeded job state.

Type declaration; no runtime value.

createAtomicAgentJobStore.

Host atomic repository enforcing durable CAS and tenant isolation.

Verified tenant/plugin/user repository scope, retained by reference.

Additional stale grace after lease expiry in milliseconds; finite and at least 1000, defaults to 300000.

Lease duration in milliseconds; finite and at least 1000, defaults to 900000.

Clock for state transitions; defaults to fresh Date.

Current host admission is checked before and after durable mutations.

Persist the domain result in the same transaction as the succeeded job state.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Version-1 hash-linked journal event storing payload hashes and optional command receipt identity.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/audit.

interface AtomicAuditEvent {
version: 1;
tenantId: string;
sequence: number;
operation: string;
actorId: string;
at: string;
inputHash: string;
resultHash: string;
commandKey: string | null;
previousHash: string | null;
hash: string;
}
Name Type Required Description
version 1 Yes Persisted journal schema version; must be 1.
tenantId string Yes Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.
sequence number Yes Positive monotonically increasing journal position within the tenant/namespace.
operation string Yes Trusted operation label recorded for this admitted command.
actorId string Yes Verified actor identity at append time.
at string Yes UTC ISO append timestamp.
inputHash string Yes Hash of JSON-normalized command input; no input payload bytes are stored here.
resultHash string Yes Hash of JSON-normalized command result; undefined is normalized to null.
commandKey string | null Yes Optional immutable command receipt key, otherwise null.
previousHash string | null Yes Previous journal event hash, or null for the first event.
hash string Yes Canonical hash of the other event fields; not an external signature.

Type declaration; no runtime value.

appendAtomicAudit for canonical host integration.

Persisted journal schema version; must be 1.

Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.

Positive monotonically increasing journal position within the tenant/namespace.

Trusted operation label recorded for this admitted command.

Verified actor identity at append time.

UTC ISO append timestamp.

Hash of JSON-normalized command input; no input payload bytes are stored here.

Hash of JSON-normalized command result; undefined is normalized to null.

Optional immutable command receipt key, otherwise null.

Previous journal event hash, or null for the first event.

Canonical hash of the other event fields; not an external signature.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Stores LangGraph checkpoints and pending writes in an existing scoped atomic repository.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic/atomic-checkpointer.

declare class AtomicCheckpointSaver extends BaseCheckpointSaver {
constructor(options: {
repository: AtomicRepository;
principal: PluginPrincipal;
verifyCurrent: () => Promise<void>;
prefix?: string;
});
getTuple(config: Config): Promise<CheckpointTuple | undefined>;
list(config: Config, options?: ListOptions): AsyncGenerator<CheckpointTuple>;
put(config: Config, checkpoint: Checkpoint, metadata: CheckpointMetadata): Promise<Config>;
putWrites(config: Config, writes: Writes, taskId: string): Promise<void>;
deleteThread(_threadId: string): Promise<void>;
}
Name Type Required Description
options { repository: AtomicRepository; principal: PluginPrincipal; verifyCurrent: () => Promise<void>; prefix?: string; } Yes Scoped repository; principal is validated/cloned; verifyCurrent must reject on revoked admission; prefix defaults to graph-checkpoint and must contain 1–64 lowercase letters/digits/underscore/hyphen.

AtomicCheckpointSaver

Admission and workflow writer serialization remain host-owned. Each saver instance serializes repository work through an internal Promise chain and calls verifyCurrent before the transaction and before/after its work. This does not serialize other saver instances or whole graph invocations. The repository owns durability/CAS; this saver installs no timers and does not close host storage. Checkpoint erasure requires a separate host retention executor.

Invalid principal, absent repository/verifier, invalid prefix, or clone failure.

Connected host atomic repository used for scoped checkpoint and pending-write transactions; this saver does not close it.

Verified plugin principal validated and cloned at construction; fixes the tenant/plugin/user scope used for repository transactions.

Recheck current host admission before repository work and at transaction boundaries.

Returns: No value; resolve only while the captured principal remains admitted and reject when admission is revoked.

Required callback; called before the repository transaction and before/after its work, and before each history yield. The host owns the live policy lookup.

AtomicCheckpointSaver

Optional repository key prefix; defaults to graph-checkpoint and must contain 1–64 lowercase letters, digits, underscores or hyphens.

Reads one scoped checkpoint and its separately stored pending writes.

Parameters:

  • config: LangGraph config with required thread_id, optional checkpoint_ns (default empty), and optional checkpoint_id (default latest lexicographic ID). Identifiers are bounded to 512 characters without control characters.

Returns: Decoded checkpoint tuple or undefined if no selected checkpoint exists.

Rejects invalid identifiers, tenant/thread/namespace or format mismatch, and admission/repository/serialization failures.

Example:

import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export async function read(saver: AtomicCheckpointSaver, config: Parameters<AtomicCheckpointSaver["getTuple"]>[0]) { return saver.getTuple(config); }

Lists scoped checkpoint history in descending lexicographic checkpoint-ID order.

Parameters:

  • config: Required thread scope, optional namespace, and optional exact checkpoint ID filter.
  • options: limit defaults to 100 and must be a safe integer 1–2000; before must use the same thread/namespace and excludes its ID and newer IDs; filter compares metadata fields by atomic hash.

Returns: Async sequence of decoded tuples, possibly empty, with admission rechecked before each yield.

History is collected in a bounded repository transaction before yielding; changing authorization can still stop later yields.

Iteration rejects invalid scope/limits, more than 2000 scanned checkpoint rows, identity/format mismatch, or admission/repository/serialization errors.

Example:

import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export async function history(saver: AtomicCheckpointSaver, config: Parameters<AtomicCheckpointSaver["list"]>[0]) {
const tuples = [];
for await (const tuple of saver.list(config, { limit: 10 })) tuples.push(tuple);
return tuples;
}

Writes an immutable version-4 checkpoint and advances the scoped latest pointer when its ID sorts later.

Parameters:

  • config: Thread/namespace scope; optional checkpoint_id becomes the new checkpoint’s parent ID.
  • checkpoint: Current LangGraph version-4 checkpoint with valid nonempty bounded ID.
  • metadata: Serializer-supported checkpoint metadata.

Returns: A config selecting the stored checkpoint ID.

Repeating identical content is accepted; latest ordering is lexicographic, so host checkpoint IDs must reflect desired chronology.

Rejects unsupported format, ID reuse with different content, admission/CAS/repository errors, or serialization failures.

Example:

import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export async function write(saver: AtomicCheckpointSaver, ...args: Parameters<AtomicCheckpointSaver["put"]>) { return saver.put(...args); }

Merges pending channel writes by task/index for one scoped checkpoint.

Parameters:

  • config: Thread/namespace with required checkpoint_id.
  • writes: At most 256 channel/value pairs; channels are valid bounded identifiers. Ordinary task/index duplicates retain their first value; reserved negative-index channels replace prior values.
  • taskId: Nonempty bounded task identifier associating writes.

Returns: No value; resolves after the merged writes are durably stored.

Rejects missing checkpoint ID, invalid task/channel, identity mismatch, more than 2000 stored pending writes, or admission/repository/serialization errors.

Example:

import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export async function writePending(saver: AtomicCheckpointSaver, ...args: Parameters<AtomicCheckpointSaver["putWrites"]>) { await saver.putWrites(...args); }

Rejects thread deletion because this repository contract provides no approved erasure operation.

Parameters:

  • _threadId: Requested thread ID; not read or deleted.

Returns: No value; this operation always rejects before performing storage work.

Always rejects with an error directing the caller to the host retention executor.

Example:

import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export async function erase(saver: AtomicCheckpointSaver, threadId: string) {
try { await saver.deleteThread(threadId); } catch (error) {
// Host retention tooling must perform reviewed erasure.
throw error;
}
}
import { AtomicCheckpointSaver } from "@alneas/eaos-server/agentic/atomic-checkpointer";
export function saver(options: ConstructorParameters<typeof AtomicCheckpointSaver>[0]) {
return new AtomicCheckpointSaver(options);
}

Replay or atomically record one principal/operation-scoped command result in an existing transaction.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function atomicCommand<T>(tx: AtomicSession, p: PluginPrincipal, operation: string, input: {
commandId: string;
}, work: () => Promise<T>): Promise<T>;
Name Type Required Description
tx AtomicSession Yes Live tenant-scoped atomic session enclosing the actual domain work.
p PluginPrincipal Yes Verified principal whose user ID scopes the command receipt.
operation string Yes Trusted operation name included in the receipt key.
input { commandId: string; } Yes Complete command input with a commandId of 1–80 letters/digits/underscore/hyphen.
work () => Promise<T> Yes Async domain callback run only for a new command; must remain inside the same transaction.

Promise<T>

The existing identical receipt result or the newly computed result.

  • T: JSON-serializable domain result stored and returned by the command receipt.

Caller performs live resource authorization before replay as well as execution. Domain writes, receipt and audit share the existing transaction; irreversible external effects must be durably queued, not performed inside work.

Rejects malformed command IDs, input reuse with a different hash, CAS/audit failures and propagated work errors.

Stable nonempty 1–80 character command ID scoped by actor and operation; identical full input replays the stored result.

import { atomicCommand, type AtomicRepository, type AtomicSession, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'
export function command<T>(repository: AtomicRepository, principal: PluginPrincipal, input: { commandId: string }, work: (session: AtomicSession) => Promise<T>) {
// The host performs live resource admission before replay or new execution.
return repository.run(principal, session => atomicCommand(session, principal, 'example-operation', input, () => work(session)))
}

Compute the canonical JSON SHA-256 used by atomic commands and scoped cursors.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function atomicHash(value: unknown): string;
Name Type Required Description
value unknown Yes Canonical-JSON-compatible value to hash.

string

Lowercase hexadecimal SHA-256.

A hash binds content; it is not a signature or external trust anchor.

Canonical serialization rejects unsupported or invalid values.

import { atomicHash } from '@alneas/eaos-server/plugin-data'
const hash = atomicHash({ id: 'example' })

Existing dispatcher options combined with the canonical atomic tenant Outbox store.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

interface AtomicOutboxDispatcherOptions extends Omit<OutboxDispatcherOptions, 'store'>, AtomicOutboxStoreOptions {
}
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

createAtomicOutboxDispatcher for canonical host integration.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Principal, repository and stale-claim settings for durable Outbox transitions.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

interface AtomicOutboxStoreOptions {
repository: AtomicRepository;
principal: PluginPrincipal;
staleAfterMs?: number;
now?: () => Date;
}
Name Type Required Description
repository AtomicRepository Yes Real atomic repository for durable tenant-scoped Outbox transitions.
principal PluginPrincipal Yes Verified fixed tenant/user scope copied at construction; replace the store when identity changes.
staleAfterMs number No Claim staleness threshold in milliseconds; defaults to 300000 and must be finite and at least 1000.
now () => Date No Optional dispatcher clock; createAtomicOutboxDispatcher forwards it, while standalone store.claim uses its explicit now parameter.

Type declaration; no runtime value.

createAtomicOutboxStore for canonical host integration.

Real atomic repository for durable tenant-scoped Outbox transitions.

Verified fixed tenant/user scope copied at construction; replace the store when identity changes.

Claim staleness threshold in milliseconds; defaults to 300000 and must be finite and at least 1000.

Optional dispatcher clock; createAtomicOutboxDispatcher forwards it, while standalone store.claim uses its explicit now parameter.

Returns: The trusted current Date when used by createAtomicOutboxDispatcher; standalone store.claim receives an explicit Date.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-admitted transactional entrypoint that scopes all session operations to one verified principal.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicRepository {
run<T>(principal: PluginPrincipal, work: (session: AtomicSession) => Promise<T>): Promise<T>;
}
Name Type Required Description
run Promise<T> Yes Runs work in one verified tenant transaction whose session expires when work settles.

Type declaration; no runtime value.

createAtomicRepository for canonical host integration.

Runs work in one verified tenant transaction whose session expires when work settles.

Parameters:

  • principal: Verified tenant/user principal; repository structure checks do not prove live permission.
  • work: Async domain work; never let session or joined SQL capabilities escape its lifetime.

Returns: The callback result after successful commit; work/commit failure rejects and triggers rollback.

  • T: Value resolved by the transaction/connection callback.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function updateTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string, title: string) {
return repository.run(principal, async session => {
const current = await session.get<{ title: string }>(id);
if (!current) throw new Error("Record unavailable");
return session.put(id, { title }, current.revision);
});
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Canonical namespace, JSON payload policy and optional document contracts for the atomic envelope table.

Plugin-owned table; tenant cannot be selected through individual row operations.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicRepositoryOptions {
namespace?: string;
storagePolicy?: PluginStoragePolicy;
documents?: readonly JsonDocumentContract[];
}
Name Type Required Description
namespace string No Optional trusted logical namespace encoded into physical IDs for a shared table.
storagePolicy PluginStoragePolicy No Declared payload/object/history limits; does not configure or authorize a provider.
documents readonly JsonDocumentContract[] No Canonical closed payload contracts copied and enforced by the wrapper.

Type declaration; no runtime value.

createAtomicRepository for canonical host integration.

Optional trusted logical namespace encoded into physical IDs for a shared table.

Declared payload/object/history limits; does not configure or authorize a provider.

Canonical closed payload contracts copied and enforced by the wrapper.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Tenant-scoped logical row and its CAS revision at the time of reading/writing.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicRow<T = unknown> {
id: string;
revision: number;
value: T;
}
Name Type Required Description
id string Yes Logical tenant/namespace-scoped record identity.
revision number Yes CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.
value T Yes Stored JSON payload whose runtime validation depends on the configured document contracts.

Type declaration; no runtime value.

  • T: JSON row payload shape; defaults to unknown.

createAtomicRepository for canonical host integration.

Logical tenant/namespace-scoped record identity.

CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.

Stored JSON payload whose runtime validation depends on the configured document contracts.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Temporary tenant/namespace-bound session valid only inside its repository work callback.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicSession {
get<T>(id: string): Promise<AtomicRow<T> | null>;
getMany?<T>(ids: string[]): Promise<(AtomicRow<T> | null)[]>;
putMany?<T>(changes: {
id: string;
value: T;
expected: number;
}[]): Promise<AtomicRow<T>[]>;
list<T>(prefix: string, after?: string, limit?: number): Promise<AtomicRow<T>[]>;
put<T>(id: string, value: T, expected: number): Promise<AtomicRow<T>>;
}
Name Type Required Description
get Promise<AtomicRow<T> | null> Yes Performs one scoped read inside the active repository transaction.
getMany Promise<(AtomicRow<T> | null)[]> No Performs ordered batch reads inside the active repository transaction. Batch reads preserve tenant scope and input order; missing rows are null.
putMany Promise<AtomicRow<T>[]> No Performs transactional batch CAS writes inside the active repository transaction. Every item uses CAS in the enclosing transaction; any failure rolls back all items.
list Promise<AtomicRow<T>[]> Yes Performs a bounded scoped keyset read inside the active repository transaction. Empty prefix reads the repository’s own tenant/namespace, never another tenant.
put Promise<AtomicRow<T>> Yes Performs one create-or-CAS write inside the active repository transaction. expected=0 creates; otherwise atomically replaces exactly the expected revision.

Type declaration; no runtime value.

createAtomicRepository for canonical host integration.

Performs one scoped read inside the active repository transaction.

Parameters:

  • id: Logical row ID; 1–240 supported record-key characters.

Returns: The scoped envelope or null when absent.

  • T: JSON payload type read or persisted by this session operation.

Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function readTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string) {
return repository.run(principal, async session => {
const row = await session.get<{ title: string }>(id);
return row?.value.title ?? null;
});
}

Performs ordered batch reads inside the active repository transaction.

Batch reads preserve tenant scope and input order; missing rows are null.

Parameters:

  • ids: Logical IDs in desired output order; duplicates retain their positions.

Returns: One envelope or null per input ID in the same order.

  • T: JSON payload type read or persisted by this session operation.

Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function readTitles(repository: AtomicRepository, principal: PluginPrincipal, ids: string[]) {
return repository.run(principal, async session => {
if (!session.getMany) throw new Error("Batch reads not supported");
return session.getMany<{ title: string }>(ids);
});
}

Performs transactional batch CAS writes inside the active repository transaction.

Every item uses CAS in the enclosing transaction; any failure rolls back all items.

Parameters:

  • changes: Unique logical-ID/value/expected changes; expected=0 creates and positive expected performs exact CAS.

Returns: Next-revision envelopes in input order; any failure must reject the enclosing transaction.

  • T: JSON payload type read or persisted by this session operation.

Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function createPair(repository: AtomicRepository, principal: PluginPrincipal) {
return repository.run(principal, async session => {
if (!session.putMany) throw new Error("Batch writes not supported");
return session.putMany([{ id: "examples/first", value: { title: "First" }, expected: 0 }, { id: "examples/second", value: { title: "Second" }, expected: 0 }]);
});
}

Unique logical record key within this batch and tenant namespace.

JSON payload to validate against configured policy/document contracts.

Expected safe CAS revision; 0 creates, positive values replace exactly that revision.

Performs a bounded scoped keyset read inside the active repository transaction.

Empty prefix reads the repository’s own tenant/namespace, never another tenant.

Parameters:

  • prefix: Logical prefix; empty stays within this repository tenant/namespace.
  • after: Optional exclusive logical ID; defaults to the start of the prefix range.
  • limit: Integer page size 1–101; defaults to 100.

Returns: Envelopes in stable logical-ID order within the prefix.

  • T: JSON payload type read or persisted by this session operation.

Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function firstPage(repository: AtomicRepository, principal: PluginPrincipal) {
return repository.run(principal, session => session.list<{ title: string }>("examples/", "", 20));
}

Performs one create-or-CAS write inside the active repository transaction.

expected=0 creates; otherwise atomically replaces exactly the expected revision.

Parameters:

  • id: Logical row ID.
  • value: JSON payload admitted by configured limits/contracts.
  • expected: Safe integer expected revision from 0 to MAX_SAFE_INTEGER-1; 0 creates, otherwise exact CAS.

Returns: A cloned-payload envelope with revision expected+1.

  • T: JSON payload type read or persisted by this session operation.

Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.

Example:

import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function createTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string, title: string) {
return repository.run(principal, session => session.put(id, { title }, 0));
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Weak capability map joining validated session wrappers to their live SQL connection, principal and dialect; trusted adapter plumbing only.

Internal capability propagation through validated session wrappers; never a new transaction.

Imports: @alneas/eaos-server/plugin-data/atomic-context.

declare const atomicSqlBindings: WeakMap<AtomicSession, {
connection: AtomicSqlConnection;
principal: PluginPrincipal;
dialect: AtomicSqlDriver["dialect"];
}>;
Name Type Required Description
— — — No call parameters.

Declared constant value.

inheritAtomicSqlSession for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Connection-bound SQL operations sharing the enclosing commit/rollback boundary.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicSqlConnection {
execute(sql: string, binds: unknown[]): Promise<{
rows?: Record<string, unknown>[];
affectedRows: number;
}>;
executeMany?(sql: string, binds: unknown[][]): Promise<{
affectedRows: number[];
}>;
}
Name Type Required Description
execute Promise<{ rows?: Record<string, unknown>[]; affectedRows: number; }> Yes Executes one trusted SQL statement on the exact connection owning the enclosing transaction.
executeMany Promise<{ affectedRows: number[]; }> No Optionally executes ordered bind batches on the same transaction connection.

Type declaration; no runtime value.

createAtomicRepository for canonical host integration.

Executes one trusted SQL statement on the exact connection owning the enclosing transaction.

Parameters:

  • sql: Trusted parameterized SQL with tenant/namespace predicates.
  • binds: Positional bind values in placeholder order.

Returns: Optional query rows and an accurate affected-row count.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function queryJoined(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantSql: string, bindings: unknown[]) {
return driver.transaction(principal, async connection => {
return (await connection.execute(trustedTenantSql, bindings)).rows ?? [];
});
}

Optional object rows from SELECT execution on this connection.

Accurate affected-row count for scalar execution or one count per ordered batch bind row.

Optionally executes ordered bind batches on the same transaction connection.

Parameters:

  • sql: Trusted parameterized DML.
  • binds: Ordered positional bind rows.

Returns: An affectedRows count for every bind row in input order; missing/wrong counts must fail CAS.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function batchReviewed(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantDml: string, binds: unknown[][]) {
return driver.transaction(principal, async connection => {
if (!connection.executeMany) throw new Error("Batch DML not supported");
return (await connection.executeMany(trustedTenantDml, binds)).affectedRows;
});
}

Accurate affected-row count for scalar execution or one count per ordered batch bind row.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Provider transaction boundary required for envelope CAS, domain writes and durable journal atomicity.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface AtomicSqlDriver {
dialect: 'sqlite' | 'oracle' | 'postgres';
transaction<T>(principal: PluginPrincipal, work: (connection: AtomicSqlConnection) => Promise<T>): Promise<T>;
}
Name Type Required Description
dialect 'sqlite' | 'oracle' | 'postgres' Yes SQL placeholder/driver dialect selected by trusted host configuration.
transaction Promise<T> Yes Acquires one transaction connection, commits success and rolls back rejection. Same connection for every statement; commits on success, rolls back on rejection.

Type declaration; no runtime value.

createAtomicRepository for canonical host integration.

SQL placeholder/driver dialect selected by trusted host configuration.

Acquires one transaction connection, commits success and rolls back rejection.

Same connection for every statement; commits on success, rolls back on rejection.

Parameters:

  • principal: Verified tenant/user principal used for host session admission.
  • work: Async work on the same connection for every domain/CAS/audit statement.

Returns: The callback result after commit; all joined writes roll back on failure.

  • T: Value resolved by the transaction/connection callback.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function readJoined(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantSql: string, bindings: unknown[]) {
return driver.transaction(principal, async connection => {
const result = await connection.execute(trustedTenantSql, bindings);
return result.rows ?? [];
});
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable acknowledgement contract for verified-context audit events.

Implementations must acknowledge durable storage; tenant/actor come from verified runtime context.

Imports: @alneas/eaos-server/platform.

interface AuditSink<T> {
append(event: Readonly<T>): Promise<void>;
}
Name Type Required Description
append Promise<void> Yes Persist the immutable event and resolve only when durable; reject when evidence cannot be recorded.

Type declaration; no runtime value.

  • T: Immutable verified-context event payload appended by the host.

PluginLifecycle for canonical integration usage.

Persist the immutable event and resolve only when durable; reject when evidence cannot be recorded.

Parameters:

  • event: Immutable event with tenant/actor derived from verified runtime context; exclude secrets.

Returns: Resolves without a value only after durable audit acknowledgement.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { AuditSink } from '@alneas/eaos-server/platform';
export async function audit(sink: AuditSink<{ action: string; tenantId: string; actorId: string }>, tenantId: string, actorId: string) {
await sink.append({ action: "example.reviewed", tenantId, actorId });
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Authentication configuration for createAuthMiddleware.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/auth.

interface AuthMiddlewareOptions {
verifier?: AuthSessionVerifier;
skipPaths?: string[];
}
Name Type Required Description
verifier AuthSessionVerifier No Host verifier; omission allows all requests through without establishing identity.
skipPaths string[] No Case-sensitive path prefixes exempt from verification; defaults to /health, /metrics, and /api/health. An empty array disables these exemptions.

Type declaration; no runtime value.

Host verifier; omission allows all requests through without establishing identity.

Case-sensitive path prefixes exempt from verification; defaults to /health, /metrics, and /api/health. An empty array disables these exemptions.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host authentication adapters used by createAuthMiddleware.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/auth.

interface AuthSessionVerifier {
verifySession(authHeader?: string, cookieHeader?: string): Promise<{
valid: boolean;
userId?: string;
email?: string;
tenantId?: string;
isSuperAdmin?: boolean;
pendingApproval?: boolean;
pendingId?: string;
user?: EaosUser;
}>;
verifyApiKey?(token: string): Promise<{
valid: boolean;
tenantId?: string;
userId?: string;
}> | {
valid: boolean;
tenantId?: string;
userId?: string;
};
}
Name Type Required Description
verifySession Promise<{ valid: boolean; userId?: string; email?: string; tenantId?: string; isSuperAdmin?: boolean; pendingApproval?: boolean; pendingId?: string; user?: EaosUser; }> Yes Verifies a session before the optional API key fallback.
verifyApiKey Promise<{ valid: boolean; tenantId?: string; userId?: string; }> | { valid: boolean; tenantId?: string; userId?: string; } No Verifies a nonempty credential after session verification fails.

Type declaration; no runtime value.

Results must come from verified credentials and trusted membership data; this middleware does not independently validate claims.

Verifies a session before the optional API key fallback.

Parameters:

  • authHeader: Raw Authorization header, or undefined if absent.
  • cookieHeader: Raw Cookie header, or undefined if absent.

Returns: Session validity and trusted optional identity claims. pendingApproval takes priority over valid and produces 403.

Rejections propagate through request handling.

Example:

import type { AuthSessionVerifier } from "@alneas/eaos-server";
export async function inspectSession(verifier: AuthSessionVerifier, request: Request) {
// The host verifier checks real credentials; a header alone is not trusted.
const result = await verifier.verifySession(
request.headers.get("Authorization") ?? undefined,
request.headers.get("Cookie") ?? undefined,
);
return { valid: result.valid, pendingApproval: result.pendingApproval === true };
}

True only after successful trusted credential verification.

Optional authenticated user ID copied to Hono context.

Optional verified email used when synthesizing a user object.

Optional verified tenant claim; session middleware can continue without it, so downstream tenant admission remains required.

Trusted platform authority enabling X-Tenant-Id selection and synthesized super_admin role.

When truthy, produces a 403 before session validity or API-key fallback is considered.

Optional approval reference included in a pending response.

Optional trusted user object copied unchanged; if omitted with userId, middleware synthesizes one.

Verifies a nonempty credential after session verification fails.

Parameters:

  • token: Authorization value with a leading Bearer prefix removed case-insensitively.

Returns: Validity and trusted identity claims; a valid result also needs tenantId to grant access.

Adapter errors propagate through request handling.

Example:

import type { AuthSessionVerifier } from "@alneas/eaos-server";
export async function inspectApiKey(verifier: AuthSessionVerifier, token: string) {
if (!verifier.verifyApiKey) throw new Error("Host API-key verification is unavailable");
// Supply the actual credential without logging or persisting it here.
const result = await verifier.verifyApiKey(token);
return result.valid && !!result.tenantId;
}

True for a verified API key; tenantId is additionally required to continue.

Required tenant claim for a successful middleware API-key fallback.

Optional authenticated key owner copied to userId; no user object is synthesized for this path.

True only when the host has verified the presented API key; middleware also requires a truthy tenantId before continuing.

Trusted tenant claim required for successful API-key fallback; middleware does not verify tenant membership independently.

Optional verified key-owner identity copied to request context; this fallback does not synthesize an EaosUser object.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-reported routing switch retaining the original database for recovery.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationCutover {
migrationId: string;
targetBackendId: string;
routingRevision: number;
cutoverAt: string;
sourceRetained: true;
}
Name Type Required Description
migrationId string Yes Plan migration identity.
targetBackendId string Yes Exact reviewed target backend.
routingRevision number Yes Nonnegative safe routing revision after cutover.
cutoverAt string Yes Parseable routing-switch timestamp.
sourceRetained true Yes Must be true; destructive source cleanup is outside this contract.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Plan migration identity.

Exact reviewed target backend.

Nonnegative safe routing revision after cutover.

Parseable routing-switch timestamp.

Must be true; destructive source cleanup is outside this contract.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-owned migration phases operating on real adapters and retained source storage.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationExecutor {
prepare(plan: BackendMigrationPlan): Promise<void>;
copy(plan: BackendMigrationPlan): Promise<void>;
verify(plan: BackendMigrationPlan): Promise<BackendMigrationVerificationReport>;
cutover(plan: BackendMigrationPlan, verification: BackendMigrationVerificationReport): Promise<BackendMigrationCutover>;
}
Name Type Required Description
prepare Promise<void> Yes Provision/adopt the reviewed target and establish quiescence without deleting source data.
copy Promise<void> Yes Copy the scoped tenant/plugin data into the target and retain source state.
verify Promise<BackendMigrationVerificationReport> Yes Produce nonempty exhaustive host match evidence for the plan’s scope.
cutover Promise<BackendMigrationCutover> Yes Switch routing only after valid verification, retaining source and returning a cutover receipt.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Provision/adopt the reviewed target and establish quiescence without deleting source data.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.

Returns: Resolves without a value after target preparation and required quiescence.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { BackendMigrationExecutor, BackendMigrationPlan } from '@alneas/eaos-server/lifecycle-engine';
export async function prepareReviewed(executor: BackendMigrationExecutor, plan: BackendMigrationPlan) {
// The host approves exact targets and serializes migration writers.
await executor.prepare(plan);
}

Copy the scoped tenant/plugin data into the target and retain source state.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.

Returns: Resolves without a value after the scoped copy completes, with source retained.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { BackendMigrationExecutor, BackendMigrationPlan } from '@alneas/eaos-server/lifecycle-engine';
export async function copyReviewed(executor: BackendMigrationExecutor, plan: BackendMigrationPlan) {
// The host approves exact targets and serializes migration writers.
await executor.copy(plan);
}

Produce nonempty exhaustive host match evidence for the plan’s scope.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.

Returns: The host verification report; caller must check it against the reviewed plan.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { BackendMigrationExecutor, BackendMigrationPlan } from '@alneas/eaos-server/lifecycle-engine';
export async function verifyReviewed(executor: BackendMigrationExecutor, plan: BackendMigrationPlan) {
// The host approves exact targets and serializes migration writers.
return executor.verify(plan);
}

Switch routing only after valid verification, retaining source and returning a cutover receipt.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.
  • verification: Matching passed host verification report; establish complete copy coverage before cutover.

Returns: A source-retaining routing cutover receipt after accepted verification.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { BackendMigrationExecutor, BackendMigrationPlan, BackendMigrationVerificationReport } from '@alneas/eaos-server/lifecycle-engine';
export async function cutoverReviewed(executor: BackendMigrationExecutor, plan: BackendMigrationPlan, verification: BackendMigrationVerificationReport) {
// Supply current, successful evidence for this exact reviewed plan.
return executor.cutover(plan, verification);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Deterministic five-phase non-destructive data migration plan.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationPlan {
format: 1;
id: string;
request: BackendMigrationRequest;
phases: readonly [
'prepare',
'copy',
'verify',
'cutover',
'retain-source'
];
requiresQuiesce: true;
retainSourceData: true;
destructiveOperations: false;
}
Name Type Required Description
format 1 Yes Plan discriminator; currently 1.
id string Yes Canonical digest of the normalized request and phase/safety flags.
request BackendMigrationRequest Yes Cloned request with sorted plugin and explicit tenant IDs.
phases readonly [ 'prepare', 'copy', 'verify', 'cutover', 'retain-source' ] Yes Ordered prepare/copy/verify/cutover/retain-source execution phases.
requiresQuiesce true Yes Always true; the host must drain affected execution before switching.
retainSourceData true Yes Always true; source data must remain available.
destructiveOperations false Yes Always false; dropping source data is outside this plan.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Plan discriminator; currently 1.

Canonical digest of the normalized request and phase/safety flags.

Cloned request with sorted plugin and explicit tenant IDs.

Ordered prepare/copy/verify/cutover/retain-source execution phases.

Always true; the host must drain affected execution before switching.

Always true; source data must remain available.

Always false; dropping source data is outside this plan.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Operator-reviewed source/target database move with bounded scope and reason.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationRequest {
migrationId: string;
source: BackendTarget;
target: BackendTarget;
scope: BackendMigrationScope;
pluginIds: readonly string[];
requestedAt: string;
reason: string;
}
Name Type Required Description
migrationId string Yes Nonblank stable migration identity, up to 256 characters.
source BackendTarget Yes Existing backend whose data remains retained.
target BackendTarget Yes Different backend and physical database identity.
scope BackendMigrationScope Yes All tenants or nonempty unique explicit tenant IDs; dedicated endpoints require their tenant in explicit scope.
pluginIds readonly string[] Yes Nonempty unique registered-style feature IDs covered by the move.
requestedAt string Yes Parseable request timestamp.
reason string Yes Nonblank reviewed operator reason, at most 1024 characters.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Nonblank stable migration identity, up to 256 characters.

Existing backend whose data remains retained.

Different backend and physical database identity.

All tenants or nonempty unique explicit tenant IDs; dedicated endpoints require their tenant in explicit scope.

Nonempty unique registered-style feature IDs covered by the move.

Parseable request timestamp.

Nonblank reviewed operator reason, at most 1024 characters.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Explicit complete fleet or nonempty concrete tenant selection for a reviewed data move.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

type BackendMigrationScope = {
kind: 'all-tenants';
} | {
kind: 'tenants';
tenantIds: readonly string[];
};
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Scope discriminator: all-tenants includes the fleet; tenants names a concrete bounded selection.

Scope discriminator: all-tenants includes the fleet; tenants names a concrete bounded selection.

Nonempty distinct concrete tenant IDs; dedicated endpoint tenants must be included.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-reported match for one tenant/plugin copy at observed revisions.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationVerification {
tenantId: string;
pluginId: string;
sourceRevision: number;
targetRevision: number;
matched: boolean;
}
Name Type Required Description
tenantId string Yes Concrete verified tenant covered by the plan.
pluginId string Yes Planned feature whose records were compared.
sourceRevision number Yes Nonnegative safe revision observed at source.
targetRevision number Yes Nonnegative safe revision observed at target; not required to numerically equal source.
matched boolean Yes True only when the host comparison passed; validator does not perform the comparison.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Concrete verified tenant covered by the plan.

Planned feature whose records were compared.

Nonnegative safe revision observed at source.

Nonnegative safe revision observed at target; not required to numerically equal source.

True only when the host comparison passed; validator does not perform the comparison.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

[INTERFACE] BackendMigrationVerificationReport

Section titled “[INTERFACE] BackendMigrationVerificationReport”

Host verification evidence bound to a reviewed source/target migration.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

interface BackendMigrationVerificationReport {
migrationId: string;
sourceBackendId: string;
targetBackendId: string;
checkedAt: string;
records: readonly BackendMigrationVerification[];
passed: boolean;
}
Name Type Required Description
migrationId string Yes Plan request migration identity.
sourceBackendId string Yes Exact source backend identity.
targetBackendId string Yes Exact target backend identity.
checkedAt string Yes Parseable verification timestamp.
records readonly BackendMigrationVerification[] Yes Nonempty matched in-scope record reports; host must establish exhaustive coverage.
passed boolean Yes Host declaration that verification passed; must be true for acceptance.

Type declaration; no runtime value.

planBackendMigration for canonical integration usage.

Plan request migration identity.

Exact source backend identity.

Exact target backend identity.

Parseable verification timestamp.

Nonempty matched in-scope record reports; host must establish exhaustive coverage.

Host declaration that verification passed; must be true for acceptance.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Opaque physical database placement and shared/dedicated tenant scope.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/lifecycle-engine.

interface BackendTarget {
id: string;
databaseId: string;
dialect: Dialect;
mode: 'shared' | 'dedicated';
tenantId?: string;
}
Name Type Required Description
id string Yes Stable execution backend ID; lifecycle plans reject identity changes under an existing ID.
databaseId string Yes Opaque physical database identity shared by aliases of the same database; never a DSN.
dialect Dialect Yes SQL dialect required by this database and migration history.
mode 'shared' | 'dedicated' Yes Shared permits tenant isolation within one database; dedicated binds one tenant.
tenantId string No Required concrete tenant for dedicated mode and forbidden for shared mode.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Stable execution backend ID; lifecycle plans reject identity changes under an existing ID.

Opaque physical database identity shared by aliases of the same database; never a DSN.

SQL dialect required by this database and migration history.

Shared permits tenant isolation within one database; dedicated binds one tenant.

Required concrete tenant for dedicated mode and forbidden for shared mode.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified browser identity and membership serialized by createBrowserSessionRouter.

Imports: @alneas/eaos-server/browser-auth.

interface BrowserSession {
userId: string;
tenantId: string;
roles: string[];
enabledModules: string[];
}
Name Type Required Description
userId string Yes Nonblank authenticated identity ID.
tenantId string Yes Nonblank selected authorized tenant ID.
roles string[] Yes Verified nonblank role names; empty arrays are accepted.
enabledModules string[] Yes Verified nonblank module entitlement names; empty arrays are accepted.

Type declaration; no runtime value.

Nonblank authenticated identity ID.

Nonblank selected authorized tenant ID.

Verified nonblank role names; empty arrays are accepted.

Verified nonblank module entitlement names; empty arrays are accepted.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Builds systemd-run arguments for transient process resource and filesystem restrictions.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

declare function buildSystemdRunArgs(command: string, args: readonly string[], policy: AgentRuntimeResourcePolicy, cwd: string | undefined, unit: string): string[];
Name Type Required Description
command string Yes Trusted executable passed after the systemd option terminator.
args readonly string[] Yes Executable arguments, passed unchanged without a shell.
policy AgentRuntimeResourcePolicy Yes Already validated resource policy; this helper does not validate it.
cwd string | undefined Yes Working directory, resolved absolutely; absent/empty uses process.cwd().
unit string Yes Host-selected transient unit name, used for later stop requests.

string[]

A new argument array, using –user for a nonroot host user and rounding runtime milliseconds upward to at least one second.

Requires a host with systemd-run and appropriate service-manager permissions when executed. This array does not implement network allowlisting, workspace capacity, or a concurrency scheduler; those policy fields require host enforcement.

import { defaultRuntimePlacementPolicy } from "@alneas/eaos-core";
import { buildSystemdRunArgs } from "@alneas/eaos-server/agentic/executor";
const args = buildSystemdRunArgs("agent-runtime", ["--version"], defaultRuntimePlacementPolicy().ai.agentRuntime, undefined, "example-agent");
console.log(args.includes("--wait")); // true

Per-fetch storage controls for MemoryCacheManager.getOrSet.

Imports: @alneas/eaos-server/cache.

interface CacheOptions {
ttlMs?: number;
tags?: string[];
bypass?: boolean;
}
Name Type Required Description
ttlMs number No Retention in milliseconds; finite and nonnegative. Zero disables storing; omission uses the manager default.
tags string[] No Tags attached to a newly stored entry for invalidation; defaults to none.
bypass boolean No Fetch even when a cached value exists; successful fetches may still populate the cache.

Type declaration; no runtime value.

Retention in milliseconds; finite and nonnegative. Zero disables storing; omission uses the manager default.

Tags attached to a newly stored entry for invalidation; defaults to none.

Fetch even when a cached value exists; successful fetches may still populate the cache.

Default: false.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified identity partition used by MemoryCacheManager.forScope.

Imports: @alneas/eaos-server/cache.

interface CacheScope {
tenantId: string;
pluginId: string;
userId: string;
permissionVersion?: string;
}
Name Type Required Description
tenantId string Yes Nonblank authenticated tenant ID.
pluginId string Yes Nonblank trusted plugin ID.
userId string Yes Nonblank authenticated user ID.
permissionVersion string No Permission revision included in the key partition; defaults to an empty string.

Type declaration; no runtime value.

Nonblank authenticated tenant ID.

Nonblank trusted plugin ID.

Nonblank authenticated user ID.

Permission revision included in the key partition; defaults to an empty string.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Marks an owned unstarted job cancelled in the caller’s atomic session.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

declare function cancelAgentJob(tx: AtomicSession, principal: PluginPrincipal, jobId: string, now?: Date): Promise<AgentJobRecord<ServerAgentTaskRequest>>;
Name Type Required Description
tx AtomicSession Yes Authorized atomic session; caller commits/rolls back.
principal PluginPrincipal Yes Verified tenant/user who owns the job.
jobId string Yes Stored queue job identifier.
now Date No Cancellation timestamp; defaults to a fresh Date.

Promise<AgentJobRecord<ServerAgentTaskRequest>>

A cloned cancelled job, unchanged when already cancelled.

Running leases cannot be interrupted by this edit. This function performs no external runtime cancellation, approval-ticket revocation, or live admission callback.

Missing/foreign job, request integrity mismatch, status other than queued/retryable/waiting_approval/cancelled, or transaction/clock errors.

import { cancelAgentJob } from "@alneas/eaos-server/agentic/agent-jobs";
import type { AtomicSession } from "@alneas/eaos-server/plugin-data/atomic";
import type { PluginPrincipal } from "@alneas/eaos-server/plugin-data";
export async function cancel(tx: AtomicSession, principal: PluginPrincipal, jobId: string) { return cancelAgentJob(tx, principal, jobId); }

Serializes JSON-compatible lifecycle values with recursively sorted object keys.

Imports: @alneas/eaos-server/lifecycle-engine.

declare function canonical(value: unknown): string;
Name Type Required Description
value unknown Yes JSON-serializable primitives, arrays or plain/null-prototype objects; avoid cycles and nonfinite numbers.

string

Deterministic JSON text; array order is preserved.

Uses JSON.stringify primitive semantics, including null for nonfinite numbers. It does not accept undefined/function/symbol values or class instances. Cyclic graphs are unsupported.

Error for unsupported values/prototypes, JSON serialization failure or recursive cycles.

import { canonical } from '@alneas/eaos-server/lifecycle-engine';
const serialized = canonical({ b: [2, 1], a: true });

Trusted Worker D1 binding supplied by the host runtime.

Imports: @alneas/eaos-server/plugin-data.

interface CloudflareD1Binding {
prepare(query: string): CloudflareD1PreparedStatement;
}
Name Type Required Description
prepare CloudflareD1PreparedStatement Yes Prepares trusted parameterized SQL on the installed Worker D1 binding.

Type declaration; no runtime value.

createCloudflareD1Driver for canonical host integration.

Prepares trusted parameterized SQL on the installed Worker D1 binding.

Parameters:

  • query: Trusted SQL text; caller must bind tenant predicates.

Returns: A statement exposing bind/all/run.

Provider preparation errors throw synchronously.

Example:

import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';
export async function tenantProjection(db: CloudflareD1Binding, tenantId: string) {
const statement = db.prepare("SELECT ? AS tenant_id");
return (await statement.bind(tenantId).all()).results ?? [];
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Explicit Worker or HTTP transport configuration for the server-side D1 record driver.

Imports: @alneas/eaos-server/plugin-data.

interface CloudflareD1DriverOptions {
binding?: CloudflareD1Binding;
accountId?: string;
databaseId?: string;
apiToken?: string;
fetch?: typeof globalThis.fetch;
apiBaseUrl?: string;
autoBootstrapTable?: string;
}
Name Type Required Description
binding CloudflareD1Binding No Optional trusted Worker D1 binding; takes precedence over HTTP credentials when valid. Direct Cloudflare Workers D1 binding (env.DB), when running inside a Worker.
accountId string No Cloudflare account identity required by HTTP mode. Cloudflare Account ID for remote D1 HTTP API access (e.g. from OCI server or CLI).
databaseId string No Cloudflare D1 database identity required by HTTP mode. Cloudflare D1 Database UUID for remote D1 HTTP API access.
apiToken string No Sensitive host API token required by HTTP mode; never expose to browser entries or docs examples. Cloudflare API Token with D1:Edit permission for remote D1 HTTP API access.
fetch typeof globalThis.fetch No Optional trusted fetch implementation; defaults to globalThis.fetch. Optional custom fetch implementation for D1 HTTP API calls.
apiBaseUrl string No Trusted HTTP API base; defaults to https://api.cloudflare.com/client/v4. Optional Cloudflare API base URL override (defaults to https://api.cloudflare.com/client/v4).
autoBootstrapTable string No Optional trusted table name; when supplied the first query runs CREATE TABLE IF NOT EXISTS. Omit when schema lifecycle is independently managed. Optional table name (e.g. 'eaos_customer_records') to auto-create via CREATE TABLE IF NOT EXISTS on first query.

Type declaration; no runtime value.

createCloudflareD1Driver for canonical host integration.

Optional trusted Worker D1 binding; takes precedence over HTTP credentials when valid.

Direct Cloudflare Workers D1 binding (env.DB), when running inside a Worker.

Cloudflare account identity required by HTTP mode.

Cloudflare Account ID for remote D1 HTTP API access (e.g. from OCI server or CLI).

Cloudflare D1 database identity required by HTTP mode.

Cloudflare D1 Database UUID for remote D1 HTTP API access.

Sensitive host API token required by HTTP mode; never expose to browser entries or docs examples.

Cloudflare API Token with D1:Edit permission for remote D1 HTTP API access.

Optional trusted fetch implementation; defaults to globalThis.fetch.

Optional custom fetch implementation for D1 HTTP API calls.

Trusted HTTP API base; defaults to https://api.cloudflare.com/client/v4.

Optional Cloudflare API base URL override (defaults to https://api.cloudflare.com/client/v4).

Optional trusted table name; when supplied the first query runs CREATE TABLE IF NOT EXISTS. Omit when schema lifecycle is independently managed.

Optional table name (e.g. 'eaos_customer_records') to auto-create via CREATE TABLE IF NOT EXISTS on first query.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Structural subset of the D1 prepared-statement API used by the record adapter.

Imports: @alneas/eaos-server/plugin-data.

interface CloudflareD1PreparedStatement {
bind(...values: unknown[]): CloudflareD1PreparedStatement;
all<T = Record<string, unknown>>(): Promise<{
results?: T[];
meta?: {
changes?: number;
};
}>;
run(): Promise<{
meta?: {
changes?: number;
};
}>;
}
Name Type Required Description
bind CloudflareD1PreparedStatement Yes Binds positional query values to a prepared Worker D1 statement.
all Promise<{ results?: T[]; meta?: { changes?: number; }; }> Yes Executes a prepared D1 read and resolves its structural query result.
run Promise<{ meta?: { changes?: number; }; }> Yes Executes a prepared D1 write and resolves provider change metadata.

Type declaration; no runtime value.

createCloudflareD1Driver for canonical host integration.

Binds positional query values to a prepared Worker D1 statement.

Parameters:

  • values: Positional values in SQL placeholder order.

Returns: The bound prepared statement used for all/run.

Provider binding errors throw synchronously.

Example:

import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';
export async function readProjection(db: CloudflareD1Binding, tenantId: string) {
const statement = db.prepare("SELECT ? AS tenant_id").bind(tenantId);
return (await statement.all<{ tenant_id: string }>()).results ?? [];
}

Executes a prepared D1 read and resolves its structural query result.

Returns: Optional typed results and provider change metadata.

  • T: Returned query row shape; defaults to a string-keyed unknown-value record.

Rejects provider query failures.

Example:

import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';
export async function projection(db: CloudflareD1Binding, tenantId: string) {
const result = await db.prepare("SELECT ? AS tenant_id").bind(tenantId).all<{ tenant_id: string }>();
return result.results ?? [];
}

Optional query rows with the caller-selected row shape.

Optional provider execution metadata.

Optional provider affected-row count; record driver normalizes absence to 0.

Executes a prepared D1 write and resolves provider change metadata.

Returns: Optional meta.changes affected-row metadata.

Rejects provider execution failures.

Example:

import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';
export async function executeReviewed(db: CloudflareD1Binding, trustedTenantDml: string, bindings: unknown[]) {
// Supply parameterized DML whose bindings include the authorized tenant.
const result = await db.prepare(trustedTenantDml).bind(...bindings).run();
return result.meta?.changes ?? 0;
}

Optional provider execution metadata.

Optional provider affected-row count; record driver normalizes absence to 0.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function collectSchemaMigrations(releases: readonly SchemaMigrationSource[], available?: readonly DataContract[]): PluginMigration[];
Name Type Required Description
releases readonly SchemaMigrationSource[] Yes See the upstream owning declaration.
available readonly DataContract[] No See the upstream owning declaration.

PluginMigration[]

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted executable, argument/environment builders, and limits for createCommandAgentExecutor.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

interface CommandAgentExecutorOptions {
command: string;
buildArgs: (request: ServerAgentTaskRequest) => readonly string[];
cwd?: string;
env?: (request: ServerAgentTaskRequest) => Record<string, string | undefined>;
includeProcessEnv?: boolean;
timeoutMs?: number;
maxOutputChars?: number;
sandbox?: CommandAgentSandboxOptions;
}
Name Type Required Description
command string Yes Host-configured executable. It is never taken from a task request.
buildArgs (request: ServerAgentTaskRequest) => readonly string[] Yes Called once per task with a structured clone; must return string arguments. Arguments are passed without a shell, and callback errors reject execution.
cwd string No Process working directory; omitted uses the host process directory. Under systemd this directory is also explicitly writable.
env (request: ServerAgentTaskRequest) => Record<string, string | undefined> No Per-task environment callback receiving a clone; its entries override framework EAOS variables. Defaults to no additional variables.
includeProcessEnv boolean No Inherit host process environment before framework/custom variables.
timeoutMs number No Default task timeout in milliseconds, safe integer 1–3600000; task.timeoutMs overrides it.
maxOutputChars number No Combined stdout/stderr string-length ceiling, safe integer 1–10000000.
sandbox CommandAgentSandboxOptions No Sandbox selection; defaults to auto and a validated task/framework policy. Direct mode does not apply systemd resource/filesystem restrictions.

Type declaration; no runtime value.

Host-configured executable. It is never taken from a task request.

Called once per task with a structured clone; must return string arguments. Arguments are passed without a shell, and callback errors reject execution.

Process working directory; omitted uses the host process directory. Under systemd this directory is also explicitly writable.

Per-task environment callback receiving a clone; its entries override framework EAOS variables. Defaults to no additional variables.

Inherit host process environment before framework/custom variables.

Default: false.

Default task timeout in milliseconds, safe integer 1–3600000; task.timeoutMs overrides it.

Default: 60000.

Combined stdout/stderr string-length ceiling, safe integer 1–10000000.

Default: 1000000.

Sandbox selection; defaults to auto and a validated task/framework policy. Direct mode does not apply systemd resource/filesystem restrictions.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Chooses Linux systemd-run, direct spawning, or automatic platform selection.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

type CommandAgentSandboxMode = 'auto' | 'systemd' | 'direct';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

createCommandAgentExecutor.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host sandbox selection for createCommandAgentExecutor.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

interface CommandAgentSandboxOptions {
mode?: CommandAgentSandboxMode;
policy?: AgentRuntimeResourcePolicy;
}
Name Type Required Description
mode CommandAgentSandboxMode No auto uses transient systemd on Linux and direct execution on local development hosts.
policy AgentRuntimeResourcePolicy No Resource policy is framework-owned by default; consumers may only tighten it in a host adapter.

Type declaration; no runtime value.

auto uses transient systemd on Linux and direct execution on local development hosts.

Resource policy is framework-owned by default; consumers may only tighten it in a host adapter.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Private mutable reducer context supplied after command and resource validation.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/commands.

interface CommandContext<T> {
principal: PluginPrincipal;
operation: string;
args: Record<string, any>;
state: T;
at: string;
recordId: string;
}
Name Type Required Description
principal PluginPrincipal Yes Cloned verified principal for this admitted reducer invocation.
operation string Yes Declared operation being executed.
args Record<string, any> Yes Cloned schema-validated operation input.
state T Yes Private mutable aggregate snapshot; persist through the owning service rather than writing the store directly.
at string Yes Trusted UTC ISO operation timestamp.
recordId string Yes Logical aggregate ID resolved for this command.

Type declaration; no runtime value.

  • T: Private mutable aggregate state supplied to the reducer.

RecordCommandService for canonical host integration.

Cloned verified principal for this admitted reducer invocation.

Declared operation being executed.

Cloned schema-validated operation input.

Private mutable aggregate snapshot; persist through the owning service rather than writing the store directly.

Trusted UTC ISO operation timestamp.

Logical aggregate ID resolved for this command.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host persistence, transaction and live authorization ports for aggregate command execution.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/commands.

interface CommandHost<T extends CommandState> {
store?: PluginRecordStore<T>;
transaction?<R>(principal: PluginPrincipal, work: (store: PluginRecordStore<T>) => Promise<R>): Promise<R>;
authorize(p: PluginPrincipal, operation: string, input: unknown, current?: Readonly<T>): Promise<boolean>;
now?: () => Date;
}
Name Type Required Description
store PluginRecordStore<T> No Optional durable tenant record store; used when transaction is absent.
transaction Promise<R> No Runs aggregate reads, CAS and final permission checks through one real connection-bound transaction. Trusted connection-bound store; all reads, CAS and final authorization share one transaction. May expose an unstored projection at revision 0; the first write creates revision 1.
authorize Promise<boolean> Yes Checks current lifecycle and permission for the operation and complete returned aggregate. Must check live activation and access to the entire returned aggregate, including referenced resources.
now () => Date No Optional trusted clock used for operation history timestamps; defaults to new Date().

Type declaration; no runtime value.

  • T: Tenant-owned aggregate state required by the store and reducer transaction.

RecordCommandService for canonical host integration.

Optional durable tenant record store; used when transaction is absent.

Runs aggregate reads, CAS and final permission checks through one real connection-bound transaction.

Trusted connection-bound store; all reads, CAS and final authorization share one transaction. May expose an unstored projection at revision 0; the first write creates revision 1.

Parameters:

  • principal: Verified current principal owning the transaction.
  • work: Async service work receiving the joined record store; do not retain that store after completion.

Returns: The callback result after commit; rejection rolls back joined writes.

  • R: Value resolved by the transaction/connection callback.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { CommandHost, CommandState, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function readAggregate(host: CommandHost<CommandState>, principal: PluginPrincipal, recordId: string) {
if (!host.transaction) throw new Error("Joined transaction port required");
return host.transaction(principal, store => store.read(principal.tenantId, recordId));
}

Checks current lifecycle and permission for the operation and complete returned aggregate.

Must check live activation and access to the entire returned aggregate, including referenced resources.

Parameters:

  • p: Verified principal copied for this check.
  • operation: Declared operation name.
  • input: Schema input (initial admission occurs before schema validation).
  • current: Optional copied current aggregate including all referenced-resource access.

Returns: Exactly true to admit; false denies with PluginError 403.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { CommandHost, CommandState, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function canOperate(host: CommandHost<CommandState>, principal: PluginPrincipal, operation: string, input: unknown, current: Readonly<CommandState>) {
return await host.authorize(principal, operation, input, current) === true;
}

Optional trusted clock used for operation history timestamps; defaults to new Date().

Returns: A valid Date whose toISOString value becomes the operation timestamp.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Tenant/record/revision envelope returned after an admitted aggregate operation.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/commands.

interface CommandResponse<T> {
tenantId: string;
recordId: string;
revision: number;
data: T;
}
Name Type Required Description
tenantId string Yes Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.
recordId string Yes Logical aggregate ID selected by the trusted definition.
revision number Yes Observed aggregate revision; new or unstored reads may use 0, while accepted writes advance it by one.
data T Yes Cloned reducer result, or the resulting aggregate state when the reducer returns undefined.

Type declaration; no runtime value.

  • T: Cloned reducer response data or resulting state payload.

RecordCommandService for canonical host integration.

Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.

Logical aggregate ID selected by the trusted definition.

Observed aggregate revision; new or unstored reads may use 0, while accepted writes advance it by one.

Cloned reducer result, or the resulting aggregate state when the reducer returns undefined.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Minimum tenant-owned aggregate state with an append-only in-record operation history.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/commands.

interface CommandState {
tenantId: string;
history: {
operation: string;
actorId: string;
at: string;
}[];
}
Name Type Required Description
tenantId string Yes Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.
history { operation: string; actorId: string; at: string; }[] Yes In-record operation/actor/ISO-time history appended for accepted writes; maximum history length is enforced by the service.

Type declaration; no runtime value.

RecordCommandService for canonical host integration.

Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.

In-record operation/actor/ISO-time history appended for accepted writes; maximum history length is enforced by the service.

Declared accepted write operation appended by RecordCommandService.

Verified user ID whose accepted write created this history entry.

Trusted UTC ISO operation timestamp.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Validated definition and configured graph produced by compileWorkflowDefinition.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-compiler.

interface CompiledWorkflow {
definition: WorkflowDefinition;
graph: AgentGraphEngine;
}
Name Type Required Description
definition WorkflowDefinition Yes Validated serializable workflow definition returned by core validation.
graph AgentGraphEngine Yes Newly assembled graph; compilation performs no workflow execution.

Type declaration; no runtime value.

Validated serializable workflow definition returned by core validation.

Newly assembled graph; compilation performs no workflow execution.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Validates a serializable workflow and resolves its catalog nodes into a LangGraph-backed runtime.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-compiler.

declare function compileWorkflowDefinition(input: unknown, options: WorkflowCompilerOptions): Promise<CompiledWorkflow>;
Name Type Required Description
input unknown Yes Unknown serialized definition accepted by core validateWorkflowDefinition.
options WorkflowCompilerOptions Yes Required catalog, optional saver, and live resume authorizer.

Promise<CompiledWorkflow>

Validated definition and newly configured graph with node retries, conditional routes, approval metadata, and subgraph mappings.

Host resolvers may have setup side effects before a later node fails; no rollback/disposal protocol is provided. Node timeouts race the handler but do not cancel underlying work. Tool scopes are passed in workflow context; handlers must enforce them. Runtime conditional routing picks the first matching condition or first default/unconditional edge and throws if none match. Durable persistence, live authorization, and safe side-effect retry contracts remain host-owned.

Rejects definition validation, missing catalog/types/subgraph resolvers, invalid resolved handlers/graphs, or propagated resolver/graph construction errors.

import { compileWorkflowDefinition, type WorkflowCompilerOptions } from "@alneas/eaos-server/agentic/workflow-compiler";
export async function compile(input: unknown, options: WorkflowCompilerOptions) {
return compileWorkflowDefinition(input, options);
}

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db.

interface ConnectionStats {
activeConnections: number;
poolSize: number;
driver: DbDriverType;
}
Name Type Required Description
activeConnections number Yes See the upstream owning declaration.
poolSize number Yes See the upstream owning declaration.
driver DbDriverType Yes See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Provides explicit baseline CREATE TABLE statements for the shared lifecycle ledger in each dialect.

Imports: @alneas/eaos-server/sql-lifecycle.

declare const controlSchemaSql: Record<Dialect, string[]>;
Name Type Required Description
— — — No call parameters.

Declared constant value.

No SQL executes on import or construction. Review and apply the selected baseline separately before initialize.

SqlLifecycleStore for host driver requirements.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Privileged primary SQL connection used by SqlLifecycleStore; it is not a tenant data adapter.

Imports: @alneas/eaos-server/sql-lifecycle.

interface ControlSqlDriver {
dialect: Dialect;
execute(sql: string, bindings: unknown[]): Promise<{
rows?: Record<string, unknown>[];
affectedRows?: number;
}>;
}
Name Type Required Description
dialect Dialect Yes SQL placeholder/schema dialect.
execute Promise<{ rows?: Record<string, unknown>[]; affectedRows?: number; }> Yes Outside an explicit withAtomicLock transaction, each write must commit before resolving. Reads must use the primary, never a lagging replica. Bind arrays are positional; Oracle payloads must be bound/read as CLOB strings. This is a privileged control DB connection, NOT a tenant data connection.

Type declaration; no runtime value.

SQL placeholder/schema dialect.

Outside an explicit withAtomicLock transaction, each write must commit before resolving. Reads must use the primary, never a lagging replica. Bind arrays are positional; Oracle payloads must be bound/read as CLOB strings. This is a privileged control DB connection, NOT a tenant data connection.

Parameters:

  • sql: Statement supplied by the lifecycle store.
  • bindings: Positional values, using the selected dialect placeholders.

Returns: Optional rows and affectedRows; lock/update statements require affectedRows exactly reflecting the write count.

Driver/database failures reject the store operation.

Example:

import type { ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function probePrimaryControlConnection(driver: ControlSqlDriver) {
// Use a host-owned primary control connection, not a tenant adapter or replica.
const sql = driver.dialect === "oracle" ? "SELECT 1 AS ready FROM dual" : "SELECT 1 AS ready";
const result = await driver.execute(sql, []);
return result.rows ?? [];
}

Optional primary-database result rows for read statements; column names and CLOB decoding follow the connected SQL driver contract.

Optional exact write count; lifecycle lock/CAS/update paths require it and reject missing or unexpected counts rather than assuming success.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Creates a cloned, hashed queued job record without persisting or executing it.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

declare function createAgentJob(input: {
request: ServerAgentTaskRequest;
kind: string;
workflowInstanceId?: string;
correlationId?: string;
idempotencyKey?: string;
maxAttempts?: number;
now?: Date;
}): AgentJobRecord<ServerAgentTaskRequest>;
Name Type Required Description
input { request: ServerAgentTaskRequest; kind: string; workflowInstanceId?: string; correlationId?: string; idempotencyKey?: string; maxAttempts?: number; now?: Date; } Yes request supplies verified task identity; kind groups idempotency; workflowInstanceId is optional; correlationId defaults to request executionContext correlation then request.id; idempotencyKey defaults to executionContext key then request.id; maxAttempts defaults to 5; now defaults to the current Date.

AgentJobRecord<ServerAgentTaskRequest>

A new queued record with generated jobId, attempt zero, request hash, and matching available/created/updated timestamps.

Clone/hash/invalid Date failures; this factory does not independently validate every task or attempt field.

Host-verified task cloned into the durable job and hashed for idempotency integrity.

Queue kind used together with tenant and idempotencyKey to partition durable deduplication.

Optional companion workflow instance ID retained in the queued record.

Queue trace label; defaults to request.executionContext.correlationId, then request.id.

Durable deduplication identity; defaults to request.executionContext.idempotencyKey, then request.id.

Job attempt ceiling retained without validation here; defaults to 5 and is later combined with dispatcher policy.

Timestamp for availableAt, createdAt, and updatedAt; defaults to a fresh Date and must support toISOString.

import { createAgentJob } from "@alneas/eaos-server/agentic/agent-jobs";
import type { ServerAgentTaskRequest } from "@alneas/eaos-server/agentic/types";
export function queued(request: ServerAgentTaskRequest) { return createAgentJob({ request, kind: "workflow" }); }

Per-application host authorization, route, and health adapters for ErpEngine.createApp.

Imports: @alneas/eaos-server, @alneas/eaos-server/engine.

interface CreateAppOptions {
entitlements?: PluginEntitlementRuntime;
resolveEntitlementPrincipal?: EntitlementPrincipalResolver;
lifecycle?: LifecycleRuntime;
requireModule?: (moduleId: string) => any;
verifier?: AuthSessionVerifier;
enableModuleGuard?: boolean;
pluginOptions?: Record<string, unknown>;
mcp?: McpRouterOptions & {
prefix?: string;
};
customRoutes?: Array<{
prefix: string;
router: Hono<any>;
}>;
health?: Omit<HealthRouterOptions, 'appName'>;
}
Name Type Required Description
entitlements PluginEntitlementRuntime No Optional shared runtime for declared commercial/usage entitlement admission.
resolveEntitlementPrincipal EntitlementPrincipalResolver No Optional verified principal resolver; defaults to resolveEngineEntitlementPrincipal.
lifecycle LifecycleRuntime No Optional current lifecycle/tenant/backend admission for plugin routes and MCP tools.
requireModule (moduleId: string) => any No Optional module middleware factory called at composition for each plugin/extension requirement; defaults to createModuleGuard.
verifier AuthSessionVerifier No Optional authentication verifier overriding config.auth.verifier.
enableModuleGuard boolean No Install module guards unless exactly false. Defaults to true.
pluginOptions Record<string, unknown> No Per-plugin dependencies passed to the route factory.
mcp McpRouterOptions & { prefix?: string; } No Optional MCP adapter configuration; prefix defaults to /api/mcp and shared entitlements take precedence.
customRoutes Array<{ prefix: string; router: Hono<any>; }> No Additional host routers mounted after plugin/MCP routes; no plugin-specific guard is automatically added.
health Omit<HealthRouterOptions, 'appName'> No Optional dependency readiness checks and clock; engine appName is supplied automatically.

Type declaration; no runtime value.

Optional shared runtime for declared commercial/usage entitlement admission.

Optional verified principal resolver; defaults to resolveEngineEntitlementPrincipal.

Optional current lifecycle/tenant/backend admission for plugin routes and MCP tools.

Optional module middleware factory called at composition for each plugin/extension requirement; defaults to createModuleGuard.

Optional authentication verifier overriding config.auth.verifier.

Install module guards unless exactly false. Defaults to true.

Per-plugin dependencies passed to the route factory.

Optional MCP adapter configuration; prefix defaults to /api/mcp and shared entitlements take precedence.

Optional mount path for the shared MCP router; defaults to /api/mcp when the engine composes routes.

Additional host routers mounted after plugin/MCP routes; no plugin-specific guard is automatically added.

Host-selected mount prefix passed directly to Hono route composition; this entry receives no automatic plugin/module-specific guard.

Trusted Hono child router; host composition must install its route-specific authorization before exposing handlers.

Optional dependency readiness checks and clock; engine appName is supplied automatically.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Creates a lease-checked agent queue over an existing tenant-scoped atomic repository.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

declare function createAtomicAgentJobStore(options: AtomicAgentJobStoreOptions): AgentJobStore;
Name Type Required Description
options AtomicAgentJobStoreOptions Yes Repository/principal plus clocks, leases, optional current-admission checks, and transactional result persistence.

AgentJobStore

Store operations validating tenant/request integrity and lease token before transitions. claim increments attempt and leases due queued/retryable jobs or sufficiently stale running jobs.

claim scans at most 100 pages of 100 rows and permits safe-integer limits 1–100. Running jobs recover only when leaseUntil is at least staleAfterMs before the claim clock. Transition timestamps use options.now, ignoring the interface-supplied now argument. No lease renewal or worker cancellation exists; stale execution can overlap a reclaimed attempt, so side effects need host idempotency. verifyCurrent runs around durable mutations when supplied. Transactional onCompleted runs before succeeded state persistence in the same session.

Synchronously for missing dependencies or lease/stale durations below 1000 ms/nonfinite. Operations reject integrity/tenant/lease/admission errors, invalid claim limits, bounded-scan exhaustion, or propagated repository/hook errors.

import { createAtomicAgentJobStore, type AtomicAgentJobStoreOptions } from "@alneas/eaos-server/agentic/agent-jobs";
export function jobStore(options: AtomicAgentJobStoreOptions) { return createAtomicAgentJobStore(options); }

Compose the existing OutboxDispatcher with the tenant-scoped atomic Outbox store.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

declare function createAtomicOutboxDispatcher(options: AtomicOutboxDispatcherOptions): OutboxDispatcher;
Name Type Required Description
options AtomicOutboxDispatcherOptions Yes Dispatcher handlers/time/retry settings plus the atomic repository and principal.

OutboxDispatcher

An OutboxDispatcher instance; construction alone does not start a worker loop.

Host scheduling and handler idempotency remain explicit; no parallel transport or global singleton is introduced.

Invalid store/dispatcher configuration throws; later dispatch rejects according to its host handlers and store.

import { createAtomicOutboxDispatcher } from '@alneas/eaos-server/plugin-data'
export function dispatcher(options: Parameters<typeof createAtomicOutboxDispatcher>[0]) { return createAtomicOutboxDispatcher(options) }

Bind durable Outbox claim/result transitions to one verified principal and atomic repository.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

declare function createAtomicOutboxStore(options: AtomicOutboxStoreOptions): OutboxStore;
Name Type Required Description
options AtomicOutboxStoreOptions Yes Repository/principal plus optional staleAfterMs (default 300000, minimum 1000) and clock.

OutboxStore

An OutboxStore using CAS claim tokens for publication/failure transitions.

Stale claims can be reclaimed, so external handlers must tolerate duplicate delivery. No global scheduler or external exactly-once guarantee is provided.

Invalid stale timeout throws; claims reject batch sizes outside 1–100, scope mismatches, nonadvancing pages or scan capacity above 30000; result writes reject changed claim tokens.

import { createAtomicOutboxStore } from '@alneas/eaos-server/plugin-data'
export function store(options: Parameters<typeof createAtomicOutboxStore>[0]) { return createAtomicOutboxStore(options) }

Adapt one active atomic session to the standard record-store boundary for exactly one tenant.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function createAtomicRecordStore<T>(session: AtomicSession, principal: PluginPrincipal): PluginRecordStore<T>;
Name Type Required Description
session AtomicSession Yes Live session obtained inside repository.run.
principal PluginPrincipal Yes Verified principal defining the only admitted tenant.

PluginRecordStore<T>

A read/list/listPage/create/replace store backed by that same session.

  • T: JSON payload shape retained by the adapted store.

Does not begin or commit a transaction and does not expose deletion. Replacement conflicts reject rather than returning false.

Malformed principals throw immediately; foreign tenant, invalid revision transitions or expired/CAS session failures reject operations.

import { createAtomicRecordStore, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'
export function readRecord<T>(repository: AtomicRepository, principal: PluginPrincipal, id: string) {
return repository.run(principal, session => createAtomicRecordStore<T>(session, principal).read(principal.tenantId, id))
}

Create tenant/namespace-scoped CAS sessions on a trusted transactional SQL driver.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function createAtomicRepository(table: string, driver: AtomicSqlDriver, options?: AtomicRepositoryOptions): AtomicRepository;
Name Type Required Description
table string Yes Trusted lowercase table identifier for envelope persistence.
driver AtomicSqlDriver Yes Driver that commits the callback result or rolls back all statements on rejection.
options AtomicRepositoryOptions No Optional namespace, payload policy and canonical document contracts.

AtomicRepository

Repository whose run callback receives a temporary session valid only until the callback settles.

Does not create tables. Driver transaction atomicity, connection cleanup and live authorization remain host-owned. Batch writes use the same transaction; session capabilities expire in finally. list supports limits 1–101; getMany preserves input order and missing nulls.

Rejects invalid table/driver/namespace/document bindings; operations reject expired sessions, invalid IDs/revisions/payloads, duplicate keys and CAS conflicts.

import { createAtomicRepository } from '@alneas/eaos-server/plugin-data'
export function repository(driver: Parameters<typeof createAtomicRepository>[1]) { return createAtomicRepository('example_records', driver) }

Bind workflow event append operations to the caller’s current atomic transaction.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

declare function createAtomicWorkflowEventSink(tx: AtomicSession, topicPrefix?: string): WorkflowEventSink;
Name Type Required Description
tx AtomicSession Yes Live session containing the same domain CAS operation.
topicPrefix string No Trusted nonempty topic prefix; defaults to workflow and admits letters/digits/underscore/dot/colon/slash/hyphen.

WorkflowEventSink

A WorkflowEventSink that enqueues copied envelopes in the existing Outbox.

The sink owns no commit boundary and performs no external transport; use it only while the parent transaction is active.

Invalid session/prefix throws at construction; appended event validation/idempotency/store failures reject.

import { createAtomicWorkflowEventSink, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'
import type { WorkflowEventEnvelope } from '@alneas/eaos-core'
export function appendWorkflow<T>(repository: AtomicRepository, principal: PluginPrincipal, event: WorkflowEventEnvelope<T>) {
return repository.run(principal, session => createAtomicWorkflowEventSink(session).append(event))
}

Resolves trusted session or API key claims into Hono context and rejects invalid credentials.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/auth.

declare function createAuthMiddleware(options?: AuthMiddlewareOptions): hono.MiddlewareHandler<EaosEnv, string, {}, Response>;
Name Type Required Description
options AuthMiddlewareOptions No Host verifier and excluded path prefixes; see {@link AuthMiddlewareOptions}.

hono.MiddlewareHandler<EaosEnv, string, {}, Response>

Middleware that continues exempt or authenticated requests, returns 403 for pending approval, and otherwise returns 401.

Requests with both userId and tenantId already in context bypass verification. Omitting a verifier also bypasses authentication. Only session results marked isSuperAdmin may select X-Tenant-Id; the host remains responsible for tenant existence and authorization. A synthesized user gets super_admin or user roles; API key fallback sets no user object.

Request execution propagates verifier and downstream middleware errors.

import { Hono } from "hono";
import type { EaosEnv } from "@alneas/eaos-core";
import { createAuthMiddleware, type AuthSessionVerifier } from "@alneas/eaos-server/middleware/auth";
export function authenticatedApp(verifier: AuthSessionVerifier) {
// Supply a host adapter that actually validates sessions and tenant claims.
const app = new Hono<EaosEnv>();
app.use("*", createAuthMiddleware({ verifier, skipPaths: [] }));
app.get("/identity", c => c.json({ userId: c.get("userId") }));
return app;
}

Exposes browser-safe provider configuration and verified session data with no-store response headers.

Imports: @alneas/eaos-server/browser-auth.

declare function createBrowserSessionRouter<T extends BrowserSession>(options: {
configuration: () => {
publicUrl: string;
provider: string;
returnTo?: string;
redirectOrigins: string[];
};
resolveSession: (context: Context) => Promise<T | null>;
tenantId?: string;
}): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
Name Type Required Description
options { configuration: () => { publicUrl: string; provider: string; returnTo?: string; redirectOrigins: string[]; }; resolveSession: (context: Context) => Promise<T | null>; tenantId?: string; } Yes configuration synchronously supplies publicUrl/provider/redirectOrigins and optional returnTo for GET /config; resolveSession receives Hono context for GET /session and resolves a verified session or null; optional tenantId restricts returned sessions to one tenant.

Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">

A router with GET /config and /session. Configuration failure returns 503; absent session returns 401, tenant mismatch returns 403, and resolver failures map status 401/403 or otherwise 503.

  • T: Host session shape extending required identity/membership fields; additional fields are serialized in full.

The host owns IdP settings and membership lookup. No identity creation, default roles, or token minting occurs. Configuration output whitelists fields, but session output serializes all T fields: do not place secrets in a session. Responses set Cache-Control: no-store and Vary: Cookie, Authorization, X-Tenant-Id.

Synchronous public IdP configuration callback evaluated on each /config request; failures become 503 and only explicitly selected fields are serialized.

Nonempty public identity-provider URL returned to the browser; the router does not validate its URL syntax.

Nonempty provider label returned to the browser.

Optional post-authentication return URL included only when truthy; host configuration must validate redirect policy.

options.configuration.result.redirectOrigins

Section titled “options.configuration.result.redirectOrigins”

Host redirect-origin list serialized to the browser; the router checks only that it is an array.

Per-request host verifier resolving a trusted session or null for 401; thrown statuses 401/403 are preserved and other failures become 503.

Optional dedicated-backend tenant restriction; a session selecting another tenant returns 403.

import type { Context } from "hono";
import { createBrowserSessionRouter, type BrowserSession } from "@alneas/eaos-server/browser-auth";
export function authRouter(resolveSession: (context: Context) => Promise<BrowserSession | null>) {
return createBrowserSessionRouter({
configuration: () => ({ publicUrl: "https://identity.example.com", provider: "kratos", redirectOrigins: ["https://app.example.com"] }),
resolveSession,
});
}

Create a SQLite-dialect record driver using a Worker D1 binding or the explicit Cloudflare HTTP query endpoint.

Imports: @alneas/eaos-server/plugin-data.

declare function createCloudflareD1Driver(options: CloudflareD1DriverOptions): RecordSqlDriver;
Name Type Required Description
options CloudflareD1DriverOptions Yes Trusted binding or complete account/database/token credentials; an available binding takes precedence over HTTP configuration.

RecordSqlDriver

A RecordSqlDriver whose execute method uses the selected D1 transport.

The execute tenantId is not an independent authorization boundary; SQL callers must bind tenant predicates. autoBootstrapTable optionally executes CREATE TABLE on the first query; omit it when schemas are managed separately. Credentials and custom fetch/base URL are trusted server configuration.

Rejects absent transport or invalid bootstrap table name; query/HTTP failures propagate and duplicate-key failures are normalized.

import { createCloudflareD1Driver } from '@alneas/eaos-server/plugin-data'
export function d1(options: Parameters<typeof createCloudflareD1Driver>[0]) { return createCloudflareD1Driver(options) }

Creates a shell-free executor for OpenCode, Codex, Goose or another trusted CLI. Authorization and approval happen before this adapter is called.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

declare function createCommandAgentExecutor(options: CommandAgentExecutorOptions): ServerAgentExecutor;
Name Type Required Description
options CommandAgentExecutorOptions Yes Trusted executable, argument/environment callbacks, output/timeout limits, and sandbox settings.

ServerAgentExecutor

A per-task async executor resolving stdout on exit code zero, including an empty string when no output was produced.

Requires Node child_process. auto selects systemd on Linux and direct execution elsewhere. No task concurrency limit is enforced here. stdin is ignored, stdout/stderr are bounded together, and stderr is excluded from successful output. On timeout/output/spawn failure the timer is cleared, SIGTERM is sent, and systemd stop is requested when managed; termination is not awaited and descendants may outlive direct-mode failure. Idempotency is only propagated through environment variables; host/runtime code must enforce safe retries.

Synchronously for invalid factory settings. Execution rejects callback/clone/policy errors and ServerAgentExecutionError for spawn, timeout, output-limit, or nonzero-exit failures.

import { createCommandAgentExecutor, type CommandAgentExecutorOptions } from "@alneas/eaos-server/agentic/executor";
export function hostExecutor(configuration: CommandAgentExecutorOptions) {
// The host provisions the executable and performs admission/approval first.
return createCommandAgentExecutor(configuration);
}

Route explicitly owned operations to their bounded service instances.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/composite.

declare function createCompositePluginService(services: Readonly<Record<string, PluginOperationService>>, operationOwners: Readonly<Record<string, string>>): PluginOperationService;
Name Type Required Description
services Readonly<Record<string, PluginOperationService>> Yes Trusted service instances keyed by owner name.
operationOwners Readonly<Record<string, string>> Yes Explicit operation-to-owner mapping copied at construction.

PluginOperationService

A principal-aware execute service forwarding to the declared owner.

Does not authenticate principals or add authorization/transactions; each owner service retains its actual boundaries.

Unknown declared owners throw at construction; unknown operations reject with PluginError 400 and owner errors propagate.

import { createCompositePluginService } from '@alneas/eaos-server/plugin-data'
export function composite(services: Parameters<typeof createCompositePluginService>[0]) { return createCompositePluginService(services, { list: 'records' }) }

Builds a newer single-migration contract release and hashes the exact historical migrations it replaces.

Final DDL comes from a schema compiler or an isolated database introspector, never concatenation.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/baseline.

declare function createDataContractBaseline(source: DataContract, version: string, sql: DataContract['migrations'][number]['sql']): DataContractBaseline;
Name Type Required Description
source DataContract Yes Valid source contract with nonempty database-scoped migration history.
version string Yes Valid semver strictly newer than source.version.
sql DataContract['migrations'][number]['sql'] Yes Compiler/introspector-generated complete baseline DDL covering exactly the original dialect set.

DataContractBaseline

Source/target contract snapshots, replacement migration checksums and integrity hash.

Read-only; the host must establish final DDL equivalence using a schema compiler or isolated introspector. SQL is not concatenated or executed here.

Error for nonnewer version, tenant-scoped/empty history, changed dialect set or invalid source/target contracts.

import { createDataContractBaseline, type DataContract } from '@alneas/eaos-server/lifecycle-engine';
export function reviewBaseline(source: DataContract, version: string, sql: DataContract['migrations'][number]['sql']) { return createDataContractBaseline(source, version, sql); }

Creates an uninitialized engine retaining the supplied host configuration.

Imports: @alneas/eaos-server, @alneas/eaos-server/engine.

declare function createErpEngine(config: EaosConfig): ErpEngine;
Name Type Required Description
config EaosConfig Yes Engine composition settings; see {@link EaosConfig}.

ErpEngine

A new engine; await initialize before createApp.

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
const app = engine.createApp();
console.log((await app.request("/health/live")).status);

Creates a Hono error handler that logs errors and renders a JSON 500 response.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/error-handler.

declare function createErrorHandler(options?: ErrorHandlerOptions): (err: Error, c: Context) => Promise<Response & hono.TypedResponse<{
stack?: string | undefined;
error: string;
}, 500, "json">>;
Name Type Required Description
options ErrorHandlerOptions No Logging and redaction settings; omitted settings use console.error and NODE_ENV.

(err: Error, c: Context) => Promise<Response & hono.TypedResponse<{ stack?: string \| undefined; error: string; }, 500, "json">>

An async handler resolving to a 500 response; production responses omit stacks and use “Internal Server Error”.

Nonproduction responses expose error messages and stacks. Choose production redaction explicitly for externally accessible services.

The returned handler rejects if the host logger throws.

import { Hono } from "hono";
import { createErrorHandler } from "@alneas/eaos-server/middleware/error-handler";
const app = new Hono();
app.onError(createErrorHandler({ isProduction: true }));
app.get("/example", () => { throw new Error("example failure"); });
console.log((await app.request("/example")).status); // 500

Creates public /health, /health/live, and /health/ready routes.

Imports: @alneas/eaos-server, @alneas/eaos-server/health.

declare function createHealthRouter(options: HealthRouterOptions): Hono;
Name Type Required Description
options HealthRouterOptions Yes Application label, readiness checks, and optional clock.

Hono

A new Hono router; liveness returns 200 and readiness returns 503 only for a not_ready report.

Check implementations and credentials remain host-owned. These routes install no authentication; mount them where public health status is appropriate. Checks run for every readiness request with no caching by this router.

If appName is missing, not a string, or blank. Request handling may reject if the supplied clock throws.

import { Hono } from "hono";
import { createHealthRouter } from "@alneas/eaos-server/health";
const app = new Hono();
app.route("/", createHealthRouter({ appName: "example-service" }));
const response = await app.request("/health/live");
console.log(response.status); // 200

Creates the standard private HTTP boundary from application-worker to an ARM/remote agent runtime. The runtime returns text only; workflow proposal parsing and all business side effects stay in EAOS/server/plugin code.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/remote-executor.

declare function createHttpAgentExecutor(options: HttpAgentExecutorOptions): ServerAgentExecutor;
Name Type Required Description
options HttpAgentExecutorOptions Yes Trusted endpoint, headers, fetch implementation, and limits.

ServerAgentExecutor

An executor resolving runtime output text after checking protocolVersion, taskId, status, and output type.

HTTPS is required except localhost/127.0.0.1/IPv6 loopback HTTP; URL credentials and fragments are rejected. Each task uses one POST with redirects disabled, cookies omitted, and an AbortSignal timeout. No retries or business authorization occur here. Remote side effects may have happened before transport failure; the host must define safe idempotency before retrying. Response readers are released and oversized streams are cancelled.

Synchronously for missing/invalid endpoint or limits. Invocations reject with ServerAgentExecutionError for transport, timeout, HTTP status, output size, JSON/contract errors, or reported runtime failure; clone/serialization errors can also reject.

import { createHttpAgentExecutor, type HttpAgentExecutorOptions } from "@alneas/eaos-server/agentic/remote-executor";
export function remoteExecutor(hostConfiguration: HttpAgentExecutorOptions) {
// Provision/authenticate the runtime separately and keep its headers server-side.
return createHttpAgentExecutor(hostConfiguration);
}

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function createJsonDocumentAssertion(document: JsonDocumentContract): (value: unknown) => void;
Name Type Required Description
document JsonDocumentContract Yes See the upstream owning declaration.

(value: unknown) => void

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Creates a public Kratos whoami verifier without using the Admin API or minting sessions.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/kratos-session.

declare function createKratosSessionVerifier(options: {
publicUrl: string;
fetch?: typeof fetch;
timeoutMs?: number;
}): (credentials: {
cookie?: string;
sessionToken?: string;
}) => Promise<{
userId: string;
identity: Record<string, unknown>;
} | null>;
Name Type Required Description
options { publicUrl: string; fetch?: typeof fetch; timeoutMs?: number; } Yes publicUrl is an HTTP(S) origin with root path and no embedded credentials/query/fragment; fetch defaults to global fetch and timeoutMs to 10000 milliseconds.

(credentials: { cookie?: string; sessionToken?: string; }) => Promise<{ userId: string; identity: Record<string, unknown>; } \| null>

An async verifier accepting cookie/sessionToken credentials and resolving userId plus provider identity, or null for absent credentials, 401/403 responses, inactive sessions, or missing identity IDs. sessionToken takes precedence over cookie.

Credentials are forwarded only to the configured origin with redirects disabled and no-store caching. The host must trust this origin and separately resolve memberships and tenant lifecycle. This verifier creates no listeners or background work.

Synchronously for an invalid provider URL. Verification rejects transport, abort, invalid timeout, non-OK provider responses other than 401/403, and JSON parsing failures.

Trusted HTTP(S) Kratos origin with a root path and no embedded credentials, query, or fragment.

Host transport for public whoami calls; defaults to global fetch, with redirects disabled and no-store caching.

AbortSignal timeout in milliseconds for each whoami request; defaults to 10000 and invalid values fail when invoked.

import { createKratosSessionVerifier } from "@alneas/eaos-server/browser-auth/kratos-session";
const verify = createKratosSessionVerifier({ publicUrl: "https://identity.example.com" });
export async function authenticate(cookie: string | undefined) {
return verify({ cookie });
}

Creates a request guard requiring a verified tenant and currently enabled plugin placement.

Imports: @alneas/eaos-server/lifecycle.

declare function createLifecycleGuard(runtime: LifecycleRuntime, pluginId: string): hono.MiddlewareHandler<any, string, {}, Response | (Response & hono.TypedResponse<{
error: string;
}, 401, "json">)>;
Name Type Required Description
runtime LifecycleRuntime Yes Host tenant verification, backend routing, and lifecycle engine.
pluginId string Yes Exact installed plugin ID required by the route.

hono.MiddlewareHandler<any, string, {}, Response \| (Response & hono.TypedResponse<{ error: string; }, 401, "json">)>

Hono middleware returning 401 for absent tenant, 403 for unavailable backend/inactive plugin, or completing downstream handling without a value after setting tenantId.

Authenticate webhook signatures or browser identity in resolveTenant; a raw header is insufficient. This guard performs a point-in-time isEnabled check and does not hold a lifecycle.run execution lease across downstream work.

Request handling propagates host resolver, lifecycle store, and downstream failures.

import { Hono } from "hono";
import { createLifecycleGuard, type LifecycleRuntime } from "@alneas/eaos-server/lifecycle";
export function pluginRoutes(runtime: LifecycleRuntime) {
const app = new Hono();
app.use("*", createLifecycleGuard(runtime, "example-plugin"));
app.get("/", c => c.json({ available: true }));
return app;
}

Create a static operation handler that dispatches through a host-bound service instance.

Imports: @alneas/eaos-server/plugin-data.

declare function createMcpOperationHandler<TService extends {
execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown>;
}>(operation: string, key: symbol): (args: unknown, context?: Record<PropertyKey, unknown>) => Promise<unknown>;
Name Type Required Description
operation string Yes Trusted operation name selected by the manifest author.
key symbol Yes Service-binding symbol used by createMcpToolBinder.

(args: unknown, context?: Record<PropertyKey, unknown>) => Promise<unknown>

An async handler accepting tool arguments and trusted principal/service context.

  • TService: Host service exposing the principal-aware execute contract.

The incoming context must already contain a verified PluginPrincipal. This helper neither authenticates a request nor verifies live resource access.

The returned handler rejects when the service is absent or has no execute method; service failures propagate.

import { createMcpOperationHandler } from '@alneas/eaos-server/plugin-data'
const key = Symbol('service')
const handler = createMcpOperationHandler('list', key)

Creates authenticated MCP tool discovery/execution routes and an SSE JSON-RPC transport.

Imports: @alneas/eaos-server, @alneas/eaos-server/mcp.

declare function createMcpRouter(runtime: McpRuntime, options: McpRouterOptions): Hono;
Name Type Required Description
runtime McpRuntime Yes Trusted plugin/tool registry and gatekeeper with audit behavior.
options McpRouterOptions Yes Host principal verification, current lifecycle/entitlement checks, scoped dependencies, AI adapters, and SSE limits.

Hono

A Hono router exposing GET /tools, POST /execute, GET /sse, and POST /message; no network listener is started.

Every request resolves current identity and enabled plugins. Tool discovery hides unavailable tools; calls validate arguments, recheck lifecycle before execution, and perform entitlement admission. Human-approval requirements return pending data without executing the handler; no client approval flag bypasses this. Request bodies are limited to 1 MiB. Host callbacks must supply tenant-scoped resources and enforce real membership and lifecycle checks; the router does not open databases or persist results. SSE session state is process-local, owner-bound, capacity-limited, and removed on stream cancellation or lazy expiry checks. Expiry removes the mapping without explicitly closing the existing stream; no heartbeat or cross-process session sharing is provided. Tool failures may occur after side effects, so retry/idempotency remains host-owned.

Router construction can propagate validator setup errors. Request-time callback, schema compilation, tool, or audit errors are passed to onError and normally rendered as a generic 500; a throwing onError can itself fail error handling.

import { createMcpRouter, type McpRuntime, type McpRouterOptions } from "@alneas/eaos-server/mcp";
export function mcpRoutes(runtime: McpRuntime, options: McpRouterOptions) {
// options.resolvePrincipal must verify live identity, membership, and enabled plugins.
// Supply only tenant-scoped resources through createToolContext.
return createMcpRouter(runtime, options);
}

Bind a service under the trusted context symbol for copied static MCP tool definitions.

Imports: @alneas/eaos-server/plugin-data.

declare function createMcpToolBinder<TService>(service: TService, tools: readonly _alneas_eaos_core_plugin_sdk.McpToolDefinition[], key: symbol): _alneas_eaos_core_plugin_sdk.McpToolDefinition[];
Name Type Required Description
service TService Yes Host-created service instance used by each copied tool handler.
tools readonly _alneas_eaos_core_plugin_sdk.McpToolDefinition[] Yes Static tool definitions whose handlers consume the service context symbol.
key symbol Yes Trusted symbol agreed by the binder and operation handler.

_alneas_eaos_core_plugin_sdk.McpToolDefinition[]

New tool objects with wrappers that preserve other context fields and override the service symbol.

  • TService: Concrete host-created service type retained in the symbol binding.

Does not resolve identity or grant permission. Tool execution still requires verified principal context and live host admission.

import { createMcpToolBinder } from '@alneas/eaos-server/plugin-data'
export function bindTools<T>(service: T, tools: Parameters<typeof createMcpToolBinder>[1], key: symbol) { return createMcpToolBinder(service, tools, key) }

Rejects requests unless verified enabledModules contains the requested module or “all”.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/module-guard.

declare function createModuleGuard(moduleKey: string, options?: ModuleGuardOptions): hono.MiddlewareHandler<EaosEnv, string, {}, Response>;
Name Type Required Description
moduleKey string Yes Exact, case-sensitive entitlement key required by this route.
options ModuleGuardOptions No Development bypass; see {@link ModuleGuardOptions}.

hono.MiddlewareHandler<EaosEnv, string, {}, Response>

Hono middleware that responds with 403 for missing, malformed, or insufficient entitlements, or completes downstream handling without returning a value.

Install authentication and trusted entitlement resolution first. This guard reads context only and does not query a contract store. The development bypass defaults from NODE_ENV.

Request execution propagates downstream middleware rejections.

import { Hono } from "hono";
import type { EaosEnv } from "@alneas/eaos-core";
import { createModuleGuard } from "@alneas/eaos-server/middleware/module-guard";
const app = new Hono<EaosEnv>();
app.use("/reports/*", createModuleGuard("reports", { isDev: false }));
// Populate verified enabledModules in earlier host middleware to allow access.
app.get("/reports/summary", c => c.json({ available: true }));
console.log((await app.request("/reports/summary")).status); // 403

Run atomic envelope SQL on a host-provided tenant Oracle connection with explicit commit/rollback.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function createOracleAtomicDriver(host: OracleAtomicHost, types: {
objectFormat: number;
stringType: unknown;
clobType: unknown;
}): AtomicSqlDriver;
Name Type Required Description
host OracleAtomicHost Yes Trusted connection provider admitting PLUGIN_RECORDS operations for the verified tenant/user.
types { objectFormat: number; stringType: unknown; clobType: unknown; } Yes Actual Oracle object-format/string/CLOB constants; no global provider settings are changed.

AtomicSqlDriver

Oracle transaction driver with optional batch execution and scalar fallback for large strings.

Host owns session authorization, tenant cleanup and connection release. Strings over 4000 characters use explicit CLOB bindings; no production connection is opened at construction.

Connection/statement/commit/rollback errors and invalid batch row counts reject; rollback failures may replace the original failure.

Actual installed Oracle object-row output format constant.

Actual Oracle string fetch type for JSON PAYLOAD extraction.

Actual Oracle CLOB type used for strings longer than 4000 characters.

import { createOracleAtomicDriver } from '@alneas/eaos-server/plugin-data'
export function driver(host: Parameters<typeof createOracleAtomicDriver>[0], types: Parameters<typeof createOracleAtomicDriver>[1]) { return createOracleAtomicDriver(host, types) }

Platform-wide control routes. They operate on host-registered opaque backends; provisioning, credentials, SQL and tenant membership remain host-owned.

Imports: @alneas/eaos-server, @alneas/eaos-server/platform-admin.

declare function createPlatformAdminRouter(options: PlatformAdminRouterOptions): Hono;
Name Type Required Description
options PlatformAdminRouterOptions Yes Shared store, live platform-admin authorization, audit sink, optional placement executor, and clock.

Hono

A Hono router for tenants, backend discovery, placement planning/execution/status/rollback/reconciliation. Unauthenticated/unauthorized requests return 401/403.

Every operation requires principal.isPlatformAdmin === true plus host authorize approval. Plan/rollback endpoints persist reviewed plans rather than directly changing routing. Execution verifies reports before cutover and records reconciling state on uncertain failures; host executor effects are not rolled back automatically. Reads expose opaque public backend metadata without credentials/SQL. A failed audit can follow a completed mutation, so errors do not prove no change occurred. No listener, deployment, or scheduler is started.

Synchronously for missing store/auth/audit dependencies. Request-time reads/auth/audit can fail through Hono error handling; mutation failures are generally 400 or migration conflict 409 data.

import { createPlatformAdminRouter, type PlatformAdminRouterOptions } from "@alneas/eaos-server/platform-admin";
export function controlRoutes(options: PlatformAdminRouterOptions) { return createPlatformAdminRouter(options); }

Combines a verified Kratos identity, unambiguous membership, active tenant, and expected backend placement.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/platform-session.

declare function createPlatformSessionResolver(options: {
verify: ReturnType<typeof createKratosSessionVerifier>;
memberships: (userId: string, tenantId: string | undefined, identity: Record<string, unknown>) => Promise<Membership[]>;
store: LifecycleStore;
targetFor: (tenantId: string) => BackendTarget;
}): (context: Context, resolution?: {
refresh?: boolean;
}) => Promise<BrowserSession | null>;
Name Type Required Description
options { verify: ReturnType<typeof createKratosSessionVerifier>; memberships: (userId: string, tenantId: string | undefined, identity: Record<string, unknown>) => Promise<Membership[]>; store: LifecycleStore; targetFor: (tenantId: string) => BackendTarget; } Yes verify checks credentials; memberships receives verified userId, optional selected tenant ID, and provider identity and resolves candidate memberships; store supplies lifecycle state; targetFor synchronously resolves the expected backend for a selected tenant.

(context: Context, resolution?: { refresh?: boolean; }) => Promise<BrowserSession \| null>

A resolver accepting Hono context and optional refresh flag. It resolves a BrowserSession or null for invalid credentials/selection, ambiguous membership, or inactive tenant. Each context caches the in-flight/result Promise unless refresh is true.

Authorization accepts only the exact Bearer syntax with one space and a nonwhitespace token. Bearer token takes precedence over X-Session-Token; the verifier gives session tokens precedence over cookies. X-Tenant-Id selects a candidate but never grants membership. No default tenant or role is invented. The WeakMap cache is per resolver/context; refresh starts another lookup without cancelling previous work.

The resolver rejects verifier, membership, store, and targetFor errors, malformed membership fields, or backend placement mismatch. Rejected Promises are cached until refresh.

Server whoami verifier receiving cookie/session-token credentials; token transport takes precedence over cookies.

Host callback receiving verified user ID, optional requested tenant, and provider identity; must resolve exactly one authorized membership or resolution returns null.

Authoritative lifecycle store used to require an active tenant and its expected backend placement.

Synchronous host backend selector for the verified membership tenant; an ID differing from lifecycle placement rejects resolution.

import { createPlatformSessionResolver } from "@alneas/eaos-server/browser-auth/platform-session";
export function hostSessionResolver(options: Parameters<typeof createPlatformSessionResolver>[0]) {
// Supply verified membership reads, lifecycle store, and backend routing.
return createPlatformSessionResolver(options);
}

Creates entitled asset URL delivery using a trusted catalog and host signing transport.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare function createPluginAssetRouter(options: {
runtime: PluginEntitlementRuntime;
resolvePrincipal: EntitlementPrincipalResolver;
plugins: Readonly<Record<string, PluginEntitlement>>;
assets: readonly ProtectedPluginAsset[];
sign: (input: {
asset: ProtectedPluginAsset;
principal: PlatformPrincipal;
expiresIn: number;
}) => Promise<string>;
}): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
Name Type Required Description
options { runtime: PluginEntitlementRuntime; resolvePrincipal: EntitlementPrincipalResolver; plugins: Readonly<Record<string, PluginEntitlement>>; assets: readonly ProtectedPluginAsset[]; sign: (input: { asset: ProtectedPluginAsset; principal: PlatformPrincipal; expiresIn: number; }) => Promise<string>; } Yes runtime checks current entitlement; resolvePrincipal authenticates the request; plugins supplies rules; assets supplies trusted object metadata; sign receives cloned asset, verified principal, and expiresIn=60 seconds and resolves a capability URL.

Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">

A router serving GET /:pluginId/:assetId with URL/checksum/contentType/60-second lifetime, or 401/404/policy denial responses. Successful responses use private, no-store caching.

Entitlement is checked before and after external signing, but no quota is reserved by this route. Signed URLs may remain usable after later revocation until expiry; the signing port must enforce private access and the requested lifetime. Catalogs, keys, and credentials must remain host-controlled.

Request handling propagates resolver/runtime/signing errors or invalid trusted checksums.

Current lifecycle/subscription policy checker; URL delivery checks it before signing and immediately before returning the capability.

Authenticates each asset request and resolves a verified tenant/user principal or null to return 401; errors propagate through Hono.

Trusted plugin-ID to entitlement-policy catalog; an unknown plugin is returned as unavailable.

Trusted asset catalog looked up by plugin ID and asset ID; client input never supplies storage object keys.

Host signing callback invoked after initial admission with exact asset/principal and a 60-second lifetime; resolves a private capability URL and may reject.

Structured clone of the trusted catalog asset, including storage key and validated lowercase SHA-256.

Verified principal for the current asset request; use it for host signing authorization.

Requested signed URL lifetime in seconds; this router always supplies 60.

import { createPluginAssetRouter } from "@alneas/eaos-server/entitlements";
export function assetRoutes(options: Parameters<typeof createPluginAssetRouter>[0]) {
return createPluginAssetRouter(options);
}

Resolve manifest storage metadata to an atomic repository with canonical document enforcement.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function createPluginAtomicRepository(manifest: Pick<PluginManifest, 'schema'>, driver: AtomicSqlDriver, catalog?: DataContractCatalog): AtomicRepository;
Name Type Required Description
manifest Pick<PluginManifest, 'schema'> Yes Trusted schema with shared-storage binding or exactly one owned table.
driver AtomicSqlDriver Yes Trusted transactional SQL driver.
catalog DataContractCatalog No Required Data Contract catalog when shared storage is declared.

AtomicRepository

Atomic repository for the manifest-selected table/namespace.

Does not install/enable storage contracts; host lifecycle and admission are separate.

Rejects absent/mismatched catalogs, ambiguous owned tables or invalid repository bindings.

import { createPluginAtomicRepository } from '@alneas/eaos-server/plugin-data'
export function repository(manifest: Parameters<typeof createPluginAtomicRepository>[0], driver: Parameters<typeof createPluginAtomicRepository>[1], catalog: Parameters<typeof createPluginAtomicRepository>[2]) { return createPluginAtomicRepository(manifest, driver, catalog) }

Creates a request guard reserving current restricted/metered plugin admission before downstream work.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare function createPluginEntitlementGuard(pluginId: string, rule: PluginEntitlement, runtime?: PluginEntitlementRuntime, resolvePrincipal?: EntitlementPrincipalResolver): hono.MiddlewareHandler<any, string, {}, Response | (Response & hono.TypedResponse<{
error: string;
}, 401, "json">)>;
Name Type Required Description
pluginId string Yes Exact plugin ID to admit.
rule PluginEntitlement Yes Declared plugin access and metering policy.
runtime PluginEntitlementRuntime No Required for restricted/metered/allowed-tenant rules; absence returns 503.
resolvePrincipal EntitlementPrincipalResolver No Verified request principal callback; defaults to resolveEngineEntitlementPrincipal.

hono.MiddlewareHandler<any, string, {}, Response \| (Response & hono.TypedResponse<{ error: string; }, 401, "json">)>

Hono middleware returning 401 for absent identity, policy status for EntitlementError, or completing downstream work without a value.

Public unmetered rules skip runtime checks after principal validation; host lifecycle/resource authorization remains required. Metered admission counts failed downstream attempts.

Request handling propagates invalid principal, host runtime, resolver, and downstream errors outside normalized entitlement denial.

import { Hono } from "hono";
import { createPluginEntitlementGuard, type PluginEntitlementRuntime, type EntitlementPrincipalResolver } from "@alneas/eaos-server/entitlements";
import type { PluginEntitlement } from "@alneas/eaos-core";
export function protectedApp(rule: PluginEntitlement, runtime: PluginEntitlementRuntime, resolvePrincipal: EntitlementPrincipalResolver) {
const app = new Hono();
app.use("*", createPluginEntitlementGuard("example-plugin", rule, runtime, resolvePrincipal));
return app;
}

Routes authenticated, authorized JSON requests to a fixed plugin/action operation map.

Imports: @alneas/eaos-server/execution.

declare function createPluginExecutionRouter(options: {
resolveIdentity: (context: Context) => Promise<ExecutionIdentity | null>;
authorize: (identity: ExecutionIdentity, pluginId: string, action: string, payload: unknown) => Promise<boolean>;
operations: Record<string, (identity: ExecutionIdentity, payload: unknown) => Promise<unknown>>;
maxBodyBytes?: number;
allowedOrigins?: string[];
}): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
Name Type Required Description
options { resolveIdentity: (context: Context) => Promise<ExecutionIdentity | null>; authorize: (identity: ExecutionIdentity, pluginId: string, action: string, payload: unknown) => Promise<boolean>; operations: Record<string, (identity: ExecutionIdentity, payload: unknown) => Promise<unknown>>; maxBodyBytes?: number; allowedOrigins?: string[]; } Yes resolveIdentity receives Hono context and resolves verified identity/null; authorize receives that identity, pluginId, action, and parsed payload and must check current membership, activation, and resource permissions; operations maps pluginId:action to async handlers receiving identity/payload. maxBodyBytes defaults to 1048576; allowedOrigins permits exact Origin values and defaults to none.

Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">

A router serving POST /:pluginId/:action with no-store responses. It returns handler output as JSON or explicit 400/401/403/404/413/415 failures; callback/transport/serialization failures become 503.

The operation map is shallow-copied at creation. Plugin IDs must be lowercase kebab-case; actions allow letters/digits/underscore/hyphen. Origin is checked only when present and is not authentication. Body readers are released and oversized streams cancelled. No transaction, idempotency, cancellation, or retry is supplied; operation side effects may precede a 503 response.

Synchronously for a nonpositive or unsafe-integer body limit.

Authenticates the Hono request and resolves nonblank verified tenant/user IDs or null; callback failure becomes a 503 response.

Must check current tenant membership, plugin activation and resource permissions.

Fixed pluginId:action handlers shallow-copied at creation; each receives admitted identity and parsed JSON and resolves JSON-serializable output.

Positive safe-integer request body limit in bytes, enforced while reading; defaults to 1048576.

Optional exact Origin allowlist; any present Origin is denied unless included, while an absent Origin skips this check.

import { createPluginExecutionRouter } from "@alneas/eaos-server/execution";
export function executionRouter(options: Parameters<typeof createPluginExecutionRouter>[0]) {
// Host adapters authenticate, authorize, validate payloads, and persist operation results.
return createPluginExecutionRouter(options);
}

Resolve a manifest-owned storage table and optional canonical namespace/document bindings.

Imports: @alneas/eaos-server/plugin-data.

declare function createPluginRecordStore<T>(manifest: Pick<PluginManifest, 'schema'>, driver: RecordSqlDriver, catalog?: DataContractCatalog): PluginRecordStore<T>;
Name Type Required Description
manifest Pick<PluginManifest, 'schema'> Yes Trusted plugin schema with one owned table or an explicit shared-storage binding.
driver RecordSqlDriver Yes Host SQL transport used by the resulting store.
catalog DataContractCatalog No Required trusted Data Contract catalog for shared-storage bindings.

PluginRecordStore<T>

The tenant-predicated record store for the declared table/namespace.

  • T: Stored payload shape retained by the record store.

Does not install schemas or activate a feature; migration and live authorization remain host responsibilities.

Rejects absent catalog, invalid storage binding or a legacy declaration without exactly one owned table; store validation failures propagate.

import { createPluginRecordStore } from '@alneas/eaos-server/plugin-data'
export function pluginRecords(manifest: Parameters<typeof createPluginRecordStore>[0], driver: Parameters<typeof createPluginRecordStore>[1], catalog: Parameters<typeof createPluginRecordStore>[2]) { return createPluginRecordStore(manifest, driver, catalog) }

Create a bounded Hono router that resolves a verified principal for every request.

Imports: @alneas/eaos-server/plugin-data.

declare function createPluginRouter(resolvePrincipal: (c: Context) => Promise<PluginPrincipal | null>, options?: PluginRouterOptions): Hono<PluginHttpEnv, hono_types.BlankSchema, "/">;
Name Type Required Description
resolvePrincipal (c: Context) => Promise<PluginPrincipal | null> Yes Async host callback returning the authenticated principal or null; host owns current session validation.
options PluginRouterOptions No Trusted body bound, default 128 KiB; accepted integer range is 1024 bytes through 8 MiB.

Hono<PluginHttpEnv, hono_types.BlankSchema, "/">

A Hono router with body limits, scoped principal context and sanitized generic failure responses.

Does not supply CSRF/Origin protection or per-resource authorization; compose those at the host/service boundary.

Invalid body limits throw at construction. Request-time missing/malformed principals produce 401; unexpected failures become sanitized 500 responses.

import { createPluginRouter } from '@alneas/eaos-server/plugin-data'
export function routes(resolvePrincipal: Parameters<typeof createPluginRouter>[0]) { return createPluginRouter(resolvePrincipal) }

Compile closed payload schemas and route records by longest canonical prefix without coercion or remote loading.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/json-documents.

declare function createRecordDocumentValidator(documents: readonly JsonDocumentContract[]): (tenantId: string, record: PluginRecord<unknown>) => void;
Name Type Required Description
documents readonly JsonDocumentContract[] Yes Nonempty trusted document list; each binds column payload to a closed object schema.

(tenantId: string, record: PluginRecord<unknown>) => void

A synchronous (tenantId, record) assertion that accepts only matching identity, revision, immutability and schema.

Does not write records or prove live authorization; document definitions are cloned before compilation.

Rejects absent/open/ambiguous contracts at construction; assertions reject invalid IDs/revisions, unmatched routes, immutable replacements, schema or embedded-tenant mismatch.

import { createRecordDocumentValidator } from '@alneas/eaos-server/plugin-data'
export function validator(documents: Parameters<typeof createRecordDocumentValidator>[0]) { return createRecordDocumentValidator(documents) }

Creates a body-limited registration endpoint that verifies the caller before parsing JSON.

Imports: @alneas/eaos-server/auth-hooks.

declare function createRegistrationHook<T>(options: {
verify(c: Context): Promise<Response | void>;
parse(body: unknown): T;
register(input: T, c: Context): Promise<Response>;
}): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
Name Type Required Description
options { verify(c: Context): Promise<Response | void>; parse(body: unknown): T; register(input: T, c: Context): Promise<Response>; } Yes Host callbacks: verify receives the request context before parsing and must return a rejection Response or no value to continue; parse synchronously validates unknown JSON; register receives the parsed input and context and resolves the final response.

Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">

A Hono router serving POST /registration with a 128 KiB body limit; JSON or parser failures return 400.

  • T: Validated registration input returned by parse and passed unchanged to register.

The host owns authentication, registration persistence, duplicate handling, and transactional behavior. Body size enforcement precedes verify.

Request handling propagates verify and register rejections; parse exceptions become 400 responses.

Verifies the caller before request JSON is parsed.

Parameters:

  • c: Hono request context containing the headers/credentials to verify.

Returns: A rejection Response, or no value to continue registration.

Host verification failures propagate through request handling.

Example:

import { createRegistrationHook } from '@alneas/eaos-server/auth-hooks';
import type { Context } from 'hono';
export async function verifyCaller(options: Parameters<typeof createRegistrationHook>[0], context: Context) {
return options.verify(context);
}

Synchronously validates parsed JSON and produces the registration input.

Parameters:

  • body: Unknown JSON value from the request body.

Returns: Validated registration data passed unchanged to register.

Validation errors are converted to a 400 Invalid registration payload response.

Example:

import { createRegistrationHook } from '@alneas/eaos-server/auth-hooks';
export function parseRegistration(options: Parameters<typeof createRegistrationHook>[0], body: unknown) {
return options.parse(body);
}

Performs host registration after caller verification and input parsing.

Parameters:

  • input: Validated parser result, passed unchanged from parse.
  • c: Same Hono request context used for caller verification.

Returns: The final host registration response.

Host persistence/registration failures propagate; earlier external effects may already have occurred.

Example:

import { createRegistrationHook } from '@alneas/eaos-server/auth-hooks';
import type { Context } from 'hono';
export async function registerValidated(options: Parameters<typeof createRegistrationHook>[0], body: unknown, context: Context) {
const denied = await options.verify(context);
if (denied) return denied;
return options.register(options.parse(body), context);
}
import type { Context } from "hono";
import { createRegistrationHook } from "@alneas/eaos-server/auth-hooks";
export function registrationRouter(
verify: (context: Context) => Promise<Response | void>,
register: (input: { email: string }, context: Context) => Promise<Response>,
) {
return createRegistrationHook({ verify, register, parse(body: unknown) {
if (!body || typeof body !== "object" || !("email" in body) || typeof body.email !== "string") {
throw new Error("email is required");
}
return { email: body.email };
} });
}

Creates an unscoped private-upload, signed-URL storage adapter for R2 or S3.

Imports: @alneas/eaos-server/storage, @alneas/eaos-server/storage/s3-compatible.

declare function createS3CompatibleStorage(config: S3CompatibleStorageConfig): Promise<StorageAdapter>;
Name Type Required Description
config S3CompatibleStorageConfig Yes Provider configuration, credentials, and URL ceiling; see {@link S3CompatibleStorageConfig}.

Promise<StorageAdapter>

A frozen app-core adapter whose uploads reject public=true and whose URLs always use signatures within the configured ceiling.

Server-only: transport/signing stay in app-core and the host supplies secrets. Credentials are resolved once at construction. Signed access also works during a public-bucket migration but cannot close existing public URLs. Keep this unscoped adapter host-owned; give plugins createTenantS3CompatibleStorage. Constructing an adapter does not verify remote credentials or create a bucket.

Rejects invalid provider, lifetime, bucket, account/region, endpoint, or empty credentials, and propagates credential callback/import/adapter construction errors. Subsequent operations propagate transport errors.

import { createS3CompatibleStorage, readS3CompatibleStorageConfig } from "@alneas/eaos-server/storage/s3-compatible";
// The host provisions a private bucket and supplies the documented storage environment.
const config = readS3CompatibleStorageConfig();
if (!config) throw new Error("Storage is not configured");
const storage = await createS3CompatibleStorage(config);
// Retain storage in trusted server code; authorize requests before performing operations.

Mounts defined plugin routes behind host authentication, live authorization, and optional entitlement admission.

Imports: @alneas/eaos-server, @alneas/eaos-server/plugin-sdk.

declare function createSdkPluginRouter(plugin: DefinedPlugin, host: PluginSdkHost): Hono;
Name Type Required Description
plugin DefinedPlugin Yes Trusted defined plugin containing route methods, paths, handlers, and optional entitlement policy.
host PluginSdkHost Yes Verified principal resolution, lifecycle/resource authorization, and tenant/plugin-scoped capability factory.

Hono

A Hono router with a 1 MiB body limit; GET/DELETE inputs are query parameter objects, other methods require JSON input.

Authorization runs before route handling and again after asynchronous context creation. The verified principal/plugin scope overwrites factory dependencies, but the host must enforce scope inside supplied capabilities. Metered entitlement admission can count requests whose later body parsing or handler fails. No transactions, retries, rollback, or idempotency are supplied around handlers.

Request handling propagates host, entitlement, context, and handler failures except malformed JSON/auth/admission responses explicitly returned by the router.

import { createSdkPluginRouter, type PluginSdkHost } from "@alneas/eaos-server/plugin-sdk";
import type { DefinedPlugin } from "@alneas/eaos-core";
export function pluginRouter(plugin: DefinedPlugin, host: PluginSdkHost) {
return createSdkPluginRouter(plugin, host);
}

Serialize BEGIN IMMEDIATE transactions on a host-owned SQLite connection.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function createSqliteAtomicDriver(db: SqliteAtomicDatabase): AtomicSqlDriver;
Name Type Required Description
db SqliteAtomicDatabase Yes Structural SQLite database whose schema and connection lifetime are owned by the host.

AtomicSqlDriver

SQLite transaction driver with one connection-local promise queue.

Queueing is per driver instance, not cross-process coordination. Do not nest repository transactions on the same connection; close the database only after all operations finish.

BEGIN/statement/COMMIT/ROLLBACK errors and callback failures reject; a rollback failure can replace the original error.

import { createSqliteAtomicDriver } from '@alneas/eaos-server/plugin-data'
export function driver(db: Parameters<typeof createSqliteAtomicDriver>[0]) { return createSqliteAtomicDriver(db) }

Bind JSON record persistence to a trusted table, namespace and host SQL driver.

Imports: @alneas/eaos-server/plugin-data.

declare function createSqlRecordStore<T>(table: string, driver: RecordSqlDriver, options?: SqlRecordStoreOptions): PluginRecordStore<T>;
Name Type Required Description
table string Yes Trusted lowercase table identifier, never a request-selected name.
driver RecordSqlDriver Yes Tenant-aware SQL transport; host owns transactions, Oracle binding/session cleanup and current authorization.
options SqlRecordStoreOptions No Optional namespace, payload policy and canonical JSON document contracts.

PluginRecordStore<T>

A record store with tenant predicates, keyset reads and revision-predicated replace/delete operations.

  • T: Stored JSON payload type; runtime shape is enforced only when canonical document contracts are supplied.

Does not create/migrate tables or add a shared transaction around separate calls. Driver affected-row reporting is required for CAS correctness; hosts enforce live authorization.

Rejects invalid table/namespace/document bindings. Operations propagate provider errors, reject invalid limits/revisions/payloads and map duplicate keys to PluginError 409.

import { createSqlRecordStore } from '@alneas/eaos-server/plugin-data'
export function records(driver: Parameters<typeof createSqlRecordStore>[1]) { return createSqlRecordStore<{ title: string }>('example_records', driver) }

[FUNCTION] createSqlTenantEntitlementLoader

Section titled “[FUNCTION] createSqlTenantEntitlementLoader”

Builds a parameterized tenant entitlement reader for the reviewed control-plane table.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare function createSqlTenantEntitlementLoader(driver: {
dialect: Dialect;
execute(sql: string, bindings: unknown[]): Promise<{
rows?: Record<string, unknown>[];
}>;
}): (tenantId: string) => Promise<TenantEntitlements | null>;
Name Type Required Description
driver { dialect: Dialect; execute(sql: string, bindings: unknown[]): Promise<{ rows?: Record<string, unknown>[]; }>; } Yes Host SQL dialect and execute callback; execute receives SQL and one tenant binding and resolves optional rows. Credentials and connection lifecycle remain host-owned.

(tenantId: string) => Promise<TenantEntitlements \| null>

An async loader accepting a verified 1–128-character tenant ID (letters/digits/underscore/dot/hyphen, starting alphanumeric) and resolving validated entitlements or null when no row exists.

Row keys are normalized to lowercase; JSON columns may be strings or already parsed values. No row-level authorization or shared transaction is established by this factory.

Loader calls reject invalid tenant IDs, multiple rows, malformed JSON/contracts, tenant mismatch, and propagated SQL errors.

SQL placeholder dialect: Oracle uses :1, PostgreSQL $1, and SQLite ? for the tenant binding.

Executes the loader’s parameterized tenant SELECT through the trusted host connection.

Parameters:

  • sql: SQL supplied by the loader with one dialect-correct tenant placeholder.
  • bindings: One verified tenant ID in placeholder order.

Returns: Optional result rows; no rows resolves to null at the loader boundary.

Host query errors reject the entitlement lookup.

Example:

import { createSqlTenantEntitlementLoader } from '@alneas/eaos-server/entitlements';
export async function loadContract(driver: Parameters<typeof createSqlTenantEntitlementLoader>[0], verifiedTenantId: string) {
// The host supplies the reviewed schema and privileged read connection.
return createSqlTenantEntitlementLoader(driver)(verifiedTenantId);
}

Optional result rows; missing rows is treated as an empty result, while more than one row rejects as ambiguous.

import { createSqlTenantEntitlementLoader } from "@alneas/eaos-server/entitlements";
export function entitlementLoader(driver: Parameters<typeof createSqlTenantEntitlementLoader>[0]) {
return createSqlTenantEntitlementLoader(driver);
}

Compose a service-backed authenticated operation router and bound static MCP tools.

Imports: @alneas/eaos-server/plugin-data.

declare function createStandardPluginServer<TOptions, TService extends StandardPluginService>(manifest: PluginManifest, ServiceClass: new (options: TOptions) => TService, bindTools: (service: TService) => McpToolDefinition[], options: TOptions, resolvePrincipal: (c: Context) => Promise<PluginPrincipal | null>, configureRoutes?: (routes: ReturnType<typeof createPluginRouter>, service: TService) => void, routerOptions?: PluginRouterOptions): {
createRoutes: () => Hono<PluginHttpEnv, hono_types.BlankSchema, "/">;
mcp: {
tools: McpToolDefinition[];
};
entitlement?: _alneas_eaos_core.PluginEntitlement;
id: string;
name: string;
version: string;
description: string;
icon: string;
category: string;
recommended?: boolean;
targets: _alneas_eaos_core.ClientTarget[];
dependencies: string[];
optionalDependencies?: string[];
tier: "public" | "standard" | "pro" | "corporate" | "free" | "premium";
industries: string[];
contracts: string[];
subscribes: string[];
publishes: string[];
navigation: _alneas_eaos_core.TargetNavigationConfig;
schema: _alneas_eaos_core.SchemaConfig;
extensions?: _alneas_eaos_core.PluginExtensionConfig[];
api: _alneas_eaos_core.ApiConfig;
secrets?: _alneas_eaos_core.PluginSecretRequirement[];
settings?: _alneas_eaos_core.PluginSettingConfig[];
agentCapabilities?: _alneas_eaos_core.AgentCapabilitiesConfig;
i18n?: _alneas_eaos_core.PluginI18nConfig;
docs?: _alneas_eaos_core.PluginDocConfig;
goExtension?: _alneas_eaos_core.GoExtensionConfig;
};
Name Type Required Description
manifest PluginManifest Yes Plugin metadata whose capabilities remain subject to host admission.
ServiceClass new (options: TOptions) => TService Yes Trusted service constructor invoked once with options.
bindTools (service: TService) => McpToolDefinition[] Yes Synchronous tool binder invoked with that same service instance.
options TOptions Yes Real store, authorization and other service configuration.
resolvePrincipal (c: Context) => Promise<PluginPrincipal | null> Yes Async trusted request-to-principal resolver; required.
configureRoutes (routes: ReturnType<typeof createPluginRouter>, service: TService) => void No Optional synchronous callback adding routes using the same service instance.
routerOptions PluginRouterOptions No Optional host-owned request body bound.

{ createRoutes: () => Hono<PluginHttpEnv, hono_types.BlankSchema, "/">; mcp: { tools: McpToolDefinition[]; }; entitlement?: _alneas_eaos_core.PluginEntitlement; id: string; name: string; version: string; description: string; icon: string; category: string; recommended?: boolean; targets: _alneas_eaos_core.ClientTarget[]; dependencies: string[]; optionalDependencies?: string[]; tier: "public" \| "standard" \| "pro" \| "corporate" \| "free" \| "premium"; industries: string[]; contracts: string[]; subscribes: string[]; publishes: string[]; navigation: _alneas_eaos_core.TargetNavigationConfig; schema: _alneas_eaos_core.SchemaConfig; extensions?: _alneas_eaos_core.PluginExtensionConfig[]; api: _alneas_eaos_core.ApiConfig; secrets?: _alneas_eaos_core.PluginSecretRequirement[]; settings?: _alneas_eaos_core.PluginSettingConfig[]; agentCapabilities?: _alneas_eaos_core.AgentCapabilitiesConfig; i18n?: _alneas_eaos_core.PluginI18nConfig; docs?: _alneas_eaos_core.PluginDocConfig; goExtension?: _alneas_eaos_core.GoExtensionConfig; }

Manifest fields plus createRoutes() and bound MCP definitions.

  • TOptions: Host service configuration passed unchanged to the constructor.
  • TService: Principal-aware service implementation shared by HTTP and MCP.

Mounting the server does not activate tenants. HTTP and MCP hosts must enforce their current lifecycle/resource admission; static tool binding alone does not do that.

Missing principal resolver or constructor/router/binder/configuration failures propagate.

import { createStandardPluginServer } from '@alneas/eaos-server/plugin-data'
export function bindServer(...args: Parameters<typeof createStandardPluginServer>) { return createStandardPluginServer(...args) }

Creates a resolver for host-owned tenant routing hints.

Imports: @alneas/eaos-server, @alneas/eaos-server/tenant.

declare function createTenantResolver(options?: TenantResolverOptions): TenantResolver;
Name Type Required Description
options TenantResolverOptions No Routing mappings and fallback; see {@link TenantResolverOptions}.

TenantResolver

A new independent resolver with copied mappings.

import { createTenantResolver } from "@alneas/eaos-server/tenant";
const resolver = createTenantResolver({ defaultTenantId: "workspace" });
console.log(resolver.resolve({}));

[FUNCTION] createTenantS3CompatibleStorage

Section titled “[FUNCTION] createTenantS3CompatibleStorage”

Creates provider-backed storage isolated to a verified tenant/plugin scope.

Imports: @alneas/eaos-server/storage, @alneas/eaos-server/storage/s3-compatible.

declare function createTenantS3CompatibleStorage(config: S3CompatibleStorageConfig, options: TenantStorageOptions): Promise<StorageAdapter>;
Name Type Required Description
config S3CompatibleStorageConfig Yes Host provider configuration and credentials.
options TenantStorageOptions Yes Trusted scope and live authorization; an omitted scope URL ceiling inherits config.maxUrlLifetimeSeconds, then 300.

Promise<StorageAdapter>

A frozen scoped adapter; see {@link createTenantStorage} for relative key and operation policy.

The provider ceiling also applies, so a larger scope ceiling cannot increase it. The host owns bucket provisioning and verified identity resolution.

Rejects provider construction failures and invalid scope settings; operations propagate authorization, policy, and transport errors.

import { createTenantS3CompatibleStorage, type S3CompatibleStorageConfig } from "@alneas/eaos-server/storage/s3-compatible";
import type { TenantStorageOptions } from "@alneas/eaos-server/storage";
export async function scopedStorage(config: S3CompatibleStorageConfig, trustedOptions: TenantStorageOptions) {
return createTenantS3CompatibleStorage(config, trustedOptions);
}

Wraps a storage adapter with tenant/plugin key isolation and per-operation authorization.

Imports: @alneas/eaos-server/storage.

declare function createTenantStorage(adapter: StorageAdapter, options: TenantStorageOptions): StorageAdapter;
Name Type Required Description
adapter StorageAdapter Yes Host-owned transport/signing adapter; optional copy and move are exposed only when supported.
options TenantStorageOptions Yes Trusted scope, authorization callback, and signed URL ceiling; see {@link TenantStorageOptions}.

StorageAdapter

A frozen adapter using relative keys while storing under tenants/{tenantId}/plugins/{pluginId}/; returned object keys and list cursors are scope-relative.

Keys cannot be absolute or contain traversal, empty segments, backslashes, percent escapes, control characters, query strings, or fragments. List permits an empty prefix and slash delimiter only. URLs default to a 300-second ceiling and remain usable until expiry after authorization changes. This wrapper supplies no persistence, locking, revocation, or transaction mechanism beyond the underlying adapter. The host must retain ownership of the unscoped adapter.

Throws synchronously for invalid scope IDs or URL lifetime. Operations reject for invalid relative keys, denied access, public uploads, unsigned or overlong URLs, invalid cursors/delimiters, out-of-scope provider results, or propagated adapter/authorization errors.

import { createTenantStorage, type StorageAdapter, type TenantStorageOptions } from "@alneas/eaos-server/storage";
export function pluginStorage(adapter: StorageAdapter, trustedOptions: TenantStorageOptions) {
// Resolve scope and authorization from verified host identity, never request body IDs.
return createTenantStorage(adapter, trustedOptions);
}

[FUNCTION] createValidatedAtomicRepository

Section titled “[FUNCTION] createValidatedAtomicRepository”

Validate canonical document payloads inside the host repository’s existing commit boundary.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/json-documents.

declare function createValidatedAtomicRepository(repository: AtomicRepository, documents: readonly JsonDocumentContract[]): AtomicRepository;
Name Type Required Description
repository AtomicRepository Yes Real tenant-scoped atomic repository.
documents readonly JsonDocumentContract[] Yes Trusted canonical payload contracts copied for validation.

AtomicRepository

A repository with validating, expiring sessions and retained joined-SQL capability bindings.

Does not open a second transaction or authorize operations. Wrapper capabilities expire after the work callback and are removed in finally.

Invalid contracts throw; work rejects wrong IDs/revisions/scopes, invalid batch order/length, expired sessions or payload/underlying repository failures.

import { createValidatedAtomicRepository } from '@alneas/eaos-server/plugin-data'
export function repository(repository: Parameters<typeof createValidatedAtomicRepository>[0], documents: Parameters<typeof createValidatedAtomicRepository>[1]) { return createValidatedAtomicRepository(repository, documents) }

Apply canonical document validation to every existing host persistence path while retaining other host methods.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/json-documents.

declare function createValidatedRecordHost<T, H extends {
store?: PluginRecordStore<T>;
repository?: AtomicRepository;
transaction?: <R>(principal: PluginPrincipal, work: (store: PluginRecordStore<T>) => Promise<R>) => Promise<R>;
}>(host: H, documents: readonly JsonDocumentContract[]): H;
Name Type Required Description
host H Yes Host with optional record store, repository and/or transaction callback.
documents readonly JsonDocumentContract[] Yes Trusted canonical JSON document definitions.

H

A proxy with wrapped persistence capabilities and other functions bound to the original host.

  • T: Stored JSON payload shape.
  • H: Concrete host shape whose existing methods and persistence capabilities are retained.

Does not replace transaction ownership or live authorization. Inputs are copied for validation; unrelated host methods keep their original receiver.

Invalid document contracts throw during wrapper creation; subsequent validation and underlying host failures propagate.

import { createValidatedRecordHost } from '@alneas/eaos-server/plugin-data'
export function validated<T>(host: Parameters<typeof createValidatedRecordHost<T, { store?: import('@alneas/eaos-server/plugin-data').PluginRecordStore<T> }>>[0], documents: Parameters<typeof createValidatedRecordHost>[1]) { return createValidatedRecordHost(host, documents) }

Validate canonical documents on host-store reads and writes while retaining its transaction semantics.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/json-documents.

declare function createValidatedRecordStore<T>(store: PluginRecordStore<T>, documents: readonly JsonDocumentContract[]): PluginRecordStore<T>;
Name Type Required Description
store PluginRecordStore<T> Yes Existing host record store with real tenant/CAS behavior.
documents readonly JsonDocumentContract[] Yes Trusted canonical payload contracts to clone and enforce.

PluginRecordStore<T>

A wrapped store retaining optional listPage/delete capabilities when supplied.

  • T: JSON payload shape retained by the wrapped store.

Does not add a transaction or independent authorization. Host returned list rows must still be correctly tenant-scoped.

Invalid contracts throw at creation; operations reject mismatched IDs, invalid revision transitions/payloads and immutable deletion, with underlying errors propagated.

import { createValidatedRecordStore } from '@alneas/eaos-server/plugin-data'
export function store<T>(store: Parameters<typeof createValidatedRecordStore<T>>[0], documents: Parameters<typeof createValidatedRecordStore>[1]) { return createValidatedRecordStore(store, documents) }

Creates a LangGraph node that records an agent proposal in workflow state. It deliberately does not execute proposed actions or create approvals.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-node.

declare function createWorkflowAgentNode<TOutput = unknown>(options: WorkflowAgentNodeOptions<TOutput>): GraphNodeHandler;
Name Type Required Description
options WorkflowAgentNodeOptions<TOutput> Yes Runner, request builder, output validator, and context key.

GraphNodeHandler

An async graph handler resolving merged context and history with an agent summary entry.

  • TOutput: Domain-specific proposal output passed to optional plugin validation; defaults to unknown.

validateOutput receives proposal output, proposal, and the current state after a completed run; its result is stored alongside the proposal. Unlike createRequest, this callback receives the original state. Host admission, durable checkpointing, and action approval remain outside this node.

Synchronously if runner or request builder is missing. Node execution rejects principal/workflow mismatch, noncompleted runner results, and callback or structuredClone failures.

import { createWorkflowAgentNode } from "@alneas/eaos-server/agentic/agent-node";
import type { WorkflowAgentNodeOptions } from "@alneas/eaos-server/agentic/agent-node";
export function proposalNode(options: WorkflowAgentNodeOptions) {
// Host callbacks build authorized requests and validate domain output.
return createWorkflowAgentNode(options);
}

Bridges the host/server executor contract to the vendor-neutral workflow runner contract. The executor output is parsed as a proposal; it is never treated as an instruction to perform a side effect.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-runner.

declare function createWorkflowAgentRunner(options: ServerWorkflowAgentRunnerOptions): WorkflowAgentRunner;
Name Type Required Description
options ServerWorkflowAgentRunnerOptions Yes Host-owned executor and optional runtime label.

WorkflowAgentRunner

A runner whose generic run method accepts a WorkflowAgentRequest and resolves a parsed proposal or a failure result. Executor errors become FAILED/UNAVAILABLE data; parse errors become nonretryable INVALID_PROPOSAL data.

The runner forwards workflow/correlation/idempotency/tool context but does not independently authorize, retry, deduplicate, execute tools, or enforce timeouts. Those boundaries belong to the host executor. Runtime text must parse as a version 1.0 proposal; domain-specific output still needs plugin validation.

Synchronously when executor is missing. run may reject before execution when request serialization fails.

import { createWorkflowAgentRunner } from "@alneas/eaos-server/agentic/agent-runner";
import type { ServerAgentExecutor } from "@alneas/eaos-server/agentic/types";
export function workflowRunner(executor: ServerAgentExecutor) {
return createWorkflowAgentRunner({ executor, runtimeId: "host-runtime" });
}

Builds a resolver that requires an existing tenant and membership or verified platform authority.

Imports: @alneas/eaos-server, @alneas/eaos-server/workspace-context.

declare function createWorkspaceContextResolver(store: WorkspaceContextStore): (identity: WorkspaceIdentity, tenantId: string | undefined) => Promise<WorkspaceContext>;
Name Type Required Description
store WorkspaceContextStore Yes Host-owned active tenant and membership reads; see {@link WorkspaceContextStore}.

(identity: WorkspaceIdentity, tenantId: string \| undefined) => Promise<WorkspaceContext>

An async resolver accepting verified identity and a selected tenant ID, resolving a fresh context. Missing email becomes null, tenantName falls back to tenant ID, and industryType falls back to “generic”.

The host supplies verified identity, schema, active-row filtering, and credentials. Reads are sequential and not wrapped in a transaction here. Platform administrators may select existing tenants without membership; membership role strings cannot grant platform authority. Blank or super_admin/superadmin membership roles normalize to member. This function writes no persistent data.

The returned resolver rejects with WorkspaceContextError: 401 for empty userId, 403 for missing/unavailable tenant or denied membership, and 503 for other store failures.

import { createWorkspaceContextResolver, type WorkspaceContextStore, type WorkspaceIdentity } from "@alneas/eaos-server/workspace-context";
export async function selectedWorkspace(store: WorkspaceContextStore, identity: WorkspaceIdentity, tenantId: string) {
// The host implements active-row reads and authenticates identity before this call.
return createWorkspaceContextResolver(store)(identity, tenantId);
}

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db.

interface DatabaseAdapter {
readonly type: DbDriverType;
withConnection<T>(domain: string, callback: (connection: any) => Promise<T>): Promise<T>;
withTenantConnection<T>(domain: string, callback: (connection: any) => Promise<T>, context: TenantSessionContext): Promise<T>;
ping(): Promise<boolean>;
getStats(): ConnectionStats;
close(): Promise<void>;
}
Name Type Required Description
type DbDriverType Yes See the upstream owning declaration.
withConnection Promise<T> Yes See the upstream owning declaration.
withTenantConnection Promise<T> Yes See the upstream owning declaration.
ping Promise<boolean> Yes See the upstream owning declaration.
getStats ConnectionStats Yes See the upstream owning declaration.
close Promise<void> Yes See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

interface DataContract {
id: string;
version: string;
description: string;
schema: Record<string, unknown>;
migrations: PluginMigration[];
dependencies?: Record<string, string>;
migrationIdentity?: string;
jsonDocuments?: JsonDocumentContract[];
}
Name Type Required Description
id string Yes See the upstream owning declaration.
version string Yes See the upstream owning declaration.
description string Yes See the upstream owning declaration.
schema Record<string, unknown> Yes See the upstream owning declaration.
migrations PluginMigration[] Yes See the upstream owning declaration.
dependencies Record<string, string> No See the upstream owning declaration.
migrationIdentity string No See the upstream owning declaration.
jsonDocuments JsonDocumentContract[] No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Hash-bound replacement of exact historical database migrations by equivalent baseline DDL.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/baseline.

interface DataContractBaseline {
format: 1;
source: DataContract;
target: DataContract;
replaces: {
id: string;
position: number;
checksum: string;
}[];
hash: string;
}
Name Type Required Description
format 1 Yes Baseline discriminator; currently 1.
source DataContract Yes Canonical contract release whose fully applied history is replaced.
target DataContract Yes Newer release retaining schema but using one database-scoped baseline migration.
replaces { id: string; position: number; checksum: string; }[] Yes Ordered historical migration IDs, positions and checksums requiring exact ledger matches.
hash string Yes Canonical digest of format/source/target/replaces.

Type declaration; no runtime value.

createDataContractBaseline for canonical integration usage.

Baseline discriminator; currently 1.

Canonical contract release whose fully applied history is replaced.

Newer release retaining schema but using one database-scoped baseline migration.

Ordered historical migration IDs, positions and checksums requiring exact ledger matches.

Original immutable migration ID replaced by the baseline.

Original zero-based migration position.

Canonical original migration definition digest.

Canonical digest of format/source/target/replaces.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

interface DataContractBinding {
contractId: string;
version: string;
table: string;
namespace?: string;
}
Name Type Required Description
contractId string Yes See the upstream owning declaration.
version string Yes See the upstream owning declaration.
table string Yes See the upstream owning declaration.
namespace string No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

interface DataContractCatalog {
contracts: DataContract[];
tables: {
name: string;
contractId: string;
version: string;
schema: Record<string, unknown>;
}[];
}
Name Type Required Description
contracts DataContract[] Yes See the upstream owning declaration.
tables { name: string; contractId: string; version: string; schema: Record<string, unknown>; }[] Yes See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function dataContractTables(schema: Record<string, unknown>): Map<string, Record<string, unknown>>;
Name Type Required Description
schema Record<string, unknown> Yes See the upstream owning declaration.

Map<string, Record<string, unknown>>

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Returns an engine configuration unchanged while checking its TypeScript shape.

Imports: @alneas/eaos-server, @alneas/eaos-server/engine.

declare function defineConfig(config: EaosConfig): EaosConfig;
Name Type Required Description
config EaosConfig Yes Configuration to retain; no runtime validation or cloning occurs.

EaosConfig

The same object reference.

import { defineConfig } from "@alneas/eaos-server/engine";
const config = defineConfig({ appName: "example-service", plugins: [] });
console.log(config.appName);

Immutable staged artifact identity, content hash and size returned by the host builder.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

interface DeliveryArtifact {
key: string;
contentHash: string;
bytes: number;
}
Name Type Required Description
key string Yes Immutable host artifact key, at most 1000 characters.
contentHash string Yes Lowercase 64-character SHA-256 for the staged artifact.
bytes number Yes Positive safe-integer artifact size in bytes.

Type declaration; no runtime value.

ArtifactDeliveryService for canonical host integration.

Immutable host artifact key, at most 1000 characters.

Lowercase 64-character SHA-256 for the staged artifact.

Positive safe-integer artifact size in bytes.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable delivery phase, worker ownership and retry state for one approved publication/withdrawal.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

interface DeliveryJob extends DeliveryRequest {
requestedBy: string;
createdAt: string;
state: 'queued' | 'running' | 'failed' | 'done' | 'cancelled';
phase: 'build' | 'activate' | 'purge' | 'cancel' | 'done';
attempts: number;
token?: string;
artifact?: DeliveryArtifact;
error?: string;
}
Name Type Required Description
requestedBy string Yes Authenticated user who enqueued the approved request.
createdAt string Yes Trusted UTC ISO enqueue time.
state 'queued' | 'running' | 'failed' | 'done' | 'cancelled' Yes queued/running/failed/done/cancelled state retained with CAS revisions.
phase 'build' | 'activate' | 'purge' | 'cancel' | 'done' Yes Last durable build/activate/purge/cancel/done phase; uncertain external effects are retried idempotently.
attempts number Yes Number of worker claims; incremented when a new run owns the job.
token string No Worker ownership token; recovery requires proving prior workers drained rather than waiting for expiry.
artifact DeliveryArtifact No Optional immutable build artifact used by the activation stage.
error string No Sanitized failure notice; sensitive host details remain in host-owned logs.

Type declaration; no runtime value.

ArtifactDeliveryService for canonical host integration.

Authenticated user who enqueued the approved request.

Trusted UTC ISO enqueue time.

queued/running/failed/done/cancelled state retained with CAS revisions.

Last durable build/activate/purge/cancel/done phase; uncertain external effects are retried idempotently.

Number of worker claims; incremented when a new run owns the job.

Worker ownership token; recovery requires proving prior workers drained rather than waiting for expiry.

Optional immutable build artifact used by the activation stage.

Sanitized failure notice; sensitive host details remain in host-owned logs.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Closed schema selecting an existing delivery job by its stable identifier.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

declare const deliveryJobSchema: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
jobId: {
type: string;
pattern: string;
};
};
};
Name Type Required Description
— — — No call parameters.

Declared constant value.

ArtifactDeliveryService for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported durable delivery command names; each requires live host resource/publication authorization.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

declare const deliveryOperations: readonly [
"enqueue_delivery",
"get_delivery",
"run_delivery",
"recover_delivery",
"cancel_delivery"
];
Name Type Required Description
— — — No call parameters.

Declared constant value.

ArtifactDeliveryService for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host publication approval, immutable artifact and idempotent external delivery capabilities.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

interface DeliveryPorts {
verify(p: PluginPrincipal, job: DeliveryRequest): Promise<boolean>;
build(p: PluginPrincipal, job: DeliveryJob): Promise<DeliveryArtifact>;
activate(p: PluginPrincipal, job: DeliveryJob): Promise<void>;
purge(p: PluginPrincipal, job: DeliveryJob): Promise<void>;
cancel?(p: PluginPrincipal, job: DeliveryJob): Promise<void>;
drained?(p: PluginPrincipal, job: DeliveryJob): Promise<boolean>;
}
Name Type Required Description
verify Promise<boolean> Yes Verify public publication/withdrawal approval for the exact target and content. Verify explicit PUBLIC publication (or withdrawal) permission, exact target/hash and approval. Ordinary reader access is insufficient.
build Promise<DeliveryArtifact> Yes Build and stage an immutable artifact outside the database transaction. Build and stage an immutable artifact outside a DB transaction. Must be idempotent for jobId.
activate Promise<void> Yes Apply or withdraw the exact public channel version idempotently. Atomic, idempotent channel update/withdrawal. Serialize with other host publishers; key=jobId.
purge Promise<void> Yes Invalidate the delivered channel idempotently before recording completion. Idempotent CDN invalidation; completion is recorded only after success.
cancel Promise<void> No Reconcile uncertain job effects and purge only this job’s owned version. Reconcile any uncertain activation for this job and purge it, idempotently. Never remove a newer publisher’s version.
drained Promise<boolean> No Prove prior workers for this job token can no longer perform effects.

Type declaration; no runtime value.

ArtifactDeliveryService for canonical host integration.

Verify public publication/withdrawal approval for the exact target and content.

Verify explicit PUBLIC publication (or withdrawal) permission, exact target/hash and approval. Ordinary reader access is insufficient.

Parameters:

  • p: Verified principal requiring explicit public publication/withdrawal permission.
  • job: Pinned request/job with exact approved target/contentHash/approvalRequestId.

Returns: Exactly true only when public permission and exact binding/approval remain valid.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryRequest, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function verifyReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryRequest) {
// The host binds permission and external effects to this exact job.
return ports.verify(principal, job);
}

Build and stage an immutable artifact outside the database transaction.

Build and stage an immutable artifact outside a DB transaction. Must be idempotent for jobId.

Parameters:

  • p: Verified current principal.
  • job: Durable job carrying the stable jobId idempotency identity.

Returns: An immutable staged artifact key, lowercase hash and positive safe byte size.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function buildReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {
// The host binds permission and external effects to this exact job.
return ports.build(principal, job);
}

Apply or withdraw the exact public channel version idempotently.

Atomic, idempotent channel update/withdrawal. Serialize with other host publishers; key=jobId.

Parameters:

  • p: Verified current principal.
  • job: Exact pinned publish/withdraw job, including staged artifact when publishing.

Returns: Resolves without a value after the idempotent channel switch/withdrawal.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function activateReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {
// The host binds permission and external effects to this exact job.
await ports.activate(principal, job);
}

Invalidate the delivered channel idempotently before recording completion.

Idempotent CDN invalidation; completion is recorded only after success.

Parameters:

  • p: Verified current principal.
  • job: Exact job channel/version requiring invalidation.

Returns: Resolves without a value only after actual idempotent invalidation succeeds.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function purgeReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {
// The host binds permission and external effects to this exact job.
await ports.purge(principal, job);
}

Reconcile uncertain job effects and purge only this job’s owned version.

Reconcile any uncertain activation for this job and purge it, idempotently. Never remove a newer publisher’s version.

Parameters:

  • p: Verified current principal admitted for cancellation.
  • job: Pinned job whose uncertain effects need reconciliation.

Returns: Resolves without a value after idempotent reconciliation/purge of only this owned version; never remove newer publications.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function cancelReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {
if (!ports.cancel) throw new Error("Required recovery port unavailable");
// The host binds permission and external effects to this exact job.
await ports.cancel(principal, job);
}

Prove prior workers for this job token can no longer perform effects.

Parameters:

  • p: Verified principal admitted for recovery.
  • job: Exact running job revision/token whose prior workers must be stopped.

Returns: Exactly true only when prior workers cannot perform further effects; false/absence prevents recovery.

Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.

Example:

import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function drainedReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {
if (!ports.drained) throw new Error("Required recovery port unavailable");
// The host binds permission and external effects to this exact job.
return ports.drained(principal, job);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Exact target/content/approval identity requested for one public channel delivery.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

interface DeliveryRequest {
jobId: string;
channel: string;
kind: 'publish' | 'withdraw';
target: Record<string, unknown>;
contentHash: string;
approvalRequestId: string;
}
Name Type Required Description
jobId string Yes Stable delivery job identity within its tenant repository.
channel string Yes Host-defined publication channel serialized against other unfinished delivery work.
kind 'publish' | 'withdraw' Yes publish stages an artifact; withdraw starts at activation/withdrawal without a build.
target Record<string, unknown> Yes Exact host-owned public destination metadata bound to the approval request.
contentHash string Yes Reviewed source-content SHA-256; the host verifies exact target/hash/approval binding.
approvalRequestId string Yes Exact host approval request admitting this public delivery; reader access alone is insufficient.

Type declaration; no runtime value.

ArtifactDeliveryService for canonical host integration.

Stable delivery job identity within its tenant repository.

Host-defined publication channel serialized against other unfinished delivery work.

publish stages an artifact; withdraw starts at activation/withdrawal without a build.

Exact host-owned public destination metadata bound to the approval request.

Reviewed source-content SHA-256; the host verifies exact target/hash/approval binding.

Exact host approval request admitting this public delivery; reader access alone is insufficient.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported declarative work phases; inspection never executes these actions.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare const deploymentActions: readonly [
"build",
"test",
"preview",
"provision",
"configure",
"migrate",
"deploy",
"verify",
"import",
"enable"
];
Name Type Required Description
— — — No call parameters.

Declared constant value.

summarizeDeployment for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

One declared deployable capability with explicit placement and nonsecret host requirements.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentComponent {
id: string;
required?: boolean;
kind: typeof deploymentComponentKinds[number];
placement: 'host' | 'container' | 'function' | 'database' | 'cloud' | 'native' | 'external';
runtime?: string;
assets?: string[];
assetPatterns?: string[];
entry?: string;
dataContracts?: Record<string, string>;
requirements?: {
tools?: Record<string, string>;
bindings?: string[];
adapters?: string[];
};
}
Name Type Required Description
id string Yes Unique component ID within the plugin.
required boolean No False marks an optional capability; omitted means required. Optional provider/native capabilities remain visible without requiring every deployment to adopt them.
kind typeof deploymentComponentKinds[number] Yes Supported frontend/server/storage/compute capability category.
placement 'host' | 'container' | 'function' | 'database' | 'cloud' | 'native' | 'external' Yes Declared host/container/function/database/cloud/native/external placement.
runtime string No Optional runtime descriptor.
assets string[] No Exact checksummed inventory asset references. References to files in the checksummed inventory, not arbitrary source paths.
assetPatterns string[] No Author-side asset selectors resolved by packing; unresolved patterns prevent completion. Author-side selectors resolved to exact assets by the packer; emitted inventories omit these.
entry string No Optional entry asset path.
dataContracts Record<string, string> No Canonical schema contract IDs and semver ranges, never copied DDL. Canonical contract IDs/ranges; no copied DDL.
requirements { tools?: Record<string, string>; bindings?: string[]; adapters?: string[]; } No Optional required tool ranges and host binding/adapter names.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Unique component ID within the plugin.

False marks an optional capability; omitted means required.

Optional provider/native capabilities remain visible without requiring every deployment to adopt them.

Supported frontend/server/storage/compute capability category.

Declared host/container/function/database/cloud/native/external placement.

Optional runtime descriptor.

Exact checksummed inventory asset references.

References to files in the checksummed inventory, not arbitrary source paths.

Author-side asset selectors resolved by packing; unresolved patterns prevent completion.

Author-side selectors resolved to exact assets by the packer; emitted inventories omit these.

Optional entry asset path.

Canonical schema contract IDs and semver ranges, never copied DDL.

Canonical contract IDs/ranges; no copied DDL.

Optional required tool ranges and host binding/adapter names.

Tool-name to required-version/range map declared by the plugin.

Required nonsecret host binding names; never credential values.

Required host adapter capability names.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported deployment capability categories used to validate component declarations.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare const deploymentComponentKinds: readonly [
"frontend",
"api",
"mcp",
"service",
"function",
"worker",
"job",
"webhook",
"workflow",
"database",
"infrastructure",
"storage",
"cache",
"queue",
"search",
"integration",
"native",
"model",
"data-import"
];
Name Type Required Description
— — — No call parameters.

Declared constant value.

summarizeDeployment for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Explicit existing host service/resource or physical database destination with a binding revision.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

interface DeploymentDestination {
id: string;
placement: DeploymentComponent['placement'];
service?: 'frontend' | 'backend' | 'worker';
reference?: string;
backendId?: string;
databaseId?: string;
tenantId?: string;
revision: string;
}
Name Type Required Description
id string Yes Unique destination identifier.
placement DeploymentComponent['placement'] Yes Host/container/function/database/cloud/native/external destination category.
service 'frontend' | 'backend' | 'worker' No Optional symbolic existing frontend/backend/worker role; host/container only. Symbolic role of an existing Platform service.
reference string No Optional nonsecret host resource/operation binding; never credentials or executable code. Host-owned resource/operation binding reference, never credentials or an executable command.
backendId string No Required existing backend ID for database destinations; forbidden otherwise.
databaseId string No Required exact physical database identity for database destinations.
tenantId string No Optional dedicated concrete tenant restriction; database destinations only. Restrict a dedicated DB destination to its verified tenant.
revision string Yes Nonblank host binding revision; change when wiring/provider/credential revision changes. Change when the host binding changes, including a credential/provider revision.

Type declaration; no runtime value.

summarizePlacedDeployment for canonical integration usage.

Unique destination identifier.

Host/container/function/database/cloud/native/external destination category.

Optional symbolic existing frontend/backend/worker role; host/container only.

Symbolic role of an existing Platform service.

Optional nonsecret host resource/operation binding; never credentials or executable code.

Host-owned resource/operation binding reference, never credentials or an executable command.

Required existing backend ID for database destinations; forbidden otherwise.

Required exact physical database identity for database destinations.

Optional dedicated concrete tenant restriction; database destinations only.

Restrict a dedicated DB destination to its verified tenant.

Nonblank host binding revision; change when wiring/provider/credential revision changes.

Change when the host binding changes, including a credential/provider revision.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

One task instance at an explicit destination or reusable artifact scope.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

interface DeploymentExecution {
taskId: string;
destinationId?: string;
componentIds: string[];
required: boolean;
status: DeploymentTaskStatus;
target?: DeploymentTarget;
result?: DeploymentResult;
dependencies: Array<{
taskId: string;
destinationId?: string;
}>;
}
Name Type Required Description
taskId string Yes Declared plugin task ID.
destinationId string No Scoped destination identity; absent for shared artifact work.
componentIds string[] Yes Adopted components covered at this destination.
required boolean Yes Whether this adopted execution must succeed for completion.
status DeploymentTaskStatus Yes Dependency-aware derived task state.
target DeploymentTarget No Resolved environment/database/tenant evidence context, if available.
result DeploymentResult No Latest matching reported result, if any.
dependencies Array<{ taskId: string; destinationId?: string; }> Yes Prerequisite task/destination identities whose evidence must succeed first.

Type declaration; no runtime value.

summarizePlacedDeployment for canonical integration usage.

Declared plugin task ID.

Scoped destination identity; absent for shared artifact work.

Adopted components covered at this destination.

Whether this adopted execution must succeed for completion.

Dependency-aware derived task state.

Resolved environment/database/tenant evidence context, if available.

Latest matching reported result, if any.

Prerequisite task/destination identities whose evidence must succeed first.

Prerequisite declared task ID.

Prerequisite destination, absent for shared artifact work.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Builds a scoped task target from a reviewed destination and the current inspection context.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

declare function deploymentExecutionTarget(destination: DeploymentDestination, scope: 'environment' | 'tenant', context?: DeploymentTarget): DeploymentTarget | undefined;
Name Type Required Description
destination DeploymentDestination Yes Validated destination with optional exact database and dedicated-tenant identities.
scope 'environment' | 'tenant' Yes Environment work omits tenant; tenant work requires a matching concrete tenant.
context DeploymentTarget No Current environment/tenant context; omitted cannot resolve a target.

DeploymentTarget \| undefined

A new target object, or undefined for missing context/tenant or dedicated-tenant mismatch.

Backend/database come from the destination, not the context. This performs no authority or resource-existence checks.

import { deploymentExecutionTarget } from '@alneas/eaos-server/platform/deployment-placements';
const target = deploymentExecutionTarget({ id: 'web', placement: 'host', service: 'frontend', revision: '1' }, 'environment', { environment: 'review' });

Checksummed artifact metadata and explicit per-plugin deployment work, separate from runtime admission.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/artifacts.

interface DeploymentInventory {
apiVersion: 1;
owner: string;
version?: string;
runtime?: string;
lifecycleBundle?: string[];
functions: Array<{
id: string;
source: string;
scope: 'tenant';
requiredTenantBindings: string[];
}>;
database?: {
source: string;
mode: 'adopt-existing-history';
tenantColumn: 'tenant_id';
};
assets: Array<{
path: string;
sha256: string;
}>;
plugins?: DeploymentPlugin[];
}
Name Type Required Description
apiVersion 1 Yes Inventory discriminator; currently 1.
owner string Yes Stable package/contribution owner used to bind receipts.
version string No Optional package release version.
runtime string No Optional declared execution runtime descriptor.
lifecycleBundle string[] No Optional ordered lifecycle plugin IDs; required for classified plugin work.
functions Array<{ id: string; source: string; scope: 'tenant'; requiredTenantBindings: string[]; }> Yes Tenant-scoped function source declarations and required tenant bindings.
database { source: string; mode: 'adopt-existing-history'; tenantColumn: 'tenant_id'; } No Optional adopted existing-history database declaration; never an instruction to recreate history.
assets Array<{ path: string; sha256: string; }> Yes Exact project-relative packaged asset paths and SHA-256 digests.
plugins DeploymentPlugin[] No Optional classified component/task declarations; absence is legacy-unclassified. Explicit per-plugin composition and required work. Omission is legacy/unclassified.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Inventory discriminator; currently 1.

Stable package/contribution owner used to bind receipts.

Optional package release version.

Optional declared execution runtime descriptor.

Optional ordered lifecycle plugin IDs; required for classified plugin work.

Tenant-scoped function source declarations and required tenant bindings.

Unique tenant-scoped function identity.

Project-relative packaged function/database source path.

Function scope discriminator; must be tenant.

Explicit binding names that the host must resolve separately for each tenant.

Optional adopted existing-history database declaration; never an instruction to recreate history.

Project-relative packaged function/database source path.

Database history policy; adopt-existing-history never recreates historical migrations.

Canonical tenant isolation column; currently tenant_id.

Exact project-relative packaged asset paths and SHA-256 digests.

Exact project-relative packaged asset path.

Lowercase SHA-256 digest of the asset bytes.

Optional classified component/task declarations; absence is legacy-unclassified.

Explicit per-plugin composition and required work. Omission is legacy/unclassified.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Hashes a selected plugin’s normalized component destinations and host binding revisions.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

declare function deploymentPlacementHash(placements: DeploymentPlacements, owner: string, pluginId: string, bindings?: Record<string, string>): string;
Name Type Required Description
placements DeploymentPlacements Yes Previously validated placement declaration.
owner string Yes Inventory owner selecting the plugin.
pluginId string Yes Selected plugin ID.
bindings Record<string, string> No Optional nonsecret destination-ID to host-binding revision map; defaults to none.

string

A lowercase SHA-256 hash bound to selected components, referenced destinations and applicable binding revisions.

Order of component/destination maps is normalized. Change binding revisions when provider credentials or host wiring change so old scoped evidence becomes stale.

Error when the owner/plugin selection is absent or canonical serialization fails.

import { deploymentPlacementHash, type DeploymentPlacements } from '@alneas/eaos-server/platform/deployment-placements';
export function bindingDigest(placements: DeploymentPlacements, owner: string, pluginId: string) { return deploymentPlacementHash(placements, owner, pluginId); }

Explicit plugin selection and destination assignments; empty lists deliberately decline optional components.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

interface DeploymentPlacements {
destinations: DeploymentDestination[];
plugins: Array<{
owner: string;
pluginId: string;
components: Record<string, string[]>;
}>;
}
Name Type Required Description
destinations DeploymentDestination[] Yes Unique nonsecret existing destination declarations.
plugins Array<{ owner: string; pluginId: string; components: Record<string, string[]>; }> Yes Selected owner/plugin pairs and complete component-ID to destination-ID lists; selection never registers/enables code. Listing a plugin selects it for this application plan; this never registers or enables code.

Type declaration; no runtime value.

summarizePlacedDeployment for canonical integration usage.

Unique nonsecret existing destination declarations.

Selected owner/plugin pairs and complete component-ID to destination-ID lists; selection never registers/enables code.

Listing a plugin selects it for this application plan; this never registers or enables code.

Exact inventory owner selecting this plugin.

Plugin declared by that owner; listing it selects application placement only.

Complete component-ID to destination-ID lists; empty declines only optional capabilities.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Classified deployment component/task graph for one lifecycle feature.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentPlugin {
id: string;
components: DeploymentComponent[];
tasks: DeploymentTask[];
}
Name Type Required Description
id string Yes Plugin ID covered by the inventory lifecycle bundle.
components DeploymentComponent[] Yes Unique deployable capability definitions.
tasks DeploymentTask[] Yes Unique work definitions forming an acyclic dependency graph.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Plugin ID covered by the inventory lifecycle bundle.

Unique deployable capability definitions.

Unique work definitions forming an acyclic dependency graph.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Operator/host-owned reported evidence journal pinned to one inventory digest.

Host/operator-owned journal. This is reported evidence, never runtime admission authority.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentReceipt {
apiVersion: 1;
owner: string;
inventorySha256: string;
results: DeploymentResult[];
}
Name Type Required Description
apiVersion 1 Yes Receipt discriminator; currently 1.
owner string Yes Exact inventory owner to which these results belong.
inventorySha256 string Yes Lowercase 64-character SHA-256 of the trusted inventory bytes.
results DeploymentResult[] Yes Reported task outcomes in increasing per-task/target/placement timestamp order.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Receipt discriminator; currently 1.

Exact inventory owner to which these results belong.

Lowercase 64-character SHA-256 of the trusted inventory bytes.

Reported task outcomes in increasing per-task/target/placement timestamp order.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reported execution evidence bound to a task, inventory and optional destination revision.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentResult {
pluginId: string;
taskId: string;
target?: DeploymentTarget;
status: 'running' | 'succeeded' | 'failed';
recordedAt: string;
actor: string;
evidence: string[];
destinationId?: string;
placementSha256?: string;
}
Name Type Required Description
pluginId string Yes Declared inventory plugin ID.
taskId string Yes Declared plugin task ID.
target DeploymentTarget No Exact environment/tenant target; absent for artifact work.
status 'running' | 'succeeded' | 'failed' Yes Reported running/succeeded/failed result; no independent execution proof is implied.
recordedAt string Yes Exact UTC ISO timestamp including millisecond precision; increases per task/target/placement.
actor string Yes Nonblank host/operator identity reporting the result.
evidence string[] Yes Nonempty distinct nonsecret evidence references, such as reviewed logs or CI receipts. Non-secret evidence references, such as a reviewed log, CI run or lifecycle plan receipt.
destinationId string No Optional explicit destination identity paired with placementSha256; forbidden for artifact results. Environment/tenant evidence bound to a reviewed component placement. Artifact results remain reusable.
placementSha256 string No Hash of reviewed placement/binding revisions paired with destinationId.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Declared inventory plugin ID.

Declared plugin task ID.

Exact environment/tenant target; absent for artifact work.

Reported running/succeeded/failed result; no independent execution proof is implied.

Exact UTC ISO timestamp including millisecond precision; increases per task/target/placement.

Nonblank host/operator identity reporting the result.

Nonempty distinct nonsecret evidence references, such as reviewed logs or CI receipts.

Non-secret evidence references, such as a reviewed log, CI run or lifecycle plan receipt.

Optional explicit destination identity paired with placementSha256; forbidden for artifact results.

Environment/tenant evidence bound to a reviewed component placement. Artifact results remain reusable.

Hash of reviewed placement/binding revisions paired with destinationId.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Nonsecret exact environment, physical placement and optional tenant context for scoped evidence.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentTarget {
environment: string;
backendId?: string;
databaseId?: string;
tenantId?: string;
}
Name Type Required Description
environment string Yes Nonblank deployment environment label.
backendId string No Optional exact lifecycle backend ID; required for database work evidence.
databaseId string No Optional physical database identity; required with backendId for database evidence.
tenantId string No Optional concrete tenant; required for tenant tasks and absent for environment tasks.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Nonblank deployment environment label.

Optional exact lifecycle backend ID; required for database work evidence.

Optional physical database identity; required with backendId for database evidence.

Optional concrete tenant; required for tenant tasks and absent for environment tasks.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Declarative host-approved work and dependency ordering for deployment evidence.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

interface DeploymentTask {
id: string;
componentIds: string[];
action: typeof deploymentActions[number];
scope: 'artifact' | 'environment' | 'tenant';
required: boolean;
dependsOn: string[];
executor: string;
argv?: string[];
instructions?: string;
}
Name Type Required Description
id string Yes Unique task ID within the plugin.
componentIds string[] Yes Existing components whose work this task covers.
action typeof deploymentActions[number] Yes Supported build/test/provision/deploy/etc. phase.
scope 'artifact' | 'environment' | 'tenant' Yes Artifact work is reusable; environment and tenant work require corresponding target evidence.
required boolean Yes Whether successful task evidence is required for completion.
dependsOn string[] Yes Existing task IDs that must succeed before this task is considered unblocked.
executor string Yes Host-approved executor reference; inspection never launches it. Host-approved executor reference. Inspection never executes it or argv.
argv string[] No Optional declarative arguments; never automatically executed by inspection.
instructions string No Optional human operator instructions.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

Unique task ID within the plugin.

Existing components whose work this task covers.

Supported build/test/provision/deploy/etc. phase.

Artifact work is reusable; environment and tenant work require corresponding target evidence.

Whether successful task evidence is required for completion.

Existing task IDs that must succeed before this task is considered unblocked.

Host-approved executor reference; inspection never launches it.

Host-approved executor reference. Inspection never executes it or argv.

Optional declarative arguments; never automatically executed by inspection.

Optional human operator instructions.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Derived task readiness: pending, dependency-blocked, stale evidence, running, succeeded or failed.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

type DeploymentTaskStatus = 'pending' | 'blocked' | 'stale' | 'running' | 'succeeded' | 'failed';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

summarizeDeployment for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported SQL dialects used to select reviewed migration statements.

Imports: @alneas/eaos-server/lifecycle-engine.

type Dialect = 'sqlite' | 'oracle' | 'postgres';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Tenant-scoped business contact/person metadata that never grants authenticated membership.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

interface DirectoryPerson {
id: string;
tenantId: string;
identityId?: string;
name: string;
email?: string;
organizationName?: string;
kinds: readonly PersonKind[];
active: boolean;
}
Name Type Required Description
id string Yes Business person record ID.
tenantId string Yes Tenant owning this directory record.
identityId string No Optional link to a host identity; linkage alone grants no access.
name string Yes Stored display/legal name from explicit or verified creation inputs.
email string No Optional contact address; never used to manufacture a name.
organizationName string No Optional organization display text.
kinds readonly PersonKind[] Yes Business relationship categories, independent of account roles.
active boolean Yes Business directory status, independent of login authorization.

Type declaration; no runtime value.

parseAccountMemberships for canonical integration usage.

Business person record ID.

Tenant owning this directory record.

Optional link to a host identity; linkage alone grants no access.

Stored display/legal name from explicit or verified creation inputs.

Optional contact address; never used to manufacture a name.

Optional organization display text.

Business relationship categories, independent of account roles.

Business directory status, independent of login authorization.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Read or mutate document checks/comments within an already authorized atomic document command.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/annotations.

declare function documentAnnotations(tx: AtomicSession, p: PluginPrincipal, target: AnnotationTarget, operation: string, a: Record<string, any>, now: string): Promise<{
revision: number;
canResolve: boolean;
id: string;
anchorId: string | null;
body: string;
visibility: "private" | "shared";
authorId: string;
createdAt: string;
resolved: boolean;
} | {
cursor?: string | undefined;
checkIds: readonly string[];
checks: Record<string, boolean>;
revision: number;
comments: {
revision: number;
canResolve: boolean;
id: string;
anchorId: string | null;
body: string;
visibility: "private" | "shared";
authorId: string;
createdAt: string;
resolved: boolean;
}[];
} | {
checks: {
[x: string]: boolean;
};
revision: number;
}>;
Name Type Required Description
tx AtomicSession Yes Live tenant-scoped atomic session inside the owner’s atomicCommand.
p PluginPrincipal Yes Verified document reader principal.
target AnnotationTarget Yes Pinned document scope hash and its admitted anchor/check IDs.
operation string Yes One of annotationOperations.
a Record<string, any> Yes Input already validated against the selected annotation schema.
now string Yes Trusted ISO timestamp used for newly created comments.

Promise<{ revision: number; canResolve: boolean; id: string; anchorId: string \| null; body: string; visibility: "private" \| "shared"; authorId: string; createdAt: string; resolved: boolean; } \| { cursor?: string \| undefined; checkIds: readonly string[]; checks: Record<string, boolean>; revision: number; comments: { revision: number; canResolve: boolean; id: string; anchorId: string \| null; body: string; visibility: "private" \| "shared"; authorId: string; createdAt: string; resolved: boolean; }[]; } \| { checks: { [x: string]: boolean; }; revision: number; }>

Operation-specific checks, comment or page data with CAS revisions and optional scoped cursor.

Does not enforce the outer schema or own authorization/transaction/table creation. The owner must authorize the exact document and wrap write operations in atomicCommand; private/shared visibility is scoped by user and document hash.

Rejects invalid scope/cursors, unknown checks/anchors/operations, comment ownership violations, missing comments, capacity or CAS conflicts.

import { documentAnnotations } from '@alneas/eaos-server/plugin-data'
export function readComments(tx: Parameters<typeof documentAnnotations>[0], p: Parameters<typeof documentAnnotations>[1], target: Parameters<typeof documentAnnotations>[2], now: string) { return documentAnnotations(tx, p, target, 'get_annotations', { visibility: 'private' }, now) }

Durable boundary between Micro 2 and an ARM agent runtime.

The store is host-owned and must persist leases, attempts and results. This class owns only one bounded pass; a host scheduler calls runOnce again.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

declare class DurableAgentJobDispatcher {
constructor(options: AgentJobDispatcherOptions);
runOnce(): Promise<AgentJobDispatchResult>;
}
Name Type Required Description
options AgentJobDispatcherOptions Yes Store/worker plus bounded batch, attempt, delay, clock, and completion settings.

DurableAgentJobDispatcher

Jobs execute sequentially within each pass, but concurrent runOnce calls are not serialized here. Leases and admission must be enforced by the host store. Completion callbacks run before markCompleted and can be repeated after retry; make external effects idempotent.

Missing store/worker, batchSize/maxAttempts outside safe integer 1–100, or nonfinite/negative/inverted retry delays.

Claims one batch and executes jobs sequentially, persisting completion, approval wait, retry, or failure.

Returns: Per-outcome counts after all claimed jobs have been processed.

Retry delay is min(maxDelayMs, baseDelayMs * 2^(attempt-1)), using job.attempt + 1 for the attempt calculation. No timer or automatic second pass is installed. Results marked PENDING_APPROVAL do not count as success.

Rejects claim/transition/clock failures; worker errors become retryable failure results. Completion callback/markCompleted errors trigger retry-or-fail handling.

Example:

import { DurableAgentJobDispatcher, type AgentJobDispatcherOptions } from "@alneas/eaos-server/agentic/agent-jobs";
export async function runOnce(options: AgentJobDispatcherOptions) { return new DurableAgentJobDispatcher(options).runOnce(); }
import { DurableAgentJobDispatcher, type AgentJobDispatcherOptions } from "@alneas/eaos-server/agentic/agent-jobs";
export async function dispatch(options: AgentJobDispatcherOptions) {
return new DurableAgentJobDispatcher(options).runOnce();
}

Micro2 controller for dynamic model/runtime allocation.

It selects only host-advertised routes and persists the selected route in the durable job. It never reads a subscription credential or starts a local process. A local-pull route is later claimed by LocalRunnerPullCoordinator.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/ai-broker.

declare class DurableAIExecutionBroker {
constructor(options: {
routes: readonly ServerAIExecutionRoute[];
policyVersion?: string;
now?: () => Date;
});
listRoutes(): readonly ServerAIExecutionRoute[];
decide(request: AIExecutionRequest): AIExecutionDecision;
plan(input: AIJobSubmission): AIJobPlan;
enqueue(tx: AtomicSession, input: AIJobSubmission): Promise<AIJobPlan>;
}
Name Type Required Description
options { routes: readonly ServerAIExecutionRoute[]; policyVersion?: string; now?: () => Date; } Yes Nonempty routes list; optional policyVersion labels selector decisions and now supplies job timestamps, defaulting to fresh Date.

DurableAIExecutionBroker

Route selection and planning are process-local. The host verifies identity and supplies current candidate availability/policy; authorization, runtime execution, and safe retries remain separate responsibilities.

Invalid/missing routes, incompatible local dispatch bindings, core selector validation, or clone failures.

Nonempty host-approved execution routes, validated/cloned before configuring the selector; route IDs and runtime dispatch bindings must be compatible.

Optional decision policy label forwarded to the Core selector; omission selects ai-execution-policy-v1.

Optional clock used when constructing agent job records; omission creates a new current Date per call.

Returns: A valid Date used for planned job timestamps; clock failures propagate from planning.

DurableAIExecutionBroker.plan

Lists registered server route bindings without exposing mutable stored objects.

Returns: Cloned route records in registration map order.

Example:

import { DurableAIExecutionBroker } from "@alneas/eaos-server/agentic/ai-broker";
export function routes(broker: DurableAIExecutionBroker) { return broker.listRoutes(); }

Selects an eligible host-advertised runtime using the core routing policy.

Parameters:

  • request: Verified AI execution requirements and context.

Returns: The core selector decision; no job is persisted or runtime started.

Propagates core routing validation/no-eligible-route errors.

Example:

import { DurableAIExecutionBroker } from "@alneas/eaos-server/agentic/ai-broker";
import type { AIExecutionRequest } from "@alneas/eaos-core";
export function decide(broker: DurableAIExecutionBroker, request: AIExecutionRequest) { return broker.decide(request); }

Selects a route and creates a queue record with host-controlled worker/dispatch/runner bindings.

Parameters:

  • input: Routing and task must have matching tenantId/userId; queue metadata follows AIJobSubmission.

Returns: Decision and newly created job; caller-supplied broker route/dispatch/runner execution fields are stripped before selected bindings are written.

No persistence or deduplication occurs until enqueue; repeated plan calls generate different job IDs.

Principal mismatch, unavailable route, invalid core routing, clone/hash/clock, or job creation failures.

Example:

import { DurableAIExecutionBroker } from "@alneas/eaos-server/agentic/ai-broker";
import type { AIJobSubmission } from "@alneas/eaos-server/agentic/ai-broker";
export function plan(broker: DurableAIExecutionBroker, input: AIJobSubmission) { return broker.plan(input); }

Plans routing and atomically inserts or deduplicates the queue job in a caller-owned session.

Parameters:

  • tx: Authorized atomic transaction/session; caller owns commit/rollback.
  • input: Verified routing/task and queue metadata.

Returns: Decision plus the newly saved or existing idempotent job.

Selection still runs before deduplication; the returned existing job is authoritative for its persisted routing. No runtime execution occurs.

Planning errors, conflicting deduplication input, corrupt index, or session failures.

Example:

import { DurableAIExecutionBroker } from "@alneas/eaos-server/agentic/ai-broker";
import type { AIJobSubmission } from "@alneas/eaos-server/agentic/ai-broker";
import type { AtomicSession } from "@alneas/eaos-server/plugin-data/atomic";
export async function enqueue(broker: DurableAIExecutionBroker, tx: AtomicSession, input: AIJobSubmission) { return broker.enqueue(tx, input); }
import { DurableAIExecutionBroker } from "@alneas/eaos-server/agentic/ai-broker";
export function broker(options: ConstructorParameters<typeof DurableAIExecutionBroker>[0]) {
return new DurableAIExecutionBroker(options);
}

Keeps the business workflow instance synchronized with the LangGraph checkpoint without making either one the other’s database implementation.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-coordinator.

declare class DurableWorkflowCoordinator extends ServerWorkflowManager {
constructor(options: DurableWorkflowCoordinatorOptions);
start(graph: AgentGraphEngine, record: WorkflowInstanceRecord, initialState: AgentGraphState): Promise<AgentGraphState>;
runWorkflow(graph: AgentGraphEngine, initialState: AgentGraphState): Promise<AgentGraphState>;
handleApproval(graph: AgentGraphEngine, payload: ServerApprovalCallbackPayload): Promise<{
resumed: boolean;
state?: AgentGraphState;
error?: string;
}>;
}
Name Type Required Description
options DurableWorkflowCoordinatorOptions Yes Host store, approval notification, and live resume authorization.

DurableWorkflowCoordinator

Checkpoint and companion record updates are separate operations; failures can leave them temporarily divergent. The host owns writer serialization, tenant authorization, durable stores, and reconciliation rather than blind retry after partial outcomes.

If store is missing.

Creates a queued companion instance then runs and persists its graph outcome.

Parameters:

  • graph: Configured graph with appropriate checkpoint persistence.
  • record: Host-admitted instance metadata; instanceId and tenantId must match initialState.
  • initialState: Verified workflow identity and starting state.

Returns: Graph state after execution and companion CAS persistence.

The queued record can exist even if graph execution later fails; no cross-store rollback occurs. Atomic duplicate prevention belongs to store.create.

Rejects alignment mismatch, existing instance, graph/callback/clone/store failures, or companion revision conflict.

Example:

import { DurableWorkflowCoordinator } from "@alneas/eaos-server/agentic/workflow-coordinator";
import type { AgentGraphEngine, AgentGraphState } from "@alneas/eaos-server/agentic/graph";
import type { WorkflowInstanceRecord } from "@alneas/eaos-core";
export async function start(coordinator: DurableWorkflowCoordinator, graph: AgentGraphEngine, record: WorkflowInstanceRecord, state: AgentGraphState) { return coordinator.start(graph, record, state); }

Runs an existing graph instance and CAS-updates its companion status.

Parameters:

  • graph: Graph whose session already has a companion record.
  • initialState: Verified state aligned with that record.

Returns: Graph result after companion persistence; status prioritizes pending approval, error, completion, then running.

Graph/store/clock failures, missing companion, or changed revision; graph checkpoints may already have advanced.

Example:

import { DurableWorkflowCoordinator } from "@alneas/eaos-server/agentic/workflow-coordinator";
import type { AgentGraphEngine, AgentGraphState } from "@alneas/eaos-server/agentic/graph";
export async function run(coordinator: DurableWorkflowCoordinator, graph: AgentGraphEngine, state: AgentGraphState) { return coordinator.runWorkflow(graph, state); }

Resumes a verified graph approval then persists its resulting companion state.

Parameters:

  • graph: Graph owning the pending checkpoint.
  • payload: Host-authenticated approver decision and optional binding checks.

Returns: Resume outcome; companion persistence failure becomes resumed:false error data even when graph resume already succeeded.

A false result does not prove no side effects occurred; reconcile graph and companion state before retrying.

Underlying graph/store failures outside normalized resume/persistence handling may reject.

Example:

import { DurableWorkflowCoordinator } from "@alneas/eaos-server/agentic/workflow-coordinator";
import type { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
import type { ServerApprovalCallbackPayload } from "@alneas/eaos-server/agentic/types";
export async function approve(coordinator: DurableWorkflowCoordinator, graph: AgentGraphEngine, payload: ServerApprovalCallbackPayload) { return coordinator.handleApproval(graph, payload); }

True only when graph resumption and companion-instance persistence complete; false may also mean companion persistence failed after the graph advanced.

Optional resumed graph state returned when companion persistence succeeds; omitted when companion persistence is normalized into failure data.

Optional graph resume or companion persistence failure detail; reconcile both stores before retrying because graph effects may already have completed.

import { DurableWorkflowCoordinator } from "@alneas/eaos-server/agentic/workflow-coordinator";
import type { DurableWorkflowCoordinatorOptions } from "@alneas/eaos-server/agentic/workflow-coordinator";
export function coordinator(options: DurableWorkflowCoordinatorOptions) { return new DurableWorkflowCoordinator(options); }

[INTERFACE] DurableWorkflowCoordinatorOptions

Section titled “[INTERFACE] DurableWorkflowCoordinatorOptions”

Workflow notification/approval callbacks plus durable companion-instance storage.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-coordinator.

interface DurableWorkflowCoordinatorOptions extends ServerWorkflowOptions {
store: WorkflowInstanceStore;
}
Name Type Required Description
store WorkflowInstanceStore Yes Host-authorized tenant-scoped store with atomic create and revision checks.

Type declaration; no runtime value.

DurableWorkflowCoordinator.

Host-authorized tenant-scoped store with atomic create and revision checks.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Engine composition settings retained by ErpEngine; host adapters own authentication and persistence.

Imports: @alneas/eaos-server, @alneas/eaos-server/engine.

interface EaosConfig {
appName: string;
plugins: PluginManifest[];
theme?: {
primaryColor?: string;
logoUrl?: string;
};
database?: {
driver: 'oracle' | 'supabase' | 'postgres';
};
cors?: {
allowOrigins: string[];
};
auth?: {
verifier?: AuthSessionVerifier;
skipPaths?: string[];
};
validateSecrets?: boolean;
middleware?: Array<(app: Hono<EaosEnv>) => void>;
}
Name Type Required Description
appName string Yes Nonblank application label used by public health responses.
plugins PluginManifest[] Yes Trusted plugin manifests registered sequentially during initialize.
theme { primaryColor?: string; logoUrl?: string; } No Optional host UI theme metadata retained in config; the server engine does not apply it.
database { driver: 'oracle' | 'supabase' | 'postgres'; } No Optional host driver metadata retained in config; this engine does not create a database connection.
cors { allowOrigins: string[]; } No Optional exact browser allowOrigins list; empty/absent disables CORS middleware.
auth { verifier?: AuthSessionVerifier; skipPaths?: string[]; } No Optional verifier and skipped path prefixes; see AuthMiddlewareOptions.
validateSecrets boolean No Validate each manifest’s declared secrets unless exactly false. Defaults to true.
middleware Array<(app: Hono<EaosEnv>) => void> No Host composition callbacks invoked synchronously after shared authentication and before plugin route guards; each receives the app and returns no value.

Type declaration; no runtime value.

Nonblank application label used by public health responses.

Trusted plugin manifests registered sequentially during initialize.

Optional host UI theme metadata retained in config; the server engine does not apply it.

Optional host UI accent color; not interpreted by this engine.

Optional host UI logo URL; not fetched by this engine.

Optional host driver metadata retained in config; this engine does not create a database connection.

Selected host database dialect; does not create or migrate a connection.

Optional exact browser allowOrigins list; empty/absent disables CORS middleware.

Exact allowed browser origins; credentials are enabled for configured CORS.

Optional verifier and skipped path prefixes; see AuthMiddlewareOptions.

Optional verified session/API-key adapter; omission installs no authentication.

Authentication-exempt path prefixes; defaults follow createAuthMiddleware.

Validate each manifest’s declared secrets unless exactly false. Defaults to true.

Host composition callbacks invoked synchronously after shared authentication and before plugin route guards; each receives the app and returns no value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Creates independent empty platform tenant, placement and migration maps.

Imports: @alneas/eaos-server/lifecycle-engine.

declare const emptyLifecyclePlatformState: () => LifecyclePlatformState;
Name Type Required Description
— — — No call parameters.

LifecyclePlatformState

A new mutable platform-state object.

import { emptyLifecyclePlatformState } from '@alneas/eaos-server/lifecycle-engine';
const platform = emptyLifecyclePlatformState();

Creates an independent empty version-1 ledger with revision zero and platform state.

Imports: @alneas/eaos-server/lifecycle-engine.

declare const emptyLifecycleState: () => LifecycleState;
Name Type Required Description
— — — No call parameters.

LifecycleState

A new mutable LifecycleState with empty maps; no persistence is performed.

import { emptyLifecycleState } from '@alneas/eaos-server/lifecycle-engine';
const state = emptyLifecycleState();

Persists a job and tenant/kind/idempotency index in the caller’s atomic transaction.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-jobs.

declare function enqueueAgentJob(tx: AtomicSession, job: AgentJobRecord<ServerAgentTaskRequest>): Promise<AgentJobRecord<ServerAgentTaskRequest>>;
Name Type Required Description
tx AtomicSession Yes Authorized active atomic session; the caller owns commit/rollback.
job AgentJobRecord<ServerAgentTaskRequest> Yes Created job whose tenant/kind/key define deduplication and whose requestHash binds input.

Promise<AgentJobRecord<ServerAgentTaskRequest>>

A clone of the saved job, or existing indexed job when its request hash matches; existing lifecycle state is preserved.

This helper neither executes the job nor opens a transaction; host transaction isolation/CAS must prevent concurrent index creation races.

Reused idempotency key with a different request hash, missing indexed job, or propagated transaction/clone errors.

import { enqueueAgentJob, createAgentJob } from "@alneas/eaos-server/agentic/agent-jobs";
import type { AtomicSession } from "@alneas/eaos-server/plugin-data/atomic";
import type { ServerAgentTaskRequest } from "@alneas/eaos-server/agentic/types";
export async function enqueue(tx: AtomicSession, request: ServerAgentTaskRequest) {
return enqueueAgentJob(tx, createAgentJob({ request, kind: "workflow" }));
}

Closed schema for a new approved delivery request with stable command/job/target/content identities.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

declare const enqueueDeliverySchema: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
commandId: {
type: string;
pattern: string;
};
jobId: {
type: string;
pattern: string;
};
channel: {
type: string;
pattern: string;
};
kind: {
enum: string[];
};
target: {
type: string;
maxProperties: number;
additionalProperties: boolean;
};
contentHash: {
type: string;
pattern: string;
};
approvalRequestId: {
type: string;
pattern: string;
};
};
};
Name Type Required Description
— — — No call parameters.

Declared constant value.

ArtifactDeliveryService for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Insert or replay one immutable Outbox event inside the same transaction as its domain write.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

declare function enqueueOutboxEvent<T>(tx: AtomicSession, input: OutboxEventInput<T>): Promise<OutboxEvent<T>>;
Name Type Required Description
tx AtomicSession Yes Live tenant-scoped atomic session.
input OutboxEventInput<T> Yes Canonical event input with stable tenant, topic and idempotency identity.

Promise<OutboxEvent<T>>

A cloned new event or the matching existing event.

  • T: JSON-serializable event payload type.

Does not deliver externally; the host scheduler and idempotent handler process the committed event later.

Rejects invalid event input, conflicting idempotency input or transaction failures.

import { enqueueOutboxEvent } from '@alneas/eaos-server/plugin-data'
export function enqueue<T>(tx: Parameters<typeof enqueueOutboxEvent>[0], input: Parameters<typeof enqueueOutboxEvent<T>>[1]) { return enqueueOutboxEvent(tx, input) }

Carries a denied entitlement decision for HTTP or host failure handling.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare class EntitlementError extends Error {
readonly decision: Exclude<EntitlementDecision, {
allowed: true;
}>;
constructor(decision: Exclude<EntitlementDecision, {
allowed: true;
}>);
}
Name Type Required Description
decision Exclude<EntitlementDecision, { allowed: true; }> Yes Denied decision retained as a public readonly property for status/reason mapping.

EntitlementError

Type-level allowed-branch discriminator removed by Exclude; this constructor accepts only denied decisions with allowed false.

import { EntitlementError } from "@alneas/eaos-server/entitlements";
const error = new EntitlementError({ allowed: false, status: 402, reason: "quota-exceeded" });
console.log(error.decision.status);

Host callback resolving authenticated user/tenant membership from a request.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

type EntitlementPrincipalResolver = (context: Context) => Promise<PlatformPrincipal | null>;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

Verified platform principal, or null to deny authentication.

Host failures propagate through request handling.

createPluginEntitlementGuard for usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted control-plane reads, lifecycle policy, and reservation persistence for PluginEntitlementRuntime.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

interface EntitlementRuntimeOptions {
repository: AtomicRepository;
load: (tenantId: string) => Promise<TenantEntitlements | null>;
loadInTransaction?: (principal: PlatformPrincipal, session: AtomicSession) => Promise<TenantEntitlements | null>;
isActive: (principal: PlatformPrincipal, pluginId: string) => Promise<boolean>;
clock?: () => Date;
}
Name Type Required Description
repository AtomicRepository Yes Shared durable control-plane repository, with transaction/CAS and tenant isolation.
load (tenantId: string) => Promise<TenantEntitlements | null> Yes Read current contracts from eaos_tenant_entitlements; never from request headers/body.
loadInTransaction (principal: PlatformPrincipal, session: AtomicSession) => Promise<TenantEntitlements | null> No Optional joined control-plane read; quota and contract observe the same host transaction.
isActive (principal: PlatformPrincipal, pluginId: string) => Promise<boolean> Yes Same live lifecycle admission for HTTP, MCP, jobs, webhooks and asset delivery.
clock () => Date No Clock for validity and UTC monthly metering period; defaults to a fresh Date per read.

Type declaration; no runtime value.

Shared durable control-plane repository, with transaction/CAS and tenant isolation.

Read current contracts from eaos_tenant_entitlements; never from request headers/body.

Optional joined control-plane read; quota and contract observe the same host transaction.

Same live lifecycle admission for HTTP, MCP, jobs, webhooks and asset delivery.

Clock for validity and UTC monthly metering period; defaults to a fresh Date per read.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Registers plugin manifests and composes Hono routes with host authentication, entitlement, and lifecycle adapters.

Imports: @alneas/eaos-server, @alneas/eaos-server/engine.

declare class ErpEngine {
readonly registry: PluginRegistry;
readonly gatekeeper: McpGatekeeper;
constructor(config: EaosConfig);
initialize(): Promise<void>;
createApp(options?: CreateAppOptions): Hono<EaosEnv>;
getRegisteredPlugins(): PluginManifest[];
getAllMcpTools(): _alneas_eaos_core.McpToolDefinition[];
getConfig(): EaosConfig;
}
Name Type Required Description
config EaosConfig Yes App label, plugin manifests, and optional host composition settings.

ErpEngine

Constructing the engine creates no HTTP listener or persistent store. Initialize once before composing apps. Configuration is retained by reference. Authentication is installed only when a verifier is supplied; custom routes need their own authorization policies beyond the shared middleware.

Public plugin registry populated during initialize; external mutation affects subsequently composed apps.

Shared MCP policy registry populated from plugin manifests during initialize.

Registers manifests and gatekeeper policies and validates declared plugin secrets by default.

Returns: No value; resolves after registration and validation, or immediately after a prior successful initialization.

Registration occurs before secret validation, so failure can leave partial registry state. Concurrent initialization is not serialized and retrying a failed initialization may encounter already-registered IDs. Create a new engine after correcting failed setup. No migrations or plugin activation are performed.

Rejects duplicate plugin IDs, registry failures, or secret validation failures.

Example:

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
console.log(engine.getRegisteredPlugins().length); // 0

Composes registered plugin routes, shared middleware, optional MCP/custom routes, and public health endpoints.

Parameters:

Returns: A new Hono app sharing this engine registry, gatekeeper, and configured adapters; it does not start a server.

Module guarding defaults on. Lifecycle enforcement is installed only when supplied, while declared plugin entitlements require their corresponding runtime checks. CORS uses configured origins with credentials enabled; unknown origins receive the first configured allow-origin value. Repeated calls create separate routers but may reuse host dependencies.

Before initialization, or for synchronous middleware, plugin route factory, or health setup failures. Request-time adapter errors pass through the app error handler.

Example:

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
const app = engine.createApp();
console.log((await app.request("/health/live")).status);

Reads the manifests currently registered in this engine.

Returns: Registry manifest list, empty before registration or with no configured plugins; objects are not deep-cloned by this method.

Example:

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
console.log(engine.getRegisteredPlugins()); // []

Collects MCP tool definitions from all currently registered manifests.

Returns: Registry tool definitions, or an empty array when none exist; this list is not filtered for a request principal or tenant.

Example:

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
console.log(engine.getAllMcpTools()); // []

Reads the host configuration retained at construction.

Returns: The original mutable configuration object; no cloning occurs.

Example:

import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
console.log(engine.getConfig().appName);
import { createErpEngine } from "@alneas/eaos-server/engine";
const engine = createErpEngine({ appName: "example-service", plugins: [] });
await engine.initialize();
const app = engine.createApp();
console.log((await app.request("/health/live")).status); // 200

Controls error response redaction and logging for createErrorHandler.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/error-handler.

interface ErrorHandlerOptions {
isProduction?: boolean;
logger?: (err: Error, c: Context) => void;
}
Name Type Required Description
isProduction boolean No Hide message and stack when true; defaults to NODE_ENV === “production”.
logger (err: Error, c: Context) => void No Called synchronously with the original error and request context before rendering; defaults to console.error. A thrown logger error propagates.

Type declaration; no runtime value.

Hide message and stack when true; defaults to NODE_ENV === “production”.

Called synchronously with the original error and request context before rendering; defaults to console.error. A thrown logger error propagates.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Converts subscribed domain events into bounded local execution or host-persisted agent work.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

declare class EventAgentBridge {
constructor(eventBus: DomainEventBus, worker: ServerAutonomousWorker, options?: EventAgentBridgeOptions);
withDurableTaskStore(store: EventAgentTaskStore): this;
runDurableOnce(limit?: number): Promise<{
claimed: number;
completed: number;
failed: number;
}>;
registerRule(rule: EventAgentRule): () => void;
whenIdle(): Promise<void>;
}
Name Type Required Description
eventBus DomainEventBus Yes Host domain bus; subscriptions begin only on registerRule.
worker ServerAutonomousWorker Yes Host worker performing gatekeeper/runtime execution.
options EventAgentBridgeOptions No Queue limits, notification/error callbacks, and optional durable store.

EventAgentBridge

Without taskStore, accepted work is process-local and can be lost on restart. With taskStore, the host explicitly calls runDurableOnce; event subscription callbacks still do not await durable persistence from the publisher’s perspective. Authorize identity in createTask before creating specifications. Generated task IDs/idempotency defaults are per emission, so repeated events are not automatically deduplicated. Dispose every registerRule callback to release subscriptions; no global destroy is provided.

Invalid limits or malformed durable store.

Persisted event work is deliberately drained by the host scheduler. The bridge never treats its in-memory queue as a durable workflow checkpoint.

Parameters:

  • store: Host durable queue with enqueue/claim/complete/fail functions.

Returns: This bridge after replacing its store reference.

Existing local queued work is not migrated by changing this store.

Missing/malformed store functions.

Example:

import { EventAgentBridge } from "@alneas/eaos-server/agentic/event-bridge";
import type { EventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
export function persist(bridge: EventAgentBridge, store: EventAgentTaskStore) { return bridge.withDurableTaskStore(store); }

Claims one bounded durable batch and processes it sequentially.

Parameters:

  • limit: Safe integer 1–maxConcurrent; defaults to maxConcurrent.

Returns: Claim/completion/failure persistence counts; a worker FAILED result counts completed if stored successfully.

Calls are not globally serialized. Notification failures are reported after result persistence. No periodic scheduler or automatic retry is installed.

Missing store, invalid limit, claim/fail persistence errors, or synchronous error-sink errors.

Example:

import { EventAgentBridge } from "@alneas/eaos-server/agentic/event-bridge";
export async function drain(bridge: EventAgentBridge) { return bridge.runDurableOnce(); }

Number of queued tasks returned by the host claim for this pass, including tasks later recorded as completed or failed.

Number of task results successfully passed to store.complete; a returned worker FAILED or PENDING_APPROVAL status still counts when its result is stored.

Number of worker throws or store.complete failures handled through store.fail; this counts persistence/execution handling failures rather than every returned worker FAILED status.

Subscribes a task-conversion rule and returns its individual unsubscribe callback.

Parameters:

  • rule: Exact event name and synchronous createTask callback; callback receives payload and returns verified task fields or null to skip.

Returns: A no-argument callback returning no value; removes this rule and unsubscribes the bus handler when no rules remain.

The rule is retained by reference; do not mutate its eventName after registration. Already accepted tasks keep running after unsubscribe.

Event bus subscription/unsubscription errors can propagate. Event conversion errors are reported through onError.

Example:

import { EventAgentBridge } from "@alneas/eaos-server/agentic/event-bridge";
import type { EventAgentRule } from "@alneas/eaos-server/agentic/event-bridge";
export function listen(bridge: EventAgentBridge, rule: EventAgentRule) { return bridge.registerRule(rule); }

Waits until the bridge’s local active count and waiting queue are empty.

Returns: No value; resolves when local work is idle. It does not wait for durable queue persistence/draining or asynchronous error sinks.

Polls with zero-delay timers and has no timeout/cancellation; continuously arriving work can delay completion indefinitely.

Example:

import { EventAgentBridge } from "@alneas/eaos-server/agentic/event-bridge";
export async function idle(bridge: EventAgentBridge) { await bridge.whenIdle(); }
import { EventAgentBridge } from "@alneas/eaos-server/agentic/event-bridge";
import type { DomainEventBus } from "@alneas/eaos-core";
import type { ServerAutonomousWorker } from "@alneas/eaos-server/agentic/autonomous-worker";
export function bridge(eventBus: DomainEventBus, worker: ServerAutonomousWorker) { return new EventAgentBridge(eventBus, worker); }

Host error/audit notification for event conversion, queueing, execution, result, or approval delivery.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface EventAgentBridgeError {
eventName: string;
taskId?: string;
phase: 'createTask' | 'queue' | 'runTask' | 'result' | 'notification';
error: unknown;
result?: ServerAgentTaskResult;
}
Name Type Required Description
eventName string Yes Domain event associated with the failure.
taskId string No Optional generated task identifier, absent before task creation.
phase 'createTask' | 'queue' | 'runTask' | 'result' | 'notification' Yes Stage where the failure was observed.
error unknown Yes Original failure value, which may not be an Error.
result ServerAgentTaskResult No Optional normalized task result associated with the failure.

Type declaration; no runtime value.

EventAgentBridgeOptions.onError.

Domain event associated with the failure.

Optional generated task identifier, absent before task creation.

Stage where the failure was observed.

Original failure value, which may not be an Error.

Optional normalized task result associated with the failure.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

In-process backpressure, host notifications, and optional durable delivery for EventAgentBridge.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface EventAgentBridgeOptions {
maxConcurrent?: number;
maxQueueSize?: number;
onPendingApproval?: (pending: EventAgentPendingApproval) => Promise<void> | void;
onError?: (error: EventAgentBridgeError) => Promise<void> | void;
taskStore?: EventAgentTaskStore;
}
Name Type Required Description
maxConcurrent number No In-process worker concurrency, safe integer 1–1024. Defaults to 1; durable run passes use this as their claim ceiling but are not globally serialized.
maxQueueSize number No In-process waiting queue ceiling while workers are fully occupied, safe integer 0–1000000. Defaults to 100.
onPendingApproval (pending: EventAgentPendingApproval) => Promise<void> | void No Host-owned notification/audit sink for approval requests.
onError (error: EventAgentBridgeError) => Promise<void> | void No Host error/audit sink; returned Promise rejection is logged. Keep the callback itself nonthrowing because synchronous errors can escape reporting.
taskStore EventAgentTaskStore No Optional host-owned durable queue. When set, events are persisted until runDurableOnce drains them.

Type declaration; no runtime value.

In-process worker concurrency, safe integer 1–1024. Defaults to 1; durable run passes use this as their claim ceiling but are not globally serialized.

In-process waiting queue ceiling while workers are fully occupied, safe integer 0–1000000. Defaults to 100.

Host-owned notification/audit sink for approval requests.

Host error/audit sink; returned Promise rejection is logged. Keep the callback itself nonthrowing because synchronous errors can escape reporting.

Optional host-owned durable queue. When set, events are persisted until runDurableOnce drains them.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Event, generated task, and pending result delivered to the host approval sink.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface EventAgentPendingApproval {
eventName: string;
payload: unknown;
task: ServerAgentTaskRequest;
result: ServerAgentTaskResult;
}
Name Type Required Description
eventName string Yes Originating domain event name.
payload unknown Yes Original event payload (cloned when durable queue mode is used).
task ServerAgentTaskRequest Yes Generated verified task whose runtime requested approval.
result ServerAgentTaskResult Yes PENDING_APPROVAL result; the host must persist/deliver the approval request.

Type declaration; no runtime value.

EventAgentBridgeOptions.onPendingApproval.

Originating domain event name.

Original event payload (cloned when durable queue mode is used).

Generated verified task whose runtime requested approval.

PENDING_APPROVAL result; the host must persist/deliver the approval request.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Maps one domain event name to a verified host task specification.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface EventAgentRule {
eventName: string;
createTask: (payload: unknown) => Omit<ServerAgentTaskRequest, 'id'> | null;
}
Name Type Required Description
eventName string Yes Exact domain event name to subscribe to.
createTask (payload: unknown) => Omit<ServerAgentTaskRequest, 'id'> | null Yes Filter or build task request from domain event payload. Return null to skip.

Type declaration; no runtime value.

EventAgentBridge.registerRule.

Exact domain event name to subscribe to.

Filter or build task request from domain event payload. Return null to skip.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-owned durable queue for event-triggered agent work.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface EventAgentTaskStore {
enqueue(task: QueuedEventTask): Promise<void>;
claim(limit: number): Promise<readonly QueuedEventTask[]>;
complete(taskId: string, result: ServerAgentTaskResult): Promise<void>;
fail(taskId: string, error: unknown): Promise<void>;
}
Name Type Required Description
enqueue Promise<void> Yes Persists accepted event work before a scheduler drains it.
claim Promise<readonly QueuedEventTask[]> Yes Exclusively claims work for one drain pass.
complete Promise<void> Yes Persists the normalized result for a claimed task.
fail Promise<void> Yes Records or handles a claimed execution/persistence failure.

Type declaration; no runtime value.

EventAgentBridge.withDurableTaskStore for usage.

Persists accepted event work before a scheduler drains it.

Parameters:

  • task: Verified generated task and cloneable event payload.

Returns: No value; resolves after host persistence.

Queue failures propagate to bridge error reporting.

Example:

import type { EventAgentTaskStore } from "@alneas/eaos-server";
export async function enqueueAdmittedEventTask(
store: EventAgentTaskStore, task: Parameters<EventAgentTaskStore["enqueue"]>[0],
) {
// Host admission and the event-to-task mapping run before queue insertion.
await store.enqueue(task);
}

Exclusively claims work for one drain pass.

Parameters:

  • limit: Requested maximum item count.

Returns: Claimed queue items, or an empty array.

Queue failures reject the drain pass.

Example:

import type { EventAgentTaskStore } from "@alneas/eaos-server";
export async function claimEventTasks(store: EventAgentTaskStore) {
const tasks = await store.claim(10);
return tasks; // Empty when no eligible tasks are available.
}

Persists the normalized result for a claimed task.

Parameters:

  • taskId: Claimed task identifier.
  • result: Runtime outcome, including failed/pending statuses.

Returns: No value; resolves after persistence.

Completion failure causes the bridge to call fail.

Example:

import type { EventAgentTaskStore } from "@alneas/eaos-server";
export async function completeEventTask(
store: EventAgentTaskStore, claimedTaskId: string,
result: Parameters<EventAgentTaskStore["complete"]>[1],
) {
await store.complete(claimedTaskId, result);
// The host decides persistence and result retention for this queue.
}

Records or handles a claimed execution/persistence failure.

Parameters:

  • taskId: Claimed task identifier.
  • error: Underlying execution or completion failure.

Returns: No value; completion/retry semantics belong to the host store.

Failures reject the drain pass.

Example:

import type { EventAgentTaskStore } from "@alneas/eaos-server";
export async function recordEventTaskFailure(
store: EventAgentTaskStore, claimedTaskId: string, observedError: unknown,
) {
await store.fail(claimedTaskId, observedError);
// Failure/retry policy belongs to the host store; this does not retry execution.
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reject top-level object keys not present in an explicit operation allowlist.

Imports: @alneas/eaos-server/plugin-data.

declare function exactKeys(value: object, keys: string[]): void;
Name Type Required Description
value object Yes Object whose own enumerable string keys are inspected.
keys string[] Yes Trusted allowed top-level key names.

void

No value when all existing keys are allowed.

Does not require listed keys to exist or validate nested fields.

Throws PluginError 400 when an unknown key is present.

import { exactKeys } from '@alneas/eaos-server/plugin-data'
exactKeys({ title: 'Example' }, ['title'])

Authenticated host identity supplied to createPluginExecutionRouter.

Imports: @alneas/eaos-server/execution.

interface ExecutionIdentity {
tenantId: string;
userId: string;
}
Name Type Required Description
tenantId string Yes Nonblank verified tenant ID.
userId string Yes Nonblank verified user ID.

Type declaration; no runtime value.

Nonblank verified tenant ID.

Nonblank verified user ID.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Single control-plane filesystem. All backend processes must read the same ledger. A crashed writer leaves its lock in place: reconcile DB/infra before operator recovery. For independent hosts, implement LifecycleStore using a shared transactional control DB.

Imports: @alneas/eaos-server/lifecycle.

declare class FileLifecycleStore implements LifecycleStore {
readonly path: string;
constructor(path: string);
read(): Promise<LifecycleState>;
withLock<T>(fn: (writer: LifecycleWriter) => Promise<T>): Promise<T>;
}
Name Type Required Description
path string Yes Ledger filename, resolved relative to the current process directory.

FileLifecycleStore

Absolute ledger path resolved at construction; lock directory is path + “.lock”.

Reads and normalizes the JSON lifecycle ledger.

Returns: Stored lifecycle state, or a fresh empty state if the file does not exist.

Rejects filesystem, JSON parsing, or state-normalization failures other than ENOENT.

Example:

import { FileLifecycleStore } from "@alneas/eaos-server/lifecycle";
const state = await new FileLifecycleStore("./state/lifecycle.json").read();
console.log(state.platform);

Runs one writer callback under an exclusive filesystem lock directory.

Parameters:

  • fn: Called after lock acquisition with ledger read and durable write operations; must await its writes before returning.

Returns: The callback result after lock directory removal. Writer.write resolves without a value after temporary-file fsync, rename, and directory fsync.

  • T: Callback result passed through unchanged.

Lock acquisition does not wait or retry. Ordinary callback failure removes the lock; a process crash can leave it behind and requires operator reconciliation. Writes may have committed before a later failure. The store does not enforce that all external writers use this lock.

Rejects an existing lock, filesystem failures, callback failures, or final lock-removal failures.

Example:

import { FileLifecycleStore } from "@alneas/eaos-server/lifecycle";
const store = new FileLifecycleStore("./state/lifecycle.json");
const state = await store.withLock(async writer => writer.read());
console.log(state.platform);
import { FileLifecycleStore } from "@alneas/eaos-server/lifecycle";
const store = new FileLifecycleStore("./state/lifecycle.json");
console.log((await store.read()).platform);

Installed server package version used as the default lifecycle compatibility version.

Imports: @alneas/eaos-server/lifecycle-engine.

declare const FRAMEWORK_VERSION: string;
Name Type Required Description
— — — No call parameters.

Declared constant value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/platform.

interface GatekeeperAuditEntry {
id: string;
traceId?: string;
toolName: string;
userId: string;
tenantId: string;
status: 'ALLOWED' | 'BLOCKED' | 'PENDING_APPROVAL';
riskLevel: RiskLevel;
approvalLevel: ApprovalLevel;
reason?: string;
evidence?: {
intent?: string;
confidence?: number;
ruleMatched?: string;
inputSummary?: string;
};
hash: string;
previousHash?: string;
timestamp: string;
args?: Record<string, unknown>;
}
Name Type Required Description
id string Yes See the upstream owning declaration.
traceId string No See the upstream owning declaration.
toolName string Yes See the upstream owning declaration.
userId string Yes See the upstream owning declaration.
tenantId string Yes See the upstream owning declaration.
status 'ALLOWED' | 'BLOCKED' | 'PENDING_APPROVAL' Yes See the upstream owning declaration.
riskLevel RiskLevel Yes See the upstream owning declaration.
approvalLevel ApprovalLevel Yes See the upstream owning declaration.
reason string No See the upstream owning declaration.
evidence { intent?: string; confidence?: number; ruleMatched?: string; inputSummary?: string; } No See the upstream owning declaration.
hash string Yes See the upstream owning declaration.
previousHash string No See the upstream owning declaration.
timestamp string Yes See the upstream owning declaration.
args Record<string, unknown> No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reads a structurally valid host authorization port from Hono context or server environment.

Imports: @alneas/eaos-server/extensions.

declare function getPlatformPluginAuthorization(context: unknown): PlatformPluginAuthorization | undefined;
Name Type Required Description
context unknown Yes Hono-like context; get(bindingKey) takes precedence over env[bindingKey] when nonnull. Missing contexts return undefined.

PlatformPluginAuthorization \| undefined

The original port when both required members are functions, or undefined otherwise.

Hono environment forwarding is internal-only; HTTP headers never supply this binding. Structural validation does not establish trust: only host middleware may install it.

Propagates errors thrown by the context get accessor.

import { Hono } from "hono";
import { getPlatformPluginAuthorization } from "@alneas/eaos-server/extensions";
const app = new Hono();
app.get("/authorization-state", c => c.json({ configured: !!getPlatformPluginAuthorization(c) }));

Host-verified human decision supplied to a pending graph approval.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface GraphApprovalDecision {
approved: boolean;
approverId: string;
approverRole: string;
comment?: string;
}
Name Type Required Description
approved boolean Yes True to continue; false to finish with a rejection error.
approverId string Yes Authenticated human approver identifier.
approverRole string Yes Verified role associated with the decision.
comment string No Optional human note; rejection uses a default description when blank.

Type declaration; no runtime value.

AgentGraphEngine.resumeAfterApproval.

True to continue; false to finish with a rejection error.

Authenticated human approver identifier.

Verified role associated with the decision.

Optional human note; rejection uses a default description when blank.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Display metadata for declared branches in AgentGraphEngine.addConditionalEdges.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface GraphConditionalEdgeOptions extends GraphEdgeOptions {
labels?: Readonly<Record<string, string>>;
}
Name Type Required Description
labels Readonly<Record<string, string>> No Per-destination labels such as approved or needs_correction.

Type declaration; no runtime value.

Per-destination labels such as approved or needs_correction.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Serializable display metadata for AgentGraphEngine.addEdge.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface GraphEdgeOptions {
visual?: WorkflowGraphEdgeInput;
}
Name Type Required Description
visual WorkflowGraphEdgeInput No Serializable metadata used by workflow viewers; never executed.

Type declaration; no runtime value.

Serializable metadata used by workflow viewers; never executed.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Async node operation receiving an isolated graph-state clone and returning partial state updates.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

type GraphNodeHandler = (state: AgentGraphState) => Promise<Partial<AgentGraphState>>;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

Partial update; context is merged, while supplied history replaces the existing history.

Handler failures propagate through LangGraph retry policy and graph execution.

AgentGraphEngine.addNode for a complete example.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Execution retry and display settings for AgentGraphEngine.addNode.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface GraphNodeOptions {
retryPolicy?: RetryPolicy;
visual?: WorkflowGraphNodeInput;
}
Name Type Required Description
retryPolicy RetryPolicy No Optional LangGraph retry settings; retries can repeat handler side effects and must be safe by host design.
visual WorkflowGraphNodeInput No Serializable metadata used by workflow viewers; never executed.

Type declaration; no runtime value.

Optional LangGraph retry settings; retries can repeat handler side effects and must be safe by host design.

Serializable metadata used by workflow viewers; never executed.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Applies domain events to an ADB Graph/PGQL or other relationship read model.

The coordinator is intentionally independent of Oracle. The host supplies the adapter and cursor store, so credentials, graph schema and transaction policy never enter core/server.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph-projection.

declare class GraphProjectionCoordinator {
constructor(options: GraphProjectionCoordinatorOptions);
apply(event: Readonly<WorkflowEventEnvelope>): Promise<void>;
rebuild(tenantId: string, sourceRevision: number, snapshot: unknown): Promise<void>;
}
Name Type Required Description
options GraphProjectionCoordinatorOptions Yes Host projection dependencies.

GraphProjectionCoordinator

Calls are not serialized by this class. The host must coordinate writers/rebuilds, authorize tenant data, and make adapter replay safe. Adapter changes and cursor writes are separate operations; a cursor failure can leave projection data applied but unacknowledged.

If projectionId is blank or adapter/cursorStore is absent.

Applies one event and records projection progress, skipping recognized duplicate/stale events.

Parameters:

  • event: Trusted workflow event envelope; the adapter receives a structured clone.

Returns: No value; resolves after application and cursor persistence or immediately for the last event ID or a nonincreasing revision of the last aggregate.

A revision gap for the last aggregate increments lagCount and records lagging but still applies the event. Deduplication covers only the last event/aggregate cursor, not full history. Failure may occur after adapter side effects; no rollback or retry occurs here.

Rejects rebuilding state, cursor/clock/clone failures, or adapter failures. Adapter failure attempts a failed cursor write, which can itself replace the original error.

Example:

import { GraphProjectionCoordinator, type GraphProjectionCoordinatorOptions } from "@alneas/eaos-server/agentic/graph-projection";
import type { WorkflowEventEnvelope } from "@alneas/eaos-core";
export async function apply(options: GraphProjectionCoordinatorOptions, event: WorkflowEventEnvelope) {
await new GraphProjectionCoordinator(options).apply(event);
}

Marks a tenant projection rebuilding, delegates snapshot replacement, then records healthy or failed state.

Parameters:

  • tenantId: Verified tenant whose relationship model is rebuilt.
  • sourceRevision: Host source revision copied to the rebuilt cursor; not validated by this coordinator.
  • snapshot: Host-authorized snapshot cloned before passing to the adapter.

Returns: No value; resolves after adapter rebuild and healthy cursor persistence.

No cancellation or exclusive lock is acquired. The host must serialize rebuild/application and determine recovery after partial adapter or cursor failure.

Rejects clock, cursor, clone, or adapter failures; a failed-status write can replace an earlier failure.

Example:

import { GraphProjectionCoordinator, type GraphProjectionCoordinatorOptions } from "@alneas/eaos-server/agentic/graph-projection";
export async function rebuild(options: GraphProjectionCoordinatorOptions, tenantId: string, revision: number, snapshot: unknown) {
await new GraphProjectionCoordinator(options).rebuild(tenantId, revision, snapshot);
}
import { GraphProjectionCoordinator, type GraphProjectionCoordinatorOptions } from "@alneas/eaos-server/agentic/graph-projection";
export function projection(options: GraphProjectionCoordinatorOptions) {
return new GraphProjectionCoordinator(options);
}

[INTERFACE] GraphProjectionCoordinatorOptions

Section titled “[INTERFACE] GraphProjectionCoordinatorOptions”

Host projection adapter, cursor persistence, and clock for GraphProjectionCoordinator.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph-projection.

interface GraphProjectionCoordinatorOptions {
projectionId: string;
adapter: GraphProjectionAdapter;
cursorStore: ProjectionCursorStore;
now?: () => Date;
}
Name Type Required Description
projectionId string Yes Nonblank projection identifier; retained exactly without trimming.
adapter GraphProjectionAdapter Yes Host relationship-model adapter; must define idempotency and transaction policy.
cursorStore ProjectionCursorStore Yes Host cursor persistence, separate from adapter transactions unless the host coordinates them.
now () => Date No Clock for ISO progress timestamps; defaults to a fresh Date.

Type declaration; no runtime value.

Nonblank projection identifier; retained exactly without trimming.

Host relationship-model adapter; must define idempotency and transaction policy.

Host cursor persistence, separate from adapter transactions unless the host coordinates them.

Clock for ISO progress timestamps; defaults to a fresh Date.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Synchronous conditional route selector over a cloned graph state.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

type GraphRouter = (state: AgentGraphState) => string;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

One exact declared destination name; undeclared destinations fail execution.

AgentGraphEngine.addConditionalEdges for a complete example.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Minimal boundary for a compiled LangGraph subgraph. The plugin owns its state schema.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph.

interface GraphSubgraph {
invoke(input: unknown, config?: unknown): Promise<unknown>;
getState?(config?: unknown): Promise<unknown>;
resume?(input: unknown, decision: GraphApprovalDecision, config?: unknown): Promise<unknown>;
}
Name Type Required Description
invoke Promise<unknown> Yes Invokes the compiled child graph.
getState Promise<unknown> No Inspects child state when a recognized interrupt needs mapping.
resume Promise<unknown> No Continues a child after a verified parent approval.

Type declaration; no runtime value.

AgentGraphEngine.addSubgraph for setup and usage.

Invokes the compiled child graph.

Parameters:

  • input: Host-mapped child input.
  • config: Parent-supplied checkpoint thread/namespace configuration.

Returns: Child output, interpreted by the parent mapOutput callback.

Child execution/checkpoint failures propagate or can be mapped for recognized interrupts.

Example:

import type { GraphSubgraph } from "@alneas/eaos-server";
export async function invokeHostSubgraph(
subgraph: GraphSubgraph,
input: Parameters<GraphSubgraph["invoke"]>[0],
config: Parameters<GraphSubgraph["invoke"]>[1],
) {
// Supply the host's admitted input and checkpoint/thread configuration.
return await subgraph.invoke(input, config);
}

Inspects child state when a recognized interrupt needs mapping.

Parameters:

  • config: Child checkpoint thread/namespace configuration.

Returns: Host-specific child checkpoint state.

Inspection failures propagate to parent execution.

Example:

* ```typescript
import type { GraphSubgraph } from "@alneas/eaos-server";
export async function inspectHostSubgraph(
subgraph: GraphSubgraph, config: Parameters<NonNullable<GraphSubgraph["getState"]>>[0],
) {
if (!subgraph.getState) throw new Error("Subgraph state inspection is unavailable");
return await subgraph.getState(config);
}
#### `resume`
Continues a child after a verified parent approval.
Parameters:
- `input`: Host-mapped child input.
- `decision`: Parent-approved human decision.
- `config`: Child checkpoint thread/namespace configuration.
Returns: Resumed child output.
### Errors and rejections
Child execution/checkpoint failures propagate.
Example:
```typescript
* ```typescript
import type { GraphSubgraph } from "@alneas/eaos-server";
export async function resumeHostSubgraph(
subgraph: GraphSubgraph,
input: Parameters<NonNullable<GraphSubgraph["resume"]>>[0],
verifiedDecision: Parameters<NonNullable<GraphSubgraph["resume"]>>[1],
config: Parameters<NonNullable<GraphSubgraph["resume"]>>[2],
) {
if (!subgraph.resume) throw new Error("Subgraph resumption is unavailable");
// The host authenticates/authorizes this decision before entering the subgraph.
return await subgraph.resume(input, verifiedDecision, config);
}
### Example
See the owning declaration and linked feature guide for usage; no standalone example is documented in source.
<a id="api-GraphSubgraphOptions"></a>
## [INTERFACE] `GraphSubgraphOptions`
Explicit state mapping, child-thread identity, and interrupt translation for [AgentGraphEngine.addSubgraph](#api-AgentGraphEngine).
Imports: `@alneas/eaos-server`, `@alneas/eaos-server/agentic`, `@alneas/eaos-server/agentic/graph`.
### Signature
```typescript
interface GraphSubgraphOptions {
mapInput?: (state: AgentGraphState) => unknown;
mapOutput?: (output: unknown, state: AgentGraphState) => Partial<AgentGraphState>;
threadId?: (state: AgentGraphState) => string;
mapInterrupted?: (error: unknown, state: AgentGraphState, subgraphState: unknown) => Partial<AgentGraphState> | Promise<Partial<AgentGraphState>>;
visual?: WorkflowGraphNodeInput;
}
Name Type Required Description
mapInput (state: AgentGraphState) => unknown No Optional synchronous parent-state to child-input mapping; defaults to passing parent state.
mapOutput (output: unknown, state: AgentGraphState) => Partial<AgentGraphState> No Optional synchronous child-output/parent-state to update mapping; absent treats output as a partial parent state.
threadId (state: AgentGraphState) => string No Optional synchronous child thread ID builder; defaults to sessionId:name and must be nonblank.
mapInterrupted (error: unknown, state: AgentGraphState, subgraphState: unknown) => Partial<AgentGraphState> | Promise<Partial<AgentGraphState>> No Called for a recognized nested LangGraph interrupt with error, parent state, and optional child checkpoint; resolves a parent update, normally pendingApproval. Errors propagate.
visual WorkflowGraphNodeInput No Serializable metadata used by workflow viewers; never executed.

Type declaration; no runtime value.

Optional synchronous parent-state to child-input mapping; defaults to passing parent state.

Optional synchronous child-output/parent-state to update mapping; absent treats output as a partial parent state.

Optional synchronous child thread ID builder; defaults to sessionId:name and must be nonblank.

Called for a recognized nested LangGraph interrupt with error, parent state, and optional child checkpoint; resolves a parent update, normally pendingApproval. Errors propagate.

Serializable metadata used by workflow viewers; never executed.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host inputs for the unauthenticated liveness and readiness routes.

Imports: @alneas/eaos-server, @alneas/eaos-server/health.

interface HealthRouterOptions {
appName: string;
checks?: readonly HealthCheck[];
now?: () => Date;
}
Name Type Required Description
appName string Yes Nonblank application label included in every response.
checks readonly HealthCheck[] No Readiness checks run on each readiness request; defaults to no checks.
now () => Date No Clock read separately for each request; defaults to the current Date.

Type declaration; no runtime value.

createHealthRouter for a complete usage example.

Nonblank application label included in every response.

Readiness checks run on each readiness request; defaults to no checks.

Clock read separately for each request; defaults to the current Date.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Plugin-manifest route factory supplied by trusted deployment composition.

Imports: @alneas/eaos-server/extensions.

type HostRouteFactory = NonNullable<PluginManifest['createRoutes']>;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PlatformExtension.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted endpoint, credentials, transport, and limits for createHttpAgentExecutor.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/remote-executor.

interface HttpAgentExecutorOptions {
url: string;
headers?: Record<string, string>;
timeoutMs?: number;
maxResponseBytes?: number;
fetch?: typeof fetch;
}
Name Type Required Description
url string Yes Private host or ARM runtime endpoint. Credentials must be host-configured.
headers Record<string, string> No Host-configured headers, including any runtime credentials; Content-Type is always application/json.
timeoutMs number No Default timeout in milliseconds, safe integer 1–3600000; task.timeoutMs overrides this.
maxResponseBytes number No Maximum response bytes, safe integer 1–134217728; content length and streaming bytes are checked.
fetch typeof fetch No Host transport implementation; defaults to global fetch.

Type declaration; no runtime value.

Private host or ARM runtime endpoint. Credentials must be host-configured.

Host-configured headers, including any runtime credentials; Content-Type is always application/json.

Default timeout in milliseconds, safe integer 1–3600000; task.timeoutMs overrides this.

Default: 60000.

Maximum response bytes, safe integer 1–134217728; content length and streaming bytes are checked.

Default: 8388608.

Host transport implementation; defaults to global fetch.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Versioned JSON envelope POSTed by createHttpAgentExecutor.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/remote-executor.

interface HttpAgentRuntimeRequest {
protocolVersion: '1.0';
task: ServerAgentTaskRequest;
}
Name Type Required Description
protocolVersion '1.0' Yes Wire protocol version; must be 1.0.
task ServerAgentTaskRequest Yes Cloned host-admitted task to execute.

Type declaration; no runtime value.

Wire protocol version; must be 1.0.

Cloned host-admitted task to execute.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Runtime reply validated by createHttpAgentExecutor; failed replies are converted to execution errors.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/remote-executor.

interface HttpAgentRuntimeResponse {
protocolVersion: '1.0';
taskId: string;
status: 'COMPLETED' | 'FAILED';
output?: string;
error?: string;
failureCode?: WorkflowAgentFailureCode;
retryable?: boolean;
}
Name Type Required Description
protocolVersion '1.0' Yes Wire protocol version; must match 1.0.
taskId string Yes Must match the submitted task ID.
status 'COMPLETED' | 'FAILED' Yes COMPLETED requires string output; FAILED is converted to a rejected execution.
output string No Required string result for COMPLETED replies; ignored on FAILED.
error string No Optional failure description; a blank/missing value uses a generic message.
failureCode WorkflowAgentFailureCode No Optional recognized classification; unrecognized values become RUNTIME_FAILED.
retryable boolean No Optional retry advice on failures; otherwise unavailable/timeout/runtime failure default to retryable.

Type declaration; no runtime value.

Wire protocol version; must match 1.0.

Must match the submitted task ID.

COMPLETED requires string output; FAILED is converted to a rejected execution.

Required string result for COMPLETED replies; ignored on FAILED.

Optional failure description; a blank/missing value uses a generic message.

Optional recognized classification; unrecognized values become RUNTIME_FAILED.

Optional retry advice on failures; otherwise unavailable/timeout/runtime failure default to retryable.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Planned host infrastructure change bound to the release and backend digest.

Imports: @alneas/eaos-server/lifecycle-engine.

interface InfrastructureStep {
key: string;
digest: string;
plugin: LifecyclePlugin;
backend: BackendTarget;
}
Name Type Required Description
key string Yes Infrastructure ledger key for backend/plugin.
digest string Yes Canonical digest binding backend and plugin infrastructure configuration.
plugin LifecyclePlugin Yes Trusted plugin release declaring infrastructure requirements.
backend BackendTarget Yes Exact target whose resources are previewed/applied.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Infrastructure ledger key for backend/plugin.

Canonical digest binding backend and plugin infrastructure configuration.

Trusted plugin release declaring infrastructure requirements.

Exact target whose resources are previewed/applied.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Temporarily propagate an existing joined SQL capability to a validated session wrapper.

Imports: @alneas/eaos-server/plugin-data/atomic-context.

declare function inheritAtomicSqlSession(source: AtomicSession, wrapper: AtomicSession): () => void;
Name Type Required Description
source AtomicSession Yes Currently bound source session; if unbound no capability is created.
wrapper AtomicSession Yes Wrapper session whose lifetime must not exceed the parent callback.

() => void

A release callback deleting the wrapper’s propagated binding.

Internal trusted capability plumbing exposed for validated host adapters. It never opens a transaction, authenticates a principal or extends the underlying session lifetime.

import { inheritAtomicSqlSession } from '@alneas/eaos-server/plugin-data/atomic-context'
export function withBinding(source: Parameters<typeof inheritAtomicSqlSession>[0], wrapper: Parameters<typeof inheritAtomicSqlSession>[1], work: () => void) { const release = inheritAtomicSqlSession(source, wrapper); try { work() } finally { release() } }

Chooses a trimmed explicit name or verified display name for initial person creation.

Only at initial creation: require a real name, never manufacture one from email.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

declare function initialPersonName(explicitName: unknown, verifiedDisplayName: unknown): string;
Name Type Required Description
explicitName unknown Yes User-supplied name; nonstring/blank values fall back to verified display name.
verifiedDisplayName unknown Yes Trusted provider display name; email addresses are not synthesized into names.

string

The chosen trimmed nonblank name, at most 200 characters.

Use only at initial registration; this helper does not update existing profiles or validate legal identity.

Error when both names are blank/nonstring or the chosen name exceeds 200 characters.

import { initialPersonName } from '@alneas/eaos-server/platform/user-directory';
const name = initialPersonName('Sample Person', undefined);

Small process-local TaskStore for development, tests and a single short- lived host. It deliberately has no lease recovery or persistence and must not be used as the production workflow/checkpoint store.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

declare class InMemoryEventAgentTaskStore implements EventAgentTaskStore {
constructor(options?: {
maxTasks?: number;
});
enqueue(task: QueuedEventTask): Promise<void>;
claim(limit: number): Promise<readonly QueuedEventTask[]>;
complete(taskId: string, result: ServerAgentTaskResult): Promise<void>;
fail(taskId: string, _error: unknown): Promise<void>;
getResult(taskId: string): ServerAgentTaskResult | undefined;
}
Name Type Required Description
options { maxTasks?: number; } No maxTasks defaults to 10000 and must be a safe integer 1–1000000.

InMemoryEventAgentTaskStore

Duplicate IDs compare JSON serialization exactly. Completed history/results are retained without the active-task capacity limit. No retry, lease recovery, or durable failure history exists.

Invalid capacity.

Maximum pending plus claimed tasks retained at once; defaults to 10000 and must be a safe integer from 1 to 1000000. Completed history/results are outside this limit.

Clones a queued task unless its ID is already identically retained.

Parameters:

  • task: Nonempty task ID and event name with structured-cloneable payload/task.

Returns: No value; resolves after local insertion or matching duplicate detection.

Missing identifiers, conflicting duplicate, active capacity exhaustion, or clone/JSON failure.

Example:

import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
import type { QueuedEventTask } from "@alneas/eaos-server/agentic/event-bridge";
export async function enqueue(store: InMemoryEventAgentTaskStore, task: QueuedEventTask) { await store.enqueue(task); }

Moves pending items into the claimed map in insertion order.

Parameters:

  • limit: Positive safe-integer maximum item count.

Returns: Cloned claimed items, or an empty array.

Invalid limit or clone failure; an item may already have moved before clone failure.

Example:

import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
const store = new InMemoryEventAgentTaskStore();
console.log(await store.claim(1)); // []

Moves a claimed task into retained completion history and clones its result.

Parameters:

  • taskId: Current claimed task identifier.
  • result: Normalized runtime outcome, including FAILED or PENDING_APPROVAL data.

Returns: No value; completes after retaining history and result.

Unknown/already completed task or clone failure; history can already have changed.

Example:

import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
import type { ServerAgentTaskResult } from "@alneas/eaos-server/agentic/types";
export async function complete(store: InMemoryEventAgentTaskStore, taskId: string, result: ServerAgentTaskResult) { await store.complete(taskId, result); }

Removes a claimed task without retaining failure history or rescheduling it.

Parameters:

  • taskId: Current claimed task identifier.
  • _error: Failure value accepted for interface compatibility and ignored.

Returns: No value; resolves after removal.

Unknown/already failed task.

Example:

import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
export async function fail(store: InMemoryEventAgentTaskStore, taskId: string, error: unknown) { await store.fail(taskId, error); }

Inspects a cloned retained completion result for local tests/development.

Parameters:

  • taskId: Previously completed task identifier.

Returns: Cloned result, or undefined if no completion result exists.

If a retained result cannot be cloned.

Example:

import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
console.log(new InMemoryEventAgentTaskStore().getResult("missing")); // undefined
import { InMemoryEventAgentTaskStore } from "@alneas/eaos-server/agentic/event-bridge";
const store = new InMemoryEventAgentTaskStore();
console.log(await store.claim(1)); // []

[CLASS] InMemoryWorkflowDefinitionRegistry

Section titled “[CLASS] InMemoryWorkflowDefinitionRegistry”

Stores versioned workflow drafts and validated/approved/published/retired records in process memory.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-registry.

declare class InMemoryWorkflowDefinitionRegistry implements WorkflowDefinitionRegistry {
constructor(options?: {
now?: () => string;
validate?: (definition: WorkflowDefinition) => void;
});
saveDraft(input: unknown, actorId?: string): WorkflowDefinitionRecord;
validate(workflowId: string, version: string, actorId?: string): WorkflowDefinitionRecord;
approve(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
publish(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
retire(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
get(workflowId: string, version: string): WorkflowDefinitionRecord | undefined;
getPublished(workflowId: string): WorkflowDefinitionRecord | undefined;
list(workflowId?: string): readonly WorkflowDefinitionRecord[];
}
Name Type Required Description
options { now?: () => string; validate?: (definition: WorkflowDefinition) => void; } No now returns a timestamp string and defaults to current ISO time; validate synchronously checks a structurally valid draft during validate and may throw.

InMemoryWorkflowDefinitionRegistry

Reference registry for tests/local authoring; it performs no actor authentication, role authorization, durable storage, or cross-process coordination. Transitions increment record revision and preserve definitions after draft.

Optional timestamp-string clock used when creating/updating registry records; defaults to current ISO time.

Returns: Timestamp text recorded without additional format validation by this registry.

InMemoryWorkflowDefinitionRegistry.saveDraft

Optional synchronous host semantic validator called after Core structural validation during a draft-to-validated transition.

Parameters:

  • definition: Structurally valid stored workflow definition presented for host semantic checks.

Returns: No value when accepted; throw to reject validation before the status update.

The callback receives the stored definition reference, so it should inspect without mutating it; this registry supplies no actor authentication or cross-process coordination.

InMemoryWorkflowDefinitionRegistry.validate

Validates and inserts or replaces a draft version, incrementing its revision.

Parameters:

  • input: Unknown workflow definition validated by core validation.
  • actorId: Optional author label recorded as creator/updater; not authenticated here.

Returns: A cloned draft record with canonical definition hash.

Invalid definition, non-draft existing version, clock/hash/clone failure.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
export function draft(input: unknown) { return new InMemoryWorkflowDefinitionRegistry().saveDraft(input); }

Transitions an existing draft to validated after core and optional host checks.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.
  • actorId: Optional updater label.

Returns: A cloned validated record with incremented revision.

Missing version, nondraft status, validation/callback/clock failure.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
export function validate(registry: InMemoryWorkflowDefinitionRegistry, workflowId: string, version: string) { return registry.validate(workflowId, version); }

Transitions a validated version to approved and records approver metadata.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.
  • actorId: Nonblank verified host approver label; no role check occurs here.

Returns: A cloned approved record.

Blank actor, missing version, nonvalidated status, or clock failure.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
export function approve(registry: InMemoryWorkflowDefinitionRegistry, workflowId: string, version: string, actorId: string) { return registry.approve(workflowId, version, actorId); }

Publishes an approved version and retires any currently published version of the same workflow.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Approved version to publish.
  • actorId: Nonblank verified host publisher label.

Returns: A cloned published record; previous published records become retired.

Blank actor, missing version, nonapproved status, or clock/clone failure; earlier retirement updates can already have occurred.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
export function publish(registry: InMemoryWorkflowDefinitionRegistry, workflowId: string, version: string, actorId: string) { return registry.publish(workflowId, version, actorId); }

Transitions a published version to retired and records retirement metadata.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Currently published version.
  • actorId: Nonblank verified host operator label.

Returns: A cloned retired record.

Blank actor, missing version, nonpublished status, or clock failure.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
export function retire(registry: InMemoryWorkflowDefinitionRegistry, workflowId: string, version: string, actorId: string) { return registry.retire(workflowId, version, actorId); }

Reads one workflow version without mutating lifecycle state.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.

Returns: A cloned record, or undefined when absent.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
console.log(new InMemoryWorkflowDefinitionRegistry().get("example", "1.0.0")); // undefined

Finds the currently published version of one workflow.

Parameters:

  • workflowId: Exact workflow identifier.

Returns: A cloned published record, or undefined when none exists.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
console.log(new InMemoryWorkflowDefinitionRegistry().getPublished("example")); // undefined

Lists records in insertion order with optional workflow filtering.

Parameters:

  • workflowId: Exact workflow identifier to filter, or omit for all workflows.

Returns: Independent cloned records, or an empty array.

Example:

import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
console.log(new InMemoryWorkflowDefinitionRegistry().list()); // []
import { InMemoryWorkflowDefinitionRegistry } from "@alneas/eaos-server/agentic/workflow-registry";
const registry = new InMemoryWorkflowDefinitionRegistry();
console.log(registry.list()); // []

Registered release snapshot and progress stored for one backend/plugin.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/lifecycle-engine.

interface Installation {
release: LifecyclePlugin;
digest: string;
status: 'installing' | 'installed' | 'failed';
}
Name Type Required Description
release LifecyclePlugin Yes Copied trusted plugin release installed on this backend.
digest string Yes Canonical digest of the release snapshot.
status 'installing' | 'installed' | 'failed' Yes Installing/installed/failed progress; noninstalled records require reconciliation.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Copied trusted plugin release installed on this backend.

Canonical digest of the release snapshot.

Installing/installed/failed progress; noninstalled records require reconciliation.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Detects request directives or query flags asking to bypass cached values.

Imports: @alneas/eaos-server/cache.

declare function isNoCacheRequested(c: Pick<Context, 'req'>): boolean;
Name Type Required Description
c Pick<Context, 'req'> Yes Hono request context; reads Cache-Control, Pragma, refresh, and nocache.

boolean

True for no-cache, max-age=0 (optionally quoted), or refresh/nocache equal to true or 1; false otherwise. Header directives are case-insensitive; query flag values are case-sensitive.

import { Hono } from "hono";
import { isNoCacheRequested } from "@alneas/eaos-server/cache";
const app = new Hono();
app.get("/cache-policy", c => c.json({ bypass: isNoCacheRequested(c) }));
console.log(await (await app.request("/cache-policy?refresh=1")).json());

Expose SQL execution on the exact active transaction that owns envelope CAS and receipts.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function joinedAtomicSqlExecutor(session: AtomicSession, principal: PluginPrincipal): {
dialect: "sqlite" | "oracle" | "postgres";
execute(tenantId: string, sql: string, binds: unknown[]): Promise<{
rows?: Record<string, unknown>[];
affectedRows: number;
}>;
};
Name Type Required Description
session AtomicSession Yes Currently active repository session carrying a trusted SQL capability binding.
principal PluginPrincipal Yes Verified principal matching both tenant and user of the joined transaction.

{ dialect: "sqlite" \| "oracle" \| "postgres"; execute(tenantId: string, sql: string, binds: unknown[]): Promise<{ rows?: Record<string, unknown>[]; affectedRows: number; }>; }

The bound driver dialect and an execute(tenantId, sql, binds) method using the existing connection.

Never retain or use the executor after the parent transaction callback returns. It does not open another transaction or authorize arbitrary SQL.

Throws for malformed/mismatched principals, missing/expired transaction bindings or a foreign execute tenant; driver failures propagate.

import { joinedAtomicSqlExecutor, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'
export function queryJoined(repository: AtomicRepository, principal: PluginPrincipal, statement: string, binds: unknown[]) {
// The host supplies trusted SQL and verifies resource permission before entry.
return repository.run(principal, session => joinedAtomicSqlExecutor(session, principal).execute(principal.tenantId, statement, binds))
}

Read a JSON object request body with explicit content-type and shape checks.

Imports: @alneas/eaos-server/plugin-data.

declare function jsonBody(c: Context): Promise<Record<string, any>>;
Name Type Required Description
c Context Yes Hono request context, normally protected by the plugin router body limit.

Promise<Record<string, any>>

Parsed nonnull object payload; arrays and primitives are rejected.

This helper does not enforce a body-size bound, tenant identity or operation schema on its own.

Rejects non-JSON content types and malformed/nonobject JSON with PluginError 400.

import { jsonBody } from '@alneas/eaos-server/plugin-data'
export async function readRequest(c: Parameters<typeof jsonBody>[0]) { return jsonBody(c) }

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

interface JsonDocumentContract {
id: string;
version: string;
table: string;
column: string;
namespace?: string;
jsonPath?: string;
recordPrefix?: string;
schema: Record<string, unknown>;
immutable?: boolean;
maxBytes?: number;
}
Name Type Required Description
id string Yes See the upstream owning declaration.
version string Yes See the upstream owning declaration.
table string Yes See the upstream owning declaration.
column string Yes See the upstream owning declaration.
namespace string No See the upstream owning declaration.
jsonPath string No See the upstream owning declaration.
recordPrefix string No See the upstream owning declaration.
schema Record<string, unknown> Yes See the upstream owning declaration.
immutable boolean No See the upstream owning declaration.
maxBytes number No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reviewable ordered collection of member plans with projected sequential ledger revisions.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleBundlePlan {
format: 1;
id: string;
bundleId: string;
operation: Operation;
plans: LifecyclePlan[];
}
Name Type Required Description
format 1 Yes Bundle discriminator; currently 1.
id string Yes Canonical digest of bundle identity, operation and member plans.
bundleId string Yes Registered host bundle alias.
operation Operation Yes Transition applied to every bundle member.
plans LifecyclePlan[] Yes Dependency-compatible member order; reversed for disable/uninstall.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Bundle discriminator; currently 1.

Canonical digest of bundle identity, operation and member plans.

Registered host bundle alias.

Transition applied to every bundle member.

Dependency-compatible member order; reversed for disable/uninstall.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Computes a lowercase SHA-256 digest of the canonical lifecycle JSON representation.

Imports: @alneas/eaos-server/lifecycle-engine.

declare const lifecycleDigest: (value: unknown) => string;
Name Type Required Description
value unknown Yes Supported canonical JSON lifecycle configuration.

string

A 64-character lowercase hexadecimal digest.

Requires Node crypto; the digest proves content identity, not authorization or authenticity.

Propagates canonical serialization errors for unsupported values.

import { lifecycleDigest } from '@alneas/eaos-server/lifecycle-engine';
const digest = lifecycleDigest({ pluginId: 'reports', version: '1.0.0' });

Read-only revision-bound plugin inventory including code-only and orphaned entries.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleInventory {
format: 1;
revision: number;
frameworkVersion: string;
plugins: LifecycleInventoryEntry[];
}
Name Type Required Description
format 1 Yes Inventory discriminator; currently 1.
revision number Yes Ledger snapshot revision inspected.
frameworkVersion string Yes Framework compatibility version used for readiness.
plugins LifecycleInventoryEntry[] Yes Deterministically ordered plugin/backend inventory entries, possibly empty.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Inventory discriminator; currently 1.

Ledger snapshot revision inspected.

Framework compatibility version used for readiness.

Deterministically ordered plugin/backend inventory entries, possibly empty.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

One registered or historical plugin/backend pair with requested and effective tenant readiness.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleInventoryEntry {
pluginId: string;
backendId: string | null;
backendConfigured: boolean;
registeredVersion: string | null;
installedVersion: string | null;
installationStatus: Installation['status'] | 'not-installed';
releaseMatches: boolean | null;
tenants: {
tenantId: string;
requestedEnabled: boolean;
enabled: boolean;
}[];
}
Name Type Required Description
pluginId string Yes Registered or historically recorded plugin ID.
backendId string | null Yes Backend associated with the entry, or null when no backend is known.
backendConfigured boolean Yes Whether this backend remains in the trusted runtime catalog.
registeredVersion string | null Yes Current registered code version, or null for orphaned history.
installedVersion string | null Yes Stored installation version, or null before installation.
installationStatus Installation['status'] | 'not-installed' Yes Stored progress or not-installed.
releaseMatches boolean | null Yes Whether stored digest matches registered code, or null without installation.
tenants { tenantId: string; requestedEnabled: boolean; enabled: boolean; }[] Yes Tenant requestedEnabled flags and effective enabled readiness results.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Registered or historically recorded plugin ID.

Backend associated with the entry, or null when no backend is known.

Whether this backend remains in the trusted runtime catalog.

Current registered code version, or null for orphaned history.

Stored installation version, or null before installation.

Stored progress or not-installed.

Whether stored digest matches registered code, or null without installation.

Tenant requestedEnabled flags and effective enabled readiness results.

Concrete tenant whose activation is inspected.

Stored requested activation flag without readiness guarantees.

Effective lifecycle readiness for the registered release and dependency closure.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reviewable hash-bound lifecycle transition generated against one ledger revision.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlan {
format: 1;
id: string;
revision: number;
frameworkVersion: string;
request: LifecycleRequest;
backend: BackendTarget;
dataCatalog?: DataContractCatalog;
plugins: LifecyclePlugin[];
migrations: MigrationStep[];
infrastructure: InfrastructureStep[];
deactivate: string[];
infrastructureProvider: string | null;
retainData: true;
}
Name Type Required Description
format 1 Yes Plan discriminator; currently 1.
id string Yes Canonical SHA-256 hash of all plan body fields.
revision number Yes Ledger revision observed during planning; apply rejects stale plans.
frameworkVersion string Yes Framework compatibility version used to resolve the plan.
request LifecycleRequest Yes Original scoped operation request.
backend BackendTarget Yes Snapshot of the exact immutable backend identity.
dataCatalog DataContractCatalog No Optional dependency-resolved canonical data contracts and table ownership.
plugins LifecyclePlugin[] Yes Dependency-ordered trusted feature releases involved in the transition.
migrations MigrationStep[] Yes Ordered migration steps not already applied with matching checksums.
infrastructure InfrastructureStep[] Yes Planned host infrastructure changes requiring the configured executor.
deactivate string[] Yes Activation map keys disabled before disruptive changes.
infrastructureProvider string | null Yes Configured executor identity, or null when none exists.
retainData true Yes Always true; lifecycle uninstall never drops business data.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Plan discriminator; currently 1.

Canonical SHA-256 hash of all plan body fields.

Ledger revision observed during planning; apply rejects stale plans.

Framework compatibility version used to resolve the plan.

Original scoped operation request.

Snapshot of the exact immutable backend identity.

Optional dependency-resolved canonical data contracts and table ownership.

Dependency-ordered trusted feature releases involved in the transition.

Ordered migration steps not already applied with matching checksums.

Planned host infrastructure changes requiring the configured executor.

Activation map keys disabled before disruptive changes.

Configured executor identity, or null when none exists.

Always true; lifecycle uninstall never drops business data.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

[INTERFACE] LifecyclePlatformBackendMetadata

Section titled “[INTERFACE] LifecyclePlatformBackendMetadata”

Nonsecret descriptive metadata for an existing backend.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlatformBackendMetadata {
label?: string;
provider?: string;
capabilities?: readonly string[];
}
Name Type Required Description
label string No Optional public display label.
provider string No Optional provider descriptor; never credentials or DSNs.
capabilities readonly string[] No Optional declared host capability names, not permission grants.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Optional public display label.

Optional provider descriptor; never credentials or DSNs.

Optional declared host capability names, not permission grants.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Platform control facade backed by the same LifecycleStore snapshot and lock. Use this with SqlLifecycleStore for distributed hosts; it intentionally does not create a second platform database or a second placement authority.

Imports: @alneas/eaos-server/platform-admin, @alneas/eaos-server/platform-admin/store.

declare class LifecyclePlatformControlStore implements PlatformControlStore {
constructor(lifecycle: LifecycleStore, now?: () => Date);
listTenants(): Promise<readonly PlatformTenantRecord[]>;
createTenant(input: PlatformTenantCreateInput): Promise<PlatformTenantRecord>;
updateTenant(tenantId: string, patch: PlatformTenantPatch): Promise<PlatformTenantRecord>;
registerBackend(backend: PlatformBackendRecord): Promise<PlatformBackendRecord>;
listBackends(): Promise<readonly PlatformBackendRecord[]>;
getBackend(backendId: string): Promise<PlatformBackendRecord | null>;
getTenantPlacement(tenantId: string): Promise<TenantBackendPlacement | null>;
saveMigrationPlan(plan: BackendMigrationPlan): Promise<void>;
getMigrationPlan(migrationId: string): Promise<BackendMigrationPlan | null>;
getMigrationStatus(migrationId: string): Promise<LifecyclePlatformMigrationRecord | null>;
beginMigrationExecution(input: {
tenantId: string;
migrationId: string;
executionId: string;
}): Promise<LifecyclePlatformMigrationRecord>;
recordMigrationVerification(input: {
tenantId: string;
plan: BackendMigrationPlan;
executionId: string;
verification: BackendMigrationVerificationReport;
cutover: BackendMigrationCutover;
}): Promise<LifecyclePlatformMigrationRecord>;
markMigrationFailure(input: {
migrationId: string;
executionId?: string;
status: 'failed' | 'reconciling';
message: string;
}): Promise<LifecyclePlatformMigrationRecord>;
reconcileMigration(input: {
migrationId: string;
action: PlatformMigrationReconcileAction;
note: string;
}): Promise<LifecyclePlatformMigrationRecord>;
createRollbackPlan(input: {
tenantId: string;
migrationId: string;
reason: string;
requestedAt: string;
}): Promise<BackendMigrationPlan>;
recordTenantPlacement(input: {
tenantId: string;
plan: BackendMigrationPlan;
cutover: BackendMigrationCutover;
}): Promise<TenantBackendPlacement>;
}
Name Type Required Description
lifecycle LifecycleStore Yes Host store providing consistent reads and exclusive writer callbacks.
now () => Date No Clock for mutation timestamps; defaults to a fresh Date.

LifecyclePlatformControlStore

Mutations normalize one locked lifecycle snapshot, increment its revision, and persist it; transaction/CAS/lock recovery depend on the host LifecycleStore. This facade performs no caller authentication, SQL/infra provisioning, remote migration, or automatic retry. Authorize operators before invoking it and reconcile uncertain store failures.

Lists tenant records from the authoritative normalized lifecycle snapshot.

Returns: Tenant records with cloned domains arrays, or an empty array.

Host read/normalization failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function listTenants(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["listTenants"]>) {
return store.listTenants(...args);
}

Creates an active tenant and its initial backend routing record under the lifecycle writer lock.

Parameters:

  • input: Valid scope ID, nonblank name, nonempty domain strings, and registered initial backendId; a dedicated backend must bind the same tenant.

Returns: Created tenant record with clock timestamps; initial routing revision is one.

Invalid input, duplicate tenant, missing/mismatched backend, or host lock/write/clock failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function createTenant(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["createTenant"]>) {
return store.createTenant(...args);
}

Updates an existing tenant name, active flag, or domains and refreshes updatedAt.

Parameters:

  • tenantId: Existing valid tenant scope ID.
  • patch: Optional nonblank name, boolean active, and nonempty nonblank domains; omitted fields remain unchanged.

Returns: Updated tenant with cloned domains.

Missing tenant, invalid supplied fields, or host lock/write/clock failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function updateTenant(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["updateTenant"]>) {
return store.updateTenant(...args);
}

Registers an immutable backend placement identity and replaceable public metadata.

Parameters:

  • backend: Valid backend/database IDs, dialect/mode, optional dedicated tenant binding, and metadata.

Returns: Materialized registered target with metadata.

Invalid target, changed placement for an existing ID, database dialect conflict, or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function registerBackend(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["registerBackend"]>) {
return store.registerBackend(...args);
}

Materializes registered backend targets with their public metadata.

Returns: Backend list, or an empty array.

Host read/normalization failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function listBackends(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["listBackends"]>) {
return store.listBackends(...args);
}

Reads a registered backend target and its public metadata.

Parameters:

  • backendId: Valid registered backend scope ID.

Returns: Materialized backend, or null when unregistered.

Invalid ID or host read failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function getBackend(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["getBackend"]>) {
return store.getBackend(...args);
}

Resolves a tenant routing record into its registered backend target.

Parameters:

  • tenantId: Valid tenant scope ID.

Returns: Placement with routing revision/time and backend, or null when absent.

Invalid ID, dangling backend reference, or host read failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function getTenantPlacement(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["getTenantPlacement"]>) {
return store.getTenantPlacement(...args);
}

Persists an immutable migration plan after checking registered backend identities.

Parameters:

  • plan: Reviewed plan matching currently registered source/target; identical saved plans may be accepted before completion.

Returns: No value; resolves after storing the plan and initial planned record if absent.

Unregistered/changed backend, conflicting reused plan ID, already completed plan, clone or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function saveMigrationPlan(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["saveMigrationPlan"]>) {
return store.saveMigrationPlan(...args);
}

Reads a cloned persisted migration plan by ID.

Parameters:

  • migrationId: Valid migration scope ID.

Returns: Plan clone, or null when absent.

Invalid ID or host read/clone failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function getMigrationPlan(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["getMigrationPlan"]>) {
return store.getMigrationPlan(...args);
}

Reads the persisted migration execution/reconciliation record.

Parameters:

  • migrationId: Valid migration scope ID.

Returns: Cloned status record, or null when absent.

Invalid ID or host read/clone failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function getMigrationStatus(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["getMigrationStatus"]>) {
return store.getMigrationStatus(...args);
}

Binds an execution token and transitions a tenant migration record to running.

Parameters:

  • input: Verified tenantId, persisted migrationId, and unique host executionId; plan scope must include the tenant.

Returns: Cloned running record, or completed cutover/rolled-back record unchanged.

Missing plan, tenant mismatch, conflicting active token, reconciling state, invalid IDs, or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function beginMigrationExecution(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["beginMigrationExecution"]>) {
return store.beginMigrationExecution(...args);
}

Verified tenant included in the persisted migration plan tenant scope; mismatch rejects before recording execution.

Identity of an already persisted migration plan and its corresponding status record.

Host execution token bound to this run; a different token cannot replace an active running/verified execution.

Records verified migration evidence and cutover data for the active execution token.

Parameters:

  • input: Tenant, exact persisted plan, active executionId, verification report, and matching validated cutover.

Returns: Cloned verified migration record.

Invalid cutover/report, nonpersisted/changed plan, tenant/token/state mismatch, changed retry verification, or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function recordMigrationVerification(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["recordMigrationVerification"]>) {
return store.recordMigrationVerification(...args);
}

recordMigrationVerification.input.tenantId

Section titled “recordMigrationVerification.input.tenantId”

Verified tenant included in the exact persisted plan tenant scope.

Exact persisted migration plan; canonical contents must match the saved plan rather than a modified caller copy.

recordMigrationVerification.input.executionId

Section titled “recordMigrationVerification.input.executionId”

Current execution token recorded by beginMigrationExecution; only running/verified records with this token may accept evidence.

recordMigrationVerification.input.verification

Section titled “recordMigrationVerification.input.verification”

Passing source/target verification report validated against the plan and cutover; a verified retry must reproduce the recorded report.

Matching validated cutover proof recorded with the report for a later explicit routing commit; recording verification does not itself switch placement.

Records a failed or reconciling migration status with host diagnostic text.

Parameters:

  • input: Persisted migrationId, optional expected executionId, failure status, and nonblank message up to 2048 characters.

Returns: Cloned updated failure record.

Missing/completed migration, mismatched token, invalid input, or host store/clock failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function markMigrationFailure(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["markMigrationFailure"]>) {
return store.markMigrationFailure(...args);
}

Persisted migration record to mark failed or reconciling; completed cutover/rolled-back records cannot be changed through this method.

Optional expected active execution token; a truthy supplied value must match, while omission skips this token check.

Failure disposition to persist: failed permits explicit retry preparation, while reconciling requires operator outcome review before retry.

Nonblank diagnostic text up to 2048 characters, stored with a generated occurrence timestamp; exclude secrets and customer payloads.

Applies an operator reconciliation status action and records its note.

Parameters:

  • input: Persisted migrationId, action, and nonblank note up to 2048 characters; retry only permits failed/reconciling state and clears execution/verification/cutover.

Returns: Cloned updated migration record.

Missing record, retry from an ineligible state, completed record for mark-failed/mark-reconciling, invalid text, or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function reconcileMigration(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["reconcileMigration"]>) {
return store.reconcileMigration(...args);
}

Persisted migration whose operator reconciliation state is being updated.

Explicit retry, mark-failed or mark-reconciling action; retry requires failed/reconciling state and clears execution, verification and cutover data.

Nonblank operator rationale up to 2048 characters, persisted as timestamped diagnostic text; this does not independently verify external outcomes.

Creates a reverse migration plan for a completed cutover without executing rollback.

Parameters:

  • input: Verified tenantId, completed migrationId, nonblank reason up to 1024 characters, and parseable requestedAt timestamp.

Returns: New planned reverse migration linked to the original record.

Incomplete/already rollback-planned migration, tenant no longer on migrated target, invalid input/planning, or host store failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function createRollbackPlan(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["createRollbackPlan"]>) {
return store.createRollbackPlan(...args);
}

Verified tenant currently placed on the completed migration target; the current placement must still match before a reverse plan is created.

Completed cutover migration to reverse; an existing rollback plan prevents creating another one.

Nonblank rollback planning rationale up to 1024 characters, copied to the new reverse migration request.

Parseable rollback request timestamp copied to the new plan/status record; no rollback is executed by planning.

Commits a verified migration routing change and transfers active plugin activations to the target backend.

Parameters:

  • input: Tenant included by the exact persisted plan and its previously recorded cutover proof.

Returns: New target placement, or current placement for an already-cutover record.

Unverified/stale/changed plan, invalid cutover or nonadvancing routing revision, target tenant mismatch, missing planned active plugin or target installation, or host lock/write failure.

Example:

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
export async function recordTenantPlacement(store: LifecyclePlatformControlStore, ...args: Parameters<LifecyclePlatformControlStore["recordTenantPlacement"]>) {
return store.recordTenantPlacement(...args);
}

Verified tenant included in the plan whose persisted routing placement and active plugin bindings will be moved.

Exact persisted verified migration plan; current source/target backend identities and installations are rechecked before commit.

Previously recorded verification proof with source retained and an advancing routing revision; its canonical contents must match the saved cutover.

import { LifecyclePlatformControlStore } from "@alneas/eaos-server/platform-admin/store";
import type { LifecycleStore } from "@alneas/eaos-server/lifecycle-engine";
export function controlStore(lifecycle: LifecycleStore) { return new LifecyclePlatformControlStore(lifecycle); }

[INTERFACE] LifecyclePlatformMigrationRecord

Section titled “[INTERFACE] LifecyclePlatformMigrationRecord”

Durable migration execution, verification and reconciliation evidence.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlatformMigrationRecord {
status: LifecyclePlatformMigrationStatus;
executionId?: string;
verification?: BackendMigrationVerificationReport;
cutover?: BackendMigrationCutover;
error?: {
message: string;
occurredAt: string;
};
updatedAt: string;
rollbackOf?: string;
rollbackPlanId?: string;
}
Name Type Required Description
status LifecyclePlatformMigrationStatus Yes Current progress; reconciling represents uncertain execution outcomes.
executionId string No Optional identity claiming the host migration execution.
verification BackendMigrationVerificationReport No Optional host-reported verification matching the migration plan.
cutover BackendMigrationCutover No Optional source-retaining cutover receipt.
error { message: string; occurredAt: string; } No Optional failure message and occurrence timestamp; exclude secrets.
updatedAt string Yes Timestamp of the latest migration-state change.
rollbackOf string No Optional original migration ID when this is a rollback execution.
rollbackPlanId string No Optional reviewed reverse plan associated with this migration.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Current progress; reconciling represents uncertain execution outcomes.

Optional identity claiming the host migration execution.

Optional host-reported verification matching the migration plan.

Optional source-retaining cutover receipt.

Optional failure message and occurrence timestamp; exclude secrets.

Nonsecret failure description retained for operator reconciliation.

Timestamp at which the error was recorded.

Timestamp of the latest migration-state change.

Optional original migration ID when this is a rollback execution.

Optional reviewed reverse plan associated with this migration.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Persisted migration progress including uncertainty, failure, reconciliation and rollback states.

Imports: @alneas/eaos-server/lifecycle-engine.

type LifecyclePlatformMigrationStatus = 'planned' | 'running' | 'verified' | 'cutover' | 'failed' | 'reconciling' | 'rolled-back';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable tenant-to-backend routing assignment with optimistic routing revision.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlatformPlacement {
tenantId: string;
backendId: string;
routingRevision: number;
changedAt: string;
}
Name Type Required Description
tenantId string Yes Verified tenant whose traffic is routed.
backendId string Yes Opaque configured backend receiving traffic.
routingRevision number Yes Nonnegative revision used to track routing changes.
changedAt string Yes Timestamp of the recorded routing switch.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Verified tenant whose traffic is routed.

Opaque configured backend receiving traffic.

Nonnegative revision used to track routing changes.

Timestamp of the recorded routing switch.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Platform-owned tenant, backend and migration control maps stored with the lifecycle ledger.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlatformState {
tenants: Record<string, LifecyclePlatformTenant>;
placements: Record<string, LifecyclePlatformPlacement>;
backendMetadata: Record<string, LifecyclePlatformBackendMetadata>;
migrationPlans: Record<string, BackendMigrationPlan>;
migrationRecords: Record<string, LifecyclePlatformMigrationRecord>;
}
Name Type Required Description
tenants Record<string, LifecyclePlatformTenant> Yes Tenant records indexed by tenant ID.
placements Record<string, LifecyclePlatformPlacement> Yes Current routing assignments indexed by tenant ID.
backendMetadata Record<string, LifecyclePlatformBackendMetadata> Yes Nonsecret backend labels/provider capabilities indexed by backend ID.
migrationPlans Record<string, BackendMigrationPlan> Yes Reviewed backend migration plans indexed by migration ID.
migrationRecords Record<string, LifecyclePlatformMigrationRecord> Yes Execution/reconciliation records indexed by migration ID.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Tenant records indexed by tenant ID.

Current routing assignments indexed by tenant ID.

Nonsecret backend labels/provider capabilities indexed by backend ID.

Reviewed backend migration plans indexed by migration ID.

Execution/reconciliation records indexed by migration ID.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable platform tenant metadata independent of business schemas.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlatformTenant {
id: string;
name: string;
active: boolean;
domains: readonly string[];
createdAt: string;
updatedAt: string;
}
Name Type Required Description
id string Yes Stable concrete tenant ID.
name string Yes Public tenant display name.
active boolean Yes Whether platform tenant admission is enabled; membership remains host-owned.
domains readonly string[] Yes Configured tenant lookup domains; domain mapping alone never proves membership.
createdAt string Yes Tenant creation timestamp.
updatedAt string Yes Latest metadata update timestamp.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Stable concrete tenant ID.

Public tenant display name.

Whether platform tenant admission is enabled; membership remains host-owned.

Configured tenant lookup domains; domain mapping alone never proves membership.

Tenant creation timestamp.

Latest metadata update timestamp.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted release definition with feature dependencies, schema requirements and immutable migrations.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecyclePlugin {
id: string;
version: string;
framework: string;
dependencies?: Record<string, string>;
schemaDependencies?: Record<string, string>;
schemaContracts?: DataContract[];
migrations: PluginMigration[];
infrastructure?: Record<string, unknown>;
}
Name Type Required Description
id string Yes Registered feature identifier, up to 128 letters/digits/underscore/hyphen characters starting alphanumeric.
version string Yes Valid semantic release version; changed contents require a version bump.
framework string Yes Valid semver range for compatible framework versions.
dependencies Record<string, string> No Optional feature ID to semver range dependencies installed/enabled as a closure.
schemaDependencies Record<string, string> No Optional canonical data contract ranges; never installs or enables feature plugins. Storage dependencies do not install or enable a feature plugin.
schemaContracts DataContract[] No Optional canonical releases supplied by a data package; duplicate IDs must agree exactly. Canonical contract releases supplied by the data package, not inline table copies.
migrations PluginMigration[] Yes Append-only reviewed plugin migrations; contract-backed plugins must put DDL in data contracts instead. Immutable, reviewed migrations generated from the plugin’s schema; never rewrite applied IDs.
infrastructure Record<string, unknown> No Optional nonsecret declarative host requirements; absence causes no infrastructure work. Declarative, host-defined resource requirements. No secrets. Absence means no infrastructure changes.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Registered feature identifier, up to 128 letters/digits/underscore/hyphen characters starting alphanumeric.

Valid semantic release version; changed contents require a version bump.

Valid semver range for compatible framework versions.

Optional feature ID to semver range dependencies installed/enabled as a closure.

Optional canonical data contract ranges; never installs or enables feature plugins.

Storage dependencies do not install or enable a feature plugin.

Optional canonical releases supplied by a data package; duplicate IDs must agree exactly.

Canonical contract releases supplied by the data package, not inline table copies.

Append-only reviewed plugin migrations; contract-backed plugins must put DDL in data contracts instead.

Immutable, reviewed migrations generated from the plugin’s schema; never rewrite applied IDs.

Optional nonsecret declarative host requirements; absence causes no infrastructure work.

Declarative, host-defined resource requirements. No secrets. Absence means no infrastructure changes.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-provided trusted release catalogs, durable lifecycle storage and side-effect adapters.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleProject {
store: LifecycleStore;
backends: BackendTarget[];
plugins: LifecyclePlugin[];
dataContracts?: readonly DataContract[];
bundles?: Record<string, readonly string[]>;
migrate: (step: MigrationStep, backend: BackendTarget) => Promise<void>;
quiesce?: (activations: LifecycleState['activations'][string][]) => Promise<void>;
infrastructure?: {
identity: string;
preview(step: InfrastructureStep): Promise<unknown>;
apply(step: InfrastructureStep): Promise<void>;
};
}
Name Type Required Description
store LifecycleStore Yes Cross-process locked atomic durable lifecycle store.
backends BackendTarget[] Yes Trusted configured backend catalog; existing physical identities are immutable.
plugins LifecyclePlugin[] Yes Trusted registered plugin releases; registration alone grants no tenant activation.
dataContracts readonly DataContract[] No Optional canonical schema contract releases, also collected from plugin schemaContracts.
bundles Record<string, readonly string[]> No Optional host aliases mapping bundle IDs to ordered registered feature IDs.
migrate (step: MigrationStep, backend: BackendTarget) => Promise<void> Yes Execute one reviewed migration step on the exact backend; reject failures so reconciliation state is recorded.
quiesce (activations: LifecycleState['activations'][string][]) => Promise<void> No Optional all-instance admission stop and active-work drain; required before upgrades affecting enabled activations. Stop admission and drain existing work on ALL affected backend instances before upgrades.
infrastructure { identity: string; preview(step: InfrastructureStep): Promise<unknown>; apply(step: InfrastructureStep): Promise<void>; } No Optional named host preview/apply capability; no credentials belong in declarative plugin settings.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Cross-process locked atomic durable lifecycle store.

Trusted configured backend catalog; existing physical identities are immutable.

Trusted registered plugin releases; registration alone grants no tenant activation.

Optional canonical schema contract releases, also collected from plugin schemaContracts.

Optional host aliases mapping bundle IDs to ordered registered feature IDs.

Execute one reviewed migration step on the exact backend; reject failures so reconciliation state is recorded.

Parameters:

  • step: Exact planned infrastructure step and target digest; do not reinterpret unreviewed settings.
  • backend: Already-provisioned opaque backend declaration; never a connection string or credentials.

Returns: Resolves without a value after the reviewed host side effect completes.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Optional all-instance admission stop and active-work drain; required before upgrades affecting enabled activations.

Stop admission and drain existing work on ALL affected backend instances before upgrades.

Parameters:

  • activations: Host operation input bound to the scope described by this member.

Returns: Resolves without a value after the reviewed host side effect completes.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Optional named host preview/apply capability; no credentials belong in declarative plugin settings.

Stable nonsecret infrastructure-provider identity bound into reviewed plans.

Preview one exact infrastructure step; host must not claim application completion from preview.

Parameters:

  • step: Exact reviewed infrastructure step for the configured backend.

Returns: Host preview information; no apply result is implied.

Rejects host adapter failures; effects may already have partially completed.

Example:

import type { LifecycleProject, InfrastructureStep } from '@alneas/eaos-server/lifecycle-engine';
export async function previewInfrastructure(project: LifecycleProject, step: InfrastructureStep) {
if (!project.infrastructure) throw new Error("Host infrastructure port required");
return project.infrastructure.preview(step);
}

Apply one reviewed infrastructure step; errors leave reconciliation state and may follow partial external success.

Parameters:

  • step: Exact reviewed infrastructure step for the configured backend.

Returns: Resolves without a value after host application completes.

Rejects host adapter failures; effects may already have partially completed.

Example:

import type { LifecycleProject, InfrastructureStep } from '@alneas/eaos-server/lifecycle-engine';
export async function applyInfrastructure(project: LifecycleProject, step: InfrastructureStep) {
if (!project.infrastructure) throw new Error("Host infrastructure port required");
await project.infrastructure.apply(step);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Concrete lifecycle operation scoped to one registered backend and verified tenant.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleRequest {
operation: Operation;
pluginId: string;
backendId: string;
tenantId: string;
}
Name Type Required Description
operation Operation Yes Requested install/update/enable/disable/uninstall transition.
pluginId string Yes Registered plugin ID, or bundle ID for bundle planning.
backendId string Yes Registered execution backend ID.
tenantId string Yes Verified concrete tenant; must match dedicated backend scope.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Requested install/update/enable/disable/uninstall transition.

Registered plugin ID, or bundle ID for bundle planning.

Registered execution backend ID.

Verified concrete tenant; must match dedicated backend scope.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host identity, backend routing, and lifecycle admission used by jobs and HTTP guards.

Imports: @alneas/eaos-server/lifecycle.

interface LifecycleRuntime {
lifecycle: PluginLifecycle;
backendId: string;
resolveBackend?: (tenantId: string) => Promise<string | null>;
resolveTenant: (context: Context) => Promise<string | null>;
}
Name Type Required Description
lifecycle PluginLifecycle Yes Lifecycle engine consulted for current plugin admission.
backendId string Yes Fallback registered backend ID used only when resolveBackend is absent.
resolveBackend (tenantId: string) => Promise<string | null> No Resolve the registered target for a verified tenant; null denies admission without fallback.
resolveTenant (context: Context) => Promise<string | null> Yes Must resolve authenticated identity / verified webhook signature, never a raw tenant header alone.

Type declaration; no runtime value.

createLifecycleGuard.

Lifecycle engine consulted for current plugin admission.

Fallback registered backend ID used only when resolveBackend is absent.

Resolve the registered target for a verified tenant; null denies admission without fallback.

Must resolve authenticated identity / verified webhook signature, never a raw tenant header alone.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Versioned durable control ledger for plugin readiness, schema history and platform placement.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/lifecycle-engine.

interface LifecycleState {
baselineHistory?: Record<string, {
hash: string;
source: DataContract;
migrations: Record<string, MigrationRecord>;
}>;
format: 1;
revision: number;
backends: Record<string, BackendTarget>;
installations: Record<string, Installation>;
activations: Record<string, {
backendId: string;
tenantId: string;
pluginId: string;
digest: string;
enabled: boolean;
}>;
migrations: Record<string, MigrationRecord>;
infrastructure: Record<string, {
digest: string;
status: 'running' | 'applied' | 'failed';
}>;
platform: LifecyclePlatformState;
dataContracts?: Record<string, {
contract: DataContract;
digest: string;
status: 'installing' | 'installed' | 'failed';
}>;
}
Name Type Required Description
baselineHistory Record<string, { hash: string; source: DataContract; migrations: Record<string, MigrationRecord>; }> No Optional archived exact histories replaced by reviewed baselines.
format 1 Yes Persistent ledger discriminator; currently 1.
revision number Yes Nonnegative safe integer incremented on persisted lifecycle changes.
backends Record<string, BackendTarget> Yes Opaque backend target definitions indexed by backend ID.
installations Record<string, Installation> Yes Release snapshots indexed by JSON [backendId, pluginId].
activations Record<string, { backendId: string; tenantId: string; pluginId: string; digest: string; enabled: boolean; }> Yes Requested tenant activation records indexed by JSON [backendId, tenantId, pluginId]; effective readiness is checked separately.
migrations Record<string, MigrationRecord> Yes Progress indexed by JSON [databaseId, migrationIdentity, migrationId, tenantId-or-*].
infrastructure Record<string, { digest: string; status: 'running' | 'applied' | 'failed'; }> Yes Infrastructure digests/progress indexed by JSON [backendId, pluginId].
platform LifecyclePlatformState Yes Tenant/control-plane metadata and backend migration evidence.
dataContracts Record<string, { contract: DataContract; digest: string; status: 'installing' | 'installed' | 'failed'; }> No Optional canonical contract installation records indexed by JSON [databaseId, contractId].

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Optional archived exact histories replaced by reviewed baselines.

Exact archived baseline integrity hash.

Original canonical contract release retained for historical evidence.

Archived exact applied migration receipts.

Persistent ledger discriminator; currently 1.

Nonnegative safe integer incremented on persisted lifecycle changes.

Opaque backend target definitions indexed by backend ID.

Release snapshots indexed by JSON [backendId, pluginId].

Requested tenant activation records indexed by JSON [backendId, tenantId, pluginId]; effective readiness is checked separately.

Registered execution backend owning this activation.

Concrete verified tenant owning this activation.

Registered feature ID requested for activation.

Canonical release or infrastructure definition digest.

Requested activation flag; effective readiness also requires matching installed digests and dependencies.

Progress indexed by JSON [databaseId, migrationIdentity, migrationId, tenantId-or-*].

Infrastructure digests/progress indexed by JSON [backendId, pluginId].

Canonical release or infrastructure definition digest.

Persisted installing/installed/failed or running/applied/failed progress, according to this ledger map.

Tenant/control-plane metadata and backend migration evidence.

Optional canonical contract installation records indexed by JSON [databaseId, contractId].

Canonical schema contract release bound by its stored digest.

Canonical release or infrastructure definition digest.

Persisted installing/installed/failed or running/applied/failed progress, according to this ledger map.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable lifecycle reads and cross-process exclusive writer coordination.

withLock must exclude every other writer, across processes. Reads must observe atomic committed snapshots.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/lifecycle-engine.

interface LifecycleStore extends Pick<LifecycleWriter, 'read'> {
withLock<T>(fn: (writer: LifecycleWriter) => Promise<T>): Promise<T>;
}
Name Type Required Description
withLock Promise<T> Yes Exclude every competing writer across processes and hold the lock until the async callback settles; release on success or failure.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Exclude every competing writer across processes and hold the lock until the async callback settles; release on success or failure.

Parameters:

  • fn: Async work invoked only while holding exclusive writer ownership; receives atomic read/write capabilities.

Returns: The callback result after its lock is released; the lock is also released on failure.

  • T: Result resolved by the exclusive-lock callback.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { LifecycleStore } from '@alneas/eaos-server/lifecycle-engine';
export async function snapshot(store: LifecycleStore) {
return store.withLock(async writer => writer.read());
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Atomic lifecycle snapshot access made available inside the host’s exclusive lock.

Imports: @alneas/eaos-server/lifecycle-engine.

interface LifecycleWriter {
read(): Promise<LifecycleState>;
write(state: LifecycleState): Promise<void>;
}
Name Type Required Description
read Promise<LifecycleState> Yes Read the currently committed ledger snapshot; must not expose uncommitted writes.
write Promise<void> Yes Atomically persist the complete next snapshot; resolve only after durable completion.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Read the currently committed ledger snapshot; must not expose uncommitted writes.

Returns: The currently committed atomic ledger snapshot.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { LifecycleStore } from '@alneas/eaos-server/lifecycle-engine';
export async function readLocked(store: LifecycleStore) {
return store.withLock(async writer => writer.read());
}

Atomically persist the complete next snapshot; resolve only after durable completion.

Parameters:

  • state: Complete next ledger snapshot with updated revision and control metadata.

Returns: Resolves without a value after the complete snapshot is durably committed.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { LifecycleStore } from '@alneas/eaos-server/lifecycle-engine';
export async function persistReviewedRevision(store: LifecycleStore) {
await store.withLock(async writer => {
const state = await writer.read();
// Domain changes belong in the same reviewed writer callback.
state.revision += 1;
await writer.write(state);
});
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Persists local mutations and an outbox, then synchronizes with a host-provided upstream adapter.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

declare class LocalFirstSqliteAdapter implements DataAccessAdapter {
readonly tenantId?: string;
constructor(options: LocalFirstSqliteAdapterOptions);
initSchema(): Promise<void>;
recordAccess(collection: string, type: 'read' | 'write'): Promise<void>;
syncActiveTables(limit?: number): Promise<string[]>;
find<T = unknown>(collection: string, filter?: Filter, options?: QueryOptions): Promise<T[]>;
count(collection: string, filter?: Filter, options?: QueryOptions): Promise<number>;
findOne<T = unknown>(collection: string, id: string, options?: QueryOptions): Promise<T | null>;
create<T = unknown>(collection: string, data: Record<string, unknown>, _options?: QueryOptions): Promise<T>;
update<T = unknown>(collection: string, id: string, data: Record<string, unknown>, _options?: QueryOptions): Promise<T>;
delete<T = unknown>(collection: string, id: string, _options?: QueryOptions): Promise<T>;
pullChanges(collection: string): Promise<number>;
processOutbox(): Promise<void>;
destroy(): void;
}
Name Type Required Description
options LocalFirstSqliteAdapterOptions Yes Host drivers and synchronization settings; see {@link LocalFirstSqliteAdapterOptions}.

LocalFirstSqliteAdapter

Call initSchema before use; it creates metadata only, so provision domain tables separately. Local mutation and outbox insertion are separate writes, so failure may leave an unqueued local change. No tenant authorization is implemented: tenantId is only a create default. Serialize transaction-sensitive operations on the host driver; processOutbox excludes overlapping calls on this instance only. Call destroy to remove timers/listeners; it does not cancel in-flight work or close either driver.

The constructor performs no schema initialization. Timers/listeners start immediately unless disabled; call destroy when the instance is no longer needed.

Optional create-time tenant_id fallback captured from options; not a read or mutation authorization filter.

Initializes SQLite synchronization metadata tables and attempts WAL, NORMAL, and 5000 ms busy-timeout pragmas.

Returns: No value; resolves after metadata table creation. Pragma failures are deliberately ignored.

Rejects metadata table creation failures; earlier tables may already exist.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
await adapter.initSchema();
} finally { adapter.destroy(); }
}

Increments a table read or write counter and records the current ISO timestamp.

Parameters:

  • collection: Table name recorded as a metadata value.
  • type: Counter to increment; read contributes weight 2 and write weight 5 in adaptive ranking.

Returns: No value; resolves after the counter upsert.

Rejects SQLite failures.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
await adapter.recordAccess("records", "read");
} finally { adapter.destroy(); }
}

Pulls every essential table plus the highest weighted access-frequency tables sequentially.

Parameters:

  • limit: Maximum frequency-ranked tables selected in addition to essential tables; defaults to 8 and is passed to SQLite without additional validation.

Returns: Names whose pullChanges calls completed, including tables with no new rows; failed tables are warned and omitted.

Rejects the initial frequency query failure; individual pull failures are caught.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.syncActiveTables(8);
} finally { adapter.destroy(); }
}

Queries local SQLite rows and schedules a best-effort read-frequency update.

Parameters:

  • collection: Local table identifier, quoted by the adapter.
  • filter: AND-combined equality/null or $eq/$gt/$gte/$lt/$lte column conditions; other operator objects are rejected.
  • options: Supports sort, limit, and skip; limit/skip must be nonnegative safe integers. Projection and other options are ignored.

Returns: Local rows, or an empty array; remote freshness is not implied.

  • T: Expected local row shape; no runtime schema validation is performed.

Rejects unsupported filters, invalid pagination, or SQLite query failures. Access-stat failures are ignored.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.find("records", { active: true }, { limit: 10 });
} finally { adapter.destroy(); }
}

Counts local rows matching a filter without pagination.

Parameters:

  • collection: Local table identifier, quoted by the adapter.
  • filter: Same supported AND-combined conditions as find.
  • options: Sort is retained; limit and skip are discarded. Other options are ignored.

Returns: Numeric count, or zero if the driver returns no count row.

Rejects unsupported filters or SQLite failures; access-stat failures are ignored.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.count("records");
} finally { adapter.destroy(); }
}

Queries a local row by its id column.

Parameters:

  • collection: Local table identifier.
  • id: ID value bound to an equality filter.
  • options: find options with limit overridden to 1; skip, if supplied, still applies.

Returns: First matching row, or null.

  • T: Expected local row shape; no runtime validation is performed.

Rejects invalid pagination or SQLite query failures.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.findOne("records", "record-1");
} finally { adapter.destroy(); }
}

Inserts a local record before separately enqueueing its upstream INSERT.

Parameters:

  • collection: Provisioned local table identifier.
  • data: Column values; a truthy id is retained, otherwise an ID is generated. Missing tenant columns may receive the configured tenantId. Object values are JSON-encoded for local SQL.
  • _options: Accepted for DataAccessAdapter compatibility and ignored.

Returns: The input record with its chosen ID and optional tenant default, before upstream acknowledgement.

  • T: Expected returned record shape; no runtime validation is performed.

Rejects local SQL, serialization, or enqueue failure; a local insert may already have committed. Background outbox errors are ignored by this call.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.create("records", { title: "Example" });
} finally { adapter.destroy(); }
}

Snapshots a local row, updates its columns, and separately enqueues an upstream UPDATE.

Parameters:

  • collection: Provisioned local table identifier.
  • id: Record ID bound in local SQL and used for upstream update.
  • data: Updated columns; local SQL excludes id but the payload is forwarded unchanged upstream. An empty update can cause a SQLite syntax failure.
  • _options: Accepted for DataAccessAdapter compatibility and ignored.

Returns: Snapshot merged with data and the supplied id, even if no local row existed.

  • T: Expected returned merged record shape.

Rejects snapshot, local SQL, serialization, or enqueue failures; local changes may already have committed.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.update("records", "record-1", { title: "Changed" });
} finally { adapter.destroy(); }
}

Deletes a local row and separately enqueues upstream deletion with a rollback snapshot.

Parameters:

  • collection: Provisioned local table identifier.
  • id: Record ID used for local and upstream deletion.
  • _options: Accepted for DataAccessAdapter compatibility and ignored.

Returns: The previous local record, or an object containing only id when absent.

  • T: Expected deleted record shape.

Rejects snapshot, local delete, or enqueue failures; local deletion may already have committed.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.delete("records", "record-1");
} finally { adapter.destroy(); }
}

Pulls incremental remote changes from Oracle ADB using ORA_ROWSCN cursor within a batch transaction.

Parameters:

  • collection: Provisioned local table whose upstream supports ORA_ROWSCN filtering, ordering, and projection.

Returns: Number of remote rows upserted, or zero when no changes were returned.

Remote deletes are not discovered by this pull. No per-table synchronization lock prevents overlapping pulls or concurrent host transactions.

Rejects upstream or local SQL failures; an opened local transaction is rolled back best-effort on upsert/cursor failure.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.pullChanges("records");
} finally { adapter.destroy(); }
}

Background Outbox Worker: Processes at most 20 pending mutations in creation order, pushes upstream, and attempts rollback for non-network failures.

Returns: No value; resolves after one batch, or immediately if this instance already has a batch running.

Recognized network failures return rows to pending and increment retry_count; no delay/backoff is applied here. Other failures attempt local snapshot rollback and mark failed; rollback/callback errors are logged. Remote success followed by local queue-delete failure may leave an uncertain delivery outcome. There is no cross-instance lease or deduplication.

Rejects metadata reads, malformed persisted JSON, or error-handling SQL failures. Ordinary upstream failures are recorded or rolled back rather than rejected.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
await adapter.processOutbox();
} finally { adapter.destroy(); }
}

Stops this instance’s polling timer and removes its browser focus/online listeners.

Returns: No value; repeated calls are safe. In-flight synchronization continues and drivers remain open.

Example:

import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
adapter.destroy();
} finally { adapter.destroy(); }
}
import { LocalFirstSqliteAdapter, type LocalFirstSqliteAdapterOptions } from "@alneas/eaos-server/db/local-first-sqlite-adapter";
export async function example(options: LocalFirstSqliteAdapterOptions) {
// The host supplies an initialized domain schema and authorized upstream adapter.
const adapter = new LocalFirstSqliteAdapter({ ...options, syncIntervalMs: 0, enableLifecycleSync: false });
try {
await adapter.initSchema();
return await adapter.find("records");
} finally { adapter.destroy(); }
}

[INTERFACE] LocalFirstSqliteAdapterOptions

Section titled “[INTERFACE] LocalFirstSqliteAdapterOptions”

Host drivers, sync behavior, and cleanup-sensitive scheduling for LocalFirstSqliteAdapter.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

interface LocalFirstSqliteAdapterOptions {
sqlite: SqliteDriver;
upstream: DataAccessAdapter;
tenantId?: string;
essentialTables?: string[];
onSyncError?: (event: SyncErrorEvent) => void;
syncIntervalMs?: number;
autoSyncOnMutation?: boolean;
enableLifecycleSync?: boolean;
}
Name Type Required Description
sqlite SqliteDriver Yes SQLite driver instance
upstream DataAccessAdapter Yes Cloud upstream adapter (e.g. OracleOrdsAdapter / SupabaseAdapter)
tenantId string No Optional tenant_id default added only on create when neither tenant_id nor tenantId is supplied; this does not scope reads, updates, deletes, or upstream access. Host authorization remains required.
essentialTables string[] No Essential master tables that are always synchronized (Tier 1)
onSyncError (event: SyncErrorEvent) => void No Callback fired when an outbox sync fails permanently and triggers a rollback
syncIntervalMs number No Outbox polling interval in milliseconds. Zero disables polling; other falsy values fall back to 5000.
autoSyncOnMutation boolean No Whether to immediately trigger background sync after local mutation (default: true)
enableLifecycleSync boolean No Whether to attach window focus / online event listeners (default: true if in browser/tauri)

Type declaration; no runtime value.

SQLite driver instance

Cloud upstream adapter (e.g. OracleOrdsAdapter / SupabaseAdapter)

Optional tenant_id default added only on create when neither tenant_id nor tenantId is supplied; this does not scope reads, updates, deletes, or upstream access. Host authorization remains required.

Essential master tables that are always synchronized (Tier 1)

Callback fired when an outbox sync fails permanently and triggers a rollback

Outbox polling interval in milliseconds. Zero disables polling; other falsy values fall back to 5000.

Default: 5000.

Whether to immediately trigger background sync after local mutation (default: true)

Whether to attach window focus / online event listeners (default: true if in browser/tauri)

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified local-runner identity and routes admitted by the host.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/local-runner.

interface LocalRunnerIdentity {
runnerId: string;
userId: string;
supportedRouteIds: readonly string[];
}
Name Type Required Description
runnerId string Yes Nonblank authenticated runner identifier.
userId string Yes Nonblank authenticated user to whom claimed jobs must belong.
supportedRouteIds readonly string[] Yes Nonempty array of nonblank host-authorized route identifiers.

Type declaration; no runtime value.

LocalRunnerPullCoordinator.

Nonblank authenticated runner identifier.

Nonblank authenticated user to whom claimed jobs must belong.

Nonempty array of nonblank host-authorized route identifiers.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Alias of core job kinds accepted by local runner coordination.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/local-runner.

type LocalRunnerJobKind = AgentJobKind;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

LocalRunnerPullCoordinator.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Server-side queue boundary for a local CLI/MLX runner.

The runner authenticates to the host and pulls jobs; the server never needs the subscription credential. The host must perform authentication and tenant/user authorization before calling claim or submit.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/local-runner.

declare class LocalRunnerPullCoordinator {
constructor(options: LocalRunnerPullCoordinatorOptions);
claim(identity: LocalRunnerIdentity, limit?: number): Promise<readonly AgentJobRecord<ServerAgentTaskRequest>[]>;
submit(identity: LocalRunnerIdentity, job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: ServerAgentTaskResult): Promise<void>;
}
Name Type Required Description
options LocalRunnerPullCoordinatorOptions Yes Queue persistence, clock, retry delay, and optional post-completion callback.

LocalRunnerPullCoordinator

If store is absent or retry delay is outside finite 0–86400000 milliseconds.

Atomically claims local-pull jobs bound to this verified user, runner, and supported routes.

Parameters:

  • identity: Host-authenticated runner identity; see LocalRunnerIdentity.
  • limit: Maximum jobs requested, safe integer 1–100; defaults to 1.

Returns: Store-claimed jobs with leases, or an empty array when none qualify.

Rejects invalid identity/limit and propagated store/clock failures.

Example:

import { LocalRunnerPullCoordinator, type LocalRunnerPullCoordinatorOptions, type LocalRunnerIdentity } from "@alneas/eaos-server/agentic/local-runner";
export async function pull(options: LocalRunnerPullCoordinatorOptions, identity: LocalRunnerIdentity) {
return new LocalRunnerPullCoordinator(options).claim(identity);
}

Persists a leased local-runner outcome after checking its user, route, and runner bindings.

Parameters:

  • identity: Host-authenticated runner identity.
  • job: Host-loaded leased job; must belong to the same user, local-pull mode, supported route, and optional runner binding.
  • result: Runtime result; COMPLETED marks completion, PENDING_APPROVAL waits, other results retry unless retryable is exactly false.

Returns: No value; resolves after the selected store transition and any completion callback.

The host loads the authoritative job and authorizes tenant/user access before calling. Error text is truncated to 1000 characters for retries/failures. Store lease validation is the concurrency boundary; no remote runtime cancellation or automatic retry execution is performed here.

Rejects invalid binding, store/clock/clone errors, or completion callback errors. Callback failure occurs after completion persistence.

Example:

import { LocalRunnerPullCoordinator, type LocalRunnerPullCoordinatorOptions, type LocalRunnerIdentity } from "@alneas/eaos-server/agentic/local-runner";
import type { AgentJobRecord } from "@alneas/eaos-core";
import type { ServerAgentTaskRequest, ServerAgentTaskResult } from "@alneas/eaos-server/agentic/types";
export async function submit(options: LocalRunnerPullCoordinatorOptions, identity: LocalRunnerIdentity, job: AgentJobRecord<ServerAgentTaskRequest>, result: ServerAgentTaskResult) {
await new LocalRunnerPullCoordinator(options).submit(identity, job, result);
}
import { LocalRunnerPullCoordinator, type LocalRunnerPullCoordinatorOptions } from "@alneas/eaos-server/agentic/local-runner";
export function localRunnerQueue(options: LocalRunnerPullCoordinatorOptions) {
return new LocalRunnerPullCoordinator(options);
}

[INTERFACE] LocalRunnerPullCoordinatorOptions

Section titled “[INTERFACE] LocalRunnerPullCoordinatorOptions”

Durable queue and completion notification for LocalRunnerPullCoordinator.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/local-runner.

interface LocalRunnerPullCoordinatorOptions {
store: AgentJobStore;
now?: () => Date;
retryDelayMs?: number;
onCompleted?: (job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: ServerAgentTaskResult) => Promise<void>;
}
Name Type Required Description
store AgentJobStore Yes Host job store enforcing atomic claims and lease ownership.
now () => Date No Clock read once per claim/submit; defaults to a fresh Date.
retryDelayMs number No Retry delay in milliseconds, finite from 0 to 86400000.
onCompleted (job: Readonly<AgentJobRecord<ServerAgentTaskRequest>>, result: ServerAgentTaskResult) => Promise<void> No Called with cloned job/result only after markCompleted succeeds; rejection propagates after the persisted completion.

Type declaration; no runtime value.

Host job store enforcing atomic claims and lease ownership.

Clock read once per claim/submit; defaults to a fresh Date.

Retry delay in milliseconds, finite from 0 to 86400000.

Default: 5000.

Called with cloned job/result only after markCompleted succeeds; rejection propagates after the persisted completion.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Provider identity snapshot used for optimistic checks and metadata-preserving writes.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

interface ManagedIdentity {
id: string;
state: string;
traits?: Record<string, unknown>;
metadata_public?: Record<string, unknown>;
metadata_admin?: Record<string, unknown>;
}
Name Type Required Description
id string Yes Provider identity ID.
state string Yes Provider lifecycle state; membership operations require active.
traits Record<string, unknown> No Optional editable traits; never used as membership authority here.
metadata_public Record<string, unknown> No Public provider metadata; published membership fields are user-visible.
metadata_admin Record<string, unknown> No Private administrator metadata; legacy membership migration defaults to this field.

Type declaration; no runtime value.

planAccountMembershipPublication.

Provider identity ID.

Provider lifecycle state; membership operations require active.

Optional editable traits; never used as membership authority here.

Public provider metadata; published membership fields are user-visible.

Private administrator metadata; legacy membership migration defaults to this field.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-verified identity, roles, and enabled plugins used for MCP discovery and execution.

Imports: @alneas/eaos-server, @alneas/eaos-server/mcp.

interface McpPrincipal {
userId: string;
tenantId: string;
roles: string[];
enabledPluginIds: string[];
}
Name Type Required Description
userId string Yes Nonblank authenticated user identifier.
tenantId string Yes Nonblank authorized tenant identifier.
roles string[] Yes Verified role strings passed to the gatekeeper; an empty array is permitted.
enabledPluginIds string[] Yes Exact installed plugin IDs, resolved from the server’s current tenant configuration.

Type declaration; no runtime value.

createMcpRouter.

Nonblank authenticated user identifier.

Nonblank authorized tenant identifier.

Verified role strings passed to the gatekeeper; an empty array is permitted.

Exact installed plugin IDs, resolved from the server’s current tenant configuration.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Live host authorization, resource injection, and bounded SSE-session settings for createMcpRouter.

Imports: @alneas/eaos-server, @alneas/eaos-server/mcp.

interface McpRouterOptions {
entitlements?: PluginEntitlementRuntime;
isPluginEnabled?: (principal: McpPrincipal, pluginId: string) => Promise<boolean>;
resolvePrincipal: (context: Context) => Promise<McpPrincipal | null>;
tenantId?: string;
createToolContext?: (principal: McpPrincipal, pluginId: string) => Promise<Record<string, unknown>>;
resolveAIHostAdapters?: (input: {
principal: McpPrincipal;
pluginId: string;
toolName: string;
context: AIExecutionContext;
}) => Promise<AIHostAdapters | undefined>;
onError?: (error: unknown) => void;
sseSessionTtlMs?: number;
maxSseSessions?: number;
}
Name Type Required Description
entitlements PluginEntitlementRuntime No Runtime for declared commercial/usage entitlements; required by plugins whose rules need external entitlement checks.
isPluginEnabled (principal: McpPrincipal, pluginId: string) => Promise<boolean> No Additional current lifecycle gate; called on discovery and immediately before execution.
resolvePrincipal (context: Context) => Promise<McpPrincipal | null> Yes Must verify authentication, tenant membership and enabled plugins on every request.
tenantId string No Optional binding for a tenant-dedicated backend.
createToolContext (principal: McpPrincipal, pluginId: string) => Promise<Record<string, unknown>> No Inject already tenant-scoped resources; never pass an unrestricted administrative DB.
resolveAIHostAdapters (input: { principal: McpPrincipal; pluginId: string; toolName: string; context: AIExecutionContext; }) => Promise<AIHostAdapters | undefined> No Resolve provider-neutral AI adapters after live authorization; the result is injected into the verified tool context.
onError (error: unknown) => void No Operational errors only; request bodies/credentials are not passed.
sseSessionTtlMs number No Maximum SSE session age and inactivity in milliseconds; finite values are floored and clamped to at least 1000. Defaults to 1800000 for absent/nonfinite input.
maxSseSessions number No Per-router SSE session capacity; finite values are floored and clamped to at least 1. Defaults to 1000 for absent/nonfinite input.

Type declaration; no runtime value.

Runtime for declared commercial/usage entitlements; required by plugins whose rules need external entitlement checks.

Additional current lifecycle gate; called on discovery and immediately before execution.

Must verify authentication, tenant membership and enabled plugins on every request.

Optional binding for a tenant-dedicated backend.

Inject already tenant-scoped resources; never pass an unrestricted administrative DB.

Resolve provider-neutral AI adapters after live authorization; the result is injected into the verified tool context.

Verified current request principal after membership and enabled-plugin resolution.

Owning plugin whose admitted tool needs host AI adapters.

Exact registered MCP tool name being executed.

Verified AI execution identity, operation mcp:toolName, and generated trace ID; no client scope overrides are accepted here.

Operational errors only; request bodies/credentials are not passed.

Maximum SSE session age and inactivity in milliseconds; finite values are floored and clamped to at least 1000. Defaults to 1800000 for absent/nonfinite input.

Per-router SSE session capacity; finite values are floored and clamped to at least 1. Defaults to 1000 for absent/nonfinite input.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Shared registry and policy/audit service used by createMcpRouter.

Imports: @alneas/eaos-server, @alneas/eaos-server/mcp.

interface McpRuntime {
registry: PluginRegistry;
gatekeeper: McpGatekeeper;
}
Name Type Required Description
registry PluginRegistry Yes Registry supplying trusted manifests and executable tool handlers. Duplicate tool names fail discovery/execution.
gatekeeper McpGatekeeper Yes Current permission/approval policy and audit sink consulted for tool discovery and calls.

Type declaration; no runtime value.

Registry supplying trusted manifests and executable tool handlers. Duplicate tool names fail discovery/execution.

Current permission/approval policy and audit sink consulted for tool discovery and calls.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Verified tenant membership candidate supplied to createPlatformSessionResolver.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/platform-session.

interface Membership {
tenantId: string;
roles: string[];
enabledModules: string[];
}
Name Type Required Description
tenantId string Yes Tenant ID matching the selected header, if provided; validated as a 1–128-character scope identifier.
roles string[] Yes Verified role names, each a nonempty string.
enabledModules string[] Yes Verified entitlement names, each a nonempty string.

Type declaration; no runtime value.

Tenant ID matching the selected header, if provided; validated as a 1–128-character scope identifier.

Verified role names, each a nonempty string.

Verified entitlement names, each a nonempty string.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reviewed membership replacement bound to a hash of the selected metadata snapshot.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

interface MembershipMigrationPlan {
identityId: string;
beforeMetadataHash: string;
memberships: AccountMemberships;
metadataField?: AccountMetadataField;
}
Name Type Required Description
identityId string Yes Identity whose metadata is being changed.
beforeMetadataHash string Yes metadataHash of the selected metadata field before the change.
memberships AccountMemberships Yes Validated target membership claims; all membership fields are replaced.
metadataField AccountMetadataField No Metadata destination; omitted preserves the metadata_admin migration contract.

Type declaration; no runtime value.

applyAccountMembershipChange.

Identity whose metadata is being changed.

metadataHash of the selected metadata field before the change.

Validated target membership claims; all membership fields are replaced.

Metadata destination; omitted preserves the metadata_admin migration contract.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reviewed plan moving existing private membership fields into public metadata without changing claims.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

interface MembershipPublicationPlan {
identityId: string;
beforeMetadataHash: string;
memberships: AccountMemberships;
}
Name Type Required Description
identityId string Yes Active identity whose memberships will become public.
beforeMetadataHash string Yes Combined public/admin metadata snapshot hash used to detect stale plans.
memberships AccountMemberships Yes Validated claims copied from private membership fields.

Type declaration; no runtime value.

planAccountMembershipPublication.

Active identity whose memberships will become public.

Combined public/admin metadata snapshot hash used to detect stale plans.

Validated claims copied from private membership fields.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Stores cloned values in a bounded process-local cache with TTL and tag invalidation.

Imports: @alneas/eaos-server/cache.

declare class MemoryCacheManager {
constructor(options?: {
maxEntries?: number;
defaultTtlMs?: number;
});
isNoCacheRequested: typeof isNoCacheRequested;
set<T>(key: string, value: T, ttlMs?: number, tags?: string[]): void;
getOrSet<T>(key: string, fetcher: () => Promise<T>, options?: CacheOptions): Promise<T>;
invalidateTags(tags: string | string[]): void;
invalidatePrefix(prefix: string): void;
clear(): void;
size(): number;
forScope(scope: CacheScope, authorize: () => boolean | Promise<boolean>): {
getOrSet: <T>(key: string, fetcher: () => Promise<T>, options?: CacheOptions) => Promise<T>;
invalidate: () => void;
};
}
Name Type Required Description
options { maxEntries?: number; defaultTtlMs?: number; } No maxEntries defaults to 1000 and must be a positive safe integer; defaultTtlMs defaults to 60000 milliseconds and must be finite and nonnegative.

MemoryCacheManager

Values must support structuredClone. Entries expire lazily on access; no timers, persistent storage, or cross-process invalidation are installed. Capacity eviction removes the oldest inserted entry. Concurrent misses run separate fetchers; only the latest fetch started for a key may populate it, and any invalidation prevents previously started fetches from repopulating entries.

If capacity or default retention is invalid.

Maximum retained cache entries; defaults to 1000 and must be a positive safe integer. Capacity eviction removes the oldest inserted entry.

Default retention in milliseconds, finite and nonnegative; defaults to 60000. Zero disables retaining newly fetched/set entries.

Request bypass detector; see isNoCacheRequested for parameter semantics and example.

Stores a cloned value, replacing an existing key and invalidating its in-flight fetch token.

Parameters:

  • key: Exact cache key, without automatic authorization or partitioning.
  • value: Value to clone for storage.
  • ttlMs: Nonnegative finite milliseconds from the current clock; defaults to the manager retention. Zero removes the prior entry without storing.
  • tags: Invalidation tags; duplicates are collapsed and omission uses none.

Returns: No value; completes after cloning and inserting or removing the entry.

  • T: Structured-cloneable value type.

For invalid TTL or a value that cannot be structured-cloned. A previous entry may already have been removed when cloning fails.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
cache.set("answer", { value: 42 }, 1000, ["answers"]);

Returns a cloned cached value or fetches and conditionally caches a new value.

Parameters:

  • key: Exact cache key; use forScope for authenticated partitions.
  • fetcher: Called without arguments on a miss or bypass; resolves a cloneable value. Concurrent misses are not coalesced.
  • options: Retention, tags, and bypass settings; see CacheOptions.

Returns: A separate clone of the cached or fetched value, including when invalidation prevents storage.

  • T: Structured-cloneable value returned by fetcher and this method.

Rejects on fetcher failure, invalid TTL used for insertion, or structuredClone failure.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
console.log(await cache.getOrSet("answer", async () => 42));

Removes entries carrying any requested tag and prevents pending fetches from populating the cache.

Parameters:

  • tags: One exact tag or multiple tags; an empty array removes no stored entries but still invalidates pending writes.

Returns: No value; removal completes synchronously.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
cache.set("answer", 42, 1000, ["answers"]);
cache.invalidateTags("answers");

Removes entries whose exact keys start with the supplied prefix and invalidates pending writes.

Parameters:

  • prefix: Case-sensitive key prefix; an empty prefix matches every entry.

Returns: No value; removal completes synchronously.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
cache.invalidatePrefix("reports:");

Removes every cached entry, tag index, and pending write token.

Returns: No value; clearing completes synchronously without cancelling fetchers already running.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
cache.clear();

Prunes expired entries and counts the remaining stored values.

Returns: Current number of unexpired entries, excluding pending fetches.

Example:

import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
console.log(cache.size()); // 0

Creates a tenant/plugin/user partition with authorization before and after asynchronous work.

Parameters:

  • scope: Verified nonblank identity IDs and optional permission revision; see CacheScope.
  • authorize: Called without arguments on every lookup, including hits, and after fetching and before returning. Any truthy result permits access; errors propagate.

Returns: A scoped getOrSet using the same key/fetcher/options semantics as this manager, plus invalidate(), which removes this partition without returning a value or calling authorize.

Tenant and plugin tags are added to fetched entries. The host must supply trusted identity and live authorization; partitioning does not authenticate callers. Invalidating a scope also prevents other in-flight manager fetches from populating entries.

Synchronously for missing/blank scope IDs. Scoped lookups reject for denied access or propagated authorization/fetch/clone errors.

Example:

import { MemoryCacheManager, type CacheScope } from "@alneas/eaos-server/cache";
export function userCache(scope: CacheScope, authorize: () => Promise<boolean>) {
return new MemoryCacheManager().forScope(scope, authorize);
}
import { MemoryCacheManager } from "@alneas/eaos-server/cache";
const cache = new MemoryCacheManager();
const result = await cache.getOrSet("answer", async () => ({ value: 42 }));
console.log(result.value);
cache.clear();

Hashes metadata after recursively sorting object keys while preserving array order.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

declare function metadataHash(metadata: unknown): string;
Name Type Required Description
metadata unknown Yes JSON-serializable metadata; null/undefined at the root are normalized to an empty object.

string

Lower-case SHA-256 hexadecimal digest of canonicalized JSON.

This is an optimistic snapshot comparison, not a signature or authentication mechanism.

For cyclic, BigInt, or other values that JSON serialization cannot encode.

import { metadataHash } from "@alneas/eaos-server/browser-auth/account-memberships";
console.log(metadataHash({ b: 2, a: 1 }) === metadataHash({ a: 1, b: 2 })); // true

Collects plugin schema sources and renders legacy PostgreSQL or Oracle DDL text.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/migration, @alneas/eaos-server/db/migration/aggregator.

declare class MigrationAggregator {
constructor(plugins: PluginManifest[], dataContracts?: DataContract[]);
collectSchemas(resolveSchema: (pluginId: string, extensionId?: string) => Record<string, any> | null): SchemaSource[];
generatePostgres(sources: SchemaSource[], dbDriver?: string): string;
generateOracle(sources: SchemaSource[]): string;
}
Name Type Required Description
plugins PluginManifest[] Yes Manifests consulted on every collection call; the array is retained rather than cloned.
dataContracts DataContract[] No Available contracts used to resolve manifest requirements; defaults to none and is retained.

MigrationAggregator

Generation never executes SQL. Schema identifiers, defaults, and comments are interpolated from trusted schema inputs; review generated SQL before applying it. Canonical data-contract JSON Schema requires reviewed lifecycle migrations rather than these legacy converters.

Collects resolved data contracts first, then plugin and extension schemas by migration order.

Parameters:

  • resolveSchema: Called with plugin ID and optional extension ID; returns a legacy schema or null to skip it. Plugin schemas declaring data contracts skip the plugin-level callback, but extensions are still resolved.

Returns: Ordered schema sources; manifests with equal order retain their sort order and missing callback results are omitted.

Propagates contract resolution or callback errors.

Example:

import { MigrationAggregator } from "@alneas/eaos-server/db/migration/aggregator";
const aggregator = new MigrationAggregator([]);
console.log(aggregator.collectSchemas(() => null)); // []

Renders PostgreSQL table DDL and tenant_id row-level-security policies as text.

Parameters:

  • sources: Trusted legacy schemas rendered in supplied order. Every table must declare tenant_id not explicitly nullable.
  • dbDriver: Label included in SQL comments only; defaults to postgres and does not change dialect.

Returns: SQL text with a generated timestamp, CREATE TABLE IF NOT EXISTS, and tenant policies using app.current_tenant as UUID.

The host must set app.current_tenant appropriately and review/apply SQL separately.

For canonical x-db/$defs schemas or missing/nullable tenant_id columns.

Example:

import { MigrationAggregator } from "@alneas/eaos-server/db/migration/aggregator";
const aggregator = new MigrationAggregator([]);
console.log(aggregator.generatePostgres([]));

Renders legacy Oracle table DDL as text.

Parameters:

  • sources: Trusted legacy schemas rendered in supplied order; every table must declare tenant_id not explicitly nullable.

Returns: SQL text with a generated timestamp and CREATE TABLE statements; no VPD policies or default clauses are emitted by this converter.

Applying SQL and enforcing Oracle tenant isolation remain host responsibilities.

For canonical x-db/$defs schemas or missing/nullable tenant_id columns.

Example:

import { MigrationAggregator } from "@alneas/eaos-server/db/migration/aggregator";
const aggregator = new MigrationAggregator([]);
console.log(aggregator.generateOracle([]));
import { MigrationAggregator } from "@alneas/eaos-server/db/migration/aggregator";
const aggregator = new MigrationAggregator([]);
console.log(aggregator.generatePostgres([]));

Durable per-database/tenant migration progress and immutable definition checksum.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/lifecycle-engine.

interface MigrationRecord {
databaseId: string;
pluginId: string;
migrationId: string;
position: number;
tenantId: string | null;
checksum: string;
status: 'running' | 'applied' | 'failed';
}
Name Type Required Description
databaseId string Yes Physical database on which the migration executes.
pluginId string Yes Plugin or canonical data-contract migration identity.
migrationId string Yes Immutable migration definition ID.
position number Yes Zero-based position in the append-only migration history.
tenantId string | null Yes Concrete tenant for tenant-scoped work, or null for database scope.
checksum string Yes Canonical definition digest used to detect rewritten applied SQL.
status 'running' | 'applied' | 'failed' Yes Running/applied/failed progress; running and failed require reconciliation before planning further changes.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Physical database on which the migration executes.

Plugin or canonical data-contract migration identity.

Immutable migration definition ID.

Zero-based position in the append-only migration history.

Concrete tenant for tenant-scoped work, or null for database scope.

Canonical definition digest used to detect rewritten applied SQL.

Running/applied/failed progress; running and failed require reconciliation before planning further changes.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Planned migration ledger identity and ordered SQL to execute on one physical target.

Imports: @alneas/eaos-server/lifecycle-engine.

interface MigrationStep {
key: string;
record: MigrationRecord;
statements: string[];
}
Name Type Required Description
key string Yes Exact ledger map key for this migration and scope.
record MigrationRecord Yes Initial running migration receipt with immutable checksum.
statements string[] Yes Reviewed target-dialect SQL executed in order by the host migrate adapter.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Exact ledger map key for this migration and scope.

Initial running migration receipt with immutable checksum.

Reviewed target-dialect SQL executed in order by the host migrate adapter.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Controls the explicit development bypass for createModuleGuard.

Imports: @alneas/eaos-server, @alneas/eaos-server/middleware/module-guard.

interface ModuleGuardOptions {
isDev?: boolean;
}
Name Type Required Description
isDev boolean No Skip entitlement checks when true; defaults to NODE_ENV === “development”.

Type declaration; no runtime value.

Skip entitlement checks when true; defaults to NODE_ENV === “development”.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Mounts tenant-dispatched extension routes, allowing a shared prefix across disjoint tenant scopes.

Imports: @alneas/eaos-server/extensions.

declare function mountExtensionRoutes(app: Hono, extensions: PlatformExtension[], requireModule: (id: string) => MiddlewareHandler): void;
Name Type Required Description
app Hono Yes Host Hono app mutated with exact-prefix and descendant dispatch routes.
extensions PlatformExtension[] Yes Trusted validated extensions with explicit tenant IDs.
requireModule (id: string) => MiddlewareHandler Yes Host factory producing current module authorization middleware for each route moduleId.

void

No value; completes after mounting all route groups.

Install verified identity/tenant middleware before these routes. Dispatch copies parent context variables into the selected child and forwards server environment; missing tenant scope returns 403. There is no automatic route unmount or per-request persistence.

For an overlapping tenant at the same prefix, or propagated route/middleware composition errors.

import { Hono } from "hono";
import { mountExtensionRoutes, type PlatformExtension } from "@alneas/eaos-server/extensions";
import { createModuleGuard } from "@alneas/eaos-server/middleware/module-guard";
export function mount(app: Hono, extensions: PlatformExtension[]) {
mountExtensionRoutes(app, extensions, id => createModuleGuard(id, { isDev: false }));
}

Clones a historical ledger snapshot and fills missing platform maps without rewriting storage.

Add fields introduced after the original snapshot format without rewriting old control rows on read.

Imports: @alneas/eaos-server/lifecycle-engine.

declare function normalizeLifecycleState(input: LifecycleState): LifecycleState;
Name Type Required Description
input LifecycleState Yes Historical state snapshot to normalize.

LifecycleState

A structured clone with a complete platform object; unrelated state validation remains the caller’s responsibility.

Error for nonobject input or malformed platform/maps; structuredClone errors propagate.

import { emptyLifecycleState, normalizeLifecycleState } from '@alneas/eaos-server/lifecycle-engine';
const state = normalizeLifecycleState(emptyLifecycleState());

Lifecycle change to installation or tenant activation; disable/uninstall retain business data.

Imports: @alneas/eaos-server/lifecycle-engine.

type Operation = 'install' | 'update' | 'enable' | 'disable' | 'uninstall';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host Oracle connection subset used with autocommit disabled and explicit commit/rollback.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface OracleAtomicConnection {
execute(sql: string, binds: unknown[], options: {
autoCommit: false;
outFormat: number;
fetchInfo?: Record<string, {
type: unknown;
}>;
}): Promise<{
rows?: Record<string, unknown>[];
rowsAffected?: number;
}>;
executeMany?(sql: string, binds: unknown[][], options: {
autoCommit: false;
dmlRowCounts: true;
}): Promise<{
dmlRowCounts?: number[];
}>;
commit(): Promise<void>;
rollback(): Promise<void>;
}
Name Type Required Description
execute Promise<{ rows?: Record<string, unknown>[]; rowsAffected?: number; }> Yes Executes one parameterized Oracle statement without autocommit.
executeMany Promise<{ dmlRowCounts?: number[]; }> No Executes ordered Oracle bind batches without autocommit.
commit Promise<void> Yes Explicitly commits the current Oracle transaction.
rollback Promise<void> Yes Explicitly rolls back the current Oracle transaction.

Type declaration; no runtime value.

createOracleAtomicDriver for canonical host integration.

Executes one parameterized Oracle statement without autocommit.

Parameters:

  • sql: Trusted parameterized SQL.
  • binds: Ordered bind values, including explicit CLOB bindings for large payloads.
  • options: Provider options requiring autoCommit=false and object row format, with optional per-column fetch types.

Returns: Optional object rows and rowsAffected count.

Rejects Oracle execution/binding failures.

Example:

import type { OracleAtomicHost, OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';
export async function queryTenant(host: OracleAtomicHost, tenantId: string, trustedTenantSql: string, binds: unknown[], options: Parameters<OracleAtomicConnection["execute"]>[2]) {
return host.withTenantConnection("PLUGIN_RECORDS", async connection => {
return (await connection.execute(trustedTenantSql, binds, options)).rows ?? [];
}, { tenantId });
}

Optional Oracle object rows returned by a query.

Optional scalar DML affected-row count; adapter normalizes absence to 0.

Must be false so the host transaction explicitly commits or rolls back all joined work.

Actual Oracle object-row output constant supplied by the installed driver.

Optional column-name to explicit fetch-type settings, including PAYLOAD string extraction.

Actual installed Oracle provider type constant; no global conversion settings are changed.

Executes ordered Oracle bind batches without autocommit.

Parameters:

  • sql: Trusted parameterized DML.
  • binds: Ordered positional bind rows.
  • options: Provider options requiring autoCommit=false and dmlRowCounts=true.

Returns: Per-bind-row DML counts; adapters reject missing/invalid lengths or counts.

Rejects Oracle batch/binding failures.

Example:

import type { OracleAtomicHost } from '@alneas/eaos-server/plugin-data';
export async function batchReviewed(host: OracleAtomicHost, tenantId: string, trustedTenantDml: string, binds: unknown[][]) {
return host.withTenantConnection("PLUGIN_RECORDS", async connection => {
if (!connection.executeMany) throw new Error("Batch DML not supported");
try {
const result = await connection.executeMany(trustedTenantDml, binds, { autoCommit: false, dmlRowCounts: true });
await connection.commit();
return result.dmlRowCounts;
} catch (error) { await connection.rollback(); throw error; }
}, { tenantId });
}

Requested per-row batch counts (true in options), or returned per-bind-row counts in the result.

Must be false so the host transaction explicitly commits or rolls back all joined work.

Requested per-row batch counts (true in options), or returned per-bind-row counts in the result.

Explicitly commits the current Oracle transaction.

Returns: Resolves without a value after provider commit completes.

Rejects provider commit failure.

Example:

import type { OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';
export async function commitOwned(connection: OracleAtomicConnection) {
// Only the owner of this transaction chooses its completion outcome.
await connection.commit();
}

Explicitly rolls back the current Oracle transaction.

Returns: Resolves without a value after provider rollback completes.

Rejects provider rollback failure.

Example:

import type { OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';
export async function rollbackOwned(connection: OracleAtomicConnection) {
// Only the owner of this transaction chooses its completion outcome.
await connection.rollback();
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted tenant Oracle connection acquisition and cleanup boundary.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface OracleAtomicHost {
withTenantConnection<T>(domain: string, callback: (connection: OracleAtomicConnection) => Promise<T>, context: {
tenantId: string;
userId?: string;
}): Promise<T>;
}
Name Type Required Description
withTenantConnection Promise<T> Yes Acquires a verified tenant Oracle connection and cleans up its host session after work.

Type declaration; no runtime value.

createOracleAtomicDriver for canonical host integration.

Acquires a verified tenant Oracle connection and cleans up its host session after work.

Parameters:

  • domain: Trusted connection domain; this adapter uses PLUGIN_RECORDS.
  • callback: Async work receiving the single admitted connection.
  • context: Verified tenant/user session context; must not come from raw request authority.

Returns: The callback result after host session cleanup and connection release.

  • T: Value resolved by the transaction/connection callback.

Rejects acquisition, admission, callback or cleanup failures.

Example:

import type { OracleAtomicHost } from '@alneas/eaos-server/plugin-data';
export async function inspectTenant(host: OracleAtomicHost, tenantId: string, userId: string, inspect: (connection: Parameters<Parameters<OracleAtomicHost["withTenantConnection"]>[1]>[0]) => Promise<unknown>) {
return host.withTenantConnection("PLUGIN_RECORDS", inspect, { tenantId, userId });
}

Verified concrete tenant admitted by the host session boundary.

Optional verified actor ID attached to the Oracle session.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Local mutation and rollback snapshot awaiting upstream synchronization.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

interface OutboxItem {
id: string;
tableName: string;
recordId: string;
operation: 'INSERT' | 'UPDATE' | 'DELETE';
payload: Record<string, any>;
previousState?: Record<string, any> | null;
status: SyncStatus;
errorMessage?: string;
retryCount: number;
createdAt: string;
}
Name Type Required Description
id string Yes Outbox row identifier.
tableName string Yes Target local/upstream table.
recordId string Yes Mutation record identifier.
operation 'INSERT' | 'UPDATE' | 'DELETE' Yes INSERT, UPDATE, or DELETE operation forwarded upstream.
payload Record<string, any> Yes Mutation data; update retains only the supplied changes.
previousState Record<string, any> | null No Optional pre-mutation row used for rollback; null for inserts or missing snapshots.
status SyncStatus Yes Persisted synchronization state.
errorMessage string No Optional most recent persisted error description.
retryCount number Yes Number of recognized transient failures recorded so far.
createdAt string Yes ISO creation timestamp used for batch ordering.

Type declaration; no runtime value.

LocalFirstSqliteAdapter.processOutbox.

Outbox row identifier.

Target local/upstream table.

Mutation record identifier.

INSERT, UPDATE, or DELETE operation forwarded upstream.

Mutation data; update retains only the supplied changes.

Optional pre-mutation row used for rollback; null for inserts or missing snapshots.

Persisted synchronization state.

Optional most recent persisted error description.

Number of recognized transient failures recorded so far.

ISO creation timestamp used for batch ordering.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Normalizes bounded tenant memberships while rejecting duplicate tenant grants and platform-wide roles.

Fail closed on malformed/duplicate membership data; provider metadata is host-owned.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

declare function parseAccountMemberships(value: unknown): AccountMemberships;
Name Type Required Description
value unknown Yes Host-owned verified provider metadata with at most 1000 membership entries and optional active defaultTenantId.

AccountMemberships

New membership records and an optional default tenant; unknown metadata fields are omitted.

Tenant roles do not grant platform administration. Parsing validates shape, not metadata authenticity; business directory people never establish access.

Error for malformed IDs/roles, duplicate tenants, nonboolean active flags, forbidden global roles or a default outside active memberships.

import { parseAccountMemberships } from '@alneas/eaos-server/platform/user-directory';
const account = parseAccountMemberships({ memberships: [{ tenantId: 'sample', role: 'member', active: true }], defaultTenantId: 'sample' });

Decode a cursor only when its scope hash and logical record key match the current query.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function parseRecordCursor(scope: unknown, cursor?: string): string;
Name Type Required Description
scope unknown Yes Current tenant/user/operation/filter scope.
cursor string No Optional base64url cursor; omission returns the initial empty position.

string

Validated exclusive record ID, or an empty string for no cursor.

Throws PluginError 400 for invalid encoding/JSON, changed scope or invalid record keys.

import { parseRecordCursor } from '@alneas/eaos-server/plugin-data'
const after = parseRecordCursor(['example-tenant', 'list'])

Validates and clones a nonsecret host publication policy for one supported publication mode.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/site-publication.

declare function parseSitePublicationPolicy(value: unknown): SitePublicationPolicy;
Name Type Required Description
value unknown Yes Untrusted plain policy declaration with explicit mode, approval flag and trigger plus mode-specific references.

SitePublicationPolicy

A structured clone narrowed to SitePublicationPolicy.

Secret fields contain uppercase environment/binding names, never actual secret values. Manual publication requires operator trigger. Parsing does not execute publication, grant approval or contact a provider.

Error for unknown/extra fields, malformed provider references, invalid secret-reference names or unsupported trigger/mode combinations.

import { parseSitePublicationPolicy } from '@alneas/eaos-server/platform/site-publication';
const policy = parseSitePublicationPolicy({ mode: 'manual', requireApproval: true, trigger: 'operator' });

One supported business relationship category from personKinds.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

type PersonKind = typeof personKinds[number];
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

parseAccountMemberships for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported business directory person categories; categories never grant account membership.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

declare const personKinds: readonly [
"employee",
"contractor",
"partner_contact",
"customer_contact",
"other"
];
Name Type Required Description
— — — No call parameters.

Declared constant value.

parseAccountMemberships for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

[FUNCTION] planAccountMembershipPublication

Section titled “[FUNCTION] planAccountMembershipPublication”

Plans moving existing administrator membership claims into public identity metadata.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

declare function planAccountMembershipPublication(identity: ManagedIdentity): MembershipPublicationPlan;
Name Type Required Description
identity ManagedIdentity Yes Active authoritative identity snapshot containing private membership fields and no public membership fields.

MembershipPublicationPlan

A new publication plan binding parsed claims to the combined public/admin metadata hash; no writes occur.

Review the returned plan before publication: membership fields become visible to the account holder.

For inactive identity, missing private memberships, existing public membership fields, invalid claims, or unhashable metadata.

import { planAccountMembershipPublication, type AccountAdminPort } from "@alneas/eaos-server/browser-auth/account-memberships";
export async function reviewPlan(admin: AccountAdminPort, identityId: string) {
return planAccountMembershipPublication(await admin.read(identityId));
}

Creates a deterministic source-retaining migration plan without touching either database.

Create a reviewable fleet/tenant data-migration plan without touching either backend.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/backend-migration.

declare function planBackendMigration(request: BackendMigrationRequest): BackendMigrationPlan;
Name Type Required Description
request BackendMigrationRequest Yes Reviewed distinct physical source/target backends, concrete tenant scope, nonempty unique plugin IDs, timestamp and reason.

BackendMigrationPlan

A shallow-frozen plan with sorted cloned scopes/plugin IDs and five ordered phases.

Dedicated backend tenants must appear in explicit tenant scope. No executor, lock, provisioning, copy or cutover runs during planning; host must implement quiescence.

Error for malformed request, same source/target identity, invalid scope or dedicated-tenant mismatch.

import { planBackendMigration } from '@alneas/eaos-server/lifecycle-engine/backend-migration';
const plan = planBackendMigration({ migrationId: 'move-1', source: { id: 'old', databaseId: 'db-old', dialect: 'sqlite', mode: 'shared' }, target: { id: 'new', databaseId: 'db-new', dialect: 'postgres', mode: 'shared' }, scope: { kind: 'tenants', tenantIds: ['sample'] }, pluginIds: ['reports'], requestedAt: '2026-01-01T00:00:00Z', reason: 'Reviewed backend move' });

Hono variable/environment key for the host-only PlatformPluginAuthorization binding.

Imports: @alneas/eaos-server/extensions.

declare const PLATFORM_PLUGIN_AUTHORIZATION = "eaosPlatformPluginAuthorization";
Name Type Required Description
— — — No call parameters.

Declared constant value.

getPlatformPluginAuthorization for access behavior.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Explicit platform administrative permissions checked independently from tenant roles.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

type PlatformAdminAction = 'tenant:list' | 'tenant:create' | 'tenant:update' | 'backend:list' | 'placement:read' | 'placement:plan' | 'placement:cutover' | 'placement:rollback' | 'placement:reconcile';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Metadata-only platform administration outcome bound to verified actor and affected scope.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformAdminAuditEvent {
action: PlatformAdminAction;
actorId: string;
tenantId?: string;
sourceBackendId?: string;
targetBackendId?: string;
migrationId?: string;
outcome: 'allowed' | 'denied' | 'failed';
occurredAt: string;
}
Name Type Required Description
action PlatformAdminAction Yes Requested platform administrative permission.
actorId string Yes Verified operator identity.
tenantId string No Optional affected concrete tenant.
sourceBackendId string No Optional existing source backend reference.
targetBackendId string No Optional reviewed target backend reference.
migrationId string No Optional backend migration identity.
outcome 'allowed' | 'denied' | 'failed' Yes Allowed/denied/failed result reported by the host.
occurredAt string Yes Audit occurrence timestamp.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Requested platform administrative permission.

Verified operator identity.

Optional affected concrete tenant.

Optional existing source backend reference.

Optional reviewed target backend reference.

Optional backend migration identity.

Allowed/denied/failed result reported by the host.

Audit occurrence timestamp.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host authentication and live action/tenant authorization for platform administration.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformAdminAuthorization {
resolvePrincipal(request: Request): Promise<PlatformAdminPrincipal | null>;
authorize(principal: PlatformAdminPrincipal, action: PlatformAdminAction, tenantId?: string): Promise<boolean>;
}
Name Type Required Description
resolvePrincipal Promise<PlatformAdminPrincipal | null> Yes Resolve verified current operator identity from the request, or null when unauthenticated.
authorize Promise<boolean> Yes Check current platform administrator permission for an action and optional concrete tenant; false denies access.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Resolve verified current operator identity from the request, or null when unauthenticated.

Parameters:

  • request: Current authenticated HTTP request; resolve identity through trusted host session verification.

Returns: The verified platform operator, or null when unauthenticated.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformAdminAuthorization } from '@alneas/eaos-server/platform';
export async function authenticate(port: PlatformAdminAuthorization, request: Request) {
const principal = await port.resolvePrincipal(request);
return principal?.isPlatformAdmin === true ? principal : null;
}

Check current platform administrator permission for an action and optional concrete tenant; false denies access.

Parameters:

  • principal: Verified current platform operator identity.
  • action: Specific platform administrative permission to check against live policy.
  • tenantId: Verified concrete tenant ID whose current state or permission is requested.

Returns: True only when live platform action/scope policy permits access.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformAdminAuthorization } from '@alneas/eaos-server/platform';
export async function canList(port: PlatformAdminAuthorization, request: Request) {
const principal = await port.resolvePrincipal(request);
return principal?.isPlatformAdmin === true && await port.authorize(principal, "tenant:list");
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-verified platform operator identity; tenant membership roles alone cannot grant platform administration.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformAdminPrincipal {
userId: string;
isPlatformAdmin: boolean;
roles?: readonly string[];
}
Name Type Required Description
userId string Yes Authenticated platform actor identity.
isPlatformAdmin boolean Yes Explicit trusted platform-administrator claim.
roles readonly string[] No Optional verified platform role metadata used by host authorization.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Authenticated platform actor identity.

Explicit trusted platform-administrator claim.

Optional verified platform role metadata used by host authorization.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted control-plane authorization, persistence, audit, and optional migration execution dependencies.

Imports: @alneas/eaos-server, @alneas/eaos-server/platform-admin.

interface PlatformAdminRouterOptions extends PlatformAdminAuthorization {
store: PlatformControlStore;
audit: (event: Readonly<PlatformAdminAuditEvent>) => Promise<void>;
placementExecutor?: PlatformPlacementExecutor;
now?: () => Date;
}
Name Type Required Description
store PlatformControlStore Yes Shared authoritative tenant/backend/placement store.
audit (event: Readonly<PlatformAdminAuditEvent>) => Promise<void> Yes Awaited on denied and successful mutations; receives operator/action/outcome/time, without request credentials. Audit failure may occur after persistence.
placementExecutor PlatformPlacementExecutor No Optional host migration executor; absent returns 501 for execute requests. Provisioning, credentials, and SQL remain host-owned.
now () => Date No Clock for audit/plan timestamps; defaults to fresh Date.

Type declaration; no runtime value.

createPlatformAdminRouter.

Shared authoritative tenant/backend/placement store.

Awaited on denied and successful mutations; receives operator/action/outcome/time, without request credentials. Audit failure may occur after persistence.

Optional host migration executor; absent returns 501 for execute requests. Provisioning, credentials, and SQL remain host-owned.

Clock for audit/plan timestamps; defaults to fresh Date.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Existing opaque backend target plus nonsecret host metadata.

Backend IDs and database IDs are opaque host references, never DSNs or credentials.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformBackendRecord extends BackendTarget {
label?: string;
provider?: string;
capabilities?: readonly string[];
}
Name Type Required Description
label string No Optional display caption.
provider string No Optional provider name; never a DSN/credential.
capabilities readonly string[] No Optional host-reported capability names.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Optional display caption.

Optional provider name; never a DSN/credential.

Optional host-reported capability names.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted code contributions restricted to explicit tenant IDs; registration never activates a plugin.

Trusted package contributions; code registration does not grant tenant activation.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/artifacts.

interface PlatformContribution {
apiVersion: 1;
id: string;
tenantIds: string[];
manifests?: PluginManifest[];
lifecycle?: LifecyclePlugin[];
routePrefixes?: Record<string, string[]>;
}
Name Type Required Description
apiVersion 1 Yes Contribution contract discriminator; currently 1.
id string Yes Contribution/package identity.
tenantIds string[] Yes Concrete admitted tenant catalog; never wildcard authorization.
manifests PluginManifest[] No Optional public plugin manifests contributed by the trusted package.
lifecycle LifecyclePlugin[] No Optional trusted lifecycle release definitions.
routePrefixes Record<string, string[]> No Optional plugin ID to allowed route-prefix contributions.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Contribution contract discriminator; currently 1.

Contribution/package identity.

Concrete admitted tenant catalog; never wildcard authorization.

Optional public plugin manifests contributed by the trusted package.

Optional trusted lifecycle release definitions.

Optional plugin ID to allowed route-prefix contributions.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host persistence for tenant catalog, verified migration evidence and atomic routing/activation changes.

Host persistence for the platform control plane. The framework never opens an ADB connection, stores credentials, or runs Pulumi from these callbacks.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformControlStore {
listTenants(): Promise<readonly PlatformTenantRecord[]>;
createTenant(input: PlatformTenantCreateInput): Promise<PlatformTenantRecord>;
updateTenant(tenantId: string, patch: PlatformTenantPatch): Promise<PlatformTenantRecord>;
registerBackend(backend: PlatformBackendRecord): Promise<PlatformBackendRecord>;
listBackends(): Promise<readonly PlatformBackendRecord[]>;
getBackend(backendId: string): Promise<PlatformBackendRecord | null>;
getTenantPlacement(tenantId: string): Promise<TenantBackendPlacement | null>;
saveMigrationPlan(plan: BackendMigrationPlan): Promise<void>;
getMigrationPlan(migrationId: string): Promise<BackendMigrationPlan | null>;
getMigrationStatus(migrationId: string): Promise<LifecyclePlatformMigrationRecord | null>;
beginMigrationExecution(input: {
tenantId: string;
migrationId: string;
executionId: string;
}): Promise<LifecyclePlatformMigrationRecord>;
recordMigrationVerification(input: {
tenantId: string;
plan: BackendMigrationPlan;
executionId: string;
verification: BackendMigrationVerificationReport;
cutover: BackendMigrationCutover;
}): Promise<LifecyclePlatformMigrationRecord>;
markMigrationFailure(input: {
migrationId: string;
executionId?: string;
status: 'failed' | 'reconciling';
message: string;
}): Promise<LifecyclePlatformMigrationRecord>;
reconcileMigration(input: {
migrationId: string;
action: PlatformMigrationReconcileAction;
note: string;
}): Promise<LifecyclePlatformMigrationRecord>;
createRollbackPlan(input: {
tenantId: string;
migrationId: string;
reason: string;
requestedAt: string;
}): Promise<BackendMigrationPlan>;
recordTenantPlacement(input: {
tenantId: string;
plan: BackendMigrationPlan;
cutover: BackendMigrationCutover;
}): Promise<TenantBackendPlacement>;
}
Name Type Required Description
listTenants Promise<readonly PlatformTenantRecord[]> Yes List current platform tenant records without granting membership.
createTenant Promise<PlatformTenantRecord> Yes Persist tenant metadata and initial configured backend assignment.
updateTenant Promise<PlatformTenantRecord> Yes Update only supplied metadata fields for the specified tenant.
registerBackend Promise<PlatformBackendRecord> Yes Register an already-provisioned opaque backend; never provision a database here. Register only an already-provisioned opaque backend; provisioning remains host-owned.
listBackends Promise<readonly PlatformBackendRecord[]> Yes List registered nonsecret backend targets.
getBackend Promise<PlatformBackendRecord | null> Yes Resolve an existing backend by ID, or null.
getTenantPlacement Promise<TenantBackendPlacement | null> Yes Read current tenant routing assignment, or null.
saveMigrationPlan Promise<void> Yes Durably persist the exact reviewed migration plan; no copy/cutover is executed.
getMigrationPlan Promise<BackendMigrationPlan | null> Yes Read a reviewed plan by migration ID, or null.
getMigrationStatus Promise<LifecyclePlatformMigrationRecord | null> Yes Read current migration progress/evidence, or null.
beginMigrationExecution Promise<LifecyclePlatformMigrationRecord> Yes Claim execution for a tenant migration with a unique execution ID before host effects begin.
recordMigrationVerification Promise<LifecyclePlatformMigrationRecord> Yes Persist verified copy/cutover evidence for the claimed execution before routing commit.
markMigrationFailure Promise<LifecyclePlatformMigrationRecord> Yes Record failed or uncertain/reconciling outcome without claiming rollback of host effects.
reconcileMigration Promise<LifecyclePlatformMigrationRecord> Yes Apply an explicit documented operator recovery action with a retained note.
createRollbackPlan Promise<BackendMigrationPlan> Yes Create a reviewed reverse placement plan referencing the retained original source; no copy/cutover executes.
recordTenantPlacement Promise<TenantBackendPlacement> Yes Atomically commit verified plan, routing assignment and lifecycle activation switch. Atomically commits the verified plan, routing placement and lifecycle activation switch.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

List current platform tenant records without granting membership.

Returns: Current platform tenant records, possibly empty.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.listTenants();
}

Persist tenant metadata and initial configured backend assignment.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The newly persisted platform tenant record.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["createTenant"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.createTenant(input);
}

Update only supplied metadata fields for the specified tenant.

Parameters:

  • tenantId: Verified concrete tenant ID whose current state or permission is requested.
  • patch: Partial tenant metadata update; omitted fields retain their values.

Returns: The updated tenant record.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, tenantId: string, patch: Parameters<PlatformControlStore["updateTenant"]>[1]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.updateTenant(tenantId, patch);
}

Register an already-provisioned opaque backend; never provision a database here.

Register only an already-provisioned opaque backend; provisioning remains host-owned.

Parameters:

  • backend: Already-provisioned opaque backend declaration; never a connection string or credentials.

Returns: The persisted existing backend registration.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, backend: Parameters<PlatformControlStore["registerBackend"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.registerBackend(backend);
}

List registered nonsecret backend targets.

Returns: Configured opaque backend records, possibly empty.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.listBackends();
}

Resolve an existing backend by ID, or null.

Parameters:

  • backendId: Existing opaque backend identity to resolve.

Returns: The existing backend, or null when absent.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, backendId: string) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.getBackend(backendId);
}

Read current tenant routing assignment, or null.

Parameters:

  • tenantId: Verified concrete tenant ID whose current state or permission is requested.

Returns: Current tenant routing placement, or null when absent.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, tenantId: string) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.getTenantPlacement(tenantId);
}

Durably persist the exact reviewed migration plan; no copy/cutover is executed.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.

Returns: Resolves without a value after the reviewed plan is durably stored.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, plan: Parameters<PlatformControlStore["saveMigrationPlan"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
await store.saveMigrationPlan(plan);
}

Read a reviewed plan by migration ID, or null.

Parameters:

  • migrationId: Stable reviewed backend migration identity.

Returns: The saved reviewed migration plan, or null when absent.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, migrationId: string) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.getMigrationPlan(migrationId);
}

Read current migration progress/evidence, or null.

Parameters:

  • migrationId: Stable reviewed backend migration identity.

Returns: The current progress/evidence record, or null when absent.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, migrationId: string) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.getMigrationStatus(migrationId);
}

Claim execution for a tenant migration with a unique execution ID before host effects begin.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The claimed running migration record.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["beginMigrationExecution"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.beginMigrationExecution(input);
}

Verified concrete tenant whose reviewed migration or routing placement is being changed.

Stable identity of the saved reviewed migration plan whose execution/progress is being changed.

Unique host execution claim; preserve it when recording results so obsolete or competing workers cannot claim the transition.

Persist verified copy/cutover evidence for the claimed execution before routing commit.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The migration record containing persisted verification and cutover evidence.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["recordMigrationVerification"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.recordMigrationVerification(input);
}

recordMigrationVerification.input.tenantId

Section titled “recordMigrationVerification.input.tenantId”

Verified concrete tenant whose reviewed migration or routing placement is being changed.

Exact reviewed backend migration plan whose source, target, scope and digest must match the saved control-plane plan.

recordMigrationVerification.input.executionId

Section titled “recordMigrationVerification.input.executionId”

Unique host execution claim; preserve it when recording results so obsolete or competing workers cannot claim the transition.

recordMigrationVerification.input.verification

Section titled “recordMigrationVerification.input.verification”

Host-produced complete copy verification matching the plan and claimed execution; persistence does not independently measure the data.

Matching source-retaining host routing receipt; commit placement only after current verification is accepted.

Record failed or uncertain/reconciling outcome without claiming rollback of host effects.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The recorded failed/reconciling migration state.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["markMigrationFailure"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.markMigrationFailure(input);
}

Stable identity of the saved reviewed migration plan whose execution/progress is being changed.

Unique host execution claim; preserve it when recording results so obsolete or competing workers cannot claim the transition.

Explicit failed or reconciling classification; use reconciling when external copy/routing outcomes are uncertain.

Nonsecret failure description retained for operator diagnosis; exclude credentials and business payloads.

Apply an explicit documented operator recovery action with a retained note.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The resulting migration record after the explicit recovery action.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["reconcileMigration"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.reconcileMigration(input);
}

Stable identity of the saved reviewed migration plan whose execution/progress is being changed.

Explicit reviewed recovery action for this migration; never infer successful cutover from a timeout.

Retained operator explanation/evidence for the selected reconciliation action.

Create a reviewed reverse placement plan referencing the retained original source; no copy/cutover executes.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: A reviewed source-retaining reverse migration plan; no backend effects run.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["createRollbackPlan"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.createRollbackPlan(input);
}

Verified concrete tenant whose reviewed migration or routing placement is being changed.

Stable identity of the saved reviewed migration plan whose execution/progress is being changed.

Reviewed operator reason for creating a reverse migration to the retained source.

Parseable timestamp of the reviewed rollback-plan request.

Atomically commit verified plan, routing assignment and lifecycle activation switch.

Atomically commits the verified plan, routing placement and lifecycle activation switch.

Parameters:

  • input: Reviewed operation inputs; preserve the verified tenant/migration/execution identity described by this contract.

Returns: The atomically committed tenant routing placement.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformControlStore } from '@alneas/eaos-server/platform';
export async function reviewedOperation(store: PlatformControlStore, input: Parameters<PlatformControlStore["recordTenantPlacement"]>[0]) {
// The host authenticates the operator and reviews any mutation inputs first.
return store.recordTenantPlacement(input);
}

Verified concrete tenant whose reviewed migration or routing placement is being changed.

Exact reviewed backend migration plan whose source, target, scope and digest must match the saved control-plane plan.

Matching source-retaining host routing receipt; commit placement only after current verification is accepted.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Lists the default and additional configured database targets in declaration order.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/runtime.

declare function platformDatabaseTargets(runtime: PlatformRuntimeConfig): BackendTarget[];
Name Type Required Description
runtime PlatformRuntimeConfig Yes Platform runtime configuration; validate it before use.

BackendTarget[]

A new array containing runtime.backend followed by databaseTargets; target objects are shared.

Does not validate or deduplicate targets and performs no discovery or connection.

import { platformDatabaseTargets } from '@alneas/eaos-server/platform/runtime';
const targets = platformDatabaseTargets({ backend: { id: 'main', databaseId: 'db-main', dialect: 'sqlite', mode: 'shared' } });

Adds host route composition to a trusted platform contribution with explicit tenant scope.

Imports: @alneas/eaos-server/extensions.

interface PlatformExtension extends PlatformContribution {
routeFactories?: Record<string, HostRouteFactory>;
routes?: Array<{
prefix: string;
moduleId: string;
router: Hono;
}>;
userContext?: (context: Context) => Promise<unknown>;
}
Name Type Required Description
routeFactories Record<string, HostRouteFactory> No Plugin-ID factories for every contributed manifest; may not override plugins absent from this contribution.
routes Array<{ prefix: string; moduleId: string; router: Hono; }> No Optional host API routes with an absolute, wildcard-free prefix, nonblank moduleId, and Hono router.
userContext (context: Context) => Promise<unknown> No Optional request context resolver; contributions using it may not overlap tenant scope. Its result/authorization semantics belong to the host.

Type declaration; no runtime value.

Never populate this object from request input.

validateExtensions for a complete composition example.

Plugin-ID factories for every contributed manifest; may not override plugins absent from this contribution.

Optional host API routes with an absolute, wildcard-free prefix, nonblank moduleId, and Hono router.

Absolute wildcard-free mount prefix; overlapping tenant contributions may not claim the same prefix.

Nonblank module identity passed to the host requireModule factory after the extension tenant-scope check.

Trusted Hono child router wrapped with tenant-scope and live host module middleware during extension composition.

Optional request context resolver; contributions using it may not overlap tenant scope. Its result/authorization semantics belong to the host.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Explicit operator recovery action for an uncertain or failed migration execution.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

type PlatformMigrationReconcileAction = 'retry' | 'mark-failed' | 'mark-reconciling' | 'commit-verified';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted project-relative artifact/module registration with explicit tenant/plugin scopes.

Paths are project-relative. Settings are non-secret; use host-resolved references for credentials.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/artifacts.

interface PlatformPackage {
id: string;
inventory: string;
module: string;
tenantIds: string[];
pluginIds: string[];
settings?: Record<string, unknown>;
}
Name Type Required Description
id string Yes Unique nonblank registration ID.
inventory string Yes Project-relative inventory path without absolute/traversal/backslash segments.
module string Yes Project-relative entry module path without traversal.
tenantIds string[] Yes Nonempty concrete trimmed tenant IDs; wildcard is forbidden.
pluginIds string[] Yes Nonempty unique plugin IDs contributed by this package.
settings Record<string, unknown> No Optional nonsecret host configuration object; resolve credentials by host references.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Unique nonblank registration ID.

Project-relative inventory path without absolute/traversal/backslash segments.

Project-relative entry module path without traversal.

Nonempty concrete trimmed tenant IDs; wildcard is forbidden.

Nonempty unique plugin IDs contributed by this package.

Optional nonsecret host configuration object; resolve credentials by host references.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host adapter performing prepare/copy/verify/cutover/retain-source phases against real resources.

The host performs the five migration phases against its own adapters and credentials.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform-admin, @alneas/eaos-server/platform/control-plane.

interface PlatformPlacementExecutor {
execute(plan: BackendMigrationPlan): Promise<{
verification: BackendMigrationVerificationReport;
cutover: BackendMigrationCutover;
}>;
}
Name Type Required Description
execute Promise<{ verification: BackendMigrationVerificationReport; cutover: BackendMigrationCutover; }> Yes Execute the reviewed plan with all-instance quiescence and return matching verification/cutover receipts; uncertain outcomes must be reconciled rather than blindly retried.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Execute the reviewed plan with all-instance quiescence and return matching verification/cutover receipts; uncertain outcomes must be reconciled rather than blindly retried.

Parameters:

  • plan: Reviewed unmodified backend migration plan; host must preserve quiescence and source data.

Returns: Matching verification and cutover receipts from the host execution.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { PlatformPlacementExecutor } from '@alneas/eaos-server/platform';
export async function executeReviewed(executor: PlatformPlacementExecutor, plan: Parameters<PlatformPlacementExecutor["execute"]>[0]) {
// This host port performs real copy/verification/routing effects.
const evidence = await executor.execute(plan);
return { verification: evidence.verification, cutover: evidence.cutover };
}

Host-reported complete copy verification for the exact reviewed plan.

Routing receipt retaining source data for recovery.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Request-scoped host authorization supplied after verified membership middleware.

Imports: @alneas/eaos-server/extensions.

interface PlatformPluginAuthorization {
resolvePrincipal(): Promise<{
tenantId: string;
userId: string;
roles: string[];
enabledPluginIds: string[];
} | null>;
isPluginEnabled(tenantId: string, pluginId: string): Promise<boolean>;
}
Name Type Required Description
resolvePrincipal Promise<{ tenantId: string; userId: string; roles: string[]; enabledPluginIds: string[]; } | null> Yes Resolves the current verified principal after host authentication/membership checks.
isPluginEnabled Promise<boolean> Yes Checks live plugin activation for a verified tenant.

Type declaration; no runtime value.

getPlatformPluginAuthorization for binding lookup and a usage example.

Resolves the current verified principal after host authentication/membership checks.

Returns: Tenant/user identity, verified roles, and current enabled plugin IDs, or null to deny.

Host authentication or persistence failures propagate to callers.

Example:

import type { PlatformPluginAuthorization } from "@alneas/eaos-server/extensions";
export async function readHostPrincipal(authorization: PlatformPluginAuthorization) {
const principal = await authorization.resolvePrincipal();
return principal; // Null denies access; never replace it with request-supplied claims.
}

Tenant identity established by trusted host authentication/membership resolution; request-supplied headers/body must not define this claim.

Authenticated user identity within the resolved tenant scope.

Verified host role claims used for downstream authorization; tenant roles must not fabricate platform authority.

Current plugin activation identities visible to this verified principal; the host supplies live lifecycle data.

Checks live plugin activation for a verified tenant.

Parameters:

  • tenantId: Verified tenant ID.
  • pluginId: Exact installed plugin ID.

Returns: True only when the plugin is currently enabled for this tenant.

Host lifecycle/persistence failures propagate to callers.

Example:

import type { PlatformPluginAuthorization } from "@alneas/eaos-server/extensions";
export async function checkCurrentPlugin(
authorization: PlatformPluginAuthorization, verifiedTenantId: string, installedPluginId: string,
) {
return await authorization.isPluginEnabled(verifiedTenantId, installedPluginId);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Nonsecret target catalog for routing databases within one shared execution host.

Database placement inside one shared execution host. Targets reuse lifecycle identities.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/runtime.

interface PlatformRuntimeConfig {
backend: BackendTarget;
databaseTargets?: BackendTarget[];
tenantPlacements?: Record<string, string>;
}
Name Type Required Description
backend BackendTarget Yes Default target used for tenants without an explicit placement.
databaseTargets BackendTarget[] No Optional additional target definitions with distinct IDs.
tenantPlacements Record<string, string> No Optional verified tenant ID to configured target-ID map; dedicated additional targets require explicit entries.

Type declaration; no runtime value.

validatePlatformRuntime for canonical integration usage.

Default target used for tenants without an explicit placement.

Optional additional target definitions with distinct IDs.

Optional verified tenant ID to configured target-ID map; dedicated additional targets require explicit entries.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Platform tenant identity and admission metadata independent of company/person business schemas.

Platform contracts are independent of a consumer’s employee/company schema.

Imports: @alneas/eaos-server/platform.

interface PlatformTenant {
id: string;
active: boolean;
domains: readonly string[];
}
Name Type Required Description
id string Yes Concrete platform tenant identifier.
active boolean Yes Whether tenant admission is enabled.
domains readonly string[] Yes Host-configured tenant lookup domains; domain mapping alone never proves membership.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Concrete platform tenant identifier.

Whether tenant admission is enabled.

Host-configured tenant lookup domains; domain mapping alone never proves membership.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Requested tenant registration bound to an already configured backend.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformTenantCreateInput {
id: string;
name: string;
domains: readonly string[];
backendId: string;
}
Name Type Required Description
id string Yes Concrete tenant identifier to create.
name string Yes Tenant display name.
domains readonly string[] Yes Requested domain lookup mappings; no membership is implied.
backendId string Yes Existing opaque backend ID to assign; does not trigger provisioning.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Concrete tenant identifier to create.

Tenant display name.

Requested domain lookup mappings; no membership is implied.

Existing opaque backend ID to assign; does not trigger provisioning.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Partial tenant metadata change; omitted properties retain their current values.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformTenantPatch {
name?: string;
active?: boolean;
domains?: readonly string[];
}
Name Type Required Description
name string No Optional replacement display name.
active boolean No Optional admission enable/disable flag.
domains readonly string[] No Optional complete replacement domain mapping list.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Optional replacement display name.

Optional admission enable/disable flag.

Optional complete replacement domain mapping list.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Tenant record managed by the control plane; account membership stays host-owned.

A tenant record managed by the platform control plane. Membership remains host-owned.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface PlatformTenantRecord extends PlatformTenant {
name: string;
createdAt: string;
updatedAt: string;
}
Name Type Required Description
name string Yes Public tenant display name.
createdAt string Yes Creation timestamp.
updatedAt string Yes Latest metadata modification timestamp.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Public tenant display name.

Creation timestamp.

Latest metadata modification timestamp.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Checks live plugin entitlements and durably reserves metered admission attempts.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare class PluginEntitlementRuntime {
constructor(options: EntitlementRuntimeOptions);
snapshot(principal: PlatformPrincipal, session?: AtomicSession): Promise<TenantEntitlements | null>;
check(principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement, session?: AtomicSession): Promise<EntitlementDecision>;
admit(principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement, operation: string): Promise<void>;
run<T>(principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement, operation: string, work: () => Promise<T>): Promise<T>;
}
Name Type Required Description
options EntitlementRuntimeOptions Yes Trusted entitlement persistence, active-plugin checks, and optional clock.

PluginEntitlementRuntime

A durable quota reservation counts admitted attempts, including failed handler attempts. No refund, cancellation, retry, or business-handler transaction is supplied. Shared concurrency/CAS and tenant isolation depend on the host AtomicRepository. For a contract snapshot consistent with reservation writes, supply loadInTransaction.

Loads and validates current tenant contract data for a verified principal.

Parameters:

  • principal: Verified platform principal validated by assertPlatformPrincipal.
  • session: Optional active atomic session; loadInTransaction is used only when both are supplied.

Returns: A structured clone of current entitlements, or null when absent.

Rejects invalid principal/contract, mismatched tenant, clone errors, or host load failures.

Example:

import { PluginEntitlementRuntime, type EntitlementRuntimeOptions } from "@alneas/eaos-server/entitlements";
import type { PlatformPrincipal } from "@alneas/eaos-core";
export async function snapshot(options: EntitlementRuntimeOptions, principal: PlatformPrincipal) {
return new PluginEntitlementRuntime(options).snapshot(principal);
}

Evaluates lifecycle and subscription policy without consuming quota.

Parameters:

  • principal: Verified user/tenant principal.
  • pluginId: Exact plugin ID used by lifecycle and entitlement evaluation.
  • rule: Plugin access tier, allowed tenants, and optional metering declaration.
  • session: Optional reservation transaction for a joined contract read.

Returns: Allowed/denied decision; inactive lifecycle returns denied 404 tenant-locked. This check does not reserve usage.

Rejects invalid data or propagated lifecycle/load/clock errors.

Example:

import { PluginEntitlementRuntime, type EntitlementRuntimeOptions } from "@alneas/eaos-server/entitlements";
import type { PlatformPrincipal, PluginEntitlement } from "@alneas/eaos-core";
export async function check(options: EntitlementRuntimeOptions, principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement) {
return new PluginEntitlementRuntime(options).check(principal, pluginId, rule);
}

Rechecks entitlement under the repository transaction and reserves one metered attempt with an audit entry.

Parameters:

  • principal: Verified principal used for tenant-scoped repository admission.
  • pluginId: Plugin whose live entitlement is required.
  • rule: Current plugin entitlement policy; unmetered rules perform no counter write.
  • operation: Host operation label recorded in metering audit data.

Returns: No value; resolves after entitlement admission and any quota/audit persistence.

Counters use a UTC YYYY-MM period and count admitted attempts, not successful work. Calling admit repeatedly consumes repeatedly; no idempotency key is applied.

Rejects EntitlementError for denied policy/quota, invalid stored usage counter, or host transaction/load/lifecycle/audit failures.

Example:

import { PluginEntitlementRuntime, type EntitlementRuntimeOptions } from "@alneas/eaos-server/entitlements";
import type { PlatformPrincipal, PluginEntitlement } from "@alneas/eaos-core";
export async function admit(options: EntitlementRuntimeOptions, principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement) {
await new PluginEntitlementRuntime(options).admit(principal, pluginId, rule, "example:execute");
}

Reserves admission before executing host work outside the reservation transaction.

Parameters:

  • principal: Verified tenant/user principal.
  • pluginId: Required plugin ID.
  • rule: Plugin entitlement policy.
  • operation: Host operation label for metering audit.
  • work: Called without arguments only after admission; resolves the business result.

Returns: The host work result.

  • T: Resolved host work result.

Rejects admission or work failures; failed work does not refund a reservation.

Example:

import { PluginEntitlementRuntime, type EntitlementRuntimeOptions } from "@alneas/eaos-server/entitlements";
import type { PlatformPrincipal, PluginEntitlement } from "@alneas/eaos-core";
export async function execute<T>(options: EntitlementRuntimeOptions, principal: PlatformPrincipal, pluginId: string, rule: PluginEntitlement, work: () => Promise<T>) {
return new PluginEntitlementRuntime(options).run(principal, pluginId, rule, "example:execute", work);
}
import { PluginEntitlementRuntime, type EntitlementRuntimeOptions } from "@alneas/eaos-server/entitlements";
export function entitlementRuntime(options: EntitlementRuntimeOptions) {
return new PluginEntitlementRuntime(options);
}

Carries an intentional sanitized plugin HTTP error status while preserving the caller-provided message.

Imports: @alneas/eaos-server/plugin-data.

declare class PluginError extends Error {
readonly status: 400 | 401 | 403 | 404 | 409 | 410;
constructor(status: 400 | 401 | 403 | 404 | 409 | 410, message: string);
}
Name Type Required Description
status 400 | 401 | 403 | 404 | 409 | 410 Yes Supported bad-input/authentication/permission/missing/conflict/gone HTTP status.
message string Yes Safe public error description exposed by createPluginRouter.

PluginError

createPluginRouter returns this message/status to HTTP callers; exclude secrets, provider details and business payloads from messages.

import { PluginError } from '@alneas/eaos-server/plugin-data';
const unavailable = new PluginError(404, 'Record unavailable');

Hono variables carrying the principal resolved by the trusted plugin router.

Imports: @alneas/eaos-server/plugin-data.

type PluginHttpEnv = {
Variables: {
principal: PluginPrincipal;
};
};
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

createPluginRouter for canonical host integration.

Hono variables populated by the trusted principal resolver before operation routes run.

Verified principal resolved for this request; still subject to current service authorization.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Plans and applies checksum-bound plugin/schema changes against an exclusively locked host ledger.

Imports: @alneas/eaos-server/lifecycle-engine.

declare class PluginLifecycle {
readonly frameworkVersion: string;
constructor(project: LifecycleProject, frameworkVersion?: string);
planBundle(request: LifecycleRequest): Promise<LifecycleBundlePlan>;
applyBundle(bundlePlan: LifecycleBundlePlan): Promise<void>;
schemaCatalog(pluginIds?: readonly string[]): DataContractCatalog;
plan(request: LifecycleRequest): Promise<LifecyclePlan>;
isEnabled(backendId: string, tenantId: string, pluginId: string): Promise<boolean>;
list(options?: {
backendId?: string;
tenantId?: string;
}): Promise<LifecycleInventory>;
run<T>(backendId: string, tenantId: string, pluginId: string, callback: () => Promise<T>): Promise<T>;
preview(plan: LifecyclePlan): Promise<unknown[]>;
apply(plan: LifecyclePlan): Promise<void>;
}
Name Type Required Description
project LifecycleProject Yes Host lifecycle storage, trusted catalogs and execution adapters.
frameworkVersion string No Valid semver framework version; defaults to the installed package version.

PluginLifecycle

Server runtime uses Node crypto and semver. The host provides durable cross-process locking, tenant authorization, SQL migration execution and any infrastructure/quiesce adapters. Installation never implies tenant enablement; disable/uninstall retain data. Migration/infrastructure failures persist reconciliation state, and DDL is not rolled back automatically.

Error for invalid/duplicate IDs, versions, migrations, conflicting schemas, unsupported backend configuration or unsatisfied contract dependencies.

Plans registered bundle members sequentially against a projected ledger state.

Parameters:

  • request: Lifecycle request whose pluginId names a registered bundle.

Returns: A checksum-bound ordered bundle plan with each member’s projected revision.

Disable/uninstall reverse bundle order. Planning executes no migrations or writes; projected revisions mirror member apply ordering.

Rejects unknown bundle, invalid member request/state or propagated store failures.

Example:

import { PluginLifecycle, type LifecycleRequest } from '@alneas/eaos-server/lifecycle-engine';
export function reviewBundle(lifecycle: PluginLifecycle, request: LifecycleRequest) { return lifecycle.planBundle(request); }

Validates a reviewed bundle plan and applies its member plans in sequence.

Parameters:

  • bundlePlan: Unmodified checksum-bound bundle plan from planBundle.

Returns: Resolves without a value after every member apply completes.

Members acquire their own ledger locks. There is no all-or-nothing bundle transaction; earlier members remain applied if a later member fails. Replan/reconcile before retrying uncertain outcomes.

Rejects modified/stale/misordered bundle plans, member apply failures and propagated host errors.

Example:

import { PluginLifecycle, type LifecycleBundlePlan } from '@alneas/eaos-server/lifecycle-engine';
export function applyReviewedBundle(lifecycle: PluginLifecycle, plan: LifecycleBundlePlan) { return lifecycle.applyBundle(plan); }

Resolves the canonical schema dependency catalog for registered feature plugins.

Read-only complete schema inventory for the selected trusted feature catalog.

Parameters:

  • pluginIds: Optional feature IDs; omitted includes all registered plugins, while an empty array selects none.

Returns: A JSON-cloned dependency-resolved DataContractCatalog.

Read-only; schema dependencies never install or enable feature plugins.

Error for unknown/incompatible feature dependencies or invalid/conflicting contract requirements.

Example:

import { PluginLifecycle } from '@alneas/eaos-server/lifecycle-engine';
export function schemas(lifecycle: PluginLifecycle) { return lifecycle.schemaCatalog(); }

Creates a reviewable lifecycle plan from one current ledger snapshot without executing side effects.

Parameters:

  • request: Concrete operation, registered plugin/backend and verified tenant; see LifecycleRequest.

Returns: A deterministic checksum-bound plan carrying the snapshot revision, dependency closure, migrations and retained-data policy.

Planning is read-only but may become stale immediately. Backend physical identity is immutable. Updates require appended immutable migrations and compatible schema versions; installation and enablement are separate operations.

Rejects invalid request/state, incompatible or missing dependencies, changed applied migrations, dirty ledger, unsupported dialect, tenant mismatch or propagated store failures.

Example:

import { PluginLifecycle, type LifecycleRequest } from '@alneas/eaos-server/lifecycle-engine';
export function review(lifecycle: PluginLifecycle, request: LifecycleRequest) { return lifecycle.plan(request); }

Checks that a tenant activation and its entire registered dependency closure match ready ledger releases.

Parameters:

  • backendId: Registered execution backend ID.
  • tenantId: Verified concrete tenant ID.
  • pluginId: Registered feature ID to check.

Returns: True only when matching installation, migrations, infrastructure and activation digests are all ready; false for missing/incompatible readiness.

Read-only admission check; a later state change can revoke access. Host must still enforce current tenant/resource authorization.

Rejects malformed IDs/state, unknown or mismatched backend/tenant and store failures.

Example:

import { PluginLifecycle } from '@alneas/eaos-server/lifecycle-engine';
export function admitted(lifecycle: PluginLifecycle, backendId: string, tenantId: string, pluginId: string) { return lifecycle.isEnabled(backendId, tenantId, pluginId); }

Reads inventory including registered uninstalled code and orphaned historical installations.

One read-only control-state snapshot; includes orphaned installation records and registered, uninstalled code.

Parameters:

  • options: Optional backendId and tenantId filters; omitted returns all known inventory.

Returns: A revision-bound inventory with effective enabled state distinct from requested activation.

Performs one ledger read without writes. Dedicated backends for another tenant are omitted unless explicitly requested, in which case the request rejects.

Rejects invalid filter IDs, unknown backend, corrupt installation/activation records, dedicated tenant mismatch or store failure.

Example:

import { PluginLifecycle } from '@alneas/eaos-server/lifecycle-engine';
export function inventory(lifecycle: PluginLifecycle) { return lifecycle.list(); }

Optional exact backend filter; unknown backends reject.

Optional concrete tenant filter; dedicated backend scope must match.

Runs a host callback only after the current plugin dependency closure passes lifecycle admission.

Parameters:

  • backendId: Registered backend ID.
  • tenantId: Verified concrete tenant ID.
  • pluginId: Feature plugin ID.
  • callback: Async work invoked once after admission; must enforce tenant/resource authorization itself.

Returns: The callback result without cloning.

  • T: Value resolved by the admitted callback.

The admission check does not hold a lock or pin activation throughout callback execution. Host quiesce/drain and live authorization remain required.

Rejects inactive plugin, lifecycle/store validation failure or callback rejection.

Example:

import { PluginLifecycle } from '@alneas/eaos-server/lifecycle-engine';
export function runAdmitted<T>(lifecycle: PluginLifecycle, backendId: string, tenantId: string, pluginId: string, work: () => Promise<T>) { return lifecycle.run(backendId, tenantId, pluginId, work); }

Checks plan freshness and invokes host infrastructure previews without applying ledger changes.

Parameters:

  • plan: Unmodified lifecycle plan to preview.

Returns: Preview results in infrastructure-step order, or an empty array when no infrastructure is needed.

Infrastructure previews run concurrently through Promise.all. Host preview adapters own any external read/preview effects; this method executes no migrations.

Rejects stale/modified plan, missing infrastructure adapter or propagated plan/preview errors.

Example:

import { PluginLifecycle, type LifecyclePlan } from '@alneas/eaos-server/lifecycle-engine';
export function preview(lifecycle: PluginLifecycle, plan: LifecyclePlan) { return lifecycle.preview(plan); }

Revalidates and executes a reviewed lifecycle plan while holding the host’s exclusive ledger lock.

Parameters:

  • plan: Unmodified plan bound to the current ledger revision and registered configuration.

Returns: Resolves without a value after ledger updates and requested side effects complete.

Before upgrade side effects, affected activations are disabled durably and all-instance quiesce is required. Infrastructure/migration running/applied/failed receipts are persisted separately. Errors can follow partial external success; no automatic rollback/retry occurs. Uninstall retains business data and migration history.

Rejects stale/modified plan, missing executors/quiesce, reconciliation conflicts or host store, migration, infrastructure or drain failures.

Example:

import { PluginLifecycle, type LifecyclePlan } from '@alneas/eaos-server/lifecycle-engine';
export function applyReviewed(lifecycle: PluginLifecycle, plan: LifecyclePlan) { return lifecycle.apply(plan); }
import { PluginLifecycle, type LifecycleProject } from '@alneas/eaos-server/lifecycle-engine';
export function connectLifecycle(project: LifecycleProject) { return new PluginLifecycle(project); }

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db.

interface PluginMigration {
id: string;
scope: 'database' | 'tenant';
sql: Partial<Record<'sqlite' | 'oracle' | 'postgres', string[]>>;
}
Name Type Required Description
id string Yes See the upstream owning declaration.
scope 'database' | 'tenant' Yes See the upstream owning declaration.
sql Partial<Record<'sqlite' | 'oracle' | 'postgres', string[]>> Yes See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Immutable reviewed migration statements scoped to a physical database or one tenant.

Imports: @alneas/eaos-server/lifecycle-engine.

interface PluginMigration {
id: string;
scope: 'database' | 'tenant';
sql: Partial<Record<Dialect, string[]>>;
}
Name Type Required Description
id string Yes Stable unique migration ID whose applied definition must never be rewritten.
scope 'database' | 'tenant' Yes Database runs once per physical database; tenant runs once per tenant.
sql Partial<Record<Dialect, string[]>> Yes Dialect-to-ordered-statements map; the target dialect must have nonempty statements.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Stable unique migration ID whose applied definition must never be rewritten.

Database runs once per physical database; tenant runs once per tenant.

Dialect-to-ordered-statements map; the target dialect must have nonempty statements.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Minimal verified-principal operation dispatch contract shared by bounded composite services.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/composite.

interface PluginOperationService {
execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown>;
}
Name Type Required Description
execute Promise<unknown> Yes Executes one service-owned operation using host-verified identity and operation input.

Type declaration; no runtime value.

createCompositePluginService for canonical host integration.

Executes one service-owned operation using host-verified identity and operation input.

Parameters:

  • principal: Verified current tenant principal.
  • operation: Declared service operation name.
  • input: Operation input whose schema/permission must be checked by the owning service.

Returns: The owner’s operation result; no composite layer adds authentication or transactions.

Rejects owning-service schema, authorization, persistence or domain failures.

Example:

import type { PluginOperationService, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function executeAdmitted(service: PluginOperationService, principal: PluginPrincipal, operation: string, input: unknown) {
// The owning service validates input and live resource permission.
return service.execute(principal, operation, input);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Structurally verified tenant/user identity supplied by a trusted host authentication boundary.

Imports: @alneas/eaos-server/plugin-data.

interface PluginPrincipal {
tenantId: string;
userId: string;
roles: readonly string[];
}
Name Type Required Description
tenantId string Yes Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.
userId string Yes Authenticated actor identity supplied by the host.
roles readonly string[] Yes Current host-verified role names; structural validation alone does not grant permission.

Type declaration; no runtime value.

createPluginRouter for canonical host integration.

Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.

Authenticated actor identity supplied by the host.

Current host-verified role names; structural validation alone does not grant permission.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Logical record identity, CAS revision and JSON payload envelope.

Imports: @alneas/eaos-server/plugin-data.

interface PluginRecord<T> {
id: string;
revision: number;
value: T;
}
Name Type Required Description
id string Yes Logical tenant/namespace-scoped record identity.
revision number Yes CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.
value T Yes Stored JSON payload whose runtime validation depends on the configured document contracts.

Type declaration; no runtime value.

  • T: Stored JSON payload shape; compile-time typing does not itself validate data.

createSqlRecordStore for canonical host integration.

Logical tenant/namespace-scoped record identity.

CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.

Stored JSON payload whose runtime validation depends on the configured document contracts.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host record persistence contract requiring tenant predicates and atomic revision-predicated writes.

Providers must enforce tenant keys and atomic compare-and-swap, never read/update without the revision predicate.

Imports: @alneas/eaos-server/plugin-data.

interface PluginRecordStore<T> {
read(tenantId: string, id: string): Promise<PluginRecord<T> | null>;
list(tenantId: string, limit: number): Promise<PluginRecord<T>[]>;
listPage?(tenantId: string, limit: number, after?: string): Promise<PluginRecord<T>[]>;
create(tenantId: string, record: PluginRecord<T>): Promise<void>;
replace(tenantId: string, record: PluginRecord<T>, expectedRevision: number): Promise<boolean>;
delete?(tenantId: string, id: string, expectedRevision?: number): Promise<boolean>;
}
Name Type Required Description
read Promise<PluginRecord<T> | null> Yes Reads one record within the exact tenant and logical namespace.
list Promise<PluginRecord<T>[]> Yes Reads a bounded set of envelopes from one tenant and namespace.
listPage Promise<PluginRecord<T>[]> No Reads a stable ID-ordered page after an optional exclusive logical record ID. Optional stable ID keyset paging; after is an exclusive logical record ID.
create Promise<void> Yes Creates a previously absent tenant record with its initial stored revision.
replace Promise<boolean> Yes Replaces a tenant record only when its stored revision matches the expected value.
delete Promise<boolean> No Optionally deletes one scoped envelope with an optional revision predicate.

Type declaration; no runtime value.

  • T: Stored payload shape shared by all scoped persistence operations.

createSqlRecordStore for canonical host integration.

Reads one record within the exact tenant and logical namespace.

Parameters:

  • tenantId: Verified tenant ID supplied by the host.
  • id: Logical record ID within this store.

Returns: The matching envelope or null when absent.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function readTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string) {
const record = await store.read(principal.tenantId, id);
return record?.value.title ?? null;
}

Reads a bounded set of envelopes from one tenant and namespace.

Parameters:

  • tenantId: Verified tenant ID.
  • limit: Required provider-supported maximum row count; canonical SQL stores accept integers 1–100.

Returns: Scoped envelopes, possibly empty; filtering this bounded set does not prove completeness.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function firstPage(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal) {
return store.list(principal.tenantId, 20);
}

Reads a stable ID-ordered page after an optional exclusive logical record ID.

Optional stable ID keyset paging; after is an exclusive logical record ID.

Parameters:

  • tenantId: Verified tenant ID.
  • limit: Required bounded page size; canonical SQL stores accept 1–100.
  • after: Optional exclusive logical record ID; omitted starts the page.

Returns: Scoped envelopes in increasing logical-ID order; fewer than limit indicates the end.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function nextPage(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, after: string) {
if (!store.listPage) throw new Error("Keyset paging not supported");
return store.listPage(principal.tenantId, 20, after);
}

Creates a previously absent tenant record with its initial stored revision.

Parameters:

  • tenantId: Verified tenant ID owning the new record.
  • record: New logical envelope; canonical validated/atomic stores require revision 1.

Returns: Resolves without a value after durable creation.

Rejects duplicate identity, invalid document/payload/revision or persistence failure.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function createTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, title: string) {
// Live create permission must be checked before persistence.
await store.create(principal.tenantId, { id, revision: 1, value: { title } });
}

Replaces a tenant record only when its stored revision matches the expected value.

Parameters:

  • tenantId: Verified tenant ID.
  • record: Next envelope whose revision must be expectedRevision+1.
  • expectedRevision: Positive previously observed CAS revision.

Returns: True when one row is replaced; false for stale rows in plain SQL stores. Atomic adapters reject CAS conflicts instead of returning false.

Rejects invalid revision/document/payload or provider failure; atomic adapters also reject stale CAS.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function replaceTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, expectedRevision: number, title: string) {
return store.replace(principal.tenantId, { id, revision: expectedRevision + 1, value: { title } }, expectedRevision);
}

Optionally deletes one scoped envelope with an optional revision predicate.

Parameters:

  • tenantId: Verified tenant ID.
  • id: Logical record ID.
  • expectedRevision: Optional expected CAS revision; omit only when unconditional scoped deletion is intended.

Returns: Whether a row was deleted; immutable document wrappers reject instead.

Rejects immutable document deletion or host persistence failure.

Example:

import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function deleteReviewed(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, expectedRevision: number) {
if (!store.delete) throw new Error("Deletion not supported");
return store.delete(principal.tenantId, id, expectedRevision);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-owned request-body bound for the shared authenticated plugin router.

Imports: @alneas/eaos-server/plugin-data.

interface PluginRouterOptions {
maxBodyBytes?: number;
}
Name Type Required Description
maxBodyBytes number No Request body size in bytes; defaults to 131072 and must be an integer from 1024 to 8388608. Trusted host bound, never request-controlled. Default 128KiB.

Type declaration; no runtime value.

createPluginRouter for canonical host integration.

Request body size in bytes; defaults to 131072 and must be an integer from 1024 to 8388608.

Trusted host bound, never request-controlled. Default 128KiB.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host authentication, live admission, and scoped capabilities injected into createSdkPluginRouter.

Imports: @alneas/eaos-server, @alneas/eaos-server/plugin-sdk.

interface PluginSdkHost {
resolvePrincipal: EntitlementPrincipalResolver;
authorize: (principal: PlatformPrincipal, pluginId: string, operation: string) => Promise<boolean>;
entitlements?: PluginEntitlementRuntime;
createContext: (principal: PlatformPrincipal, pluginId: string) => Promise<Omit<PluginContext<any>, 'principal' | 'pluginId'>>;
}
Name Type Required Description
resolvePrincipal EntitlementPrincipalResolver Yes Resolves a verified current principal for each invocation, or null to deny; may be invoked multiple times in one request.
authorize (principal: PlatformPrincipal, pluginId: string, operation: string) => Promise<boolean> Yes Mandatory live lifecycle/resource gate, independent of commercial licensing.
entitlements PluginEntitlementRuntime No Optional subscription/quota runtime; required when the plugin declares a rule needing external entitlement admission.
createContext (principal: PlatformPrincipal, pluginId: string) => Promise<Omit<PluginContext<any>, 'principal' | 'pluginId'>> Yes Must return tenant/plugin-scoped app-core/EAOS capabilities with per-operation authorization.

Type declaration; no runtime value.

Resolves a verified current principal for each invocation, or null to deny; may be invoked multiple times in one request.

Mandatory live lifecycle/resource gate, independent of commercial licensing.

Optional subscription/quota runtime; required when the plugin declares a rule needing external entitlement admission.

Must return tenant/plugin-scoped app-core/EAOS capabilities with per-operation authorization.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host persistence for per-projection, per-tenant progress and failure state.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/graph-projection.

interface ProjectionCursorStore {
get(projectionId: string, tenantId: string): Promise<GraphProjectionCursor | null>;
put(cursor: GraphProjectionCursor): Promise<void>;
}
Name Type Required Description
get Promise<GraphProjectionCursor | null> Yes Reads current projection progress for a tenant.
put Promise<void> Yes Persists replacement projection progress.

Type declaration; no runtime value.

GraphProjectionCoordinator.

Reads current projection progress for a tenant.

Parameters:

  • projectionId: Host projection identifier.
  • tenantId: Verified event/snapshot tenant.

Returns: Stored cursor, or null when absent.

Store errors propagate to the coordinator.

Example:

import type { ProjectionCursorStore } from "@alneas/eaos-server";
export async function inspectTenantProjection(
store: ProjectionCursorStore, projectionId: string, verifiedTenantId: string,
) {
const cursor = await store.get(projectionId, verifiedTenantId);
return cursor?.status; // Null means no cursor was stored.
}

Persists replacement projection progress.

Parameters:

  • cursor: Full progress/failure cursor to store.

Returns: No value; resolves after persistence.

Store errors propagate; the projection adapter may already have applied changes.

Example:

import type { ProjectionCursorStore } from "@alneas/eaos-server";
export async function saveProjectionProgress(
store: ProjectionCursorStore, cursor: Parameters<ProjectionCursorStore["put"]>[0],
) {
// The host aligns this tenant cursor with committed projection work.
await store.put(cursor);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted downloadable asset catalog entry; client input selects IDs rather than object keys.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

interface ProtectedPluginAsset {
id: string;
pluginId: string;
key: string;
sha256: string;
contentType: string;
}
Name Type Required Description
id string Yes Public asset ID unique within a plugin catalog.
pluginId string Yes Owning plugin ID.
key string Yes Host storage object key passed to the signing port.
sha256 string Yes Lowercase 64-hex checksum validated before signing.
contentType string Yes Host-declared media type returned as metadata.

Type declaration; no runtime value.

createPluginAssetRouter.

Public asset ID unique within a plugin catalog.

Owning plugin ID.

Host storage object key passed to the signing port.

Lowercase 64-hex checksum validated before signing.

Host-declared media type returned as metadata.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Parses account membership claims exclusively from an active identity’s public metadata.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/public-memberships.

declare function publicAccountMemberships(identity: Record<string, unknown>): AccountMemberships;
Name Type Required Description
identity Record<string, unknown> Yes Identity returned by a server-verified Kratos session; state must equal active.

AccountMemberships

Parsed memberships and optional defaultTenantId; absent/null public metadata supplies an empty membership list.

Never pass editable traits or unverified client JSON. There is no fallback to private metadata or SQL membership lookup, and parsing does not authenticate the identity.

For inactive identities, malformed public metadata, or invalid membership claims rejected by the platform parser.

import { publicAccountMemberships } from "@alneas/eaos-server/browser-auth/public-memberships";
import { createKratosSessionVerifier } from "@alneas/eaos-server/browser-auth/kratos-session";
const verify = createKratosSessionVerifier({ publicUrl: "https://identity.example.com" });
export async function memberships(cookie: string | undefined) {
const session = await verify({ cookie });
return session ? publicAccountMemberships(session.identity) : null;
}

Moves reviewed membership fields from administrator to public metadata in one provider write and verifies readback.

Imports: @alneas/eaos-server/browser-auth, @alneas/eaos-server/browser-auth/account-memberships.

declare function publishAccountMemberships(plan: MembershipPublicationPlan, actor: string, store: AccountMutationStore, admin: AccountAdminPort): Promise<void>;
Name Type Required Description
plan MembershipPublicationPlan Yes Reviewed publication plan; current private claims must still match exactly.
actor string Yes Nonblank authenticated operator identity.
store AccountMutationStore Yes Durable exclusive mutation lock and completion audit.
admin AccountAdminPort Yes Provider port that must write both metadata fields from the supplied identity in one request.

Promise<void>

No value; resolves after verified readback and durable completion, retaining unrelated public/private metadata.

The durable lock remains on any failed or uncertain outcome; reconcile instead of blind retry. This function does not roll back or independently authenticate the operator. Atomicity of the two-field update depends on the host port honoring its single-request contract.

Rejects invalid actor/claims, stale snapshot, changed memberships, failed provider verification, or propagated store/provider failures.

import { publishAccountMemberships, type MembershipPublicationPlan, type AccountMutationStore, type AccountAdminPort } from "@alneas/eaos-server/browser-auth/account-memberships";
export async function publishReviewedPlan(plan: MembershipPublicationPlan, actor: string, store: AccountMutationStore, admin: AccountAdminPort) {
await publishAccountMemberships(plan, actor, store, admin);
}

Domain event and generated task stored as one event queue item.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/event-bridge.

interface QueuedEventTask {
eventName: string;
payload: unknown;
task: ServerAgentTaskRequest;
}
Name Type Required Description
eventName string Yes Originating subscribed event name.
payload unknown Yes Associated event payload; durable enqueue receives a structured clone.
task ServerAgentTaskRequest Yes Generated task with ID and execution idempotency context.

Type declaration; no runtime value.

EventAgentTaskStore.

Originating subscribed event name.

Associated event payload; durable enqueue receives a structured clone.

Generated task with ID and execution idempotency context.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Read and verify one bounded page of immutable tenant audit events.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/audit.

declare function readAtomicAudit(tx: AtomicSession, p: PluginPrincipal, afterSequence?: number, limit?: number): Promise<{
events: AtomicAuditEvent[];
nextSequence: number | null;
}>;
Name Type Required Description
tx AtomicSession Yes Live tenant-scoped atomic session.
p PluginPrincipal Yes Verified principal whose tenant must match each event.
afterSequence number No Exclusive nonnegative sequence; defaults to 0.
limit number No Integer page size from 1 to 100; defaults to 50.

Promise<{ events: AtomicAuditEvent[]; nextSequence: number \| null; }>

Verified events and a continuation sequence or null when no further row was observed.

Caller enforces current resource permission before and after reading. One page does not verify full chain continuity or an external trust anchor.

Rejects invalid pagination, event identity/version/revision/hash mismatches or store failures.

import { readAtomicAudit } from '@alneas/eaos-server/plugin-data'
export function auditPage(tx: Parameters<typeof readAtomicAudit>[0], p: Parameters<typeof readAtomicAudit>[1]) { return readAtomicAudit(tx, p, 0, 50) }

Document-scoped reader comment with author-controlled resolution and private/shared visibility.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/annotations.

interface ReaderComment {
id: string;
anchorId: string | null;
body: string;
visibility: 'private' | 'shared';
authorId: string;
createdAt: string;
resolved: boolean;
}
Name Type Required Description
id string Yes Generated comment UUID; physical storage also prefixes the pinned document and visibility scope.
anchorId string | null Yes Pinned valid document anchor, or null for a document-wide comment.
body string Yes Nonblank trimmed comment text; outer schema limits input to 4000 characters.
visibility 'private' | 'shared' Yes private scopes rows to the actor hash; shared scopes them to the authorized document audience.
authorId string Yes Authenticated creator; only this actor may change resolution.
createdAt string Yes Trusted ISO timestamp supplied by the owning command.
resolved boolean Yes Author-controlled resolution flag, updated using the stored CAS revision.

Type declaration; no runtime value.

documentAnnotations for canonical host integration.

Generated comment UUID; physical storage also prefixes the pinned document and visibility scope.

Pinned valid document anchor, or null for a document-wide comment.

Nonblank trimmed comment text; outer schema limits input to 4000 characters.

private scopes rows to the actor hash; shared scopes them to the authorized document audience.

Authenticated creator; only this actor may change resolution.

Trusted ISO timestamp supplied by the owning command.

Author-controlled resolution flag, updated using the stored CAS revision.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reads trimmed S3 or R2 configuration from a host environment map.

Imports: @alneas/eaos-server/storage, @alneas/eaos-server/storage/s3-compatible.

declare function readS3CompatibleStorageConfig(env?: Record<string, string | undefined>): S3CompatibleStorageConfig | null;
Name Type Required Description
env Record<string, string | undefined> No Environment values; defaults to process.env. EAOS_STORAGE_PROVIDER selects s3/r2 case-insensitively. R2 uses R2_ACCOUNT_ID, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and optional R2_ENDPOINT. S3 uses S3_BUCKET, S3_REGION, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, optional S3_ENDPOINT, and S3_FORCE_PATH_STYLE (true or 1). EAOS_STORAGE_MAX_URL_SECONDS is converted with Number.

S3CompatibleStorageConfig \| null

Configuration, or null when the provider is absent/blank. This read does not fully validate values; creation validates provider settings.

Returned configuration contains secrets and belongs exclusively in trusted server code.

If a selected provider lacks required nonblank values, or the provider is unsupported.

import { readS3CompatibleStorageConfig } from "@alneas/eaos-server/storage/s3-compatible";
const config = readS3CompatibleStorageConfig();
console.log(config ? "Storage configured" : "Storage disabled");

Replaces a completely applied exact contract history with its reviewed baseline ledger record without running DDL.

Rebase only a completely applied exact history. This function never executes DDL.

Imports: @alneas/eaos-server/lifecycle-engine, @alneas/eaos-server/lifecycle-engine/baseline.

declare function rebaseDataContractBaseline(store: LifecycleStore, databaseId: string, baseline: DataContractBaseline, options: {
expectedRevision: number;
quiesce?: (input: {
databaseId: string;
pluginIds: string[];
}) => Promise<void>;
}): Promise<{
baselineHash: string;
revision: number;
rebased: number;
ddlExecuted: false;
}>;
Name Type Required Description
store LifecycleStore Yes Durable cross-process exclusive lifecycle store.
databaseId string Yes Physical database ledger identity whose contract history is rebased.
baseline DataContractBaseline Yes Unmodified baseline created by createDataContractBaseline.
options { expectedRevision: number; quiesce?: (input: { databaseId: string; pluginIds: string[]; }) => Promise<void>; } Yes Expected ledger revision and optional all-instance quiesce callback, required when affected consumers are active.

Promise<{ baselineHash: string; revision: number; rebased: number; ddlExecuted: false; }>

Baseline hash, next revision, count of replaced records and ddlExecuted=false.

Runs under the store lock, archives old migration history and disables affected live consumers. Host drain happens before the final atomic state write; external drain may have occurred even if that write fails. No schema or data migration is executed.

Rejects integrity mismatch, stale revision, partial/dirty history, incompatible installed consumer range, absent drain or propagated store/quiesce failures.

Exact current ledger revision reviewed by the caller; mismatch rejects before mutation.

Host drains all instances before disabling the affected live consumers.

Exact physical database identity whose live consumers must drain.

Distinct affected feature IDs consuming the rebased contract.

import { rebaseDataContractBaseline, type DataContractBaseline, type LifecycleStore } from '@alneas/eaos-server/lifecycle-engine';
export function rebaseReviewed(store: LifecycleStore, databaseId: string, baseline: DataContractBaseline, options: Parameters<typeof rebaseDataContractBaseline>[3]) { return rebaseDataContractBaseline(store, databaseId, baseline, options); }

Executes schema-validated aggregate reducers through tenant isolation, live admission and revision-predicated persistence.

Plugin-owned reducers may change their private snapshot only; irreversible external effects must be queued durably.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/commands.

declare class RecordCommandService<T extends CommandState> {
constructor(host: CommandHost<T>, definition: {
schemas: Record<string, object>;
writes: readonly string[];
recordId?: (input: Record<string, any>) => string;
initial: (tenantId: string, recordId: string) => T;
reduce: (context: CommandContext<T>) => Promise<unknown>;
validate: (state: T) => void;
});
execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<CommandResponse<any>>;
}
Name Type Required Description
host CommandHost<T> Yes Live authorization and durable store or transaction; transaction takes precedence when provided.
definition { schemas: Record<string, object>; writes: readonly string[]; recordId?: (input: Record<string, any>) => string; initial: (tenantId: string, recordId: string) => T; reduce: (context: CommandContext<T>) => Promise<unknown>; validate: (state: T) => void; } Yes Plugin schemas, write-operation allowlist, record-ID resolver, initial-state factory, reducer and invariant validator.

RecordCommandService

  • T: Tenant-owned aggregate state with tenantId and appendable operation history.

Requires server Ajv/formats and a real host store or connection-bound transaction. Reducers mutate only their private cloned snapshot; queue irreversible external effects durably. Transactional hosts keep reads, write/CAS and final admission in one commit boundary; plain stores do not add a transaction. No command deduplication or automatic retry is added.

Throws for absent durable store/transaction or live authorization and for invalid strict Ajv schemas.

Strict noncoercing JSON Schemas indexed by accepted operation names.

Explicit operation names that persist state, require matching revision and append history.

Optional pure resolver from admitted input to a nonblank record scope up to 256 characters; omitted uses state.

Parameters:

  • input: Cloned schema-admitted input.

Returns: Nonblank logical record ID up to 256 characters; omitted resolver defaults to state.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Create a tenant/record-bound unstored aggregate snapshot when no row exists.

Parameters:

  • tenantId: Verified tenant ID owning the aggregate.
  • recordId: Resolved logical record ID.

Returns: A new private unstored tenant-owned state with initialized history.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Async plugin reducer receiving private state/input and verified context; mutate only that snapshot and queue external effects durably.

Parameters:

  • context: Private mutable state, cloned principal/input and trusted operation time.

Returns: Optional domain response data; undefined selects the resulting state for response data.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Synchronous aggregate invariant assertion before/after writes; throw to reject invalid state.

Parameters:

  • state: Private aggregate state whose tenant/history/domain invariants must hold.

Returns: Completes without a value when invariants pass; throw to reject before persistence.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Validates and admits one aggregate operation, running a reducer against a private current snapshot.

Parameters:

  • principal: Host-authenticated current tenant/user context; structural validation alone proves no membership.
  • operation: Declared schema key; membership in definition.writes selects persistence.
  • input: Operation-schema input; writes require a safe integer revision matching the current snapshot, including 0 for a new/unstored aggregate.

Returns: A tenant/record/revision envelope with cloned reducer data, or resulting state when the reducer returns undefined; read-only reducers do not persist mutations.

Record ID defaults to state and must be nonblank/up to 256 characters. Writes append actor/UTC history and reject over 5000 entries or 8 MiB JSON state. Host transaction projections may start at revision 0. Rejections can follow partial plain-store/adapter effects; callers must reload before retrying uncertain outcomes.

Rejects malformed principal (401), denied live admission (403), schema/scope errors (400), stale revision/capacity/CAS conflict (409), invalid foreign records/reducer scope, and propagated reducer/invariant/clock/store/transaction failures.

Example:

import { RecordCommandService, type CommandState, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export function executeAggregate<T extends CommandState>(service: RecordCommandService<T>, principal: PluginPrincipal, operation: string, input: unknown) { return service.execute(principal, operation, input); }
import { RecordCommandService, type CommandState, type CommandHost } from '@alneas/eaos-server/plugin-data';
export function connectAggregate<T extends CommandState>(host: CommandHost<T>, definition: ConstructorParameters<typeof RecordCommandService<T>>[1]) { return new RecordCommandService(host, definition); }

Encode an exclusive record position bound to the canonical hash of its query scope.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

declare function recordCursor(scope: unknown, after: string): string;
Name Type Required Description
scope unknown Yes Tenant/user/operation/filter scope defined by the caller.
after string Yes Exclusive logical record ID to resume after.

string

Base64url cursor containing the scope hash and position.

Encoding is not encryption or a signature; the reader validates scope and record-key grammar.

Unsupported canonical scope values or JSON serialization failures propagate.

import { recordCursor } from '@alneas/eaos-server/plugin-data'
const cursor = recordCursor(['example-tenant', 'list'], 'record-1')

Resolve canonical payload document contracts for one verified Data Contract table/namespace binding.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/json-documents.

declare function recordDocuments(catalog: DataContractCatalog, binding: DataContractBinding & {
jsonDocuments?: readonly string[];
}): JsonDocumentContract[];
Name Type Required Description
catalog DataContractCatalog Yes Trusted resolved Data Contract catalog.
binding DataContractBinding & { jsonDocuments?: readonly string[]; } Yes Contract identity, table, namespace and optional declared document IDs.

JsonDocumentContract[]

All matching payload document contracts for the bound table/namespace, possibly empty.

Validates requested document selection but returns every matching namespace document, not only the requested-ID subset.

Rejects missing/mismatched bindings, a table without id/revision/payload envelope fields or unavailable/duplicate requested document IDs.

Optional explicit nonempty unique document IDs to verify against the bound namespace; all matching namespace documents are returned.

import { recordDocuments } from '@alneas/eaos-server/plugin-data'
export function documents(catalog: Parameters<typeof recordDocuments>[0], binding: Parameters<typeof recordDocuments>[1]) { return recordDocuments(catalog, binding) }

Parameterized SQL transport whose host owns tenant session, transaction and provider binding behavior.

Imports: @alneas/eaos-server/plugin-data.

interface RecordSqlDriver {
dialect: 'sqlite' | 'postgres' | 'oracle';
execute(tenantId: string, sql: string, bindings: unknown[]): Promise<{
rows?: Record<string, unknown>[];
affectedRows?: number;
}>;
}
Name Type Required Description
dialect 'sqlite' | 'postgres' | 'oracle' Yes SQL placeholder/driver dialect selected by trusted host configuration.
execute Promise<{ rows?: Record<string, unknown>[]; affectedRows?: number; }> Yes Executes trusted parameterized SQL through the host-selected tenant session or transport. Bind arrays are positional. Host owns transaction/commit, Oracle CLOB bindings and authenticated tenant session.

Type declaration; no runtime value.

createSqlRecordStore for canonical host integration.

SQL placeholder/driver dialect selected by trusted host configuration.

Executes trusted parameterized SQL through the host-selected tenant session or transport.

Bind arrays are positional. Host owns transaction/commit, Oracle CLOB bindings and authenticated tenant session.

Parameters:

  • tenantId: Verified tenant context for host routing/session setup; it is not an independent permission proof.
  • sql: Trusted SQL containing explicit tenant predicates; never untrusted SQL text.
  • bindings: Positional binds in SQL placeholder order; host handles Oracle CLOB/session details.

Returns: Optional row data and affected-row count; CAS callers require accurate affectedRows.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { RecordSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function queryTenant(driver: RecordSqlDriver, principal: PluginPrincipal, trustedSql: string, bindings: unknown[]) {
// The host supplies dialect-correct SQL with explicit tenant predicates.
const result = await driver.execute(principal.tenantId, trustedSql, bindings);
return result.rows ?? [];
}

Optional SQL result rows using host provider object-column names.

Accurate DML row count; required by revision-predicated replace.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Closed schema requiring the exact job revision for explicit drained-worker recovery.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/delivery.

declare const recoverDeliverySchema: {
type: string;
additionalProperties: boolean;
required: string[];
properties: {
jobId: {
type: string;
pattern: string;
};
revision: {
type: string;
minimum: number;
maximum: number;
};
};
};
Name Type Required Description
— — — No call parameters.

Declared constant value.

ArtifactDeliveryService for canonical usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reset one failed tenant event to pending while retaining its immutable identity.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/outbox.

declare function requeueOutboxEvent(tx: AtomicSession, tenantId: string, id: string, availableAt?: string): Promise<OutboxEvent>;
Name Type Required Description
tx AtomicSession Yes Live session entered after explicit host recovery authorization.
tenantId string Yes Verified tenant identity required to match the stored event.
id string Yes Existing failed event ID, nonempty and at most 256 characters.
availableAt string No Parseable retry timestamp; defaults to the current ISO time.

Promise<OutboxEvent>

The requeued event with claim/error fields cleared.

Does not perform delivery or authorize recovery. A prior uncertain external effect may already exist; handlers must deduplicate by the retained identity.

Rejects invalid identifiers/timestamps, missing/nonfailed/foreign events or CAS failures.

import { requeueOutboxEvent } from '@alneas/eaos-server/plugin-data'
export function requeue(tx: Parameters<typeof requeueOutboxEvent>[0], tenantId: string, id: string) { return requeueOutboxEvent(tx, tenantId, id) }

Determines whether a plugin rule needs the external entitlement runtime.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare function requiresEntitlementRuntime(rule: PluginEntitlement): boolean;
Name Type Required Description
rule PluginEntitlement Yes Declared plugin entitlement policy.

boolean

True for nonpublic tier, any metering, or any allowedTenants property; otherwise false.

Public unmetered rules still require authentication and host lifecycle/resource admission.

import { requiresEntitlementRuntime } from "@alneas/eaos-server/entitlements";
import type { PluginEntitlement } from "@alneas/eaos-core";
export function needsSubscription(rule: PluginEntitlement) { return requiresEntitlementRuntime(rule); }

Verifies a stored API key and resolves its trusted user, tenant, and copied scopes.

Imports: @alneas/eaos-server/auth-hooks, @alneas/eaos-server/auth-hooks/api-key.

declare function resolveApiKey(headers: {
authorization?: string | null;
apiKey?: string | null;
}, lookup: ApiKeyLookup, options?: {
requiredScope?: string;
now?: Date;
authorize?: (record: ApiKeyRecord) => Promise<boolean> | boolean;
}): Promise<(PlatformPrincipal & {
apiKeyId: string;
}) | null>;
Name Type Required Description
headers { authorization?: string | null; apiKey?: string | null; } Yes Raw authorization and apiKey header values; a Bearer credential takes precedence, and credentials must begin with eaos_.
lookup ApiKeyLookup Yes Host record lookup by public prefix; see {@link ApiKeyLookup}.
options { requiredScope?: string; now?: Date; authorize?: (record: ApiKeyRecord) => Promise<boolean> | boolean; } No requiredScope is checked by core verification; now overrides the verification clock; authorize runs only after cryptographic and scope checks and must return exactly true.

Promise<(PlatformPrincipal & { apiKeyId: string; }) \| null>

A principal with apiKeyId and empty roles, or null for malformed, missing, invalid, expired, insufficiently scoped, or host-denied credentials.

Membership and tenant lifecycle checks belong in authorize. No key usage or persistence update occurs here.

Rejects on lookup or authorize failure; these are not converted to null.

Optional raw Authorization header; a parsed Bearer credential takes precedence over the dedicated apiKey value.

Optional dedicated API-key header used only when no Bearer credential is parsed; surrounding whitespace is trimmed.

Optional exact key scope checked by core cryptographic/lifecycle verification.

Optional verification clock override; omission uses the core verifier clock.

Optional live membership/lifecycle callback after key verification; receives the stored record and must return exactly true to allow, while errors reject resolution.

Stored key record ID attached to the resolved principal for audit/correlation, never the credential secret.

import { resolveApiKey, type ApiKeyLookup } from "@alneas/eaos-server/auth-hooks/api-key";
import type { ApiKeyRecord } from "@alneas/eaos-core";
export async function authenticate(
authorization: string | null,
lookup: ApiKeyLookup,
authorize: (record: ApiKeyRecord) => Promise<boolean>,
) {
return resolveApiKey({ authorization }, lookup, { requiredScope: "records:read", authorize });
}

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

declare function resolveDataContracts(available: readonly DataContract[], requirements: Record<string, string>): DataContractCatalog;
Name Type Required Description
available readonly DataContract[] Yes See the upstream owning declaration.
requirements Record<string, string> Yes See the upstream owning declaration.

DataContractCatalog

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Resolves each selected plugin component against explicit compatible deployment destinations.

All selected components are explicit; [] means an optional capability was deliberately not adopted.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

declare function resolveDeploymentPlacements(placements: DeploymentPlacements, inventories: DeploymentInventory[]): {
owner: string;
pluginId: string;
componentId: string;
destinationIds: string[];
adopted: boolean;
}[];
Name Type Required Description
placements DeploymentPlacements Yes Validated explicit selections; every component must have a destination list.
inventories DeploymentInventory[] Yes Trusted inventories with unique owner IDs and declared plugin work.

{ owner: string; pluginId: string; componentId: string; destinationIds: string[]; adopted: boolean; }[]

Component selections with copied destinationIds and adopted flags; an empty list deliberately declines an optional component.

Selecting a plugin does not register or enable it. Required components cannot be declined, and adopted work cannot depend on declined nonartifact work. A host component may target a container destination.

Error for unknown inventory/plugin/component/destination, duplicate owners, missing required placement, incompatible role/kind or declined dependency.

import { resolveDeploymentPlacements } from '@alneas/eaos-server/platform/deployment-placements';
import type { DeploymentInventory } from '@alneas/eaos-server/platform/artifacts';
export function resolve(placements: Parameters<typeof resolveDeploymentPlacements>[0], inventories: DeploymentInventory[]) { return resolveDeploymentPlacements(placements, inventories); }

[CONSTANT] resolveEngineEntitlementPrincipal

Section titled “[CONSTANT] resolveEngineEntitlementPrincipal”

Resolves the engine context principal only when user.tenantId matches tenantId and userId exists.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare const resolveEngineEntitlementPrincipal: EntitlementPrincipalResolver;
Name Type Required Description
— — — No call parameters.

Declared constant value.

Principal using context IDs and user roles, or null for missing/mismatched identity.

Does not independently query live membership or authenticate headers.

import { Hono } from "hono";
import { resolveEngineEntitlementPrincipal } from "@alneas/eaos-server/entitlements";
const app = new Hono();
app.get("/identity-state", async c => c.json({ authenticated: !!await resolveEngineEntitlementPrincipal(c) }));

Resolves the host-selected backend for a verified tenant without falling back after a resolver denial.

Imports: @alneas/eaos-server/lifecycle.

declare function resolveLifecycleBackend(runtime: LifecycleRuntime, tenantId: string): Promise<string>;
Name Type Required Description
runtime LifecycleRuntime Yes Lifecycle runtime with either a backend resolver or fixed backend ID.
tenantId string Yes Verified tenant whose placement is being resolved.

Promise<string>

Nonempty resolved backend ID, or runtime.backendId when no callback exists.

Rejects an empty/null backend result or propagated resolver errors.

import { resolveLifecycleBackend, type LifecycleRuntime } from "@alneas/eaos-server/lifecycle";
export async function backend(runtime: LifecycleRuntime, tenantId: string) {
return resolveLifecycleBackend(runtime, tenantId);
}

Resolves a verified tenant to its explicit placement or the configured default backend.

Tenant comes from verified host membership, never raw request input. No implicit migration/fallback.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/runtime.

declare function resolvePlatformDatabaseTarget(runtime: PlatformRuntimeConfig, tenantId: string): BackendTarget;
Name Type Required Description
runtime PlatformRuntimeConfig Yes Previously validated runtime configuration.
tenantId string Yes Verified concrete tenant from host membership, never raw request input.

BackendTarget

The configured target object without cloning.

Unmapped tenants use the configured default; a missing or dedicated-mismatched selected target fails rather than trying another database. No migration or database operation occurs.

Error for missing/wildcard tenant or unavailable/mismatched target.

import { resolvePlatformDatabaseTarget } from '@alneas/eaos-server/platform/runtime';
const target = resolvePlatformDatabaseTarget({ backend: { id: 'main', databaseId: 'db-main', dialect: 'sqlite', mode: 'shared' } }, 'sample');

Require a positive safe-integer revision without coercing string inputs.

Imports: @alneas/eaos-server/plugin-data.

declare function revisionInput(value: unknown): number;
Name Type Required Description
value unknown Yes Untrusted revision value.

number

The positive safe-integer revision.

Throws PluginError 400 for nonintegers, numeric strings, zero, negatives or unsafe integers.

import { revisionInput } from '@alneas/eaos-server/plugin-data'
const revision = revisionInput(1)

Runs a host job through lifecycle admission for its verified tenant and plugin.

Imports: @alneas/eaos-server/lifecycle.

declare function runLifecycleJob<T>(runtime: LifecycleRuntime, job: {
tenantId: string;
pluginId: string;
}, callback: () => Promise<T>): Promise<T>;
Name Type Required Description
runtime LifecycleRuntime Yes Backend routing and lifecycle engine.
job { tenantId: string; pluginId: string; } Yes Trusted tenantId/pluginId binding of the queued job.
callback () => Promise<T> Yes Invoked without arguments by lifecycle.run after admission; resolves the job result.

Promise<T>

The callback result after lifecycle.run completes.

  • T: Result resolved by the admitted callback.

Persistence, retries, and idempotency of the job body belong to the host. This wrapper delegates concurrency/drain behavior to lifecycle.run.

Rejects unavailable backend, lifecycle admission/store failure, or callback failure.

Verified tenant identity of the queued job, used to select its lifecycle backend.

Exact plugin ID whose current lifecycle admission gates this job body.

import { runLifecycleJob, type LifecycleRuntime } from "@alneas/eaos-server/lifecycle";
export async function runJob<T>(runtime: LifecycleRuntime, tenantId: string, pluginId: string, execute: () => Promise<T>) {
return runLifecycleJob(runtime, { tenantId, pluginId }, execute);
}

Selects R2 or S3 transport settings with host-held credentials and a signed URL ceiling.

Imports: @alneas/eaos-server/storage, @alneas/eaos-server/storage/s3-compatible.

type S3CompatibleStorageConfig = Common & (({
provider: 'r2';
} & Omit<R2StorageConfig, 'accessKeyId' | 'secretAccessKey' | 'publicUrl' | 'defaultExpiresIn'>) | ({
provider: 's3';
} & Omit<S3StorageConfig, 'accessKeyId' | 'secretAccessKey' | 'defaultExpiresIn'>));
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

R2 requires a 32-hex-character accountId; S3 requires region. Both require a valid bucket name. Optional endpoints must be HTTPS URLs without credentials, query, or fragment. Provider-specific fields follow app-core storage configuration; public URLs are not configured by this factory.

createS3CompatibleStorage for a complete setup example.

Select Cloudflare R2 transport; accountId must be 32 hexadecimal characters and bucket/credentials must be configured.

Select S3-compatible transport; a nonempty region and valid bucket/credentials are required, with optional HTTPS endpoint.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/lifecycle-engine.

interface SchemaMigrationSource {
migrations: PluginMigration[];
schemaDependencies?: Record<string, string>;
schemaContracts?: DataContract[];
}
Name Type Required Description
migrations PluginMigration[] Yes See the upstream owning declaration.
schemaDependencies Record<string, string> No See the upstream owning declaration.
schemaContracts DataContract[] No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Legacy table-schema input collected for migration text generation.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/migration, @alneas/eaos-server/db/migration/aggregator.

interface SchemaSource {
pluginId: string;
pluginName?: string;
extensionId?: string;
migrationOrder?: number;
schemaJson: Record<string, any>;
}
Name Type Required Description
pluginId string Yes Plugin ID, or data:{contractId} for resolved data contracts.
pluginName string No Optional display label used in generated SQL comments.
extensionId string No Optional extension ID appended to the source identifier.
migrationOrder number No Sort order from the plugin manifest; defaults to 999 for plugin schemas.
schemaJson Record<string, any> Yes Legacy tables/columns schema; canonical x-db/$defs schemas require reviewed lifecycle migrations instead.

Type declaration; no runtime value.

MigrationAggregator for a complete usage example.

Plugin ID, or data:{contractId} for resolved data contracts.

Optional display label used in generated SQL comments.

Optional extension ID appended to the source identifier.

Sort order from the plugin manifest; defaults to 999 for plugin schemas.

Legacy tables/columns schema; canonical x-db/$defs schemas require reviewed lifecycle migrations instead.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Plugin-owned schemas, CRUD reducers, filtering and transactional identity/composition rules.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/scoped-records.

interface ScopedRecordDefinition<T extends {
tenantId: string;
id: string;
}, S extends T & {
revision: number;
}> {
schemas: Record<string, object>;
operations: {
list: string;
get: string;
create: string;
update: string;
archive: string;
};
listKey: string;
label: string;
pagination?: boolean;
excludedIdPrefixes?: readonly string[];
unique?: readonly {
name: string;
fields: readonly (keyof T & string)[];
when?: (record: T) => boolean;
}[];
searchableFields?: readonly (keyof S & string)[];
filter?: (input: Record<string, any>, value: S) => boolean;
create(input: Record<string, any>, principal: PluginPrincipal, at: string): T;
update(value: S, patch: Record<string, unknown>, at: string): void;
archive(value: S, at: string, input?: Record<string, any>, principal?: PluginPrincipal): void;
custom?: Record<string, (value: S, input: Record<string, any>, at: string, principal: PluginPrincipal) => void>;
afterWrite?: (principal: PluginPrincipal, operation: string, input: Record<string, any>, current: S, previous?: S) => Promise<void>;
}
Name Type Required Description
schemas Record<string, object> Yes Explicit per-operation JSON Schemas compiled with coercion disabled.
operations { list: string; get: string; create: string; update: string; archive: string; } Yes Exact list/get/create/update/archive operation names used for shared dispatch.
listKey string Yes Response property under which admitted records are returned.
label string Yes Trusted domain label used in validation/conflict errors.
pagination boolean No Enable filtered keyset scanning when the host store supplies listPage; otherwise a supplied cursor is rejected. Enable complete filtered paging when the store supplies listPage.
excludedIdPrefixes readonly string[] No Additional auxiliary record prefixes omitted from business CRUD results. Plugin-owned auxiliary keys must not appear as business records.
unique readonly { name: string; fields: readonly (keyof T & string)[]; when?: (record: T) => boolean; }[] No Optional composite identity reservation rules; require a shared transaction for concurrent enforcement. Transactional reservations enforce composite business identities across concurrent writers.
searchableFields readonly (keyof S & string)[] No Fields searched by the generic case-insensitive query filter.
filter (input: Record<string, any>, value: S) => boolean No Optional synchronous domain filter applied in addition to standard criteria and live record authorization.
create T Yes Creates a new tenant-owned domain payload from admitted inputs.
update void Yes Mutates only the private record snapshot with the admitted patch.
archive void Yes Mutates the private record snapshot to the plugin’s archive state.
custom Record<string, (value: S, input: Record<string, any>, at: string, principal: PluginPrincipal) => void> No Additional plugin-owned mutation reducers persisted through the same CAS path; never perform irreversible external effects here. Plugin-owned durable workflow commands. Each command is validated by its declared schema, receives the current revision, and is persisted through the same tenant-scoped CAS path as update/archive.
afterWrite (principal: PluginPrincipal, operation: string, input: Record<string, any>, current: S, previous?: S) => Promise<void> No Optional async owning-domain composition inside the shared transaction before final authorization; not an external side-effect hook. Owning domain composition inside the existing transaction, before final live authorization. Never use for external effects.

Type declaration; no runtime value.

  • T: Stored record payload with stable tenantId/id.
  • S: Decoded record view extending T with a positive CAS revision.

ScopedRecordService for canonical host integration.

Explicit per-operation JSON Schemas compiled with coercion disabled.

Exact list/get/create/update/archive operation names used for shared dispatch.

Host operation name for bounded or keyset-paged authorized record listing.

Host operation name for reading one authorized record.

Host operation name for creating one tenant record.

Host operation name for revision-predicated record patching.

Host operation name for the plugin-owned retained-data archive transition.

Response property under which admitted records are returned.

Trusted domain label used in validation/conflict errors.

Enable filtered keyset scanning when the host store supplies listPage; otherwise a supplied cursor is rejected.

Enable complete filtered paging when the store supplies listPage.

Additional auxiliary record prefixes omitted from business CRUD results.

Plugin-owned auxiliary keys must not appear as business records.

Optional composite identity reservation rules; require a shared transaction for concurrent enforcement.

Transactional reservations enforce composite business identities across concurrent writers.

Trusted uniqueness constraint label matching lowercase letter followed by up to 60 lowercase letters/digits/underscore/hyphen characters.

Nonempty ordered stored field keys; every active value must be a nonblank string.

Trusted domain predicate; false releases this record’s reservation.

Parameters:

  • record: Cloned current record; this predicate must be pure.

Returns: True to reserve the composite identity, false to release it; nonboolean results reject.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Fields searched by the generic case-insensitive query filter.

Optional synchronous domain filter applied in addition to standard criteria and live record authorization.

Parameters:

  • input: Schema-admitted list criteria.
  • value: Decoded scoped record being considered.

Returns: True to retain this candidate before the additional search/live-record permission checks.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Creates a new tenant-owned domain payload from admitted inputs.

Parameters:

  • input: Schema-validated create input.
  • principal: Verified current tenant principal.
  • at: Trusted UTC ISO operation timestamp.

Returns: The new payload with stable id and matching tenantId; no persistence is performed by this reducer.

Reducer errors propagate; do not perform irreversible external effects.

Example:

import type { ScopedRecordDefinition, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
type Stored = { tenantId: string; id: string; archived: boolean };
type View = Stored & { revision: number };
export function reduceCreate(definition: ScopedRecordDefinition<Stored, View>, principal: PluginPrincipal, admittedInput: Record<string, unknown>) {
return definition.create(admittedInput, principal, new Date().toISOString());
}

Mutates only the private record snapshot with the admitted patch.

Parameters:

  • value: Mutable current decoded revisioned record; preserve tenantId/id.
  • patch: Schema-admitted patch fields.
  • at: Trusted UTC ISO operation timestamp.

Returns: Completes without a value; the owning service performs CAS persistence.

Reducer errors propagate and roll back joined transactional work.

Example:

import type { ScopedRecordDefinition } from '@alneas/eaos-server/plugin-data';
type Stored = { tenantId: string; id: string; archived: boolean };
type View = Stored & { revision: number };
export function reduceUpdate(definition: ScopedRecordDefinition<Stored, View>, snapshot: View, admittedPatch: Record<string, unknown>) {
const next = structuredClone(snapshot);
definition.update(next, admittedPatch, new Date().toISOString());
return next; // The owning service still performs revision-checked persistence.
}

Mutates the private record snapshot to the plugin’s archive state.

Parameters:

  • value: Mutable current record; preserve stable tenantId/id.
  • at: Trusted UTC ISO operation timestamp.
  • input: Optional schema-admitted archive command input.
  • principal: Optional verified current principal supplied by the service.

Returns: Completes without a value; archive retains data according to the plugin reducer.

Reducer errors propagate; do not perform irreversible external effects.

Example:

import type { ScopedRecordDefinition, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
type Stored = { tenantId: string; id: string; archived: boolean };
type View = Stored & { revision: number };
export function reduceArchive(definition: ScopedRecordDefinition<Stored, View>, snapshot: View, principal: PluginPrincipal, admittedInput: Record<string, unknown>) {
const next = structuredClone(snapshot);
definition.archive(next, new Date().toISOString(), admittedInput, principal);
return next; // No persistence is performed by this reducer call.
}

Additional plugin-owned mutation reducers persisted through the same CAS path; never perform irreversible external effects here.

Plugin-owned durable workflow commands. Each command is validated by its declared schema, receives the current revision, and is persisted through the same tenant-scoped CAS path as update/archive.

Parameters:

  • value: Private mutable revisioned record; preserve stable tenant/id.
  • input: Schema-admitted custom command input.
  • at: Trusted ISO operation timestamp.
  • principal: Verified current principal.

Returns: Completes without a value after mutating the private snapshot; the owning service performs CAS persistence.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Optional async owning-domain composition inside the shared transaction before final authorization; not an external side-effect hook.

Owning domain composition inside the existing transaction, before final live authorization. Never use for external effects.

Parameters:

  • principal: Verified current principal.
  • operation: Declared mutation operation.
  • input: Schema-admitted command input.
  • current: Cloned resulting decoded record; do not mutate service state through this copy.
  • previous: Optional prior decoded record, absent on create.

Returns: Resolves without a value after owning-domain composition inside the same transaction; no external effects.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host record storage and live resource authorization, optionally joined to a shared atomic repository.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/scoped-records.

interface ScopedRecordHost<T> {
store: PluginRecordStore<T>;
authorize(principal: PluginPrincipal, operation: string, input: unknown, current?: unknown): Promise<boolean>;
now?: () => Date;
repository?: AtomicRepository;
}
Name Type Required Description
store PluginRecordStore<T> Yes Host record store with real tenant scoping and revision-predicated writes.
authorize Promise<boolean> Yes Checks current plugin activation and resource permission before exposing or persisting records.
now () => Date No Optional trusted operation clock; defaults to new Date().
repository AtomicRepository No Optional existing atomic repository joining ordinary CRUD, workflow commands, reservations and audit in one commit boundary. Ordinary CRUD and workflow commands share the provided transaction boundary.

Type declaration; no runtime value.

  • T: Tenant-owned stored record payload.

ScopedRecordService for canonical host integration.

Host record store with real tenant scoping and revision-predicated writes.

Checks current plugin activation and resource permission before exposing or persisting records.

Parameters:

  • principal: Verified current principal.
  • operation: Declared operation name.
  • input: Operation input, list criteria or created payload appropriate to the check.
  • current: Optional copied current record; absence requires operation-level admission.

Returns: Exactly true to admit the operation/record; false denies or filters the record during lists.

Rejects propagated host persistence, validation or callback failures.

Example:

import type { ScopedRecordHost, PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export async function admitted(host: ScopedRecordHost<{ title: string }>, principal: PluginPrincipal, operation: string, input: unknown, current?: unknown) {
return await host.authorize(principal, operation, input, current) === true;
}

Optional trusted operation clock; defaults to new Date().

Returns: A valid Date used for the current CRUD/domain operation timestamp.

Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.

Optional existing atomic repository joining ordinary CRUD, workflow commands, reservations and audit in one commit boundary.

Ordinary CRUD and workflow commands share the provided transaction boundary.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Applies schema-validated record CRUD and workflow commands through tenant checks, live admission and optimistic revisions.

Shared tenant-scoped CRUD/CAS boundary for small plugin-owned master records.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/scoped-records.

declare class ScopedRecordService<T extends {
tenantId: string;
id: string;
}, S extends T & {
revision: number;
}> {
constructor(host: ScopedRecordHost<T>, definition: ScopedRecordDefinition<T, S>, atomicSession?: AtomicSession | undefined);
execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown>;
}
Name Type Required Description
host ScopedRecordHost<T> Yes Durable tenant-scoped store, live authorization, optional clock and shared atomic repository.
definition ScopedRecordDefinition<T, S> Yes Plugin-owned operation names, schemas, reducers, paging and identity rules.
atomicSession AtomicSession | undefined No Optional already active internal session used for joined composition/uniqueness; its lifetime must not exceed the enclosing repository callback.

ScopedRecordService

  • T: Stored tenant-owned record payload containing stable tenantId and id.
  • S: Decoded public record view extending T with a positive CAS revision.

Use a real atomic repository for unique identity reservations, owning-domain composition and command/audit receipts. Repository execution joins CRUD/domain writes and final authorization in one transaction; plain stores do not gain those guarantees. Domain reducers must not perform irreversible external effects. Auxiliary audit/command/event/unique keys are excluded from business results as configured.

Throws when durable store or live authorization is missing, or strict schema compilation fails.

Dispatches one admitted record operation and optionally joins it to durable command/audit receipt handling.

Parameters:

  • principal: Verified current tenant/user principal; host authorization is rechecked throughout the operation.
  • operation: Declared list/get/create/update/archive or plugin custom reducer key.
  • input: Operation-schema input; mutations require matching record revision and optional durable commandId when declared.

Returns: List operations return the configured listKey with scoped records and paging metadata; get/mutations return a decoded revisioned record. Paged results may be incomplete and carry nextCursor/mayHaveMore.

Pagination scans at most 10000 rows per request, selecting authorized/filter-matching records. Without paging, filtering applies only to the bounded store result. Repository writes with declared commandId replay the stored identical result; other repository writes append audit. Recheck live resource permission before replay, and reload uncertain plain-store outcomes rather than retrying blindly.

Rejects invalid principal (401), denied/revoked admission (403), schema/operation errors (400), missing/excluded record (404), stale revision/uniqueness/CAS conflict or missing required transactional capability (409), foreign/corrupt records, and propagated domain/store/clock/callback failures.

Example:

import { ScopedRecordService, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';
export function dispatch<T extends {tenantId: string; id: string}, S extends T & {revision: number}>(service: ScopedRecordService<T, S>, principal: PluginPrincipal, operation: string, input: unknown) { return service.execute(principal, operation, input); }
import { ScopedRecordService, type ScopedRecordHost, type ScopedRecordDefinition } from '@alneas/eaos-server/plugin-data';
type Row = { tenantId: string; id: string; title: string };
type RevisionedRow = Row & { revision: number };
export function connectRecords(host: ScopedRecordHost<Row>, definition: ScopedRecordDefinition<Row, RevisionedRow>) { return new ScopedRecordService(host, definition); }

Wraps each contributed plugin route factory with an explicit tenant-scope middleware.

Imports: @alneas/eaos-server/extensions.

declare function scopeExtensionFactories(item: PlatformExtension): PlatformExtension;
Name Type Required Description
item PlatformExtension Yes Trusted validated extension; tenantIds is consulted at request time.

PlatformExtension

A shallow copy with fresh route factory wrappers; each wrapper invokes the original factory with unchanged arguments.

Set trusted tenantId context before handling requests. Out-of-scope or missing tenantId returns 403. This wrapper performs no membership or module authorization.

Calling a wrapped factory propagates the original route-factory errors.

import { scopeExtensionFactories, validateExtensions } from "@alneas/eaos-server/extensions";
const [extension] = validateExtensions([{ apiVersion: 1, id: "example", tenantIds: ["example"] }]);
const scoped = scopeExtensionFactories(extension);
console.log(scoped.id);

Wraps contributed host routers with tenant-scope checks followed by host module authorization.

Imports: @alneas/eaos-server/extensions.

declare function scopeExtensionRoutes(extension: PlatformExtension, requireModule: (moduleId: string) => MiddlewareHandler): Array<{
prefix: string;
router: Hono;
}>;
Name Type Required Description
extension PlatformExtension Yes Trusted validated contribution; omitted routes produce an empty array.
requireModule (moduleId: string) => MiddlewareHandler Yes Called once per route with moduleId during composition; returns middleware enforcing current module permissions.

Array<{ prefix: string; router: Hono; }>

New prefix/router pairs preserving original route order and mounting original routers beneath their guards.

Requires a verified tenantId in Hono context. No authentication is installed here.

Propagates module middleware factory or route composition errors; request execution propagates downstream failures.

Original host route prefix preserved for subsequent mounting.

Fresh Hono wrapper enforcing tenant scope and host module authorization before forwarding to the original router.

import { scopeExtensionRoutes, validateExtensions } from "@alneas/eaos-server/extensions";
import { createModuleGuard } from "@alneas/eaos-server/middleware/module-guard";
const [extension] = validateExtensions([{ apiVersion: 1, id: "example", tenantIds: ["example"] }]);
console.log(scopeExtensionRoutes(extension, id => createModuleGuard(id, { isDev: false }))); // []

Selects an account’s declared default or its only active membership without choosing among multiple active tenants.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/user-directory.

declare function selectAccountTenant(account: AccountMemberships): string | undefined;
Name Type Required Description
account AccountMemberships Yes Previously parsed AccountMemberships; this helper does not revalidate the default.

string \| undefined

The default tenant, the sole active tenant, or undefined when explicit selection is needed/no active membership exists.

import { parseAccountMemberships, selectAccountTenant } from '@alneas/eaos-server/platform/user-directory';
const tenantId = selectAccountTenant(parseAccountMemberships({ memberships: [{ tenantId: 'sample', role: 'member', active: true }] }));

Selects server-side queue execution or authenticated local runner pull delivery.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

type ServerAgentDispatchMode = 'server-queue' | 'local-pull';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

ServerAgentExecutionContext.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-selected workflow, correlation, tool scope, and local-runner bindings sent to the runtime.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

interface ServerAgentExecutionContext {
workflowId?: string;
correlationId?: string;
idempotencyKey?: string;
toolMode?: WorkflowAgentToolMode;
allowedToolNames?: readonly string[];
routeId?: string;
dispatchMode?: ServerAgentDispatchMode;
runnerId?: string;
}
Name Type Required Description
workflowId string No Optional workflow/session association.
correlationId string No Optional host tracing identifier.
idempotencyKey string No Optional host deduplication key; propagation alone does not enforce idempotency.
toolMode WorkflowAgentToolMode No Optional workflow tool-execution mode admitted by the host.
allowedToolNames readonly string[] No Optional allowlisted tool names; runtime adapters must enforce the intended boundary.
routeId string No Selected by the server broker; clients cannot override it.
dispatchMode ServerAgentDispatchMode No Optional delivery mode; local-pull jobs are claimed by authenticated local runners.
runnerId string No User/runner binding for local subscription or MLX execution.

Type declaration; no runtime value.

ServerAgentTaskRequest.

Optional workflow/session association.

Optional host tracing identifier.

Optional host deduplication key; propagation alone does not enforce idempotency.

Optional workflow tool-execution mode admitted by the host.

Optional allowlisted tool names; runtime adapters must enforce the intended boundary.

Selected by the server broker; clients cannot override it.

Optional delivery mode; local-pull jobs are claimed by authenticated local runners.

User/runner binding for local subscription or MLX execution.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Carries stable failure classification and retry advice from runtime adapters to queue coordination.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

declare class ServerAgentExecutionError extends Error {
readonly failureCode: WorkflowAgentFailureCode;
readonly retryable: boolean;
constructor(message: string, failureCode: WorkflowAgentFailureCode, retryable: boolean, options?: {
cause?: unknown;
});
}
Name Type Required Description
message string Yes Human-readable failure description.
failureCode WorkflowAgentFailureCode Yes Stable classification for caller retry policy.
retryable boolean Yes Whether the caller may consider retrying this failure.
options { cause?: unknown; } No Optional cause; omission does not attach an error cause.

ServerAgentExecutionError

Classification used by runner normalization and durable retry handling.

Host retry advice; true does not itself retry or make execution idempotent.

Optional underlying error attached through the standard Error cause option; omission leaves the cause unset.

import { ServerAgentExecutionError } from "@alneas/eaos-server/agentic/types";
const error = new ServerAgentExecutionError("Runtime unavailable", "AGENT_UNAVAILABLE", true);
console.log(error.failureCode, error.retryable);

Host- or plugin-owned agent execution adapter.

The server owns admission, authorization and result normalization; the adapter owns the configured runtime (OpenCode, Codex, Goose, LiteLLM, etc.).

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

type ServerAgentExecutor = (request: ServerAgentTaskRequest) => Promise<string>;
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

Runtime text output, which is not permission to perform business side effects.

Reject for unavailable, failed, timed-out, or invalid runtime work; ServerAgentExecutionError preserves classification and retry advice.

import type { ServerAgentExecutor } from "@alneas/eaos-server/agentic/types";
export function instrument(execute: ServerAgentExecutor): ServerAgentExecutor {
return async request => execute(structuredClone(request));
}

Host-admitted task passed to an agent runtime; tenant/user claims must already be verified.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

interface ServerAgentTaskRequest {
id: string;
tenantId: string;
userId: string;
title: string;
instructions: string;
workerType: ServerAgentWorkerType;
jobKind?: AgentJobKind;
context?: Record<string, unknown>;
executionContext?: ServerAgentExecutionContext;
runtimePolicy?: AgentRuntimeResourcePolicy;
timeoutMs?: number;
}
Name Type Required Description
id string Yes Stable task identifier used for result and checkpoint binding.
tenantId string Yes Verified tenant ID; never accepted directly as an authenticated request-body claim.
userId string Yes Verified submitting user ID.
title string Yes Nonblank task label; ServerAutonomousWorker limits this to 500 characters.
instructions string Yes Nonblank runtime instructions; ServerAutonomousWorker limits this to 1000000 characters.
workerType ServerAgentWorkerType Yes Selected built-in or host runtime adapter key.
jobKind AgentJobKind No Why the agent is running; not limited to task-graph workflows.
context Record<string, unknown> No Optional domain context; interpretation belongs to the executor.
executionContext ServerAgentExecutionContext No Host-verified workflow context propagated to the external runtime.
runtimePolicy AgentRuntimeResourcePolicy No Framework-selected resource policy. Callers cannot loosen this policy.
timeoutMs number No Optional execution timeout in milliseconds; built-in executors default to 60000 and accept safe integers from 1 to 3600000.

Type declaration; no runtime value.

ServerAgentExecutor for a complete adapter example.

Stable task identifier used for result and checkpoint binding.

Verified tenant ID; never accepted directly as an authenticated request-body claim.

Verified submitting user ID.

Nonblank task label; ServerAutonomousWorker limits this to 500 characters.

Nonblank runtime instructions; ServerAutonomousWorker limits this to 1000000 characters.

Selected built-in or host runtime adapter key.

Why the agent is running; not limited to task-graph workflows.

Optional domain context; interpretation belongs to the executor.

Host-verified workflow context propagated to the external runtime.

Framework-selected resource policy. Callers cannot loosen this policy.

Optional execution timeout in milliseconds; built-in executors default to 60000 and accept safe integers from 1 to 3600000.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Normalized runtime outcome; FAILED and PENDING_APPROVAL are returned data rather than successful output.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

interface ServerAgentTaskResult {
taskId: string;
status: 'COMPLETED' | 'PENDING_APPROVAL' | 'FAILED';
output?: string;
error?: string;
failureCode?: WorkflowAgentFailureCode;
retryable?: boolean;
approvalTicketId?: string;
approvalLevel?: ApprovalLevel;
riskLevel?: RiskLevel;
durationMs: number;
}
Name Type Required Description
taskId string Yes Task identifier to which this result belongs.
status 'COMPLETED' | 'PENDING_APPROVAL' | 'FAILED' Yes COMPLETED has runtime output; PENDING_APPROVAL awaits a host decision; FAILED records a rejected or failed run.
output string No Runtime text when available; omitted on failures and pending approval.
error string No Optional failure message for FAILED results.
failureCode WorkflowAgentFailureCode No Stable failure classification for durable retry/circuit-breaker handling.
retryable boolean No Optional retry advice; absence leaves retry policy to the caller.
approvalTicketId string No Optional generated approval binding for PENDING_APPROVAL.
approvalLevel ApprovalLevel No Optional human-approval level returned by the gatekeeper.
riskLevel RiskLevel No Optional risk classification returned by the gatekeeper.
durationMs number Yes Elapsed wall-clock milliseconds for this attempt.

Type declaration; no runtime value.

ServerAgentExecutor.

Task identifier to which this result belongs.

COMPLETED has runtime output; PENDING_APPROVAL awaits a host decision; FAILED records a rejected or failed run.

Runtime text when available; omitted on failures and pending approval.

Optional failure message for FAILED results.

Stable failure classification for durable retry/circuit-breaker handling.

Optional retry advice; absence leaves retry policy to the caller.

Optional generated approval binding for PENDING_APPROVAL.

Optional human-approval level returned by the gatekeeper.

Optional risk classification returned by the gatekeeper.

Elapsed wall-clock milliseconds for this attempt.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Runtime selector used to dispatch server tasks to built-in or host-provided executors.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

type ServerAgentWorkerType = 'goose' | 'hermes_agent' | 'litellm' | 'local_cli' | 'local_mlx' | 'external_no_training' | 'custom';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

ServerAgentExecutor for the host adapter contract.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-advertised AI candidate with server worker and queue/local-runner delivery binding.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/ai-broker.

interface ServerAIExecutionRoute extends AIExecutionCandidate {
workerType: ServerAgentWorkerType;
dispatchMode: ServerAgentDispatchMode;
runnerId?: string;
}
Name Type Required Description
workerType ServerAgentWorkerType Yes Executor key bound to the selected host route.
dispatchMode ServerAgentDispatchMode Yes Local CLI/MLX candidates must use local-pull; nonlocal candidates cannot use local-pull.
runnerId string No Pin a route to one registered local runner when the host requires it.

Type declaration; no runtime value.

DurableAIExecutionBroker.

Executor key bound to the selected host route.

Local CLI/MLX candidates must use local-pull; nonlocal candidates cannot use local-pull.

Pin a route to one registered local runner when the host requires it.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-verified approval decision submitted against a pending task checkpoint.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/types.

interface ServerApprovalCallbackPayload {
taskId: string;
approvalId?: string;
bindingHash?: string;
approved: boolean;
approverId: string;
approverRole: string;
comment?: string;
}
Name Type Required Description
taskId string Yes Task checkpoint identifier whose approval is being decided.
approvalId string No Optional external ticket binding; when supplied it must match the checkpoint.
bindingHash string No Optional binding hash for clients that persist the approval payload.
approved boolean Yes True to approve; false to reject the pending work.
approverId string Yes Authenticated host approver identifier.
approverRole string Yes Verified role used for approval authorization.
comment string No Optional human decision note.

Type declaration; no runtime value.

The host authenticates the approver and verifies role authority before passing this payload to a coordinator.

ServerAgentTaskResult.

Task checkpoint identifier whose approval is being decided.

Optional external ticket binding; when supplied it must match the checkpoint.

Optional binding hash for clients that persist the approval payload.

True to approve; false to reject the pending work.

Authenticated host approver identifier.

Verified role used for approval authorization.

Optional human decision note.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Admits and executes host agent tasks through a gatekeeper and bounded runtime adapters.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/autonomous-worker.

declare class ServerAutonomousWorker {
constructor(options?: ServerWorkerOptions);
runTask(request: ServerAgentTaskRequest): Promise<ServerAgentTaskResult>;
}
Name Type Required Description
options ServerWorkerOptions No Trusted host configuration; omitted gatekeeper uses a new McpGatekeeper and runtime role uses EAOS_RUNTIME_ROLE, then ai on arm64 or application-worker otherwise.

ServerAutonomousWorker

This class runs only when runTask is called; it installs no scheduler. The host authenticates tenant/user claims before admission. Framework-managed tasks share a per-instance concurrency counter; injected executors own scheduling and are exempt from it. Built-in Goose/Hermes require the ai role and Node process/systemd support. Queue persistence, approvals, retries, and side-effect idempotency belong to the host.

Invalid resource policy, role, or output limit.

Checks task limits and gatekeeper policy before dispatching one runtime attempt.

Parameters:

  • request: Verified task identity and instructions; required strings must be nonblank, title at most 500 characters, instructions at most 1000000, and timeout a safe integer 1–3600000 milliseconds when provided.

Returns: COMPLETED text output, PENDING_APPROVAL ticket data without execution, or FAILED data with error and optional classification/retry advice. Duration is measured in wall-clock milliseconds.

Gatekeeper receives fixed agent/server_bot roles rather than request user roles. Approval tickets are generated but not persisted here. The configured framework policy overrides request.runtimePolicy before execution. Injected executors and built-in LiteLLM outputs are bounded by maxOutputChars; LiteLLM response bodies are parsed before text length is checked.

Can reject a throwing gatekeeper or malformed gatekeeper interaction before dispatch; runtime execution errors are normally returned as FAILED data.

Example:

import { ServerAutonomousWorker, type ServerWorkerOptions } from "@alneas/eaos-server/agentic/autonomous-worker";
import type { ServerAgentTaskRequest } from "@alneas/eaos-server/agentic/types";
export async function execute(options: ServerWorkerOptions, request: ServerAgentTaskRequest) {
return new ServerAutonomousWorker(options).runTask(request);
}
import { ServerAutonomousWorker, type ServerWorkerOptions } from "@alneas/eaos-server/agentic/autonomous-worker";
export function worker(options: ServerWorkerOptions) { return new ServerAutonomousWorker(options); }

Host placement role controlling whether built-in Goose/Hermes processes may run locally.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/autonomous-worker.

type ServerRuntimeRole = 'edge' | 'application-worker' | 'ai';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

ServerAutonomousWorker.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted gatekeeper, runtime endpoints/adapters, and execution limits for ServerAutonomousWorker.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/autonomous-worker.

interface ServerWorkerOptions {
gatekeeper?: McpGatekeeper;
gooseBinaryPath?: string;
hermesAgentBinaryPath?: string;
litellmEndpoint?: string;
litellmModel?: string;
maxOutputChars?: number;
runtimePolicy?: AgentRuntimeResourcePolicy;
runtimeRole?: ServerRuntimeRole;
fetch?: typeof fetch;
executors?: Partial<Record<ServerAgentWorkerType, ServerAgentExecutor>>;
}
Name Type Required Description
gatekeeper McpGatekeeper No Host security/approval policies; defaults to a new McpGatekeeper.
gooseBinaryPath string No Trusted executable path; defaults to GOOSE_BIN_PATH or goose.
hermesAgentBinaryPath string No Trusted executable path; defaults to HERMES_AGENT_BIN_PATH or hermes.
litellmEndpoint string No Host LiteLLM base URL; defaults to LITELLM_ENDPOINT or http://localhost:4000/v1.
litellmModel string No Host model identifier; defaults to LITELLM_MODEL and is required for built-in LiteLLM execution.
maxOutputChars number No Combined command output/string result ceiling, safe integer 1–10000000; defaults to 1000000.
runtimePolicy AgentRuntimeResourcePolicy No Framework default is safe for the ARM agent host. Host adapters may tighten it.
runtimeRole ServerRuntimeRole No Built-in Goose/Hermes execution is permitted only on the AI placement.
fetch typeof fetch No Host fetch implementation for built-in LiteLLM; defaults to global fetch.
executors Partial<Record<ServerAgentWorkerType, ServerAgentExecutor>> No Host/plugin adapters for coding agents and other external runtimes.

Type declaration; no runtime value.

Host security/approval policies; defaults to a new McpGatekeeper.

Trusted executable path; defaults to GOOSE_BIN_PATH or goose.

Trusted executable path; defaults to HERMES_AGENT_BIN_PATH or hermes.

Host LiteLLM base URL; defaults to LITELLM_ENDPOINT or http://localhost:4000/v1.

Host model identifier; defaults to LITELLM_MODEL and is required for built-in LiteLLM execution.

Combined command output/string result ceiling, safe integer 1–10000000; defaults to 1000000.

Framework default is safe for the ARM agent host. Host adapters may tighten it.

Built-in Goose/Hermes execution is permitted only on the AI placement.

Host fetch implementation for built-in LiteLLM; defaults to global fetch.

Host/plugin adapters for coding agents and other external runtimes.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

[INTERFACE] ServerWorkflowAgentRunnerOptions

Section titled “[INTERFACE] ServerWorkflowAgentRunnerOptions”

Host executor configuration for createWorkflowAgentRunner.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-runner.

interface ServerWorkflowAgentRunnerOptions {
executor: ServerAgentExecutor;
runtimeId?: string;
}
Name Type Required Description
executor ServerAgentExecutor Yes Host-owned executor. It may be backed by Goose, Hermes or another runtime.
runtimeId string No Optional host runtime label copied into every normalized run result.

Type declaration; no runtime value.

Host-owned executor. It may be backed by Goose, Hermes or another runtime.

Optional host runtime label copied into every normalized run result.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Coordinates graph execution and host approval notifications without choosing a notification transport.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-manager.

declare class ServerWorkflowManager {
constructor(options?: ServerWorkflowOptions);
runWorkflow(graph: AgentGraphEngine, initialState: AgentGraphState): Promise<AgentGraphState>;
handleApproval(graph: AgentGraphEngine, payload: ServerApprovalCallbackPayload): Promise<{
resumed: boolean;
state?: AgentGraphState;
error?: string;
}>;
}
Name Type Required Description
options ServerWorkflowOptions No Host callbacks; omitted options perform no external notification and supply no resume authorizer.

ServerWorkflowManager

Checkpoint persistence and approval binding are delegated to AgentGraphEngine; the host authenticates approval callbacks. No webhook listener, retry queue, or delivery guarantee is installed.

Runs the graph and notifies the host if execution pauses for approval.

Parameters:

  • graph: Configured graph with appropriate durable checkpointer/admission.
  • initialState: Verified workflow identity and starting state.

Returns: Graph state after runStep, including any pending approval; notification failures do not change it.

Rejects graph execution failures; notification errors are caught and warned.

Example:

import { ServerWorkflowManager } from "@alneas/eaos-server/agentic/workflow-manager";
import type { AgentGraphEngine, AgentGraphState } from "@alneas/eaos-server/agentic/graph";
export async function run(graph: AgentGraphEngine, initialState: AgentGraphState) {
return new ServerWorkflowManager().runWorkflow(graph, initialState);
}

Delegates an authenticated approval decision to graph checkpoint/binding verification and resume.

Parameters:

  • graph: Graph owning the pending task checkpoint.
  • payload: Verified approver decision with optional approval/hash bindings; taskId selects the graph session.

Returns: Resume outcome, optional updated state, or failure data from resumeAfterApproval.

The host verifies caller identity and role before constructing payload. This wrapper does not send a second approval notification after resume.

Propagates graph/checkpointer errors not normalized by resumeAfterApproval.

Example:

import { ServerWorkflowManager, type ServerWorkflowOptions } from "@alneas/eaos-server/agentic/workflow-manager";
import type { AgentGraphEngine } from "@alneas/eaos-server/agentic/graph";
import type { ServerApprovalCallbackPayload } from "@alneas/eaos-server/agentic/types";
export async function approve(graph: AgentGraphEngine, options: ServerWorkflowOptions, payload: ServerApprovalCallbackPayload) {
return new ServerWorkflowManager(options).handleApproval(graph, payload);
}

Whether graph approval verification/resumption produced a saved state; false can follow partial effects and is not proof that nothing ran.

Optional graph checkpoint state returned after successful resumption; absent on the normalized failure paths.

Optional normalized checkpoint, approval, authorization or invocation failure detail when resumed is false; other errors can still reject the Promise.

import { ServerWorkflowManager, type ServerWorkflowOptions } from "@alneas/eaos-server/agentic/workflow-manager";
export function workflowManager(options: ServerWorkflowOptions) {
return new ServerWorkflowManager(options);
}

Host notification and approval authority callbacks used by ServerWorkflowManager.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-manager.

interface ServerWorkflowOptions {
onApprovalRequired?: (state: AgentGraphState) => Promise<void>;
authorizeResume?: (state: AgentGraphState, input: {
approverId: string;
approverRole: string;
approved: boolean;
}) => Promise<boolean>;
}
Name Type Required Description
onApprovalRequired (state: AgentGraphState) => Promise<void> No Called after runStep returns pendingApproval; receives the returned state. Notification failures are warned and do not fail runWorkflow.
authorizeResume (state: AgentGraphState, input: { approverId: string; approverRole: string; approved: boolean; }) => Promise<boolean> No Live host approval check receiving workflow state and verified approver/decision; must resolve true to permit resume. Errors are delegated to graph resume handling.

Type declaration; no runtime value.

Called after runStep returns pendingApproval; receives the returned state. Notification failures are warned and do not fail runWorkflow.

Live host approval check receiving workflow state and verified approver/decision; must resolve true to permit resume. Errors are delegated to graph resume handling.

Host-authenticated approver identifier attached to the pending decision.

Host-verified approver role to recheck against current resource/approval policy.

True requests continuation; false requests rejection, and a supplied authorizer also checks that decision.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Supported publication integration: Pages Git, GitHub Actions, artifact adapter or manual operator flow.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/site-publication.

type SitePublicationMode = SitePublicationPolicy['mode'];
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

parseSitePublicationPolicy for canonical integration usage.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-owned nonsecret publication mode and approval/trigger requirements; secret fields name bindings rather than contain secrets.

Host-owned policy; secrets and executable commands are never configuration values.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/site-publication.

type SitePublicationPolicy = {
requireApproval: boolean;
trigger: 'operator' | 'cms-published';
} & ({
mode: 'pages-git';
accountId: string;
project: string;
branch: string;
deployHookSecret: string;
} | {
mode: 'github-actions';
repository: string;
workflow: string;
ref: string;
tokenSecret: string;
} | {
mode: 'artifact';
provider: string;
target: string;
} | {
mode: 'manual';
});
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

parseSitePublicationPolicy for canonical integration usage.

Whether host workflow must obtain approval before publication; parsing does not grant approval.

Operator initiation or CMS-published event; manual mode permits only operator.

Publication integration discriminator selecting its required nonsecret fields.

Cloudflare account identifier, exactly 32 lowercase hexadecimal characters; not an access token.

Registered Pages project slug, at most 63 lowercase letters/digits/hyphens.

Reviewed Git branch reference without traversal or trailing slash.

Uppercase host secret-binding name for the deploy hook; never the hook value.

Publication integration discriminator selecting its required nonsecret fields.

Reviewed GitHub owner/repository reference.

Reviewed workflow basename ending .yml or .yaml.

Reviewed Git ref without traversal or trailing slash.

Uppercase host secret-binding name for the provider token; never the token value.

Publication integration discriminator selecting its required nonsecret fields.

Registered artifact publication adapter ID, up to 100 letters/digits/underscore/hyphen characters.

Registered nonsecret artifact publication target ID.

Publication integration discriminator selecting its required nonsecret fields.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Structural synchronous SQLite database API; lifecycle and physical migrations remain host-owned.

Structural Bun SQLite connection. The host owns the database and migration application.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/atomic.

interface SqliteAtomicDatabase {
exec(sql: string): unknown;
query(sql: string): {
all(...values: any[]): unknown[];
run(...values: any[]): {
changes: number;
};
};
}
Name Type Required Description
exec unknown Yes Executes trusted SQLite control SQL on the host-owned connection.
query { all(...values: any[]): unknown[]; run(...values: any[]): { changes: number; }; } Yes Prepares trusted parameterized SQLite SQL on the host-owned connection.

Type declaration; no runtime value.

createSqliteAtomicDriver for canonical host integration.

Executes trusted SQLite control SQL on the host-owned connection.

Parameters:

  • sql: Trusted transaction/control SQL text.

Returns: The native database execution result.

SQLite control failures throw synchronously.

Example:

import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';
export function enforceForeignKeys(db: SqliteAtomicDatabase) {
db.exec("PRAGMA foreign_keys = ON");
}

Prepares trusted parameterized SQLite SQL on the host-owned connection.

Parameters:

  • sql: Trusted SQL text with explicit tenant predicates.

Returns: A statement exposing synchronous all/run methods.

Preparation errors throw synchronously.

Example:

import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';
export function tenantProjection(db: SqliteAtomicDatabase, tenantId: string) {
return db.query("SELECT ? AS tenant_id").all(tenantId);
}

Synchronously execute the prepared query with positional values and return all rows.

Parameters:

  • values: Positional prepared-statement values.

Returns: All prepared-query rows in provider order.

Provider execution/binding errors throw synchronously.

Example:

import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';
export function projectedRows(db: SqliteAtomicDatabase, tenantId: string) {
const statement = db.query("SELECT ? AS tenant_id");
return statement.all(tenantId);
}

Synchronously execute the prepared DML with positional values and return its change count.

Parameters:

  • values: Positional prepared-statement values.

Returns: Native DML change-count metadata.

Provider execution/binding errors throw synchronously.

Example:

import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';
export function executeReviewed(db: SqliteAtomicDatabase, trustedTenantDml: string, bindings: unknown[]) {
return db.query(trustedTenantDml).run(...bindings).changes;
}

Number of rows affected by this prepared DML execution.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host SQLite operations required by LocalFirstSqliteAdapter; execution and transaction ownership belong to the host.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

interface SqliteDriver {
execute(sql: string, params?: any[]): Promise<any>;
select<T = any>(sql: string, params?: any[]): Promise<T[]>;
}
Name Type Required Description
execute Promise<any> Yes Executes SQLite SQL with positional bindings.
select Promise<T[]> Yes Selects SQLite rows using positional bindings.

Type declaration; no runtime value.

Executes SQLite SQL with positional bindings.

Parameters:

  • sql: SQL statement, including transaction control statements.
  • params: Positional values for question-mark placeholders; omitted for parameterless SQL.

Returns: Driver-specific execution result, which the adapter does not inspect.

Rejects on driver/database failure; callers determine rollback handling.

Example:

import type { SqliteDriver } from "@alneas/eaos-server/db";
export async function inspectConnectedSqlite(driver: SqliteDriver) {
// The host opens and closes the connection; this statement changes no records.
return await driver.execute("SELECT 1 AS ready", []);
}

Selects SQLite rows using positional bindings.

Parameters:

  • sql: SELECT statement.
  • params: Positional values, or omitted for parameterless queries.

Returns: Matching rows, or an empty array.

  • T: Row shape expected by the caller; the driver does not establish runtime validation.

Rejects on driver/database failure.

Example:

import type { SqliteDriver } from "@alneas/eaos-server/db";
export async function selectConnectedSqlite(driver: SqliteDriver) {
const rows = await driver.select<{ ready: number }>("SELECT 1 AS ready", []);
return rows[0]?.ready; // The type argument does not perform runtime validation.
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Persists lifecycle state with durable writer-token exclusion and revision-checked updates across hosts.

Imports: @alneas/eaos-server/sql-lifecycle.

declare class SqlLifecycleStore implements LifecycleStore {
constructor(driver: ControlSqlDriver, controlId: string);
initialize(): Promise<void>;
read(): Promise<LifecycleState>;
withLock<T>(fn: (writer: LifecycleWriter) => Promise<T>): Promise<T>;
withAtomicLock<T>(transaction: <R>(fn: (driver: ControlSqlDriver) => Promise<R>) => Promise<R>, fn: (writer: LifecycleWriter, driver: ControlSqlDriver) => Promise<T>): Promise<T>;
}
Name Type Required Description
driver ControlSqlDriver Yes Primary control-plane driver; connection lifecycle remains host-owned.
controlId string Yes Alphanumeric-first scope ID containing letters/digits/underscore/hyphen, length 1–128.

SqlLifecycleStore

Apply reviewed controlSchemaSql before initialize. Host connections must read the primary and report affectedRows. Locks do not expire; a crashed writer requires operator reconciliation. Normal callback failures attempt token release; database outcomes can be uncertain if commit or cleanup fails. No connection is opened or disposed by this store.

If controlId fails validation.

Bootstraps an empty ledger row after reviewed schema application, preserving an existing valid ledger.

Returns: No value; resolves after existing-state validation or insertion, including a recognized concurrent duplicate-insert race.

Rejects schema/driver failures or corrupt existing state.

Example:

import { SqlLifecycleStore, type ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function example(driver: ControlSqlDriver, controlId: string) {
const store = new SqlLifecycleStore(driver, controlId);
await store.initialize();
}

Reads and validates the primary control ledger and its revision.

Returns: Normalized lifecycle state decoded from the driver row.

Rejects missing initialization, corrupt JSON/state, revision mismatch, or SQL failures.

Example:

import { SqlLifecycleStore, type ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function example(driver: ControlSqlDriver, controlId: string) {
const store = new SqlLifecycleStore(driver, controlId);
return store.read();
}

Runs lifecycle read/write work under a durably committed exclusive writer token.

Parameters:

  • fn: Receives a writer; each write must advance revision exactly once and is independently committed by the driver.

Returns: The callback result after token release; writes made before callback failure are not rolled back by this method.

  • T: Callback result forwarded after lock cleanup.

No wait, expiry, or retry is supplied. Never nest locks. For atomic host records plus ledger updates use withAtomicLock instead.

Rejects locked/uninitialized state, invalid revision, lost lock, callback/driver failures, or cleanup failure; combined operation/cleanup errors use AggregateError.

Example:

import { SqlLifecycleStore, type ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function example(driver: ControlSqlDriver, controlId: string) {
const store = new SqlLifecycleStore(driver, controlId);
return store.withLock(async writer => writer.read());
}

Hold a durably committed writer token while atomically committing lifecycle state and host records. The host transaction must use one primary connection, commit before resolving, and roll back on rejection. Transaction-scoped driver writes are deliberately uncommitted until the callback finishes. Never use this for DDL, remote effects or nested locks; a crashed writer still requires reconciliation.

Parameters:

  • transaction: Host transaction wrapper receiving a driver callback; use one primary connection, commit before resolving, and roll back on rejection.
  • fn: Receives a lifecycle writer and the same transaction driver; await all work and advance ledger revision exactly once per write.

Returns: The callback result after the host transaction commits and the durable writer token is released.

  • T: Callback result forwarded after transaction completion and token cleanup.

The token is acquired outside the host transaction and is released separately. Transaction rollback and commit uncertainty depend on the host adapter; reconcile uncertain outcomes.

Rejects acquisition, revision/lock, callback, transaction, or cleanup failures; combined operation/cleanup failures use AggregateError.

Example:

import { SqlLifecycleStore, type ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function example(driver: ControlSqlDriver, controlId: string, transaction: Parameters<SqlLifecycleStore["withAtomicLock"]>[0]) {
const store = new SqlLifecycleStore(driver, controlId);
// Supply a real single-primary-connection host transaction wrapper.
return store.withAtomicLock(transaction, async writer => writer.read());
}
import { SqlLifecycleStore, type ControlSqlDriver } from "@alneas/eaos-server/sql-lifecycle";
export async function example(driver: ControlSqlDriver, controlId: string) {
const store = new SqlLifecycleStore(driver, controlId);
await store.initialize();
return store.read();
}

Manifest namespace, payload limits and optional canonical JSON document validation for SQL records.

Imports: @alneas/eaos-server/plugin-data.

interface SqlRecordStoreOptions {
namespace?: string;
storagePolicy?: PluginStoragePolicy;
documents?: readonly JsonDocumentContract[];
}
Name Type Required Description
namespace string No Optional trusted logical namespace encoded into physical IDs for a shared table. Logical namespace encoded into the trusted physical id for a shared foundation table.
storagePolicy PluginStoragePolicy No Declared payload/object/history limits; does not configure or authorize a provider. Payload/object/history policy declared by the plugin manifest.
documents readonly JsonDocumentContract[] No Canonical closed payload contracts copied and enforced by the wrapper.

Type declaration; no runtime value.

createSqlRecordStore for canonical host integration.

Optional trusted logical namespace encoded into physical IDs for a shared table.

Logical namespace encoded into the trusted physical id for a shared foundation table.

Declared payload/object/history limits; does not configure or authorize a provider.

Payload/object/history policy declared by the plugin manifest.

Canonical closed payload contracts copied and enforced by the wrapper.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning package @dataarthub/app-core.

Imports: @alneas/eaos-server/storage.

export interface StorageAdapter {
upload(key: string, data: Buffer | Blob | ReadableStream | string, options?: StorageUploadOptions): Promise<StorageObject>;
download(key: string): Promise<Buffer | null>;
getUrl(key: string, options?: StorageURLOptions): Promise<string>;
delete(key: string): Promise<boolean>;
exists(key: string): Promise<boolean>;
head(key: string): Promise<StorageObject | null>;
list(options?: StorageListOptions): Promise<StorageListResult>;
copy?(sourceKey: string, destinationKey: string): Promise<StorageObject>;
move?(sourceKey: string, destinationKey: string): Promise<StorageObject>;
}
Name Type Required Description
upload Promise<StorageObject> Yes See the upstream owning declaration.
download Promise<Buffer | null> Yes See the upstream owning declaration.
getUrl Promise<string> Yes See the upstream owning declaration.
delete Promise<boolean> Yes See the upstream owning declaration.
exists Promise<boolean> Yes See the upstream owning declaration.
head Promise<StorageObject | null> Yes See the upstream owning declaration.
list Promise<StorageListResult> Yes See the upstream owning declaration.
copy Promise<StorageObject> No See the upstream owning declaration.
move Promise<StorageObject> No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Server-held signing credentials; never expose these through browser configuration.

Imports: @alneas/eaos-server/storage, @alneas/eaos-server/storage/s3-compatible.

interface StorageCredentials {
accessKeyId: string;
secretAccessKey: string;
}
Name Type Required Description
accessKeyId string Yes Nonempty access key identifier for the selected provider.
secretAccessKey string Yes Nonempty secret used for request signing.

Type declaration; no runtime value.

createS3CompatibleStorage for host setup.

Nonempty access key identifier for the selected provider.

Nonempty secret used for request signing.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Operation names passed to the host authorization callback before scoped storage access.

Imports: @alneas/eaos-server/storage.

type StorageOperation = 'upload' | 'download' | 'delete' | 'exists' | 'head' | 'list' | 'getUrl' | 'copy' | 'move';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

createTenantStorage for a complete usage example.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Durable business-instance record with host compare-and-swap revision.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-coordinator.

interface StoredWorkflowInstance {
id: string;
revision: number;
value: WorkflowInstanceRecord;
}
Name Type Required Description
id string Yes Workflow instance ID, aligned with graph sessionId.
revision number Yes Host CAS revision, starting at one for coordinator-created records.
value WorkflowInstanceRecord Yes Domain workflow instance metadata; graph payload remains in its checkpointer.

Type declaration; no runtime value.

DurableWorkflowCoordinator.

Workflow instance ID, aligned with graph sessionId.

Host CAS revision, starting at one for coordinator-created records.

Domain workflow instance metadata; graph payload remains in its checkpointer.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Aggregates host/operator task evidence into dependency-aware plugin and component completion states.

Aggregate operator/host evidence only. A build receipt cannot complete DB/infra/deployment tasks.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare function summarizeDeployment(inventory: DeploymentInventory, inventorySha256: string, receipts?: DeploymentReceipt[], target?: DeploymentTarget): {
owner: string;
inventorySha256: string;
target: DeploymentTarget | undefined;
coverage: "declared" | "legacy-unclassified";
artifactResolved: boolean;
complete: boolean;
plugins: {
id: string;
artifactResolved: boolean;
complete: boolean;
components: {
complete: boolean;
id: string;
required?: boolean;
kind: (typeof deploymentComponentKinds)[number];
placement: "host" | "container" | "function" | "database" | "cloud" | "native" | "external";
runtime?: string;
assets?: string[];
assetPatterns?: string[];
entry?: string;
dataContracts?: Record<string, string>;
requirements?: {
tools?: Record<string, string>;
bindings?: string[];
adapters?: string[];
};
}[];
tasks: {
status: DeploymentTaskStatus;
result?: DeploymentResult;
id: string;
componentIds: string[];
action: (typeof deploymentActions)[number];
scope: "artifact" | "environment" | "tenant";
required: boolean;
dependsOn: string[];
executor: string;
argv?: string[];
instructions?: string;
}[];
}[];
ignoredReceipts: {
owner: string;
reason: string;
}[];
evidencePolicy: string;
};
Name Type Required Description
inventory DeploymentInventory Yes Validated artifact declaration; missing plugins remains legacy-unclassified.
inventorySha256 string Yes Trusted lowercase 64-character inventory digest.
receipts DeploymentReceipt[] No Reported receipts; defaults to none.
target DeploymentTarget No Optional current environment/backend/database/tenant context for scoped work.

{ owner: string; inventorySha256: string; target: DeploymentTarget \| undefined; coverage: "declared" \| "legacy-unclassified"; artifactResolved: boolean; complete: boolean; plugins: { id: string; artifactResolved: boolean; complete: boolean; components: { complete: boolean; id: string; required?: boolean; kind: (typeof deploymentComponentKinds)[number]; placement: "host" \| "container" \| "function" \| "database" \| "cloud" \| "native" \| "external"; runtime?: string; assets?: string[]; assetPatterns?: string[]; entry?: string; dataContracts?: Record<string, string>; requirements?: { tools?: Record<string, string>; bindings?: string[]; adapters?: string[]; }; }[]; tasks: { status: DeploymentTaskStatus; result?: DeploymentResult; id: string; componentIds: string[]; action: (typeof deploymentActions)[number]; scope: "artifact" \| "environment" \| "tenant"; required: boolean; dependsOn: string[]; executor: string; argv?: string[]; instructions?: string; }[]; }[]; ignoredReceipts: { owner: string; reason: string; }[]; evidencePolicy: string; }

A read-only summary with coverage, artifact resolution, task states and ignored owner/stale-inventory/placement receipts.

No task executes. Artifact work is reusable; environment/tenant evidence must match scope and database work needs explicit backend/database identities. Newer dependency evidence makes older success stale. Completion is host-reported evidence, never admission authority.

Error for invalid declarations/receipts/hash/target, undeclared tasks, scope mismatch or conflicting equal-time evidence.

import { summarizeDeployment, type DeploymentInventory, type DeploymentReceipt, type DeploymentTarget } from '@alneas/eaos-server/platform';
export function inspect(inventory: DeploymentInventory, digest: string, receipts: DeploymentReceipt[], target?: DeploymentTarget) { return summarizeDeployment(inventory, digest, receipts, target); }

Builds one placement-bound execution graph shared by plugin and destination evidence projections.

One execution graph powers both plugin and destination projections. Shared artifact work is never duplicated.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

declare function summarizePlacedDeployment(inventory: DeploymentInventory, inventorySha256: string, receipts: DeploymentReceipt[], placements: DeploymentPlacements, context?: DeploymentTarget, bindings?: Record<string, string>): {
plugins: ({
selected: boolean;
components: {
adopted: boolean;
destinationIds: string[];
complete: boolean;
id: string;
required?: boolean;
kind: typeof deploymentComponentKinds[number];
placement: "host" | "container" | "function" | "database" | "cloud" | "native" | "external";
runtime?: string;
assets?: string[];
assetPatterns?: string[];
entry?: string;
dataContracts?: Record<string, string>;
requirements?: {
tools?: Record<string, string>;
bindings?: string[];
adapters?: string[];
};
}[];
tasks: {
adopted: boolean;
executions: DeploymentExecution[];
status: DeploymentTaskStatus;
result?: DeploymentResult;
id: string;
componentIds: string[];
action: typeof deploymentActions[number];
scope: "artifact" | "environment" | "tenant";
required: boolean;
dependsOn: string[];
executor: string;
argv?: string[];
instructions?: string;
}[];
complete: boolean;
id: string;
artifactResolved: boolean;
} | {
selected: boolean;
placementSha256: string;
tasks: {
adopted: boolean;
required: boolean;
status: DeploymentTaskStatus;
executions: DeploymentExecution[];
result?: DeploymentResult;
id: string;
componentIds: string[];
action: typeof deploymentActions[number];
scope: "artifact" | "environment" | "tenant";
dependsOn: string[];
executor: string;
argv?: string[];
instructions?: string;
}[];
complete: boolean;
components: {
adopted: boolean;
destinationIds: string[];
complete: boolean;
id: string;
required?: boolean;
kind: typeof deploymentComponentKinds[number];
placement: "host" | "container" | "function" | "database" | "cloud" | "native" | "external";
runtime?: string;
assets?: string[];
assetPatterns?: string[];
entry?: string;
dataContracts?: Record<string, string>;
requirements?: {
tools?: Record<string, string>;
bindings?: string[];
adapters?: string[];
};
}[];
id: string;
artifactResolved: boolean;
})[];
complete: boolean;
ignoredReceipts: {
owner: string;
reason: string;
}[];
placementCoverage: "explicit";
destinations: {
executions: {
pluginId: string;
owner: string;
taskId: string;
destinationId?: string;
componentIds: string[];
required: boolean;
status: DeploymentTaskStatus;
target?: DeploymentTarget;
result?: DeploymentResult;
dependencies: Array<{
taskId: string;
destinationId?: string;
}>;
}[];
id: string;
placement: DeploymentComponent["placement"];
service?: "frontend" | "backend" | "worker";
reference?: string;
backendId?: string;
databaseId?: string;
tenantId?: string;
revision: string;
}[];
artifactExecutions: {
pluginId: string;
owner: string;
taskId: string;
destinationId?: string;
componentIds: string[];
required: boolean;
status: DeploymentTaskStatus;
target?: DeploymentTarget;
result?: DeploymentResult;
dependencies: Array<{
taskId: string;
destinationId?: string;
}>;
}[];
owner: string;
inventorySha256: string;
target: DeploymentTarget | undefined;
coverage: "declared" | "legacy-unclassified";
artifactResolved: boolean;
evidencePolicy: string;
};
Name Type Required Description
inventory DeploymentInventory Yes Trusted artifact inventory with declared plugin work.
inventorySha256 string Yes Trusted lowercase inventory digest.
receipts DeploymentReceipt[] Yes Reported task evidence, including placement-bound scoped results.
placements DeploymentPlacements Yes Explicit compatible destination selections.
context DeploymentTarget No Optional environment and tenant only; backend/database must come from destinations.
bindings Record<string, string> No Optional destination host-binding revisions; defaults to none.

{ plugins: ({ selected: boolean; components: { adopted: boolean; destinationIds: string[]; complete: boolean; id: string; required?: boolean; kind: typeof deploymentComponentKinds[number]; placement: "host" \| "container" \| "function" \| "database" \| "cloud" \| "native" \| "external"; runtime?: string; assets?: string[]; assetPatterns?: string[]; entry?: string; dataContracts?: Record<string, string>; requirements?: { tools?: Record<string, string>; bindings?: string[]; adapters?: string[]; }; }[]; tasks: { adopted: boolean; executions: DeploymentExecution[]; status: DeploymentTaskStatus; result?: DeploymentResult; id: string; componentIds: string[]; action: typeof deploymentActions[number]; scope: "artifact" \| "environment" \| "tenant"; required: boolean; dependsOn: string[]; executor: string; argv?: string[]; instructions?: string; }[]; complete: boolean; id: string; artifactResolved: boolean; } \| { selected: boolean; placementSha256: string; tasks: { adopted: boolean; required: boolean; status: DeploymentTaskStatus; executions: DeploymentExecution[]; result?: DeploymentResult; id: string; componentIds: string[]; action: typeof deploymentActions[number]; scope: "artifact" \| "environment" \| "tenant"; dependsOn: string[]; executor: string; argv?: string[]; instructions?: string; }[]; complete: boolean; components: { adopted: boolean; destinationIds: string[]; complete: boolean; id: string; required?: boolean; kind: typeof deploymentComponentKinds[number]; placement: "host" \| "container" \| "function" \| "database" \| "cloud" \| "native" \| "external"; runtime?: string; assets?: string[]; assetPatterns?: string[]; entry?: string; dataContracts?: Record<string, string>; requirements?: { tools?: Record<string, string>; bindings?: string[]; adapters?: string[]; }; }[]; id: string; artifactResolved: boolean; })[]; complete: boolean; ignoredReceipts: { owner: string; reason: string; }[]; placementCoverage: "explicit"; destinations: { executions: { pluginId: string; owner: string; taskId: string; destinationId?: string; componentIds: string[]; required: boolean; status: DeploymentTaskStatus; target?: DeploymentTarget; result?: DeploymentResult; dependencies: Array<{ taskId: string; destinationId?: string; }>; }[]; id: string; placement: DeploymentComponent["placement"]; service?: "frontend" \| "backend" \| "worker"; reference?: string; backendId?: string; databaseId?: string; tenantId?: string; revision: string; }[]; artifactExecutions: { pluginId: string; owner: string; taskId: string; destinationId?: string; componentIds: string[]; required: boolean; status: DeploymentTaskStatus; target?: DeploymentTarget; result?: DeploymentResult; dependencies: Array<{ taskId: string; destinationId?: string; }>; }[]; owner: string; inventorySha256: string; target: DeploymentTarget \| undefined; coverage: "declared" \| "legacy-unclassified"; artifactResolved: boolean; evidencePolicy: string; }

A deployment summary with selected/adopted components, task executions, destinations, artifact executions and explicit placement coverage.

Shared artifact work is not duplicated. Old binding hashes are ignored as stale; declined optional components do not satisfy adopted dependency work. No task executes, and reported completion does not grant runtime admission.

Error for invalid placements/context/receipts, undeclared tasks, mismatched task scope or conflicting equal-time evidence.

import { summarizePlacedDeployment, type DeploymentPlacements } from '@alneas/eaos-server/platform/deployment-placements';
import type { DeploymentInventory, DeploymentReceipt } from '@alneas/eaos-server/platform';
export function inspectPlaced(inventory: DeploymentInventory, digest: string, receipts: DeploymentReceipt[], placements: DeploymentPlacements) { return summarizePlacedDeployment(inventory, digest, receipts, placements, { environment: 'review' }); }

Permanent synchronization failure notification emitted after local rollback handling.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

interface SyncErrorEvent {
item: OutboxItem;
error: Error;
rolledBack: boolean;
}
Name Type Required Description
item OutboxItem Yes Outbox item whose permanent failure caused rollback handling.
error Error Yes Underlying synchronization failure.
rolledBack boolean Yes True when rollback handling reached the callback; it is not a remote rollback guarantee.

Type declaration; no runtime value.

LocalFirstSqliteAdapterOptions.onSyncError.

Outbox item whose permanent failure caused rollback handling.

Underlying synchronization failure.

True when rollback handling reached the callback; it is not a remote rollback guarantee.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Local outbox lifecycle status; successfully synchronized rows are removed by processOutbox.

Imports: @alneas/eaos-server/db, @alneas/eaos-server/db/local-first-sqlite-adapter.

type SyncStatus = 'pending' | 'syncing' | 'synced' | 'failed';
Name Type Required Description
— — — No call parameters.

Type declaration; no runtime value.

LocalFirstSqliteAdapter.processOutbox.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Current tenant routing assignment and its recorded revision.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/control-plane.

interface TenantBackendPlacement {
tenantId: string;
backend: PlatformBackendRecord;
routingRevision: number;
changedAt: string;
}
Name Type Required Description
tenantId string Yes Concrete tenant whose traffic is routed.
backend PlatformBackendRecord Yes Configured target and its nonsecret metadata.
routingRevision number Yes Nonnegative routing revision tracking cutover.
changedAt string Yes Routing-change timestamp.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Concrete tenant whose traffic is routed.

Configured target and its nonsecret metadata.

Nonnegative routing revision tracking cutover.

Routing-change timestamp.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Routes verified tenant operations to isolated existing database pools without implicit fallback.

One execution host, isolated pools per DB. No implicit shared fallback or unscoped business access.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/database-router.

declare class TenantDatabaseRouter implements DatabaseAdapter {
readonly type: DatabaseAdapter['type'];
constructor(resolveTarget: (verifiedTenantId: string) => BackendTarget, adapters: ReadonlyMap<string, DatabaseAdapter>);
withConnection<T>(_domain: string, _callback: (connection: unknown) => Promise<T>): Promise<T>;
withTenantConnection<T>(domain: string, callback: (connection: unknown) => Promise<T>, context: TenantSessionContext): Promise<T>;
ping(): Promise<boolean>;
getStats(): ConnectionStats;
close(): Promise<void>;
}
Name Type Required Description
resolveTarget (verifiedTenantId: string) => BackendTarget Yes Resolve the verified tenant to its trusted lifecycle backend; synchronous errors propagate.
adapters ReadonlyMap<string, DatabaseAdapter> Yes Nonempty map keyed by physical databaseId; adapter objects are shared and later owned by close().

TenantDatabaseRouter

All configured adapters must share one dialect. The host supplies membership-verified tenant context, trusted target resolution and real adapter pools. Unscoped business connections always reject; administration requires a separate control adapter. close owns and closes every distinct supplied adapter.

Error for no adapters or multiple adapter dialects.

The single SQL dialect shared by every configured adapter.

Rejects unscoped business database access to require a verified tenant context.

Parameters:

  • _domain: Unused business domain; no connection is opened.
  • _callback: Unused callback; it is never invoked.

Returns: A rejected Promise; this method never resolves a callback result.

  • T: Callback result type required by DatabaseAdapter; this method always rejects.

Always rejects with the verified-context requirement.

Example:

import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
export async function rejectUnscoped(router: TenantDatabaseRouter) { await router.withConnection('reports', async () => undefined); }

Delegates one verified tenant connection to its exact configured physical database adapter.

Parameters:

  • domain: Business domain forwarded to the selected adapter.
  • callback: Async work invoked by the adapter with its connection; must enforce resource permission.
  • context: Verified nonblank trimmed tenant session; a copied context is forwarded.

Returns: The selected adapter callback result.

  • T: Value resolved by work on the selected tenant connection.

Dedicated target tenant must match. Missing target adapters and dedicated failures never fall back to shared storage. Cancellation/transaction/connection cleanup follow the selected adapter contract.

Rejects invalid tenant, dedicated mismatch, missing adapter or adapter/callback failure; target resolver errors may throw synchronously.

Example:

import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
export function withVerifiedTenant<T>(router: TenantDatabaseRouter, tenantId: string, work: (connection: unknown) => Promise<T>) { return router.withTenantConnection('reports', work, { tenantId }); }

Checks every distinct configured database adapter concurrently.

Returns: True only when every adapter ping resolves true; false if any resolves false.

Rejects if any adapter ping rejects.

Example:

import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
export const health = (router: TenantDatabaseRouter) => router.ping();

Aggregates connection and pool counts from every distinct configured adapter.

Returns: ConnectionStats with the router dialect and summed counts.

Propagates adapter getStats errors.

Example:

import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
export const stats = (router: TenantDatabaseRouter) => router.getStats();

Closes all distinct configured adapters and collects asynchronous cleanup failures.

Returns: Resolves without a value after every adapter close settles successfully.

The router does not mark itself closed or make repeated calls idempotent; each adapter owns its lifecycle semantics. A synchronously throwing close implementation can interrupt initial dispatch.

Rejects with AggregateError for one or more rejected close Promises; synchronous adapter errors may also reject.

Example:

import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
export async function shutdown(router: TenantDatabaseRouter) { await router.close(); }
import { TenantDatabaseRouter } from '@alneas/eaos-server/platform/database-router';
import type { DatabaseAdapter } from '@alneas/eaos-core/db/adapter';
import type { BackendTarget } from '@alneas/eaos-server/lifecycle-engine';
export function connectRouter(resolve: (verifiedTenantId: string) => BackendTarget, adapters: ReadonlyMap<string, DatabaseAdapter>) { return new TenantDatabaseRouter(resolve, adapters); }

Host tenant lookup and current authenticated membership checks.

Imports: @alneas/eaos-server/platform.

interface TenantDirectory {
find(id: string): Promise<PlatformTenant | null>;
findByDomain(domain: string): Promise<PlatformTenant | null>;
isMember(tenantId: string, userId: string): Promise<boolean>;
}
Name Type Required Description
find Promise<PlatformTenant | null> Yes Find a tenant by exact ID; resolve null when unavailable.
findByDomain Promise<PlatformTenant | null> Yes Find a tenant by verified host/domain mapping; null when unmapped; never infer user membership. A domain mapping does not prove user membership.
isMember Promise<boolean> Yes Check the current authenticated user’s membership in the specified tenant.

Type declaration; no runtime value.

PluginLifecycle for canonical integration usage.

Find a tenant by exact ID; resolve null when unavailable.

Parameters:

  • id: Concrete tenant ID whose platform record is requested.

Returns: The matching platform tenant, or null when unavailable.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { TenantDirectory } from '@alneas/eaos-server/platform';
export async function findTenant(directory: TenantDirectory, verifiedTenantId: string) {
const tenant = await directory.find(verifiedTenantId);
return tenant?.active === true ? tenant : null;
}

Find a tenant by verified host/domain mapping; null when unmapped; never infer user membership.

A domain mapping does not prove user membership.

Parameters:

  • domain: Verified lookup domain; mapping alone never proves membership.

Returns: The mapped tenant, or null; membership must be checked separately.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { TenantDirectory } from '@alneas/eaos-server/platform';
export async function routeTenant(directory: TenantDirectory, trustedHostname: string) {
// Routing hints still require independent authenticated membership checks.
return directory.findByDomain(trustedHostname);
}

Check the current authenticated user’s membership in the specified tenant.

Parameters:

  • tenantId: Verified concrete tenant ID whose current state or permission is requested.
  • userId: Authenticated user ID checked against live host membership.

Returns: True only when current host membership permits this tenant.

Host adapter or callback failures reject the returned Promise; side effects may already be partially complete.

Example:

import type { TenantDirectory } from '@alneas/eaos-server/platform';
export async function admitted(directory: TenantDirectory, tenantId: string, userId: string) {
return directory.isMember(tenantId, userId);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Declares reviewed control-plane storage for tenant subscription/addon/quota state across supported SQL dialects.

Imports: @alneas/eaos-server, @alneas/eaos-server/entitlements.

declare const tenantEntitlementContract: DataContract;
Name Type Required Description
— — — No call parameters.

Declared constant value.

Hosts install this contract through reviewed lifecycle operations; importing the constant performs no migration.

createSqlTenantEntitlementLoader for the reader usage example.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Selects a tenant routing ID from an explicit trusted ID, configured host, or fallback.

Imports: @alneas/eaos-server, @alneas/eaos-server/tenant.

declare class TenantResolver {
constructor(options?: TenantResolverOptions);
resolveFromEmail(email: string | null | undefined): string | null;
resolveFromHost(host: string | null | undefined): string | null;
resolve(input: {
host?: string | null;
email?: string | null;
explicitTenantId?: string | null;
}): string;
getDefaultTenantId(): string;
}
Name Type Required Description
options TenantResolverOptions No Routing mappings and fallback; omitted options use empty mappings and “default”.

TenantResolver

This resolver performs no authentication or membership check. Host headers and explicit IDs must be validated by the host before being used for authorization. Email mappings are exposed only by resolveFromEmail.

Looks up the lower-case domain following the first @ in an email routing hint.

Parameters:

  • email: Email hint; missing, empty, or missing @ returns null. No address validation is performed.

Returns: The configured routing ID, or null when no domain matches.

Example:

import { TenantResolver } from "@alneas/eaos-server/tenant";
const resolver = new TenantResolver({ domainTenantMap: { "example.com": "workspace" } });
console.log(resolver.resolveFromEmail("[email protected]"));

Looks up a configured hostname after removing text following the first colon and lower-casing.

Parameters:

  • host: Host routing hint, optionally including a port; missing or empty values return null. IPv6 host parsing is not provided.

Returns: The exact configured host mapping, or null.

Example:

import { TenantResolver } from "@alneas/eaos-server/tenant";
const resolver = new TenantResolver({ hostTenantMap: { "workspace.example.com": "workspace" } });
console.log(resolver.resolveFromHost("workspace.example.com:443"));

Selects a truthy explicit ID, then a host mapping, then the configured fallback.

Parameters:

  • input: Routing hints: explicitTenantId takes precedence over host; email is intentionally ignored. The host must establish whether an explicit ID is trusted.

Returns: The selected routing ID, without validating tenant existence or membership.

TenantResolver for a complete usage example.

Example:

import { TenantResolver } from "@alneas/eaos-server/tenant";
const resolver = new TenantResolver();
console.log(resolver.resolve({ explicitTenantId: "workspace" }));

Optional host routing hint, including a possible port; checked only after a falsy/absent explicitTenantId against configured exact host mappings.

Optional compatibility routing hint intentionally ignored by resolve; an email domain is not an authenticated tenant claim.

Optional trusted tenant routing selection; any truthy value takes precedence without tenant-existence or membership validation.

Reads the fallback ID captured at construction.

Returns: The configured fallback, or “default” when none was supplied.

Example:

import { TenantResolver } from "@alneas/eaos-server/tenant";
console.log(new TenantResolver().getDefaultTenantId());
import { TenantResolver } from "@alneas/eaos-server/tenant";
const resolver = new TenantResolver({ hostTenantMap: { "workspace.example.com": "workspace" } });
const tenantId = resolver.resolve({ host: "workspace.example.com:443" });
console.log(tenantId); // "workspace"

Routing hints used by TenantResolver; they do not authenticate a tenant.

Imports: @alneas/eaos-server, @alneas/eaos-server/tenant.

interface TenantResolverOptions {
defaultTenantId?: string;
domainTenantMap?: Record<string, string>;
hostTenantMap?: Record<string, string>;
}
Name Type Required Description
defaultTenantId string No Fallback when no explicit ID or host mapping matches.
domainTenantMap Record<string, string> No Routing-only email domain mappings. Never use email-derived results as an authenticated tenant claim.
hostTenantMap Record<string, string> No Trusted, exact hostname mappings (e.g. { “demo.example.com”: “tenant-demo” }).

Type declaration; no runtime value.

TenantResolver for a complete usage example.

Fallback when no explicit ID or host mapping matches.

Default: "default".

Routing-only email domain mappings. Never use email-derived results as an authenticated tenant claim.

Trusted, exact hostname mappings (e.g. { “demo.example.com”: “tenant-demo” }).

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Compatibility re-export; its implementation and documentation are owned by the owning API reference.

Imports: @alneas/eaos-server/db.

interface TenantSessionContext {
tenantId: string;
userId?: string;
}
Name Type Required Description
tenantId string Yes See the upstream owning declaration.
userId string No See the upstream owning declaration.

Type declaration; no runtime value.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted tenant/plugin scope and per-operation authorization for createTenantStorage.

Imports: @alneas/eaos-server/storage.

interface TenantStorageOptions {
tenantId: string;
pluginId: string;
authorize: (request: {
tenantId: string;
pluginId: string;
operation: StorageOperation;
keys: readonly string[];
}) => boolean | Promise<boolean>;
maxUrlLifetimeSeconds?: number;
}
Name Type Required Description
tenantId string Yes Trusted tenant ID: 1–128 ASCII letters, digits, underscores, or hyphens, starting alphanumeric. It must come from verified server identity/configuration, never request body keys.
pluginId string Yes Trusted plugin ID: 1–128 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit.
authorize (request: { tenantId: string; pluginId: string; operation: StorageOperation; keys: readonly string[]; }) => boolean | Promise<boolean> Yes Invoked before each operation with trusted scope, operation, and frozen relative keys (list receives its prefix); only exactly true allows access. Errors propagate.
maxUrlLifetimeSeconds number No Signed URLs remain usable until expiry; default ceiling 300 seconds.

Type declaration; no runtime value.

Trusted tenant ID: 1–128 ASCII letters, digits, underscores, or hyphens, starting alphanumeric. It must come from verified server identity/configuration, never request body keys.

Trusted plugin ID: 1–128 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit.

Invoked before each operation with trusted scope, operation, and frozen relative keys (list receives its prefix); only exactly true allows access. Errors propagate.

Trusted tenant scope captured at adapter construction, independent of caller object keys.

Trusted plugin scope captured at adapter construction.

Storage operation about to be delegated to the provider.

Frozen relative-key array; copy/move supplies source then destination, and list supplies its requested prefix.

Signed URLs remain usable until expiry; default ceiling 300 seconds.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Validate bounded nonblank string input while preserving the original whitespace.

Imports: @alneas/eaos-server/plugin-data.

declare function textInput(value: unknown, name: string, max?: number): string;
Name Type Required Description
value unknown Yes Untrusted value to validate.
name string Yes Trusted field label used in the failure message.
max number No Maximum JavaScript string length; defaults to 256.

string

The original string without trimming.

Throws PluginError 400 if input is not a string, trims to empty or exceeds max.

import { textInput } from '@alneas/eaos-server/plugin-data'
const title = textInput('Example', 'title', 80)

Derive a stable atomic reservation key for a named composite business identity.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/scoped-records.

declare function uniqueRecordKey(name: string, values: readonly unknown[]): string;
Name Type Required Description
name string Yes Trusted lowercase uniqueness label of at most 61 characters.
values readonly unknown[] Yes Nonempty tuple of nonblank string values in canonical field order.

string

unique/ followed by a canonical content hash.

Derivation alone reserves nothing; concurrent uniqueness requires CAS reservations in the enclosing atomic transaction.

Invalid declarations throw Error; nonstring/blank identity values throw PluginError 409.

import { uniqueRecordKey } from '@alneas/eaos-server/plugin-data'
const key = uniqueRecordKey('external-id', ['example'])

Validates that resource-policy fields retain or tighten the current framework baseline.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/executor.

declare function validateAgentRuntimePolicy(policy: AgentRuntimeResourcePolicy): AgentRuntimeResourcePolicy;
Name Type Required Description
policy AgentRuntimeResourcePolicy Yes Runtime resource policy with AI placement, read-only root, private-only network, and bounded resources.

AgentRuntimeResourcePolicy

A structured clone of the accepted policy.

Validation does not itself apply operating-system isolation, concurrency, or network controls.

For weaker/invalid fields; malformed nested fields can also throw property-access errors.

import { defaultRuntimePlacementPolicy } from "@alneas/eaos-core";
import { validateAgentRuntimePolicy } from "@alneas/eaos-server/agentic/executor";
const policy = validateAgentRuntimePolicy(defaultRuntimePlacementPolicy().ai.agentRuntime);
console.log(policy.placement); // "ai"

Validates nonsecret destination definitions and explicit component-to-destination selections.

Validate only non-secret declarations here; no service discovery, provisioning or code execution.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment-placements.

declare function validateDeploymentPlacements(value: unknown): asserts value is DeploymentPlacements;
Name Type Required Description
value unknown Yes Untrusted destinations/plugins declaration.

asserts value is DeploymentPlacements

Completes without a value and narrows the input to DeploymentPlacements.

A database destination uses exact backend/database IDs; other destinations use exactly one symbolic service or host reference. Dedicated tenant restrictions apply only to database destinations. No discovery, provisioning or code execution occurs.

Error for duplicate/unknown IDs, unknown fields, invalid placement kind, malformed host references or conflicting destination configuration.

import { validateDeploymentPlacements } from '@alneas/eaos-server/platform/deployment-placements';
const placements: unknown = { destinations: [], plugins: [] };
validateDeploymentPlacements(placements);

Validates declared plugin component references and task dependencies before artifact inspection.

Validate references and the dependency DAG before artifact registration or status inspection.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare function validateDeploymentPlugins(inventory: DeploymentInventory): DeploymentPlugin[] | undefined;
Name Type Required Description
inventory DeploymentInventory Yes Deployment inventory with checksummed asset metadata and optional per-plugin work declarations.

DeploymentPlugin[] \| undefined

The original plugin array, or undefined for legacy inventories without plugin declarations.

Requires explicit lifecycle-bundle coverage, known assets/components, acyclic dependencies and work for adopted components. This validates declarations without executing tasks or proving artifact file checksums.

Error for invalid/duplicate declarations, unsupported component/action/scope, unknown references, cycles or missing required work.

import { validateDeploymentPlugins, type DeploymentInventory } from '@alneas/eaos-server/platform';
export function inspectDeclaration(inventory: DeploymentInventory) { return validateDeploymentPlugins(inventory); }

Validates version-1 reported task evidence and strictly increasing timestamps per task/target/placement.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare function validateDeploymentReceipt(value: unknown): asserts value is DeploymentReceipt;
Name Type Required Description
value unknown Yes Untrusted receipt with owner, pinned inventory SHA-256 and task result records.

asserts value is DeploymentReceipt

Completes without a value and narrows the input to DeploymentReceipt.

Each result needs a UTC millisecond ISO timestamp, actor and nonempty distinct evidence references. destinationId and placementSha256 must occur together. This validates shape/order only; it does not independently verify evidence or grant runtime admission.

Error for malformed/extra fields, invalid hashes/timestamps, missing evidence or nonincreasing repeated-result timestamps.

import { validateDeploymentReceipt } from '@alneas/eaos-server/platform/deployment';
const receipt: unknown = { apiVersion: 1, owner: 'reports', inventorySha256: 'a'.repeat(64), results: [] };
validateDeploymentReceipt(receipt);

Validates the exact nonsecret environment/backend/database/tenant target shape.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/deployment.

declare function validateDeploymentTarget(value: unknown): asserts value is DeploymentTarget;
Name Type Required Description
value unknown Yes Untrusted target object with a nonblank environment and optional nonblank identity references.

asserts value is DeploymentTarget

Completes without a value and narrows the input to DeploymentTarget.

Does not resolve backend existence, tenant membership or deployment authority.

Error for missing/blank identity fields or unknown target properties.

import { validateDeploymentTarget } from '@alneas/eaos-server/platform/deployment';
const target: unknown = { environment: 'review' };
validateDeploymentTarget(target);

Checks trusted extension shapes, IDs, route factories, and conflicting tenant/user-context contributions.

Imports: @alneas/eaos-server/extensions.

declare function validateExtensions(values: unknown[]): PlatformExtension[];
Name Type Required Description
values unknown[] Yes Deployment module values to validate; request input must not supply implementations.

PlatformExtension[]

A new array containing the original validated objects; no deep clone or sandboxing occurs.

Independent plugins can share tenants. This validates composition constraints, not manifest internals or implementation safety.

For invalid version/ID/explicit tenant scopes, duplicate extension/plugin IDs, overlapping userContext tenant scopes, invalid routes, or missing/unauthorized route factories.

import { validateExtensions } from "@alneas/eaos-server/extensions";
const extensions = validateExtensions([{ apiVersion: 1, id: "example", tenantIds: ["example"] }]);
console.log(extensions.length); // 1

Validates explicit checksummed package registrations and concrete tenant/plugin scope metadata.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/artifacts.

declare function validatePlatformPackages(value: unknown): PlatformPackage[];
Name Type Required Description
value unknown Yes Untrusted package registration array, or undefined for no packages.

PlatformPackage[]

The original accepted array, or a new empty array for undefined.

Checks project-relative nontraversing inventory/module paths and nonsecret settings shape. It does not load files, verify checksums, resolve membership or activate plugins.

Error for nonarray input, unknown fields, duplicate package IDs, invalid paths, empty/duplicate plugin IDs or invalid tenant scopes.

import { validatePlatformPackages } from '@alneas/eaos-server/platform/artifacts';
const packages = validatePlatformPackages([{ id: 'reports', inventory: '.eaos/packages/reports/deployment.json', module: '.eaos/packages/reports/index.js', tenantIds: ['sample'], pluginIds: ['reports'] }]);

Validates explicit database placements and verifies that registered package tenants resolve to permitted targets.

Imports: @alneas/eaos-server/platform, @alneas/eaos-server/platform/runtime.

declare function validatePlatformRuntime(value: unknown, packages?: PlatformPackage[]): PlatformRuntimeConfig | undefined;
Name Type Required Description
value unknown Yes Untrusted runtime declaration, or undefined when no runtime is configured.
packages PlatformPackage[] No Validated package registrations whose tenant scopes must resolve; defaults to none.

PlatformRuntimeConfig \| undefined

The original runtime object when accepted, or undefined for absent configuration.

Dedicated targets require unique physical database IDs and explicit placements unless they are the default backend. This checks nonsecret declarations only; host pools, provisioning and membership remain external.

Error for malformed/duplicate targets, shared/dedicated scope mismatch, missing explicit placements or unresolved package tenants.

import { validatePlatformRuntime } from '@alneas/eaos-server/platform/runtime';
const runtime = validatePlatformRuntime({ backend: { id: 'main', databaseId: 'db-main', dialect: 'sqlite', mode: 'shared' } });

Verify a bounded audit chain, its head and linked command receipts within the current tenant transaction.

Imports: @alneas/eaos-server/plugin-data, @alneas/eaos-server/plugin-data/audit.

declare function verifyAtomicAudit(tx: AtomicSession, p: PluginPrincipal): Promise<{
tenantId: string;
status: "verified";
count: number;
headHash: string | null;
coverage: "atomic-journal-v1";
externalTrustAnchor: false;
}>;
Name Type Required Description
tx AtomicSession Yes Live atomic session containing the journal and receipts.
p PluginPrincipal Yes Verified tenant/user principal with host-admitted audit access.

Promise<{ tenantId: string; status: "verified"; count: number; headHash: string \| null; coverage: "atomic-journal-v1"; externalTrustAnchor: false; }>

Tenant identity, verified event count/head hash and explicit externalTrustAnchor=false.

Integrity verification cannot prove an external actor has not rewritten the entire journal. Larger histories need the host’s reviewed archival verifier.

Rejects more than 10000 events, discontinuous sequence/hash links, receipt mismatches, corrupt head/tail or store failures.

import { verifyAtomicAudit } from '@alneas/eaos-server/plugin-data'
export function verifyJournal(tx: Parameters<typeof verifyAtomicAudit>[0], p: Parameters<typeof verifyAtomicAudit>[1]) { return verifyAtomicAudit(tx, p) }

Host runner, request construction, and output validation for createWorkflowAgentNode.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/agent-node.

interface WorkflowAgentNodeOptions<TOutput = unknown> {
runner: WorkflowAgentRunner;
createRequest: (state: AgentGraphState) => WorkflowAgentRequest | Promise<WorkflowAgentRequest>;
validateOutput?: (output: TOutput, proposal: WorkflowAgentProposal<TOutput>, state: AgentGraphState) => TOutput | Promise<TOutput>;
contextKey?: string;
}
Name Type Required Description
runner WorkflowAgentRunner Yes Host-owned runner that returns proposals; this node performs no proposed action.
createRequest (state: AgentGraphState) => WorkflowAgentRequest | Promise<WorkflowAgentRequest> Yes Called per node invocation with a structured clone of state; must resolve a request matching tenantId, userId, and sessionId/workflowId.
validateOutput (output: TOutput, proposal: WorkflowAgentProposal<TOutput>, state: AgentGraphState) => TOutput | Promise<TOutput> No Called after a completed proposal with output, full proposal, and original current state; resolves the domain-validated output stored beside the proposal. Errors reject node execution.
contextKey string No Context property receiving cloned proposal and validated output; existing data at this key is overwritten.

Type declaration; no runtime value.

  • TOutput: Domain output expected from the proposal; defaults to unknown and runtime validation remains plugin-owned.

Host-owned runner that returns proposals; this node performs no proposed action.

Called per node invocation with a structured clone of state; must resolve a request matching tenantId, userId, and sessionId/workflowId.

Called after a completed proposal with output, full proposal, and original current state; resolves the domain-validated output stored beside the proposal. Errors reject node execution.

Context property receiving cloned proposal and validated output; existing data at this key is overwritten.

Default: "agentProposal".

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted node catalog, checkpoint persistence, and live approval authority for compileWorkflowDefinition.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-compiler.

interface WorkflowCompilerOptions {
catalog: WorkflowNodeCatalog;
checkpointer?: BaseCheckpointSaver;
authorizeResume?: AgentGraphEngineOptions['authorizeResume'];
}
Name Type Required Description
catalog WorkflowNodeCatalog Yes Required host/plugin node resolver catalog.
checkpointer BaseCheckpointSaver No Optional LangGraph saver; absent uses the graph engine default, which is not durable host storage.
authorizeResume AgentGraphEngineOptions['authorizeResume'] No Optional live host approval authorization forwarded to the graph engine.

Type declaration; no runtime value.

Required host/plugin node resolver catalog.

Optional LangGraph saver; absent uses the graph engine default, which is not durable host storage.

Optional live host approval authorization forwarded to the graph engine.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Versioned workflow definition with lifecycle, integrity hash, revision, and actor/timestamp metadata.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-registry.

interface WorkflowDefinitionRecord {
workflowId: string;
version: string;
status: WorkflowDefinitionLifecycle;
definition: WorkflowDefinition;
definitionHash: string;
revision: number;
createdAt: string;
updatedAt: string;
createdBy?: string;
updatedBy?: string;
approvedAt?: string;
approvedBy?: string;
publishedAt?: string;
publishedBy?: string;
retiredAt?: string;
retiredBy?: string;
}
Name Type Required Description
workflowId string Yes Workflow identifier copied from the validated definition.
version string Yes Immutable version key within a workflow after draft.
status WorkflowDefinitionLifecycle Yes Current draft/validated/approved/published/retired lifecycle phase.
definition WorkflowDefinition Yes Validated serializable definition; returned records are cloned by this registry.
definitionHash string Yes Canonical SHA-256 definition hash calculated on saveDraft.
revision number Yes Record revision starting at one and incrementing on each saved transition.
createdAt string Yes Creation timestamp from the registry clock.
updatedAt string Yes Latest transition timestamp from the registry clock.
createdBy string No Optional first author label.
updatedBy string No Optional latest actor label.
approvedAt string No Optional approval timestamp.
approvedBy string No Optional approver label.
publishedAt string No Optional publication timestamp.
publishedBy string No Optional publisher label.
retiredAt string No Optional retirement timestamp.
retiredBy string No Optional retiring actor label.

Type declaration; no runtime value.

InMemoryWorkflowDefinitionRegistry.

Workflow identifier copied from the validated definition.

Immutable version key within a workflow after draft.

Current draft/validated/approved/published/retired lifecycle phase.

Validated serializable definition; returned records are cloned by this registry.

Canonical SHA-256 definition hash calculated on saveDraft.

Record revision starting at one and incrementing on each saved transition.

Creation timestamp from the registry clock.

Latest transition timestamp from the registry clock.

Optional first author label.

Optional latest actor label.

Optional approval timestamp.

Optional approver label.

Optional publication timestamp.

Optional publisher label.

Optional retirement timestamp.

Optional retiring actor label.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Workflow authoring lifecycle contract; durable hosts must supply authorization and consistent persistence.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-registry.

interface WorkflowDefinitionRegistry {
saveDraft(definition: unknown, actorId?: string): WorkflowDefinitionRecord;
validate(workflowId: string, version: string, actorId?: string): WorkflowDefinitionRecord;
approve(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
publish(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
retire(workflowId: string, version: string, actorId: string): WorkflowDefinitionRecord;
get(workflowId: string, version: string): WorkflowDefinitionRecord | undefined;
getPublished(workflowId: string): WorkflowDefinitionRecord | undefined;
list(workflowId?: string): readonly WorkflowDefinitionRecord[];
}
Name Type Required Description
saveDraft WorkflowDefinitionRecord Yes Validates and inserts or replaces a draft version, incrementing its revision.
validate WorkflowDefinitionRecord Yes Transitions an existing draft to validated after core and optional host checks.
approve WorkflowDefinitionRecord Yes Transitions a validated version to approved and records approver metadata.
publish WorkflowDefinitionRecord Yes Publishes an approved version and retires any currently published version of the same workflow.
retire WorkflowDefinitionRecord Yes Transitions a published version to retired and records retirement metadata.
get WorkflowDefinitionRecord | undefined Yes Reads one workflow version without mutating lifecycle state.
getPublished WorkflowDefinitionRecord | undefined Yes Finds the currently published version of one workflow.
list readonly WorkflowDefinitionRecord[] Yes Lists records in insertion order with optional workflow filtering.

Type declaration; no runtime value.

InMemoryWorkflowDefinitionRegistry for transition semantics.

Validates and inserts or replaces a draft version, incrementing its revision.

Parameters:

  • definition: Unknown workflow definition validated by core validation.
  • actorId: Optional author label recorded as creator/updater; not authenticated here.

Returns: A cloned draft record with canonical definition hash.

Invalid definition, non-draft existing version, clock/hash/clone failure.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function saveReviewedDraft(
registry: WorkflowDefinitionRegistry,
definition: Parameters<WorkflowDefinitionRegistry["saveDraft"]>[0], authenticatedActorId: string,
) {
// Supply a real host workflow definition with its registered node types.
return registry.saveDraft(definition, authenticatedActorId);
}

Transitions an existing draft to validated after core and optional host checks.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.
  • actorId: Optional updater label.

Returns: A cloned validated record with incremented revision.

Missing version, nondraft status, validation/callback/clock failure.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function validateStoredDraft(
registry: WorkflowDefinitionRegistry, workflowId: string, version: string, actorId: string,
) {
const record = registry.validate(workflowId, version, actorId);
return record.status; // Host/Core validation must succeed before transition.
}

Transitions a validated version to approved and records approver metadata.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.
  • actorId: Nonblank verified host approver label; no role check occurs here.

Returns: A cloned approved record.

Blank actor, missing version, nonvalidated status, or clock failure.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function approveValidatedWorkflow(
registry: WorkflowDefinitionRegistry, workflowId: string, version: string, authorizedApproverId: string,
) {
// The host checks reviewer authority before requesting this lifecycle change.
return registry.approve(workflowId, version, authorizedApproverId);
}

Publishes an approved version and retires any currently published version of the same workflow.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Approved version to publish.
  • actorId: Nonblank verified host publisher label.

Returns: A cloned published record; previous published records become retired.

Blank actor, missing version, nonapproved status, or clock/clone failure; earlier retirement updates can already have occurred.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function publishApprovedWorkflow(
registry: WorkflowDefinitionRegistry, workflowId: string, version: string, authorizedPublisherId: string,
) {
return registry.publish(workflowId, version, authorizedPublisherId);
// Host execution can select the resulting published record explicitly.
}

Transitions a published version to retired and records retirement metadata.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Currently published version.
  • actorId: Nonblank verified host operator label.

Returns: A cloned retired record.

Blank actor, missing version, nonpublished status, or clock failure.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function retirePublishedWorkflow(
registry: WorkflowDefinitionRegistry, workflowId: string, version: string, authorizedActorId: string,
) {
return registry.retire(workflowId, version, authorizedActorId);
}

Reads one workflow version without mutating lifecycle state.

Parameters:

  • workflowId: Exact workflow identifier.
  • version: Exact stored version.

Returns: A cloned record, or undefined when absent.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function inspectWorkflowVersion(
registry: WorkflowDefinitionRegistry, workflowId: string, version: string,
) {
return registry.get(workflowId, version); // Undefined when this version is absent.
}

Finds the currently published version of one workflow.

Parameters:

  • workflowId: Exact workflow identifier.

Returns: A cloned published record, or undefined when none exists.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function inspectPublishedWorkflow(registry: WorkflowDefinitionRegistry, workflowId: string) {
return registry.getPublished(workflowId); // Undefined when no version is published.
}

Lists records in insertion order with optional workflow filtering.

Parameters:

  • workflowId: Exact workflow identifier to filter, or omit for all workflows.

Returns: Independent cloned records, or an empty array.

Example:

import type { WorkflowDefinitionRegistry } from "@alneas/eaos-server";
export function listWorkflowVersions(registry: WorkflowDefinitionRegistry, workflowId: string) {
return registry.list(workflowId).map(record => ({ version: record.version, status: record.status }));
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Host-owned durable store for the companion workflow instance record.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-coordinator.

interface WorkflowInstanceStore {
read(tenantId: string, instanceId: string): Promise<StoredWorkflowInstance | null>;
create(tenantId: string, record: StoredWorkflowInstance): Promise<void>;
replace(tenantId: string, record: StoredWorkflowInstance, expectedRevision: number): Promise<boolean>;
}
Name Type Required Description
read Promise<StoredWorkflowInstance | null> Yes Reads an authorized tenant’s companion instance.
create Promise<void> Yes Atomically inserts a new companion instance, rejecting duplicates.
replace Promise<boolean> Yes Atomically replaces a companion record only if its revision matches.

Type declaration; no runtime value.

DurableWorkflowCoordinator for usage.

Reads an authorized tenant’s companion instance.

Parameters:

  • tenantId: Verified owning tenant.
  • instanceId: Workflow session/instance ID.

Returns: Stored record, or null if absent.

Persistence failures propagate.

Example:

import type { WorkflowInstanceStore } from "@alneas/eaos-server";
export async function readTenantInstance(
store: WorkflowInstanceStore, verifiedTenantId: string, instanceId: string,
) {
const record = await store.read(verifiedTenantId, instanceId);
return record?.value.status; // A missing instance yields undefined here.
}

Atomically inserts a new companion instance, rejecting duplicates.

Parameters:

  • tenantId: Verified owning tenant.
  • record: Initial revision-one queued record.

Returns: No value; resolves when durable creation completes.

Duplicate/conflicting identity or persistence failure must reject.

Example:

import type { WorkflowInstanceStore } from "@alneas/eaos-server";
export async function createQueuedInstance(
store: WorkflowInstanceStore, verifiedTenantId: string,
initialRecord: Parameters<WorkflowInstanceStore["create"]>[1],
) {
// Supply an aligned, admitted revision-one queued record.
await store.create(verifiedTenantId, initialRecord);
}

Atomically replaces a companion record only if its revision matches.

Parameters:

  • tenantId: Verified owning tenant.
  • record: Replacement with incremented revision.
  • expectedRevision: Previously read revision required for CAS.

Returns: True on replacement, false on stale revision.

Persistence failures propagate.

Example:

import type { WorkflowInstanceStore } from "@alneas/eaos-server";
export async function replaceTenantInstance(
store: WorkflowInstanceStore, verifiedTenantId: string,
nextRecord: Parameters<WorkflowInstanceStore["replace"]>[1], previouslyReadRevision: number,
) {
// nextRecord has the incremented revision; false means another writer won.
return await store.replace(verifiedTenantId, nextRecord, previouslyReadRevision);
}

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Registers trusted host/plugin node resolvers and cloned descriptors for workflow compilation and editors.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-catalog.

declare class WorkflowNodeCatalog {
register(registration: WorkflowNodeRegistration): () => void;
get(type: string): WorkflowNodeRegistration | undefined;
require(type: string): WorkflowNodeRegistration;
list(): readonly WorkflowNodeDescriptor[];
}
Name Type Required Description
— — — No call parameters.

WorkflowNodeCatalog

Storage is process-local; no persistence or authorization is supplied.

Registers a unique node type and returns a safe unregister callback.

Parameters:

  • registration: Descriptor with nonblank label and type matching lowercase letters/digits/dot/underscore/hyphen up to 128 characters, plus a handler resolver.

Returns: A no-argument callback returning no value; it removes only this registration and does not remove a later replacement.

The descriptor is cloned and its label trimmed; resolver function references are retained.

Invalid type/label, duplicate type, missing resolver, or descriptor clone failure.

Example:

import { WorkflowNodeCatalog } from "@alneas/eaos-server/agentic/workflow-catalog";
const catalog = new WorkflowNodeCatalog();
const dispose = catalog.register({ descriptor: { type: "example.task", label: "Example", kind: "task" }, resolve: () => async () => ({}) });
dispose();

Reads a registered resolver by exact node type.

Parameters:

  • type: Case-sensitive catalog type identifier.

Returns: The retained registration, or undefined; mutation is not isolated by cloning.

Example:

import { WorkflowNodeCatalog } from "@alneas/eaos-server/agentic/workflow-catalog";
console.log(new WorkflowNodeCatalog().get("example.task")); // undefined

Reads a registered resolver or fails if the type is unavailable.

Parameters:

  • type: Exact catalog node type required by a workflow definition.

Returns: The retained registration.

If no registration exists for type.

Example:

import { WorkflowNodeCatalog, type WorkflowNodeRegistration } from "@alneas/eaos-server/agentic/workflow-catalog";
export function registered(registration: WorkflowNodeRegistration) {
const catalog = new WorkflowNodeCatalog();
catalog.register(registration);
return catalog.require(registration.descriptor.type);
}

Lists cloned descriptors in registration insertion order.

Returns: A new descriptor array, empty for an empty catalog; caller changes do not affect stored descriptors.

If descriptors were externally mutated to contain uncloneable values.

Example:

import { WorkflowNodeCatalog } from "@alneas/eaos-server/agentic/workflow-catalog";
console.log(new WorkflowNodeCatalog().list()); // []
import { WorkflowNodeCatalog } from "@alneas/eaos-server/agentic/workflow-catalog";
const catalog = new WorkflowNodeCatalog();
const unregister = catalog.register({ descriptor: { type: "example.task", label: "Example", kind: "task" }, resolve: () => async () => ({}) });
console.log(catalog.list().length); // 1
unregister();

Serializable node metadata exposed to workflow editors by WorkflowNodeCatalog.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-catalog.

interface WorkflowNodeDescriptor {
type: string;
label: string;
description?: string;
pluginId?: string;
kind: WorkflowDefinitionNodeKind;
toolScope?: WorkflowToolScopeDefinition;
canRequestApproval?: boolean;
}
Name Type Required Description
type string Yes Unique lowercase catalog type identifier, at most 128 characters.
label string Yes Editor label, trimmed and required during registration.
description string No Optional human-readable editor description.
pluginId string No Optional owning plugin ID included in visual metadata.
kind WorkflowDefinitionNodeKind Yes Workflow node category used unless a definition overrides it.
toolScope WorkflowToolScopeDefinition No Optional declared tool-scope metadata; execution enforcement belongs to the host handler.
canRequestApproval boolean No Optional visual capability flag; compilation defaults to true when no node approval is declared.

Type declaration; no runtime value.

Unique lowercase catalog type identifier, at most 128 characters.

Editor label, trimmed and required during registration.

Optional human-readable editor description.

Optional owning plugin ID included in visual metadata.

Workflow node category used unless a definition overrides it.

Optional declared tool-scope metadata; execution enforcement belongs to the host handler.

Optional visual capability flag; compilation defaults to true when no node approval is declared.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Trusted host/plugin handler and optional subgraph resolution for one catalog node type.

Imports: @alneas/eaos-server, @alneas/eaos-server/agentic, @alneas/eaos-server/agentic/workflow-catalog.

interface WorkflowNodeRegistration {
descriptor: WorkflowNodeDescriptor;
resolve(input: WorkflowNodeResolverInput): GraphNodeHandler | Promise<GraphNodeHandler>;
resolveSubgraph?(input: WorkflowNodeResolverInput): GraphSubgraph | Promise<GraphSubgraph>;
}
Name Type Required Description
descriptor WorkflowNodeDescriptor Yes Serializable editor metadata cloned at registration.
resolve GraphNodeHandler | Promise<GraphNodeHandler> Yes Resolves a plugin/host handler while preserving the Effect/Receipt boundary.
resolveSubgraph GraphSubgraph | Promise<GraphSubgraph> No Resolves a compiled LangGraph subgraph for a definition declaring subflow.

Type declaration; no runtime value.

WorkflowNodeCatalog.register.

Serializable editor metadata cloned at registration.

Resolves a plugin/host handler while preserving the Effect/Receipt boundary.

Parameters:

  • input: Validated definition and node being compiled.

Returns: A graph handler, synchronously or asynchronously; the compiler rejects nonfunctions.

Resolver failures reject compilation.

Example:

* ```typescript
import type { WorkflowNodeRegistration } from "@alneas/eaos-server";
export async function resolveHostNode(
registration: WorkflowNodeRegistration,
validatedInput: Parameters<WorkflowNodeRegistration["resolve"]>[0],
) {
const handler = await registration.resolve(validatedInput);
return handler; // Resolving a handler does not execute its effects.
}
#### `resolveSubgraph`
Resolves a compiled LangGraph subgraph for a definition declaring subflow.
Parameters:
- `input`: Validated definition and subflow node.
Returns: A graph exposing invoke, synchronously or asynchronously.
### Errors and rejections
Resolver failures reject compilation.
Example:
```typescript
* ```typescript
import type { WorkflowNodeRegistration } from "@alneas/eaos-server";
export async function resolveHostSubflow(
registration: WorkflowNodeRegistration,
validatedInput: Parameters<NonNullable<WorkflowNodeRegistration["resolveSubgraph"]>>[0],
) {
if (!registration.resolveSubgraph) throw new Error("This node has no subgraph resolver");
return await registration.resolveSubgraph(validatedInput);
}
### Example
See the owning declaration and linked feature guide for usage; no standalone example is documented in source.
<a id="api-WorkflowNodeResolverInput"></a>
## [INTERFACE] `WorkflowNodeResolverInput`
Definition and node context supplied when compiling a registered workflow node.
Imports: `@alneas/eaos-server`, `@alneas/eaos-server/agentic`, `@alneas/eaos-server/agentic/workflow-catalog`.
### Signature
```typescript
interface WorkflowNodeResolverInput {
definition: WorkflowDefinition;
node: WorkflowDefinitionNode;
state?: AgentGraphState;
}
Name Type Required Description
definition WorkflowDefinition Yes Validated serializable workflow definition being compiled.
node WorkflowDefinitionNode Yes Specific definition node being resolved.
state AgentGraphState No Optional runtime state for host-specific resolution; the standard compiler omits it.

Type declaration; no runtime value.

WorkflowNodeRegistration.

Validated serializable workflow definition being compiled.

Specific definition node being resolved.

Optional runtime state for host-specific resolution; the standard compiler omits it.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Resolved user identity and authorized tenant context returned by createWorkspaceContextResolver.

Imports: @alneas/eaos-server, @alneas/eaos-server/workspace-context.

interface WorkspaceContext {
userId: string;
tenantId: string;
email: string | null;
tenantName: string;
industryType: string;
role: string;
roles: string[];
isSuperAdmin: boolean;
}
Name Type Required Description
userId string Yes Authenticated user ID.
tenantId string Yes Authorized selected tenant ID.
email string | null Yes Verified email, or null when absent.
tenantName string Yes Tenant display name, falling back to tenantId for an empty stored name.
industryType string Yes Tenant industry, falling back to “generic” for an empty stored value.
role string Yes Trimmed membership role, member for unsafe/blank roles, or admin for a platform administrator without membership.
roles string[] Yes Platform administrators receive SUPER_ADMIN, super_admin, admin; other users receive USER and their normalized role.
isSuperAdmin boolean Yes True only when the verified identity explicitly has platform authority.

Type declaration; no runtime value.

Authenticated user ID.

Authorized selected tenant ID.

Verified email, or null when absent.

Tenant display name, falling back to tenantId for an empty stored name.

Tenant industry, falling back to “generic” for an empty stored value.

Trimmed membership role, member for unsafe/blank roles, or admin for a platform administrator without membership.

Platform administrators receive SUPER_ADMIN, super_admin, admin; other users receive USER and their normalized role.

True only when the verified identity explicitly has platform authority.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Reports an authentication, membership, or host-store failure using an HTTP-compatible status.

Imports: @alneas/eaos-server, @alneas/eaos-server/workspace-context.

declare class WorkspaceContextError extends Error {
readonly status: 401 | 403 | 503;
constructor(status: 401 | 403 | 503, message: string);
}
Name Type Required Description
status 401 | 403 | 503 Yes 401 for missing identity, 403 for denied tenant access, or 503 for unavailable context data. This public readonly property is available for HTTP error mapping.
message string Yes Human-readable failure description.

WorkspaceContextError

createWorkspaceContextResolver for the resolver that rejects with this error.

import { WorkspaceContextError } from "@alneas/eaos-server/workspace-context";
const error = new WorkspaceContextError(403, "Tenant membership required");
console.log(error.status); // 403

Host reads used by createWorkspaceContextResolver; filter inactive rows and apply schema policy in the adapter.

Imports: @alneas/eaos-server, @alneas/eaos-server/workspace-context.

interface WorkspaceContextStore {
readTenant(tenantId: string): Promise<{
tenantName: string;
industryType?: string;
} | undefined>;
readMembership(tenantId: string, userId: string): Promise<{
role: string;
} | undefined>;
}
Name Type Required Description
readTenant Promise<{ tenantName: string; industryType?: string; } | undefined> Yes Loads the selected active tenant.
readMembership Promise<{ role: string; } | undefined> Yes Loads the active membership for this tenant/user pair.

Type declaration; no runtime value.

Loads the selected active tenant.

Parameters:

  • tenantId: Selected tenant ID from trusted routing.

Returns: Active tenant display data, or undefined if unavailable.

Persistence failures are wrapped as WorkspaceContextError with status 503.

Example:

import type { WorkspaceContextStore } from "@alneas/eaos-server";
export async function readSelectedTenant(store: WorkspaceContextStore, trustedTenantId: string) {
// Host storage filters inactive tenants and enforces its schema/access policy.
const tenant = await store.readTenant(trustedTenantId);
return tenant?.tenantName;
}

Display name of the selected active tenant; the context resolver falls back to tenantId when this value is empty.

Optional tenant industry classification; the context resolver substitutes generic when absent or empty.

Loads the active membership for this tenant/user pair.

Parameters:

  • tenantId: Selected active tenant ID.
  • userId: Authenticated user ID.

Returns: Membership role, or undefined if absent; tenant roles never establish platform authority.

Persistence failures are wrapped as WorkspaceContextError with status 503.

Example:

import type { WorkspaceContextStore } from "@alneas/eaos-server";
export async function readVerifiedMembership(
store: WorkspaceContextStore, trustedTenantId: string, authenticatedUserId: string,
) {
const membership = await store.readMembership(trustedTenantId, authenticatedUserId);
return membership?.role; // Absence must not grant tenant access.
}

Role from the active tenant/user membership; the resolver trims it and normalizes blank or super_admin/superadmin values to member rather than granting platform authority.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.

Identity is supplied exclusively by the host’s verified authentication middleware.

Imports: @alneas/eaos-server, @alneas/eaos-server/workspace-context.

interface WorkspaceIdentity {
userId: string;
email?: string | null;
isSuperAdmin?: boolean;
}
Name Type Required Description
userId string Yes User ID established by verified host authentication.
email string | null No Verified optional email; resolved contexts normalize absence to null.
isSuperAdmin boolean No Trusted platform authority; tenant roles cannot grant this privilege. Defaults to false.

Type declaration; no runtime value.

createWorkspaceContextResolver for host setup and usage.

User ID established by verified host authentication.

Verified optional email; resolved contexts normalize absence to null.

Trusted platform authority; tenant roles cannot grant this privilege. Defaults to false.

See the owning declaration and linked feature guide for usage; no standalone example is documented in source.