doorae-machine 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.
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .ruff_cache/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ *.db
11
+ .env
@@ -0,0 +1,201 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please also get an in-depth
186
+ understanding of "Why should I apply the Apache License" FAQ at
187
+ <http://www.apache.org/foundation/license-faq.html>
188
+
189
+ Copyright 2024 Changyong Um
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: doorae-machine
3
+ Version: 0.1.0
4
+ Summary: Machine daemon for Doorae agent orchestration
5
+ Author: Changyong Um
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: argon2-cffi>=23.1
10
+ Requires-Dist: click>=8.1
11
+ Requires-Dist: httpx>=0.27
12
+ Requires-Dist: psutil>=5.9
13
+ Requires-Dist: pydantic-settings>=2.2
14
+ Requires-Dist: pydantic<3.0,>=2.6
15
+ Requires-Dist: pyyaml>=6.0
16
+ Requires-Dist: structlog>=24.1
17
+ Requires-Dist: websockets>=12.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: mypy>=1.9; extra == 'dev'
20
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
21
+ Requires-Dist: pytest>=8.0; extra == 'dev'
22
+ Requires-Dist: ruff>=0.3; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # doorae-machine
26
+
27
+ Machine daemon for Doorae agent orchestration. Connects to the doorae-server via WebSocket and manages agent subprocesses on the local machine.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install -e ".[dev]"
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```bash
38
+ # Register this machine with a Doorae server
39
+ doorae-machine register --server wss://doorae.example.com --name my-machine
40
+
41
+ # Run the daemon
42
+ doorae-machine run
43
+
44
+ # Check status
45
+ doorae-machine status
46
+
47
+ # Install as systemd user service
48
+ doorae-machine install-systemd-unit
49
+ ```
@@ -0,0 +1,25 @@
1
+ # doorae-machine
2
+
3
+ Machine daemon for Doorae agent orchestration. Connects to the doorae-server via WebSocket and manages agent subprocesses on the local machine.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install -e ".[dev]"
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```bash
14
+ # Register this machine with a Doorae server
15
+ doorae-machine register --server wss://doorae.example.com --name my-machine
16
+
17
+ # Run the daemon
18
+ doorae-machine run
19
+
20
+ # Check status
21
+ doorae-machine status
22
+
23
+ # Install as systemd user service
24
+ doorae-machine install-systemd-unit
25
+ ```
@@ -0,0 +1,3 @@
1
+ """Machine daemon for Doorae agent orchestration."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,151 @@
1
+ """Per-agent directory path validation.
2
+
3
+ Shared whitelist rules for files that the server manifest (via
4
+ ``spawn_agent.files``) is allowed to materialize under an agent's
5
+ directory on disk. The same rules must be enforced server-side when
6
+ rows go into ``agent_files``, but this module is the machine-side
7
+ defense-in-depth layer.
8
+
9
+ Goals:
10
+
11
+ - **No agent-id escape**: ``msg.agent_id`` is used as a path segment
12
+ under ``~/.doorae/agents/``, so a malicious server that sends
13
+ ``agent_id="../other"`` or ``agent_id="/etc"`` would have
14
+ ``Path(root) / agent_id`` escape the managed root. A narrow
15
+ filename-like regex makes this impossible at the source.
16
+ - **No path escape**: absolute paths, ``..`` traversal, symlink-expressed
17
+ paths, and control characters are rejected.
18
+ - **No workspace clobber**: ``workspace/`` is the agent's runtime
19
+ scratch and must not be writable from the manifest, otherwise the
20
+ server could overwrite state the agent was relying on between
21
+ spawns.
22
+ - **No synthetic file collisions**: ``AGENTS.md`` is written by the
23
+ materializer from ``spawn_agent.agents_md``, and ``CLAUDE.md`` is a
24
+ synthetic symlink the materializer creates — neither can come
25
+ through the ``files`` map.
26
+ - **No executables**: only text-ish configuration extensions are
27
+ allowed, so a compromised admin account can't smuggle a binary or
28
+ shell script onto the host.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import re
34
+ from pathlib import PurePosixPath
35
+
36
+ _ALLOWED_PREFIXES: tuple[str, ...] = (
37
+ "skills/",
38
+ ".codex/",
39
+ ".claude/",
40
+ ".gemini/",
41
+ ".openhands/",
42
+ )
43
+
44
+ _ALLOWED_EXTENSIONS: frozenset[str] = frozenset(
45
+ {".md", ".json", ".toml", ".txt", ".yaml", ".yml", ".env"}
46
+ )
47
+
48
+ # Cap path depth so a manifest can't force the materializer into
49
+ # unbounded mkdir trees. Six segments (e.g.
50
+ # skills/a/b/c/refs/deep.md) is plenty for realistic skill layouts.
51
+ _MAX_DEPTH = 6
52
+
53
+ # Bound total length to keep pathological inputs from ballooning
54
+ # filesystem syscalls.
55
+ _MAX_PATH_LEN = 512
56
+
57
+ # ``agent_id`` is used as a path segment, so it has to be safe to
58
+ # concatenate with a directory. Doorae itself generates UUID4 strings
59
+ # (36 chars, ``[0-9a-f-]``), but we allow a slightly wider alphabet
60
+ # so test fixtures like ``agent-x`` also fit. No dots (which would
61
+ # let ``.`` and ``..`` through), no slashes, no control characters.
62
+ _AGENT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
63
+
64
+
65
+ class AgentFilePathError(ValueError):
66
+ """Raised when a manifest path does not meet the whitelist rules."""
67
+
68
+
69
+ def validate_agent_id(agent_id: str) -> None:
70
+ """Raise :class:`AgentFilePathError` if *agent_id* is not safe to
71
+ use as a directory name under the agent-dir root.
72
+
73
+ This is a critical defense: ``Path(root) / agent_id`` does not
74
+ protect against absolute paths (``/etc`` clobbers the join) or
75
+ ``..`` traversal (``../other`` escapes). Reject both by requiring
76
+ a narrow filename-like alphabet.
77
+ """
78
+ if not isinstance(agent_id, str):
79
+ raise AgentFilePathError(
80
+ f"agent_id must be a string, got {type(agent_id).__name__}"
81
+ )
82
+ if not _AGENT_ID_RE.match(agent_id):
83
+ raise AgentFilePathError(
84
+ f"agent_id {agent_id!r} must match {_AGENT_ID_RE.pattern}"
85
+ )
86
+
87
+
88
+ def validate_agent_file_path(path: str) -> None:
89
+ """Raise :class:`AgentFilePathError` if *path* is not an allowed
90
+ agent-manifest path.
91
+
92
+ Rules mirror the plan doc and ADR-002 — keep in sync with the
93
+ server-side copy in ``doorae_server/agent_files.py``.
94
+ """
95
+ if not path:
96
+ raise AgentFilePathError("path is empty")
97
+
98
+ if len(path) > _MAX_PATH_LEN:
99
+ raise AgentFilePathError(
100
+ f"path longer than {_MAX_PATH_LEN} chars ({len(path)} given)"
101
+ )
102
+
103
+ if any(ord(ch) < 0x20 for ch in path):
104
+ raise AgentFilePathError("path contains control/null character")
105
+
106
+ if path.startswith("/"):
107
+ raise AgentFilePathError("absolute paths are forbidden")
108
+
109
+ if "\\" in path:
110
+ raise AgentFilePathError("backslashes are forbidden")
111
+
112
+ if "//" in path:
113
+ raise AgentFilePathError("double slashes are forbidden")
114
+
115
+ # Break into POSIX parts after the checks above so PurePosixPath
116
+ # cannot normalize away segments we care about rejecting.
117
+ parts = path.split("/")
118
+ for part in parts:
119
+ if part in ("", ".", ".."):
120
+ raise AgentFilePathError(f"segment {part!r} is forbidden")
121
+
122
+ if len(parts) > _MAX_DEPTH:
123
+ raise AgentFilePathError(
124
+ f"path deeper than {_MAX_DEPTH} segments ({len(parts)} given)"
125
+ )
126
+
127
+ # Extension check. Leading-dot filenames (e.g. ``.env``) are
128
+ # ``PurePosixPath(...).suffix == ""`` because Python treats the
129
+ # whole basename as an extension marker, so we read the name
130
+ # directly for those.
131
+ name = PurePosixPath(path).name
132
+ if name.startswith(".") and "." not in name[1:]:
133
+ suffix = name
134
+ else:
135
+ suffix = PurePosixPath(path).suffix
136
+ if suffix not in _ALLOWED_EXTENSIONS:
137
+ raise AgentFilePathError(
138
+ f"extension {suffix!r} is not in the allowed set"
139
+ )
140
+
141
+ if not any(path.startswith(prefix) for prefix in _ALLOWED_PREFIXES):
142
+ raise AgentFilePathError(
143
+ f"path must start with one of {_ALLOWED_PREFIXES}"
144
+ )
145
+
146
+ # workspace/ is the runtime scratch for the agent and must never
147
+ # be clobbered by a manifest write. The prefix list above already
148
+ # excludes it, but we assert explicitly to keep this rule obvious
149
+ # when someone adds a future prefix.
150
+ if parts[0] == "workspace":
151
+ raise AgentFilePathError("workspace/ is runtime-only, not manifest")
@@ -0,0 +1,234 @@
1
+ """CLI entry point: register, run, status, install-systemd-unit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import getpass
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import click
11
+ import httpx
12
+ import structlog
13
+
14
+ from doorae_machine.config import MachineConfig, load_token, save_token
15
+ from doorae_machine.daemon import MachineDaemon
16
+ from doorae_machine.detector import detect_engines
17
+
18
+ log = structlog.get_logger()
19
+
20
+
21
+ @click.group()
22
+ def main() -> None:
23
+ """Doorae Machine Daemon - manages agent subprocesses."""
24
+ structlog.configure(
25
+ processors=[
26
+ structlog.dev.ConsoleRenderer(),
27
+ ],
28
+ wrapper_class=structlog.make_filtering_bound_logger(20), # INFO
29
+ )
30
+
31
+
32
+ @main.command()
33
+ @click.option("--server", required=True, help="Doorae server URL (e.g. https://doorae.example.com)")
34
+ @click.option("--name", required=True, help="Human-readable machine name")
35
+ @click.option("--max-agents", default=4, help="Maximum concurrent agents")
36
+ def register(server: str, name: str, max_agents: int) -> None:
37
+ """Register this machine with a Doorae server."""
38
+ # Step 1: Authenticate user
39
+ click.echo("Authenticate with Doorae server:")
40
+ email = click.prompt(" Email")
41
+ password = getpass.getpass(" Password: ")
42
+
43
+ base_url = server.rstrip("/")
44
+ try:
45
+ with httpx.Client(timeout=30) as client:
46
+ # Get JWT
47
+ resp = client.post(
48
+ f"{base_url}/api/v1/auth/login",
49
+ json={"email": email, "password": password},
50
+ )
51
+ resp.raise_for_status()
52
+ jwt_token = resp.json()["token"]
53
+
54
+ # Step 2: Detect engines
55
+ click.echo("Detecting available engines...")
56
+ result = asyncio.run(detect_engines())
57
+ capabilities = [
58
+ {"engine": e.engine, "version": e.version, "path": e.path}
59
+ for e in result.engines
60
+ ]
61
+ click.echo(f" Found {len(capabilities)} engine(s)")
62
+ for cap in capabilities:
63
+ click.echo(f" - {cap['engine']} ({cap['version']})")
64
+
65
+ # Step 3: Register machine
66
+ resp = client.post(
67
+ f"{base_url}/api/v1/machines",
68
+ json={
69
+ "name": name,
70
+ "capabilities": capabilities,
71
+ "max_agents": max_agents,
72
+ },
73
+ headers={"Authorization": f"Bearer {jwt_token}"},
74
+ )
75
+ resp.raise_for_status()
76
+ data = resp.json()
77
+ machine_id = data.get("id") or data.get("machine_id")
78
+ machine_token = data["machine_token"]
79
+
80
+ except httpx.HTTPStatusError as exc:
81
+ click.echo(f"Error: Server returned {exc.response.status_code}", err=True)
82
+ sys.exit(1)
83
+ except httpx.RequestError as exc:
84
+ click.echo(f"Error: Could not connect to server: {exc}", err=True)
85
+ sys.exit(1)
86
+
87
+ # Step 4: Save config and token
88
+ # Determine WS URL from server base
89
+ ws_url = base_url.replace("https://", "wss://").replace("http://", "ws://")
90
+ ws_url = f"{ws_url}/ws/machines/{machine_id}"
91
+
92
+ config = MachineConfig(
93
+ machine_id=machine_id,
94
+ name=name,
95
+ server_url=ws_url,
96
+ max_agents=max_agents,
97
+ )
98
+ config.save()
99
+ save_token(machine_token)
100
+
101
+ click.echo(f"Registered! machine_id={machine_id}")
102
+ click.echo(f"Config saved to ~/.doorae/machine.toml")
103
+ click.echo(f"Token saved to ~/.doorae/machine.token (chmod 600)")
104
+
105
+
106
+ @main.command()
107
+ @click.option("--config", "config_path", type=click.Path(exists=True), default=None,
108
+ help="Config file path (default: ~/.doorae/machine.toml)")
109
+ @click.option("--server", default=None, help="Server WS URL override (e.g. ws://host:8000)")
110
+ @click.option("--token", default=None, help="Machine token override (or use ~/.doorae/machine.token)")
111
+ @click.option("--machine-id", default=None, help="Machine ID override")
112
+ @click.option("--max-agents", default=None, type=int, help="Max agents override")
113
+ def run(config_path: str | None, server: str | None, token: str | None, machine_id: str | None, max_agents: int | None) -> None:
114
+ """Run the machine daemon (connects to server via WebSocket)."""
115
+ # Try loading config file, but allow all-CLI usage
116
+ try:
117
+ path = Path(config_path) if config_path else None
118
+ config = MachineConfig.load(path)
119
+ except Exception:
120
+ config = MachineConfig(machine_id="", name="", server_url="")
121
+
122
+ file_token = None
123
+ try:
124
+ file_token = load_token()
125
+ except Exception:
126
+ pass
127
+
128
+ # CLI overrides
129
+ final_id = machine_id or config.machine_id
130
+ final_server = server or config.server_url
131
+ final_token = token or file_token
132
+ final_max = max_agents or config.max_agents or 4
133
+
134
+ # Build WS URL if HTTP URL given
135
+ if final_server and final_server.startswith("http"):
136
+ final_server = final_server.replace("https://", "wss://").replace("http://", "ws://")
137
+ # Append /ws/machines/{id} if not already present
138
+ if final_server and "/ws/machines/" not in final_server and final_id:
139
+ final_server = f"{final_server.rstrip('/')}/ws/machines/{final_id}"
140
+
141
+ if not final_id:
142
+ click.echo("Error: No machine_id. Run 'doorae-machine register' or pass --machine-id.", err=True)
143
+ sys.exit(1)
144
+ if not final_server:
145
+ click.echo("Error: No server URL. Run 'doorae-machine register' or pass --server.", err=True)
146
+ sys.exit(1)
147
+ if not final_token:
148
+ click.echo("Error: No token. Run 'doorae-machine register' or pass --token.", err=True)
149
+ sys.exit(1)
150
+
151
+ click.echo(f"Starting daemon: machine_id={final_id}, server={final_server}")
152
+ daemon = MachineDaemon(
153
+ server_url=final_server,
154
+ machine_id=final_id,
155
+ machine_token=final_token,
156
+ max_agents=final_max,
157
+ labels=config.labels if hasattr(config, 'labels') else {},
158
+ )
159
+ try:
160
+ asyncio.run(daemon.run())
161
+ except KeyboardInterrupt:
162
+ click.echo("Daemon stopped.")
163
+
164
+
165
+ @main.command()
166
+ def status() -> None:
167
+ """Show machine status from the server."""
168
+ config = MachineConfig.load()
169
+ token = load_token()
170
+
171
+ if not config.machine_id or not token:
172
+ click.echo("Error: Not registered. Run 'doorae-machine register' first.", err=True)
173
+ sys.exit(1)
174
+
175
+ # Derive HTTP base URL from WS URL
176
+ base_url = config.server_url.replace("wss://", "https://").replace("ws://", "http://")
177
+ base_url = base_url.rsplit("/ws/", 1)[0]
178
+
179
+ try:
180
+ with httpx.Client(timeout=15) as client:
181
+ resp = client.get(
182
+ f"{base_url}/api/v1/machines/{config.machine_id}",
183
+ headers={"Authorization": f"Bearer {token}"},
184
+ )
185
+ resp.raise_for_status()
186
+ data = resp.json()
187
+ except httpx.HTTPStatusError as exc:
188
+ click.echo(f"Error: Server returned {exc.response.status_code}", err=True)
189
+ sys.exit(1)
190
+ except httpx.RequestError as exc:
191
+ click.echo(f"Error: Could not connect: {exc}", err=True)
192
+ sys.exit(1)
193
+
194
+ click.echo(f"Machine: {data.get('name', config.name)} ({config.machine_id})")
195
+ click.echo(f"Status: {data.get('status', 'unknown')}")
196
+ agents = data.get("running_agents", [])
197
+ click.echo(f"Agents: {len(agents)} running")
198
+ for agent in agents:
199
+ click.echo(f" - {agent.get('agent_id', '?')} (engine={agent.get('engine', '?')})")
200
+
201
+
202
+ @main.command("install-systemd-unit")
203
+ def install_systemd_unit() -> None:
204
+ """Generate and install a systemd user unit file."""
205
+ unit_dir = Path.home() / ".config" / "systemd" / "user"
206
+ unit_dir.mkdir(parents=True, exist_ok=True)
207
+ unit_path = unit_dir / "doorae-machine.service"
208
+
209
+ unit_content = f"""\
210
+ [Unit]
211
+ Description=Doorae Machine Daemon
212
+ After=network-online.target
213
+ Wants=network-online.target
214
+
215
+ [Service]
216
+ Type=simple
217
+ ExecStart={sys.executable} -m doorae_machine.cli run
218
+ Restart=always
219
+ RestartSec=5
220
+ Environment=PATH={Path(sys.executable).parent}:/usr/bin:/bin
221
+
222
+ [Install]
223
+ WantedBy=default.target
224
+ """
225
+
226
+ unit_path.write_text(unit_content)
227
+ click.echo(f"Unit file written to {unit_path}")
228
+ click.echo("Enable and start with:")
229
+ click.echo(" systemctl --user daemon-reload")
230
+ click.echo(" systemctl --user enable --now doorae-machine")
231
+
232
+
233
+ if __name__ == "__main__":
234
+ main()