one-setup-all-agents 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.
Files changed (49) hide show
  1. one_setup_all_agents/__init__.py +19 -0
  2. one_setup_all_agents/__main__.py +8 -0
  3. one_setup_all_agents/_core/__init__.py +4 -0
  4. one_setup_all_agents/_core/fsutil.py +21 -0
  5. one_setup_all_agents/_core/jsonc.py +76 -0
  6. one_setup_all_agents/_core/jsonc_edit.py +218 -0
  7. one_setup_all_agents/_core/mask.py +98 -0
  8. one_setup_all_agents/_core/runner.py +240 -0
  9. one_setup_all_agents/_core/toml_edit.py +277 -0
  10. one_setup_all_agents/adapters/__init__.py +37 -0
  11. one_setup_all_agents/adapters/_common.py +316 -0
  12. one_setup_all_agents/adapters/antigravity.py +949 -0
  13. one_setup_all_agents/adapters/base.py +216 -0
  14. one_setup_all_agents/adapters/claude_code.py +809 -0
  15. one_setup_all_agents/adapters/codex.py +775 -0
  16. one_setup_all_agents/adapters/opencode.py +661 -0
  17. one_setup_all_agents/cli.py +198 -0
  18. one_setup_all_agents/commands/__init__.py +5 -0
  19. one_setup_all_agents/commands/init.py +322 -0
  20. one_setup_all_agents/commands/status.py +286 -0
  21. one_setup_all_agents/commands/sync.py +150 -0
  22. one_setup_all_agents/commands/undo.py +121 -0
  23. one_setup_all_agents/config_source.py +698 -0
  24. one_setup_all_agents/context.py +41 -0
  25. one_setup_all_agents/detect.py +266 -0
  26. one_setup_all_agents/engine/__init__.py +20 -0
  27. one_setup_all_agents/engine/apply.py +448 -0
  28. one_setup_all_agents/engine/atomic.py +144 -0
  29. one_setup_all_agents/engine/backup.py +190 -0
  30. one_setup_all_agents/engine/errors.py +86 -0
  31. one_setup_all_agents/engine/fsops.py +361 -0
  32. one_setup_all_agents/engine/journal.py +520 -0
  33. one_setup_all_agents/engine/links.py +116 -0
  34. one_setup_all_agents/engine/lock.py +129 -0
  35. one_setup_all_agents/engine/plan.py +367 -0
  36. one_setup_all_agents/engine/revert.py +242 -0
  37. one_setup_all_agents/engine/runcli.py +52 -0
  38. one_setup_all_agents/engine/undo.py +205 -0
  39. one_setup_all_agents/importer.py +737 -0
  40. one_setup_all_agents/model.py +361 -0
  41. one_setup_all_agents/paths.py +82 -0
  42. one_setup_all_agents/reader.py +104 -0
  43. one_setup_all_agents/snapshot.py +70 -0
  44. one_setup_all_agents/ui.py +61 -0
  45. one_setup_all_agents-0.1.0.dist-info/METADATA +204 -0
  46. one_setup_all_agents-0.1.0.dist-info/RECORD +49 -0
  47. one_setup_all_agents-0.1.0.dist-info/WHEEL +4 -0
  48. one_setup_all_agents-0.1.0.dist-info/entry_points.txt +3 -0
  49. one_setup_all_agents-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,19 @@
1
+ """one-setup-all-agents: one setup for all your AI coding agents.
2
+
3
+ A shared agent config for every supported tool (the registry in `adapters/` lists them).
4
+ Write your config once, every agent gets the same setup, and any change can be
5
+ undone with one command.
6
+
7
+ Status: pre-alpha. The four public commands (`init`, `sync`, `status`, `undo`) are implemented.
8
+
9
+
10
+ Layout:
11
+ cli.py command-line entry point (`all-agents init|sync|status|undo`)
12
+ model.py shared data types: Env, Scope, Detection, Paths, Op kinds
13
+ paths.py where the user's source config and the engine state live, per OS
14
+ _core/ internal helpers (JSONC/TOML formatting, secret masking, runner)
15
+ engine/ the only code that writes: plan, apply, backup, journal, undo
16
+ adapters/ one module per tool; adapters detect, read and plan, never write
17
+ """
18
+
19
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ """Allow `python -m one_setup_all_agents`."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,4 @@
1
+ """Transitional core ported from the prototype this project grew out of (Phase 1).
2
+
3
+ Phase 3 restructures it into the engine and the adapters (docs/decisions/0008). Until then it keeps working as it is.
4
+ """
@@ -0,0 +1,21 @@
1
+ """Small file-system helpers that must behave the same on Python 3.11 to 3.13 and on every OS."""
2
+
3
+ import os
4
+ import stat
5
+
6
+
7
+ def is_junction(path):
8
+ """True for a Windows directory junction. Always False elsewhere.
9
+
10
+ `os.path.isjunction` exists only from Python 3.12; the minimum supported version is 3.11 (ADR 0004), so older
11
+ interpreters read the reparse tag themselves."""
12
+ isj = getattr(os.path, "isjunction", None)
13
+ if isj is not None:
14
+ return bool(isj(str(path)))
15
+ if os.name != "nt":
16
+ return False
17
+ try:
18
+ st = os.lstat(str(path))
19
+ except OSError:
20
+ return False
21
+ return getattr(st, "st_reparse_tag", 0) == stat.IO_REPARSE_TAG_MOUNT_POINT
@@ -0,0 +1,76 @@
1
+ """Minimal JSONC reader: strips // and /* */ comments and trailing commas (string-aware), then json.loads.
2
+
3
+ Error messages carry line/column only, never file content.
4
+ """
5
+
6
+ import json
7
+
8
+
9
+ def strip_jsonc(text):
10
+ """Return `text` with comments and trailing commas removed. Strings are left untouched."""
11
+ out = []
12
+ i, n = 0, len(text)
13
+ while i < n:
14
+ c = text[i]
15
+ if c == '"': # copy a whole string literal, honouring escapes
16
+ j = i + 1
17
+ while j < n:
18
+ if text[j] == "\\":
19
+ j += 2
20
+ continue
21
+ if text[j] == '"':
22
+ break
23
+ j += 1
24
+ out.append(text[i : j + 1])
25
+ i = j + 1
26
+ elif c == "/" and i + 1 < n and text[i + 1] == "/":
27
+ while i < n and text[i] not in "\r\n":
28
+ i += 1
29
+ elif c == "/" and i + 1 < n and text[i + 1] == "*":
30
+ end = text.find("*/", i + 2)
31
+ if end == -1:
32
+ raise ValueError("unterminated /* comment")
33
+ # keep newlines so that json error line numbers still point at the original file
34
+ out.append("\n" * text.count("\n", i, end))
35
+ i = end + 2
36
+ else:
37
+ out.append(c)
38
+ i += 1
39
+ return _drop_trailing_commas("".join(out))
40
+
41
+
42
+ def _drop_trailing_commas(text):
43
+ out = []
44
+ i, n = 0, len(text)
45
+ while i < n:
46
+ c = text[i]
47
+ if c == '"':
48
+ j = i + 1
49
+ while j < n:
50
+ if text[j] == "\\":
51
+ j += 2
52
+ continue
53
+ if text[j] == '"':
54
+ break
55
+ j += 1
56
+ out.append(text[i : j + 1])
57
+ i = j + 1
58
+ elif c == ",":
59
+ j = i + 1
60
+ while j < n and text[j] in " \t\r\n":
61
+ j += 1
62
+ if j < n and text[j] in "}]":
63
+ i += 1 # drop the comma, keep the whitespace that follows
64
+ else:
65
+ out.append(c)
66
+ i += 1
67
+ else:
68
+ out.append(c)
69
+ i += 1
70
+ return "".join(out)
71
+
72
+
73
+ def loads(text):
74
+ if text.startswith("\ufeff"):
75
+ text = text[1:]
76
+ return json.loads(strip_jsonc(text))
@@ -0,0 +1,218 @@
1
+ """Surgical edits of one JSONC object (the `mcp.servers` block): remove, replace or add members and leave every
2
+ other byte, including the comments, exactly as it was.
3
+
4
+ Works on text with "\\n" line endings (the caller converts CRLF).
5
+ """
6
+
7
+ import json
8
+
9
+
10
+ class EditError(Exception):
11
+ pass
12
+
13
+
14
+ def _skip_string(text, i):
15
+ j = i + 1
16
+ while j < len(text):
17
+ if text[j] == "\\":
18
+ j += 2
19
+ continue
20
+ if text[j] == '"':
21
+ return j + 1
22
+ j += 1
23
+ raise EditError("unterminated string")
24
+
25
+
26
+ def _skip_ws_comments(text, i):
27
+ n = len(text)
28
+ while i < n:
29
+ c = text[i]
30
+ if c in " \t\r\n":
31
+ i += 1
32
+ elif text.startswith("//", i):
33
+ while i < n and text[i] != "\n":
34
+ i += 1
35
+ elif text.startswith("/*", i):
36
+ end = text.find("*/", i + 2)
37
+ if end == -1:
38
+ raise EditError("unterminated block comment")
39
+ i = end + 2
40
+ else:
41
+ break
42
+ return i
43
+
44
+
45
+ def _skip_value(text, i):
46
+ """Index just after the JSON value that starts at i."""
47
+ c = text[i]
48
+ if c == '"':
49
+ return _skip_string(text, i)
50
+ if c in "{[":
51
+ depth = 0
52
+ while i < len(text):
53
+ c = text[i]
54
+ if c == '"':
55
+ i = _skip_string(text, i)
56
+ continue
57
+ if text.startswith("//", i) or text.startswith("/*", i):
58
+ i = _skip_ws_comments(text, i)
59
+ continue
60
+ if c in "{[":
61
+ depth += 1
62
+ elif c in "}]":
63
+ depth -= 1
64
+ if depth == 0:
65
+ return i + 1
66
+ i += 1
67
+ raise EditError("unbalanced brackets")
68
+ while i < len(text) and text[i] not in ",}] \t\r\n/":
69
+ i += 1
70
+ return i
71
+
72
+
73
+ class Member:
74
+ def __init__(self, key, lead_start, key_start, value_start, value_end, comma, end):
75
+ self.key, self.lead_start, self.key_start = key, lead_start, key_start
76
+ self.value_start, self.value_end, self.comma, self.end = value_start, value_end, comma, end
77
+
78
+
79
+ def members_of(text, open_idx):
80
+ """(members, close_idx) of the object whose '{' is at open_idx."""
81
+ if text[open_idx] != "{":
82
+ raise EditError("expected '{'")
83
+ out = []
84
+ i = open_idx + 1
85
+ prev_end = i
86
+ while True:
87
+ j = _skip_ws_comments(text, i)
88
+ if j >= len(text):
89
+ raise EditError("unterminated object")
90
+ if text[j] == "}":
91
+ return out, j
92
+ if text[j] != '"':
93
+ raise EditError(f"expected a key at offset {j}")
94
+ key_end = _skip_string(text, j)
95
+ key = json.loads(text[j:key_end])
96
+ k = _skip_ws_comments(text, key_end)
97
+ if text[k] != ":":
98
+ raise EditError("expected ':'")
99
+ v = _skip_ws_comments(text, k + 1)
100
+ v_end = _skip_value(text, v)
101
+ after = _skip_ws_comments(text, v_end)
102
+ comma = after if after < len(text) and text[after] == "," else None
103
+ member_end = (comma + 1) if comma is not None else v_end
104
+ # the rest of the line (a trailing // comment) belongs to this member
105
+ nl = text.find("\n", member_end)
106
+ tail = text[member_end : nl if nl != -1 else len(text)]
107
+ if (
108
+ tail.strip() == ""
109
+ or tail.lstrip().startswith("//")
110
+ or (
111
+ tail.lstrip().startswith("/*")
112
+ and "*/" in tail
113
+ and tail[tail.index("*/") + 2 :].strip() == ""
114
+ )
115
+ ):
116
+ member_end = (nl + 1) if nl != -1 else len(text)
117
+ region = text[prev_end:j]
118
+ nl_in = region.find("\n")
119
+ lead_start = prev_end + nl_in + 1 if nl_in != -1 else prev_end
120
+ out.append(Member(key, lead_start, j, v, v_end, comma, member_end))
121
+ i = comma + 1 if comma is not None else v_end
122
+ prev_end = i
123
+
124
+
125
+ def find_object(text, path):
126
+ """Index of the '{' of the object at `path` (list of keys) from the root object."""
127
+ i = _skip_ws_comments(text, 0)
128
+ if i >= len(text) or text[i] != "{":
129
+ raise EditError("root is not an object")
130
+ for key in path:
131
+ members, _ = members_of(text, i)
132
+ hit = [m for m in members if m.key == key]
133
+ if not hit:
134
+ raise EditError(f"key '{key}' not found")
135
+ i = hit[0].value_start
136
+ if text[i] != "{":
137
+ raise EditError(f"'{key}' is not an object")
138
+ return i
139
+
140
+
141
+ def _indent_of(text, idx):
142
+ ls = text.rfind("\n", 0, idx) + 1
143
+ return text[ls:idx] if text[ls:idx].strip() == "" else ""
144
+
145
+
146
+ def render_member(key, value, indent, comment=None, comma=True):
147
+ body = json.dumps(value, indent=2, ensure_ascii=False).replace("\n", "\n" + indent)
148
+ lines = []
149
+ if comment:
150
+ for c in str(comment).splitlines():
151
+ lines.append(f"{indent}// {c}")
152
+ lines.append(f"{indent}{json.dumps(key, ensure_ascii=False)}: {body}" + ("," if comma else ""))
153
+ return "\n".join(lines) + "\n"
154
+
155
+
156
+ def edit_object(text, path, removes=(), replaces=None, adds=None):
157
+ """Apply edits to the object at `path`. replaces: {key: value}; adds: [(key, value, comment)] appended at the end."""
158
+ replaces = replaces or {}
159
+ adds = adds or []
160
+ open_idx = find_object(text, path)
161
+ members, close_idx = members_of(text, open_idx)
162
+ by_key = {m.key: m for m in members}
163
+ for k in list(removes) + list(replaces):
164
+ if k not in by_key:
165
+ raise EditError(f"member '{k}' not found")
166
+ edits = [] # (start, end, new_text), applied from the end backwards
167
+ for k, value in replaces.items():
168
+ m = by_key[k]
169
+ indent = _indent_of(text, m.key_start)
170
+ body = json.dumps(value, indent=2, ensure_ascii=False).replace("\n", "\n" + indent)
171
+ edits.append((m.value_start, m.value_end, body))
172
+ for k in removes:
173
+ m = by_key[k]
174
+ edits.append((m.lead_start, m.end, ""))
175
+ remaining = [m for m in members if m.key not in removes]
176
+ # removing the last member that had no comma: drop the comma of the new last member (keeps strict JSON)
177
+ if (
178
+ removes
179
+ and not adds
180
+ and remaining
181
+ and members[-1].key in removes
182
+ and members[-1].comma is None
183
+ and remaining[-1].comma is not None
184
+ ):
185
+ c = remaining[-1].comma
186
+ edits.append((c, c + 1, ""))
187
+ if adds:
188
+ indent = (
189
+ _indent_of(text, members[0].key_start)
190
+ if members
191
+ else _indent_of(text, close_idx) + " "
192
+ )
193
+ trailing_style = bool(
194
+ members and members[-1].comma is not None
195
+ ) # keep the file's style for the last member
196
+ close_line_start = text.rfind("\n", 0, close_idx) + 1
197
+ before_close = text[close_line_start:close_idx]
198
+ if before_close.strip() == "":
199
+ ins_at, prefix = close_line_start, ""
200
+ else:
201
+ ins_at, prefix = close_idx, "\n"
202
+ pieces = []
203
+ if remaining and remaining[-1].comma is None and remaining[-1].key not in removes:
204
+ c_at = remaining[-1].value_end
205
+ edits.append((c_at, c_at, ","))
206
+ for n, (key, value, comment) in enumerate(adds):
207
+ last = n == len(adds) - 1
208
+ pieces.append(
209
+ render_member(key, value, indent, comment, comma=(trailing_style or not last))
210
+ )
211
+ edits.append((ins_at, ins_at, prefix + "".join(pieces)))
212
+ # a member removed and an insertion at the same offset cannot overlap; sort by start descending
213
+ edits.sort(
214
+ key=lambda e: (e[0], e[1], len(e[2])), reverse=True
215
+ ) # at one offset the longer insertion goes in first, so a comma lands before it
216
+ for start, end, new in edits:
217
+ text = text[:start] + new + text[end:]
218
+ return text
@@ -0,0 +1,98 @@
1
+ """Masking of anything secret-looking in text that all-agents prints.
2
+
3
+ The neutral model keeps env-variable and header-variable NAMES, plus non-secret literal env values
4
+ (`env_value_looks_secret` is the one check for those). This module also covers the places a literal
5
+ secret can hide: `command`, `args` and `url`.
6
+ Env references (${VAR}, {env:VAR}, {{VAR}}, {{$VAR}}, $VAR, %VAR%) are names, not secrets, and are kept.
7
+ """
8
+
9
+ import re
10
+
11
+ MASK = "***"
12
+
13
+ _REF_AHEAD = r"(?!\$\{|\{env:|\{\{\$?[A-Za-z_]|\$[A-Za-z_]|%[A-Za-z_])"
14
+
15
+ # Known token shapes.
16
+ _TOKEN_SHAPES = re.compile(
17
+ r"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}"
18
+ r"|github_pat_[A-Za-z0-9_]{16,}"
19
+ r"|nfp_[A-Za-z0-9]{16,}"
20
+ r"|sk-[A-Za-z0-9_-]{16,}"
21
+ r"|xox[abprs]-[A-Za-z0-9-]{10,}"
22
+ r"|AIza[0-9A-Za-z_-]{20,}"
23
+ r"|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"
24
+ )
25
+ _BEARER = re.compile(r"(?i)\b(bearer|basic)(\s+)" + _REF_AHEAD + r"[^\s\"']+")
26
+ _URL_USERINFO = re.compile(r"(://[^/\s:@]+):" + _REF_AHEAD + r"[^@/\s]+@")
27
+ _NAME_VALUE = re.compile(
28
+ r"(?i)(?<![\w.-])([\w.-]*(?:token|secret|passw(?:or)?d|pwd|api[_-]?key|apikey|credential"
29
+ r"|private[_-]?key|access[_-]?key|authorization|auth[_-]?token|auth[_-]?key|signature|sig)[\w.-]*)"
30
+ r"(=)" + _REF_AHEAD + r"([^\s&;\"']+)"
31
+ )
32
+ _HEADER_VALUE = re.compile(
33
+ r"(?i)\b(authorization|x-api-key|api-key|x-auth-token)(\s*:\s*)"
34
+ + _REF_AHEAD
35
+ + r"(?!bearer\b|basic\b)[^\s\"']+"
36
+ )
37
+ _SECRET_FLAG = re.compile(
38
+ r"(?i)^--?[\w.-]*(token|secret|passw(?:or)?d|pwd|api[_-]?key|apikey|credential|private[_-]?key|access[_-]?key)[\w.-]*$"
39
+ )
40
+ _LONG_TOKEN = re.compile(r"^[A-Za-z0-9_+=.-]{32,}$")
41
+
42
+ # A variable name that suggests a secret, and a value that is only a reference to a variable.
43
+ SECRET_NAME = re.compile(
44
+ r"(?i)(token|secret|passw(or)?d|api[_-]?key|credential|private[_-]?key|access[_-]?key)"
45
+ )
46
+ ENV_REF = re.compile(
47
+ r"^(\$\{[^}]+\}|\{env:[^}]+\}|\{\{\$?[A-Za-z_]\w*\}\}|\$[A-Za-z_]\w*|%[^%]+%)$"
48
+ )
49
+
50
+
51
+ def _is_ref(value):
52
+ return bool(re.match(r"^(\$\{|\{env:|\{\{\$?[A-Za-z_]|\$[A-Za-z_]|%[A-Za-z_])", value))
53
+
54
+
55
+ def mask_text(text):
56
+ """Mask secret-looking parts of one string (a command, an argument or a URL)."""
57
+ if not isinstance(text, str):
58
+ return text
59
+ s = _TOKEN_SHAPES.sub(MASK, text)
60
+ s = _BEARER.sub(lambda m: m.group(1) + m.group(2) + MASK, s)
61
+ s = _URL_USERINFO.sub(lambda m: m.group(1) + ":" + MASK + "@", s)
62
+ s = _NAME_VALUE.sub(lambda m: m.group(1) + m.group(2) + MASK, s)
63
+ s = _HEADER_VALUE.sub(lambda m: m.group(1) + m.group(2) + MASK, s)
64
+ if _LONG_TOKEN.match(s) and re.search(r"[A-Za-z]", s) and re.search(r"\d", s):
65
+ # a whole argument that is one long opaque string (key-like); paths and URLs never match
66
+ s = MASK
67
+ return s
68
+
69
+
70
+ def env_value_looks_secret(name, value):
71
+ """True when an env entry `name=value` must not be stored as a literal.
72
+
73
+ A value that masking would change looks like a secret; so does any non-empty value of a
74
+ secret-sounding name unless it is only a reference to a variable. Used by the legacy source
75
+ and by `McpServer` so the rule exists once.
76
+ """
77
+ value = "" if value is None else str(value)
78
+ return mask_text(value) != value or bool(
79
+ SECRET_NAME.search(str(name)) and value and not ENV_REF.match(value.strip())
80
+ )
81
+
82
+
83
+ def mask_args(args):
84
+ """Mask a list of arguments; the value after a secret-looking flag (`--token abc`) is masked too."""
85
+ out = []
86
+ hide_next = False
87
+ for a in args:
88
+ a = str(a)
89
+ if hide_next and not a.startswith("-") and not _is_ref(a):
90
+ out.append(MASK)
91
+ hide_next = False
92
+ continue
93
+ hide_next = False
94
+ masked = mask_text(a)
95
+ if a.startswith("-") and "=" not in a and _SECRET_FLAG.match(a):
96
+ hide_next = True
97
+ out.append(masked)
98
+ return out
@@ -0,0 +1,240 @@
1
+ """The runner: start a command after expanding variable placeholders in its arguments.
2
+
3
+ all-agents _run [--derive NAME=template]... -- <command> [args...]
4
+
5
+ Why it exists: Codex and Antigravity do not expand ${VAR} in their own configs, and a header that carries
6
+ a secret must not be written into a config file or an argument list. The generated entry for such a
7
+ server is a small stdio bridge:
8
+
9
+ all-agents _run --derive MCP_HDR_1=Bearer{sp}{{TOKEN}} -- npx -y mcp-remote <url> --header "Authorization:{{$MCP_HDR_1}}"
10
+
11
+ * --derive NAME=template sets one more variable in the CHILD'S ENVIRONMENT only, computed from variables of
12
+ the environment (`{{VAR}}` or `${VAR}`; `{sp}` is one space, so the argument never needs a space). A variable
13
+ that is nowhere is a refusal that names it. On Windows the User environment is read too, for a variable the
14
+ process does not have.
15
+ * `{{VAR}}` / `${VAR}` in the child's arguments are replaced from that environment. `{{$VAR}}` becomes the
16
+ literal `${VAR}`, left for the child to expand itself, so the value never appears on a command line.
17
+ * stdin/stdout/stderr pass straight through to the child (MCP stdio). On Windows the child runs in a Job
18
+ Object with KILL_ON_JOB_CLOSE, so it dies with the runner. On other systems there is no equivalent and the
19
+ child may outlive the runner (unverified, see docs/decisions/0007).
20
+
21
+ Exit codes: 0..N the child's exit code, 2 refusal or bad arguments, 126 could not start, 127 command not found.
22
+ Never prints a value: only variable NAMES.
23
+ """
24
+
25
+ import os
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import sys
30
+
31
+ ENV_NAME = re.compile(
32
+ r"^[A-Z][A-Z0-9_]{0,63}$"
33
+ ) # a pasted token (lowercase, long) cannot pass as a "name"
34
+ VAR_REF = re.compile(
35
+ r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}|\{\{\$([A-Za-z_][A-Za-z0-9_]*)\}\}"
36
+ )
37
+
38
+
39
+ class RunnerError(Exception):
40
+ """A refusal or a bad argument. The message never contains a secret value."""
41
+
42
+ exit_code = 2
43
+
44
+
45
+ class CommandNotFound(RunnerError):
46
+ exit_code = 127
47
+
48
+ def __init__(self, name):
49
+ super().__init__(f"command not found on PATH: {name}")
50
+
51
+
52
+ def read_user_env(name):
53
+ """Windows User environment (HKCU\\Environment), for a variable the process env lacks. None elsewhere or if absent."""
54
+ if os.name != "nt":
55
+ return None
56
+ try:
57
+ import winreg
58
+
59
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as k:
60
+ value, _ = winreg.QueryValueEx(k, name)
61
+ return value if isinstance(value, str) and value else None
62
+ except OSError:
63
+ return None
64
+
65
+
66
+ def get_value(name, env):
67
+ v = env.get(name)
68
+ return v if v else read_user_env(name)
69
+
70
+
71
+ def expand_args(args, env):
72
+ """Replace ${NAME} and {{NAME}} using env. A missing or empty name is a refusal (naming only the variable).
73
+ {{$NAME}} becomes the literal ${NAME}, left for the child to expand from its own environment."""
74
+ out = []
75
+ for a in args:
76
+
77
+ def sub(m):
78
+ if m.group(3):
79
+ return "${" + m.group(3) + "}"
80
+ name = m.group(1) or m.group(2)
81
+ v = get_value(name, env)
82
+ if not v:
83
+ raise RunnerError(f"argument references {name} which is not set")
84
+ return v
85
+
86
+ out.append(VAR_REF.sub(sub, a))
87
+ return out
88
+
89
+
90
+ def parse_derive(specs):
91
+ """['NAME=template', ...] -> [(NAME, template)]. {{$VAR}} is not allowed in a template: a derived value is
92
+ computed now, not passed through."""
93
+ out, seen = [], set()
94
+ for spec in specs or []:
95
+ name, eq, tmpl = spec.partition("=")
96
+ if not eq or not ENV_NAME.match(name):
97
+ raise RunnerError("--derive needs NAME=template with an UPPER_CASE variable name")
98
+ if name in seen:
99
+ raise RunnerError(f"--derive {name} given twice")
100
+ if not tmpl:
101
+ raise RunnerError(f"--derive {name} has an empty template")
102
+ if any(m.group(3) for m in VAR_REF.finditer(tmpl)):
103
+ raise RunnerError(
104
+ f"--derive {name}: use {{{{VAR}}}} or ${{VAR}} (not {{{{$VAR}}}}) inside a derive template"
105
+ )
106
+ seen.add(name)
107
+ out.append((name, tmpl))
108
+ return out
109
+
110
+
111
+ def apply_derive(env, derived):
112
+ """Set each derived variable in `env` (the child's environment, never its arguments). Returns the names."""
113
+ lookup = dict(env)
114
+ names = []
115
+ for name, tmpl in derived:
116
+ value = expand_args([tmpl.replace("{sp}", " ")], lookup)[
117
+ 0
118
+ ] # {sp} first: a value is never rewritten
119
+ for k in [k for k in env if k.upper() == name and k != name]:
120
+ del env[k]
121
+ env[name] = value
122
+ names.append(name)
123
+ return names
124
+
125
+
126
+ # ---------------------------------------------------------------- Windows Job Object
127
+ _JOB_KEEPALIVE = [] # the handle must live until the runner exits
128
+
129
+
130
+ def create_kill_on_close_job():
131
+ """A Job Object with KILL_ON_JOB_CLOSE. Returns (kernel32, handle) or None (not Windows / API failure)."""
132
+ if os.name != "nt":
133
+ return None
134
+ try:
135
+ import ctypes
136
+ from ctypes import wintypes
137
+
138
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
139
+ k32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR]
140
+ k32.CreateJobObjectW.restype = wintypes.HANDLE
141
+ k32.SetInformationJobObject.argtypes = [
142
+ wintypes.HANDLE,
143
+ ctypes.c_int,
144
+ wintypes.LPVOID,
145
+ wintypes.DWORD,
146
+ ]
147
+ k32.SetInformationJobObject.restype = wintypes.BOOL
148
+ k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
149
+ k32.AssignProcessToJobObject.restype = wintypes.BOOL
150
+ k32.GetCurrentProcess.restype = wintypes.HANDLE
151
+
152
+ class BASIC(ctypes.Structure):
153
+ _fields_ = [
154
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
155
+ ("PerJobUserTimeLimit", ctypes.c_int64),
156
+ ("LimitFlags", wintypes.DWORD),
157
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
158
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
159
+ ("ActiveProcessLimit", wintypes.DWORD),
160
+ ("Affinity", ctypes.c_size_t),
161
+ ("PriorityClass", wintypes.DWORD),
162
+ ("SchedulingClass", wintypes.DWORD),
163
+ ]
164
+
165
+ class IOC(ctypes.Structure):
166
+ _fields_ = [(n, ctypes.c_uint64) for n in ("ro", "wo", "oo", "rb", "wb", "ob")]
167
+
168
+ class EXT(ctypes.Structure):
169
+ _fields_ = [
170
+ ("Basic", BASIC),
171
+ ("Io", IOC),
172
+ ("ProcessMemoryLimit", ctypes.c_size_t),
173
+ ("JobMemoryLimit", ctypes.c_size_t),
174
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
175
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
176
+ ]
177
+
178
+ job = k32.CreateJobObjectW(None, None)
179
+ if not job:
180
+ return None
181
+ info = EXT()
182
+ info.Basic.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
183
+ if not k32.SetInformationJobObject(
184
+ job, 9, ctypes.byref(info), ctypes.sizeof(info)
185
+ ): # ExtendedLimitInformation
186
+ return None
187
+ _JOB_KEEPALIVE.append(job)
188
+ return k32, job
189
+ except Exception: # noqa: BLE001 - the job is a convenience; a launch without it is still correct
190
+ return None
191
+
192
+
193
+ def run_child(argv, env, cwd=None):
194
+ """Start argv with inherited stdio inside the kill-on-close job (Windows). Returns the Popen."""
195
+ exe = shutil.which(argv[0], path=env.get("PATH") or env.get("Path"))
196
+ if not exe:
197
+ raise CommandNotFound(argv[0])
198
+ job = create_kill_on_close_job()
199
+ if job: # put the runner itself in the job: the child inherits membership with no race
200
+ k32, handle = job
201
+ k32.AssignProcessToJobObject(handle, k32.GetCurrentProcess())
202
+ return subprocess.Popen([exe, *argv[1:]], env=env, cwd=cwd)
203
+
204
+
205
+ def parse(argv):
206
+ if "--" not in argv:
207
+ raise RunnerError(
208
+ "usage: _run [--cwd DIR] [--derive NAME=template]... -- <command> [args...]"
209
+ )
210
+ i = argv.index("--")
211
+ head, cmd = argv[:i], argv[i + 1 :]
212
+ if not cmd:
213
+ raise RunnerError("no command after --")
214
+ import argparse
215
+
216
+ ap = argparse.ArgumentParser(prog="_run", add_help=False)
217
+ ap.add_argument("--cwd")
218
+ ap.add_argument("--derive", action="append", default=[])
219
+ ns, extra = ap.parse_known_args(head)
220
+ if extra:
221
+ raise RunnerError(f"unknown option(s) before --: {' '.join(extra)}")
222
+ ns.derived = parse_derive(ns.derive)
223
+ return ns, cmd
224
+
225
+
226
+ def main(argv):
227
+ try:
228
+ ns, cmd = parse(list(argv))
229
+ env = dict(os.environ)
230
+ apply_derive(env, ns.derived)
231
+ child_argv = [cmd[0], *expand_args(cmd[1:], env)]
232
+ return run_child(child_argv, env, cwd=ns.cwd).wait()
233
+ except RunnerError as e:
234
+ print(f"all-agents _run: {e}", file=sys.stderr)
235
+ return e.exit_code
236
+ except KeyboardInterrupt:
237
+ return 130
238
+ except OSError as e:
239
+ print(f"all-agents _run: could not start the command: {type(e).__name__}", file=sys.stderr)
240
+ return 126