dex-agents-claude-sdk-cli 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.
- dex_agents_claude_sdk_cli/__init__.py +65 -0
- dex_agents_claude_sdk_cli/__main__.py +14 -0
- dex_agents_claude_sdk_cli/harness.py +410 -0
- dex_agents_claude_sdk_cli/py.typed +0 -0
- dex_agents_claude_sdk_cli-0.6.0.dist-info/METADATA +138 -0
- dex_agents_claude_sdk_cli-0.6.0.dist-info/RECORD +9 -0
- dex_agents_claude_sdk_cli-0.6.0.dist-info/WHEEL +4 -0
- dex_agents_claude_sdk_cli-0.6.0.dist-info/entry_points.txt +3 -0
- dex_agents_claude_sdk_cli-0.6.0.dist-info/licenses/LICENSE +105 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable, Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Sustainable Use License 1.0.
|
|
4
|
+
# You may not use this file except in compliance with the License.
|
|
5
|
+
# See the LICENSE file in the repository root.
|
|
6
|
+
#
|
|
7
|
+
# SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
|
|
8
|
+
|
|
9
|
+
"""The ``dex-agents-claude-sdk`` command: a Claude Agent SDK agent in the terminal.
|
|
10
|
+
|
|
11
|
+
It builds the agent session Flow with the Claude Agent SDK adapter and runs
|
|
12
|
+
it with the shared Dex Agents CLI core. See the package README.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import dex_agents_cli_core # noqa: F401 # first: it configures gRPC before anything imports it
|
|
16
|
+
|
|
17
|
+
# isort: split
|
|
18
|
+
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from dex_agents_claude_sdk_cli.harness import (
|
|
22
|
+
CLAUDE_CODE_LOCAL_TOOLS,
|
|
23
|
+
CLAUDE_SDK_CLI_FLOW_TYPE,
|
|
24
|
+
DEFAULT_CLAUDE_MODEL,
|
|
25
|
+
DEFAULT_INSTRUCTIONS,
|
|
26
|
+
ClaudeCodeLocalTools,
|
|
27
|
+
ClaudeSdkHarness,
|
|
28
|
+
validate_claude_section,
|
|
29
|
+
)
|
|
30
|
+
from dex_agents_cli_core import ConfigError, command_name, run_agent_cli
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"CLAUDE_CODE_LOCAL_TOOLS",
|
|
34
|
+
"CLAUDE_SDK_CLI_FLOW_TYPE",
|
|
35
|
+
"DEFAULT_CLAUDE_MODEL",
|
|
36
|
+
"DEFAULT_INSTRUCTIONS",
|
|
37
|
+
"ClaudeCodeLocalTools",
|
|
38
|
+
"ClaudeSdkHarness",
|
|
39
|
+
"main",
|
|
40
|
+
"run",
|
|
41
|
+
"validate_claude_section",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv: list[str] | None = None) -> int:
|
|
46
|
+
"""Run the command and return its exit code.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
argv: The arguments without the program name; ``None`` reads ``sys.argv``.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
0 on success, 1 for a failure at run time, and 2 for a usage or
|
|
53
|
+
configuration error, such as a key in the ``claude`` section.
|
|
54
|
+
"""
|
|
55
|
+
harness = ClaudeSdkHarness()
|
|
56
|
+
try:
|
|
57
|
+
return run_agent_cli(harness, argv)
|
|
58
|
+
except ConfigError as error:
|
|
59
|
+
print(f"{command_name(harness)}: {error}", file=sys.stderr)
|
|
60
|
+
return 2
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def run() -> None:
|
|
64
|
+
"""Run the command from its console script and exit with its code."""
|
|
65
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable, Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Sustainable Use License 1.0.
|
|
4
|
+
# You may not use this file except in compliance with the License.
|
|
5
|
+
# See the LICENSE file in the repository root.
|
|
6
|
+
#
|
|
7
|
+
# SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
|
|
8
|
+
|
|
9
|
+
"""``python -m dex_agents_claude_sdk_cli`` runs the ``dex-agents-claude-sdk`` command."""
|
|
10
|
+
|
|
11
|
+
from dex_agents_claude_sdk_cli import run
|
|
12
|
+
|
|
13
|
+
if __name__ == "__main__":
|
|
14
|
+
run()
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable, Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Sustainable Use License 1.0.
|
|
4
|
+
# You may not use this file except in compliance with the License.
|
|
5
|
+
# See the LICENSE file in the repository root.
|
|
6
|
+
#
|
|
7
|
+
# SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
|
|
8
|
+
|
|
9
|
+
"""The Claude Agent SDK harness: a session Flow with Claude Code's own local tools."""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from contextvars import ContextVar
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import dex_agents_cli_core # noqa: F401 # first: it configures gRPC before anything imports it
|
|
24
|
+
|
|
25
|
+
# isort: split
|
|
26
|
+
|
|
27
|
+
from claude_agent_sdk import ClaudeAgentOptions
|
|
28
|
+
|
|
29
|
+
from dex_agents import (
|
|
30
|
+
AgentSessionFlow,
|
|
31
|
+
AgentSessionOptions,
|
|
32
|
+
AgentTracingOptions,
|
|
33
|
+
AgentTurnContext,
|
|
34
|
+
AgentTurnOutcome,
|
|
35
|
+
DeferredToolExecution,
|
|
36
|
+
DeferredToolOutcome,
|
|
37
|
+
RunModelLimit,
|
|
38
|
+
ToolEffect,
|
|
39
|
+
ToolExecutionError,
|
|
40
|
+
ToolPolicy,
|
|
41
|
+
)
|
|
42
|
+
from dex_agents_claude_agent_sdk import (
|
|
43
|
+
ClaudeAgentOptionsContext,
|
|
44
|
+
ClaudeAgentRunner,
|
|
45
|
+
ClaudeCodeToolDenial,
|
|
46
|
+
)
|
|
47
|
+
from dex_agents_cli_core import (
|
|
48
|
+
ConfigError,
|
|
49
|
+
EffectiveConfig,
|
|
50
|
+
HarnessContext,
|
|
51
|
+
LocalToolGroup,
|
|
52
|
+
current_turn_config,
|
|
53
|
+
is_local_tool_group_enabled,
|
|
54
|
+
is_shell_command_approval_required,
|
|
55
|
+
resolve_turn_tool_policy,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
#: The Flow type of the command's sessions, before the CLI core namespaces it.
|
|
59
|
+
CLAUDE_SDK_CLI_FLOW_TYPE = "DexAgentsClaudeSdkCliSession"
|
|
60
|
+
|
|
61
|
+
#: The model the command uses when the configuration file sets none.
|
|
62
|
+
DEFAULT_CLAUDE_MODEL = "claude-opus-5-5"
|
|
63
|
+
|
|
64
|
+
#: The instructions the agent gets when the configuration sets none.
|
|
65
|
+
DEFAULT_INSTRUCTIONS = (
|
|
66
|
+
"You are a helpful assistant. Use your tools to work with the files and commands "
|
|
67
|
+
"in your working directory and with the connected services."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class _ClaudeCodeLocalTool:
|
|
73
|
+
group: LocalToolGroup
|
|
74
|
+
effect: ToolEffect
|
|
75
|
+
is_approval_required: bool
|
|
76
|
+
path_argument: str | None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# Claude Code's tools that replace the CLI core's files, shell, and web_fetch groups.
|
|
80
|
+
CLAUDE_CODE_LOCAL_TOOLS: Mapping[str, _ClaudeCodeLocalTool] = {
|
|
81
|
+
"Read": _ClaudeCodeLocalTool(LocalToolGroup.FILES, ToolEffect.READ, False, "file_path"),
|
|
82
|
+
"Grep": _ClaudeCodeLocalTool(LocalToolGroup.FILES, ToolEffect.READ, False, "path"),
|
|
83
|
+
"Glob": _ClaudeCodeLocalTool(LocalToolGroup.FILES, ToolEffect.READ, False, "path"),
|
|
84
|
+
"Write": _ClaudeCodeLocalTool(
|
|
85
|
+
LocalToolGroup.FILES, ToolEffect.IDEMPOTENT_WRITE, True, "file_path"
|
|
86
|
+
),
|
|
87
|
+
"Edit": _ClaudeCodeLocalTool(
|
|
88
|
+
LocalToolGroup.FILES, ToolEffect.NON_IDEMPOTENT_WRITE, True, "file_path"
|
|
89
|
+
),
|
|
90
|
+
"Bash": _ClaudeCodeLocalTool(LocalToolGroup.SHELL, ToolEffect.NON_IDEMPOTENT_WRITE, True, None),
|
|
91
|
+
"WebFetch": _ClaudeCodeLocalTool(LocalToolGroup.WEB_FETCH, ToolEffect.READ, False, None),
|
|
92
|
+
}
|
|
93
|
+
_RUNNING_TURN: ContextVar[AgentTurnContext] = ContextVar("dex_agents_claude_sdk_cli_turn")
|
|
94
|
+
# OSC, then CSI (Claude Code resets the cursor with one on exit), then other escapes.
|
|
95
|
+
_TERMINAL_CONTROL_SEQUENCE = re.compile(
|
|
96
|
+
r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)"
|
|
97
|
+
r"|\x1b\[[0-?]*[ -/]*[@-~]"
|
|
98
|
+
r"|\x1b[ -/]*[0-~]"
|
|
99
|
+
r"|[\x00-\x08\x0b-\x1f\x7f]"
|
|
100
|
+
)
|
|
101
|
+
_GLOB_CHARACTERS = frozenset("*?[{")
|
|
102
|
+
# The input field of each file tool that holds a glob pattern.
|
|
103
|
+
_GLOB_PATTERN_ARGUMENTS = {"Glob": "pattern", "Grep": "glob"}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ClaudeSdkHarness:
|
|
107
|
+
"""The ``dex-agents-claude-sdk`` command: a Claude Agent SDK agent in the terminal.
|
|
108
|
+
|
|
109
|
+
Claude Code's own Read, Grep, Glob, Write, Edit, Bash, and WebFetch tools
|
|
110
|
+
replace the CLI core's ``files``, ``shell``, and ``web_fetch`` groups; the
|
|
111
|
+
CLI core's browser tools and connector tools stay. Each turn offers only
|
|
112
|
+
the Claude Code tools whose group the turn switches on, plus, in a
|
|
113
|
+
resumed segment, the tools of calls the turn already recorded, so their
|
|
114
|
+
records replay; new calls of a switched-off tool are refused. The
|
|
115
|
+
workspace is the working directory. Reads run at once, Write, Edit, and
|
|
116
|
+
Bash wait for approval, and a Bash command whose whole text is in the
|
|
117
|
+
shell allow list runs at once. File tools refuse paths outside the
|
|
118
|
+
workspace.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
name = "claude-sdk"
|
|
122
|
+
config_section = "claude"
|
|
123
|
+
flow_type = CLAUDE_SDK_CLI_FLOW_TYPE
|
|
124
|
+
default_model: str | None = DEFAULT_CLAUDE_MODEL
|
|
125
|
+
replaced_local_tools = frozenset(
|
|
126
|
+
{LocalToolGroup.FILES, LocalToolGroup.SHELL, LocalToolGroup.WEB_FETCH}
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def create_session_flow(self, context: HarnessContext) -> AgentSessionFlow:
|
|
130
|
+
"""Build the Claude agent session Flow from the effective configuration.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
context: The configuration, workspace, and tool sources.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
The Flow, with ``context.flow_type`` as its type.
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
ConfigError: If the ``claude`` section has a key; it has no options yet.
|
|
140
|
+
"""
|
|
141
|
+
validate_claude_section(context.harness_options)
|
|
142
|
+
local_tools = ClaudeCodeLocalTools(context)
|
|
143
|
+
runner = _ReauthorizingClaudeAgentRunner(
|
|
144
|
+
context,
|
|
145
|
+
local_tools,
|
|
146
|
+
local_tools.build_options,
|
|
147
|
+
tool_sources=context.tool_sources,
|
|
148
|
+
claude_code_tool_permission=local_tools.decide_tool_call,
|
|
149
|
+
media_store=context.media_store,
|
|
150
|
+
)
|
|
151
|
+
return AgentSessionFlow(
|
|
152
|
+
runner,
|
|
153
|
+
flow_type=context.flow_type,
|
|
154
|
+
options=AgentSessionOptions(
|
|
155
|
+
tool_policies={},
|
|
156
|
+
default_tool_effect=ToolEffect.UNCLASSIFIED,
|
|
157
|
+
tracing=AgentTracingOptions(),
|
|
158
|
+
run_model_limit=RunModelLimit(),
|
|
159
|
+
summary_attributes_indexed=context.is_session_summary_indexed,
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def validate_claude_section(options: Mapping[str, Any]) -> None:
|
|
165
|
+
"""Reject every key of the ``claude`` section, which has no options yet.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
options: The section, ``{}`` when the file omits it.
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
ConfigError: ``schema`` with the first key's JSON Pointer.
|
|
172
|
+
"""
|
|
173
|
+
for key in sorted(options):
|
|
174
|
+
escaped = key.replace("~", "~0").replace("/", "~1")
|
|
175
|
+
raise ConfigError("schema", f"/claude/{escaped}", keyword="additionalProperties")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class ClaudeCodeLocalTools:
|
|
179
|
+
"""Apply the CLI core's local tool rules to Claude Code's own tools."""
|
|
180
|
+
|
|
181
|
+
def __init__(self, context: HarnessContext) -> None:
|
|
182
|
+
"""Bind the rules to one command's configuration and workspace.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
context: The harness context.
|
|
186
|
+
"""
|
|
187
|
+
self._context = context
|
|
188
|
+
self._workspace = Path(os.path.realpath(context.workspace))
|
|
189
|
+
|
|
190
|
+
def build_options(self, options_context: ClaudeAgentOptionsContext) -> ClaudeAgentOptions:
|
|
191
|
+
"""Return one turn segment's options: the turn's model, instructions, and tools.
|
|
192
|
+
|
|
193
|
+
.. versionchanged:: 0.6.0
|
|
194
|
+
The options load no MCP servers or claude.ai connectors from the
|
|
195
|
+
user's Claude Code configuration or login.
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
options_context: The segment's Flow ID, turn ID, and attempt.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
Options with the Claude Code tools the turn switches on and the
|
|
202
|
+
tools of calls the turn already recorded, the workspace as
|
|
203
|
+
``cwd``, no settings files, and no MCP servers or claude.ai
|
|
204
|
+
connectors from the user's Claude Code configuration. The environment
|
|
205
|
+
passes through unchanged, so ``ANTHROPIC_API_KEY`` or the
|
|
206
|
+
machine's Claude Code login reaches the CLI. The CLI's standard
|
|
207
|
+
error goes to the command's log file, never to the chat terminal.
|
|
208
|
+
|
|
209
|
+
Raises:
|
|
210
|
+
RuntimeError: Outside a model call, which never happens.
|
|
211
|
+
"""
|
|
212
|
+
turn = current_turn_config()
|
|
213
|
+
turn_context = _RUNNING_TURN.get(None)
|
|
214
|
+
if turn is None or turn_context is None:
|
|
215
|
+
raise RuntimeError("the Claude options need the running turn's configuration")
|
|
216
|
+
# A resumed CLI must find a recorded call's tool to replay it; new calls stay denied.
|
|
217
|
+
recorded_tool_names = {record.tool_name for record in turn_context.tool_calls.values()}
|
|
218
|
+
return ClaudeAgentOptions(
|
|
219
|
+
model=turn.model,
|
|
220
|
+
system_prompt=turn.instructions or DEFAULT_INSTRUCTIONS,
|
|
221
|
+
tools=[
|
|
222
|
+
tool_name
|
|
223
|
+
for tool_name, tool in CLAUDE_CODE_LOCAL_TOOLS.items()
|
|
224
|
+
if is_local_tool_group_enabled(turn, tool.group) or tool_name in recorded_tool_names
|
|
225
|
+
],
|
|
226
|
+
cwd=str(self._context.workspace),
|
|
227
|
+
# Settings files could allow tools before the session's policy sees them.
|
|
228
|
+
setting_sources=[],
|
|
229
|
+
# External tools come only from the Dex connectors, never the user's MCP config.
|
|
230
|
+
strict_mcp_config=True,
|
|
231
|
+
settings=json.dumps({"disableClaudeAiConnectors": True}, separators=(",", ":")),
|
|
232
|
+
# An inherited terminal would get the CLI's control sequences in the chat.
|
|
233
|
+
stderr=ClaudeCodeStderrLog.for_command_log().write_line,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
def decide_tool_call(
|
|
237
|
+
self, turn: AgentTurnContext, tool_name: str, tool_input: Mapping[str, Any]
|
|
238
|
+
) -> ToolPolicy | ClaudeCodeToolDenial | None:
|
|
239
|
+
"""Decide one call of a Claude Code tool in the model call.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
turn: The ``RunModel`` context.
|
|
243
|
+
tool_name: The tool's Claude Code name.
|
|
244
|
+
tool_input: The call's input.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
The call's policy, or a denial for a switched-off tool or a path
|
|
248
|
+
outside the workspace.
|
|
249
|
+
"""
|
|
250
|
+
turn_config = self._context.resolve_turn(turn.session_settings)
|
|
251
|
+
tool = CLAUDE_CODE_LOCAL_TOOLS.get(tool_name)
|
|
252
|
+
if tool is None:
|
|
253
|
+
return ClaudeCodeToolDenial(f"{tool_name} is not available in this session")
|
|
254
|
+
refusal = self.refusal_reason(turn_config, tool_name, tool_input)
|
|
255
|
+
if refusal is not None:
|
|
256
|
+
return ClaudeCodeToolDenial(refusal)
|
|
257
|
+
is_approval_required = tool.is_approval_required
|
|
258
|
+
if tool_name == "Bash":
|
|
259
|
+
# A background command outlives the turn, so it always waits for approval.
|
|
260
|
+
is_approval_required = (
|
|
261
|
+
is_shell_command_approval_required(turn_config, str(tool_input.get("command", "")))
|
|
262
|
+
or tool_input.get("run_in_background") is True
|
|
263
|
+
)
|
|
264
|
+
return resolve_turn_tool_policy(
|
|
265
|
+
turn, tool_name, tool.effect, is_approval_required, turn_config
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def refusal_reason(
|
|
269
|
+
self, turn_config: EffectiveConfig, tool_name: str, tool_input: Mapping[str, Any]
|
|
270
|
+
) -> str | None:
|
|
271
|
+
"""Return why a call of a Claude Code tool must not run, or ``None``.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
turn_config: The configuration of the call's turn.
|
|
275
|
+
tool_name: The tool's Claude Code name.
|
|
276
|
+
tool_input: The call's input.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
The reason when the turn switches the tool's group off or a file
|
|
280
|
+
tool names a path outside the workspace; ``None`` otherwise.
|
|
281
|
+
"""
|
|
282
|
+
tool = CLAUDE_CODE_LOCAL_TOOLS.get(tool_name)
|
|
283
|
+
if tool is None:
|
|
284
|
+
return None
|
|
285
|
+
if not is_local_tool_group_enabled(turn_config, tool.group):
|
|
286
|
+
return f"{tool_name} is switched off for this session"
|
|
287
|
+
paths = []
|
|
288
|
+
if tool.path_argument is not None and isinstance(tool_input.get(tool.path_argument), str):
|
|
289
|
+
paths.append(str(tool_input[tool.path_argument]))
|
|
290
|
+
pattern_argument = _GLOB_PATTERN_ARGUMENTS.get(tool_name)
|
|
291
|
+
pattern = None if pattern_argument is None else tool_input.get(pattern_argument)
|
|
292
|
+
if isinstance(pattern, str):
|
|
293
|
+
# Brace expansion can produce .. from any part of a pattern, so none may contain it.
|
|
294
|
+
if ".." in pattern:
|
|
295
|
+
return f"{tool_name} may only use paths inside the workspace {self._workspace}"
|
|
296
|
+
paths.append(_glob_base(pattern))
|
|
297
|
+
for path in paths:
|
|
298
|
+
if not self._is_inside_workspace(path):
|
|
299
|
+
return f"{tool_name} may only use paths inside the workspace {self._workspace}"
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
def _is_inside_workspace(self, path_text: str) -> bool:
|
|
303
|
+
if ".." in Path(path_text).parts:
|
|
304
|
+
return False
|
|
305
|
+
candidate = Path(os.path.expanduser(path_text))
|
|
306
|
+
if not candidate.is_absolute():
|
|
307
|
+
candidate = self._workspace / candidate
|
|
308
|
+
# realpath also follows a dangling link to the target it would create.
|
|
309
|
+
resolved = Path(os.path.realpath(candidate))
|
|
310
|
+
return resolved == self._workspace or self._workspace in resolved.parents
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class ClaudeCodeStderrLog:
|
|
314
|
+
"""Append the Claude Code CLI's standard error lines to the command's log file.
|
|
315
|
+
|
|
316
|
+
Each line loses its terminal control sequences and goes to the log in the
|
|
317
|
+
command's log format. A failed write drops the line: unlike a logging
|
|
318
|
+
handler, it never reports the failure on the chat terminal.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
def __init__(self, log_path: Path | None, formatter: logging.Formatter) -> None:
|
|
322
|
+
"""Write to one log file.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
log_path: The log file, or ``None`` to drop every line.
|
|
326
|
+
formatter: The format of each line, the log file's own.
|
|
327
|
+
"""
|
|
328
|
+
self._log_path = log_path
|
|
329
|
+
self._formatter = formatter
|
|
330
|
+
|
|
331
|
+
@classmethod
|
|
332
|
+
def for_command_log(cls) -> ClaudeCodeStderrLog:
|
|
333
|
+
"""Return a log that writes to the file of the root logger's file handler.
|
|
334
|
+
|
|
335
|
+
Returns:
|
|
336
|
+
A log for that file in its handler's format, or one that drops
|
|
337
|
+
every line when the root logger has no file handler.
|
|
338
|
+
"""
|
|
339
|
+
for handler in logging.getLogger().handlers:
|
|
340
|
+
if isinstance(handler, logging.FileHandler):
|
|
341
|
+
return cls(Path(handler.baseFilename), handler.formatter or logging.Formatter())
|
|
342
|
+
return cls(None, logging.Formatter())
|
|
343
|
+
|
|
344
|
+
def write_line(self, line: str) -> None:
|
|
345
|
+
"""Append one standard error line, without its control sequences.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
line: The line as the CLI wrote it. A line that is empty without
|
|
349
|
+
its control sequences is dropped.
|
|
350
|
+
"""
|
|
351
|
+
text = _TERMINAL_CONTROL_SEQUENCE.sub("", line).strip()
|
|
352
|
+
if not text or self._log_path is None:
|
|
353
|
+
return
|
|
354
|
+
record = logging.LogRecord(
|
|
355
|
+
__name__, logging.INFO, __file__, 0, "Claude Code stderr: %s", (text,), None
|
|
356
|
+
)
|
|
357
|
+
try:
|
|
358
|
+
with self._log_path.open("a", encoding="utf-8") as log_file:
|
|
359
|
+
log_file.write(self._formatter.format(record) + "\n")
|
|
360
|
+
except OSError:
|
|
361
|
+
# The chat terminal must never show this line, so a failed write loses it.
|
|
362
|
+
return
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _glob_base(pattern: str) -> str:
|
|
366
|
+
"""Return the leading directories of a glob pattern, before its first glob character."""
|
|
367
|
+
parts: list[str] = []
|
|
368
|
+
for part in Path(pattern).parts:
|
|
369
|
+
if _GLOB_CHARACTERS & set(part):
|
|
370
|
+
break
|
|
371
|
+
parts.append(part)
|
|
372
|
+
return str(Path(*parts)) if parts else "."
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class _ReauthorizingClaudeAgentRunner(ClaudeAgentRunner):
|
|
376
|
+
"""Give the options their turn, and check an approved Claude Code tool call in its tool Step."""
|
|
377
|
+
|
|
378
|
+
def __init__(
|
|
379
|
+
self,
|
|
380
|
+
context: HarnessContext,
|
|
381
|
+
local_tools: ClaudeCodeLocalTools,
|
|
382
|
+
*args: Any,
|
|
383
|
+
**kwargs: Any,
|
|
384
|
+
) -> None:
|
|
385
|
+
super().__init__(*args, **kwargs)
|
|
386
|
+
self._context = context
|
|
387
|
+
self._local_tools = local_tools
|
|
388
|
+
|
|
389
|
+
async def run_model_step(self, turn: AgentTurnContext) -> AgentTurnOutcome:
|
|
390
|
+
token = _RUNNING_TURN.set(turn)
|
|
391
|
+
try:
|
|
392
|
+
return await super().run_model_step(turn)
|
|
393
|
+
finally:
|
|
394
|
+
_RUNNING_TURN.reset(token)
|
|
395
|
+
|
|
396
|
+
async def execute_deferred_tool_call(self, call: DeferredToolExecution) -> DeferredToolOutcome:
|
|
397
|
+
tool_name = call.tool_call.tool_name
|
|
398
|
+
if tool_name in CLAUDE_CODE_LOCAL_TOOLS:
|
|
399
|
+
permissions = self._context.resolve_tool_step_permissions(call)
|
|
400
|
+
refusal = self._local_tools.refusal_reason(
|
|
401
|
+
permissions, tool_name, _tool_input(call.tool_call.arguments)
|
|
402
|
+
)
|
|
403
|
+
if refusal is not None:
|
|
404
|
+
raise ToolExecutionError(f"{refusal}; the call did not run")
|
|
405
|
+
return await super().execute_deferred_tool_call(call)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _tool_input(arguments: str) -> Mapping[str, Any]:
|
|
409
|
+
parsed = json.loads(arguments)
|
|
410
|
+
return parsed if isinstance(parsed, dict) else {}
|
|
File without changes
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dex-agents-claude-sdk-cli
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: The dex-agents-claude-sdk command: a durable Claude Agent SDK agent in your terminal
|
|
5
|
+
Author: Super Durable
|
|
6
|
+
License-Expression: LicenseRef-Sustainable-Use-1.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Dist: claude-agent-sdk>=0.2.176,<0.3
|
|
13
|
+
Requires-Dist: dex-agents==0.6.0
|
|
14
|
+
Requires-Dist: dex-agents-claude-agent-sdk==0.6.0
|
|
15
|
+
Requires-Dist: dex-agents-cli-core==0.6.0
|
|
16
|
+
Requires-Dist: dex-python-sdk==1.45.0
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Project-URL: Homepage, https://github.com/superdurable/dex/tree/main/agents/cli/python/claude-sdk
|
|
19
|
+
Project-URL: Repository, https://github.com/superdurable/dex
|
|
20
|
+
Project-URL: Changelog, https://github.com/superdurable/dex/blob/main/agents/CHANGELOG.md
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# dex-agents-claude-sdk-cli
|
|
24
|
+
|
|
25
|
+
`dex-agents-claude-sdk-cli` provides the `dex-agents-claude-sdk` command. It
|
|
26
|
+
runs a [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-python)
|
|
27
|
+
agent as a durable Dex agent session and chats with it in your terminal. The
|
|
28
|
+
shared CLI core, [`dex-agents-cli-core`](../core/README.md), starts or reuses
|
|
29
|
+
`dexcli dev`, connects the connectors MCP server, and runs the Worker. This
|
|
30
|
+
package only builds the agent with the
|
|
31
|
+
[Claude Agent SDK adapter](../../../python/claude-agent-sdk/README.md).
|
|
32
|
+
|
|
33
|
+
The TypeScript package `@superdurable/dex-agents-claude-sdk-cli` provides the
|
|
34
|
+
same command with the same behavior.
|
|
35
|
+
|
|
36
|
+
## Running it
|
|
37
|
+
|
|
38
|
+
The command needs Python 3.11 or later and an Anthropic API key:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
export ANTHROPIC_API_KEY=sk-ant-...
|
|
42
|
+
uvx --from dex-agents-claude-sdk-cli dex-agents-claude-sdk
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The first run asks the `init` questions and writes
|
|
46
|
+
`~/.dex/agents/claude-sdk.yaml`. Then type a message at the `>` prompt. Approve
|
|
47
|
+
or reject tool calls with `y` or `n`, and press Ctrl-D to exit. The session
|
|
48
|
+
stays in Dex, and the command prints the `--resume` line that continues it.
|
|
49
|
+
See the [CLI core README](../core/README.md#running-a-command) for every
|
|
50
|
+
subcommand and option, and [`agents/cli`](../../README.md) for the
|
|
51
|
+
configuration file.
|
|
52
|
+
|
|
53
|
+
The command passes its environment to Claude Code unchanged and never stores
|
|
54
|
+
the key.
|
|
55
|
+
|
|
56
|
+
## Configuration
|
|
57
|
+
|
|
58
|
+
The model defaults to `claude-opus-5-5`; set `model` in the file or pass
|
|
59
|
+
`--model` to change it. `system_prompt` replaces the default instructions.
|
|
60
|
+
The `claude` section has no options yet, and any key in it is a configuration
|
|
61
|
+
error.
|
|
62
|
+
|
|
63
|
+
## Local tools
|
|
64
|
+
|
|
65
|
+
Claude Code's own tools replace the CLI core's `files`, `shell`, and
|
|
66
|
+
`web_fetch` tools. The CLI core's browser tools and connector tools stay.
|
|
67
|
+
|
|
68
|
+
| `local_tools` group | Claude Code tools | Approval |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `files` | `Read`, `Grep`, `Glob` | No |
|
|
71
|
+
| `files` | `Write`, `Edit` | Every call |
|
|
72
|
+
| `shell` | `Bash` | Unless `local_tools.shell.allow` has the whole command text. A background command always waits. |
|
|
73
|
+
| `web_fetch` | `WebFetch` | No |
|
|
74
|
+
|
|
75
|
+
- Each turn offers only the tools whose group the turn switches on, after
|
|
76
|
+
the session settings narrow the file. A switched-off group's tools are not
|
|
77
|
+
offered, and a call of one is refused. One exception: a resumed segment
|
|
78
|
+
also lists the Claude Code tools the turn already recorded calls of, so the
|
|
79
|
+
CLI can replay those records; a new call of such a tool is still refused
|
|
80
|
+
while its group is off.
|
|
81
|
+
- `approval.always` adds approval to any of these tools by name, such as
|
|
82
|
+
`Read`.
|
|
83
|
+
- Claude Code runs in the workspace. The file tools refuse a path outside it,
|
|
84
|
+
after resolving `~`, symbolic links, and relative paths, and refuse any
|
|
85
|
+
path with `..`. A dangling symbolic link counts as the target it would
|
|
86
|
+
create. A `Glob` pattern or a `Grep` `glob` must not contain `..` at all,
|
|
87
|
+
and an absolute one must start inside the workspace. `Bash` is not confined:
|
|
88
|
+
an approved command runs with your permissions.
|
|
89
|
+
- Claude Code reads no settings files, so their allow rules cannot skip an
|
|
90
|
+
approval. Its other tools, such as subagents, are not offered.
|
|
91
|
+
- The command uses only these Claude Code tools, the CLI core's browser
|
|
92
|
+
tools, and the connector tools. It loads no MCP servers and no claude.ai
|
|
93
|
+
connectors from your Claude Code configuration or login, such as a
|
|
94
|
+
workspace `.mcp.json` or the Gmail connector of a claude.ai account.
|
|
95
|
+
External tools come only from the Dex connectors, which Dex approves and
|
|
96
|
+
records as Steps.
|
|
97
|
+
- An approved call is checked again in its tool Step, on the Worker that runs
|
|
98
|
+
it, with that Worker's configuration file narrowed by the turn's session
|
|
99
|
+
settings. It fails without running when its group is off there or its path
|
|
100
|
+
is outside the workspace, and the model sees why. The session settings
|
|
101
|
+
count as the turn started with them, so a change takes effect from the next
|
|
102
|
+
turn.
|
|
103
|
+
- These tools run inside the Claude Code CLI, not in their own Dex Steps. A
|
|
104
|
+
Worker that dies during a turn segment runs the segment again, so a tool
|
|
105
|
+
call in it can run twice. Connector and browser tools run in their own
|
|
106
|
+
Steps and are recorded.
|
|
107
|
+
|
|
108
|
+
## Images
|
|
109
|
+
|
|
110
|
+
`/image <path>` attaches an image file to the next message. The command gives
|
|
111
|
+
the Claude Agent SDK adapter the media store of `media.store`, so the model sees the
|
|
112
|
+
image, and images that tools return go to the same store. See
|
|
113
|
+
[Images](../../README.md#images).
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
Develop with uv 0.12.2. The package resolves `dex-agents`, the adapter, and
|
|
118
|
+
the CLI core from this repository by path. `ci.sh` installs the locked
|
|
119
|
+
dependencies, checks lint and types, and runs the tests against a private
|
|
120
|
+
`dexcli dev`:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
cd agents/cli/python/claude-sdk
|
|
124
|
+
DEXCLI=/path/to/dexcli ./ci.sh
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The tests run the command in a pseudo-terminal with a private home. The
|
|
128
|
+
bundled Claude Code CLI calls `tests/mock_messages_api.py`, a scripted
|
|
129
|
+
Messages API on 127.0.0.1; a refused proxy stops any other request. A fake
|
|
130
|
+
connectors MCP server serves a connector read and write. The tests cover a
|
|
131
|
+
chat turn and `--resume`, a connector read and an approved connector write
|
|
132
|
+
that runs once, `Read`, `Glob`, `Grep`, and `WebFetch` without approval,
|
|
133
|
+
`Write`, `Edit`, and `Bash` after approval, an allow-listed command run in the
|
|
134
|
+
workspace and an allow-listed background command that still waits, paths and
|
|
135
|
+
patterns that leave the workspace, a dangling link to outside, session
|
|
136
|
+
settings that switch the shell off, an approved call that the Worker running
|
|
137
|
+
it refuses after its file switched the group off, and the environment that
|
|
138
|
+
reaches Claude Code with and without a key.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
dex_agents_claude_sdk_cli/__init__.py,sha256=fjt3qjUguZYzjhGb2j_yZwqFyPbvy81bsG3_Zd5pyGg,1860
|
|
2
|
+
dex_agents_claude_sdk_cli/__main__.py,sha256=1QlK2BTxjJBdCQYJ0hflXZ8WQKDOeYBf8_QiKWuyak0,439
|
|
3
|
+
dex_agents_claude_sdk_cli/harness.py,sha256=zCXF03yIk5loebQxfDACvMB8K_mF4JNrJ7MKW6U_8bo,16513
|
|
4
|
+
dex_agents_claude_sdk_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
dex_agents_claude_sdk_cli-0.6.0.dist-info/licenses/LICENSE,sha256=0AJCV4ky-vrSnT08IIdYpyiFPPoF2UrtKsBAvuvt1G4,4220
|
|
6
|
+
dex_agents_claude_sdk_cli-0.6.0.dist-info/WHEEL,sha256=q9Wah2_CgP24mRNSlTyb0F8Yrbz55SzVl8eHLkZ_wvE,80
|
|
7
|
+
dex_agents_claude_sdk_cli-0.6.0.dist-info/entry_points.txt,sha256=SokQXq835ezy2RJVXSDwMtADqCNSONyxc3flPd_I4kA,73
|
|
8
|
+
dex_agents_claude_sdk_cli-0.6.0.dist-info/METADATA,sha256=yG5_oDSrxp9MWyMJr_gpLz2fvhv8mhDiLkD0-LGJ8WE,6591
|
|
9
|
+
dex_agents_claude_sdk_cli-0.6.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Super Durable, Inc.
|
|
4
|
+
|
|
5
|
+
Portions of this software are licensed as follows:
|
|
6
|
+
|
|
7
|
+
- Legacy Materials remain under their original licenses as described in
|
|
8
|
+
`LEGACY_NOTICES.md`.
|
|
9
|
+
- Third-Party Materials remain under the licenses provided by their owners.
|
|
10
|
+
- The `docs/` and `examples/` directories are not licensed under the
|
|
11
|
+
Sustainable Use License and retain their existing licensing status.
|
|
12
|
+
- All other material owned or licensable by Super Durable, Inc. is available
|
|
13
|
+
under the Sustainable Use License below.
|
|
14
|
+
|
|
15
|
+
See `LEGACY_NOTICES.md` for the applicable legacy and third-party notices.
|
|
16
|
+
|
|
17
|
+
## Sustainable Use License
|
|
18
|
+
|
|
19
|
+
Version 1.0
|
|
20
|
+
|
|
21
|
+
### Acceptance
|
|
22
|
+
|
|
23
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
24
|
+
|
|
25
|
+
### Copyright License
|
|
26
|
+
|
|
27
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
28
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
29
|
+
available, and prepare derivative works of the software, in each case subject
|
|
30
|
+
to the limitations below.
|
|
31
|
+
|
|
32
|
+
### Limitations
|
|
33
|
+
|
|
34
|
+
You may use or modify the software only for your own internal business purposes
|
|
35
|
+
or for non-commercial or personal use. You may distribute the software or
|
|
36
|
+
provide it to others only if you do so free of charge for non-commercial
|
|
37
|
+
purposes. You may not alter, remove, or obscure any licensing, copyright, or
|
|
38
|
+
other notices of the licensor in the software. Any use of the licensor's
|
|
39
|
+
trademarks is subject to applicable law.
|
|
40
|
+
|
|
41
|
+
### Patents
|
|
42
|
+
|
|
43
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
44
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
45
|
+
sale, import and have imported the software, in each case subject to the
|
|
46
|
+
limitations and conditions in this license. This license does not cover any
|
|
47
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
48
|
+
the software.
|
|
49
|
+
|
|
50
|
+
If you or your company make any written claim that the software infringes or
|
|
51
|
+
contributes to infringement of any patent, your patent license for the software
|
|
52
|
+
granted under these terms ends immediately. If your company makes such a claim,
|
|
53
|
+
your patent license ends immediately for work on behalf of your company.
|
|
54
|
+
|
|
55
|
+
### Notices
|
|
56
|
+
|
|
57
|
+
You must ensure that anyone who gets a copy of any part of the software from
|
|
58
|
+
you also gets a copy of these terms. If you modify the software, you must
|
|
59
|
+
include in any modified copies of the software a prominent notice stating that
|
|
60
|
+
you have modified the software.
|
|
61
|
+
|
|
62
|
+
### No Other Rights
|
|
63
|
+
|
|
64
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
65
|
+
these terms.
|
|
66
|
+
|
|
67
|
+
### Termination
|
|
68
|
+
|
|
69
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
70
|
+
and your license will automatically terminate. If the licensor provides you
|
|
71
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
72
|
+
later than 30 days after you receive that notice, your license will be
|
|
73
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
74
|
+
reinstatement, any additional violation of these terms will cause your license
|
|
75
|
+
to terminate automatically and permanently.
|
|
76
|
+
|
|
77
|
+
### No Liability
|
|
78
|
+
|
|
79
|
+
As far as the law allows, the software comes as is, without any warranty or
|
|
80
|
+
condition, and the licensor will not be liable to you for any damages arising
|
|
81
|
+
out of these terms or the use or nature of the software, under any kind of
|
|
82
|
+
legal claim.
|
|
83
|
+
|
|
84
|
+
### Definitions
|
|
85
|
+
|
|
86
|
+
The "licensor" is the entity offering these terms.
|
|
87
|
+
|
|
88
|
+
The "software" is the software the licensor makes available under these terms,
|
|
89
|
+
including any portion of it.
|
|
90
|
+
|
|
91
|
+
"You" refers to the individual or entity agreeing to these terms.
|
|
92
|
+
|
|
93
|
+
"Your company" is any legal entity, sole proprietorship, or other kind of
|
|
94
|
+
organization that you work for, plus all organizations that have control over,
|
|
95
|
+
are under the control of, or are under common control with that organization.
|
|
96
|
+
Control means ownership of substantially all the assets of an entity, or the
|
|
97
|
+
power to direct its management and policies by vote, contract, or otherwise.
|
|
98
|
+
Control can be direct or indirect.
|
|
99
|
+
|
|
100
|
+
"Your license" is the license granted to you for the software under these
|
|
101
|
+
terms.
|
|
102
|
+
|
|
103
|
+
"Use" means anything you do with the software requiring your license.
|
|
104
|
+
|
|
105
|
+
"Trademark" means trademarks, service marks, and similar rights.
|