@agentropy/core 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ /** Lifecycle transition tables as data (docs/runtime-contract.md is authoritative). */
2
+ import { AgentropyError } from './errors.js';
3
+ const expand = (id, from, to, trigger) => from.map((f) => ({ id, from: f, to, trigger }));
4
+ export const TASK_MACHINE = {
5
+ name: 'task',
6
+ states: [
7
+ 'created',
8
+ 'assigned',
9
+ 'running',
10
+ 'waiting',
11
+ 'completed',
12
+ 'failed',
13
+ 'cancelled',
14
+ ],
15
+ terminal: ['completed', 'failed', 'cancelled'],
16
+ transitions: [
17
+ ...expand('T1', [null], 'created', 'delegate accepted'),
18
+ ...expand('T2', ['created'], 'assigned', 'instance bound'),
19
+ ...expand('T3', ['assigned'], 'running', 'execution leased'),
20
+ ...expand('T4', ['running'], 'waiting', 'handler returned waiting'),
21
+ ...expand('T5', ['waiting'], 'assigned', 'wake-up fired'),
22
+ ...expand('T6', ['running'], 'assigned', 'retryable attempt failure or lease lost'),
23
+ ...expand('T7', ['running'], 'completed', 'handler returned completed'),
24
+ ...expand('T8', ['running'], 'failed', 'non-retryable failure, attempts exhausted, invalid output or IncompatibleVersion'),
25
+ ...expand('T9', ['created', 'assigned', 'waiting'], 'failed', 'deadline, wake-up timeout with fail, or expired human action'),
26
+ ...expand('T10', ['created', 'assigned', 'waiting'], 'cancelled', 'cancel or forced retire'),
27
+ ...expand('T11', ['running'], 'cancelled', 'cancel after execution end or grace period'),
28
+ ],
29
+ };
30
+ export const EXECUTION_MACHINE = {
31
+ name: 'execution',
32
+ states: [
33
+ 'queued',
34
+ 'leased',
35
+ 'running',
36
+ 'succeeded',
37
+ 'yielded',
38
+ 'failed',
39
+ 'aborted',
40
+ 'lost',
41
+ ],
42
+ terminal: ['succeeded', 'yielded', 'failed', 'aborted', 'lost'],
43
+ transitions: [
44
+ ...expand('E1', [null], 'queued', 'task T2/T5/T6'),
45
+ ...expand('E2', ['queued'], 'leased', 'pool grant'),
46
+ ...expand('E3', ['leased'], 'running', 'handler invoked'),
47
+ ...expand('E4', ['running'], 'succeeded', 'disposition completed'),
48
+ ...expand('E5', ['running'], 'yielded', 'disposition waiting'),
49
+ ...expand('E6', ['running'], 'failed', 'disposition failed or handler threw'),
50
+ ...expand('E7', ['queued', 'leased'], 'aborted', 'task left a runnable state before start'),
51
+ ...expand('E7b', ['running'], 'aborted', 'cancel observed by handler'),
52
+ ...expand('E8', ['leased', 'running'], 'lost', 'lease expired, crash or grace period expired'),
53
+ ],
54
+ };
55
+ export const INSTANCE_MACHINE = {
56
+ name: 'instance',
57
+ states: ['available', 'suspended', 'retired'],
58
+ terminal: ['retired'],
59
+ transitions: [
60
+ ...expand('I-create', [null], 'available', 'instance created'),
61
+ ...expand('I-suspend', ['available'], 'suspended', 'operator/owner suspend'),
62
+ ...expand('I-resume', ['suspended'], 'available', 'resume'),
63
+ ...expand('I-retire', ['available', 'suspended'], 'retired', 'retire'),
64
+ ],
65
+ };
66
+ export const HUMAN_ACTION_MACHINE = {
67
+ name: 'human-action',
68
+ states: ['pending', 'claimed', 'resolved', 'expired', 'revoked'],
69
+ terminal: ['resolved', 'expired', 'revoked'],
70
+ transitions: [
71
+ ...expand('H-create', [null], 'pending', 'request created'),
72
+ ...expand('H-claim', ['pending'], 'claimed', 'claim'),
73
+ ...expand('H-release', ['claimed'], 'pending', 'claim released or expired'),
74
+ ...expand('H-resolve', ['pending', 'claimed'], 'resolved', 'decision accepted'),
75
+ ...expand('H-expire', ['pending', 'claimed'], 'expired', 'due time passed'),
76
+ ...expand('H-revoke', ['pending', 'claimed'], 'revoked', 'request revoked'),
77
+ ],
78
+ };
79
+ export function findTransition(machine, from, to) {
80
+ return machine.transitions.find((t) => t.from === from && t.to === to);
81
+ }
82
+ /** Returns the edge or throws InvalidState for any edge not listed in the contract table. */
83
+ export function assertTransition(machine, from, to, edgeId) {
84
+ const edge = machine.transitions.find((t) => t.from === from &&
85
+ t.to === to &&
86
+ (edgeId === undefined || t.id === edgeId));
87
+ if (!edge) {
88
+ throw new AgentropyError('InvalidState', `Illegal ${machine.name} transition ${from ?? '∅'} → ${to}`, {
89
+ details: {
90
+ machine: machine.name,
91
+ from: from ?? 'none',
92
+ to,
93
+ ...(edgeId ? { edge: edgeId } : {}),
94
+ },
95
+ });
96
+ }
97
+ return edge;
98
+ }
99
+ export function isTerminal(machine, state) {
100
+ return machine.terminal.includes(state);
101
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Messaging, inbox and human-action types (docs/messaging-contract.md, docs/human-actions.md, Agent v1).
3
+ * Types only; the runtime package implements publication, projection and decisions.
4
+ */
5
+ import type { AgentInstanceId, JsonSchema, TaskId, TaskSnapshot } from './agent.js';
6
+ export declare const TRANSITION_EVENT_TYPES: readonly ["taskAccepted", "taskAssigned", "taskStarted", "taskWaiting", "taskCompleted", "taskFailed", "taskCancelled"];
7
+ export declare const NON_TRANSITION_EVENT_TYPES: readonly ["taskCancelRequested", "agentProgressUpdated", "notificationCreated", "humanActionRequested", "humanActionResolved"];
8
+ export type TaskEventType = (typeof TRANSITION_EVENT_TYPES)[number] | (typeof NON_TRANSITION_EVENT_TYPES)[number];
9
+ /** Transition event type for the status a task enters. */
10
+ export declare const TRANSITION_EVENT: Record<TaskSnapshot['status'], TaskEventType>;
11
+ export interface TaskEvent {
12
+ eventId: string;
13
+ taskId: TaskId;
14
+ /** Task revision current when the event was committed. */
15
+ revision: number;
16
+ /** 0 for the transition event itself, 1.. for later non-transition events at that revision. */
17
+ sequence: number;
18
+ type: TaskEventType;
19
+ status: TaskSnapshot['status'];
20
+ occurredAt: string;
21
+ data?: unknown;
22
+ }
23
+ /** True when `e` is strictly after the last seen `(revision, sequence)` pair. */
24
+ export declare function isAfter(e: {
25
+ revision: number;
26
+ sequence: number;
27
+ }, last: {
28
+ revision: number;
29
+ sequence: number;
30
+ } | undefined): boolean;
31
+ export type Severity = 'critical' | 'high' | 'normal' | 'low';
32
+ export interface InboxEntry {
33
+ entryId: string;
34
+ userId: string;
35
+ tenantId: string;
36
+ source: {
37
+ eventId: string;
38
+ taskId: TaskId;
39
+ type: 'notificationCreated' | 'humanActionRequested' | 'taskCompleted' | 'taskFailed';
40
+ };
41
+ agentInstanceId: AgentInstanceId;
42
+ severity: Severity;
43
+ title: string;
44
+ body?: string;
45
+ actionRequestId?: string;
46
+ /** Bumps when the underlying item changes (e.g. a request is resolved or a deduplicated notification is revised). */
47
+ revision: number;
48
+ markers: {
49
+ deliveredAt?: string;
50
+ presentedAt?: string;
51
+ presentedRevision?: number;
52
+ readAt?: string;
53
+ acknowledgedAt?: string;
54
+ resolvedAt?: string;
55
+ };
56
+ }
57
+ export type InboxMarker = 'presented' | 'read' | 'acknowledged';
58
+ export interface NotifyInput {
59
+ severity: Severity;
60
+ title: string;
61
+ body: string;
62
+ /** Same key from the same task owner revises one entry instead of creating another. */
63
+ dedupeKey?: string;
64
+ }
65
+ export interface ConversationTurn {
66
+ /** The user's conversational agent instance. */
67
+ instanceId: AgentInstanceId;
68
+ sessionId: string;
69
+ text: string;
70
+ idempotencyKey: string;
71
+ /** Generated if absent. */
72
+ correlationId?: string;
73
+ }
74
+ export type HumanActionKind = 'approval' | 'choice' | 'text' | 'form';
75
+ export interface HumanActionInput {
76
+ kind: HumanActionKind;
77
+ /** Rendered by the platform, never trusted as instructions. */
78
+ prompt: string;
79
+ inputSchema: JsonSchema;
80
+ assignees: {
81
+ principalIds?: string[];
82
+ roles?: string[];
83
+ };
84
+ dueAt?: string;
85
+ onExpiry: 'resume' | 'fail-task';
86
+ /**
87
+ * Approvals only (FEAT-028.5): distinct eligible principals who must submit the same decision input before the
88
+ * request resolves (default 1, at most 5). Differing decisions are recorded and the request stays open.
89
+ */
90
+ requiredApprovals?: number;
91
+ /** Approvals only: whether the principal who delegated the task may approve it (default false). */
92
+ allowSelfApproval?: boolean;
93
+ }
94
+ export interface HumanActionRequest extends HumanActionInput {
95
+ requestId: string;
96
+ taskId: TaskId;
97
+ agentInstanceId: AgentInstanceId;
98
+ tenantId: string;
99
+ requestedBy: string;
100
+ status: 'pending' | 'claimed' | 'resolved' | 'expired' | 'revoked';
101
+ claimedBy?: string;
102
+ claimExpiresAt?: string;
103
+ revision: number;
104
+ }
105
+ export interface HumanDecision {
106
+ requestId: string;
107
+ /** The revision the user saw; mismatch → StaleRevision. */
108
+ expectedRevision: number;
109
+ /** Validated against the request's inputSchema. */
110
+ input: unknown;
111
+ idempotencyKey: string;
112
+ }
@@ -0,0 +1,32 @@
1
+ export const TRANSITION_EVENT_TYPES = [
2
+ 'taskAccepted',
3
+ 'taskAssigned',
4
+ 'taskStarted',
5
+ 'taskWaiting',
6
+ 'taskCompleted',
7
+ 'taskFailed',
8
+ 'taskCancelled',
9
+ ];
10
+ export const NON_TRANSITION_EVENT_TYPES = [
11
+ 'taskCancelRequested',
12
+ 'agentProgressUpdated',
13
+ 'notificationCreated',
14
+ 'humanActionRequested',
15
+ 'humanActionResolved',
16
+ ];
17
+ /** Transition event type for the status a task enters. */
18
+ export const TRANSITION_EVENT = {
19
+ created: 'taskAccepted',
20
+ assigned: 'taskAssigned',
21
+ running: 'taskStarted',
22
+ waiting: 'taskWaiting',
23
+ completed: 'taskCompleted',
24
+ failed: 'taskFailed',
25
+ cancelled: 'taskCancelled',
26
+ };
27
+ /** True when `e` is strictly after the last seen `(revision, sequence)` pair. */
28
+ export function isAfter(e, last) {
29
+ return (!last ||
30
+ e.revision > last.revision ||
31
+ (e.revision === last.revision && e.sequence > last.sequence));
32
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Provider SPIs behind the `reasoning` and `workflow` capabilities (Capability v1, ADR-0006, M2-07/M2-08).
3
+ * Engines and model APIs plug in here; agents only ever see the capability operations.
4
+ */
5
+ export interface ReasoningMessage {
6
+ role: 'system' | 'user' | 'assistant';
7
+ content: string;
8
+ }
9
+ export interface ReasoningToolSpec {
10
+ /** Provider-safe function name derived from the pinned tool ID. */
11
+ name: string;
12
+ description: string;
13
+ inputSchema: unknown;
14
+ }
15
+ export interface ReasoningRequest {
16
+ messages: ReasoningMessage[];
17
+ maxTokens: number;
18
+ temperature?: number;
19
+ tools?: ReasoningToolSpec[];
20
+ /**
21
+ * Routing hints for a routing provider (FEAT-035.3): identifiers set by the calling code, never by model output.
22
+ * A plain provider ignores them.
23
+ */
24
+ route?: {
25
+ zone?: string;
26
+ dataClass?: string;
27
+ tier?: string;
28
+ latency?: 'low' | 'normal';
29
+ };
30
+ }
31
+ export interface ReasoningResult {
32
+ text: string;
33
+ toolCalls?: {
34
+ name: string;
35
+ input: unknown;
36
+ }[];
37
+ usage: {
38
+ inputTokens: number;
39
+ outputTokens: number;
40
+ };
41
+ model: string;
42
+ }
43
+ export interface ReasoningProvider {
44
+ readonly id: string;
45
+ complete(request: ReasoningRequest, ctx: {
46
+ tenantId: string;
47
+ taskId: string;
48
+ signal: AbortSignal;
49
+ }): Promise<ReasoningResult>;
50
+ }
51
+ export type WorkflowState = 'running' | 'completed' | 'failed';
52
+ export interface WorkflowRun {
53
+ runId: string;
54
+ state: WorkflowState;
55
+ output?: unknown;
56
+ /** Errors v1 code when failed. */
57
+ code?: string;
58
+ }
59
+ /**
60
+ * A deterministic workflow engine (Temporal, Quarkus Flow, …). `start` must be idempotent per `idempotencyKey`
61
+ * (same key → same run). On completion the engine (or its adapter) calls `onFinished` so the runtime can wake
62
+ * the waiting task through its `workflow` event subscription.
63
+ */
64
+ export interface WorkflowEngine {
65
+ readonly id: string;
66
+ start(workflow: string, input: unknown, ctx: {
67
+ tenantId: string;
68
+ taskId: string;
69
+ idempotencyKey: string;
70
+ }): Promise<WorkflowRun>;
71
+ status(runId: string, ctx: {
72
+ tenantId: string;
73
+ }): Promise<WorkflowRun>;
74
+ onFinished(listener: (run: WorkflowRun & {
75
+ tenantId: string;
76
+ }) => void): void;
77
+ /**
78
+ * Optional, for engines that cannot push: re-checks the runs the engine started and reports the finished ones
79
+ * through `onFinished`. `createLocalApp` calls it as a scheduler sweep, at most every `workflowPollMs`.
80
+ */
81
+ poll?(): Promise<unknown>;
82
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Provider SPIs behind the `reasoning` and `workflow` capabilities (Capability v1, ADR-0006, M2-07/M2-08).
3
+ * Engines and model APIs plug in here; agents only ever see the capability operations.
4
+ */
5
+ export {};
@@ -0,0 +1,30 @@
1
+ import type { AgentDefinition, DurabilityLevel, VersionedRef } from './agent.js';
2
+ import type { AgentProfile, CapabilityBinding, CapabilityContract, CapabilitySelection } from './capability.js';
3
+ export interface CapabilityProviderDescriptor {
4
+ id: string;
5
+ version: string;
6
+ contracts: {
7
+ id: string;
8
+ version: string;
9
+ level?: string;
10
+ }[];
11
+ }
12
+ export interface CapabilityEnvironment {
13
+ contracts: readonly CapabilityContract[];
14
+ profiles: readonly AgentProfile[];
15
+ providers: readonly CapabilityProviderDescriptor[];
16
+ /** Deployment default provider per capability ID; used when a selection names none and several match. */
17
+ defaultProviders?: Readonly<Record<string, string>>;
18
+ /** Strongest durability level the runtime/store itself can honor. */
19
+ runtimeDurability: DurabilityLevel;
20
+ }
21
+ export interface CapabilityResolution {
22
+ profile: AgentProfile;
23
+ bindings: CapabilityBinding[];
24
+ /** Strongest requested durability level, or the runtime level when nothing was requested. */
25
+ durability: DurabilityLevel;
26
+ requestedDurability?: DurabilityLevel;
27
+ }
28
+ export declare function findProfile(env: Pick<CapabilityEnvironment, 'profiles'>, ref: VersionedRef): AgentProfile;
29
+ /** Steps 1–5: merge, expand dependencies, resolve versions/providers/config, verify guarantees. */
30
+ export declare function resolveCapabilities(definition: AgentDefinition, env: CapabilityEnvironment, instanceSelections?: readonly CapabilitySelection[]): CapabilityResolution;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Pure capability resolution (Capability v1 revision 6, "Resolution algorithm", steps 1–5 and 7).
3
+ * Policy (step 6) and implementation/tool/skill resolution live in acceptance.ts.
4
+ */
5
+ import semver from 'semver';
6
+ import { DURABILITY_LEVELS } from './catalog.js';
7
+ import { AgentropyError } from './errors.js';
8
+ import { validateAgainst } from './schemas.js';
9
+ const fail = (code, message, details) => new AgentropyError(code, message, { details });
10
+ function levelRank(contract, level) {
11
+ if (level === undefined)
12
+ return -1;
13
+ const rank = (contract.levels ?? []).indexOf(level);
14
+ if (rank < 0)
15
+ throw fail('InvalidConfiguration', `Unknown level ${level} for ${contract.id}`, { reason: 'level', id: contract.id, level });
16
+ return rank;
17
+ }
18
+ function contractsFor(env, id) {
19
+ return env.contracts.filter((c) => c.id === id);
20
+ }
21
+ export function findProfile(env, ref) {
22
+ const profile = env.profiles.find((p) => p.id === ref.id && p.version === ref.version);
23
+ if (!profile)
24
+ throw fail('NotFound', `Profile ${ref.id}@${ref.version} not found`, {
25
+ kind: 'profile',
26
+ id: ref.id,
27
+ });
28
+ return profile;
29
+ }
30
+ /** Steps 1–5: merge, expand dependencies, resolve versions/providers/config, verify guarantees. */
31
+ export function resolveCapabilities(definition, env, instanceSelections = []) {
32
+ // Step 1: exact profile.
33
+ const profile = findProfile(env, definition.profile);
34
+ const working = new Map();
35
+ const apply = (s, required) => {
36
+ const contracts = contractsFor(env, s.id);
37
+ if (contracts.length === 0)
38
+ throw fail('CapabilityUnavailable', `Unknown capability ${s.id}`, {
39
+ reason: 'unknown',
40
+ id: s.id,
41
+ });
42
+ const existing = working.get(s.id);
43
+ if (s.remove) {
44
+ if (existing?.required)
45
+ throw fail('InvalidConfiguration', `Required capability ${s.id} cannot be removed`, { reason: 'required-removal', id: s.id });
46
+ working.delete(s.id);
47
+ return;
48
+ }
49
+ if (!existing) {
50
+ working.set(s.id, {
51
+ id: s.id,
52
+ ranges: [s.versionRange],
53
+ required,
54
+ config: { ...(s.config ?? {}) },
55
+ providerId: s.providerId,
56
+ level: s.level,
57
+ });
58
+ return;
59
+ }
60
+ // Nearer selection overrides ordinary config/provider; ranges accumulate; guarantee level only strengthens.
61
+ existing.ranges.push(s.versionRange);
62
+ existing.required ||= required;
63
+ if (s.config)
64
+ existing.config = { ...existing.config, ...s.config };
65
+ if (s.providerId)
66
+ existing.providerId = s.providerId;
67
+ if (s.level !== undefined) {
68
+ const contract = contracts[0];
69
+ if (levelRank(contract, s.level) > levelRank(contract, existing.level))
70
+ existing.level = s.level;
71
+ }
72
+ };
73
+ // Step 2: profile required + defaults, then definition, runtime requirements, then instance.
74
+ for (const s of profile.required)
75
+ apply(s, true);
76
+ for (const s of profile.defaults)
77
+ apply(s, false);
78
+ for (const s of definition.capabilities ?? [])
79
+ apply(s, false);
80
+ for (const s of definition.runtimeRequirements.guarantees)
81
+ apply(s, false);
82
+ for (const s of instanceSelections)
83
+ apply(s, false);
84
+ // Step 3: dependencies (transitive), cycles and conflicts over the contract graph.
85
+ const visiting = new Set();
86
+ const done = new Set();
87
+ const visit = (id, path) => {
88
+ if (done.has(id))
89
+ return;
90
+ if (visiting.has(id))
91
+ throw fail('InvalidConfiguration', `Capability dependency cycle ${[...path, id].join(' → ')}`, { reason: 'cycle', id });
92
+ visiting.add(id);
93
+ for (const c of contractsFor(env, id)) {
94
+ for (const dep of c.dependencies) {
95
+ if (contractsFor(env, dep.id).length === 0)
96
+ throw fail('CapabilityUnavailable', `Unknown dependency ${dep.id} of ${id}`, { reason: 'unknown', id: dep.id });
97
+ const w = working.get(dep.id);
98
+ if (w)
99
+ w.ranges.push(dep.versionRange);
100
+ else
101
+ working.set(dep.id, {
102
+ id: dep.id,
103
+ ranges: [dep.versionRange],
104
+ required: true,
105
+ config: {},
106
+ });
107
+ visit(dep.id, [...path, id]);
108
+ }
109
+ }
110
+ visiting.delete(id);
111
+ done.add(id);
112
+ };
113
+ for (const id of [...working.keys()])
114
+ visit(id, []);
115
+ // Step 4: exact versions, providers, config.
116
+ const bindings = [];
117
+ let requestedDurability;
118
+ for (const w of [...working.values()].sort((a, b) => a.id.localeCompare(b.id))) {
119
+ const candidates = contractsFor(env, w.id)
120
+ .filter((c) => w.ranges.every((r) => semver.satisfies(c.version, r)))
121
+ .sort((a, b) => semver.rcompare(a.version, b.version));
122
+ const contract = candidates[0];
123
+ if (!contract)
124
+ throw fail('CapabilityUnavailable', `No version of ${w.id} satisfies ${w.ranges.join(' and ')}`, { reason: 'version', id: w.id });
125
+ for (const conflict of contract.conflicts ?? []) {
126
+ const other = working.get(conflict.id);
127
+ if (other)
128
+ throw fail('InvalidConfiguration', `${w.id} conflicts with ${conflict.id}`, { reason: 'conflict', id: w.id, with: conflict.id });
129
+ }
130
+ const matching = env.providers.filter((p) => p.contracts.some((c) => c.id === contract.id && c.version === contract.version));
131
+ let provider;
132
+ if (w.providerId) {
133
+ provider = matching.find((p) => p.id === w.providerId);
134
+ if (!provider)
135
+ throw fail('CapabilityUnavailable', `Provider ${w.providerId} does not offer ${w.id}@${contract.version}`, { reason: 'provider', id: w.id });
136
+ }
137
+ else if (matching.length === 1) {
138
+ provider = matching[0];
139
+ }
140
+ else if (matching.length > 1) {
141
+ const preferred = env.defaultProviders?.[w.id];
142
+ provider = matching.find((p) => p.id === preferred);
143
+ if (!provider)
144
+ throw fail('CapabilityUnavailable', `Ambiguous provider for ${w.id}`, {
145
+ reason: 'ambiguous',
146
+ id: w.id,
147
+ candidates: matching.map((p) => p.id),
148
+ });
149
+ }
150
+ else {
151
+ throw fail('CapabilityUnavailable', `No provider for ${w.id}@${contract.version}`, { reason: 'provider', id: w.id });
152
+ }
153
+ try {
154
+ validateAgainst(contract.configSchema, w.config, `${w.id} config`);
155
+ }
156
+ catch (cause) {
157
+ throw new AgentropyError('InvalidConfiguration', `Invalid config for ${w.id}`, { details: { reason: 'config', id: w.id }, cause });
158
+ }
159
+ const binding = {
160
+ id: w.id,
161
+ version: contract.version,
162
+ providerId: provider.id,
163
+ providerVersion: provider.version,
164
+ config: w.config,
165
+ };
166
+ // Step 5: guarantees — the provided level is the weaker of provider and runtime.
167
+ if (contract.kind === 'guarantee') {
168
+ const requested = levelRank(contract, w.level);
169
+ let provided = levelRank(contract, provider.contracts.find((c) => c.id === contract.id)?.level ??
170
+ contract.levels?.[0]);
171
+ if (contract.id === 'durability')
172
+ provided = Math.min(provided, DURABILITY_LEVELS.indexOf(env.runtimeDurability));
173
+ if (provided < requested) {
174
+ throw fail('GuaranteeUnavailable', `${w.id} level ${w.level} is not available`, {
175
+ id: w.id,
176
+ requested: w.level ?? 'none',
177
+ provided: contract.levels?.[provided] ?? 'none',
178
+ });
179
+ }
180
+ binding.level = contract.levels?.[provided];
181
+ if (contract.id === 'durability' && w.level !== undefined)
182
+ requestedDurability = w.level;
183
+ }
184
+ bindings.push(binding);
185
+ }
186
+ return {
187
+ profile,
188
+ bindings,
189
+ durability: requestedDurability ?? env.runtimeDurability,
190
+ requestedDurability,
191
+ };
192
+ }