@alma-harness/conversation 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +89 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.js +313 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
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,89 @@
|
|
|
1
|
+
# @alma-harness/conversation
|
|
2
|
+
|
|
3
|
+
Governed buffered conversations. Use matching core, execution, loop
|
|
4
|
+
and single-call packages. `createConversationRunner(config)` composes durable
|
|
5
|
+
session admission, operation roots, governed model steps and final result storage.
|
|
6
|
+
It is independent of the legacy agent's lease/claim and financial writers.
|
|
7
|
+
|
|
8
|
+
Supply `step: GovernedStepConfig`, `admissions`, `rootResults`, `sessions`, ordinary
|
|
9
|
+
agent prompt/policy/tools/profiles/hooks/media/recall options, `caps`, `prices`,
|
|
10
|
+
`policyVersion`, `priceVersion`, `configRevision`, `resultContractVersion`,
|
|
11
|
+
`resultRetentionMs`, `runTimeoutMs`, `maxCalls`, `maxInputChars` and `consumers`.
|
|
12
|
+
`runTimeoutMs` is at most five minutes. Clients must be single-dispatch. Ordinary
|
|
13
|
+
configuration is copied; store/client/policy/schema implementations and revision
|
|
14
|
+
mappings are trusted host capabilities. Tools use `ConversationTool` and receive
|
|
15
|
+
`ConversationToolCtx`, including `models.direct({tier,sensitivity,prompt})` for a
|
|
16
|
+
single tool-free child call, and the narrowing `models.delegate` gateway.
|
|
17
|
+
|
|
18
|
+
`run({root,intent,loadInput,trigger?,toolProfile?,signal?})` requires the root's
|
|
19
|
+
closed request descriptor. Its configuration/output versions and retention must
|
|
20
|
+
match construction, caps must match, maxCalls may narrow, and the declared root
|
|
21
|
+
sensitivity must equal the intent. The host assigns inputRevision to the complete
|
|
22
|
+
immutable request, including profile/trigger/intent. Changed metadata conflicts
|
|
23
|
+
before content access; never accept browser/model identities as authority.
|
|
24
|
+
The root ID is the turn ID; only the runner allocates child slots, IDs and parents.
|
|
25
|
+
|
|
26
|
+
Admission, root claim and pending final-result reservation precede loadInput,
|
|
27
|
+
hooks, recall, history and media. Busy/replayed requests run nothing. Successful
|
|
28
|
+
steps expose usable output only behind governed receipts. Main, direct, delegate
|
|
29
|
+
and cold-start summary calls share the root; inclusive totals are not new charges.
|
|
30
|
+
Explicit warn caps preserve results. Numeric/explicit block caps retain their
|
|
31
|
+
stopping behavior, including zero-cost preflight refusal. The legacy SpendStore.add
|
|
32
|
+
and AuditLog.cost writers are never called by this runner.
|
|
33
|
+
|
|
34
|
+
## Final results and deployment
|
|
35
|
+
|
|
36
|
+
`rootResults` MUST be physically separate from `step.results`. For PostgreSQL,
|
|
37
|
+
create a dedicated schema and pool whose search_path resolves only that schema,
|
|
38
|
+
then use migrateExecutionResultStore/PostgresExecutionResultStore there. Configure
|
|
39
|
+
the same scoped roles and grant schema USAGE. Object inequality is checked but
|
|
40
|
+
cannot prove database isolation: two adapters pointing to the same table are an
|
|
41
|
+
invalid host composition. Final IDs are scoped root keys in this namespace; no
|
|
42
|
+
billable call or ordinal is fabricated. Do not use untrusted search_path entries.
|
|
43
|
+
|
|
44
|
+
Deploy all execution/accounting/admission migrations before the matching readers.
|
|
45
|
+
Register both result namespaces and sessions in host erasure/retention workflows;
|
|
46
|
+
createMemoryErasure's single results handle alone cannot cover both. Erasure or
|
|
47
|
+
expiry of completed output returns unavailable and never regenerates content.
|
|
48
|
+
Provider live smokes, publication and product delivery are separate evidence.
|
|
49
|
+
|
|
50
|
+
## Completion and reconciliation
|
|
51
|
+
|
|
52
|
+
The result is a status view: completed with a TurnResult, busy with a root key,
|
|
53
|
+
in_progress, reconciliation_required, or unavailable. `read(scope,key)` rechecks
|
|
54
|
+
admission, closed root, financial completion and authorized final content. It does
|
|
55
|
+
not dispatch, repair effects or load conversation context. Replays retain original
|
|
56
|
+
usage/cost and mark `replayed: true`; do not add them to new spend. Root warnings
|
|
57
|
+
are historical deduplicated evidence; notification delivery is a host concern.
|
|
58
|
+
|
|
59
|
+
Normal completion awaits handlers/children, append and turn:end, closes the root,
|
|
60
|
+
persists and rechecks the final envelope, then finishes admission. A lost finish
|
|
61
|
+
ACK is accepted only after reading back matching owner release, never operator
|
|
62
|
+
resolution. Other uncertain writes, failures, cancellation and timeouts retain
|
|
63
|
+
occupancy for explicit operator reconciliation. Available content alone is not
|
|
64
|
+
proof of session/effect completion. No runner path calls resolve or retries append.
|
|
65
|
+
If the public timeout races with an already-started finish after all work is
|
|
66
|
+
quiescent, that finish may commit later; a subsequent read can verify completion.
|
|
67
|
+
This exception never authorizes a finish after an earlier uncertain operation.
|
|
68
|
+
|
|
69
|
+
Handlers MUST await all external work. The harness tracks started model children,
|
|
70
|
+
poisons swallowed child failures, and revokes gateways after each handler settles;
|
|
71
|
+
it cannot discover arbitrary detached work hidden inside trusted host code. An
|
|
72
|
+
ordinary handler rejection is uncertain even if labelled read-only. Hanging or
|
|
73
|
+
failed context/hook work cannot authorize further effects. Timed-out dependencies
|
|
74
|
+
may finish late; settlement evidence can drain in the background, but the turn
|
|
75
|
+
never resumes automatically. Operators must reconcile effects/writes and establish
|
|
76
|
+
quiescence before resolution. Use the step runner's recovery APIs for accounting;
|
|
77
|
+
that does not complete a conversation.
|
|
78
|
+
|
|
79
|
+
Governed output preserves cross-category block order and omits reasoning from the
|
|
80
|
+
reply. Refusal/truncation obey the governed-step output contract. This is buffered:
|
|
81
|
+
no token streaming or automatic reactive context-window retry. Cold-start rotation
|
|
82
|
+
is supported; uncertain provider failures require reconciliation. Batch/routines,
|
|
83
|
+
history import and channel delivery remain separate adoption work.
|
|
84
|
+
|
|
85
|
+
The full PostgreSQL-backed gate exercises deterministic conversation composition,
|
|
86
|
+
separate result namespaces, durable replay/erasure and lost append acknowledgements.
|
|
87
|
+
No Prumo tour scene is added here: its source budget is nearly full, and the new
|
|
88
|
+
capability's executable acceptance path is packages/conversation/test. A tour
|
|
89
|
+
integration needs a separate budget-preserving scene slice.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ToolDefinition, ToolCtx, DelegateRequest, DelegateResult, ExecutionResultStore, BudgetCaps, ModelPrice, RoutingIntent, ToolProfileRef, TurnTrigger, Msg, Scope } from '@alma-harness/core';
|
|
2
|
+
import { OperationSessionStore, OperationRootInput } from '@alma-harness/execution';
|
|
3
|
+
import { AgentConfig, TurnResult } from '@alma-harness/loop';
|
|
4
|
+
import { GovernedStepConfig } from '@alma-harness/single-call';
|
|
5
|
+
|
|
6
|
+
interface ConversationToolCtx extends ToolCtx {
|
|
7
|
+
models: ToolCtx["models"] & {
|
|
8
|
+
direct(req: Omit<DelegateRequest, "tools">): Promise<DelegateResult>;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
type ConversationTool = Omit<ToolDefinition, "handler"> & {
|
|
12
|
+
handler(input: unknown, ctx: ConversationToolCtx): Promise<unknown>;
|
|
13
|
+
};
|
|
14
|
+
interface ConversationConfig extends Omit<AgentConfig, "clients" | "audit" | "budget" | "turnStore" | "leaseTtlMs" | "leaseWaitMs" | "tools"> {
|
|
15
|
+
tools?: ConversationTool[];
|
|
16
|
+
step: GovernedStepConfig;
|
|
17
|
+
admissions: OperationSessionStore;
|
|
18
|
+
/** Physically separate from step.results; PostgreSQL requires a separate schema/pool namespace. */
|
|
19
|
+
rootResults: ExecutionResultStore;
|
|
20
|
+
caps: BudgetCaps;
|
|
21
|
+
prices: ModelPrice[];
|
|
22
|
+
policyVersion: string;
|
|
23
|
+
priceVersion: string;
|
|
24
|
+
configRevision: string;
|
|
25
|
+
resultContractVersion: string;
|
|
26
|
+
resultRetentionMs: number;
|
|
27
|
+
runTimeoutMs: number;
|
|
28
|
+
maxCalls: number;
|
|
29
|
+
maxInputChars: number;
|
|
30
|
+
consumers: string[];
|
|
31
|
+
}
|
|
32
|
+
interface ConversationInput {
|
|
33
|
+
root: OperationRootInput;
|
|
34
|
+
intent: RoutingIntent;
|
|
35
|
+
toolProfile?: ToolProfileRef;
|
|
36
|
+
trigger?: TurnTrigger;
|
|
37
|
+
loadInput(): Promise<Msg>;
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
type ConversationView = {
|
|
41
|
+
status: "completed";
|
|
42
|
+
result: TurnResult;
|
|
43
|
+
replayed: boolean;
|
|
44
|
+
} | {
|
|
45
|
+
status: "busy";
|
|
46
|
+
rootKey: string;
|
|
47
|
+
} | {
|
|
48
|
+
status: "in_progress" | "reconciliation_required" | "unavailable";
|
|
49
|
+
};
|
|
50
|
+
interface ConversationRunner {
|
|
51
|
+
run(input: ConversationInput): Promise<ConversationView>;
|
|
52
|
+
read(scope: Scope, rootKey: string): Promise<ConversationView | null>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
declare function createConversationRunner(value: ConversationConfig): ConversationRunner;
|
|
56
|
+
|
|
57
|
+
export { type ConversationConfig, type ConversationInput, type ConversationRunner, type ConversationTool, type ConversationToolCtx, type ConversationView, createConversationRunner };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { equalExecution, ExecutionConflictError, ExecutionResultPolicyError, normalizeExecutionEvidence, settlementIdentifier, settlementScope } from "@alma-harness/core";
|
|
3
|
+
import { normalizeOperationRoot } from "@alma-harness/execution";
|
|
4
|
+
import { createInternals as createInternals2, NO_EMIT, runTurnBody } from "@alma-harness/loop/internal";
|
|
5
|
+
|
|
6
|
+
// src/config.ts
|
|
7
|
+
import { normalizeBudgetCaps, settlementIdentifier as id } from "@alma-harness/core";
|
|
8
|
+
import { createInternals } from "@alma-harness/loop/internal";
|
|
9
|
+
import { createGovernedStepRunner } from "@alma-harness/single-call";
|
|
10
|
+
function config(value) {
|
|
11
|
+
if (value.rootResults === value.step.results) throw new TypeError("Conversation results require a separate physical namespace");
|
|
12
|
+
for (const [key, max] of Object.entries({ runTimeoutMs: 3e5, resultRetentionMs: 31536e6, maxCalls: 512, maxInputChars: 64e6 })) {
|
|
13
|
+
const n = value[key];
|
|
14
|
+
if (!Number.isSafeInteger(n) || Number(n) < 1 || Number(n) > max) throw new TypeError(`Invalid conversation ${key}`);
|
|
15
|
+
}
|
|
16
|
+
for (const n of [value.maxSteps ?? 24, value.maxDelegateDepth ?? 2, value.maxTokens ?? 8192]) if (!Number.isSafeInteger(n) || n < 1) throw new TypeError("Invalid conversation technical limit");
|
|
17
|
+
for (const key of ["policyVersion", "priceVersion", "configRevision", "resultContractVersion"]) id(value[key]);
|
|
18
|
+
if (!Array.isArray(value.consumers) || value.consumers.length > 16) throw new TypeError("Invalid consumers");
|
|
19
|
+
for (const client of Object.values(value.step.clients)) if (!client || client.dispatchPolicy !== "single" || typeof client.validate !== "function") throw new TypeError("Conversation requires single-dispatch clients");
|
|
20
|
+
const c = {
|
|
21
|
+
...value,
|
|
22
|
+
caps: normalizeBudgetCaps(value.caps),
|
|
23
|
+
prices: structuredClone(value.prices),
|
|
24
|
+
consumers: [...new Set(value.consumers.map(id))].sort(),
|
|
25
|
+
system: structuredClone(value.system),
|
|
26
|
+
step: { ...value.step, clients: { ...value.step.clients } },
|
|
27
|
+
...value.providerTools ? { providerTools: structuredClone(value.providerTools) } : {},
|
|
28
|
+
...value.profiles ? { profiles: structuredClone(value.profiles) } : {},
|
|
29
|
+
...value.tools ? { tools: value.tools.map((t) => ({ ...t, ...t.jsonSchema ? { jsonSchema: structuredClone(t.jsonSchema) } : {} })) } : {},
|
|
30
|
+
...value.hooks ? { hooks: value.hooks.map((h) => ({ ...h })) } : {},
|
|
31
|
+
...value.longContext ? { longContext: { ...value.longContext } } : {},
|
|
32
|
+
...value.media ? { media: { ...value.media } } : {}
|
|
33
|
+
};
|
|
34
|
+
createGovernedStepRunner(c.step);
|
|
35
|
+
createInternals(agentConfig(c), true);
|
|
36
|
+
return c;
|
|
37
|
+
}
|
|
38
|
+
function agentConfig(c) {
|
|
39
|
+
return { ...c, ...c.tools ? { tools: c.tools } : {}, clients: c.step.clients, audit: c.step.audit, budget: { caps: c.caps, prices: c.prices } };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/execution.ts
|
|
43
|
+
import { BudgetExceededError, normalizeSpendTotals } from "@alma-harness/core";
|
|
44
|
+
import { createGovernedStepRunner as createGovernedStepRunner2 } from "@alma-harness/single-call";
|
|
45
|
+
function ordered(step) {
|
|
46
|
+
return step.order.map((p) => p.type === "text" ? { type: "text", text: step.text.slice(p.start, p.end) } : p.type === "reasoning" ? step.reasoning[p.index] : p.type === "provider_block" ? step.providerBlocks[p.index] : { type: "tool_call", id: step.toolCalls[p.index].id, name: step.toolCalls[p.index].name, input: step.toolCalls[p.index].input });
|
|
47
|
+
}
|
|
48
|
+
function execution(c, root, fence, signal, lifecycle) {
|
|
49
|
+
const runner = createGovernedStepRunner2(c.step);
|
|
50
|
+
let sequence = 0, spent = 0;
|
|
51
|
+
const warnings = /* @__PURE__ */ new Set();
|
|
52
|
+
const refuse = async () => {
|
|
53
|
+
lifecycle.poison();
|
|
54
|
+
throw new Error("Legacy charging is forbidden");
|
|
55
|
+
};
|
|
56
|
+
async function preflight() {
|
|
57
|
+
lifecycle.check();
|
|
58
|
+
const configured = Object.entries(root.caps).filter(([, v]) => typeof v === "object" && v.onExceeded === "block");
|
|
59
|
+
if (!configured.length) return;
|
|
60
|
+
const totals = configured.some(([k]) => k !== "perTurnUsd") ? normalizeSpendTotals(await c.step.spend.peek({ scope: root.scope, sessionId: root.sessionId, at: (/* @__PURE__ */ new Date()).toISOString() })) : { sessionUsd: 0, tenantDayUsd: 0 };
|
|
61
|
+
lifecycle.check();
|
|
62
|
+
for (const [key, cap] of configured) {
|
|
63
|
+
const usd = key === "perTurnUsd" ? spent : key === "perSessionUsd" ? totals.sessionUsd : totals.tenantDayUsd;
|
|
64
|
+
if (usd >= cap.usd) throw new BudgetExceededError(key, cap.usd, usd);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
...lifecycle,
|
|
69
|
+
turnId: root.id,
|
|
70
|
+
guard: { charge: refuse, chargePriced: refuse, preflight, spentUsd: () => spent, drainCrossings: () => [], capsCrossed: () => [...warnings], accountingError: () => void 0 },
|
|
71
|
+
async run(request, meta) {
|
|
72
|
+
try {
|
|
73
|
+
lifecycle.check();
|
|
74
|
+
await preflight();
|
|
75
|
+
lifecycle.check();
|
|
76
|
+
const slot = String(++sequence), callId = crypto.randomUUID(), operationKey = crypto.randomUUID();
|
|
77
|
+
const controls = { maxTokens: request.maxTokens, ...request.reasoning ? { reasoning: request.reasoning } : {}, ...request.cache !== void 0 ? { cache: request.cache } : {}, ...request.temperature !== void 0 ? { temperature: request.temperature } : {} };
|
|
78
|
+
const v = await runner.run({
|
|
79
|
+
fence,
|
|
80
|
+
signal,
|
|
81
|
+
rationale: meta.rationale,
|
|
82
|
+
call: { slot, kind: meta.kind, ...meta.parentCallId ? { parentCallId: meta.parentCallId } : {}, execution: {
|
|
83
|
+
scope: root.scope,
|
|
84
|
+
sessionId: root.sessionId,
|
|
85
|
+
operationKey,
|
|
86
|
+
operationId: crypto.randomUUID(),
|
|
87
|
+
attemptId: crypto.randomUUID(),
|
|
88
|
+
callId,
|
|
89
|
+
settlementId: crypto.randomUUID(),
|
|
90
|
+
inputRevision: root.request.inputRevision,
|
|
91
|
+
policyVersion: root.policyVersion,
|
|
92
|
+
outputContractVersion: "governed-step-v1",
|
|
93
|
+
intent: { tier: meta.intent.tier, sensitivity: meta.intent.sensitivity },
|
|
94
|
+
model: request.model,
|
|
95
|
+
requestedTier: request.serviceTier ?? "standard",
|
|
96
|
+
priceVersion: c.priceVersion,
|
|
97
|
+
prices: c.prices.filter((p) => p.model.provider === request.model.provider && p.model.id === request.model.id),
|
|
98
|
+
controls,
|
|
99
|
+
occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
100
|
+
deadlineAt: root.deadlineAt,
|
|
101
|
+
governance: { caps: root.caps, consumers: c.consumers, resultRetentionMs: c.resultRetentionMs }
|
|
102
|
+
} },
|
|
103
|
+
loadRequest: async () => {
|
|
104
|
+
lifecycle.check();
|
|
105
|
+
return request;
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
lifecycle.check();
|
|
109
|
+
if (v.status !== "completed") throw new Error("Model step requires reconciliation");
|
|
110
|
+
spent = Math.max(spent, v.rootReceipt.currentUsd);
|
|
111
|
+
for (const cap of v.rootReceipt.newWarnings) warnings.add(cap);
|
|
112
|
+
const usage = v.receipt.receipt.settlement.usage;
|
|
113
|
+
const decision = v.rootReceipt.decisions.find((d) => d.exceeded && d.onExceeded === "block");
|
|
114
|
+
if (v.result.outcome === "blocked" && decision) return {
|
|
115
|
+
callId,
|
|
116
|
+
usage,
|
|
117
|
+
text: "",
|
|
118
|
+
toolCalls: [],
|
|
119
|
+
reasoning: [],
|
|
120
|
+
providerBlocks: [],
|
|
121
|
+
blocks: [],
|
|
122
|
+
stop: v.result.stopReason,
|
|
123
|
+
error: new BudgetExceededError(decision.cap, decision.thresholdUsd, decision.currentUsd)
|
|
124
|
+
};
|
|
125
|
+
if (meta.kind === "summary" && (v.result.outcome !== "success" || !v.step?.text.trim())) throw new Error("Summary output is unusable");
|
|
126
|
+
if (v.result.outcome === "refusal" || v.result.outcome === "truncated") return { callId, usage, text: "", toolCalls: [], reasoning: [], providerBlocks: [], blocks: [], stop: v.result.stopReason };
|
|
127
|
+
if (!v.step || v.result.outcome !== "success") throw new Error("Model output is unavailable");
|
|
128
|
+
return {
|
|
129
|
+
callId,
|
|
130
|
+
usage,
|
|
131
|
+
text: v.step.text,
|
|
132
|
+
stop: v.step.stop,
|
|
133
|
+
reasoning: v.step.reasoning,
|
|
134
|
+
providerBlocks: v.step.providerBlocks,
|
|
135
|
+
blocks: ordered(v.step),
|
|
136
|
+
toolCalls: v.step.toolCalls.map((t) => ({ id: t.id, name: t.name, input: t.input, ...t.malformed ? { malformed: "Invalid JSON" } : {} }))
|
|
137
|
+
};
|
|
138
|
+
} catch (e) {
|
|
139
|
+
if (!(e instanceof BudgetExceededError)) lifecycle.poison();
|
|
140
|
+
throw e;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/index.ts
|
|
147
|
+
var pending = () => ({ status: "reconciliation_required" });
|
|
148
|
+
var interrupted = () => new Error("Conversation requires reconciliation");
|
|
149
|
+
function createConversationRunner(value) {
|
|
150
|
+
const c = config(value);
|
|
151
|
+
const binding = (root) => ({ scope: root.scope, callId: root.key, sessionId: root.sessionId, sensitivity: root.maxSensitivity, retentionMs: root.request.resultRetentionMs });
|
|
152
|
+
async function read(scope, key) {
|
|
153
|
+
const s = settlementScope(scope), k = settlementIdentifier(key), a = await c.admissions.get(s, k);
|
|
154
|
+
if (!a) return null;
|
|
155
|
+
if (a.status !== "released") return { status: a.status === "active" && a.input.deadlineAt > (/* @__PURE__ */ new Date()).toISOString() ? "in_progress" : "reconciliation_required" };
|
|
156
|
+
if (a.resolutionId || !a.input.request) return pending();
|
|
157
|
+
const root = await c.step.trees.get(s, k);
|
|
158
|
+
if (!root || root.status !== "closed" || !equalExecution(root.input, a.input)) return pending();
|
|
159
|
+
let stored;
|
|
160
|
+
try {
|
|
161
|
+
stored = await c.rootResults.get(s, k);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
if (e instanceof ExecutionResultPolicyError) return { status: "unavailable" };
|
|
164
|
+
throw e;
|
|
165
|
+
}
|
|
166
|
+
if (!stored || stored.state !== "available" || !equalExecution(stored.binding, binding(root.input)) || stored.result?.outcome !== "success" || stored.result.output.format !== "json") return { status: "unavailable" };
|
|
167
|
+
const financial = await c.step.accounting.get(s, k);
|
|
168
|
+
if (!financial || financial.reservedCalls !== financial.settledCalls || financial.rootStatus !== "closed") return pending();
|
|
169
|
+
try {
|
|
170
|
+
const data = JSON.parse(stored.result.output.text);
|
|
171
|
+
const r = data.result;
|
|
172
|
+
if (data.version !== "governed-conversation-v1" || data.rootId !== root.input.id || data.contract !== root.input.request.resultContractVersion || !r || r.turnId !== root.input.id || r.costUsd !== financial.costUsd || !["completed", "budget_exceeded"].includes(r.terminalReason) || r.reply?.role !== "assistant" || !Array.isArray(r.reply.blocks) || r.reply.blocks.some((b) => b.type === "reasoning") || !Number.isSafeInteger(r.steps) || r.steps < 0 || !Number.isFinite(r.durationMs) || r.durationMs < 0) return { status: "unavailable" };
|
|
173
|
+
normalizeExecutionEvidence({ status: "known", usage: r.usage });
|
|
174
|
+
return { status: "completed", result: { ...r, replayed: true }, replayed: true };
|
|
175
|
+
} catch {
|
|
176
|
+
return { status: "unavailable" };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function run(input) {
|
|
180
|
+
const root = normalizeOperationRoot(input.root), req = root.request;
|
|
181
|
+
const opts = { intent: structuredClone(input.intent), ...input.trigger ? { trigger: input.trigger } : {}, ...input.toolProfile ? { toolProfile: input.toolProfile } : {} }, load = input.loadInput, external = input.signal;
|
|
182
|
+
if (!req || req.configRevision !== c.configRevision || req.resultContractVersion !== c.resultContractVersion || req.resultRetentionMs !== c.resultRetentionMs || root.policyVersion !== c.policyVersion || !equalExecution(root.caps, c.caps) || root.maxCalls > c.maxCalls || root.maxSensitivity !== opts.intent.sensitivity || typeof load !== "function") throw new ExecutionConflictError();
|
|
183
|
+
const controller = new AbortController();
|
|
184
|
+
let uncertain = false, children = 0, sealed = false, admission;
|
|
185
|
+
const poison = () => {
|
|
186
|
+
uncertain = true;
|
|
187
|
+
controller.abort();
|
|
188
|
+
};
|
|
189
|
+
const check = () => {
|
|
190
|
+
if (uncertain || sealed || controller.signal.aborted || admission && Date.now() >= Date.parse(root.deadlineAt)) throw interrupted();
|
|
191
|
+
};
|
|
192
|
+
function track(fn) {
|
|
193
|
+
const p = (async () => {
|
|
194
|
+
check();
|
|
195
|
+
children++;
|
|
196
|
+
try {
|
|
197
|
+
return await fn();
|
|
198
|
+
} catch (e) {
|
|
199
|
+
poison();
|
|
200
|
+
throw e;
|
|
201
|
+
} finally {
|
|
202
|
+
children--;
|
|
203
|
+
}
|
|
204
|
+
})();
|
|
205
|
+
void p.catch(() => {
|
|
206
|
+
});
|
|
207
|
+
return p;
|
|
208
|
+
}
|
|
209
|
+
const abort = () => poison();
|
|
210
|
+
const timer = setTimeout(abort, c.runTimeoutMs);
|
|
211
|
+
let deadline;
|
|
212
|
+
const cancelled = new Promise((resolve) => controller.signal.addEventListener("abort", () => resolve(pending()), { once: true }));
|
|
213
|
+
external?.addEventListener("abort", abort, { once: true });
|
|
214
|
+
if (external?.aborted) abort();
|
|
215
|
+
const work = execute();
|
|
216
|
+
void work.catch(() => {
|
|
217
|
+
});
|
|
218
|
+
return Promise.race([work, cancelled]).finally(() => {
|
|
219
|
+
sealed = true;
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
clearTimeout(deadline);
|
|
222
|
+
external?.removeEventListener("abort", abort);
|
|
223
|
+
});
|
|
224
|
+
async function uncertainAdmission() {
|
|
225
|
+
if (admission) {
|
|
226
|
+
try {
|
|
227
|
+
await c.admissions.markUncertain(admission);
|
|
228
|
+
} catch {
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async function execute() {
|
|
233
|
+
try {
|
|
234
|
+
check();
|
|
235
|
+
const a = await c.admissions.claim(root);
|
|
236
|
+
if (a.status === "claimed") admission = a.fence;
|
|
237
|
+
check();
|
|
238
|
+
if (a.status === "busy") return { status: "busy", rootKey: a.rootKey };
|
|
239
|
+
if (a.status === "existing") return await read(root.scope, root.key) ?? pending();
|
|
240
|
+
deadline = setTimeout(abort, Math.max(0, Date.parse(root.deadlineAt) - Date.now()));
|
|
241
|
+
const claim = await c.step.trees.claim(root);
|
|
242
|
+
check();
|
|
243
|
+
if (claim.status !== "claimed" || !equalExecution(claim.record.input, root)) throw interrupted();
|
|
244
|
+
const prepared = await c.rootResults.prepare(binding(root));
|
|
245
|
+
check();
|
|
246
|
+
if (prepared.state !== "pending") throw interrupted();
|
|
247
|
+
const message = structuredClone(await load());
|
|
248
|
+
check();
|
|
249
|
+
if (message.role !== "user" || JSON.stringify(message).length > c.maxInputChars) throw new TypeError("Invalid conversation input");
|
|
250
|
+
const base = agentConfig(c), sessionStore = c.sessions;
|
|
251
|
+
const guarded = async (fn) => {
|
|
252
|
+
check();
|
|
253
|
+
try {
|
|
254
|
+
const result2 = await fn();
|
|
255
|
+
check();
|
|
256
|
+
return result2;
|
|
257
|
+
} catch (e) {
|
|
258
|
+
poison();
|
|
259
|
+
throw e;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
base.hooks = (base.hooks ?? []).map((h) => Object.fromEntries(Object.entries(h).filter(([, fn]) => typeof fn === "function").map(([key, fn]) => [key, async (...args) => {
|
|
263
|
+
check();
|
|
264
|
+
try {
|
|
265
|
+
const r = await fn(...args);
|
|
266
|
+
check();
|
|
267
|
+
return r;
|
|
268
|
+
} catch (e) {
|
|
269
|
+
poison();
|
|
270
|
+
throw e;
|
|
271
|
+
}
|
|
272
|
+
}])));
|
|
273
|
+
base.sessions = { ...sessionStore, load: (s, id2) => guarded(() => sessionStore.load(s, id2)), append: (s, id2, msgs) => guarded(() => sessionStore.append(s, id2, msgs)), erase: (s, id2) => sessionStore.erase(s, id2), expireToolTraffic: (s, id2, opts2) => sessionStore.expireToolTraffic(s, id2, opts2) };
|
|
274
|
+
if (c.recall) base.recall = { build: (...args) => {
|
|
275
|
+
const timeout = setTimeout(poison, c.recallTimeoutMs ?? 5e3);
|
|
276
|
+
return guarded(() => c.recall.build(...args)).finally(() => clearTimeout(timeout));
|
|
277
|
+
} };
|
|
278
|
+
if (c.media?.source) base.media = { ...c.media, source: { load: (...args) => guarded(() => c.media.source.load(...args)) } };
|
|
279
|
+
const runtime = execution(c, root, claim.fence, controller.signal, { check, poison, track });
|
|
280
|
+
const body = await runTurnBody(createInternals2(base, true), { scope: root.scope, sessionId: root.sessionId, input: message, ...opts, signal: controller.signal }, root.caps, NO_EMIT, runtime);
|
|
281
|
+
check();
|
|
282
|
+
if (children !== 0 || !["completed", "budget_exceeded"].includes(body.terminalReason)) throw interrupted();
|
|
283
|
+
const totals = await c.step.accounting.get(root.scope, root.key);
|
|
284
|
+
check();
|
|
285
|
+
if (!totals || totals.reservedCalls !== totals.settledCalls || totals.costUsd !== body.costUsd) throw interrupted();
|
|
286
|
+
await c.step.trees.close(claim.fence);
|
|
287
|
+
check();
|
|
288
|
+
const result = { outcome: "success", stopReason: body.stopReason, output: { format: "json", text: JSON.stringify({ version: "governed-conversation-v1", rootId: root.id, contract: req.resultContractVersion, result: body }) } };
|
|
289
|
+
await c.rootResults.put(root.scope, root.key, result);
|
|
290
|
+
check();
|
|
291
|
+
const final = await c.rootResults.get(root.scope, root.key);
|
|
292
|
+
check();
|
|
293
|
+
if (final?.state !== "available" || !equalExecution(final.binding, binding(root)) || !equalExecution(final.result, result)) throw interrupted();
|
|
294
|
+
try {
|
|
295
|
+
await c.admissions.finish(admission);
|
|
296
|
+
} catch {
|
|
297
|
+
const released = await c.admissions.get(root.scope, root.key);
|
|
298
|
+
if (!released || released.status !== "released" || released.resolutionId || !equalExecution(released.input, root)) throw interrupted();
|
|
299
|
+
}
|
|
300
|
+
return { status: "completed", result: body, replayed: false };
|
|
301
|
+
} catch {
|
|
302
|
+
poison();
|
|
303
|
+
await uncertainAdmission();
|
|
304
|
+
return pending();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { run, read };
|
|
309
|
+
}
|
|
310
|
+
export {
|
|
311
|
+
createConversationRunner
|
|
312
|
+
};
|
|
313
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/execution.ts"],"sourcesContent":["import { equalExecution, ExecutionConflictError, ExecutionResultPolicyError, normalizeExecutionEvidence, settlementIdentifier, settlementScope, type ExecutionResultRecord, type Scope } from \"@alma-harness/core\";\nimport { normalizeOperationRoot, type OperationRootInput, type OperationSessionFence } from \"@alma-harness/execution\";\nimport { createInternals, NO_EMIT, runTurnBody } from \"@alma-harness/loop/internal\";\nimport type { TurnResult } from \"@alma-harness/loop\";\nimport { agentConfig, config } from \"./config\";\nimport { execution } from \"./execution\";\nimport type { ConversationConfig, ConversationInput, ConversationRunner, ConversationView } from \"./types\";\nexport type { ConversationConfig, ConversationInput, ConversationRunner, ConversationView, ConversationTool, ConversationToolCtx } from \"./types\";\nconst pending = (): ConversationView => ({ status:\"reconciliation_required\" });\nconst interrupted = () => new Error(\"Conversation requires reconciliation\");\nexport function createConversationRunner(value: ConversationConfig): ConversationRunner {\n const c = config(value);\n const binding = (root:OperationRootInput) => ({ scope:root.scope,callId:root.key,sessionId:root.sessionId,sensitivity:root.maxSensitivity,retentionMs:root.request!.resultRetentionMs });\n async function read(scope:Scope, key:string): Promise<ConversationView|null> {\n const s = settlementScope(scope), k = settlementIdentifier(key), a = await c.admissions.get(s,k);\n if (!a) return null;\n if (a.status !== \"released\") return { status:a.status === \"active\" && a.input.deadlineAt > new Date().toISOString() ? \"in_progress\" : \"reconciliation_required\" };\n if (a.resolutionId || !a.input.request) return pending();\n const root = await c.step.trees.get(s,k);\n if (!root || root.status !== \"closed\" || !equalExecution(root.input,a.input)) return pending();\n let stored:ExecutionResultRecord|null;\n try { stored = await c.rootResults.get(s,k); } catch (e) { if (e instanceof ExecutionResultPolicyError) return { status:\"unavailable\" }; throw e; }\n if (!stored || stored.state !== \"available\" || !equalExecution(stored.binding,binding(root.input)) || stored.result?.outcome !== \"success\" || stored.result.output.format !== \"json\") return { status:\"unavailable\" };\n const financial = await c.step.accounting.get(s,k);\n if (!financial || financial.reservedCalls !== financial.settledCalls || financial.rootStatus !== \"closed\") return pending();\n try {\n const data = JSON.parse(stored.result.output.text) as { version:string; rootId:string; contract:string; result:TurnResult };\n const r = data.result;\n if (data.version !== \"governed-conversation-v1\" || data.rootId !== root.input.id || data.contract !== root.input.request!.resultContractVersion || !r || r.turnId !== root.input.id || r.costUsd !== financial.costUsd || ![\"completed\",\"budget_exceeded\"].includes(r.terminalReason) || r.reply?.role !== \"assistant\" || !Array.isArray(r.reply.blocks) || r.reply.blocks.some(b => b.type === \"reasoning\") || !Number.isSafeInteger(r.steps) || r.steps < 0 || !Number.isFinite(r.durationMs) || r.durationMs < 0) return { status:\"unavailable\" };\n normalizeExecutionEvidence({ status:\"known\",usage:r.usage });\n return { status:\"completed\",result:{ ...r,replayed:true },replayed:true };\n } catch { return { status:\"unavailable\" }; }\n }\n function run(input:ConversationInput): Promise<ConversationView> {\n const root = normalizeOperationRoot(input.root), req = root.request;\n const opts = { intent:structuredClone(input.intent),...(input.trigger ? {trigger:input.trigger} : {}),...(input.toolProfile ? {toolProfile:input.toolProfile} : {}) }, load = input.loadInput, external = input.signal;\n if (!req || req.configRevision !== c.configRevision || req.resultContractVersion !== c.resultContractVersion || req.resultRetentionMs !== c.resultRetentionMs || root.policyVersion !== c.policyVersion || !equalExecution(root.caps,c.caps) || root.maxCalls > c.maxCalls || root.maxSensitivity !== opts.intent.sensitivity || typeof load !== \"function\") throw new ExecutionConflictError();\n const controller = new AbortController(); let uncertain = false, children = 0, sealed = false, admission:OperationSessionFence|undefined;\n const poison = () => { uncertain = true; controller.abort(); };\n const check = () => { if (uncertain || sealed || controller.signal.aborted || (admission && Date.now() >= Date.parse(root.deadlineAt))) throw interrupted(); };\n function track<T>(fn:()=>Promise<T>):Promise<T> {\n const p = (async () => { check(); children++; try { return await fn(); } catch (e) { poison(); throw e; } finally { children--; } })();\n void p.catch(() => {}); return p;\n }\n const abort = () => poison();\n const timer = setTimeout(abort,c.runTimeoutMs); let deadline:ReturnType<typeof setTimeout>|undefined;\n const cancelled = new Promise<ConversationView>(resolve => controller.signal.addEventListener(\"abort\",() => resolve(pending()),{once:true}));\n external?.addEventListener(\"abort\",abort,{once:true}); if (external?.aborted) abort();\n const work = execute(); void work.catch(() => {});\n return Promise.race([work,cancelled]).finally(() => { sealed = true; clearTimeout(timer); clearTimeout(deadline); external?.removeEventListener(\"abort\",abort); });\n async function uncertainAdmission() { if (admission) { try { await c.admissions.markUncertain(admission); } catch { /* Occupancy survives this failed acknowledgement. */ } } }\n async function execute():Promise<ConversationView> {\n try {\n check(); const a = await c.admissions.claim(root);\n if (a.status === \"claimed\") admission = a.fence;\n check();\n if (a.status === \"busy\") return { status:\"busy\",rootKey:a.rootKey };\n if (a.status === \"existing\") return (await read(root.scope,root.key)) ?? pending();\n deadline = setTimeout(abort,Math.max(0,Date.parse(root.deadlineAt)-Date.now()));\n const claim = await c.step.trees.claim(root); check();\n if (claim.status !== \"claimed\" || !equalExecution(claim.record.input,root)) throw interrupted();\n const prepared = await c.rootResults.prepare(binding(root)); check();\n if (prepared.state !== \"pending\") throw interrupted();\n const message = structuredClone(await load()); check();\n if (message.role !== \"user\" || JSON.stringify(message).length > c.maxInputChars) throw new TypeError(\"Invalid conversation input\");\n const base = agentConfig(c), sessionStore = c.sessions;\n const guarded = async <T>(fn:()=>Promise<T>):Promise<T> => { check(); try { const result = await fn(); check(); return result; } catch (e) { poison(); throw e; } };\n // Every effect-capable hook and all asynchronous context sources are per-turn closures.\n base.hooks = (base.hooks ?? []).map(h => Object.fromEntries(Object.entries(h).filter(([,fn]) => typeof fn === \"function\").map(([key,fn]) => [key,async (...args:unknown[]) => { check(); try { const r = await (fn as (...a:unknown[])=>unknown)(...args); check(); return r; } catch (e) { poison(); throw e; } }])));\n base.sessions = { ...sessionStore, load:(s,id) => guarded(() => sessionStore.load(s,id)), append:(s,id,msgs) => guarded(() => sessionStore.append(s,id,msgs)), erase:(s,id) => sessionStore.erase(s,id), expireToolTraffic:(s,id,opts) => sessionStore.expireToolTraffic(s,id,opts) };\n if (c.recall) base.recall = { build:(...args) => { const timeout = setTimeout(poison,c.recallTimeoutMs ?? 5000); return guarded(() => c.recall!.build(...args)).finally(() => clearTimeout(timeout)); } };\n if (c.media?.source) base.media = { ...c.media,source:{load:(...args) => guarded(() => c.media!.source!.load(...args))} };\n const runtime = execution(c,root,claim.fence,controller.signal,{check,poison,track});\n const body = await runTurnBody(createInternals(base,true), { scope:root.scope,sessionId:root.sessionId,input:message,...opts,signal:controller.signal },root.caps,NO_EMIT,runtime);\n check();\n if (children !== 0 || ![\"completed\",\"budget_exceeded\"].includes(body.terminalReason)) throw interrupted();\n const totals = await c.step.accounting.get(root.scope,root.key); check();\n if (!totals || totals.reservedCalls !== totals.settledCalls || totals.costUsd !== body.costUsd) throw interrupted();\n await c.step.trees.close(claim.fence); check();\n const result = { outcome:\"success\" as const,stopReason:body.stopReason,output:{format:\"json\" as const,text:JSON.stringify({version:\"governed-conversation-v1\",rootId:root.id,contract:req!.resultContractVersion,result:body})} };\n await c.rootResults.put(root.scope,root.key,result); check();\n const final = await c.rootResults.get(root.scope,root.key); check();\n if (final?.state !== \"available\" || !equalExecution(final.binding,binding(root)) || !equalExecution(final.result,result)) throw interrupted();\n try { await c.admissions.finish(admission!); }\n catch {\n // Finish is attempted only AFTER proven local quiescence and durable writes.\n const released = await c.admissions.get(root.scope,root.key);\n if (!released || released.status !== \"released\" || released.resolutionId || !equalExecution(released.input,root)) throw interrupted();\n }\n return {status:\"completed\",result:body,replayed:false};\n } catch { poison(); await uncertainAdmission(); return pending(); }\n }\n }\n return {run,read};\n}\n","import { normalizeBudgetCaps, settlementIdentifier as id, type ToolDefinition } from \"@alma-harness/core\";\nimport { createInternals } from \"@alma-harness/loop/internal\";\nimport type { AgentConfig } from \"@alma-harness/loop\";\nimport { createGovernedStepRunner } from \"@alma-harness/single-call\";\nimport type { ConversationConfig } from \"./types\";\nexport function config(value: ConversationConfig): ConversationConfig {\n if (value.rootResults === value.step.results) throw new TypeError(\"Conversation results require a separate physical namespace\");\n for (const [key, max] of Object.entries({ runTimeoutMs: 300000, resultRetentionMs: 31536000000, maxCalls: 512, maxInputChars: 64000000 })) {\n const n = value[key as keyof ConversationConfig]; if (!Number.isSafeInteger(n) || Number(n) < 1 || Number(n) > max) throw new TypeError(`Invalid conversation ${key}`);\n }\n for (const n of [value.maxSteps ?? 24, value.maxDelegateDepth ?? 2, value.maxTokens ?? 8192]) if (!Number.isSafeInteger(n) || n < 1) throw new TypeError(\"Invalid conversation technical limit\");\n for (const key of [\"policyVersion\", \"priceVersion\", \"configRevision\", \"resultContractVersion\"] as const) id(value[key]);\n if (!Array.isArray(value.consumers) || value.consumers.length > 16) throw new TypeError(\"Invalid consumers\");\n for (const client of Object.values(value.step.clients)) if (!client || client.dispatchPolicy !== \"single\" || typeof client.validate !== \"function\") throw new TypeError(\"Conversation requires single-dispatch clients\");\n const c = { ...value, caps: normalizeBudgetCaps(value.caps), prices: structuredClone(value.prices), consumers: [...new Set(value.consumers.map(id))].sort(),\n system: structuredClone(value.system), step: { ...value.step, clients: { ...value.step.clients } },\n ...(value.providerTools ? { providerTools: structuredClone(value.providerTools) } : {}),\n ...(value.profiles ? { profiles: structuredClone(value.profiles) } : {}),\n ...(value.tools ? { tools: value.tools.map(t => ({ ...t, ...(t.jsonSchema ? { jsonSchema: structuredClone(t.jsonSchema) } : {}) })) } : {}),\n ...(value.hooks ? { hooks: value.hooks.map(h => ({ ...h })) } : {}),\n ...(value.longContext ? { longContext: { ...value.longContext } } : {}), ...(value.media ? { media: { ...value.media } } : {}) };\n createGovernedStepRunner(c.step);\n createInternals(agentConfig(c), true); // Registry/config errors precede claims.\n return c;\n}\nexport function agentConfig(c: ConversationConfig): AgentConfig {\n // The internal governed dispatch branch supplies the declared extended gateway.\n return { ...c, ...(c.tools ? { tools: c.tools as ToolDefinition[] } : {}), clients: c.step.clients, audit: c.step.audit, budget: { caps: c.caps, prices: c.prices } };\n}\n","import { BudgetExceededError, normalizeSpendTotals, type Block, type BudgetCapName, type ModelRequest } from \"@alma-harness/core\";\nimport type { OperationFence, OperationRootInput } from \"@alma-harness/execution\";\nimport type { StepOutcome, TurnExecution } from \"@alma-harness/loop/internal\";\nimport { createGovernedStepRunner, type GovernedStepOutput } from \"@alma-harness/single-call\";\nimport type { ConversationConfig } from \"./types\";\nexport function ordered(step: GovernedStepOutput): Block[] {\n return step.order.map(p => p.type === \"text\" ? { type: \"text\", text: step.text.slice(p.start,p.end) }\n : p.type === \"reasoning\" ? step.reasoning[p.index]!\n : p.type === \"provider_block\" ? step.providerBlocks[p.index]!\n : { type: \"tool_call\", id: step.toolCalls[p.index]!.id, name: step.toolCalls[p.index]!.name, input: step.toolCalls[p.index]!.input });\n}\nexport function execution(c: ConversationConfig, root: OperationRootInput, fence: OperationFence, signal: AbortSignal,\n lifecycle: Pick<TurnExecution,\"check\"|\"poison\"|\"track\">): TurnExecution {\n const runner = createGovernedStepRunner(c.step); let sequence = 0, spent = 0; const warnings = new Set<BudgetCapName>();\n const refuse = async (): Promise<never> => { lifecycle.poison(); throw new Error(\"Legacy charging is forbidden\"); };\n async function preflight() {\n lifecycle.check();\n const configured = Object.entries(root.caps).filter(([,v]) => typeof v === \"object\" && v.onExceeded === \"block\");\n if (!configured.length) return;\n const totals = configured.some(([k]) => k !== \"perTurnUsd\") ? normalizeSpendTotals(await c.step.spend.peek({ scope: root.scope, sessionId: root.sessionId, at: new Date().toISOString() })) : { sessionUsd:0,tenantDayUsd:0 };\n lifecycle.check();\n for (const [key,cap] of configured) { const usd = key === \"perTurnUsd\" ? spent : key === \"perSessionUsd\" ? totals.sessionUsd : totals.tenantDayUsd;\n if (usd >= (cap as {usd:number}).usd) throw new BudgetExceededError(key as BudgetCapName,(cap as {usd:number}).usd,usd); }\n }\n return { ...lifecycle, turnId: root.id,\n guard: { charge: refuse, chargePriced: refuse, preflight, spentUsd: () => spent, drainCrossings: () => [], capsCrossed: () => [...warnings], accountingError: () => undefined },\n async run(request: ModelRequest, meta): Promise<StepOutcome> {\n try {\n lifecycle.check(); await preflight(); lifecycle.check();\n const slot = String(++sequence), callId = crypto.randomUUID(), operationKey = crypto.randomUUID();\n const controls = { maxTokens: request.maxTokens, ...(request.reasoning ? { reasoning: request.reasoning } : {}), ...(request.cache !== undefined ? { cache: request.cache } : {}), ...(request.temperature !== undefined ? { temperature: request.temperature } : {}) };\n const v = await runner.run({ fence, signal, rationale: meta.rationale,\n call: { slot, kind: meta.kind, ...(meta.parentCallId ? { parentCallId: meta.parentCallId } : {}), execution: {\n scope: root.scope, sessionId: root.sessionId, operationKey, operationId: crypto.randomUUID(), attemptId: crypto.randomUUID(), callId, settlementId: crypto.randomUUID(),\n inputRevision: root.request!.inputRevision, policyVersion: root.policyVersion, outputContractVersion: \"governed-step-v1\", intent: {tier:meta.intent.tier,sensitivity:meta.intent.sensitivity},\n model: request.model, requestedTier: request.serviceTier ?? \"standard\", priceVersion: c.priceVersion,\n prices: c.prices.filter(p => p.model.provider === request.model.provider && p.model.id === request.model.id), controls,\n occurredAt: new Date().toISOString(), deadlineAt: root.deadlineAt, governance: { caps: root.caps, consumers: c.consumers, resultRetentionMs: c.resultRetentionMs } } },\n loadRequest: async () => { lifecycle.check(); return request; } });\n lifecycle.check();\n if (v.status !== \"completed\") throw new Error(\"Model step requires reconciliation\");\n spent = Math.max(spent, v.rootReceipt.currentUsd); for (const cap of v.rootReceipt.newWarnings) warnings.add(cap);\n const usage = v.receipt.receipt.settlement.usage;\n const decision = v.rootReceipt.decisions.find(d => d.exceeded && d.onExceeded === \"block\");\n if (v.result.outcome === \"blocked\" && decision) return { callId, usage, text:\"\", toolCalls:[], reasoning:[], providerBlocks:[], blocks:[], stop: v.result.stopReason,\n error: new BudgetExceededError(decision.cap,decision.thresholdUsd,decision.currentUsd) };\n if (meta.kind === \"summary\" && (v.result.outcome !== \"success\" || !v.step?.text.trim())) throw new Error(\"Summary output is unusable\");\n if (v.result.outcome === \"refusal\" || v.result.outcome === \"truncated\") return { callId,usage,text:\"\",toolCalls:[],reasoning:[],providerBlocks:[],blocks:[],stop:v.result.stopReason };\n if (!v.step || v.result.outcome !== \"success\") throw new Error(\"Model output is unavailable\");\n return { callId, usage, text:v.step.text, stop:v.step.stop, reasoning:v.step.reasoning, providerBlocks:v.step.providerBlocks, blocks:ordered(v.step),\n toolCalls:v.step.toolCalls.map(t => ({ id:t.id,name:t.name,input:t.input, ...(t.malformed ? { malformed:\"Invalid JSON\" } : {}) })) };\n } catch (e) { if (!(e instanceof BudgetExceededError)) lifecycle.poison(); throw e; }\n },\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAgB,wBAAwB,4BAA4B,4BAA4B,sBAAsB,uBAA+D;AAC9L,SAAS,8BAAmF;AAC5F,SAAS,mBAAAA,kBAAiB,SAAS,mBAAmB;;;ACFtD,SAAS,qBAAqB,wBAAwB,UAA+B;AACrF,SAAS,uBAAuB;AAEhC,SAAS,gCAAgC;AAElC,SAAS,OAAO,OAA+C;AACpE,MAAI,MAAM,gBAAgB,MAAM,KAAK,QAAS,OAAM,IAAI,UAAU,4DAA4D;AAC9H,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,EAAE,cAAc,KAAQ,mBAAmB,SAAa,UAAU,KAAK,eAAe,KAAS,CAAC,GAAG;AACzI,UAAM,IAAI,MAAM,GAA+B;AAAG,QAAI,CAAC,OAAO,cAAc,CAAC,KAAK,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI,IAAK,OAAM,IAAI,UAAU,wBAAwB,GAAG,EAAE;AAAA,EACvK;AACA,aAAW,KAAK,CAAC,MAAM,YAAY,IAAI,MAAM,oBAAoB,GAAG,MAAM,aAAa,IAAI,EAAG,KAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI,EAAG,OAAM,IAAI,UAAU,sCAAsC;AAC/L,aAAW,O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AS,gBAAgB,CAAC,eAAe,SAAS,OAAM,IAAI,EAAG,OAAM,YAAY;AAAA,QACtI;AACA,eAAO,EAAC,QAAO,aAAY,QAAO,MAAK,UAAS,MAAK;AAAA,MACvD,QAAQ;AAAE,eAAO;AAAG,cAAM,mBAAmB;AAAG,eAAO,QAAQ;AAAA,MAAG;AAAA,IACpE;AAAA,EACF;AACA,SAAO,EAAC,KAAI,KAAI;AAClB;","names":["createInternals","createGovernedStepRunner","result","id","opts","createInternals"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@alma-harness/conversation",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Governed buffered conversations for Alma.",
|
|
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
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/FabioFernandesCarneiro/alma.git",
|
|
19
|
+
"directory": "packages/conversation"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@alma-harness/core": "^0.6.0",
|
|
23
|
+
"@alma-harness/execution": "^0.6.0",
|
|
24
|
+
"@alma-harness/loop": "^0.6.0",
|
|
25
|
+
"@alma-harness/single-call": "^0.6.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^24.1.0",
|
|
29
|
+
"typescript": "^5.9.2",
|
|
30
|
+
"vitest": "^3.2.4",
|
|
31
|
+
"pg": "^8.16.3",
|
|
32
|
+
"@types/pg": "^8.15.4",
|
|
33
|
+
"@alma-harness/core": "^0.6.0",
|
|
34
|
+
"@alma-harness/execution": "^0.6.0",
|
|
35
|
+
"@alma-harness/memory": "^0.6.0",
|
|
36
|
+
"@alma-harness/postgres": "^0.6.0",
|
|
37
|
+
"@alma-harness/postgres-execution": "^0.6.0",
|
|
38
|
+
"@alma-harness/loop": "^0.6.0",
|
|
39
|
+
"@alma-harness/single-call": "^0.6.0"
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"typecheck": "tsc --noEmit",
|
|
49
|
+
"test": "vitest run",
|
|
50
|
+
"build": "tsup"
|
|
51
|
+
},
|
|
52
|
+
"main": "./dist/index.js",
|
|
53
|
+
"types": "./dist/index.d.ts"
|
|
54
|
+
}
|