python-codex 0.5.2__py3-none-any.whl → 0.6.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 (71) hide show
  1. pycodex/__init__.py +18 -8
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +27 -239
  4. pycodex/cli.py +19 -14
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +369 -51
  7. pycodex/events.py +13 -186
  8. pycodex/model.py +181 -88
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1069 -140
  18. pycodex/protocol.py +78 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +100 -7
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +2 -181
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +381 -0
  29. pycodex/tools/exec_tool.py +78 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/request_user_input_tool.py +3 -23
  38. pycodex/tools/runtime_services.py +122 -450
  39. pycodex/tools/send_message_tool.py +42 -0
  40. pycodex/tools/spawn_agent_tool.py +55 -94
  41. pycodex/tools/unified_exec_manager.py +26 -35
  42. pycodex/tools/wait_agent_tool.py +46 -66
  43. pycodex/tools/wait_tool.py +24 -13
  44. pycodex/tools/web_search_tool.py +1 -0
  45. pycodex/utils/codex_config.py +105 -0
  46. pycodex/utils/compactor.py +4 -0
  47. pycodex/utils/compat.py +2 -2
  48. pycodex/utils/doctor.py +5 -4
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +33 -0
  51. pycodex/utils/session_persist.py +78 -36
  52. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/METADATA +117 -27
  53. python_codex-0.6.0.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +7 -6
  56. responses_server/config.py +0 -11
  57. responses_server/payload_processors.py +4 -4
  58. responses_server/request_translation.py +480 -0
  59. responses_server/server.py +31 -24
  60. responses_server/stream_events.py +124 -0
  61. responses_server/stream_router.py +33 -830
  62. responses_server/tools/custom_adapter.py +29 -29
  63. responses_server/transport.py +332 -0
  64. pycodex/tools/close_agent_tool.py +0 -60
  65. pycodex/tools/exec_runtime.js +0 -161
  66. pycodex/tools/resume_agent_tool.py +0 -54
  67. pycodex/tools/send_input_tool.py +0 -110
  68. python_codex-0.5.2.dist-info/RECORD +0 -90
  69. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
  70. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
  71. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,205 @@
1
+ """Per-session goal state, usage accounting and continuation scheduling."""
2
+
3
+ import time
4
+
5
+ from ..context import build_goal_message
6
+ from ..events import (
7
+ CompactStartedEvent,
8
+ TerminalEvent,
9
+ TokenCountEvent,
10
+ TurnCompletedEvent,
11
+ TurnInterruptedEvent,
12
+ TurnStartedEvent,
13
+ )
14
+
15
+
16
+ class GoalManager:
17
+ def __init__(self):
18
+ self._goal = None
19
+ self._pending_tokens = 0
20
+ self._last_accounted_at = None
21
+ self._count_tokens = False
22
+ self._continuation_ready = False
23
+ self._budget_message = None
24
+
25
+ @staticmethod
26
+ def _validate_objective(objective):
27
+ if not isinstance(objective, str):
28
+ raise ValueError("goal objective must be a string")
29
+ if not objective:
30
+ raise ValueError("goal objective must not be empty")
31
+ if len(objective) > 4000:
32
+ raise ValueError("goal objective must be at most 4000 characters")
33
+
34
+ @staticmethod
35
+ def _validate_budget(token_budget):
36
+ if token_budget is None:
37
+ return
38
+ if type(token_budget) is not int or token_budget > 9223372036854775807:
39
+ raise ValueError("goal token_budget must be an integer in the i64 range")
40
+ if token_budget <= 0:
41
+ raise ValueError("goal budgets must be positive when provided")
42
+
43
+ def create(self, thread_id, objective, token_budget=None):
44
+ if isinstance(objective, str):
45
+ objective = objective.strip()
46
+ self._validate_objective(objective)
47
+ self._validate_budget(token_budget)
48
+ if not isinstance(thread_id, str) or not thread_id:
49
+ raise ValueError("goal requires a session ID")
50
+ if self._goal is not None and self._goal["status"] != "complete":
51
+ raise ValueError(
52
+ "cannot create a new goal because this thread has an unfinished "
53
+ "goal; complete the existing goal first"
54
+ )
55
+ now = int(time.time())
56
+ self._goal = {
57
+ "threadId": thread_id,
58
+ "objective": objective,
59
+ "status": "active",
60
+ "tokensUsed": 0,
61
+ "timeUsedSeconds": 0,
62
+ "createdAt": now,
63
+ "updatedAt": now,
64
+ }
65
+ if token_budget is not None:
66
+ self._goal["tokenBudget"] = token_budget
67
+ self._pending_tokens = 0
68
+ self._last_accounted_at = time.monotonic()
69
+ self._count_tokens = True
70
+ self._continuation_ready = False
71
+ self._budget_message = None
72
+ return self.response()
73
+
74
+ def update(self, status):
75
+ if status not in ("complete", "blocked", "paused"):
76
+ raise ValueError(
77
+ "update_goal can only mark the existing goal complete, blocked, "
78
+ "or paused at the user's explicit request; resume, budget-limited, "
79
+ "and usage-limited status changes are controlled by the user or system"
80
+ )
81
+ if self._goal is None:
82
+ raise ValueError("cannot update goal because this thread has no goal")
83
+ self.account(steer=status != "complete")
84
+ if status != "paused" or self._goal["status"] != "budgetLimited":
85
+ self._goal["status"] = status
86
+ self._last_accounted_at = None
87
+ self._count_tokens = False
88
+ self._budget_message = None
89
+ self._goal["updatedAt"] = int(time.time())
90
+ self._continuation_ready = False
91
+ return self.response(include_completion=status == "complete")
92
+
93
+ def response(self, include_completion=False):
94
+ goal = self.dump_state()
95
+ budget = None if goal is None else goal.get("tokenBudget")
96
+ report = None
97
+ if include_completion and (budget is not None or goal["timeUsedSeconds"] > 0):
98
+ report = (
99
+ "Goal achieved. Report final usage from this tool result's structured "
100
+ "goal fields. If `goal.tokenBudget` is present, include token usage "
101
+ "from `goal.tokensUsed` and `goal.tokenBudget`. If "
102
+ "`goal.timeUsedSeconds` is greater than 0, summarize elapsed time "
103
+ "in a concise, human-friendly form appropriate to the response language."
104
+ )
105
+ return {
106
+ "goal": goal,
107
+ "remainingTokens": None if budget is None else max(0, budget - goal["tokensUsed"]),
108
+ "completionBudgetReport": report,
109
+ }
110
+
111
+ def account(self, steer=True):
112
+ if self._last_accounted_at is None:
113
+ return
114
+ seconds = int(time.monotonic() - self._last_accounted_at)
115
+ if not seconds and not self._pending_tokens:
116
+ return
117
+ goal = self._goal
118
+ goal["tokensUsed"] += self._pending_tokens
119
+ goal["timeUsedSeconds"] += seconds
120
+ goal["updatedAt"] = int(time.time())
121
+ self._pending_tokens = 0
122
+ self._last_accounted_at += seconds
123
+ budget = goal.get("tokenBudget")
124
+ if goal["status"] == "active" and budget is not None and goal["tokensUsed"] >= budget:
125
+ goal["status"] = "budgetLimited"
126
+ if steer:
127
+ self._budget_message = build_goal_message(goal, budget_limited=True)
128
+
129
+ def handle_agent_event(self, event):
130
+ if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
131
+ self.start()
132
+ self._continuation_ready = False
133
+ self._count_tokens = self._goal is not None and self._goal["status"] == "active"
134
+ elif isinstance(event, TokenCountEvent):
135
+ if self._count_tokens and event.usage is not None:
136
+ usage = event.usage
137
+ cached = usage.get("input_tokens_details", {}).get("cached_tokens", 0)
138
+ self._pending_tokens += (
139
+ max(0, usage.get("input_tokens", 0) - cached)
140
+ + max(0, usage.get("output_tokens", 0))
141
+ )
142
+ elif isinstance(event, TerminalEvent):
143
+ self.account(steer=False)
144
+ self._count_tokens = False
145
+ if self._goal is not None:
146
+ if isinstance(event, TurnInterruptedEvent) and self._goal["status"] == "active":
147
+ self._goal["status"] = "paused"
148
+ self._goal["updatedAt"] = int(time.time())
149
+ active = self._goal["status"] == "active"
150
+ self._continuation_ready = active and isinstance(event, TurnCompletedEvent)
151
+ if not active:
152
+ self._last_accounted_at = None
153
+
154
+ def follow_up_messages(self):
155
+ message, self._budget_message = self._budget_message, None
156
+ return () if message is None else (message,)
157
+
158
+ def take_continuation(self):
159
+ if not self._continuation_ready:
160
+ return None
161
+ self._continuation_ready = False
162
+ return build_goal_message(self._goal)
163
+
164
+ def dump_state(self):
165
+ return None if self._goal is None else dict(self._goal)
166
+
167
+ def validate_state(self, state):
168
+ if state is None:
169
+ return
170
+ self._validate_objective(state["objective"])
171
+ self._validate_budget(state.get("tokenBudget"))
172
+ if not isinstance(state["threadId"], str) or not state["threadId"]:
173
+ raise ValueError("goal requires a session ID")
174
+ if state["status"] not in (
175
+ "active", "paused", "blocked", "usageLimited", "budgetLimited", "complete",
176
+ ):
177
+ raise ValueError("invalid goal status")
178
+ for name in ("tokensUsed", "timeUsedSeconds", "createdAt", "updatedAt"):
179
+ if type(state[name]) is not int or state[name] < 0:
180
+ raise ValueError("goal " + name + " must be a non-negative integer")
181
+
182
+ def restore_state(self, state):
183
+ self.validate_state(state)
184
+ self._goal = None if state is None else dict(state)
185
+ self._pending_tokens = 0
186
+ self._last_accounted_at = None
187
+ self._count_tokens = False
188
+ self._continuation_ready = state is not None and state["status"] == "active"
189
+ self._budget_message = None
190
+ self.start()
191
+
192
+ def start(self):
193
+ if (
194
+ self._goal is not None and self._goal["status"] == "active"
195
+ and self._last_accounted_at is None
196
+ ):
197
+ self._last_accounted_at = time.monotonic()
198
+ self._continuation_ready = True
199
+
200
+ def shutdown(self):
201
+ self.account(steer=False)
202
+ self._last_accounted_at = None
203
+ self._count_tokens = False
204
+ self._continuation_ready = False
205
+ self._budget_message = None
@@ -0,0 +1,126 @@
1
+ """Built-in tools for creating, inspecting and stopping a thread goal."""
2
+
3
+ from .base_tool import BaseTool, StructuredToolOutput
4
+
5
+
6
+ class CreateGoalTool(BaseTool):
7
+ name = "create_goal"
8
+ description = (
9
+ "Create a goal only when explicitly requested by the user or system/developer "
10
+ "instructions; do not infer goals from ordinary tasks.\n"
11
+ "Set token_budget only when an explicit token budget is requested. Fails if "
12
+ "an unfinished goal exists; use update_goal only for status."
13
+ )
14
+ input_schema = {
15
+ "type": "object",
16
+ "properties": {
17
+ "objective": {
18
+ "type": "string",
19
+ "description": (
20
+ "Required. The concrete objective to start pursuing. This starts "
21
+ "a new active goal when no goal exists or replaces the current "
22
+ "goal when it is complete."
23
+ ),
24
+ },
25
+ "token_budget": {
26
+ "type": "integer",
27
+ "description": (
28
+ "Positive token budget for the new goal. Omit unless explicitly requested."
29
+ ),
30
+ },
31
+ },
32
+ "required": ["objective"],
33
+ "additionalProperties": False,
34
+ }
35
+ supports_parallel = False
36
+
37
+ def __init__(self, manager):
38
+ self._manager = manager
39
+
40
+ async def run(self, context, args):
41
+ try:
42
+ return self._manager.create(
43
+ context.session_id, args["objective"], args.get("token_budget"),
44
+ )
45
+ except ValueError as exc:
46
+ return StructuredToolOutput(str(exc), success=False)
47
+
48
+
49
+ class GetGoalTool(BaseTool):
50
+ name = "get_goal"
51
+ description = (
52
+ "Get the current goal for this thread, including status, budgets, token and "
53
+ "elapsed-time usage, and remaining token budget."
54
+ )
55
+ input_schema = {
56
+ "type": "object",
57
+ "properties": {},
58
+ "required": [],
59
+ "additionalProperties": False,
60
+ }
61
+
62
+ def __init__(self, manager):
63
+ self._manager = manager
64
+
65
+ async def run(self, context, args):
66
+ return self._manager.response()
67
+
68
+
69
+ class UpdateGoalTool(BaseTool):
70
+ name = "update_goal"
71
+ description = (
72
+ "Update the existing goal.\n"
73
+ "Set status to `paused` only at the user's explicit request to pause this goal, "
74
+ "never on your own initiative. Ask if unclear; a later resume revokes that "
75
+ "request. Report the returned status and stop goal work. Budget limits take "
76
+ "precedence over pausing.\n"
77
+ "Set status to `complete` only when the objective has actually been achieved "
78
+ "and no required work remains.\n"
79
+ "Set status to `blocked` only when the same blocking condition has repeated "
80
+ "for at least three consecutive goal turns, counting the original/user-triggered "
81
+ "turn and any automatic continuations, and the agent cannot make meaningful "
82
+ "progress without user input or an external-state change.\n"
83
+ "If the user resumes a goal that was previously marked `blocked`, treat the "
84
+ "resumed run as a fresh blocked audit. If the same blocking condition then "
85
+ "repeats for at least three consecutive resumed goal turns, set status to "
86
+ "`blocked` again.\n"
87
+ "Once the blocked threshold is satisfied, do not keep reporting that you are "
88
+ "still blocked while leaving the goal active; set status to `blocked`.\n"
89
+ "Do not use `blocked` merely because the work is hard, slow, uncertain, "
90
+ "incomplete, or would benefit from clarification.\n"
91
+ "Do not mark a goal complete merely because its budget is nearly exhausted "
92
+ "or because you are stopping work.\n"
93
+ "You cannot use this tool to resume, budget-limit, or usage-limit a goal; "
94
+ "those status changes are controlled by the user or system.\n"
95
+ "When marking a budgeted goal achieved with status `complete`, report the "
96
+ "final token usage from the tool result to the user."
97
+ )
98
+ input_schema = {
99
+ "type": "object",
100
+ "properties": {
101
+ "status": {
102
+ "type": "string",
103
+ "enum": ["complete", "blocked", "paused"],
104
+ "description": (
105
+ "Required. `paused` requires an explicit user request. Set to "
106
+ "`complete` only when the objective is achieved and no required "
107
+ "work remains. Set to `blocked` only after the same blocking "
108
+ "condition has recurred for at least three consecutive goal turns "
109
+ "and the agent is at an impasse. After a previously blocked goal "
110
+ "is resumed, the resumed run starts a fresh blocked audit."
111
+ ),
112
+ },
113
+ },
114
+ "required": ["status"],
115
+ "additionalProperties": False,
116
+ }
117
+ supports_parallel = False
118
+
119
+ def __init__(self, manager):
120
+ self._manager = manager
121
+
122
+ async def run(self, context, args):
123
+ try:
124
+ return self._manager.update(args["status"])
125
+ except ValueError as exc:
126
+ return StructuredToolOutput(str(exc), success=False)
@@ -0,0 +1,48 @@
1
+ """Request a cooperative stop while retaining the recipient agent."""
2
+
3
+ from .agent_tool_schemas import AGENT_STATUS_SCHEMA
4
+ from .base_tool import BaseTool
5
+
6
+
7
+ class InterruptAgentTool(BaseTool):
8
+ name = "interrupt_agent"
9
+ namespace = "collaboration"
10
+ namespace_description = "Tools for spawning and managing sub-agents."
11
+ exec_only = False
12
+ description = (
13
+ "Interrupt an agent's current turn, if any, and return its previous "
14
+ "status. The agent remains available for messages and follow-up tasks."
15
+ )
16
+ input_schema = {
17
+ "type": "object",
18
+ "properties": {
19
+ "target": {
20
+ "type": "string",
21
+ "description": "Agent id or canonical task name to interrupt (from spawn_agent).",
22
+ },
23
+ },
24
+ "required": ["target"],
25
+ "additionalProperties": False,
26
+ }
27
+ output_schema = {
28
+ "type": "object",
29
+ "properties": {
30
+ "previous_status": {
31
+ "description": "The agent status observed before the interrupt request was handled.",
32
+ "allOf": [AGENT_STATUS_SCHEMA],
33
+ },
34
+ },
35
+ "required": ["previous_status"],
36
+ "additionalProperties": False,
37
+ }
38
+ supports_parallel = False
39
+
40
+ def __init__(self, agents_manager):
41
+ self._agents_manager = agents_manager
42
+
43
+ async def run(self, context, args):
44
+ if set(args) != {"target"}:
45
+ raise ValueError("expected target")
46
+ return await self._agents_manager.interrupt_agent(
47
+ context.agent_id, args["target"],
48
+ )
@@ -0,0 +1,66 @@
1
+ """Query live agents in the caller's MultiAgentV2 task tree."""
2
+
3
+ from .agent_tool_schemas import AGENT_STATUS_SCHEMA
4
+ from .base_tool import BaseTool
5
+
6
+
7
+ class ListAgentsTool(BaseTool):
8
+ name = "list_agents"
9
+ namespace = "collaboration"
10
+ namespace_description = "Tools for spawning and managing sub-agents."
11
+ exec_only = False
12
+ description = (
13
+ "List live agents in the current root thread tree. Optionally filter "
14
+ "by task-path prefix."
15
+ )
16
+ input_schema = {
17
+ "type": "object",
18
+ "properties": {
19
+ "path_prefix": {
20
+ "type": "string",
21
+ "description": "Task-path prefix filter without a trailing slash. Omit to list all live agents.",
22
+ },
23
+ },
24
+ "additionalProperties": False,
25
+ }
26
+ output_schema = {
27
+ "type": "object",
28
+ "properties": {
29
+ "agents": {
30
+ "type": "array",
31
+ "items": {
32
+ "type": "object",
33
+ "properties": {
34
+ "agent_name": {
35
+ "type": "string",
36
+ "description": "Canonical task name for the agent when available, otherwise the agent id.",
37
+ },
38
+ "agent_status": {
39
+ "description": "Last known status of the agent.",
40
+ "allOf": [AGENT_STATUS_SCHEMA],
41
+ },
42
+ },
43
+ "required": ["agent_name", "agent_status"],
44
+ "additionalProperties": False,
45
+ },
46
+ "description": "Live agents visible in the current root thread tree.",
47
+ },
48
+ },
49
+ "required": ["agents"],
50
+ "additionalProperties": False,
51
+ }
52
+ supports_parallel = True
53
+
54
+ def __init__(self, agents_manager):
55
+ self._agents_manager = agents_manager
56
+
57
+ async def run(self, context, args):
58
+ if set(args) - {"path_prefix"}:
59
+ raise ValueError("unexpected list_agents argument")
60
+ return {"agents": [
61
+ {"agent_name": agent["agent_path"], "agent_status": agent["status"]}
62
+ for agent in self._agents_manager.list_agents(
63
+ context.agent_id, args.get("path_prefix"),
64
+ )
65
+ if agent["status"] != "shutdown"
66
+ ]}
@@ -0,0 +1,141 @@
1
+ """Render tool schemas as Python function signatures for code mode."""
2
+
3
+ import inspect
4
+ import keyword
5
+
6
+ from ..utils.compat import is_ascii
7
+
8
+
9
+ def python_tool_identifier(name, namespace):
10
+ if namespace not in (None, "", "functions", "collaboration"):
11
+ separator = "" if namespace.endswith("_") or name.startswith("_") else "__"
12
+ name = namespace + separator + name
13
+ identifier = []
14
+ for index, char in enumerate(name):
15
+ valid = char == "_" or (
16
+ is_ascii(char) and char.isalnum() and (index != 0 or char.isalpha())
17
+ )
18
+ identifier.append(char if valid else "_")
19
+ name = "".join(identifier) or "_"
20
+ if keyword.iskeyword(name):
21
+ name += "_"
22
+ return "collaboration" if namespace == "collaboration" else "tools", name
23
+
24
+
25
+ def python_tool_signature(tool):
26
+ parameters = []
27
+ if tool["tool_type"] == "custom":
28
+ parameters.append(inspect.Parameter(
29
+ "input", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation="str",
30
+ ))
31
+ else:
32
+ schema = {} if tool["parameters"] is None else tool["parameters"]
33
+ properties = schema.get("properties", {})
34
+ required = set(schema.get("required", ()))
35
+ for name in sorted(properties, key=lambda key: (key not in required, key)):
36
+ if not name.isidentifier() or keyword.iskeyword(name):
37
+ raise ValueError("invalid Python tool parameter name: " + name)
38
+ parameter = properties[name]
39
+ default = inspect.Parameter.empty if name in required else (
40
+ parameter.get("default", ...) if isinstance(parameter, dict) else ...
41
+ )
42
+ parameters.append(inspect.Parameter(
43
+ name, inspect.Parameter.POSITIONAL_OR_KEYWORD,
44
+ default=default, annotation=_annotation(parameter),
45
+ ))
46
+ return inspect.Signature(parameters, return_annotation=_annotation(tool["output_schema"]))
47
+
48
+
49
+ def python_tool_declaration(tool):
50
+ signature = python_tool_signature(tool)
51
+ result = signature.return_annotation
52
+ if tool["tool_type"] == "custom":
53
+ lines = ["async def {0}(input: str) -> {1}:".format(tool["name"], result)]
54
+ else:
55
+ schema = {} if tool["parameters"] is None else tool["parameters"]
56
+ properties = schema.get("properties", {})
57
+ if not properties and not _comments(tool["output_schema"]):
58
+ return "async def {0}() -> {1}: ...".format(tool["name"], result)
59
+ lines = ["async def " + tool["name"] + "("]
60
+ for parameter in signature.parameters.values():
61
+ lines.extend(" # " + line for line in _comments(properties[parameter.name]))
62
+ default = ""
63
+ if parameter.default is not inspect.Parameter.empty:
64
+ default = " = " + (
65
+ "..." if parameter.default is ... else repr(parameter.default)
66
+ )
67
+ lines.append(" {0}: {1}{2},".format(
68
+ parameter.name, parameter.annotation, default,
69
+ ))
70
+ lines.append(") -> " + result + ":")
71
+ result_comments = _comments(tool["output_schema"])
72
+ if not result_comments:
73
+ lines[-1] += " ..."
74
+ return "\n".join(lines)
75
+ lines.append(" # Returns:")
76
+ lines.extend(" # " + line for line in result_comments)
77
+ lines.append(" ...")
78
+ return "\n".join(lines)
79
+
80
+
81
+ def _annotation(schema):
82
+ if schema is None or schema is True or schema == {}:
83
+ return "Any"
84
+ if schema is False:
85
+ return "NoReturn"
86
+ if "$ref" in schema:
87
+ raise ValueError("Python tool declarations require resolved schema references")
88
+ if "const" in schema:
89
+ return "Literal[{0!r}]".format(schema["const"])
90
+ if "enum" in schema:
91
+ return "Literal[" + ", ".join(repr(value) for value in schema["enum"]) + "]"
92
+ for union in ("anyOf", "oneOf"):
93
+ if union in schema:
94
+ return _union([_annotation(item) for item in schema[union]])
95
+ kind = schema.get("type")
96
+ if isinstance(kind, list):
97
+ return _union([_annotation(dict(schema, type=item)) for item in kind])
98
+ if kind == "object" or "properties" in schema:
99
+ additional = schema.get("additionalProperties")
100
+ if not schema.get("properties") and isinstance(additional, dict):
101
+ return "Dict[str, " + _annotation(additional) + "]"
102
+ return "dict"
103
+ if kind == "array":
104
+ return "List[" + _annotation(schema.get("items")) + "]"
105
+ types = {
106
+ None: "Any", "string": "str", "integer": "int",
107
+ "number": "Union[int, float]", "boolean": "bool", "null": "None",
108
+ }
109
+ return types[kind]
110
+
111
+
112
+ def _comments(schema):
113
+ if schema is None or isinstance(schema, bool):
114
+ return []
115
+ lines = schema.get("description", "").splitlines()
116
+ for key in (
117
+ "default", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum",
118
+ "minLength", "maxLength", "pattern", "format", "minItems", "maxItems",
119
+ "uniqueItems",
120
+ ):
121
+ if key in schema:
122
+ lines.append("{0} = {1!r}".format(key, schema[key]))
123
+ required = set(schema.get("required", ()))
124
+ for name, value in sorted(schema.get("properties", {}).items()):
125
+ lines.append("{0}: {1} ({2})".format(
126
+ name, _annotation(value), "required" if name in required else "optional",
127
+ ))
128
+ lines.extend(" " + line for line in _comments(value))
129
+ if schema.get("type") == "array":
130
+ items = _comments(schema.get("items"))
131
+ if items:
132
+ lines.append("Items:")
133
+ lines.extend(" " + line for line in items)
134
+ return lines
135
+
136
+
137
+ def _union(annotations):
138
+ annotations = list(dict.fromkeys(annotations))
139
+ if len(annotations) == 1:
140
+ return annotations[0]
141
+ return "Union[" + ", ".join(annotations) + "]"
@@ -52,6 +52,7 @@ REQUEST_PERMISSION_PROFILE_SCHEMA = {
52
52
 
53
53
 
54
54
  class RequestPermissionsTool(BaseTool):
55
+ exec_only = False
55
56
  name = "request_permissions"
56
57
  description = (
57
58
  "Request additional filesystem or network permissions from the user "
@@ -11,9 +11,6 @@ Expected behavior:
11
11
  from ..protocol import JSONDict, JSONValue
12
12
  from .base_tool import BaseTool, ToolContext
13
13
 
14
- MIN_AUTO_RESOLUTION_MS = 60_000
15
- MAX_AUTO_RESOLUTION_MS = 240_000
16
-
17
14
  REQUEST_USER_INPUT_QUESTION_SCHEMA = {
18
15
  "type": "object",
19
16
  "properties": {
@@ -35,7 +32,7 @@ REQUEST_USER_INPUT_QUESTION_SCHEMA = {
35
32
  "Provide 2-3 mutually exclusive choices. Put the recommended option "
36
33
  'first and suffix its label with "(Recommended)". Do not include '
37
34
  'an "Other" option in this list; the client will add a free-form '
38
- "Other option automatically."
35
+ '"Other" option automatically.'
39
36
  ),
40
37
  "items": {
41
38
  "type": "object",
@@ -60,14 +57,11 @@ REQUEST_USER_INPUT_QUESTION_SCHEMA = {
60
57
 
61
58
 
62
59
  class RequestUserInputTool(BaseTool):
60
+ exec_only = False
63
61
  name = "request_user_input"
64
62
  description = (
65
63
  "Request user input for one to three short questions and wait for the "
66
- f"response. Set autoResolutionMs, from {MIN_AUTO_RESOLUTION_MS} to "
67
- f"{MAX_AUTO_RESOLUTION_MS} milliseconds, only when the question is "
68
- "useful but non-blocking and continuing with best judgment is "
69
- "acceptable if the user does not answer; omit it when explicit user "
70
- "input is required. This tool is unavailable in Default mode."
64
+ "response. This tool is only available in Plan mode."
71
65
  )
72
66
  input_schema = {
73
67
  "type": "object",
@@ -77,20 +71,6 @@ class RequestUserInputTool(BaseTool):
77
71
  "description": "Questions to show the user. Prefer 1 and do not exceed 3",
78
72
  "items": REQUEST_USER_INPUT_QUESTION_SCHEMA,
79
73
  },
80
- "autoResolutionMs": {
81
- "type": "number",
82
- "description": (
83
- "Optional auto-resolution window in milliseconds, from "
84
- f"{MIN_AUTO_RESOLUTION_MS} to {MAX_AUTO_RESOLUTION_MS}. "
85
- "Include this only when the question is useful but "
86
- "non-blocking and continuing with best judgment is "
87
- "acceptable if the user does not answer; omit it when "
88
- "explicit user input is required before continuing. Use "
89
- f"{MIN_AUTO_RESOLUTION_MS} for lightly helpful context and "
90
- f"up to {MAX_AUTO_RESOLUTION_MS} when the answer would "
91
- "materially unblock better work."
92
- ),
93
- },
94
74
  },
95
75
  "required": ["questions"],
96
76
  "additionalProperties": False,