react-instantsearch-core 7.47.0 → 7.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! React InstantSearch Core 7.47.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
1
+ /*! React InstantSearch Core 7.49.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
4
4
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
@@ -24,7 +24,7 @@
24
24
 
25
25
  var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
26
26
 
27
- var version$2 = '7.47.0';
27
+ var version$2 = '7.49.0';
28
28
 
29
29
  function _define_property(obj, key, value) {
30
30
  if (key in obj) {
@@ -9418,7 +9418,7 @@
9418
9418
  });
9419
9419
  }
9420
9420
 
9421
- var version = '4.114.0';
9421
+ var version = '4.116.0';
9422
9422
 
9423
9423
  var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
9424
9424
  function getCookie(name) {
@@ -13077,6 +13077,26 @@
13077
13077
  var _computedKey$1;
13078
13078
  var defaultGuardrailFallbackResponse = 'Sorry, we are not able to generate a response at the moment.';
13079
13079
  var TOOL_CALL_CANCELLED_ERROR_TEXT = 'The tool call was cancelled: the conversation moved on before a result was provided.';
13080
+ var RESTORED_TOOL_CALL_ERROR_TEXT = 'The page was reloaded before a tool result was received. The operation may have completed.';
13081
+ var RESTORED_TOOL_INPUT_ERROR_TEXT = 'The page was reloaded before the tool input was complete. The operation was not started.';
13082
+ function getTerminalToolState(options) {
13083
+ if (options.state === 'output-error') {
13084
+ return {
13085
+ state: 'output-error',
13086
+ errorText: options.errorText || 'Tool call failed.'
13087
+ };
13088
+ }
13089
+ if (options.state === undefined && 'errorText' in options && typeof options.errorText === 'string') {
13090
+ return {
13091
+ state: 'output-error',
13092
+ errorText: options.errorText || 'Tool call failed.'
13093
+ };
13094
+ }
13095
+ return {
13096
+ state: 'output-available',
13097
+ output: options.output
13098
+ };
13099
+ }
13080
13100
  function getToolName(part) {
13081
13101
  if (part.type === 'dynamic-tool') {
13082
13102
  var _part_toolName;
@@ -13114,7 +13134,7 @@
13114
13134
  */ var AbstractChat = /*#__PURE__*/ function() {
13115
13135
  function AbstractChat(param) {
13116
13136
  var _this = this;
13117
- var _param_generateId = param.generateId, generateId$1 = _param_generateId === void 0 ? generateId : _param_generateId, _param_id = param.id, id = _param_id === void 0 ? generateId$1() : _param_id, transport = param.transport, state = param.state, onError = param.onError, onToolCall = param.onToolCall, onFinish = param.onFinish, onData = param.onData, sendAutomaticallyWhen = param.sendAutomaticallyWhen, shouldRepairToolInput = param.shouldRepairToolInput, resolveCancelledToolOutput = param.resolveCancelledToolOutput;
13137
+ var _param_generateId = param.generateId, generateId$1 = _param_generateId === void 0 ? generateId : _param_generateId, _param_id = param.id, id = _param_id === void 0 ? generateId$1() : _param_id, transport = param.transport, state = param.state, onError = param.onError, onToolCall = param.onToolCall, onFinish = param.onFinish, onData = param.onData, sendAutomaticallyWhen = param.sendAutomaticallyWhen, shouldRepairToolInput = param.shouldRepairToolInput, shouldRepairRestoredPendingToolPart = param.shouldRepairRestoredPendingToolPart, resolveCancelledToolOutput = param.resolveCancelledToolOutput;
13118
13138
  var _this1 = this;
13119
13139
  _class_call_check(this, AbstractChat);
13120
13140
  _define_property(this, "conversationId", void 0);
@@ -13127,11 +13147,13 @@
13127
13147
  _define_property(this, "onData", void 0);
13128
13148
  _define_property(this, "sendAutomaticallyWhen", void 0);
13129
13149
  _define_property(this, "shouldRepairToolInput", void 0);
13150
+ _define_property(this, "shouldRepairRestoredPendingToolPart", void 0);
13130
13151
  _define_property(this, "resolveCancelledToolOutput", void 0);
13131
13152
  _define_property(this, "activeResponse", null);
13132
13153
  _define_property(this, "latestResponse", null);
13133
13154
  _define_property(this, "responsesByToolCallId", new Map());
13134
13155
  _define_property(this, "responseByMessage", new WeakMap());
13156
+ _define_property(this, "restoredToolCalls", void 0);
13135
13157
  // Once tool ownership is discarded, an identifier-only result cannot prove
13136
13158
  // which response generation submitted it. Scoped submissions remain safe.
13137
13159
  _define_property(this, "acceptsIdentifierOnlyToolResults", true);
@@ -13299,7 +13321,7 @@
13299
13321
  warnInvalidGlobalToolResult(options.toolCallId);
13300
13322
  return Promise.resolve();
13301
13323
  }
13302
- if (!_this.commit(options.toolCallId, options.output, message.id, undefined, message)) {
13324
+ if (!_this.commit(options.toolCallId, getTerminalToolState(options), message.id, undefined, message)) {
13303
13325
  return Promise.resolve();
13304
13326
  }
13305
13327
  return _this.continueResponse();
@@ -13346,6 +13368,7 @@
13346
13368
  this.onData = onData;
13347
13369
  this.sendAutomaticallyWhen = sendAutomaticallyWhen;
13348
13370
  this.shouldRepairToolInput = shouldRepairToolInput;
13371
+ this.shouldRepairRestoredPendingToolPart = shouldRepairRestoredPendingToolPart;
13349
13372
  this.resolveCancelledToolOutput = resolveCancelledToolOutput;
13350
13373
  }
13351
13374
  _create_class(AbstractChat, [
@@ -13518,7 +13541,7 @@
13518
13541
  },
13519
13542
  {
13520
13543
  key: "commit",
13521
- value: function commit(toolCallId, output, messageId, response, expectedMessage) {
13544
+ value: function commit(toolCallId, terminalState, messageId, response, expectedMessage) {
13522
13545
  var isTargetPart = function isTargetPart(part) {
13523
13546
  return 'toolCallId' in part && part.toolCallId === toolCallId;
13524
13547
  };
@@ -13533,10 +13556,7 @@
13533
13556
  return false;
13534
13557
  }
13535
13558
  var updatedParts = _to_consumable_array(message.parts);
13536
- updatedParts[partIndex] = withTerminalToolState(part, {
13537
- state: 'output-available',
13538
- output: output
13539
- });
13559
+ updatedParts[partIndex] = withTerminalToolState(part, terminalState);
13540
13560
  var updatedMessage = _object_spread_props(_object_spread({}, message), {
13541
13561
  parts: updatedParts
13542
13562
  });
@@ -13544,6 +13564,60 @@
13544
13564
  return true;
13545
13565
  }
13546
13566
  },
13567
+ {
13568
+ key: "captureRestoredToolCalls",
13569
+ value: function captureRestoredToolCalls() {
13570
+ var restoredToolCalls = new Map();
13571
+ this.messages.forEach(function(message) {
13572
+ message.parts.forEach(function(part) {
13573
+ var _restoredToolCalls_get;
13574
+ if (!isPendingToolPart(part)) return;
13575
+ var toolCallIds = (_restoredToolCalls_get = restoredToolCalls.get(message.id)) !== null && _restoredToolCalls_get !== void 0 ? _restoredToolCalls_get : new Set();
13576
+ toolCallIds.add(part.toolCallId);
13577
+ restoredToolCalls.set(message.id, toolCallIds);
13578
+ });
13579
+ });
13580
+ this.restoredToolCalls = restoredToolCalls;
13581
+ }
13582
+ },
13583
+ {
13584
+ key: "clearRestoredToolCalls",
13585
+ value: function clearRestoredToolCalls() {
13586
+ this.restoredToolCalls = undefined;
13587
+ }
13588
+ },
13589
+ {
13590
+ key: "repairRestoredPendingToolParts",
13591
+ value: function repairRestoredPendingToolParts() {
13592
+ var _this = this;
13593
+ var shouldRepairRestoredPendingToolPart = this.shouldRepairRestoredPendingToolPart;
13594
+ if (!shouldRepairRestoredPendingToolPart) return;
13595
+ this.messages.forEach(function(message, messageIndex) {
13596
+ message.parts.forEach(function(part) {
13597
+ var _this_restoredToolCalls_get;
13598
+ if (!isPendingToolPart(part)) return;
13599
+ if (_this.restoredToolCalls && !((_this_restoredToolCalls_get = _this.restoredToolCalls.get(message.id)) === null || _this_restoredToolCalls_get === void 0 ? void 0 : _this_restoredToolCalls_get.has(part.toolCallId))) {
13600
+ return;
13601
+ }
13602
+ var shouldRepair = false;
13603
+ try {
13604
+ shouldRepair = shouldRepairRestoredPendingToolPart({
13605
+ toolName: getToolName(part),
13606
+ toolCallId: part.toolCallId,
13607
+ input: 'input' in part ? part.input : undefined
13608
+ });
13609
+ } catch (unused) {
13610
+ return;
13611
+ }
13612
+ if (!shouldRepair) return;
13613
+ _this.commit(part.toolCallId, {
13614
+ state: 'output-error',
13615
+ errorText: part.state === 'input-streaming' ? RESTORED_TOOL_INPUT_ERROR_TEXT : RESTORED_TOOL_CALL_ERROR_TEXT
13616
+ }, message.id, undefined, _this.messages[messageIndex]);
13617
+ });
13618
+ });
13619
+ }
13620
+ },
13547
13621
  {
13548
13622
  key: "getOutboundMessages",
13549
13623
  value: /**
@@ -13678,18 +13752,18 @@
13678
13752
  },
13679
13753
  {
13680
13754
  key: "submitToolResult",
13681
- value: function submitToolResult(response, param) {
13755
+ value: function submitToolResult(response, options) {
13682
13756
  var _this = this;
13683
- var toolCallId = param.toolCallId, output = param.output, messageId = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : response === null || response === void 0 ? void 0 : response.messageId, expectedMessage = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : messageId ? this.messages.find(function(message) {
13757
+ var messageId = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : response === null || response === void 0 ? void 0 : response.messageId, expectedMessage = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : messageId ? this.messages.find(function(message) {
13684
13758
  return message.id === messageId;
13685
13759
  }) : undefined;
13686
13760
  if (response === null || response === void 0 ? void 0 : response.isRetired) return Promise.resolve();
13687
13761
  var commitResult = function commitResult() {
13688
- if (!_this.commit(toolCallId, output, messageId, response, expectedMessage)) {
13762
+ if (!_this.commit(options.toolCallId, getTerminalToolState(options), messageId, response, expectedMessage)) {
13689
13763
  return Promise.resolve();
13690
13764
  }
13691
- if (response === null || response === void 0 ? void 0 : response.requiredToolCallIds.has(toolCallId)) {
13692
- response.resolvedToolCallIds.add(toolCallId);
13765
+ if (response === null || response === void 0 ? void 0 : response.requiredToolCallIds.has(options.toolCallId)) {
13766
+ response.resolvedToolCallIds.add(options.toolCallId);
13693
13767
  }
13694
13768
  return _this.continueResponse(response);
13695
13769
  };
@@ -14073,13 +14147,16 @@
14073
14147
  _this.responsesByToolCallId.set(chunk.toolCallId, owners);
14074
14148
  response.pendingToolCallbacks++;
14075
14149
  try {
14150
+ var _this_restoredToolCalls_get, _this_restoredToolCalls;
14151
+ (_this_restoredToolCalls = _this.restoredToolCalls) === null || _this_restoredToolCalls === void 0 ? void 0 : (_this_restoredToolCalls_get = _this_restoredToolCalls.get(currentMessage.id)) === null || _this_restoredToolCalls_get === void 0 ? void 0 : _this_restoredToolCalls_get.delete(chunk.toolCallId);
14076
14152
  var result = _this.onToolCall({
14077
14153
  toolCall: {
14078
14154
  toolName: chunk.toolName,
14079
14155
  toolCallId: chunk.toolCallId,
14080
14156
  input: chunk.input,
14081
14157
  dynamic: 'dynamic' in chunk ? chunk.dynamic : undefined
14082
- }
14158
+ },
14159
+ signal: response.abortController.signal
14083
14160
  }, function(options) {
14084
14161
  return response.isRetired ? Promise.resolve() : _this.submitToolResult(response, options);
14085
14162
  });
@@ -14399,7 +14476,7 @@
14399
14476
  return AbstractChat;
14400
14477
  }();
14401
14478
 
14402
- var _computedKey, _computedKey1, _computedKey2, _computedKey3, _computedKey4, _computedKey5;
14479
+ var _computedKey, _computedKey1, _computedKey2, _computedKey3, _computedKey4, _computedKey5, _computedKey6, _computedKey7;
14403
14480
  var CACHE_KEY = 'instantsearch-chat-initial-messages';
14404
14481
  // Message history is a browser concern, and a server render constructs a Chat
14405
14482
  // too. Reading storage there throws during rendering; the write below only
@@ -14421,8 +14498,8 @@
14421
14498
  }
14422
14499
  });
14423
14500
  }
14424
- _computedKey = '~registerMessagesCallback', _computedKey1 = '~registerStatusCallback', _computedKey2 = '~registerErrorCallback';
14425
- var _computedKey6 = _computedKey, _computedKey7 = _computedKey1, _computedKey8 = _computedKey2;
14501
+ _computedKey = '~persistMessages', _computedKey1 = '~registerMessagesCallback', _computedKey2 = '~registerStatusCallback', _computedKey3 = '~registerErrorCallback';
14502
+ var _computedKey8 = _computedKey, _computedKey9 = _computedKey1, _computedKey10 = _computedKey2, _computedKey11 = _computedKey3;
14426
14503
  var ChatState = /*#__PURE__*/ function() {
14427
14504
  function ChatState() {
14428
14505
  var _this = this;
@@ -14434,6 +14511,7 @@
14434
14511
  _define_property(this, "_messagesCallbacks", new Set());
14435
14512
  _define_property(this, "_statusCallbacks", new Set());
14436
14513
  _define_property(this, "_errorCallbacks", new Set());
14514
+ _define_property(this, "persistenceKey", void 0);
14437
14515
  _define_property(this, "pushMessage", function(message) {
14438
14516
  _this._messages = _this._messages.concat(message);
14439
14517
  _this._callMessagesCallbacks();
@@ -14452,20 +14530,31 @@
14452
14530
  _define_property(this, "snapshot", function(thing) {
14453
14531
  return JSON.parse(JSON.stringify(thing));
14454
14532
  });
14455
- _define_property(this, _computedKey6, function(onChange) {
14533
+ _define_property(this, _computedKey8, function() {
14534
+ var persistenceKey = _this.persistenceKey;
14535
+ if (!persistenceKey) return;
14536
+ safelyRunOnBrowser(function() {
14537
+ try {
14538
+ sessionStorage.setItem(persistenceKey, JSON.stringify(_this.messages));
14539
+ } catch (e) {
14540
+ // Do nothing if sessionStorage is not available or full
14541
+ }
14542
+ });
14543
+ });
14544
+ _define_property(this, _computedKey9, function(onChange) {
14456
14545
  var callback = onChange;
14457
14546
  _this._messagesCallbacks.add(callback);
14458
14547
  return function() {
14459
14548
  _this._messagesCallbacks.delete(callback);
14460
14549
  };
14461
14550
  });
14462
- _define_property(this, _computedKey7, function(onChange) {
14551
+ _define_property(this, _computedKey10, function(onChange) {
14463
14552
  _this._statusCallbacks.add(onChange);
14464
14553
  return function() {
14465
14554
  _this._statusCallbacks.delete(onChange);
14466
14555
  };
14467
14556
  });
14468
- _define_property(this, _computedKey8, function(onChange) {
14557
+ _define_property(this, _computedKey11, function(onChange) {
14469
14558
  _this._errorCallbacks.add(onChange);
14470
14559
  return function() {
14471
14560
  _this._errorCallbacks.delete(onChange);
@@ -14496,19 +14585,14 @@
14496
14585
  if (!persistence) {
14497
14586
  return;
14498
14587
  }
14499
- var saveMessagesInLocalStorage = function saveMessagesInLocalStorage() {
14588
+ this.persistenceKey = CACHE_KEY + (id ? "-".concat(id) : '');
14589
+ var saveMessagesInSessionStorage = function saveMessagesInSessionStorage() {
14500
14590
  if (_this.status === 'ready') {
14501
- safelyRunOnBrowser(function() {
14502
- try {
14503
- sessionStorage.setItem(CACHE_KEY + (id ? "-".concat(id) : ''), JSON.stringify(_this.messages));
14504
- } catch (e) {
14505
- // Do nothing if sessionStorage is not available or full
14506
- }
14507
- });
14591
+ _this['~persistMessages']();
14508
14592
  }
14509
14593
  };
14510
- this['~registerMessagesCallback'](saveMessagesInLocalStorage);
14511
- this['~registerStatusCallback'](saveMessagesInLocalStorage);
14594
+ this['~registerMessagesCallback'](saveMessagesInSessionStorage);
14595
+ this['~registerStatusCallback'](saveMessagesInSessionStorage);
14512
14596
  }
14513
14597
  _create_class(ChatState, [
14514
14598
  {
@@ -14544,8 +14628,8 @@
14544
14628
  ]);
14545
14629
  return ChatState;
14546
14630
  }();
14547
- _computedKey3 = '~registerMessagesCallback', _computedKey4 = '~registerStatusCallback', _computedKey5 = '~registerErrorCallback';
14548
- var _computedKey9 = _computedKey3, _computedKey10 = _computedKey4, _computedKey11 = _computedKey5;
14631
+ _computedKey4 = '~repairRestoredPendingToolParts', _computedKey5 = '~registerMessagesCallback', _computedKey6 = '~registerStatusCallback', _computedKey7 = '~registerErrorCallback';
14632
+ var _computedKey12 = _computedKey4, _computedKey13 = _computedKey5, _computedKey14 = _computedKey6, _computedKey15 = _computedKey7;
14549
14633
  var Chat = /*#__PURE__*/ function(AbstractChat) {
14550
14634
  _inherits(Chat, AbstractChat);
14551
14635
  function Chat(_0) {
@@ -14561,14 +14645,25 @@
14561
14645
  _object_spread_props(_object_spread({}, init), {
14562
14646
  state: state
14563
14647
  })
14564
- ]), _define_property(_this, "_state", void 0), _define_property(_this, _computedKey9, function(onChange) {
14648
+ ]), _define_property(_this, "_state", void 0), _define_property(_this, "hasRestoredMessages", false), _define_property(_this, _computedKey12, function() {
14649
+ if (!_this.hasRestoredMessages) return;
14650
+ _this.hasRestoredMessages = false;
14651
+ _this.repairRestoredPendingToolParts();
14652
+ _this.clearRestoredToolCalls();
14653
+ _this._state['~persistMessages']();
14654
+ }), _define_property(_this, _computedKey13, function(onChange) {
14565
14655
  return _this._state['~registerMessagesCallback'](onChange);
14566
- }), _define_property(_this, _computedKey10, function(onChange) {
14656
+ }), _define_property(_this, _computedKey14, function(onChange) {
14567
14657
  return _this._state['~registerStatusCallback'](onChange);
14568
- }), _define_property(_this, _computedKey11, function(onChange) {
14658
+ }), _define_property(_this, _computedKey15, function(onChange) {
14569
14659
  return _this._state['~registerErrorCallback'](onChange);
14570
14660
  });
14571
14661
  _this._state = state;
14662
+ if (messages === undefined && persistence) {
14663
+ _this.hasRestoredMessages = true;
14664
+ _this.captureRestoredToolCalls();
14665
+ _this.repairRestoredPendingToolParts();
14666
+ }
14572
14667
  return _this;
14573
14668
  }
14574
14669
  return Chat;
@@ -14826,6 +14921,9 @@
14826
14921
  name: 'chat',
14827
14922
  connector: true
14828
14923
  });
14924
+ var DEFAULT_TOOL_TIMEOUT = 20000;
14925
+ var TOOL_TIMEOUT_ERROR_TEXT = 'The tool call timed out before a result was received. The operation may have completed.';
14926
+ var TOOL_ABORTED_ERROR_TEXT = 'The tool call was cancelled before a result was received.';
14829
14927
  var OPEN_STATE_CACHE_KEY$1 = 'instantsearch-chat-open-state';
14830
14928
  function normalizePersistence(persistence, hasCustomChat) {
14831
14929
  if (hasCustomChat) {
@@ -15173,7 +15271,8 @@
15173
15271
  if (!transport) {
15174
15272
  throw new Error(withUsage$q('You need to provide either an `agentId` or a `transport`.'));
15175
15273
  }
15176
- return new Chat(_object_spread_props(_object_spread({}, options), {
15274
+ var canRepairRestoredPendingToolParts = !resume;
15275
+ var chat = new Chat(_object_spread_props(_object_spread({}, options), {
15177
15276
  persistence: normalizedPersistence.messages,
15178
15277
  sendAutomaticallyWhen: sendAutomaticallyWhen,
15179
15278
  transport: transport,
@@ -15182,6 +15281,11 @@
15182
15281
  if (!tool) return true;
15183
15282
  return Boolean(tool.streamInput);
15184
15283
  },
15284
+ shouldRepairRestoredPendingToolPart: function shouldRepairRestoredPendingToolPart(param) {
15285
+ var toolName = param.toolName;
15286
+ var tool = findTool(toolName, tools);
15287
+ return Boolean(canRepairRestoredPendingToolParts && (tool === null || tool === void 0 ? void 0 : tool.onToolCall) && tool.timeout !== false);
15288
+ },
15185
15289
  resolveCancelledToolOutput: function resolveCancelledToolOutput(param) {
15186
15290
  var toolName = param.toolName, toolCallId = param.toolCallId, input = param.input;
15187
15291
  var _findTool;
@@ -15201,7 +15305,7 @@
15201
15305
  }
15202
15306
  },
15203
15307
  onToolCall: function onToolCall(param, submitToolResult) {
15204
- var toolCall = param.toolCall;
15308
+ var toolCall = param.toolCall, signal = param.signal;
15205
15309
  var tool = findTool(toolCall.toolName, tools);
15206
15310
  if (!tool) {
15207
15311
  return submitToolResult({
@@ -15211,21 +15315,103 @@
15211
15315
  });
15212
15316
  }
15213
15317
  if (tool.onToolCall) {
15214
- var addToolResult = function addToolResult(param) {
15215
- var output = param.output;
15216
- return submitToolResult({
15217
- output: output,
15318
+ var toolAbortController = new AbortController();
15319
+ var timeoutId;
15320
+ var settled = false;
15321
+ var resolveExecution;
15322
+ var rejectExecution;
15323
+ var execution = new Promise(function(resolve, reject) {
15324
+ resolveExecution = resolve;
15325
+ rejectExecution = reject;
15326
+ });
15327
+ var cleanup = function cleanup() {
15328
+ if (timeoutId !== undefined) {
15329
+ clearTimeout(timeoutId);
15330
+ }
15331
+ signal.removeEventListener('abort', abortToolCall);
15332
+ };
15333
+ var addToolResult = function addToolResult(options) {
15334
+ if (settled) return Promise.resolve();
15335
+ settled = true;
15336
+ cleanup();
15337
+ var submission = submitToolResult(_object_spread_props(_object_spread({}, options), {
15218
15338
  tool: toolCall.toolName,
15219
15339
  toolCallId: toolCall.toolCallId
15340
+ }));
15341
+ submission.then(resolveExecution, rejectExecution);
15342
+ return submission;
15343
+ };
15344
+ var addToolError = function addToolError(error) {
15345
+ var errorText = _instanceof(error, Error) ? error.message : String(error !== null && error !== void 0 ? error : '');
15346
+ return addToolResult({
15347
+ state: 'output-error',
15348
+ errorText: errorText || 'Tool call failed.'
15220
15349
  });
15221
15350
  };
15222
- return tool.onToolCall(_object_spread_props(_object_spread({}, toolCall), {
15223
- addToolResult: addToolResult
15224
- }));
15351
+ function abortToolCall() {
15352
+ var submission = addToolResult({
15353
+ state: 'output-error',
15354
+ errorText: TOOL_ABORTED_ERROR_TEXT
15355
+ });
15356
+ toolAbortController.abort();
15357
+ void submission.catch(function() {
15358
+ return undefined;
15359
+ });
15360
+ }
15361
+ if (signal.aborted) {
15362
+ abortToolCall();
15363
+ return execution;
15364
+ }
15365
+ signal.addEventListener('abort', abortToolCall, {
15366
+ once: true
15367
+ });
15368
+ if (tool.timeout !== false) {
15369
+ var _tool_timeout;
15370
+ timeoutId = setTimeout(function() {
15371
+ var submission = addToolResult({
15372
+ state: 'output-error',
15373
+ errorText: TOOL_TIMEOUT_ERROR_TEXT
15374
+ });
15375
+ toolAbortController.abort();
15376
+ void submission.catch(function() {
15377
+ return undefined;
15378
+ });
15379
+ }, (_tool_timeout = tool.timeout) !== null && _tool_timeout !== void 0 ? _tool_timeout : DEFAULT_TOOL_TIMEOUT);
15380
+ }
15381
+ var toolExecution;
15382
+ try {
15383
+ toolExecution = tool.onToolCall(_object_spread_props(_object_spread({}, toolCall), {
15384
+ addToolResult: addToolResult,
15385
+ signal: toolAbortController.signal
15386
+ }));
15387
+ } catch (error) {
15388
+ return addToolError(error);
15389
+ }
15390
+ var returnedExecution = Promise.resolve(toolExecution).catch(addToolError);
15391
+ if (tool.timeout === false) {
15392
+ return Promise.race([
15393
+ returnedExecution.then(cleanup),
15394
+ execution
15395
+ ]);
15396
+ }
15397
+ void returnedExecution.catch(function() {
15398
+ return undefined;
15399
+ });
15400
+ return execution;
15225
15401
  }
15226
15402
  return Promise.resolve();
15227
15403
  }
15228
15404
  }));
15405
+ if (resume) {
15406
+ var resumeStream = chat.resumeStream;
15407
+ chat.resumeStream = function(requestOptions) {
15408
+ return resumeStream(requestOptions).finally(function() {
15409
+ canRepairRestoredPendingToolParts = true;
15410
+ chat['~repairRestoredPendingToolParts']();
15411
+ });
15412
+ };
15413
+ }
15414
+ return chat;
15229
15415
  };
15230
15416
  return {
15231
15417
  $$type: 'ais.chat',
@@ -16061,8 +16247,35 @@
16061
16247
  return typeof s === 'string';
16062
16248
  });
16063
16249
  }
16064
- function buildSuggestionMessage(suggestion) {
16065
- return "The user clicked this on-page suggestion. Use the current page context first, then search only if needed.\n\nSuggestion: ".concat(suggestion);
16250
+ // Key order is not significant to the request, so a plain `JSON.stringify` would
16251
+ // report two identical payloads as different.
16252
+ function stableKey(value) {
16253
+ if (value === null || (typeof value === "undefined" ? "undefined" : _type_of(value)) !== 'object') {
16254
+ var _JSON_stringify;
16255
+ return (_JSON_stringify = JSON.stringify(value)) !== null && _JSON_stringify !== void 0 ? _JSON_stringify : 'null';
16256
+ }
16257
+ if (Array.isArray(value)) {
16258
+ return "[".concat(value.map(stableKey).join(','), "]");
16259
+ }
16260
+ var record = value;
16261
+ return "{".concat(Object.keys(record).sort().map(function(key) {
16262
+ return "".concat(JSON.stringify(key), ":").concat(stableKey(record[key]));
16263
+ }).join(','), "}");
16264
+ }
16265
+ /**
16266
+ * Comparable identity of a task payload, or `null` when it cannot be compared.
16267
+ */ function taskPayloadKey(payload) {
16268
+ try {
16269
+ // Round-trip first so the comparison sees what the request will actually
16270
+ // carry: `JSON.stringify` applies `toJSON` (a `Date` becomes its ISO string)
16271
+ // and drops the values the wire drops. Walking the raw object instead would
16272
+ // read a `Date` as a key-less object and call two different instants equal.
16273
+ return stableKey(JSON.parse(JSON.stringify(payload)));
16274
+ } catch (unused) {
16275
+ // Circular or otherwise unserializable. Never claim a match on a payload we
16276
+ // could not read; let the request go out and fail where it does today.
16277
+ return null;
16278
+ }
16066
16279
  }
16067
16280
  function stripInternalHitMetadata(hit) {
16068
16281
  var clean = {};
@@ -16128,16 +16341,27 @@
16128
16341
  var error;
16129
16342
  var debounceTimer;
16130
16343
  var lastStateSignature = null;
16344
+ // The payload of the last request that was actually sent. The automatic
16345
+ // trigger keys on the search state, which is only a proxy for the payload,
16346
+ // so this is what decides whether a request would ask anything new.
16347
+ var lastSubmittedPayload = null;
16131
16348
  var latestRenderOptions = null;
16132
16349
  // Set in `dispose()`. A debounced or in-flight `fetch()` can resolve after
16133
16350
  // the widget is unmounted; this guard stops those late callbacks from
16134
16351
  // calling `renderFn` into a torn-down container.
16135
16352
  var disposed = false;
16353
+ // Whether the "is a chat widget mounted on this index?" question has been
16354
+ // settled — see `validateChat`.
16355
+ var hasValidatedChat = false;
16136
16356
  // True between a state-signature change and the debounced refetch that
16137
16357
  // follows it. While pending, the search state has already moved on, so a
16138
16358
  // still-in-flight request from the previous state must not paint its
16139
16359
  // suggestions, its inner render is ignored until the new `submit` starts.
16140
16360
  var refetchPending = false;
16361
+ // True when `refetchPending` made an inner render be dropped. The fetch
16362
+ // that dropped it was expected to render in its place; if that fetch turns
16363
+ // out to send nothing, it has to reconcile the dropped state instead.
16364
+ var droppedInnerRender = false;
16141
16365
  var getStateSignature = function getStateSignature(results) {
16142
16366
  var _buildFilters;
16143
16367
  if (results.queryID) {
@@ -16161,21 +16385,26 @@
16161
16385
  };
16162
16386
  var sendToChat = function sendToChat(renderOptions) {
16163
16387
  return function(prompt) {
16164
- var _ref, _ref1;
16388
+ var _ref, _getLatestResults;
16165
16389
  var chatRenderState = getChatRenderState(renderOptions);
16166
16390
  if (!chatRenderState || !chatRenderState.sendMessage) {
16167
16391
  return false;
16168
16392
  }
16169
- var results = (_ref = (_ref1 = latestRenderOptions === null || latestRenderOptions === void 0 ? void 0 : latestRenderOptions.results) !== null && _ref1 !== void 0 ? _ref1 : 'results' in renderOptions ? renderOptions.results : null) !== null && _ref !== void 0 ? _ref : null;
16393
+ var results = (_ref = (_getLatestResults = getLatestResults()) !== null && _getLatestResults !== void 0 ? _getLatestResults : 'results' in renderOptions ? renderOptions.results : null) !== null && _ref !== void 0 ? _ref : null;
16170
16394
  return openChat(chatRenderState, {
16171
- message: buildSuggestionMessage(prompt),
16395
+ message: prompt,
16172
16396
  referer: 'prompt-suggestions-widget',
16173
16397
  turnContext: buildTurnContext(results)
16174
16398
  });
16175
16399
  };
16176
16400
  };
16177
- var resolvePageContext = function resolvePageContext(results) {
16178
- var resolvedContext = typeof context === 'function' ? context() : context;
16401
+ // `context` may be a function, so the option alone says nothing about what
16402
+ // a given fetch actually has to send. Resolve it once per fetch and let
16403
+ // callers read the value rather than the option.
16404
+ var resolveContext = function resolveContext() {
16405
+ return typeof context === 'function' ? context() : context;
16406
+ };
16407
+ var buildPageContext = function buildPageContext(resolvedContext, results) {
16179
16408
  // Explicit context replaces auto-extraction; otherwise derive it from
16180
16409
  // the current search state. The task's server-owned instructions decide
16181
16410
  // how to interpret the shape — the client doesn't label it.
@@ -16194,15 +16423,11 @@
16194
16423
  hitsSample: transformHits(results.hits)
16195
16424
  });
16196
16425
  };
16197
- var buildInput = function buildInput(results) {
16198
- var _resolvePageContext;
16199
- return (_resolvePageContext = resolvePageContext(results)) !== null && _resolvePageContext !== void 0 ? _resolvePageContext : {};
16200
- };
16201
16426
  // The same page context, flattened for the chat handoff: `turnContext` is
16202
16427
  // a flat `Record<string, string>` per the Agent Studio contract, so
16203
16428
  // non-string values (e.g. `hitsSample`) are serialized.
16204
16429
  var buildTurnContext = function buildTurnContext(results) {
16205
- var pageContext = resolvePageContext(results);
16430
+ var pageContext = buildPageContext(resolveContext(), results);
16206
16431
  if (!pageContext) {
16207
16432
  return undefined;
16208
16433
  }
@@ -16218,33 +16443,98 @@
16218
16443
  });
16219
16444
  return entries.length > 0 ? Object.fromEntries(entries) : undefined;
16220
16445
  };
16446
+ // `latestRenderOptions` may be the `init()` options, which carry no
16447
+ // `results` key at all, so the read has to be narrowed rather than
16448
+ // optional-chained.
16449
+ var getLatestResults = function getLatestResults() {
16450
+ var _latestRenderOptions_results;
16451
+ if (!latestRenderOptions || !('results' in latestRenderOptions)) {
16452
+ return null;
16453
+ }
16454
+ return (_latestRenderOptions_results = latestRenderOptions.results) !== null && _latestRenderOptions_results !== void 0 ? _latestRenderOptions_results : null;
16455
+ };
16221
16456
  var renderOutward = function renderOutward(renderOptions) {
16222
16457
  if (disposed) return;
16223
16458
  renderFn(_object_spread_props(_object_spread({}, getWidgetRenderState(renderOptions)), {
16224
16459
  instantSearchInstance: renderOptions.instantSearchInstance
16225
16460
  }), false);
16226
16461
  };
16462
+ // Copies an inner render's state into this widget's and re-renders on the
16463
+ // client.
16464
+ var adoptInnerState = function adoptInnerState(renderState) {
16465
+ error = renderState.error;
16466
+ if (renderState.error) {
16467
+ // A failed task (including a mid-stream `error` event) must not leave
16468
+ // any streamed partial visible.
16469
+ suggestions = [];
16470
+ } else if (renderState.isLoading || renderState.output !== undefined) {
16471
+ // Only adopt the inner output once a request is loading or has
16472
+ // produced one, so the initial no-op render doesn't clobber pills.
16473
+ suggestions = parseSuggestions(renderState.output);
16474
+ }
16475
+ isLoading = renderState.isLoading;
16476
+ if (!latestRenderOptions) return;
16477
+ renderOutward(latestRenderOptions);
16478
+ };
16227
16479
  var fetchAndRender = function fetchAndRender(results, renderOptions) {
16480
+ var _ref = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, _ref_force = _ref.force, force = _ref_force === void 0 ? false : _ref_force;
16481
+ var _buildPageContext;
16228
16482
  var _results_hits;
16229
16483
  if (disposed || !tasksState) return;
16484
+ var hadDroppedInnerRender = droppedInnerRender;
16230
16485
  refetchPending = false;
16231
- var hasContext = context !== undefined;
16232
- if (!hasContext && !(results === null || results === void 0 ? void 0 : (_results_hits = results.hits) === null || _results_hits === void 0 ? void 0 : _results_hits.length)) {
16486
+ droppedInnerRender = false;
16487
+ var resolvedContext = resolveContext();
16488
+ var input = (_buildPageContext = buildPageContext(resolvedContext, results)) !== null && _buildPageContext !== void 0 ? _buildPageContext : {};
16489
+ // Two ways there is nothing worth sending: no context for this fetch and
16490
+ // no hits to derive one from, or a context that resolved to something
16491
+ // empty. The first reads the resolved value rather than the option, so
16492
+ // `context: () => undefined` is gated exactly like an omitted `context`.
16493
+ // Sending an empty input spends a model call on no information.
16494
+ if (resolvedContext === undefined && !(results === null || results === void 0 ? void 0 : (_results_hits = results.hits) === null || _results_hits === void 0 ? void 0 : _results_hits.length) || Object.keys(input).length === 0) {
16233
16495
  tasksState.invalidate();
16234
16496
  suggestions = [];
16235
16497
  isLoading = false;
16498
+ // The output is gone, so the same payload must be allowed to rebuild it.
16499
+ lastSubmittedPayload = null;
16236
16500
  renderOutward(renderOptions);
16237
16501
  return;
16238
16502
  }
16239
- tasksState.submit(buildInput(results));
16503
+ var payload = taskPayloadKey(input);
16504
+ // A moved search state does not always mean a different question: with an
16505
+ // explicit `context` the payload ignores the results entirely, so a new
16506
+ // `queryID` or a new hit order produces a byte-identical request. Sending
16507
+ // it again spends a model call on an answer already on screen. Leave the
16508
+ // current suggestions alone and send nothing. `force` is the explicit
16509
+ // path (`refresh()`), which must always reach the network.
16510
+ if (!force && payload !== null && payload === lastSubmittedPayload) {
16511
+ // Nothing goes out, so nothing will render — but the state change that
16512
+ // scheduled this fetch also made `handleInnerRender` drop the render
16513
+ // that was carrying the previous request's result. Reconcile it here or
16514
+ // the widget keeps that request's `isLoading: true` with no
16515
+ // suggestions, and nothing later clears it: `refresh()` is blocked by
16516
+ // its own `isLoading` guard and an unchanged payload keeps skipping.
16517
+ if (hadDroppedInnerRender) {
16518
+ adoptInnerState(tasksState);
16519
+ }
16520
+ return;
16521
+ }
16522
+ lastSubmittedPayload = payload;
16523
+ tasksState.submit(input);
16240
16524
  };
16241
16525
  var refresh = function refresh() {
16242
16526
  if (isLoading) return;
16243
- var results = latestRenderOptions === null || latestRenderOptions === void 0 ? void 0 : latestRenderOptions.results;
16244
- if (!results || !latestRenderOptions) return;
16527
+ if (!latestRenderOptions) return;
16528
+ var results = getLatestResults();
16245
16529
  clearTimeout(debounceTimer);
16246
- lastStateSignature = getStateSignature(results);
16247
- fetchAndRender(results, latestRenderOptions);
16530
+ // Only meaningful with results: without them there is no signature for a
16531
+ // later automatic fetch to compare against.
16532
+ if (results) {
16533
+ lastStateSignature = getStateSignature(results);
16534
+ }
16535
+ fetchAndRender(results, latestRenderOptions, {
16536
+ force: true
16537
+ });
16248
16538
  };
16249
16539
  var getWidgetRenderState = function getWidgetRenderState(renderOptions) {
16250
16540
  var results = 'results' in renderOptions ? renderOptions.results : undefined;
@@ -16255,12 +16545,17 @@
16255
16545
  var chatRenderState = getChatRenderState(renderOptions);
16256
16546
  var isChatBusy$1 = chatRenderState ? !chatRenderState.sendMessage || isChatBusy(chatRenderState) : false;
16257
16547
  var send = sendToChat(renderOptions);
16548
+ // `sendToChat` is withheld only once the mount window has closed: a chat
16549
+ // widget further down a React tree is added after this widget's `init`,
16550
+ // so until `validateChat` runs its absence is not yet conclusive and
16551
+ // withholding the handler would make a valid setup look broken.
16552
+ var canSendToChat = Boolean(chatRenderState === null || chatRenderState === void 0 ? void 0 : chatRenderState.sendMessage) || !hasValidatedChat;
16258
16553
  return {
16259
16554
  suggestions: transformed,
16260
16555
  isLoading: isLoading,
16261
16556
  error: error,
16262
- onSuggestionClick: send,
16263
- sendToChat: send,
16557
+ onSuggestionClick: canSendToChat ? send : noop,
16558
+ sendToChat: canSendToChat ? send : undefined,
16264
16559
  refresh: refresh,
16265
16560
  isChatBusy: isChatBusy$1,
16266
16561
  widgetParams: widgetParams
@@ -16270,21 +16565,37 @@
16270
16565
  // resolve/error) into this widget's state and re-renders on the client.
16271
16566
  var handleInnerRender = function handleInnerRender(renderState) {
16272
16567
  tasksState = renderState;
16273
- if (refetchPending) return;
16274
- error = renderState.error;
16275
16568
  if (renderState.error) {
16276
- // A failed task (including a mid-stream `error` event) must not leave
16277
- // any streamed partial visible.
16278
- suggestions = [];
16279
- } else if (renderState.isLoading || renderState.output !== undefined) {
16280
- // Only adopt the inner output once a request is loading or has
16281
- // produced one, so the initial no-op render doesn't clobber pills.
16282
- suggestions = parseSuggestions(renderState.output);
16569
+ // Keep a failed payload retryable: without this the next automatic
16570
+ // attempt with the same payload would be skipped as a duplicate and
16571
+ // the error would have no way to clear. Set before the `refetchPending`
16572
+ // return so a failure that lands mid-refetch is not swallowed.
16573
+ lastSubmittedPayload = null;
16574
+ }
16575
+ if (refetchPending) {
16576
+ droppedInnerRender = true;
16577
+ return;
16283
16578
  }
16284
- isLoading = renderState.isLoading;
16285
- if (!latestRenderOptions) return;
16286
- renderOutward(latestRenderOptions);
16579
+ adoptInnerState(renderState);
16287
16580
  };
16581
+ // Deferred because a chat widget can be registered after this one: React
16582
+ // adds widgets in mount order, so a `chat` further down the tree only
16583
+ // lands after this widget's `init` has run. Until this closes the window,
16584
+ // `sendToChat` is handed out optimistically.
16585
+ var validateChat = defer(function(renderOptions) {
16586
+ var _getChatRenderState;
16587
+ if (hasValidatedChat) return;
16588
+ hasValidatedChat = true;
16589
+ if ((_getChatRenderState = getChatRenderState(renderOptions)) === null || _getChatRenderState === void 0 ? void 0 : _getChatRenderState.sendMessage) return;
16590
+ // A render may already have gone out with the optimistic `sendToChat`;
16591
+ // re-render so the widget layer sees the settled answer. The `init()`
16592
+ // options don't count: nothing has painted yet, so the next render
16593
+ // carries it — and a mount that never renders results shows no pills
16594
+ // to mislead anyone.
16595
+ if (latestRenderOptions && 'results' in latestRenderOptions) {
16596
+ renderOutward(latestRenderOptions);
16597
+ }
16598
+ });
16288
16599
  var tasksParams;
16289
16600
  if (agentId) {
16290
16601
  tasksParams = {
@@ -16307,12 +16618,37 @@
16307
16618
  var tasksWidget = connectTasks(handleInnerRender, noop)(tasksParams);
16308
16619
  return {
16309
16620
  $$type: 'ais.promptSuggestions',
16621
+ // Clicking a suggestion opens the chat, so this widget counts as an
16622
+ // entry point for `connectChat`'s trigger validation.
16623
+ opensChat: true,
16310
16624
  init: function init(initOptions) {
16311
16625
  var instantSearchInstance = initOptions.instantSearchInstance;
16312
16626
  tasksWidget.init(initOptions);
16627
+ // Set after the inner init so its initial no-op render is still
16628
+ // ignored, and before the first outward render so `refresh()` has a
16629
+ // render target even on a mount where `render()` never sees results.
16630
+ latestRenderOptions = initOptions;
16631
+ validateChat(initOptions);
16313
16632
  renderFn(_object_spread_props(_object_spread({}, getWidgetRenderState(initOptions)), {
16314
16633
  instantSearchInstance: instantSearchInstance
16315
16634
  }), true);
16635
+ // With an explicit `context` the payload never reads the results, so
16636
+ // waiting for a search is waiting on something the request does not
16637
+ // use — and a page that triggers no search (a `searchFunction` query
16638
+ // gate, or a mount made only for the widgets) would wait forever.
16639
+ // Fetch here instead, after the first render so the `isFirstRender`
16640
+ // one still arrives first.
16641
+ //
16642
+ // There are no results yet by definition, so "is there anything to
16643
+ // send" reduces to "did the context resolve to something". Checking it
16644
+ // here rather than letting `fetchAndRender` reject the call keeps init
16645
+ // out of the "nothing to send" branch, whose `invalidate()` would add
16646
+ // two outward renders to every mount that has no context — leaving the
16647
+ // auto-extracted path, the one that does need results, untouched.
16648
+ var initialContext = resolveContext();
16649
+ if (initialContext && Object.keys(initialContext).length > 0) {
16650
+ fetchAndRender(null, initOptions);
16651
+ }
16316
16652
  },
16317
16653
  render: function render(renderOptions) {
16318
16654
  var results = renderOptions.results, instantSearchInstance = renderOptions.instantSearchInstance;
@@ -16330,8 +16666,9 @@
16330
16666
  error = undefined;
16331
16667
  clearTimeout(debounceTimer);
16332
16668
  debounceTimer = setTimeout(function() {
16333
- if (latestRenderOptions === null || latestRenderOptions === void 0 ? void 0 : latestRenderOptions.results) {
16334
- fetchAndRender(latestRenderOptions.results, latestRenderOptions);
16669
+ var latestResults = getLatestResults();
16670
+ if (latestResults && latestRenderOptions) {
16671
+ fetchAndRender(latestResults, latestRenderOptions);
16335
16672
  }
16336
16673
  }, DEBOUNCE_MS);
16337
16674
  }
@@ -16342,6 +16679,7 @@
16342
16679
  dispose: function dispose(disposeOptions) {
16343
16680
  disposed = true;
16344
16681
  clearTimeout(debounceTimer);
16682
+ validateChat.cancel();
16345
16683
  tasksWidget.dispose(disposeOptions);
16346
16684
  unmountFn();
16347
16685
  },