harnext 0.1.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.
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: harnext
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the harnext coding agent — subprocesses the harnext CLI with a Claude Agent SDK-compatible API.
5
+ Author-email: Yasha Boroumand <yasha1boroumand@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/QualityUnit/harnext
8
+ Project-URL: Repository, https://github.com/QualityUnit/harnext
9
+ Project-URL: Documentation, https://github.com/QualityUnit/harnext/blob/main/sdk/python/README.md
10
+ Project-URL: Issues, https://github.com/QualityUnit/harnext/issues
11
+ Keywords: ai-agent,coding-agent,harnext,claude-agent-sdk,llm,agent
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.4; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
28
+ Requires-Dist: build>=1.2; extra == "dev"
29
+ Requires-Dist: twine>=5.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # harnext Python SDK
33
+
34
+ Run the [harnext](https://github.com/QualityUnit/harnext) coding agent from Python. The SDK subprocesses
35
+ the harnext CLI (`harnext -p --output-format stream-json`) and yields parsed
36
+ messages, with an API that mirrors the
37
+ [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) for the
38
+ supported surface.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install harnext # from PyPI
44
+ # or, from a checkout of this repo:
45
+ pip install -e sdk/python
46
+
47
+ # the harnext CLI must be installed too:
48
+ npm install -g harnext # or set HARNEXT_CLI_PATH to the CLI entry
49
+ ```
50
+
51
+ The SDK locates the CLI via, in order: the `cli_path` option, the
52
+ `HARNEXT_CLI_PATH` env var, or `harnext` on `PATH`. A `.js` path is run with
53
+ `node`.
54
+
55
+ ## Quickstart
56
+
57
+ ```python
58
+ import asyncio
59
+ from harnext_sdk import query, HarnextAgentOptions, ResultMessage
60
+
61
+ async def main():
62
+ async for message in query(
63
+ prompt="What files are in this directory?",
64
+ options=HarnextAgentOptions(allowed_tools=["Read", "Bash"]),
65
+ ):
66
+ if isinstance(message, ResultMessage):
67
+ print(message.result)
68
+
69
+ asyncio.run(main())
70
+ ```
71
+
72
+ ## Options (`HarnextAgentOptions`)
73
+
74
+ Field names match `claude_agent_sdk.ClaudeAgentOptions`; `ClaudeAgentOptions` is
75
+ exported as an alias so ported code runs unchanged.
76
+
77
+ | Option | CLI flag | Notes |
78
+ | --- | --- | --- |
79
+ | `model` | `--model` | |
80
+ | `system_prompt` | `--system-prompt` | |
81
+ | `append_system_prompt` | `--append-system-prompt` | |
82
+ | `cwd` | `--cwd` | |
83
+ | `allowed_tools` | `--allowed-tools` | auto-approve list |
84
+ | `disallowed_tools` | `--disallowed-tools` | blocked + hidden |
85
+ | `permission_mode` | `--permission-mode` | `default`/`acceptEdits`/`plan`/`dontAsk`/`bypassPermissions` |
86
+ | `max_turns` | `--max-turns` | |
87
+ | `setting_sources` | `--setting-sources` | `user`/`project`/`local` → loads `CLAUDE.md` |
88
+ | `add_dirs` | `--add-dir` | accepted; not yet enforced |
89
+ | `fallback_model` | `--fallback-model` | accepted; reserved |
90
+ | `sandbox` | `--sandbox` | accepted; **currently a no-op** in harnext |
91
+ | `provider` | `--provider` | harnext extra |
92
+ | `thinking` | `--thinking` | harnext extra |
93
+ | `env` | (process env) | merged over `os.environ` |
94
+ | `cli_path` | — | path to the CLI entry point |
95
+ | `extra_args` | passthrough | `{"flag": "value"}` → `--flag value` |
96
+
97
+ ### Tool names
98
+
99
+ Use the Claude names (`Read`, `Write`, `Edit`, `Bash`); they are matched
100
+ case-insensitively against harnext's native tools and echoed back in PascalCase.
101
+
102
+ ## Messages
103
+
104
+ `query()` yields `SystemMessage` (init), `AssistantMessage`, `UserMessage`
105
+ (tool results), then a terminal `ResultMessage` with `subtype`
106
+ (`success` / `error_max_turns` / `error_during_execution`), `result`,
107
+ `num_turns`, `duration_ms`, `total_cost_usd`, and `usage`.
108
+
109
+ ## Tests
110
+
111
+ ```bash
112
+ cd sdk/python
113
+ pip install -e ".[dev]"
114
+ pytest # unit + stub-subprocess e2e
115
+ HARNEXT_LIVE_E2E=1 pytest -k live # live run against the real CLI (needs a provider key)
116
+ ```
117
+
118
+ ## Publishing to PyPI
119
+
120
+ The package name on PyPI is **`harnext`** (import name `harnext_sdk`).
121
+
122
+ ### CI (recommended): trusted publishing
123
+
124
+ `.github/workflows/publish-python-sdk.yml` builds, tests, and publishes via PyPI
125
+ [trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC — no token
126
+ stored in the repo).
127
+
128
+ 1. One-time: on PyPI (and TestPyPI) add a *pending publisher* for project
129
+ `harnext`, owner `QualityUnit`, repo `harnext`, workflow
130
+ `publish-python-sdk.yml`.
131
+ 2. Dry run to TestPyPI: run the workflow manually (`workflow_dispatch`, default
132
+ target `testpypi`).
133
+ 3. Release to PyPI: push a tag `python-v0.1.0` (independent of the CLI's `v*`
134
+ tags), or run the workflow manually with target `pypi`.
135
+
136
+ ### Manual
137
+
138
+ ```bash
139
+ cd sdk/python
140
+ python -m build # -> dist/*.whl, dist/*.tar.gz
141
+ python -m twine check dist/*
142
+ python -m twine upload dist/* # needs a PyPI API token (TWINE_USERNAME=__token__)
143
+ ```
144
+
145
+ Bump `version` in `pyproject.toml` and `__version__` in `harnext_sdk/__init__.py`
146
+ together for each release.
@@ -0,0 +1,13 @@
1
+ harnext-0.1.0.dist-info/licenses/LICENSE,sha256=-8janKSe89TaFCYzzf_Fwth5QP365tf7ImAhjHilws8,1072
2
+ harnext_sdk/__init__.py,sha256=AvgN_lYXLlaSv55klbBlTIf3rpK5BD-UlXFlCnUYxQw,1760
3
+ harnext_sdk/_cli.py,sha256=NudQE2OdWk9k5cKfiOCI3KqT9GxUL15ajGjuAGo6wAs,3454
4
+ harnext_sdk/_errors.py,sha256=xSG5RMAXXfuD244G9ThKRdlhzz7xCrEyTiWC1jCBVZM,828
5
+ harnext_sdk/_parser.py,sha256=9VZhY_1hPsO1ws6V2dnhUlShBHTPYn5fyHuQgHG638g,3364
6
+ harnext_sdk/_transport.py,sha256=Hed4RIIaas1nvvaXQVdx_5LxO1OEy0zJEoagSJWNipw,3671
7
+ harnext_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ harnext_sdk/query.py,sha256=e5OJ9rMjiEB_hjOAcKEJY5wFK0sKYsik56y_UwIkelA,2038
9
+ harnext_sdk/types.py,sha256=7USZPbYMfoEk3ctQv485TgCwKVdSllY5ThP-rTzSG4c,4016
10
+ harnext-0.1.0.dist-info/METADATA,sha256=9-PxtRv8bnaovF96cZiVjjTemINsqRNZriVZD6-xO2Q,5458
11
+ harnext-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ harnext-0.1.0.dist-info/top_level.txt,sha256=TN8r-fN3e_1e6QVKx9ulhuufp3SxhANJGgRhqSC2AGA,12
13
+ harnext-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yasha Boroumand
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ harnext_sdk
@@ -0,0 +1,79 @@
1
+ """harnext Python SDK.
2
+
3
+ Run the harnext coding agent from Python by subprocessing its CLI, with an API
4
+ that mirrors the Claude Agent SDK for the supported surface.
5
+
6
+ import asyncio
7
+ from harnext_sdk import query, HarnextAgentOptions, ResultMessage
8
+
9
+ async def main():
10
+ async for message in query(
11
+ prompt="What files are in this directory?",
12
+ options=HarnextAgentOptions(allowed_tools=["Read", "Bash"]),
13
+ ):
14
+ if isinstance(message, ResultMessage):
15
+ print(message.result)
16
+
17
+ asyncio.run(main())
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from ._cli import build_command, resolve_cli_invocation
23
+ from ._errors import (
24
+ CLINotFoundError,
25
+ HarnextSDKError,
26
+ MessageParseError,
27
+ ProcessError,
28
+ )
29
+ from ._parser import parse_line, parse_message
30
+ from .query import query
31
+ from .types import (
32
+ AssistantMessage,
33
+ ClaudeAgentOptions,
34
+ ContentBlock,
35
+ HarnextAgentOptions,
36
+ InputFormat,
37
+ Message,
38
+ OutputFormat,
39
+ PermissionMode,
40
+ ResultMessage,
41
+ SettingSource,
42
+ SystemMessage,
43
+ TextBlock,
44
+ ThinkingBlock,
45
+ ToolResultBlock,
46
+ ToolUseBlock,
47
+ UserMessage,
48
+ )
49
+
50
+ __version__ = "0.1.0"
51
+
52
+ __all__ = [
53
+ "query",
54
+ "HarnextAgentOptions",
55
+ "ClaudeAgentOptions",
56
+ "PermissionMode",
57
+ "OutputFormat",
58
+ "InputFormat",
59
+ "SettingSource",
60
+ "Message",
61
+ "SystemMessage",
62
+ "AssistantMessage",
63
+ "UserMessage",
64
+ "ResultMessage",
65
+ "ContentBlock",
66
+ "TextBlock",
67
+ "ThinkingBlock",
68
+ "ToolUseBlock",
69
+ "ToolResultBlock",
70
+ "HarnextSDKError",
71
+ "CLINotFoundError",
72
+ "ProcessError",
73
+ "MessageParseError",
74
+ "build_command",
75
+ "resolve_cli_invocation",
76
+ "parse_line",
77
+ "parse_message",
78
+ "__version__",
79
+ ]
harnext_sdk/_cli.py ADDED
@@ -0,0 +1,105 @@
1
+ """Locate the harnext CLI and translate options into CLI arguments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ from typing import Optional
10
+
11
+ from ._errors import CLINotFoundError
12
+ from .types import HarnextAgentOptions, InputFormat, OutputFormat
13
+
14
+
15
+ def resolve_cli_invocation(cli_path: Optional[os.PathLike[str] | str]) -> list[str]:
16
+ """Return the argv prefix that launches the harnext CLI.
17
+
18
+ Resolution order:
19
+ 1. explicit ``cli_path`` option,
20
+ 2. ``HARNEXT_CLI_PATH`` environment variable,
21
+ 3. ``harnext`` on ``PATH``.
22
+
23
+ A path ending in ``.js``/``.mjs`` is run with ``node``; one ending in
24
+ ``.py`` is run with the current interpreter (used by the test stub);
25
+ anything else is assumed directly executable.
26
+ """
27
+ candidate = cli_path or os.environ.get("HARNEXT_CLI_PATH")
28
+ if candidate:
29
+ path = os.fspath(candidate)
30
+ suffix = os.path.splitext(path)[1].lower()
31
+ if suffix in (".js", ".mjs"):
32
+ return ["node", path]
33
+ if suffix == ".py":
34
+ return [sys.executable, path]
35
+ return [path]
36
+
37
+ found = shutil.which("harnext")
38
+ if found:
39
+ return [found]
40
+
41
+ raise CLINotFoundError(
42
+ "Could not find the harnext CLI. Install it (npm i -g harnext), or set "
43
+ "the HARNEXT_CLI_PATH environment variable / cli_path option to the CLI "
44
+ "entry point."
45
+ )
46
+
47
+
48
+ def build_command(
49
+ prompt: str,
50
+ options: HarnextAgentOptions,
51
+ *,
52
+ output_format: OutputFormat = "stream-json",
53
+ input_format: InputFormat = "text",
54
+ ) -> list[str]:
55
+ """Build the full argv for a one-shot ``harnext -p`` run."""
56
+ argv = resolve_cli_invocation(options.cli_path)
57
+ argv += ["-p", "--output-format", output_format]
58
+ if input_format != "text":
59
+ argv += ["--input-format", input_format]
60
+
61
+ if options.model:
62
+ argv += ["--model", options.model]
63
+ if options.fallback_model:
64
+ argv += ["--fallback-model", options.fallback_model]
65
+ if options.provider:
66
+ argv += ["--provider", options.provider]
67
+ if options.thinking:
68
+ argv += ["--thinking", options.thinking]
69
+
70
+ if options.system_prompt is not None:
71
+ argv += ["--system-prompt", options.system_prompt]
72
+ if options.append_system_prompt is not None:
73
+ argv += ["--append-system-prompt", options.append_system_prompt]
74
+
75
+ if options.cwd is not None:
76
+ argv += ["--cwd", os.fspath(options.cwd)]
77
+ if options.permission_mode:
78
+ argv += ["--permission-mode", options.permission_mode]
79
+ if options.max_turns is not None:
80
+ argv += ["--max-turns", str(options.max_turns)]
81
+
82
+ for tool in options.allowed_tools or []:
83
+ argv += ["--allowed-tools", tool]
84
+ for tool in options.disallowed_tools or []:
85
+ argv += ["--disallowed-tools", tool]
86
+ for source in options.setting_sources or []:
87
+ argv += ["--setting-sources", source]
88
+ for directory in options.add_dirs or []:
89
+ argv += ["--add-dir", os.fspath(directory)]
90
+
91
+ if options.sandbox is not None:
92
+ argv += ["--sandbox", json.dumps(options.sandbox)]
93
+
94
+ for key, value in (options.extra_args or {}).items():
95
+ flag = f"--{key}"
96
+ if value is None:
97
+ argv.append(flag)
98
+ else:
99
+ argv += [flag, value]
100
+
101
+ # Text input: the prompt is the trailing positional argument.
102
+ if input_format == "text":
103
+ argv.append(prompt)
104
+
105
+ return argv
harnext_sdk/_errors.py ADDED
@@ -0,0 +1,28 @@
1
+ """Exceptions raised by the harnext Python SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class HarnextSDKError(Exception):
7
+ """Base class for all SDK errors."""
8
+
9
+
10
+ class CLINotFoundError(HarnextSDKError):
11
+ """The harnext CLI executable could not be located."""
12
+
13
+
14
+ class ProcessError(HarnextSDKError):
15
+ """The CLI subprocess exited with a non-zero status and no result message."""
16
+
17
+ def __init__(self, message: str, *, exit_code: int | None = None, stderr: str = "") -> None:
18
+ super().__init__(message)
19
+ self.exit_code = exit_code
20
+ self.stderr = stderr
21
+
22
+
23
+ class MessageParseError(HarnextSDKError):
24
+ """A line emitted by the CLI could not be parsed as a known message."""
25
+
26
+ def __init__(self, message: str, *, line: str = "") -> None:
27
+ super().__init__(message)
28
+ self.line = line
harnext_sdk/_parser.py ADDED
@@ -0,0 +1,109 @@
1
+ """Parse the CLI's stream-json envelopes into message dataclasses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Optional
7
+
8
+ from ._errors import MessageParseError
9
+ from .types import (
10
+ AssistantMessage,
11
+ ContentBlock,
12
+ Message,
13
+ ResultMessage,
14
+ SystemMessage,
15
+ TextBlock,
16
+ ThinkingBlock,
17
+ ToolResultBlock,
18
+ ToolUseBlock,
19
+ UserMessage,
20
+ )
21
+
22
+
23
+ def _parse_content_blocks(content: Any) -> list[ContentBlock]:
24
+ blocks: list[ContentBlock] = []
25
+ if not isinstance(content, list):
26
+ return blocks
27
+ for raw in content:
28
+ if not isinstance(raw, dict):
29
+ continue
30
+ block_type = raw.get("type")
31
+ if block_type == "text":
32
+ blocks.append(TextBlock(text=raw.get("text", "")))
33
+ elif block_type == "thinking":
34
+ blocks.append(ThinkingBlock(thinking=raw.get("thinking", "")))
35
+ elif block_type == "tool_use":
36
+ blocks.append(
37
+ ToolUseBlock(
38
+ id=raw.get("id", ""),
39
+ name=raw.get("name", ""),
40
+ input=raw.get("input", {}) or {},
41
+ )
42
+ )
43
+ elif block_type == "tool_result":
44
+ blocks.append(
45
+ ToolResultBlock(
46
+ tool_use_id=raw.get("tool_use_id", ""),
47
+ content=raw.get("content"),
48
+ is_error=bool(raw.get("is_error", False)),
49
+ )
50
+ )
51
+ return blocks
52
+
53
+
54
+ def parse_message(obj: dict[str, Any]) -> Optional[Message]:
55
+ """Convert a decoded envelope dict into a message, or ``None`` if unknown."""
56
+ msg_type = obj.get("type")
57
+ session_id = obj.get("session_id")
58
+
59
+ if msg_type == "system":
60
+ return SystemMessage(
61
+ subtype=obj.get("subtype", ""),
62
+ data=obj,
63
+ session_id=session_id,
64
+ )
65
+
66
+ if msg_type == "assistant":
67
+ message = obj.get("message", {}) or {}
68
+ return AssistantMessage(
69
+ content=_parse_content_blocks(message.get("content")),
70
+ model=message.get("model"),
71
+ usage=message.get("usage"),
72
+ stop_reason=message.get("stop_reason"),
73
+ session_id=session_id,
74
+ )
75
+
76
+ if msg_type == "user":
77
+ message = obj.get("message", {}) or {}
78
+ return UserMessage(
79
+ content=_parse_content_blocks(message.get("content")),
80
+ session_id=session_id,
81
+ )
82
+
83
+ if msg_type == "result":
84
+ return ResultMessage(
85
+ subtype=obj.get("subtype", ""),
86
+ is_error=bool(obj.get("is_error", False)),
87
+ result=obj.get("result"),
88
+ session_id=session_id,
89
+ num_turns=int(obj.get("num_turns", 0)),
90
+ duration_ms=int(obj.get("duration_ms", 0)),
91
+ total_cost_usd=obj.get("total_cost_usd"),
92
+ usage=obj.get("usage", {}) or {},
93
+ )
94
+
95
+ return None
96
+
97
+
98
+ def parse_line(line: str) -> Optional[Message]:
99
+ """Decode a single NDJSON line into a message (``None`` for blank/unknown)."""
100
+ stripped = line.strip()
101
+ if not stripped:
102
+ return None
103
+ try:
104
+ obj = json.loads(stripped)
105
+ except json.JSONDecodeError as exc:
106
+ raise MessageParseError(f"Invalid JSON from CLI: {exc}", line=stripped) from exc
107
+ if not isinstance(obj, dict):
108
+ return None
109
+ return parse_message(obj)
@@ -0,0 +1,99 @@
1
+ """Async subprocess transport: spawn the harnext CLI, stream its NDJSON stdout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ from typing import AsyncIterator, Callable, Optional
8
+
9
+ from ._errors import ProcessError
10
+
11
+ _DEFAULT_BUFFER_LIMIT = 10 * 1024 * 1024 # 10 MiB per stdout line
12
+
13
+
14
+ class SubprocessCLITransport:
15
+ """Spawns the CLI and yields decoded stdout lines.
16
+
17
+ Use as an async context manager::
18
+
19
+ transport = SubprocessCLITransport(command=argv, cwd=cwd)
20
+ async with transport:
21
+ async for line in transport.read_lines():
22
+ ...
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ command: list[str],
29
+ cwd: Optional[os.PathLike[str] | str] = None,
30
+ env: Optional[dict[str, str]] = None,
31
+ stderr_callback: Optional[Callable[[str], None]] = None,
32
+ buffer_limit: Optional[int] = None,
33
+ ) -> None:
34
+ self._command = command
35
+ self._cwd = os.fspath(cwd) if cwd is not None else None
36
+ self._env = env
37
+ self._stderr_callback = stderr_callback
38
+ self._buffer_limit = buffer_limit or _DEFAULT_BUFFER_LIMIT
39
+ self._process: Optional[asyncio.subprocess.Process] = None
40
+ self._stderr_task: Optional[asyncio.Task[None]] = None
41
+ self._stderr_lines: list[str] = []
42
+ self._saw_result = False
43
+
44
+ async def __aenter__(self) -> "SubprocessCLITransport":
45
+ self._process = await asyncio.create_subprocess_exec(
46
+ *self._command,
47
+ stdin=asyncio.subprocess.DEVNULL,
48
+ stdout=asyncio.subprocess.PIPE,
49
+ stderr=asyncio.subprocess.PIPE,
50
+ cwd=self._cwd,
51
+ env=self._env,
52
+ limit=self._buffer_limit,
53
+ )
54
+ self._stderr_task = asyncio.ensure_future(self._drain_stderr())
55
+ return self
56
+
57
+ async def __aexit__(self, exc_type, exc, tb) -> None:
58
+ process = self._process
59
+ if process is None:
60
+ return
61
+
62
+ if exc_type is not None and process.returncode is None:
63
+ # The consumer bailed out early — terminate the child.
64
+ try:
65
+ process.terminate()
66
+ except ProcessLookupError:
67
+ pass
68
+
69
+ await process.wait()
70
+ if self._stderr_task is not None:
71
+ await self._stderr_task
72
+
73
+ # Surface a hard failure only when the CLI exited non-zero *and* never
74
+ # produced a result envelope (which already carries error details).
75
+ if exc_type is None and process.returncode not in (0, None) and not self._saw_result:
76
+ stderr_text = "\n".join(self._stderr_lines)
77
+ raise ProcessError(
78
+ f"harnext CLI exited with code {process.returncode}.",
79
+ exit_code=process.returncode,
80
+ stderr=stderr_text,
81
+ )
82
+
83
+ async def _drain_stderr(self) -> None:
84
+ assert self._process is not None and self._process.stderr is not None
85
+ async for raw in self._process.stderr:
86
+ text = raw.decode("utf-8", errors="replace").rstrip("\n")
87
+ self._stderr_lines.append(text)
88
+ if self._stderr_callback is not None:
89
+ self._stderr_callback(text)
90
+
91
+ async def read_lines(self) -> AsyncIterator[str]:
92
+ """Yield each stdout line (without the trailing newline)."""
93
+ assert self._process is not None and self._process.stdout is not None
94
+ async for raw in self._process.stdout:
95
+ yield raw.decode("utf-8", errors="replace").rstrip("\n")
96
+
97
+ def mark_result_seen(self) -> None:
98
+ """Record that a result envelope arrived (suppresses exit-code errors)."""
99
+ self._saw_result = True
harnext_sdk/py.typed ADDED
File without changes
harnext_sdk/query.py ADDED
@@ -0,0 +1,63 @@
1
+ """The ``query()`` entry point: run harnext once and stream parsed messages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import AsyncIterator, Optional
7
+
8
+ from ._cli import build_command
9
+ from ._parser import parse_line
10
+ from ._transport import SubprocessCLITransport
11
+ from .types import HarnextAgentOptions, Message, ResultMessage
12
+
13
+
14
+ def _merge_env(options: HarnextAgentOptions) -> Optional[dict[str, str]]:
15
+ # Inherit the full environment by default (so provider API keys flow
16
+ # through). When the caller supplies env vars, layer them on top.
17
+ if not options.env:
18
+ return None
19
+ return {**os.environ, **options.env}
20
+
21
+
22
+ async def query(
23
+ *,
24
+ prompt: str,
25
+ options: Optional[HarnextAgentOptions] = None,
26
+ ) -> AsyncIterator[Message]:
27
+ """Run a one-shot harnext task and yield messages as they arrive.
28
+
29
+ Mirrors ``claude_agent_sdk.query``: spawns the harnext CLI as a subprocess
30
+ with ``--output-format stream-json`` and yields
31
+ :class:`~harnext_sdk.types.SystemMessage`,
32
+ :class:`~harnext_sdk.types.AssistantMessage`,
33
+ :class:`~harnext_sdk.types.UserMessage`, and a terminal
34
+ :class:`~harnext_sdk.types.ResultMessage`.
35
+
36
+ Example::
37
+
38
+ async for message in query(
39
+ prompt="List the files here",
40
+ options=HarnextAgentOptions(allowed_tools=["Read", "Bash"]),
41
+ ):
42
+ if isinstance(message, ResultMessage):
43
+ print(message.result)
44
+ """
45
+ opts = options or HarnextAgentOptions()
46
+ command = build_command(prompt, opts)
47
+
48
+ transport = SubprocessCLITransport(
49
+ command=command,
50
+ cwd=opts.cwd,
51
+ env=_merge_env(opts),
52
+ stderr_callback=opts.stderr,
53
+ buffer_limit=opts.max_buffer_size,
54
+ )
55
+
56
+ async with transport:
57
+ async for line in transport.read_lines():
58
+ message = parse_line(line)
59
+ if message is None:
60
+ continue
61
+ if isinstance(message, ResultMessage):
62
+ transport.mark_result_seen()
63
+ yield message
harnext_sdk/types.py ADDED
@@ -0,0 +1,142 @@
1
+ """Public types for the harnext Python SDK.
2
+
3
+ The option and message shapes mirror the Claude Agent SDK one-to-one for the
4
+ surface we support, so existing ``claude_agent_sdk`` code ports over by swapping
5
+ the import. ``ClaudeAgentOptions`` is exported as an alias of
6
+ ``HarnextAgentOptions`` for drop-in use.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Callable, Literal, Optional, Union
14
+
15
+ PermissionMode = Literal["default", "acceptEdits", "plan", "dontAsk", "bypassPermissions"]
16
+ OutputFormat = Literal["text", "json", "stream-json"]
17
+ InputFormat = Literal["text", "stream-json"]
18
+ SettingSource = Literal["user", "project", "local"]
19
+
20
+
21
+ @dataclass
22
+ class HarnextAgentOptions:
23
+ """Configuration for a :func:`harnext_sdk.query` run.
24
+
25
+ Field names match ``claude_agent_sdk.ClaudeAgentOptions`` for the supported
26
+ surface. Options the harness does not yet act on (``sandbox``,
27
+ ``fallback_model``, ``add_dirs``) are accepted so caller code is unchanged.
28
+ """
29
+
30
+ # --- Tools ---
31
+ allowed_tools: list[str] = field(default_factory=list)
32
+ disallowed_tools: list[str] = field(default_factory=list)
33
+
34
+ # --- System prompt ---
35
+ system_prompt: Optional[str] = None
36
+ append_system_prompt: Optional[str] = None
37
+
38
+ # --- Permissions ---
39
+ permission_mode: Optional[PermissionMode] = None
40
+
41
+ # --- Limits ---
42
+ max_turns: Optional[int] = None
43
+
44
+ # --- Model ---
45
+ model: Optional[str] = None
46
+ fallback_model: Optional[str] = None
47
+ # harnext extras (no Claude equivalent):
48
+ provider: Optional[str] = None
49
+ thinking: Optional[str] = None
50
+
51
+ # --- Environment / filesystem ---
52
+ cwd: Optional[Union[str, os.PathLike[str]]] = None
53
+ add_dirs: list[Union[str, os.PathLike[str]]] = field(default_factory=list)
54
+ env: dict[str, str] = field(default_factory=dict)
55
+ setting_sources: Optional[list[SettingSource]] = None
56
+
57
+ # --- Sandbox (accepted; currently a no-op in harnext) ---
58
+ sandbox: Optional[dict[str, Any]] = None
59
+
60
+ # --- Transport / advanced ---
61
+ cli_path: Optional[Union[str, os.PathLike[str]]] = None
62
+ extra_args: dict[str, Optional[str]] = field(default_factory=dict)
63
+ stderr: Optional[Callable[[str], None]] = None
64
+ max_buffer_size: Optional[int] = None
65
+
66
+
67
+ # Drop-in alias for ported claude_agent_sdk code.
68
+ ClaudeAgentOptions = HarnextAgentOptions
69
+
70
+
71
+ # --------------------------------------------------------------------------- #
72
+ # Content blocks
73
+ # --------------------------------------------------------------------------- #
74
+ @dataclass
75
+ class TextBlock:
76
+ text: str
77
+
78
+
79
+ @dataclass
80
+ class ThinkingBlock:
81
+ thinking: str
82
+
83
+
84
+ @dataclass
85
+ class ToolUseBlock:
86
+ id: str
87
+ name: str
88
+ input: dict[str, Any] = field(default_factory=dict)
89
+
90
+
91
+ @dataclass
92
+ class ToolResultBlock:
93
+ tool_use_id: str
94
+ content: Any = None
95
+ is_error: bool = False
96
+
97
+
98
+ ContentBlock = Union[TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock]
99
+
100
+
101
+ # --------------------------------------------------------------------------- #
102
+ # Messages
103
+ # --------------------------------------------------------------------------- #
104
+ @dataclass
105
+ class SystemMessage:
106
+ """A system event, e.g. the ``init`` envelope at session start."""
107
+
108
+ subtype: str
109
+ data: dict[str, Any]
110
+ session_id: Optional[str] = None
111
+
112
+
113
+ @dataclass
114
+ class AssistantMessage:
115
+ content: list[ContentBlock]
116
+ model: Optional[str] = None
117
+ usage: Optional[dict[str, Any]] = None
118
+ stop_reason: Optional[str] = None
119
+ session_id: Optional[str] = None
120
+
121
+
122
+ @dataclass
123
+ class UserMessage:
124
+ """User-role message; in practice carries tool_result blocks."""
125
+
126
+ content: list[ContentBlock]
127
+ session_id: Optional[str] = None
128
+
129
+
130
+ @dataclass
131
+ class ResultMessage:
132
+ subtype: str
133
+ is_error: bool
134
+ result: Optional[str]
135
+ session_id: Optional[str]
136
+ num_turns: int
137
+ duration_ms: int
138
+ total_cost_usd: Optional[float]
139
+ usage: dict[str, Any]
140
+
141
+
142
+ Message = Union[SystemMessage, AssistantMessage, UserMessage, ResultMessage]