@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/src/turn.ts
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_INTERRUPTED,
|
|
3
|
+
type AgentHistoryMessage,
|
|
4
|
+
type InterruptedAgentRun,
|
|
5
|
+
agentLoop$,
|
|
6
|
+
classifyModelCallFailure,
|
|
7
|
+
} from "@loomwork/agent";
|
|
8
|
+
import { TypedFailure, flow$, fnv1a64 } from "@loomwork/core";
|
|
9
|
+
import { ToolEffect } from "@loomwork/effect-runtime";
|
|
10
|
+
import type { EffectRuntime, PrincipalChain } from "@loomwork/effect-runtime";
|
|
11
|
+
import type { EventStore } from "@loomwork/event-runtime";
|
|
12
|
+
import { readRangeOf } from "@loomwork/event-runtime";
|
|
13
|
+
import type { RegisteredFlow, WorkflowRuntime } from "@loomwork/workflow-runtime";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import {
|
|
16
|
+
ENVELOPE_DOMAIN,
|
|
17
|
+
type Identity,
|
|
18
|
+
identityKey,
|
|
19
|
+
identityOf,
|
|
20
|
+
parseIdentity,
|
|
21
|
+
sameIdentity,
|
|
22
|
+
sign,
|
|
23
|
+
verifySignature,
|
|
24
|
+
} from "./access";
|
|
25
|
+
import type { BargeInSource, StoredInboxMessage } from "./bargeIn";
|
|
26
|
+
import { withTurnScope } from "./hub";
|
|
27
|
+
import { type ConversationConfig, USER_ORIGIN } from "./types";
|
|
28
|
+
|
|
29
|
+
// ── SHARED MODE: a turn is its own execution, started as the ASKER (ADR 0122 D10) ───────────────────
|
|
30
|
+
//
|
|
31
|
+
// The conversation execution runs under its OWNER's authority and only COORDINATES: it dequeues a turn,
|
|
32
|
+
// asks this effect to run it, and records the transcript. The turn itself is a separate execution
|
|
33
|
+
// started with the asker's principal (ADR 0111), so every tool call, memory write, quota and capability
|
|
34
|
+
// check inside it is the ASKER's. A participant with fewer grants than the owner cannot reach a tool the
|
|
35
|
+
// owner can: the denial is raised inside the turn, and surfaces to that participant as a failed turn.
|
|
36
|
+
|
|
37
|
+
/** What the coordinator hands the turn. */
|
|
38
|
+
export interface TurnInput {
|
|
39
|
+
conversationId: string;
|
|
40
|
+
turn: number;
|
|
41
|
+
ord: number;
|
|
42
|
+
asker: Identity;
|
|
43
|
+
text: string;
|
|
44
|
+
/** The key the message was sent under (the barge-in watcher's retry test). */
|
|
45
|
+
id?: string;
|
|
46
|
+
history: AgentHistoryMessage[];
|
|
47
|
+
/** Idempotency keys of recent turns (the watcher must not treat a retry as an interruption). */
|
|
48
|
+
known: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface TurnResult {
|
|
52
|
+
status: "complete" | "interrupted" | "failed";
|
|
53
|
+
content: string;
|
|
54
|
+
/** Names of the tools the turn called (for classification). */
|
|
55
|
+
tools: string[];
|
|
56
|
+
/** A fixed, user-safe reason for `failed`. */
|
|
57
|
+
reason?:
|
|
58
|
+
| "denied"
|
|
59
|
+
| "model-error"
|
|
60
|
+
| "rate-limited"
|
|
61
|
+
| "quota"
|
|
62
|
+
| "tool-error"
|
|
63
|
+
| "turn-failed"
|
|
64
|
+
| "cancelled";
|
|
65
|
+
errorId?: string;
|
|
66
|
+
/** The memory scope this turn recalled from / wrote to, when the agent has a memory. */
|
|
67
|
+
memoryScope?: string;
|
|
68
|
+
/** The execution that ran the turn. */
|
|
69
|
+
turnExecutionId: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The turn execution's id: deterministic (a recovery finds the same execution) and UNGUESSABLE: the tail is
|
|
74
|
+
* an HMAC of the conversation and ordinal under the host's key. A predictable id let anyone who can start an
|
|
75
|
+
* execution plant one first and have the conversation adopt it (a forged answer, or a refusal to run).
|
|
76
|
+
*/
|
|
77
|
+
export const turnExecutionId = (conversationId: string, ord: number, key: string): string =>
|
|
78
|
+
`turn:${conversationId}:o${ord}:${sign(key, { conversationId, ord, purpose: "turn-id" }).slice(0, 24)}`;
|
|
79
|
+
|
|
80
|
+
/** The flow a shared turn runs as (one `agentLoop$`), with the abort signals the effect registers. */
|
|
81
|
+
export function sharedTurnFlow(
|
|
82
|
+
config: ConversationConfig,
|
|
83
|
+
signals: Map<string, AbortSignal>,
|
|
84
|
+
flowId: string
|
|
85
|
+
): RegisteredFlow<TurnInput, Omit<TurnResult, "turnExecutionId">> {
|
|
86
|
+
const definition = flow$({
|
|
87
|
+
id: flowId,
|
|
88
|
+
name: "Conversation turn",
|
|
89
|
+
version: "1.0.0",
|
|
90
|
+
inputSchema: z.any(),
|
|
91
|
+
outputSchema: z.any(),
|
|
92
|
+
steps: [],
|
|
93
|
+
});
|
|
94
|
+
const runner = async (
|
|
95
|
+
ctx: Parameters<RegisteredFlow["runner"]>[0],
|
|
96
|
+
input: TurnInput
|
|
97
|
+
): Promise<Omit<TurnResult, "turnExecutionId">> => {
|
|
98
|
+
const signal = signals.get(ctx.executionId);
|
|
99
|
+
const errorId = `err-${fnv1a64(ctx.executionId)}`;
|
|
100
|
+
// Memory is PER ASKER: the scope comes from the asker, never from a constant the host wrote once.
|
|
101
|
+
const scope = config.shared?.memoryScope?.(input.asker);
|
|
102
|
+
const wb = config.agent.writeBack;
|
|
103
|
+
try {
|
|
104
|
+
const out = await agentLoop$(
|
|
105
|
+
ctx,
|
|
106
|
+
{
|
|
107
|
+
...config.agent,
|
|
108
|
+
loopId: "turn",
|
|
109
|
+
...(signal !== undefined && { signal }),
|
|
110
|
+
...(scope !== undefined && { memoryScope: scope }),
|
|
111
|
+
...(scope !== undefined &&
|
|
112
|
+
typeof wb === "object" &&
|
|
113
|
+
wb !== null && { writeBack: { ...wb, scope } }),
|
|
114
|
+
},
|
|
115
|
+
{ prompt: input.text, promptOrigin: USER_ORIGIN, history: input.history }
|
|
116
|
+
);
|
|
117
|
+
return {
|
|
118
|
+
status: "complete",
|
|
119
|
+
content: out.content,
|
|
120
|
+
tools: out.toolCallLog.map((s) => s.toolName),
|
|
121
|
+
...(config.agent.memory !== undefined && scope !== undefined && { memoryScope: scope }),
|
|
122
|
+
};
|
|
123
|
+
} catch (e) {
|
|
124
|
+
if (e instanceof TypedFailure && e.channel === AGENT_INTERRUPTED) {
|
|
125
|
+
const run = e.payload as InterruptedAgentRun;
|
|
126
|
+
return {
|
|
127
|
+
status: "interrupted",
|
|
128
|
+
content: run.content ?? "",
|
|
129
|
+
tools: (run.toolCallLog ?? []).map((s) => s.toolName),
|
|
130
|
+
...(config.agent.memory !== undefined && scope !== undefined && { memoryScope: scope }),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Control flow (a park, a cancel, a kill switch, a divergence) is the runtime's and propagates;
|
|
134
|
+
// every other failure, even retryable=false, ends the turn failed with a fixed reason.
|
|
135
|
+
const kind = classifyModelCallFailure(e);
|
|
136
|
+
if (kind === "terminal") throw e;
|
|
137
|
+
config.onError?.(errorId, e, { conversationId: input.conversationId, turn: input.turn });
|
|
138
|
+
return { status: "failed", content: "", tools: [], reason: kind, errorId };
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
return { definition, runner } as unknown as RegisteredFlow<
|
|
142
|
+
TurnInput,
|
|
143
|
+
Omit<TurnResult, "turnExecutionId">
|
|
144
|
+
>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface TurnEffectDeps {
|
|
148
|
+
runtime: WorkflowRuntime;
|
|
149
|
+
/** Where the turn execution's recorded start is verified before it is adopted. */
|
|
150
|
+
eventStore: EventStore;
|
|
151
|
+
/** The host's log of the real error behind a failed turn. */
|
|
152
|
+
onError?: ConversationConfig["onError"];
|
|
153
|
+
turnFlow: RegisteredFlow<TurnInput, Omit<TurnResult, "turnExecutionId">>;
|
|
154
|
+
signals: Map<string, AbortSignal>;
|
|
155
|
+
key: string;
|
|
156
|
+
/** Keys still accepted for VERIFICATION during a rotation window. */
|
|
157
|
+
previousKeys?: readonly string[];
|
|
158
|
+
bargeIn?: BargeInSource;
|
|
159
|
+
/** The principal a turn runs as for an asker identity. Default: the identity itself (tenant, actor, onBehalfOf). */
|
|
160
|
+
principalFor?: (asker: Identity) => PrincipalChain | Promise<PrincipalChain>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The effect the coordinator runs a turn through. Idempotent by construction: the turn execution has a
|
|
167
|
+
* deterministic id, a re-run after a crash finds it (finished: use its output; unfinished: continue it).
|
|
168
|
+
*/
|
|
169
|
+
export function sharedTurnEffect(
|
|
170
|
+
deps: TurnEffectDeps
|
|
171
|
+
): ToolEffect<TurnInput & { ownerExecutionId: string }, TurnResult> {
|
|
172
|
+
const { runtime } = deps;
|
|
173
|
+
return new ToolEffect<TurnInput & { ownerExecutionId: string }, TurnResult>(
|
|
174
|
+
async (input, ctx) => {
|
|
175
|
+
const turnId = turnExecutionId(input.conversationId, input.ord, deps.key);
|
|
176
|
+
const ctl = new AbortController();
|
|
177
|
+
deps.signals.set(turnId, ctl.signal);
|
|
178
|
+
const sys = runtime.systemOptions();
|
|
179
|
+
// The coordinator being cancelled cancels the turn it is waiting on.
|
|
180
|
+
const onCancel = (): void => {
|
|
181
|
+
void runtime.cancel(turnId, undefined, sys).catch(() => undefined);
|
|
182
|
+
};
|
|
183
|
+
ctx.signal?.addEventListener("abort", onCancel, { once: true });
|
|
184
|
+
const askerKey = identityKey(input.asker);
|
|
185
|
+
let unwatch: (() => void) | undefined;
|
|
186
|
+
try {
|
|
187
|
+
if (deps.bargeIn !== undefined) {
|
|
188
|
+
unwatch = await deps.bargeIn(input.conversationId, input.ownerExecutionId, {
|
|
189
|
+
onMessage: () => ctl.abort(),
|
|
190
|
+
isKnown: (id) => input.known.includes(id) || id === input.id,
|
|
191
|
+
// Only the SAME asker's own signed message, for THIS conversation, interrupts their turn.
|
|
192
|
+
accept: (m: StoredInboxMessage) => {
|
|
193
|
+
const p = m.payload as Record<string, unknown> | null;
|
|
194
|
+
if (p === null || typeof p !== "object" || p.kind !== "user") return false;
|
|
195
|
+
const { sig, ...body } = p;
|
|
196
|
+
const asker = parseIdentity(p.asker);
|
|
197
|
+
return (
|
|
198
|
+
asker !== undefined &&
|
|
199
|
+
identityKey(asker) === askerKey &&
|
|
200
|
+
p.conversationId === input.conversationId &&
|
|
201
|
+
verifySignature(
|
|
202
|
+
[deps.key, ...(deps.previousKeys ?? [])],
|
|
203
|
+
body,
|
|
204
|
+
sig,
|
|
205
|
+
ENVELOPE_DOMAIN
|
|
206
|
+
)
|
|
207
|
+
);
|
|
208
|
+
},
|
|
209
|
+
idOf: (m) => {
|
|
210
|
+
const id = (m.payload as { id?: unknown } | null)?.id;
|
|
211
|
+
return typeof id === "string" ? id : undefined;
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const principal = await (deps.principalFor?.(input.asker) ?? {
|
|
216
|
+
actor: input.asker.actor,
|
|
217
|
+
...(input.asker.tenant !== undefined && { tenant: input.asker.tenant }),
|
|
218
|
+
...(input.asker.onBehalfOf !== undefined && { onBehalfOf: input.asker.onBehalfOf }),
|
|
219
|
+
});
|
|
220
|
+
return await withTurnScope(
|
|
221
|
+
input.conversationId,
|
|
222
|
+
input.turn,
|
|
223
|
+
ctl.signal,
|
|
224
|
+
async (): Promise<TurnResult> => {
|
|
225
|
+
const out = await runTurnExecution(deps, turnId, input, principal);
|
|
226
|
+
return { ...out, turnExecutionId: turnId };
|
|
227
|
+
},
|
|
228
|
+
undefined,
|
|
229
|
+
askerKey
|
|
230
|
+
);
|
|
231
|
+
} finally {
|
|
232
|
+
ctx.signal?.removeEventListener("abort", onCancel);
|
|
233
|
+
unwatch?.();
|
|
234
|
+
deps.signals.delete(turnId);
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
// Re-running it is safe: the turn execution is found by its deterministic id.
|
|
238
|
+
{ idempotent: true }
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* An execution already living under the turn's id is ADOPTED only if it is provably the one this turn
|
|
244
|
+
* would have started: our flow, started as THIS asker (the principal the kernel recorded), on THIS
|
|
245
|
+
* conversation, ordinal, message and text. Anything else is refused, never continued: continuing it would
|
|
246
|
+
* serve whatever its starter wanted as the participant's answer.
|
|
247
|
+
*/
|
|
248
|
+
async function adoptable(
|
|
249
|
+
deps: TurnEffectDeps,
|
|
250
|
+
turnId: string,
|
|
251
|
+
input: TurnInput,
|
|
252
|
+
principal: PrincipalChain
|
|
253
|
+
): Promise<boolean> {
|
|
254
|
+
const first = (await readRangeOf(deps.eventStore, turnId, 0, 0))[0];
|
|
255
|
+
if (first === undefined) return false;
|
|
256
|
+
if (first.workflowId !== deps.turnFlow.definition.id) return false;
|
|
257
|
+
const payload = first.payload as {
|
|
258
|
+
input?: Partial<TurnInput>;
|
|
259
|
+
principal?: { identity?: unknown };
|
|
260
|
+
} | null;
|
|
261
|
+
const recorded = parseIdentity(payload?.principal?.identity);
|
|
262
|
+
const expected = identityOf(principal);
|
|
263
|
+
if (recorded === undefined || expected === undefined || !sameIdentity(recorded, expected))
|
|
264
|
+
return false;
|
|
265
|
+
const started = payload?.input;
|
|
266
|
+
const a = started?.asker === undefined ? undefined : parseIdentity(started.asker);
|
|
267
|
+
return (
|
|
268
|
+
started?.conversationId === input.conversationId &&
|
|
269
|
+
started.ord === input.ord &&
|
|
270
|
+
started.turn === input.turn &&
|
|
271
|
+
started.text === input.text &&
|
|
272
|
+
started.id === input.id &&
|
|
273
|
+
a !== undefined &&
|
|
274
|
+
sameIdentity(a, input.asker)
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function runTurnExecution(
|
|
279
|
+
deps: TurnEffectDeps,
|
|
280
|
+
turnId: string,
|
|
281
|
+
input: TurnInput,
|
|
282
|
+
principal: PrincipalChain
|
|
283
|
+
): Promise<Omit<TurnResult, "turnExecutionId">> {
|
|
284
|
+
const { runtime, turnFlow } = deps;
|
|
285
|
+
const sys = runtime.systemOptions();
|
|
286
|
+
const errorId = `err-${fnv1a64(turnId)}`;
|
|
287
|
+
const failed = (
|
|
288
|
+
reason: NonNullable<TurnResult["reason"]>,
|
|
289
|
+
cause?: unknown
|
|
290
|
+
): Omit<TurnResult, "turnExecutionId"> => {
|
|
291
|
+
// The user sees the fixed reason; the host gets the cause (the first cut swallowed it).
|
|
292
|
+
deps.onError?.(errorId, cause ?? new Error(`turn execution ${reason}`), {
|
|
293
|
+
conversationId: input.conversationId,
|
|
294
|
+
turn: input.turn,
|
|
295
|
+
});
|
|
296
|
+
return { status: "failed", content: "", tools: [], reason, errorId };
|
|
297
|
+
};
|
|
298
|
+
try {
|
|
299
|
+
let state = await runtime.loadState(turnId, sys);
|
|
300
|
+
if (state === null) {
|
|
301
|
+
const handle = await runtime.start(
|
|
302
|
+
turnFlow,
|
|
303
|
+
{
|
|
304
|
+
conversationId: input.conversationId,
|
|
305
|
+
turn: input.turn,
|
|
306
|
+
ord: input.ord,
|
|
307
|
+
asker: input.asker,
|
|
308
|
+
text: input.text,
|
|
309
|
+
...(input.id !== undefined && { id: input.id }),
|
|
310
|
+
history: input.history,
|
|
311
|
+
known: [],
|
|
312
|
+
},
|
|
313
|
+
{ executionId: turnId, principal }
|
|
314
|
+
);
|
|
315
|
+
state = await handle.waitForCompletion();
|
|
316
|
+
} else {
|
|
317
|
+
if (!(await adoptable(deps, turnId, input, principal))) {
|
|
318
|
+
return failed(
|
|
319
|
+
"turn-failed",
|
|
320
|
+
new Error(`refused to adopt a foreign execution at "${turnId}"`)
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
if (!TERMINAL.has(state.status)) {
|
|
324
|
+
// The process died mid-turn: continue THE SAME execution (its log, its principal).
|
|
325
|
+
state = await (await runtime.restoreFromState(state)).waitForCompletion();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (state.status === "completed") {
|
|
329
|
+
return state.variables._output as Omit<TurnResult, "turnExecutionId">;
|
|
330
|
+
}
|
|
331
|
+
return failed(state.status === "cancelled" ? "cancelled" : "turn-failed");
|
|
332
|
+
} catch (err) {
|
|
333
|
+
return failed("turn-failed", err);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Register the turn effect on `effects` under `effectId`. */
|
|
338
|
+
export function registerSharedTurnEffect(
|
|
339
|
+
effects: EffectRuntime,
|
|
340
|
+
effectId: string,
|
|
341
|
+
deps: TurnEffectDeps
|
|
342
|
+
): void {
|
|
343
|
+
effects.register(effectId, sharedTurnEffect(deps) as never);
|
|
344
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import type { AgentLoopConfig } from "@loomwork/agent";
|
|
2
|
+
import type { PrincipalChain } from "@loomwork/effect-runtime";
|
|
3
|
+
import type { Identity, ParticipantDirectory } from "./access";
|
|
4
|
+
import type { BargeInSource } from "./bargeIn";
|
|
5
|
+
import type { TokenCounter } from "./budget";
|
|
6
|
+
import type { ConversationHub } from "./hub";
|
|
7
|
+
|
|
8
|
+
/** The inbox topic a conversation reads its turns from. */
|
|
9
|
+
export const CONVERSATION_TOPIC = "conversation:turn";
|
|
10
|
+
/**
|
|
11
|
+
* How a message (user turn, reply, partial, rejection) and the close are recorded: a DECISION with this
|
|
12
|
+
* `source`, one per fact, under a deterministic id (`conv#o<n>:user`, `conv#o<n>:reply`, `conv#closed`).
|
|
13
|
+
* Not `ctx.emit`: an emit is served on a re-run only when the log PROVES the replay (ADR 0102 D2), and
|
|
14
|
+
* an interrupted turn leaves an unsettled step behind that defeats the proof, so every re-run would
|
|
15
|
+
* append the transcript again. A decision is served by its id, always: exactly once.
|
|
16
|
+
*/
|
|
17
|
+
export const RECORD_SOURCE = "conversation-record";
|
|
18
|
+
/** The taint origin of an end user's words (ADR 0085). */
|
|
19
|
+
export const USER_ORIGIN = "conversation:user";
|
|
20
|
+
/** The taint origin of the rolling summary of evicted turns (it is model output over untrusted text). */
|
|
21
|
+
export const SUMMARY_ORIGIN = "conversation:summary";
|
|
22
|
+
|
|
23
|
+
/** What travels on the inbox topic. */
|
|
24
|
+
/** The body of a signed envelope (the signature covers every field). */
|
|
25
|
+
export interface SignedBody {
|
|
26
|
+
conversationId: string;
|
|
27
|
+
kind: "user" | "close";
|
|
28
|
+
/** The sender-bound idempotency key of the message (also its kernel messageId in shared mode). */
|
|
29
|
+
id: string;
|
|
30
|
+
/** Issue time, epoch ms. */
|
|
31
|
+
iat: number;
|
|
32
|
+
text?: string;
|
|
33
|
+
/** A user turn that EDITS an earlier one: the `ord` of that earlier user record. Signed with the rest. */
|
|
34
|
+
editOf?: number;
|
|
35
|
+
/** Who is speaking. Owner mode: the owner. Shared mode: the asker (or, for a close, the closer). */
|
|
36
|
+
asker?: Identity;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type TurnEnvelope =
|
|
40
|
+
/**
|
|
41
|
+
* `id` is the client idempotency key: the kernel's dedupe identity of the message (sender + messageId,
|
|
42
|
+
* see `senderKey`). It lets the barge-in watcher tell a sender's own retry from a new message.
|
|
43
|
+
* `asker` / `sig` appear only in shared mode (host-signed, see `sign`).
|
|
44
|
+
*/
|
|
45
|
+
| {
|
|
46
|
+
kind: "user";
|
|
47
|
+
text: string;
|
|
48
|
+
id?: string;
|
|
49
|
+
asker?: Identity;
|
|
50
|
+
iat?: number;
|
|
51
|
+
/** The `ord` of the user record this turn edits (validated by the body, ADR 0122 amendment R17b). */
|
|
52
|
+
editOf?: number;
|
|
53
|
+
}
|
|
54
|
+
| { kind: "close"; id?: string; asker?: Identity; iat?: number };
|
|
55
|
+
|
|
56
|
+
export type MessageStatus = "complete" | "interrupted" | "failed" | "rejected" | "restricted";
|
|
57
|
+
|
|
58
|
+
/** The payload of a {@link MESSAGE_EVENT}: the unit `history` returns. */
|
|
59
|
+
export interface MessageRecord {
|
|
60
|
+
kind?: "message";
|
|
61
|
+
/**
|
|
62
|
+
* The turn number, 1-based, global across the chain's generations. A REJECTED user record belongs to no
|
|
63
|
+
* turn and carries `0` (it used to carry the NEXT turn's number, which the next accepted turn then
|
|
64
|
+
* reused: use `ord` to tell records apart).
|
|
65
|
+
*/
|
|
66
|
+
turn: number;
|
|
67
|
+
/**
|
|
68
|
+
* A unique, monotonically increasing ordinal of this record within the conversation (1-based), carried
|
|
69
|
+
* across continue-as-new rotations. Not content: a restricted placeholder keeps it. ABSENT on records
|
|
70
|
+
* written before R17b (ADR 0122 amendment); uniqueness holds among the records that carry one.
|
|
71
|
+
*/
|
|
72
|
+
ord?: number;
|
|
73
|
+
/** A user turn that edits an earlier user turn: that turn's `ord` (the canonical reference). The edit is still a NEW turn (append-only). */
|
|
74
|
+
editOf?: number;
|
|
75
|
+
/** The NUMBER of the edited turn (for display); `editOf` stays the canonical reference. */
|
|
76
|
+
editOfTurn?: number;
|
|
77
|
+
role: "user" | "assistant";
|
|
78
|
+
/** The message. Untrusted when `role === "user"`: render it as TEXT, never as markup. */
|
|
79
|
+
text: string;
|
|
80
|
+
/**
|
|
81
|
+
* user: `complete` (accepted) or `rejected` (malformed / too long / over budget, with `reason`);
|
|
82
|
+
* assistant: `complete`, `interrupted` (a barge-in: `text` is the partial, possibly empty) or `failed`.
|
|
83
|
+
*/
|
|
84
|
+
status: MessageStatus;
|
|
85
|
+
reason?: string;
|
|
86
|
+
/** Shared mode: who asked (a user message) / whose turn this answers (a reply). Attribution, never an authority. */
|
|
87
|
+
asker?: Identity;
|
|
88
|
+
/**
|
|
89
|
+
* Shared mode: the data classes this entry touched (the declared class of every tool the turn called,
|
|
90
|
+
* plus the classes of every earlier entry that fed its context). Absent / empty = unrestricted. A viewer
|
|
91
|
+
* sees the entry only if the host's `cleared` policy clears EVERY class.
|
|
92
|
+
*/
|
|
93
|
+
classes?: string[];
|
|
94
|
+
/** A failed turn: a correlation id for the host's `onError` log. The error text itself never reaches a user. */
|
|
95
|
+
errorId?: string;
|
|
96
|
+
/** Shared mode: the execution that ran the turn (as the asker). */
|
|
97
|
+
turnExecutionId?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A message plus where it sits in the log: the cursor a client resumes from. */
|
|
101
|
+
export interface HistoryEntry extends MessageRecord {
|
|
102
|
+
/** `<generation>.<sequence>` of the event; pass it back as `cursor` / `Last-Event-ID`. */
|
|
103
|
+
cursor: string;
|
|
104
|
+
/** The execution (generation) that holds the event. */
|
|
105
|
+
executionId: string;
|
|
106
|
+
/** Journal time of the event, epoch ms. */
|
|
107
|
+
at?: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface BudgetConfig {
|
|
111
|
+
/** The model's context window, in tokens. */
|
|
112
|
+
contextWindow: number;
|
|
113
|
+
/** Tokens held back for the reply. Default `min(4096, window / 4)`. */
|
|
114
|
+
reserveOutputTokens?: number;
|
|
115
|
+
/** Default {@link heuristicTokenCounter}. A provider's exact counter may be supplied. */
|
|
116
|
+
counter?: TokenCounter;
|
|
117
|
+
/**
|
|
118
|
+
* An effect id that folds evicted turns into the rolling summary: `{ messages } -> { summary }`.
|
|
119
|
+
* Without it, evicted turns are simply dropped from the PROMPT (they stay in `history`).
|
|
120
|
+
*
|
|
121
|
+
* INPUT SHAPE (shared with `agentLoop$` `compaction.toolId`; BOTH may carry `tainted()` wrappers):
|
|
122
|
+
* `messages` is `{ role, content }[]`. The USER's words (and the previous summary) arrive with
|
|
123
|
+
* `content` as a TAINTED wrapper `{ __loomTainted: { origin }, value }` - untrusted data, neither
|
|
124
|
+
* a string nor parts. Assistant replies are plain strings. `textOf(content)` on a wrapper throws
|
|
125
|
+
* `TaintedContentError`; read every message with {@link summarizerText} from this package, which
|
|
126
|
+
* unwraps the taint at every level (top level, text parts, `tool_result` content) and returns text. Compaction input carries wrappers too (tool failures, MCP results, origin-bearing history), so one effect through `summarizerText` serves both. The result is untrusted DATA: never put it in an
|
|
127
|
+
* instruction position (system prompt, assistant role); pass it to a model only as fenced
|
|
128
|
+
* `tainted()` user content. The returned `summary` is cut to `maxSummaryTokens` and re-injected
|
|
129
|
+
* as a fenced `user` message with origin `conversation:summary` (`SUMMARY_ORIGIN`).
|
|
130
|
+
*
|
|
131
|
+
* A summarizer that THROWS (anything but control flow: park, authority/safety stop, cancel,
|
|
132
|
+
* divergence) degrades like an output with no `summary`: the previous summary is kept and the turn
|
|
133
|
+
* runs. The outcome is recorded (`conv#o<ord>:summarize:outcome`), so replay never re-runs it.
|
|
134
|
+
*/
|
|
135
|
+
summarizerToolId?: string;
|
|
136
|
+
/** The rolling summary is cut to this many tokens (by the counter) so it can never crowd out the prompt. Default `floor(contextWindow / 4)`. */
|
|
137
|
+
maxSummaryTokens?: number;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface SharedConfig {
|
|
141
|
+
/**
|
|
142
|
+
* The principal the COORDINATING execution is started under. Required, and no end-user identity may
|
|
143
|
+
* equal it. The coordinator's log holds every restricted reply and every signed envelope, so it must be
|
|
144
|
+
* owned by something no participant is: the owner-scoped runtime policy then refuses everyone else a
|
|
145
|
+
* `query` of it (ADR 0122 D10). Its authority is only to run the turn effect and the summarizer.
|
|
146
|
+
*/
|
|
147
|
+
servicePrincipal: PrincipalChain;
|
|
148
|
+
/**
|
|
149
|
+
* Maps an asker to the memory scope their turns recall from and write back to. REQUIRED when
|
|
150
|
+
* `agent.memory` is set, and a constant `agent.memoryScope` is refused: a shared scope would hand one
|
|
151
|
+
* participant's remembered content to every other. The scope is also a data class of the answer
|
|
152
|
+
* (`memory:<scope>`), so an answer that drew on it is filtered like any other.
|
|
153
|
+
*/
|
|
154
|
+
memoryScope?: (asker: Identity) => string;
|
|
155
|
+
/** Where the participant set lives (`logParticipants(eventStore)` is the standard one). */
|
|
156
|
+
directory: ParticipantDirectory;
|
|
157
|
+
/**
|
|
158
|
+
* Whether `viewer` is cleared to read an entry that touched `classes`. REQUIRED, and called with a
|
|
159
|
+
* non-empty list only. Fail closed: return `false` for a class you do not recognise; `"unclassified"` is
|
|
160
|
+
* the label of a tool `classOf` does not know.
|
|
161
|
+
*/
|
|
162
|
+
cleared: (viewer: Identity, classes: readonly string[]) => boolean | Promise<boolean>;
|
|
163
|
+
/** The declared data class of a tool, by tool name. `undefined` = unclassified (a label of its own). */
|
|
164
|
+
classOf?: (toolName: string) => string | undefined;
|
|
165
|
+
/**
|
|
166
|
+
* Who may add / remove participants and close, beside the owner. Default: the owner only.
|
|
167
|
+
*
|
|
168
|
+
* The callback is called inside a recorded decision. If it throws or rejects, the decision throws and the
|
|
169
|
+
* whole shared conversation fails (the same as `directory.list`). It should not throw: return `false` on
|
|
170
|
+
* a transient error (the manage action is then refused and can be retried).
|
|
171
|
+
*/
|
|
172
|
+
manageParticipants?: (manager: Identity, conversationId: string) => boolean | Promise<boolean>;
|
|
173
|
+
/** The effect id the coordinator runs a turn through. Default `conversation.turn`. */
|
|
174
|
+
turnEffectId?: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface ConversationConfig {
|
|
178
|
+
/**
|
|
179
|
+
* Secret the host signs every inbox envelope with (HMAC). REQUIRED, both modes: the body acts only on a
|
|
180
|
+
* message the host's client signed for THIS conversation, naming the asker and an issue time, and never
|
|
181
|
+
* twice; whatever else the runtime's policy lets into the inbox is recorded as rejected and ignored.
|
|
182
|
+
*/
|
|
183
|
+
key: string;
|
|
184
|
+
/**
|
|
185
|
+
* Keys still ACCEPTED when verifying an envelope (signing always uses `key`): the rotation window. Rotate by
|
|
186
|
+
* deploying `key: new, previousKeys: [old]`, wait out `maxEnvelopeAgeMs`, then drop the old one. Turn
|
|
187
|
+
* execution ids are derived from `key` alone, so a turn that is mid-flight at the moment of rotation is
|
|
188
|
+
* started afresh under its new id (rotate while the conversations are quiet).
|
|
189
|
+
*/
|
|
190
|
+
previousKeys?: readonly string[];
|
|
191
|
+
/** How old (ms) a signed envelope may be when it is dequeued. Default 1 hour. */
|
|
192
|
+
maxEnvelopeAgeMs?: number;
|
|
193
|
+
/** Rejected envelopes recorded as transcript entries per conversation before further ones are only COUNTED. Default 50. */
|
|
194
|
+
maxInvalidRecords?: number;
|
|
195
|
+
/**
|
|
196
|
+
* The agent that answers each turn: any `agentLoop$` config. `signal`, `loopId`, `needsApproval`
|
|
197
|
+
* and its deprecated alias `requireApproval` are owned by the conversation (a parked approval cannot coexist with the
|
|
198
|
+
* barge-in watcher, ADR 0122 D2) and refused here.
|
|
199
|
+
*/
|
|
200
|
+
agent: Omit<AgentLoopConfig, "signal" | "loopId" | "requireApproval" | "needsApproval">;
|
|
201
|
+
budget?: BudgetConfig;
|
|
202
|
+
/** Turns per generation before the conversation continues as new. Default 100. */
|
|
203
|
+
rotateEveryTurns?: number;
|
|
204
|
+
/** Characters of one user turn accepted; a longer one is rejected. Default 32 000. */
|
|
205
|
+
maxTurnChars?: number;
|
|
206
|
+
/** Characters of one reply kept in history and the carry (the log keeps what the model said up to this). Default 64 000. */
|
|
207
|
+
maxReplyChars?: number;
|
|
208
|
+
/** Turns the prompt window holds at most (older ones are evicted, summarized when configured). Default 64. */
|
|
209
|
+
maxWindowTurns?: number;
|
|
210
|
+
/** The carried window is trimmed to this many serialized bytes at a rotation. Default 256 KiB. */
|
|
211
|
+
maxCarryBytes?: number;
|
|
212
|
+
/**
|
|
213
|
+
* What fires the running turn's abort signal when a message lands (see {@link inboxBargeIn}).
|
|
214
|
+
* Without it the conversation QUEUES: a message sent mid-turn waits for the turn to finish.
|
|
215
|
+
*/
|
|
216
|
+
bargeIn?: BargeInSource;
|
|
217
|
+
/** The host's log of the real error behind a failed turn (the user only ever sees a fixed reason and `errorId`). */
|
|
218
|
+
onError?: (errorId: string, err: unknown, info: { conversationId: string; turn: number }) => void;
|
|
219
|
+
/**
|
|
220
|
+
* SHARED MODE (ADR 0122 D10): an explicit participant set, each turn run as its ASKER, classified,
|
|
221
|
+
* filtered per viewer. Absent: owner-only (the default).
|
|
222
|
+
*/
|
|
223
|
+
shared?: SharedConfig;
|
|
224
|
+
/** Where live model deltas go (see {@link ConversationHub.deltaSink}); only its turn bookkeeping is touched here. */
|
|
225
|
+
hub?: ConversationHub;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** One turn as the flow holds it between prompts. */
|
|
229
|
+
export interface CarriedTurn {
|
|
230
|
+
n: number;
|
|
231
|
+
asker?: Identity;
|
|
232
|
+
classes?: string[];
|
|
233
|
+
/** The `ord` of the turn's user record (absent for turns carried from before R17b). */
|
|
234
|
+
ord?: number;
|
|
235
|
+
user: string;
|
|
236
|
+
assistant?: string;
|
|
237
|
+
status: MessageStatus;
|
|
238
|
+
/** Cached token cost of the turn's messages. */
|
|
239
|
+
tokens?: number;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The conversation's working state: the input of every generation. */
|
|
243
|
+
export interface ConversationCarry {
|
|
244
|
+
v: 1;
|
|
245
|
+
/** Turns taken so far (the next turn is `seq + 1`). */
|
|
246
|
+
seq: number;
|
|
247
|
+
/** Messages consumed so far, accepted or not: the id space of the recorded facts. */
|
|
248
|
+
ord: number;
|
|
249
|
+
/** Transcript records written so far: the source of each record's unique `ord` (absent in carries from before R17b). */
|
|
250
|
+
rec?: number;
|
|
251
|
+
/** The identity that started the conversation (the client stamps it; the owner check reads it). */
|
|
252
|
+
owner?: Identity;
|
|
253
|
+
/** Signed ids of the most recent envelopes (bounded): the replay set, and what the barge-in watcher recognises as a retry. */
|
|
254
|
+
ids?: string[];
|
|
255
|
+
/** The issue time of each id in `ids`. */
|
|
256
|
+
iats?: number[];
|
|
257
|
+
/** High-water mark of evicted issue times: an envelope issued at or before it is stale. */
|
|
258
|
+
floor?: number;
|
|
259
|
+
/** Rejected envelopes seen so far (recorded up to `maxInvalidRecords`, then only counted). */
|
|
260
|
+
dropped?: number;
|
|
261
|
+
summary?: string;
|
|
262
|
+
turns: CarriedTurn[];
|
|
263
|
+
/** A message already consumed from the inbox but not yet handled (the rotation point sits between the two). */
|
|
264
|
+
pending?: unknown;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export interface ConversationResult {
|
|
268
|
+
conversationId: string;
|
|
269
|
+
turns: number;
|
|
270
|
+
closed: boolean;
|
|
271
|
+
}
|