harnext 0.1.0__tar.gz

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.
harnext-0.1.0/LICENSE ADDED
@@ -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.
harnext-0.1.0/PKG-INFO ADDED
@@ -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,115 @@
1
+ # harnext Python SDK
2
+
3
+ Run the [harnext](https://github.com/QualityUnit/harnext) coding agent from Python. The SDK subprocesses
4
+ the harnext CLI (`harnext -p --output-format stream-json`) and yields parsed
5
+ messages, with an API that mirrors the
6
+ [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) for the
7
+ supported surface.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install harnext # from PyPI
13
+ # or, from a checkout of this repo:
14
+ pip install -e sdk/python
15
+
16
+ # the harnext CLI must be installed too:
17
+ npm install -g harnext # or set HARNEXT_CLI_PATH to the CLI entry
18
+ ```
19
+
20
+ The SDK locates the CLI via, in order: the `cli_path` option, the
21
+ `HARNEXT_CLI_PATH` env var, or `harnext` on `PATH`. A `.js` path is run with
22
+ `node`.
23
+
24
+ ## Quickstart
25
+
26
+ ```python
27
+ import asyncio
28
+ from harnext_sdk import query, HarnextAgentOptions, ResultMessage
29
+
30
+ async def main():
31
+ async for message in query(
32
+ prompt="What files are in this directory?",
33
+ options=HarnextAgentOptions(allowed_tools=["Read", "Bash"]),
34
+ ):
35
+ if isinstance(message, ResultMessage):
36
+ print(message.result)
37
+
38
+ asyncio.run(main())
39
+ ```
40
+
41
+ ## Options (`HarnextAgentOptions`)
42
+
43
+ Field names match `claude_agent_sdk.ClaudeAgentOptions`; `ClaudeAgentOptions` is
44
+ exported as an alias so ported code runs unchanged.
45
+
46
+ | Option | CLI flag | Notes |
47
+ | --- | --- | --- |
48
+ | `model` | `--model` | |
49
+ | `system_prompt` | `--system-prompt` | |
50
+ | `append_system_prompt` | `--append-system-prompt` | |
51
+ | `cwd` | `--cwd` | |
52
+ | `allowed_tools` | `--allowed-tools` | auto-approve list |
53
+ | `disallowed_tools` | `--disallowed-tools` | blocked + hidden |
54
+ | `permission_mode` | `--permission-mode` | `default`/`acceptEdits`/`plan`/`dontAsk`/`bypassPermissions` |
55
+ | `max_turns` | `--max-turns` | |
56
+ | `setting_sources` | `--setting-sources` | `user`/`project`/`local` → loads `CLAUDE.md` |
57
+ | `add_dirs` | `--add-dir` | accepted; not yet enforced |
58
+ | `fallback_model` | `--fallback-model` | accepted; reserved |
59
+ | `sandbox` | `--sandbox` | accepted; **currently a no-op** in harnext |
60
+ | `provider` | `--provider` | harnext extra |
61
+ | `thinking` | `--thinking` | harnext extra |
62
+ | `env` | (process env) | merged over `os.environ` |
63
+ | `cli_path` | — | path to the CLI entry point |
64
+ | `extra_args` | passthrough | `{"flag": "value"}` → `--flag value` |
65
+
66
+ ### Tool names
67
+
68
+ Use the Claude names (`Read`, `Write`, `Edit`, `Bash`); they are matched
69
+ case-insensitively against harnext's native tools and echoed back in PascalCase.
70
+
71
+ ## Messages
72
+
73
+ `query()` yields `SystemMessage` (init), `AssistantMessage`, `UserMessage`
74
+ (tool results), then a terminal `ResultMessage` with `subtype`
75
+ (`success` / `error_max_turns` / `error_during_execution`), `result`,
76
+ `num_turns`, `duration_ms`, `total_cost_usd`, and `usage`.
77
+
78
+ ## Tests
79
+
80
+ ```bash
81
+ cd sdk/python
82
+ pip install -e ".[dev]"
83
+ pytest # unit + stub-subprocess e2e
84
+ HARNEXT_LIVE_E2E=1 pytest -k live # live run against the real CLI (needs a provider key)
85
+ ```
86
+
87
+ ## Publishing to PyPI
88
+
89
+ The package name on PyPI is **`harnext`** (import name `harnext_sdk`).
90
+
91
+ ### CI (recommended): trusted publishing
92
+
93
+ `.github/workflows/publish-python-sdk.yml` builds, tests, and publishes via PyPI
94
+ [trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC — no token
95
+ stored in the repo).
96
+
97
+ 1. One-time: on PyPI (and TestPyPI) add a *pending publisher* for project
98
+ `harnext`, owner `QualityUnit`, repo `harnext`, workflow
99
+ `publish-python-sdk.yml`.
100
+ 2. Dry run to TestPyPI: run the workflow manually (`workflow_dispatch`, default
101
+ target `testpypi`).
102
+ 3. Release to PyPI: push a tag `python-v0.1.0` (independent of the CLI's `v*`
103
+ tags), or run the workflow manually with target `pypi`.
104
+
105
+ ### Manual
106
+
107
+ ```bash
108
+ cd sdk/python
109
+ python -m build # -> dist/*.whl, dist/*.tar.gz
110
+ python -m twine check dist/*
111
+ python -m twine upload dist/* # needs a PyPI API token (TWINE_USERNAME=__token__)
112
+ ```
113
+
114
+ Bump `version` in `pyproject.toml` and `__version__` in `harnext_sdk/__init__.py`
115
+ together for each release.
@@ -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,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ harnext.egg-info/PKG-INFO
5
+ harnext.egg-info/SOURCES.txt
6
+ harnext.egg-info/dependency_links.txt
7
+ harnext.egg-info/requires.txt
8
+ harnext.egg-info/top_level.txt
9
+ harnext_sdk/__init__.py
10
+ harnext_sdk/_cli.py
11
+ harnext_sdk/_errors.py
12
+ harnext_sdk/_parser.py
13
+ harnext_sdk/_transport.py
14
+ harnext_sdk/py.typed
15
+ harnext_sdk/query.py
16
+ harnext_sdk/types.py
17
+ tests/test_cli_args.py
18
+ tests/test_e2e_stub.py
19
+ tests/test_live.py
20
+ tests/test_parser.py
@@ -0,0 +1,6 @@
1
+
2
+ [dev]
3
+ pytest>=7.4
4
+ pytest-asyncio>=0.23
5
+ build>=1.2
6
+ twine>=5.0
@@ -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
+ ]
@@ -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
@@ -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