feat(update): integrate managed installs and recoverable in-app updates (#6168)
Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback. Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers. This code integration does not publish packages, enable signing or advance the public update channel. Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
76da55994b
commit
fbb61a373f
216 files changed
+27948
-1084
No files matched your search
+101
-68
@@ -65,6 +65,7 @@ from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import source_from_request
|
||||
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
|
||||
from nanobot.providers.factory import ProviderSnapshot
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_HISTORY_META,
|
||||
RUNTIME_CONTEXT_MESSAGE_META,
|
||||
@@ -970,13 +971,14 @@ class AgentLoop:
|
||||
|
||||
async def discard_session(self, key: str) -> None:
|
||||
"""Stop active work for *key* and forget its cached session."""
|
||||
self._discarding_sessions.add(key)
|
||||
try:
|
||||
await self.sessions.state.discard(key)
|
||||
await self._cancel_active_tasks(key)
|
||||
finally:
|
||||
self.discard_session_file_state(key)
|
||||
self._discarding_sessions.discard(key)
|
||||
with self.bus.admission.activity():
|
||||
self._discarding_sessions.add(key)
|
||||
try:
|
||||
await self.sessions.state.discard(key)
|
||||
await self._cancel_active_tasks(key)
|
||||
finally:
|
||||
self.discard_session_file_state(key)
|
||||
self._discarding_sessions.discard(key)
|
||||
|
||||
def discard_session_file_state(self, key: str) -> None:
|
||||
"""Forget ephemeral file-read state for a reset or removed session."""
|
||||
@@ -1393,16 +1395,19 @@ class AgentLoop:
|
||||
|
||||
async def _check_expired_sessions_if_due(self) -> None:
|
||||
"""Scan idle sessions without blocking the event loop."""
|
||||
if self.bus.admission.paused:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now < self._next_idle_compact_check_at:
|
||||
return
|
||||
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
|
||||
try:
|
||||
await self.auto_compact.check_expired(
|
||||
self.schedule_background,
|
||||
self.runtime_for_session,
|
||||
active_session_keys=self._pending_queues.keys(),
|
||||
)
|
||||
with self.bus.admission.activity():
|
||||
await self.auto_compact.check_expired(
|
||||
self.schedule_background,
|
||||
self.runtime_for_session,
|
||||
active_session_keys=self._pending_queues.keys(),
|
||||
)
|
||||
except SessionOperationQueueFullError:
|
||||
logger.debug("Skipping idle archival while session storage is busy")
|
||||
|
||||
@@ -1414,7 +1419,10 @@ class AgentLoop:
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
|
||||
# Keep dequeue and admission in this task. wait_for would
|
||||
# dequeue in another task, leaving a false-idle handoff gap.
|
||||
async with asyncio.timeout(1.0):
|
||||
msg = await self.bus.consume_inbound()
|
||||
except asyncio.TimeoutError:
|
||||
await self._check_expired_sessions_if_due()
|
||||
continue
|
||||
@@ -1431,14 +1439,15 @@ class AgentLoop:
|
||||
logger.warning("Error consuming inbound message: {}, continuing...", e)
|
||||
continue
|
||||
|
||||
try:
|
||||
await self._dispatch_inbound(msg)
|
||||
except (SessionOperationQueueFullError, SessionConflictError) as exc:
|
||||
key = self._effective_session_key(msg)
|
||||
logger.warning("Session input rejected for {}: {}", key, exc)
|
||||
if msg.is_user_input:
|
||||
delivery = self.turn_delivery_factory.unrouted(msg, key)
|
||||
await delivery.fail(publish_completion=key not in self._pending_queues)
|
||||
with self.bus.admission.activity():
|
||||
try:
|
||||
await self._dispatch_inbound(msg)
|
||||
except (SessionOperationQueueFullError, SessionConflictError) as exc:
|
||||
key = self._effective_session_key(msg)
|
||||
logger.warning("Session input rejected for {}: {}", key, exc)
|
||||
if msg.is_user_input:
|
||||
delivery = self.turn_delivery_factory.unrouted(msg, key)
|
||||
await delivery.fail(publish_completion=key not in self._pending_queues)
|
||||
finally:
|
||||
await self.aclose()
|
||||
|
||||
@@ -1491,6 +1500,23 @@ class AgentLoop:
|
||||
return
|
||||
await self._enqueue_session_message(routed_msg)
|
||||
|
||||
def maintenance(self) -> AbstractContextManager[None]:
|
||||
"""Close task intake only when this runtime's accepted work is finished.
|
||||
|
||||
The gateway shares the bus gate with cron and local trigger intake.
|
||||
This does not stop other processes or channel/configuration writes;
|
||||
those must be shut down before an updater takes a data backup.
|
||||
"""
|
||||
return self.bus.admission.pause_if_idle(self._has_pending_work)
|
||||
|
||||
def _has_pending_work(self) -> bool:
|
||||
return bool(
|
||||
self.bus.inbound_size or self._pending_queues or self._deferred_automation_turns
|
||||
or self.bus.has_pending_events or self._active_tasks or self._background_tasks
|
||||
or self._close_lock.locked()
|
||||
or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work
|
||||
)
|
||||
|
||||
def preserve_inflight_turns_on_shutdown(self) -> None:
|
||||
"""Keep durable checkpoints when the owning gateway exits.
|
||||
|
||||
@@ -1523,6 +1549,7 @@ class AgentLoop:
|
||||
|
||||
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
|
||||
"""Admit session work without waiting for its execution or result."""
|
||||
self.bus.admission.check()
|
||||
session_key = self._effective_session_key(msg)
|
||||
if not self.subagents.accepts_result(msg, session_key):
|
||||
return
|
||||
@@ -1808,6 +1835,11 @@ class AgentLoop:
|
||||
|
||||
def schedule_background(self, coro: Coroutine[Any, Any, Any]) -> None:
|
||||
"""Schedule a coroutine as a tracked background task (drained on shutdown)."""
|
||||
try:
|
||||
self.bus.admission.check()
|
||||
except RuntimeMaintenanceError:
|
||||
coro.close()
|
||||
raise
|
||||
task = asyncio.create_task(coro)
|
||||
self._background_tasks.add(task)
|
||||
task.add_done_callback(self._background_task_done)
|
||||
@@ -2657,53 +2689,54 @@ class AgentLoop:
|
||||
)
|
||||
# Share the dispatch lock so direct calls serialize with bus turns.
|
||||
lock = self._get_session_lock(session_key)
|
||||
temporary_parent = False
|
||||
try:
|
||||
async with lock:
|
||||
kwargs: dict[str, Any] = {
|
||||
"session_key": session_key,
|
||||
"on_progress": on_progress,
|
||||
"on_stream": on_stream,
|
||||
"on_stream_end": on_stream_end,
|
||||
"ephemeral": ephemeral,
|
||||
}
|
||||
if _session_policy is not None:
|
||||
# Isolate per-run state before any early save or checkpoint;
|
||||
# the cached conversation must survive a temporary SDK turn.
|
||||
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
|
||||
if not _session_policy.persist
|
||||
else await self.sessions.state.get(session_key))
|
||||
temporary_parent = not _session_policy.persist and not session.persisted
|
||||
session.policy = SessionPolicy(
|
||||
persist=session.policy.persist and _session_policy.persist,
|
||||
log_content=session.policy.log_content and _session_policy.log_content,
|
||||
disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
|
||||
)
|
||||
kwargs["session"] = session
|
||||
if _run_extra_hooks_for_ephemeral:
|
||||
kwargs["run_extra_hooks_for_ephemeral"] = True
|
||||
if hooks is not None:
|
||||
kwargs["hooks"] = hooks
|
||||
if hook_factories is not None:
|
||||
kwargs["hook_factories"] = hook_factories
|
||||
if tools is not None:
|
||||
kwargs["tools"] = tools
|
||||
if runtime is not None:
|
||||
kwargs["runtime"] = runtime
|
||||
if on_runtime_admitted is not None:
|
||||
kwargs["on_runtime_admitted"] = on_runtime_admitted
|
||||
if attributes is not None:
|
||||
kwargs["attributes"] = dict(attributes)
|
||||
try:
|
||||
return await self._process_message(msg, **kwargs)
|
||||
finally:
|
||||
if temporary_parent:
|
||||
parent = self.sessions.state.peek_header(session_key)
|
||||
if parent is not None and not parent.policy.persist:
|
||||
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
|
||||
finally:
|
||||
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
|
||||
self.runtime_event_publisher.clear_turn(session_key)
|
||||
with self.bus.admission.activity():
|
||||
temporary_parent = False
|
||||
try:
|
||||
async with lock:
|
||||
kwargs: dict[str, Any] = {
|
||||
"session_key": session_key,
|
||||
"on_progress": on_progress,
|
||||
"on_stream": on_stream,
|
||||
"on_stream_end": on_stream_end,
|
||||
"ephemeral": ephemeral,
|
||||
}
|
||||
if _session_policy is not None:
|
||||
# Isolate per-run state before any early save or checkpoint;
|
||||
# the cached conversation must survive a temporary SDK turn.
|
||||
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
|
||||
if not _session_policy.persist
|
||||
else await self.sessions.state.get(session_key))
|
||||
temporary_parent = not _session_policy.persist and not session.persisted
|
||||
session.policy = SessionPolicy(
|
||||
persist=session.policy.persist and _session_policy.persist,
|
||||
log_content=session.policy.log_content and _session_policy.log_content,
|
||||
disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
|
||||
)
|
||||
kwargs["session"] = session
|
||||
if _run_extra_hooks_for_ephemeral:
|
||||
kwargs["run_extra_hooks_for_ephemeral"] = True
|
||||
if hooks is not None:
|
||||
kwargs["hooks"] = hooks
|
||||
if hook_factories is not None:
|
||||
kwargs["hook_factories"] = hook_factories
|
||||
if tools is not None:
|
||||
kwargs["tools"] = tools
|
||||
if runtime is not None:
|
||||
kwargs["runtime"] = runtime
|
||||
if on_runtime_admitted is not None:
|
||||
kwargs["on_runtime_admitted"] = on_runtime_admitted
|
||||
if attributes is not None:
|
||||
kwargs["attributes"] = dict(attributes)
|
||||
try:
|
||||
return await self._process_message(msg, **kwargs)
|
||||
finally:
|
||||
if temporary_parent:
|
||||
parent = self.sessions.state.peek_header(session_key)
|
||||
if parent is not None and not parent.policy.persist:
|
||||
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
|
||||
finally:
|
||||
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
|
||||
self.runtime_event_publisher.clear_turn(session_key)
|
||||
|
||||
def _get_session_lock(self, session_key: str) -> asyncio.Lock:
|
||||
"""Return the shared lock while allowing idle session entries to expire."""
|
||||
|
||||
@@ -544,6 +544,7 @@ class SubagentManager:
|
||||
runtime: LLMRuntime | None, *, announce: bool, origin_turn_id: str | None,
|
||||
session_policy: SessionPolicy | None,
|
||||
) -> _SubagentTask:
|
||||
self.bus.admission.check()
|
||||
if runtime is None:
|
||||
runtime = self._compat_spawn_runtime()
|
||||
if temperature is not None:
|
||||
@@ -1003,6 +1004,11 @@ class SubagentManager:
|
||||
"""Return the number of currently running subagents."""
|
||||
return len(self._running_tasks)
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Completed turns may still own exec cleanup, including failed cleanup."""
|
||||
return bool(self._tasks) or self._exec_session_manager.has_pending_work
|
||||
|
||||
def get_running_count_by_session(self, session_key: str) -> int:
|
||||
"""Return the number of currently running subagents for a session."""
|
||||
return sum(
|
||||
|
||||
@@ -238,7 +238,10 @@ class _ExecSession:
|
||||
finally:
|
||||
stopped.cancel()
|
||||
await asyncio.gather(stopped, return_exceptions=True)
|
||||
from nanobot.agent.tools.shell import ExecTool, _reap_pid # pyright: ignore[reportPrivateUsage]
|
||||
from nanobot.agent.tools.shell import (
|
||||
ExecTool,
|
||||
_reap_pid, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
|
||||
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
|
||||
_reap_pid(self.process.pid)
|
||||
@@ -253,6 +256,18 @@ class _ExecSession:
|
||||
self._state_changed.clear()
|
||||
await self._state_changed.wait()
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Include pipe draining and failed/in-flight process-tree cleanup."""
|
||||
cleanup = self._kill_task
|
||||
return (
|
||||
self.finished_at is None
|
||||
or not self._stdout_task.done() or not self._stderr_task.done()
|
||||
or (cleanup is not None and (
|
||||
not cleanup.done() or cleanup.cancelled() or cleanup.exception() is not None
|
||||
))
|
||||
)
|
||||
|
||||
async def _watch_timeout(self) -> None:
|
||||
"""Supervise execution budgets independently of tool waits and log reads."""
|
||||
while not self._completion_task.done():
|
||||
@@ -371,13 +386,16 @@ class _ExecSession:
|
||||
await asyncio.shield(self._completion_task)
|
||||
|
||||
async def _begin_stop(self, reason: FinishReason) -> None:
|
||||
if self.finished_at is not None:
|
||||
if not self.has_pending_work:
|
||||
return
|
||||
if self._execution_exited and self._stop_reason is None:
|
||||
return
|
||||
if self._stop_reason is None:
|
||||
self._stop_reason = reason
|
||||
if self._kill_task is None:
|
||||
if self._kill_task is None or (
|
||||
self._kill_task.done()
|
||||
and (self._kill_task.cancelled() or self._kill_task.exception() is not None)
|
||||
):
|
||||
self.cleanup_error = None
|
||||
self._kill_task = asyncio.create_task(self._kill())
|
||||
self._kill_task.add_done_callback(self._on_kill_done)
|
||||
@@ -391,8 +409,8 @@ class _ExecSession:
|
||||
logger.opt(exception=error if tool_log_content_allowed() else False).error(
|
||||
"Failed to terminate exec session {}", self.session_id,
|
||||
)
|
||||
if (task.cancelled() or error is not None) and self._kill_task is task:
|
||||
self._kill_task = None
|
||||
# Retain failed cleanup as unsettled work, even if the parent exited.
|
||||
# kill() replaces it on an explicit retry.
|
||||
|
||||
async def _kill(self) -> None:
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
@@ -410,9 +428,18 @@ class ExecSessionManager:
|
||||
self.result_retention = result_retention
|
||||
self._sessions: dict[str, _ExecSession] = {}
|
||||
self._starting: dict[str, tuple[str | None, asyncio.Task[_ExecSession]]] = {}
|
||||
self._stopping_launches: set[asyncio.Task[_ExecSession]] = set()
|
||||
self._lock = asyncio.Lock()
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Inspect owned work without polling, terminating or removing sessions."""
|
||||
return bool(
|
||||
self._lock.locked() or self._starting or self._stopping_launches
|
||||
or any(s.has_pending_work for s in self._sessions.values())
|
||||
)
|
||||
|
||||
async def start(
|
||||
self,
|
||||
*,
|
||||
@@ -574,7 +601,6 @@ class ExecSessionManager:
|
||||
async with self._lock:
|
||||
self._closed = True
|
||||
sessions: list[_ExecSession] = list(self._sessions.values())
|
||||
self._sessions.clear()
|
||||
launches = [task for _, task in self._starting.values()]
|
||||
self._starting.clear()
|
||||
return await self._stop_owned(sessions, launches, "shutdown")
|
||||
@@ -583,9 +609,9 @@ class ExecSessionManager:
|
||||
"""Terminate all sessions owned by owner_session_key. Returns count."""
|
||||
async with self._lock:
|
||||
victims: list[_ExecSession] = []
|
||||
for sid, s in list(self._sessions.items()):
|
||||
for s in self._sessions.values():
|
||||
if s.owner_session_key == owner_session_key:
|
||||
victims.append(self._sessions.pop(sid))
|
||||
victims.append(s)
|
||||
launches = [
|
||||
task for owner, task in self._starting.values() if owner == owner_session_key
|
||||
]
|
||||
@@ -598,6 +624,10 @@ class ExecSessionManager:
|
||||
self, sessions: list[_ExecSession], launches: list[asyncio.Task[_ExecSession]],
|
||||
reason: FinishReason,
|
||||
) -> int:
|
||||
# Removed startup reservations must stay visible until cancellation drains.
|
||||
self._stopping_launches.update(launches)
|
||||
for task in launches:
|
||||
task.add_done_callback(self._stopping_launches.discard)
|
||||
results: list[None | BaseException] = list(await asyncio.gather(
|
||||
*(session.kill(reason) for session in sessions),
|
||||
self._cancel_launches(launches),
|
||||
@@ -609,10 +639,10 @@ class ExecSessionManager:
|
||||
for session, result in zip(sessions, results, strict=True)
|
||||
if isinstance(result, BaseException)
|
||||
]
|
||||
if failures:
|
||||
async with self._lock:
|
||||
for session, _ in failures:
|
||||
self._sessions[session.session_id] = session
|
||||
async with self._lock:
|
||||
for session, result in zip(sessions, results, strict=True):
|
||||
if not isinstance(result, BaseException):
|
||||
self._sessions.pop(session.session_id, None)
|
||||
errors = [result for _, result in failures]
|
||||
if isinstance(startup_error, BaseException):
|
||||
errors.append(startup_error)
|
||||
|
||||
Reference in new issue
Block a user