@apia/ai 5.2.3 → 6.0.2

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 (86) hide show
  1. package/dist/assistant/index.d.d.ts +49 -0
  2. package/dist/assistant/index.d.d.ts.map +1 -0
  3. package/dist/assistant/index.js +154 -0
  4. package/dist/assistant/index.js.map +1 -0
  5. package/dist/assistant/runtime/conversationActivity.js +11 -0
  6. package/dist/assistant/runtime/conversationActivity.js.map +1 -0
  7. package/dist/assistant/runtime/conversationAnnotations.js +28 -0
  8. package/dist/assistant/runtime/conversationAnnotations.js.map +1 -0
  9. package/dist/assistant/runtime/conversationAttachmentPreview.js +33 -0
  10. package/dist/assistant/runtime/conversationAttachmentPreview.js.map +1 -0
  11. package/dist/assistant/runtime/conversationAttachments.js +24 -0
  12. package/dist/assistant/runtime/conversationAttachments.js.map +1 -0
  13. package/dist/assistant/runtime/conversationClient.d.d.ts +26 -0
  14. package/dist/assistant/runtime/conversationClient.d.d.ts.map +1 -0
  15. package/dist/assistant/runtime/conversationClient.js +599 -0
  16. package/dist/assistant/runtime/conversationClient.js.map +1 -0
  17. package/dist/assistant/runtime/conversationPlan.js +12 -0
  18. package/dist/assistant/runtime/conversationPlan.js.map +1 -0
  19. package/dist/assistant/runtime/conversationProjection.d.d.ts +8 -0
  20. package/dist/assistant/runtime/conversationProjection.d.d.ts.map +1 -0
  21. package/dist/assistant/runtime/conversationProjection.js +184 -0
  22. package/dist/assistant/runtime/conversationProjection.js.map +1 -0
  23. package/dist/assistant/runtime/coordinatorProxy.js +302 -0
  24. package/dist/assistant/runtime/coordinatorProxy.js.map +1 -0
  25. package/dist/chat/ChatController/ChatController.d.ts +13 -9
  26. package/dist/chat/ChatController/ChatController.js +103 -94
  27. package/dist/chat/ChatController/ChatController.js.map +1 -1
  28. package/dist/chat/ChatController/annotationStyles.js +1 -78
  29. package/dist/chat/ChatController/annotationStyles.js.map +1 -1
  30. package/dist/chat/ChatController/annotationTargets.d.ts +3 -1
  31. package/dist/chat/ChatController/annotationTargets.js +7 -1
  32. package/dist/chat/ChatController/annotationTargets.js.map +1 -1
  33. package/dist/chat/ChatController/components/AnnotationDraft.js +79 -0
  34. package/dist/chat/ChatController/components/AnnotationDraft.js.map +1 -0
  35. package/dist/chat/ChatController/components/AssistantMessageActions.d.ts +4 -0
  36. package/dist/chat/ChatController/components/AssistantMessageActions.d.ts.map +1 -0
  37. package/dist/chat/ChatController/components/AssistantMessageActions.js +102 -0
  38. package/dist/chat/ChatController/components/AssistantMessageActions.js.map +1 -0
  39. package/dist/chat/ChatController/components/AssistantTurnMessage.d.ts +24 -1
  40. package/dist/chat/ChatController/components/AssistantTurnMessage.js +155 -26
  41. package/dist/chat/ChatController/components/AssistantTurnMessage.js.map +1 -1
  42. package/dist/chat/ChatController/components/ChatMessage.d.ts +8 -5
  43. package/dist/chat/ChatController/components/ChatMessage.js +27 -22
  44. package/dist/chat/ChatController/components/ChatMessage.js.map +1 -1
  45. package/dist/chat/ChatController/components/History.d.ts +5 -1
  46. package/dist/chat/ChatController/components/History.js +17 -7
  47. package/dist/chat/ChatController/components/History.js.map +1 -1
  48. package/dist/chat/ChatController/components/Message.d.ts +7 -2
  49. package/dist/chat/ChatController/components/Message.js +22 -8
  50. package/dist/chat/ChatController/components/Message.js.map +1 -1
  51. package/dist/chat/ChatController/components/MessageBlocks.d.ts +2 -5
  52. package/dist/chat/ChatController/components/MessageBlocks.js +6 -48
  53. package/dist/chat/ChatController/components/MessageBlocks.js.map +1 -1
  54. package/dist/chat/ChatController/components/MessageBody.js +10 -3
  55. package/dist/chat/ChatController/components/MessageBody.js.map +1 -1
  56. package/dist/chat/ChatController/components/PendingMessagesPanel.js +2 -3
  57. package/dist/chat/ChatController/components/PendingMessagesPanel.js.map +1 -1
  58. package/dist/chat/ChatController/components/SentAnnotations.js +5 -3
  59. package/dist/chat/ChatController/components/SentAnnotations.js.map +1 -1
  60. package/dist/chat/ChatController/components/TextArea/QuestionComposer.js +1 -2
  61. package/dist/chat/ChatController/components/TextArea/QuestionComposer.js.map +1 -1
  62. package/dist/chat/ChatController/components/TextArea.d.ts +3 -5
  63. package/dist/chat/ChatController/components/TextArea.js +5 -69
  64. package/dist/chat/ChatController/components/TextArea.js.map +1 -1
  65. package/dist/chat/ChatController/types.d.ts +28 -1
  66. package/dist/index.d.ts +7 -8
  67. package/dist/index.js +5 -6
  68. package/dist/index.js.map +1 -1
  69. package/dist/stream/ResponseStream.d.ts +15 -10
  70. package/dist/stream/ResponseStream.js +58 -61
  71. package/dist/stream/ResponseStream.js.map +1 -1
  72. package/dist/stream/reasoningSummary.js +19 -0
  73. package/dist/stream/reasoningSummary.js.map +1 -0
  74. package/package.json +8 -8
  75. package/dist/assistant/AssistantController.d.ts +0 -53
  76. package/dist/assistant/AssistantController.d.ts.map +0 -1
  77. package/dist/assistant/AssistantController.js +0 -131
  78. package/dist/assistant/AssistantController.js.map +0 -1
  79. package/dist/assistant/HandoffCoordinator.d.ts +0 -18
  80. package/dist/assistant/HandoffCoordinator.d.ts.map +0 -1
  81. package/dist/assistant/HandoffCoordinator.js +0 -35
  82. package/dist/assistant/HandoffCoordinator.js.map +0 -1
  83. package/dist/assistant/PanelAssistantTransport.d.ts +0 -28
  84. package/dist/assistant/PanelAssistantTransport.d.ts.map +0 -1
  85. package/dist/assistant/PanelAssistantTransport.js +0 -48
  86. package/dist/assistant/PanelAssistantTransport.js.map +0 -1
@@ -0,0 +1,599 @@
1
+ import { normalizeConversationAnnotations } from './conversationAnnotations.js';
2
+ import { CoordinatorProxy } from './coordinatorProxy.js';
3
+ import { validateConversationAttachments, MAX_CONVERSATION_REQUEST_BYTES } from './conversationAttachments.js';
4
+
5
+ const clone = value => JSON.parse(JSON.stringify(value));
6
+ const terminal = new Set(['completed', 'failed', 'cancelled', 'closed']);
7
+ const admissionIdWithdrawn = error => error instanceof Error && error.message === 'ADMISSION_WITHDRAWN';
8
+ let clientSequence = 0;
9
+ const evidenceLost = error => error?.code === 'CONVERSATION_EVIDENCE_LOST' && error?.status === 409;
10
+ const attachmentRejected = error => (error?.status === 415 && error?.code === 'ATTACHMENT_UNSUPPORTED_EXTENSION')
11
+ || (error?.status === 400 && error?.code === 'INVALID_ATTACHMENT');
12
+ const TAB_DISCOVERY_WAIT_MS = 1000;
13
+ const checkpointOf = ({ admissions, admissionError, ...checkpoint }) => checkpoint;
14
+
15
+ /** Durable consumer of public facts. Server ack follows local retention and server deduplication. */
16
+ class ConversationClient {
17
+ constructor({ api, tabs, storage, key, contentId, onChange, replyMode, closeTaskTab, tabOrder, pause = () => new Promise(resolve => setTimeout(resolve, 500)) }) {
18
+ Object.assign(this, { api, tabs, storage, key, contentId, onChange, closeTaskTab, tabOrder, pause });
19
+ const raw = storage.getItem(key);
20
+ this.state = raw ? JSON.parse(raw) : { creationId: `conversation:${tabs.newRequestId()}`, messages: [], deliveries: {}, events: [], responses: {}, response: undefined };
21
+ this.owner = `${tabs.newRequestId()}:${++clientSequence}`;
22
+ this.ownerKey = `${key}:owner`; storage.setItem(this.ownerKey, this.owner);
23
+ this.state.generation ??= this.state.creationId ?? `generation:${tabs.newRequestId()}`;
24
+ const request = this.api, changed = this.onChange;
25
+ this.onChange = state => { if (this.current) changed(state); };
26
+ this.api = async body => {
27
+ const generation = this.state.generation;
28
+ try {
29
+ const inventory = this.inventory();
30
+ const payload = { ...body, inventory };
31
+ if (body.action === 'create' && replyMode === 'automatic') payload.replyMode = 'automatic';
32
+ const response = await request(['create', 'status', 'turn'].includes(body.action)
33
+ ? { ...payload, runtimeId: this.owner } : payload);
34
+ if (!this.current) return {};
35
+ if (generation !== this.state.generation) throw new Error('CONVERSATION_GENERATION_STALE');
36
+ return response;
37
+ } catch (error) {
38
+ if (!this.current) return {};
39
+ if (generation !== this.state.generation) throw new Error('CONVERSATION_GENERATION_STALE');
40
+ throw error;
41
+ }
42
+ };
43
+ this.idleWaiters = []; this.disposed = false;
44
+ // Legacy checkpoints can contain queued messages. Only admitted turns are recoverable.
45
+ delete this.state.queuePause;
46
+ delete this.state.admissionError;
47
+ this.state.admissions = [];
48
+ this.persist(this.state);
49
+ this.active = undefined;
50
+ }
51
+ get current() { return !this.disposed && this.storage.getItem(this.ownerKey) === this.owner; }
52
+ retainedAttachment(reference) {
53
+ const pending = this.state.pending?.attachments?.find(file => file.reference === reference);
54
+ if (pending) return pending;
55
+ for (const message of [...this.state.messages].reverse()) {
56
+ const file = message.attachments?.find(file => file.reference === reference);
57
+ if (file) return file;
58
+ }
59
+ return undefined;
60
+ }
61
+ hasOperatedTab(tabId) {
62
+ return Boolean(tabId) && Object.values(this.proxy?.state?.operations ?? {}).some(operation => operation.tabId === tabId);
63
+ }
64
+ inventory() {
65
+ const inventory = clone(this.tabs.snapshot());
66
+ const liveOrder = this.tabOrder?.();
67
+ const order = Array.isArray(liveOrder) ? liveOrder : [];
68
+ const liveIds = new Set(order);
69
+ if (Array.isArray(liveOrder)) inventory.tabOrder = order;
70
+ inventory.tabs = (inventory.tabs ?? []).filter(tab => tab.state === 'closed' ? this.hasOperatedTab(tab.tabId)
71
+ : !Array.isArray(liveOrder) || liveIds.has(String(tab.tabId)));
72
+ for (const tab of inventory.tabs ?? []) {
73
+ const index = order.indexOf(String(tab.tabId));
74
+ if (index >= 0) tab.tabNumber = index + 1;
75
+ }
76
+ return inventory;
77
+ }
78
+ freshState() {
79
+ const generation = `conversation:${this.tabs.newRequestId()}:${++clientSequence}`;
80
+ return { generation, creationId: generation, messages: [], admissions: [], deliveries: {}, events: [], responses: {} };
81
+ }
82
+ async clearHistory() {
83
+ if (!this.current) throw new Error('La conversación se desmontó.');
84
+ if (this.initializing) await this.initializing;
85
+ const old = this.state;
86
+ // Retain operation evidence outside the new model conversation. Never replay old effects.
87
+ this.storage.setItem(`${this.key}:archive:${old.generation}`, JSON.stringify({ reason: 'USER_CLEARED_HISTORY', checkpoint: checkpointOf(old) }));
88
+ this.ready = false; this.proxy?.dispose(); this.proxy = undefined;
89
+ this.active = undefined; this.activeTurnId = undefined;
90
+ this.pumping = false;
91
+ this.persist(this.freshState());
92
+ this.onChange(this.state);
93
+ await this.initialize();
94
+ }
95
+ invalidate(error) {
96
+ if (!this.current) return;
97
+ const old = this.state;
98
+ // Retain evidence before replacing the active checkpoint. No tab/request effects are performed.
99
+ this.storage.setItem(`${this.key}:archive:${old.generation}`, JSON.stringify({ reason: error.code, checkpoint: checkpointOf(old) }));
100
+ this.ready = false; this.proxy?.dispose(); this.proxy = undefined;
101
+ this.active = undefined; this.activeTurnId = undefined;
102
+ this.pumping = false;
103
+ this.persist(this.freshState());
104
+ this.onChange(this.state);
105
+ }
106
+ persist(state) {
107
+ if (!this.current) return; // A replaced client's late callbacks cannot overwrite the current checkpoint.
108
+ this.storage.setItem(this.key, JSON.stringify(checkpointOf(state))); this.state = state;
109
+ this.releaseIdle();
110
+ }
111
+ releaseIdle() { if (!this.state.pending && !this.active) for (const waiter of this.idleWaiters.splice(0)) waiter.resolve(); }
112
+ waitUntilIdle() {
113
+ if (!this.current) return Promise.reject(new Error('La conversación se desmontó.'));
114
+ if (!this.state.pending && !this.active) return Promise.resolve();
115
+ return new Promise((resolve, reject) => this.idleWaiters.push({ resolve, reject }));
116
+ }
117
+ initialize(validate = false) {
118
+ if (!this.current) return Promise.reject(new Error('La conversación se desmontó.'));
119
+ if (this.initializing) return this.initializing;
120
+ if (this.ready && !validate) return Promise.resolve(this.state.response);
121
+ const run = this.connect().finally(() => { if (this.initializing === run) this.initializing = undefined; this.pumpAdmissions(); });
122
+ this.initializing = run; return run;
123
+ }
124
+ async connect() {
125
+ this.ready = false;
126
+ let generation = this.state.generation;
127
+ let response;
128
+ try {
129
+ response = await this.api(this.state.conversationId
130
+ ? { action: 'status', conversationId: this.state.conversationId }
131
+ : { action: 'create', contentId: this.contentId, creationId: this.state.creationId });
132
+ } catch (error) {
133
+ if (!this.current || generation !== this.state.generation) return;
134
+ if (!this.state.conversationId || !evidenceLost(error)) throw error;
135
+ this.invalidate(error); generation = this.state.generation;
136
+ response = await this.api({ action: 'create', contentId: this.contentId, creationId: this.state.creationId });
137
+ }
138
+ if (!this.current || generation !== this.state.generation) return;
139
+ if (!response.conversationId || (this.state.conversationId && response.conversationId !== this.state.conversationId))
140
+ throw new Error('CONVERSATION_ID_CONFLICT');
141
+ this.persist({ ...this.state, conversationId: response.conversationId });
142
+ this.proxy ??= new CoordinatorProxy({ client: this.tabs, storage: this.storage, key: `coordinator:${response.conversationId}`, closeTaskTab: this.closeTaskTab,
143
+ attachmentForTurn: reference => this.retainedAttachment(reference),
144
+ publish: fact => this.current && generation === this.state.generation ? this.consume(fact) : false,
145
+ isCurrent: () => this.current && generation === this.state.generation, filterRequests: true });
146
+ this.proxy.observe(); await this.proxy.drain();
147
+ if (!this.current || generation !== this.state.generation) return;
148
+ await this.observeResponse(response);
149
+ if (!this.current || generation !== this.state.generation) return;
150
+ this.ready = true;
151
+ this.scheduleTerminalObservation();
152
+ this.pumpAdmissions();
153
+ return response;
154
+ }
155
+ async enqueue(message, attachments = [], annotations = [], referralTurnId) {
156
+ validateConversationAttachments(attachments);
157
+ const retainedAttachments = clone(attachments), retainedAnnotations = normalizeConversationAnnotations(annotations);
158
+ if (!message.trim() && !retainedAnnotations.length && !retainedAttachments.length) throw new Error('La instrucción está vacía.');
159
+ if (!this.current) throw new Error('La conversación se desmontó.');
160
+ if (!this.active && !this.state.pending && !this.state.admissions.length) await this.initialize(true);
161
+ if (!this.current) throw new Error('La conversación se desmontó.');
162
+ const generation = this.state.generation;
163
+ if (referralTurnId && (this.activeTurnId === referralTurnId || this.state.messages.some(entry => entry.id === referralTurnId) ||
164
+ this.state.admissions.some(entry => entry.id === referralTurnId))) return referralTurnId;
165
+ const entry = { id: referralTurnId ?? `turn:${this.tabs.newRequestId()}`, message, attachments: retainedAttachments, annotations: retainedAnnotations };
166
+ const turnId = this.state.pending?.turnId ?? this.activeTurnId;
167
+ if (turnId && !terminal.has(this.state.responses[turnId]?.status)) {
168
+ if ((this.activeTurnId !== turnId && this.localTurnId !== turnId) || this.state.turnCancellation?.turnId === turnId ||
169
+ (this.state.response?.turnId === turnId &&
170
+ ['requires-intervention', 'suspended'].includes(this.state.response.status)))
171
+ throw new Error('Continuá el turno pendiente antes de enviar otro mensaje.');
172
+ this.persist({ ...this.state, admissions: [...this.state.admissions, { ...entry, afterTurn: turnId }], admissionError: undefined });
173
+ this.onChange(this.state);
174
+ return entry.id;
175
+ }
176
+ // A final response can render just before the active promise releases the turn.
177
+ if (this.active) await this.active;
178
+ if (!this.current || generation !== this.state.generation || !this.ready)
179
+ throw new Error('La conversación cambió antes de enviar el mensaje.');
180
+ if (this.active || this.state.pending)
181
+ return this.enqueue(message, retainedAttachments, retainedAnnotations, referralTurnId);
182
+ return new Promise((resolve, reject) => {
183
+ this.submit(entry.message, entry.attachments, entry.id, entry.annotations, () => resolve(entry.id))
184
+ .then(() => reject(new Error('El envío se interrumpió antes de iniciar el turno.')), reject);
185
+ });
186
+ }
187
+ withdrawAdmission(id) {
188
+ if (!this.current) return;
189
+ this.persist({ ...this.state, admissions: this.state.admissions.filter(entry => entry.id !== id), admissionError: undefined });
190
+ this.onChange(this.state); this.pumpAdmissions();
191
+ }
192
+ pumpAdmissions() {
193
+ if (!this.current || !this.ready || this.initializing || this.pumping || this.active || this.state.pending || !this.state.admissions.length) return;
194
+ this.pumping = true;
195
+ const generation = this.state.generation;
196
+ this.admissionPump = (async () => {
197
+ while (this.current && generation === this.state.generation && this.ready && !this.initializing && !this.state.pending && this.state.admissions.length) {
198
+ const entry = this.state.admissions[0];
199
+ const previous = this.state.responses[entry.afterTurn];
200
+ if (previous?.status !== 'completed' || previous.deliverySettled) {
201
+ this.persist({ ...this.state, admissions: [] });
202
+ this.onChange(this.state);
203
+ break;
204
+ }
205
+ try { await this.submit(entry.message, entry.attachments, entry.id, entry.annotations, undefined, true); }
206
+ catch (error) {
207
+ if (!this.current || generation !== this.state.generation) break;
208
+ if (admissionIdWithdrawn(error)) continue;
209
+ break;
210
+ }
211
+ }
212
+ })().catch(error => {
213
+ if (!this.current || generation !== this.state.generation) return;
214
+ this.reportAdmissionFailure(error);
215
+ }).finally(() => {
216
+ if (this.current && generation === this.state.generation) { this.pumping = false; this.pumpAdmissions(); }
217
+ });
218
+ }
219
+ reportAdmissionFailure(error) {
220
+ if (!this.current) return;
221
+ if (evidenceLost(error)) {
222
+ this.invalidate(error);
223
+ return;
224
+ }
225
+ this.persist({ ...this.state, admissions: this.state.pending ? this.state.admissions : [],
226
+ admissionError: error instanceof Error ? error.message : String(error) });
227
+ this.onChange(this.state);
228
+ }
229
+ async consume(fact) {
230
+ if (!this.current) return false;
231
+ if (fact.kind === 'tab-event' && fact.event?.kind === 'tab.closed' && !this.hasOperatedTab(fact.event.tabId)) return true;
232
+ fact = clone(fact);
233
+ if (fact.process) delete fact.process.url;
234
+ const id = fact.deliveryId ?? `relation:${fact.operationId}`;
235
+ const fingerprint = JSON.stringify(fact);
236
+ if (this.state.deliveries[id] && this.state.deliveries[id] !== fingerprint) throw new Error('FACT_ID_CONFLICT');
237
+ if (!this.state.deliveries[id]) {
238
+ if (Object.keys(this.state.deliveries).length >= 2048) throw new Error('CONVERSATION_FACT_RETENTION_LIMIT');
239
+ const next = clone(this.state); next.deliveries[id] = fingerprint;
240
+ next.events.push({ ...fact, deliveryId: id }); this.persist(next);
241
+ }
242
+ // The UI reflects retained public evidence immediately; the next model turn still waits for drain/ack.
243
+ if (this.current) this.onChange(this.state);
244
+ if (!this.current) return false;
245
+ // Retry this call even if local retention already completed: the previous server ack may have been lost.
246
+ await this.api({ action: 'fact', conversationId: this.state.conversationId, fact: { ...fact, deliveryId: id }, inventory: this.tabs.snapshot() });
247
+ if (this.current) this.observeLateTerminal(fact);
248
+ return this.current;
249
+ }
250
+ observeLateTerminal(fact) {
251
+ const event = fact.kind === 'tab-event' ? fact.event : undefined;
252
+ if (event?.kind !== 'request.final' || !terminal.has(event.data?.status) || !this.state.pending) return;
253
+ const operation = this.state.response?.operation;
254
+ const retained = operation && this.proxy?.state.operations[operation.id];
255
+ if (!retained || retained.requestId !== event.requestId || retained.tabId !== event.tabId ||
256
+ (retained.assistantId && retained.assistantId !== event.assistantId)) return;
257
+ const identity = { generation: this.state.generation, turnId: this.state.pending.turnId,
258
+ operationId: operation.id, requestId: event.requestId };
259
+ this.persist({ ...this.state, terminalObservation: identity });
260
+ this.scheduleTerminalObservation();
261
+ }
262
+ scheduleTerminalObservation() {
263
+ if (this.terminalObserver || !this.state.terminalObservation) return;
264
+ const identity = this.state.terminalObservation;
265
+ // Never await follow/resume inside consume: drain is awaiting consume's ack.
266
+ const run = Promise.resolve().then(async () => {
267
+ await this.proxy?.drain();
268
+ if (this.active) { try { await this.active; } catch { /* Retained evidence permits observing the same request. */ } }
269
+ if (!this.current || identity.generation !== this.state.generation ||
270
+ this.state.pending?.turnId !== identity.turnId || this.state.response?.operation?.id !== identity.operationId) return;
271
+ await this.resume(false);
272
+ }).catch(error => {
273
+ if (this.current && identity.generation === this.state.generation) this.onChange({ ...this.state,
274
+ observationError: error instanceof Error ? error.message : String(error) });
275
+ }).finally(() => {
276
+ if (this.terminalObserver === run) this.terminalObserver = undefined;
277
+ if (this.current && identity.generation === this.state.generation && !this.state.pending)
278
+ this.persist({ ...this.state, terminalObservation: undefined });
279
+ });
280
+ this.terminalObserver = run;
281
+ }
282
+ async observeResponse(response) {
283
+ if (!this.current) return;
284
+ const responses = { ...(this.state.responses ?? {}) };
285
+ if (response.turnId) {
286
+ const previous = responses[response.turnId];
287
+ responses[response.turnId] = { ...previous, ...response,
288
+ operation: response.operation ?? previous?.operation,
289
+ completedAt: terminal.has(response.status) ? previous?.completedAt ?? Date.now() : undefined };
290
+ }
291
+ const pending = this.state.pending;
292
+ const matches = !pending || response.turnId === pending.turnId;
293
+ const settled = pending && matches && terminal.has(response.status);
294
+ const connectionFailure = settled && response.status === 'failed' && response.code === 'MODEL_CONNECTION_FAILED';
295
+ this.persist({ ...this.state, response: matches ? response : this.state.response, responses,
296
+ pending: settled ? undefined : pending,
297
+ failedTurn: connectionFailure ? clone(pending) : this.state.failedTurn,
298
+ admissions: settled && (response.status !== 'completed' || response.deliverySettled ||
299
+ this.state.turnCancellation?.turnId === response.turnId) ? [] : this.state.admissions });
300
+ if (this.current) this.onChange(this.state);
301
+ }
302
+ submit(message, attachments = [], turnId = `turn:${this.tabs.newRequestId()}`, annotations = [], onAdmitted, queued = false) {
303
+ if (!this.current || !this.ready) return Promise.reject(new Error('El coordinador todavía no está conectado.'));
304
+ if (this.active) return Promise.reject(new Error('Hay un turno pendiente.'));
305
+ this.activeTurnId = turnId;
306
+ const generation = this.state.generation;
307
+ const run = this.run(message, attachments, turnId, annotations, onAdmitted, queued).catch(error => {
308
+ if (this.current && generation === this.state.generation && !admissionIdWithdrawn(error)) this.reportAdmissionFailure(error);
309
+ throw error;
310
+ }).finally(() => {
311
+ if (this.active === run) {
312
+ this.active = undefined;
313
+ this.activeTurnId = undefined;
314
+ }
315
+ this.releaseIdle();
316
+ this.pumpAdmissions();
317
+ });
318
+ this.active = run; return run;
319
+ }
320
+ async run(message, attachments, turnId = `turn:${this.tabs.newRequestId()}`, annotations, onAdmitted, queued = false) {
321
+ const generation = this.state.generation;
322
+ await this.proxy.drain();
323
+ await this.refreshTabDiscovery();
324
+ if (!this.current || generation !== this.state.generation) return;
325
+ if (queued && !this.state.admissions.some(entry => entry.id === turnId)) throw new Error('ADMISSION_WITHDRAWN');
326
+ if (this.state.pending) throw new Error('Existe un turno recuperable; continuá su observación antes de enviar otro.');
327
+ annotations = normalizeConversationAnnotations(annotations);
328
+ if (!message.trim() && !annotations.length && !attachments.length) throw new Error('La instrucción está vacía.');
329
+ validateConversationAttachments(attachments);
330
+ const resolved = attachments.map(file => ({ ...file,
331
+ reference: `attachment:${this.tabs.newRequestId()}` }));
332
+ const request = { action: 'turn', conversationId: this.state.conversationId, turnId, message, annotations, attachments: resolved, inventory: this.proxy.inventory() };
333
+ if (new TextEncoder().encode(JSON.stringify(request)).length > MAX_CONVERSATION_REQUEST_BYTES)
334
+ throw new Error('La petición supera el tamaño permitido para este mensaje.');
335
+ if (!this.current) return;
336
+ this.persist({ ...this.state, pending: request, admissions: this.state.admissions.filter(entry => entry.id !== turnId),
337
+ admissionError: undefined, messages: [...this.state.messages, { id: turnId, text: message, annotations, startedAt: Date.now(),
338
+ attachments: resolved.map(file => ({...file, id:file.reference})) }] });
339
+ this.localTurnId = turnId;
340
+ this.onChange(this.state); // Retained request is visible while the server accepts the turn, before its first token.
341
+ let response;
342
+ try {
343
+ response = await this.api(request);
344
+ } catch (error) {
345
+ if (attachmentRejected(error)
346
+ && this.current && generation === this.state.generation && this.state.pending?.turnId === turnId) {
347
+ this.localTurnId = undefined;
348
+ this.persist({ ...this.state, pending: undefined, messages: this.state.messages.filter(entry => entry.id !== turnId) });
349
+ } else if (this.current && generation === this.state.generation) {
350
+ onAdmitted?.();
351
+ }
352
+ throw error;
353
+ }
354
+ if (!this.current || generation !== this.state.generation) return;
355
+ onAdmitted?.();
356
+ await this.observeResponse(response);
357
+ if (!this.current || generation !== this.state.generation) return;
358
+ return this.follow(response);
359
+ }
360
+ async refreshTabDiscovery() {
361
+ if (!this.tabs.refreshConnections) return;
362
+ let timer;
363
+ try {
364
+ // Discovery can enrich the inventory. Existing request evidence was already drained.
365
+ await Promise.race([
366
+ Promise.resolve().then(() => this.tabs.refreshConnections()),
367
+ new Promise(resolve => { timer = setTimeout(resolve, TAB_DISCOVERY_WAIT_MS); }),
368
+ ]);
369
+ } catch {
370
+ // The registry still has the last observed state and reports unavailable destinations.
371
+ } finally {
372
+ clearTimeout(timer);
373
+ }
374
+ }
375
+ requestActions() {
376
+ const taskAction = this.state.response?.operation?.delegation?.arguments?.taskAction;
377
+ if (taskAction === 'confirm' || taskAction === 'cancel') return { actions: [] };
378
+ const operationId = this.state.response?.operation?.id;
379
+ const requestId = this.proxy?.state.operations[operationId]?.requestId;
380
+ if (!this.state.pending || !requestId) return { actions: [] };
381
+ let request;
382
+ try { request = this.tabs.request(requestId).snapshot(); } catch { return { actions: [] }; }
383
+ return { operationId, requestId, status: request.status, message: request.attention?.message, confirmation: request.attention?.confirmation, actions: request.actions ?? request.attention?.actions ?? [] };
384
+ }
385
+ async confirm(requestId, confirmationId, approvedItemIds) {
386
+ if (!this.current) throw new Error('La conversación se desmontó.');
387
+ const current = this.requestActions();
388
+ if (current.requestId !== requestId || !current.actions.includes('confirm') || current.confirmation?.id !== confirmationId)
389
+ throw new Error('CONFIRMATION_STALE');
390
+ const result = await this.tabs.request(requestId).confirm(confirmationId, approvedItemIds);
391
+ this.onChange?.(this.state);
392
+ return result;
393
+ }
394
+ async act(action, requestId) {
395
+ if (!this.current) throw new Error('La conversación se desmontó.');
396
+ const generation = this.state.generation;
397
+ const valid = () => {
398
+ const current = this.requestActions();
399
+ if (!requestId || current.requestId !== requestId || !current.actions.includes(action)) throw new Error('REQUEST_ACTION_UNAVAILABLE');
400
+ return current;
401
+ };
402
+ valid();
403
+ if (this.active) await this.active;
404
+ if (!this.current || generation !== this.state.generation) return;
405
+ valid();
406
+ if (action === 'cancel') return this.cancel(requestId);
407
+ return this.resume(action === 'recover', action === 'reconcile' ? requestId : undefined, requestId);
408
+ }
409
+ async resume(recover = true, reconcileRequestId, expectedRequestId) {
410
+ if (!this.current) throw new Error('La conversación se desmontó.');
411
+ if (!this.ready) await this.initialize();
412
+ if (!this.current) return;
413
+ if (this.active) return this.active;
414
+ if (!this.state.pending) {
415
+ this.persist({ ...this.state, admissionError: undefined }); this.pumpAdmissions(); return;
416
+ }
417
+ const generation = this.state.generation;
418
+ const run = (async () => {
419
+ await this.proxy.drain();
420
+ if (!this.current || generation !== this.state.generation) return;
421
+ // Request identities and exact inventory are retained. Status never starts another turn.
422
+ let response = await this.api({ action: 'status', conversationId: this.state.conversationId });
423
+ if (!this.current) return;
424
+ if (response.turnId === this.state.pending?.turnId && terminal.has(response.status)) {
425
+ await this.observeResponse(response); return response;
426
+ }
427
+ if (expectedRequestId && (response.turnId !== this.state.pending?.turnId || response.operation?.id !== this.requestActions().operationId || this.requestActions().requestId !== expectedRequestId)) throw new Error('REQUEST_ACTION_STALE');
428
+ if (response.turnId !== this.state.pending.turnId) response = await this.api(this.state.pending);
429
+ if (!this.current) return;
430
+ await this.observeResponse(response);
431
+ if (!this.current || generation !== this.state.generation) return;
432
+ return this.follow(response, recover, reconcileRequestId);
433
+ })().catch(error => {
434
+ if (this.current && generation === this.state.generation && evidenceLost(error)) this.invalidate(error);
435
+ throw error;
436
+ }).finally(() => {
437
+ if (this.active === run) this.active = undefined; this.releaseIdle();
438
+ if (this.current && generation === this.state.generation && !this.state.pending) { this.persist({ ...this.state, admissionError: undefined }); this.pumpAdmissions(); }
439
+ }); this.active = run; return run;
440
+ }
441
+ async follow(response, recover = false, reconcileRequestId) {
442
+ const generation = this.state.generation;
443
+ const turnId = this.state.pending?.turnId ?? response.turnId;
444
+ while (this.current && generation === this.state.generation) {
445
+ if ((response.turnId && turnId && response.turnId !== turnId) ||
446
+ (this.state.pending && turnId && this.state.pending.turnId !== turnId)) return response;
447
+ if (response.operation) {
448
+ const observeOnly = !recover && !reconcileRequestId && (response.operation.deliveryRecovery || ['requires-intervention', 'suspended'].includes(response.status));
449
+ const result = await this.proxy.execute(response.operation, { recover, reconcileRequestId, observeOnly }); recover = false; reconcileRequestId = undefined;
450
+ if (!this.current || generation !== this.state.generation) return;
451
+ await this.proxy.drain();
452
+ if (!this.current || generation !== this.state.generation) return;
453
+ // Return the destination's actual public answer through the communication interface.
454
+ result.finalText = this.state.events.filter(item => item.kind === 'tab-event' && item.event.requestId === result.requestId && item.event.kind === 'assistant_final')
455
+ .map(item => item.event.data?.text ?? '').join('');
456
+ if (result.process) { result.process = { ...result.process }; delete result.process.url; }
457
+ response = await this.submitOperationResult(result);
458
+ if (!this.current) return;
459
+ await this.observeResponse(response);
460
+ if (!terminal.has(result.status) && ['requires-intervention', 'suspended'].includes(response.status)) return response;
461
+ }
462
+ if (terminal.has(response.status)) {
463
+ if (this.state.pending?.turnId === turnId) this.persist({ ...this.state, pending: undefined });
464
+ if (this.current) this.onChange(this.state); return response;
465
+ }
466
+ if (response.status === 'requires-intervention' || response.status === 'suspended') return response;
467
+ await this.pause();
468
+ if (!this.current || generation !== this.state.generation) return;
469
+ response = await this.api({ action: 'status', conversationId: this.state.conversationId });
470
+ if (!this.current) return;
471
+ await this.observeResponse(response);
472
+ }
473
+ }
474
+ async submitOperationResult(result) {
475
+ const generation = this.state.generation;
476
+ const operationId = result.operationId;
477
+ const retained = this.state.resultSubmissions?.[operationId];
478
+ const acknowledge = async payload => {
479
+ const response = await this.api({ action: 'result', conversationId: this.state.conversationId, result: payload });
480
+ if (!this.current || generation !== this.state.generation) return response;
481
+ this.persist({ ...this.state, resultSubmissions: { ...this.state.resultSubmissions,
482
+ [operationId]: { payload, acknowledged: true } } });
483
+ return response;
484
+ };
485
+ // A terminal result is immutable even if subsequent public observations alter the local view.
486
+ if (retained && terminal.has(retained.payload.status)) return acknowledge(clone(retained.payload));
487
+ if (retained && !retained.acknowledged) await acknowledge(clone(retained.payload));
488
+ if (!this.current || generation !== this.state.generation) return {};
489
+ const submissions = this.state.resultSubmissions ?? {};
490
+ if (!submissions[operationId] && Object.keys(submissions).length >= 128) throw new Error('CONVERSATION_RESULT_RETENTION_LIMIT');
491
+ const payload = clone(result);
492
+ this.persist({ ...this.state, resultSubmissions: { ...submissions, [operationId]: { payload, acknowledged: false } } });
493
+ return acknowledge(payload);
494
+ }
495
+ async deliveryAction(action, attention) {
496
+ if (!this.current || !['reconcileDelivery', 'abandonDelivery'].includes(action)) throw new Error('DELIVERY_ACTION_UNAVAILABLE');
497
+ const generation = this.state.generation;
498
+ const current = this.state.response?.attention;
499
+ if (!current || !current.actions?.includes(action) || this.state.pending?.turnId !== current.turnId ||
500
+ ['turnId', 'toolCallId', 'startId', 'revision'].some(key => current[key] !== attention[key])) throw new Error('DELIVERY_ACTION_STALE');
501
+ const observing = this.active;
502
+ if (observing && action !== 'abandonDelivery') await observing;
503
+ if (!this.current || generation !== this.state.generation) return;
504
+ const identity = { action, conversationId: this.state.conversationId, turnId: attention.turnId,
505
+ toolCallId: attention.toolCallId, startId: attention.startId, expectedRevision: attention.revision };
506
+ if (['turnId', 'toolCallId', 'startId', 'revision'].some(key => this.state.response?.attention?.[key] !== attention[key]) ||
507
+ !this.state.response?.attention?.actions?.includes(action)) throw new Error('DELIVERY_ACTION_STALE');
508
+ const fingerprint = JSON.stringify(identity);
509
+ const prior = this.state.deliveryAction;
510
+ const retryLostAck = prior && !prior.acknowledged && prior.request.action === action &&
511
+ ['turnId', 'toolCallId', 'startId'].every(key => prior.request[key] === attention[key]);
512
+ const retained = retryLostAck || prior?.fingerprint === fingerprint && !prior.rejected ? prior
513
+ : { fingerprint, request: { ...identity, actionId: `delivery:${this.tabs.newRequestId()}` } };
514
+ this.persist({ ...this.state, deliveryAction: retained }); // Before effects/HTTP; lost ack keeps exact action.
515
+ const run = (async () => {
516
+ let response;
517
+ try { response = await this.api(retained.request); }
518
+ catch (error) {
519
+ // A structured HTTP rejection is acknowledged; network/5xx ambiguity retains the exact action.
520
+ if (this.current && error?.status >= 400 && error.status < 500) {
521
+ this.persist({ ...this.state, deliveryAction: { ...retained, acknowledged: true, rejected: true } });
522
+ this.onChange(this.state);
523
+ }
524
+ throw error;
525
+ }
526
+ if (!this.current) return;
527
+ if (response.turnId !== attention.turnId) throw new Error('DELIVERY_ACTION_STALE');
528
+ this.persist({ ...this.state, deliveryAction: { ...retained, acknowledged: true,
529
+ rejected: response.deliveryActionOutcome?.kind === 'REJECTED' } });
530
+ await this.observeResponse(response);
531
+ if (!this.current || generation !== this.state.generation) return;
532
+ // A retained operation is evidence, not permission after a definitive preparation rejection.
533
+ if (response.deliveryActionOutcome?.kind === 'REJECTED') return response;
534
+ if (action === 'abandonDelivery' && response.abandonDeliveryPending && response.operation) {
535
+ await this.proxy.cancel(response.operation.id);
536
+ if (!this.current || generation !== this.state.generation) return;
537
+ }
538
+ if (observing && action === 'abandonDelivery') return observing;
539
+ return this.follow(response, action === 'reconcileDelivery');
540
+ })().finally(() => {
541
+ if (this.active === run) this.active = undefined;
542
+ this.releaseIdle();
543
+ this.pumpAdmissions();
544
+ });
545
+ if (observing && action === 'abandonDelivery') return run;
546
+ this.active = run; return run;
547
+ }
548
+ async cancelTurn(turnId) {
549
+ if (!this.current || this.state.pending?.turnId !== turnId || !this.state.response?.turnActions?.includes('cancelTurn')) throw new Error('TURN_ACTION_UNAVAILABLE');
550
+ const retained = this.state.turnCancellation?.turnId === turnId ? this.state.turnCancellation
551
+ : { turnId, actionId: `cancel:${this.tabs.newRequestId()}` };
552
+ this.persist({ ...this.state, turnCancellation: retained, admissions: [] });
553
+ this.onChange(this.state);
554
+ const response = await this.api({ action: 'cancelTurn', conversationId: this.state.conversationId, ...retained });
555
+ if (!this.current) return;
556
+ if (response.turnId !== turnId) throw new Error('TURN_ACTION_STALE');
557
+ await this.observeResponse(response);
558
+ if (this.active) return this.active;
559
+ return this.resume(false);
560
+ }
561
+ async openTaskLink(conversationId, reference) {
562
+ const generation = this.state.generation;
563
+ if (!this.current || conversationId !== this.state.conversationId)
564
+ throw new Error('El enlace pertenece a otra conversación.');
565
+ const destination = await this.api({ action: 'resolveTaskLink', conversationId, reference });
566
+ if (!this.current || generation !== this.state.generation) return;
567
+ const { tab } = await this.tabs.open({ title: destination.title, url: destination.url });
568
+ if (!this.current || generation !== this.state.generation) return;
569
+ const tabNumber = (this.tabOrder?.() ?? []).indexOf(tab.tabId) + 1;
570
+ await this.api({ action: 'recordTaskLinkOpened', conversationId, reference, tabId: tab.tabId,
571
+ ...(tabNumber > 0 ? { tabNumber } : {}) });
572
+ }
573
+ async cancel(expectedRequestId) {
574
+ if (!this.current) return;
575
+ const generation = this.state.generation;
576
+ if (expectedRequestId && (this.requestActions().requestId !== expectedRequestId || !this.requestActions().actions.includes('cancel'))) throw new Error('REQUEST_ACTION_UNAVAILABLE');
577
+ this.persist({ ...this.state, admissions: [] });
578
+ this.onChange(this.state);
579
+ const operation = this.state.response?.operation;
580
+ if (operation) {
581
+ await this.api({ action: 'cancel', conversationId: this.state.conversationId });
582
+ if (!this.current || generation !== this.state.generation) return;
583
+ await this.proxy.cancel(operation.id);
584
+ if (!this.current || generation !== this.state.generation) return;
585
+ await this.proxy.drain();
586
+ if (!this.current || generation !== this.state.generation) return;
587
+ if (this.active) await this.active;
588
+ else await this.resume();
589
+ } else await this.api({ action: 'cancel', conversationId: this.state.conversationId });
590
+ }
591
+ dispose() {
592
+ this.state.admissions = [];
593
+ this.disposed = true; this.proxy?.dispose();
594
+ for (const waiter of this.idleWaiters.splice(0)) waiter.reject(new Error('La conversación se desmontó.'));
595
+ }
596
+ }
597
+
598
+ export { ConversationClient };
599
+ //# sourceMappingURL=conversationClient.js.map