agent-bios 0.19.2 → 0.19.4
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.
- package/DEPENDENCIES.md +76 -20
- package/INSTALL.md +1 -1
- package/README.md +55 -5
- package/claude/agents/sweep.md +2 -1
- package/claude/agents/workhorse.md +2 -2
- package/claude/guides/claude-prompting.md +101 -15
- package/claude/guides/cli-multi-model-workflow.md +5 -5
- package/claude/guides/coding-staged-workflow.md +17 -0
- package/claude/guides/gpt-prompting.md +40 -9
- package/claude/guides/llm-capability-boundary.md +7 -1
- package/claude/guides/tooling-gotchas.md +20 -1
- package/claude/guides/ui-design/visual-direction.md +88 -0
- package/claude/guides/ui-design.md +90 -0
- package/claude/guides/verification-discipline.md +10 -1
- package/claude/hooks/tooling-gotchas-hook.py +41 -0
- package/codex/agents/reviewer.toml +2 -2
- package/codex/agents/sweep.toml +1 -1
- package/codex/agents/workhorse.toml +2 -2
- package/codex/guides/claude-prompting.md +101 -15
- package/codex/guides/cli-multi-model-workflow.md +5 -5
- package/codex/guides/coding-staged-workflow.md +17 -0
- package/codex/guides/gpt-prompting.md +40 -9
- package/codex/guides/llm-capability-boundary.md +7 -1
- package/codex/guides/tooling-gotchas.md +20 -1
- package/codex/guides/ui-design/visual-direction.md +88 -0
- package/codex/guides/ui-design.md +90 -0
- package/codex/guides/verification-discipline.md +10 -1
- package/compose/app_bridge/scripts/bridge.py +23 -6
- package/compose/app_desktop/server.py +250 -0
- package/compose/domains.json +1 -0
- package/compose/host_platform.py +121 -0
- package/compose/instructions-state.py +5 -2
- package/compose/instructions_app.py +281 -48
- package/compose/instructions_catalog.py +2 -2
- package/compose/instructions_import.py +19 -11
- package/compose/instructions_install.py +77 -11
- package/compose/instructions_session.py +6 -6
- package/compose/instructions_setup.py +47 -10
- package/compose/instructions_setup_cli.py +31 -10
- package/compose/instructions_setup_i18n.py +6 -3
- package/compose/instructions_store.py +6 -6
- package/compose/instructions_transaction.py +8 -6
- package/compose/instructions_ui_runtime.py +4 -3
- package/compose/native_cli.py +52 -0
- package/compose/runtime_entry.py +58 -0
- package/compose/setup/START.md +1 -1
- package/compose/windows_deploy.py +719 -0
- package/docs/instructions.md +1 -0
- package/docs/releases/0.19.3.md +107 -0
- package/docs/releases/0.19.4.md +99 -0
- package/docs/session-model.md +8 -0
- package/docs/setup.md +39 -3
- package/docs/windows.md +99 -0
- package/install.sh +13 -6
- package/launch/agent-launch.py +31 -8
- package/launch/agent-launch.toml +49 -24
- package/launch/agent-launch.zsh +11 -1
- package/launch/provision-venv.sh +1 -1
- package/package.json +9 -4
- package/provenance.json +1 -1
- package/session-cost.py +61 -9
- package/wrappers/codex-helm.sh +6 -6
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Claude Desktop MCP server for explicit agent-bios instructions delivery.
|
|
3
|
+
|
|
4
|
+
It is a transport at the same layer as `compose/app_bridge/scripts/bridge.py`: it
|
|
5
|
+
owns no selection, ContentRef, receipt or identifier. Each tool call resolves the
|
|
6
|
+
confirmed private release again and runs that release's
|
|
7
|
+
`compose/instructions_app.py session <op> --host claude-desktop` in a child
|
|
8
|
+
process, so a package update answers from the next call and this long-lived
|
|
9
|
+
process holds nothing across requests.
|
|
10
|
+
|
|
11
|
+
Protocol 2025-11-25 over stdio, the revision Desktop speaks; a call that arrives
|
|
12
|
+
without a handshake is still answered, because nothing here depends on one.
|
|
13
|
+
Standard library only; stdout carries protocol messages and nothing else.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
HERE = Path(__file__).resolve().parent
|
|
25
|
+
PROTOCOL = "2025-11-25"
|
|
26
|
+
KNOWN_PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
27
|
+
CALL_TIMEOUT = 120
|
|
28
|
+
|
|
29
|
+
_SESSION_ID = {"type": "string", "description": "The session_id an earlier preview or use returned in this conversation."}
|
|
30
|
+
_DOMAINS = {"type": "array", "items": {"type": "string"},
|
|
31
|
+
"description": "Only when the user names a selection; omit to use their saved installation selection."}
|
|
32
|
+
# One owner: the bundle builder reads this list for the manifest.
|
|
33
|
+
TOOLS = [
|
|
34
|
+
{"name": "status",
|
|
35
|
+
"description": "Show whether agent-bios instructions were delivered to this conversation. After reading a "
|
|
36
|
+
"delivery to its last line, call this with end_marker_seen set to that line.",
|
|
37
|
+
"inputSchema": {"type": "object", "properties": {
|
|
38
|
+
"session_id": _SESSION_ID,
|
|
39
|
+
"end_marker_seen": {"type": "string", "description": "The delivery's last line, exactly as read."}},
|
|
40
|
+
"required": ["session_id"]}},
|
|
41
|
+
{"name": "preview",
|
|
42
|
+
"description": "Describe the agent-bios work environment use would return, without delivering it. "
|
|
43
|
+
"Call only when the user asks for their agent-bios instructions or environment.",
|
|
44
|
+
"inputSchema": {"type": "object", "properties": {"session_id": _SESSION_ID, "domains": _DOMAINS}}},
|
|
45
|
+
{"name": "use",
|
|
46
|
+
"description": "Return the user's selected agent-bios work environment as context for this conversation. "
|
|
47
|
+
"Call only when the user asks for it.",
|
|
48
|
+
"inputSchema": {"type": "object", "properties": {
|
|
49
|
+
"session_id": _SESSION_ID, "domains": _DOMAINS,
|
|
50
|
+
"expected_content_ref": {"type": "string", "description": "The content_ref preview returned, to refuse a changed snapshot."}}}},
|
|
51
|
+
{"name": "off",
|
|
52
|
+
"description": "Stop agent-bios delivery in this conversation. Text already returned stays in context.",
|
|
53
|
+
"inputSchema": {"type": "object", "properties": {"session_id": _SESSION_ID}, "required": ["session_id"]}},
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ToolError(RuntimeError):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _config() -> dict[str, Any]:
|
|
62
|
+
config = json.loads((HERE / "desktop.json").read_text(encoding="utf-8"))
|
|
63
|
+
if config.get("schema_version") != 1:
|
|
64
|
+
raise ToolError("this agent-bios Desktop bundle has an unsupported configuration; generate it again with agent-bios app desktop")
|
|
65
|
+
for key in ("home", "state_root", "user_root"):
|
|
66
|
+
if not isinstance(config.get(key), str) or not Path(config[key]).is_absolute():
|
|
67
|
+
raise ToolError("this agent-bios Desktop bundle needs absolute private roots")
|
|
68
|
+
return config
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _string(arguments: dict[str, Any], key: str) -> str | None:
|
|
72
|
+
value = arguments.get(key)
|
|
73
|
+
if value is None:
|
|
74
|
+
return None
|
|
75
|
+
if not isinstance(value, str) or not value.strip():
|
|
76
|
+
raise ToolError(f"{key} must be a nonempty string")
|
|
77
|
+
return value.strip()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _argv(operation: str, arguments: dict[str, Any]) -> list[str]:
|
|
81
|
+
tail = ["--host", "claude-desktop"]
|
|
82
|
+
session = _string(arguments, "session_id")
|
|
83
|
+
if session is not None:
|
|
84
|
+
tail += ["--session", session]
|
|
85
|
+
if operation in {"preview", "use"} and arguments.get("domains") is not None:
|
|
86
|
+
domains = arguments["domains"]
|
|
87
|
+
if not isinstance(domains, list) or not domains or not all(isinstance(v, str) and v.strip() for v in domains):
|
|
88
|
+
raise ToolError("domains must be a nonempty list of selection names")
|
|
89
|
+
tail += ["--domains", ",".join(v.strip() for v in domains)]
|
|
90
|
+
if operation == "use" and (ref := _string(arguments, "expected_content_ref")) is not None:
|
|
91
|
+
tail += ["--expected-content-ref", ref]
|
|
92
|
+
if operation == "status" and (marker := _string(arguments, "end_marker_seen")) is not None:
|
|
93
|
+
tail += ["--end-marker-seen", marker]
|
|
94
|
+
return tail
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def run_session(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
98
|
+
config = _config()
|
|
99
|
+
sys.dont_write_bytecode = True
|
|
100
|
+
sys.path.insert(0, str(HERE))
|
|
101
|
+
from host_platform import python_argv, runtime_environment
|
|
102
|
+
from instructions_transaction import confirmed_release, guard_pending, reject_symlink_ancestors
|
|
103
|
+
state = Path(config["state_root"])
|
|
104
|
+
reject_symlink_ancestors(state)
|
|
105
|
+
reject_symlink_ancestors(Path(config["user_root"]))
|
|
106
|
+
guard_pending(state)
|
|
107
|
+
release = confirmed_release(state)
|
|
108
|
+
reject_symlink_ancestors(release)
|
|
109
|
+
env = dict(os.environ)
|
|
110
|
+
env.update({"HOME": config["home"], "AGENT_BIOS_STATE_DIR": config["state_root"],
|
|
111
|
+
"AGENT_BIOS_INSTRUCTIONS_DIR": config["user_root"], "AGENT_BIOS_CORPUS_DIR": config["user_root"],
|
|
112
|
+
"AGENT_BIOS_PACKAGE_ROOT": str(release), "AGENT_BIOS_PRIVATE_INSTRUCTIONS": "1",
|
|
113
|
+
"AGENT_BIOS_PRIVATE_CORPUS": "1", "AGENT_BIOS_LEGACY_INSTALL": "0",
|
|
114
|
+
"PYTHONDONTWRITEBYTECODE": "1"})
|
|
115
|
+
if "python_binding" in config:
|
|
116
|
+
if not isinstance(config["python_binding"], dict):
|
|
117
|
+
raise ToolError("the bundle's Python binding must be an object")
|
|
118
|
+
env.update(runtime_environment(config["python_binding"]))
|
|
119
|
+
manager = release / "compose/instructions_app.py"
|
|
120
|
+
argv = python_argv(manager, "--repo", str(release), "--state-dir", config["state_root"],
|
|
121
|
+
"--user-dir", config["user_root"], "--json", "session", operation,
|
|
122
|
+
*_argv(operation, arguments), environ=env)
|
|
123
|
+
try:
|
|
124
|
+
done = subprocess.run(argv, env=env, stdin=subprocess.DEVNULL, capture_output=True,
|
|
125
|
+
text=True, encoding="utf-8", timeout=CALL_TIMEOUT)
|
|
126
|
+
except subprocess.TimeoutExpired as exc:
|
|
127
|
+
raise ToolError(f"agent-bios did not answer within {CALL_TIMEOUT} seconds") from exc
|
|
128
|
+
if done.returncode != 0:
|
|
129
|
+
raise ToolError(done.stderr.strip() or f"agent-bios session {operation} failed")
|
|
130
|
+
try:
|
|
131
|
+
return json.loads(done.stdout)
|
|
132
|
+
except ValueError as exc:
|
|
133
|
+
raise ToolError("agent-bios returned an unreadable session result") from exc
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _scope(result: dict[str, Any]) -> str:
|
|
137
|
+
return ("Project scope: none. Desktop names no project, so project-scoped imported "
|
|
138
|
+
"instructions are not included.") if result.get("project_scope") == "none" else ""
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _size_note(result: dict[str, Any]) -> str:
|
|
142
|
+
if not result.get("host_may_save_to_file"):
|
|
143
|
+
return ""
|
|
144
|
+
return (f"{result['instruction_bytes']} bytes is above the smallest limit Desktop has kept inline; "
|
|
145
|
+
"Desktop may save this result to a file instead of showing it.")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _unavailable(result: dict[str, Any]) -> str:
|
|
149
|
+
items = result.get("unavailable") or []
|
|
150
|
+
names = [f"{item.get('ref')} ({item.get('reason')})" if isinstance(item, dict) else str(item) for item in items]
|
|
151
|
+
return "Not included: " + "; ".join(names) if names else ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def render(operation: str, result: dict[str, Any]) -> str:
|
|
155
|
+
session = result.get("session_id")
|
|
156
|
+
if operation == "use" and isinstance(result.get("instruction_text"), str):
|
|
157
|
+
lines = [f"agent-bios session_id: {session} — pass it to status, off and use in this conversation.",
|
|
158
|
+
f"content_ref: {result['content_ref']}", _scope(result), _size_note(result)]
|
|
159
|
+
if result.get("repeat"):
|
|
160
|
+
lines.append("Same snapshot as this conversation's latest delivery; returned again with its existing receipt.")
|
|
161
|
+
lines.append(_unavailable(result))
|
|
162
|
+
lines.append("The text below ends with a line beginning 'agent-bios end'. After reading to it, "
|
|
163
|
+
"call status with that whole line as end_marker_seen.")
|
|
164
|
+
header = "\n".join(line for line in lines if line)
|
|
165
|
+
return f"{header}\n\n{result['instruction_text'].rstrip()}\n\n{result['end_marker']}"
|
|
166
|
+
if operation == "preview":
|
|
167
|
+
if result.get("selection_mode") == "none":
|
|
168
|
+
return f"agent-bios session_id: {session}\nNo instructions are selected; use would return nothing."
|
|
169
|
+
lines = [f"agent-bios session_id: {session} — pass it to use, status and off in this conversation.",
|
|
170
|
+
f"content_ref: {result['content_ref']}",
|
|
171
|
+
f"Size: {result.get('instruction_characters')} characters, {result.get('instruction_bytes')} bytes.",
|
|
172
|
+
_scope(result), _size_note(result),
|
|
173
|
+
_unavailable(result),
|
|
174
|
+
"Nothing was delivered. Call use to return this text."]
|
|
175
|
+
return "\n".join(line for line in lines if line)
|
|
176
|
+
lines = [f"agent-bios session_id: {session}",
|
|
177
|
+
f"Delivery: {'on' if result.get('enabled') else 'off'}; "
|
|
178
|
+
f"deliveries recorded: {len(result.get('deliveries', []))}.",
|
|
179
|
+
f"Latest delivery read to its end: {'yes' if result.get('latest_end_confirmed') else 'no'}."
|
|
180
|
+
if result.get("ever_delivered") else "",
|
|
181
|
+
result.get("message", "")]
|
|
182
|
+
return "\n".join(line for line in lines if line)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def call_tool(params: dict[str, Any]) -> dict[str, Any]:
|
|
186
|
+
name = params.get("name")
|
|
187
|
+
arguments = params.get("arguments") or {}
|
|
188
|
+
if name not in {tool["name"] for tool in TOOLS}:
|
|
189
|
+
return {"content": [{"type": "text", "text": f"unknown tool: {name}"}], "isError": True}
|
|
190
|
+
if not isinstance(arguments, dict):
|
|
191
|
+
return {"content": [{"type": "text", "text": "arguments must be an object"}], "isError": True}
|
|
192
|
+
try:
|
|
193
|
+
text = render(name, run_session(name, arguments))
|
|
194
|
+
return {"content": [{"type": "text", "text": text}], "isError": False}
|
|
195
|
+
except (ToolError, OSError, RuntimeError, ValueError, KeyError) as exc:
|
|
196
|
+
return {"content": [{"type": "text", "text": f"agent-bios: {exc}"}], "isError": True}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def respond(message: Any) -> dict[str, Any] | None:
|
|
200
|
+
if not isinstance(message, dict):
|
|
201
|
+
return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "expected one JSON-RPC request object"}}
|
|
202
|
+
method, ident = message.get("method"), message.get("id")
|
|
203
|
+
params = message.get("params") if isinstance(message.get("params"), dict) else {}
|
|
204
|
+
if method == "initialize":
|
|
205
|
+
asked = params.get("protocolVersion")
|
|
206
|
+
result: dict[str, Any] = {"protocolVersion": asked if asked in KNOWN_PROTOCOLS else PROTOCOL,
|
|
207
|
+
"capabilities": {"tools": {}},
|
|
208
|
+
"serverInfo": {"name": "agent-bios", "version": _version()}}
|
|
209
|
+
elif method == "ping":
|
|
210
|
+
result = {}
|
|
211
|
+
elif method == "tools/list":
|
|
212
|
+
result = {"tools": TOOLS}
|
|
213
|
+
elif method == "tools/call":
|
|
214
|
+
result = call_tool(params)
|
|
215
|
+
elif ident is None:
|
|
216
|
+
return None
|
|
217
|
+
else:
|
|
218
|
+
return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32601, "message": f"method not supported: {method}"}}
|
|
219
|
+
return None if ident is None else {"jsonrpc": "2.0", "id": ident, "result": result}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _version() -> str:
|
|
223
|
+
try:
|
|
224
|
+
return str(json.loads((HERE.parent / "manifest.json").read_text(encoding="utf-8"))["version"])
|
|
225
|
+
except (OSError, ValueError, KeyError):
|
|
226
|
+
return "unknown"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def main() -> int:
|
|
230
|
+
for stream in (sys.stdin, sys.stdout):
|
|
231
|
+
if hasattr(stream, "reconfigure"):
|
|
232
|
+
stream.reconfigure(encoding="utf-8")
|
|
233
|
+
for line in sys.stdin:
|
|
234
|
+
if not line.strip():
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
message = json.loads(line)
|
|
238
|
+
except ValueError:
|
|
239
|
+
reply: dict[str, Any] | None = {"jsonrpc": "2.0", "id": None,
|
|
240
|
+
"error": {"code": -32700, "message": "parse error"}}
|
|
241
|
+
else:
|
|
242
|
+
reply = respond(message)
|
|
243
|
+
if reply is not None:
|
|
244
|
+
sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
|
|
245
|
+
sys.stdout.flush()
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
if __name__ == "__main__":
|
|
250
|
+
raise SystemExit(main())
|
package/compose/domains.json
CHANGED
|
@@ -108,6 +108,7 @@
|
|
|
108
108
|
"slide-writing.md": {"tier": "domain", "domains": ["office-work", "visualization-docs"], "item_id": "skill-slide-writing"},
|
|
109
109
|
"verification-discipline.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-verification-discipline"},
|
|
110
110
|
"tooling-gotchas.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-tooling-gotchas"},
|
|
111
|
+
"ui-design.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-ui-design"},
|
|
111
112
|
"korean-writing.md": {"tier": "core", "domains": [], "item_id": "korean-writing"}
|
|
112
113
|
},
|
|
113
114
|
"hooks": {
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Small OS boundary shared by the native entrypoint, installer and launcher."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import errno
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
WINDOWS = os.name == 'nt'
|
|
11
|
+
|
|
12
|
+
if not WINDOWS:
|
|
13
|
+
import fcntl as file_locks
|
|
14
|
+
else:
|
|
15
|
+
import msvcrt
|
|
16
|
+
|
|
17
|
+
class file_locks:
|
|
18
|
+
LOCK_EX, LOCK_NB, LOCK_UN = 2, 4, 8
|
|
19
|
+
|
|
20
|
+
@staticmethod
|
|
21
|
+
def flock(file, operation):
|
|
22
|
+
fd = file if isinstance(file, int) else file.fileno()
|
|
23
|
+
position = os.lseek(fd, 0, os.SEEK_CUR)
|
|
24
|
+
try:
|
|
25
|
+
while True:
|
|
26
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
27
|
+
try:
|
|
28
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK if operation & 8 else msvcrt.LK_NBLCK, 1)
|
|
29
|
+
return
|
|
30
|
+
except OSError as exc:
|
|
31
|
+
if operation & 8 or exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
|
32
|
+
raise
|
|
33
|
+
if operation & 4:
|
|
34
|
+
raise BlockingIOError(exc.errno, str(exc)) from exc
|
|
35
|
+
time.sleep(.05)
|
|
36
|
+
finally:
|
|
37
|
+
os.lseek(fd, position, os.SEEK_SET)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cli_argv(root: Path, *args: str) -> list[str]:
|
|
41
|
+
if WINDOWS:
|
|
42
|
+
return python_argv(root / 'compose/native_cli.py', *args)
|
|
43
|
+
return ['/bin/bash', str(root / 'install.sh'), *args]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def runtime_environment(environ=None) -> dict[str, str]:
|
|
47
|
+
env = os.environ if environ is None else environ
|
|
48
|
+
entry, deps = env.get('AGENT_BIOS_PYTHON_ENTRY'), env.get('AGENT_BIOS_PYTHON_DEPS')
|
|
49
|
+
if bool(entry) != bool(deps):
|
|
50
|
+
raise RuntimeError('application Python entry and dependencies must be bound together')
|
|
51
|
+
if not entry:
|
|
52
|
+
return {}
|
|
53
|
+
if not Path(entry).is_absolute() or not Path(entry).is_file() or not Path(deps).is_absolute() or not Path(deps).is_dir():
|
|
54
|
+
raise RuntimeError('application Python binding is unavailable; repair the script installation')
|
|
55
|
+
executable = env.get('AGENT_BIOS_PYTHON_EXECUTABLE', sys.executable)
|
|
56
|
+
if not Path(executable).is_absolute() or not Path(executable).is_file():
|
|
57
|
+
raise RuntimeError('bound Python interpreter is unavailable')
|
|
58
|
+
return {'AGENT_BIOS_PYTHON_ENTRY': str(entry), 'AGENT_BIOS_PYTHON_DEPS': str(deps), 'AGENT_BIOS_PYTHON_EXECUTABLE': str(executable)}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def python_argv(script: Path, *args: str, interpreter=None, environ=None) -> list[str]:
|
|
62
|
+
binding = runtime_environment(environ)
|
|
63
|
+
executable = str(interpreter or binding.get("AGENT_BIOS_PYTHON_EXECUTABLE") or sys.executable)
|
|
64
|
+
if binding:
|
|
65
|
+
return [executable, '-I', '-X', 'utf8', binding['AGENT_BIOS_PYTHON_ENTRY'],
|
|
66
|
+
'--dependencies', binding['AGENT_BIOS_PYTHON_DEPS'], '--script', str(script), *args]
|
|
67
|
+
return [executable, str(script), *args]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def sync_directory(path: Path) -> None:
|
|
71
|
+
# Windows CRT cannot open directory descriptors. File bytes are flushed by
|
|
72
|
+
# the writer; replace/restart tests establish process recovery, not power-loss durability.
|
|
73
|
+
if WINDOWS:
|
|
74
|
+
return
|
|
75
|
+
fd = os.open(path, os.O_RDONLY)
|
|
76
|
+
try:
|
|
77
|
+
os.fsync(fd)
|
|
78
|
+
finally:
|
|
79
|
+
os.close(fd)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def redirected(path: Path) -> bool:
|
|
83
|
+
return path.is_symlink() or (hasattr(path, 'is_junction') and path.is_junction())
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def create_junction(link: Path, target: Path) -> None:
|
|
87
|
+
"""Create a directory junction without shell expansion or symlink privileges."""
|
|
88
|
+
if not WINDOWS:
|
|
89
|
+
raise OSError('junction creation is Windows-only')
|
|
90
|
+
import ctypes
|
|
91
|
+
from ctypes import wintypes
|
|
92
|
+
import struct
|
|
93
|
+
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
94
|
+
kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
|
95
|
+
kernel.CreateFileW.restype = wintypes.HANDLE
|
|
96
|
+
kernel.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
|
|
97
|
+
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
98
|
+
target = target.resolve(strict=True)
|
|
99
|
+
substitute = ('\\??\\' + str(target)).encode('utf-16-le')
|
|
100
|
+
display = str(target).encode('utf-16-le')
|
|
101
|
+
names = substitute + b'\0\0' + display + b'\0\0'
|
|
102
|
+
payload = struct.pack('<HHHH', 0, len(substitute), len(substitute)+2, len(display)) + names
|
|
103
|
+
data = struct.pack('<IHH', 0xA0000003, len(payload), 0) + payload
|
|
104
|
+
link.mkdir()
|
|
105
|
+
handle = kernel.CreateFileW(str(link), 0x40000000, 0, None, 3, 0x02200000, None)
|
|
106
|
+
try:
|
|
107
|
+
if handle == ctypes.c_void_p(-1).value:
|
|
108
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
109
|
+
returned = wintypes.DWORD()
|
|
110
|
+
buffer = ctypes.create_string_buffer(data)
|
|
111
|
+
if not kernel.DeviceIoControl(handle, 0x000900A4, buffer, len(data), None, 0, ctypes.byref(returned), None):
|
|
112
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
113
|
+
except BaseException:
|
|
114
|
+
if handle != ctypes.c_void_p(-1).value:
|
|
115
|
+
kernel.CloseHandle(handle)
|
|
116
|
+
handle = ctypes.c_void_p(-1).value
|
|
117
|
+
link.rmdir()
|
|
118
|
+
raise
|
|
119
|
+
finally:
|
|
120
|
+
if handle != ctypes.c_void_p(-1).value:
|
|
121
|
+
kernel.CloseHandle(handle)
|
|
@@ -21,7 +21,10 @@ import datetime
|
|
|
21
21
|
import io
|
|
22
22
|
import json
|
|
23
23
|
import contextlib
|
|
24
|
-
|
|
24
|
+
try:
|
|
25
|
+
from host_platform import file_locks as fcntl
|
|
26
|
+
except ImportError:
|
|
27
|
+
from .host_platform import file_locks as fcntl
|
|
25
28
|
import os
|
|
26
29
|
import pathlib
|
|
27
30
|
import shutil
|
|
@@ -561,7 +564,7 @@ def _flock(lock_path: pathlib.Path):
|
|
|
561
564
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
562
565
|
# O_NOFOLLOW and no truncation: a "w" open follows a planted symlink and
|
|
563
566
|
# truncates its target merely by running the command.
|
|
564
|
-
fd = os.open(str(lock_path), os.O_CREAT | os.O_WRONLY | os
|
|
567
|
+
fd = os.open(str(lock_path), os.O_CREAT | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
|
565
568
|
with os.fdopen(fd, "w") as handle:
|
|
566
569
|
fcntl.flock(handle, fcntl.LOCK_EX)
|
|
567
570
|
yield
|