@loomwork/conversation 0.0.0-stage → 0.1.1
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/NOTICE +8 -0
- package/README.md +117 -2
- package/dist/access.d.ts +59 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +178 -0
- package/dist/access.js.map +1 -0
- package/dist/bargeIn.d.ts +62 -0
- package/dist/bargeIn.d.ts.map +1 -0
- package/dist/bargeIn.js +110 -0
- package/dist/bargeIn.js.map +1 -0
- package/dist/budget.d.ts +82 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +134 -0
- package/dist/budget.js.map +1 -0
- package/dist/conversation.d.ts +59 -0
- package/dist/conversation.d.ts.map +1 -0
- package/dist/conversation.js +786 -0
- package/dist/conversation.js.map +1 -0
- package/dist/conversations.d.ts +149 -0
- package/dist/conversations.d.ts.map +1 -0
- package/dist/conversations.js +498 -0
- package/dist/conversations.js.map +1 -0
- package/dist/feed.d.ts +32 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +83 -0
- package/dist/feed.js.map +1 -0
- package/dist/hub.d.ts +119 -0
- package/dist/hub.d.ts.map +1 -0
- package/dist/hub.js +257 -0
- package/dist/hub.js.map +1 -0
- package/dist/ids.d.ts +9 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +29 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +65 -0
- package/dist/index.js.map +1 -0
- package/dist/providerError.d.ts +10 -0
- package/dist/providerError.d.ts.map +1 -0
- package/dist/providerError.js +16 -0
- package/dist/providerError.js.map +1 -0
- package/dist/reader.d.ts +53 -0
- package/dist/reader.d.ts.map +1 -0
- package/dist/reader.js +217 -0
- package/dist/reader.js.map +1 -0
- package/dist/settled.d.ts +49 -0
- package/dist/settled.d.ts.map +1 -0
- package/dist/settled.js +51 -0
- package/dist/settled.js.map +1 -0
- package/dist/signEnvelope.d.ts +51 -0
- package/dist/signEnvelope.d.ts.map +1 -0
- package/dist/signEnvelope.js +55 -0
- package/dist/signEnvelope.js.map +1 -0
- package/dist/summarizerText.d.ts +2 -0
- package/dist/summarizerText.d.ts.map +1 -0
- package/dist/summarizerText.js +9 -0
- package/dist/summarizerText.js.map +1 -0
- package/dist/turn.d.ts +67 -0
- package/dist/turn.d.ts.map +1 -0
- package/dist/turn.js +213 -0
- package/dist/turn.js.map +1 -0
- package/dist/types.d.ts +267 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +18 -0
- package/dist/types.js.map +1 -0
- package/package.json +61 -3
- package/src/access.ts +221 -0
- package/src/bargeIn.ts +172 -0
- package/src/budget.ts +170 -0
- package/src/conversation.ts +961 -0
- package/src/conversations.ts +690 -0
- package/src/feed.ts +112 -0
- package/src/hub.ts +336 -0
- package/src/ids.ts +25 -0
- package/src/index.ts +75 -0
- package/src/reader.ts +274 -0
- package/src/settled.ts +80 -0
- package/src/signEnvelope.ts +76 -0
- package/src/summarizerText.ts +3 -0
- package/src/turn.ts +344 -0
- package/src/types.ts +271 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,118 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/conversation — a durable dialogue as one chained execution
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A chat is not a request; it is a long-lived thing that is answered turn by turn, interrupted, resumed after a restart and rotated so it never grows without bound. `@loomwork/conversation` assembles that from parts the kernel already has — the inbox (ADR 0110), `agentLoop$` (ADR 0121) and `continueAsNew` (ADR 0109) — and adds nothing to the kernel (ADR 0122).
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { agent$ } from "@loomwork/core";
|
|
7
|
+
import { createAgentModelEffect } from "@loomwork/agent";
|
|
8
|
+
import {
|
|
9
|
+
ConversationHub, conversation$, createConversations, inboxBargeIn,
|
|
10
|
+
} from "@loomwork/conversation";
|
|
11
|
+
|
|
12
|
+
const hub = new ConversationHub();
|
|
13
|
+
effects.register("model", createAgentModelEffect(hub.wrapProvider(provider), {
|
|
14
|
+
stream: true,
|
|
15
|
+
onDelta: hub.deltaSink(), // live tokens, attributed to the conversation turn running the call
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
const chat = conversation$({
|
|
19
|
+
key: process.env.CONVERSATION_KEY!, // signs every inbox envelope: the body acts only on what the host's client signed
|
|
20
|
+
agent: { definition: agent$({ id: "assistant", name: "Assistant", tools: [] }), modelToolId: "model" },
|
|
21
|
+
budget: { contextWindow: 200_000, summarizerToolId: "summarize" }, // token-aware; evicted turns are summarized
|
|
22
|
+
bargeIn: inboxBargeIn(eventStore), // a new message interrupts the running turn
|
|
23
|
+
hub,
|
|
24
|
+
});
|
|
25
|
+
runtime.registerFlow(chat.definition, chat.runner); // runtime needs kernel.features.inbox + continueAsNew
|
|
26
|
+
|
|
27
|
+
const conversations = createConversations({ runtime, eventStore, flow: chat, policy }); // policy: the owner-scoped executionAccessPolicy the runtime uses
|
|
28
|
+
const { conversationId } = await conversations.start({ principal });
|
|
29
|
+
await conversations.sendTurn(conversationId, "Plan my trip", { principal }); // a retry with the same messageId is delivered once
|
|
30
|
+
await conversations.sendTurn(conversationId, "Actually, make it two days", { principal }); // barges in
|
|
31
|
+
const page = await conversations.history(conversationId, { principal, direction: "backward", limit: 20 });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Writing a summarizer (`budget.summarizerToolId`)
|
|
35
|
+
|
|
36
|
+
The effect receives `{ messages: { role, content }[] }` and returns `{ summary: string }`. Like `agentLoop$` `compaction.toolId` (whose input also carries wrappers: failed tool calls, MCP results and origin-bearing history are tainted, in text parts and `tool_result` content), the user's words (and the previous summary) arrive with `content` as a **tainted wrapper** `{ __loomTainted: { origin }, value }` - untrusted data, neither a string nor parts; assistant replies are plain strings. `textOf(m.content)` on a wrapper throws `TaintedContentError` (it used to be an obscure `TypeError` that failed the step and killed the conversation at its first rotation). Read messages with `summarizerText`, which unwraps every level (top level, text parts, `tool_result` content) and so serves both effects:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { summarizerText } from "@loomwork/conversation";
|
|
40
|
+
const transcript = input.messages.map((m) => `${m.role}: ${summarizerText(m.content)}`).join("\n");
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The text is **untrusted data**: summarize or quote it, never put it in a system prompt or assistant message (if the summarizer calls an LLM with this text, re-wrap it with `tainted(text, origin)` and put it in a user message, never the system prompt: `guardRequest` can no longer refuse it after unwrapping). The returned summary is clipped to `maxSummaryTokens` and re-injected as a fenced `user` message with origin `conversation:summary`, never the system prompt.
|
|
44
|
+
|
|
45
|
+
## Work after a turn (`turnSettledObserver`)
|
|
46
|
+
|
|
47
|
+
To start work once a reply exists (a title, an index entry, something composed from the answer), observe the runtime's durable writes. The listener is called once per settled turn of ANY conversation of the flow, after the closing record is in the log:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { turnSettledObserver } from "@loomwork/conversation";
|
|
51
|
+
|
|
52
|
+
const runtime = new WorkflowRuntime({
|
|
53
|
+
...deps,
|
|
54
|
+
onDurableEvent: turnSettledObserver(chat, (e) => {
|
|
55
|
+
// { conversationId, executionId, turn, ord, status, asker? }: ids and status, never text
|
|
56
|
+
if (e.status === "complete") jobs.enqueue(`visual:${e.conversationId}:${e.ord}`);
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
// or defineConfig({ observability: { onDurableEvent: turnSettledObserver(chat, listener) } })
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- **Which records.** The assistant record closes an answered turn (`complete`, `interrupted`, `failed`); a message refused before any model call is closed by its user record (`rejected`, `turn: 0`). An edit is a new turn and is reported as one.
|
|
63
|
+
- **After the write, at most once** (ADR 0147). A `history` read made from the listener sees the record. Replay and recovery serve records from the log and append nothing, so they never call it again. A process that dies after the write but before the call never makes it: keep a recovery path (for example, read `history` from the last `ord` you handled) and key the work by `conversationId` + `ord`.
|
|
64
|
+
- **Isolated, not awaited.** A throw or a rejection goes to the runtime's `onWarn` and never touches the turn. The listener's synchronous part runs on the runtime's write chain, so enqueue the work and return.
|
|
65
|
+
- **One `onDurableEvent` per runtime**, and only this runtime's writes. To observe other things too, call each observer from one function.
|
|
66
|
+
|
|
67
|
+
## What it is
|
|
68
|
+
|
|
69
|
+
- **One chained execution per conversation.** The id is the chain id. Idle, it is parked on the inbox; a user turn wakes it. Every `rotateEveryTurns` (default 100) it `continueAsNew`s, carrying the rolling summary and a bounded window, so any one generation's fold and log stay small. The inbox cursors and dedupe window cross the rotation (kernel).
|
|
70
|
+
- **Barge-in without killing the execution.** The turn runs with an `AbortSignal`; `inboxBargeIn` fires it when a message lands. `agentLoop$` reads it only through *recorded* checkpoints, so the interruption is replayed identically after a restart. The partial reply is kept (`status: "interrupted"`) and is part of the context of the next turn. Without a `bargeIn` source the conversation queues instead.
|
|
71
|
+
- **A transcript with no second store.** Every message is a decision (`source: "conversation-record"`) recorded exactly once; `history` / `followConversation` read them back with bounded `readRange` reads across all generations. Cursors are `<generation>.<sequence>`. Every record carries a unique, increasing `ord` (kept across rotations; absent on records written before R17b); a rejected message is no turn (`turn: 0`) so it never shares a number with the next accepted turn.
|
|
72
|
+
- **Editing an earlier turn.** `sendTurn(id, text, { editOf: <ord of your earlier user turn> })`. `editOf` is signed inside the host envelope and validated by the conversation: it must be an accepted user turn of the same asker still in the prompt window, else the message is recorded as rejected (`edit-invalid`) and not obeyed. An edit is still a NEW turn (append-only) that records `editOf` (and `editOfTurn`, the edited turn's number, for display); the model is told, inside the fenced user text, which earlier message it replaces.
|
|
73
|
+
- **Token budgeting.** `fitToWindow` keeps the newest turns that fit beside the system prompt, the summary and the new message, with a pluggable `TokenCounter` (a conservative heuristic by default, a provider's exact counter if you have one). The verdict is a recorded decision, so a replay never re-decides it, and a prompt that cannot fit even alone is rejected without a model call. `agent.compaction` keeps bounding the transcript *inside* a run; the two compose.
|
|
74
|
+
- **Trust.** A turn runs as the conversation owner, and **only the owner may talk to it**: the identity that started it (tenant, actor and `onBehalfOf` all equal) may send, close, read and stream; anyone else, a same-tenant colleague included, gets the same not-found as for a conversation that does not exist. A user's words are untrusted data: tainted `conversation:user`, fenced at the prompt boundary, never in the system prompt. A failed turn records a fixed reason and an `errorId`; the real error goes to `onError`.
|
|
75
|
+
- **Shared mode** (`conversation$({ shared })`, ADR 0122 D10) for a chat several people use: an explicit participant set (not a tenant), each turn run as its **asker** in its own execution (their grants, their quotas), each answer classified by the tools it touched and filtered per viewer (a bare placeholder for whoever is not cleared, in history, on the stream and in the model's context), a summary built only from unrestricted turns, FIFO queueing, and a participant may interrupt only their own turn.
|
|
76
|
+
|
|
77
|
+
## Signing an inbox envelope yourself (`signInboxEnvelope`)
|
|
78
|
+
|
|
79
|
+
`sendTurn` builds and signs the envelope for you. A test, or a trusted server-side bridge that writes to the inbox itself, can sign one with the conversation's key:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { CONVERSATION_TOPIC, signInboxEnvelope } from "@loomwork/conversation";
|
|
83
|
+
|
|
84
|
+
await runtime.send(conversationId, {
|
|
85
|
+
topic: CONVERSATION_TOPIC,
|
|
86
|
+
payload: signInboxEnvelope(process.env.CONVERSATION_KEY!, {
|
|
87
|
+
conversationId, kind: "user", text: "hello", id: crypto.randomUUID(), iat: Date.now(),
|
|
88
|
+
asker: { actor: "alice", tenant: "t1" },
|
|
89
|
+
}),
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- It needs the conversation's envelope key (`key`). **The key is the authority of a trusted bridge**: keep it server-side, never in a browser, and rotate it with `previousKeys`. The body is validated up front with the conversation's own shape rules; a malformed body (including a `user` envelope with blank `text`) throws `InvalidEnvelopeError` instead of being signed. `maxTurnChars` is a check the conversation applies to the body, not one the signer can make (it does not know the flow's limit).
|
|
94
|
+
- A key holder CAN: speak as ANY participant in shared mode (the body checks only that the named `asker` is a participant); edit that asker's earlier turns (`editOf` is checked against the signed `asker`, so it is only as strong as that); bypass the client-only checks (the per-asker `maxQueuedPerAsker` cap, and "a delegated sender needs `principalFor`"); write to every conversation the runtime's `send` policy admits (the key is per flow, not per tenant, so that policy alone decides which conversations a bridge can reach); and, in owner mode, nothing beyond what the runtime access policy lets it `send` (the `asker` = owner comparison is a consistency check, not authentication).
|
|
95
|
+
- A key holder can NOT: sign for another conversation, replay an `id`, use an `iat` at or before the staleness floor or outside the age window, speak as anyone but the owner in owner mode, name a non-participant in shared mode, close a shared conversation unless the named closer is the owner, the service principal or a `manageParticipants` manager, send a turn over `maxTurnChars` (the body rejects it), or send a malformed envelope.
|
|
96
|
+
- A future `iat` up to +60 s is accepted. Once that id is evicted from the replay set the staleness floor moves forward, so a key holder can make legitimate envelopes issued in the following ~60 s `stale`.
|
|
97
|
+
- Use it in tests and trusted bridges. Applications call `sendTurn`.
|
|
98
|
+
|
|
99
|
+
## Read these before relying on it
|
|
100
|
+
|
|
101
|
+
- **The runtime policy must be owner-scoped** for `query`, `send`, `cancel` and `resume` (`executionAccessPolicy({ rules: { query: "owner", send: "owner", cancel: "owner", resume: "owner" } })`): the conversation's log holds the unfiltered transcript. `createConversations` refuses anything looser unless you acknowledge it. Every inbox message is also a host-signed, conversation-bound, single-use, fresh envelope, so what the policy lets through is still not obeyed unless the host signed it.
|
|
102
|
+
|
|
103
|
+
- A registered `ctx.receive` is **not** woken while a step is in flight (ADR 0110): barge-in cannot be built from the inbox primitives, which is why the signal comes from a store subscription outside the flow body (ADR 0122 D2).
|
|
104
|
+
- A tool call already in flight when a barge-in lands completes; the loop stops before issuing the next call. Wrap the provider with `hub.wrapProvider` to cut the *generation* itself.
|
|
105
|
+
- `needsApproval` (and its deprecated alias `requireApproval`) is refused (a parked approval gate and the barge-in model do not compose).
|
|
106
|
+
- Live deltas are transient and per-process. Only the durable messages are resumable.
|
|
107
|
+
|
|
108
|
+
## Security: the raw inbox path
|
|
109
|
+
|
|
110
|
+
Anything holding the host's system grant can bypass the client API and write straight into a conversation's inbox:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
runtime.send(conversationId, { topic: CONVERSATION_TOPIC, payload }, runtime.systemOptions());
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`conversations.send` is the intended door; this raw path skips it. What still defends the conversation is the envelope check in the body, not the caller's good manners: the payload must be a host-signed, conversation-bound, single-use envelope (a forged or unsigned one is dropped), it must be above the replay floor (an old or replayed envelope is dropped), and in shared mode its author must pass the participant check. **A host must never expose this path** to users, to a route handler that forwards a client-supplied `executionId` or payload, or to a plugin it does not trust, and must keep `CONVERSATION_KEY` out of anything that can send. Expose conversations only through `createConversations` (or `@loomwork/plugin-conversation-sse`, which does) ([ADR 0122](../../docs/adr/0122-conversation-layer-streaming-transport-and-token-budgeting.md) D10).
|
|
117
|
+
|
|
118
|
+
See [ADR 0122](../../docs/adr/0122-conversation-layer-streaming-transport-and-token-budgeting.md) and, for the browser, [`@loomwork/plugin-conversation-sse`](../../plugins/conversation-sse/README.md).
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type PrincipalChain } from "@loomwork/effect-runtime";
|
|
2
|
+
import { type EventStore } from "@loomwork/event-runtime";
|
|
3
|
+
export interface Identity {
|
|
4
|
+
tenant?: string;
|
|
5
|
+
actor: string;
|
|
6
|
+
onBehalfOf?: string;
|
|
7
|
+
}
|
|
8
|
+
/** The identity of a principal, or `undefined` when it names no actor (it cannot own or join anything). */
|
|
9
|
+
export declare function identityOf(principal: PrincipalChain | undefined): Identity | undefined;
|
|
10
|
+
/** A stable key for an identity. */
|
|
11
|
+
export declare function identityKey(i: Identity): string;
|
|
12
|
+
export declare function sameIdentity(a: Identity | undefined, b: Identity | undefined): boolean;
|
|
13
|
+
/** Validate an untrusted value as an identity (log content, a request body). */
|
|
14
|
+
export declare function parseIdentity(v: unknown): Identity | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* The key the kernel dedupes a message on (`MESSAGE_CONSUMED.messageId`, ADR 0110 D6): SHA-256 of
|
|
17
|
+
* `[tenant, actor, onBehalfOf, messageId]` for the SENDER the runtime recorded. The client stamps it into
|
|
18
|
+
* the payload so a barge-in watcher can tell a sender's own retry from someone else replaying the id.
|
|
19
|
+
*/
|
|
20
|
+
export declare function senderKey(sender: {
|
|
21
|
+
tenant?: string;
|
|
22
|
+
actor?: string;
|
|
23
|
+
onBehalfOf?: string;
|
|
24
|
+
}, messageId: string): string;
|
|
25
|
+
/** The domain every inbox envelope is signed under, so a MAC made for another purpose with the same key is not one. */
|
|
26
|
+
export declare const ENVELOPE_DOMAIN = "loom/conversation/envelope/v1";
|
|
27
|
+
/**
|
|
28
|
+
* HMAC-SHA-256 of the canonical body under `key`, separated by `domain` (empty = none: the turn-id derivation
|
|
29
|
+
* keeps its original input so ids of in-flight turn executions do not move).
|
|
30
|
+
*/
|
|
31
|
+
export declare function sign(key: string, body: Record<string, unknown>, domain?: string): string;
|
|
32
|
+
/** Verify against `key` and, for a rotation window, any of `previous`. */
|
|
33
|
+
export declare function verifySignature(key: string | readonly string[], body: Record<string, unknown>, sig: unknown, domain?: string): boolean;
|
|
34
|
+
export interface ParticipantChange {
|
|
35
|
+
op: "add" | "remove";
|
|
36
|
+
identity: Identity;
|
|
37
|
+
by: Identity;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The participant set of shared conversations. Reads are consulted on EVERY request (a removal takes
|
|
41
|
+
* effect on the next one) and by the conversation body, inside a recorded decision, when it dequeues a turn.
|
|
42
|
+
*/
|
|
43
|
+
export interface ParticipantDirectory {
|
|
44
|
+
list(conversationId: string): Promise<Identity[]>;
|
|
45
|
+
apply(conversationId: string, change: ParticipantChange): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
export declare const MAX_PARTICIPANTS = 100;
|
|
48
|
+
export declare class ParticipantLimitError extends Error {
|
|
49
|
+
readonly code = "PARTICIPANT_LIMIT";
|
|
50
|
+
constructor();
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The standard directory: an append-only side stream `conversation-participants:<id>` on the event store,
|
|
54
|
+
* one `PARTICIPANT_CHANGED` event per change, so membership is a durable, ordered, auditable log (who added
|
|
55
|
+
* whom, when) shared by every node that reads the same store. It is NOT the conversation's own log (a
|
|
56
|
+
* sender must never append to the owner's log; ADR 0110 D1) and not a kernel stream.
|
|
57
|
+
*/
|
|
58
|
+
export declare function logParticipants(store: EventStore, now?: () => number): ParticipantDirectory;
|
|
59
|
+
//# sourceMappingURL=access.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,cAAc,EAAiB,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAEL,KAAK,UAAU,EAGhB,MAAM,yBAAyB,CAAC;AAUjC,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,2GAA2G;AAC3G,wBAAgB,UAAU,CAAC,SAAS,EAAE,cAAc,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,CAStF;AAED,oCAAoC;AACpC,wBAAgB,WAAW,CAAC,CAAC,EAAE,QAAQ,GAAG,MAAM,CAE/C;AAED,wBAAgB,YAAY,CAAC,CAAC,EAAE,QAAQ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,uBAAuB;;CAKrC;AAmBD;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,UAAU,EACjB,GAAG,GAAE,MAAM,MAAiB,GAC3B,oBAAoB,CA2CtB"}
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ParticipantLimitError = exports.MAX_PARTICIPANTS = exports.ENVELOPE_DOMAIN = void 0;
|
|
4
|
+
exports.identityOf = identityOf;
|
|
5
|
+
exports.identityKey = identityKey;
|
|
6
|
+
exports.sameIdentity = sameIdentity;
|
|
7
|
+
exports.parseIdentity = parseIdentity;
|
|
8
|
+
exports.senderKey = senderKey;
|
|
9
|
+
exports.sign = sign;
|
|
10
|
+
exports.verifySignature = verifySignature;
|
|
11
|
+
exports.logParticipants = logParticipants;
|
|
12
|
+
const node_crypto_1 = require("node:crypto");
|
|
13
|
+
const effect_runtime_1 = require("@loomwork/effect-runtime");
|
|
14
|
+
const event_runtime_1 = require("@loomwork/event-runtime");
|
|
15
|
+
/** The identity of a principal, or `undefined` when it names no actor (it cannot own or join anything). */
|
|
16
|
+
function identityOf(principal) {
|
|
17
|
+
if (principal === undefined)
|
|
18
|
+
return undefined;
|
|
19
|
+
const actor = principal.actor;
|
|
20
|
+
if (typeof actor !== "string" || actor.trim() === "")
|
|
21
|
+
return undefined;
|
|
22
|
+
return {
|
|
23
|
+
actor,
|
|
24
|
+
...(typeof principal.tenant === "string" && { tenant: principal.tenant }),
|
|
25
|
+
...(typeof principal.onBehalfOf === "string" && { onBehalfOf: principal.onBehalfOf }),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** A stable key for an identity. */
|
|
29
|
+
function identityKey(i) {
|
|
30
|
+
return (0, effect_runtime_1.identityKeyOf)(i);
|
|
31
|
+
}
|
|
32
|
+
function sameIdentity(a, b) {
|
|
33
|
+
return a !== undefined && b !== undefined && identityKey(a) === identityKey(b);
|
|
34
|
+
}
|
|
35
|
+
/** Validate an untrusted value as an identity (log content, a request body). */
|
|
36
|
+
function parseIdentity(v) {
|
|
37
|
+
if (typeof v !== "object" || v === null)
|
|
38
|
+
return undefined;
|
|
39
|
+
const o = v;
|
|
40
|
+
if (typeof o.actor !== "string" || o.actor.trim() === "" || o.actor.length > 256)
|
|
41
|
+
return undefined;
|
|
42
|
+
for (const k of ["tenant", "onBehalfOf"]) {
|
|
43
|
+
if (o[k] !== undefined && (typeof o[k] !== "string" || o[k].length > 256)) {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
actor: o.actor,
|
|
49
|
+
...(typeof o.tenant === "string" && { tenant: o.tenant }),
|
|
50
|
+
...(typeof o.onBehalfOf === "string" && { onBehalfOf: o.onBehalfOf }),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The key the kernel dedupes a message on (`MESSAGE_CONSUMED.messageId`, ADR 0110 D6): SHA-256 of
|
|
55
|
+
* `[tenant, actor, onBehalfOf, messageId]` for the SENDER the runtime recorded. The client stamps it into
|
|
56
|
+
* the payload so a barge-in watcher can tell a sender's own retry from someone else replaying the id.
|
|
57
|
+
*/
|
|
58
|
+
function senderKey(sender, messageId) {
|
|
59
|
+
return (0, node_crypto_1.createHash)("sha256")
|
|
60
|
+
.update(JSON.stringify([sender.tenant ?? "", sender.actor ?? "", sender.onBehalfOf ?? "", messageId]))
|
|
61
|
+
.digest("hex");
|
|
62
|
+
}
|
|
63
|
+
// ── Host-signed envelopes (shared mode) ───────────────────────────────────────────────────────────
|
|
64
|
+
//
|
|
65
|
+
// In shared mode the asker is named INSIDE the message, because the sender the runtime records is the
|
|
66
|
+
// host. The inbox is writable by anything the runtime's policy admits, so the body accepts an asker only
|
|
67
|
+
// from an envelope signed with the host's key: a colleague who can raw-`send` cannot speak as someone else.
|
|
68
|
+
function canonical(v) {
|
|
69
|
+
return JSON.stringify(v, (_k, x) => x !== null && typeof x === "object" && !Array.isArray(x)
|
|
70
|
+
? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1)))
|
|
71
|
+
: x);
|
|
72
|
+
}
|
|
73
|
+
/** The domain every inbox envelope is signed under, so a MAC made for another purpose with the same key is not one. */
|
|
74
|
+
exports.ENVELOPE_DOMAIN = "loom/conversation/envelope/v1";
|
|
75
|
+
/**
|
|
76
|
+
* HMAC-SHA-256 of the canonical body under `key`, separated by `domain` (empty = none: the turn-id derivation
|
|
77
|
+
* keeps its original input so ids of in-flight turn executions do not move).
|
|
78
|
+
*/
|
|
79
|
+
function sign(key, body, domain = "") {
|
|
80
|
+
const input = domain === "" ? canonical(body) : `${domain}\u0000${canonical(body)}`;
|
|
81
|
+
return (0, node_crypto_1.createHmac)("sha256", key).update(input).digest("hex");
|
|
82
|
+
}
|
|
83
|
+
/** Verify against `key` and, for a rotation window, any of `previous`. */
|
|
84
|
+
function verifySignature(key, body, sig, domain = "") {
|
|
85
|
+
if (typeof sig !== "string" || sig.length !== 64)
|
|
86
|
+
return false;
|
|
87
|
+
const got = Buffer.from(sig, "hex");
|
|
88
|
+
let ok = false;
|
|
89
|
+
for (const k of typeof key === "string" ? [key] : key) {
|
|
90
|
+
const want = Buffer.from(sign(k, body, domain), "hex");
|
|
91
|
+
// no early exit: the time taken does not say which key matched
|
|
92
|
+
if (got.length === want.length && (0, node_crypto_1.timingSafeEqual)(got, want))
|
|
93
|
+
ok = true;
|
|
94
|
+
}
|
|
95
|
+
return ok;
|
|
96
|
+
}
|
|
97
|
+
exports.MAX_PARTICIPANTS = 100;
|
|
98
|
+
const MAX_CHANGES = 2000;
|
|
99
|
+
const MEMBERS_WORKFLOW = "conversation-participants";
|
|
100
|
+
class ParticipantLimitError extends Error {
|
|
101
|
+
code = "PARTICIPANT_LIMIT";
|
|
102
|
+
constructor() {
|
|
103
|
+
super(`a conversation holds at most ${exports.MAX_PARTICIPANTS} participants`);
|
|
104
|
+
this.name = "ParticipantLimitError";
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
exports.ParticipantLimitError = ParticipantLimitError;
|
|
108
|
+
function fold(events) {
|
|
109
|
+
const set = new Map();
|
|
110
|
+
for (const e of events) {
|
|
111
|
+
// Anyone who can start an execution under this stream's id can write ITS first event; only our own
|
|
112
|
+
// change events count, whoever else has written there.
|
|
113
|
+
if (e.eventType !== "PARTICIPANT_CHANGED" || e.workflowId !== MEMBERS_WORKFLOW)
|
|
114
|
+
continue;
|
|
115
|
+
const p = e.payload;
|
|
116
|
+
const identity = parseIdentity(p?.identity);
|
|
117
|
+
if (identity === undefined)
|
|
118
|
+
continue;
|
|
119
|
+
if (p?.op === "add")
|
|
120
|
+
set.set(identityKey(identity), identity);
|
|
121
|
+
else if (p?.op === "remove")
|
|
122
|
+
set.delete(identityKey(identity));
|
|
123
|
+
}
|
|
124
|
+
return [...set.values()];
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The standard directory: an append-only side stream `conversation-participants:<id>` on the event store,
|
|
128
|
+
* one `PARTICIPANT_CHANGED` event per change, so membership is a durable, ordered, auditable log (who added
|
|
129
|
+
* whom, when) shared by every node that reads the same store. It is NOT the conversation's own log (a
|
|
130
|
+
* sender must never append to the owner's log; ADR 0110 D1) and not a kernel stream.
|
|
131
|
+
*/
|
|
132
|
+
function logParticipants(store, now = Date.now) {
|
|
133
|
+
const streamOf = (id) => `conversation-participants:${id}`;
|
|
134
|
+
return {
|
|
135
|
+
async list(conversationId) {
|
|
136
|
+
const stream = streamOf(conversationId);
|
|
137
|
+
const tip = await (0, event_runtime_1.headOf)(store, stream);
|
|
138
|
+
if (tip === null)
|
|
139
|
+
return [];
|
|
140
|
+
return fold(await (0, event_runtime_1.readRangeOf)(store, stream, 0, Math.min(tip, MAX_CHANGES)));
|
|
141
|
+
},
|
|
142
|
+
async apply(conversationId, change) {
|
|
143
|
+
const stream = streamOf(conversationId);
|
|
144
|
+
for (let attempt = 0; attempt < 32; attempt++) {
|
|
145
|
+
const tip = await (0, event_runtime_1.headOf)(store, stream);
|
|
146
|
+
const next = (tip ?? -1) + 1;
|
|
147
|
+
if (next >= MAX_CHANGES)
|
|
148
|
+
throw new Error("participant change log is full; compact it");
|
|
149
|
+
const events = tip === null ? [] : await (0, event_runtime_1.readRangeOf)(store, stream, 0, tip);
|
|
150
|
+
const current = fold(events);
|
|
151
|
+
if (change.op === "add" &&
|
|
152
|
+
current.length >= exports.MAX_PARTICIPANTS &&
|
|
153
|
+
!current.some((i) => sameIdentity(i, change.identity))) {
|
|
154
|
+
throw new ParticipantLimitError();
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await store.append({
|
|
158
|
+
id: `${stream}#${next}`,
|
|
159
|
+
workflowId: MEMBERS_WORKFLOW,
|
|
160
|
+
executionId: stream,
|
|
161
|
+
eventType: "PARTICIPANT_CHANGED",
|
|
162
|
+
sequence: next,
|
|
163
|
+
timestamp: now(),
|
|
164
|
+
payload: change,
|
|
165
|
+
});
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
if (err instanceof event_runtime_1.DuplicateSequenceError)
|
|
170
|
+
continue; // another writer took the slot: re-read
|
|
171
|
+
throw err;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
throw new Error("could not record the participant change (contended)");
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=access.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"access.js","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":";;;AAwBA,gCASC;AAGD,kCAEC;AAED,oCAEC;AAGD,sCAeC;AAOD,8BASC;AAuBD,oBAGC;AAGD,0CAeC;AAsDD,0CA8CC;AA5ND,6CAAsE;AACtE,6DAA8E;AAC9E,2DAKiC;AAgBjC,2GAA2G;AAC3G,SAAgB,UAAU,CAAC,SAAqC;IAC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