Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

Merge remote-tracking branch 'origin/master' into codex-integrate-org-into-master

Max40f319e77f7c
diff --cc core/watches.py
index 5e8533519,d627de229..e5c4a0272
--- a/core/watches.py
+++ b/core/watches.py
@@@ -594,8 -640,9 +649,9 @@@ class ManagedWatchStore
retry_delay_seconds=retry_delay_seconds,
post_to=post_to,
deliver_key=deliver_key,
- metadata=dict(metadata or {}),
+ metadata=metadata_with_resource_user_context(metadata, user_context),
)
+ watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY] = watch.created_at
return self.upsert_watch(
watch,
expected_enabled_agent_id=expected_enabled_agent_id,
@@@ -707,10 -755,11 +773,13 @@@
watch.retry_delay_seconds = retry_delay_seconds
watch.post_to = post_to
watch.deliver_key = deliver_key
- if metadata is not None:
- watch.metadata = dict(metadata)
+ watch.metadata = metadata_with_resource_user_context(
+ metadata if metadata is not None else watch.metadata,
+ user_context,
+ )
+ if waiter_lifecycle_changed:
+ watch.metadata = dict(watch.metadata)
+ watch.metadata.pop(RECENT_EVENT_TIMESTAMPS_METADATA_KEY, None)
watch.updated_at = _utc_now_iso()
if not self._write_watch(
watch,
@@@ -1734,13 -1797,265 +1817,270 @@@ class ManagedWatchService
self._begin_stop()
return False
+ def _circuit_repair_prompt(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ event_timestamps: list[str],
+ ) -> str:
+ return self._t(
+ "harness.watch.circuitRepairPrompt",
+ name=watch.name or watch.id,
+ id=watch.id,
+ count=len(event_timestamps),
+ window=int(WATCH_EVENT_BURST_WINDOW_SECONDS),
+ timestamps="\n".join(f"- {value}" for value in event_timestamps),
+ stdout=_squash_tail(result.stdout, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ or self._t("harness.watch.emptyOutput"),
+ stderr=_squash_tail(result.stderr, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ or self._t("harness.watch.emptyOutput"),
+ retry_codes=", ".join(str(code) for code in watch.retry_exit_codes),
+ )
+
+ def _commit_success_cycle(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ ) -> bool:
+ now = datetime.now(timezone.utc)
+ now_iso = now.isoformat()
+ recent = _recent_event_timestamps(watch.metadata, now=now)
+ observed = [*recent, now_iso]
+ if watch.mode == "forever" and len(observed) > WATCH_EVENT_BURST_LIMIT:
+ stdout = _squash_tail(result.stdout, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ stderr = _squash_tail(result.stderr, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ request = self._hook_request(
+ watch,
+ event_detected=True,
+ hook_outcome=WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
+ prompt=self._circuit_repair_prompt(watch, result, observed),
+ )
+ if request is None:
+ return False
+ incident = {
+ "status": "tripped",
+ "triggered_at": now_iso,
+ "event_timestamps": observed,
+ "exit_code": 0,
+ "stdout": stdout,
+ "stderr": stderr,
+ "repair_run_id": request.id,
+ }
+ return self._persist_cycle_result(
+ watch,
+ request=request,
+ exit_code=0,
+ error=self._t(
+ "harness.watch.circuitPausedError",
+ count=len(observed),
+ window=int(WATCH_EVENT_BURST_WINDOW_SECONDS),
+ run_id=request.id,
+ ),
+ event_detected=True,
+ acknowledge_event=False,
+ disable=False,
+ pause=True,
+ metadata_updates={
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY: observed,
+ CIRCUIT_BREAKER_METADATA_KEY: incident,
+ },
+ )
+
+ metadata_updates = (
+ {RECENT_EVENT_TIMESTAMPS_METADATA_KEY: observed}
+ if watch.mode == "forever"
+ else None
+ )
+ return self._commit_cycle_result(
+ watch,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=watch.mode == "once",
+ prompt=_build_prompt(watch.message or watch.prefix, result.stdout),
+ metadata_updates=metadata_updates,
+ )
+
+ async def _commit_success_cycle_async(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ ) -> bool:
+ try:
+ return await self._run_runtime_sync(
+ self._commit_success_cycle,
+ watch,
+ result,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "commit successful watch cycle",
+ exc,
+ watch_id=watch.id,
+ )
+ return False
+
+ async def _wait_for_follow_up_slot(
+ self,
+ watch_id: str,
+ *,
+ lifetime_started: float,
+ ) -> _FollowUpSlot:
+ """Wait for the prior Agent work without letting Watch lifetime drift."""
+
+ terminal_statuses = {"succeeded", "failed", "canceled"}
+ future_completion_seen: tuple[str, float] | None = None
+ while self._running:
+ if not self._owns_service_instance():
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if not await self._watch_store_call_async(
+ watch_id,
+ "reload before follow-up fence",
+ self.store.maybe_reload,
+ ):
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ watch = self.store.get_watch(watch_id)
+ if watch is None or not watch.enabled:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ lifetime_remaining = None
+ if watch.lifetime_timeout_seconds > 0:
+ lifetime_remaining = watch.lifetime_timeout_seconds - (
+ asyncio.get_running_loop().time() - lifetime_started
+ )
+ try:
+ unsettled = await self._run_runtime_sync(
+ self.request_store.get_unsettled_watch_run,
+ watch_id,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "read follow-up fence",
+ exc,
+ watch_id=watch_id,
+ )
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if unsettled:
+ blocking_run_id = str(unsettled["id"])
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(
+ FOLLOW_UP_SLOT_LIFETIME_EXPIRED,
+ blocking_run_id=blocking_run_id,
+ )
+ delay = WATCH_FOLLOW_UP_POLL_SECONDS
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ continue
+
+ run_id = str(watch.metadata.get(FOLLOW_UP_RUN_ID_METADATA_KEY) or "").strip()
+ if not run_id:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ try:
+ run = await self._run_runtime_sync(self.request_store.get_run, run_id)
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "read previous follow-up",
+ exc,
+ watch_id=watch_id,
+ )
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if run is None:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ status = str(run.get("status") or "").strip().lower()
+ if status not in terminal_statuses:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(
+ FOLLOW_UP_SLOT_LIFETIME_EXPIRED,
+ blocking_run_id=run_id,
+ )
+ delay = WATCH_FOLLOW_UP_POLL_SECONDS
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ continue
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ if watch.mode != "forever":
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ completed_at = _parse_utc_timestamp(
+ run.get("completed_at") or run.get("updated_at")
+ )
+ if completed_at is None:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ wall_elapsed = (datetime.now(timezone.utc) - completed_at).total_seconds()
+ if wall_elapsed >= 0:
+ elapsed = wall_elapsed
+ else:
+ loop_now = asyncio.get_running_loop().time()
+ if future_completion_seen is None or future_completion_seen[0] != run_id:
+ future_completion_seen = (run_id, loop_now)
+ elapsed = loop_now - future_completion_seen[1]
+ remaining = WATCH_MIN_REARM_SECONDS - elapsed
+ if remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ delay = min(remaining, WATCH_FOLLOW_UP_POLL_SECONDS)
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+
+ async def _commit_lifetime_timeout_async(
+ self,
+ watch: ManagedWatch,
+ *,
+ blocking_run_id: str | None = None,
+ ) -> bool:
+ kwargs: dict[str, Any] = {}
+ if blocking_run_id is None:
+ kwargs = {
+ "prefix": watch.message
+ or watch.prefix
+ or self._t("harness.watch.lifetimeTimeoutPrefix"),
+ "body": self._t(
+ "harness.watch.lifetimeTimeoutBody",
+ name=watch.name or watch.id,
+ seconds=int(watch.lifetime_timeout_seconds),
+ ),
+ }
+ else:
+ kwargs["error"] = self._t(
+ "harness.watch.lifetimeExpiredWithActiveFollowUp",
+ run_id=blocking_run_id,
+ )
+ return await self._commit_cycle_result_async(
+ watch,
+ exit_code=124,
+ error=kwargs.pop("error", None),
+ disable=True,
+ **kwargs,
+ )
+
+ async def _sleep_before_retry(
+ self,
+ watch: ManagedWatch,
+ *,
+ lifetime_started: float,
+ ) -> None:
+ delay = watch.retry_delay_seconds
+ if watch.lifetime_timeout_seconds > 0:
+ elapsed = asyncio.get_running_loop().time() - lifetime_started
+ delay = min(
+ delay,
+ max(0.0, watch.lifetime_timeout_seconds - elapsed),
+ )
+ await asyncio.sleep(delay)
+
async def _run_watch(self, watch_id: str) -> None:
+ from storage.resource_access_service import (
+ REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
+ metadata_has_remote_resource_context,
+ )
+
- lifetime_started = asyncio.get_running_loop().time()
+ lifetime_started: float | None = None
self._watch_started_at[watch_id] = _utc_now_iso()
self._runtime_state_dirty = True
self._write_runtime_state()
@@@ -1759,21 -2074,26 +2099,39 @@@
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
return
+ if metadata_has_remote_resource_context(watch.metadata):
+ self._watch_store_call(
+ watch.id,
+ "suspend_remote_origin",
+ lambda: self.store.mark_cycle_result(
+ watch.id,
+ exit_code=None,
+ error=REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
+ disable=True,
+ ),
+ guarded=True,
+ )
+ return
+ if lifetime_started is None:
+ lifetime_started = _lifetime_started_monotonic(watch)
+
+ follow_up_slot = await self._wait_for_follow_up_slot(
+ watch_id,
+ lifetime_started=lifetime_started,
+ )
+ if follow_up_slot.state == FOLLOW_UP_SLOT_STOPPED:
+ return
+ watch = self.store.get_watch(watch_id)
+ if watch is None or not watch.enabled:
+ return
+ if follow_up_slot.state == FOLLOW_UP_SLOT_LIFETIME_EXPIRED:
+ await self._commit_lifetime_timeout_async(
+ watch,
+ blocking_run_id=follow_up_slot.blocking_run_id,
+ )
+ return
- if watch.mode == "forever" and watch.lifetime_timeout_seconds > 0:
+ if watch.lifetime_timeout_seconds > 0:
elapsed = asyncio.get_running_loop().time() - lifetime_started
remaining_lifetime = watch.lifetime_timeout_seconds - elapsed
if remaining_lifetime <= 0:
diff --cc tests/test_cli_watch_command.py
index e7dacc612,f276e19ef..16fc8dc7e
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@@ -445,25 -466,14 +468,31 @@@ def test_remote_watch_add_is_rejected_w
"AVIBE_CALLER_SOURCE": "agent_turn",
"AVIBE_CALLER_BACKEND": "opencode",
"AVIBE_NATIVE_SESSION_ID": "native-opencode-1",
+ "AVIBE_CALLER_REMOTE": "1",
+ "AVIBE_CALLER_RESOURCE_CONTEXT": json.dumps(
+ {
+ "sub": "remote-editor",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_group_ids": [],
+ "claims_issued_at": 1_900_000_000,
+ "authorization_expires_at": 1_900_043_200,
+ }
+ ),
+ "AVIBE_CALLER_PLATFORM": "",
+ "AVIBE_CALLER_USER_ID": "",
+ "AVIBE_CALLER_CHANNEL_ID": "",
+ "AVIBE_CALLER_SESSION_KEY": "",
+ "AVIBE_CALLER_MESSAGE_ID": "",
+ "AVIBE_CALLER_WORKSPACE_ID": "",
}
+ startup_calls: list[str] = []
+
+ def unexpected_startup(*args, **kwargs):
+ startup_calls.append(args[2])
+ raise AssertionError("remote Watch must not start")
+
with (
patch.dict(os.environ, caller_env, clear=False),
patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),