synth-code 0.0.1__py3-none-macosx_15_0_arm64.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 (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
@@ -0,0 +1,309 @@
1
+ """Read-only side agent and Temper projection of the owner journal."""
2
+
3
+ from collections import defaultdict, deque
4
+
5
+ from .conversation import _wrapped
6
+ from .history_wire import input_text, steering_receipt, steering_request
7
+ from .slash import binding_detail, public_role
8
+
9
+ _ADVISOR = "side"
10
+
11
+
12
+ def _name(role):
13
+ return public_role(role.casefold()) if role.casefold() in {"core", "side", "owner"} else role
14
+
15
+
16
+ def _event_ref(sequence):
17
+ return f"#{sequence}" if isinstance(sequence, int) else "Unknown event"
18
+
19
+
20
+ def _summary(value):
21
+ if not isinstance(value, str):
22
+ return ""
23
+ return " ".join(value.split())[:220]
24
+
25
+
26
+ def _machine_routes(definition):
27
+ for transition in definition.get("transitions", ()):
28
+ action = transition.get("action", {})
29
+ if target := action.get("role") or action.get("recipient"):
30
+ yield target
31
+
32
+
33
+ class SideSummary:
34
+ """Incremental count of configured and open side agents in one owner journal."""
35
+
36
+ def __init__(self) -> None:
37
+ self.configured_advisor = False
38
+ self.open_agents: set[str] = set()
39
+ self.run_ended = False
40
+
41
+ def observe(self, event) -> None:
42
+ if self.run_ended:
43
+ return
44
+ kind = event["kind"]
45
+ if kind == "run.finished":
46
+ self.run_ended = True
47
+ return
48
+ data = event["payload"]
49
+ if kind == "config.changed" and data["field"] == "profile":
50
+ self.configured_advisor = bool(data["to"]["config"].get(_ADVISOR))
51
+ elif kind == "node.opened" and data["class"] == "side":
52
+ self.open_agents.add(data["node"])
53
+ elif kind == "node.closed":
54
+ self.open_agents.discard(data["node"])
55
+
56
+ @property
57
+ def text(self) -> str:
58
+ if self.run_ended:
59
+ return "0 side agents"
60
+ count = len(self.open_agents) + self.configured_advisor
61
+ return f"{count} side agent" if count == 1 else f"{count} side agents"
62
+
63
+
64
+ def side_summary(events):
65
+ """Count configured and open side agents in one ordered owner journal."""
66
+ summary = SideSummary()
67
+ for event in events:
68
+ summary.observe(event)
69
+ return summary.text
70
+
71
+
72
+ def side_rows(events, width, *, only=None):
73
+ """Project one ordered owner run history without observing or dispatching work."""
74
+ history = {event["seq"]: event for event in events}
75
+ by_role = defaultdict(lambda: deque(maxlen=6))
76
+ turns = {}
77
+ turn_sources = {}
78
+ last_turn = {}
79
+ nodes = {}
80
+ machine_states = defaultdict(lambda: deque(maxlen=3))
81
+ machine_counts = defaultdict(int)
82
+ machine_routes = defaultdict(set)
83
+ consumed = {}
84
+ delivered = {}
85
+ steering = {}
86
+ models = {}
87
+ profile = None
88
+ revision = None
89
+ closed = False
90
+
91
+ for seq, event in history.items():
92
+ kind = event["kind"]
93
+ data = event["payload"]
94
+ cause = event.get("cause")
95
+ identity = data.get("id")
96
+ if kind == "config.changed" and data["field"] == "profile":
97
+ profile = data["to"]["config"]
98
+ revision = data["to"]["revision"]
99
+ machine_states.clear()
100
+ machine_counts.clear()
101
+ machine_routes.clear()
102
+ elif kind == "run.finished":
103
+ closed = True
104
+ elif kind == "config.changed" and data["field"] == "model":
105
+ scope = data["scope"]
106
+ models[scope["role"], scope["provider"]] = data["to"]
107
+ elif kind == "node.opened":
108
+ nodes[data["node"]] = (data, "Open")
109
+ elif kind in {"node.status", "node.closed"} and data["node"] in nodes:
110
+ definition, _ = nodes[data["node"]]
111
+ nodes[data["node"]] = (
112
+ definition,
113
+ data["status"].replace("_", " ").capitalize(),
114
+ )
115
+ elif kind == "core.machine.transition" and data.get("profile") == revision:
116
+ name = data["machine"]
117
+ source = data.get("source") or cause
118
+ machine_counts[name] += 1
119
+ machine_states[name].append((seq, data["from"], data["to"], source))
120
+ elif kind in {"core.agent.woken", "core.machine.woken"}:
121
+ role = data["role"]
122
+ if kind == "core.machine.woken" and data.get("profile") == revision:
123
+ transition = history.get(cause, {})
124
+ if transition.get("kind") == "core.machine.transition":
125
+ machine_routes[role].add(transition["payload"]["machine"])
126
+ by_role[role].append((seq, "detail", "Wake recorded", data.get("goal")))
127
+ elif kind == "turn.reserved":
128
+ role = data["role"]
129
+ turn = event["turn"]
130
+ turns[turn] = role
131
+ last_turn[role] = (seq, "Turn reserved", data.get("provider"))
132
+ source = history.get(cause, {})
133
+ turn_sources[turn] = source.get("kind")
134
+ if turn_sources[turn] == "input.received":
135
+ by_role[role].append(
136
+ (seq, "detail", f"You → {_name(role)}", input_text(source["payload"]["parts"]))
137
+ )
138
+ for message in data.get("inbox") or ():
139
+ consumed[message.get("event")] = seq
140
+ elif kind == "message.completed":
141
+ turn = event["turn"]
142
+ role = data["role"]
143
+ if turn_sources.get(turn) not in {"core.agent.woken", "core.machine.woken"}:
144
+ label = (
145
+ f"{_name(role)} → You"
146
+ if turn_sources.get(turn) == "input.received"
147
+ else "Turn reply"
148
+ )
149
+ text = data.get("text")
150
+ if text is None:
151
+ text = f"Reply stored as text attachment · {data['text_ref']['bytes']} bytes"
152
+ by_role[role].append((seq, "detail", label, text))
153
+ elif kind in {"turn.cancel_requested", "turn.finished"}:
154
+ role = turns.get(event["turn"])
155
+ if role:
156
+ if kind == "turn.cancel_requested":
157
+ last_turn[role] = (seq, "Cancellation requested", None)
158
+ else:
159
+ outcome = data["outcome"]
160
+ last_turn[role] = (seq, f"Turn {outcome['kind']}", outcome.get("reason"))
161
+ elif kind in {"core.wake.blocked", "core.machine.blocked"}:
162
+ role = history.get(cause, {}).get("payload", {}).get("role")
163
+ if role:
164
+ last_turn[role] = (seq, "Wake blocked", data.get("reason"))
165
+ elif kind in {"agent.message", "core.message.sent", "core.machine.returned"}:
166
+ sender, recipient = data.get("from"), data.get("to")
167
+ if sender and recipient and (summary := data.get("summary")):
168
+ direction = f"{_name(sender)} → {_name(recipient)}"
169
+ receipt = (seq, "detail", direction, summary)
170
+ by_role[sender].append(receipt)
171
+ if recipient != sender:
172
+ by_role[recipient].append(receipt)
173
+ elif steering_request(event):
174
+ bound = event.get("turn") or identity
175
+ role = turns.get(bound)
176
+ if role:
177
+ source = history.get(data.get("source"), {}).get("payload", {})
178
+ sender = data.get("from") or source.get("from", "owner")
179
+ direction = f"{_name(sender)} → {_name(role)} · steering"
180
+ text = input_text(data["parts"]) if kind == "input.received" else data.get("summary")
181
+ by_role[role].append((seq, "detail", direction, text))
182
+ elif steering_receipt(event):
183
+ bound = event.get("turn") or identity
184
+ role = turns.get(bound)
185
+ if role:
186
+ steering[(bound, data.get("operation"))] = data.get("outcome")
187
+ by_role[role].append((seq, "detail", "Steering receipt", data.get("outcome")))
188
+ elif kind == "side.recommendation":
189
+ by_role[_ADVISOR].append((seq, "detail", "Recommendation", data.get("summary")))
190
+ elif kind == "notification.requested":
191
+ # The request is durable independently of its delivery surface.
192
+ by_role[_ADVISOR].append(
193
+ (seq, "detail", "Side agent → You · notice", data.get("summary"))
194
+ )
195
+ elif kind == "notification.delivered":
196
+ delivered[data["notice_id"]] = seq
197
+ elif (
198
+ kind in {"core.intent.admitted", "core.intent.rejected"}
199
+ and data.get("target") == _ADVISOR
200
+ and data.get("capability") == "core.wake"
201
+ ):
202
+ status = "Wake admitted" if kind == "core.intent.admitted" else "Wake rejected"
203
+ by_role[_ADVISOR].append((seq, "detail", status, data.get("code")))
204
+
205
+ blocks = []
206
+
207
+ def add(style, text):
208
+ blocks.append((style, text))
209
+
210
+ roles = {
211
+ _ADVISOR: None,
212
+ **{role: node for role, node in nodes.items() if node[0]["class"] == "side"},
213
+ }
214
+ for role, node in roles.items():
215
+ if only and only != role:
216
+ continue
217
+ if blocks:
218
+ add("blank", "")
219
+ add("side", "Side agent" if node is None else f"Side agent · {role}")
220
+ if profile and (choice := models.get((role, profile.get("side")))) and choice.get("model"):
221
+ add(
222
+ "detail",
223
+ binding_detail(profile["side"], choice["model"], choice.get("effort")),
224
+ )
225
+ if node is None:
226
+ if profile is None:
227
+ add("muted", "No advisor profile recorded")
228
+ else:
229
+ provider = profile.get("side") or "Unknown provider"
230
+ wake = profile.get("wake") or "Unknown wake rule"
231
+ add("status", f"Configured · {provider} · wake {wake}")
232
+ add(
233
+ "muted",
234
+ f"Automatic advisor {'enabled' if profile.get('advisor') else 'disabled'}",
235
+ )
236
+ if profile.get("hillclimb_wake") is True and "hillclimb" in (
237
+ profile.get("plugins") or ()
238
+ ):
239
+ add("muted", "Wake grant · Hillclimb → Side agent")
240
+ else:
241
+ definition, state = node
242
+ add("status", f"{state} · parent {_name(definition['parent'])}")
243
+ if goal := _summary(definition.get("goal")):
244
+ add("detail", goal)
245
+ if grants := definition.get("grants"):
246
+ label = "Recorded grant" if state == "Open" else "Historical grant"
247
+ add("muted", f"{label} · {', '.join(grants)}")
248
+ if closed:
249
+ add("muted", "Run closed")
250
+
251
+ machines = [
252
+ definition
253
+ for definition in ((profile or {}).get("machines") or ())
254
+ if role in _machine_routes(definition) or definition["name"] in machine_routes[role]
255
+ ]
256
+ if not machines and only is None:
257
+ add("muted", "No role-linked Temper machine recorded")
258
+ for definition in machines:
259
+ name = definition["name"]
260
+ if transitions := machine_states.get(name):
261
+ current = transitions[-1][2]
262
+ add("status", f"Temper · {name} · {current}")
263
+ for sequence, previous, next_state, source in transitions:
264
+ source_kind = history.get(source, {}).get("kind")
265
+ trigger = f" · {source_kind} #{source}" if source_kind else ""
266
+ add("detail", f"{previous} → {next_state} · #{sequence}{trigger}")
267
+ else:
268
+ current = definition["initial"]
269
+ add("muted", f"Temper · {name} · initial {current}")
270
+ limit = definition.get("limit")
271
+ if isinstance(limit, int) and machine_counts[name] >= limit:
272
+ add("muted", "Configured transition limit reached")
273
+ else:
274
+ next_triggers = dict.fromkeys(
275
+ rule["on"]
276
+ for rule in definition.get("transitions", ())
277
+ if rule.get("from") == current and rule.get("on")
278
+ )
279
+ if next_triggers:
280
+ add("muted", f"Configured next · {', '.join(next_triggers)}")
281
+ if requirements := definition.get("requires"):
282
+ add("muted", f"Requires · {', '.join(requirements)}")
283
+
284
+ if role in last_turn:
285
+ sequence, status, detail = last_turn[role]
286
+ suffix = f" · {detail}" if detail else ""
287
+ add("status", f"Last observed · {status} · #{sequence}{suffix}")
288
+ elif not by_role[role] and only is None:
289
+ add("muted", "No activity recorded")
290
+
291
+ for sequence, style, label, text in by_role[role]:
292
+ event = history[sequence]
293
+ suffix = ""
294
+ if event["kind"] == "notification.requested":
295
+ receipt = delivered.get(event["payload"]["notice_id"])
296
+ suffix = f" · delivered #{receipt}" if receipt else " · requested"
297
+ elif event["kind"] in {"core.message.sent", "core.machine.returned"}:
298
+ receipt = consumed.get(sequence)
299
+ suffix = f" · included in #{receipt}" if receipt else " · recorded"
300
+ elif steering_request(event):
301
+ payload = event["payload"]
302
+ bound = event.get("turn") or payload["id"]
303
+ result = steering.get((bound, payload.get("operation")))
304
+ suffix = f" · {result}" if result else " · requested"
305
+ body = _summary(text)
306
+ preview = f" · {body}" if body else ""
307
+ add(style, f"{label}{suffix} · {_event_ref(sequence)}{preview}")
308
+
309
+ return [(style, line) for style, text in blocks for line in _wrapped(text, max(1, width))]
synth_code/skills.py ADDED
@@ -0,0 +1,269 @@
1
+ """Operator-selected, project-local guides and run-scoped skill pins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ from . import edition
11
+ from .edition import EditionUnavailable, Feature, require_skill_action
12
+
13
+ # Skills every edition offers, and the edition-gated ones with the feature they belong to.
14
+ SHIPPED_SKILLS = ("synth-code", "rex")
15
+ FEATURE_SKILLS: dict[str, Feature] = {"subagent-delegation": Feature.MULTI_AGENT}
16
+
17
+ # The built-in guide, one line or section per entry. An entry names the features its
18
+ # commands need; an edition renders only the entries whose features it ships, so the public
19
+ # guide never names a command (CLI verb or slash command) that build does not register.
20
+ _GUIDE: tuple[tuple[frozenset[Feature], str], ...] = (
21
+ (
22
+ frozenset(),
23
+ """---
24
+ name: synth-code
25
+ description: Work with the installed Synth Code runtime and its research evidence.
26
+ ---
27
+
28
+ # Synth Code
29
+
30
+ Read the installed guide at any time with `synth-code skill show` (or `/skills read synth-code` in the TUI).
31
+
32
+ ## Start, reattach, and inspect runs
33
+ - Start or reattach in the target workspace with `synth-code` or `synth-code --workspace PATH --run RUN attach`.
34
+ - Open a specific saved event directly in the TUI with `synth-code --workspace PATH --run RUN attach --event SEQ`.
35
+ - Inspect a saved run non-interactively (works cold without a running daemon):
36
+ - `synth-code --workspace PATH --run RUN query` (JSONL events with seq, kind, cause, payload)
37
+ - `synth-code --workspace PATH --run RUN inspect --after 0`
38
+ """,
39
+ ),
40
+ (frozenset({Feature.RESEARCH}), " - `synth-code --workspace PATH --run RUN explain TURN`\n"),
41
+ (
42
+ frozenset(),
43
+ "- In the TUI, open an event with `/event SEQ` and follow `/cause` to the event that caused it.\n",
44
+ ),
45
+ (
46
+ frozenset({Feature.MULTI_AGENT, Feature.RESEARCH}),
47
+ """
48
+ ## Consult Side and compare paired seeds
49
+ - Ask Side for an advisory turn: `synth-code --workspace PATH --run RUN ask side MESSAGE`.
50
+ - In the TUI, follow `/grade` to paired scores and open a panel revision with `/panel SEQ`.
51
+ - From the CLI, inspect a paired-seed panel (run, source cursor, immutable SHA-256 artifact revision, paired scores, and summary) with `synth-code --workspace PATH --run RUN panel SEQ`.
52
+ - Check the seed, baseline/candidate policy hashes, and any missing measurements.
53
+ """,
54
+ ),
55
+ (
56
+ frozenset(),
57
+ """
58
+ ## Open cited evidence in Rex
59
+ - Open a specific saved event in an explicitly selected Rex session and pane (required for background/non-interactive processes):
60
+ `synth-code --workspace PATH --run RUN rex SEQ --session SESSION_ID --block BLOCK_ID`
61
+ """,
62
+ ),
63
+ (
64
+ frozenset({Feature.RESEARCH}),
65
+ """- Serve a single immutable HTML panel over an explicit Rex forward:
66
+ `synth-code --workspace PATH --run RUN panel-serve SEQ --session SESSION_ID`
67
+ """,
68
+ ),
69
+ (
70
+ frozenset(),
71
+ """
72
+ ## Propose and approve edits
73
+ - Use `/edit FILE REQUEST` to propose an edit and `/review ID` to inspect it.
74
+ - Approve the exact digest and keep uncertain effects for reconciliation.
75
+ """,
76
+ ),
77
+ )
78
+
79
+
80
+ def general_guide() -> str:
81
+ """The `synth-code` guide for this edition: only the commands its build registers."""
82
+ return "".join(
83
+ text
84
+ for features, text in _GUIDE
85
+ if all(edition.feature_available(feature) for feature in features)
86
+ )
87
+
88
+
89
+ def _rex_failure_detail(result: subprocess.CompletedProcess[str]) -> str:
90
+ details: list[str] = []
91
+ stdout = (result.stdout or "").strip()
92
+ if stdout:
93
+ try:
94
+ payload = json.loads(stdout)
95
+ except json.JSONDecodeError:
96
+ details.append(stdout[:300])
97
+ else:
98
+ steps = payload.get("steps") if isinstance(payload, dict) else None
99
+ if isinstance(steps, list):
100
+ for step in steps:
101
+ if not isinstance(step, dict):
102
+ continue
103
+ change = step.get("change")
104
+ kind = step.get("kind", "item")
105
+ path = step.get("path")
106
+ reason = step.get("reason")
107
+ if change == "conflict":
108
+ target = f" ({path})" if path else ""
109
+ details.append(
110
+ f"existing user-owned rex {kind} conflict{target}"
111
+ )
112
+ elif reason:
113
+ details.append(f"{kind} {change}: {reason}")
114
+ stderr = (result.stderr or "").strip()
115
+ if stderr and stderr not in details:
116
+ details.append(stderr[:300])
117
+ return "; ".join(details) if details else "no diagnostic output"
118
+
119
+
120
+ def _hook_notes(payload: object) -> list[str]:
121
+ if not isinstance(payload, dict):
122
+ return []
123
+ notes: list[str] = []
124
+ for step in payload.get("steps") or []:
125
+ if not isinstance(step, dict):
126
+ continue
127
+ if step.get("kind") == "hook" and step.get("change") in ("skipped", "pending"):
128
+ reason = step.get("reason") or "hook approval required"
129
+ notes.append(f"Rex hook {step['change']}: {reason}")
130
+ return notes
131
+
132
+
133
+ class RexUnavailable(ValueError):
134
+ """The Rex CLI is not on PATH, so the Rex skill cannot be read or set up."""
135
+
136
+ code = "rex_unavailable"
137
+ stage = "rex_skill"
138
+ failed_check = "rex_cli_on_path"
139
+
140
+ def __init__(self) -> None:
141
+ super().__init__(
142
+ f"{self.code}: Rex CLI not found on PATH; install Rex to set up the Rex skill"
143
+ )
144
+
145
+
146
+ def rex(args, workspace):
147
+ try:
148
+ result = subprocess.run(
149
+ ["rex", "skill", *args],
150
+ cwd=workspace,
151
+ timeout=20,
152
+ text=True,
153
+ check=False,
154
+ capture_output=True,
155
+ )
156
+ except FileNotFoundError as error:
157
+ raise RexUnavailable() from error
158
+ if result.returncode:
159
+ raise ValueError(f"Rex skill failed ({result.returncode}): {_rex_failure_detail(result)}")
160
+ return result.stdout
161
+
162
+
163
+ def available_skills() -> tuple[str, ...]:
164
+ """Skills this edition offers; a gated skill appears only where its feature ships."""
165
+ return SHIPPED_SKILLS + tuple(
166
+ name for name, feature in FEATURE_SKILLS.items() if edition.feature_available(feature)
167
+ )
168
+
169
+
170
+ def guide(name):
171
+ if name in FEATURE_SKILLS and not edition.feature_available(FEATURE_SKILLS[name]):
172
+ raise EditionUnavailable(FEATURE_SKILLS[name])
173
+ if name == "synth-code":
174
+ return general_guide()
175
+ if name == "rex":
176
+ return rex(["show"], None)
177
+ if name == "subagent-delegation":
178
+ return (Path(__file__).parent / "guides/subagent-delegation/SKILL.md").read_text(
179
+ encoding="utf-8"
180
+ )
181
+ raise ValueError("Unknown skill")
182
+
183
+
184
+ def revision(text):
185
+ return hashlib.sha256(text.encode()).hexdigest()
186
+
187
+
188
+ def setup_one(root, name, *, preview=False):
189
+ root = Path(root).resolve(strict=True)
190
+ if name == "rex":
191
+ flags = ["setup", "--agent", "codex", "--project", "--json"]
192
+ proposed = json.loads(rex([*flags, "--dry-run"], root))
193
+ if preview:
194
+ notes = _hook_notes(proposed)
195
+ return proposed | ({"notes": notes} if notes else {})
196
+ applied = json.loads(rex(flags, root))
197
+ status = json.loads(rex(["status", "--project", "--json"], root))
198
+ notes = _hook_notes(applied)
199
+ result = {"apply": applied, "status": status}
200
+ if notes:
201
+ result["notes"] = notes
202
+ return result
203
+ if name != "synth-code":
204
+ raise ValueError("Unknown skill")
205
+ guide_text = general_guide()
206
+ path = root / ".agents/skills/synth-code/SKILL.md"
207
+ if any(p.is_symlink() for p in [path, *path.parents] if root in p.parents):
208
+ raise ValueError("Symlink in skill destination")
209
+ if path.exists() and path.read_text() != guide_text:
210
+ raise ValueError("Existing user-owned synth-code guide")
211
+ if not preview:
212
+ path.parent.mkdir(parents=True, exist_ok=True)
213
+ try:
214
+ with path.open("x") as out:
215
+ out.write(guide_text)
216
+ except FileExistsError:
217
+ if path.read_text() != guide_text:
218
+ raise ValueError("Concurrent skill conflict") from None
219
+ return {
220
+ "general": str(path.relative_to(root)),
221
+ "revision": revision(guide_text),
222
+ "preview": preview,
223
+ }
224
+
225
+
226
+ def setup(workspace: Path, rex: bool):
227
+ result = setup_one(workspace, "synth-code")
228
+ if rex:
229
+ result["rex"] = setup_one(workspace, "rex")["apply"]
230
+ return result
231
+
232
+
233
+ def action(client, verb, name=None, workspace=None, operation=None):
234
+ from .session import latest, revise
235
+
236
+ if verb in ("list", "search"):
237
+ return [
238
+ skill
239
+ for skill in available_skills()
240
+ if not name or name.lower() in skill
241
+ ]
242
+ require_skill_action(verb)
243
+ name = name or "synth-code"
244
+ if verb in ("read", "show"):
245
+ return guide(name)
246
+ if verb in ("preview", "setup"):
247
+ return setup_one(workspace, name, preview=verb == "preview")
248
+ if verb not in ("pin", "unpin") or name not in ("synth-code", "rex"):
249
+ raise ValueError("Unknown skill operation")
250
+ key = "skill-" + name
251
+ prior = latest(client, client.run, key)
252
+ text = "unpinned"
253
+ if verb == "pin":
254
+ content = guide(name)
255
+ text = json.dumps(
256
+ {"skill": name, "sha256": revision(content), "excerpt": content[:2100]},
257
+ ensure_ascii=False,
258
+ )
259
+ if prior and prior["text"] == text:
260
+ return prior
261
+ return revise(
262
+ client,
263
+ "skill.pin",
264
+ client.run,
265
+ key,
266
+ prior["revision"] if prior else 0,
267
+ text,
268
+ operation,
269
+ )