@loomwork/conversation 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { EffectRuntime, PrincipalChain } from "@loomwork/effect-runtime";
|
|
3
|
+
import { type EventStore, readRangeOf } from "@loomwork/event-runtime";
|
|
4
|
+
import type { SendResult, WorkflowRuntime } from "@loomwork/workflow-runtime";
|
|
5
|
+
import {
|
|
6
|
+
ENVELOPE_DOMAIN,
|
|
7
|
+
type Identity,
|
|
8
|
+
identityKey,
|
|
9
|
+
identityOf,
|
|
10
|
+
parseIdentity,
|
|
11
|
+
sameIdentity,
|
|
12
|
+
senderKey,
|
|
13
|
+
verifySignature,
|
|
14
|
+
} from "./access";
|
|
15
|
+
import { type BargeInSource, inboxBargeIn, pendingMessages } from "./bargeIn";
|
|
16
|
+
import { type ConversationFlow, signedEnvelope } from "./conversation";
|
|
17
|
+
import { generationId, generationOf, isValidConversationId } from "./ids";
|
|
18
|
+
import {
|
|
19
|
+
type ConversationReader,
|
|
20
|
+
InvalidCursorError,
|
|
21
|
+
type ReadOptions,
|
|
22
|
+
type ReadResult,
|
|
23
|
+
createConversationReader,
|
|
24
|
+
parseCursor,
|
|
25
|
+
recordOf,
|
|
26
|
+
} from "./reader";
|
|
27
|
+
import { registerSharedTurnEffect } from "./turn";
|
|
28
|
+
import { CONVERSATION_TOPIC, type HistoryEntry } from "./types";
|
|
29
|
+
|
|
30
|
+
// ── The client API of a conversation (ADR 0122 D1, D8, D10) ──────────────────────────────────────
|
|
31
|
+
//
|
|
32
|
+
// WHO MAY DO WHAT. Every call is first judged HERE, against the conversation's recorded owner, and a
|
|
33
|
+
// caller who is not allowed gets the same `ConversationNotFoundError` as for a conversation that does not
|
|
34
|
+
// exist (existence is not revealed). The default is OWNER-ONLY: only the identity that started the
|
|
35
|
+
// conversation (tenant, actor and onBehalfOf all equal; a delegate is a different identity) may send,
|
|
36
|
+
// close, read or stream. SHARED mode adds an explicit participant set (D10). The runtime's own policy
|
|
37
|
+
// still applies underneath in owner-only mode; in shared mode the client, being the one place that knows
|
|
38
|
+
// the participant set, performs the runtime calls with the runtime's system grant after its own check.
|
|
39
|
+
|
|
40
|
+
export class ConversationNotFoundError extends Error {
|
|
41
|
+
readonly code = "CONVERSATION_NOT_FOUND";
|
|
42
|
+
constructor(readonly conversationId: string) {
|
|
43
|
+
super(`conversation "${conversationId}" not found`);
|
|
44
|
+
this.name = "ConversationNotFoundError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class InvalidTurnError extends Error {
|
|
49
|
+
readonly code = "INVALID_TURN";
|
|
50
|
+
constructor(detail: string) {
|
|
51
|
+
super(`invalid turn: ${detail}`);
|
|
52
|
+
this.name = "InvalidTurnError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ConversationsDeps {
|
|
57
|
+
runtime: WorkflowRuntime;
|
|
58
|
+
/** The store the runtime appends to (history is read from it with bounded range reads). */
|
|
59
|
+
eventStore: EventStore;
|
|
60
|
+
/** The `conversation$` flow (registered here if the runtime does not know it yet). */
|
|
61
|
+
flow: ConversationFlow;
|
|
62
|
+
/** Characters a sent turn may have (the flow enforces its own `maxTurnChars` too). Default 32 000. */
|
|
63
|
+
maxTurnChars?: number;
|
|
64
|
+
/** Shared mode: the effect runtime to register the turn effect on. Required for a shared flow. */
|
|
65
|
+
effects?: EffectRuntime;
|
|
66
|
+
/** Shared mode: what notices a participant's own follow-up while their turn runs. Default `inboxBargeIn(eventStore)`. */
|
|
67
|
+
bargeIn?: BargeInSource;
|
|
68
|
+
/**
|
|
69
|
+
* Shared mode: the principal a turn runs as for an asker identity. Default: the identity itself (tenant,
|
|
70
|
+
* actor, onBehalfOf), which carries NO delegation token. A sender who presents a delegation (an attenuated
|
|
71
|
+
* grant) is therefore REFUSED unless this is supplied: rebuilding their principal from identity alone
|
|
72
|
+
* would give the turn the actor's full grants. A host that supplies it maps the identity to the narrowed
|
|
73
|
+
* principal (re-issuing the delegation from its own grant table, ADR 0111 D4).
|
|
74
|
+
*/
|
|
75
|
+
principalFor?: (asker: Identity) => PrincipalChain | Promise<PrincipalChain>;
|
|
76
|
+
/**
|
|
77
|
+
* The execution policy the runtime was built with (`executionAccessPolicy(...)`, the SAME object). The
|
|
78
|
+
* conversation's log holds the unfiltered transcript, so a runtime that lets a tenant peer `query`,
|
|
79
|
+
* `send` to, `cancel` or `resume` another principal's execution defeats every per-viewer rule here: it is
|
|
80
|
+
* REFUSED at construction unless `query`, `send`, `cancel`, `resume` and `actAsOwner` are `owner`-scoped
|
|
81
|
+
* (or denied).
|
|
82
|
+
*/
|
|
83
|
+
policy?: { readonly scopes?: Readonly<Record<string, string>> };
|
|
84
|
+
/**
|
|
85
|
+
* Acknowledge that the runtime's policy is owner-scoped for those ops although it cannot be inspected
|
|
86
|
+
* (a custom `ExecutionAuthorizer`, or no authorizer in a development process). The host asserts it; this
|
|
87
|
+
* layer cannot check it. The body still acts only on envelopes signed by the host (D10), which is what
|
|
88
|
+
* remains if the assertion is false.
|
|
89
|
+
*/
|
|
90
|
+
runtimePolicyIsOwnerScoped?: boolean;
|
|
91
|
+
/** Shared mode: turns one asker may have waiting in the inbox before `sendTurn` refuses. Default 8. */
|
|
92
|
+
maxQueuedPerAsker?: number;
|
|
93
|
+
/** The clock envelopes are stamped with (tests). */
|
|
94
|
+
now?: () => number;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class QueueFullError extends Error {
|
|
98
|
+
readonly code = "QUEUE_FULL";
|
|
99
|
+
constructor() {
|
|
100
|
+
super("too many of your turns are already waiting");
|
|
101
|
+
this.name = "QueueFullError";
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const POLICED_OPS = [
|
|
106
|
+
"query",
|
|
107
|
+
"send",
|
|
108
|
+
"cancel",
|
|
109
|
+
"resume",
|
|
110
|
+
"actAsOwner",
|
|
111
|
+
"annotate",
|
|
112
|
+
"discard",
|
|
113
|
+
"quarantine",
|
|
114
|
+
"release",
|
|
115
|
+
] as const;
|
|
116
|
+
|
|
117
|
+
function assertOwnerScopedPolicy(deps: ConversationsDeps): void {
|
|
118
|
+
if (deps.runtimePolicyIsOwnerScoped === true) return;
|
|
119
|
+
const scopes = deps.policy?.scopes;
|
|
120
|
+
if (scopes === undefined) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
"createConversations: cannot establish that the runtime's execution policy is owner-scoped. Pass `policy` (the `executionAccessPolicy(...)` object the runtime was built with) or acknowledge it with `runtimePolicyIsOwnerScoped: true`. A conversation's log holds the unfiltered transcript; a policy that lets a tenant peer query, send to, cancel or resume it defeats every access rule."
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
for (const op of POLICED_OPS) {
|
|
126
|
+
const scope = scopes[op];
|
|
127
|
+
if (scope !== "owner" && scope !== "deny") {
|
|
128
|
+
throw new Error(
|
|
129
|
+
`createConversations: the runtime's policy scopes "${op}" as "${String(scope)}"; it must be "owner" or "deny" (rules: { ${POLICED_OPS.map((o) => `${o}: "owner"`).join(", ")} })`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface CallOptions {
|
|
136
|
+
/** The authenticated caller. */
|
|
137
|
+
principal?: PrincipalChain;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface SendTurnOptions extends CallOptions {
|
|
141
|
+
/**
|
|
142
|
+
* The idempotency key. A retry with the SAME id from the SAME sender is consumed once (at-least-once
|
|
143
|
+
* send, exactly-once consume, within the kernel's dedupe window); minted when omitted.
|
|
144
|
+
*/
|
|
145
|
+
messageId?: string;
|
|
146
|
+
/**
|
|
147
|
+
* This turn EDITS an earlier user turn of yours: that turn's `ord` (from `history`). Signed into the
|
|
148
|
+
* envelope and validated by the conversation: it must be an accepted user turn of the same asker still in
|
|
149
|
+
* the prompt window, else the turn is recorded as rejected (`edit-invalid`) and not obeyed. The edit is a
|
|
150
|
+
* NEW turn (the log is append-only); the model is told it replaces the earlier message.
|
|
151
|
+
*/
|
|
152
|
+
editOf?: number;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export type ConversationState = "open" | "closed" | "failed" | "cancelled";
|
|
156
|
+
|
|
157
|
+
export interface ConversationStatus {
|
|
158
|
+
conversationId: string;
|
|
159
|
+
/** The generation that currently holds the conversation (it advances at each rotation). */
|
|
160
|
+
executionId: string;
|
|
161
|
+
generation: number;
|
|
162
|
+
state: ConversationState;
|
|
163
|
+
/** A turn is being answered right now (the last recorded message is an unanswered user turn). */
|
|
164
|
+
running: boolean;
|
|
165
|
+
/** Turns accepted so far (the highest turn number in the transcript), 0 if none. */
|
|
166
|
+
turns: number;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface Conversations {
|
|
170
|
+
readonly mode: "owner" | "shared";
|
|
171
|
+
/** Whether the runtime fails closed on a principal-less call (it has an execution authorizer that requires one). */
|
|
172
|
+
readonly requiresPrincipal: boolean;
|
|
173
|
+
start(options?: CallOptions & { conversationId?: string }): Promise<{ conversationId: string }>;
|
|
174
|
+
sendTurn(conversationId: string, text: string, options?: SendTurnOptions): Promise<SendResult>;
|
|
175
|
+
close(conversationId: string, options?: SendTurnOptions): Promise<SendResult>;
|
|
176
|
+
history(conversationId: string, options?: ReadOptions & CallOptions): Promise<ReadResult>;
|
|
177
|
+
status(conversationId: string, options?: CallOptions): Promise<ConversationStatus>;
|
|
178
|
+
/**
|
|
179
|
+
* Prove the caller may read the conversation and return its head generation, WITHOUT reading any
|
|
180
|
+
* history: the gate a streaming transport runs once per connection (and again to re-authorize).
|
|
181
|
+
*/
|
|
182
|
+
authorizeRead(conversationId: string, options?: CallOptions): Promise<{ generation: number }>;
|
|
183
|
+
/**
|
|
184
|
+
* SHARED mode: apply the per-viewer filter to raw entries (from `followConversation`, a history page):
|
|
185
|
+
* an entry whose classes the viewer is not cleared for becomes a bare `restricted` placeholder. Owner-only
|
|
186
|
+
* conversations pass entries through. Does NOT authorize: call `authorizeRead` first.
|
|
187
|
+
*/
|
|
188
|
+
filterEntries(
|
|
189
|
+
entries: readonly HistoryEntry[],
|
|
190
|
+
principal?: PrincipalChain
|
|
191
|
+
): Promise<HistoryEntry[]>;
|
|
192
|
+
/** SHARED mode: the viewer's identity key (to match against a live event's `asker`), or undefined. */
|
|
193
|
+
viewerKey(principal?: PrincipalChain): string | undefined;
|
|
194
|
+
/** Whether `principal` may (still) read the conversation: a cheap membership check, for a stream to run per delivered message. */
|
|
195
|
+
isParticipant(conversationId: string, principal?: PrincipalChain): Promise<boolean>;
|
|
196
|
+
/**
|
|
197
|
+
* Whether `principal` is the conversation's OWNER (the same identity rule as ownership: tenant, actor and
|
|
198
|
+
* onBehalfOf all equal). Any refusal (unknown conversation, a non-participant, another tenant) is `false`,
|
|
199
|
+
* never a distinguishable error. ADR 0133 D6 uses it for the live reasoning audience.
|
|
200
|
+
*/
|
|
201
|
+
isOwner(conversationId: string, principal?: PrincipalChain): Promise<boolean>;
|
|
202
|
+
/** SHARED mode: the participant set. Owner / manager only. */
|
|
203
|
+
participants(conversationId: string, options?: CallOptions): Promise<Identity[]>;
|
|
204
|
+
addParticipant(conversationId: string, who: Identity, options?: CallOptions): Promise<void>;
|
|
205
|
+
removeParticipant(conversationId: string, who: Identity, options?: CallOptions): Promise<void>;
|
|
206
|
+
readonly reader: ConversationReader;
|
|
207
|
+
/**
|
|
208
|
+
* ADR 0133 D6 - where the DURABLE reasoning of one assistant reply lives, for a caller entitled to read it.
|
|
209
|
+
* `cursor` is the reply's history cursor. OWNER mode: the owner (the only reader) gets the generation that
|
|
210
|
+
* ran the turn, narrowed to that turn's steps. SHARED mode: the reply's asker AND the conversation's
|
|
211
|
+
* owner get it (the turn's own execution); every other participant, a non-participant, another tenant, an unknown
|
|
212
|
+
* cursor and a record that is not an assistant reply all get the same `ConversationNotFoundError`.
|
|
213
|
+
* Does not read the reasoning itself: the transport joins it with `readReasoning` and its store.
|
|
214
|
+
*/
|
|
215
|
+
reasoningTarget(
|
|
216
|
+
conversationId: string,
|
|
217
|
+
cursor: string,
|
|
218
|
+
options?: CallOptions
|
|
219
|
+
): Promise<{ executionId: string; stepPrefix?: string }>;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The identity fields exactly as `runtime.send` stamps them on a message (ADR 0110 D1). */
|
|
223
|
+
function rawSender(p: PrincipalChain | undefined): {
|
|
224
|
+
tenant?: string;
|
|
225
|
+
actor?: string;
|
|
226
|
+
onBehalfOf?: string;
|
|
227
|
+
} {
|
|
228
|
+
return {
|
|
229
|
+
...(typeof p?.tenant === "string" && { tenant: p.tenant }),
|
|
230
|
+
...(typeof p?.actor === "string" && { actor: p.actor }),
|
|
231
|
+
...(typeof p?.onBehalfOf === "string" && { onBehalfOf: p.onBehalfOf }),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Pages of 100 records `status` walks back at most to find the newest accepted turn. */
|
|
236
|
+
const STATUS_MAX_PAGES = 50;
|
|
237
|
+
const OWNER_CACHE_MAX = 1024;
|
|
238
|
+
|
|
239
|
+
export function createConversations(deps: ConversationsDeps): Conversations {
|
|
240
|
+
assertOwnerScopedPolicy(deps);
|
|
241
|
+
const { runtime, eventStore, flow } = deps;
|
|
242
|
+
const key = flow.config.key;
|
|
243
|
+
const now = deps.now ?? Date.now;
|
|
244
|
+
const maxQueued = deps.maxQueuedPerAsker ?? 8;
|
|
245
|
+
const maxTurnChars = deps.maxTurnChars ?? 32_000;
|
|
246
|
+
const reader = createConversationReader(eventStore);
|
|
247
|
+
const mode = flow.mode;
|
|
248
|
+
const shared = flow.config.shared;
|
|
249
|
+
const service = shared === undefined ? undefined : identityOf(shared.servicePrincipal);
|
|
250
|
+
/** No end-user identity may be the service principal that owns the coordinating executions. */
|
|
251
|
+
const isService = (i: Identity | undefined): boolean =>
|
|
252
|
+
service !== undefined && sameIdentity(i, service);
|
|
253
|
+
let registered = false;
|
|
254
|
+
const ensureRegistered = (): void => {
|
|
255
|
+
if (registered) return;
|
|
256
|
+
// Idempotent for the same id + version + content (the kernel's own rule).
|
|
257
|
+
runtime.registerFlow(flow.definition as never, flow.runner as never);
|
|
258
|
+
if (shared !== undefined && flow.sharedTurn !== undefined) {
|
|
259
|
+
runtime.registerFlow(
|
|
260
|
+
flow.sharedTurn.flow.definition as never,
|
|
261
|
+
flow.sharedTurn.flow.runner as never
|
|
262
|
+
);
|
|
263
|
+
if (deps.effects === undefined) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
"createConversations: a shared conversation needs `effects` to register its turn effect on"
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
registerSharedTurnEffect(deps.effects, flow.sharedTurn.effectId, {
|
|
269
|
+
runtime,
|
|
270
|
+
turnFlow: flow.sharedTurn.flow,
|
|
271
|
+
signals: flow.sharedTurn.signals,
|
|
272
|
+
key,
|
|
273
|
+
...(flow.config.previousKeys !== undefined && { previousKeys: flow.config.previousKeys }),
|
|
274
|
+
eventStore,
|
|
275
|
+
...(flow.config.onError !== undefined && { onError: flow.config.onError }),
|
|
276
|
+
bargeIn: deps.bargeIn ?? inboxBargeIn(eventStore),
|
|
277
|
+
...(deps.principalFor !== undefined && { principalFor: deps.principalFor }),
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
registered = true;
|
|
281
|
+
};
|
|
282
|
+
if (shared !== undefined) ensureRegistered();
|
|
283
|
+
|
|
284
|
+
// ── ownership ─────────────────────────────────────────────────────────────────────────────────
|
|
285
|
+
// The owner is read once per conversation from sequence 0 of generation 0 (immutable, start-once):
|
|
286
|
+
// the identity the client stamped into the start input, cross-checked against the identity the
|
|
287
|
+
// kernel recorded for the starting principal when that is stored verbatim. A disagreement is an
|
|
288
|
+
// UNKNOWN owner, which nobody matches.
|
|
289
|
+
const CONFLICT = "conflict" as const;
|
|
290
|
+
const owners = new Map<string, Identity | null | typeof CONFLICT>();
|
|
291
|
+
async function ownerOf(conversationId: string): Promise<Identity | undefined | typeof CONFLICT> {
|
|
292
|
+
const cached = owners.get(conversationId);
|
|
293
|
+
if (cached !== undefined) return cached ?? undefined;
|
|
294
|
+
const first = (await readRangeOf(eventStore, conversationId, 0, 0))[0];
|
|
295
|
+
if (first === undefined) throw new ConversationNotFoundError(conversationId);
|
|
296
|
+
const payload = first.payload as {
|
|
297
|
+
input?: { owner?: unknown };
|
|
298
|
+
principal?: { identity?: unknown };
|
|
299
|
+
} | null;
|
|
300
|
+
const stamped = parseIdentity(payload?.input?.owner);
|
|
301
|
+
const recorded = parseIdentity(payload?.principal?.identity);
|
|
302
|
+
let owner: Identity | undefined | typeof CONFLICT;
|
|
303
|
+
if (shared !== undefined) {
|
|
304
|
+
// SHARED: the coordinator is owned by the SERVICE principal, and the human owner is the stamp. Anything
|
|
305
|
+
// else (a coordinator someone started as themselves, claiming another owner) is a conflict.
|
|
306
|
+
owner =
|
|
307
|
+
recorded !== undefined && isService(recorded) && stamped !== undefined ? stamped : CONFLICT;
|
|
308
|
+
} else if (stamped !== undefined && recorded !== undefined) {
|
|
309
|
+
owner = sameIdentity(stamped, recorded) ? stamped : CONFLICT;
|
|
310
|
+
} else owner = stamped ?? recorded;
|
|
311
|
+
if (owners.size >= OWNER_CACHE_MAX) owners.delete(owners.keys().next().value as string);
|
|
312
|
+
owners.set(conversationId, owner ?? null);
|
|
313
|
+
return owner;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
interface Access {
|
|
317
|
+
owner: Identity | undefined;
|
|
318
|
+
viewer: Identity | undefined;
|
|
319
|
+
isOwner: boolean;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Judge `principal` for `need`. ANY refusal is the same `ConversationNotFoundError`. */
|
|
323
|
+
async function authorize(
|
|
324
|
+
conversationId: string,
|
|
325
|
+
principal: PrincipalChain | undefined,
|
|
326
|
+
need: "member" | "manage"
|
|
327
|
+
): Promise<Access> {
|
|
328
|
+
if (!isValidConversationId(conversationId)) throw new ConversationNotFoundError(conversationId);
|
|
329
|
+
const recorded = await ownerOf(conversationId);
|
|
330
|
+
// A conflicting owner record is its own state: it matches NOBODY, the anonymous caller included.
|
|
331
|
+
if (recorded === CONFLICT) throw new ConversationNotFoundError(conversationId);
|
|
332
|
+
const owner = recorded;
|
|
333
|
+
const viewer = identityOf(principal);
|
|
334
|
+
if (isService(viewer)) throw new ConversationNotFoundError(conversationId);
|
|
335
|
+
// A conversation with no recorded owner (started with no principal) is "owned" by the anonymous.
|
|
336
|
+
const isOwner = owner === undefined ? principal === undefined : sameIdentity(viewer, owner);
|
|
337
|
+
const access = { owner, viewer, isOwner };
|
|
338
|
+
if (isOwner) return access;
|
|
339
|
+
if (shared === undefined || viewer === undefined)
|
|
340
|
+
throw new ConversationNotFoundError(conversationId);
|
|
341
|
+
if (need === "manage") {
|
|
342
|
+
if ((await shared.manageParticipants?.(viewer, conversationId)) !== true) {
|
|
343
|
+
throw new ConversationNotFoundError(conversationId);
|
|
344
|
+
}
|
|
345
|
+
return access;
|
|
346
|
+
}
|
|
347
|
+
const members = await shared.directory.list(conversationId);
|
|
348
|
+
if (!members.some((m) => sameIdentity(m, viewer)))
|
|
349
|
+
throw new ConversationNotFoundError(conversationId);
|
|
350
|
+
return access;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** The runtime options for an authorized call: the caller's principal (owner-only) or the host's grant (shared). */
|
|
354
|
+
const runtimeOpts = (principal: PrincipalChain | undefined) =>
|
|
355
|
+
mode === "shared" ? runtime.systemOptions() : principal !== undefined ? { principal } : {};
|
|
356
|
+
|
|
357
|
+
async function head(
|
|
358
|
+
conversationId: string,
|
|
359
|
+
principal: PrincipalChain | undefined,
|
|
360
|
+
need: "member" | "manage" = "member"
|
|
361
|
+
) {
|
|
362
|
+
const access = await authorize(conversationId, principal, need);
|
|
363
|
+
const h = await runtime.followToHead(conversationId, runtimeOpts(principal));
|
|
364
|
+
if (h === null) throw new ConversationNotFoundError(conversationId);
|
|
365
|
+
return { h, access };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function send(
|
|
369
|
+
conversationId: string,
|
|
370
|
+
body: Record<string, unknown>,
|
|
371
|
+
need: "member" | "manage",
|
|
372
|
+
o?: SendTurnOptions
|
|
373
|
+
): Promise<SendResult> {
|
|
374
|
+
const { viewer } = await authorize(conversationId, o?.principal, need);
|
|
375
|
+
const messageId = o?.messageId ?? randomUUID();
|
|
376
|
+
let id: string;
|
|
377
|
+
let kernelId: string;
|
|
378
|
+
if (mode === "shared") {
|
|
379
|
+
if (viewer === undefined) throw new ConversationNotFoundError(conversationId);
|
|
380
|
+
// A sender presenting a delegation (an attenuated grant) cannot be run faithfully from their identity
|
|
381
|
+
// alone: the turn would get the actor's FULL grants. Refused unless the host maps identity to a
|
|
382
|
+
// principal itself.
|
|
383
|
+
if (o?.principal?.delegation !== undefined && deps.principalFor === undefined) {
|
|
384
|
+
throw new InvalidTurnError(
|
|
385
|
+
"a delegated sender cannot be run as themselves in a shared conversation unless the host supplies `principalFor`"
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
if (body.kind === "user" && (await queuedFor(conversationId, viewer)) >= maxQueued) {
|
|
389
|
+
throw new QueueFullError();
|
|
390
|
+
}
|
|
391
|
+
// The kernel sees the HOST as the sender, so its dedupe key is made per-asker here.
|
|
392
|
+
id = senderKey(viewer, messageId);
|
|
393
|
+
kernelId = id;
|
|
394
|
+
} else {
|
|
395
|
+
id = senderKey(rawSender(o?.principal), messageId);
|
|
396
|
+
kernelId = messageId;
|
|
397
|
+
}
|
|
398
|
+
// The signature covers the conversation, the sender's voice, the text, the id and the issue time: none
|
|
399
|
+
// of it can be lifted into another message, conversation or time (the body also refuses a replayed id).
|
|
400
|
+
const payload = signedEnvelope(key, {
|
|
401
|
+
...body,
|
|
402
|
+
conversationId,
|
|
403
|
+
id,
|
|
404
|
+
iat: now(),
|
|
405
|
+
...(viewer !== undefined && { asker: viewer }),
|
|
406
|
+
});
|
|
407
|
+
try {
|
|
408
|
+
return await runtime.send(
|
|
409
|
+
conversationId,
|
|
410
|
+
{ topic: CONVERSATION_TOPIC, payload, messageId: kernelId },
|
|
411
|
+
runtimeOpts(o?.principal)
|
|
412
|
+
);
|
|
413
|
+
} catch (err) {
|
|
414
|
+
// The runtime throws a plain Error for an unknown id (after the authorization-hiding step).
|
|
415
|
+
if (err instanceof Error && err.message.startsWith("No execution found for id")) {
|
|
416
|
+
throw new ConversationNotFoundError(conversationId);
|
|
417
|
+
}
|
|
418
|
+
throw err;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** How many of `asker`'s turns are waiting in the inbox (best effort across processes; small overshoot is possible). */
|
|
423
|
+
async function queuedFor(conversationId: string, asker: Identity): Promise<number> {
|
|
424
|
+
const g = (await reader.headGeneration(conversationId)) ?? 0;
|
|
425
|
+
const waiting = await pendingMessages(
|
|
426
|
+
eventStore,
|
|
427
|
+
conversationId,
|
|
428
|
+
generationId(conversationId, g),
|
|
429
|
+
maxQueued + 16
|
|
430
|
+
);
|
|
431
|
+
const k = identityKey(asker);
|
|
432
|
+
return (waiting ?? []).filter((m) => {
|
|
433
|
+
// Only envelopes the host SIGNED for this conversation count: a garbage-signature message naming
|
|
434
|
+
// someone as its asker must not fill that person's quota (a targeted denial of service).
|
|
435
|
+
const p = m.payload as Record<string, unknown> | null;
|
|
436
|
+
if (p === null || typeof p !== "object") return false;
|
|
437
|
+
const { sig, ...body } = p;
|
|
438
|
+
if (body.conversationId !== conversationId) return false;
|
|
439
|
+
if (!verifySignature([key, ...(flow.config.previousKeys ?? [])], body, sig, ENVELOPE_DOMAIN))
|
|
440
|
+
return false;
|
|
441
|
+
const a = parseIdentity(body.asker);
|
|
442
|
+
return a !== undefined && identityKey(a) === k;
|
|
443
|
+
}).length;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// A placeholder keeps `ord` (an ordinal is not content) and never `editOf` or any text.
|
|
447
|
+
const restricted = (e: HistoryEntry): HistoryEntry => ({
|
|
448
|
+
turn: e.turn,
|
|
449
|
+
...(e.ord !== undefined && { ord: e.ord }),
|
|
450
|
+
role: e.role,
|
|
451
|
+
text: "",
|
|
452
|
+
status: "restricted",
|
|
453
|
+
cursor: e.cursor,
|
|
454
|
+
executionId: e.executionId,
|
|
455
|
+
...(e.at !== undefined && { at: e.at }),
|
|
456
|
+
// Attribution survives: who asked is on the (unrestricted) user message beside it anyway.
|
|
457
|
+
...(e.asker !== undefined && { asker: e.asker }),
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
async function manageGuard(conversationId: string, o?: CallOptions): Promise<Access> {
|
|
461
|
+
if (shared === undefined) throw new Error("not a shared conversation");
|
|
462
|
+
return authorize(conversationId, o?.principal, "manage");
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
reader,
|
|
467
|
+
mode,
|
|
468
|
+
requiresPrincipal: runtime.requiresPrincipal === true,
|
|
469
|
+
async start(options = {}) {
|
|
470
|
+
ensureRegistered();
|
|
471
|
+
const conversationId = options.conversationId ?? `conv-${randomUUID()}`;
|
|
472
|
+
if (!isValidConversationId(conversationId)) {
|
|
473
|
+
throw new InvalidTurnError(`conversation id "${conversationId}" is not valid`);
|
|
474
|
+
}
|
|
475
|
+
const owner = identityOf(options.principal);
|
|
476
|
+
if (mode === "shared" && owner === undefined) {
|
|
477
|
+
throw new InvalidTurnError(
|
|
478
|
+
"a shared conversation needs an identified owner (a principal with an actor)"
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
if (isService(owner))
|
|
482
|
+
throw new InvalidTurnError("that identity is reserved for the service principal");
|
|
483
|
+
// Start-once for a chosen id (ADR 0103): a duplicate start rejects, nothing re-runs. The owner is
|
|
484
|
+
// stamped into the input: sequence 0 is immutable, which is what makes it a record. In SHARED mode the
|
|
485
|
+
// coordinating execution is owned by the SERVICE principal, so no participant (the human owner
|
|
486
|
+
// included) can `query` its unfiltered log through the runtime.
|
|
487
|
+
await runtime.start(
|
|
488
|
+
flow as never,
|
|
489
|
+
{ v: 1, seq: 0, ord: 0, turns: [], ...(owner !== undefined && { owner }) } as never,
|
|
490
|
+
{
|
|
491
|
+
executionId: conversationId,
|
|
492
|
+
...(shared !== undefined
|
|
493
|
+
? { principal: shared.servicePrincipal }
|
|
494
|
+
: options.principal !== undefined && { principal: options.principal }),
|
|
495
|
+
}
|
|
496
|
+
);
|
|
497
|
+
if (owner !== undefined) owners.set(conversationId, owner);
|
|
498
|
+
return { conversationId };
|
|
499
|
+
},
|
|
500
|
+
async sendTurn(conversationId, text, options) {
|
|
501
|
+
if (typeof text !== "string" || text.trim() === "") throw new InvalidTurnError("empty text");
|
|
502
|
+
if (text.length > maxTurnChars) throw new InvalidTurnError(`over ${maxTurnChars} characters`);
|
|
503
|
+
if (
|
|
504
|
+
options?.editOf !== undefined &&
|
|
505
|
+
(!Number.isSafeInteger(options.editOf) || options.editOf < 1)
|
|
506
|
+
) {
|
|
507
|
+
throw new InvalidTurnError(
|
|
508
|
+
"editOf must be a positive integer (the ord of an earlier turn)"
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
return send(
|
|
512
|
+
conversationId,
|
|
513
|
+
{ kind: "user", text, ...(options?.editOf !== undefined && { editOf: options.editOf }) },
|
|
514
|
+
"member",
|
|
515
|
+
options
|
|
516
|
+
);
|
|
517
|
+
},
|
|
518
|
+
close(conversationId, options) {
|
|
519
|
+
// Closing ends everyone's conversation: the owner (or, shared, a manager).
|
|
520
|
+
return send(
|
|
521
|
+
conversationId,
|
|
522
|
+
{ kind: "close" },
|
|
523
|
+
mode === "shared" ? "manage" : "member",
|
|
524
|
+
options
|
|
525
|
+
);
|
|
526
|
+
},
|
|
527
|
+
async authorizeRead(conversationId, options) {
|
|
528
|
+
const { h } = await head(conversationId, options?.principal);
|
|
529
|
+
return { generation: generationOf(h.executionId) };
|
|
530
|
+
},
|
|
531
|
+
async history(conversationId, options = {}) {
|
|
532
|
+
await authorize(conversationId, options.principal, "member");
|
|
533
|
+
const page = await reader.read(conversationId, options);
|
|
534
|
+
if (mode === "owner") return page;
|
|
535
|
+
return { ...page, entries: await this.filterEntries(page.entries, options.principal) };
|
|
536
|
+
},
|
|
537
|
+
async status(conversationId, options) {
|
|
538
|
+
const { h } = await head(conversationId, options?.principal);
|
|
539
|
+
const generation = generationOf(h.executionId);
|
|
540
|
+
// A rejected record belongs to no turn (`turn: 0`): the turn count is the newest ACCEPTED record's
|
|
541
|
+
// number, looked for by paging backward (bounded: STATUS_MAX_PAGES pages of 100 records).
|
|
542
|
+
let last = await reader.read(conversationId, { direction: "backward", limit: 100 });
|
|
543
|
+
const newest = last.entries[0];
|
|
544
|
+
let accepted = last.entries.find((e) => e.turn > 0)?.turn;
|
|
545
|
+
for (let page = 1; accepted === undefined && !last.done && page < STATUS_MAX_PAGES; page++) {
|
|
546
|
+
last = await reader.read(conversationId, {
|
|
547
|
+
direction: "backward",
|
|
548
|
+
limit: 100,
|
|
549
|
+
...(last.nextCursor !== undefined && { cursor: last.nextCursor }),
|
|
550
|
+
});
|
|
551
|
+
accepted = last.entries.find((e) => e.turn > 0)?.turn;
|
|
552
|
+
}
|
|
553
|
+
const st = h.state.status;
|
|
554
|
+
const state: ConversationState =
|
|
555
|
+
st === "completed"
|
|
556
|
+
? "closed"
|
|
557
|
+
: st === "failed"
|
|
558
|
+
? "failed"
|
|
559
|
+
: st === "cancelled"
|
|
560
|
+
? "cancelled"
|
|
561
|
+
: "open";
|
|
562
|
+
return {
|
|
563
|
+
conversationId,
|
|
564
|
+
executionId: h.executionId,
|
|
565
|
+
generation,
|
|
566
|
+
state,
|
|
567
|
+
running: state === "open" && newest?.role === "user" && newest.status === "complete",
|
|
568
|
+
turns: accepted ?? 0,
|
|
569
|
+
};
|
|
570
|
+
},
|
|
571
|
+
async filterEntries(entries, principal) {
|
|
572
|
+
if (shared === undefined) return [...entries];
|
|
573
|
+
const viewer = identityOf(principal);
|
|
574
|
+
const cache = new Map<string, boolean>();
|
|
575
|
+
const out: HistoryEntry[] = [];
|
|
576
|
+
for (const e of entries) {
|
|
577
|
+
if (!e.classes?.length) {
|
|
578
|
+
out.push(stripTurnExecution(e, viewer));
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
// Your own answer is yours; anything else needs clearance for EVERY class, fail closed.
|
|
582
|
+
let ok = viewer !== undefined && sameIdentity(e.asker, viewer);
|
|
583
|
+
if (!ok && viewer !== undefined) {
|
|
584
|
+
const k = e.classes.join("\u0000");
|
|
585
|
+
let c = cache.get(k);
|
|
586
|
+
if (c === undefined) {
|
|
587
|
+
c = (await shared.cleared(viewer, e.classes)) === true;
|
|
588
|
+
cache.set(k, c);
|
|
589
|
+
}
|
|
590
|
+
ok = c;
|
|
591
|
+
}
|
|
592
|
+
out.push(ok ? stripClasses(e, viewer) : restricted(e));
|
|
593
|
+
}
|
|
594
|
+
return out;
|
|
595
|
+
},
|
|
596
|
+
async reasoningTarget(conversationId, cursor, options) {
|
|
597
|
+
const { viewer, isOwner } = await authorize(conversationId, options?.principal, "member");
|
|
598
|
+
const pos = parseCursor(cursor);
|
|
599
|
+
if (pos === undefined) throw new InvalidCursorError();
|
|
600
|
+
const head = await reader.headGeneration(conversationId);
|
|
601
|
+
if (head === undefined || pos.g > head) throw new ConversationNotFoundError(conversationId);
|
|
602
|
+
const ev = (
|
|
603
|
+
await readRangeOf(eventStore, generationId(conversationId, pos.g), pos.seq, pos.seq)
|
|
604
|
+
)[0];
|
|
605
|
+
const rec = ev === undefined ? undefined : recordOf(ev);
|
|
606
|
+
if (ev === undefined || rec === undefined || rec.role !== "assistant") {
|
|
607
|
+
throw new ConversationNotFoundError(conversationId);
|
|
608
|
+
}
|
|
609
|
+
if (shared !== undefined) {
|
|
610
|
+
// The turn's reasoning carries what the ASKER's turn saw; the per-viewer filter is not designed to
|
|
611
|
+
// classify free text, so nobody but the asker and the conversation's OWNER (owner ruling
|
|
612
|
+
// 2026-10-20) gets it.
|
|
613
|
+
const isAsker = viewer !== undefined && sameIdentity(rec.asker, viewer);
|
|
614
|
+
if (!isAsker && !isOwner) {
|
|
615
|
+
throw new ConversationNotFoundError(conversationId);
|
|
616
|
+
}
|
|
617
|
+
if (rec.turnExecutionId === undefined) throw new ConversationNotFoundError(conversationId);
|
|
618
|
+
return { executionId: rec.turnExecutionId };
|
|
619
|
+
}
|
|
620
|
+
const decisionId = (ev.payload as { decisionId?: unknown } | null)?.decisionId;
|
|
621
|
+
const loop = typeof decisionId === "string" ? /^(conv#o\d+):reply$/.exec(decisionId) : null;
|
|
622
|
+
if (loop === null) throw new ConversationNotFoundError(conversationId);
|
|
623
|
+
return { executionId: ev.executionId, stepPrefix: `${loop[1]}#` };
|
|
624
|
+
},
|
|
625
|
+
async isParticipant(conversationId, principal) {
|
|
626
|
+
try {
|
|
627
|
+
await authorize(conversationId, principal, "member");
|
|
628
|
+
return true;
|
|
629
|
+
} catch (err) {
|
|
630
|
+
if (err instanceof ConversationNotFoundError) return false;
|
|
631
|
+
throw err;
|
|
632
|
+
}
|
|
633
|
+
},
|
|
634
|
+
async isOwner(conversationId, principal) {
|
|
635
|
+
try {
|
|
636
|
+
return (await authorize(conversationId, principal, "member")).isOwner;
|
|
637
|
+
} catch (err) {
|
|
638
|
+
if (err instanceof ConversationNotFoundError) return false;
|
|
639
|
+
throw err;
|
|
640
|
+
}
|
|
641
|
+
},
|
|
642
|
+
viewerKey(principal) {
|
|
643
|
+
const v = identityOf(principal);
|
|
644
|
+
return v === undefined ? undefined : identityKey(v);
|
|
645
|
+
},
|
|
646
|
+
async participants(conversationId, options) {
|
|
647
|
+
await manageGuard(conversationId, options);
|
|
648
|
+
return (shared as NonNullable<typeof shared>).directory.list(conversationId);
|
|
649
|
+
},
|
|
650
|
+
async addParticipant(conversationId, who, options) {
|
|
651
|
+
const { viewer, owner } = await manageGuard(conversationId, options);
|
|
652
|
+
const identity = parseIdentity(who);
|
|
653
|
+
if (identity === undefined || viewer === undefined)
|
|
654
|
+
throw new InvalidTurnError("a participant needs an actor");
|
|
655
|
+
if (isService(identity))
|
|
656
|
+
throw new InvalidTurnError("that identity is reserved for the service principal");
|
|
657
|
+
if (sameIdentity(identity, owner)) return; // the owner is always a participant
|
|
658
|
+
await (shared as NonNullable<typeof shared>).directory.apply(conversationId, {
|
|
659
|
+
op: "add",
|
|
660
|
+
identity,
|
|
661
|
+
by: viewer,
|
|
662
|
+
});
|
|
663
|
+
},
|
|
664
|
+
async removeParticipant(conversationId, who, options) {
|
|
665
|
+
const { viewer, owner } = await manageGuard(conversationId, options);
|
|
666
|
+
const identity = parseIdentity(who);
|
|
667
|
+
if (identity === undefined || viewer === undefined)
|
|
668
|
+
throw new InvalidTurnError("a participant needs an actor");
|
|
669
|
+
if (sameIdentity(identity, owner)) throw new InvalidTurnError("the owner cannot be removed");
|
|
670
|
+
await (shared as NonNullable<typeof shared>).directory.apply(conversationId, {
|
|
671
|
+
op: "remove",
|
|
672
|
+
identity,
|
|
673
|
+
by: viewer,
|
|
674
|
+
});
|
|
675
|
+
},
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** A visible entry still tells the viewer WHICH classes it touched? No: labels may themselves be sensitive. */
|
|
680
|
+
function stripClasses(e: HistoryEntry, viewer: Identity | undefined): HistoryEntry {
|
|
681
|
+
const { classes: _classes, ...rest } = e;
|
|
682
|
+
return stripTurnExecution(rest, viewer);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** The turn execution's id is the ASKER's: another viewer is not handed a handle on it. */
|
|
686
|
+
function stripTurnExecution(e: HistoryEntry, viewer: Identity | undefined): HistoryEntry {
|
|
687
|
+
if (e.turnExecutionId === undefined || sameIdentity(e.asker, viewer)) return e;
|
|
688
|
+
const { turnExecutionId: _t, ...rest } = e;
|
|
689
|
+
return rest;
|
|
690
|
+
}
|