tandem-kit-core 0.0.0 → 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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -1
  3. package/dist/src/browser.d.ts +19 -0
  4. package/dist/src/browser.js +19 -0
  5. package/dist/src/client-tools.d.ts +31 -0
  6. package/dist/src/client-tools.js +82 -0
  7. package/dist/src/client.d.ts +179 -0
  8. package/dist/src/client.js +213 -0
  9. package/dist/src/delta.d.ts +16 -0
  10. package/dist/src/delta.js +99 -0
  11. package/dist/src/durable.d.ts +39 -0
  12. package/dist/src/durable.js +104 -0
  13. package/dist/src/errors.d.ts +5 -0
  14. package/dist/src/errors.js +10 -0
  15. package/dist/src/eventlog-file.d.ts +12 -0
  16. package/dist/src/eventlog-file.js +39 -0
  17. package/dist/src/eventlog.d.ts +31 -0
  18. package/dist/src/eventlog.js +63 -0
  19. package/dist/src/events.d.ts +15 -0
  20. package/dist/src/events.js +79 -0
  21. package/dist/src/events.json +80 -0
  22. package/dist/src/files.d.ts +34 -0
  23. package/dist/src/files.js +122 -0
  24. package/dist/src/fsutil.d.ts +8 -0
  25. package/dist/src/fsutil.js +68 -0
  26. package/dist/src/hash.d.ts +3 -0
  27. package/dist/src/hash.js +65 -0
  28. package/dist/src/images.d.ts +24 -0
  29. package/dist/src/images.js +70 -0
  30. package/dist/src/index.d.ts +25 -0
  31. package/dist/src/index.js +25 -0
  32. package/dist/src/json.d.ts +10 -0
  33. package/dist/src/json.js +68 -0
  34. package/dist/src/merge.d.ts +34 -0
  35. package/dist/src/merge.js +111 -0
  36. package/dist/src/persist.d.ts +49 -0
  37. package/dist/src/persist.js +29 -0
  38. package/dist/src/proposals-file.d.ts +12 -0
  39. package/dist/src/proposals-file.js +36 -0
  40. package/dist/src/proposals.d.ts +149 -0
  41. package/dist/src/proposals.js +296 -0
  42. package/dist/src/reconcile.d.ts +63 -0
  43. package/dist/src/reconcile.js +61 -0
  44. package/dist/src/replica.d.ts +147 -0
  45. package/dist/src/replica.js +320 -0
  46. package/dist/src/revisions-file.d.ts +14 -0
  47. package/dist/src/revisions-file.js +28 -0
  48. package/dist/src/revisions.d.ts +78 -0
  49. package/dist/src/revisions.js +152 -0
  50. package/dist/src/revisions.json +19 -0
  51. package/dist/src/schema.d.ts +12 -0
  52. package/dist/src/schema.js +49 -0
  53. package/dist/src/session-state.d.ts +36 -0
  54. package/dist/src/session-state.js +95 -0
  55. package/dist/src/sse.d.ts +17 -0
  56. package/dist/src/sse.js +59 -0
  57. package/dist/src/workcopy.d.ts +145 -0
  58. package/dist/src/workcopy.js +556 -0
  59. package/package.json +34 -4
@@ -0,0 +1,49 @@
1
+ import { type Json } from './json.js';
2
+ import type { Finding } from './revisions.js';
3
+ import type { ClashRecord } from './workcopy.js';
4
+ export declare const MAX_CLOSED_CLASHES = 1000;
5
+ export interface ClashState {
6
+ open: ClashRecord[];
7
+ closed: string[];
8
+ count: number;
9
+ ids?: 'content';
10
+ }
11
+ export interface ClashStore {
12
+ load(): ClashState;
13
+ save(state: ClashState): void;
14
+ }
15
+ export declare class MemoryClashStore implements ClashStore {
16
+ private state;
17
+ load(): ClashState;
18
+ save(state: ClashState): void;
19
+ }
20
+ export interface DocSnapshot {
21
+ version: number;
22
+ state: Json;
23
+ last_writer: string;
24
+ pending: {
25
+ actor: string;
26
+ reasons: string[];
27
+ findings: Finding[];
28
+ } | null;
29
+ }
30
+ export interface SnapshotStore {
31
+ load(): DocSnapshot | null;
32
+ save(snapshot: DocSnapshot): void;
33
+ }
34
+ export declare class MemorySnapshotStore implements SnapshotStore {
35
+ private snapshot;
36
+ load(): DocSnapshot | null;
37
+ save(snapshot: DocSnapshot): void;
38
+ }
39
+ export type SavePolicy = 'immediate' | 'explicit' | 'turn-end' | {
40
+ quietMs: number;
41
+ maxMs: number;
42
+ };
43
+ export declare function savePolicyOf(options: {
44
+ save?: SavePolicy;
45
+ autosave?: {
46
+ quietMs: number;
47
+ maxMs: number;
48
+ } | false;
49
+ }, fallback: SavePolicy): SavePolicy;
@@ -0,0 +1,29 @@
1
+ import { clone } from "./json.js";
2
+ export const MAX_CLOSED_CLASHES = 1000;
3
+ export class MemoryClashStore {
4
+ state = { open: [], closed: [], count: 0 };
5
+ load() {
6
+ return clone(this.state);
7
+ }
8
+ save(state) {
9
+ this.state = clone(state);
10
+ }
11
+ }
12
+ export class MemorySnapshotStore {
13
+ snapshot = null;
14
+ load() {
15
+ return this.snapshot ? clone(this.snapshot) : null;
16
+ }
17
+ save(snapshot) {
18
+ this.snapshot = clone(snapshot);
19
+ }
20
+ }
21
+ export function savePolicyOf(options, fallback) {
22
+ if (options.save !== undefined)
23
+ return options.save;
24
+ if (options.autosave === false)
25
+ return 'immediate';
26
+ if (options.autosave)
27
+ return options.autosave;
28
+ return fallback;
29
+ }
@@ -0,0 +1,12 @@
1
+ import { type FileOptions } from './fsutil.js';
2
+ import type { ProposalStore, StoredProposal } from './proposals.js';
3
+ export declare const PROPOSALS_FORMAT = "tandem-proposals/1";
4
+ export declare class FileProposalStore implements ProposalStore {
5
+ private readonly path;
6
+ private readonly options;
7
+ private readonly items;
8
+ constructor(path: string, options?: FileOptions);
9
+ list(): StoredProposal[];
10
+ get(id: string): StoredProposal | undefined;
11
+ save(proposal: StoredProposal): void;
12
+ }
@@ -0,0 +1,36 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { writeFileAtomic } from "./fsutil.js";
3
+ import { clone } from "./json.js";
4
+ export const PROPOSALS_FORMAT = 'tandem-proposals/1';
5
+ // every proposal in one file, replaced whole on each change (temp file and rename), so a restart finds all of them or the state before the last change
6
+ export class FileProposalStore {
7
+ path;
8
+ options;
9
+ items = new Map();
10
+ constructor(path, options = {}) {
11
+ this.path = path;
12
+ this.options = options;
13
+ if (existsSync(path)) {
14
+ try {
15
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
16
+ for (const p of parsed.proposals ?? [])
17
+ if (p && typeof p.id === 'string')
18
+ this.items.set(p.id, p);
19
+ }
20
+ catch {
21
+ this.items.clear();
22
+ }
23
+ }
24
+ }
25
+ list() {
26
+ return [...this.items.values()].map((p) => clone(p));
27
+ }
28
+ get(id) {
29
+ const found = this.items.get(id);
30
+ return found ? clone(found) : undefined;
31
+ }
32
+ save(proposal) {
33
+ this.items.set(proposal.id, clone(proposal));
34
+ writeFileAtomic(this.path, `${JSON.stringify({ format: PROPOSALS_FORMAT, proposals: [...this.items.values()] }, null, 1)}\n`, this.options);
35
+ }
36
+ }
@@ -0,0 +1,149 @@
1
+ import { type Delta } from './delta.js';
2
+ import { TandemError } from './errors.js';
3
+ import { EventLog } from './eventlog.js';
4
+ import { type Json } from './json.js';
5
+ import type { WriteResult, Workcopy } from './workcopy.js';
6
+ export declare const PROPOSAL_STATES: readonly ["proposed", "applied", "discarded", "refused"];
7
+ export type ProposalState = (typeof PROPOSAL_STATES)[number];
8
+ export interface Proposal {
9
+ id: string;
10
+ session: string | null;
11
+ kind: string;
12
+ title: string | null;
13
+ reason: string | null;
14
+ doc: string | null;
15
+ version: number | null;
16
+ delta: Delta | null;
17
+ data: Json | null;
18
+ state: ProposalState;
19
+ problems: string[];
20
+ edited: boolean;
21
+ by: string | null;
22
+ at: string;
23
+ resolved_at: string | null;
24
+ revision: string | null;
25
+ result: Json | null;
26
+ }
27
+ export interface StoredProposal extends Proposal {
28
+ told: boolean;
29
+ }
30
+ export interface ProposalStore {
31
+ list(): StoredProposal[];
32
+ get(id: string): StoredProposal | undefined;
33
+ save(proposal: StoredProposal): void;
34
+ }
35
+ export declare class MemoryProposalStore implements ProposalStore {
36
+ private readonly items;
37
+ list(): StoredProposal[];
38
+ get(id: string): StoredProposal | undefined;
39
+ save(proposal: StoredProposal): void;
40
+ }
41
+ export interface ProposeInput {
42
+ session?: string | null;
43
+ kind: string;
44
+ title?: string | null;
45
+ reason?: string | null;
46
+ doc?: string | null;
47
+ version?: number | null;
48
+ delta?: Delta | null;
49
+ state?: Json;
50
+ data?: Json | null;
51
+ /** the caller already showed the agent a refusal (a tool call returned it), so the book does not tell it again with the news. Only matters when the proposal is refused and kept */
52
+ seen?: boolean;
53
+ }
54
+ export interface ProposalEdit {
55
+ title?: string | null;
56
+ reason?: string | null;
57
+ data?: Json | null;
58
+ delta?: Delta | null;
59
+ }
60
+ export interface ProposalHandler {
61
+ validate?(input: ProposeInput & {
62
+ delta: Delta | null;
63
+ }): string | readonly string[] | null | undefined | void;
64
+ apply?(proposal: Proposal, context: {
65
+ actor: string;
66
+ edited: boolean;
67
+ }): Json | undefined | void | Promise<Json | undefined | void>;
68
+ }
69
+ export type WorkcopySource = Record<string, Workcopy> | {
70
+ get(name: string): Workcopy | undefined;
71
+ };
72
+ export interface ProposalBookOptions {
73
+ store?: ProposalStore;
74
+ log?: EventLog;
75
+ workcopies?: WorkcopySource;
76
+ handlers?: Record<string, ProposalHandler>;
77
+ applyActor?: string;
78
+ recordRefused?: boolean;
79
+ tellRefused?: boolean;
80
+ idScope?: 'book' | 'session';
81
+ idPrefix?: string;
82
+ news?: false | ((proposal: Proposal) => string);
83
+ newsPrefix?: string;
84
+ clock?: () => string;
85
+ }
86
+ export interface ProposalFilter {
87
+ session?: string | null;
88
+ doc?: string | null;
89
+ state?: ProposalState;
90
+ kind?: string;
91
+ }
92
+ export interface ApplyOptions {
93
+ edit?: ProposalEdit;
94
+ actor?: string;
95
+ }
96
+ export interface ApplyResult {
97
+ proposal: Proposal;
98
+ write?: WriteResult;
99
+ result?: Json;
100
+ }
101
+ export declare class ProposalRefused extends TandemError {
102
+ readonly problems: string[];
103
+ constructor(problems: string[]);
104
+ }
105
+ export interface ProposalNews {
106
+ /** the proposals the lines are about, to hand to `markTold` once the agent has the note */
107
+ ids: string[];
108
+ lines: string[];
109
+ }
110
+ export declare function publicProposal(stored: StoredProposal): Proposal;
111
+ export declare function newsLine(proposal: Proposal): string;
112
+ export declare class ProposalBook {
113
+ readonly log: EventLog;
114
+ private readonly store;
115
+ private source;
116
+ private readonly handlers;
117
+ private readonly applyActor;
118
+ private readonly recordRefused;
119
+ private readonly tellRefused;
120
+ private readonly idScope;
121
+ private readonly idPrefix;
122
+ private readonly newsWording;
123
+ private readonly newsPrefix;
124
+ private readonly clock;
125
+ constructor(options?: ProposalBookOptions);
126
+ newsNote(lines: string[]): string;
127
+ bind(source: WorkcopySource): void;
128
+ private workcopy;
129
+ private nextId;
130
+ private order;
131
+ private publish;
132
+ private dryRun;
133
+ private deltaOf;
134
+ propose(input: ProposeInput): Proposal;
135
+ private make;
136
+ get(id: string): Proposal;
137
+ private stored;
138
+ private open;
139
+ list(filter?: ProposalFilter): Proposal[];
140
+ edit(id: string, change: ProposalEdit, _actor?: string): Proposal;
141
+ apply(id: string, options?: ApplyOptions): Promise<ApplyResult>;
142
+ discard(id: string, options?: {
143
+ actor?: string;
144
+ }): Proposal;
145
+ peekNews(session: string): ProposalNews;
146
+ markTold(ids: readonly string[]): void;
147
+ takeNews(session: string): string[];
148
+ }
149
+ export declare function applyProposalDelta(state: Json, proposal: Pick<Proposal, 'delta'>): Json;
@@ -0,0 +1,296 @@
1
+ import { apply as applyDelta, diff } from "./delta.js";
2
+ import { TandemError } from "./errors.js";
3
+ import { nowIso } from "./events.js";
4
+ import { EventLog } from "./eventlog.js";
5
+ import { clone, equal } from "./json.js";
6
+ export const PROPOSAL_STATES = ['proposed', 'applied', 'discarded', 'refused'];
7
+ export class MemoryProposalStore {
8
+ items = new Map();
9
+ list() {
10
+ return [...this.items.values()].map((p) => clone(p));
11
+ }
12
+ get(id) {
13
+ const found = this.items.get(id);
14
+ return found ? clone(found) : undefined;
15
+ }
16
+ save(proposal) {
17
+ this.items.set(proposal.id, clone(proposal));
18
+ }
19
+ }
20
+ export class ProposalRefused extends TandemError {
21
+ problems;
22
+ constructor(problems) {
23
+ super(422, 'refused', problems.join('; '));
24
+ this.name = 'ProposalRefused';
25
+ this.problems = problems;
26
+ }
27
+ }
28
+ const KIND = /^[A-Za-z0-9_.:-]{1,64}$/;
29
+ const TRAILING = /p(\d+)$/;
30
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+ const numberOf = (id) => Number(TRAILING.exec(id)?.[1] ?? 0);
32
+ export function publicProposal(stored) {
33
+ const { told: _told, ...proposal } = stored;
34
+ return clone(proposal);
35
+ }
36
+ export function newsLine(proposal) {
37
+ const name = `proposal ${proposal.id}${proposal.title ? ` (${proposal.title})` : ''}`;
38
+ if (proposal.state === 'applied')
39
+ return `the person applied ${name}${proposal.edited ? ' after editing it' : ''}`;
40
+ if (proposal.state === 'discarded')
41
+ return `the person discarded ${name}`;
42
+ return `${name} was refused${proposal.problems.length ? ` (${proposal.problems.join('; ')})` : ''}`;
43
+ }
44
+ function listOf(value) {
45
+ if (value === undefined || value === null)
46
+ return [];
47
+ return typeof value === 'string' ? (value ? [value] : []) : value.filter((p) => p);
48
+ }
49
+ export class ProposalBook {
50
+ log;
51
+ store;
52
+ source;
53
+ handlers;
54
+ applyActor;
55
+ recordRefused;
56
+ tellRefused;
57
+ idScope;
58
+ idPrefix;
59
+ newsWording;
60
+ newsPrefix;
61
+ clock;
62
+ constructor(options = {}) {
63
+ this.clock = options.clock ?? nowIso;
64
+ this.store = options.store ?? new MemoryProposalStore();
65
+ this.log = options.log ?? new EventLog(undefined, this.clock);
66
+ this.source = options.workcopies;
67
+ this.handlers = options.handlers ?? {};
68
+ this.applyActor = options.applyActor ?? 'agent';
69
+ this.recordRefused = options.recordRefused ?? false;
70
+ this.tellRefused = options.tellRefused ?? true;
71
+ this.idScope = options.idScope ?? 'book';
72
+ this.idPrefix = options.idPrefix ?? '';
73
+ this.newsWording = options.news ?? newsLine;
74
+ this.newsPrefix = options.newsPrefix ?? 'since your last message';
75
+ }
76
+ // the lines from `takeNews` as the one sentence that goes into the note to the agent
77
+ newsNote(lines) {
78
+ return `${this.newsPrefix}: ${lines.join('; ')}.`;
79
+ }
80
+ // an engine gives the book its documents when the app did not
81
+ bind(source) {
82
+ this.source ??= source;
83
+ }
84
+ workcopy(name) {
85
+ const source = this.source;
86
+ const found = source ? (typeof source.get === 'function' ? source.get(name) : Object.hasOwn(source, name) ? source[name] : undefined) : undefined;
87
+ if (!found)
88
+ throw new TandemError(404, 'not_found', `no such document: ${name}`);
89
+ return found;
90
+ }
91
+ nextId(session) {
92
+ const namespace = `${this.idPrefix}${this.idScope === 'session' && session ? `${session}.` : ''}`;
93
+ const own = new RegExp(`^${escapeRegExp(namespace)}p(\\d+)$`);
94
+ let top = 0;
95
+ for (const p of this.store.list()) {
96
+ const n = own.exec(p.id);
97
+ if (n)
98
+ top = Math.max(top, Number(n[1]));
99
+ }
100
+ return `${namespace}p${top + 1}`;
101
+ }
102
+ // creation order. one count for the book orders by number; scoped ids repeat their numbers, so they order by time, and a store that lists in the order it was saved settles two made in the same instant (the sort is stable)
103
+ order(a, b) {
104
+ if (this.idScope === 'book' && !this.idPrefix)
105
+ return numberOf(a.id) - numberOf(b.id);
106
+ return a.at < b.at ? -1 : a.at > b.at ? 1 : 0;
107
+ }
108
+ publish(stored) {
109
+ this.log.publish({ type: 'proposal', ...publicProposal(stored) });
110
+ }
111
+ // check a delta the way the write would, on a copy, so a proposal is refused for the same reasons a write is
112
+ dryRun(doc, delta) {
113
+ const copy = this.workcopy(doc).fork();
114
+ const outcome = copy.write({ version: copy.version, delta, actor: this.applyActor });
115
+ return outcome.status === 'rejected' ? outcome.findings.filter((f) => f.level === 'block').map((f) => f.message) : [];
116
+ }
117
+ deltaOf(input) {
118
+ if (!input.doc)
119
+ return null;
120
+ const wc = this.workcopy(input.doc);
121
+ if (input.delta)
122
+ return clone(input.delta);
123
+ if (input.state !== undefined)
124
+ return diff(wc.state, input.state);
125
+ throw new TandemError(400, 'bad_request', 'a proposal for a document needs a delta or a state');
126
+ }
127
+ propose(input) {
128
+ if (typeof input.kind !== 'string' || !KIND.test(input.kind))
129
+ throw new TandemError(400, 'bad_request', 'kind must be 1 to 64 letters, digits, _ . : or -');
130
+ if (input.session !== undefined && input.session !== null && typeof input.session !== 'string')
131
+ throw new TandemError(400, 'bad_request', 'session must be a string');
132
+ for (const field of ['title', 'reason']) {
133
+ const value = input[field];
134
+ if (value !== undefined && value !== null && typeof value !== 'string')
135
+ throw new TandemError(400, 'bad_request', `${field} must be a string`);
136
+ }
137
+ if (input.doc !== undefined && input.doc !== null && typeof input.doc !== 'string')
138
+ throw new TandemError(400, 'bad_request', 'doc must be a string');
139
+ if (!input.doc && input.data === undefined && !input.title)
140
+ throw new TandemError(400, 'bad_request', 'a proposal needs a document change, data or a title');
141
+ const delta = this.deltaOf(input);
142
+ const doc = input.doc || null;
143
+ const wc = doc ? this.workcopy(doc) : undefined;
144
+ const problems = [...(doc && delta ? this.dryRun(doc, delta) : []), ...listOf(this.handlers[input.kind]?.validate?.({ ...input, delta }))];
145
+ if (problems.length) {
146
+ if (this.recordRefused) {
147
+ const refused = this.make(input, delta, wc, 'refused', problems, input.seen === true || !this.tellRefused);
148
+ this.store.save(refused);
149
+ this.publish(refused);
150
+ }
151
+ throw new ProposalRefused(problems);
152
+ }
153
+ const stored = this.make(input, delta, wc, 'proposed', [], false);
154
+ this.store.save(stored);
155
+ this.publish(stored);
156
+ return publicProposal(stored);
157
+ }
158
+ make(input, delta, wc, state, problems, told) {
159
+ return {
160
+ id: this.nextId(input.session ?? null),
161
+ session: input.session ?? null,
162
+ kind: input.kind,
163
+ title: input.title ?? null,
164
+ reason: input.reason ?? null,
165
+ doc: wc ? wc.name : null,
166
+ version: wc ? (input.version ?? wc.version) : null,
167
+ delta,
168
+ data: input.data === undefined ? null : clone(input.data),
169
+ state,
170
+ problems,
171
+ edited: false,
172
+ by: null,
173
+ at: this.clock(),
174
+ resolved_at: null,
175
+ revision: null,
176
+ result: null,
177
+ told,
178
+ };
179
+ }
180
+ get(id) {
181
+ return publicProposal(this.stored(id));
182
+ }
183
+ stored(id) {
184
+ const found = this.store.get(id);
185
+ if (!found)
186
+ throw new TandemError(404, 'not_found', `no such proposal: ${id}`);
187
+ return found;
188
+ }
189
+ open(id) {
190
+ const found = this.stored(id);
191
+ if (found.state !== 'proposed')
192
+ throw new TandemError(409, 'gone', `proposal ${id} is already ${found.state}`);
193
+ return found;
194
+ }
195
+ list(filter = {}) {
196
+ return this.store
197
+ .list()
198
+ .filter((p) => (filter.session === undefined || p.session === filter.session) && (filter.doc === undefined || p.doc === filter.doc) && (filter.state === undefined || p.state === filter.state) && (filter.kind === undefined || p.kind === filter.kind))
199
+ .sort((a, b) => this.order(a, b))
200
+ .map(publicProposal);
201
+ }
202
+ edit(id, change, _actor = 'human') {
203
+ const stored = this.open(id);
204
+ const next = clone(stored);
205
+ if (change.title !== undefined)
206
+ next.title = change.title;
207
+ if (change.reason !== undefined)
208
+ next.reason = change.reason;
209
+ if (change.data !== undefined)
210
+ next.data = clone(change.data);
211
+ if (change.delta !== undefined) {
212
+ if (!stored.doc)
213
+ throw new TandemError(400, 'bad_request', 'this proposal has no document to change');
214
+ next.delta = change.delta === null ? null : clone(change.delta);
215
+ if (next.delta) {
216
+ const problems = this.dryRun(stored.doc, next.delta);
217
+ if (problems.length)
218
+ throw new ProposalRefused(problems);
219
+ }
220
+ }
221
+ if (equal(next, stored))
222
+ return publicProposal(stored);
223
+ next.edited = true;
224
+ this.store.save(next);
225
+ this.publish(next);
226
+ return publicProposal(next);
227
+ }
228
+ async apply(id, options = {}) {
229
+ const actor = options.actor ?? 'human';
230
+ let stored = this.open(id);
231
+ if (options.edit) {
232
+ this.edit(id, options.edit, actor);
233
+ stored = this.open(id);
234
+ }
235
+ let write;
236
+ if (stored.doc && stored.delta) {
237
+ write = this.workcopy(stored.doc).write({ version: stored.version ?? this.workcopy(stored.doc).version, delta: stored.delta, actor: this.applyActor, reason: stored.title ?? stored.reason ?? `apply proposal ${stored.id}`, commit: true });
238
+ if (write.status === 'rejected')
239
+ throw new TandemError(422, 'rejected', write.findings.filter((f) => f.level === 'block').map((f) => f.message).join('; '));
240
+ if (write.status === 'stale')
241
+ throw new TandemError(409, 'stale', `the document moved on since proposal ${stored.id} was made`);
242
+ }
243
+ const done = { ...stored, state: 'applied', by: actor, resolved_at: this.clock(), revision: write?.revision ?? null };
244
+ const handler = this.handlers[stored.kind]?.apply;
245
+ let failure;
246
+ if (handler) {
247
+ try {
248
+ const result = await handler(publicProposal(done), { actor, edited: stored.edited });
249
+ done.result = result === undefined ? null : clone(result);
250
+ }
251
+ catch (error) {
252
+ if (!write)
253
+ throw error;
254
+ failure = error;
255
+ done.result = { error: error instanceof Error ? error.message : String(error) };
256
+ }
257
+ }
258
+ this.store.save(done);
259
+ this.publish(done);
260
+ if (failure)
261
+ throw failure;
262
+ return { proposal: publicProposal(done), ...(write ? { write } : {}), ...(done.result !== null ? { result: done.result } : {}) };
263
+ }
264
+ discard(id, options = {}) {
265
+ const stored = this.open(id);
266
+ const done = { ...stored, state: 'discarded', by: options.actor ?? 'human', resolved_at: this.clock() };
267
+ this.store.save(done);
268
+ this.publish(done);
269
+ return publicProposal(done);
270
+ }
271
+ // what happened to a session's proposals since its agent was last told, worded for the agent, without marking any of it told. Hand `ids` to `markTold` once the note has really reached the agent, so a turn that never starts keeps its news for the next one
272
+ peekNews(session) {
273
+ if (this.newsWording === false)
274
+ return { ids: [], lines: [] };
275
+ const wording = this.newsWording;
276
+ const fresh = this.store.list().filter((p) => p.session === session && p.state !== 'proposed' && !p.told);
277
+ fresh.sort((a, b) => this.order(a, b));
278
+ return { ids: fresh.map((p) => p.id), lines: fresh.map((p) => wording(publicProposal(p))) };
279
+ }
280
+ markTold(ids) {
281
+ for (const id of ids) {
282
+ const found = this.store.get(id);
283
+ if (found && !found.told)
284
+ this.store.save({ ...found, told: true });
285
+ }
286
+ }
287
+ // `peekNews` and `markTold` in one step, for a host that has nothing between the two
288
+ takeNews(session) {
289
+ const news = this.peekNews(session);
290
+ this.markTold(news.ids);
291
+ return news.lines;
292
+ }
293
+ }
294
+ export function applyProposalDelta(state, proposal) {
295
+ return proposal.delta ? applyDelta(state, proposal.delta) : state;
296
+ }
@@ -0,0 +1,63 @@
1
+ import type { Path } from './delta.js';
2
+ import type { Json } from './json.js';
3
+ import { type Clash, type MergeOptions, type MergeResult } from './merge.js';
4
+ import type { Finding } from './revisions.js';
5
+ import type { ClashRecord } from './workcopy.js';
6
+ export type SyncSide = 'client' | 'server';
7
+ export type SyncStep = 'synced' | 'push' | 'pull' | 'merge' | 'compare' | 'rejected';
8
+ export type FirstSync = 'compare' | 'client' | 'server';
9
+ export interface SyncRequest {
10
+ base?: Json;
11
+ state?: Json;
12
+ actors?: string[];
13
+ pristine?: boolean;
14
+ mark?: number;
15
+ site?: string;
16
+ tie?: SyncSide;
17
+ first?: FirstSync;
18
+ clashes?: ClashRecord[];
19
+ closed?: string[];
20
+ }
21
+ export interface SyncResponse {
22
+ step: SyncStep;
23
+ version: number;
24
+ mark: number;
25
+ actors: string[];
26
+ state: Json;
27
+ clashes: ClashRecord[];
28
+ closed: string[];
29
+ changed: boolean;
30
+ findings: Finding[];
31
+ }
32
+ export interface ReconcileSide {
33
+ state: Json;
34
+ actors: string[];
35
+ pristine?: boolean;
36
+ }
37
+ export interface ReconcileInput {
38
+ base?: Json;
39
+ client: Omit<ReconcileSide, 'state'> & {
40
+ state?: Json;
41
+ };
42
+ server: ReconcileSide;
43
+ tie?: SyncSide;
44
+ first?: FirstSync;
45
+ wins?: (actor: string) => boolean;
46
+ print?: (state: Json) => string;
47
+ keyed?: MergeOptions['keyed'];
48
+ merge?: (base: Json, mine: Json, theirs: Json, ctx: {
49
+ writerWins: boolean;
50
+ }) => MergeResult;
51
+ }
52
+ export interface ReconcileResult {
53
+ step: Exclude<SyncStep, 'rejected'>;
54
+ state: Json;
55
+ winner?: SyncSide;
56
+ clashes: Clash[];
57
+ }
58
+ export declare const defaultPrint: (state: Json) => string;
59
+ export declare function reconcileStates(input: ReconcileInput): ReconcileResult;
60
+ export declare function contentClashId(path: Path, kept: Json | null | undefined, dropped: Json | null | undefined): string;
61
+ export declare function clashIdOf(clash: Clash): string;
62
+ export declare function syncClashRecord(clash: Clash, keptActor: string, droppedActor: string): ClashRecord;
63
+ export declare function primaryActor(actors: string[], wins: (actor: string) => boolean, fallback: string): string;