python-codex 0.4.8__py3-none-any.whl → 0.5.1__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.
pycodex/agent.py CHANGED
@@ -17,6 +17,7 @@ from .events import (
17
17
  ModelCalledEvent,
18
18
  ModelCompletedEvent,
19
19
  ModelEvent,
20
+ ModelRequestTimingEvent,
20
21
  StreamErrorEvent,
21
22
  TerminalEvent,
22
23
  TokenCountEvent,
@@ -558,7 +559,7 @@ class Agent:
558
559
  self._emit(started_type(*details))
559
560
 
560
561
  def handle_compact_stream_event(event: "ModelEvent") -> "None":
561
- if isinstance(event, StreamErrorEvent) or (
562
+ if isinstance(event, (StreamErrorEvent, ModelRequestTimingEvent)) or (
562
563
  phase == "manual" and isinstance(event, TokenCountEvent)
563
564
  ):
564
565
  self._emit(replace(event, turn_id=turn_id))
pycodex/events.py CHANGED
@@ -271,6 +271,17 @@ class TokenCountEvent(ModelEvent):
271
271
  display.set_prompt(display.main_prompt())
272
272
 
273
273
 
274
+ @dataclass(frozen=True)
275
+ class ModelRequestTimingEvent(ModelEvent):
276
+ model: "str"
277
+ elapsed_seconds: "float"
278
+ first_data_seconds: "typing.Union[float, None]"
279
+ outcome: "str"
280
+ turn_id: "str" = ""
281
+ submission_id: "typing.Union[str, None]" = None
282
+ kind: ClassVar[str] = "model_request_timing"
283
+
284
+
274
285
  @dataclass(frozen=True)
275
286
  class StreamErrorEvent(ModelEvent):
276
287
  message: "str"
@@ -285,9 +296,14 @@ class StreamErrorEvent(ModelEvent):
285
296
  def visualize(self) -> "str":
286
297
  return self.message
287
298
 
299
+ def detail(self) -> "str":
300
+ if not self.error:
301
+ return self.message
302
+ return "{0}\n{1}".format(self.message, self.error)
303
+
288
304
  def render(self, display: "EventDisplay") -> "None":
289
305
  display.stream_buffer = ""
290
- display.write("[status] " + self.visualize(), "status")
306
+ display.write("[status] " + self.detail(), "status")
291
307
  display.set_status("reconnecting")
292
308
 
293
309
 
pycodex/model.py CHANGED
@@ -8,9 +8,11 @@ import urllib.parse
8
8
  import uuid
9
9
  from dataclasses import dataclass, field, replace
10
10
  from pathlib import Path
11
+ from time import monotonic
11
12
  from typing import Callable
12
13
 
13
14
  import requests
15
+ from urllib3.exceptions import ReadTimeoutError
14
16
 
15
17
  from .utils.compat import Protocol
16
18
 
@@ -22,6 +24,7 @@ except ModuleNotFoundError: # pragma: no cover - Python 3.10 path
22
24
  from .events import (
23
25
  AssistantDeltaEvent,
24
26
  ModelEvent,
27
+ ModelRequestTimingEvent,
25
28
  StreamErrorEvent,
26
29
  TokenCountEvent,
27
30
  ToolCalledEvent,
@@ -48,7 +51,7 @@ DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000
48
51
  INITIAL_RETRY_DELAY_SECONDS = 0.2
49
52
  RETRY_BACKOFF_FACTOR = 2.0
50
53
  RATE_LIMIT_RETRY_AFTER_RE = re.compile(
51
- r"(?i)try again in\s*(\d+(?:\.\d+)?)\s*(s|ms|seconds?)"
54
+ r"(?i)(?:try again in|retry after)\s*(\d+(?:\.\d+)?)\s*(ms|seconds?|s)"
52
55
  )
53
56
 
54
57
 
@@ -97,6 +100,19 @@ class ResponsesProviderConfig:
97
100
  stream_idle_timeout_ms: "typing.Union[int, None]" = None
98
101
  service_tier: "typing.Union[str, None]" = None
99
102
  responses_lite_override: "typing.Union[bool, None]" = None
103
+ fallback_models: "typing.Tuple[str, ...]" = ()
104
+ fallback_cooldown_seconds: "int" = 900
105
+ stream_first_data_timeout_ms: "typing.Union[int, None]" = None
106
+
107
+ def __post_init__(self):
108
+ cooldown = self.fallback_cooldown_seconds
109
+ if isinstance(cooldown, bool) or not isinstance(cooldown, int) or cooldown < 0:
110
+ raise ValueError("fallback_cooldown_seconds must be a non-negative integer")
111
+ value = self.stream_first_data_timeout_ms
112
+ if value is not None and (
113
+ isinstance(value, bool) or not isinstance(value, int) or value <= 0
114
+ ):
115
+ raise ValueError("stream_first_data_timeout_ms must be a positive integer")
100
116
 
101
117
  @classmethod
102
118
  def from_codex_config(
@@ -142,6 +158,12 @@ class ResponsesProviderConfig:
142
158
  use_chat_completion = _optional_bool(provider.get("use_chat_completion"))
143
159
  if use_chat_completion is None:
144
160
  use_chat_completion = False
161
+ fallback_models = provider.get("fallback_models", [])
162
+ if not isinstance(fallback_models, list) or any(
163
+ not isinstance(model, str) or not model or any(c.isspace() for c in model)
164
+ for model in fallback_models
165
+ ):
166
+ raise ValueError("fallback_models must be an array of non-empty model IDs")
145
167
  return cls(
146
168
  model=selected["model"],
147
169
  provider_name=provider_name,
@@ -160,6 +182,9 @@ class ResponsesProviderConfig:
160
182
  stream_idle_timeout_ms=_optional_int(
161
183
  provider.get("stream_idle_timeout_ms")
162
184
  ),
185
+ fallback_models=tuple(dict.fromkeys(fallback_models)),
186
+ fallback_cooldown_seconds=provider.get("fallback_cooldown_seconds", 900),
187
+ stream_first_data_timeout_ms=provider.get("stream_first_data_timeout_ms"),
163
188
  )
164
189
 
165
190
  def api_key(self) -> "typing.Union[str, None]":
@@ -361,6 +386,14 @@ class ResponsesRetryableError(ResponsesApiError):
361
386
  self.retry_delay_seconds = retry_delay_seconds
362
387
 
363
388
 
389
+ class ResponsesModelUnavailableError(ResponsesApiError):
390
+ """The selected model cannot serve this request; another model may work."""
391
+
392
+
393
+ class ResponsesFirstDataTimeout(ResponsesRetryableError):
394
+ """The configured wait for initial response data has expired."""
395
+
396
+
364
397
  @dataclass
365
398
  class _StreamDiagnostics:
366
399
  raw_lines_received: "int" = 0
@@ -369,6 +402,8 @@ class _StreamDiagnostics:
369
402
  last_sse_event_name: "str" = ""
370
403
  last_event_type: "str" = ""
371
404
  last_payload_excerpt: "str" = ""
405
+ started_at: "float" = field(default_factory=monotonic)
406
+ first_data_seconds: "typing.Union[float, None]" = None
372
407
 
373
408
 
374
409
  class ResponsesModelClient:
@@ -394,6 +429,7 @@ class ResponsesModelClient:
394
429
  self._originator = originator
395
430
  self._user_agent = user_agent or build_user_agent(originator)
396
431
  self._openai_subagent = openai_subagent
432
+ self._model_cooldowns: "typing.Dict[str, float]" = {}
397
433
 
398
434
  @property
399
435
  def model(self) -> "str":
@@ -402,6 +438,7 @@ class ResponsesModelClient:
402
438
  @model.setter
403
439
  def model(self, model: "str") -> "None":
404
440
  self._config = replace(self._config, model=model)
441
+ self._model_cooldowns.clear()
405
442
 
406
443
  @property
407
444
  def reasoning_effort(self) -> "typing.Union[str, None]":
@@ -486,6 +523,26 @@ class ResponsesModelClient:
486
523
  ) -> "ModelResponse":
487
524
  retries = 0
488
525
  max_retries = self._config.effective_stream_max_retries()
526
+ models = tuple(dict.fromkeys((self.model,) + self._config.fallback_models))
527
+ now = monotonic()
528
+ self._model_cooldowns = {
529
+ model: deadline
530
+ for model, deadline in self._model_cooldowns.items()
531
+ if model in models and deadline > now
532
+ }
533
+ available_models = [
534
+ model for model in models if model not in self._model_cooldowns
535
+ ]
536
+ if not available_models:
537
+ self._model_cooldowns.clear()
538
+ available_models = list(models)
539
+ fallback_models = iter(available_models)
540
+ first_model = next(fallback_models)
541
+ request_client = (
542
+ self
543
+ if first_model == self.model
544
+ else self.with_overrides(model=first_model)
545
+ )
489
546
  loop = asyncio.get_running_loop()
490
547
  active = True
491
548
  callback_lock = threading.Lock()
@@ -502,14 +559,35 @@ class ResponsesModelClient:
502
559
  try:
503
560
  while True:
504
561
  try:
505
- return await asyncio.to_thread(
506
- self._complete_sync,
507
- prompt,
508
- receive,
509
- )
510
- except ResponsesRetryableError as exc:
511
- if retries >= max_retries:
512
- raise
562
+ response = await asyncio.to_thread(request_client._complete_sync, prompt, receive)
563
+ self._model_cooldowns.pop(request_client.model, None)
564
+ return response
565
+ except (ResponsesRetryableError, ResponsesModelUnavailableError) as exc:
566
+ if (
567
+ isinstance(exc, ResponsesModelUnavailableError)
568
+ or (isinstance(exc, ResponsesFirstDataTimeout) and len(models) > 1)
569
+ or retries >= max_retries
570
+ ):
571
+ cooldown = self._config.fallback_cooldown_seconds
572
+ if len(models) > 1 and cooldown > 0:
573
+ self._model_cooldowns[request_client.model] = (
574
+ monotonic() + cooldown
575
+ )
576
+ fallback_model = next(fallback_models, None)
577
+ if fallback_model is None:
578
+ raise
579
+ event_handler(
580
+ StreamErrorEvent(
581
+ f"Falling back: {request_client.model} -> {fallback_model}",
582
+ 0,
583
+ max_retries,
584
+ 0.0,
585
+ str(exc),
586
+ )
587
+ )
588
+ request_client = self.with_overrides(model=fallback_model)
589
+ retries = 0
590
+ continue
513
591
  retries += 1
514
592
  delay_seconds = exc.retry_delay_seconds
515
593
  if delay_seconds is None:
@@ -545,6 +623,9 @@ class ResponsesModelClient:
545
623
  data=body,
546
624
  )
547
625
  diagnostics = _StreamDiagnostics()
626
+ completed = False
627
+ first_data_ms = self._config.stream_first_data_timeout_ms
628
+ first_timeout = first_data_ms / 1000.0 if first_data_ms is not None else None
548
629
  try:
549
630
  with requests.Session() as session:
550
631
  settings = session.merge_environment_settings(
@@ -558,8 +639,10 @@ class ResponsesModelClient:
558
639
  if verify is not None:
559
640
  settings["verify"] = verify
560
641
  timeout = (
561
- max(self._timeout_seconds, 1.0),
562
- self._config.effective_stream_idle_timeout_seconds(),
642
+ min(max(self._timeout_seconds, 1.0), first_timeout)
643
+ if first_timeout is not None else max(self._timeout_seconds, 1.0),
644
+ first_timeout if first_timeout is not None
645
+ else self._config.effective_stream_idle_timeout_seconds(),
563
646
  )
564
647
  response = session.send(
565
648
  prepared,
@@ -576,22 +659,62 @@ class ResponsesModelClient:
576
659
  )
577
660
  if _is_context_length_error_message(error_body):
578
661
  raise ContextLengthExceeded(message)
579
- if response.status_code >= 500:
580
- raise ResponsesRetryableError(message)
662
+ if response.status_code >= 500 or response.status_code in (408, 429):
663
+ raise ResponsesRetryableError(
664
+ message,
665
+ retry_delay_seconds=self._try_parse_retry_after_seconds(
666
+ "rate_limit_exceeded" if response.status_code == 429 else "",
667
+ error_body,
668
+ ),
669
+ )
670
+ if response.status_code in (403, 404):
671
+ raise ResponsesModelUnavailableError(message)
581
672
  raise ResponsesApiError(message)
582
- tracked_lines = self._track_stream_lines(
583
- response.iter_lines(chunk_size=1, decode_unicode=False),
584
- diagnostics,
585
- )
586
- return self._parse_stream(
673
+ if first_timeout is not None:
674
+ remaining = first_timeout - (monotonic() - diagnostics.started_at)
675
+ if remaining <= 0:
676
+ raise ResponsesFirstDataTimeout(
677
+ "responses first-data timeout after {:.1f}s".format(first_timeout)
678
+ )
679
+ _set_response_read_timeout(response, remaining)
680
+ lines = _stream_lines(self._track_stream_chunks(
681
+ response.iter_content(chunk_size=1, decode_unicode=False),
682
+ diagnostics, response,
683
+ ))
684
+ else:
685
+ lines = response.iter_lines(chunk_size=1, decode_unicode=False)
686
+ tracked_lines = self._track_stream_lines(lines, diagnostics)
687
+ result = self._parse_stream(
587
688
  tracked_lines,
588
689
  event_handler,
589
690
  diagnostics=diagnostics,
590
691
  )
692
+ completed = True
693
+ return result
591
694
  except requests.RequestException as exc:
592
- raise ResponsesRetryableError(
593
- self._format_transport_error(url, exc, diagnostics)
594
- ) from exc
695
+ error_type = ResponsesRetryableError
696
+ if (
697
+ first_timeout is not None and diagnostics.first_data_seconds is None
698
+ and (
699
+ isinstance(exc, requests.Timeout)
700
+ or isinstance(exc.__context__, ReadTimeoutError)
701
+ or any(isinstance(arg, ReadTimeoutError) for arg in exc.args)
702
+ )
703
+ ):
704
+ error_type = ResponsesFirstDataTimeout
705
+ error = error_type(self._format_transport_error(url, exc, diagnostics))
706
+ error.elapsed_seconds = monotonic() - diagnostics.started_at
707
+ error.first_data_seconds = diagnostics.first_data_seconds
708
+ raise error from exc
709
+ except ResponsesApiError as exc:
710
+ exc.elapsed_seconds = monotonic() - diagnostics.started_at
711
+ exc.first_data_seconds = diagnostics.first_data_seconds
712
+ raise
713
+ finally:
714
+ event_handler(ModelRequestTimingEvent(
715
+ self.model, monotonic() - diagnostics.started_at,
716
+ diagnostics.first_data_seconds, "completed" if completed else "failed",
717
+ ))
595
718
 
596
719
  def _build_payload(self, prompt: "Prompt") -> "typing.Dict[str, object]":
597
720
  use_responses_lite = self._config.use_responses_lite()
@@ -974,9 +1097,20 @@ class ResponsesModelClient:
974
1097
  diagnostics: "_StreamDiagnostics",
975
1098
  ):
976
1099
  for raw_line in response:
1100
+ if diagnostics.first_data_seconds is None:
1101
+ diagnostics.first_data_seconds = monotonic() - diagnostics.started_at
977
1102
  diagnostics.raw_lines_received += 1
978
1103
  yield raw_line
979
1104
 
1105
+ def _track_stream_chunks(self, chunks, diagnostics, response):
1106
+ for chunk in chunks:
1107
+ if chunk and diagnostics.first_data_seconds is None:
1108
+ diagnostics.first_data_seconds = monotonic() - diagnostics.started_at
1109
+ _set_response_read_timeout(
1110
+ response, self._config.effective_stream_idle_timeout_seconds()
1111
+ )
1112
+ yield chunk
1113
+
980
1114
  def _base_error_details(
981
1115
  self,
982
1116
  url: "str",
@@ -1010,6 +1144,8 @@ class ResponsesModelClient:
1010
1144
  details = self._base_error_details(url)
1011
1145
  if diagnostics is not None:
1012
1146
  details.extend(self._transport_diagnostics_details(diagnostics))
1147
+ details.append(("elapsed_seconds", round(monotonic() - diagnostics.started_at, 3)))
1148
+ details.append(("first_data_seconds", diagnostics.first_data_seconds))
1013
1149
  details.append(("exception", type(exc).__name__))
1014
1150
  details.append(("detail", str(exc) or repr(exc)))
1015
1151
  details.append(
@@ -1109,6 +1245,8 @@ class ResponsesModelClient:
1109
1245
  raise ContextLengthExceeded(
1110
1246
  self._format_response_failed_error(message, code)
1111
1247
  )
1248
+ if code in {"model_not_found", "model_not_available", "permission_denied"}:
1249
+ raise ResponsesModelUnavailableError(self._format_response_failed_error(message, code))
1112
1250
  if code in {
1113
1251
  "insufficient_quota",
1114
1252
  "invalid_prompt",
@@ -1210,6 +1348,34 @@ class ResponsesModelClient:
1210
1348
  return value
1211
1349
 
1212
1350
 
1351
+ def _set_response_read_timeout(response, seconds):
1352
+ # Keep-alive responses expose the socket on the urllib3 connection. For
1353
+ # Connection: close, http.client retains it on the response file instead.
1354
+ raw = getattr(response, "raw", None)
1355
+ connection = getattr(raw, "connection", None)
1356
+ sock = getattr(connection, "sock", None)
1357
+ if sock is None:
1358
+ fp = getattr(getattr(raw, "_fp", None), "fp", None)
1359
+ sock = getattr(getattr(fp, "raw", None), "_sock", None)
1360
+ if sock is not None:
1361
+ sock.settimeout(seconds)
1362
+
1363
+
1364
+ def _stream_lines(chunks):
1365
+ pending = None
1366
+ for chunk in chunks:
1367
+ if pending is not None:
1368
+ chunk = pending + chunk
1369
+ lines = chunk.splitlines()
1370
+ if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
1371
+ pending = lines.pop()
1372
+ else:
1373
+ pending = None
1374
+ yield from lines
1375
+ if pending is not None:
1376
+ yield pending
1377
+
1378
+
1213
1379
  def _optional_int(value: "object") -> "typing.Union[int, None]":
1214
1380
  if value is None:
1215
1381
  return None
pycodex/runtime.py CHANGED
@@ -240,8 +240,18 @@ class AgentRuntime:
240
240
  async def submit_input(self, text, sender="user"):
241
241
  if not self.agent.accepts_input:
242
242
  raise RuntimeError("agent is shutting down")
243
+ input_starts_with_space = text.startswith(" ")
243
244
  text = text.strip()
244
- if self._input_request is not None and not text.startswith("/"):
245
+ command = text.split(None, 1)[0] if text else ""
246
+ # Codex treats another slash in the name as a path and a leading
247
+ # ASCII space as an escape, even for a registered command.
248
+ is_command = (
249
+ command.startswith("/")
250
+ and not input_starts_with_space
251
+ and "/" not in command[1:]
252
+ and len(command) > 1
253
+ )
254
+ if self._input_request is not None and not is_command:
245
255
  self._answer_input(text)
246
256
  future = asyncio.get_running_loop().create_future()
247
257
  future.set_result(None)
@@ -251,14 +261,13 @@ class AgentRuntime:
251
261
  future.set_result(None)
252
262
  return SubmittedInput(uuid7_string(), "empty", future)
253
263
  parts = text.split(None, 1)
254
- command = parts[0]
255
264
  argument = parts[1] if len(parts) == 2 else ""
265
+ if not is_command:
266
+ return await self._submit_message(text, "steer", sender, False)
256
267
  if command == "/queue":
257
268
  if not argument.strip():
258
269
  raise ValueError("Usage: /queue <message>")
259
270
  return await self._submit_message(argument.strip(), "enqueue", sender, True)
260
- if not command.startswith("/"):
261
- return await self._submit_message(text, "steer", sender, False)
262
271
  submission_id = uuid7_string()
263
272
  future = asyncio.get_running_loop().create_future()
264
273
  try:
@@ -604,11 +613,15 @@ class AgentRuntime:
604
613
  "user_texts": list(event.user_texts),
605
614
  "assistant_text": "",
606
615
  "completed_history": conversation_history_to_turns(self.agent.history),
616
+ "model_errors": [],
607
617
  }
608
618
  elif self._active_turn is not None:
609
619
  if isinstance(event, AssistantDeltaEvent):
610
620
  self._active_turn["assistant_text"] += event.delta
611
- elif isinstance(event, (StreamErrorEvent, ToolCompletedEvent)):
621
+ elif isinstance(event, StreamErrorEvent):
622
+ self._active_turn["assistant_text"] = ""
623
+ self._active_turn["model_errors"].append(event.detail())
624
+ elif isinstance(event, ToolCompletedEvent):
612
625
  self._active_turn["assistant_text"] = ""
613
626
  elif isinstance(event, AutoCompactCompletedEvent):
614
627
  self._active_turn["completed_history"] = conversation_history_to_turns(
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-codex
3
+ Version: 0.5.1
4
+ Summary: A minimal Python extraction of Codex's main agent loop
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.6.2
7
+ Requires-Dist: dataclasses>=0.8; python_version < '3.7'
8
+ Requires-Dist: importlib-metadata>=4.8.3; python_version < '3.8'
9
+ Requires-Dist: loguru>=0.7.3
10
+ Requires-Dist: prompt-toolkit>=3.0.36
11
+ Requires-Dist: pyyaml>=6.0
12
+ Requires-Dist: requests>=2.27.1
13
+ Requires-Dist: starlette<0.20,>=0.19.1; python_version < '3.7'
14
+ Requires-Dist: starlette>=0.19.1; python_version >= '3.7'
15
+ Requires-Dist: tomli<2,>=1.2.3; python_version < '3.11'
16
+ Requires-Dist: typing-extensions>=4.1.1; python_version < '3.8'
17
+ Requires-Dist: uvicorn<0.17,>=0.16.0; python_version < '3.7'
18
+ Requires-Dist: uvicorn>=0.16.0; python_version >= '3.7'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pycodex
22
+
23
+ [中文](README_ZH.md)
24
+
25
+ pycodex brings the [Codex](https://github.com/openai/codex) agent loop to Python,
26
+ with a CLI, reusable Agent API and browser workspace. It aims to follow upstream
27
+ behavior; supported features and deliberate differences are documented in
28
+ [Alignment](docs/ALIGNMENT.md).
29
+
30
+ | Package | Provides | Python |
31
+ | --- | --- | --- |
32
+ | `python-codex` | Agent, runtime, CLI, tools, Responses compatibility server and portable storage | 3.6.2+ |
33
+ | `pycodex-ws` | Browser workspace, Canvas, file/diff viewers and optional Feishu integration | 3.7+ |
34
+
35
+ The workspace package installs the matching core version. Python imports use
36
+ `pycodex`; the commands are `pycodex` and `pycodex-ws`.
37
+
38
+ ## Install and run
39
+
40
+ Install the core CLI:
41
+
42
+ ```bash
43
+ python3 -m pip install python-codex
44
+ pycodex
45
+ ```
46
+
47
+ Or install the browser workspace, which includes core:
48
+
49
+ ```bash
50
+ python3 -m pip install pycodex-ws
51
+ pycodex-ws --help
52
+ ```
53
+
54
+ Use `python3 -m pip install --upgrade pycodex-ws` to upgrade both packages
55
+ together. If a command is missing from `PATH`, use `python3 -m pycodex` or
56
+ `python3 -m workspace_server` with the interpreter used for installation.
57
+
58
+ ## Model configuration
59
+
60
+ pycodex reads `~/.codex/config.toml` and the adjacent `.env`. Configure `model`,
61
+ `model_provider`, and the provider's `base_url` and `env_key` as needed.
62
+ The built-in `openai` provider uses `OPENAI_API_KEY`. Authentication uses API
63
+ keys; ChatGPT sign-in credentials from `auth.json` or the OS keychain are not
64
+ loaded.
65
+
66
+ ```bash
67
+ pycodex --profile my_profile "Summarize this repository."
68
+ pycodex --config /path/to/config.toml
69
+ pycodex doctor
70
+ ```
71
+
72
+ Models use the streaming Responses API. For a Chat Completions backend, set
73
+ `use_chat_completion = true` in its provider table. Other backend options include:
74
+
75
+ ```bash
76
+ pycodex --vllm-endpoint http://127.0.0.1:18000
77
+ pycodex --profile my_profile --use-messages
78
+ ```
79
+
80
+ See [context and configuration](docs/CONTEXT.md) and the
81
+ [Responses compatibility server](docs/responses_server/README.md).
82
+
83
+ ## CLI
84
+
85
+ Run `pycodex` without a prompt for an interactive session, or supply a prompt
86
+ for a single turn:
87
+
88
+ ```bash
89
+ pycodex "Summarize this repository in one sentence."
90
+ printf 'Reply with exactly OK.' | pycodex
91
+ pycodex --json "Reply with exactly OK."
92
+ ```
93
+
94
+ | Command | Purpose |
95
+ | --- | --- |
96
+ | `/model`, `/effort` | Show or change the model and reasoning effort |
97
+ | `/cd <directory>` | Change the session's working directory while idle |
98
+ | `/title`, `/history` | Manage the title and inspect conversation history |
99
+ | `/resume` | List saved sessions; pass an index or session UUID to resume |
100
+ | `/compact` | Summarize history to free context |
101
+ | `/fork` | Continue the current history under a new session ID |
102
+ | `/queue <message>` | Wait for the active turn to finish before submitting |
103
+
104
+ Ordinary input during a turn steers at the next safe sampling boundary.
105
+ Slash input uses Codex's command rules: `/data/project` and `/tmp/` are
106
+ ordinary messages, while an unknown single-component name such as `/modle`
107
+ or `/tmp` reports a command error. Start the input with a space to send any
108
+ slash-prefixed text literally, including known commands such as ` /model`.
109
+ These rules also apply to the browser workspace and Feishu.
110
+ Sessions are saved under `CODEX_HOME/sessions`. Set
111
+ `model_auto_compact_token_limit` in the configuration to compact automatically.
112
+
113
+ Ctrl+D or Ctrl+C closes the CLI after accepted work finishes. A second Ctrl+C
114
+ during closing exits immediately. Use `pycodex --help` for startup options.
115
+
116
+ ## Browser workspace
117
+
118
+ Create `workspaces.json`:
119
+
120
+ ```json
121
+ {
122
+ "workspaces": [
123
+ {"id": "demo", "work_dir": ".", "state_path": "demo", "enable_board": true}
124
+ ]
125
+ }
126
+ ```
127
+
128
+ ```bash
129
+ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
130
+ ```
131
+
132
+ Open `http://127.0.0.1:6007`. The workspace combines conversations with a live
133
+ HTML Canvas and read-only file/diff viewers. Click file links in replies to open
134
+ them, and use **Insert into chat** to add selected code to an editable draft.
135
+ Keep the server's stdin open: EOF initiates shutdown.
136
+ The gear button starts an Agent conversation for customizing the interface
137
+ through files in `~/.pycodex/frontend/`.
138
+
139
+ See the [workspace guide](packages/pycodex-ws/README.md) for session controls,
140
+ storage and Feishu setup. The separately distributed
141
+ [VS Code extension](packages/pycodex-ws/extensions/vscode/README.md) uses the same
142
+ workspace backend, including on Remote SSH hosts.
143
+
144
+ ## Python API
145
+
146
+ Use the standard model and tool setup from Python:
147
+
148
+ ```python
149
+ from pycodex.bootstrap import build_agent, build_model
150
+
151
+ agent = build_agent(build_model())
152
+ try:
153
+ result = agent.ask("Summarize this repository in one sentence.")
154
+ print(result.output_text)
155
+ finally:
156
+ agent.shutdown()
157
+ ```
158
+
159
+ For custom integrations, `Agent` accepts a model client, `ToolRegistry` and
160
+ `ContextConfig`. `await agent.run_turn([...])` runs an asynchronous turn;
161
+ `AgentRuntime` adds input queues, commands and frontend subscriptions.
162
+ See [runtime contracts and examples](docs/RUNTIME.md).
163
+
164
+ ## Portable configuration
165
+
166
+ Portable mode transfers an encrypted bundle of your configuration, instructions
167
+ and skills to another machine. Start a storage service in a separate terminal:
168
+
169
+ ```bash
170
+ python3 -m pycodex.portable.server --root .tmp/pycodex_storage --host 127.0.0.1 --port 5577
171
+ ```
172
+
173
+ Upload the default Codex home, or specify another directory:
174
+
175
+ ```bash
176
+ pycodex --put @127.0.0.1:5577
177
+ pycodex --put /path/to/.codex/@127.0.0.1:5577
178
+ ```
179
+
180
+ After verifying a download round trip, the command prints a reusable
181
+ `pycodex --call ...` command. Run it on the target machine using a storage
182
+ address reachable from that machine.
183
+
184
+ ## Development and reference
185
+
186
+ ```bash
187
+ uv sync --dev
188
+ uv run pycodex
189
+ uv run --dev pytest
190
+ ```
191
+
192
+ - [Test environments and coverage](tests/TESTS.md)
193
+ - [Architecture, package layout and runtime contracts](docs/RUNTIME.md)
194
+ - [Prompts, configuration and context](docs/CONTEXT.md)
195
+ - [Upstream alignment](docs/ALIGNMENT.md)
196
+ - [Responses compatibility server](docs/responses_server/README.md)
197
+
198
+ Release notes and implementation details live in `docs/`.
199
+
200
+ ## Markdown view modes
201
+
202
+ Markdown file views include a Show source / Show preview button. Switching
203
+ modes preserves each mode's reading position without replaying a previous line
204
+ target.
205
+
206
+ ## Responses reliability
207
+
208
+ Providers can opt into ordered failover with `fallback_models = ["backup-one",
209
+ "backup-two"]` in their `[model_providers.<name>]` table. Each target uses the
210
+ same endpoint, credentials, history and tools; request settings are rebuilt for
211
+ that model, while the session's selected model stays unchanged. Transient errors
212
+ exhaust `stream_max_retries` before advancing. Unavailable-model errors and
213
+ first-data timeouts advance immediately. Existing retry notices name both models
214
+ and include the underlying error.
215
+
216
+ Failed models cool down for 900 seconds within that client. Subsequent requests
217
+ skip them, retry them after expiry, and restart the full chain when every target
218
+ is cooling. `fallback_cooldown_seconds = 0` disables cooldown; explicit model
219
+ selection clears it. New sessions and subagents have independent cooldowns.
220
+ An absent or empty list disables failover. Invalid input, context-length and
221
+ terminal incomplete errors retain their existing handling. Backups must support
222
+ the active tools and context size; compaction keeps the selected model's policy.
223
+
224
+ Responses HTTP 408/429 and server errors use the provider retry budget.
225
+ Rate-limit messages containing `try again in` or `retry after` supply the retry
226
+ delay. CLI and workspace retry notices include the underlying error details;
227
+ workspace notices survive browser refresh and active-turn reattachment, and
228
+ remain separate from the assistant reply. They are not persisted in rollouts.
229
+
230
+ ## Workspace input history
231
+
232
+ The workspace message box supports Up/Down input history. Up recalls earlier
233
+ human inputs in the current conversation; Down returns to the unsent draft.
234
+ Automatic wake-up messages are excluded, and arrows retain normal cursor
235
+ movement inside multiline drafts.