polyctl 0.7.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 (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/acp.py ADDED
@@ -0,0 +1,417 @@
1
+ """A client of the Agent Client Protocol just wide enough to ask an agent what it supports (ACP-PROBE).
2
+
3
+ polyctl has driven each harness through flags measured by hand and read what each did from its private stores
4
+ (docs/adapters.md). Most of the harnesses polyctl drives now also speak ACP: JSON-RPC 2.0, one message a line, over
5
+ the standard streams of a process the client starts, and an agent says what it supports when it is asked
6
+ `initialize`. This asks that and, when told to, `session/list`, and nothing else: it opens no session and
7
+ sends no prompt, so asking spends no quota. It is the first step of driving harnesses through ACP; nothing
8
+ in polyctl reads what it measures yet but `polyctl harness`.
9
+
10
+ The standard library only, as the rest of polyctl: a reader thread, a queue and a deadline. A request the agent
11
+ sends back is answered as a method this client does not have, since it declares no capability, and a line
12
+ that is not JSON is passed over.
13
+ """
14
+ import json
15
+ import os
16
+ import queue
17
+ import signal
18
+ import subprocess
19
+ import threading
20
+ import time
21
+
22
+ from . import __version__, procs
23
+
24
+ PROTOCOL_VERSION = 1
25
+ PROBE_TIMEOUT = 20.0
26
+ CANCEL_GRACE = 5.0 # seconds a cancelled turn has to end before its agent is stopped
27
+ METHOD_NOT_FOUND = -32601
28
+ # Why a prompt turn stops, in the protocol's own words (StopReason): its whole answer given, or not - a token
29
+ # limit, a request limit, a refusal, a cancellation. They are ACP's, whatever a harness writes in its own
30
+ # transcript, and only the first is an answer that ended as the agent meant it to (ACP-REVIEWER).
31
+ STOP_REASONS = ("end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled")
32
+ END_TURN = STOP_REASONS[0]
33
+
34
+
35
+ class ProbeError(RuntimeError):
36
+ """An agent that did not answer what it was asked, and why; `still_running` is what of it still ran after
37
+ a probe that failed stopped it (ACP-PROBE-LEFT)."""
38
+ still_running = ()
39
+
40
+
41
+ def _take(parts, update):
42
+ """Add a session update's message text to `parts`, or the line break a tool call makes between two messages.
43
+
44
+ An agent writes a remark, calls a tool and writes its answer: run together, the answer's first line went on
45
+ from the remark's last word, and a verdict line polyctl reads at the start of a line was not read (REVIEW-SEGMENTS).
46
+ """
47
+ kind = update.get("sessionUpdate") if isinstance(update, dict) else None
48
+ if kind == "agent_message_chunk":
49
+ content = update.get("content") if isinstance(update.get("content"), dict) else {}
50
+ if content.get("type") == "text":
51
+ parts.append(str(content.get("text") or ""))
52
+ elif kind == "tool_call":
53
+ last = next((part for part in reversed(parts) if part), "")
54
+ if last and not last.endswith("\n"):
55
+ parts.append("\n")
56
+
57
+
58
+ def answer_text(updates):
59
+ """The text of an agent's messages in a turn's session updates, broken where a tool call fell between two."""
60
+ parts = []
61
+ for update in updates or []:
62
+ _take(parts, update)
63
+ return "".join(parts)
64
+
65
+
66
+ def _group(suspended=False):
67
+ """Start the agent as the leader of its own process group, so stopping it stops what it started.
68
+
69
+ With `suspended`, the process is also started with CREATE_SUSPENDED so polyctl can verify and resume it
70
+ inside a Windows job before its main thread runs (WIN-JOB).
71
+ """
72
+ if os.name == "nt" or suspended:
73
+ from . import procs
74
+ flags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
75
+ if suspended:
76
+ flags |= procs.CREATE_SUSPENDED
77
+ return {"creationflags": flags}
78
+ return {"start_new_session": True}
79
+
80
+
81
+ def _stop(proc, tree=True):
82
+ """Stop the agent and everything it started, wait for it, and return what of it still runs after the stop.
83
+
84
+ The stop is polyctl's own: its group on POSIX, Windows' own taskkill on Windows (WINDOWS-NO-CWD-EXEC),
85
+ and each process of the agent's tree is asked afterwards whether it runs, where the stop was
86
+ taken for done (WINDOWS-STOP-PROVEN). `tree` is False only for a process started with
87
+ CREATE_SUSPENDED whose job was refused while it still had one suspended thread and had never run
88
+ (WIN-JOB).
89
+ """
90
+ left = []
91
+ if proc.poll() is None:
92
+ if tree:
93
+ try:
94
+ from . import lib as A
95
+ left = A.kill_turn(proc.pid, getattr(signal, "SIGKILL", signal.SIGTERM)) or []
96
+ except OSError:
97
+ pass
98
+ else:
99
+ try:
100
+ proc.kill()
101
+ except OSError:
102
+ pass
103
+ for stream in (proc.stdin, proc.stdout):
104
+ try:
105
+ if stream:
106
+ stream.close()
107
+ except OSError:
108
+ pass
109
+ try:
110
+ proc.wait(timeout=5)
111
+ except subprocess.TimeoutExpired:
112
+ proc.kill()
113
+ return left
114
+
115
+
116
+ def _read(stream, lines):
117
+ for line in iter(stream.readline, ""):
118
+ lines.put(line)
119
+ lines.put(None)
120
+
121
+
122
+ def _send(proc, message):
123
+ proc.stdin.write(json.dumps(message, separators=(",", ":")) + "\n")
124
+ proc.stdin.flush()
125
+
126
+
127
+ def _answer(proc, lines, request_id, method, deadline):
128
+ """The agent's response to request `request_id`, answering what it asks meanwhile; raises ProbeError."""
129
+ while True:
130
+ left = deadline - time.monotonic()
131
+ if left <= 0:
132
+ raise ProbeError(f"no answer to {method} within the time allowed")
133
+ try:
134
+ line = lines.get(timeout=left)
135
+ except queue.Empty:
136
+ continue
137
+ if line is None:
138
+ code = proc.poll()
139
+ raise ProbeError(f"the agent ended before it answered {method}"
140
+ + (f" (exit {code})" if code is not None else ""))
141
+ try:
142
+ message = json.loads(line)
143
+ except ValueError:
144
+ continue # a line of the agent's own that is not a message
145
+ if not isinstance(message, dict):
146
+ continue
147
+ if "method" in message:
148
+ if "id" in message: # a request of the agent's: this client has no methods
149
+ _send(proc, {"jsonrpc": "2.0", "id": message["id"],
150
+ "error": {"code": METHOD_NOT_FOUND, "message": "polyctl's probe answers no requests"}})
151
+ continue # a notification: nothing to do
152
+ if message.get("id") != request_id:
153
+ continue
154
+ if "error" in message:
155
+ error = message["error"] if isinstance(message["error"], dict) else {}
156
+ raise ProbeError(f"{method} was refused: {error.get('message') or error.get('code') or 'no reason'}")
157
+ return message.get("result")
158
+
159
+
160
+ def summary(result):
161
+ """What an `initialize` result says the agent supports, as flags and names polyctl keeps."""
162
+ result = result if isinstance(result, dict) else {}
163
+ caps = result.get("agentCapabilities") if isinstance(result.get("agentCapabilities"), dict) else {}
164
+
165
+ def present(block):
166
+ block = caps.get(block) if isinstance(caps.get(block), dict) else {}
167
+ return sorted(key for key, value in block.items() if value not in (None, False))
168
+
169
+ info = result.get("agentInfo") if isinstance(result.get("agentInfo"), dict) else {}
170
+ methods = result.get("authMethods") if isinstance(result.get("authMethods"), list) else []
171
+ return {
172
+ "protocol_version": result.get("protocolVersion"),
173
+ "agent": {"name": info.get("name"), "version": info.get("version")},
174
+ "load_session": bool(caps.get("loadSession")),
175
+ "session": present("sessionCapabilities"),
176
+ "prompt": present("promptCapabilities"),
177
+ "mcp": present("mcpCapabilities"),
178
+ "auth": sorted(str(m["id"]) for m in methods if isinstance(m, dict) and m.get("id")),
179
+ }
180
+
181
+
182
+ def probe(argv, cwd, timeout=PROBE_TIMEOUT, sessions=False, env=None):
183
+ """What the agent `argv` starts says it supports; raises ProbeError when it does not say.
184
+
185
+ Asks `initialize` and, with `sessions`, `session/list` for `cwd` where the agent lists sessions,
186
+ keeping how many it listed and nothing of what they are. The agent is stopped, with everything it
187
+ started, whatever it answers; what of it still runs after that, if anything, is `still_running`,
188
+ never kept in a profile (WINDOWS-STOP-PROVEN) - a key of the answer, and of the ProbeError where there
189
+ is no answer (ACP-PROBE-LEFT).
190
+ """
191
+ try:
192
+ proc = subprocess.Popen(list(argv), cwd=cwd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
193
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
194
+ **_group())
195
+ except OSError as exc:
196
+ raise ProbeError(f"could not start {argv[0]}: {exc}") from exc
197
+ lines = queue.Queue()
198
+ threading.Thread(target=_read, args=(proc.stdout, lines), daemon=True).start()
199
+ deadline, failed = time.monotonic() + timeout, None
200
+ try:
201
+ _send(proc, {"jsonrpc": "2.0", "id": 0, "method": "initialize",
202
+ "params": {"protocolVersion": PROTOCOL_VERSION, "clientCapabilities": {},
203
+ "clientInfo": {"name": "polyctl", "version": __version__}}})
204
+ found = summary(_answer(proc, lines, 0, "initialize", deadline))
205
+ if sessions and "list" in found["session"]:
206
+ _send(proc, {"jsonrpc": "2.0", "id": 1, "method": "session/list", "params": {"cwd": cwd}})
207
+ listed = _answer(proc, lines, 1, "session/list", deadline)
208
+ found["sessions"] = len(listed.get("sessions") or []) if isinstance(listed, dict) else 0
209
+ except ProbeError as exc:
210
+ failed = exc
211
+ except (OSError, ValueError) as exc:
212
+ failed = ProbeError(f"the agent's streams failed: {exc}")
213
+ failed.__cause__ = exc
214
+ finally:
215
+ left = _stop(proc)
216
+ if failed is not None:
217
+ # An agent that did not answer is stopped as one that did, and what its stop left is said as well: the
218
+ # error went up without it, and a probe that timed out named nothing still running (ACP-PROBE-LEFT).
219
+ failed.still_running = left
220
+ raise failed
221
+ if left:
222
+ found["still_running"] = left
223
+ return found
224
+
225
+
226
+ # ---- one session: a prompt turn, its updates and the permissions it asks for (ACP-CLIENT) ----------------------
227
+
228
+ def reject_everything(tool_call, options):
229
+ """The default permission policy: no tool the agent asks leave to run is allowed."""
230
+ return None
231
+
232
+
233
+ class Session:
234
+ """One agent process speaking ACP, and one session in it (ACP-CLIENT).
235
+
236
+ `permission(tool_call, options)` decides each `session/request_permission`: it returns the optionId it
237
+ picks, or None, which picks the agent's first reject option or, where it offers none, answers cancelled.
238
+ Every decision is kept in `decisions`, with the tool call it was about. A request for a client method
239
+ polyctl does not provide - files, terminals - is answered as a method it does not have, since it declares
240
+ no such capability. Use as a context manager, so the agent is stopped with everything it started.
241
+ """
242
+
243
+ def __init__(self, argv, cwd, env=None, permission=None, suspended=False):
244
+ self.cwd = cwd
245
+ self.permission = permission or reject_everything
246
+ self.decisions, self.session_id, self._next = [], None, 0
247
+ suspended = bool(suspended or procs._ACTIVE_JOB is not None)
248
+ # What the session holds is made before its agent starts, so nothing but the reader stands between the start
249
+ # and the guard below (REVIEWER-ORPHAN-6).
250
+ self.lines, self._turn, self.still_running = queue.Queue(), None, None
251
+ try:
252
+ self.proc = subprocess.Popen(list(argv), cwd=cwd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
253
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
254
+ **_group(suspended=suspended))
255
+ except OSError as exc:
256
+ raise ProbeError(f"could not start {argv[0]}: {exc}") from exc
257
+ # A session that fails to start after its agent did - no thread left for the reader - stops the agent: nobody
258
+ # holds a session to close (REVIEWER-ORPHAN-5).
259
+ try:
260
+ threading.Thread(target=_read, args=(self.proc.stdout, self.lines), daemon=True).start()
261
+ except BaseException:
262
+ _stop(self.proc, tree=not suspended)
263
+ raise
264
+
265
+ def __enter__(self):
266
+ return self
267
+
268
+ def __exit__(self, *exc):
269
+ self.close()
270
+
271
+ def close(self, tree=True):
272
+ """Stop the agent; what of it still runs after the first stop, every later one keeps (WINDOWS-STOP-PROVEN)."""
273
+ left = _stop(self.proc) if tree else _stop(self.proc, tree=False)
274
+ if self.still_running is None:
275
+ self.still_running = left
276
+ return self.still_running
277
+
278
+ def _request(self, method, params, timeout):
279
+ request_id = self._next
280
+ self._next += 1
281
+ _send(self.proc, {"jsonrpc": "2.0", "id": request_id, "method": method, "params": params})
282
+ return self._await(request_id, method, time.monotonic() + timeout)
283
+
284
+ def _await(self, request_id, method, deadline, heartbeat=None):
285
+ """The response to `request_id`, handling what the agent sends meanwhile; raises ProbeError.
286
+
287
+ With `heartbeat`, (seconds, callback), callback() is called each time that many seconds pass while it
288
+ waits, whatever the agent streams meanwhile (ACP-REVIEWER).
289
+ """
290
+ beat = time.monotonic() + heartbeat[0] if heartbeat else None
291
+ while True:
292
+ now = time.monotonic()
293
+ left = deadline - now
294
+ if left <= 0:
295
+ raise ProbeError(f"no answer to {method} within the time allowed")
296
+ if beat is not None and now >= beat:
297
+ beat = now + heartbeat[0]
298
+ heartbeat[1]()
299
+ try:
300
+ line = self.lines.get(timeout=left if beat is None else min(left, beat - now))
301
+ except queue.Empty:
302
+ continue
303
+ if line is None:
304
+ code = self.proc.poll()
305
+ raise ProbeError(f"the agent ended before it answered {method}"
306
+ + (f" (exit {code})" if code is not None else ""))
307
+ try:
308
+ message = json.loads(line)
309
+ except ValueError:
310
+ continue
311
+ if not isinstance(message, dict):
312
+ continue
313
+ if "method" in message:
314
+ self._handle(message)
315
+ continue
316
+ if message.get("id") != request_id:
317
+ continue
318
+ if "error" in message:
319
+ error = message["error"] if isinstance(message["error"], dict) else {}
320
+ raise ProbeError(f"{method} was refused: {error.get('message') or error.get('code') or 'no reason'}")
321
+ return message.get("result")
322
+
323
+ def _handle(self, message):
324
+ """A request or a notification of the agent's."""
325
+ method, params = message.get("method"), message.get("params") or {}
326
+ if method == "session/update" and self._turn is not None:
327
+ update = params.get("update") if isinstance(params.get("update"), dict) else {}
328
+ kind = update.get("sessionUpdate")
329
+ _take(self._turn["text"], update)
330
+ if kind in ("tool_call", "tool_call_update"):
331
+ call_id = update.get("toolCallId")
332
+ call = self._turn["tool_calls"].setdefault(call_id, {"id": call_id})
333
+ call.update({key: update[key] for key in ("title", "kind", "status") if key in update})
334
+ # A later report under the same id - the call's own, or another call's that shares it - takes back
335
+ # neither a kind it was reported as nor that it completed (ACP-REVIEWER-5).
336
+ if update.get("kind") is not None and update["kind"] not in call.setdefault("kinds", []):
337
+ call["kinds"].append(update["kind"])
338
+ if update.get("status") == "completed":
339
+ call["completed"] = True
340
+ return
341
+ if "id" not in message:
342
+ return # another notification: nothing to do
343
+ if method == "session/request_permission":
344
+ self._reply(message["id"], {"outcome": self._decide(params)})
345
+ return
346
+ _send(self.proc, {"jsonrpc": "2.0", "id": message["id"],
347
+ "error": {"code": METHOD_NOT_FOUND, "message": f"polyctl provides no {method}"}})
348
+
349
+ def _decide(self, params):
350
+ """The outcome of one permission request, by the policy, kept in `decisions`."""
351
+ tool_call = params.get("toolCall") if isinstance(params.get("toolCall"), dict) else {}
352
+ options = [o for o in params.get("options") or [] if isinstance(o, dict) and o.get("optionId")]
353
+ if self._turn is not None and self._turn.get("cancelled"):
354
+ # A request pending when the turn was cancelled is answered cancelled, as the protocol asks.
355
+ self.decisions.append({"id": tool_call.get("toolCallId"), "tool": tool_call.get("title"),
356
+ "kind": tool_call.get("kind"), "decision": "cancelled"})
357
+ return {"outcome": "cancelled"}
358
+ try:
359
+ chosen = None if self._turn is None else self.permission(tool_call, options)
360
+ except Exception:
361
+ chosen = None # a policy that fails allows nothing
362
+ ids = {o["optionId"]: o for o in options}
363
+ if chosen not in ids:
364
+ chosen = next((o["optionId"] for o in options if str(o.get("kind", "")).startswith("reject")), None)
365
+ outcome = {"outcome": "selected", "optionId": chosen} if chosen else {"outcome": "cancelled"}
366
+ kind = ids.get(chosen, {}).get("kind") if chosen else "cancelled"
367
+ self.decisions.append({"id": tool_call.get("toolCallId"), "tool": tool_call.get("title"),
368
+ "kind": tool_call.get("kind"), "decision": kind})
369
+ return outcome
370
+
371
+ def _reply(self, request_id, result):
372
+ _send(self.proc, {"jsonrpc": "2.0", "id": request_id, "result": result})
373
+
374
+ def initialize(self, timeout=PROBE_TIMEOUT):
375
+ """What the agent supports, as `probe` keeps it."""
376
+ return summary(self._request("initialize", {"protocolVersion": PROTOCOL_VERSION, "clientCapabilities": {},
377
+ "clientInfo": {"name": "polyctl", "version": __version__}}, timeout))
378
+
379
+ def new_session(self, timeout=PROBE_TIMEOUT, mcp_servers=()):
380
+ """Open a session in `cwd`; returns its id."""
381
+ result = self._request("session/new", {"cwd": self.cwd, "mcpServers": list(mcp_servers)}, timeout)
382
+ self.session_id = (result or {}).get("sessionId") if isinstance(result, dict) else None
383
+ if not self.session_id:
384
+ raise ProbeError("session/new answered no sessionId")
385
+ return self.session_id
386
+
387
+ def prompt(self, text, timeout, heartbeat=None):
388
+ """One prompt turn: {"ended", "text", "tool_calls"}, where "ended" is the stop reason the agent gave.
389
+
390
+ The text is the agent's message chunks joined in the order they came. A turn that has not
391
+ ended by `timeout` is cancelled - pending permission requests answered cancelled, as the
392
+ protocol asks - and given a few seconds to end; its stop reason is then "cancelled", or
393
+ "timeout" when it did not end even so. `heartbeat`, (seconds, callback), is called while the
394
+ turn runs, as `_await` says, so a caller can say it is alive (ACP-REVIEWER).
395
+ """
396
+ if not self.session_id:
397
+ raise ProbeError("no session: new_session first")
398
+ self._turn = {"text": [], "tool_calls": {}}
399
+ request_id = self._next
400
+ self._next += 1
401
+ _send(self.proc, {"jsonrpc": "2.0", "id": request_id, "method": "session/prompt",
402
+ "params": {"sessionId": self.session_id, "prompt": [{"type": "text", "text": text}]}})
403
+ try:
404
+ result = self._await(request_id, "session/prompt", time.monotonic() + timeout, heartbeat)
405
+ stop = (result or {}).get("stopReason") if isinstance(result, dict) else None
406
+ except ProbeError as exc:
407
+ if "within the time allowed" not in str(exc):
408
+ raise
409
+ self._turn["cancelled"] = True
410
+ _send(self.proc, {"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": self.session_id}})
411
+ try:
412
+ result = self._await(request_id, "session/prompt", time.monotonic() + CANCEL_GRACE)
413
+ stop = (result or {}).get("stopReason") if isinstance(result, dict) else "cancelled"
414
+ except ProbeError:
415
+ stop = "timeout"
416
+ turn, self._turn = self._turn, None
417
+ return {"ended": stop, "text": "".join(turn["text"]), "tool_calls": list(turn["tool_calls"].values())}
@@ -0,0 +1,101 @@
1
+ # Adapters
2
+
3
+ One JSON file per agent CLI. Everything vendor-specific lives here; the orchestrator core
4
+ knows nothing about any provider. See [`../docs/adapters.md`](../docs/adapters.md) for the
5
+ interface, the two observation modes and the support matrix.
6
+
7
+ ## Status of what is here
8
+
9
+ | File | Status | Verified against |
10
+ |---|---|---|
11
+ | `kiro.json` | **full** | kiro-cli / Kiro IDE 1.0.411 — reference adapter, multi-week production use |
12
+ | `antigravity.json` | **full** | agy 1.1.19, measured again on 1.3.0 — call-return mode, token accounting verified; reviews as an agent that only reads |
13
+ | `claude-code.json` | **full** | Claude Code |
14
+ | `opencode.json` | partial | storage path verified, flags from docs; reviews as an agent that only reads, measured on 1.18.27 |
15
+ | `codex.json` | partial | codex-cli 0.160.0 — the reviewer's command measured; the session store not |
16
+ | everything else | untested | written from documented interfaces |
17
+
18
+ `untested` means exactly that: the file encodes a documented interface that nobody has run
19
+ against a live install. Flags drift between releases. Treat those adapters as a starting
20
+ point, not a promise.
21
+
22
+ `rewriters/` holds no adapter. Each file there says how a command rewriter - a program a
23
+ harness's hook runs an agent's shell commands through, such as rtk - rewrites the commands a
24
+ grant names, measured on one of its releases, so every grant polyctl composes also admits the
25
+ rewritten form (docs/adapters.md, "A grant admits what a command rewriter makes of the
26
+ commands it names").
27
+
28
+ ## Contributing one
29
+
30
+ The most valuable contribution to this project is moving a row from `untested` to `full`.
31
+ It takes about fifteen minutes.
32
+
33
+ **1. Verify the command surface.**
34
+
35
+ ```bash
36
+ <cli> --help
37
+ ```
38
+
39
+ Record the exact non-interactive form. Note whether flags take attached values
40
+ (`--print='x'`) or separated ones (`-p 'x'`) — this is not cosmetic. A CLI using Go-style
41
+ flags will silently swallow a separated prompt, exit 0, and store nothing. That failure
42
+ looks identical to an agent deciding to do nothing, and it cost us an afternoon.
43
+
44
+ **2. Find out how it reports a turn.**
45
+
46
+ ```bash
47
+ <cli> --output-format json --print='say OK'
48
+ ```
49
+
50
+ If you get a structured record back, it is a **call-return** adapter — usually with a
51
+ session id and token usage included, which is better than any transcript. Record the field
52
+ names in `result_record` and `telemetry`.
53
+
54
+ **3. If not, find the transcript.**
55
+
56
+ ```bash
57
+ cd /tmp && mkdir probe && cd probe
58
+ <cli> <non-interactive form> 'MYPROBE12345 write this word only'
59
+ grep -rl "MYPROBE12345" ~/.<tool> ~/.config ~/.local/share ~/Library/Application\ Support 2>/dev/null
60
+ ```
61
+
62
+ Beware false positives: some tools record your *shell history*, so the marker can appear
63
+ in a completely unrelated store because your command text contained it. Confirm by looking
64
+ at the surrounding record, not just the filename.
65
+
66
+ **4. Work out busy detection.** A status field in session metadata, the write age of the
67
+ transcript, or — for call-return adapters — nothing at all, because the call is
68
+ synchronous.
69
+
70
+ **5. Fill in the file** using `kiro.json` as the model, set `verified` honestly, and open a
71
+ pull request. Include the CLI version you tested against.
72
+
73
+ ## Rules
74
+
75
+ - **argv arrays, never shell strings.** Prompts contain quotes, newlines and backticks;
76
+ there must be no string for them to escape out of.
77
+ - **Encode the exact flag form.** Never improvise separated/attached syntax at call time.
78
+ - **Read-only observation.** Never write to a vendor's session store. For SQLite-backed
79
+ agents, open read-only — a second writer corrupts the agent's own state.
80
+ - **Record where credentials live, never their values.**
81
+ - **`verified` is a claim about you, not the tool.** Set it to what you actually ran.
82
+ - **Name it in `vendors.json`.** Every shipped adapter is named by one vendor there, and a vendor
83
+ with no adapter says why; a test fails when the list and the files disagree (#89). If the
84
+ command it runs is not `send.argv[0]`, declare it in `detect.binaries`.
85
+ - **Declare what the harness reads from a project.** `project_config` lists the files and folders it
86
+ reads from the folder it starts in as its configuration - hooks, plugins, MCP servers, agents,
87
+ settings - and `directives.steering_files` the instruction files. polyctl withholds every adapter's
88
+ names from the tree a reviewer reads, wherever they are, and unpacks that tree into a folder of
89
+ its own: a harness started where the candidate's tree was ran the candidate's hooks, plugins and
90
+ MCP servers (REVIEW-TREE-3). A test fails when an adapter that can review a tree declares none.
91
+ The same names are what polyctl watches in a working tree: a change to one that no person has seen is
92
+ named by `polyctl verify`, `polyctl doctor` and the watchdog, and holds every wake, refill, nudge, hunt and
93
+ lane there until a person reads it with `polyctl harness seen` (HARNESS-CONFIG). A harness that makes
94
+ worktrees inside one of those folders declares where in `worktree_dirs` (`.claude/worktrees`):
95
+ a worktree of the repository is skipped there and only there, so one made at `.claude` itself
96
+ is read as configuration; and a link git tracks at one of the names is read through to what it
97
+ leads to, so its target cannot change unseen.
98
+ - **Declare how an unattended turn looks.** `detect.headless` lists the arguments of the
99
+ non-interactive form (`-p`, `--print`, a subcommand such as `exec`). `polyctl hold` and the
100
+ watchdog's reap stop only a process holding one its own harness declares, and a test fails
101
+ when a command the adapter's `send` or `resume` runs holds none.
@@ -0,0 +1,32 @@
1
+ {
2
+ "project_config": [".aider.conf.yml", ".aider.model.settings.yml", "CONVENTIONS.md"],
3
+ "id": "aider", "name": "Aider", "verified": "untested",
4
+ "disclaimer": "Written from documented interface, not verified against an install.",
5
+ "note": "Unusual and useful: Aider keeps a human-readable transcript in the repo, so observation needs no vendor store.",
6
+ "detect": { "headless": ["--message"] },
7
+ "send": { "argv": ["aider", "--message", "{prompt}", "--yes-always"],
8
+ "file": { "replaces": ["--message", "{prompt}"], "with": ["--message-file", "{prompt_file}"],
9
+ "note": "Verified from the options reference (aider.chat/docs/config/options.html), read 2026-09-17: --message-file names a file containing the message to send the LLM, process the reply and exit, as --message does with the message itself." } },
10
+ "resume": { "argv": ["aider", "--message", "{prompt}", "--restore-chat-history", "--yes-always"],
11
+ "file": { "replaces": ["--message", "{prompt}"], "with": ["--message-file", "{prompt_file}"],
12
+ "note": "As send: both are options of every aider command." } },
13
+ "options": {
14
+ "trust_none": null,
15
+ "trust_none_why": "aider works by editing files; it has no mode without its edit tools",
16
+ "model": ["--model", "{model}"],
17
+ "effort": ["--reasoning-effort", "{effort}"],
18
+ "effort_values": ["low", "medium", "high"],
19
+ "thinking_tokens": ["--thinking-tokens", "{tokens}"],
20
+ "trust_all": ["--yes-always"],
21
+ "unattended": [],
22
+ "unattended_note": "Nothing is appended: resume already carries --yes-always.",
23
+ "bypass": {
24
+ "--yes-always": { "roles": ["implementer", "architect"],
25
+ "why": "Kept in every command because it is narrower than leaving it out. aider has no permission rules: --yes-always answers yes to its edit and file confirmations and no to running a shell command the model suggests (aider/io.py answers n to a question that needs an explicit yes), while a run without it takes each question's default from a closed stdin, yes to shell commands included. Read on 2026-09-17 from aider.chat/docs/config/options.html and github.com/Aider-AI/aider (aider/io.py)." }
26
+ },
27
+ "no_auto_commit": ["--no-auto-commits"]
28
+ },
29
+ "transcript": { "kind": "markdown", "path": "{cwd}/.aider.chat.history.md", "record": "markdown sections per exchange" },
30
+ "busy": { "mtime_file": "{cwd}/.aider.chat.history.md", "idle_seconds": 240 },
31
+ "directives": { "steering_files": ["CONVENTIONS.md"], "config": ".aider.conf.yml" }
32
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "project_config": [".amazonq", "AmazonQ.md"],
3
+ "id": "amazon-q", "name": "Amazon Q Developer CLI", "verified": "untested",
4
+ "disclaimer": "Written from documented interface, not verified against an install.",
5
+ "note": "Shares lineage with Kiro CLI: the flag surface is nearly identical, so the kiro adapter is the best starting point if this one drifts.",
6
+ "detect": { "headless": ["--no-interactive"] },
7
+ "send": { "argv": ["q", "chat", "--no-interactive", "{prompt}"] },
8
+ "resume": { "argv": ["q", "chat", "--resume", "--no-interactive", "{prompt}"] },
9
+ "options": { "trust_none": null, "trust_none_why": "no flag verified to deny every tool; --trust-tools narrows the set but was not run tool-less", "model": ["--model", "{model}"], "effort": null, "trust_all": ["--trust-all-tools"], "trust_some": ["--trust-tools={tools}"],
10
+ "bypass": { "--trust-all-tools": { "roles": ["implementer"],
11
+ "why": "Kept: --trust-tools only adds tools to the agent's trusted set, a command allowlist (toolsSettings execute_bash allowedCommands with denyByDefault) lives only in an agent file polyctl does not write, and without a trust a --no-interactive run ends at its first approval (Tool approval required but --no-interactive was specified). The CLI is no longer developed and continues as Kiro CLI. Read on 2026-09-17 from github.com/aws/amazon-q-developer-cli (docs/agent-format.md, docs/built-in-tools.md, crates/chat-cli/src/cli/chat/mod.rs)." } } },
12
+ "transcript": { "kind": "unknown", "candidates": ["~/.aws/amazonq"] },
13
+ "busy": { "kind": "unknown" },
14
+ "directives": { "steering_files": [".amazonq/rules", "AmazonQ.md"] }
15
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "id": "amp", "name": "Amp (Sourcegraph)", "verified": "untested",
3
+ "disclaimer": "Written from documented interface, not verified against an install.",
4
+ "detect": { "headless": ["-x"] },
5
+ "send": { "argv": ["amp", "-x", "{prompt}"],
6
+ "stdin": { "replaces": ["{prompt}"], "with": [],
7
+ "note": "Verified from the execute mode documentation (ampcode.com/docs/cli/execute-mode), read 2026-09-17: its example pipes the whole prompt to `amp -x` with no message. Continuing a thread with piped input is not documented, so resume declares none." } },
8
+ "resume": { "argv": ["amp", "threads", "continue", "{session}", "-x", "{prompt}"] },
9
+ "list_sessions": { "argv": ["amp", "threads", "list"] },
10
+ "options": { "trust_none": null, "trust_none_why": "no documented flag denies tools", "model": null, "model_note": "Amp selects models internally; no user-facing model flag.", "effort": null, "trust_all": ["--dangerously-allow-all"],
11
+ "bypass": { "--dangerously-allow-all": { "roles": ["implementer"],
12
+ "why": "Kept, and leaving it out narrows nothing: since May 2026 Amp asks no permission before a tool runs unless permissions are configured, and narrowing it takes a tool.call plugin or permission settings, neither of which polyctl writes. Read on 2026-09-17 from ampcode.com/news/neo, ampcode.com/docs/tools and ampcode.com/docs/cli/execute-mode." } } },
13
+ "transcript": { "kind": "unknown", "candidates": ["~/.amp/threads"] },
14
+ "busy": { "kind": "unknown" },
15
+ "directives": { "steering_files": ["AGENT.md", "AGENTS.md"] }
16
+ }