code-context-control 2.160.0__py3-none-any.whl → 2.161.0__py3-none-any.whl

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.
cli/c3.py CHANGED
@@ -96,7 +96,7 @@ console = Console() if HAS_RICH else None
96
96
  # Config
97
97
  CONFIG_DIR = ".c3"
98
98
  CONFIG_FILE = ".c3/config.json"
99
- __version__ = "2.160.0"
99
+ __version__ = "2.161.0"
100
100
 
101
101
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
102
102
  AGENT_MATCHER = "Agent|Task"
cli/hub_server.py CHANGED
@@ -3349,6 +3349,13 @@ def api_hub_schedule_runs():
3349
3349
  return jsonify({"runs": _sched_with_names(rows), "count": len(rows), "project": project_path})
3350
3350
 
3351
3351
 
3352
+ @app.route("/api/hub/schedules/runs/<run_id>/output", methods=["GET"])
3353
+ def api_hub_schedule_run_output(run_id):
3354
+ data, err = _sched_call(_schedule_api().run_output, str(run_id), after=request.args.get("after"),
3355
+ limit=request.args.get("limit"))
3356
+ return err or jsonify(data)
3357
+
3358
+
3352
3359
  @app.route("/api/hub/schedules/approvals", methods=["GET"])
3353
3360
  def api_hub_schedule_approvals():
3354
3361
  project_path, err = _sched_project_arg()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-context-control
3
- Version: 2.160.0
3
+ Version: 2.161.0
4
4
  Summary: Local MCP code-intelligence for AI coding tools: surgical search/read/edit, agent-config version history, path-level access + masking guards, and a multi-project hub.
5
5
  Author-email: Dimitri Tselenchuk <dtselenc@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -1,7 +1,7 @@
1
1
  cli/__init__.py,sha256=ec66drCZGNMRU4V6ov0zVhYZph1us12Vn8OvG_LJyRY,22
2
2
  cli/_hook_utils.py,sha256=tzpdF413jakQKMbTru_GdHxQXxLLQKiZzVkTm4Fo_eU,23258
3
3
  cli/_shell_writes.py,sha256=iBbzK0v0d29rhrYgF3zKJIJbb1WSZhQjD_6w8-nOUec,7348
4
- cli/c3.py,sha256=ch3_Yt_vVdqvIyJ7ctdT6q0dy20Jl5S9xnXWORRmAcU,439974
4
+ cli/c3.py,sha256=756qSx3772RsjgPOuhRLnDcQGLM3L1zZDp6JT_sQuTg,439974
5
5
  cli/docs.html,sha256=pPxcP5ieY0DcfEDvegwIcRxbz1woLZoKLVSF-4JVy0Q,146784
6
6
  cli/edits.html,sha256=UjAhoCmBmQ89cklGvJqzC6eyNP2tc8H6T-e01DVkLvE,43418
7
7
  cli/hook_access_guard.py,sha256=4UF2YHp5_vISH7Gvolc_Bz3ppSye2lGpGx38egRLj1g,32116
@@ -23,7 +23,7 @@ cli/hook_session_end.py,sha256=toFEPDKRoutDuVOmuOgHmQ8CM0o7tF7yALhMxJz7VEM,3482
23
23
  cli/hook_session_open.py,sha256=Bq8zKPkucPYASQDxJcT1bGm975d__RbTvaiWj9yVcDs,11969
24
24
  cli/hook_session_stats.py,sha256=I-2NeLlV1NxeqKtTM2JH9haSpFU7r4qG0u8pfCJ80YU,8725
25
25
  cli/hook_terse_advisor.py,sha256=W_zaTfX2akgX-ifuUTsLu2H1atM8XmWt6jpPoeU7Pm0,6252
26
- cli/hub_server.py,sha256=b2zz2pSaz5wFhIirzPgUFp1B04bgfB6kNy0j-KKXAoc,230216
26
+ cli/hub_server.py,sha256=0bGnpetegI-bs0tCLdsDFDuvEu-OdnEqzxywqdcJkiw,230525
27
27
  cli/hub_ui.html,sha256=v41R_JAH4Jwodpy3tbeBUel-80FbNmffBrey-QH5Q64,2963
28
28
  cli/mcp_proxy.py,sha256=r-Qhlie7gCtotex8yQUudCyBLRUK-IW6cNIW5RhBW0o,17648
29
29
  cli/mcp_server.py,sha256=DisVVExGIbeEABxtDPzdaGJpu7P1okA4l_dzu-VFD3E,84862
@@ -135,7 +135,7 @@ cli/ui/components/sessions.js,sha256=FIKtil76B8tCkAmcFV7hlj6GQ_DCJK2jCzvEmdK7NBE
135
135
  cli/ui/components/settings.js,sha256=FXcn-UQE2mXC6HFsLeEas-wAUFKt0OJaLySroZQMhGA,84095
136
136
  cli/ui/components/sidebar.js,sha256=K2ym2kUgpbyG-EBA_wBIIiqQY8qTatsiBZwzseMWuIQ,9939
137
137
  cli/ui/components/tasks.js,sha256=vyKQ3uwoppMwvdEaHlhWXW4oWcAisx4NveqzMhsYqHo,38438
138
- code_context_control-2.160.0.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
138
+ code_context_control-2.161.0.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
139
139
  core/__init__.py,sha256=qiheEC2r3KCd3vscukDVkjCXFcadzGgNhDhs9PbLVPA,2835
140
140
  core/blas_threads.py,sha256=Do7pR9YdumshhOmP6TV5oAv65i3gN7Lvt93b5EAO1bo,1256
141
141
  core/codex_patch.py,sha256=CxvT_rQIwPNTRJZj9EHJmx0ZdOeSLxjiixuLI3Z7lPc,2107
@@ -169,11 +169,11 @@ oracle/services/insight_engine.py,sha256=lwcdXtjt3CSZLqHVpXx6SG5gDhZYUKwXt4Z8dGy
169
169
  oracle/services/local_session.py,sha256=nkawOjDbotUp5wtZQnC1wPDw3HopNYMkoYqWpP5ToCU,9227
170
170
  oracle/services/memory_reader.py,sha256=rSEmoIXQu2JkolHJIQWpn0piPJpyuf1KZvW_9liQwkU,3727
171
171
  oracle/services/memory_writer.py,sha256=hpvYsxjhl293jEjGcRKfjG5njUaAOXKqbmJaUu1WdUU,6997
172
- oracle/services/mobile_api.py,sha256=ficoM5OlPGbyegryXJokABaaw7sxUdbl7mFaAN34krw,152332
172
+ oracle/services/mobile_api.py,sha256=SNcu0o_J0ym0H7lyTVccJBD7TTiSqzM7kFSFyucZ8eQ,153291
173
173
  oracle/services/mobile_fleet.py,sha256=1M6vN4vOlYdVt1qFDSK97PLPHjvZkus4ZZSRm-ow2Nc,23968
174
174
  oracle/services/project_scanner.py,sha256=PkYJtwOLRME1EzwRy3GIkYk6Xw0u1_BzFcaMJ5gJ1_s,6118
175
175
  oracle/services/review_agent.py,sha256=m_fzoHowpiibf0_iz3dF72LWSrwB_FbDd1am-SbeWXg,11273
176
- oracle/services/schedule_api.py,sha256=wArv-2QE-P1qn5gNiMGisXA4kX-JJvsRabFpVqsClzQ,9212
176
+ oracle/services/schedule_api.py,sha256=6NgmSYf2h4RSwqChuKvceWvRq3jC_ACdBKcZGi9-Wqs,12798
177
177
  oracle/services/scheduler.py,sha256=cz6N1YXv2OdseJ8_XBS5szt_zjkcvd27xYfbF3to2kM,14730
178
178
  oracle/services/tool_executor.py,sha256=xtAkBWkclh_FwOgzprjGkyRIV8-A7Lc3bz0UFPShrv0,1113
179
179
  oracle/services/tool_registry.py,sha256=mJUZSS99PDH8whkndNxcQXT1uoNxPviE3MotGzj2jtk,26046
@@ -305,8 +305,8 @@ services/router.py,sha256=Cz10nx2fKTbaGn14mSBePWIDrw5rdcs_1JFYXeik084,15626
305
305
  services/runtime.py,sha256=W7Og5gmLVEjm6IG3oT-l046-b6pmz5VUaZ1asZu4W-o,13898
306
306
  services/scanner.py,sha256=lH0aiDCdCRruKS-VTAD_LsF4zrhMLpMRhFlOZZlw4VM,9613
307
307
  services/schedule_approvals.py,sha256=tzf_YTnOoJf-DOx3m83m54EQnNBXE752nv4eE6N0PwU,8516
308
- services/schedule_runner.py,sha256=WkWrPhLa2j_Z06l7R9cJEE6zhlzn4aV58w619Ewarvk,11997
309
- services/schedule_store.py,sha256=CnhqbDjolpslBVT8kAaN1wf0s9b2q5KRhJJdZHlglHo,25147
308
+ services/schedule_runner.py,sha256=Rk05QsGT-lTqDA_FHWdyGCVFRUCnygmpbJtUjdGc6hE,21519
309
+ services/schedule_store.py,sha256=NyweZBYG3E6RS9Rx72aa6vcMk6Brt-tVwdpLUHJ1ok0,25789
310
310
  services/session_benchmark.py,sha256=KUcWWC5X088p_ao6DgglUMwj7jCzdecPKxJ7XiGKob0,106255
311
311
  services/session_catalog.py,sha256=P57Z4OUnx6hbLKECJ1Xzxz8BCKxxPncAqx1cB7HbXwo,47607
312
312
  services/session_live.py,sha256=RPFhxqVh0QmKIDn_PN0OxjpK2wHOOrvJkIgsvogMuwQ,5646
@@ -354,8 +354,8 @@ tui/screens/search_view.py,sha256=MMHjVdlk3HZSuDBSvq8IGrqv_Mh5Us6YqXQ80bcWSMk,19
354
354
  tui/screens/session_view.py,sha256=eZ1eDwHTvPOck1wCCviixtOaCxIkBT_95ytNNNriGNA,5991
355
355
  tui/screens/stats.py,sha256=p81PjzdaIv7hllb8f45-rlVe4lJZwSdIMqu7e86_u5s,6223
356
356
  tui/screens/ui_view.py,sha256=1QJCgLh2YfgWIpvzRG1KOGXYEaOYX6ojN61Azjf2oX0,2125
357
- code_context_control-2.160.0.dist-info/METADATA,sha256=CYjsfkLA26nOOIcsEFO7Myo5b4-2kuypQqrW-2gZfzQ,29355
358
- code_context_control-2.160.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
- code_context_control-2.160.0.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
- code_context_control-2.160.0.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
- code_context_control-2.160.0.dist-info/RECORD,,
357
+ code_context_control-2.161.0.dist-info/METADATA,sha256=RYTXEHC7XZbgWpo422zZ7iZ5VmXrzDOdRAoKSmZR688,29355
358
+ code_context_control-2.161.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
+ code_context_control-2.161.0.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
+ code_context_control-2.161.0.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
+ code_context_control-2.161.0.dist-info/RECORD,,
@@ -87,6 +87,8 @@ from services.atomic_json import write_json_atomic
87
87
  # and /overrides/policy/clear; built-in guards read + tighten + lease
88
88
  # revoke (/access/builtin*); the session catalog (/sessions*, no
89
89
  # transcript text by default); and /now.
90
+ # 7 (unchanged, additive): `schedule_output` capability and
91
+ # GET /schedules/runs/<run_id>/output, a run's stdout paged by line.
90
92
  API_VERSION = 7
91
93
 
92
94
  CAPABILITIES = [
@@ -105,7 +107,8 @@ CAPABILITIES = [
105
107
  "jobs", "ci",
106
108
  # Scheduled tasks (/schedules): read the schedules, their runs and pending
107
109
  # approvals; write = create/edit/run-now/decide (docs/scheduled-tasks.md).
108
- "schedules", "schedules_write",
110
+ # schedule_output: a run's stdout while it runs and after it ends.
111
+ "schedules", "schedules_write", "schedule_output",
109
112
  # Poll-based chat transport, served by services/chat_poll.py under
110
113
  # /api/mobile/chat/*. Advertised here because /info is the single place a
111
114
  # client probes; the routes themselves live in that blueprint.
@@ -139,6 +142,7 @@ _CAPABILITY_SWITCHES = {
139
142
  "suggestions_write": "mobile_suggestions_write",
140
143
  "schedules": "mobile_schedules_enabled",
141
144
  "schedules_write": "mobile_schedules_write",
145
+ "schedule_output": "mobile_schedules_enabled",
142
146
  # v7: each overview goes dark with the subsystem it reads; locks_overview
143
147
  # and now are ops reads like /locks and /status, so always on.
144
148
  "access_overview": "mobile_access_enabled",
@@ -1194,6 +1198,21 @@ def mobile_schedule_runs():
1194
1198
  return jsonify({"runs": rows, "count": len(rows), "project": project_path})
1195
1199
 
1196
1200
 
1201
+ @bp.route("/schedules/runs/<run_id>/output", methods=["GET"])
1202
+ def mobile_schedule_run_output(run_id):
1203
+ """A run's stdout lines after ``after`` (query: after, limit); see schedule_api.run_output."""
1204
+ gate = _feature_or_404("schedule_output")
1205
+ if gate:
1206
+ return gate
1207
+ api = _schedule_api()
1208
+ run = api._get_store().get_run(str(run_id))
1209
+ if run is None or _resolve_registered(str(run.get("project_path") or "")) is None:
1210
+ return jsonify({"error": "unknown run"}), 404
1211
+ data, err = _schedule_call(api.run_output, str(run_id), after=request.args.get("after"),
1212
+ limit=request.args.get("limit"))
1213
+ return err or jsonify(data)
1214
+
1215
+
1197
1216
  @bp.route("/schedules/approvals", methods=["GET"])
1198
1217
  def mobile_schedule_approvals():
1199
1218
  gate = _feature_or_404("schedules")
@@ -13,9 +13,13 @@ from pathlib import Path
13
13
 
14
14
  from flask import Blueprint, jsonify, request
15
15
 
16
+ from services import schedule_runner as runner
16
17
  from services.cron_expr import preview, validate_when
17
18
  from services.schedule_approvals import ApprovalError
18
- from services.schedule_store import RUN_STATUSES, RevConflict, ScheduleError
19
+ from services.schedule_store import OPEN_RUN_STATUSES, RUN_STATUSES, RevConflict, ScheduleError
20
+
21
+ OUTPUT_DEFAULT_LIMIT = 500
22
+ OUTPUT_MAX_LIMIT = 2000
19
23
 
20
24
  bp = Blueprint("schedule_api", __name__, url_prefix="/api/schedules")
21
25
 
@@ -131,6 +135,85 @@ def preview_when(body: dict) -> dict:
131
135
  return {"when": when, "next": [f.isoformat() for f in fires]}
132
136
 
133
137
 
138
+ def run_output(run_id: str, after=0, limit=OUTPUT_DEFAULT_LIMIT, *, jobstore=None) -> dict:
139
+ """One page of a run's stdout: the lines numbered ``n > after``.
140
+
141
+ Reads ``schedule_runs/<run_id>.out`` once the run has one; before that the
142
+ job's spool while it runs (``live``, complete lines only) or its kept
143
+ output once it ended (``output_store``). A line keeps its number across
144
+ the three. ``after`` and ``limit`` may be strings from a query;
145
+ ``limit`` is clamped to 1..2000. Raises ``ApiError`` 404 for an unknown
146
+ run and 400 for a non-integer ``after``/``limit``.
147
+ """
148
+ store = _get_store()
149
+ run = store.get_run(str(run_id or ""))
150
+ if run is None:
151
+ raise ApiError(f"no run {run_id}", 404)
152
+ after = _int_arg(after, 0, "after")
153
+ limit = min(max(_int_arg(limit, OUTPUT_DEFAULT_LIMIT, "limit"), 1), OUTPUT_MAX_LIMIT)
154
+ status = run.get("status")
155
+ out = {"run_id": run["run_id"], "status": status, "open": status in OPEN_RUN_STATUSES,
156
+ "job_id": run.get("job_id") or None, "format": _run_format(store, run),
157
+ "source": "none", "lines": [], "next": after, "total": 0, "dropped": 0,
158
+ "stderr_tail": str(run.get("stderr_tail") or "")}
159
+
160
+ def page(path, source: str, first_n: int = 1) -> bool:
161
+ try:
162
+ lines, total = runner.page_lines(path, first_n=first_n, after=after, limit=limit,
163
+ complete_only=source == "live")
164
+ except OSError:
165
+ return False
166
+ out.update(source=source, lines=lines, total=total, next=lines[-1]["n"] if lines else after)
167
+ return True
168
+
169
+ archive = store.runs_dir / f"{run['run_id']}.out"
170
+ if run.get("output_lines") is not None and archive.is_file():
171
+ dropped = int(run.get("output_dropped") or 0)
172
+ if page(archive, "archive", dropped + 1):
173
+ out["dropped"] = dropped
174
+ return out
175
+ job_id = run.get("job_id")
176
+ if not job_id:
177
+ return out
178
+ jobs = jobstore if jobstore is not None else _jobstore()
179
+ job = jobs.find(job_id)
180
+ if job is not None and not job.terminal and job.spool.get("stdout"):
181
+ if page(job.spool["stdout"], "live"):
182
+ return out
183
+ job = jobs.find(job_id) # the spool was promoted between the two reads
184
+ if job is not None and job.terminal:
185
+ path = runner.job_stream_path(jobs, job, "stdout")
186
+ if path is not None:
187
+ page(path, "output_store")
188
+ return out
189
+
190
+
191
+ def _int_arg(value, default: int, name: str) -> int:
192
+ if value is None or value == "":
193
+ return default
194
+ try:
195
+ return max(0, int(value))
196
+ except (TypeError, ValueError) as exc:
197
+ raise ApiError(f"{name} must be an integer", 400) from exc
198
+
199
+
200
+ def _run_format(store, run: dict) -> str:
201
+ if run.get("output_format"):
202
+ return str(run["output_format"])
203
+ if run.get("status") in ("check_running", "check_skipped"):
204
+ return "text"
205
+ schedule = store.get(run.get("schedule_id") or "")
206
+ return runner.output_format(schedule) if schedule else "text"
207
+
208
+
209
+ def _jobstore():
210
+ jobstore = getattr(_get_scheduler(), "jobstore", None)
211
+ if jobstore is not None:
212
+ return jobstore
213
+ from services.shell_jobs import JobStore
214
+ return JobStore()
215
+
216
+
134
217
  def _limit(default: int = 50, cap: int = 500) -> int:
135
218
  try:
136
219
  return max(1, min(int(request.args.get("limit") or default), cap))
@@ -198,6 +281,11 @@ def one_run(run_id: str):
198
281
  return jsonify(run)
199
282
 
200
283
 
284
+ @bp.route("/runs/<run_id>/output", methods=["GET"])
285
+ def one_run_output(run_id: str):
286
+ return jsonify(run_output(run_id, after=request.args.get("after"), limit=request.args.get("limit")))
287
+
288
+
201
289
  @bp.route("/approvals", methods=["GET"])
202
290
  def approvals():
203
291
  status = (request.args.get("status") or "").strip() or None
@@ -10,10 +10,13 @@ owns the order in which that happens.
10
10
  from __future__ import annotations
11
11
 
12
12
  import json
13
+ import os
13
14
  import shutil
14
15
  from dataclasses import dataclass, field
16
+ from pathlib import Path
15
17
 
16
18
  from services.schedule_store import EXECUTED_STATUSES, ScheduleStore, prompt_text
19
+ from services.shell_output import OutputAccessError, _restrict_file
17
20
 
18
21
  SESSION_ID = "scheduler"
19
22
  CLAUDE_NESTING_VARS = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SESSION_ID",
@@ -23,6 +26,12 @@ CODEX_EFFORTS = {"": "medium", "low": "low", "medium": "medium", "high": "high",
23
26
  GROK_EFFORTS = {"": "", "low": "low", "medium": "medium", "high": "high", "xhigh": "high", "max": "high"}
24
27
  JOB_TO_RUN = {"done": "done", "failed": "failed", "timeout": "timeout",
25
28
  "cancelled": "cancelled", "lost": "lost"}
29
+ ARCHIVE_MAX_BYTES = 8 * 1024 * 1024
30
+ STDERR_TAIL_LINES = 60
31
+ STDERR_TAIL_BYTES = 8 * 1024
32
+ OUTPUT_PAGE_BYTES = 1024 * 1024
33
+ OUTPUT_LINE_CLIP = 256 * 1024
34
+ _CHUNK = 1024 * 1024
26
35
 
27
36
 
28
37
  class PlanError(ValueError):
@@ -86,7 +95,7 @@ def _exe(name: str) -> str:
86
95
 
87
96
  def _plan_claude(schedule: dict, prompt: str, cwd: str, timeout_s: int, _prompt_file: str) -> FirePlan:
88
97
  from cli.tools.delegate import _EFFORT_LEVELS, _MODEL_NAME_RE
89
- argv = [_exe("claude"), "-p", "--output-format", "json", "--no-session-persistence",
98
+ argv = [_exe("claude"), "-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence",
90
99
  "--permission-mode", str(schedule.get("permission_mode") or "acceptEdits"),
91
100
  "--permission-prompts", "none", "--name", f"sched:{schedule.get('id', '')}"]
92
101
  model = str(schedule.get("model") or "").strip()
@@ -145,6 +154,14 @@ def _plan_grok(schedule: dict, prompt: str, cwd: str, timeout_s: int, prompt_fil
145
154
  _PROVIDERS = {"claude": _plan_claude, "codex": _plan_codex, "gemini": _plan_gemini, "grok": _plan_grok}
146
155
 
147
156
 
157
+ def output_format(schedule: dict) -> str:
158
+ """How a client reads this schedule's stdout: ``claude-stream``, ``codex-json`` or ``text``."""
159
+ if schedule.get("kind") == "command":
160
+ return "text"
161
+ provider = str(schedule.get("provider") or "claude")
162
+ return {"claude": "claude-stream", "codex": "codex-json"}.get(provider, "text")
163
+
164
+
148
165
  def dispatch(store: ScheduleStore, jobstore, schedule: dict, run: dict, *, check: bool = False) -> dict:
149
166
  """Start the job for ``run`` and record it; a spawn failure finishes the run."""
150
167
  run_id = run["run_id"]
@@ -160,22 +177,37 @@ def dispatch(store: ScheduleStore, jobstore, schedule: dict, run: dict, *, check
160
177
  job = jobstore.start(project_path=schedule["project_path"], session_id=SESSION_ID,
161
178
  cmd=fire.display, cwd=fire.cwd, timeout_s=fire.timeout_s,
162
179
  payload=fire.payload())
180
+ fmt = "text" if check else output_format(schedule)
163
181
  if job.terminal and job.status != "done":
164
- return store.finish_run(run_id, JOB_TO_RUN.get(job.status, "failed"), job_id=job.id,
165
- exit_code=job.exit_code, error=job.error or "job ended before it ran")
182
+ status = JOB_TO_RUN.get(job.status, "failed")
183
+ return store.finish_run(run_id, status, job_id=job.id, exit_code=job.exit_code,
184
+ error=job.error or "job ended before it ran", output_format=fmt,
185
+ **_output_fields(store, jobstore, run_id, job, status))
166
186
  status = "check_running" if check else "dispatched"
167
- return store.update_run(run_id, status=status, job_id=job.id, dispatched_at=job.created_at)
187
+ return store.update_run(run_id, status=status, job_id=job.id, dispatched_at=job.created_at,
188
+ output_format=fmt)
189
+
190
+
191
+ def job_stream_path(jobstore, job, stream: str = "stdout") -> Path | None:
192
+ """Where a terminal job's kept ``stream`` lives, or None when it was not kept or has expired."""
193
+ if not getattr(job, "output_id", ""):
194
+ return None
195
+ try:
196
+ meta = jobstore.output_store.resolve(job.output_id, project_path=job.project_path,
197
+ session_id=job.session_id, guard_check=lambda _p: None)
198
+ return Path(meta.stream_path(stream))
199
+ except (OutputAccessError, OSError, ValueError):
200
+ return None
168
201
 
169
202
 
170
203
  def job_stdout(jobstore, job) -> str:
171
204
  """Raw kept stdout of a terminal job, or empty when it was not kept."""
172
- if not job.output_id:
205
+ path = job_stream_path(jobstore, job, "stdout")
206
+ if path is None:
173
207
  return ""
174
208
  try:
175
- meta = jobstore.output_store.resolve(job.output_id, project_path=job.project_path,
176
- session_id=job.session_id, guard_check=lambda _p: None)
177
- return meta.stream_path("stdout").read_bytes().decode("utf-8", "replace")
178
- except Exception:
209
+ return path.read_bytes().decode("utf-8", "replace")
210
+ except OSError:
179
211
  return ""
180
212
 
181
213
 
@@ -183,7 +215,10 @@ def parse_result(parser: str, stdout: str) -> dict:
183
215
  """Cost, tokens, turns, model and a result excerpt from a provider's JSON stdout."""
184
216
  if parser == "claude":
185
217
  from cli.tools.delegate import parse_claude_json
186
- text, _ok, stats = parse_claude_json(stdout)
218
+ result_line, last_text = _claude_stream(stdout)
219
+ if result_line is None and last_text:
220
+ return {"result_excerpt": last_text}
221
+ text, _ok, stats = parse_claude_json(stdout if result_line is None else result_line)
187
222
  out = {"result_excerpt": text}
188
223
  tokens = {k: stats[k] for k in ("input_tokens", "output_tokens", "cache_read_tokens",
189
224
  "cache_write_tokens") if k in stats}
@@ -214,6 +249,34 @@ def parse_result(parser: str, stdout: str) -> dict:
214
249
  return {"result_excerpt": stdout.strip()}
215
250
 
216
251
 
252
+ def _claude_stream(stdout: str) -> tuple[str | None, str]:
253
+ """The last ``result`` event line of a stream-json transcript and the last assistant text.
254
+
255
+ ``(None, "")`` for a single JSON document without a ``type``; a stream cut
256
+ off before its result (timeout, cancel) gives ``(None, <last text the
257
+ model wrote>)``. Split on newlines only: an event may carry a raw U+2028.
258
+ """
259
+ result_line, last_text = None, ""
260
+ for line in (stdout or "").split("\n"):
261
+ line = line.strip()
262
+ if not line.startswith("{"):
263
+ continue
264
+ try:
265
+ event = json.loads(line)
266
+ except ValueError:
267
+ continue
268
+ if not isinstance(event, dict):
269
+ continue
270
+ if event.get("type") == "result":
271
+ result_line = line
272
+ elif event.get("type") == "assistant":
273
+ content = (event.get("message") or {}).get("content")
274
+ texts = [str(c.get("text") or "") for c in content or [] if isinstance(c, dict) and c.get("type") == "text"]
275
+ if any(texts):
276
+ last_text = "\n".join(t for t in texts if t).strip()
277
+ return result_line, last_text
278
+
279
+
217
280
  def _trailing_json(text: str):
218
281
  raw = (text or "").strip()
219
282
  start = raw.find("{")
@@ -256,9 +319,189 @@ def finalize(store: ScheduleStore, jobstore, run: dict, job, parser: str = "comm
256
319
  stdout = job_stdout(jobstore, job)
257
320
  if stdout:
258
321
  extra.update(parse_result(parser, stdout))
322
+ extra.update(_output_fields(store, jobstore, run["run_id"], job, status))
259
323
  return store.finish_run(run["run_id"], status, **extra)
260
324
 
261
325
 
326
+ def _output_fields(store: ScheduleStore, jobstore, run_id: str, job, status: str) -> dict:
327
+ """The archive's run fields, plus ``stderr_tail`` when the run ended badly."""
328
+ fields = archive_output(store, jobstore, run_id, job)
329
+ if status != "done" or (job.exit_code or 0) != 0:
330
+ tail = stderr_tail(jobstore, job)
331
+ if tail:
332
+ fields["stderr_tail"] = tail
333
+ return fields
334
+
335
+
336
+ def archive_output(store: ScheduleStore, jobstore, run_id: str, job) -> dict:
337
+ """Copy the job's kept stdout to ``schedule_runs/<run_id>.out``, keeping its last 8 MiB.
338
+
339
+ Returns ``{"output_lines": lines in the whole stream, "output_dropped":
340
+ lines cut from its head}``, or ``{}`` when the job kept no stdout or the
341
+ copy failed. Line N of the archive is line ``output_dropped + N`` of the
342
+ stream. The archive starts at a line boundary unless the stream's last
343
+ line alone is longer than the cap; then it holds that line's tail.
344
+ """
345
+ src = job_stream_path(jobstore, job, "stdout")
346
+ if src is None:
347
+ return {}
348
+ dst = store.runs_dir / f"{run_id}.out"
349
+ tmp = dst.with_name(dst.name + ".tmp")
350
+ try:
351
+ with open(src, "rb") as fh:
352
+ size = os.fstat(fh.fileno()).st_size
353
+ start = _archive_start(fh, size)
354
+ fh.seek(0)
355
+ dropped = _count_lines(fh, start, complete_only=True)
356
+ lines = dropped + _count_lines(fh, size, complete_only=False)
357
+ fh.seek(start)
358
+ store.runs_dir.mkdir(parents=True, exist_ok=True)
359
+ with open(tmp, "wb") as out:
360
+ shutil.copyfileobj(fh, out, _CHUNK)
361
+ os.replace(tmp, dst)
362
+ except OSError:
363
+ try:
364
+ tmp.unlink()
365
+ except OSError:
366
+ pass
367
+ return {}
368
+ _restrict_file(dst)
369
+ return {"output_lines": lines, "output_dropped": dropped}
370
+
371
+
372
+ def _archive_start(fh, size: int) -> int:
373
+ """Offset the archive copies from: the first line start inside the last ``ARCHIVE_MAX_BYTES``."""
374
+ if size <= ARCHIVE_MAX_BYTES:
375
+ return 0
376
+ cut = size - ARCHIVE_MAX_BYTES
377
+ fh.seek(cut)
378
+ pos = cut
379
+ while pos < size:
380
+ chunk = fh.read(min(_CHUNK, size - pos))
381
+ if not chunk:
382
+ break
383
+ nl = chunk.find(b"\n")
384
+ if nl >= 0:
385
+ start = pos + nl + 1
386
+ return start if start < size else cut
387
+ pos += len(chunk)
388
+ return cut
389
+
390
+
391
+ def stderr_tail(jobstore, job) -> str:
392
+ """The last ``STDERR_TAIL_LINES`` lines (at most ``STDERR_TAIL_BYTES``) of the job's stderr."""
393
+ path = job_stream_path(jobstore, job, "stderr")
394
+ if path is None:
395
+ return ""
396
+ try:
397
+ with open(path, "rb") as fh:
398
+ size = os.fstat(fh.fileno()).st_size
399
+ fh.seek(max(0, size - STDERR_TAIL_BYTES))
400
+ data = fh.read(STDERR_TAIL_BYTES)
401
+ except OSError:
402
+ return ""
403
+ lines = [line.rstrip("\r") for line in data.decode("utf-8", "replace").split("\n")]
404
+ if size > STDERR_TAIL_BYTES and len(lines) > 1:
405
+ lines = lines[1:] # the read started inside this line
406
+ while lines and not lines[-1]:
407
+ lines.pop()
408
+ return "\n".join(lines[-STDERR_TAIL_LINES:])
409
+
410
+
411
+ def page_lines(path, *, first_n: int = 1, after: int = 0, limit: int = 500,
412
+ max_bytes: int = OUTPUT_PAGE_BYTES, clip: int = OUTPUT_LINE_CLIP,
413
+ complete_only: bool = False) -> tuple[list[dict], int]:
414
+ """The lines of ``path`` numbered from ``first_n`` with ``n > after``, and the last line's number.
415
+
416
+ Returns ``([{"n", "text", "clipped"?}], total)``; ``total`` is
417
+ ``first_n - 1`` for an empty file. At most ``limit`` lines and about
418
+ ``max_bytes`` of text, but at least one line when one is due. A line
419
+ longer than ``clip`` bytes keeps its first ``clip`` bytes and carries
420
+ ``clipped: true``. ``complete_only`` leaves out a last line that has no
421
+ newline yet, for a file another process is still writing; the file is
422
+ read only up to its size at open. Raises ``OSError`` when it cannot be opened.
423
+ """
424
+ lines: list[dict] = []
425
+ with open(path, "rb") as fh:
426
+ size = os.fstat(fh.fileno()).st_size
427
+ n = first_n - 1
428
+ n += _skip_lines(fh, max(0, after - n), size)
429
+ used = 0
430
+ while len(lines) < limit and fh.tell() < size:
431
+ mark = fh.tell()
432
+ raw, complete, clipped = _read_line(fh, size, clip)
433
+ if not complete and complete_only:
434
+ fh.seek(mark)
435
+ break
436
+ if n + 1 > after:
437
+ cost = len(raw) + 1
438
+ if lines and used + cost > max_bytes:
439
+ fh.seek(mark)
440
+ break
441
+ used += cost
442
+ row = {"n": n + 1, "text": raw.decode("utf-8", "replace").rstrip("\r")}
443
+ if clipped:
444
+ row["clipped"] = True
445
+ lines.append(row)
446
+ n += 1
447
+ n += _count_lines(fh, size, complete_only=complete_only)
448
+ return lines, n
449
+
450
+
451
+ def _skip_lines(fh, count: int, size: int) -> int:
452
+ """Move past ``count`` newline-terminated lines (fewer at the end); returns how many."""
453
+ passed = 0
454
+ pos = resume = fh.tell()
455
+ while passed < count and pos < size:
456
+ chunk = fh.read(min(_CHUNK, size - pos))
457
+ if not chunk:
458
+ break
459
+ found = chunk.count(b"\n")
460
+ if found and passed + found <= count:
461
+ passed += found
462
+ resume = pos + chunk.rfind(b"\n") + 1
463
+ elif found:
464
+ idx = -1
465
+ for _ in range(count - passed):
466
+ idx = chunk.find(b"\n", idx + 1)
467
+ resume = pos + idx + 1
468
+ passed = count
469
+ pos += len(chunk)
470
+ fh.seek(resume)
471
+ return passed
472
+
473
+
474
+ def _read_line(fh, size: int, clip: int) -> tuple[bytes, bool, bool]:
475
+ """``(first clip bytes, complete, clipped)`` of the line at the cursor; consumes the whole line."""
476
+ raw = fh.readline(min(clip + 1, size - fh.tell()))
477
+ if raw.endswith(b"\n"):
478
+ return raw[:-1], True, False
479
+ if len(raw) <= clip:
480
+ return raw, False, False
481
+ while fh.tell() < size:
482
+ more = fh.readline(min(_CHUNK, size - fh.tell()))
483
+ if not more:
484
+ break
485
+ if more.endswith(b"\n"):
486
+ return raw[:clip], True, True
487
+ return raw[:clip], False, True
488
+
489
+
490
+ def _count_lines(fh, end: int, *, complete_only: bool) -> int:
491
+ """Lines from the cursor to ``end``; a last one with no newline counts unless ``complete_only``."""
492
+ count, last, pos = 0, b"\n", fh.tell()
493
+ while pos < end:
494
+ chunk = fh.read(min(_CHUNK, end - pos))
495
+ if not chunk:
496
+ break
497
+ count += chunk.count(b"\n")
498
+ last = chunk[-1:]
499
+ pos += len(chunk)
500
+ if last != b"\n" and not complete_only:
501
+ count += 1
502
+ return count
503
+
504
+
262
505
  def cli_available(provider: str) -> bool:
263
506
  return bool(shutil.which({"claude": "claude", "codex": "codex", "gemini": "gemini",
264
507
  "grok": "grok"}.get(provider, provider)))
@@ -20,6 +20,7 @@ from __future__ import annotations
20
20
 
21
21
  import json
22
22
  import os
23
+ import re
23
24
  import threading
24
25
  import time
25
26
  import uuid
@@ -72,7 +73,12 @@ _RUN_FIELDS = (
72
73
  "run_id", "schedule_id", "schedule_name", "project_path", "trigger", "due_at", "claimed_at",
73
74
  "dispatched_at", "finished_at", "status", "job_id", "approval_id", "exit_code", "duration_ms",
74
75
  "output_id", "cost_usd", "tokens", "turns", "model", "result_excerpt", "error",
76
+ "output_format", "output_lines", "output_dropped", "stderr_tail",
75
77
  )
78
+ # Files kept beside ``<run_id>.json`` and swept with it: the stdout archive
79
+ # (services/schedule_runner.archive_output) and grok's prompt file.
80
+ RUN_SIDE_FILES = (".out", ".out.tmp", ".prompt.txt")
81
+ _RUN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
76
82
 
77
83
 
78
84
  class ScheduleError(ValueError):
@@ -454,6 +460,8 @@ class ScheduleStore:
454
460
  write_json_atomic(self._run_path(run["run_id"]), run, ensure_ascii=False, fsync=False)
455
461
 
456
462
  def get_run(self, run_id: str) -> dict | None:
463
+ if not _RUN_ID_RE.match(run_id or ""):
464
+ return None
457
465
  path = self._run_path(run_id)
458
466
  if not path.exists():
459
467
  return None
@@ -555,7 +563,12 @@ class ScheduleStore:
555
563
  self._run_path(run["run_id"]).unlink()
556
564
  removed += 1
557
565
  except OSError:
558
- pass
566
+ continue
567
+ for suffix in RUN_SIDE_FILES:
568
+ try:
569
+ (self.runs_dir / f"{run['run_id']}{suffix}").unlink(missing_ok=True)
570
+ except OSError:
571
+ pass
559
572
  return removed
560
573
 
561
574