self-evolve-framework 1.4.0 → 1.6.0

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.
Files changed (171) hide show
  1. package/package.json +1 -1
  2. package/template/rules/ponytail.mdc +98 -23
  3. package/template/skills/skillopt-sleep/SKILL.md +42 -0
  4. package/template/skills/skillopt-sleep/configs/_base_/default.yaml +103 -0
  5. package/template/skills/skillopt-sleep/configs/alfworld/default.yaml +29 -0
  6. package/template/skills/skillopt-sleep/configs/docvqa/default.yaml +28 -0
  7. package/template/skills/skillopt-sleep/configs/features/soft_gate.yaml +47 -0
  8. package/template/skills/skillopt-sleep/configs/livemathematicianbench/default.yaml +22 -0
  9. package/template/skills/skillopt-sleep/configs/officeqa/default.yaml +34 -0
  10. package/template/skills/skillopt-sleep/configs/searchqa/default.yaml +32 -0
  11. package/template/skills/skillopt-sleep/configs/spreadsheetbench/default.yaml +34 -0
  12. package/template/skills/skillopt-sleep/scripts/framework/skillopt/__init__.py +28 -0
  13. package/template/skills/skillopt-sleep/scripts/framework/skillopt/config.py +282 -0
  14. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/__init__.py +7 -0
  15. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/base.py +512 -0
  16. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/__init__.py +9 -0
  17. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/trainer.py +2379 -0
  18. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/__init__.py +1 -0
  19. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/README.md +43 -0
  20. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/config_template.yaml +55 -0
  21. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/env_template.py +151 -0
  22. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/loader_template.py +87 -0
  23. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/__init__.py +5 -0
  24. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/adapter.py +428 -0
  25. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/dataloader.py +123 -0
  26. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_error.md +55 -0
  27. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_success.md +33 -0
  28. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_no_history.md +8 -0
  29. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_history.md +9 -0
  30. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_memory.md +16 -0
  31. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/reflect.py +4 -0
  32. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/rollout.py +366 -0
  33. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/skills/initial.md +45 -0
  34. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/__init__.py +9 -0
  35. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_envs.py +221 -0
  36. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_projection.py +60 -0
  37. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_prompts.py +8 -0
  38. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/config_tw.yaml +145 -0
  39. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_base.py +84 -0
  40. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_manager.py +139 -0
  41. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/memory.py +87 -0
  42. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/base.py +329 -0
  43. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/__init__.py +1 -0
  44. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/adapter.py +90 -0
  45. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/dataloader.py +61 -0
  46. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/evaluator.py +113 -0
  47. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_error.md +35 -0
  48. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_success.md +24 -0
  49. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/rollout_system.md +12 -0
  50. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/rollout.py +391 -0
  51. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/skills/initial.md +11 -0
  52. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/__init__.py +1 -0
  53. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/adapter.py +129 -0
  54. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/dataloader.py +308 -0
  55. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/evaluator.py +62 -0
  56. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_error.md +37 -0
  57. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_success.md +25 -0
  58. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/rollout_system.md +12 -0
  59. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/reflect.py +4 -0
  60. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/rollout.py +434 -0
  61. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/skills/initial.md +16 -0
  62. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/__init__.py +1 -0
  63. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/adapter.py +112 -0
  64. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/dataloader.py +71 -0
  65. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/evaluator.py +46 -0
  66. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_error.md +37 -0
  67. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_success.md +25 -0
  68. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/rollout_system.md +15 -0
  69. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/rollout.py +799 -0
  70. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/skills/initial.md +15 -0
  71. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/tool_runtime.py +552 -0
  72. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/__init__.py +1 -0
  73. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/adapter.py +96 -0
  74. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/dataloader.py +42 -0
  75. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/evaluator.py +100 -0
  76. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_error.md +46 -0
  77. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_success.md +32 -0
  78. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/rollout_system.md +13 -0
  79. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/reflect.py +4 -0
  80. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/rollout.py +494 -0
  81. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/skills/initial.md +3 -0
  82. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/__init__.py +5 -0
  83. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/adapter.py +159 -0
  84. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/codegen_agent.py +731 -0
  85. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/dataloader.py +37 -0
  86. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/evaluator.py +158 -0
  87. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/executor.py +67 -0
  88. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_error.md +46 -0
  89. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_success.md +32 -0
  90. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/codegen_system.md +1 -0
  91. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/critical_rules.md +9 -0
  92. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/react_system.md +21 -0
  93. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/react_agent.py +395 -0
  94. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/reflect.py +4 -0
  95. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/rollout.py +979 -0
  96. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/skills/initial.md +56 -0
  97. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/__init__.py +13 -0
  98. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/gate.py +148 -0
  99. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/__init__.py +15 -0
  100. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/aggregate.py +253 -0
  101. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/reflect.py +635 -0
  102. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/__init__.py +514 -0
  103. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/azure_openai.py +915 -0
  104. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/backend_config.py +185 -0
  105. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/claude_backend.py +371 -0
  106. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_backend.py +666 -0
  107. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_harness.py +1057 -0
  108. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/common.py +229 -0
  109. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/minimax_backend.py +277 -0
  110. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/qwen_backend.py +456 -0
  111. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/router.py +236 -0
  112. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/__init__.py +15 -0
  113. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/appendix.py +156 -0
  114. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/clip.py +109 -0
  115. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/lr_autonomous.py +108 -0
  116. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/meta_skill.py +79 -0
  117. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/rewrite.py +59 -0
  118. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/scheduler.py +127 -0
  119. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/select.py +4 -0
  120. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill.py +201 -0
  121. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill_aware.py +206 -0
  122. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/slow_update.py +396 -0
  123. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/update_modes.py +135 -0
  124. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/__init__.py +63 -0
  125. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error.md +41 -0
  126. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_full_rewrite.md +32 -0
  127. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_rewrite.md +44 -0
  128. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success.md +36 -0
  129. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_full_rewrite.md +30 -0
  130. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_rewrite.md +33 -0
  131. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/lr_autonomous.md +20 -0
  132. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure.md +30 -0
  133. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_full_rewrite.md +28 -0
  134. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_rewrite.md +26 -0
  135. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final.md +33 -0
  136. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_full_rewrite.md +28 -0
  137. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_rewrite.md +25 -0
  138. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success.md +28 -0
  139. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_full_rewrite.md +28 -0
  140. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_rewrite.md +25 -0
  141. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/meta_skill.md +40 -0
  142. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking.md +20 -0
  143. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking_rewrite.md +15 -0
  144. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/rewrite_skill.md +25 -0
  145. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/slow_update.md +60 -0
  146. package/template/skills/skillopt-sleep/scripts/framework/skillopt/scheduler/__init__.py +8 -0
  147. package/template/skills/skillopt-sleep/scripts/framework/skillopt/types.py +306 -0
  148. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/__init__.py +4 -0
  149. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/json_utils.py +172 -0
  150. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/scoring.py +28 -0
  151. package/template/skills/ponytail/SKILL.md +0 -133
  152. package/template/skills/ponytail/scripts/hooks/claude-codex-hooks.json +0 -44
  153. package/template/skills/ponytail/scripts/hooks/copilot-hooks.json +0 -21
  154. package/template/skills/ponytail/scripts/hooks/ponytail-activate.js +0 -91
  155. package/template/skills/ponytail/scripts/hooks/ponytail-config.js +0 -122
  156. package/template/skills/ponytail/scripts/hooks/ponytail-instructions.js +0 -94
  157. package/template/skills/ponytail/scripts/hooks/ponytail-mode-tracker.js +0 -55
  158. package/template/skills/ponytail/scripts/hooks/ponytail-runtime.js +0 -68
  159. package/template/skills/ponytail/scripts/hooks/ponytail-statusline.ps1 +0 -21
  160. package/template/skills/ponytail/scripts/hooks/ponytail-statusline.sh +0 -12
  161. package/template/skills/ponytail/scripts/hooks/ponytail-subagent.js +0 -22
  162. package/template/skills/ponytail/scripts/mcp/README.md +0 -46
  163. package/template/skills/ponytail/scripts/mcp/index.js +0 -48
  164. package/template/skills/ponytail/scripts/mcp/instructions.js +0 -26
  165. package/template/skills/ponytail/scripts/mcp/package.json +0 -13
  166. package/template/skills/ponytail/scripts/mcp/test/instructions.test.js +0 -22
  167. package/template/skills/ponytail-audit/SKILL.md +0 -41
  168. package/template/skills/ponytail-debt/SKILL.md +0 -44
  169. package/template/skills/ponytail-gain/SKILL.md +0 -50
  170. package/template/skills/ponytail-help/SKILL.md +0 -69
  171. package/template/skills/ponytail-review/SKILL.md +0 -57
@@ -0,0 +1,666 @@
1
+ """Codex CLI backend for ReflACT."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import json
6
+ import mimetypes
7
+ import os
8
+ import subprocess
9
+ import tempfile
10
+ import time
11
+ import uuid
12
+ from typing import Any
13
+ from urllib.parse import unquote, urlparse
14
+
15
+ from skillopt.model.common import (
16
+ CompatAssistantMessage,
17
+ CompatToolCall,
18
+ CompatToolFunction,
19
+ tracker,
20
+ )
21
+
22
+
23
+ CODEX_BIN = os.environ.get("CODEX_CLI_BIN", "codex")
24
+ CODEX_PROFILE = os.environ.get("CODEX_PROFILE", "review")
25
+ CODEX_SANDBOX_MODE = os.environ.get("CODEX_SANDBOX_MODE", "read-only")
26
+
27
+ OPTIMIZER_DEPLOYMENT = os.environ.get("OPTIMIZER_DEPLOYMENT", "gpt-4o")
28
+ TARGET_DEPLOYMENT = os.environ.get("TARGET_DEPLOYMENT", "gpt-4o")
29
+
30
+ REASONING_EFFORT: str | None = None
31
+
32
+
33
+ def _default_working_directory() -> str:
34
+ return os.environ.get("CODEX_WORKING_DIRECTORY", os.getcwd())
35
+
36
+
37
+ def _parse_data_uri(url: str) -> tuple[bytes, str]:
38
+ header, data = url.split(",", 1)
39
+ mime = header[5:].split(";", 1)[0] or "image/png"
40
+ return base64.b64decode(data), mime
41
+
42
+
43
+ def _content_to_text(
44
+ content: Any,
45
+ attachments: list[dict[str, Any]],
46
+ *,
47
+ image_counter: int,
48
+ ) -> tuple[str, int]:
49
+ if isinstance(content, str):
50
+ return content, image_counter
51
+
52
+ if not isinstance(content, list):
53
+ return str(content), image_counter
54
+
55
+ parts: list[str] = []
56
+ for item in content:
57
+ if not isinstance(item, dict):
58
+ continue
59
+ item_type = item.get("type")
60
+ if item_type == "text":
61
+ parts.append(str(item.get("text", "")))
62
+ continue
63
+ if item_type != "image_url":
64
+ continue
65
+
66
+ image_counter += 1
67
+ label = f"[Attached image {image_counter}]"
68
+ parts.append(label)
69
+
70
+ image_url = item.get("image_url", {}) or {}
71
+ url = str(image_url.get("url", "") or "")
72
+ if not url:
73
+ continue
74
+ if url.startswith("data:") and ";base64," in url:
75
+ data, mime = _parse_data_uri(url)
76
+ attachments.append({"bytes": data, "mime": mime})
77
+ continue
78
+ if url.startswith("file://"):
79
+ parsed = urlparse(url)
80
+ path = unquote(parsed.path)
81
+ if path:
82
+ attachments.append({"path": path})
83
+ continue
84
+ if os.path.exists(url):
85
+ attachments.append({"path": url})
86
+
87
+ return "".join(parts), image_counter
88
+
89
+
90
+ def _simplify_tool_schemas(tools: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
91
+ simplified: list[dict[str, Any]] = []
92
+ for tool in tools or []:
93
+ function = tool.get("function", tool)
94
+ simplified.append(
95
+ {
96
+ "name": function.get("name", ""),
97
+ "description": function.get("description", ""),
98
+ "parameters": function.get("parameters", {}),
99
+ }
100
+ )
101
+ return simplified
102
+
103
+
104
+ def _build_prompt_from_messages(
105
+ messages: list[dict[str, Any]],
106
+ *,
107
+ tools: list[dict[str, Any]] | None = None,
108
+ tool_choice: str | dict[str, Any] | None = None,
109
+ structured_output: bool = False,
110
+ ) -> tuple[str, list[dict[str, Any]]]:
111
+ system_parts: list[str] = []
112
+ history_parts: list[str] = []
113
+ attachments: list[dict[str, Any]] = []
114
+ image_counter = 0
115
+
116
+ def _history_line(label: str, body: str) -> str:
117
+ stripped = body.strip()
118
+ if not stripped:
119
+ return f"- {label}:"
120
+ indented = stripped.replace("\n", "\n ")
121
+ return f"- {label}: {indented}"
122
+
123
+ for message in messages:
124
+ role = str(message.get("role", "user"))
125
+ text, image_counter = _content_to_text(
126
+ message.get("content", ""),
127
+ attachments,
128
+ image_counter=image_counter,
129
+ )
130
+
131
+ if role == "system":
132
+ if text.strip():
133
+ system_parts.append(text.strip())
134
+ continue
135
+
136
+ if role == "assistant":
137
+ block = _history_line("Assistant", text)
138
+ tool_calls = message.get("tool_calls") or []
139
+ if tool_calls:
140
+ simplified_calls = []
141
+ for tool_call in tool_calls:
142
+ function = tool_call.get("function", {}) or {}
143
+ simplified_calls.append(
144
+ {
145
+ "name": function.get("name", ""),
146
+ "arguments": function.get("arguments", "{}"),
147
+ }
148
+ )
149
+ block += (
150
+ "\n Compatibility tool requests:\n"
151
+ + json.dumps(simplified_calls, ensure_ascii=False, indent=2)
152
+ )
153
+ history_parts.append(block)
154
+ continue
155
+
156
+ if role == "tool":
157
+ tool_call_id = str(message.get("tool_call_id", "") or "")
158
+ label = f"Tool result (tool_call_id={tool_call_id})"
159
+ history_parts.append(_history_line(label, text))
160
+ continue
161
+
162
+ history_parts.append(_history_line(role.capitalize(), text))
163
+
164
+ prompt_parts: list[str] = []
165
+
166
+ system_text = "\n\n".join(part for part in system_parts if part).strip()
167
+ if system_text:
168
+ prompt_parts.append(system_text)
169
+
170
+ if tools:
171
+ simplified_tools = _simplify_tool_schemas(tools)
172
+ prompt_parts.append(
173
+ "Available compatibility tools:\n"
174
+ + json.dumps(simplified_tools, ensure_ascii=False, indent=2)
175
+ )
176
+ prompt_parts.append(
177
+ "Do not execute these tools yourself. If you need one, request it in "
178
+ "`tool_calls`. Each `arguments` field must be a JSON string."
179
+ )
180
+
181
+ if tool_choice == "required":
182
+ prompt_parts.append(
183
+ "Tool choice policy: you must request at least one compatibility tool."
184
+ )
185
+ elif isinstance(tool_choice, dict) and tool_choice.get("type") == "function":
186
+ function = tool_choice.get("function", {}) or {}
187
+ prompt_parts.append(
188
+ "Tool choice policy: you must request the compatibility tool "
189
+ f"`{function.get('name', '')}`."
190
+ )
191
+
192
+ history_text = "\n".join(part for part in history_parts if part).strip()
193
+ if history_text:
194
+ prompt_parts.append("History:\n" + history_text)
195
+
196
+ if structured_output:
197
+ prompt_parts.append("Return only JSON matching the provided schema.")
198
+ if tools:
199
+ prompt_parts.append(
200
+ "Set `content` to the assistant-visible reply. Set `tool_calls` to "
201
+ "an empty array when no tool is needed."
202
+ )
203
+ else:
204
+ prompt_parts.append("Answer the latest user request.")
205
+
206
+ return "\n\n".join(prompt_parts), attachments
207
+
208
+
209
+ def _assistant_message_schema() -> dict[str, Any]:
210
+ return {
211
+ "type": "object",
212
+ "properties": {
213
+ "content": {"type": "string"},
214
+ "tool_calls": {
215
+ "type": "array",
216
+ "items": {
217
+ "type": "object",
218
+ "properties": {
219
+ "name": {"type": "string"},
220
+ "arguments": {"type": "string"},
221
+ },
222
+ "required": ["name", "arguments"],
223
+ "additionalProperties": False,
224
+ },
225
+ },
226
+ },
227
+ "required": ["content", "tool_calls"],
228
+ "additionalProperties": False,
229
+ }
230
+
231
+
232
+ def _materialize_attachments(
233
+ attachments: list[dict[str, Any]],
234
+ temp_dir: str,
235
+ ) -> list[str]:
236
+ image_paths: list[str] = []
237
+ for index, attachment in enumerate(attachments, 1):
238
+ path = attachment.get("path")
239
+ if path:
240
+ image_paths.append(str(path))
241
+ continue
242
+
243
+ mime = str(attachment.get("mime", "image/png"))
244
+ suffix = mimetypes.guess_extension(mime) or ".png"
245
+ image_path = os.path.join(temp_dir, f"image_{index}{suffix}")
246
+ with open(image_path, "wb") as f:
247
+ f.write(attachment.get("bytes", b""))
248
+ image_paths.append(image_path)
249
+ return image_paths
250
+
251
+
252
+ def _usage_from_event(usage: dict[str, Any] | None) -> dict[str, int]:
253
+ usage = usage or {}
254
+ prompt_tokens = int(usage.get("input_tokens", 0) or 0)
255
+ completion_tokens = int(usage.get("output_tokens", 0) or 0)
256
+ return {
257
+ "prompt_tokens": prompt_tokens,
258
+ "completion_tokens": completion_tokens,
259
+ "total_tokens": prompt_tokens + completion_tokens,
260
+ }
261
+
262
+
263
+ def _extract_error(stdout: str, stderr: str) -> str:
264
+ for raw_line in reversed(stdout.splitlines()):
265
+ line = raw_line.strip()
266
+ if not line:
267
+ continue
268
+ try:
269
+ payload = json.loads(line)
270
+ except json.JSONDecodeError:
271
+ continue
272
+ if payload.get("type") == "turn.failed":
273
+ error = payload.get("error", {}) or {}
274
+ return str(error.get("message", "") or "Codex turn failed")
275
+ if payload.get("type") == "error":
276
+ return str(payload.get("message", "") or "Codex execution failed")
277
+ return stderr.strip() or stdout.strip() or "Codex execution failed"
278
+
279
+
280
+ def _run_codex_exec(
281
+ *,
282
+ model: str,
283
+ prompt: str,
284
+ attachments: list[dict[str, Any]],
285
+ output_schema: dict[str, Any] | None,
286
+ timeout: int | None,
287
+ ) -> tuple[str, dict[str, int]]:
288
+ with tempfile.TemporaryDirectory(prefix="skillopt_codex_") as temp_dir:
289
+ output_path = os.path.join(temp_dir, "last_message.txt")
290
+ image_paths = _materialize_attachments(attachments, temp_dir)
291
+
292
+ command = [
293
+ CODEX_BIN,
294
+ "exec",
295
+ "--json",
296
+ "--ephemeral",
297
+ "--profile",
298
+ CODEX_PROFILE,
299
+ "-c",
300
+ "approval_policy=\"never\"",
301
+ "--sandbox",
302
+ CODEX_SANDBOX_MODE,
303
+ "--skip-git-repo-check",
304
+ "--cd",
305
+ _default_working_directory(),
306
+ "--model",
307
+ model,
308
+ "--output-last-message",
309
+ output_path,
310
+ ]
311
+
312
+ if REASONING_EFFORT:
313
+ command.extend(["-c", f"model_reasoning_effort={json.dumps(REASONING_EFFORT)}"])
314
+
315
+ schema_path = None
316
+ if output_schema is not None:
317
+ schema_path = os.path.join(temp_dir, "schema.json")
318
+ with open(schema_path, "w", encoding="utf-8") as f:
319
+ json.dump(output_schema, f, ensure_ascii=False)
320
+ command.extend(["--output-schema", schema_path])
321
+
322
+ for image_path in image_paths:
323
+ command.extend(["--image", image_path])
324
+
325
+ command.append("-")
326
+
327
+ proc = subprocess.run(
328
+ command,
329
+ input=prompt,
330
+ text=True,
331
+ encoding="utf-8",
332
+ errors="replace",
333
+ capture_output=True,
334
+ timeout=timeout,
335
+ check=False,
336
+ )
337
+
338
+ usage_info = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
339
+ fallback_text = ""
340
+ for raw_line in proc.stdout.splitlines():
341
+ line = raw_line.strip()
342
+ if not line:
343
+ continue
344
+ try:
345
+ payload = json.loads(line)
346
+ except json.JSONDecodeError:
347
+ continue
348
+ if payload.get("type") == "item.completed":
349
+ item = payload.get("item", {}) or {}
350
+ if item.get("type") == "agent_message":
351
+ fallback_text = str(item.get("text", "") or fallback_text)
352
+ if payload.get("type") == "turn.completed":
353
+ usage_info = _usage_from_event(payload.get("usage"))
354
+
355
+ last_message = ""
356
+ if os.path.exists(output_path):
357
+ with open(output_path, encoding="utf-8") as f:
358
+ last_message = f.read().strip()
359
+ if not last_message:
360
+ last_message = fallback_text.strip()
361
+
362
+ if proc.returncode != 0:
363
+ raise RuntimeError(_extract_error(proc.stdout, proc.stderr))
364
+ if not last_message:
365
+ raise RuntimeError("Codex returned an empty final message")
366
+ return last_message, usage_info
367
+
368
+
369
+ def _tool_name_from_choice(tool_choice: str | dict[str, Any] | None) -> str | None:
370
+ if not isinstance(tool_choice, dict):
371
+ return None
372
+ if tool_choice.get("type") != "function":
373
+ return None
374
+ function = tool_choice.get("function", {}) or {}
375
+ return str(function.get("name", "") or "") or None
376
+
377
+
378
+ def _compat_message_from_payload(
379
+ payload: dict[str, Any],
380
+ *,
381
+ tool_choice: str | dict[str, Any] | None = None,
382
+ ) -> CompatAssistantMessage:
383
+ content = str(payload.get("content", "") or "")
384
+ tool_calls: list[CompatToolCall] = []
385
+ for index, raw_tool_call in enumerate(payload.get("tool_calls", []) or [], 1):
386
+ if not isinstance(raw_tool_call, dict):
387
+ continue
388
+ name = str(raw_tool_call.get("name", "") or "")
389
+ arguments = raw_tool_call.get("arguments", "{}")
390
+ if not isinstance(arguments, str):
391
+ arguments = json.dumps(arguments, ensure_ascii=False)
392
+ tool_calls.append(
393
+ CompatToolCall(
394
+ id=f"tool_{index}_{uuid.uuid4().hex[:12]}",
395
+ function=CompatToolFunction(name=name, arguments=arguments),
396
+ )
397
+ )
398
+
399
+ if tool_choice == "required" and not tool_calls:
400
+ raise RuntimeError("Codex response did not request a tool under tool_choice='required'")
401
+
402
+ required_name = _tool_name_from_choice(tool_choice)
403
+ if required_name and all(
404
+ tool_call.function.name != required_name for tool_call in tool_calls
405
+ ):
406
+ raise RuntimeError(
407
+ f"Codex response did not request the required tool {required_name!r}"
408
+ )
409
+
410
+ return CompatAssistantMessage(content=content, tool_calls=tool_calls)
411
+
412
+
413
+ def _chat_messages_impl(
414
+ model: str,
415
+ messages: list[dict[str, Any]],
416
+ max_completion_tokens: int,
417
+ retries: int,
418
+ stage: str,
419
+ *,
420
+ tools: list[dict[str, Any]] | None = None,
421
+ tool_choice: str | dict[str, Any] | None = None,
422
+ return_message: bool = False,
423
+ timeout: int | None = None,
424
+ ) -> tuple[Any, dict[str, int]]:
425
+ del max_completion_tokens
426
+ last_err = None
427
+ structured_output = bool(tools) or return_message
428
+
429
+ for attempt in range(retries):
430
+ try:
431
+ prompt, attachments = _build_prompt_from_messages(
432
+ messages,
433
+ tools=tools,
434
+ tool_choice=tool_choice,
435
+ structured_output=structured_output,
436
+ )
437
+ raw_text, usage_info = _run_codex_exec(
438
+ model=model,
439
+ prompt=prompt,
440
+ attachments=attachments,
441
+ output_schema=_assistant_message_schema() if structured_output else None,
442
+ timeout=timeout,
443
+ )
444
+ tracker.record(
445
+ stage,
446
+ usage_info["prompt_tokens"],
447
+ usage_info["completion_tokens"],
448
+ )
449
+
450
+ if not structured_output:
451
+ return raw_text, usage_info
452
+
453
+ payload = json.loads(raw_text)
454
+ compat = _compat_message_from_payload(payload, tool_choice=tool_choice)
455
+ return (compat if return_message else compat.content), usage_info
456
+ except subprocess.TimeoutExpired as exc:
457
+ last_err = RuntimeError(f"Codex CLI timed out after {timeout}s") if timeout else exc
458
+ except Exception as exc: # noqa: BLE001
459
+ last_err = exc
460
+ time.sleep(min(2 ** attempt, 30))
461
+
462
+ raise RuntimeError(f"Codex call failed after {retries} retries: {last_err}")
463
+
464
+
465
+ def chat_with_model(
466
+ model: str,
467
+ system: str,
468
+ user: str,
469
+ max_completion_tokens: int = 16384,
470
+ retries: int = 5,
471
+ stage: str = "custom",
472
+ timeout: int | None = None,
473
+ ) -> tuple[str, dict[str, int]]:
474
+ messages = [
475
+ {"role": "system", "content": system},
476
+ {"role": "user", "content": user},
477
+ ]
478
+ return _chat_messages_impl(
479
+ model,
480
+ messages,
481
+ max_completion_tokens,
482
+ retries,
483
+ stage,
484
+ timeout=timeout,
485
+ )
486
+
487
+
488
+ def chat_messages_with_model(
489
+ model: str,
490
+ messages: list[dict[str, Any]],
491
+ max_completion_tokens: int = 16384,
492
+ retries: int = 5,
493
+ stage: str = "custom",
494
+ *,
495
+ tools: list[dict[str, Any]] | None = None,
496
+ tool_choice: str | dict[str, Any] | None = None,
497
+ return_message: bool = False,
498
+ timeout: int | None = None,
499
+ ) -> tuple[Any, dict[str, int]]:
500
+ return _chat_messages_impl(
501
+ model,
502
+ messages,
503
+ max_completion_tokens,
504
+ retries,
505
+ stage,
506
+ tools=tools,
507
+ tool_choice=tool_choice,
508
+ return_message=return_message,
509
+ timeout=timeout,
510
+ )
511
+
512
+
513
+ def chat_optimizer(
514
+ system: str,
515
+ user: str,
516
+ max_completion_tokens: int = 16384,
517
+ retries: int = 5,
518
+ stage: str = "optimizer",
519
+ timeout: int | None = None,
520
+ ) -> tuple[str, dict[str, int]]:
521
+ return chat_with_model(
522
+ model=OPTIMIZER_DEPLOYMENT,
523
+ system=system,
524
+ user=user,
525
+ max_completion_tokens=max_completion_tokens,
526
+ retries=retries,
527
+ stage=stage,
528
+ timeout=timeout,
529
+ )
530
+
531
+
532
+ def chat_with_deployment(
533
+ deployment: str,
534
+ system: str,
535
+ user: str,
536
+ max_completion_tokens: int = 16384,
537
+ retries: int = 5,
538
+ stage: str = "custom",
539
+ timeout: int | None = None,
540
+ ) -> tuple[str, dict[str, int]]:
541
+ return chat_with_model(
542
+ model=deployment,
543
+ system=system,
544
+ user=user,
545
+ max_completion_tokens=max_completion_tokens,
546
+ retries=retries,
547
+ stage=stage,
548
+ timeout=timeout,
549
+ )
550
+
551
+
552
+ def chat_target(
553
+ system: str,
554
+ user: str,
555
+ max_completion_tokens: int = 16384,
556
+ retries: int = 5,
557
+ stage: str = "target",
558
+ timeout: int | None = None,
559
+ ) -> tuple[str, dict[str, int]]:
560
+ return chat_with_model(
561
+ model=TARGET_DEPLOYMENT,
562
+ system=system,
563
+ user=user,
564
+ max_completion_tokens=max_completion_tokens,
565
+ retries=retries,
566
+ stage=stage,
567
+ timeout=timeout,
568
+ )
569
+
570
+
571
+ def chat_optimizer_messages(
572
+ messages: list[dict[str, Any]],
573
+ max_completion_tokens: int = 16384,
574
+ retries: int = 5,
575
+ stage: str = "optimizer",
576
+ *,
577
+ tools: list[dict[str, Any]] | None = None,
578
+ tool_choice: str | dict[str, Any] | None = None,
579
+ return_message: bool = False,
580
+ timeout: int | None = None,
581
+ ) -> tuple[Any, dict[str, int]]:
582
+ return _chat_messages_impl(
583
+ OPTIMIZER_DEPLOYMENT,
584
+ messages,
585
+ max_completion_tokens,
586
+ retries,
587
+ stage,
588
+ tools=tools,
589
+ tool_choice=tool_choice,
590
+ return_message=return_message,
591
+ timeout=timeout,
592
+ )
593
+
594
+
595
+ def chat_messages_with_deployment(
596
+ deployment: str,
597
+ messages: list[dict[str, Any]],
598
+ max_completion_tokens: int = 16384,
599
+ retries: int = 5,
600
+ stage: str = "custom",
601
+ *,
602
+ tools: list[dict[str, Any]] | None = None,
603
+ tool_choice: str | dict[str, Any] | None = None,
604
+ return_message: bool = False,
605
+ timeout: int | None = None,
606
+ ) -> tuple[Any, dict[str, int]]:
607
+ return _chat_messages_impl(
608
+ deployment,
609
+ messages,
610
+ max_completion_tokens,
611
+ retries,
612
+ stage,
613
+ tools=tools,
614
+ tool_choice=tool_choice,
615
+ return_message=return_message,
616
+ timeout=timeout,
617
+ )
618
+
619
+
620
+ def chat_target_messages(
621
+ messages: list[dict[str, Any]],
622
+ max_completion_tokens: int = 16384,
623
+ retries: int = 5,
624
+ stage: str = "target",
625
+ *,
626
+ tools: list[dict[str, Any]] | None = None,
627
+ tool_choice: str | dict[str, Any] | None = None,
628
+ return_message: bool = False,
629
+ timeout: int | None = None,
630
+ ) -> tuple[Any, dict[str, int]]:
631
+ return _chat_messages_impl(
632
+ TARGET_DEPLOYMENT,
633
+ messages,
634
+ max_completion_tokens,
635
+ retries,
636
+ stage,
637
+ tools=tools,
638
+ tool_choice=tool_choice,
639
+ return_message=return_message,
640
+ timeout=timeout,
641
+ )
642
+
643
+
644
+ def get_token_summary() -> dict[str, dict[str, int]]:
645
+ return tracker.summary()
646
+
647
+
648
+ def reset_token_tracker() -> None:
649
+ tracker.reset()
650
+
651
+
652
+ def set_target_deployment(deployment: str) -> None:
653
+ global TARGET_DEPLOYMENT
654
+ TARGET_DEPLOYMENT = deployment
655
+ os.environ["TARGET_DEPLOYMENT"] = deployment
656
+
657
+
658
+ def set_reasoning_effort(effort: str | None) -> None:
659
+ global REASONING_EFFORT
660
+ REASONING_EFFORT = effort if effort else None
661
+
662
+
663
+ def set_optimizer_deployment(deployment: str) -> None:
664
+ global OPTIMIZER_DEPLOYMENT
665
+ OPTIMIZER_DEPLOYMENT = deployment
666
+ os.environ["OPTIMIZER_DEPLOYMENT"] = deployment