@alma-harness/runtime 0.7.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # @alma-harness/runtime
2
+
3
+ Official storage composition for `createConversationRunner`. This package wires
4
+ existing stores; the host still supplies clients, audit, policy, prices, caps,
5
+ revisions and limits. The root export contains types only.
6
+
7
+ ```ts
8
+ import { createMemoryRuntime } from '@alma-harness/runtime/memory';
9
+ import { createConversationRunner } from '@alma-harness/conversation';
10
+ const resultPolicy = { maxSensitivity: 'personal' as const, maxRetentionMs: 60_000, maxChars: 100_000 };
11
+ const runtime = createMemoryRuntime({ stepResultPolicy: resultPolicy, rootResultPolicy: resultPolicy });
12
+ // hostConfig contains the non-storage conversation configuration.
13
+ const runner = createConversationRunner({ ...hostConfig, ...runtime.stores,
14
+ step: { ...hostConfig.step, ...runtime.stores.step } });
15
+ // Reuse the original idempotencyKey and input when retrying a delivery.
16
+ const result = await runner.runTurn(request);
17
+ await runtime.close();
18
+ ```
19
+
20
+ See [the complete quickstart](../../examples/quickstart/src/agent.ts) for executable
21
+ configuration. Memory is ephemeral: restarting loses notes, history, admission and
22
+ replay protection. `close()` does not erase stores or reconcile uncertain work.
23
+
24
+ ## PostgreSQL
25
+
26
+ Install the PostgreSQL peers and `pg` when using this subpath. Provision two trusted,
27
+ dedicated schemas with different lowercase ASCII names (at most 63 characters).
28
+ Public/system namespaces and connection URLs with startup `options` are rejected.
29
+
30
+ ```ts
31
+ import { createPostgresRuntime, migratePostgresRuntime } from '@alma-harness/runtime/postgres';
32
+ const namespace = { schema: 'agent_execution', rootSchema: 'agent_results',
33
+ onPoolError: (error: Error, schema: string) => console.error('Database pool error', schema, error) };
34
+ // Run explicitly under a migration principal, outside request handling.
35
+ await migratePostgresRuntime({ ...namespace, connectionString: migrationURL });
36
+ const runtime = createPostgresRuntime({ ...namespace, connectionString: runtimeURL,
37
+ poolMax: { execution: 2, roots: 1 }, // Example connection budget, not a production recommendation.
38
+ stepResultPolicy: resultPolicy, rootResultPolicy: resultPolicy });
39
+ ```
40
+
41
+ The migration principal needs schema/table/role provisioning rights. Migration
42
+ installs official adapters, grants schema USAGE to `alma_app`/`alma_retention` and
43
+ revokes their and PUBLIC's schema CREATE. It never grants login membership. The
44
+ operator separately provisions the runtime login with `alma_app` membership,
45
+ without superuser/BYPASSRLS/owner privileges. `alma_retention` membership belongs
46
+ to a separately authorized operator login. Existing role attributes are unchanged.
47
+ Migration is repeatable but not atomic across schemas: after a failure, correct the
48
+ cause and rerun explicitly. Do not drop populated schemas to retry installation.
49
+
50
+ The required synchronous `onPoolError(error, schema)` listener reports idle-client
51
+ failures from both pools, including during migration. The host must not throw from
52
+ this listener. Reporting does not retry work or release admission.
53
+
54
+ Construction performs no connection, migration or grants. It owns two bounded pools
55
+ (five connections each by default), pins their namespace and float settings, and uses the
56
+ official scoped transactions. The result tables are physically separate for steps
57
+ and conversation roots. Runtime startup fails on missing tables or memberships.
58
+
59
+ `poolMax: { execution, roots }` sets the two independent limits. Both must be
60
+ positive safe integers with a safe sum; null, partial objects and extra fields are
61
+ rejected before either pool is allocated. The values are copied at construction;
62
+ mutating the configuration cannot resize live pools. Checkout/connect timeout
63
+ remains five seconds and idle timeout ten seconds. Generic driver overrides and
64
+ public pool handles are not provided. Migrations have their own two max1 pools,
65
+ always closed on completion/failure; application sizing does not tune migrations.
66
+
67
+ Budget `sum(runtime instances × (execution + roots))` plus migrations, retention,
68
+ backup, other pools and an administrative reserve against database capacity.
69
+ Count every replica/worker class and reuse a runtime across its turns/observers.
70
+ Connection limits do not bound worker concurrency or driver waiter queues. Host
71
+ queue limits remain necessary; pressure cannot authorize retries or release
72
+ uncertain admission. The deterministic max1 tests prove correctness with minimal
73
+ capacity, not production throughput or a recommended server configuration.
74
+
75
+ Register sessions and **both** result stores in the host's audited retention and
76
+ erasure workflows. Erasing one result store does not erase the other. Quiesce workers
77
+ before `close()`; it attempts both pools and is idempotent. Closing neither aborts
78
+ nor releases uncertain admissions. Resolve `reconciliation_required` through the
79
+ existing operator procedure, never by issuing a new delivery key.
80
+
81
+ ## Conversation operations
82
+
83
+ `@alma-harness/runtime/operations` exports `createConversationOperations`. Supply
84
+ runtime stores for metadata-only inspect, an existing step recovery capability for
85
+ accounting-only repair, and separately privileged admission resolution plus a
86
+ trusted maintained host quiescence capability for resolve. No default operator,
87
+ provider clients, effect replay or automatic takeover is supplied.
88
+
89
+ The installed `alma-operations` CLI accepts inspect/repair/resolve, an explicit
90
+ local `--host` module and bounded JSON stdin. The host owns credentials and cleanup.
91
+ See [the operator runbook](../../docs/conversation-operations.md) and its real
92
+ PostgreSQL installed-consumer drill. Unknown/unpriced or late-only evidence stays
93
+ blocked; release never marks an incomplete root successful. Expiry sweeps are
94
+ explicitly scope-wide. A stale digest requires reinspection, while lost resolution
95
+ ACK retries retain the same resolutionId. This is operator infrastructure, not a
96
+ request-path fallback or a remote-worker fencing implementation.
@@ -0,0 +1,10 @@
1
+ // src/policies.ts
2
+ import { normalizeExecutionResultPolicy } from "@alma-harness/memory";
3
+ function policies(value) {
4
+ return { stepResultPolicy: normalizeExecutionResultPolicy(value.stepResultPolicy), rootResultPolicy: normalizeExecutionResultPolicy(value.rootResultPolicy) };
5
+ }
6
+
7
+ export {
8
+ policies
9
+ };
10
+ //# sourceMappingURL=chunk-3OEFEOI4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/policies.ts"],"sourcesContent":["import { normalizeExecutionResultPolicy } from \"@alma-harness/memory\";\nimport type { RuntimePolicies } from \"./index\";\nexport function policies(value: RuntimePolicies): RuntimePolicies {\n return { stepResultPolicy: normalizeExecutionResultPolicy(value.stepResultPolicy), rootResultPolicy: normalizeExecutionResultPolicy(value.rootResultPolicy) };\n}\n"],"mappings":";AAAA,SAAS,sCAAsC;AAExC,SAAS,SAAS,OAAyC;AAChE,SAAO,EAAE,kBAAkB,+BAA+B,MAAM,gBAAgB,GAAG,kBAAkB,+BAA+B,MAAM,gBAAgB,EAAE;AAC9J;","names":[]}
@@ -0,0 +1,239 @@
1
+ // src/operations-input.ts
2
+ import { settlementIdentifier, settlementScope } from "@alma-harness/core";
3
+ var ConversationOperationError = class extends Error {
4
+ constructor(code) {
5
+ super(`Conversation operation: ${["invalid_request", "binding_conflict", "incomplete_inspection", "permission_required", "resolution_blocked", "stale_snapshot", "operation_failed"].includes(code) ? code : "operation_failed"}`);
6
+ this.code = code;
7
+ if (!["invalid_request", "binding_conflict", "incomplete_inspection", "permission_required", "resolution_blocked", "stale_snapshot", "operation_failed"].includes(code)) this.code = "operation_failed";
8
+ this.name = "ConversationOperationError";
9
+ }
10
+ code;
11
+ };
12
+ var fail = (code) => {
13
+ throw new ConversationOperationError(code);
14
+ };
15
+ function fields(value, keys) {
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fail("invalid_request");
17
+ const descriptors = Object.getOwnPropertyDescriptors(value);
18
+ if (Reflect.ownKeys(descriptors).some((k) => typeof k !== "string" || !keys.includes(k) || !("value" in descriptors[k]))) return fail("invalid_request");
19
+ return Object.fromEntries(Object.entries(descriptors).map(([k, d]) => [k, d.value]));
20
+ }
21
+ function key(value) {
22
+ try {
23
+ const v = fields(value, ["scope", "sessionId", "rootKey"]);
24
+ return { scope: settlementScope(v.scope), sessionId: settlementIdentifier(v.sessionId), rootKey: settlementIdentifier(v.rootKey) };
25
+ } catch {
26
+ return fail("invalid_request");
27
+ }
28
+ }
29
+ function resolution(value) {
30
+ try {
31
+ const v = fields(value, ["key", "snapshotDigest", "resolutionId", "evidenceId"]);
32
+ if (typeof v.snapshotDigest !== "string" || !/^[a-f0-9]{64}$/.test(v.snapshotDigest)) return fail("invalid_request");
33
+ return { key: key(v.key), snapshotDigest: v.snapshotDigest, resolutionId: settlementIdentifier(v.resolutionId), evidenceId: settlementIdentifier(v.evidenceId) };
34
+ } catch {
35
+ return fail("invalid_request");
36
+ }
37
+ }
38
+
39
+ // src/operations.ts
40
+ import { createHash } from "crypto";
41
+ import { equalExecution, executionSettlementRequest, settlementIdentifier as settlementIdentifier2 } from "@alma-harness/core";
42
+ import { bindOperationCost, checkOperationCall, normalizeRootCallReceipt } from "@alma-harness/execution";
43
+ function canonical(value) {
44
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
45
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
46
+ return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
47
+ }
48
+ var hash = (value) => createHash("sha256").update(canonical(value)).digest("hex");
49
+ async function safe(fn) {
50
+ try {
51
+ return await fn();
52
+ } catch (error) {
53
+ if (error instanceof ConversationOperationError) throw error;
54
+ return fail("operation_failed");
55
+ }
56
+ }
57
+ function createConversationOperations(options) {
58
+ const { stores, recovery, operator, quiescence } = options;
59
+ const { admissions, step } = stores;
60
+ async function snapshot(k) {
61
+ const admission = await admissions.get(k.scope, k.rootKey);
62
+ if (!admission || admission.input.sessionId !== k.sessionId || admission.input.key !== k.rootKey || !equalExecution(admission.input.scope, k.scope)) return fail("binding_conflict");
63
+ const root = await step.trees.get(k.scope, k.rootKey);
64
+ if (root && !equalExecution(root.input, admission.input)) return fail("binding_conflict");
65
+ const members = [], receipts = [];
66
+ if (root) {
67
+ for (let afterOrdinal = 0; ; ) {
68
+ const page = await step.trees.listCalls(k.scope, k.rootKey, { afterOrdinal, limit: 100 });
69
+ for (const m of page) {
70
+ if (m.ordinal !== members.length + 1 || m.rootId !== root.input.id || members.length >= root.input.maxCalls) return fail("incomplete_inspection");
71
+ checkOperationCall(root.input, m.input);
72
+ members.push(m);
73
+ }
74
+ if (page.length < 100) break;
75
+ afterOrdinal = page.at(-1).ordinal;
76
+ }
77
+ if (members.length !== root.callCount) return fail("incomplete_inspection");
78
+ for (let afterOrdinal = 0; ; ) {
79
+ const page = await step.accounting.list(k.scope, k.rootKey, { afterOrdinal, limit: 100 });
80
+ for (const raw of page) {
81
+ const r = normalizeRootCallReceipt(raw);
82
+ if (r.accountingOrdinal !== receipts.length + 1 || r.rootId !== root.input.id || receipts.length >= members.length || receipts.some((x) => x.callId === r.callId)) return fail("binding_conflict");
83
+ if (r.previousUsd !== (receipts.at(-1)?.currentUsd ?? 0)) return fail("binding_conflict");
84
+ receipts.push(r);
85
+ }
86
+ if (page.length < 100) break;
87
+ afterOrdinal = page.at(-1).accountingOrdinal;
88
+ }
89
+ }
90
+ const accounting = await step.accounting.get(k.scope, k.rootKey);
91
+ if (root && (!accounting || accounting.rootId !== root.input.id || accounting.rootStatus !== root.status || accounting.reservedCalls !== members.length || accounting.settledCalls !== receipts.length || accounting.costUsd !== (receipts.at(-1)?.currentUsd ?? 0))) return fail("binding_conflict");
92
+ if (!root && accounting) return fail("binding_conflict");
93
+ const calls = [], proof = [admission, root, receipts, accounting];
94
+ for (const member of members) {
95
+ const e = member.input.execution, journal = await step.executions.get(k.scope, e.operationKey), receipt = receipts.find((r) => r.callId === e.callId);
96
+ if (journal && !equalExecution(journal.input, e)) return fail("binding_conflict");
97
+ const source = await step.settlements.getGoverned(k.scope, e.settlementId);
98
+ if (source) {
99
+ bindOperationCost(root.input, member, source);
100
+ if (!journal || !equalExecution(source.request, executionSettlementRequest(journal)) || journal.settlement && !equalExecution(journal.settlement, source.receipt)) return fail("binding_conflict");
101
+ }
102
+ if (receipt && (!source || receipt.reservationOrdinal !== member.ordinal || receipt.settlementId !== e.settlementId || receipt.costUsd !== source.receipt.settlement.costUsd)) return fail("binding_conflict");
103
+ const complete = journal?.state === "completed" && !!journal.settlement && !!source && !!receipt;
104
+ calls.push({
105
+ ordinal: member.ordinal,
106
+ kind: member.input.kind,
107
+ callId: e.callId,
108
+ operationKey: e.operationKey,
109
+ settlementId: e.settlementId,
110
+ deadlineAt: e.deadlineAt,
111
+ model: e.model,
112
+ priceVersion: e.priceVersion,
113
+ prices: e.prices,
114
+ providerRequestId: journal?.providerRequestId,
115
+ usage: journal?.evidence?.status === "known" ? journal.evidence.usage : void 0,
116
+ state: journal?.state ?? "missing",
117
+ evidence: journal?.evidence?.status ?? "missing",
118
+ pricing: journal?.pricing?.status ?? "missing",
119
+ accounted: complete,
120
+ ...receipt ? { costUsd: receipt.costUsd } : {},
121
+ recoveryUntil: journal?.recoveryUntil
122
+ });
123
+ proof.push(member, journal, source);
124
+ }
125
+ const pending = [];
126
+ let after;
127
+ for (let scanned = 0; ; ) {
128
+ const page = await step.inbox.listPending(k.scope, { limit: 100, ...after ? { after } : {} });
129
+ for (const row of page) {
130
+ if (!equalExecution(row.input.execution.scope, k.scope)) return fail("binding_conflict");
131
+ const cursor = { receivedAt: row.receivedAt, id: row.input.id };
132
+ if (after && (cursor.receivedAt < after.receivedAt || cursor.receivedAt === after.receivedAt && cursor.id <= after.id)) return fail("incomplete_inspection");
133
+ after = cursor;
134
+ const member = members.find((m) => m.input.execution.operationKey === row.input.execution.operationKey);
135
+ if (member) {
136
+ proof.push(row);
137
+ pending.push({ id: row.input.id, operationKey: row.input.execution.operationKey, receivedAt: row.receivedAt, evidence: row.input.evidence.status });
138
+ }
139
+ }
140
+ scanned += page.length;
141
+ if (page.length < 100) break;
142
+ if (scanned >= 1e4) return fail("incomplete_inspection");
143
+ }
144
+ if (!equalExecution(admission, await admissions.get(k.scope, k.rootKey)) || !equalExecution(root, await step.trees.get(k.scope, k.rootKey))) return fail("stale_snapshot");
145
+ const blockers = [
146
+ ...!root ? ["root_missing"] : [],
147
+ ...admission.status !== "reconciliation_required" ? ["admission_not_uncertain"] : [],
148
+ ...Date.now() < Date.parse(admission.input.deadlineAt) ? ["deadline_not_expired"] : [],
149
+ ...calls.some((c) => !c.accounted) ? ["incomplete_accounting"] : [],
150
+ ...pending.length ? ["pending_usage"] : []
151
+ ];
152
+ return {
153
+ key: k,
154
+ digest: hash(proof),
155
+ admission: { status: admission.status, rootId: admission.input.id, deadlineAt: admission.input.deadlineAt, resolutionId: admission.resolutionId },
156
+ root: root ? { status: root.status, callCount: root.callCount } : null,
157
+ accounting: accounting ? { costUsd: accounting.costUsd, reservedCalls: accounting.reservedCalls, settledCalls: accounting.settledCalls } : null,
158
+ calls,
159
+ pending,
160
+ blockers
161
+ };
162
+ }
163
+ async function barrier(intent, fn) {
164
+ if (!quiescence) return fail("permission_required");
165
+ let entered = false, active = true;
166
+ try {
167
+ return await quiescence.withQuiescence(structuredClone(intent), async () => {
168
+ if (!active || entered) return fail("permission_required");
169
+ entered = true;
170
+ return fn();
171
+ });
172
+ } finally {
173
+ active = false;
174
+ }
175
+ }
176
+ return {
177
+ inspect(value) {
178
+ return safe(() => snapshot(key(value)));
179
+ },
180
+ repair(value) {
181
+ return safe(async () => {
182
+ const k = key(value);
183
+ if (!recovery) return fail("permission_required");
184
+ return barrier({ action: "repair", key: k }, async () => {
185
+ if (!(await snapshot(k)).root) return fail("resolution_blocked");
186
+ const expired = {
187
+ admissions: (await admissions.reconcileExpired(k.scope, { limit: 100 })).length,
188
+ trees: (await step.trees.reconcileExpired(k.scope, { limit: 100 })).length,
189
+ executions: (await step.executions.reconcileExpired(k.scope, { limit: 100 })).length
190
+ };
191
+ const before = await snapshot(k);
192
+ for (const call of before.calls) if (call.state === "completed" || (call.state === "result_received" || call.state === "settled") && call.pricing === "ready") {
193
+ await recovery.recover({ scope: k.scope, rootKey: k.rootKey, operationKey: call.operationKey }, { leaseMs: 5e3 });
194
+ }
195
+ for (let after, scanned = 0; ; ) {
196
+ const page = await recovery.reconcileUsage(k, { limit: 100, ...after ? { after } : {} });
197
+ scanned += page.scanned;
198
+ if (page.scanned < 100) break;
199
+ if (!page.after || scanned >= 1e4 || equalExecution(after, page.after)) return fail("incomplete_inspection");
200
+ after = page.after;
201
+ }
202
+ return { sweepScope: k.scope, expired, snapshot: await snapshot(k) };
203
+ });
204
+ });
205
+ },
206
+ resolve(value) {
207
+ return safe(async () => {
208
+ const v = fields(value, ["key", "snapshotDigest", "resolutionId", "evidenceId"]), k = key(v.key);
209
+ const resolutionId = settlementIdentifier2(v.resolutionId), evidenceId = settlementIdentifier2(v.evidenceId);
210
+ if (typeof v.snapshotDigest !== "string" || !/^[a-f0-9]{64}$/.test(v.snapshotDigest)) return fail("invalid_request");
211
+ if (!operator) return fail("permission_required");
212
+ return barrier({ action: "resolve", key: k, resolutionId, evidenceId, snapshotDigest: v.snapshotDigest }, async () => {
213
+ const current = await snapshot(k);
214
+ if (current.admission.status === "released") {
215
+ if (current.admission.resolutionId !== resolutionId) return fail("binding_conflict");
216
+ return { status: "resolved", key: k, resolutionId };
217
+ }
218
+ if (current.digest !== v.snapshotDigest) return fail("stale_snapshot");
219
+ if (current.blockers.length) return fail("resolution_blocked");
220
+ try {
221
+ await operator.resolve(k.scope, k.rootKey, { resolutionId });
222
+ } catch {
223
+ }
224
+ const saved = await admissions.get(k.scope, k.rootKey);
225
+ if (!saved || saved.status !== "released" || saved.resolutionId !== resolutionId || saved.input.id !== current.admission.rootId || saved.input.sessionId !== k.sessionId || !equalExecution(saved.input.scope, k.scope) || saved.input.key !== k.rootKey) return fail("operation_failed");
226
+ return { status: "resolved", key: k, resolutionId };
227
+ });
228
+ });
229
+ }
230
+ };
231
+ }
232
+
233
+ export {
234
+ ConversationOperationError,
235
+ key,
236
+ resolution,
237
+ createConversationOperations
238
+ };
239
+ //# sourceMappingURL=chunk-AZVGB23H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/operations-input.ts","../src/operations.ts"],"sourcesContent":["import { settlementIdentifier, settlementScope, type Scope } from \"@alma-harness/core\";\nimport type { ConversationOperationKey, ConversationResolution } from \"./operations\";\nexport class ConversationOperationError extends Error {\n constructor(readonly code: \"invalid_request\" | \"binding_conflict\" | \"incomplete_inspection\" | \"permission_required\" | \"resolution_blocked\" | \"stale_snapshot\" | \"operation_failed\") {\n super(`Conversation operation: ${[\"invalid_request\", \"binding_conflict\", \"incomplete_inspection\", \"permission_required\", \"resolution_blocked\", \"stale_snapshot\", \"operation_failed\"].includes(code) ? code : \"operation_failed\"}`);\n if (![\"invalid_request\", \"binding_conflict\", \"incomplete_inspection\", \"permission_required\", \"resolution_blocked\", \"stale_snapshot\", \"operation_failed\"].includes(code)) this.code = \"operation_failed\";\n this.name = \"ConversationOperationError\";\n }\n}\nexport const fail = (code: ConversationOperationError[\"code\"]): never => { throw new ConversationOperationError(code); };\nexport function fields(value: unknown, keys: string[]): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return fail(\"invalid_request\");\n const descriptors = Object.getOwnPropertyDescriptors(value);\n if (Reflect.ownKeys(descriptors).some(k => typeof k !== \"string\" || !keys.includes(k) || !(\"value\" in descriptors[k]!))) return fail(\"invalid_request\");\n return Object.fromEntries(Object.entries(descriptors).map(([k, d]) => [k, d.value]));\n}\nexport function key(value: unknown): ConversationOperationKey {\n try { const v = fields(value, [\"scope\", \"sessionId\", \"rootKey\"]); return { scope: settlementScope(v.scope as Scope), sessionId: settlementIdentifier(v.sessionId), rootKey: settlementIdentifier(v.rootKey) }; }\n catch { return fail(\"invalid_request\"); }\n}\n\nexport function resolution(value: unknown): ConversationResolution {\n try {\n const v = fields(value, [\"key\", \"snapshotDigest\", \"resolutionId\", \"evidenceId\"]);\n if (typeof v.snapshotDigest !== \"string\" || !/^[a-f0-9]{64}$/.test(v.snapshotDigest)) return fail(\"invalid_request\");\n return { key: key(v.key), snapshotDigest: v.snapshotDigest, resolutionId: settlementIdentifier(v.resolutionId), evidenceId: settlementIdentifier(v.evidenceId) };\n } catch { return fail(\"invalid_request\"); }\n}\n","import { ConversationOperationError, fail, fields, key } from \"./operations-input\";\nexport { ConversationOperationError } from \"./operations-input\";\nimport { createHash } from \"node:crypto\";\nimport { equalExecution, executionSettlementRequest, settlementIdentifier, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { bindOperationCost, checkOperationCall, normalizeRootCallReceipt, type OperationSessionStore, type RootCallReceipt, type OperationCallRecord } from \"@alma-harness/execution\";\nimport type { createGovernedStepRunner } from \"@alma-harness/single-call\";\nimport type { RuntimeStores } from \"./index\";\n\nexport interface ConversationOperationKey { scope: Scope; sessionId: string; rootKey: string }\nexport interface ConversationResolution { key: ConversationOperationKey; snapshotDigest: string; resolutionId: string; evidenceId: string }\nexport type ConversationOperationIntent = { action: \"repair\"; key: ConversationOperationKey } | ({ action: \"resolve\" } & ConversationResolution);\n/** Trusted host infrastructure: maintain the barrier for the whole callback, after verifying workers, effects and operator intent. */\nexport interface ConversationQuiescence {\n withQuiescence<T>(intent: ConversationOperationIntent, operation: () => Promise<T>): Promise<T>;\n}\nexport interface ConversationOperationsOptions {\n stores: RuntimeStores;\n recovery?: Pick<ReturnType<typeof createGovernedStepRunner>, \"recover\" | \"reconcileUsage\">;\n operator?: Pick<OperationSessionStore, \"resolve\">;\n quiescence?: ConversationQuiescence;\n}\nfunction canonical(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(\",\")}}`;\n}\nconst hash = (value: unknown) => createHash(\"sha256\").update(canonical(value)).digest(\"hex\");\nasync function safe<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); } catch (error) { if (error instanceof ConversationOperationError) throw error; return fail(\"operation_failed\"); }\n}\n\n/** Inspection never reads content. Mutation has no default operator or quiescence authority. */\nexport function createConversationOperations(options: ConversationOperationsOptions) {\n const { stores, recovery, operator, quiescence } = options;\n const { admissions, step } = stores;\n async function snapshot(k: ConversationOperationKey) {\n const admission = await admissions.get(k.scope, k.rootKey);\n if (!admission || admission.input.sessionId !== k.sessionId || admission.input.key !== k.rootKey || !equalExecution(admission.input.scope, k.scope)) return fail(\"binding_conflict\");\n const root = await step.trees.get(k.scope, k.rootKey);\n if (root && !equalExecution(root.input, admission.input)) return fail(\"binding_conflict\");\n const members: OperationCallRecord[] = [], receipts: RootCallReceipt[] = [];\n if (root) {\n for (let afterOrdinal = 0;;) {\n const page = await step.trees.listCalls(k.scope, k.rootKey, { afterOrdinal, limit: 100 });\n for (const m of page) {\n if (m.ordinal !== members.length + 1 || m.rootId !== root.input.id || members.length >= root.input.maxCalls) return fail(\"incomplete_inspection\");\n checkOperationCall(root.input, m.input); members.push(m);\n }\n if (page.length < 100) break; afterOrdinal = page.at(-1)!.ordinal;\n }\n if (members.length !== root.callCount) return fail(\"incomplete_inspection\");\n for (let afterOrdinal = 0;;) {\n const page = await step.accounting.list(k.scope, k.rootKey, { afterOrdinal, limit: 100 });\n for (const raw of page) {\n const r = normalizeRootCallReceipt(raw);\n if (r.accountingOrdinal !== receipts.length + 1 || r.rootId !== root.input.id || receipts.length >= members.length || receipts.some(x => x.callId === r.callId)) return fail(\"binding_conflict\");\n if (r.previousUsd !== (receipts.at(-1)?.currentUsd ?? 0)) return fail(\"binding_conflict\");\n receipts.push(r);\n }\n if (page.length < 100) break; afterOrdinal = page.at(-1)!.accountingOrdinal;\n }\n }\n const accounting = await step.accounting.get(k.scope, k.rootKey);\n if (root && (!accounting || accounting.rootId !== root.input.id || accounting.rootStatus !== root.status || accounting.reservedCalls !== members.length || accounting.settledCalls !== receipts.length || accounting.costUsd !== (receipts.at(-1)?.currentUsd ?? 0))) return fail(\"binding_conflict\");\n if (!root && accounting) return fail(\"binding_conflict\");\n const calls = [], proof: unknown[] = [admission, root, receipts, accounting];\n for (const member of members) {\n const e = member.input.execution, journal = await step.executions.get(k.scope, e.operationKey), receipt = receipts.find(r => r.callId === e.callId);\n if (journal && !equalExecution(journal.input, e)) return fail(\"binding_conflict\");\n const source = await step.settlements.getGoverned(k.scope, e.settlementId);\n if (source) {\n bindOperationCost(root!.input, member, source);\n if (!journal || !equalExecution(source.request, executionSettlementRequest(journal)) || (journal.settlement && !equalExecution(journal.settlement, source.receipt))) return fail(\"binding_conflict\");\n }\n if (receipt && (!source || receipt.reservationOrdinal !== member.ordinal || receipt.settlementId !== e.settlementId || receipt.costUsd !== source.receipt.settlement.costUsd)) return fail(\"binding_conflict\");\n const complete = journal?.state === \"completed\" && !!journal.settlement && !!source && !!receipt;\n calls.push({ ordinal: member.ordinal, kind: member.input.kind, callId: e.callId, operationKey: e.operationKey, settlementId: e.settlementId,\n deadlineAt: e.deadlineAt, model: e.model, priceVersion: e.priceVersion, prices: e.prices, providerRequestId: journal?.providerRequestId, usage: journal?.evidence?.status === \"known\" ? journal.evidence.usage : undefined, state: journal?.state ?? \"missing\", evidence: journal?.evidence?.status ?? \"missing\", pricing: journal?.pricing?.status ?? \"missing\",\n accounted: complete, ...(receipt ? { costUsd: receipt.costUsd } : {}), recoveryUntil: journal?.recoveryUntil });\n proof.push(member, journal, source);\n }\n const pending = [];\n let after: { receivedAt: string; id: string } | undefined;\n for (let scanned = 0;;) {\n const page = await step.inbox.listPending(k.scope, { limit: 100, ...(after ? { after } : {}) });\n for (const row of page) {\n if (!equalExecution(row.input.execution.scope, k.scope)) return fail(\"binding_conflict\");\n const cursor = { receivedAt: row.receivedAt, id: row.input.id };\n if (after && (cursor.receivedAt < after.receivedAt || (cursor.receivedAt === after.receivedAt && cursor.id <= after.id))) return fail(\"incomplete_inspection\");\n after = cursor;\n const member = members.find(m => m.input.execution.operationKey === row.input.execution.operationKey);\n if (member) { proof.push(row); pending.push({ id: row.input.id, operationKey: row.input.execution.operationKey, receivedAt: row.receivedAt, evidence: row.input.evidence.status }); }\n }\n scanned += page.length;\n if (page.length < 100) break;\n if (scanned >= 10000) return fail(\"incomplete_inspection\");\n }\n if (!equalExecution(admission, await admissions.get(k.scope, k.rootKey)) || !equalExecution(root, await step.trees.get(k.scope, k.rootKey))) return fail(\"stale_snapshot\");\n const blockers = [\n ...(!root ? [\"root_missing\"] : []),\n ...(admission.status !== \"reconciliation_required\" ? [\"admission_not_uncertain\"] : []),\n ...(Date.now() < Date.parse(admission.input.deadlineAt) ? [\"deadline_not_expired\"] : []),\n ...(calls.some(c => !c.accounted) ? [\"incomplete_accounting\"] : []),\n ...(pending.length ? [\"pending_usage\"] : []),\n ];\n return { key: k, digest: hash(proof), admission: { status: admission.status, rootId: admission.input.id, deadlineAt: admission.input.deadlineAt, resolutionId: admission.resolutionId },\n root: root ? { status: root.status, callCount: root.callCount } : null,\n accounting: accounting ? { costUsd: accounting.costUsd, reservedCalls: accounting.reservedCalls, settledCalls: accounting.settledCalls } : null,\n calls, pending, blockers };\n }\n async function barrier<T>(intent: ConversationOperationIntent, fn: () => Promise<T>): Promise<T> {\n if (!quiescence) return fail(\"permission_required\");\n let entered = false, active = true;\n try {\n return await quiescence.withQuiescence(structuredClone(intent), async () => {\n if (!active || entered) return fail(\"permission_required\"); entered = true; return fn();\n });\n } finally { active = false; }\n }\n return {\n inspect(value: ConversationOperationKey) { return safe(() => snapshot(key(value))); },\n repair(value: ConversationOperationKey) { return safe(async () => {\n const k = key(value); if (!recovery) return fail(\"permission_required\");\n return barrier({ action: \"repair\", key: k }, async () => {\n if (!(await snapshot(k)).root) return fail(\"resolution_blocked\");\n const expired = { admissions: (await admissions.reconcileExpired(k.scope, { limit: 100 })).length,\n trees: (await step.trees.reconcileExpired(k.scope, { limit: 100 })).length,\n executions: (await step.executions.reconcileExpired(k.scope, { limit: 100 })).length };\n const before = await snapshot(k);\n for (const call of before.calls) if (call.state === \"completed\" || ((call.state === \"result_received\" || call.state === \"settled\") && call.pricing === \"ready\")) {\n await recovery.recover({ scope: k.scope, rootKey: k.rootKey, operationKey: call.operationKey }, { leaseMs: 5000 });\n }\n for (let after: { receivedAt: string; id: string } | undefined, scanned = 0;;) {\n const page = await recovery.reconcileUsage(k, { limit: 100, ...(after ? { after } : {}) }); scanned += page.scanned;\n if (page.scanned < 100) break;\n if (!page.after || scanned >= 10000 || equalExecution(after, page.after)) return fail(\"incomplete_inspection\"); after = page.after;\n }\n return { sweepScope: k.scope, expired, snapshot: await snapshot(k) };\n });\n }); },\n resolve(value: ConversationResolution) { return safe(async () => {\n const v = fields(value, [\"key\", \"snapshotDigest\", \"resolutionId\", \"evidenceId\"]), k = key(v.key);\n const resolutionId = settlementIdentifier(v.resolutionId), evidenceId = settlementIdentifier(v.evidenceId);\n if (typeof v.snapshotDigest !== \"string\" || !/^[a-f0-9]{64}$/.test(v.snapshotDigest)) return fail(\"invalid_request\");\n if (!operator) return fail(\"permission_required\");\n return barrier({ action: \"resolve\", key: k, resolutionId, evidenceId, snapshotDigest: v.snapshotDigest }, async () => {\n const current = await snapshot(k);\n if (current.admission.status === \"released\") { if (current.admission.resolutionId !== resolutionId) return fail(\"binding_conflict\"); return { status: \"resolved\" as const, key: k, resolutionId }; }\n if (current.digest !== v.snapshotDigest) return fail(\"stale_snapshot\");\n if (current.blockers.length) return fail(\"resolution_blocked\");\n try { await operator.resolve(k.scope, k.rootKey, { resolutionId }); }\n catch { /* Only verified readback of this exact resolution can confirm a lost ACK. */ }\n const saved = await admissions.get(k.scope, k.rootKey);\n if (!saved || saved.status !== \"released\" || saved.resolutionId !== resolutionId || saved.input.id !== current.admission.rootId || saved.input.sessionId !== k.sessionId || !equalExecution(saved.input.scope, k.scope) || saved.input.key !== k.rootKey) return fail(\"operation_failed\");\n return { status: \"resolved\" as const, key: k, resolutionId };\n });\n }); },\n };\n}\n"],"mappings":";AAAA,SAAS,sBAAsB,uBAAmC;AAE3D,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAAqB,MAA+J;AAClL,UAAM,2BAA2B,CAAC,mBAAmB,oBAAoB,yBAAyB,uBAAuB,sBAAsB,kBAAkB,kBAAkB,EAAE,SAAS,IAAI,IAAI,OAAO,kBAAkB,EAAE;AAD9M;AAEnB,QAAI,CAAC,CAAC,mBAAmB,oBAAoB,yBAAyB,uBAAuB,sBAAsB,kBAAkB,kBAAkB,EAAE,SAAS,IAAI,EA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,oBAAoB;AAC7D,cAAI;AAAE,kBAAM,SAAS,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC;AAAA,UAAG,QAC9D;AAAA,UAAgF;AACtF,gBAAM,QAAQ,MAAM,WAAW,IAAI,EAAE,OAAO,EAAE,OAAO;AACrD,cAAI,CAAC,SAAS,MAAM,WAAW,cAAc,MAAM,iBAAiB,gBAAgB,MAAM,MAAM,OAAO,QAAQ,UAAU,UAAU,MAAM,MAAM,cAAc,EAAE,aAAa,CAAC,eAAe,MAAM,MAAM,OAAO,EAAE,KAAK,KAAK,MAAM,MAAM,QAAQ,EAAE,QAAS,QAAO,KAAK,kBAAkB;AACxR,iBAAO,EAAE,QAAQ,YAAqB,KAAK,GAAG,aAAa;AAAA,QAC7D,CAAC;AAAA,MACH,CAAC;AAAA,IAAG;AAAA,EACN;AACF;","names":["settlementIdentifier"]}
@@ -0,0 +1,17 @@
1
+ import { ExecutionResultPolicy } from '@alma-harness/core';
2
+ import { ConversationConfig } from '@alma-harness/conversation';
3
+
4
+ interface RuntimePolicies {
5
+ stepResultPolicy: ExecutionResultPolicy;
6
+ rootResultPolicy: ExecutionResultPolicy;
7
+ }
8
+ type RuntimeStores = Pick<ConversationConfig, "sessions" | "admissions" | "rootResults"> & {
9
+ step: Pick<ConversationConfig["step"], "executions" | "results" | "inbox" | "settlements" | "spend" | "trees" | "accounting">;
10
+ };
11
+ interface Runtime {
12
+ stores: RuntimeStores;
13
+ /** Quiesce workers first. Resource cleanup never erases content or resolves admission. */
14
+ close(): Promise<void>;
15
+ }
16
+
17
+ export type { Runtime, RuntimePolicies, RuntimeStores };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,8 @@
1
+ import { RuntimePolicies, Runtime } from './index.js';
2
+ import '@alma-harness/core';
3
+ import '@alma-harness/conversation';
4
+
5
+ /** Ephemeral reference composition. Reconstructing it loses all data and execution history. */
6
+ declare function createMemoryRuntime(value: RuntimePolicies): Runtime;
7
+
8
+ export { createMemoryRuntime };
package/dist/memory.js ADDED
@@ -0,0 +1,33 @@
1
+ import {
2
+ policies
3
+ } from "./chunk-3OEFEOI4.js";
4
+
5
+ // src/memory.ts
6
+ import { InMemoryExecutionStore, InMemorySessionStore } from "@alma-harness/core/testing";
7
+ import { InMemoryOperationSessionStore, InMemoryOperationTreeStore, InMemoryOperationAccountingStore, InMemoryUsageInbox, InMemoryGovernedCostSettlementStore } from "@alma-harness/execution/testing";
8
+ import { InMemoryExecutionResultStore } from "@alma-harness/memory/testing";
9
+ function createMemoryRuntime(value) {
10
+ const p = policies(value), settlements = new InMemoryGovernedCostSettlementStore(), trees = new InMemoryOperationTreeStore();
11
+ return {
12
+ stores: {
13
+ sessions: new InMemorySessionStore(),
14
+ admissions: new InMemoryOperationSessionStore(),
15
+ rootResults: new InMemoryExecutionResultStore(p.rootResultPolicy),
16
+ step: {
17
+ executions: new InMemoryExecutionStore(),
18
+ results: new InMemoryExecutionResultStore(p.stepResultPolicy),
19
+ inbox: new InMemoryUsageInbox(),
20
+ settlements,
21
+ spend: settlements,
22
+ trees,
23
+ accounting: new InMemoryOperationAccountingStore(trees, settlements)
24
+ }
25
+ },
26
+ async close() {
27
+ }
28
+ };
29
+ }
30
+ export {
31
+ createMemoryRuntime
32
+ };
33
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryExecutionStore, InMemorySessionStore } from \"@alma-harness/core/testing\";\nimport { InMemoryOperationSessionStore, InMemoryOperationTreeStore, InMemoryOperationAccountingStore, InMemoryUsageInbox, InMemoryGovernedCostSettlementStore } from \"@alma-harness/execution/testing\";\nimport { InMemoryExecutionResultStore } from \"@alma-harness/memory/testing\";\nimport type { Runtime, RuntimePolicies } from \"./index\";\nimport { policies } from \"./policies\";\n/** Ephemeral reference composition. Reconstructing it loses all data and execution history. */\nexport function createMemoryRuntime(value: RuntimePolicies): Runtime {\n const p = policies(value), settlements = new InMemoryGovernedCostSettlementStore(), trees = new InMemoryOperationTreeStore();\n return {\n stores: {\n sessions: new InMemorySessionStore(), admissions: new InMemoryOperationSessionStore(),\n rootResults: new InMemoryExecutionResultStore(p.rootResultPolicy),\n step: { executions: new InMemoryExecutionStore(), results: new InMemoryExecutionResultStore(p.stepResultPolicy), inbox: new InMemoryUsageInbox(),\n settlements, spend: settlements, trees, accounting: new InMemoryOperationAccountingStore(trees, settlements) },\n },\n async close() {},\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,wBAAwB,4BAA4B;AAC7D,SAAS,+BAA+B,4BAA4B,kCAAkC,oBAAoB,2CAA2C;AACrK,SAAS,oCAAoC;AAItC,SAAS,oBAAoB,OAAiC;AACnE,QAAM,IAAI,SAAS,KAAK,GAAG,cAAc,IAAI,oCAAoC,GAAG,QAAQ,IAAI,2BAA2B;AAC3H,SAAO;AAAA,IACL,QAAQ;AAAA,MACN,UAAU,IAAI,qBAAqB;AAAA,MAAG,YAAY,IAAI,8BAA8B;AAAA,MACpF,aAAa,IAAI,6BAA6B,EAAE,gBAAgB;AAAA,MAChE,MAAM;AAAA,QAAE,YAAY,IAAI,uBAAuB;AAAA,QAAG,SAAS,IAAI,6BAA6B,EAAE,gBAAgB;AAAA,QAAG,OAAO,IAAI,mBAAmB;AAAA,QAC7I;AAAA,QAAa,OAAO;AAAA,QAAa;AAAA,QAAO,YAAY,IAAI,iCAAiC,OAAO,WAAW;AAAA,MAAE;AAAA,IACjH;AAAA,IACA,MAAM,QAAQ;AAAA,IAAC;AAAA,EACjB;AACF;","names":[]}
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { createConversationOperations } from './operations.js';
3
+ import '@alma-harness/core';
4
+ import '@alma-harness/execution';
5
+ import '@alma-harness/single-call';
6
+ import './index.js';
7
+ import '@alma-harness/conversation';
8
+
9
+ type Operations = ReturnType<typeof createConversationOperations>;
10
+ interface ConversationOperationsHost {
11
+ operations: Operations;
12
+ close(): Promise<void>;
13
+ }
14
+ declare function runConversationOperationsCli(args: string[], io: {
15
+ input: AsyncIterable<string | Uint8Array>;
16
+ output(text: string): void;
17
+ loadHost(path: string): Promise<ConversationOperationsHost>;
18
+ }): Promise<number>;
19
+
20
+ export { type ConversationOperationsHost, runConversationOperationsCli };
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ConversationOperationError,
4
+ key,
5
+ resolution
6
+ } from "./chunk-AZVGB23H.js";
7
+
8
+ // src/operations-cli.ts
9
+ import { realpathSync } from "fs";
10
+ import { pathToFileURL } from "url";
11
+ import { resolve } from "path";
12
+ var help = "alma-operations <inspect|repair|resolve> --host <trusted-local-module>\nRead one scoped JSON request from stdin. Host owns credentials, operator authorization and maintained quiescence.\n";
13
+ async function runConversationOperationsCli(args, io) {
14
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "help")) {
15
+ io.output(help);
16
+ return 0;
17
+ }
18
+ let host;
19
+ let code = 0, response;
20
+ try {
21
+ const command = args[0];
22
+ if (args.length !== 3 || !["inspect", "repair", "resolve"].includes(command ?? "") || args[1] !== "--host" || !args[2] || /^[a-z][a-z0-9+.-]*:/i.test(args[2]) || args[2].includes("\0")) throw new ConversationOperationError("invalid_request");
23
+ let bytes = 0;
24
+ const parts = [];
25
+ for await (const chunk of io.input) {
26
+ const b = Buffer.from(chunk);
27
+ bytes += b.length;
28
+ if (bytes > 65536) throw new ConversationOperationError("invalid_request");
29
+ parts.push(b);
30
+ }
31
+ let request;
32
+ try {
33
+ request = JSON.parse(Buffer.concat(parts).toString("utf8"));
34
+ } catch {
35
+ throw new ConversationOperationError("invalid_request");
36
+ }
37
+ request = command === "resolve" ? resolution(request) : key(request);
38
+ host = await io.loadHost(resolve(args[2]));
39
+ if (!host || typeof host.close !== "function" || !host.operations) throw new ConversationOperationError("invalid_request");
40
+ if (command === "inspect") response = await host.operations.inspect(request);
41
+ else if (command === "repair") response = await host.operations.repair(request);
42
+ else response = await host.operations.resolve(request);
43
+ const text = JSON.stringify(response);
44
+ if (typeof text !== "string" || Buffer.byteLength(text) > 1e6) throw new ConversationOperationError("incomplete_inspection");
45
+ } catch (error) {
46
+ const kind = error instanceof ConversationOperationError ? error.code : "operation_failed";
47
+ response = { error: kind };
48
+ code = kind === "invalid_request" ? 2 : 3;
49
+ } finally {
50
+ if (host) try {
51
+ await host.close();
52
+ } catch {
53
+ code = 3;
54
+ response = { error: "operation_failed" };
55
+ }
56
+ }
57
+ io.output(`${JSON.stringify(response)}
58
+ `);
59
+ return code;
60
+ }
61
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
62
+ process.exitCode = await runConversationOperationsCli(process.argv.slice(2), {
63
+ input: process.stdin,
64
+ output: (text) => {
65
+ process.stdout.write(text);
66
+ },
67
+ async loadHost(path) {
68
+ const module = await import(pathToFileURL(path).href);
69
+ return await module.createOperationsHost();
70
+ }
71
+ });
72
+ }
73
+ export {
74
+ runConversationOperationsCli
75
+ };
76
+ //# sourceMappingURL=operations-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/operations-cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { key, resolution } from \"./operations-input\";\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolve } from \"node:path\";\nimport { ConversationOperationError, type createConversationOperations } from \"./operations\";\ntype Operations = ReturnType<typeof createConversationOperations>;\nexport interface ConversationOperationsHost { operations: Operations; close(): Promise<void> }\nconst help = \"alma-operations <inspect|repair|resolve> --host <trusted-local-module>\\nRead one scoped JSON request from stdin. Host owns credentials, operator authorization and maintained quiescence.\\n\";\nexport async function runConversationOperationsCli(args: string[], io: {\n input: AsyncIterable<string | Uint8Array>; output(text: string): void;\n loadHost(path: string): Promise<ConversationOperationsHost>;\n}): Promise<number> {\n if (args.length === 1 && (args[0] === \"--help\" || args[0] === \"help\")) { io.output(help); return 0; }\n let host: ConversationOperationsHost | undefined;\n let code = 0, response: unknown;\n try {\n const command = args[0];\n if (args.length !== 3 || ![\"inspect\", \"repair\", \"resolve\"].includes(command ?? \"\") || args[1] !== \"--host\" || !args[2] || /^[a-z][a-z0-9+.-]*:/i.test(args[2]) || args[2].includes(\"\\0\")) throw new ConversationOperationError(\"invalid_request\");\n let bytes = 0; const parts: Buffer[] = [];\n for await (const chunk of io.input) { const b = Buffer.from(chunk); bytes += b.length; if (bytes > 65536) throw new ConversationOperationError(\"invalid_request\"); parts.push(b); }\n let request: unknown;\n try { request = JSON.parse(Buffer.concat(parts).toString(\"utf8\")); } catch { throw new ConversationOperationError(\"invalid_request\"); }\n request = command === \"resolve\" ? resolution(request) : key(request);\n host = await io.loadHost(resolve(args[2]));\n if (!host || typeof host.close !== \"function\" || !host.operations) throw new ConversationOperationError(\"invalid_request\");\n if (command === \"inspect\") response = await host.operations.inspect(request as Parameters<Operations[\"inspect\"]>[0]);\n else if (command === \"repair\") response = await host.operations.repair(request as Parameters<Operations[\"repair\"]>[0]);\n else response = await host.operations.resolve(request as Parameters<Operations[\"resolve\"]>[0]);\n const text = JSON.stringify(response);\n if (typeof text !== \"string\" || Buffer.byteLength(text) > 1_000_000) throw new ConversationOperationError(\"incomplete_inspection\");\n } catch (error) {\n const kind = error instanceof ConversationOperationError ? error.code : \"operation_failed\";\n response = { error: kind }; code = kind === \"invalid_request\" ? 2 : 3;\n } finally {\n if (host) try { await host.close(); } catch { code = 3; response = { error: \"operation_failed\" }; }\n }\n io.output(`${JSON.stringify(response)}\\n`); return code;\n}\n// Importing the subpath does not load a host or touch stdin.\nif (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {\n process.exitCode = await runConversationOperationsCli(process.argv.slice(2), {\n input: process.stdin, output: text => { process.stdout.write(text); },\n async loadHost(path) { const module = await import(pathToFileURL(path).href); return await module.createOperationsHost(); },\n });\n}\n"],"mappings":";;;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,YAAY,SAAU,YAAW,MAAM,KAAK,WAAW,OAAO,OAA8C;AAAA,QAChH,YAAW,MAAM,KAAK,WAAW,QAAQ,OAA+C;AAC7F,UAAM,OAAO,KAAK,UAAU,QAAQ;AACpC,QAAI,OAAO,SAAS,YAAY,OAAO,WAAW,IAAI,IAAI,IAAW,OAAM,IAAI,2BAA2B,uBAAuB;AAAA,EACnI,SAAS,OAAO;AACd,UAAM,OAAO,iBAAiB,6BAA6B,MAAM,OAAO;AACxE,eAAW,EAAE,OAAO,KAAK;AAAG,WAAO,SAAS,oBAAoB,IAAI;AAAA,EACtE,UAAE;AACA,QAAI,KAAM,KAAI;AAAE,YAAM,KAAK,MAAM;AAAA,IAAG,QAAQ;AAAE,aAAO;AAAG,iBAAW,EAAE,OAAO,mBAAmB;AAAA,IAAG;AAAA,EACpG;AACA,KAAG,OAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,CAAI;AAAG,SAAO;AACrD;AAEA,IAAI,QAAQ,KAAK,CAAC,KAAK,YAAY,QAAQ,cAAc,aAAa,QAAQ,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM;AAC5F,UAAQ,WAAW,MAAM,6BAA6B,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,IAC3E,OAAO,QAAQ;AAAA,IAAO,QAAQ,UAAQ;AAAE,cAAQ,OAAO,MAAM,IAAI;AAAA,IAAG;AAAA,IACpE,MAAM,SAAS,MAAM;AAAE,YAAM,SAAS,MAAM,OAAO,cAAc,IAAI,EAAE;AAAO,aAAO,MAAM,OAAO,qBAAqB;AAAA,IAAG;AAAA,EAC5H,CAAC;AACH;","names":[]}
@@ -0,0 +1,147 @@
1
+ import * as _alma_harness_core from '@alma-harness/core';
2
+ import { Scope } from '@alma-harness/core';
3
+ import { OperationSessionStore } from '@alma-harness/execution';
4
+ import { createGovernedStepRunner } from '@alma-harness/single-call';
5
+ import { RuntimeStores } from './index.js';
6
+ import '@alma-harness/conversation';
7
+
8
+ declare class ConversationOperationError extends Error {
9
+ readonly code: "invalid_request" | "binding_conflict" | "incomplete_inspection" | "permission_required" | "resolution_blocked" | "stale_snapshot" | "operation_failed";
10
+ constructor(code: "invalid_request" | "binding_conflict" | "incomplete_inspection" | "permission_required" | "resolution_blocked" | "stale_snapshot" | "operation_failed");
11
+ }
12
+
13
+ interface ConversationOperationKey {
14
+ scope: Scope;
15
+ sessionId: string;
16
+ rootKey: string;
17
+ }
18
+ interface ConversationResolution {
19
+ key: ConversationOperationKey;
20
+ snapshotDigest: string;
21
+ resolutionId: string;
22
+ evidenceId: string;
23
+ }
24
+ type ConversationOperationIntent = {
25
+ action: "repair";
26
+ key: ConversationOperationKey;
27
+ } | ({
28
+ action: "resolve";
29
+ } & ConversationResolution);
30
+ /** Trusted host infrastructure: maintain the barrier for the whole callback, after verifying workers, effects and operator intent. */
31
+ interface ConversationQuiescence {
32
+ withQuiescence<T>(intent: ConversationOperationIntent, operation: () => Promise<T>): Promise<T>;
33
+ }
34
+ interface ConversationOperationsOptions {
35
+ stores: RuntimeStores;
36
+ recovery?: Pick<ReturnType<typeof createGovernedStepRunner>, "recover" | "reconcileUsage">;
37
+ operator?: Pick<OperationSessionStore, "resolve">;
38
+ quiescence?: ConversationQuiescence;
39
+ }
40
+ /** Inspection never reads content. Mutation has no default operator or quiescence authority. */
41
+ declare function createConversationOperations(options: ConversationOperationsOptions): {
42
+ inspect(value: ConversationOperationKey): Promise<{
43
+ key: ConversationOperationKey;
44
+ digest: string;
45
+ admission: {
46
+ status: "reconciliation_required" | "active" | "released";
47
+ rootId: string;
48
+ deadlineAt: string;
49
+ resolutionId: string | undefined;
50
+ };
51
+ root: {
52
+ status: "reconciliation_required" | "active" | "closed";
53
+ callCount: number;
54
+ } | null;
55
+ accounting: {
56
+ costUsd: number;
57
+ reservedCalls: number;
58
+ settledCalls: number;
59
+ } | null;
60
+ calls: {
61
+ recoveryUntil: string | undefined;
62
+ costUsd?: number;
63
+ ordinal: number;
64
+ kind: "main" | "direct" | "delegate" | "summary";
65
+ callId: string;
66
+ operationKey: string;
67
+ settlementId: string;
68
+ deadlineAt: string;
69
+ model: _alma_harness_core.ModelRef;
70
+ priceVersion: string;
71
+ prices: _alma_harness_core.ModelPrice[];
72
+ providerRequestId: string | undefined;
73
+ usage: _alma_harness_core.Usage | undefined;
74
+ state: string;
75
+ evidence: string;
76
+ pricing: string;
77
+ accounted: boolean;
78
+ }[];
79
+ pending: {
80
+ id: string;
81
+ operationKey: string;
82
+ receivedAt: string;
83
+ evidence: "known" | "unpriced" | "not_dispatched" | "unknown";
84
+ }[];
85
+ blockers: string[];
86
+ }>;
87
+ repair(value: ConversationOperationKey): Promise<{
88
+ sweepScope: Scope;
89
+ expired: {
90
+ admissions: number;
91
+ trees: number;
92
+ executions: number;
93
+ };
94
+ snapshot: {
95
+ key: ConversationOperationKey;
96
+ digest: string;
97
+ admission: {
98
+ status: "reconciliation_required" | "active" | "released";
99
+ rootId: string;
100
+ deadlineAt: string;
101
+ resolutionId: string | undefined;
102
+ };
103
+ root: {
104
+ status: "reconciliation_required" | "active" | "closed";
105
+ callCount: number;
106
+ } | null;
107
+ accounting: {
108
+ costUsd: number;
109
+ reservedCalls: number;
110
+ settledCalls: number;
111
+ } | null;
112
+ calls: {
113
+ recoveryUntil: string | undefined;
114
+ costUsd?: number;
115
+ ordinal: number;
116
+ kind: "main" | "direct" | "delegate" | "summary";
117
+ callId: string;
118
+ operationKey: string;
119
+ settlementId: string;
120
+ deadlineAt: string;
121
+ model: _alma_harness_core.ModelRef;
122
+ priceVersion: string;
123
+ prices: _alma_harness_core.ModelPrice[];
124
+ providerRequestId: string | undefined;
125
+ usage: _alma_harness_core.Usage | undefined;
126
+ state: string;
127
+ evidence: string;
128
+ pricing: string;
129
+ accounted: boolean;
130
+ }[];
131
+ pending: {
132
+ id: string;
133
+ operationKey: string;
134
+ receivedAt: string;
135
+ evidence: "known" | "unpriced" | "not_dispatched" | "unknown";
136
+ }[];
137
+ blockers: string[];
138
+ };
139
+ }>;
140
+ resolve(value: ConversationResolution): Promise<{
141
+ status: "resolved";
142
+ key: ConversationOperationKey;
143
+ resolutionId: string;
144
+ }>;
145
+ };
146
+
147
+ export { ConversationOperationError, type ConversationOperationIntent, type ConversationOperationKey, type ConversationOperationsOptions, type ConversationQuiescence, type ConversationResolution, createConversationOperations };
@@ -0,0 +1,9 @@
1
+ import {
2
+ ConversationOperationError,
3
+ createConversationOperations
4
+ } from "./chunk-AZVGB23H.js";
5
+ export {
6
+ ConversationOperationError,
7
+ createConversationOperations
8
+ };
9
+ //# sourceMappingURL=operations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,23 @@
1
+ import { RuntimePolicies, Runtime } from './index.js';
2
+ import '@alma-harness/core';
3
+ import '@alma-harness/conversation';
4
+
5
+ interface PostgresRuntimeNamespace {
6
+ connectionString: string;
7
+ schema: string;
8
+ rootSchema: string;
9
+ onPoolError: (error: Error, schema: string) => void;
10
+ }
11
+ type PostgresRuntimeOptions = PostgresRuntimeNamespace & RuntimePolicies & {
12
+ /** Per owned pool, not per turn. Omission keeps five connections in each pool. */
13
+ poolMax?: {
14
+ execution: number;
15
+ roots: number;
16
+ };
17
+ };
18
+ /** No connections, migrations or grants occur at construction. Owned pools pin both namespaces. */
19
+ declare function createPostgresRuntime(value: PostgresRuntimeOptions): Runtime;
20
+ /** Explicit administrator operation. Partial installation may be rerun; no login memberships are granted. */
21
+ declare function migratePostgresRuntime(value: PostgresRuntimeNamespace): Promise<void>;
22
+
23
+ export { type PostgresRuntimeNamespace, type PostgresRuntimeOptions, createPostgresRuntime, migratePostgresRuntime };
@@ -0,0 +1,106 @@
1
+ import {
2
+ policies
3
+ } from "./chunk-3OEFEOI4.js";
4
+
5
+ // src/postgres.ts
6
+ import pg from "pg";
7
+ import {
8
+ PostgresSessionStore,
9
+ PostgresExecutionStore,
10
+ PostgresExecutionResultStore,
11
+ PostgresUsageInbox,
12
+ PostgresCostSettlementStore,
13
+ PostgresSpendStore,
14
+ migrateSessionStore,
15
+ migrateExecutionStore,
16
+ migrateExecutionResultStore,
17
+ migrateUsageInbox
18
+ } from "@alma-harness/postgres";
19
+ import { PostgresOperationSessionStore, PostgresOperationTreeStore, PostgresOperationAccountingStore, migrateOperationAccountingStore, migrateOperationSessionStore } from "@alma-harness/postgres-execution";
20
+ function limits(value) {
21
+ if (value === void 0) return { execution: 5, roots: 5 };
22
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid runtime pool limits");
23
+ const fields = Object.getOwnPropertyDescriptors(value), keys = Reflect.ownKeys(fields);
24
+ if (keys.length !== 2 || !keys.includes("execution") || !keys.includes("roots")) throw new TypeError("Invalid runtime pool limits");
25
+ const execution = fields.execution?.value, roots = fields.roots?.value;
26
+ if (!Number.isSafeInteger(execution) || execution < 1 || !Number.isSafeInteger(roots) || roots < 1 || !Number.isSafeInteger(execution + roots)) throw new TypeError("Invalid runtime pool limits");
27
+ return { execution, roots };
28
+ }
29
+ function namespace(value) {
30
+ const { connectionString, schema, rootSchema, onPoolError } = value;
31
+ if (typeof onPoolError !== "function") throw new TypeError("Runtime requires onPoolError reporting");
32
+ for (const s of [schema, rootSchema]) {
33
+ if (typeof s !== "string" || !/^[a-z_][a-z0-9_]{0,62}$/.test(s) || s === "public" || s === "information_schema" || s.startsWith("pg_")) throw new TypeError("Invalid dedicated runtime schema");
34
+ }
35
+ if (schema === rootSchema) throw new TypeError("Runtime result namespaces must be distinct");
36
+ let url;
37
+ try {
38
+ url = new URL(connectionString);
39
+ } catch {
40
+ throw new TypeError("Invalid PostgreSQL connection URL");
41
+ }
42
+ if (!["postgres:", "postgresql:"].includes(url.protocol) || !url.hostname || url.searchParams.has("options")) throw new TypeError("Runtime requires a PostgreSQL URL without startup options");
43
+ return { connectionString, schema, rootSchema, onPoolError };
44
+ }
45
+ function pools(n, max) {
46
+ const open = (schema, size) => {
47
+ const pool = new pg.Pool({
48
+ connectionString: n.connectionString,
49
+ options: `-c search_path=${schema} -c extra_float_digits=3`,
50
+ max: size,
51
+ connectionTimeoutMillis: 5e3,
52
+ idleTimeoutMillis: 1e4
53
+ });
54
+ pool.on("error", (error) => n.onPoolError(error, schema));
55
+ return pool;
56
+ };
57
+ const execution = open(n.schema, max.execution), roots = open(n.rootSchema, max.roots);
58
+ let closing;
59
+ return { execution, roots, close() {
60
+ return closing ??= Promise.allSettled([Promise.resolve().then(() => execution.end()), Promise.resolve().then(() => roots.end())]).then((results) => {
61
+ const errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
62
+ if (errors.length) throw new AggregateError(errors, "Runtime pool cleanup failed");
63
+ });
64
+ } };
65
+ }
66
+ function createPostgresRuntime(value) {
67
+ const n = namespace(value), p = policies(value), max = limits(value.poolMax), owned = pools(n, max);
68
+ return { stores: {
69
+ sessions: new PostgresSessionStore(owned.execution),
70
+ admissions: new PostgresOperationSessionStore(owned.execution),
71
+ rootResults: new PostgresExecutionResultStore(owned.roots, p.rootResultPolicy),
72
+ step: {
73
+ executions: new PostgresExecutionStore(owned.execution),
74
+ results: new PostgresExecutionResultStore(owned.execution, p.stepResultPolicy),
75
+ inbox: new PostgresUsageInbox(owned.execution),
76
+ settlements: new PostgresCostSettlementStore(owned.execution),
77
+ spend: new PostgresSpendStore(owned.execution),
78
+ trees: new PostgresOperationTreeStore(owned.execution),
79
+ accounting: new PostgresOperationAccountingStore(owned.execution)
80
+ }
81
+ }, close: owned.close };
82
+ }
83
+ async function migratePostgresRuntime(value) {
84
+ const n = namespace(value), owned = pools(n, { execution: 1, roots: 1 });
85
+ try {
86
+ await owned.execution.query(`create schema if not exists ${n.schema}`);
87
+ await owned.roots.query(`create schema if not exists ${n.rootSchema}`);
88
+ await migrateSessionStore(owned.execution);
89
+ await migrateExecutionStore(owned.execution);
90
+ await migrateExecutionResultStore(owned.execution);
91
+ await migrateUsageInbox(owned.execution);
92
+ await migrateOperationAccountingStore(owned.execution);
93
+ await migrateOperationSessionStore(owned.execution);
94
+ await migrateExecutionResultStore(owned.roots);
95
+ for (const [pool, schema] of [[owned.execution, n.schema], [owned.roots, n.rootSchema]]) {
96
+ await pool.query(`grant usage on schema ${schema} to alma_app, alma_retention; revoke create on schema ${schema} from public, alma_app, alma_retention`);
97
+ }
98
+ } finally {
99
+ await owned.close();
100
+ }
101
+ }
102
+ export {
103
+ createPostgresRuntime,
104
+ migratePostgresRuntime
105
+ };
106
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/postgres.ts"],"sourcesContent":["import pg from \"pg\";\nimport { PostgresSessionStore, PostgresExecutionStore, PostgresExecutionResultStore, PostgresUsageInbox, PostgresCostSettlementStore, PostgresSpendStore,\n migrateSessionStore, migrateExecutionStore, migrateExecutionResultStore, migrateUsageInbox } from \"@alma-harness/postgres\";\nimport { PostgresOperationSessionStore, PostgresOperationTreeStore, PostgresOperationAccountingStore, migrateOperationAccountingStore, migrateOperationSessionStore } from \"@alma-harness/postgres-execution\";\nimport type { Runtime, RuntimePolicies } from \"./index\";\nimport { policies } from \"./policies\";\nexport interface PostgresRuntimeNamespace { connectionString: string; schema: string; rootSchema: string; onPoolError: (error: Error, schema: string) => void }\nexport type PostgresRuntimeOptions = PostgresRuntimeNamespace & RuntimePolicies & {\n /** Per owned pool, not per turn. Omission keeps five connections in each pool. */\n poolMax?: { execution: number; roots: number };\n};\nfunction limits(value: unknown): { execution: number; roots: number } {\n if(value===undefined)return {execution:5,roots:5};\n if(!value || typeof value!==\"object\" || Array.isArray(value))throw new TypeError(\"Invalid runtime pool limits\");\n const fields=Object.getOwnPropertyDescriptors(value),keys=Reflect.ownKeys(fields);\n if(keys.length!==2 || !keys.includes(\"execution\") || !keys.includes(\"roots\"))throw new TypeError(\"Invalid runtime pool limits\");\n const execution=fields.execution?.value,roots=fields.roots?.value;\n if(!Number.isSafeInteger(execution) || execution<1 || !Number.isSafeInteger(roots) || roots<1 || !Number.isSafeInteger(execution+roots))throw new TypeError(\"Invalid runtime pool limits\");\n return {execution,roots};\n}\nfunction namespace(value: PostgresRuntimeNamespace): PostgresRuntimeNamespace {\n const { connectionString, schema, rootSchema, onPoolError } = value;\n if (typeof onPoolError !== \"function\") throw new TypeError(\"Runtime requires onPoolError reporting\");\n for (const s of [schema, rootSchema]) {\n if (typeof s !== \"string\" || !/^[a-z_][a-z0-9_]{0,62}$/.test(s) || s === \"public\" || s === \"information_schema\" || s.startsWith(\"pg_\")) throw new TypeError(\"Invalid dedicated runtime schema\");\n }\n if (schema === rootSchema) throw new TypeError(\"Runtime result namespaces must be distinct\");\n let url: URL;\n try { url = new URL(connectionString); } catch { throw new TypeError(\"Invalid PostgreSQL connection URL\"); }\n if (![\"postgres:\", \"postgresql:\"].includes(url.protocol) || !url.hostname || url.searchParams.has(\"options\")) throw new TypeError(\"Runtime requires a PostgreSQL URL without startup options\");\n return { connectionString, schema, rootSchema, onPoolError };\n}\nfunction pools(n: PostgresRuntimeNamespace, max: { execution: number; roots: number }) {\n const open = (schema: string, size: number) => {\n const pool = new pg.Pool({ connectionString: n.connectionString,\n options: `-c search_path=${schema} -c extra_float_digits=3`, max: size, connectionTimeoutMillis: 5000, idleTimeoutMillis: 10000 });\n pool.on(\"error\", error => n.onPoolError(error, schema));\n return pool;\n };\n const execution = open(n.schema,max.execution), roots = open(n.rootSchema,max.roots);\n let closing: Promise<void> | undefined;\n return { execution, roots, close() {\n return closing ??= Promise.allSettled([Promise.resolve().then(() => execution.end()), Promise.resolve().then(() => roots.end())]).then(results => {\n const errors = results.flatMap(r => r.status === \"rejected\" ? [r.reason] : []);\n if (errors.length) throw new AggregateError(errors, \"Runtime pool cleanup failed\");\n });\n } };\n}\n/** No connections, migrations or grants occur at construction. Owned pools pin both namespaces. */\nexport function createPostgresRuntime(value: PostgresRuntimeOptions): Runtime {\n const n = namespace(value), p = policies(value), max = limits(value.poolMax), owned = pools(n,max);\n return { stores: {\n sessions: new PostgresSessionStore(owned.execution), admissions: new PostgresOperationSessionStore(owned.execution),\n rootResults: new PostgresExecutionResultStore(owned.roots, p.rootResultPolicy),\n step: { executions: new PostgresExecutionStore(owned.execution), results: new PostgresExecutionResultStore(owned.execution, p.stepResultPolicy),\n inbox: new PostgresUsageInbox(owned.execution), settlements: new PostgresCostSettlementStore(owned.execution), spend: new PostgresSpendStore(owned.execution),\n trees: new PostgresOperationTreeStore(owned.execution), accounting: new PostgresOperationAccountingStore(owned.execution) },\n }, close: owned.close };\n}\n/** Explicit administrator operation. Partial installation may be rerun; no login memberships are granted. */\nexport async function migratePostgresRuntime(value: PostgresRuntimeNamespace): Promise<void> {\n const n = namespace(value), owned = pools(n,{execution:1,roots:1});\n try {\n await owned.execution.query(`create schema if not exists ${n.schema}`);\n await owned.roots.query(`create schema if not exists ${n.rootSchema}`);\n await migrateSessionStore(owned.execution);\n await migrateExecutionStore(owned.execution);\n await migrateExecutionResultStore(owned.execution);\n await migrateUsageInbox(owned.execution);\n await migrateOperationAccountingStore(owned.execution);\n await migrateOperationSessionStore(owned.execution);\n await migrateExecutionResultStore(owned.roots);\n for (const [pool, schema] of [[owned.execution, n.schema], [owned.roots, n.rootSchema]] as const) {\n await pool.query(`grant usage on schema ${schema} to alma_app, alma_retention; revoke create on schema ${schema} from public, alma_app, alma_retention`);\n }\n } finally { await owned.close(); }\n}\n"],"mappings":";;;;;AAAA,OAAO,QAAQ;AACf;AAAA,EAAS;AAAA,EAAsB;AAAA,EAAwB;AAAA,EAA8B;AAAA,EAAoB;AAAA,EAA6B;AAAA,EACpI;AAAA,EAAqB;AAAA,EAAuB;AAAA,EAA6B;AAAA,OAAyB;AACpG,SAAS,+BAA+B,4BAA4B,kCAAkC,iCAAiC,oCAAoC;AAQ3K,SAAS,OAAO,OAAsD;AACpE,MAAG,UAAQ,OAAU,QAAO,EAAC,WAAU,GAAE,OAAM,EAAC;AAChD,MAAG,CAAC,SAAS,OAAO,UAAQ,YAAY,MAAM,QAAQ,KAAK,EAAE,OAAM,IAAI,UAAU,6BAA6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;AAAA,MAAG,aAAa,IAAI,4BAA4B,MAAM,SAAS;AAAA,MAAG,OAAO,IAAI,mBAAmB,MAAM,SAAS;AAAA,MAC5J,OAAO,IAAI,2BAA2B,MAAM,SAAS;AAAA,MAAG,YAAY,IAAI,iCAAiC,MAAM,SAAS;AAAA,IAAE;AAAA,EAC9H,GAAG,OAAO,MAAM,MAAM;AACxB;AAEA,eAAsB,uBAAuB,OAAgD;AAC3F,QAAM,IAAI,UAAU,KAAK,GAAG,QAAQ,MAAM,GAAE,EAAC,WAAU,GAAE,OAAM,EAAC,CAAC;AACjE,MAAI;AACF,UAAM,MAAM,UAAU,MAAM,+BAA+B,EAAE,MAAM,EAAE;AACrE,UAAM,MAAM,MAAM,MAAM,+BAA+B,EAAE,UAAU,EAAE;AACrE,UAAM,oBAAoB,MAAM,SAAS;AACzC,UAAM,sBAAsB,MAAM,SAAS;AAC3C,UAAM,4BAA4B,MAAM,SAAS;AACjD,UAAM,kBAAkB,MAAM,SAAS;AACvC,UAAM,gCAAgC,MAAM,SAAS;AACrD,UAAM,6BAA6B,MAAM,SAAS;AAClD,UAAM,4BAA4B,MAAM,KAAK;AAC7C,eAAW,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC,MAAM,WAAW,EAAE,MAAM,GAAG,CAAC,MAAM,OAAO,EAAE,UAAU,CAAC,GAAY;AAChG,YAAM,KAAK,MAAM,yBAAyB,MAAM,yDAAyD,MAAM,wCAAwC;AAAA,IACzJ;AAAA,EACF,UAAE;AAAU,UAAM,MAAM,MAAM;AAAA,EAAG;AACnC;","names":[]}
package/package.json ADDED
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "@alma-harness/runtime",
3
+ "version": "0.7.0",
4
+ "description": "Official store composition for governed Alma conversations.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./memory": {
16
+ "types": "./dist/memory.d.ts",
17
+ "default": "./dist/memory.js"
18
+ },
19
+ "./postgres": {
20
+ "types": "./dist/postgres.d.ts",
21
+ "default": "./dist/postgres.js"
22
+ },
23
+ "./operations": {
24
+ "types": "./dist/operations.d.ts",
25
+ "default": "./dist/operations.js"
26
+ },
27
+ "./operations-cli": {
28
+ "types": "./dist/operations-cli.d.ts",
29
+ "default": "./dist/operations-cli.js"
30
+ }
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/FabioFernandesCarneiro/alma.git",
35
+ "directory": "packages/runtime"
36
+ },
37
+ "peerDependencies": {
38
+ "pg": "^8.16.3",
39
+ "@alma-harness/core": "^0.7.0",
40
+ "@alma-harness/conversation": "^0.7.0",
41
+ "@alma-harness/postgres": "^0.7.0",
42
+ "@alma-harness/memory": "^0.7.0",
43
+ "@alma-harness/execution": "^0.7.0",
44
+ "@alma-harness/single-call": "^0.7.0",
45
+ "@alma-harness/postgres-execution": "^0.7.0"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "pg": {
49
+ "optional": true
50
+ },
51
+ "@alma-harness/postgres": {
52
+ "optional": true
53
+ },
54
+ "@alma-harness/postgres-execution": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^24.1.0",
60
+ "@types/pg": "^8.15.4",
61
+ "typescript": "^5.9.2",
62
+ "vitest": "^3.2.4",
63
+ "pg": "^8.16.3",
64
+ "@alma-harness/core": "^0.7.0",
65
+ "@alma-harness/conversation": "^0.7.0",
66
+ "@alma-harness/single-call": "^0.7.0",
67
+ "@alma-harness/postgres": "^0.7.0",
68
+ "@alma-harness/execution": "^0.7.0",
69
+ "@alma-harness/memory": "^0.7.0",
70
+ "@alma-harness/postgres-execution": "^0.7.0"
71
+ },
72
+ "files": [
73
+ "dist"
74
+ ],
75
+ "publishConfig": {
76
+ "access": "public"
77
+ },
78
+ "bin": {
79
+ "alma-operations": "./dist/operations-cli.js"
80
+ },
81
+ "scripts": {
82
+ "typecheck": "tsc --noEmit",
83
+ "test": "vitest run",
84
+ "build": "tsup"
85
+ },
86
+ "main": "./dist/index.js",
87
+ "types": "./dist/index.d.ts"
88
+ }