@peer-agent/runtime-core 0.1.0-rc.5 → 0.1.0-rc.51
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/dist/context-accounting-lifecycle.d.ts +1 -1
- package/dist/context-accounting-lifecycle.js +1 -1
- package/dist/context-accounting-pipeline.d.ts +14 -2
- package/dist/context-accounting-pipeline.js +43 -24
- package/dist/context-compaction.d.ts +1 -0
- package/dist/context-compaction.js +1 -1
- package/dist/contracts.d.ts +3 -0
- package/dist/conversation-history-projector.d.ts +12 -1
- package/dist/conversation-history-projector.js +111 -17
- package/dist/evidence.js +8 -3
- package/dist/goal-idempotency.d.ts +2 -0
- package/dist/goal-idempotency.js +5 -0
- package/dist/goal-tool-contracts.d.ts +225 -0
- package/dist/goal-tool-contracts.js +297 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/input-prediction.d.ts +40 -0
- package/dist/input-prediction.js +146 -0
- package/dist/microcompact.d.ts +15 -1
- package/dist/microcompact.js +108 -2
- package/dist/project-input-recovery.d.ts +49 -0
- package/dist/project-input-recovery.js +530 -0
- package/dist/resource-edit-state.d.ts +101 -0
- package/dist/resource-edit-state.js +179 -0
- package/package.json +2 -2
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
import { encodeResourceFeedbackTransport, normalizeResourceFeedbackList, emptyInputDraft, isDefiniteProjectInputRejection, projectInputWasReceived } from '@peer-agent/protocol';
|
|
2
|
+
const EMPTY_REJECTED = Object.freeze({});
|
|
3
|
+
const EMPTY_IDS = Object.freeze([]);
|
|
4
|
+
const RESOURCE_REJECTION_CODES = new Set([
|
|
5
|
+
'INVALID_RESOURCE_FEEDBACK',
|
|
6
|
+
'RESOURCE_FEEDBACK_RECIPIENT_CHANGED',
|
|
7
|
+
'RESOURCE_FEEDBACK_ATTACHMENT_LIMIT',
|
|
8
|
+
'INTERACTIVE_FEEDBACK_UNAVAILABLE',
|
|
9
|
+
]);
|
|
10
|
+
const DRAFT_UPLOAD_CHUNK_BYTES = 16 * 1024 * 1024;
|
|
11
|
+
function estimateUploadBytes(item) {
|
|
12
|
+
const body = item.kind === 'image' ? item.dataUrl.length : item.kind === 'text' ? item.text.length : 0;
|
|
13
|
+
return body + 512;
|
|
14
|
+
}
|
|
15
|
+
function partitionUploadChunks(uploads) {
|
|
16
|
+
if (uploads.length <= 1)
|
|
17
|
+
return [uploads];
|
|
18
|
+
const chunks = [];
|
|
19
|
+
let current = [];
|
|
20
|
+
let currentBytes = 0;
|
|
21
|
+
for (const item of uploads) {
|
|
22
|
+
const bytes = estimateUploadBytes(item);
|
|
23
|
+
if (current.length > 0 && currentBytes + bytes > DRAFT_UPLOAD_CHUNK_BYTES) {
|
|
24
|
+
chunks.push(current);
|
|
25
|
+
current = [item];
|
|
26
|
+
currentBytes = bytes;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
current.push(item);
|
|
30
|
+
currentBytes += bytes;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (current.length > 0)
|
|
34
|
+
chunks.push(current);
|
|
35
|
+
return chunks;
|
|
36
|
+
}
|
|
37
|
+
/** Presentation continuity only; ports own storage and the existing governed input queue. */
|
|
38
|
+
export function createProjectInputRecovery({ workspaceId, surface, port, createId, now = () => new Date().toISOString(), receiptTimeoutMs = 30_000, debounceMs = 300, maxWaitMs = 1_000 }) {
|
|
39
|
+
const address = { workspaceId, surface };
|
|
40
|
+
let view = { revision: 0, draft: emptyInputDraft(), pending: [], ready: false, error: null, sending: EMPTY_IDS, received: [], rejected: EMPTY_REJECTED, mutating: EMPTY_IDS };
|
|
41
|
+
let changed = 0, saved = 0;
|
|
42
|
+
let earlyEdits = null;
|
|
43
|
+
let writing = null, loading = null;
|
|
44
|
+
let saveTimer;
|
|
45
|
+
let saveDeadline;
|
|
46
|
+
// A deadline or explicit flush can become due while the CAS writer is busy.
|
|
47
|
+
let writeRequested = false;
|
|
48
|
+
const listeners = new Set(), storedAttachments = new Map(), active = new Map();
|
|
49
|
+
const draftOrigins = new Map();
|
|
50
|
+
const optionOrigins = new Set();
|
|
51
|
+
const mutatingIds = new Set();
|
|
52
|
+
const publish = (patch) => { view = { ...view, ...patch }; for (const fn of listeners)
|
|
53
|
+
fn(); };
|
|
54
|
+
const isDraftEmpty = (draft) => !draft.text && !draft.quote && !draft.attachments.length
|
|
55
|
+
&& !draft.taskRefs?.length && !draft.resourceFeedback?.length;
|
|
56
|
+
const hasComposedContent = (input) => Boolean(input.attachments.length || input.quoteRefs.length || input.taskRefs?.length || input.resourceFeedback?.length);
|
|
57
|
+
const omitRejected = (ids) => {
|
|
58
|
+
if (!ids.some(id => Object.prototype.hasOwnProperty.call(view.rejected, id)))
|
|
59
|
+
return view.rejected;
|
|
60
|
+
const next = {};
|
|
61
|
+
for (const [key, value] of Object.entries(view.rejected)) {
|
|
62
|
+
if (!ids.includes(key))
|
|
63
|
+
next[key] = value;
|
|
64
|
+
}
|
|
65
|
+
return Object.keys(next).length ? next : EMPTY_REJECTED;
|
|
66
|
+
};
|
|
67
|
+
const markRejected = (inputId, code) => {
|
|
68
|
+
if (view.rejected[inputId] === code)
|
|
69
|
+
return;
|
|
70
|
+
publish({ rejected: { ...view.rejected, [inputId]: code } });
|
|
71
|
+
};
|
|
72
|
+
const clearRejected = (ids) => {
|
|
73
|
+
const rejected = omitRejected(ids);
|
|
74
|
+
if (rejected !== view.rejected)
|
|
75
|
+
publish({ rejected });
|
|
76
|
+
};
|
|
77
|
+
const quoteForRestore = (input) => {
|
|
78
|
+
const savedQuote = draftOrigins.get(input.inputId);
|
|
79
|
+
if (savedQuote !== undefined)
|
|
80
|
+
return savedQuote;
|
|
81
|
+
if (input.quoteRefs.length >= 2 && input.quoteRefs[0] && input.quoteRefs[1]) {
|
|
82
|
+
return { messageId: input.quoteRefs[0], text: input.quoteRefs[1] };
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
};
|
|
86
|
+
const buildRestoredDraft = (input, rejectionCode) => {
|
|
87
|
+
const keepResourceFeedback = Boolean(input.resourceFeedback?.length && (!rejectionCode || !RESOURCE_REJECTION_CODES.has(rejectionCode)));
|
|
88
|
+
return {
|
|
89
|
+
text: input.text,
|
|
90
|
+
quote: quoteForRestore(input),
|
|
91
|
+
attachments: input.attachments,
|
|
92
|
+
...(input.taskRefs?.length ? { taskRefs: input.taskRefs } : {}),
|
|
93
|
+
...(keepResourceFeedback ? { resourceFeedback: input.resourceFeedback } : {}),
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
async function writeState(draftValue, pendingList) {
|
|
97
|
+
const all = [...draftValue.attachments, ...pendingList.flatMap(item => item.attachments)];
|
|
98
|
+
const uploads = [...new Map(all.filter(item => storedAttachments.get(item.id) !== item).map(item => [item.id, item])).values()];
|
|
99
|
+
const { attachments, ...draft } = draftValue;
|
|
100
|
+
const chunks = partitionUploadChunks(uploads);
|
|
101
|
+
let revision = view.revision;
|
|
102
|
+
const available = new Set(storedAttachments.keys());
|
|
103
|
+
try {
|
|
104
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
105
|
+
const chunk = chunks[i];
|
|
106
|
+
for (const item of chunk)
|
|
107
|
+
available.add(item.id);
|
|
108
|
+
const isFinal = i === chunks.length - 1;
|
|
109
|
+
const result = await port.write({
|
|
110
|
+
...address,
|
|
111
|
+
revision,
|
|
112
|
+
draft: {
|
|
113
|
+
...draft,
|
|
114
|
+
attachmentIds: isFinal
|
|
115
|
+
? attachments.map(item => item.id)
|
|
116
|
+
: attachments.filter(item => available.has(item.id)).map(item => item.id),
|
|
117
|
+
},
|
|
118
|
+
pending: pendingList.map(({ attachments: pendingAttachments, ...input }) => ({
|
|
119
|
+
...input,
|
|
120
|
+
attachmentIds: isFinal
|
|
121
|
+
? pendingAttachments.map(item => item.id)
|
|
122
|
+
: pendingAttachments.filter(item => available.has(item.id)).map(item => item.id),
|
|
123
|
+
})),
|
|
124
|
+
uploads: chunk,
|
|
125
|
+
});
|
|
126
|
+
if (!result.ok) {
|
|
127
|
+
publish({ error: result.code });
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
revision = result.revision;
|
|
131
|
+
for (const item of chunk)
|
|
132
|
+
storedAttachments.set(item.id, item);
|
|
133
|
+
if (!isFinal)
|
|
134
|
+
publish({ revision, error: null });
|
|
135
|
+
}
|
|
136
|
+
storedAttachments.clear();
|
|
137
|
+
for (const item of all)
|
|
138
|
+
storedAttachments.set(item.id, item);
|
|
139
|
+
return revision;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
publish({ error: 'DRAFT_SAVE_FAILED' });
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function load() {
|
|
147
|
+
if (loading)
|
|
148
|
+
return loading;
|
|
149
|
+
loading = (async () => {
|
|
150
|
+
try {
|
|
151
|
+
const result = await port.read(address);
|
|
152
|
+
if (!result.ok) {
|
|
153
|
+
publish({ error: result.code });
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
for (const item of [...result.snapshot.draft.attachments, ...result.snapshot.pending.flatMap(item => item.attachments)])
|
|
157
|
+
storedAttachments.set(item.id, item);
|
|
158
|
+
publish({ ...result.snapshot, draft: earlyEdits ? { ...result.snapshot.draft, ...earlyEdits } : result.snapshot.draft, ready: true, error: null });
|
|
159
|
+
if (earlyEdits) {
|
|
160
|
+
earlyEdits = null;
|
|
161
|
+
changed++;
|
|
162
|
+
void flush();
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
publish({ error: 'DRAFT_UNAVAILABLE' });
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
loading = null;
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
return loading;
|
|
175
|
+
}
|
|
176
|
+
function clearScheduledSave() {
|
|
177
|
+
clearTimeout(saveTimer);
|
|
178
|
+
saveTimer = undefined;
|
|
179
|
+
saveDeadline = undefined;
|
|
180
|
+
}
|
|
181
|
+
function scheduleSave() {
|
|
182
|
+
if (debounceMs <= 0 || maxWaitMs <= 0) {
|
|
183
|
+
void flush();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (writeRequested || saved === changed)
|
|
187
|
+
return;
|
|
188
|
+
const time = Date.now();
|
|
189
|
+
saveDeadline ??= time + maxWaitMs;
|
|
190
|
+
clearTimeout(saveTimer);
|
|
191
|
+
saveTimer = setTimeout(() => { void flush(); }, Math.min(debounceMs, Math.max(0, saveDeadline - time)));
|
|
192
|
+
}
|
|
193
|
+
async function flush() {
|
|
194
|
+
clearScheduledSave();
|
|
195
|
+
if (!view.ready && (!earlyEdits || !await load()))
|
|
196
|
+
return false;
|
|
197
|
+
writeRequested = true;
|
|
198
|
+
while (writing) {
|
|
199
|
+
const ok = await writing;
|
|
200
|
+
if (!ok)
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
if (!writeRequested || saved === changed) {
|
|
204
|
+
writeRequested = false;
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
writing = (async () => {
|
|
208
|
+
while (writeRequested && saved !== changed) {
|
|
209
|
+
writeRequested = false;
|
|
210
|
+
clearScheduledSave();
|
|
211
|
+
const version = changed, state = view;
|
|
212
|
+
const revision = await writeState(state.draft, state.pending);
|
|
213
|
+
if (revision === null) {
|
|
214
|
+
writeRequested = false;
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
saved = version;
|
|
218
|
+
publish({ revision, error: null });
|
|
219
|
+
}
|
|
220
|
+
writeRequested = false;
|
|
221
|
+
return true;
|
|
222
|
+
})().finally(() => { writing = null; });
|
|
223
|
+
return writing;
|
|
224
|
+
}
|
|
225
|
+
function edit(patch) {
|
|
226
|
+
if (patch.resourceFeedback !== undefined) {
|
|
227
|
+
const rows = normalizeResourceFeedbackList(patch.resourceFeedback);
|
|
228
|
+
if (!rows || rows.some(row => row.recipient.workspaceId !== workspaceId)) {
|
|
229
|
+
publish({ error: 'INVALID_RESOURCE_FEEDBACK' });
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
patch = { ...patch, resourceFeedback: rows };
|
|
233
|
+
}
|
|
234
|
+
const keys = Object.keys(patch);
|
|
235
|
+
// Before hydration, even an empty value can deliberately override the stored field.
|
|
236
|
+
if (!keys.length || (view.ready && keys.every(key => Object.is(view.draft[key], patch[key]))))
|
|
237
|
+
return;
|
|
238
|
+
if (!view.ready)
|
|
239
|
+
earlyEdits = { ...earlyEdits, ...patch };
|
|
240
|
+
changed++;
|
|
241
|
+
publish({ draft: { ...view.draft, ...patch } });
|
|
242
|
+
if (view.ready) {
|
|
243
|
+
if (keys.length === 1 && keys[0] === 'text')
|
|
244
|
+
scheduleSave();
|
|
245
|
+
else
|
|
246
|
+
void flush();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function acknowledge(ids) {
|
|
250
|
+
for (const id of ids) {
|
|
251
|
+
draftOrigins.delete(id);
|
|
252
|
+
optionOrigins.delete(id);
|
|
253
|
+
}
|
|
254
|
+
const rejected = omitRejected(ids);
|
|
255
|
+
const pending = view.pending.filter(item => !ids.includes(item.inputId));
|
|
256
|
+
if (pending.length === view.pending.length) {
|
|
257
|
+
if (rejected !== view.rejected)
|
|
258
|
+
publish({ rejected });
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const received = [...view.received, ...view.pending.filter(item => ids.includes(item.inputId))];
|
|
262
|
+
changed++;
|
|
263
|
+
publish({ pending, received, ...(rejected !== view.rejected ? { rejected } : {}) });
|
|
264
|
+
void flush();
|
|
265
|
+
}
|
|
266
|
+
function dismiss(ids) {
|
|
267
|
+
for (const id of ids) {
|
|
268
|
+
draftOrigins.delete(id);
|
|
269
|
+
optionOrigins.delete(id);
|
|
270
|
+
}
|
|
271
|
+
const rejected = omitRejected(ids);
|
|
272
|
+
const pending = view.pending.filter(item => !ids.includes(item.inputId));
|
|
273
|
+
if (pending.length === view.pending.length) {
|
|
274
|
+
if (rejected !== view.rejected)
|
|
275
|
+
publish({ rejected });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
changed++;
|
|
279
|
+
publish({ pending, ...(rejected !== view.rejected ? { rejected } : {}) });
|
|
280
|
+
void flush();
|
|
281
|
+
}
|
|
282
|
+
function recoverClosedDraft(input, originalQuote) {
|
|
283
|
+
if (!view.pending.some(item => item.inputId === input.inputId))
|
|
284
|
+
return;
|
|
285
|
+
const rejected = omitRejected([input.inputId]);
|
|
286
|
+
if (isDraftEmpty(view.draft)) {
|
|
287
|
+
const pending = view.pending.filter(item => item.inputId !== input.inputId);
|
|
288
|
+
const restored = {
|
|
289
|
+
text: input.text,
|
|
290
|
+
quote: originalQuote,
|
|
291
|
+
attachments: input.attachments,
|
|
292
|
+
...(input.taskRefs?.length ? { taskRefs: input.taskRefs } : {}),
|
|
293
|
+
...(input.resourceFeedback?.length ? { resourceFeedback: input.resourceFeedback } : {}),
|
|
294
|
+
};
|
|
295
|
+
changed++;
|
|
296
|
+
publish({ pending, draft: restored, ...(rejected !== view.rejected ? { rejected } : {}) });
|
|
297
|
+
void flush();
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const pending = view.pending.map(item => {
|
|
301
|
+
if (item.inputId !== input.inputId || !item.answerTo)
|
|
302
|
+
return item;
|
|
303
|
+
const { answerTo: _closed, ...plain } = item;
|
|
304
|
+
return plain;
|
|
305
|
+
});
|
|
306
|
+
changed++;
|
|
307
|
+
publish({ pending, ...(rejected !== view.rejected ? { rejected } : {}) });
|
|
308
|
+
void flush();
|
|
309
|
+
}
|
|
310
|
+
async function persistPendingMutation(inputId, mode, options) {
|
|
311
|
+
if (!view.ready && !await load())
|
|
312
|
+
return { ok: false, code: view.error || 'DRAFT_UNAVAILABLE' };
|
|
313
|
+
if (active.has(inputId))
|
|
314
|
+
return { ok: false, code: 'INPUT_SENDING' };
|
|
315
|
+
if (mutatingIds.has(inputId))
|
|
316
|
+
return { ok: false, code: 'INPUT_BUSY' };
|
|
317
|
+
if (!view.pending.some(item => item.inputId === inputId))
|
|
318
|
+
return { ok: false, code: 'INPUT_NOT_PENDING' };
|
|
319
|
+
mutatingIds.add(inputId);
|
|
320
|
+
publish({ mutating: [...mutatingIds] });
|
|
321
|
+
try {
|
|
322
|
+
while (writing || saved !== changed) {
|
|
323
|
+
const ok = await flush();
|
|
324
|
+
if (!ok)
|
|
325
|
+
return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
|
|
326
|
+
}
|
|
327
|
+
if (active.has(inputId))
|
|
328
|
+
return { ok: false, code: 'INPUT_SENDING' };
|
|
329
|
+
const target = view.pending.find(item => item.inputId === inputId);
|
|
330
|
+
if (!target)
|
|
331
|
+
return { ok: false, code: 'INPUT_NOT_PENDING' };
|
|
332
|
+
if (mode === 'restore' && !options?.replaceDraft && !isDraftEmpty(view.draft)) {
|
|
333
|
+
return { ok: false, code: 'DRAFT_NOT_EMPTY' };
|
|
334
|
+
}
|
|
335
|
+
const baseVersion = changed;
|
|
336
|
+
const nextPendingForDisk = view.pending.filter(item => item.inputId !== inputId);
|
|
337
|
+
const nextDraftForDisk = mode === 'restore' ? buildRestoredDraft(target, view.rejected[inputId]) : view.draft;
|
|
338
|
+
let writtenRevision = null;
|
|
339
|
+
writing = (async () => {
|
|
340
|
+
writtenRevision = await writeState(nextDraftForDisk, nextPendingForDisk);
|
|
341
|
+
return writtenRevision !== null;
|
|
342
|
+
})().finally(() => { writing = null; });
|
|
343
|
+
const ok = await writing;
|
|
344
|
+
if (!ok || writtenRevision === null)
|
|
345
|
+
return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
|
|
346
|
+
if (mode === 'restore' && changed !== baseVersion) {
|
|
347
|
+
publish({ revision: writtenRevision, error: null });
|
|
348
|
+
void flush();
|
|
349
|
+
return { ok: false, code: 'DRAFT_NOT_EMPTY' };
|
|
350
|
+
}
|
|
351
|
+
draftOrigins.delete(inputId);
|
|
352
|
+
optionOrigins.delete(inputId);
|
|
353
|
+
const rejected = omitRejected([inputId]);
|
|
354
|
+
const nextPending = view.pending.filter(item => item.inputId !== inputId);
|
|
355
|
+
if (changed === baseVersion)
|
|
356
|
+
saved = baseVersion;
|
|
357
|
+
publish({
|
|
358
|
+
revision: writtenRevision,
|
|
359
|
+
error: null,
|
|
360
|
+
pending: nextPending,
|
|
361
|
+
...(mode === 'restore' ? { draft: nextDraftForDisk } : {}),
|
|
362
|
+
...(rejected !== view.rejected ? { rejected } : {}),
|
|
363
|
+
});
|
|
364
|
+
if (saved !== changed)
|
|
365
|
+
void flush();
|
|
366
|
+
return { ok: true };
|
|
367
|
+
}
|
|
368
|
+
finally {
|
|
369
|
+
mutatingIds.delete(inputId);
|
|
370
|
+
publish({ mutating: mutatingIds.size ? [...mutatingIds] : EMPTY_IDS });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function dispatch(input) {
|
|
374
|
+
if (mutatingIds.has(input.inputId))
|
|
375
|
+
return Promise.resolve({ ok: false, code: 'INPUT_BUSY' });
|
|
376
|
+
const running = active.get(input.inputId);
|
|
377
|
+
if (running)
|
|
378
|
+
return running;
|
|
379
|
+
const job = (async () => {
|
|
380
|
+
publish({ sending: [...view.sending, input.inputId] });
|
|
381
|
+
try {
|
|
382
|
+
if (!await flush())
|
|
383
|
+
return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
|
|
384
|
+
// This deadline ends the presentation wait, never the host operation. A late
|
|
385
|
+
// factual receipt still reconciles the original envelope without resending.
|
|
386
|
+
const submitted = port.submit({ ...address, ...input }).then(result => {
|
|
387
|
+
if (projectInputWasReceived(result, workspaceId, input.inputId)) {
|
|
388
|
+
acknowledge([input.inputId]);
|
|
389
|
+
return result;
|
|
390
|
+
}
|
|
391
|
+
if (isDefiniteProjectInputRejection(result, workspaceId, input.inputId)) {
|
|
392
|
+
const code = result.code;
|
|
393
|
+
if (!view.pending.some(item => item.inputId === input.inputId))
|
|
394
|
+
return { ok: false, code };
|
|
395
|
+
if (code === 'QUESTION_CLOSED') {
|
|
396
|
+
if (optionOrigins.has(input.inputId) && !hasComposedContent(input)) {
|
|
397
|
+
dismiss([input.inputId]);
|
|
398
|
+
}
|
|
399
|
+
else if (draftOrigins.has(input.inputId)) {
|
|
400
|
+
const originalQuote = draftOrigins.get(input.inputId) ?? null;
|
|
401
|
+
draftOrigins.delete(input.inputId);
|
|
402
|
+
recoverClosedDraft(input, originalQuote);
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
markRejected(input.inputId, code);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
markRejected(input.inputId, code);
|
|
410
|
+
}
|
|
411
|
+
return { ok: false, code };
|
|
412
|
+
}
|
|
413
|
+
clearRejected([input.inputId]);
|
|
414
|
+
return { ok: false, code: result.code || 'INPUT_OUTCOME_UNKNOWN' };
|
|
415
|
+
}).catch(() => {
|
|
416
|
+
clearRejected([input.inputId]);
|
|
417
|
+
return { ok: false, code: 'INPUT_OUTCOME_UNKNOWN' };
|
|
418
|
+
});
|
|
419
|
+
let timer;
|
|
420
|
+
try {
|
|
421
|
+
return await Promise.race([submitted, new Promise(resolve => {
|
|
422
|
+
timer = setTimeout(() => resolve({ ok: false, code: 'INPUT_OUTCOME_UNKNOWN' }), receiptTimeoutMs);
|
|
423
|
+
})]);
|
|
424
|
+
}
|
|
425
|
+
finally {
|
|
426
|
+
clearTimeout(timer);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return { ok: false, code: 'INPUT_OUTCOME_UNKNOWN' };
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
active.delete(input.inputId);
|
|
434
|
+
const sending = view.sending.filter(id => id !== input.inputId);
|
|
435
|
+
publish({ sending: sending.length ? sending : EMPTY_IDS });
|
|
436
|
+
}
|
|
437
|
+
})();
|
|
438
|
+
active.set(input.inputId, job);
|
|
439
|
+
return job;
|
|
440
|
+
}
|
|
441
|
+
async function send(options = {}) {
|
|
442
|
+
if (!view.ready && !await load())
|
|
443
|
+
return { ok: false, code: view.error || 'DRAFT_UNAVAILABLE' };
|
|
444
|
+
const useDraft = options.useDraft !== false, draft = view.draft;
|
|
445
|
+
const text = (options.text ?? draft.text).trim(), attachments = useDraft ? draft.attachments : [];
|
|
446
|
+
const taskRefs = options.taskRefs ?? (useDraft ? (draft.taskRefs ?? []) : []);
|
|
447
|
+
if (useDraft && options.text !== undefined && text !== draft.text.trim())
|
|
448
|
+
return { ok: false, code: 'INPUT_CHANGED' };
|
|
449
|
+
const resourceFeedback = useDraft ? normalizeResourceFeedbackList(draft.resourceFeedback) : [];
|
|
450
|
+
if (!resourceFeedback)
|
|
451
|
+
return { ok: false, code: 'INVALID_RESOURCE_FEEDBACK' };
|
|
452
|
+
if (!text && !attachments.length && !taskRefs.length && !resourceFeedback.some(row => row.resource.kind === 'interactive'))
|
|
453
|
+
return { ok: false, code: 'INVALID_INPUT' };
|
|
454
|
+
if (!useDraft && options.answerTo) {
|
|
455
|
+
if (view.received.some(item => item.answerTo === options.answerTo))
|
|
456
|
+
return { ok: false, code: 'QUESTION_CLOSED' };
|
|
457
|
+
const existing = view.pending.find(item => item.answerTo === options.answerTo);
|
|
458
|
+
if (existing) {
|
|
459
|
+
if (view.rejected[existing.inputId] === 'QUESTION_CLOSED')
|
|
460
|
+
return { ok: false, code: 'QUESTION_CLOSED' };
|
|
461
|
+
if (!view.rejected[existing.inputId])
|
|
462
|
+
return existing.text === text ? dispatch(existing) : { ok: false, code: 'INPUT_PENDING_ANSWER' };
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (view.pending.length >= 32)
|
|
466
|
+
return { ok: false, code: 'DRAFT_LIMIT' };
|
|
467
|
+
if (resourceFeedback.some(item => item.recipient.workspaceId !== workspaceId))
|
|
468
|
+
return { ok: false, code: 'RESOURCE_FEEDBACK_RECIPIENT_CHANGED' };
|
|
469
|
+
try {
|
|
470
|
+
encodeResourceFeedbackTransport(resourceFeedback, attachments);
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
return { ok: false, code: error.code ?? 'INVALID_RESOURCE_FEEDBACK' };
|
|
474
|
+
}
|
|
475
|
+
const input = { inputId: createId(), text, attachments, ...(resourceFeedback.length ? { resourceFeedback } : {}), ...(taskRefs.length ? { taskRefs } : {}), createdAt: now(), quoteRefs: options.quoteRefs ?? [],
|
|
476
|
+
...(options.answerTo ? { answerTo: options.answerTo } : {}) };
|
|
477
|
+
if (useDraft)
|
|
478
|
+
draftOrigins.set(input.inputId, draft.quote);
|
|
479
|
+
else if (options.answerTo)
|
|
480
|
+
optionOrigins.add(input.inputId);
|
|
481
|
+
changed++;
|
|
482
|
+
publish({ pending: [...view.pending, input], ...(useDraft ? { draft: emptyInputDraft() } : {}) });
|
|
483
|
+
return dispatch(input);
|
|
484
|
+
}
|
|
485
|
+
return {
|
|
486
|
+
getSnapshot: () => view,
|
|
487
|
+
subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
|
488
|
+
load, edit, flush, acknowledge, send,
|
|
489
|
+
// The surface detaches here; cached sessions can still reconcile late receipts.
|
|
490
|
+
dispose: flush,
|
|
491
|
+
hasUnsavedChanges: () => saved !== changed || writing !== null,
|
|
492
|
+
discard: (inputId) => persistPendingMutation(inputId, 'discard'),
|
|
493
|
+
restoreToDraft: (inputId, options) => persistPendingMutation(inputId, 'restore', options),
|
|
494
|
+
observeReceived(ids, answered) {
|
|
495
|
+
const isDuplicateCommittedReplyAnswer = (item) => Boolean(answered?.length
|
|
496
|
+
&& !active.has(item.inputId)
|
|
497
|
+
&& item.answerTo?.startsWith('card:question:reply:')
|
|
498
|
+
&& !item.attachments.length
|
|
499
|
+
&& !item.taskRefs?.length
|
|
500
|
+
&& !item.resourceFeedback?.length
|
|
501
|
+
&& !item.quoteRefs.length
|
|
502
|
+
&& answered.some(entry => entry.answerTo === item.answerTo && entry.text.trim() === item.text.trim()));
|
|
503
|
+
const dropped = [];
|
|
504
|
+
const pending = view.pending.filter(item => {
|
|
505
|
+
const drop = ids.includes(item.inputId) || isDuplicateCommittedReplyAnswer(item);
|
|
506
|
+
if (drop) {
|
|
507
|
+
draftOrigins.delete(item.inputId);
|
|
508
|
+
optionOrigins.delete(item.inputId);
|
|
509
|
+
dropped.push(item.inputId);
|
|
510
|
+
}
|
|
511
|
+
return !drop;
|
|
512
|
+
});
|
|
513
|
+
const rejected = dropped.length ? omitRejected(dropped) : view.rejected;
|
|
514
|
+
const received = view.received.filter(item => !ids.includes(item.inputId));
|
|
515
|
+
if (pending.length !== view.pending.length) {
|
|
516
|
+
changed++;
|
|
517
|
+
publish({ pending, received, ...(rejected !== view.rejected ? { rejected } : {}) });
|
|
518
|
+
void flush();
|
|
519
|
+
}
|
|
520
|
+
else if (received.length !== view.received.length)
|
|
521
|
+
publish({ received });
|
|
522
|
+
},
|
|
523
|
+
retry(inputId) {
|
|
524
|
+
if (mutatingIds.has(inputId))
|
|
525
|
+
return Promise.resolve({ ok: false, code: 'INPUT_BUSY' });
|
|
526
|
+
const input = view.pending.find(item => item.inputId === inputId);
|
|
527
|
+
return input ? dispatch(input) : Promise.resolve({ ok: false, code: 'INPUT_NOT_PENDING' });
|
|
528
|
+
},
|
|
529
|
+
};
|
|
530
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type ResourceEditTarget, type ResourceTextDraft, type ResourceEditWriter, type ResourceEditOperation, type ResourceEditReceipt } from '@peer-agent/protocol';
|
|
2
|
+
/** No filesystem, permission, runner, tool or Evidence creation ports. Host facts enter explicitly. */
|
|
3
|
+
export interface ResourceEditState {
|
|
4
|
+
readonly schemaVersion: 1;
|
|
5
|
+
readonly workspaceId: string;
|
|
6
|
+
readonly hostEpoch: string;
|
|
7
|
+
readonly revision: number;
|
|
8
|
+
readonly drafts: readonly ResourceTextDraft[];
|
|
9
|
+
readonly operations: readonly ResourceEditOperation[];
|
|
10
|
+
readonly retiredOperations: readonly ResourceEditOperation[];
|
|
11
|
+
readonly writerSequence: number;
|
|
12
|
+
readonly writers: readonly {
|
|
13
|
+
readonly draftId: string;
|
|
14
|
+
readonly writer: ResourceEditWriter;
|
|
15
|
+
}[];
|
|
16
|
+
}
|
|
17
|
+
export interface ResourceEditPorts {
|
|
18
|
+
readonly hashText: (text: string) => string;
|
|
19
|
+
readonly now: () => string;
|
|
20
|
+
}
|
|
21
|
+
export type ResourceEditEvent = {
|
|
22
|
+
readonly type: 'open';
|
|
23
|
+
readonly id: string;
|
|
24
|
+
readonly target: ResourceEditTarget;
|
|
25
|
+
readonly baseText: string;
|
|
26
|
+
} | {
|
|
27
|
+
readonly type: 'acquire';
|
|
28
|
+
readonly draftId: string;
|
|
29
|
+
readonly writer: Omit<ResourceEditWriter, 'lease'>;
|
|
30
|
+
readonly takeover?: boolean;
|
|
31
|
+
} | {
|
|
32
|
+
readonly type: 'release';
|
|
33
|
+
readonly draftId: string;
|
|
34
|
+
readonly writer: ResourceEditWriter;
|
|
35
|
+
} | {
|
|
36
|
+
readonly type: 'edit';
|
|
37
|
+
readonly draftId: string;
|
|
38
|
+
readonly revision: number;
|
|
39
|
+
readonly writer: ResourceEditWriter;
|
|
40
|
+
readonly text: string;
|
|
41
|
+
} | {
|
|
42
|
+
readonly type: 'discard';
|
|
43
|
+
readonly draftId: string;
|
|
44
|
+
readonly revision: number;
|
|
45
|
+
readonly writer: ResourceEditWriter;
|
|
46
|
+
} | {
|
|
47
|
+
readonly type: 'reserve';
|
|
48
|
+
readonly requestId: string;
|
|
49
|
+
readonly draftId: string;
|
|
50
|
+
readonly revision: number;
|
|
51
|
+
readonly writer: ResourceEditWriter;
|
|
52
|
+
readonly providerId: string;
|
|
53
|
+
readonly proposedVersion: string;
|
|
54
|
+
} | {
|
|
55
|
+
readonly type: 'archive';
|
|
56
|
+
readonly requestId: string;
|
|
57
|
+
} | {
|
|
58
|
+
readonly type: 'start';
|
|
59
|
+
readonly requestId: string;
|
|
60
|
+
readonly payloadHash: string;
|
|
61
|
+
} | {
|
|
62
|
+
readonly type: 'withdraw';
|
|
63
|
+
readonly requestId: string;
|
|
64
|
+
readonly payloadHash: string;
|
|
65
|
+
} | {
|
|
66
|
+
readonly type: 'uncertain';
|
|
67
|
+
readonly requestId: string;
|
|
68
|
+
readonly payloadHash: string;
|
|
69
|
+
} | {
|
|
70
|
+
readonly type: 'settle';
|
|
71
|
+
readonly requestId: string;
|
|
72
|
+
readonly receipt: ResourceEditReceipt;
|
|
73
|
+
};
|
|
74
|
+
export type ResourceEditTransition = {
|
|
75
|
+
readonly ok: false;
|
|
76
|
+
readonly code: string;
|
|
77
|
+
} | {
|
|
78
|
+
readonly ok: true;
|
|
79
|
+
readonly state: ResourceEditState;
|
|
80
|
+
readonly persist: boolean;
|
|
81
|
+
/** execute only marks a fresh journal transition; persist it, then use the governed runtime. It is never a grant. */
|
|
82
|
+
readonly value: {
|
|
83
|
+
readonly draft?: ResourceTextDraft;
|
|
84
|
+
readonly writer?: ResourceEditWriter;
|
|
85
|
+
readonly operation?: ResourceEditOperation;
|
|
86
|
+
readonly execute?: boolean;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
export declare function resourceEditOperationPayload(op: Pick<ResourceEditOperation, 'draftId' | 'draftRevision' | 'target' | 'providerId' | 'proposedVersion'>): string;
|
|
90
|
+
export declare function emptyResourceEditState(workspaceId: string, hostEpoch: string): ResourceEditState;
|
|
91
|
+
/** Hydrated durable intent. Writer handles are deliberately absent from the persisted shape. */
|
|
92
|
+
export declare function resourceEditManifest(state: ResourceEditState): {
|
|
93
|
+
schemaVersion: 1;
|
|
94
|
+
workspaceId: string;
|
|
95
|
+
revision: number;
|
|
96
|
+
drafts: readonly ResourceTextDraft[];
|
|
97
|
+
operations: readonly ResourceEditOperation[];
|
|
98
|
+
retiredOperations: readonly ResourceEditOperation[];
|
|
99
|
+
};
|
|
100
|
+
export declare function recoverResourceEditState(raw: unknown, workspaceId: string, hostEpoch: string, hashText: ResourceEditPorts['hashText']): ResourceEditState | undefined;
|
|
101
|
+
export declare function reduceResourceEdit(state: ResourceEditState, event: ResourceEditEvent, ports: ResourceEditPorts): ResourceEditTransition;
|