@handsforbots/conversation-state 0.0.0-stage → 2.0.0-alpha.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.md ADDED
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright © 2024 Alex Lana and Hands for Bots contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @handsforbots/conversation-state
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Explicit conversation state for Hands for Bots: a small, structured, auditable record of topic, goal, entities, decisions, sourced facts and pending items, changed only by checked operations and sent with every request.
4
+
5
+ Part of [Hands for Bots](https://github.com/handsforbots/handsforbots), a headless multimodal and action layer between users, GUIs and agents.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @handsforbots/conversation-state@alpha @handsforbots/core@alpha
11
+ ```
12
+
13
+ ## Documentation
14
+
15
+ - [This package](https://github.com/handsforbots/handsforbots/blob/main/docs/en-us/plugins.md#conversation-state)
16
+ - [Getting started](https://github.com/handsforbots/handsforbots/blob/main/docs/en-us/getting-started.md)
17
+ - [Documentação em português](https://github.com/handsforbots/handsforbots/blob/main/docs/pt-br/README.md)
18
+
19
+ ## License
20
+
21
+ MIT
@@ -0,0 +1,114 @@
1
+ import type { Message } from '@handsforbots/core';
2
+ import { type AttrValue, type Confidence, type Evidence, type Origin, type Rejection, type Sections, type StateView, type Writer } from './shared.js';
3
+ export type StateItem = {
4
+ id: string;
5
+ text: string;
6
+ attrs?: Record<string, AttrValue>;
7
+ /** What it belongs to (a project, product, account). */
8
+ scope?: string;
9
+ origin: Origin;
10
+ /** As asked by the writer, capped by the origin (see `capConfidence`). */
11
+ confidence: Confidence;
12
+ evidence?: Evidence[];
13
+ /** Set by the page: the backend can't change or remove it. */
14
+ locked?: boolean;
15
+ /** Revision of the last change. */
16
+ rev: number;
17
+ /** Revision that created it. */
18
+ since: number;
19
+ by: Writer;
20
+ turnId?: string;
21
+ /** Time of the last change (ms). */
22
+ at: number;
23
+ };
24
+ /** One change in the journal: the item before and after (absent when added or removed). */
25
+ export type Change = {
26
+ section: string;
27
+ id: string;
28
+ before?: StateItem;
29
+ after?: StateItem;
30
+ reason?: string;
31
+ };
32
+ export type JournalEntry = {
33
+ revision: number;
34
+ at: number;
35
+ by: Writer;
36
+ turnId?: string;
37
+ /** `'update'` or `'revert'`. */
38
+ kind: 'update' | 'revert';
39
+ reason?: string;
40
+ changes: Change[];
41
+ rejected: Rejection[];
42
+ };
43
+ /** Kept in `SessionSnapshot.conversationState` (or in memory with `persist: false`). */
44
+ export type StoredState = {
45
+ v: 1;
46
+ revision: number;
47
+ items: Record<string, StateItem[]>;
48
+ journal: JournalEntry[];
49
+ };
50
+ export type UpdateResult = {
51
+ revision: number;
52
+ applied: Change[];
53
+ rejected: Rejection[];
54
+ };
55
+ export type Limits = {
56
+ sections: Sections;
57
+ maxChars: number;
58
+ maxRemovals: number;
59
+ journal: number;
60
+ screen?: (text: string, where: {
61
+ section: string;
62
+ by: Writer;
63
+ }) => string | false;
64
+ };
65
+ export type ApplyContext = Limits & {
66
+ by: Writer;
67
+ turnId?: string;
68
+ now: number;
69
+ messages: readonly Message[];
70
+ };
71
+ export declare const emptyState: () => StoredState;
72
+ /** Characters an item costs in what is sent: its text and attrs. */
73
+ export declare function itemSize(item: Pick<StateItem, 'text' | 'attrs' | 'scope'>): number;
74
+ export declare function stateSize(items: Record<string, StateItem[]>): number;
75
+ /** Text a quote is checked against: the message's text, or a tool's result. */
76
+ export declare function messageText(message: Message): string;
77
+ /**
78
+ * Applies an update and returns the next state (the same object when
79
+ * nothing changed and nothing was rejected). Pure: never throws.
80
+ *
81
+ * Each operation is checked on its own and a bad one is rejected with a
82
+ * reason while the others go through. Two checks reject the whole update,
83
+ * because they only make sense on the result: more removals than
84
+ * `maxRemovals` (a model that "forgot" half of the state), and a result over
85
+ * `maxChars`.
86
+ */
87
+ export declare function applyUpdate(current: StoredState, update: unknown, context: ApplyContext): {
88
+ next: StoredState;
89
+ result: UpdateResult;
90
+ };
91
+ /**
92
+ * Undoes every change made after `revision`, from the journal. Fails (and
93
+ * changes nothing) when the journal no longer reaches that far back.
94
+ */
95
+ export declare function revertTo(current: StoredState, revision: number, reason: string, context: Omit<ApplyContext, 'messages' | 'screen'>): {
96
+ next: StoredState;
97
+ result: UpdateResult;
98
+ } | {
99
+ error: string;
100
+ };
101
+ /** What the backend receives. */
102
+ export declare function viewOf(state: StoredState, sections: Sections, rejected?: Rejection[]): StateView;
103
+ /**
104
+ * Reads a stored state (from storage or another tab): keeps known sections
105
+ * and well-formed items, drops the rest. Never throws.
106
+ */
107
+ export declare function loadState(raw: unknown, sections: Sections): StoredState;
108
+ /**
109
+ * The confidence an item keeps: what the writer asked, never above what its
110
+ * origin supports. The user, a tool result or the page: up to `'high'`
111
+ * (default). The assistant's own message: up to `'medium'`. No evidence: `'low'`.
112
+ */
113
+ export declare function capConfidence(asked: Confidence | undefined, origin: Origin): Confidence;
114
+ //# sourceMappingURL=apply.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../src/apply.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAcL,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,SAAS,EAGd,KAAK,QAAQ,EAEb,KAAK,SAAS,EAEd,KAAK,MAAM,EACZ,MAAM,aAAa,CAAA;AAEpB,MAAM,MAAM,SAAS,GAAG;IACtB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;IACjC,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,0EAA0E;IAC1E,UAAU,EAAE,UAAU,CAAA;IACtB,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAA;IACrB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAA;IACX,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,EAAE,EAAE,MAAM,CAAA;IACV,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAA;CACX,CAAA;AAED,2FAA2F;AAC3F,MAAM,MAAM,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAE5G,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,EA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ATTR_CHARS, MAX_ATTRS, MAX_EVIDENCE, MAX_OPS, MAX_QUOTE_CHARS, MAX_SCOPE_CHARS, MIN_QUOTE_CHARS, CONFIDENCE, } from './shared.js';
2
+ export const emptyState = () => ({ v: 1, revision: 0, items: {}, journal: [] });
3
+ /** Characters an item costs in what is sent: its text and attrs. */
4
+ export function itemSize(item) {
5
+ return item.text.length + (item.scope?.length ?? 0) + (item.attrs ? JSON.stringify(item.attrs).length : 0);
6
+ }
7
+ export function stateSize(items) {
8
+ let size = 0;
9
+ for (const list of Object.values(items))
10
+ for (const item of list)
11
+ size += itemSize(item);
12
+ return size;
13
+ }
14
+ /** Text a quote is checked against: the message's text, or a tool's result. */
15
+ export function messageText(message) {
16
+ if (message.role === 'tool') {
17
+ let payload = '';
18
+ try {
19
+ payload = JSON.stringify(message.error ?? message.result ?? '') ?? '';
20
+ }
21
+ catch {
22
+ /* unserializable result */
23
+ }
24
+ return `${message.name} ${message.error ?? ''} ${payload}`;
25
+ }
26
+ return message.parts.map((p) => (p.type === 'text' ? p.text : '')).join('\n');
27
+ }
28
+ /**
29
+ * Applies an update and returns the next state (the same object when
30
+ * nothing changed and nothing was rejected). Pure: never throws.
31
+ *
32
+ * Each operation is checked on its own and a bad one is rejected with a
33
+ * reason while the others go through. Two checks reject the whole update,
34
+ * because they only make sense on the result: more removals than
35
+ * `maxRemovals` (a model that "forgot" half of the state), and a result over
36
+ * `maxChars`.
37
+ */
38
+ export function applyUpdate(current, update, context) {
39
+ const rejected = [];
40
+ const changes = [];
41
+ const reject = (index, reason, op, detail) => rejected.push({
42
+ index,
43
+ reason,
44
+ ...(op && typeof op.op === 'string' ? { op: op.op } : {}),
45
+ ...(op && typeof op.section === 'string' ? { section: op.section } : {}),
46
+ ...(op && typeof op.id === 'string' ? { id: op.id } : {}),
47
+ ...(detail ? { detail } : {}),
48
+ });
49
+ const done = (next) => ({ next, result: { revision: next.revision, applied: changes, rejected } });
50
+ if (!isRecord(update) || !Array.isArray(update.ops)) {
51
+ reject(-1, 'invalid', undefined, 'expected { base?, ops: [...] }');
52
+ return done(record(current, [], rejected, context, 'update'));
53
+ }
54
+ const base = typeof update.base === 'number' && Number.isInteger(update.base) ? update.base : undefined;
55
+ const ops = update.ops;
56
+ const revision = current.revision + 1;
57
+ const work = { ...current.items };
58
+ let removals = 0;
59
+ ops.forEach((raw, index) => {
60
+ if (index >= MAX_OPS)
61
+ return reject(index, 'invalid', undefined, `at most ${MAX_OPS} ops per update`);
62
+ if (!isRecord(raw))
63
+ return reject(index, 'invalid');
64
+ const op = raw;
65
+ const section = typeof op.section === 'string' ? op.section : undefined;
66
+ const spec = section && Object.hasOwn(context.sections, section) ? context.sections[section] : undefined;
67
+ if (!section || !spec)
68
+ return reject(index, 'unknown-section', op);
69
+ const kind = op.op;
70
+ if (kind !== 'set' && kind !== 'add' && kind !== 'update' && kind !== 'remove')
71
+ return reject(index, 'invalid', op, 'op must be set, add, update or remove');
72
+ if ((kind === 'set' && spec.kind !== 'value') || ((kind === 'add' || kind === 'update') && spec.kind !== 'list'))
73
+ return reject(index, 'invalid', op, `${kind} does not apply to a ${spec.kind} section`);
74
+ const list = work[section] ?? [];
75
+ const byApp = context.by === 'app';
76
+ // Text
77
+ let text;
78
+ if (op.text !== undefined) {
79
+ const checked = checkText(op.text, spec, section, context);
80
+ if (typeof checked !== 'string')
81
+ return reject(index, checked.reason, op, checked.detail);
82
+ text = checked;
83
+ }
84
+ else if (kind === 'set' || kind === 'add')
85
+ return reject(index, 'invalid', op, 'text is required');
86
+ // Attrs
87
+ let attrs;
88
+ if (op.attrs !== undefined && kind !== 'remove') {
89
+ const checked = checkAttrs(op.attrs, kind === 'update', section, context);
90
+ if ('reason' in checked)
91
+ return reject(index, checked.reason, op, checked.detail);
92
+ attrs = checked;
93
+ }
94
+ // Scope and confidence
95
+ let scope;
96
+ if (op.scope !== undefined && kind !== 'remove') {
97
+ if (op.scope === null && kind === 'update')
98
+ scope = null;
99
+ else {
100
+ const checked = checkText(op.scope, { kind: 'value', description: '', maxChars: MAX_SCOPE_CHARS }, section, context);
101
+ if (typeof checked !== 'string')
102
+ return reject(index, checked.reason, op, `scope: ${checked.detail ?? checked.reason}`);
103
+ scope = checked;
104
+ }
105
+ }
106
+ let asked;
107
+ if (op.confidence !== undefined && kind !== 'remove') {
108
+ if (!CONFIDENCE.includes(op.confidence))
109
+ return reject(index, 'invalid', op, `confidence must be one of ${CONFIDENCE.join(', ')}`);
110
+ asked = op.confidence;
111
+ }
112
+ // Evidence
113
+ let evidence;
114
+ if (op.evidence !== undefined) {
115
+ const checked = checkEvidence(op.evidence, context.messages);
116
+ if (!Array.isArray(checked))
117
+ return reject(index, checked.reason, op, checked.detail);
118
+ evidence = checked;
119
+ }
120
+ const origin = originOf(evidence, byApp);
121
+ const needs = spec.evidence ?? 'none';
122
+ const changesContent = kind !== 'remove' && (text !== undefined || kind !== 'update');
123
+ if (!byApp && changesContent && needs !== 'none') {
124
+ if (!evidence?.length)
125
+ return reject(index, 'evidence-required', op, `${section} needs ${needs === 'quote' ? 'a message id and a verbatim quote' : 'a message id'}`);
126
+ if (needs === 'quote' && !evidence.some((e) => e.quote))
127
+ return reject(index, 'evidence-required', op, `${section} needs a verbatim quote`);
128
+ }
129
+ // Target
130
+ let target;
131
+ if (kind === 'set')
132
+ target = list[0];
133
+ else if (kind === 'update' || (kind === 'remove' && spec.kind === 'list')) {
134
+ if (typeof op.id !== 'string')
135
+ return reject(index, 'invalid', op, 'id is required');
136
+ target = list.find((item) => item.id === op.id);
137
+ if (!target)
138
+ return reject(index, 'unknown-item', op);
139
+ }
140
+ else if (kind === 'remove') {
141
+ target = list[0];
142
+ if (!target)
143
+ return reject(index, 'unknown-item', op, 'the section is empty');
144
+ }
145
+ if (target) {
146
+ if (target.locked && !byApp)
147
+ return reject(index, 'locked', op);
148
+ if (base !== undefined && target.rev > base)
149
+ return reject(index, 'stale', op, `changed in revision ${target.rev}, after ${base}`);
150
+ if (!byApp && (spec.keepUserStated ?? true) && target.origin === 'user' && origin !== 'user')
151
+ return reject(index, 'user-stated', op, 'the user stated this; change it with evidence from a user message');
152
+ }
153
+ if (kind === 'remove') {
154
+ const reason = typeof op.reason === 'string' ? cleanText(op.reason).slice(0, 200) : '';
155
+ if (!reason)
156
+ return reject(index, 'reason-required', op);
157
+ removals++;
158
+ work[section] = list.filter((item) => item !== target);
159
+ changes.push({ section, id: target.id, before: target, reason });
160
+ return;
161
+ }
162
+ const locked = byApp && typeof op.locked === 'boolean' ? op.locked : target?.locked;
163
+ const stamp = { rev: revision, by: context.by, at: context.now, ...(context.turnId ? { turnId: context.turnId } : {}) };
164
+ if (kind === 'add') {
165
+ // Same text in another scope is another thing ("Terraform" of two projects).
166
+ const key = comparable(text);
167
+ const where = scope ? comparable(scope) : '';
168
+ if (list.some((item) => comparable(item.text) === key && (item.scope ? comparable(item.scope) : '') === where))
169
+ return reject(index, 'duplicate', op, 'already there');
170
+ if (list.length >= (spec.max ?? 20))
171
+ return reject(index, 'section-full', op, `at most ${spec.max ?? 20}; remove or merge items first`);
172
+ let id;
173
+ if (op.id !== undefined) {
174
+ if (typeof op.id !== 'string' || !ITEM_ID.test(op.id) || list.some((item) => item.id === op.id))
175
+ return reject(index, 'invalid', op, 'id must be new and match [A-Za-z0-9_.:-]{1,40}');
176
+ id = op.id;
177
+ }
178
+ else
179
+ id = freshId(section, list);
180
+ const item = {
181
+ id,
182
+ text: text,
183
+ ...(attrs ? { attrs: dropNulls(attrs) } : {}),
184
+ ...(scope ? { scope } : {}),
185
+ origin,
186
+ confidence: capConfidence(asked, origin),
187
+ ...(evidence?.length ? { evidence } : {}),
188
+ ...(locked ? { locked: true } : {}),
189
+ since: revision,
190
+ ...stamp,
191
+ };
192
+ work[section] = [...list, item];
193
+ changes.push({ section, id, after: item });
194
+ return;
195
+ }
196
+ // set / update
197
+ const nextText = text ?? target.text;
198
+ const nextAttrs = kind === 'set' ? (attrs ? dropNulls(attrs) : undefined) : mergeAttrs(target.attrs, attrs);
199
+ const nextScope = scope === null ? undefined : (scope ?? (kind === 'update' ? target?.scope : undefined));
200
+ const keepsContent = !!target && text === undefined;
201
+ // New text without new evidence loses the old evidence (it may not support the new text).
202
+ const nextOrigin = evidence ? origin : keepsContent ? target.origin : byApp ? 'app' : 'unsourced';
203
+ const nextConfidence = capConfidence(asked ?? (evidence || !keepsContent ? undefined : target.confidence), nextOrigin);
204
+ if (target &&
205
+ comparable(nextText) === comparable(target.text) &&
206
+ sameAttrs(nextAttrs, target.attrs) &&
207
+ nextScope === target.scope &&
208
+ nextConfidence === target.confidence &&
209
+ !evidence &&
210
+ locked === target.locked)
211
+ return reject(index, 'duplicate', op, 'no change');
212
+ const item = {
213
+ id: target?.id ?? section,
214
+ text: nextText,
215
+ ...(nextAttrs && Object.keys(nextAttrs).length ? { attrs: nextAttrs } : {}),
216
+ ...(nextScope ? { scope: nextScope } : {}),
217
+ origin: nextOrigin,
218
+ confidence: nextConfidence,
219
+ ...(evidence ? { evidence } : keepsContent && target.evidence ? { evidence: target.evidence } : {}),
220
+ ...(locked ? { locked: true } : {}),
221
+ since: target && comparable(nextText) === comparable(target.text) ? target.since : revision,
222
+ ...stamp,
223
+ };
224
+ work[section] = target ? list.map((i) => (i === target ? item : i)) : [item];
225
+ changes.push({ section, id: item.id, ...(target ? { before: target } : {}), after: item });
226
+ });
227
+ if (changes.length > 0 && !(context.by === 'app')) {
228
+ if (removals > context.maxRemovals)
229
+ return rejectAll(current, changes, rejected, 'too-many-removals', `${removals} removals; at most ${context.maxRemovals} per update`, context);
230
+ }
231
+ if (changes.length > 0) {
232
+ const size = stateSize(work);
233
+ if (size > context.maxChars && size > stateSize(current.items))
234
+ return rejectAll(current, changes, rejected, 'over-budget', `${size} characters; free ${size - context.maxChars} (limit ${context.maxChars})`, context);
235
+ }
236
+ if (changes.length === 0)
237
+ return done(record(current, [], rejected, context, 'update'));
238
+ for (const key of Object.keys(work))
239
+ if (work[key].length === 0)
240
+ delete work[key];
241
+ return done(record({ ...current, revision, items: work }, changes, rejected, context, 'update'));
242
+ function rejectAll(state, applied, earlier, reason, detail, ctx) {
243
+ // Nothing applies; every op that would have applied is listed with the reason.
244
+ const failed = new Set(earlier.map((r) => r.index));
245
+ const all = ops
246
+ .map((op, index) => ({ op, index }))
247
+ .filter(({ index }) => !failed.has(index) && index < MAX_OPS)
248
+ .map(({ op, index }) => {
249
+ const o = isRecord(op) ? op : {};
250
+ return {
251
+ index,
252
+ reason,
253
+ ...(typeof o.op === 'string' ? { op: o.op } : {}),
254
+ ...(typeof o.section === 'string' ? { section: o.section } : {}),
255
+ ...(typeof o.id === 'string' ? { id: o.id } : {}),
256
+ detail,
257
+ };
258
+ });
259
+ applied.length = 0;
260
+ rejected.push(...all);
261
+ rejected.sort((a, b) => a.index - b.index);
262
+ return done(record(state, [], rejected, ctx, 'update'));
263
+ }
264
+ }
265
+ /**
266
+ * Undoes every change made after `revision`, from the journal. Fails (and
267
+ * changes nothing) when the journal no longer reaches that far back.
268
+ */
269
+ export function revertTo(current, revision, reason, context) {
270
+ if (!Number.isInteger(revision) || revision < 0 || revision >= current.revision)
271
+ return { error: `revision must be an integer from 0 to ${current.revision - 1}` };
272
+ const entries = current.journal.filter((e) => e.revision > revision && e.changes.length > 0);
273
+ const covered = new Set(entries.map((e) => e.revision));
274
+ for (let r = revision + 1; r <= current.revision; r++)
275
+ if (!covered.has(r))
276
+ return { error: `the journal no longer has revision ${r}` };
277
+ const next = current.revision + 1;
278
+ const work = { ...current.items };
279
+ const changes = [];
280
+ for (const entry of [...entries].reverse()) {
281
+ for (const change of [...entry.changes].reverse()) {
282
+ const list = work[change.section] ?? [];
283
+ const now = list.find((item) => item.id === change.id);
284
+ const restored = change.before ? { ...change.before, rev: next, at: context.now, by: context.by } : undefined;
285
+ const rest = list.filter((item) => item.id !== change.id);
286
+ work[change.section] = restored ? (now ? list.map((i) => (i.id === change.id ? restored : i)) : [...rest, restored]) : rest;
287
+ changes.push({ section: change.section, id: change.id, ...(now ? { before: now } : {}), ...(restored ? { after: restored } : {}), reason });
288
+ }
289
+ }
290
+ for (const key of Object.keys(work))
291
+ if (work[key].length === 0)
292
+ delete work[key];
293
+ const state = record({ ...current, revision: next, items: work }, changes, [], context, 'revert', reason);
294
+ return { next: state, result: { revision: next, applied: changes, rejected: [] } };
295
+ }
296
+ /** What the backend receives. */
297
+ export function viewOf(state, sections, rejected) {
298
+ const view = {};
299
+ for (const [name, spec] of Object.entries(sections)) {
300
+ const items = (state.items[name] ?? []).map(toView);
301
+ view[name] = spec.kind === 'value' ? (items[0] ?? null) : items;
302
+ }
303
+ return { revision: state.revision, sections: view, ...(rejected?.length ? { rejected } : {}) };
304
+ }
305
+ function toView(item) {
306
+ return {
307
+ id: item.id,
308
+ text: item.text,
309
+ ...(item.attrs ? { attrs: item.attrs } : {}),
310
+ ...(item.scope ? { scope: item.scope } : {}),
311
+ origin: item.origin,
312
+ confidence: item.confidence,
313
+ ...(item.evidence?.length ? { src: item.evidence.map((e) => e.messageId) } : {}),
314
+ ...(stated(item) ? { stated: stated(item) } : {}),
315
+ ...(item.locked ? { locked: true } : {}),
316
+ };
317
+ }
318
+ /**
319
+ * Reads a stored state (from storage or another tab): keeps known sections
320
+ * and well-formed items, drops the rest. Never throws.
321
+ */
322
+ export function loadState(raw, sections) {
323
+ if (!isRecord(raw) || raw.v !== 1 || !isRecord(raw.items))
324
+ return emptyState();
325
+ const revision = Number.isInteger(raw.revision) && raw.revision >= 0 ? raw.revision : 0;
326
+ const items = {};
327
+ for (const [name, list] of Object.entries(raw.items)) {
328
+ if (!Object.hasOwn(sections, name) || !Array.isArray(list))
329
+ continue;
330
+ const kept = list.filter(isStoredItem).slice(0, sections[name].kind === 'value' ? 1 : 1000);
331
+ if (kept.length)
332
+ items[name] = kept;
333
+ }
334
+ const journal = Array.isArray(raw.journal) ? raw.journal.filter((e) => isRecord(e) && Number.isInteger(e.revision) && Array.isArray(e.changes)) : [];
335
+ return { v: 1, revision, items, journal };
336
+ }
337
+ function stated(item) {
338
+ const times = (item.evidence ?? []).map((e) => e.at).filter((t) => typeof t === 'number' && Number.isFinite(t));
339
+ return times.length ? new Date(Math.max(...times)).toISOString() : undefined;
340
+ }
341
+ /**
342
+ * The confidence an item keeps: what the writer asked, never above what its
343
+ * origin supports. The user, a tool result or the page: up to `'high'`
344
+ * (default). The assistant's own message: up to `'medium'`. No evidence: `'low'`.
345
+ */
346
+ export function capConfidence(asked, origin) {
347
+ const ceiling = origin === 'unsourced' ? 'low' : origin === 'assistant' ? 'medium' : 'high';
348
+ const rank = (c) => CONFIDENCE.indexOf(c); // 0 = high
349
+ const wanted = asked ?? ceiling;
350
+ return rank(wanted) >= rank(ceiling) ? wanted : ceiling;
351
+ }
352
+ function isStoredItem(value) {
353
+ return (isRecord(value) &&
354
+ typeof value.id === 'string' &&
355
+ typeof value.text === 'string' &&
356
+ typeof value.origin === 'string' &&
357
+ CONFIDENCE.includes(value.confidence) &&
358
+ Number.isInteger(value.rev) &&
359
+ Number.isInteger(value.since));
360
+ }
361
+ function checkText(raw, spec, section, context) {
362
+ if (typeof raw !== 'string')
363
+ return { reason: 'invalid', detail: 'text must be a string' };
364
+ let text = cleanText(raw);
365
+ if (context.screen) {
366
+ let screened;
367
+ try {
368
+ screened = context.screen(text, { section, by: context.by });
369
+ }
370
+ catch {
371
+ screened = false;
372
+ }
373
+ if (screened === false)
374
+ return { reason: 'screened' };
375
+ text = cleanText(screened);
376
+ }
377
+ if (!text)
378
+ return { reason: 'invalid', detail: 'text is empty' };
379
+ const max = spec.maxChars ?? 300;
380
+ // Never cut: a cut sentence can say something else.
381
+ if (text.length > max)
382
+ return { reason: 'too-long', detail: `${text.length} characters; at most ${max}` };
383
+ if (spec.values && !spec.values.includes(text))
384
+ return { reason: 'not-allowed-value', detail: `one of: ${spec.values.join(', ')}` };
385
+ return text;
386
+ }
387
+ function checkAttrs(raw, allowNull, section, context) {
388
+ if (!isRecord(raw))
389
+ return { reason: 'invalid', detail: 'attrs must be an object' };
390
+ const entries = Object.entries(raw);
391
+ if (entries.length > MAX_ATTRS)
392
+ return { reason: 'invalid', detail: `at most ${MAX_ATTRS} attrs` };
393
+ const out = {};
394
+ for (const [key, value] of entries) {
395
+ if (!ATTR_KEY.test(key))
396
+ return { reason: 'invalid', detail: `attr name "${key.slice(0, 40)}"` };
397
+ if (value === null && allowNull)
398
+ out[key] = null;
399
+ else if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
400
+ out[key] = value;
401
+ else if (typeof value === 'string') {
402
+ const checked = checkText(value, { kind: 'value', description: '', maxChars: MAX_ATTR_CHARS }, section, context);
403
+ if (typeof checked !== 'string')
404
+ return { reason: checked.reason, detail: `attr ${key}: ${checked.detail ?? checked.reason}` };
405
+ out[key] = checked;
406
+ }
407
+ else
408
+ return { reason: 'invalid', detail: `attr ${key} must be a string, number or boolean` };
409
+ }
410
+ return out;
411
+ }
412
+ function checkEvidence(raw, messages) {
413
+ if (!Array.isArray(raw))
414
+ return { reason: 'invalid', detail: 'evidence must be an array' };
415
+ if (raw.length > MAX_EVIDENCE)
416
+ return { reason: 'invalid', detail: `at most ${MAX_EVIDENCE} evidence items` };
417
+ const out = [];
418
+ for (const entry of raw) {
419
+ if (!isRecord(entry) || typeof entry.messageId !== 'string')
420
+ return { reason: 'invalid', detail: 'evidence items need a messageId' };
421
+ const message = messages.find((m) => m.id === entry.messageId);
422
+ if (!message)
423
+ return { reason: 'evidence-not-found', detail: `no message ${entry.messageId.slice(0, 60)} in this conversation` };
424
+ const evidence = { messageId: message.id, role: message.role, at: message.createdAt };
425
+ if (entry.quote !== undefined) {
426
+ if (typeof entry.quote !== 'string')
427
+ return { reason: 'invalid', detail: 'quote must be a string' };
428
+ const quote = cleanText(entry.quote);
429
+ if (quote.length < MIN_QUOTE_CHARS || quote.length > MAX_QUOTE_CHARS)
430
+ return { reason: 'invalid', detail: `quote must have ${MIN_QUOTE_CHARS} to ${MAX_QUOTE_CHARS} characters` };
431
+ // The deterministic check against invented facts: the quote must be in the message.
432
+ if (!comparable(messageText(message)).includes(comparable(quote).replace(/^["'.\s]+|["'.\s]+$/g, '')))
433
+ return { reason: 'quote-not-found', detail: `the quote is not in message ${message.id}` };
434
+ evidence.quote = quote;
435
+ }
436
+ out.push(evidence);
437
+ }
438
+ return out;
439
+ }
440
+ function originOf(evidence, byApp) {
441
+ if (!evidence?.length)
442
+ return byApp ? 'app' : 'unsourced';
443
+ if (evidence.some((e) => e.role === 'user'))
444
+ return 'user';
445
+ if (evidence.some((e) => e.role === 'tool'))
446
+ return 'tool';
447
+ return 'assistant';
448
+ }
449
+ function freshId(section, list) {
450
+ const prefix = section.replace(/[^A-Za-z0-9]/g, '').slice(0, 1).toLowerCase() || 'i';
451
+ let n = list.length + 1;
452
+ while (list.some((item) => item.id === `${prefix}${n}`))
453
+ n++;
454
+ return `${prefix}${n}`;
455
+ }
456
+ function dropNulls(attrs) {
457
+ return Object.fromEntries(Object.entries(attrs).filter(([, v]) => v !== null));
458
+ }
459
+ function mergeAttrs(before, change) {
460
+ if (!change)
461
+ return before;
462
+ const merged = dropNulls({ ...before, ...change });
463
+ return Object.keys(merged).length ? merged : undefined;
464
+ }
465
+ function sameAttrs(a, b) {
466
+ const ak = Object.keys(a ?? {});
467
+ const bk = Object.keys(b ?? {});
468
+ return ak.length === bk.length && ak.every((k) => a[k] === b?.[k]);
469
+ }
470
+ function record(state, changes, rejected, context, kind, reason) {
471
+ if (changes.length === 0 && rejected.length === 0)
472
+ return state;
473
+ const entry = {
474
+ revision: state.revision,
475
+ at: context.now,
476
+ by: context.by,
477
+ ...(context.turnId ? { turnId: context.turnId } : {}),
478
+ kind,
479
+ ...(reason ? { reason } : {}),
480
+ changes,
481
+ rejected,
482
+ };
483
+ return { ...state, journal: [...state.journal, entry].slice(-Math.max(1, context.journal)) };
484
+ }
485
+ //# sourceMappingURL=apply.js.map