python-codex 0.2.7__py3-none-any.whl → 0.3.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.
Files changed (84) hide show
  1. pycodex/__init__.py +14 -14
  2. pycodex/agent.py +465 -499
  3. pycodex/bootstrap.py +417 -0
  4. pycodex/cli.py +236 -510
  5. pycodex/compat.py +19 -5
  6. pycodex/context.py +222 -212
  7. pycodex/doctor.py +52 -48
  8. pycodex/events.py +857 -0
  9. pycodex/feishu_card.py +217 -163
  10. pycodex/feishu_link.py +43 -83
  11. pycodex/model.py +324 -253
  12. pycodex/model_metadata.py +19 -7
  13. pycodex/portable.py +76 -45
  14. pycodex/portable_server.py +32 -24
  15. pycodex/prompts/models.json +245 -983
  16. pycodex/protocol.py +177 -137
  17. pycodex/runtime.py +579 -176
  18. pycodex/runtime_services.py +204 -157
  19. pycodex/tools/__init__.py +1 -1
  20. pycodex/tools/apply_patch_tool.py +69 -48
  21. pycodex/tools/base_tool.py +89 -42
  22. pycodex/tools/clock_tool.py +58 -25
  23. pycodex/tools/close_agent_tool.py +2 -2
  24. pycodex/tools/code_mode_manager.py +77 -64
  25. pycodex/tools/exec_command_tool.py +26 -11
  26. pycodex/tools/exec_tool.py +4 -4
  27. pycodex/tools/grep_files_tool.py +12 -10
  28. pycodex/tools/ipython_tool.py +10 -13
  29. pycodex/tools/list_dir_tool.py +13 -9
  30. pycodex/tools/read_file_tool.py +29 -17
  31. pycodex/tools/request_permissions_tool.py +15 -5
  32. pycodex/tools/request_user_input_tool.py +13 -104
  33. pycodex/tools/resume_agent_tool.py +2 -2
  34. pycodex/tools/send_input_tool.py +11 -8
  35. pycodex/tools/shell_command_tool.py +7 -5
  36. pycodex/tools/shell_tool.py +7 -5
  37. pycodex/tools/spawn_agent_tool.py +7 -4
  38. pycodex/tools/unified_exec_manager.py +102 -69
  39. pycodex/tools/update_plan_tool.py +8 -5
  40. pycodex/tools/view_image_tool.py +7 -5
  41. pycodex/tools/wait_agent_tool.py +27 -4
  42. pycodex/tools/wait_tool.py +5 -4
  43. pycodex/tools/web_search_tool.py +4 -2
  44. pycodex/tools/write_stdin_tool.py +12 -11
  45. pycodex/utils/__init__.py +2 -17
  46. pycodex/utils/compactor.py +41 -72
  47. pycodex/utils/debug.py +2 -2
  48. pycodex/utils/dotenv.py +6 -7
  49. pycodex/utils/event_helpers.py +190 -0
  50. pycodex/utils/get_env.py +27 -70
  51. pycodex/{image_utils.py → utils/image_utils.py} +8 -11
  52. pycodex/utils/random_ids.py +1 -2
  53. pycodex/utils/session_persist.py +217 -163
  54. pycodex/utils/truncation.py +21 -45
  55. python_codex-0.3.0.dist-info/METADATA +704 -0
  56. python_codex-0.3.0.dist-info/RECORD +90 -0
  57. responses_server/__init__.py +1 -5
  58. responses_server/__main__.py +0 -1
  59. responses_server/app.py +36 -31
  60. responses_server/config.py +23 -23
  61. responses_server/messages_api.py +51 -53
  62. responses_server/payload_processors.py +25 -20
  63. responses_server/server.py +11 -11
  64. responses_server/session_store.py +14 -11
  65. responses_server/stream_router.py +101 -98
  66. responses_server/tools/custom_adapter.py +17 -16
  67. responses_server/tools/web_search.py +39 -36
  68. responses_server/trajectory_dump.py +36 -14
  69. workspace_server/__main__.py +0 -1
  70. workspace_server/app.py +461 -375
  71. workspace_server/workspace.html +852 -228
  72. workspace_server/workspaces.html +94 -95
  73. workspace_server/workspaces.py +137 -79
  74. pycodex/collaboration.py +0 -20
  75. pycodex/interactive_session.py +0 -415
  76. pycodex/prompts/collaboration_default.md +0 -11
  77. pycodex/prompts/collaboration_plan.md +0 -128
  78. pycodex/utils/toolcall_visualize.py +0 -713
  79. pycodex/utils/visualize.py +0 -560
  80. python_codex-0.2.7.dist-info/METADATA +0 -455
  81. python_codex-0.2.7.dist-info/RECORD +0 -93
  82. {python_codex-0.2.7.dist-info → python_codex-0.3.0.dist-info}/WHEEL +0 -0
  83. {python_codex-0.2.7.dist-info → python_codex-0.3.0.dist-info}/entry_points.txt +0 -0
  84. {python_codex-0.2.7.dist-info → python_codex-0.3.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,415 +0,0 @@
1
- import asyncio
2
- import json
3
- from dataclasses import asdict
4
-
5
- from .protocol import AgentEvent
6
- from .runtime import CliSubmissionQueue
7
- from .runtime_services import create_agent_runtime_environment
8
- from .utils import CliSessionView, uuid7_string
9
- from .utils.compactor import compact_agent
10
- from .utils.session_persist import (
11
- SessionRolloutRecorder,
12
- conversation_history_to_turns,
13
- list_resumable_sessions,
14
- load_resumed_session,
15
- resolve_codex_home,
16
- )
17
- import typing
18
-
19
-
20
- EXIT_COMMANDS = {"/exit", "/quit"}
21
- HELP_COMMAND = "/help"
22
- HISTORY_COMMAND = "/history"
23
- TITLE_COMMAND = "/title"
24
- MODEL_COMMAND = "/model"
25
- QUEUE_COMMAND = "/queue"
26
- RESUME_COMMAND = "/resume"
27
- COMPACT_COMMAND = "/compact"
28
- FORK_COMMAND = "/fork"
29
- LINK_COMMAND = "/link"
30
- UNLINK_COMMAND = "/unlink"
31
- EXTRA_COMMANDS_LINE = (
32
- "Extra commands: /help, /history, /title, /model, /resume, /compact, /fork, /link, /unlink"
33
- )
34
-
35
-
36
- def format_turn_output(result, json_mode: "bool") -> "str":
37
- if json_mode:
38
- return json.dumps(asdict(result), ensure_ascii=False, indent=2)
39
- return result.output_text or ""
40
-
41
-
42
- async def prompt_request_user_input(
43
- view,
44
- payload: "typing.Dict[str, object]",
45
- ) -> "typing.Union[typing.Dict[str, object], None]":
46
- view.finish_stream()
47
- view.write_line("[request_user_input] waiting for user response")
48
- answers: "typing.Dict[str, typing.Dict[str, typing.List[str]]]" = {}
49
- for question in payload.get("questions", []):
50
- if not isinstance(question, dict):
51
- continue
52
- header = str(question.get("header", "")).strip()
53
- question_text = str(question.get("question", "")).strip()
54
- question_id = str(question.get("id", "")).strip()
55
- if header:
56
- view.write_line(f"[{header}] {question_text}")
57
- else:
58
- view.write_line(question_text)
59
-
60
- options = question.get("options") or []
61
- if isinstance(options, list):
62
- for index, option in enumerate(options, start=1):
63
- if not isinstance(option, dict):
64
- continue
65
- label = str(option.get("label", "")).strip()
66
- description = str(option.get("description", "")).strip()
67
- view.write_line(f" {index}. {label} - {description}")
68
- view.write_line(" 0. Other")
69
-
70
- try:
71
- raw_answer = await view.get_prompt("answer> ")
72
- except EOFError:
73
- return None
74
- answer_text = raw_answer.strip()
75
- if not answer_text:
76
- return None
77
-
78
- selected_answer = answer_text
79
- if answer_text.isdigit() and isinstance(options, list):
80
- choice = int(answer_text)
81
- if 1 <= choice <= len(options):
82
- option = options[choice - 1]
83
- if isinstance(option, dict):
84
- selected_answer = (
85
- str(option.get("label", "")).strip() or answer_text
86
- )
87
- elif choice == 0:
88
- try:
89
- raw_answer = await view.get_prompt("other> ")
90
- except EOFError:
91
- return None
92
- selected_answer = raw_answer.strip()
93
- if not selected_answer:
94
- return None
95
-
96
- answers[question_id] = {"answers": [selected_answer]}
97
-
98
- return {"answers": answers}
99
-
100
-
101
- async def prompt_request_permissions(
102
- view,
103
- payload: "typing.Dict[str, object]",
104
- ) -> "typing.Union[typing.Dict[str, object], None]":
105
- view.finish_stream()
106
- view.write_line("[request_permissions] user approval required")
107
- reason = payload.get("reason")
108
- if reason:
109
- view.write_line(f"Reason: {reason}")
110
- view.write_line("Requested permissions:")
111
- view.write_line(
112
- json.dumps(payload.get("permissions", {}), ensure_ascii=False, indent=2)
113
- )
114
- view.write_line("Choose: [n] deny / [t] grant for turn / [s] grant for session")
115
- try:
116
- raw_answer = await view.get_prompt("permissions> ")
117
- except EOFError:
118
- return None
119
-
120
- answer = raw_answer.strip().lower()
121
- if answer in {"t", "turn", "y", "yes"}:
122
- return {
123
- "permissions": payload.get("permissions", {}),
124
- "scope": "turn",
125
- }
126
- if answer in {"s", "session"}:
127
- return {
128
- "permissions": payload.get("permissions", {}),
129
- "scope": "session",
130
- }
131
- return {
132
- "permissions": {},
133
- "scope": "turn",
134
- }
135
-
136
-
137
- async def run_interactive_session(
138
- queue: "CliSubmissionQueue",
139
- json_mode: "bool",
140
- config_path: "typing.Union[str, None]" = None,
141
- view=None,
142
- view_factory=None,
143
- show_banner: "bool" = True,
144
- ) -> "int":
145
- worker = asyncio.create_task(queue.run_forever())
146
- context_window_tokens = queue._agent._context_manager.resolve_model_context_window()
147
- if view is None:
148
- factory = view_factory or CliSessionView
149
- view = factory()
150
- view.set_context_window_tokens(context_window_tokens)
151
- model_client = queue._agent._model_client
152
- codex_home = resolve_codex_home(config_path)
153
- queue.set_event_handler(view.handle_event)
154
- pending_turn_tasks: "typing.Set[asyncio.Task[None]]" = set()
155
- runtime_environment = queue._agent.runtime_environment
156
- if runtime_environment is None:
157
- runtime_environment = create_agent_runtime_environment()
158
- queue._agent.runtime_environment = runtime_environment
159
- runtime_environment.request_user_input_manager.set_handler(
160
- lambda payload: prompt_request_user_input(view, payload)
161
- )
162
- runtime_environment.request_permissions_manager.set_handler(
163
- lambda payload: prompt_request_permissions(view, payload)
164
- )
165
- if show_banner:
166
- view.write_line("pycodex interactive mode. Type /exit to quit.")
167
- view.write_line(EXTRA_COMMANDS_LINE)
168
- feishu_link = None
169
- try:
170
-
171
- def has_pending_turn_tasks() -> "bool":
172
- pending_turn_tasks.difference_update(
173
- task for task in tuple(pending_turn_tasks) if task.done()
174
- )
175
- return bool(pending_turn_tasks)
176
-
177
- async def run_manual_compact() -> "None":
178
- current_agent = queue._agent
179
- if not current_agent.history:
180
- view.write_line("Nothing to compact.")
181
- return
182
-
183
- compact_turn_id = uuid7_string()
184
-
185
- def handle_compact_stream_event(event) -> "None":
186
- if event.kind not in {"token_count", "stream_error"}:
187
- return
188
- view.handle_event(
189
- AgentEvent(
190
- kind=event.kind,
191
- turn_id=compact_turn_id,
192
- payload=dict(event.payload),
193
- )
194
- )
195
-
196
- view.write_line("Compacting conversation history...")
197
- compact_result = await compact_agent(
198
- current_agent,
199
- handle_compact_stream_event,
200
- True,
201
- )
202
- if compact_result is None:
203
- view.write_line("Nothing to compact.")
204
- return
205
- view.load_session_history(
206
- getattr(view, "_title", None),
207
- conversation_history_to_turns(compact_result.history),
208
- )
209
- view.write_line(compact_result.display_text())
210
-
211
- async def wait_for_turn_result(future) -> "None":
212
- try:
213
- result = await future
214
- except Exception as exc: # pragma: no cover - defensive surface
215
- if str(exc) == "submission interrupted":
216
- return
217
- view.show_error(str(exc))
218
- return
219
-
220
- if json_mode:
221
- view.write_line(format_turn_output(result, True))
222
-
223
- while True:
224
- try:
225
- raw_line = await view.poll_prompt()
226
- except EOFError:
227
- break
228
- if raw_line is None:
229
- await asyncio.sleep(0.05)
230
- continue
231
-
232
- prompt_text = raw_line.strip()
233
- if not prompt_text:
234
- continue
235
- if prompt_text in EXIT_COMMANDS:
236
- break
237
- if prompt_text == HELP_COMMAND:
238
- view.write_line(EXTRA_COMMANDS_LINE)
239
- continue
240
- if prompt_text == HISTORY_COMMAND:
241
- view.show_history()
242
- continue
243
- if prompt_text == TITLE_COMMAND:
244
- view.show_title()
245
- continue
246
- if prompt_text.startswith(f"{TITLE_COMMAND} "):
247
- title = prompt_text[len(TITLE_COMMAND) :].strip()
248
- if not title:
249
- view.write_line("Usage: /title <title>")
250
- continue
251
- set_session_title = getattr(view, "set_session_title", None)
252
- if callable(set_session_title):
253
- set_session_title(title)
254
- else:
255
- view.write_line(f"Session: {title}")
256
- continue
257
- if prompt_text == RESUME_COMMAND:
258
- sessions = list_resumable_sessions(codex_home)
259
- if not sessions:
260
- view.write_line("No resumable sessions found.")
261
- continue
262
- view.write_line("Available sessions:")
263
- for index, session in enumerate(sessions, start=1):
264
- view.write_line(f"[{index}] {session['preview']}")
265
- continue
266
- if prompt_text.startswith(f"{RESUME_COMMAND} "):
267
- if has_pending_turn_tasks():
268
- view.write_line(
269
- "Cannot resume while work is running or queued."
270
- )
271
- continue
272
- resume_target = prompt_text[len(RESUME_COMMAND) :].strip()
273
- try:
274
- resumed = load_resumed_session(codex_home, resume_target)
275
- queue._agent.replace_history(resumed["history"])
276
- if hasattr(model_client, "_session_id"):
277
- model_client._session_id = str(resumed["session_id"])
278
- queue._agent.set_rollout_recorder(
279
- SessionRolloutRecorder.resume(resumed["rollout_path"])
280
- )
281
- view.load_session_history(
282
- str(resumed["title"]),
283
- tuple(resumed["turns"]),
284
- )
285
- show_resumed_session = getattr(view, "show_resumed_session", None)
286
- if callable(show_resumed_session):
287
- show_resumed_session(str(resumed["title"]))
288
- else:
289
- view.write_line(f"Resumed session: {resumed['title']}")
290
- view.show_history()
291
- except Exception as exc: # pragma: no cover - defensive surface
292
- view.show_error(str(exc))
293
- continue
294
- if prompt_text == COMPACT_COMMAND:
295
- if has_pending_turn_tasks():
296
- view.write_line(
297
- "Cannot compact while work is running or queued."
298
- )
299
- continue
300
- try:
301
- await run_manual_compact()
302
- except Exception as exc: # pragma: no cover - defensive surface
303
- view.show_error(str(exc))
304
- continue
305
- if prompt_text == FORK_COMMAND:
306
- if has_pending_turn_tasks():
307
- view.write_line(
308
- "Cannot fork while work is running or queued."
309
- )
310
- continue
311
- if not hasattr(model_client, "_session_id"):
312
- view.write_line("Current model does not support session IDs.")
313
- continue
314
- new_session_id = uuid7_string()
315
- model_client._session_id = new_session_id
316
- view.write_line(f"Forked session: {new_session_id}")
317
- continue
318
- if prompt_text.startswith(f"{LINK_COMMAND} "):
319
- link_target = prompt_text[len(LINK_COMMAND) :].strip()
320
- if not link_target:
321
- view.write_line("Usage: /link <feishu-email|open_id|chat_id>")
322
- continue
323
- if feishu_link:
324
- view.write_line("A Feishu card is already linked. Use /unlink first.")
325
- continue
326
- try:
327
- from .feishu_link import PycodexRuntimeLink
328
-
329
- view.write_line(f"Linking Feishu card to current session: {link_target}")
330
- link = await PycodexRuntimeLink(
331
- queue,
332
- link_target,
333
- ).start_async()
334
- feishu_link = link
335
- view.write_line(
336
- "Linked Feishu card: session_key={0} message_id={1}".format(
337
- link.session_key,
338
- link.message_id or "-",
339
- )
340
- )
341
- except Exception as exc: # pragma: no cover - defensive surface
342
- view.show_error(str(exc))
343
- continue
344
- if prompt_text == UNLINK_COMMAND:
345
- if not feishu_link:
346
- view.write_line("No Feishu card is linked.")
347
- continue
348
- feishu_link.detach()
349
- feishu_link = None
350
- view.write_line("Unlinked Feishu card.")
351
- continue
352
- if prompt_text.startswith(f"{QUEUE_COMMAND} "):
353
- queued_text = prompt_text[len(QUEUE_COMMAND) :].strip()
354
- if not queued_text:
355
- view.write_line("Usage: /queue <message>")
356
- continue
357
- try:
358
- submission_id, future = await queue.enqueue_user_turn(
359
- queued_text, queue="enqueue"
360
- )
361
- view.show_steer_queued(submission_id, queued_text)
362
- turn_task = asyncio.create_task(wait_for_turn_result(future))
363
- pending_turn_tasks.add(turn_task)
364
- except Exception as exc: # pragma: no cover - defensive surface
365
- view.show_error(str(exc))
366
- continue
367
- if prompt_text == MODEL_COMMAND:
368
- view.write_line(
369
- f"Current model: {getattr(model_client, 'model', None) or 'unavailable'}"
370
- )
371
- models = await model_client.list_models()
372
- view.write_line(f"Available models: {', '.join(models)}")
373
- continue
374
- if prompt_text.startswith(f"{MODEL_COMMAND} "):
375
- if has_pending_turn_tasks():
376
- view.write_line(
377
- "Cannot change model while work is running or queued in steer mode."
378
- )
379
- continue
380
- model_name = prompt_text[len(MODEL_COMMAND) :].strip()
381
- if not model_name:
382
- view.write_line("Usage: /model <model>")
383
- continue
384
-
385
- model_client.model = model_name
386
- view.write_line(f"Switched model to {model_name}.")
387
- continue
388
-
389
- try:
390
- steered = has_pending_turn_tasks()
391
- submission_id, future = await queue.enqueue_user_turn(
392
- prompt_text,
393
- queue="steer",
394
- )
395
- if steered:
396
- view.schedule_steer_inserted(submission_id, prompt_text)
397
- turn_task = asyncio.create_task(wait_for_turn_result(future))
398
- pending_turn_tasks.add(turn_task)
399
- continue
400
- except Exception as exc: # pragma: no cover - defensive surface
401
- view.show_error(str(exc))
402
- continue
403
- finally:
404
- if feishu_link:
405
- feishu_link.detach()
406
- feishu_link.stop()
407
- runtime_environment.request_user_input_manager.set_handler(None)
408
- runtime_environment.request_permissions_manager.set_handler(None)
409
- await queue.shutdown()
410
- await worker
411
- if pending_turn_tasks:
412
- await asyncio.gather(*pending_turn_tasks, return_exceptions=True)
413
- view.close()
414
-
415
- return 0
@@ -1,11 +0,0 @@
1
- # Collaboration Mode: Default
2
-
3
- You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
4
-
5
- Your active mode changes only when new developer instructions with a different `<collaboration_mode>...</collaboration_mode>` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
6
-
7
- ## request_user_input availability
8
-
9
- The `request_user_input` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
10
-
11
- In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
@@ -1,128 +0,0 @@
1
- # Plan Mode (Conversational)
2
-
3
- You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed—intent- and implementation-wise—so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
4
-
5
- ## Mode rules (strict)
6
-
7
- You are in **Plan Mode** until a developer message explicitly ends it.
8
-
9
- Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
10
-
11
- ## Plan Mode vs update_plan tool
12
-
13
- Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `<proposed_plan>` block.
14
-
15
- Separately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error.
16
-
17
- ## Execution vs. mutation in Plan Mode
18
-
19
- You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
20
-
21
- ### Allowed (non-mutating, plan-improving)
22
-
23
- Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
24
-
25
- * Reading or searching files, configs, schemas, types, manifests, and docs
26
- * Static analysis, inspection, and repo exploration
27
- * Dry-run style commands when they do not edit repo-tracked files
28
- * Tests, builds, or checks that may write to caches or build artifacts (for example, `target/`, `.cache/`, or snapshots) so long as they do not edit repo-tracked files
29
-
30
- ### Not allowed (mutating, plan-executing)
31
-
32
- Actions that implement the plan or change repo-tracked state. Examples:
33
-
34
- * Editing or writing files
35
- * Running formatters or linters that rewrite files
36
- * Applying patches, migrations, or codegen that updates repo-tracked files
37
- * Side-effectful commands whose purpose is to carry out the plan rather than refine it
38
-
39
- When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
40
-
41
- ## PHASE 1 — Ground in the environment (explore first, ask second)
42
-
43
- Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
44
-
45
- Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
46
-
47
- Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
48
-
49
- Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
50
-
51
- ## PHASE 2 — Intent chat (what they actually want)
52
-
53
- * Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
54
- * Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet—ask.
55
-
56
- ## PHASE 3 — Implementation chat (what/how we’ll build)
57
-
58
- * Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
59
-
60
- ## Asking questions
61
-
62
- Critical rules:
63
-
64
- * Strongly prefer using the `request_user_input` tool to ask any questions.
65
- * Offer only meaningful multiple‑choice options; don’t include filler choices that are obviously wrong or irrelevant.
66
- * In rare cases where an unavoidable, important question can’t be expressed with reasonable multiple‑choice options (due to extreme ambiguity), you may ask it directly without the tool.
67
-
68
- You SHOULD ask many questions, but each question must:
69
-
70
- * materially change the spec/plan, OR
71
- * confirm/lock an assumption, OR
72
- * choose between meaningful tradeoffs.
73
- * not be answerable by non-mutating commands.
74
-
75
- Use the `request_user_input` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
76
-
77
- ## Two kinds of unknowns (treat differently)
78
-
79
- 1. **Discoverable facts** (repo/system truth): explore first.
80
-
81
- * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
82
- * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
83
- * If asking, present concrete candidates (paths/service names) + recommend one.
84
- * Never ask questions you can answer from your environment (e.g., “where is this struct”).
85
-
86
- 2. **Preferences/tradeoffs** (not discoverable): ask early.
87
-
88
- * These are intent or implementation preferences that cannot be derived from exploration.
89
- * Provide 2–4 mutually exclusive options + a recommended default.
90
- * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
91
-
92
- ## Finalization rule
93
-
94
- Only output the final plan when it is decision complete and leaves no decisions to the implementer.
95
-
96
- When you present the official plan, wrap it in a `<proposed_plan>` block so the client can render it specially:
97
-
98
- 1) The opening tag must be on its own line.
99
- 2) Start the plan content on the next line (no text on the same line as the tag).
100
- 3) The closing tag must be on its own line.
101
- 4) Use Markdown inside the block.
102
- 5) Keep the tags exactly as `<proposed_plan>` and `</proposed_plan>` (do not translate or rename them), even if the plan content is in another language.
103
-
104
- Example:
105
-
106
- <proposed_plan>
107
- plan content
108
- </proposed_plan>
109
-
110
- plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include:
111
-
112
- * A clear title
113
- * A brief summary section
114
- * Important changes or additions to public APIs/interfaces/types
115
- * Test cases and scenarios
116
- * Explicit assumptions and defaults chosen where needed
117
-
118
- When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes.
119
-
120
- Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes.
121
-
122
- Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand.
123
-
124
- Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `<proposed_plan>` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
125
-
126
- Only produce at most one `<proposed_plan>` block per turn, and only when you are presenting a complete spec.
127
-
128
- If the user stays in Plan mode and asks for revisions after a prior `<proposed_plan>`, any new `<proposed_plan>` must be a complete replacement.