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.
- polyctl/__init__.py +7 -0
- polyctl/__main__.py +5 -0
- polyctl/a2a.py +226 -0
- polyctl/a2a_mcp.py +546 -0
- polyctl/acp.py +417 -0
- polyctl/adapters/README.md +101 -0
- polyctl/adapters/aider.json +32 -0
- polyctl/adapters/amazon-q.json +15 -0
- polyctl/adapters/amp.json +16 -0
- polyctl/adapters/antigravity.json +120 -0
- polyctl/adapters/claude-code.json +229 -0
- polyctl/adapters/cloud-generic.json +57 -0
- polyctl/adapters/codex.json +47 -0
- polyctl/adapters/command-code.json +45 -0
- polyctl/adapters/copilot.json +17 -0
- polyctl/adapters/cursor-agent.json +29 -0
- polyctl/adapters/deepseek.json +13 -0
- polyctl/adapters/droid.json +34 -0
- polyctl/adapters/gemini.json +30 -0
- polyctl/adapters/grok.json +22 -0
- polyctl/adapters/hermes.json +34 -0
- polyctl/adapters/kilocode.json +30 -0
- polyctl/adapters/kimi.json +23 -0
- polyctl/adapters/kiro.json +332 -0
- polyctl/adapters/ollama.json +29 -0
- polyctl/adapters/omp.json +34 -0
- polyctl/adapters/openai-api.json +68 -0
- polyctl/adapters/opencode.json +162 -0
- polyctl/adapters/pi.json +24 -0
- polyctl/adapters/pr-agent.json +54 -0
- polyctl/adapters/profiles.json +9 -0
- polyctl/adapters/qoder.json +163 -0
- polyctl/adapters/qwen.json +27 -0
- polyctl/adapters/reasonix.json +25 -0
- polyctl/adapters/rewriters/rtk.json +24 -0
- polyctl/adapters/trae.json +31 -0
- polyctl/adapters/vendors.json +42 -0
- polyctl/adapters/warp.json +88 -0
- polyctl/allowlist.py +1756 -0
- polyctl/api_review.py +920 -0
- polyctl/cli.py +835 -0
- polyctl/conformance_harness.py +9 -0
- polyctl/demo.py +503 -0
- polyctl/drivers.py +146 -0
- polyctl/email.py +160 -0
- polyctl/features.py +98 -0
- polyctl/journal.py +144 -0
- polyctl/language.py +945 -0
- polyctl/lib.py +1296 -0
- polyctl/matrix.py +660 -0
- polyctl/mcp.py +1362 -0
- polyctl/ntfy.py +169 -0
- polyctl/outbound.py +39 -0
- polyctl/parts/__init__.py +5 -0
- polyctl/parts/cli_authority.py +2615 -0
- polyctl/parts/cli_channels.py +1325 -0
- polyctl/parts/cli_checks.py +2293 -0
- polyctl/parts/cli_completion.py +686 -0
- polyctl/parts/cli_evidence.py +141 -0
- polyctl/parts/cli_gain.py +375 -0
- polyctl/parts/cli_harness.py +392 -0
- polyctl/parts/cli_hooks.py +1816 -0
- polyctl/parts/cli_install.py +638 -0
- polyctl/parts/cli_lanes.py +106 -0
- polyctl/parts/cli_maintenance.py +2536 -0
- polyctl/parts/cli_next.py +248 -0
- polyctl/parts/cli_pr.py +53 -0
- polyctl/parts/cli_project.py +2857 -0
- polyctl/parts/cli_review.py +5158 -0
- polyctl/parts/cli_status.py +898 -0
- polyctl/parts/lib_adapters.py +2933 -0
- polyctl/parts/lib_alarms.py +2106 -0
- polyctl/parts/lib_events.py +224 -0
- polyctl/parts/lib_evidence.py +412 -0
- polyctl/parts/lib_gates.py +2099 -0
- polyctl/parts/lib_lanes.py +829 -0
- polyctl/parts/lib_mail.py +1541 -0
- polyctl/parts/lib_next.py +652 -0
- polyctl/parts/lib_pr.py +331 -0
- polyctl/parts/lib_slices.py +3337 -0
- polyctl/parts/lib_state.py +2415 -0
- polyctl/parts/lib_transcript.py +4118 -0
- polyctl/pressure.py +325 -0
- polyctl/prices.json +47 -0
- polyctl/procs.py +1194 -0
- polyctl/settings.py +505 -0
- polyctl/skill/SKILL.md +365 -0
- polyctl/skillkit.py +503 -0
- polyctl/storage.py +2055 -0
- polyctl/telegram.py +327 -0
- polyctl/tiers.py +123 -0
- polyctl/verdicts.py +41 -0
- polyctl/watchdog.py +3887 -0
- polyctl/web.py +337 -0
- polyctl-0.7.0.dist-info/METADATA +235 -0
- polyctl-0.7.0.dist-info/RECORD +99 -0
- polyctl-0.7.0.dist-info/WHEEL +4 -0
- polyctl-0.7.0.dist-info/entry_points.txt +5 -0
- polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""A fixture harness for `polyctl adapters conform`: it records the argv it was given, and nothing else (#77)."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
if __name__ == "__main__":
|
|
7
|
+
with open(os.environ["POLYCTL_HARNESS_RECORD"], "w", encoding="utf-8") as fh:
|
|
8
|
+
json.dump({"argv": sys.argv[1:]}, fh)
|
|
9
|
+
print(json.dumps({"status": "SUCCESS", "response": "conformance"}))
|
polyctl/demo.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
"""`polyctl demo`: polyctl's guarantee shown in about a minute, on a project of its own in a scratch folder (DEMO).
|
|
2
|
+
|
|
3
|
+
The README states the guarantee - a model of another family reviews the exact change an agent
|
|
4
|
+
staged, and nothing else commits - and `polyctl prove` checks the wiring of a project that has polyctl
|
|
5
|
+
already. Neither shows someone who has not adopted polyctl what that looks like when an agent's change
|
|
6
|
+
is wrong, and the first time anyone saw a refusal was on their own repository. The demo plays one
|
|
7
|
+
change through the real command line twice: first with a bug whose tests pass, which the review
|
|
8
|
+
finds and which neither `polyctl commit-ok` nor a plain `git commit` lets land; then with the fix, which
|
|
9
|
+
is reviewed, granted and committed with the trailers that name its grant.
|
|
10
|
+
|
|
11
|
+
Everything happens in a folder made for it in the temporary directory: a git project, a home of
|
|
12
|
+
its own and a stand-in reviewer. Every polyctl command runs as `sys.executable -m polyctl`, the command line
|
|
13
|
+
a person types, with HOME and USERPROFILE naming that home, so ~/.polyctl, git's identity and every
|
|
14
|
+
harness's store are the folder's, never the person's; the variables of polyctl's and git's that point
|
|
15
|
+
anywhere else are left out. No model is called and nothing is installed: the reviewer is a short
|
|
16
|
+
script that answers in polyctl's verdict format, declared in the project's .polyctl/config.json with a family
|
|
17
|
+
of its own, as any reviewer is, and held to every check a reviewer is held to.
|
|
18
|
+
"""
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import shlex
|
|
22
|
+
import shutil
|
|
23
|
+
import stat
|
|
24
|
+
import subprocess
|
|
25
|
+
import sys
|
|
26
|
+
import tempfile
|
|
27
|
+
|
|
28
|
+
from . import lib as A
|
|
29
|
+
from .verdicts import Verdict
|
|
30
|
+
|
|
31
|
+
UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
|
|
32
|
+
|
|
33
|
+
C = A.C
|
|
34
|
+
|
|
35
|
+
# The scratch folder's name starts with this, and only a folder the demo made itself is removed.
|
|
36
|
+
PREFIX = "polyctl-demo-"
|
|
37
|
+
# What points polyctl or git at a person's own files besides HOME: their XDG directories. Every variable of
|
|
38
|
+
# polyctl's (POLYCTL_) and of git's (GIT_) is left out as well, as the suite leaves them out of its own home.
|
|
39
|
+
HOME_POINTERS = ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME")
|
|
40
|
+
# polyctl's one variable that points nowhere: a traceback for whoever has to find where a failure came from.
|
|
41
|
+
KEPT = ("POLYCTL_DEBUG",)
|
|
42
|
+
# What the demo sets itself, each once: Windows reads `Path` and `PATH` as one name, and a block holding both may hand git
|
|
43
|
+
# the one the demo did not set (DEMO-2).
|
|
44
|
+
SET_HERE = ("HOME", "USERPROFILE", "TMPDIR", "TEMP", "TMP", "PYTHONDONTWRITEBYTECODE", "PATH")
|
|
45
|
+
# Longer than any step needs; a command past it is a demo that went wrong, said as one.
|
|
46
|
+
COMMAND_SECONDS = 600
|
|
47
|
+
|
|
48
|
+
# The acceptance boundary the agent works to. One sentence, so the review is asked no criteria of
|
|
49
|
+
# its own (docs/pipeline.md, CRITERIA-VERDICTS): what decides is the reviewer's verdict alone.
|
|
50
|
+
BOUNDARY = "calc.divide(a, b) returns a divided by b and raises ValueError when b is 0"
|
|
51
|
+
REVIEWER_ID = "stand-in-reviewer"
|
|
52
|
+
REVIEWER_FAMILY = "stand-in"
|
|
53
|
+
|
|
54
|
+
CALC = '''"""A tiny calculator: the module the demo's agent changes."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def add(a, b):
|
|
58
|
+
return a + b
|
|
59
|
+
'''
|
|
60
|
+
DIVIDE_WITH_BUG = '''
|
|
61
|
+
|
|
62
|
+
def divide(a, b):
|
|
63
|
+
return a / b
|
|
64
|
+
'''
|
|
65
|
+
DIVIDE_FIXED = '''
|
|
66
|
+
|
|
67
|
+
def divide(a, b):
|
|
68
|
+
if b == 0:
|
|
69
|
+
raise ValueError("divide: b must not be 0")
|
|
70
|
+
return a / b
|
|
71
|
+
'''
|
|
72
|
+
|
|
73
|
+
TEST_HEAD = '''import unittest
|
|
74
|
+
|
|
75
|
+
from calc import {names}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class CalcTest(unittest.TestCase):
|
|
79
|
+
def test_add(self):
|
|
80
|
+
self.assertEqual(add(2, 3), 5)
|
|
81
|
+
'''
|
|
82
|
+
TEST_DIVIDE = '''
|
|
83
|
+
def test_divide(self):
|
|
84
|
+
self.assertEqual(divide(6, 3), 2)
|
|
85
|
+
'''
|
|
86
|
+
TEST_DIVIDE_BY_ZERO = '''
|
|
87
|
+
def test_divide_by_zero_is_refused(self):
|
|
88
|
+
with self.assertRaises(ValueError):
|
|
89
|
+
divide(1, 0)
|
|
90
|
+
'''
|
|
91
|
+
TEST_TAIL = '''
|
|
92
|
+
|
|
93
|
+
if __name__ == "__main__":
|
|
94
|
+
unittest.main()
|
|
95
|
+
'''
|
|
96
|
+
|
|
97
|
+
# The stand-in reviewer, run as [python, reviewer.py, prompt]: no shebang, so Windows runs it too. It
|
|
98
|
+
# answers the probe `polyctl init` sends by echoing its nonce, and a review in polyctl's verdict format. It asks
|
|
99
|
+
# one question of the candidate: does `divide` handle a divisor of 0? polyctl unpacks the staged tree into
|
|
100
|
+
# candidate/ in the directory it runs a reviewer in (REVIEW-TREE-3), and that copy is what it reads.
|
|
101
|
+
REVIEWER = '''"""The stand-in reviewer of `polyctl demo`: a script that answers in polyctl's verdict format, not a model."""
|
|
102
|
+
import ast
|
|
103
|
+
import os
|
|
104
|
+
import sys
|
|
105
|
+
|
|
106
|
+
prompt = sys.argv[1] if len(sys.argv) > 1 else ""
|
|
107
|
+
if prompt.startswith("Reviewer invocation probe"):
|
|
108
|
+
print(prompt.strip().splitlines()[-1])
|
|
109
|
+
sys.exit(0)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def answer(verdict, findings):
|
|
113
|
+
print("VERDICT: " + verdict)
|
|
114
|
+
print("BLOCKER: 0")
|
|
115
|
+
print("HIGH: %d" % len(findings))
|
|
116
|
+
print("MEDIUM: 0")
|
|
117
|
+
print("LOW: 0")
|
|
118
|
+
print()
|
|
119
|
+
print("## Findings")
|
|
120
|
+
print("\\n".join(findings) if findings else "None.")
|
|
121
|
+
print()
|
|
122
|
+
print("## Notes")
|
|
123
|
+
print("A stand-in: a script that asks one question of divide in the staged calc.py.")
|
|
124
|
+
sys.exit(0)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
with open(os.path.join("candidate", "calc.py"), encoding="utf-8") as fh:
|
|
129
|
+
tree = ast.parse(fh.read())
|
|
130
|
+
except (OSError, SyntaxError) as exc:
|
|
131
|
+
answer("NEEDS_CHANGES", ["- [HIGH] calc.py:1 - the staged calc.py could not be read (%s)" % type(exc).__name__])
|
|
132
|
+
divide = next((node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == "divide"), None)
|
|
133
|
+
if divide is None:
|
|
134
|
+
answer("NEEDS_CHANGES", ["- [HIGH] calc.py:1 - the boundary asks for divide(a, b), and calc.py defines none"])
|
|
135
|
+
names = [arg.arg for arg in divide.args.args]
|
|
136
|
+
divisor = names[1] if len(names) > 1 else "b"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def compares_with_zero(node):
|
|
140
|
+
if isinstance(node, ast.Compare):
|
|
141
|
+
parts = [node.left] + list(node.comparators)
|
|
142
|
+
return any(isinstance(part, ast.Name) and part.id == divisor for part in parts) \\
|
|
143
|
+
and any(isinstance(part, ast.Constant) and part.value == 0 for part in parts)
|
|
144
|
+
return isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) \\
|
|
145
|
+
and isinstance(node.operand, ast.Name) and node.operand.id == divisor
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if any(compares_with_zero(node) for node in ast.walk(divide)):
|
|
149
|
+
answer("APPROVED", [])
|
|
150
|
+
line = next((node.lineno for node in ast.walk(divide) if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div)),
|
|
151
|
+
divide.lineno)
|
|
152
|
+
answer("NEEDS_CHANGES", ["- [HIGH] calc.py:%d - divide(1, 0) raises ZeroDivisionError: nothing in divide handles "
|
|
153
|
+
"%s == 0, where the boundary asks for a ValueError" % (line, divisor)])
|
|
154
|
+
'''
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class _Stopped(Exception):
|
|
158
|
+
"""A step that did not behave as the demo says it does; the message says what happened instead."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _test_module(*cases):
|
|
162
|
+
names = "add, divide" if cases else "add"
|
|
163
|
+
return TEST_HEAD.format(names=names) + "".join(cases) + TEST_TAIL
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _shell_words(words):
|
|
167
|
+
"""The words of a command as a person would type them, for the transcript only: nothing runs this text."""
|
|
168
|
+
shown = []
|
|
169
|
+
for word in words:
|
|
170
|
+
plain = word and all(ch.isalnum() or ch in "-_./:=~@%+," for ch in word)
|
|
171
|
+
shown.append(word if plain else '"' + word.replace("\\", "\\\\").replace('"', '\\"') + '"')
|
|
172
|
+
return " ".join(shown)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _gate_command(argv):
|
|
176
|
+
"""A gate's `run` for the shell `polyctl verify` hands it to: cmd.exe's quoting on Windows, sh's elsewhere."""
|
|
177
|
+
return subprocess.list2cmdline(argv) if os.name == "nt" else " ".join(shlex.quote(word) for word in argv)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _environment(scratch, home, bin_dir):
|
|
181
|
+
"""The environment of every command the demo runs: the scratch home, its own temporary directory, and
|
|
182
|
+
this polyctl first on PATH.
|
|
183
|
+
|
|
184
|
+
HOME and USERPROFILE name the scratch home, so ~/.polyctl - the registry, the settings, the gate lock, the
|
|
185
|
+
event log - and git's global config are the demo's. Every POLYCTL_ variable named one of the person's
|
|
186
|
+
own files, every GIT_ variable could point git at another repository or another config, and an XDG
|
|
187
|
+
directory is a home of its own to git; all are left out. Temporary files go into the scratch folder
|
|
188
|
+
too, a reviewer's working directory among them, and no Python the demo starts writes its bytecode
|
|
189
|
+
beside the polyctl it imports.
|
|
190
|
+
"""
|
|
191
|
+
env = {name: value for name, value in os.environ.items()
|
|
192
|
+
if name.upper() in KEPT or not (name.upper().startswith(("POLYCTL_", "GIT_")) or name.upper() in HOME_POINTERS
|
|
193
|
+
or name.upper() in SET_HERE)}
|
|
194
|
+
temporary = os.path.join(scratch, "tmp")
|
|
195
|
+
env.update(HOME=home, USERPROFILE=home, TMPDIR=temporary, TEMP=temporary, TMP=temporary,
|
|
196
|
+
PYTHONDONTWRITEBYTECODE="1")
|
|
197
|
+
env["PATH"] = os.pathsep.join([bin_dir] + [entry for entry in os.environ.get("PATH", "").split(os.pathsep)
|
|
198
|
+
if entry])
|
|
199
|
+
return A.self_child_env(env)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _polyctl_on_path(bin_dir):
|
|
203
|
+
"""Write a `polyctl` that is this polyctl into the scratch bin, which the demo's PATH names first.
|
|
204
|
+
|
|
205
|
+
The commit hook finds polyctl by name on PATH (docs/commands.md), and a person's PATH can hold none -
|
|
206
|
+
polyctl run from a clone - or another release of it, and Windows' hook falls back on no installed one.
|
|
207
|
+
The hook the demo installs must run the polyctl that installed it, so the name is this interpreter running
|
|
208
|
+
this package, with the package's own directory on PYTHONPATH, as the `polyctl` the suite puts on a hook's
|
|
209
|
+
PATH is (tests/test_hook_paths.py). Git runs hooks with its own sh on every platform, so the file is a
|
|
210
|
+
sh script on Windows too, its paths written with forward slashes, which that sh and Python both read.
|
|
211
|
+
"""
|
|
212
|
+
os.makedirs(bin_dir)
|
|
213
|
+
path = os.path.join(bin_dir, "polyctl")
|
|
214
|
+
python, package = (os.path.abspath(where).replace("\\", "/")
|
|
215
|
+
for where in (sys.executable, os.path.dirname(os.path.dirname(A.__file__))))
|
|
216
|
+
with open(path, "w", encoding=UTF8, newline="\n") as fh:
|
|
217
|
+
fh.write(f"#!/bin/sh\nexport PYTHONPATH={shlex.quote(package)}\nexec {shlex.quote(python)} -m polyctl \"$@\"\n")
|
|
218
|
+
os.chmod(path, 0o755)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _remove(scratch):
|
|
222
|
+
"""Remove the scratch folder the demo made, and nothing else; None when it is gone, else why not.
|
|
223
|
+
|
|
224
|
+
Git writes its objects read-only, and Windows refuses to delete a read-only file, so a file that
|
|
225
|
+
cannot be removed is made writable and removed again.
|
|
226
|
+
"""
|
|
227
|
+
made = os.path.realpath(scratch)
|
|
228
|
+
if not (os.path.basename(made).startswith(PREFIX)
|
|
229
|
+
and os.path.dirname(made) == os.path.realpath(tempfile.gettempdir())):
|
|
230
|
+
return f"{scratch} is not a folder the demo made in the temporary directory, so it is left alone"
|
|
231
|
+
|
|
232
|
+
def again(function, path, _):
|
|
233
|
+
os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
|
|
234
|
+
function(path)
|
|
235
|
+
|
|
236
|
+
handler = {"onexc": again} if sys.version_info >= (3, 12) else {"onerror": again}
|
|
237
|
+
try:
|
|
238
|
+
shutil.rmtree(made, **handler)
|
|
239
|
+
except OSError as exc:
|
|
240
|
+
return f"{type(exc).__name__}: {exc}"
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class _Demo:
|
|
245
|
+
"""One run: the scratch folder's places, the environment of its commands, and the step being played."""
|
|
246
|
+
|
|
247
|
+
def __init__(self, scratch):
|
|
248
|
+
self.scratch = scratch
|
|
249
|
+
self.home = os.path.join(scratch, "home")
|
|
250
|
+
self.project = os.path.join(scratch, "project")
|
|
251
|
+
self.bin = os.path.join(scratch, "bin")
|
|
252
|
+
self.reviewer = os.path.join(scratch, "reviewer.py")
|
|
253
|
+
self.env = _environment(scratch, self.home, self.bin)
|
|
254
|
+
# polyctl and git name the folder as it was made and as the file system resolves it.
|
|
255
|
+
spellings = {scratch, os.path.realpath(scratch)}
|
|
256
|
+
self.spellings = sorted(spellings | {path.replace("\\", "/") for path in spellings}, key=len, reverse=True)
|
|
257
|
+
|
|
258
|
+
# ---- what a person reads ------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
def short(self, text):
|
|
261
|
+
"""`text` with the scratch folder written <scratch>: its full path is said once, at the start."""
|
|
262
|
+
for spelling in self.spellings:
|
|
263
|
+
text = text.replace(spelling, "<scratch>")
|
|
264
|
+
return text
|
|
265
|
+
|
|
266
|
+
def say(self, text=""):
|
|
267
|
+
print(f" {text}" if text else "", flush=True)
|
|
268
|
+
|
|
269
|
+
def show(self, command, output):
|
|
270
|
+
print(f" {C['b']}$ {self.short(command)}{C['reset']}", flush=True)
|
|
271
|
+
for line in self.short(output).rstrip().splitlines():
|
|
272
|
+
print(f" {line.rstrip()}", flush=True)
|
|
273
|
+
|
|
274
|
+
# ---- what runs ----------------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
def polyctl(self, *args):
|
|
277
|
+
"""Run `polyctl <args>` in the project as the command line it is, show it and what it printed; (exit, output)."""
|
|
278
|
+
try:
|
|
279
|
+
done = subprocess.run([sys.executable, "-m", "polyctl", *args], cwd=self.project,
|
|
280
|
+
env=A.self_child_env(self.env), stdin=subprocess.DEVNULL,
|
|
281
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding=UTF8,
|
|
282
|
+
errors="replace", timeout=COMMAND_SECONDS)
|
|
283
|
+
except subprocess.TimeoutExpired:
|
|
284
|
+
raise _Stopped(f"polyctl {args[0]} did not finish in {COMMAND_SECONDS}s")
|
|
285
|
+
self.show(_shell_words(("polyctl",) + args), done.stdout)
|
|
286
|
+
return done.returncode, done.stdout
|
|
287
|
+
|
|
288
|
+
def git(self, *args, shown=False):
|
|
289
|
+
"""Run git in the project; shown, it is part of the transcript, else only a failure is said.
|
|
290
|
+
|
|
291
|
+
The git on PATH, never one the current directory holds, which Windows looks in first (WINDOWS-NO-CWD-EXEC).
|
|
292
|
+
"""
|
|
293
|
+
git = A.program_path("git")
|
|
294
|
+
if git is None:
|
|
295
|
+
raise _Stopped("git is no longer on PATH")
|
|
296
|
+
try:
|
|
297
|
+
done = subprocess.run([git, *args], cwd=self.project, env=self.env, stdin=subprocess.DEVNULL,
|
|
298
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding=UTF8,
|
|
299
|
+
errors="replace", timeout=COMMAND_SECONDS)
|
|
300
|
+
except subprocess.TimeoutExpired:
|
|
301
|
+
raise _Stopped(f"git {args[0]} did not finish in {COMMAND_SECONDS}s")
|
|
302
|
+
if shown:
|
|
303
|
+
self.show(_shell_words(("git",) + args), done.stdout)
|
|
304
|
+
return done.returncode, done.stdout
|
|
305
|
+
|
|
306
|
+
def setup_git(self, *args):
|
|
307
|
+
"""A git step of the setup, which must succeed; its output is said only when it does not."""
|
|
308
|
+
code, output = self.git(*args)
|
|
309
|
+
if code:
|
|
310
|
+
self.show(_shell_words(("git",) + args), output)
|
|
311
|
+
raise _Stopped(f"git {args[0]} exited {code}")
|
|
312
|
+
return output
|
|
313
|
+
|
|
314
|
+
def head(self):
|
|
315
|
+
return self.setup_git("rev-parse", "HEAD").strip()
|
|
316
|
+
|
|
317
|
+
def write(self, name, text):
|
|
318
|
+
with open(os.path.join(self.project, name), "w", encoding=UTF8, newline="\n") as fh:
|
|
319
|
+
fh.write(text)
|
|
320
|
+
|
|
321
|
+
# ---- the steps ------------------------------------------------------------------------------
|
|
322
|
+
|
|
323
|
+
def a_project(self):
|
|
324
|
+
"""A home of its own, a git project with a tested module, and the stand-in reviewer beside it."""
|
|
325
|
+
for folder in (self.home, self.project, os.path.join(self.scratch, "tmp")):
|
|
326
|
+
os.makedirs(folder)
|
|
327
|
+
with open(os.path.join(self.home, ".gitconfig"), "w", encoding=UTF8, newline="\n") as fh:
|
|
328
|
+
fh.write("[user]\n\tname = polyctl demo\n\temail = demo@example.invalid\n"
|
|
329
|
+
"[init]\n\tdefaultBranch = main\n[commit]\n\tgpgsign = false\n")
|
|
330
|
+
_polyctl_on_path(self.bin)
|
|
331
|
+
with open(self.reviewer, "w", encoding=UTF8, newline="\n") as fh:
|
|
332
|
+
fh.write(REVIEWER)
|
|
333
|
+
self.setup_git("init", "-q")
|
|
334
|
+
self.write("calc.py", CALC)
|
|
335
|
+
self.write("test_calc.py", _test_module())
|
|
336
|
+
# Running the tests writes __pycache__/, which a Python project ignores; untracked, it would be a change
|
|
337
|
+
# outside the staged candidate, and `polyctl verify` refuses to measure one.
|
|
338
|
+
self.write(".gitignore", "__pycache__/\n")
|
|
339
|
+
self.setup_git("add", "calc.py", "test_calc.py", ".gitignore")
|
|
340
|
+
self.setup_git("commit", "-q", "-m", "calc: add(a, b) and its test")
|
|
341
|
+
self.say(f"scratch folder {self.scratch} (written <scratch> from here on)")
|
|
342
|
+
self.say("home <scratch>/home: ~/.polyctl and git's identity are these, not yours")
|
|
343
|
+
self.say("project <scratch>/project: calc.py with add(a, b), test_calc.py, .gitignore, one commit")
|
|
344
|
+
self.say("reviewer <scratch>/reviewer.py: a stand-in script, not a model")
|
|
345
|
+
|
|
346
|
+
def put_polyctl_on_it(self):
|
|
347
|
+
"""The reviewer and the gate declared first, then `polyctl init`, the adoption commit and the hook."""
|
|
348
|
+
os.makedirs(os.path.join(self.project, ".polyctl"))
|
|
349
|
+
config = {"project": "calc",
|
|
350
|
+
"reviewer": {"id": REVIEWER_ID, "family": REVIEWER_FAMILY,
|
|
351
|
+
"argv": [sys.executable, self.reviewer, "{prompt}"],
|
|
352
|
+
"_why": "polyctl demo's stand-in: a script of a family of its own, never the implementer"}}
|
|
353
|
+
with open(os.path.join(self.project, ".polyctl", "config.json"), "w", encoding=UTF8, newline="\n") as fh:
|
|
354
|
+
fh.write(json.dumps(config, indent=2) + "\n")
|
|
355
|
+
gates = {"gates": {"tests": {"run": _gate_command([sys.executable, "-m", "unittest", "-q"]),
|
|
356
|
+
"expect": "exit_zero", "timeout": 300}},
|
|
357
|
+
"profiles": {"quick": ["tests"], "full": ["tests"]}, "default_profile": "quick"}
|
|
358
|
+
with open(os.path.join(self.project, ".polyctl", "gates.json"), "w", encoding=UTF8, newline="\n") as fh:
|
|
359
|
+
fh.write(json.dumps(gates, indent=2) + "\n")
|
|
360
|
+
self.say(f".polyctl/config.json the reviewer: {REVIEWER_ID}, family {REVIEWER_FAMILY}, "
|
|
361
|
+
"runs <scratch>/reviewer.py")
|
|
362
|
+
self.say(".polyctl/gates.json one gate, the project's tests: python -m unittest")
|
|
363
|
+
profile = A.default_profile()
|
|
364
|
+
implementer = (A.profiles().get(profile) or {}).get("implementer")
|
|
365
|
+
# No MCP registration: registering one can run a harness's own command where it is installed, and the
|
|
366
|
+
# demo starts none. The agent named is the profile's implementer, so what init writes is the same
|
|
367
|
+
# on every machine, whatever harnesses its PATH holds.
|
|
368
|
+
code, _ = self.polyctl("init", "--profile", profile, *(["--agent", implementer] if implementer else []),
|
|
369
|
+
"--no-mcp")
|
|
370
|
+
if code:
|
|
371
|
+
raise _Stopped(f"polyctl init exited {code}")
|
|
372
|
+
self.say("the next steps polyctl init names are for a repository of your own; the demo goes on without them")
|
|
373
|
+
# `polyctl init` stages nothing. The marker turns enforcement on, and .gitignore is product: left
|
|
374
|
+
# uncommitted, it is a change outside the staged candidate, and `polyctl verify` refuses to measure one.
|
|
375
|
+
code, _ = self.git("add", ".polyctl-project", ".gitignore", shown=True)
|
|
376
|
+
if code:
|
|
377
|
+
raise _Stopped(f"git add exited {code}")
|
|
378
|
+
code, _ = self.git("commit", "-q", "-m", "adopt polyctl", shown=True)
|
|
379
|
+
if code:
|
|
380
|
+
raise _Stopped(f"git commit of the adoption exited {code}")
|
|
381
|
+
code, _ = self.polyctl("hooks", "install")
|
|
382
|
+
if code:
|
|
383
|
+
raise _Stopped(f"polyctl hooks install exited {code}")
|
|
384
|
+
self.say("from here on a commit lands only with a grant for its exact staged tree")
|
|
385
|
+
|
|
386
|
+
def a_change_with_a_bug(self):
|
|
387
|
+
"""divide(a, b) whose tests pass and that does not handle b == 0: refused by review, commit-ok and git."""
|
|
388
|
+
self.write("calc.py", CALC + DIVIDE_WITH_BUG)
|
|
389
|
+
self.write("test_calc.py", _test_module(TEST_DIVIDE))
|
|
390
|
+
self.say("the agent adds divide(a, b) to calc.py, and a test that divides 6 by 3:")
|
|
391
|
+
for line in DIVIDE_WITH_BUG.strip("\n").splitlines():
|
|
392
|
+
self.say(f" + {line}")
|
|
393
|
+
self.git("add", "calc.py", "test_calc.py", shown=True)
|
|
394
|
+
before = self.head()
|
|
395
|
+
code, _ = self.polyctl("verify")
|
|
396
|
+
if code:
|
|
397
|
+
raise _Stopped(f"polyctl verify exited {code}, where the tests pass")
|
|
398
|
+
code, output = self.polyctl("review", "--boundary", BOUNDARY)
|
|
399
|
+
if code != 1 or Verdict.NEEDS_CHANGES.value not in output:
|
|
400
|
+
raise _Stopped(f"polyctl review exited {code}, where the review was to find the bug and say "
|
|
401
|
+
f"{Verdict.NEEDS_CHANGES.value}")
|
|
402
|
+
code, output = self.polyctl("commit-ok")
|
|
403
|
+
if code != 1 or "REFUSED" not in output:
|
|
404
|
+
raise _Stopped(f"polyctl commit-ok exited {code}, where it was to refuse")
|
|
405
|
+
code, output = self.git("commit", "-m", "add divide", shown=True)
|
|
406
|
+
if code == 0 or self.head() != before or "COMMIT REFUSED" not in output:
|
|
407
|
+
raise _Stopped(f"git commit exited {code}, where polyctl's hook was to refuse it")
|
|
408
|
+
self.say(f"{C['green']}nothing landed{C['reset']}: the tests passed, the review found the bug, and "
|
|
409
|
+
f"HEAD is still {before[:12]}")
|
|
410
|
+
|
|
411
|
+
def the_fix(self):
|
|
412
|
+
"""divide refuses b == 0: reviewed, granted and committed, its commit naming its grant."""
|
|
413
|
+
self.write("calc.py", CALC + DIVIDE_FIXED)
|
|
414
|
+
self.write("test_calc.py", _test_module(TEST_DIVIDE, TEST_DIVIDE_BY_ZERO))
|
|
415
|
+
self.say("the agent makes divide refuse b == 0, and tests that it does:")
|
|
416
|
+
for line in DIVIDE_FIXED.strip("\n").splitlines():
|
|
417
|
+
self.say(f" + {line}")
|
|
418
|
+
self.git("add", "calc.py", "test_calc.py", shown=True)
|
|
419
|
+
before = self.head()
|
|
420
|
+
code, _ = self.polyctl("verify")
|
|
421
|
+
if code:
|
|
422
|
+
raise _Stopped(f"polyctl verify exited {code}, where the tests pass")
|
|
423
|
+
code, output = self.polyctl("review", "--boundary", BOUNDARY)
|
|
424
|
+
if code != 0 or Verdict.APPROVED.value not in output:
|
|
425
|
+
raise _Stopped(f"polyctl review exited {code}, where the fix was to be {Verdict.APPROVED.value}")
|
|
426
|
+
code, output = self.polyctl("commit-ok")
|
|
427
|
+
if code != 0 or "GRANTED" not in output:
|
|
428
|
+
raise _Stopped(f"polyctl commit-ok exited {code}, where it was to grant")
|
|
429
|
+
code, _ = self.polyctl("commit", "-m", "feat: add divide, which refuses b == 0")
|
|
430
|
+
landed = self.head()
|
|
431
|
+
if code or landed == before:
|
|
432
|
+
raise _Stopped(f"polyctl commit exited {code}, where the granted candidate was to land")
|
|
433
|
+
code, message = self.git("log", "-1", "--format=%B", shown=True)
|
|
434
|
+
if code or "Polyctl-Grant:" not in message:
|
|
435
|
+
raise _Stopped("the commit that landed names no grant in its trailers")
|
|
436
|
+
code, _ = self.polyctl("commit-check", "--range", "HEAD~1..HEAD")
|
|
437
|
+
if code:
|
|
438
|
+
raise _Stopped(f"polyctl commit-check --range exited {code}, where the commit matches its grant")
|
|
439
|
+
code, _ = self.polyctl("digest")
|
|
440
|
+
if code:
|
|
441
|
+
raise _Stopped(f"polyctl digest exited {code}")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
STEPS = (
|
|
445
|
+
("a project of its own", _Demo.a_project),
|
|
446
|
+
("polyctl on it, the reviewer a stand-in of another family", _Demo.put_polyctl_on_it),
|
|
447
|
+
("the agent stages a change with a bug", _Demo.a_change_with_a_bug),
|
|
448
|
+
("the agent stages the fix", _Demo.the_fix),
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def run(keep=False):
|
|
453
|
+
"""Play the demo; 0 when every step behaved as it says, 1 naming the first that did not (DEMO).
|
|
454
|
+
|
|
455
|
+
The scratch folder is removed at the end whatever happened, unless `keep` asks for it to stay, and
|
|
456
|
+
the last lines say which, and where it is.
|
|
457
|
+
"""
|
|
458
|
+
if not A.program_path("git"):
|
|
459
|
+
print(f"{C['red']}polyctl demo needs git{C['reset']}: install git, so that `git --version` answers, and run it "
|
|
460
|
+
"again")
|
|
461
|
+
return 1
|
|
462
|
+
print(f"{C['b']}polyctl demo{C['reset']}: an agent stages a change whose tests pass and whose code is wrong. A "
|
|
463
|
+
"reviewer of another\nmodel family finds it, and nothing lands until the fix is reviewed: not through "
|
|
464
|
+
"polyctl, not through\na plain git commit. Nothing outside a scratch folder is touched, no model is called, "
|
|
465
|
+
"and nothing\nis spent: the reviewer is a stand-in script.", flush=True)
|
|
466
|
+
scratch = tempfile.mkdtemp(prefix=PREFIX)
|
|
467
|
+
demo, stopped = _Demo(scratch), None
|
|
468
|
+
try:
|
|
469
|
+
for number, (title, step) in enumerate(STEPS, 1):
|
|
470
|
+
print(f"\n{C['b']}{number}. {title}{C['reset']}", flush=True)
|
|
471
|
+
try:
|
|
472
|
+
step(demo)
|
|
473
|
+
except _Stopped as exc:
|
|
474
|
+
stopped = (number, title, str(exc))
|
|
475
|
+
break
|
|
476
|
+
except OSError as exc:
|
|
477
|
+
stopped = (number, title, f"{type(exc).__name__}: {demo.short(str(exc))}")
|
|
478
|
+
break
|
|
479
|
+
finally:
|
|
480
|
+
print(f"\n{C['b']}{len(STEPS) + 1}. the scratch folder{C['reset']}", flush=True)
|
|
481
|
+
if keep:
|
|
482
|
+
demo.say(f"kept: {scratch}")
|
|
483
|
+
demo.say("the project, its .polyctl/ ledgers and its review artefacts are there; delete the folder when "
|
|
484
|
+
"you are done")
|
|
485
|
+
problem = None
|
|
486
|
+
else:
|
|
487
|
+
problem = _remove(scratch)
|
|
488
|
+
demo.say(f"removed {scratch}" if problem is None else
|
|
489
|
+
f"{C['red']}not removed{C['reset']}: {problem}; delete {scratch} by hand")
|
|
490
|
+
if stopped:
|
|
491
|
+
number, title, what = stopped
|
|
492
|
+
then = f"Read what polyctl wrote in {scratch}." if keep else \
|
|
493
|
+
"Run `polyctl demo --keep` to keep the scratch folder and read what polyctl wrote there."
|
|
494
|
+
print(f"\n{C['red']}{C['b']}DEMO STOPPED{C['reset']} at step {number}, {title}: {demo.short(what)}. {then}")
|
|
495
|
+
return 1
|
|
496
|
+
if problem:
|
|
497
|
+
print(f"\n{C['red']}{C['b']}DEMO STOPPED{C['reset']} at step {len(STEPS) + 1}, the scratch folder: it "
|
|
498
|
+
"could not be removed.")
|
|
499
|
+
return 1
|
|
500
|
+
print(f"\n{C['green']}{C['b']}DEMO PASSED{C['reset']} every step behaved as it says. To put polyctl on a "
|
|
501
|
+
"repository of your own:\ndocs/getting-started.md, or `polyctl init --profile "
|
|
502
|
+
f"{A.default_profile()}` in it.")
|
|
503
|
+
return 0
|
polyctl/drivers.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Protocols an adapter names that its data alone cannot describe (#76).
|
|
2
|
+
|
|
3
|
+
An adapter declares where a credential lives, which command names the account and
|
|
4
|
+
which endpoint answers. The request and the shape of the answer are a protocol,
|
|
5
|
+
and a protocol is code. Each driver here is chosen by the name an adapter gives it
|
|
6
|
+
in `billing.api.driver` and reads every path, key, command and endpoint from that
|
|
7
|
+
adapter, so no driver names a harness.
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def usage_limits(api, timeout=20):
|
|
18
|
+
"""Real credit usage from the provider, not an estimate.
|
|
19
|
+
|
|
20
|
+
A usage-limits endpoint returns exactly what the app's dashboard shows: credits
|
|
21
|
+
used, the plan limit, the reset date, overage settings. It authenticates with
|
|
22
|
+
the OIDC access token the CLI already holds after login, read from its local
|
|
23
|
+
store (`api.token`) — the same credential, on the same machine, for the same
|
|
24
|
+
account; the profile it asks about is the line the CLI's `api.profile` command
|
|
25
|
+
prints with the declared prefix.
|
|
26
|
+
|
|
27
|
+
Two things this is not. It is not an API key: such a key is rejected as a
|
|
28
|
+
bearer token here, so it authenticates something else. And it is not
|
|
29
|
+
guesswork from transcripts — that reading exists as an offline fallback and
|
|
30
|
+
undercounts by whatever ran on another machine, which measured about a third.
|
|
31
|
+
|
|
32
|
+
Returns None when there is no usable token; the caller falls back rather than
|
|
33
|
+
presenting an error as a balance. The token is used and never stored, logged
|
|
34
|
+
or returned. A missing token store, a CLI that cannot run or a failed request
|
|
35
|
+
returns {"error": ...} naming the step without the exception's text, so a caller
|
|
36
|
+
can report a broken check without copying a credential (TRIAGE-3-MEDIUM).
|
|
37
|
+
"""
|
|
38
|
+
from . import lib as A
|
|
39
|
+
token = api.get("token") or {}
|
|
40
|
+
db = A._home_path(token.get("sqlite"))
|
|
41
|
+
if not db or not os.path.exists(db):
|
|
42
|
+
return {"error": "the CLI's token store is missing; sign in to the CLI and retry the usage check"}
|
|
43
|
+
# The store's path and the query are arguments, never shell text: through cmd.exe the
|
|
44
|
+
# JSON-quoted path reached sqlite3 with every backslash doubled (#71). The sqlite3 is one
|
|
45
|
+
# on PATH, never one the current directory holds (WINDOWS-NO-CWD-EXEC).
|
|
46
|
+
query = f"SELECT value FROM {token['table']} WHERE key='{token['key']}';"
|
|
47
|
+
sqlite3 = A.program_path("sqlite3")
|
|
48
|
+
try:
|
|
49
|
+
raw = subprocess.run([sqlite3, db, query], capture_output=True, text=True, encoding=UTF8,
|
|
50
|
+
errors="replace", timeout=timeout).stdout.strip() if sqlite3 else ""
|
|
51
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
52
|
+
raw = ""
|
|
53
|
+
if not raw:
|
|
54
|
+
return None
|
|
55
|
+
try:
|
|
56
|
+
tok = json.loads(raw)
|
|
57
|
+
except Exception:
|
|
58
|
+
return None
|
|
59
|
+
# A store value that is JSON but no object, or a token that is no string, is no usable token: `tok.get` and
|
|
60
|
+
# "Bearer " + a number raised out of here, where the caller expects None (HUNT-LEADS-SEC).
|
|
61
|
+
access = tok.get(token.get("field") or "access_token") if isinstance(tok, dict) else None
|
|
62
|
+
if not access or not isinstance(access, str):
|
|
63
|
+
return None
|
|
64
|
+
expires = token.get("expires") or "expires_at"
|
|
65
|
+
if tok.get(expires):
|
|
66
|
+
try:
|
|
67
|
+
exp = tok[expires]
|
|
68
|
+
exp = float(exp) if not isinstance(exp, str) else \
|
|
69
|
+
__import__("datetime").datetime.fromisoformat(
|
|
70
|
+
exp.replace("Z", "+00:00")).timestamp()
|
|
71
|
+
if exp < time.time():
|
|
72
|
+
return {"expired": True}
|
|
73
|
+
except Exception:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
# Resolve the CLI through the harness binary search, not the ambient PATH: under
|
|
77
|
+
# launchd that PATH is /usr/bin:/bin:/usr/sbin:/sbin, the CLI was never found,
|
|
78
|
+
# and a `2>/dev/null` turned the miss into None, so the watchdog never recorded
|
|
79
|
+
# a sample and the exhaustion alarm could not fire. Say which step failed.
|
|
80
|
+
profile = api.get("profile") or {}
|
|
81
|
+
argv = [str(part) for part in profile.get("argv") or []]
|
|
82
|
+
found = A.binary_candidates(argv[0]) if argv else []
|
|
83
|
+
if not found:
|
|
84
|
+
return {"error": f"{argv[0] if argv else 'the CLI'} is not on PATH or in the usual install directories"}
|
|
85
|
+
step = " ".join(argv[1:])
|
|
86
|
+
try:
|
|
87
|
+
prof = subprocess.run([found[0]] + argv[1:], capture_output=True, text=True, encoding=UTF8,
|
|
88
|
+
errors="replace", timeout=timeout)
|
|
89
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
90
|
+
return {"error": f"{found[0]} {step} could not run ({type(exc).__name__})"}
|
|
91
|
+
arn = next((line.strip() for line in (prof.stdout or "").splitlines()
|
|
92
|
+
if line.strip().startswith(profile.get("prefix") or "arn:")), "")
|
|
93
|
+
if not arn:
|
|
94
|
+
return {"error": f"{found[0]} {step} returned no profile ARN (exit {prof.returncode})"}
|
|
95
|
+
|
|
96
|
+
import urllib.error
|
|
97
|
+
import urllib.request
|
|
98
|
+
from . import outbound
|
|
99
|
+
body = {key: (arn if value == "{profile}" else value) for key, value in (api.get("body") or {}).items()}
|
|
100
|
+
req = urllib.request.Request(
|
|
101
|
+
api["endpoint"],
|
|
102
|
+
data=json.dumps(body).encode(),
|
|
103
|
+
headers={"Content-Type": api["content_type"],
|
|
104
|
+
"x-amz-target": api["target"],
|
|
105
|
+
"Authorization": "Bearer " + access})
|
|
106
|
+
# The token goes to the endpoint the adapter names and nowhere else: urlopen followed a redirect with every
|
|
107
|
+
# header, this one among them, to whatever host it named (HUNT-LEADS-SEC).
|
|
108
|
+
opener = outbound.OPENER
|
|
109
|
+
try:
|
|
110
|
+
with opener.open(req, timeout=timeout) as r:
|
|
111
|
+
d = json.loads(r.read().decode())
|
|
112
|
+
except urllib.error.HTTPError as e:
|
|
113
|
+
if outbound.is_redirect(e.code):
|
|
114
|
+
return {"error": f"HTTP {e.code}, a redirect, which polyctl does not follow with the account's token: the URL "
|
|
115
|
+
"the endpoint moved to belongs in the adapter's billing.api.endpoint, which ships with "
|
|
116
|
+
"polyctl - report it, and read the transcripts meanwhile with polyctl credits --offline"}
|
|
117
|
+
return {"error": f"HTTP {e.code}"}
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
return {"error": f"the usage request failed ({type(exc).__name__}); check connectivity and retry"}
|
|
120
|
+
# The answer is read as the store is: JSON that is no object, or a field of another shape, is said, not raised.
|
|
121
|
+
if not isinstance(d, dict):
|
|
122
|
+
return {"error": "the response is no JSON object"}
|
|
123
|
+
|
|
124
|
+
resource = api.get("resource") or "CREDIT"
|
|
125
|
+
rows = d.get("usageBreakdownList") if isinstance(d.get("usageBreakdownList"), list) else []
|
|
126
|
+
row = next((b for b in rows if isinstance(b, dict) and b.get("resourceType") == resource), None)
|
|
127
|
+
if not row:
|
|
128
|
+
return {"error": f"no {resource} row in response"}
|
|
129
|
+
sub = d.get("subscriptionInfo") if isinstance(d.get("subscriptionInfo"), dict) else {}
|
|
130
|
+
over = d.get("overageConfiguration") if isinstance(d.get("overageConfiguration"), dict) else {}
|
|
131
|
+
return {
|
|
132
|
+
"used": row.get("currentUsageWithPrecision", row.get("currentUsage")),
|
|
133
|
+
"limit": row.get("usageLimitWithPrecision", row.get("usageLimit")),
|
|
134
|
+
"reset_at": row.get("nextDateReset") or d.get("nextDateReset"),
|
|
135
|
+
"days_until_reset": d.get("daysUntilReset"),
|
|
136
|
+
"plan": sub.get("subscriptionTitle"),
|
|
137
|
+
"overage_status": over.get("overageStatus"),
|
|
138
|
+
"overage_cap": row.get("overageCapWithPrecision", row.get("overageCap")),
|
|
139
|
+
"overage_rate": row.get("overageRate"),
|
|
140
|
+
"overage_now": row.get("currentOveragesWithPrecision", row.get("currentOverages")),
|
|
141
|
+
# Which account the figures belong to, without keeping the profile ARN itself (#36).
|
|
142
|
+
"account": A.credit_account(arn),
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
USAGE = {"usage-limits": usage_limits}
|