@peer-agent/runtime-core 0.1.0-rc.5 → 0.1.0-rc.50

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.
@@ -6,10 +6,17 @@
6
6
  // 保留骨架与检索路径;无结构的长文本抽取可回捞线索(artifact/path/retrieval)后再预览化。
7
7
  //
8
8
  // 原则(17 号文档):It moves evidence out of prompt and keeps the route back.
9
+ import { isHumanUserMessage } from "./context-compaction.js";
9
10
  export const MICROCOMPACTION_CONFIG = Object.freeze({
10
11
  keepRecentCount: 8,
11
12
  triggerChars: 6_000,
12
13
  previewChars: 800,
14
+ /**
15
+ * Hard cap for one tool-result body in a provider request.
16
+ * The recent window stays more complete than older history, but it cannot
17
+ * carry a multi-megabyte tool body. File reads under this cap stay inline.
18
+ */
19
+ recentToolResultChars: 32_000,
13
20
  });
14
21
  export function previewHistoricalText(text, maxChars = MICROCOMPACTION_CONFIG.previewChars) {
15
22
  const value = String(text ?? '');
@@ -281,6 +288,82 @@ function microcompactBlockContent(block, config) {
281
288
  }
282
289
  return { block, compacted: false, beforeChars: 0, afterChars: 0 };
283
290
  }
291
+ /**
292
+ * Bound one tool-result body before it is serialized into a provider request.
293
+ * Small and already-structured results pass through. Oversized text keeps a
294
+ * retrieval skeleton or a short preview, including original size.
295
+ */
296
+ export function boundProviderToolResultContent(content, maxChars = MICROCOMPACTION_CONFIG.recentToolResultChars) {
297
+ if (content.length <= maxChars)
298
+ return content;
299
+ const previewChars = Math.min(MICROCOMPACTION_CONFIG.previewChars, Math.max(200, maxChars));
300
+ const parsed = tryParseJsonObject(content);
301
+ if (parsed) {
302
+ const ref = compactLocalRefPayload(parsed, previewChars);
303
+ const shrunk = ref ?? shrinkOversizedToolRecord(parsed, previewChars, content.length);
304
+ const next = JSON.stringify(ref ? { ...shrunk, originalChars: content.length } : shrunk);
305
+ if (next.length <= maxChars && next.length < content.length)
306
+ return next;
307
+ }
308
+ const preview = compactLongHistoricalString(content, previewChars);
309
+ return preview.length <= maxChars ? preview : preview.slice(0, maxChars);
310
+ }
311
+ function shrinkOversizedToolRecord(value, previewChars, originalChars) {
312
+ const next = {
313
+ contextPreviewTruncated: true,
314
+ originalChars,
315
+ note: 'Tool result omitted from provider history; use artifact, path, or evidence refs for the full output.',
316
+ };
317
+ for (const [key, item] of Object.entries(value)) {
318
+ if (typeof item === 'string') {
319
+ next[key] = item.length > previewChars ? previewHistoricalText(item, previewChars) : item;
320
+ continue;
321
+ }
322
+ if (Array.isArray(item)) {
323
+ next[key] = item.length > 16 ? item.slice(0, 16) : item;
324
+ continue;
325
+ }
326
+ if (item && typeof item === 'object') {
327
+ const nested = shrinkOversizedToolRecord(item, Math.min(previewChars, 400), originalChars);
328
+ delete nested.note;
329
+ delete nested.originalChars;
330
+ next[key] = nested;
331
+ continue;
332
+ }
333
+ next[key] = item;
334
+ }
335
+ return next;
336
+ }
337
+ function boundToolMessageContent(content, maxChars) {
338
+ if (typeof content === 'string') {
339
+ const next = boundProviderToolResultContent(content, maxChars);
340
+ return {
341
+ content: next,
342
+ bounded: next !== content,
343
+ beforeChars: content.length,
344
+ afterChars: next.length,
345
+ };
346
+ }
347
+ if (!Array.isArray(content)) {
348
+ return { content, bounded: false, beforeChars: 0, afterChars: 0 };
349
+ }
350
+ let bounded = false;
351
+ let beforeChars = 0;
352
+ let afterChars = 0;
353
+ const blocks = content.map((block) => {
354
+ const record = block;
355
+ if (record?.type !== 'tool_result' || typeof record.content !== 'string')
356
+ return block;
357
+ const next = boundProviderToolResultContent(record.content, maxChars);
358
+ if (next === record.content)
359
+ return block;
360
+ bounded = true;
361
+ beforeChars += record.content.length;
362
+ afterChars += next.length;
363
+ return { ...record, content: next };
364
+ });
365
+ return { content: blocks, bounded, beforeChars, afterChars };
366
+ }
284
367
  function microcompactMessageContent(content, config) {
285
368
  if (typeof content === 'string') {
286
369
  const result = microcompactStringContent(content, config);
@@ -309,6 +392,7 @@ function microcompactMessageContent(content, config) {
309
392
  */
310
393
  export function microcompactMessagesForContext(messages, options = {}) {
311
394
  const config = { ...MICROCOMPACTION_CONFIG, ...options };
395
+ let protectLatestUser = options.preserveLatestUserTurn === true;
312
396
  let recentNonSystemSeen = 0;
313
397
  const compactableIndexes = new Set();
314
398
  for (let index = messages.length - 1; index >= 0; index--) {
@@ -316,6 +400,10 @@ export function microcompactMessagesForContext(messages, options = {}) {
316
400
  if (message?.role === 'system' || message?._compaction)
317
401
  continue;
318
402
  recentNonSystemSeen++;
403
+ if (protectLatestUser && message && isHumanUserMessage(message)) {
404
+ protectLatestUser = false;
405
+ continue;
406
+ }
319
407
  if (recentNonSystemSeen > config.keepRecentCount) {
320
408
  compactableIndexes.add(index);
321
409
  }
@@ -323,9 +411,27 @@ export function microcompactMessagesForContext(messages, options = {}) {
323
411
  let compactedCount = 0;
324
412
  let beforeChars = 0;
325
413
  let afterChars = 0;
414
+ const recentCap = config.recentToolResultChars;
326
415
  const nextMessages = messages.map((message, index) => {
327
- if (!compactableIndexes.has(index))
328
- return message;
416
+ if (!compactableIndexes.has(index)) {
417
+ if (message?.role !== 'tool' && !Array.isArray(message?.content))
418
+ return message;
419
+ const bounded = boundToolMessageContent(message?.content, recentCap);
420
+ if (!bounded.bounded)
421
+ return message;
422
+ compactedCount++;
423
+ beforeChars += bounded.beforeChars;
424
+ afterChars += bounded.afterChars;
425
+ return {
426
+ ...message,
427
+ content: bounded.content,
428
+ _microCompaction: {
429
+ method: 'provider_tool_result_cap',
430
+ beforeChars: bounded.beforeChars,
431
+ afterChars: bounded.afterChars,
432
+ },
433
+ };
434
+ }
329
435
  const result = microcompactMessageContent(message.content, config);
330
436
  if (!result.compacted)
331
437
  return message;
@@ -0,0 +1,45 @@
1
+ import { type InputDraftValue, type LocalInputSurface, type ProjectAgentSubmitInputResult, type ProjectInputDraftSnapshot, type ProjectInputMutationResult, type ProjectInputRecoveryPort, type UnconfirmedProjectInput } from '@peer-agent/protocol';
2
+ export interface InputRecoveryView extends ProjectInputDraftSnapshot {
3
+ readonly ready: boolean;
4
+ readonly error: string | null;
5
+ readonly sending: readonly string[];
6
+ readonly received: readonly UnconfirmedProjectInput[];
7
+ readonly rejected: Readonly<Record<string, string>>;
8
+ readonly mutating: readonly string[];
9
+ }
10
+ /** Presentation continuity only; ports own storage and the existing governed input queue. */
11
+ export declare function createProjectInputRecovery({ workspaceId, surface, port, createId, now, receiptTimeoutMs }: {
12
+ workspaceId: string;
13
+ surface: LocalInputSurface;
14
+ port: ProjectInputRecoveryPort;
15
+ createId: () => string;
16
+ now?: () => string;
17
+ receiptTimeoutMs?: number;
18
+ }): {
19
+ getSnapshot: () => InputRecoveryView;
20
+ subscribe(fn: () => void): () => void;
21
+ load: () => Promise<boolean>;
22
+ edit: (patch: Partial<InputDraftValue>) => void;
23
+ flush: () => Promise<boolean>;
24
+ acknowledge: (ids: readonly string[]) => void;
25
+ send: (options?: {
26
+ text?: string;
27
+ quoteRefs?: readonly string[];
28
+ taskRefs?: readonly import("@peer-agent/protocol").InputDraftTaskRef[];
29
+ answerTo?: string;
30
+ useDraft?: boolean;
31
+ }) => Promise<ProjectAgentSubmitInputResult>;
32
+ discard: (inputId: string) => Promise<ProjectInputMutationResult>;
33
+ restoreToDraft: (inputId: string, options?: {
34
+ readonly replaceDraft?: boolean;
35
+ }) => Promise<ProjectInputMutationResult>;
36
+ observeReceived(ids: readonly string[], answered?: readonly {
37
+ readonly answerTo: string;
38
+ readonly text: string;
39
+ }[]): void;
40
+ retry(inputId: string): Promise<ProjectAgentSubmitInputResult> | Promise<{
41
+ ok: boolean;
42
+ code: string;
43
+ }>;
44
+ };
45
+ export type ProjectInputRecovery = ReturnType<typeof createProjectInputRecovery>;
@@ -0,0 +1,491 @@
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 }) {
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
+ const listeners = new Set(), storedAttachments = new Map(), active = new Map();
45
+ const draftOrigins = new Map();
46
+ const optionOrigins = new Set();
47
+ const mutatingIds = new Set();
48
+ const publish = (patch) => { view = { ...view, ...patch }; for (const fn of listeners)
49
+ fn(); };
50
+ const isDraftEmpty = (draft) => !draft.text && !draft.quote && !draft.attachments.length
51
+ && !draft.taskRefs?.length && !draft.resourceFeedback?.length;
52
+ const hasComposedContent = (input) => Boolean(input.attachments.length || input.quoteRefs.length || input.taskRefs?.length || input.resourceFeedback?.length);
53
+ const omitRejected = (ids) => {
54
+ if (!ids.some(id => Object.prototype.hasOwnProperty.call(view.rejected, id)))
55
+ return view.rejected;
56
+ const next = {};
57
+ for (const [key, value] of Object.entries(view.rejected)) {
58
+ if (!ids.includes(key))
59
+ next[key] = value;
60
+ }
61
+ return Object.keys(next).length ? next : EMPTY_REJECTED;
62
+ };
63
+ const markRejected = (inputId, code) => {
64
+ if (view.rejected[inputId] === code)
65
+ return;
66
+ publish({ rejected: { ...view.rejected, [inputId]: code } });
67
+ };
68
+ const clearRejected = (ids) => {
69
+ const rejected = omitRejected(ids);
70
+ if (rejected !== view.rejected)
71
+ publish({ rejected });
72
+ };
73
+ const quoteForRestore = (input) => {
74
+ const savedQuote = draftOrigins.get(input.inputId);
75
+ if (savedQuote !== undefined)
76
+ return savedQuote;
77
+ if (input.quoteRefs.length >= 2 && input.quoteRefs[0] && input.quoteRefs[1]) {
78
+ return { messageId: input.quoteRefs[0], text: input.quoteRefs[1] };
79
+ }
80
+ return null;
81
+ };
82
+ const buildRestoredDraft = (input, rejectionCode) => {
83
+ const keepResourceFeedback = Boolean(input.resourceFeedback?.length && (!rejectionCode || !RESOURCE_REJECTION_CODES.has(rejectionCode)));
84
+ return {
85
+ text: input.text,
86
+ quote: quoteForRestore(input),
87
+ attachments: input.attachments,
88
+ ...(input.taskRefs?.length ? { taskRefs: input.taskRefs } : {}),
89
+ ...(keepResourceFeedback ? { resourceFeedback: input.resourceFeedback } : {}),
90
+ };
91
+ };
92
+ async function writeState(draftValue, pendingList) {
93
+ const all = [...draftValue.attachments, ...pendingList.flatMap(item => item.attachments)];
94
+ const uploads = [...new Map(all.filter(item => storedAttachments.get(item.id) !== item).map(item => [item.id, item])).values()];
95
+ const { attachments, ...draft } = draftValue;
96
+ const chunks = partitionUploadChunks(uploads);
97
+ let revision = view.revision;
98
+ const available = new Set(storedAttachments.keys());
99
+ try {
100
+ for (let i = 0; i < chunks.length; i++) {
101
+ const chunk = chunks[i];
102
+ for (const item of chunk)
103
+ available.add(item.id);
104
+ const isFinal = i === chunks.length - 1;
105
+ const result = await port.write({
106
+ ...address,
107
+ revision,
108
+ draft: {
109
+ ...draft,
110
+ attachmentIds: isFinal
111
+ ? attachments.map(item => item.id)
112
+ : attachments.filter(item => available.has(item.id)).map(item => item.id),
113
+ },
114
+ pending: pendingList.map(({ attachments: pendingAttachments, ...input }) => ({
115
+ ...input,
116
+ attachmentIds: isFinal
117
+ ? pendingAttachments.map(item => item.id)
118
+ : pendingAttachments.filter(item => available.has(item.id)).map(item => item.id),
119
+ })),
120
+ uploads: chunk,
121
+ });
122
+ if (!result.ok) {
123
+ publish({ error: result.code });
124
+ return null;
125
+ }
126
+ revision = result.revision;
127
+ for (const item of chunk)
128
+ storedAttachments.set(item.id, item);
129
+ if (!isFinal)
130
+ publish({ revision, error: null });
131
+ }
132
+ storedAttachments.clear();
133
+ for (const item of all)
134
+ storedAttachments.set(item.id, item);
135
+ return revision;
136
+ }
137
+ catch {
138
+ publish({ error: 'DRAFT_SAVE_FAILED' });
139
+ return null;
140
+ }
141
+ }
142
+ async function load() {
143
+ if (loading)
144
+ return loading;
145
+ loading = (async () => {
146
+ try {
147
+ const result = await port.read(address);
148
+ if (!result.ok) {
149
+ publish({ error: result.code });
150
+ return false;
151
+ }
152
+ for (const item of [...result.snapshot.draft.attachments, ...result.snapshot.pending.flatMap(item => item.attachments)])
153
+ storedAttachments.set(item.id, item);
154
+ publish({ ...result.snapshot, draft: earlyEdits ? { ...result.snapshot.draft, ...earlyEdits } : result.snapshot.draft, ready: true, error: null });
155
+ if (earlyEdits) {
156
+ earlyEdits = null;
157
+ changed++;
158
+ void flush();
159
+ }
160
+ return true;
161
+ }
162
+ catch {
163
+ publish({ error: 'DRAFT_UNAVAILABLE' });
164
+ return false;
165
+ }
166
+ finally {
167
+ loading = null;
168
+ }
169
+ })();
170
+ return loading;
171
+ }
172
+ async function flush() {
173
+ if (!view.ready)
174
+ return false;
175
+ while (writing) {
176
+ const ok = await writing;
177
+ if (!ok)
178
+ return false;
179
+ if (saved === changed)
180
+ return true;
181
+ }
182
+ if (saved === changed)
183
+ return true;
184
+ writing = (async () => {
185
+ while (saved !== changed) {
186
+ const version = changed, state = view;
187
+ const revision = await writeState(state.draft, state.pending);
188
+ if (revision === null)
189
+ return false;
190
+ saved = version;
191
+ publish({ revision, error: null });
192
+ }
193
+ return true;
194
+ })().finally(() => { writing = null; });
195
+ return writing;
196
+ }
197
+ function edit(patch) {
198
+ if (patch.resourceFeedback !== undefined) {
199
+ const rows = normalizeResourceFeedbackList(patch.resourceFeedback);
200
+ if (!rows || rows.some(row => row.recipient.workspaceId !== workspaceId)) {
201
+ publish({ error: 'INVALID_RESOURCE_FEEDBACK' });
202
+ return;
203
+ }
204
+ patch = { ...patch, resourceFeedback: rows };
205
+ }
206
+ if (!view.ready)
207
+ earlyEdits = { ...earlyEdits, ...patch };
208
+ changed++;
209
+ publish({ draft: { ...view.draft, ...patch } });
210
+ if (view.ready)
211
+ void flush();
212
+ }
213
+ function acknowledge(ids) {
214
+ for (const id of ids) {
215
+ draftOrigins.delete(id);
216
+ optionOrigins.delete(id);
217
+ }
218
+ const rejected = omitRejected(ids);
219
+ const pending = view.pending.filter(item => !ids.includes(item.inputId));
220
+ if (pending.length === view.pending.length) {
221
+ if (rejected !== view.rejected)
222
+ publish({ rejected });
223
+ return;
224
+ }
225
+ const received = [...view.received, ...view.pending.filter(item => ids.includes(item.inputId))];
226
+ changed++;
227
+ publish({ pending, received, ...(rejected !== view.rejected ? { rejected } : {}) });
228
+ void flush();
229
+ }
230
+ function dismiss(ids) {
231
+ for (const id of ids) {
232
+ draftOrigins.delete(id);
233
+ optionOrigins.delete(id);
234
+ }
235
+ const rejected = omitRejected(ids);
236
+ const pending = view.pending.filter(item => !ids.includes(item.inputId));
237
+ if (pending.length === view.pending.length) {
238
+ if (rejected !== view.rejected)
239
+ publish({ rejected });
240
+ return;
241
+ }
242
+ changed++;
243
+ publish({ pending, ...(rejected !== view.rejected ? { rejected } : {}) });
244
+ void flush();
245
+ }
246
+ function recoverClosedDraft(input, originalQuote) {
247
+ if (!view.pending.some(item => item.inputId === input.inputId))
248
+ return;
249
+ const rejected = omitRejected([input.inputId]);
250
+ if (isDraftEmpty(view.draft)) {
251
+ const pending = view.pending.filter(item => item.inputId !== input.inputId);
252
+ const restored = {
253
+ text: input.text,
254
+ quote: originalQuote,
255
+ attachments: input.attachments,
256
+ ...(input.taskRefs?.length ? { taskRefs: input.taskRefs } : {}),
257
+ ...(input.resourceFeedback?.length ? { resourceFeedback: input.resourceFeedback } : {}),
258
+ };
259
+ changed++;
260
+ publish({ pending, draft: restored, ...(rejected !== view.rejected ? { rejected } : {}) });
261
+ void flush();
262
+ return;
263
+ }
264
+ const pending = view.pending.map(item => {
265
+ if (item.inputId !== input.inputId || !item.answerTo)
266
+ return item;
267
+ const { answerTo: _closed, ...plain } = item;
268
+ return plain;
269
+ });
270
+ changed++;
271
+ publish({ pending, ...(rejected !== view.rejected ? { rejected } : {}) });
272
+ void flush();
273
+ }
274
+ async function persistPendingMutation(inputId, mode, options) {
275
+ if (!view.ready && !await load())
276
+ return { ok: false, code: view.error || 'DRAFT_UNAVAILABLE' };
277
+ if (active.has(inputId))
278
+ return { ok: false, code: 'INPUT_SENDING' };
279
+ if (mutatingIds.has(inputId))
280
+ return { ok: false, code: 'INPUT_BUSY' };
281
+ if (!view.pending.some(item => item.inputId === inputId))
282
+ return { ok: false, code: 'INPUT_NOT_PENDING' };
283
+ mutatingIds.add(inputId);
284
+ publish({ mutating: [...mutatingIds] });
285
+ try {
286
+ while (writing || saved !== changed) {
287
+ const ok = writing ? await writing : await flush();
288
+ if (!ok)
289
+ return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
290
+ }
291
+ if (active.has(inputId))
292
+ return { ok: false, code: 'INPUT_SENDING' };
293
+ const target = view.pending.find(item => item.inputId === inputId);
294
+ if (!target)
295
+ return { ok: false, code: 'INPUT_NOT_PENDING' };
296
+ if (mode === 'restore' && !options?.replaceDraft && !isDraftEmpty(view.draft)) {
297
+ return { ok: false, code: 'DRAFT_NOT_EMPTY' };
298
+ }
299
+ const baseVersion = changed;
300
+ const nextPendingForDisk = view.pending.filter(item => item.inputId !== inputId);
301
+ const nextDraftForDisk = mode === 'restore' ? buildRestoredDraft(target, view.rejected[inputId]) : view.draft;
302
+ let writtenRevision = null;
303
+ writing = (async () => {
304
+ writtenRevision = await writeState(nextDraftForDisk, nextPendingForDisk);
305
+ return writtenRevision !== null;
306
+ })().finally(() => { writing = null; });
307
+ const ok = await writing;
308
+ if (!ok || writtenRevision === null)
309
+ return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
310
+ if (mode === 'restore' && changed !== baseVersion) {
311
+ publish({ revision: writtenRevision, error: null });
312
+ void flush();
313
+ return { ok: false, code: 'DRAFT_NOT_EMPTY' };
314
+ }
315
+ draftOrigins.delete(inputId);
316
+ optionOrigins.delete(inputId);
317
+ const rejected = omitRejected([inputId]);
318
+ const nextPending = view.pending.filter(item => item.inputId !== inputId);
319
+ if (changed === baseVersion)
320
+ saved = baseVersion;
321
+ publish({
322
+ revision: writtenRevision,
323
+ error: null,
324
+ pending: nextPending,
325
+ ...(mode === 'restore' ? { draft: nextDraftForDisk } : {}),
326
+ ...(rejected !== view.rejected ? { rejected } : {}),
327
+ });
328
+ if (saved !== changed)
329
+ void flush();
330
+ return { ok: true };
331
+ }
332
+ finally {
333
+ mutatingIds.delete(inputId);
334
+ publish({ mutating: mutatingIds.size ? [...mutatingIds] : EMPTY_IDS });
335
+ }
336
+ }
337
+ function dispatch(input) {
338
+ if (mutatingIds.has(input.inputId))
339
+ return Promise.resolve({ ok: false, code: 'INPUT_BUSY' });
340
+ const running = active.get(input.inputId);
341
+ if (running)
342
+ return running;
343
+ const job = (async () => {
344
+ publish({ sending: [...view.sending, input.inputId] });
345
+ try {
346
+ if (!await flush())
347
+ return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
348
+ // This deadline ends the presentation wait, never the host operation. A late
349
+ // factual receipt still reconciles the original envelope without resending.
350
+ const submitted = port.submit({ ...address, ...input }).then(result => {
351
+ if (projectInputWasReceived(result, workspaceId, input.inputId)) {
352
+ acknowledge([input.inputId]);
353
+ return result;
354
+ }
355
+ if (isDefiniteProjectInputRejection(result, workspaceId, input.inputId)) {
356
+ const code = result.code;
357
+ if (!view.pending.some(item => item.inputId === input.inputId))
358
+ return { ok: false, code };
359
+ if (code === 'QUESTION_CLOSED') {
360
+ if (optionOrigins.has(input.inputId) && !hasComposedContent(input)) {
361
+ dismiss([input.inputId]);
362
+ }
363
+ else if (draftOrigins.has(input.inputId)) {
364
+ const originalQuote = draftOrigins.get(input.inputId) ?? null;
365
+ draftOrigins.delete(input.inputId);
366
+ recoverClosedDraft(input, originalQuote);
367
+ }
368
+ else {
369
+ markRejected(input.inputId, code);
370
+ }
371
+ }
372
+ else {
373
+ markRejected(input.inputId, code);
374
+ }
375
+ return { ok: false, code };
376
+ }
377
+ clearRejected([input.inputId]);
378
+ return { ok: false, code: result.code || 'INPUT_OUTCOME_UNKNOWN' };
379
+ }).catch(() => {
380
+ clearRejected([input.inputId]);
381
+ return { ok: false, code: 'INPUT_OUTCOME_UNKNOWN' };
382
+ });
383
+ let timer;
384
+ try {
385
+ return await Promise.race([submitted, new Promise(resolve => {
386
+ timer = setTimeout(() => resolve({ ok: false, code: 'INPUT_OUTCOME_UNKNOWN' }), receiptTimeoutMs);
387
+ })]);
388
+ }
389
+ finally {
390
+ clearTimeout(timer);
391
+ }
392
+ }
393
+ catch {
394
+ return { ok: false, code: 'INPUT_OUTCOME_UNKNOWN' };
395
+ }
396
+ finally {
397
+ active.delete(input.inputId);
398
+ const sending = view.sending.filter(id => id !== input.inputId);
399
+ publish({ sending: sending.length ? sending : EMPTY_IDS });
400
+ }
401
+ })();
402
+ active.set(input.inputId, job);
403
+ return job;
404
+ }
405
+ async function send(options = {}) {
406
+ if (!view.ready && !await load())
407
+ return { ok: false, code: view.error || 'DRAFT_UNAVAILABLE' };
408
+ const useDraft = options.useDraft !== false, draft = view.draft;
409
+ const text = (options.text ?? draft.text).trim(), attachments = useDraft ? draft.attachments : [];
410
+ const taskRefs = options.taskRefs ?? (useDraft ? (draft.taskRefs ?? []) : []);
411
+ if (useDraft && options.text !== undefined && text !== draft.text.trim())
412
+ return { ok: false, code: 'INPUT_CHANGED' };
413
+ const resourceFeedback = useDraft ? normalizeResourceFeedbackList(draft.resourceFeedback) : [];
414
+ if (!resourceFeedback)
415
+ return { ok: false, code: 'INVALID_RESOURCE_FEEDBACK' };
416
+ if (!text && !attachments.length && !taskRefs.length && !resourceFeedback.some(row => row.resource.kind === 'interactive'))
417
+ return { ok: false, code: 'INVALID_INPUT' };
418
+ if (!useDraft && options.answerTo) {
419
+ if (view.received.some(item => item.answerTo === options.answerTo))
420
+ return { ok: false, code: 'QUESTION_CLOSED' };
421
+ const existing = view.pending.find(item => item.answerTo === options.answerTo);
422
+ if (existing) {
423
+ if (view.rejected[existing.inputId] === 'QUESTION_CLOSED')
424
+ return { ok: false, code: 'QUESTION_CLOSED' };
425
+ if (!view.rejected[existing.inputId])
426
+ return existing.text === text ? dispatch(existing) : { ok: false, code: 'INPUT_PENDING_ANSWER' };
427
+ }
428
+ }
429
+ if (view.pending.length >= 32)
430
+ return { ok: false, code: 'DRAFT_LIMIT' };
431
+ if (resourceFeedback.some(item => item.recipient.workspaceId !== workspaceId))
432
+ return { ok: false, code: 'RESOURCE_FEEDBACK_RECIPIENT_CHANGED' };
433
+ try {
434
+ encodeResourceFeedbackTransport(resourceFeedback, attachments);
435
+ }
436
+ catch (error) {
437
+ return { ok: false, code: error.code ?? 'INVALID_RESOURCE_FEEDBACK' };
438
+ }
439
+ const input = { inputId: createId(), text, attachments, ...(resourceFeedback.length ? { resourceFeedback } : {}), ...(taskRefs.length ? { taskRefs } : {}), createdAt: now(), quoteRefs: options.quoteRefs ?? [],
440
+ ...(options.answerTo ? { answerTo: options.answerTo } : {}) };
441
+ if (useDraft)
442
+ draftOrigins.set(input.inputId, draft.quote);
443
+ else if (options.answerTo)
444
+ optionOrigins.add(input.inputId);
445
+ changed++;
446
+ publish({ pending: [...view.pending, input], ...(useDraft ? { draft: emptyInputDraft() } : {}) });
447
+ return dispatch(input);
448
+ }
449
+ return {
450
+ getSnapshot: () => view,
451
+ subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
452
+ load, edit, flush, acknowledge, send,
453
+ discard: (inputId) => persistPendingMutation(inputId, 'discard'),
454
+ restoreToDraft: (inputId, options) => persistPendingMutation(inputId, 'restore', options),
455
+ observeReceived(ids, answered) {
456
+ const isDuplicateCommittedReplyAnswer = (item) => Boolean(answered?.length
457
+ && !active.has(item.inputId)
458
+ && item.answerTo?.startsWith('card:question:reply:')
459
+ && !item.attachments.length
460
+ && !item.taskRefs?.length
461
+ && !item.resourceFeedback?.length
462
+ && !item.quoteRefs.length
463
+ && answered.some(entry => entry.answerTo === item.answerTo && entry.text.trim() === item.text.trim()));
464
+ const dropped = [];
465
+ const pending = view.pending.filter(item => {
466
+ const drop = ids.includes(item.inputId) || isDuplicateCommittedReplyAnswer(item);
467
+ if (drop) {
468
+ draftOrigins.delete(item.inputId);
469
+ optionOrigins.delete(item.inputId);
470
+ dropped.push(item.inputId);
471
+ }
472
+ return !drop;
473
+ });
474
+ const rejected = dropped.length ? omitRejected(dropped) : view.rejected;
475
+ const received = view.received.filter(item => !ids.includes(item.inputId));
476
+ if (pending.length !== view.pending.length) {
477
+ changed++;
478
+ publish({ pending, received, ...(rejected !== view.rejected ? { rejected } : {}) });
479
+ void flush();
480
+ }
481
+ else if (received.length !== view.received.length)
482
+ publish({ received });
483
+ },
484
+ retry(inputId) {
485
+ if (mutatingIds.has(inputId))
486
+ return Promise.resolve({ ok: false, code: 'INPUT_BUSY' });
487
+ const input = view.pending.find(item => item.inputId === inputId);
488
+ return input ? dispatch(input) : Promise.resolve({ ok: false, code: 'INPUT_NOT_PENDING' });
489
+ },
490
+ };
491
+ }