unique-sdk 2026.50.0.dev3__tar.gz → 2026.50.0.dev5__tar.gz

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 (93) hide show
  1. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/PKG-INFO +1 -1
  2. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/pyproject.toml +1 -1
  3. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_message.py +41 -0
  4. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_web_search.py +8 -0
  5. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/subagent.py +108 -18
  6. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/web_search.py +38 -5
  7. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/chat_in_space.py +179 -3
  8. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/README.md +0 -0
  9. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/__init__.py +0 -0
  10. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_api_requestor.py +0 -0
  11. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_api_resource.py +0 -0
  12. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_api_version.py +0 -0
  13. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_error.py +0 -0
  14. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_http_client.py +0 -0
  15. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_list_object.py +0 -0
  16. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_object_classes.py +0 -0
  17. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_request_options.py +0 -0
  18. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_unique_object.py +0 -0
  19. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_unique_ql.py +0 -0
  20. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_unique_response.py +0 -0
  21. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_util.py +0 -0
  22. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_version.py +0 -0
  23. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/_webhook.py +0 -0
  24. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/__init__.py +0 -0
  25. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_acronyms.py +0 -0
  26. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_agentic_table.py +0 -0
  27. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_analytics_order.py +0 -0
  28. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_benchmarking.py +0 -0
  29. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_briefing.py +0 -0
  30. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_chat_completion.py +0 -0
  31. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_content.py +0 -0
  32. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_context_memory.py +0 -0
  33. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_elicitation.py +0 -0
  34. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_embedding.py +0 -0
  35. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_event.py +0 -0
  36. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_folder.py +0 -0
  37. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_group.py +0 -0
  38. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_integrated.py +0 -0
  39. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_llm_models.py +0 -0
  40. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_mcp.py +0 -0
  41. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_message_assessment.py +0 -0
  42. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_message_execution.py +0 -0
  43. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_message_log.py +0 -0
  44. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_message_tool.py +0 -0
  45. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_module.py +0 -0
  46. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_project_memory.py +0 -0
  47. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_scheduled_task.py +0 -0
  48. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_search.py +0 -0
  49. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_search_string.py +0 -0
  50. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_short_term_memory.py +0 -0
  51. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_space.py +0 -0
  52. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/api_resources/_user.py +0 -0
  53. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/__init__.py +0 -0
  54. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/__main__.py +0 -0
  55. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/cli.py +0 -0
  56. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/__init__.py +0 -0
  57. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/_citation_manifest.py +0 -0
  58. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/agentic_table.py +0 -0
  59. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/agentic_table_write.py +0 -0
  60. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/browser.py +0 -0
  61. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/cite_file.py +0 -0
  62. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/elicitation.py +0 -0
  63. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/files.py +0 -0
  64. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/folders.py +0 -0
  65. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/mcp.py +0 -0
  66. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/navigation.py +0 -0
  67. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/read.py +0 -0
  68. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/scheduled_tasks.py +0 -0
  69. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/search.py +0 -0
  70. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/commands/web_search_config.py +0 -0
  71. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/config.py +0 -0
  72. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/formatting.py +0 -0
  73. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/identity.py +0 -0
  74. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/metadata_filter.py +0 -0
  75. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/paths.py +0 -0
  76. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/shell.py +0 -0
  77. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-agentic-table/SKILL.md +0 -0
  78. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-elicitation/SKILL.md +0 -0
  79. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-file-management/SKILL.md +0 -0
  80. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-mcp/SKILL.md +0 -0
  81. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-scheduled-tasks/SKILL.md +0 -0
  82. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-search/SKILL.md +0 -0
  83. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-subagent/SKILL.md +0 -0
  84. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-uploaded-search/SKILL.md +0 -0
  85. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/skills/unique-cli-web-search/SKILL.md +0 -0
  86. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/state.py +0 -0
  87. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/cli/workspace.py +0 -0
  88. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/analytics_order_run.py +0 -0
  89. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/benchmarking_run.py +0 -0
  90. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/chat_history.py +0 -0
  91. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/file_io.py +0 -0
  92. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/sources.py +0 -0
  93. {unique_sdk-2026.50.0.dev3 → unique_sdk-2026.50.0.dev5}/unique_sdk/utils/token.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: unique-sdk
3
- Version: 2026.50.0.dev3
3
+ Version: 2026.50.0.dev5
4
4
  Summary:
5
5
  Author: Martin Fadler, Konstantin Krauss, Andreas Hauri
6
6
  Author-email: Martin Fadler <martin.fadler@unique.ch>, Konstantin Krauss <konstantin@unique.ch>, Andreas Hauri <andreas@unique.ch>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "unique_sdk"
3
- version = "2026.50.0.dev3"
3
+ version = "2026.50.0.dev5"
4
4
  description = ""
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -71,6 +71,9 @@ class Message(APIResource["Message"]):
71
71
  class MarkTurnSystemInterruptedParams(RequestOptions):
72
72
  chatId: str
73
73
 
74
+ class StopParams(RequestOptions):
75
+ chatId: str
76
+
74
77
  class DeleteParams(RequestOptions):
75
78
  chatId: str
76
79
 
@@ -342,6 +345,44 @@ class Message(APIResource["Message"]):
342
345
  ),
343
346
  )
344
347
 
348
+ @classmethod
349
+ def stop(
350
+ cls,
351
+ user_id: str,
352
+ company_id: str,
353
+ id: str,
354
+ **params: Unpack["Message.StopParams"],
355
+ ) -> "Message":
356
+ """
357
+ Stops the running assistant turn that the given message belongs to.
358
+
359
+ ``id`` may be the USER message that started the turn or one of its replies.
360
+ """
361
+ url = "%s/%s/stop" % (cls.class_url(), quote_plus(id))
362
+ return cast(
363
+ "Message",
364
+ cls._static_request("post", url, user_id, company_id, params),
365
+ )
366
+
367
+ @classmethod
368
+ async def stop_async(
369
+ cls,
370
+ user_id: str,
371
+ company_id: str,
372
+ id: str,
373
+ **params: Unpack["Message.StopParams"],
374
+ ) -> "Message":
375
+ """
376
+ Stops the running assistant turn that the given message belongs to.
377
+
378
+ ``id`` may be the USER message that started the turn or one of its replies.
379
+ """
380
+ url = "%s/%s/stop" % (cls.class_url(), quote_plus(id))
381
+ return cast(
382
+ "Message",
383
+ await cls._static_request_async("post", url, user_id, company_id, params),
384
+ )
385
+
345
386
  @classmethod
346
387
  def _cls_delete(
347
388
  cls,
@@ -62,6 +62,10 @@ class WebSearch(APIResource["WebSearch"]):
62
62
  # server-side for this call. Omit for callers not acting on
63
63
  # behalf of a specific chat (unchanged legacy behavior).
64
64
  chatId: NotRequired[str | None]
65
+ # Optional: the assistant message this call serves, for grouping
66
+ # the call's activity records per turn. Send it only to a backend
67
+ # that accepts it; older public APIs reject unknown body fields.
68
+ messageId: NotRequired[str | None]
65
69
 
66
70
  # Response envelope.
67
71
  engine: str
@@ -138,6 +142,10 @@ class WebCrawl(APIResource["WebCrawl"]):
138
142
  # server-side for this call. Omit for callers not acting on
139
143
  # behalf of a specific chat (unchanged legacy behavior).
140
144
  chatId: NotRequired[str | None]
145
+ # Optional: the assistant message this call serves, for grouping
146
+ # the call's activity records per turn. Send it only to a backend
147
+ # that accepts it; older public APIs reject unknown body fields.
148
+ messageId: NotRequired[str | None]
141
149
 
142
150
  # Response envelope.
143
151
  crawler: str
@@ -5,13 +5,18 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import json
7
7
  import os
8
+ import signal
9
+ from collections.abc import Callable
8
10
  from pathlib import Path
9
11
  from typing import Any, Literal, TypedDict, cast
10
12
 
11
13
  from unique_sdk._error import APIError
12
14
  from unique_sdk.api_resources._space import Space
13
15
  from unique_sdk.cli.state import ShellState
14
- from unique_sdk.utils.chat_in_space import send_message_and_wait_for_completion
16
+ from unique_sdk.utils.chat_in_space import (
17
+ MessageWaitTimeoutError,
18
+ send_message_and_wait_for_completion,
19
+ )
15
20
 
16
21
  CONFIG_FILENAME = ".unique-subagents.json"
17
22
  STATE_FILENAME = ".unique-subagent-chats.json"
@@ -196,6 +201,7 @@ async def _send_to_subagent(
196
201
  parent_chat_id: str | None,
197
202
  parent_message_id: str | None,
198
203
  parent_assistant_id: str | None,
204
+ on_chat_created: Callable[[str], None],
199
205
  ) -> Space.Message:
200
206
  assistant_id = _get_str(
201
207
  subagent,
@@ -204,6 +210,7 @@ async def _send_to_subagent(
204
210
  required=True,
205
211
  )
206
212
  assert assistant_id is not None
213
+ _cancel_wait_on_sigterm()
207
214
 
208
215
  correlation: Space.Correlation | None = None
209
216
  if parent_chat_id and parent_message_id and parent_assistant_id:
@@ -213,6 +220,9 @@ async def _send_to_subagent(
213
220
  "parentAssistantId": parent_assistant_id,
214
221
  }
215
222
 
223
+ async def _on_message_created(posted: Space.Message) -> None:
224
+ on_chat_created(posted["chatId"])
225
+
216
226
  return await send_message_and_wait_for_completion(
217
227
  user_id=state.config.user_id,
218
228
  company_id=state.config.company_id,
@@ -234,6 +244,56 @@ async def _send_to_subagent(
234
244
  ),
235
245
  stop_condition=_get_stop_condition(subagent),
236
246
  correlation=correlation,
247
+ stop_on_abandon=True,
248
+ on_message_created=_on_message_created,
249
+ )
250
+
251
+
252
+ def _cancel_wait_on_sigterm() -> None:
253
+ """Turn SIGTERM into a cancellation, so the wait stops the subagent turn first."""
254
+ task = asyncio.current_task()
255
+ if task is None:
256
+ return
257
+ try:
258
+ asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, task.cancel)
259
+ except (NotImplementedError, RuntimeError, ValueError):
260
+ # Windows event loops and non-main threads cannot install signal handlers.
261
+ return
262
+
263
+
264
+ def _remember_chat(
265
+ *,
266
+ state_path: Path,
267
+ chat_state: dict[str, str],
268
+ tool_name: str,
269
+ chat_id: str,
270
+ ) -> bool:
271
+ chat_state = chat_state or _load_chat_state(state_path)
272
+ chat_state[tool_name] = chat_id
273
+ try:
274
+ _save_chat_state(state_path, chat_state)
275
+ except OSError:
276
+ return False
277
+ return True
278
+
279
+
280
+ def _timeout_note(*, display_name: str, timeout: MessageWaitTimeoutError) -> str:
281
+ if timeout.turn_stopped:
282
+ return f"{display_name} did not answer in time. Its turn was stopped."
283
+ return (
284
+ f"{display_name} did not answer in time and could not be stopped. "
285
+ f"It is still running in chat {timeout.chat_id}. "
286
+ "Do not send the same task again."
287
+ )
288
+
289
+
290
+ def _terminated_note(*, display_name: str, chat_id: str | None) -> str:
291
+ note = f"{SUBAGENT_ERROR_PREFIX} terminated while waiting for {display_name}."
292
+ if chat_id is None:
293
+ return note
294
+ return (
295
+ f"{note} Its turn in chat {chat_id} was asked to stop. "
296
+ "Do not send the same task again before checking that chat."
237
297
  )
238
298
 
239
299
 
@@ -267,26 +327,56 @@ def cmd_subagent(
267
327
  chat_state = _load_chat_state(state_path)
268
328
  chat_id = chat_state.get(tool_name)
269
329
 
270
- response = asyncio.run(
271
- _send_to_subagent(
272
- state=state,
273
- subagent=subagent,
274
- message=message,
275
- chat_id=chat_id,
276
- parent_chat_id=parent_chat_id,
277
- parent_message_id=parent_message_id,
278
- parent_assistant_id=parent_assistant_id,
330
+ remembers_chat = configured_chat_id is None and reuse_chat
331
+ created_chat_ids: list[str] = []
332
+ saved_chat_ids: set[str] = set()
333
+
334
+ def _on_chat_created(created_chat_id: str) -> None:
335
+ created_chat_ids.append(created_chat_id)
336
+ if remembers_chat and _remember_chat(
337
+ state_path=state_path,
338
+ chat_state=chat_state,
339
+ tool_name=tool_name,
340
+ chat_id=created_chat_id,
341
+ ):
342
+ saved_chat_ids.add(created_chat_id)
343
+
344
+ try:
345
+ response = asyncio.run(
346
+ _send_to_subagent(
347
+ state=state,
348
+ subagent=subagent,
349
+ message=message,
350
+ chat_id=chat_id,
351
+ parent_chat_id=parent_chat_id,
352
+ parent_message_id=parent_message_id,
353
+ parent_assistant_id=parent_assistant_id,
354
+ on_chat_created=_on_chat_created,
355
+ )
279
356
  )
280
- )
357
+ except MessageWaitTimeoutError as timeout:
358
+ note = _timeout_note(display_name=display_name, timeout=timeout)
359
+ return f"{SUBAGENT_ERROR_PREFIX} {note}"
360
+ except asyncio.CancelledError:
361
+ # The process is ending, so the note cannot be returned. It goes
362
+ # to stdout, where the caller reads the command's output.
363
+ print(
364
+ _terminated_note(
365
+ display_name=display_name,
366
+ chat_id=created_chat_ids[0] if created_chat_ids else None,
367
+ ),
368
+ flush=True,
369
+ )
370
+ raise SystemExit(128 + signal.SIGTERM) from None
281
371
 
282
372
  response_chat_id = response.get("chatId")
283
- if configured_chat_id is None and reuse_chat and response_chat_id:
284
- chat_state = chat_state or _load_chat_state(state_path)
285
- chat_state[tool_name] = response_chat_id
286
- try:
287
- _save_chat_state(state_path, chat_state)
288
- except OSError:
289
- pass
373
+ if remembers_chat and response_chat_id not in (None, *saved_chat_ids):
374
+ _remember_chat(
375
+ state_path=state_path,
376
+ chat_state=chat_state,
377
+ tool_name=tool_name,
378
+ chat_id=response_chat_id,
379
+ )
290
380
 
291
381
  return _format_response(
292
382
  tool_name=tool_name,
@@ -42,7 +42,7 @@ _LOGGER = logging.getLogger(__name__)
42
42
 
43
43
  DEFAULT_PARALLEL = 10
44
44
  MAX_SEARCH_QUERIES = 8
45
- SEARCH_CONCURRENCY = 4
45
+ SEARCH_CONCURRENCY = MAX_SEARCH_QUERIES
46
46
  _SNIPPET_PREVIEW_LIMIT = 200
47
47
  _CONTENT_PREVIEW_LIMIT = 500
48
48
  _WEB_REFS_LOG_RELATIVE_PATH = Path(".unique") / "web-refs.jsonl"
@@ -365,6 +365,9 @@ def cmd_web_search(
365
365
  output_json: bool = False,
366
366
  config_path: str | None = None,
367
367
  chat_id: str | None = None,
368
+ *,
369
+ refs_log_path: Path | None = None,
370
+ message_id: str | None = None,
368
371
  ) -> str:
369
372
  """Run a web search via the public API.
370
373
 
@@ -391,6 +394,10 @@ def cmd_web_search(
391
394
  human-friendly table.
392
395
  chat_id: Optional chat id this call is made on behalf of. When
393
396
  set, the space's Web Search toggle is enforced server-side.
397
+ refs_log_path: The per-turn web citation manifest. When ``None``,
398
+ it resolves from the workspace root.
399
+ message_id: Optional assistant message this call serves; sent as
400
+ ``messageId`` only when set.
394
401
  """
395
402
  options = _search_request_options(
396
403
  fetch_size=fetch_size,
@@ -399,6 +406,7 @@ def cmd_web_search(
399
406
  crawler_config_raw=crawler_config_raw,
400
407
  config_path=config_path,
401
408
  chat_id=chat_id,
409
+ message_id=message_id,
402
410
  )
403
411
  if isinstance(options, str):
404
412
  return options
@@ -408,7 +416,9 @@ def cmd_web_search(
408
416
  return payload
409
417
 
410
418
  try:
411
- payload = _annotate_web_results_for_citations(payload)
419
+ payload = _annotate_web_results_for_citations(
420
+ payload, refs_log_path=refs_log_path
421
+ )
412
422
  except UnsafeRefsLogPathError as exc:
413
423
  return f"{WEB_SEARCH_ERROR_PREFIX} {exc}"
414
424
  if output_json:
@@ -424,6 +434,7 @@ def _search_request_options(
424
434
  crawler_config_raw: str | None,
425
435
  config_path: str | None,
426
436
  chat_id: str | None,
437
+ message_id: str | None = None,
427
438
  ) -> dict[str, Any] | str:
428
439
  """Build the request fields shared by every query, or return an error string."""
429
440
  file_overrides = _load_file_overrides(config_path)
@@ -454,6 +465,8 @@ def _search_request_options(
454
465
  options["crawlerConfig"] = crawler_override
455
466
  if chat_id:
456
467
  options["chatId"] = chat_id
468
+ if message_id:
469
+ options["messageId"] = message_id
457
470
  return options
458
471
 
459
472
 
@@ -485,6 +498,9 @@ def cmd_web_search_many(
485
498
  output_json: bool = False,
486
499
  config_path: str | None = None,
487
500
  chat_id: str | None = None,
501
+ *,
502
+ refs_log_path: Path | None = None,
503
+ message_id: str | None = None,
488
504
  ) -> str:
489
505
  """Run several web searches in one call and return one block per query.
490
506
 
@@ -497,6 +513,9 @@ def cmd_web_search_many(
497
513
  output is a ``web-search:`` error only when every query failed.
498
514
  ``output_json`` returns a list with one entry per query: the usual
499
515
  ``{engine, query, results}`` object, or ``{query, error}`` on failure.
516
+ ``refs_log_path`` is the per-turn web citation manifest; ``None``
517
+ resolves it from the workspace root. ``message_id`` is sent as
518
+ ``messageId`` only when set.
500
519
  """
501
520
  if not queries:
502
521
  return f"{WEB_SEARCH_ERROR_PREFIX} no queries provided."
@@ -514,6 +533,7 @@ def cmd_web_search_many(
514
533
  crawler_config_raw=crawler_config_raw,
515
534
  config_path=config_path,
516
535
  chat_id=chat_id,
536
+ message_id=message_id,
517
537
  )
518
538
  if isinstance(options, str):
519
539
  return options
@@ -533,7 +553,9 @@ def cmd_web_search_many(
533
553
  outcomes.append(item)
534
554
  continue
535
555
  try:
536
- outcomes.append(_annotate_web_results_for_citations(item))
556
+ outcomes.append(
557
+ _annotate_web_results_for_citations(item, refs_log_path=refs_log_path)
558
+ )
537
559
  except UnsafeRefsLogPathError as exc:
538
560
  return f"{WEB_SEARCH_ERROR_PREFIX} {exc}"
539
561
 
@@ -594,6 +616,9 @@ def cmd_web_crawl(
594
616
  output_json: bool = False,
595
617
  config_path: str | None = None,
596
618
  chat_id: str | None = None,
619
+ *,
620
+ refs_log_path: Path | None = None,
621
+ message_id: str | None = None,
597
622
  ) -> str:
598
623
  """Crawl a list of URLs via the public API.
599
624
 
@@ -612,6 +637,10 @@ def cmd_web_crawl(
612
637
  human-friendly table.
613
638
  chat_id: Optional chat id this call is made on behalf of. When
614
639
  set, the space's Web Search toggle is enforced server-side.
640
+ refs_log_path: The per-turn web citation manifest. When ``None``,
641
+ it resolves from the workspace root.
642
+ message_id: Optional assistant message this call serves; sent as
643
+ ``messageId`` only when set.
615
644
  """
616
645
  if not urls:
617
646
  return f"{WEB_CRAWL_ERROR_PREFIX} no URLs provided. Pass URLs as arguments or use --stdin."
@@ -636,6 +665,8 @@ def cmd_web_crawl(
636
665
  params["crawlerConfig"] = crawler_override
637
666
  if chat_id:
638
667
  params["chatId"] = chat_id
668
+ if message_id:
669
+ params["messageId"] = message_id
639
670
 
640
671
  try:
641
672
  resource = unique_sdk.WebCrawl.crawl(
@@ -643,11 +674,13 @@ def cmd_web_crawl(
643
674
  company_id=state.config.company_id,
644
675
  **params,
645
676
  )
646
- except (ValueError, unique_sdk.APIError) as exc:
677
+ except (ValueError, unique_sdk.UniqueError) as exc:
647
678
  return f"{WEB_CRAWL_ERROR_PREFIX} {exc}"
648
679
 
649
680
  try:
650
- payload = _annotate_web_results_for_citations(_payload_from_resource(resource))
681
+ payload = _annotate_web_results_for_citations(
682
+ _payload_from_resource(resource), refs_log_path=refs_log_path
683
+ )
651
684
  except UnsafeRefsLogPathError as exc:
652
685
  return f"{WEB_CRAWL_ERROR_PREFIX} {exc}"
653
686
  if output_json:
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import asyncio
4
+ import logging
4
5
  import warnings
5
6
  from collections.abc import Awaitable, Callable, Sequence
6
7
  from typing import Any, Literal
@@ -12,6 +13,27 @@ from unique_sdk.utils.file_io import (
12
13
  wait_for_ingestion_completion as _wait_for_ingestion_completion,
13
14
  )
14
15
 
16
+ _log = logging.getLogger(__name__)
17
+
18
+ _ABANDON_STOP_TIMEOUT_S = 5.0
19
+
20
+ # asyncio holds tasks weakly. A stop that outlives its cancelled caller needs a
21
+ # strong reference until it finishes.
22
+ _abandon_stops: set[asyncio.Task[bool]] = set()
23
+
24
+
25
+ class MessageWaitTimeoutError(TimeoutError):
26
+ """The assistant turn did not finish within ``max_wait``.
27
+
28
+ ``turn_stopped`` is False when no stop was requested or the stop failed.
29
+ """
30
+
31
+ def __init__(self, *, chat_id: str, message_id: str, turn_stopped: bool) -> None:
32
+ super().__init__("Timed out waiting for prompt completion.")
33
+ self.chat_id = chat_id
34
+ self.message_id = message_id
35
+ self.turn_stopped = turn_stopped
36
+
15
37
 
16
38
  def get_message_invocations(message: Space.Message) -> list[dict[str, Any]]:
17
39
  """Per-LLM-invocation stats for a completed Space message, read from
@@ -41,6 +63,8 @@ async def send_message_and_wait_for_completion(
41
63
  language_model: str | None = None,
42
64
  on_message_update: Callable[[Space.Message], Awaitable[None]] | None = None,
43
65
  wait_for_invocations: bool = False,
66
+ stop_on_abandon: bool = False,
67
+ on_message_created: Callable[[Space.Message], Awaitable[None]] | None = None,
44
68
  ) -> Space.Message:
45
69
  """
46
70
  Sends a prompt asynchronously and polls for completion. (until stoppedStreamingAt is not None)
@@ -77,9 +101,17 @@ async def send_message_and_wait_for_completion(
77
101
  message changes while waiting for completion.
78
102
  wait_for_invocations: When True, briefly wait for the orchestrator's final
79
103
  ``debugInfo.llm_invocations`` write after the visible response completes.
104
+ stop_on_abandon: When True, stop the assistant turn if the wait ends without
105
+ an answer. See ``wait_for_message_completion``.
106
+ on_message_created: Optional async callback called once with the posted USER
107
+ message, before the wait starts. Its ``chatId`` and ``id`` identify the
108
+ turn, for example to stop it with ``Message.stop_async``.
80
109
 
81
110
  Returns:
82
111
  The completed Space.Message.
112
+
113
+ Raises:
114
+ MessageWaitTimeoutError: The turn did not finish within ``max_wait``.
83
115
  """
84
116
  create_message_params: Space.CreateMessageParams = {
85
117
  "assistantId": assistant_id,
@@ -101,9 +133,115 @@ async def send_message_and_wait_for_completion(
101
133
  company_id=company_id,
102
134
  **create_message_params,
103
135
  )
104
- chat_id = response.get("chatId")
105
- message_id = response.get("id")
136
+ if on_message_created is not None:
137
+ try:
138
+ await on_message_created(response)
139
+ except BaseException:
140
+ if stop_on_abandon:
141
+ _ = await _stop_turn_despite_cancellation(
142
+ user_id=user_id,
143
+ company_id=company_id,
144
+ chat_id=response["chatId"],
145
+ message_id=response["id"],
146
+ )
147
+ raise
148
+ return await wait_for_message_completion(
149
+ user_id=user_id,
150
+ company_id=company_id,
151
+ chat_id=response["chatId"],
152
+ message_id=response["id"],
153
+ poll_interval=poll_interval,
154
+ max_wait=max_wait,
155
+ stop_condition=stop_condition,
156
+ on_message_update=on_message_update,
157
+ wait_for_invocations=wait_for_invocations,
158
+ stop_on_abandon=stop_on_abandon,
159
+ )
160
+
161
+
162
+ async def wait_for_message_completion(
163
+ user_id: str,
164
+ company_id: str,
165
+ chat_id: str,
166
+ message_id: str,
167
+ poll_interval: float = 1.0,
168
+ max_wait: float = 60.0,
169
+ stop_condition: Literal["stoppedStreamingAt", "completedAt"] = "stoppedStreamingAt",
170
+ on_message_update: Callable[[Space.Message], Awaitable[None]] | None = None,
171
+ wait_for_invocations: bool = False,
172
+ stop_on_abandon: bool = False,
173
+ ) -> Space.Message:
174
+ """
175
+ Polls a chat until the assistant turn started by an already posted message finishes.
176
+
177
+ Args:
178
+ user_id: The user ID.
179
+ company_id: The company ID.
180
+ chat_id: The chat the message was posted to.
181
+ message_id: The ID of the posted USER message that started the turn.
182
+ poll_interval: Seconds between polls.
183
+ max_wait: Maximum seconds to wait for completion.
184
+ stop_condition: See ``send_message_and_wait_for_completion``.
185
+ on_message_update: See ``send_message_and_wait_for_completion``.
186
+ wait_for_invocations: See ``send_message_and_wait_for_completion``.
187
+ stop_on_abandon: When True, stop the assistant turn if this wait ends without
188
+ an answer: at ``max_wait``, on cancellation, or on an error.
189
+
190
+ Returns:
191
+ The completed Space.Message.
192
+
193
+ Raises:
194
+ MessageWaitTimeoutError: The turn did not finish within ``max_wait``. It is a
195
+ ``TimeoutError`` and says whether the turn was stopped.
196
+ """
197
+ try:
198
+ answer = await _poll_for_completion(
199
+ user_id=user_id,
200
+ company_id=company_id,
201
+ chat_id=chat_id,
202
+ message_id=message_id,
203
+ poll_interval=poll_interval,
204
+ max_wait=max_wait,
205
+ stop_condition=stop_condition,
206
+ on_message_update=on_message_update,
207
+ wait_for_invocations=wait_for_invocations,
208
+ )
209
+ except BaseException:
210
+ if stop_on_abandon:
211
+ _ = await _stop_turn_despite_cancellation(
212
+ user_id=user_id,
213
+ company_id=company_id,
214
+ chat_id=chat_id,
215
+ message_id=message_id,
216
+ )
217
+ raise
218
+ if answer is not None:
219
+ return answer
220
+
221
+ turn_stopped = stop_on_abandon and await _stop_turn_despite_cancellation(
222
+ user_id=user_id,
223
+ company_id=company_id,
224
+ chat_id=chat_id,
225
+ message_id=message_id,
226
+ )
227
+ raise MessageWaitTimeoutError(
228
+ chat_id=chat_id, message_id=message_id, turn_stopped=turn_stopped
229
+ )
230
+
106
231
 
232
+ async def _poll_for_completion(
233
+ *,
234
+ user_id: str,
235
+ company_id: str,
236
+ chat_id: str,
237
+ message_id: str,
238
+ poll_interval: float,
239
+ max_wait: float,
240
+ stop_condition: Literal["stoppedStreamingAt", "completedAt"],
241
+ on_message_update: Callable[[Space.Message], Awaitable[None]] | None,
242
+ wait_for_invocations: bool,
243
+ ) -> Space.Message | None:
244
+ """Return the finished message, or None when ``max_wait`` ran out."""
107
245
  max_attempts = int(max_wait // poll_interval)
108
246
  # The final up-to-3 polls spent waiting for `llm_invocations_complete`
109
247
  # happen after the stop condition is already met, so they must not eat
@@ -155,7 +293,45 @@ async def send_message_and_wait_for_completion(
155
293
  return answer
156
294
  await asyncio.sleep(poll_interval)
157
295
 
158
- raise TimeoutError("Timed out waiting for prompt completion.")
296
+ return None
297
+
298
+
299
+ async def _stop_turn(
300
+ *, user_id: str, company_id: str, chat_id: str, message_id: str
301
+ ) -> bool:
302
+ """Stop the turn. Return False when the stop failed or took too long."""
303
+ try:
304
+ async with asyncio.timeout(_ABANDON_STOP_TIMEOUT_S):
305
+ await Message.stop_async(user_id, company_id, message_id, chatId=chat_id)
306
+ except Exception as exc:
307
+ _log.warning("Could not stop the abandoned turn: %s", type(exc).__name__)
308
+ return False
309
+ return True
310
+
311
+
312
+ async def _stop_turn_despite_cancellation(
313
+ *, user_id: str, company_id: str, chat_id: str, message_id: str
314
+ ) -> bool:
315
+ """Stop the turn. Wait for the stop to settle, even when cancelled."""
316
+ stop = asyncio.ensure_future(
317
+ _stop_turn(
318
+ user_id=user_id,
319
+ company_id=company_id,
320
+ chat_id=chat_id,
321
+ message_id=message_id,
322
+ )
323
+ )
324
+ _abandon_stops.add(stop)
325
+ stop.add_done_callback(_abandon_stops.discard)
326
+ cancelled = False
327
+ while not stop.done():
328
+ try:
329
+ _ = await asyncio.shield(stop)
330
+ except asyncio.CancelledError:
331
+ cancelled = True
332
+ if cancelled:
333
+ raise asyncio.CancelledError
334
+ return stop.result()
159
335
 
160
336
 
161
337
  async def chat_against_file(