@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,961 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_INTERRUPTED,
|
|
3
|
+
type AgentHistoryMessage,
|
|
4
|
+
type InterruptedAgentRun,
|
|
5
|
+
agentLoop$,
|
|
6
|
+
classifyModelCallFailure,
|
|
7
|
+
continueEvery,
|
|
8
|
+
} from "@loomwork/agent";
|
|
9
|
+
import { tainted, unwrapTainted } from "@loomwork/classify";
|
|
10
|
+
import { TypedFailure, flow$, fnv1a64 } from "@loomwork/core";
|
|
11
|
+
import type { ExecutionContext, FlowRunner, RegisteredFlow } from "@loomwork/workflow-runtime";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import {
|
|
14
|
+
ENVELOPE_DOMAIN,
|
|
15
|
+
type Identity,
|
|
16
|
+
identityOf,
|
|
17
|
+
parseIdentity,
|
|
18
|
+
sameIdentity,
|
|
19
|
+
sign,
|
|
20
|
+
verifySignature,
|
|
21
|
+
} from "./access";
|
|
22
|
+
import {
|
|
23
|
+
type BudgetVerdict,
|
|
24
|
+
fitWithSummaryFallback,
|
|
25
|
+
heuristicTokenCounter,
|
|
26
|
+
truncateToTokens,
|
|
27
|
+
} from "./budget";
|
|
28
|
+
import { withTurnScope } from "./hub";
|
|
29
|
+
import { conversationIdOf } from "./ids";
|
|
30
|
+
import {
|
|
31
|
+
type TurnInput,
|
|
32
|
+
type TurnResult,
|
|
33
|
+
registerSharedTurnEffect,
|
|
34
|
+
sharedTurnEffect,
|
|
35
|
+
sharedTurnFlow,
|
|
36
|
+
} from "./turn";
|
|
37
|
+
import {
|
|
38
|
+
CONVERSATION_TOPIC,
|
|
39
|
+
type CarriedTurn,
|
|
40
|
+
type ConversationCarry,
|
|
41
|
+
type ConversationConfig,
|
|
42
|
+
type ConversationResult,
|
|
43
|
+
type MessageRecord,
|
|
44
|
+
type MessageStatus,
|
|
45
|
+
RECORD_SOURCE,
|
|
46
|
+
SUMMARY_ORIGIN,
|
|
47
|
+
type TurnEnvelope,
|
|
48
|
+
USER_ORIGIN,
|
|
49
|
+
} from "./types";
|
|
50
|
+
|
|
51
|
+
// ── conversation$: a durable dialogue as ONE chained execution (ADR 0122) ────────────────────────
|
|
52
|
+
//
|
|
53
|
+
// idle: parked on the inbox (`ctx.receive`) — costs nothing, survives a restart
|
|
54
|
+
// a turn: the user's message is consumed, the prompt is fitted to the token budget (a RECORDED
|
|
55
|
+
// decision), `agentLoop$` answers it, the reply is recorded as a durable event
|
|
56
|
+
// barge-in: while a turn runs, the NEXT inbox message is already being waited on; when it lands
|
|
57
|
+
// the turn's AbortSignal fires. `agentLoop$` stops at its next recorded checkpoint with
|
|
58
|
+
// AGENT_INTERRUPTED, the partial is kept as an `interrupted` reply, and the loop goes on
|
|
59
|
+
// with the new message. The execution is never cancelled.
|
|
60
|
+
// rotation: every `rotateEveryTurns` the flow `continueAsNew`s, carrying the summary and the
|
|
61
|
+
// bounded window, so the fold and the log of any one generation stay bounded.
|
|
62
|
+
//
|
|
63
|
+
// Everything non-deterministic is already a recorded fact by the time this body re-runs: the inbox
|
|
64
|
+
// message is a `MESSAGE_CONSUMED`, the budget verdict a decision, the summary and the model calls
|
|
65
|
+
// frames, the abort checkpoints decisions. The body adds no clock, no random, no I/O of its own.
|
|
66
|
+
|
|
67
|
+
const DEFAULTS = {
|
|
68
|
+
rotateEveryTurns: 100,
|
|
69
|
+
maxTurnChars: 32_000,
|
|
70
|
+
maxReplyChars: 64_000,
|
|
71
|
+
maxWindowTurns: 64,
|
|
72
|
+
maxCarryBytes: 256 * 1024,
|
|
73
|
+
maxSummaryChars: 16_000,
|
|
74
|
+
} as const;
|
|
75
|
+
const MAX_RECENT_IDS = 1024;
|
|
76
|
+
const MAX_KNOWN_FOR_WATCH = 256;
|
|
77
|
+
const MAX_CLOCK_SKEW_MS = 60_000;
|
|
78
|
+
const MAX_CLASSES = 16;
|
|
79
|
+
const EDIT_QUOTE_CHARS = 500;
|
|
80
|
+
const MAX_CLASS_LEN = 64;
|
|
81
|
+
const STATUSES = new Set<MessageStatus>(["complete", "interrupted", "failed", "rejected"]);
|
|
82
|
+
|
|
83
|
+
const UTF8 = new TextEncoder();
|
|
84
|
+
|
|
85
|
+
function positive(name: string, v: number): void {
|
|
86
|
+
if (!Number.isSafeInteger(v) || v < 1) {
|
|
87
|
+
throw new RangeError(`conversation$: ${name} must be a positive integer (got ${String(v)})`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type EnvelopeRefusal = "malformed" | "unauthenticated";
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Both modes: an envelope is acted on only if the host's client SIGNED it, for THIS conversation, with an
|
|
95
|
+
* issue time and an id (the replay set's key). The signature covers every field, so none can be lifted
|
|
96
|
+
* from one message into another.
|
|
97
|
+
*/
|
|
98
|
+
export function parseSignedEnvelope(
|
|
99
|
+
value: unknown,
|
|
100
|
+
keys: string | readonly string[],
|
|
101
|
+
conversationId: string
|
|
102
|
+
): { env?: TurnEnvelope; reason?: EnvelopeRefusal } {
|
|
103
|
+
if (typeof value !== "object" || value === null) return { reason: "malformed" };
|
|
104
|
+
const { sig, ...body } = value as Record<string, unknown>;
|
|
105
|
+
if (!verifySignature(keys, body, sig, ENVELOPE_DOMAIN)) return { reason: "unauthenticated" };
|
|
106
|
+
if (body.conversationId !== conversationId) return { reason: "unauthenticated" };
|
|
107
|
+
const id = body.id;
|
|
108
|
+
const iat = body.iat;
|
|
109
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 256) return { reason: "malformed" };
|
|
110
|
+
if (typeof iat !== "number" || !Number.isFinite(iat)) return { reason: "malformed" };
|
|
111
|
+
let asker: Identity | undefined;
|
|
112
|
+
if (body.asker !== undefined) {
|
|
113
|
+
asker = parseIdentity(body.asker);
|
|
114
|
+
if (asker === undefined) return { reason: "malformed" };
|
|
115
|
+
}
|
|
116
|
+
const who = asker === undefined ? {} : { asker };
|
|
117
|
+
if (body.kind === "close") return { env: { kind: "close", id, iat, ...who } };
|
|
118
|
+
if (body.kind === "user" && typeof body.text === "string") {
|
|
119
|
+
let editOf: number | undefined;
|
|
120
|
+
if (body.editOf !== undefined) {
|
|
121
|
+
if (typeof body.editOf !== "number" || !Number.isSafeInteger(body.editOf) || body.editOf < 1)
|
|
122
|
+
return { reason: "malformed" };
|
|
123
|
+
editOf = body.editOf;
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
env: {
|
|
127
|
+
kind: "user",
|
|
128
|
+
text: body.text,
|
|
129
|
+
id,
|
|
130
|
+
iat,
|
|
131
|
+
...who,
|
|
132
|
+
...(editOf !== undefined && { editOf }),
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return { reason: "malformed" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** What the client signs / the body checks (the envelope without its signature). */
|
|
140
|
+
export function signedEnvelope(
|
|
141
|
+
key: string,
|
|
142
|
+
body: Record<string, unknown>
|
|
143
|
+
): Record<string, unknown> {
|
|
144
|
+
return { ...body, sig: sign(key, body, ENVELOPE_DOMAIN) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const clip = (s: string, max: number): string => (s.length <= max ? s : `${s.slice(0, max)}…`);
|
|
148
|
+
|
|
149
|
+
function emptyCarry(): ConversationCarry {
|
|
150
|
+
return { v: 1, seq: 0, ord: 0, turns: [] };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const safeInt = (v: unknown): number =>
|
|
154
|
+
typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : 0;
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The start input is the owner's, but it is read like any untrusted JSON: shape, counts and bytes are
|
|
158
|
+
* all bounded here, so a malformed or oversized input can neither crash the body nor inflate the window.
|
|
159
|
+
*/
|
|
160
|
+
export function carryOf(
|
|
161
|
+
input: unknown,
|
|
162
|
+
lim: { turns: number; turnChars: number; replyChars: number; summaryChars: number; bytes: number }
|
|
163
|
+
): ConversationCarry {
|
|
164
|
+
if (typeof input !== "object" || input === null) return emptyCarry();
|
|
165
|
+
const c = input as Record<string, unknown>;
|
|
166
|
+
if (c.v !== 1) return emptyCarry();
|
|
167
|
+
const turns: CarriedTurn[] = [];
|
|
168
|
+
for (const t of Array.isArray(c.turns) ? c.turns : []) {
|
|
169
|
+
if (typeof t !== "object" || t === null) continue;
|
|
170
|
+
const o = t as Record<string, unknown>;
|
|
171
|
+
if (typeof o.user !== "string" || !STATUSES.has(o.status as MessageStatus)) continue;
|
|
172
|
+
const asker = parseIdentity(o.asker);
|
|
173
|
+
const classes = Array.isArray(o.classes)
|
|
174
|
+
? o.classes
|
|
175
|
+
.filter((x): x is string => typeof x === "string" && x.length <= MAX_CLASS_LEN)
|
|
176
|
+
.slice(0, MAX_CLASSES)
|
|
177
|
+
: undefined;
|
|
178
|
+
turns.push({
|
|
179
|
+
n: safeInt(o.n),
|
|
180
|
+
...(typeof o.ord === "number" && Number.isSafeInteger(o.ord) && o.ord >= 1 && { ord: o.ord }),
|
|
181
|
+
user: clip(o.user, lim.turnChars),
|
|
182
|
+
...(typeof o.assistant === "string" && { assistant: clip(o.assistant, lim.replyChars) }),
|
|
183
|
+
status: o.status as MessageStatus,
|
|
184
|
+
...(typeof o.tokens === "number" &&
|
|
185
|
+
Number.isFinite(o.tokens) &&
|
|
186
|
+
o.tokens >= 0 && { tokens: o.tokens }),
|
|
187
|
+
...(asker !== undefined && { asker }),
|
|
188
|
+
...(classes !== undefined && classes.length > 0 && { classes }),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const owner = parseIdentity(c.owner);
|
|
192
|
+
const rawIds = Array.isArray(c.ids) ? c.ids : [];
|
|
193
|
+
const rawIats = Array.isArray(c.iats) ? c.iats : [];
|
|
194
|
+
const iatOfId = new Map<string, number>();
|
|
195
|
+
const idsKept: string[] = [];
|
|
196
|
+
rawIds.forEach((x, i) => {
|
|
197
|
+
if (typeof x !== "string" || x.length > 256) return;
|
|
198
|
+
idsKept.push(x);
|
|
199
|
+
const t = rawIats[i];
|
|
200
|
+
iatOfId.set(x, typeof t === "number" && Number.isFinite(t) ? t : 0);
|
|
201
|
+
});
|
|
202
|
+
idsKept.splice(0, Math.max(0, idsKept.length - MAX_RECENT_IDS));
|
|
203
|
+
const carry: ConversationCarry = {
|
|
204
|
+
v: 1,
|
|
205
|
+
seq: safeInt(c.seq),
|
|
206
|
+
ord: safeInt(c.ord),
|
|
207
|
+
...(safeInt(c.rec) > 0 && { rec: safeInt(c.rec) }),
|
|
208
|
+
dropped: safeInt(c.dropped),
|
|
209
|
+
...(owner !== undefined && { owner }),
|
|
210
|
+
...(typeof c.summary === "string" && { summary: clip(c.summary, lim.summaryChars) }),
|
|
211
|
+
ids: idsKept,
|
|
212
|
+
iats: idsKept.map((id) => iatOfId.get(id) ?? 0),
|
|
213
|
+
floor: typeof c.floor === "number" && Number.isFinite(c.floor) && c.floor >= 0 ? c.floor : 0,
|
|
214
|
+
turns: turns.slice(-lim.turns),
|
|
215
|
+
...(c.pending !== undefined && { pending: c.pending }),
|
|
216
|
+
};
|
|
217
|
+
return trimCarry(carry, lim.bytes);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const PLACEHOLDER = {
|
|
221
|
+
interrupted: "(interrupted)",
|
|
222
|
+
failed: "(no reply: the request failed)",
|
|
223
|
+
rejected: "(no reply)",
|
|
224
|
+
complete: "(no reply)",
|
|
225
|
+
restricted: "(no reply)",
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The earlier turns as the loop's history: the summary first, then whole turns, oldest first. Roles
|
|
230
|
+
* ALTERNATE: a turn with no reply text (interrupted before any, failed) gets a placeholder assistant
|
|
231
|
+
* message, and the summary a short acknowledgement, so no provider that rejects consecutive user
|
|
232
|
+
* messages is ever sent two in a row.
|
|
233
|
+
*/
|
|
234
|
+
function historyOf(
|
|
235
|
+
summary: string | undefined,
|
|
236
|
+
turns: readonly CarriedTurn[]
|
|
237
|
+
): AgentHistoryMessage[] {
|
|
238
|
+
const out: AgentHistoryMessage[] = [];
|
|
239
|
+
if (summary !== undefined && summary !== "") {
|
|
240
|
+
out.push({
|
|
241
|
+
role: "user",
|
|
242
|
+
content: `Summary of the earlier conversation: ${summary}`,
|
|
243
|
+
origin: SUMMARY_ORIGIN,
|
|
244
|
+
});
|
|
245
|
+
out.push({ role: "assistant", content: "(earlier conversation summarized above)" });
|
|
246
|
+
}
|
|
247
|
+
for (const t of turns) {
|
|
248
|
+
out.push({ role: "user", content: t.user, origin: USER_ORIGIN });
|
|
249
|
+
out.push({
|
|
250
|
+
role: "assistant",
|
|
251
|
+
content:
|
|
252
|
+
t.assistant !== undefined && t.assistant !== "" ? t.assistant : PLACEHOLDER[t.status],
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const union = (...lists: (readonly string[] | undefined)[]): string[] =>
|
|
259
|
+
[...new Set(lists.flatMap((l) => l ?? []))].sort();
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The flow body of a conversation. Register it with {@link conversation$} (which also builds the
|
|
263
|
+
* definition) or call it from your own runner.
|
|
264
|
+
*/
|
|
265
|
+
export function conversationRunner(
|
|
266
|
+
config: ConversationConfig,
|
|
267
|
+
shared?: { turnEffectId: string }
|
|
268
|
+
): FlowRunner<ConversationCarry | Record<string, never>, ConversationResult> {
|
|
269
|
+
const rotateEvery = config.rotateEveryTurns ?? DEFAULTS.rotateEveryTurns;
|
|
270
|
+
const maxTurnChars = config.maxTurnChars ?? DEFAULTS.maxTurnChars;
|
|
271
|
+
const maxReplyChars = config.maxReplyChars ?? DEFAULTS.maxReplyChars;
|
|
272
|
+
const maxWindowTurns = config.maxWindowTurns ?? DEFAULTS.maxWindowTurns;
|
|
273
|
+
const maxCarryBytes = config.maxCarryBytes ?? DEFAULTS.maxCarryBytes;
|
|
274
|
+
const maxEnvelopeAge = config.maxEnvelopeAgeMs ?? 60 * 60_000;
|
|
275
|
+
const maxInvalid = config.maxInvalidRecords ?? 50;
|
|
276
|
+
if (typeof config.key !== "string" || config.key.length < 8) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
"conversation$: `key` (the host's envelope-signing secret, at least 8 characters) is required"
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
positive("rotateEveryTurns", rotateEvery);
|
|
282
|
+
positive("maxTurnChars", maxTurnChars);
|
|
283
|
+
positive("maxReplyChars", maxReplyChars);
|
|
284
|
+
positive("maxWindowTurns", maxWindowTurns);
|
|
285
|
+
positive("maxCarryBytes", maxCarryBytes);
|
|
286
|
+
for (const k of ["requireApproval", "needsApproval"] as const) {
|
|
287
|
+
if ((config.agent as Record<string, unknown>)[k] === undefined) continue;
|
|
288
|
+
throw new Error(
|
|
289
|
+
`conversation$: \`${k}\` is not supported (a parked approval cannot coexist with the barge-in watcher); gate tools with the effect authorizer`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
for (const k of ["signal", "loopId"] as const) {
|
|
293
|
+
if ((config.agent as Record<string, unknown>)[k] !== undefined) {
|
|
294
|
+
throw new Error(`conversation$: agent.${k} is owned by the conversation`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
const budget = config.budget;
|
|
298
|
+
if (budget !== undefined && !(budget.contextWindow > 0)) {
|
|
299
|
+
throw new RangeError("conversation$: budget.contextWindow must be a positive number");
|
|
300
|
+
}
|
|
301
|
+
const sharedCfg = config.shared;
|
|
302
|
+
if (sharedCfg !== undefined) {
|
|
303
|
+
const wb = config.agent.writeBack;
|
|
304
|
+
if (wb !== undefined && wb !== false && (typeof wb !== "object" || wb.toolId === undefined)) {
|
|
305
|
+
throw new Error(
|
|
306
|
+
"conversation$ (shared): `agent.writeBack` must go through an effect (`toolId`): a direct write would not be the asker's"
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
if (typeof sharedCfg.cleared !== "function") {
|
|
310
|
+
throw new Error("conversation$ (shared): `shared.cleared` is required (fail closed)");
|
|
311
|
+
}
|
|
312
|
+
if (identityOf(sharedCfg.servicePrincipal) === undefined) {
|
|
313
|
+
throw new Error(
|
|
314
|
+
"conversation$ (shared): `shared.servicePrincipal` (a principal with an actor) is required: it owns the coordinating execution"
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
const a = config.agent;
|
|
318
|
+
if (a.memoryScope !== undefined) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
"conversation$ (shared): a constant `agent.memoryScope` would hand one participant's memory to every other; give `shared.memoryScope(asker)` instead"
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
if (typeof wb === "object" && wb !== null && wb.scope !== undefined) {
|
|
324
|
+
throw new Error(
|
|
325
|
+
"conversation$ (shared): `agent.writeBack.scope` must come from `shared.memoryScope(asker)`"
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
if (a.memory !== undefined && typeof sharedCfg.memoryScope !== "function") {
|
|
329
|
+
throw new Error(
|
|
330
|
+
"conversation$ (shared): `agent.memory` needs `shared.memoryScope(asker)` (a per-asker scope)"
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const counter = budget?.counter ?? heuristicTokenCounter();
|
|
335
|
+
const maxSummaryTokens =
|
|
336
|
+
budget === undefined ? 0 : (budget.maxSummaryTokens ?? Math.floor(budget.contextWindow / 4));
|
|
337
|
+
const toolText = config.agent.definition.tools
|
|
338
|
+
.map((t) => `${t.name} ${t.description}`)
|
|
339
|
+
.join("\n");
|
|
340
|
+
const systemForCount = [config.agent.systemPrompt, toolText].filter((s) => !!s).join("\n");
|
|
341
|
+
|
|
342
|
+
return async (ctx: ExecutionContext, input) => {
|
|
343
|
+
const conversationId = conversationIdOf(ctx.executionId);
|
|
344
|
+
const carry = carryOf(input, {
|
|
345
|
+
turns: maxWindowTurns,
|
|
346
|
+
turnChars: maxTurnChars,
|
|
347
|
+
replyChars: maxReplyChars,
|
|
348
|
+
summaryChars: DEFAULTS.maxSummaryChars,
|
|
349
|
+
bytes: maxCarryBytes,
|
|
350
|
+
});
|
|
351
|
+
let seq = carry.seq;
|
|
352
|
+
/** Rejected envelopes so far: recorded up to `maxInvalidRecords`, then only counted. */
|
|
353
|
+
let droppedCount = carry.dropped ?? 0;
|
|
354
|
+
/** Messages consumed so far (accepted or not): the id space of every recorded fact, never reused. */
|
|
355
|
+
let ord = carry.ord;
|
|
356
|
+
/** Transcript records written so far (the unique `ord` of each record; carried across rotations). */
|
|
357
|
+
let rec = carry.rec ?? 0;
|
|
358
|
+
let summary = carry.summary;
|
|
359
|
+
let turns: CarriedTurn[] = carry.turns.slice();
|
|
360
|
+
let pending: unknown = carry.pending;
|
|
361
|
+
const owner = carry.owner;
|
|
362
|
+
/** Idempotency keys of recent turns, oldest first: what a barge-in watcher must NOT treat as new. */
|
|
363
|
+
const ids: string[] = (carry.ids ?? []).slice(-MAX_RECENT_IDS);
|
|
364
|
+
/** The issue time of each remembered id (parallel to `ids`). */
|
|
365
|
+
const iats: number[] = ids.map((_, i) => carry.iats?.[i] ?? 0);
|
|
366
|
+
/**
|
|
367
|
+
* HIGH-WATER MARK of evicted issue times. The replay set is bounded, so an id can fall out of it; the
|
|
368
|
+
* guarantee that a captured envelope cannot be replayed after that is THIS floor: anything issued at or
|
|
369
|
+
* before the newest evicted envelope is refused as stale, whatever the set still remembers. (An attacker
|
|
370
|
+
* who floods the set can only raise the floor, never reopen an old envelope.)
|
|
371
|
+
*/
|
|
372
|
+
let floor = carry.floor ?? 0;
|
|
373
|
+
const known = new Set(ids);
|
|
374
|
+
const remember = (id: string | undefined, iat = 0): void => {
|
|
375
|
+
if (id === undefined || known.has(id)) return;
|
|
376
|
+
known.add(id);
|
|
377
|
+
ids.push(id);
|
|
378
|
+
iats.push(iat);
|
|
379
|
+
if (ids.length > MAX_RECENT_IDS) {
|
|
380
|
+
known.delete(ids.shift() as string);
|
|
381
|
+
floor = Math.max(floor, iats.shift() as number);
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
let rotateDue = false;
|
|
385
|
+
const turnsCounter = continueEvery(rotateEvery);
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Record a fact exactly once (a decision under a deterministic id; see {@link RECORD_SOURCE}).
|
|
389
|
+
* `live` runs only when the fact is NEW (a decider never runs for a recorded one).
|
|
390
|
+
*/
|
|
391
|
+
const record = async (
|
|
392
|
+
id: string,
|
|
393
|
+
message: MessageRecord,
|
|
394
|
+
live?: () => Promise<void>
|
|
395
|
+
): Promise<number> => {
|
|
396
|
+
// The record's own ordinal, counted whether the fact is new or served from the log: the body is
|
|
397
|
+
// deterministic, so a replay counts the same. The value only matters when the fact is NEW.
|
|
398
|
+
const recOrd = ++rec;
|
|
399
|
+
await ctx.decide(
|
|
400
|
+
`conv#o${ord}:${id}`,
|
|
401
|
+
async () => {
|
|
402
|
+
await live?.();
|
|
403
|
+
return { ...message, ord: recOrd };
|
|
404
|
+
},
|
|
405
|
+
{ source: RECORD_SOURCE }
|
|
406
|
+
);
|
|
407
|
+
return recOrd;
|
|
408
|
+
};
|
|
409
|
+
// A rejected message is not a turn: `turn: 0`, so it can never share a number with an accepted turn.
|
|
410
|
+
const reject = (reason: string, asker?: Identity): Promise<unknown> =>
|
|
411
|
+
record("user", {
|
|
412
|
+
turn: 0,
|
|
413
|
+
role: "user",
|
|
414
|
+
text: "",
|
|
415
|
+
status: "rejected",
|
|
416
|
+
reason,
|
|
417
|
+
...(asker !== undefined && { asker }),
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Fold `dropped` turns into the rolling summary (when a summarizer is configured): the user's words
|
|
422
|
+
* go in TAINTED, the previous summary too (model output over untrusted text), and the new summary is
|
|
423
|
+
* cut to `maxSummaryTokens` by a recorded decision, so it can never crowd the prompt out.
|
|
424
|
+
*/
|
|
425
|
+
const summarize = async (dropped: readonly CarriedTurn[]): Promise<void> => {
|
|
426
|
+
if (budget?.summarizerToolId === undefined) return;
|
|
427
|
+
// SHARED: only unrestricted turns may be summarized. The summary reaches every participant's
|
|
428
|
+
// prompt, so restricted content must never be in it (evicted restricted turns are just dropped).
|
|
429
|
+
const usable = sharedCfg === undefined ? dropped : dropped.filter((t) => !t.classes?.length);
|
|
430
|
+
if (usable.length === 0) return;
|
|
431
|
+
const messages = [
|
|
432
|
+
...(summary !== undefined && summary !== ""
|
|
433
|
+
? [{ role: "user", content: tainted(`Summary so far: ${summary}`, SUMMARY_ORIGIN) }]
|
|
434
|
+
: []),
|
|
435
|
+
...usable.flatMap((t) => [
|
|
436
|
+
{ role: "user", content: tainted(t.user, USER_ORIGIN) },
|
|
437
|
+
...(t.assistant ? [{ role: "assistant", content: t.assistant }] : []),
|
|
438
|
+
]),
|
|
439
|
+
];
|
|
440
|
+
const task = {
|
|
441
|
+
_tag: "TaskDefinition",
|
|
442
|
+
kind: "memory",
|
|
443
|
+
id: `conv#o${ord}:summarize`,
|
|
444
|
+
toolId: budget.summarizerToolId,
|
|
445
|
+
} as const;
|
|
446
|
+
// A failed summarizer DEGRADES, as an output with no `summary` does: the previous summary is kept
|
|
447
|
+
// and the evicted turns are just dropped from the prompt. Summarizing is housekeeping, so its
|
|
448
|
+
// failure must not end the conversation (the turn has not even started). The OUTCOME is a recorded
|
|
449
|
+
// decision wrapping the step: the kernel re-runs a failed step live on replay (at-least-once), so
|
|
450
|
+
// without it a replay whose summarizer now succeeds would rebuild a different prompt history.
|
|
451
|
+
// Control flow (a park, an authority/safety stop, a cancel, a replay divergence) is the runtime's:
|
|
452
|
+
// not recorded, it propagates. (Same pattern as `agentLoop$`'s `:outcome` for a failing tool.)
|
|
453
|
+
const outcome = await ctx.decide<{ ok: true } | { failed: true }>(
|
|
454
|
+
`conv#o${ord}:summarize:outcome`,
|
|
455
|
+
async () => {
|
|
456
|
+
try {
|
|
457
|
+
await ctx.execute(task, { messages });
|
|
458
|
+
return { ok: true as const };
|
|
459
|
+
} catch (e) {
|
|
460
|
+
if (classifyModelCallFailure(e) === "terminal") throw e;
|
|
461
|
+
return { failed: true as const };
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
{ source: "conversation-summarizer" }
|
|
465
|
+
);
|
|
466
|
+
if ("failed" in outcome) return;
|
|
467
|
+
// Served from the completed frame (no second run).
|
|
468
|
+
const out = (await ctx.execute(task, { messages })) as { summary?: unknown };
|
|
469
|
+
if (typeof out?.summary === "string") {
|
|
470
|
+
const raw = clip(out.summary, DEFAULTS.maxSummaryChars);
|
|
471
|
+
summary = await ctx.decide<string>(
|
|
472
|
+
`conv#o${ord}:summary-fit`,
|
|
473
|
+
() => truncateToTokens(raw, maxSummaryTokens, counter),
|
|
474
|
+
{ source: "conversation-budget" }
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
for (;;) {
|
|
480
|
+
// Idle: the next message is either one already consumed (a rotation's `pending`) or a wait.
|
|
481
|
+
// This is the ONLY place the execution parks.
|
|
482
|
+
const raw: unknown = pending !== undefined ? pending : await ctx.receive(CONVERSATION_TOPIC);
|
|
483
|
+
pending = undefined;
|
|
484
|
+
const parsed = parseSignedEnvelope(
|
|
485
|
+
unwrapTainted(raw),
|
|
486
|
+
[config.key, ...(config.previousKeys ?? [])],
|
|
487
|
+
conversationId
|
|
488
|
+
);
|
|
489
|
+
const env = parsed.env;
|
|
490
|
+
|
|
491
|
+
// Rotation sits BETWEEN consuming a message and starting its turn: no wait is outstanding
|
|
492
|
+
// here, which `continueAsNew` requires. The consumed message rides
|
|
493
|
+
// the carry, so the successor handles it first and the inbox cursor never re-delivers it.
|
|
494
|
+
if (rotateDue) {
|
|
495
|
+
return ctx.continueAsNew(
|
|
496
|
+
trimCarry(
|
|
497
|
+
{
|
|
498
|
+
v: 1,
|
|
499
|
+
seq,
|
|
500
|
+
ord,
|
|
501
|
+
rec,
|
|
502
|
+
ids,
|
|
503
|
+
iats,
|
|
504
|
+
floor,
|
|
505
|
+
dropped: droppedCount,
|
|
506
|
+
...(owner !== undefined && { owner }),
|
|
507
|
+
...(summary !== undefined && { summary }),
|
|
508
|
+
turns,
|
|
509
|
+
pending: raw,
|
|
510
|
+
},
|
|
511
|
+
maxCarryBytes
|
|
512
|
+
)
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
ord++;
|
|
517
|
+
|
|
518
|
+
// ── is this message ONE THE HOST SIGNED, for this conversation, from the right voice, once, and still fresh? ──
|
|
519
|
+
// The inbox is writable by whatever the runtime's policy admits, so nothing in it is trusted until it
|
|
520
|
+
// passes here. A refusal is a recorded entry (up to `maxInvalidRecords`), after that only counted.
|
|
521
|
+
let invalid: string | undefined = parsed.reason;
|
|
522
|
+
if (env !== undefined && invalid === undefined) {
|
|
523
|
+
const id = env.id as string;
|
|
524
|
+
if (known.has(id)) invalid = "replayed";
|
|
525
|
+
else if ((env.iat as number) <= floor) invalid = "stale";
|
|
526
|
+
else if (
|
|
527
|
+
sharedCfg === undefined
|
|
528
|
+
? !(sameIdentity(env.asker, owner) || (env.asker === undefined && owner === undefined))
|
|
529
|
+
: env.asker === undefined
|
|
530
|
+
) {
|
|
531
|
+
// owner mode: only the OWNER's voice; shared: some asker is named (membership is judged below)
|
|
532
|
+
invalid = "unauthenticated";
|
|
533
|
+
} else {
|
|
534
|
+
const iat = env.iat as number;
|
|
535
|
+
const fresh = await ctx.decide<boolean>(
|
|
536
|
+
`conv#o${ord}:fresh`,
|
|
537
|
+
() => {
|
|
538
|
+
const age = Date.now() - iat;
|
|
539
|
+
return age <= maxEnvelopeAge && age >= -MAX_CLOCK_SKEW_MS;
|
|
540
|
+
},
|
|
541
|
+
{ source: "conversation-access" }
|
|
542
|
+
);
|
|
543
|
+
if (!fresh) invalid = "stale";
|
|
544
|
+
else remember(id, iat);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (invalid !== undefined) {
|
|
548
|
+
droppedCount++;
|
|
549
|
+
if (droppedCount <= maxInvalid) await reject(invalid);
|
|
550
|
+
else if (droppedCount % 100 === 0) {
|
|
551
|
+
const count = droppedCount;
|
|
552
|
+
await ctx.decide(`conv#o${ord}:dropped`, () => ({ kind: "dropped", count }), {
|
|
553
|
+
source: RECORD_SOURCE,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const verified = env as TurnEnvelope;
|
|
559
|
+
|
|
560
|
+
if (verified.kind === "close") {
|
|
561
|
+
// SHARED: a close ends EVERYONE's conversation, so the body re-judges the "manage" rule the client
|
|
562
|
+
// applies (the key alone must not be enough): the owner, the service principal, or a host manager
|
|
563
|
+
// (`manageParticipants`). A plain participant may not close. Recorded verdict, so replay is stable.
|
|
564
|
+
if (sharedCfg !== undefined) {
|
|
565
|
+
const closer = verified.asker;
|
|
566
|
+
const mayClose = await ctx.decide<boolean>(
|
|
567
|
+
`conv#o${ord}:close-auth`,
|
|
568
|
+
async () =>
|
|
569
|
+
closer !== undefined &&
|
|
570
|
+
(sameIdentity(closer, owner) ||
|
|
571
|
+
sameIdentity(closer, identityOf(sharedCfg.servicePrincipal)) ||
|
|
572
|
+
(await sharedCfg.manageParticipants?.(closer, conversationId)) === true),
|
|
573
|
+
{ source: "conversation-access" }
|
|
574
|
+
);
|
|
575
|
+
if (!mayClose) {
|
|
576
|
+
await reject("unauthenticated", closer);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
await ctx.decide("conv#closed", () => ({ kind: "closed", turns: seq }), {
|
|
581
|
+
source: RECORD_SOURCE,
|
|
582
|
+
});
|
|
583
|
+
return { conversationId, turns: seq, closed: true };
|
|
584
|
+
}
|
|
585
|
+
if (verified.text.trim() === "") {
|
|
586
|
+
await reject("malformed");
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
const asker = verified.asker;
|
|
590
|
+
const attributed = sharedCfg !== undefined ? asker : undefined;
|
|
591
|
+
if (verified.text.length > maxTurnChars) {
|
|
592
|
+
await reject("too-long", attributed);
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// SHARED: is the asker (still) a participant? Judged when the turn is DEQUEUED, as a recorded
|
|
597
|
+
// verdict, so a participant removed while their message queued is not served.
|
|
598
|
+
if (sharedCfg !== undefined && asker !== undefined) {
|
|
599
|
+
const member = await ctx.decide<boolean>(
|
|
600
|
+
`conv#o${ord}:member`,
|
|
601
|
+
async () =>
|
|
602
|
+
sameIdentity(asker, owner) ||
|
|
603
|
+
(await sharedCfg.directory.list(conversationId)).some((i) => sameIdentity(i, asker)),
|
|
604
|
+
{ source: "conversation-access" }
|
|
605
|
+
);
|
|
606
|
+
if (!member) {
|
|
607
|
+
await reject("not-a-participant", asker);
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// EDIT: the signed `editOf` names an earlier user record. It must be a turn of this conversation that
|
|
613
|
+
// was ACCEPTED (only accepted turns are in the window) and is the ASKER's own (owner mode: the owner's
|
|
614
|
+
// voice is the only one admitted, so every turn in it is the owner's). Anything else is refused with
|
|
615
|
+
// a fixed reason and nothing is obeyed; the reason does not say which of the cases it was.
|
|
616
|
+
let edited: CarriedTurn | undefined;
|
|
617
|
+
if (verified.editOf !== undefined) {
|
|
618
|
+
edited = turns.find(
|
|
619
|
+
(t) =>
|
|
620
|
+
t.ord === verified.editOf && (sharedCfg === undefined || sameIdentity(t.asker, asker))
|
|
621
|
+
);
|
|
622
|
+
if (edited === undefined) {
|
|
623
|
+
await reject("edit-invalid", attributed);
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
// The model sees the edit as DATA inside the (tainted, fenced) user text, never as an instruction.
|
|
628
|
+
const promptText =
|
|
629
|
+
edited === undefined
|
|
630
|
+
? verified.text
|
|
631
|
+
: `[This message edits the user's earlier message ${JSON.stringify(
|
|
632
|
+
clip(edited.user, EDIT_QUOTE_CHARS)
|
|
633
|
+
)}.]\n\n${verified.text}`;
|
|
634
|
+
|
|
635
|
+
const ctl = new AbortController();
|
|
636
|
+
|
|
637
|
+
// The turns the asker's prompt may draw on. OWNER: all of them. SHARED: only the entries the ASKER
|
|
638
|
+
// is cleared for (a recorded verdict), so restricted content never enters an uncleared asker's context.
|
|
639
|
+
let visibleTurns = turns;
|
|
640
|
+
if (sharedCfg !== undefined && asker !== undefined) {
|
|
641
|
+
const verdict = await ctx.decide<boolean[]>(
|
|
642
|
+
`conv#o${ord}:visible`,
|
|
643
|
+
async () => {
|
|
644
|
+
const cache = new Map<string, boolean>();
|
|
645
|
+
return Promise.all(
|
|
646
|
+
turns.map(async (t) => {
|
|
647
|
+
if (!t.classes?.length || sameIdentity(t.asker, asker)) return true;
|
|
648
|
+
const k = t.classes.join("\u0000");
|
|
649
|
+
let ok = cache.get(k);
|
|
650
|
+
if (ok === undefined) {
|
|
651
|
+
ok = (await sharedCfg.cleared(asker, t.classes)) === true;
|
|
652
|
+
cache.set(k, ok);
|
|
653
|
+
}
|
|
654
|
+
return ok;
|
|
655
|
+
})
|
|
656
|
+
);
|
|
657
|
+
},
|
|
658
|
+
{ source: "conversation-access" }
|
|
659
|
+
);
|
|
660
|
+
visibleTurns = turns.filter((_, i) => verdict[i] === true);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// ── the token budget: a recorded verdict, then the (deterministic) eviction ────────────────
|
|
664
|
+
const overflow = Math.max(0, turns.length - maxWindowTurns);
|
|
665
|
+
let dropCount = sharedCfg === undefined ? overflow : 0;
|
|
666
|
+
let promptTurns: CarriedTurn[] = turns;
|
|
667
|
+
let skipSummary = false;
|
|
668
|
+
const summaryForTurn = (): string | undefined => (skipSummary ? undefined : summary);
|
|
669
|
+
if (sharedCfg !== undefined)
|
|
670
|
+
promptTurns = visibleTurns.slice(Math.max(0, visibleTurns.length - maxWindowTurns));
|
|
671
|
+
if (budget !== undefined) {
|
|
672
|
+
const view = sharedCfg !== undefined ? promptTurns : turns.slice(overflow);
|
|
673
|
+
const verdict = await ctx.decide<BudgetVerdict>(
|
|
674
|
+
`conv#fit:${ord}`,
|
|
675
|
+
() =>
|
|
676
|
+
fitWithSummaryFallback({
|
|
677
|
+
contextWindow: budget.contextWindow,
|
|
678
|
+
...(budget.reserveOutputTokens !== undefined && {
|
|
679
|
+
reserveOutputTokens: budget.reserveOutputTokens,
|
|
680
|
+
}),
|
|
681
|
+
...(systemForCount !== "" && { system: systemForCount }),
|
|
682
|
+
...(summary !== undefined && { summary }),
|
|
683
|
+
prompt: promptText,
|
|
684
|
+
turns: view.map((t) => ({
|
|
685
|
+
user: t.user,
|
|
686
|
+
...(t.assistant !== undefined && { assistant: t.assistant }),
|
|
687
|
+
...(t.tokens !== undefined && { tokens: t.tokens }),
|
|
688
|
+
})),
|
|
689
|
+
counter,
|
|
690
|
+
}),
|
|
691
|
+
{ source: "conversation-budget" }
|
|
692
|
+
);
|
|
693
|
+
if (!verdict.ok) {
|
|
694
|
+
// The message does not fit even alone: refused, never sent to the model, not a turn.
|
|
695
|
+
await reject("prompt-too-large", asker);
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
if (verdict.dropSummary === true) {
|
|
699
|
+
// OWNER: the summary is only this one user's, drop it. SHARED: it is everyone's, so only THIS turn goes without.
|
|
700
|
+
if (sharedCfg === undefined) summary = undefined;
|
|
701
|
+
else skipSummary = true;
|
|
702
|
+
}
|
|
703
|
+
for (const [i, tokens] of verdict.counted) {
|
|
704
|
+
const t = view[i];
|
|
705
|
+
if (t !== undefined) t.tokens = tokens;
|
|
706
|
+
}
|
|
707
|
+
if (sharedCfg !== undefined) promptTurns = view.slice(view.length - verdict.keep);
|
|
708
|
+
else dropCount = overflow + (view.length - verdict.keep);
|
|
709
|
+
}
|
|
710
|
+
const n = ++seq;
|
|
711
|
+
// The barge-in watch starts when the turn goes LIVE: this decider runs only for a new turn, and
|
|
712
|
+
// the provider wrapper starts it for a recovered one whose model call re-runs. A turn replayed
|
|
713
|
+
// from the log (every wake re-runs the whole generation) never subscribes to anything.
|
|
714
|
+
// (SHARED mode watches inside the turn effect, for the asker's own messages only.)
|
|
715
|
+
let watching: Promise<() => void> | undefined;
|
|
716
|
+
const ensureWatch = (): Promise<() => void> => {
|
|
717
|
+
if (watching === undefined) {
|
|
718
|
+
watching =
|
|
719
|
+
sharedCfg !== undefined
|
|
720
|
+
? Promise.resolve(() => undefined)
|
|
721
|
+
: Promise.resolve(
|
|
722
|
+
config.bargeIn?.(conversationId, ctx.executionId, {
|
|
723
|
+
onMessage: () => ctl.abort(),
|
|
724
|
+
isKnown: (id) => known.has(id),
|
|
725
|
+
}) ?? (() => undefined)
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
return watching;
|
|
729
|
+
};
|
|
730
|
+
// The question is classified by what it was ASKED AGAINST: the classes of every entry in the context
|
|
731
|
+
// it was built on (known before the turn), so a question that quotes restricted content is filtered
|
|
732
|
+
// like the answer is.
|
|
733
|
+
const contextClasses = union(...promptTurns.map((t) => t.classes), edited?.classes);
|
|
734
|
+
const userOrd = await record(
|
|
735
|
+
"user",
|
|
736
|
+
{
|
|
737
|
+
turn: n,
|
|
738
|
+
role: "user",
|
|
739
|
+
text: verified.text,
|
|
740
|
+
status: "complete",
|
|
741
|
+
...(edited?.ord !== undefined && { editOf: edited.ord, editOfTurn: edited.n }),
|
|
742
|
+
...(attributed !== undefined && { asker: attributed }),
|
|
743
|
+
...(contextClasses.length > 0 && { classes: contextClasses }),
|
|
744
|
+
},
|
|
745
|
+
async () => {
|
|
746
|
+
await ensureWatch();
|
|
747
|
+
}
|
|
748
|
+
);
|
|
749
|
+
if (dropCount > 0) {
|
|
750
|
+
const dropped = turns.slice(0, dropCount);
|
|
751
|
+
turns = turns.slice(dropCount);
|
|
752
|
+
await summarize(dropped);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// ── the turn ──────────────────────────────────────────────────────────────────────────────
|
|
756
|
+
let reply = "";
|
|
757
|
+
let status: MessageStatus = "complete";
|
|
758
|
+
let reason: string | undefined;
|
|
759
|
+
let errorId: string | undefined;
|
|
760
|
+
let failure: unknown;
|
|
761
|
+
let toolNames: string[] = [];
|
|
762
|
+
let turnExecutionId: string | undefined;
|
|
763
|
+
let memoryScope: string | undefined;
|
|
764
|
+
try {
|
|
765
|
+
if (sharedCfg !== undefined && asker !== undefined) {
|
|
766
|
+
const out = (await ctx.execute(
|
|
767
|
+
{
|
|
768
|
+
_tag: "TaskDefinition",
|
|
769
|
+
kind: "tool",
|
|
770
|
+
id: `conv#o${ord}:turn`,
|
|
771
|
+
toolId: shared?.turnEffectId ?? "conversation.turn",
|
|
772
|
+
},
|
|
773
|
+
{
|
|
774
|
+
conversationId,
|
|
775
|
+
turn: n,
|
|
776
|
+
ord,
|
|
777
|
+
asker,
|
|
778
|
+
text: promptText,
|
|
779
|
+
...(verified.id !== undefined && { id: verified.id }),
|
|
780
|
+
history: historyOf(summaryForTurn(), promptTurns),
|
|
781
|
+
known: [...known].slice(-MAX_KNOWN_FOR_WATCH),
|
|
782
|
+
ownerExecutionId: ctx.executionId,
|
|
783
|
+
}
|
|
784
|
+
)) as TurnResult;
|
|
785
|
+
status = out.status;
|
|
786
|
+
reply = clip(out.content ?? "", maxReplyChars);
|
|
787
|
+
toolNames = out.tools ?? [];
|
|
788
|
+
turnExecutionId = out.turnExecutionId;
|
|
789
|
+
memoryScope = out.memoryScope;
|
|
790
|
+
if (out.status === "failed") {
|
|
791
|
+
reason = out.reason ?? "turn-failed";
|
|
792
|
+
errorId = out.errorId;
|
|
793
|
+
}
|
|
794
|
+
} else {
|
|
795
|
+
const out = await withTurnScope(
|
|
796
|
+
conversationId,
|
|
797
|
+
n,
|
|
798
|
+
ctl.signal,
|
|
799
|
+
() =>
|
|
800
|
+
agentLoop$(
|
|
801
|
+
ctx,
|
|
802
|
+
{ ...config.agent, loopId: `conv#o${ord}`, signal: ctl.signal },
|
|
803
|
+
{
|
|
804
|
+
prompt: promptText,
|
|
805
|
+
promptOrigin: USER_ORIGIN,
|
|
806
|
+
history: historyOf(summaryForTurn(), turns),
|
|
807
|
+
}
|
|
808
|
+
),
|
|
809
|
+
ensureWatch
|
|
810
|
+
);
|
|
811
|
+
reply = clip(out.content, maxReplyChars);
|
|
812
|
+
}
|
|
813
|
+
} catch (e) {
|
|
814
|
+
if (e instanceof TypedFailure && e.channel === AGENT_INTERRUPTED) {
|
|
815
|
+
status = "interrupted";
|
|
816
|
+
reply = clip((e.payload as InterruptedAgentRun).content ?? "", maxReplyChars);
|
|
817
|
+
} else {
|
|
818
|
+
const kind = classifyModelCallFailure(e);
|
|
819
|
+
// Control flow only (a park, an authority/safety stop, a cancel, a replay divergence) is the
|
|
820
|
+
// runtime's, not a failed turn. Any other error, even retryable=false, ends the turn failed.
|
|
821
|
+
if (kind === "terminal") throw e;
|
|
822
|
+
// The user sees a FIXED reason and a correlation id; the real error goes to the host's log.
|
|
823
|
+
status = "failed";
|
|
824
|
+
reason = kind;
|
|
825
|
+
errorId = `err-${fnv1a64(`${ctx.executionId}:${ord}`)}`;
|
|
826
|
+
failure = e;
|
|
827
|
+
}
|
|
828
|
+
} finally {
|
|
829
|
+
// Host-side, not a `ctx` operation: it can only fire the signal, which the loop reads
|
|
830
|
+
// through its recorded checkpoints.
|
|
831
|
+
if (watching !== undefined) (await watching.catch(() => () => undefined))();
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// SHARED: what the answer touched. The declared class of every tool called plus the classes of
|
|
835
|
+
// every entry that fed the context; a tool the policy does not know is "unclassified".
|
|
836
|
+
let classes: string[] = [];
|
|
837
|
+
if (sharedCfg !== undefined) {
|
|
838
|
+
classes = await ctx.decide<string[]>(
|
|
839
|
+
`conv#o${ord}:classes`,
|
|
840
|
+
() =>
|
|
841
|
+
union(
|
|
842
|
+
contextClasses,
|
|
843
|
+
toolNames.map((name) => sharedCfg.classOf?.(name) ?? "unclassified"),
|
|
844
|
+
// recalled / written memory is a data class of its own: whoever the scope belongs to
|
|
845
|
+
memoryScope === undefined ? [] : [`memory:${memoryScope}`]
|
|
846
|
+
),
|
|
847
|
+
{ source: "conversation-access" }
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
await record(
|
|
851
|
+
"reply",
|
|
852
|
+
{
|
|
853
|
+
turn: n,
|
|
854
|
+
role: "assistant",
|
|
855
|
+
text: reply,
|
|
856
|
+
status,
|
|
857
|
+
...(reason !== undefined && { reason }),
|
|
858
|
+
...(errorId !== undefined && { errorId }),
|
|
859
|
+
...(attributed !== undefined && { asker: attributed }),
|
|
860
|
+
...(classes.length > 0 && { classes }),
|
|
861
|
+
...(turnExecutionId !== undefined && { turnExecutionId }),
|
|
862
|
+
},
|
|
863
|
+
async () => {
|
|
864
|
+
if (failure !== undefined && errorId !== undefined) {
|
|
865
|
+
config.onError?.(errorId, failure, { conversationId, turn: n });
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
);
|
|
869
|
+
turns.push({
|
|
870
|
+
n,
|
|
871
|
+
ord: userOrd,
|
|
872
|
+
user: verified.text,
|
|
873
|
+
assistant: reply,
|
|
874
|
+
status,
|
|
875
|
+
...(attributed !== undefined && { asker: attributed }),
|
|
876
|
+
...(classes.length > 0 && { classes }),
|
|
877
|
+
});
|
|
878
|
+
if (sharedCfg !== undefined && turns.length > maxWindowTurns) {
|
|
879
|
+
const dropped = turns.slice(0, turns.length - maxWindowTurns);
|
|
880
|
+
turns = turns.slice(turns.length - maxWindowTurns);
|
|
881
|
+
await summarize(dropped);
|
|
882
|
+
}
|
|
883
|
+
hubEnd(config, conversationId, n);
|
|
884
|
+
if (turnsCounter.turn()) rotateDue = true;
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function hubEnd(config: ConversationConfig, conversationId: string, turn: number): void {
|
|
890
|
+
config.hub?.endTurn(conversationId, turn);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/** Keep the carry under `maxBytes` by dropping the oldest turns (deterministic: a function of the carry). */
|
|
894
|
+
function trimCarry(carry: ConversationCarry, maxBytes: number): ConversationCarry {
|
|
895
|
+
let size = UTF8.encode(JSON.stringify(carry)).length;
|
|
896
|
+
if (size <= maxBytes) return carry;
|
|
897
|
+
const turns = carry.turns.slice();
|
|
898
|
+
while (turns.length > 0 && size > maxBytes) {
|
|
899
|
+
const gone = turns.shift() as CarriedTurn;
|
|
900
|
+
size -= UTF8.encode(JSON.stringify(gone)).length + 1;
|
|
901
|
+
}
|
|
902
|
+
return { ...carry, turns };
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
export interface ConversationFlowOptions {
|
|
906
|
+
/** The flow id (default `"conversation"`). */
|
|
907
|
+
id?: string;
|
|
908
|
+
name?: string;
|
|
909
|
+
version?: string;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** A conversation flow plus what a client needs to drive it. */
|
|
913
|
+
export type ConversationFlow = RegisteredFlow<
|
|
914
|
+
ConversationCarry | Record<string, never>,
|
|
915
|
+
ConversationResult
|
|
916
|
+
> & {
|
|
917
|
+
/** `"owner"` (default) or `"shared"` (a participant set; see {@link SharedConfig}). */
|
|
918
|
+
readonly mode: "owner" | "shared";
|
|
919
|
+
readonly config: ConversationConfig;
|
|
920
|
+
/** Shared mode only: the turn flow and the effect id to register. */
|
|
921
|
+
readonly sharedTurn?: {
|
|
922
|
+
flow: RegisteredFlow<TurnInput, Omit<TurnResult, "turnExecutionId">>;
|
|
923
|
+
effectId: string;
|
|
924
|
+
signals: Map<string, AbortSignal>;
|
|
925
|
+
};
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Build the registered flow of a conversation. Register it on the runtime
|
|
930
|
+
* (`runtime.registerFlow(flow.definition, flow.runner)`) and drive it with {@link createConversations}.
|
|
931
|
+
* Needs `kernel.features.inbox` and `kernel.features.continueAsNew` on the runtime.
|
|
932
|
+
*/
|
|
933
|
+
export function conversation$(
|
|
934
|
+
config: ConversationConfig,
|
|
935
|
+
options: ConversationFlowOptions = {}
|
|
936
|
+
): ConversationFlow {
|
|
937
|
+
const id = options.id ?? "conversation";
|
|
938
|
+
const definition = flow$({
|
|
939
|
+
id,
|
|
940
|
+
name: options.name ?? "Conversation",
|
|
941
|
+
version: options.version ?? "1.0.0",
|
|
942
|
+
inputSchema: z.any(),
|
|
943
|
+
outputSchema: z.any(),
|
|
944
|
+
steps: [],
|
|
945
|
+
});
|
|
946
|
+
const effectId = config.shared?.turnEffectId ?? "conversation.turn";
|
|
947
|
+
const base = {
|
|
948
|
+
definition,
|
|
949
|
+
runner: conversationRunner(config, { turnEffectId: effectId }),
|
|
950
|
+
mode: config.shared === undefined ? "owner" : "shared",
|
|
951
|
+
config,
|
|
952
|
+
} as ConversationFlow;
|
|
953
|
+
if (config.shared === undefined) return base;
|
|
954
|
+
const signals = new Map<string, AbortSignal>();
|
|
955
|
+
return {
|
|
956
|
+
...base,
|
|
957
|
+
sharedTurn: { flow: sharedTurnFlow(config, signals, `${id}-turn`), effectId, signals },
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
export { registerSharedTurnEffect, sharedTurnEffect };
|