@agentsdock/server 1.0.11 → 1.0.12-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/install.sh CHANGED
@@ -1846,7 +1846,7 @@ if [[ "$TEAM_HUB_MODE" == "host" && "$TEAM_HUB_OPERATION_PENDING" != "true" \
1846
1846
  fi
1847
1847
  fi
1848
1848
 
1849
- RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py claude_sdk_client.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1849
+ RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py workspace_intelligence.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_chat_routing.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1850
1850
  RELEASE_DIRECTORIES=(agentsdock_team_hub)
1851
1851
  TEAM_HUB_RELEASE_FILES=(
1852
1852
  __init__.py
@@ -3753,12 +3753,15 @@ validate_staged_release_runtime() (
3753
3753
  "$STAGE_DIR/agentsdock_chats.py" \
3754
3754
  "$STAGE_DIR/chat_mailbox.py" \
3755
3755
  "$STAGE_DIR/agentsdock_emergency.py" \
3756
+ "$STAGE_DIR/agentsdock_notify.py" \
3756
3757
  "$STAGE_DIR/agentsdock_publish.py" \
3757
3758
  "$STAGE_DIR/agentsdock_mail.py" \
3758
3759
  "$STAGE_DIR/agentsdock_team.py" \
3759
3760
  "$STAGE_DIR/provider_commands.py" \
3760
3761
  "$STAGE_DIR/provider_usage.py" \
3762
+ "$STAGE_DIR/session_unread.py" \
3761
3763
  "$STAGE_DIR/claude_sdk_client.py" \
3764
+ "$STAGE_DIR/claude_chat_routing.py" \
3762
3765
  "$STAGE_DIR/claude_model_catalog.py" \
3763
3766
  "$STAGE_DIR/claude_goals.py" \
3764
3767
  "$STAGE_DIR/claude_background_reconciliation.py" \
@@ -3768,6 +3771,7 @@ validate_staged_release_runtime() (
3768
3771
  "$STAGE_DIR/provider_connections.py" "$STAGE_DIR/cursor_api_key.py" \
3769
3772
  "$STAGE_DIR/side_questions.py" \
3770
3773
  "$STAGE_DIR/workspace_git.py" \
3774
+ "$STAGE_DIR/workspace_intelligence.py" \
3771
3775
  "$STAGE_DIR/codex_side_question.py" \
3772
3776
  "$STAGE_DIR/codex_side_chat_progress.py" \
3773
3777
  "$STAGE_DIR/title_generation.py" \
@@ -3804,7 +3808,7 @@ validate_staged_release_runtime() (
3804
3808
  "$STAGE_DIR/update_runner.py"
3805
3809
  "$STAGE_DIR/.venv/bin/python" -m py_compile "$STAGE_DIR/server_instances.py"
3806
3810
  "$STAGE_DIR/.venv/bin/python" -m compileall -q "$STAGE_DIR/agentsdock_team_hub"
3807
- PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, claude_model_catalog, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3811
+ PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, workspace_intelligence, claude_model_catalog, claude_chat_routing, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3808
3812
  )
3809
3813
 
3810
3814
  abort_unclaimed_team_hub_reactivation() {
@@ -4132,7 +4136,7 @@ for name in "${TEAM_HUB_RELEASE_FILES[@]}"; do
4132
4136
  "$SOURCE_DIR/agentsdock_team_hub/$name" \
4133
4137
  "$STAGE_DIR/agentsdock_team_hub/$name"
4134
4138
  done
4135
- chmod 755 "$STAGE_DIR/agent_server.py" "$STAGE_DIR/agentsdock_jobs.py" "$STAGE_DIR/agentsdock_chats.py" "$STAGE_DIR/agentsdock_emergency.py" "$STAGE_DIR/agentsdock_publish.py" "$STAGE_DIR/agentsdock_mail.py" "$STAGE_DIR/agentsdock_team.py" "$STAGE_DIR/install.sh" "$STAGE_DIR/uninstall.sh" "$STAGE_DIR/update_runner.py"
4139
+ chmod 755 "$STAGE_DIR/agent_server.py" "$STAGE_DIR/agentsdock_jobs.py" "$STAGE_DIR/agentsdock_chats.py" "$STAGE_DIR/agentsdock_emergency.py" "$STAGE_DIR/agentsdock_notify.py" "$STAGE_DIR/agentsdock_publish.py" "$STAGE_DIR/agentsdock_mail.py" "$STAGE_DIR/agentsdock_team.py" "$STAGE_DIR/install.sh" "$STAGE_DIR/uninstall.sh" "$STAGE_DIR/update_runner.py"
4136
4140
  chmod 755 "$STAGE_DIR/instances.sh"
4137
4141
 
4138
4142
  if [[ "$PREPARE_ONLY" == "true" ]]; then
@@ -7015,15 +7019,31 @@ fi
7015
7019
  # links or configuration. Legacy runners can report a failed installer, so an
7016
7020
  # unfinished journal must never leave their old, unfenced API accepting work.
7017
7021
  if [[ "${EXECUTION_MODE:-legacy}" == "split" ]]; then
7018
- if ! execution_activation_command durability "$STAGE_DIR" \
7019
- || ! execution_recovery_arm "$STAGE_DIR" \
7020
- || ! record_activation_phase quiescing "$STAGE_DIR" \
7021
- || ! execution_stop_services "$STAGE_DIR" preflight \
7022
- || ! execution_activation_command suppress "$STAGE_DIR" \
7023
- || ! execution_stop_services "$STAGE_DIR" stop \
7024
- || ! record_activation_phase quiesced "$STAGE_DIR"; then
7022
+ # Name the quiesce boundary that actually failed. Arming the activation
7023
+ # recovery owner validates the recovery interpreter's ownership and
7024
+ # permission bits, which needs a different operator response than a native
7025
+ # service-stop failure; the single generic message below previously blamed
7026
+ # the service stop for every failure in this chain.
7027
+ ACTIVATION_QUIESCE_BOUNDARY=""
7028
+ if ! execution_activation_command durability "$STAGE_DIR"; then
7029
+ ACTIVATION_QUIESCE_BOUNDARY="recording activation durability evidence"
7030
+ elif ! execution_recovery_arm "$STAGE_DIR"; then
7031
+ ACTIVATION_QUIESCE_BOUNDARY="arming the activation recovery owner"
7032
+ elif ! record_activation_phase quiescing "$STAGE_DIR"; then
7033
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiescing phase"
7034
+ elif ! execution_stop_services "$STAGE_DIR" preflight; then
7035
+ ACTIVATION_QUIESCE_BOUNDARY="preflighting the admitted execution service"
7036
+ elif ! execution_activation_command suppress "$STAGE_DIR"; then
7037
+ ACTIVATION_QUIESCE_BOUNDARY="suppressing the admitted execution service"
7038
+ elif ! execution_stop_services "$STAGE_DIR" stop; then
7039
+ ACTIVATION_QUIESCE_BOUNDARY="stopping the admitted execution service"
7040
+ elif ! record_activation_phase quiesced "$STAGE_DIR"; then
7041
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiesced phase"
7042
+ fi
7043
+ if [[ -n "$ACTIVATION_QUIESCE_BOUNDARY" ]]; then
7025
7044
  [[ "$COLD_TEAM_HUB_HANDOFF" != "true" ]] || resume_install_signals
7026
7045
  echo "The admitted execution service could not be durably stopped before takeover." >&2
7046
+ echo " The failure occurred while $ACTIVATION_QUIESCE_BOUNDARY; the error above identifies the specific cause." >&2
7027
7047
  exit 1
7028
7048
  fi
7029
7049
  fi
@@ -242,7 +242,7 @@ class ConnectionStore:
242
242
  except HTTPException:
243
243
  return {"configured": False, "available": False, "models": [], "efforts": [], "model": None, "base_url": None}
244
244
 
245
- def claude_overrides(self, session: dict) -> tuple[dict, str | None]:
245
+ def claude_overrides(self, session: dict, *, runtime_settings: dict | None = None) -> tuple[dict, str | None]:
246
246
  value = self.for_session(session)
247
247
  if not value:
248
248
  return {}, None
@@ -259,7 +259,7 @@ class ConnectionStore:
259
259
  env["CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"] = str(session["subagent_limit"])
260
260
  # Flag settings outrank project/user settings. Pass a private file path,
261
261
  # never a key-bearing JSON argument visible in process listings.
262
- content = json.dumps({"env": env, "apiKeyHelper": ""}, sort_keys=True)
262
+ content = json.dumps({**(runtime_settings or {}), "env": env, "apiKeyHelper": ""}, sort_keys=True)
263
263
  digest = hashlib.sha256(content.encode()).hexdigest()
264
264
  path = self.root / f"claude-runtime-{digest}.json"
265
265
  with self.lock:
@@ -28,11 +28,19 @@ class PublicTranscriptError(ValueError):
28
28
  def _is_goal_followup(event: dict) -> bool:
29
29
  return bool(
30
30
  event.get("type") == "turn_steered"
31
- and event.get("native_goal_steer") is True
32
31
  and event.get("native_steer") is True
33
32
  and event.get("provider_user_authored") is True
34
- and event.get("backend") == "codex"
35
- and event.get("purpose") == "codex_goal_resume"
33
+ and (
34
+ (event.get("native_goal_steer") is True
35
+ and event.get("backend") == "codex"
36
+ and event.get("purpose") == "codex_goal_resume")
37
+ or (event.get("native_followup") is True
38
+ and event.get("backend") == "claude"
39
+ and event.get("purpose") is None
40
+ and event.get("provider_generated") is not True
41
+ and isinstance(event.get("provider_message_id"), str)
42
+ and event["provider_message_id"].strip())
43
+ )
36
44
  and isinstance(event.get("run_id"), str)
37
45
  and event["run_id"].strip()
38
46
  )
@@ -0,0 +1,184 @@
1
+ """Incremental unread provenance; journal recovery runs off the event loop."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Iterable
6
+ from transcript_reader import jsonl_records
7
+
8
+
9
+ COUNTER = "latest_non_job_agent_event_seq"
10
+ CHECKPOINT = "_non_job_agent_event_checkpoint_seq"
11
+ PENDING_COUNTER = "_non_job_agent_event_pending_seq"
12
+ LAST_RUN = "_non_job_agent_last_run"
13
+ JOURNAL = "_non_job_agent_event_journal"
14
+
15
+
16
+ def imported_event(event: dict[str, Any]) -> bool:
17
+ return event.get("imported") is True or str(event.get("run_id") or "").startswith("import_")
18
+
19
+
20
+ def scheduled_event(event: dict[str, Any]) -> bool:
21
+ job = event.get("job")
22
+ return bool(
23
+ event.get("purpose") == "scheduled_job"
24
+ or str(event.get("job_id") or "").strip()
25
+ or isinstance(job, dict) and str(job.get("id") or "").strip()
26
+ or str(event.get("type") or "").startswith("job_")
27
+ )
28
+
29
+
30
+ def project_event(
31
+ session: dict[str, Any], event: dict[str, Any], *,
32
+ visible: bool, run_metadata: dict[str, Any],
33
+ ) -> None:
34
+ """Apply an appended event without I/O or changing the ordinary read cursor."""
35
+ seq = int(event.get("seq") or 0)
36
+ if seq <= 0:
37
+ return
38
+ # Only a new journal can establish an empty baseline without recovery.
39
+ if seq == 1 and not int(session.get("latest_event_seq") or 0):
40
+ session.setdefault(COUNTER, 0)
41
+ session.setdefault(CHECKPOINT, 0)
42
+ known = isinstance(session.get(COUNTER), int) and CHECKPOINT in session
43
+ run_id = str(event.get("run_id") or "")
44
+ contexts: list[dict[str, Any]] = []
45
+ if event.get("type") == "turn_started" and run_id:
46
+ context = {"run_id": run_id, "scheduled_job": scheduled_event(event) or scheduled_event(run_metadata)}
47
+ session[LAST_RUN] = context
48
+ contexts.append(context)
49
+ else:
50
+ for candidate in (session.get("active_run"), session.get(LAST_RUN)):
51
+ if isinstance(candidate, dict) and run_id and candidate.get("run_id") == run_id:
52
+ contexts.append(candidate)
53
+ scheduled = scheduled_event(event) or scheduled_event(run_metadata) or any(
54
+ scheduled_event(context) or context.get("scheduled_job") is True for context in contexts
55
+ )
56
+ if scheduled and run_id and (session.get(LAST_RUN) or {}).get("run_id") == run_id:
57
+ session[LAST_RUN] = {"run_id": run_id, "scheduled_job": True}
58
+ if visible and not scheduled and not imported_event(event):
59
+ field = COUNTER if known else PENDING_COUNTER
60
+ session[field] = max(int(session.get(field) or 0), seq)
61
+ if known:
62
+ session[CHECKPOINT] = max(int(session.get(CHECKPOINT) or 0), seq)
63
+
64
+
65
+ def recover_projection(
66
+ path: Path, snapshot: dict[str, Any], *,
67
+ visible: Callable[[str, dict[str, Any]], bool],
68
+ resume_offset: Callable[[Path, int], int],
69
+ prior_events: Callable[[], Iterable[dict[str, Any]]],
70
+ cancelled: Callable[[], bool],
71
+ ) -> dict[str, Any]:
72
+ """Project one fixed journal extent, then resolve missing run provenance once.
73
+
74
+ Legacy chats need one forward pass. A durable checkpoint resumes through the
75
+ existing sparse index; only an untagged tail run whose start precedes that
76
+ checkpoint requires a backwards provenance pass. No history is read by the
77
+ session-list endpoint or the live event projection.
78
+ """
79
+ known = isinstance(snapshot.get(COUNTER), int) and CHECKPOINT in snapshot
80
+ after = int(snapshot.get(CHECKPOINT) or 0) if known else 0
81
+ latest = int(snapshot.get(COUNTER) or 0) if known else 0
82
+ through = after
83
+ last_run = dict(snapshot.get(LAST_RUN) or {})
84
+ runs: dict[str, dict[str, Any]] = {}
85
+ unresolved: dict[str, list[dict[str, Any]]] = {}
86
+
87
+ def finish(run_id: str, run: dict[str, Any]) -> None:
88
+ nonlocal latest
89
+ if run["scheduled"] or not run["visible_seq"]:
90
+ return
91
+ if run["origin"]:
92
+ latest = max(latest, run["visible_seq"])
93
+ else:
94
+ unresolved.setdefault(run_id, []).append(run)
95
+
96
+ try:
97
+ source = path.open("rb")
98
+ except FileNotFoundError:
99
+ if after or int(snapshot.get("latest_event_seq") or 0):
100
+ raise
101
+ return {COUNTER: 0, CHECKPOINT: 0, LAST_RUN: {}}
102
+ with source:
103
+ extent = source.seek(0, 2)
104
+ inode = path.stat().st_ino
105
+ journal = snapshot.get(JOURNAL) or {}
106
+ if known and journal and (journal.get("inode") != inode or int(journal.get("offset") or 0) > extent):
107
+ after = latest = through = 0
108
+ last_run = {}
109
+ offset = int(journal.get("offset") or 0) if after and journal.get("inode") == inode else 0
110
+ source.seek(offset or (resume_offset(path, after) if after else 0))
111
+ complete_offset = source.tell()
112
+ for event, ending, raw in jsonl_records(
113
+ source, end=extent, project=False, require_newline=False, deadline=float("inf"), cancelled=cancelled,
114
+ max_records=float("inf"), max_nodes=None, max_depth=512,
115
+ retained_fields=frozenset({"seq", "type", "run_id", "purpose", "job_id", "job", "text", "result_text", "goal", "imported"}),
116
+ ):
117
+ if not raw.complete:
118
+ break # Leave a concurrently written/crash fragment unclaimed.
119
+ complete_offset = ending
120
+ if not isinstance(event, dict):
121
+ continue
122
+ seq = int(event.get("seq") or 0)
123
+ if seq <= after:
124
+ continue
125
+ through = max(through, seq)
126
+ event_type = str(event.get("type") or "")
127
+ is_visible = visible(event_type, event) and not imported_event(event)
128
+ run_id = str(event.get("run_id") or "")
129
+ scheduled = scheduled_event(event)
130
+ if not run_id:
131
+ if is_visible and not scheduled:
132
+ latest = max(latest, seq)
133
+ continue
134
+ if event_type == "turn_started" and run_id in runs:
135
+ finish(run_id, runs.pop(run_id))
136
+ run = runs.setdefault(run_id, {"first_seq": seq, "visible_seq": 0, "scheduled": False, "origin": False})
137
+ run["scheduled"] = run["scheduled"] or scheduled
138
+ if event_type == "turn_started":
139
+ run["origin"] = True
140
+ last_run = {"run_id": run_id, "scheduled_job": scheduled}
141
+ elif scheduled and last_run.get("run_id") == run_id:
142
+ last_run["scheduled_job"] = True
143
+ if is_visible:
144
+ run["visible_seq"] = max(run["visible_seq"], seq)
145
+ if event_type in {"turn_finished", "turn_stopped"} and (run["scheduled"] or not run["visible_seq"]):
146
+ # Completed cron runs do not accumulate with the schedule's
147
+ # history. A later untagged event is resolved by the single
148
+ # backwards provenance pass, just like a restart tail.
149
+ runs.pop(run_id, None)
150
+ for run_id, run in runs.items():
151
+ finish(run_id, run)
152
+ # One reverse pass resolves all tail runs together, including stripped raw
153
+ # provider events and a job_ran marker emitted after the provider's start.
154
+ if unresolved:
155
+ for event in prior_events():
156
+ if cancelled():
157
+ raise InterruptedError("unread projection cancelled")
158
+ run_id = str(event.get("run_id") or "")
159
+ candidates = unresolved.get(run_id)
160
+ if not candidates:
161
+ continue
162
+ seq = int(event.get("seq") or 0)
163
+ scheduled = scheduled_event(event)
164
+ if not scheduled and event.get("type") != "turn_started":
165
+ continue
166
+ remaining = []
167
+ for run in candidates:
168
+ if seq >= run["first_seq"]:
169
+ remaining.append(run)
170
+ elif not scheduled:
171
+ latest = max(latest, run["visible_seq"])
172
+ if remaining:
173
+ unresolved[run_id] = remaining
174
+ else:
175
+ unresolved.pop(run_id)
176
+ if not unresolved:
177
+ break
178
+ # Legacy output with no recorded job provenance remains ordinary;
179
+ # merely owning a schedule never suppresses a human conversation.
180
+ for candidates in unresolved.values():
181
+ for run in candidates:
182
+ latest = max(latest, run["visible_seq"])
183
+ return {COUNTER: latest, CHECKPOINT: through, LAST_RUN: last_run,
184
+ JOURNAL: {"inode": inode, "offset": complete_offset}}
@@ -27,10 +27,11 @@ from fastapi import APIRouter, HTTPException, Request
27
27
  from fastapi.responses import JSONResponse
28
28
 
29
29
 
30
- MAX_QUESTION_CHARS = 8000
31
30
  MAX_HISTORY_ITEMS = 32
32
31
  MAX_HISTORY_CHARS = 60000
33
32
  MAX_REQUEST_BYTES = 512 * 1024
33
+ # The streamed body limit bounds input; avoid a second, smaller model-text cap.
34
+ MAX_QUESTION_CHARS = MAX_REQUEST_BYTES
34
35
  MAX_CONTEXT_CHARS = 60000
35
36
  MAX_LOG_BYTES = 4 * 1024 * 1024
36
37
  MAX_OUTPUT_BYTES = 1024 * 1024
@@ -369,11 +370,6 @@ class _NativeConversation:
369
370
  closed: bool = False
370
371
  timer: object = None
371
372
  close_task: asyncio.Task | None = None
372
-
373
-
374
- NATIVE_IDLE_SECONDS = 30 * 60
375
-
376
-
377
373
  class SideQuestions:
378
374
  def __init__(self, answer=None, *, native_factory=None, storage_path=None, notify=None, admission_check=None, runtime_settings_for_session=None):
379
375
  self.answer = answer
@@ -396,6 +392,43 @@ class SideQuestions:
396
392
  def active_work_labels(self):
397
393
  return [f"Side chat in {session_id}" for session_id in sorted(self.active_session_ids())]
398
394
 
395
+ def background_work_scopes(self):
396
+ handles = [(key[1], conversation.handle) for key, conversation in self.conversations.items()
397
+ if not conversation.closed and conversation.handle is not None]
398
+ if self.synced is not None:
399
+ handles.extend((key[1], handle) for key, handle in self.synced.handles.items())
400
+ scopes = []
401
+ for session_id, handle in handles:
402
+ inspect = getattr(handle, "background_work_scope", None)
403
+ scope = inspect() if callable(inspect) else None
404
+ if scope is not None:
405
+ scopes.append((session_id, handle, scope))
406
+ return tuple(scopes)
407
+
408
+ async def prepare_background_work_snapshot(self, *, timeout_seconds=5.0):
409
+ scopes = self.background_work_scopes()
410
+
411
+ async def inspect(session_id, handle, _scope):
412
+ try:
413
+ active = await handle.has_background_work()
414
+ except Exception:
415
+ return f"Side chat provider state unknown in {session_id}"
416
+ return f"Side chat background work in {session_id}" if active else None
417
+
418
+ try:
419
+ values = await asyncio.wait_for(asyncio.gather(*(inspect(*scope) for scope in scopes)),
420
+ timeout=timeout_seconds)
421
+ labels = tuple(sorted(set(value for value in values if value)))
422
+ except asyncio.TimeoutError:
423
+ labels = tuple(f"Side chat provider state unknown in {session_id}" for session_id, _, _ in scopes)
424
+ return {"scopes": scopes, "labels": labels}
425
+
426
+ def background_work_labels_from_snapshot(self, snapshot):
427
+ scopes = self.background_work_scopes()
428
+ if snapshot.get("scopes", ()) != scopes:
429
+ return ["Side chat provider state changed during inspection"]
430
+ return list(snapshot.get("labels", ()))
431
+
399
432
  async def _close_conversation(self, conversation):
400
433
  conversation.closed = True
401
434
  if conversation.timer is not None:
@@ -415,7 +448,7 @@ class SideQuestions:
415
448
  await asyncio.shield(conversation.close_task)
416
449
 
417
450
  def _expire_conversation(self, key, conversation):
418
- if self.conversations.get(key) is not conversation or conversation.busy:
451
+ if self.conversations.get(key) is not conversation or conversation.busy or not conversation.closed:
419
452
  return
420
453
  self.conversations.pop(key, None)
421
454
  task = asyncio.create_task(self._close_conversation(conversation), name="side-chat-expiry")
@@ -461,8 +494,9 @@ class SideQuestions:
461
494
  raise
462
495
  finally:
463
496
  conversation.busy = False
464
- conversation.timer = asyncio.get_running_loop().call_later(
465
- NATIVE_IDLE_SECONDS, self._expire_conversation, key, conversation)
497
+ if conversation.closed:
498
+ conversation.timer = asyncio.get_running_loop().call_later(
499
+ RECEIPT_TTL_SECONDS, self._expire_conversation, key, conversation)
466
500
 
467
501
  async def close_conversation(self, owner, session_id, side_chat_id):
468
502
  key = (owner, session_id, side_chat_id)
@@ -473,7 +507,7 @@ class SideQuestions:
473
507
  await self.cancel(*receipt_key)
474
508
  await self._close_conversation(conversation)
475
509
  conversation.timer = asyncio.get_running_loop().call_later(
476
- NATIVE_IDLE_SECONDS, self._expire_conversation, key, conversation)
510
+ RECEIPT_TTL_SECONDS, self._expire_conversation, key, conversation)
477
511
 
478
512
  def _prune(self):
479
513
  now = time.monotonic()
@@ -874,8 +908,6 @@ class SyncedSideChats:
874
908
  self.cleanup_tasks.discard(cleanup)
875
909
  if self.tasks.get(key) is asyncio.current_task():
876
910
  self.tasks.pop(key, None)
877
- if not self.stopping:
878
- self.timers[key] = asyncio.get_running_loop().call_later(NATIVE_IDLE_SECONDS, self._expire, key)
879
911
 
880
912
  async def _finish(self, key, side_chat_id, request_id, status, **result):
881
913
  async with self._lock(key):
@@ -1053,7 +1085,7 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1053
1085
  if not isinstance(request_id, str) or not IDENTIFIER.fullmatch(request_id):
1054
1086
  raise HTTPException(400, "Invalid side question request ID")
1055
1087
  if not isinstance(question, str) or not question.strip() or len(question) > MAX_QUESTION_CHARS:
1056
- raise HTTPException(400, "Question must contain 1 to 8000 characters")
1088
+ raise HTTPException(400, f"Question must contain 1 to {MAX_QUESTION_CHARS} characters")
1057
1089
  try:
1058
1090
  question.encode("utf-8")
1059
1091
  except UnicodeEncodeError:
@@ -1152,7 +1184,7 @@ def create_side_question_router(*, authorize, session_exists, runtime: SideQuest
1152
1184
  raise HTTPException(400, "Invalid side conversation ID")
1153
1185
  question = value["question"]
1154
1186
  if not isinstance(question, str) or not question.strip() or len(question) > MAX_QUESTION_CHARS:
1155
- raise HTTPException(400, "Question must contain 1 to 8000 characters")
1187
+ raise HTTPException(400, f"Question must contain 1 to {MAX_QUESTION_CHARS} characters")
1156
1188
  try:
1157
1189
  question.encode("utf-8")
1158
1190
  except UnicodeEncodeError:
@@ -281,7 +281,7 @@ class _RecordParser:
281
281
  def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
282
282
  require_newline=True, max_records=250_000, deadline=None,
283
283
  cancelled=None, max_retained_bytes=MAX_RETAINED_BYTES, retained_fields=None,
284
- max_nodes=-1, max_depth=None):
284
+ max_nodes=-1, max_depth=None, allow_nul_padding=False):
285
285
  """Yield (projected object or None, ending offset, RawRecord).
286
286
 
287
287
  Malformed provider lines may be represented by None, as before. Resource
@@ -289,6 +289,8 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
289
289
  A fixed end excludes concurrent appends; callers own file identity checks.
290
290
  Native-import work budgets remain the default. Durable metadata-only scans
291
291
  can supply separate structural limits without imposing import caps on logs.
292
+ Native Claude recovery can explicitly accept NUL-only padding lines. They
293
+ provide no event or ownership evidence, but retain their exact raw receipt.
292
294
  """
293
295
  # Externally supplied deadlines can belong to a larger operation. Do not
294
296
  # invent a duration for them; the caller can provide its own timeout detail.
@@ -306,14 +308,23 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
306
308
  parser = _RecordParser(stream, end, deadline, cancelled, project, max_retained_bytes, budget_seconds, retained_fields, max_nodes, max_depth)
307
309
  blank = False
308
310
  malformed = False
311
+ nul_padding = False
309
312
  try:
310
313
  try:
311
- parser.space()
312
- blank = parser.peek() is None
313
- value = None if blank else parser.value()
314
- parser.space()
315
- if parser.peek() is not None:
316
- raise InvalidRecord('trailing JSON content')
314
+ if allow_nul_padding and parser.peek() == 0:
315
+ while parser.peek() == 0:
316
+ parser.index += 1
317
+ if parser.take() != 10 or parser.peek() is not None:
318
+ raise InvalidRecord('invalid NUL padding record')
319
+ nul_padding = malformed = True
320
+ value = None
321
+ else:
322
+ parser.space()
323
+ blank = parser.peek() is None
324
+ value = None if blank else parser.value()
325
+ parser.space()
326
+ if parser.peek() is not None:
327
+ raise InvalidRecord('trailing JSON content')
317
328
  except (InvalidRecord, UnicodeDecodeError, json.JSONDecodeError) as error:
318
329
  if strict:
319
330
  raise ValueError('malformed transcript record') from error
@@ -329,6 +340,6 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
329
340
  raise ValueError('transcript cursor does not end on a complete line')
330
341
  raw = RawRecord(stream, start, stop, parser.complete, blank, malformed or blank,
331
342
  deadline, cancelled, count, budget_seconds)
332
- if strict and not isinstance(value, dict):
343
+ if strict and not isinstance(value, dict) and not nul_padding:
333
344
  raise ValueError('transcript object expected')
334
345
  yield value if isinstance(value, dict) else None, stop, raw