AskTim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
asktim/records.py ADDED
@@ -0,0 +1,319 @@
1
+ """The record of an agent's run, written by AskTim! from what really happened - not by the model.
2
+
3
+ In the run's folder (asktim-runs/N-mode/):
4
+
5
+ RUN.md to read: the task, the model, every step with its reason, the command, its exit
6
+ status, the end of what it printed, what the AI was shown of it, what was
7
+ refused or changed, the files made (with checksums), the agent's report, and a
8
+ draft statement on the use of AI
9
+ run.json the same, for programs
10
+ rerun.sh the commands that worked, in order, with the files the agent wrote: a script
11
+ to repeat the analysis (read it before you run it)
12
+ agent-record.ipynb (notebook runs) the run as a notebook: explanations and code cells
13
+ """
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import shlex
19
+ import time
20
+
21
+ from . import __version__, paths
22
+
23
+ MODE_NAMES = {"approve": "approve each step", "plan": "plan first", "auto": "autonomous", "script": "write a script"}
24
+
25
+
26
+ def _md5(path, limit=2 << 30):
27
+ try:
28
+ if os.path.getsize(path) > limit:
29
+ return "(too large to checksum here)"
30
+ h = hashlib.md5()
31
+ with open(path, "rb") as f:
32
+ for chunk in iter(lambda: f.read(1 << 20), b""):
33
+ h.update(chunk)
34
+ return h.hexdigest()
35
+ except OSError:
36
+ return ""
37
+
38
+
39
+ def _files(folder, skip=("RUN.md", "run.json", "rerun.sh", "agent-record.ipynb")):
40
+ out = []
41
+ for root, dirs, files in os.walk(folder):
42
+ dirs[:] = [d for d in dirs if not d.startswith(".")]
43
+ for fn in sorted(files):
44
+ if fn in skip and root == folder or fn.startswith(".asktim"):
45
+ continue
46
+ p = os.path.join(root, fn)
47
+ try:
48
+ size = os.path.getsize(p)
49
+ except OSError:
50
+ continue
51
+ out.append((os.path.relpath(p, folder), size, _md5(p)))
52
+ return out
53
+
54
+
55
+ def _fence(text, lang="text"):
56
+ text = text or ""
57
+ fence = "```"
58
+ while fence in text:
59
+ fence += "`"
60
+ return "%s%s\n%s\n%s" % (fence, lang, text.rstrip("\n"), fence)
61
+
62
+
63
+ def write(run, folder):
64
+ """run: dict built by the agent. Returns the paths written."""
65
+ paths.ensure(folder)
66
+ written = []
67
+ files = _files(run["work_dir"]) if os.path.isdir(run["work_dir"]) else []
68
+ run["files"] = [{"path": p, "bytes": s, "md5": m} for p, s, m in files]
69
+ # run.json
70
+ jp = os.path.join(folder, "run.json")
71
+ with open(jp, "w", encoding="utf-8") as f:
72
+ json.dump(run, f, indent=2, ensure_ascii=False, default=str)
73
+ written.append(jp)
74
+ # RUN.md
75
+ mp = os.path.join(folder, "RUN.md")
76
+ with open(mp, "w", encoding="utf-8") as f:
77
+ f.write(markdown(run))
78
+ written.append(mp)
79
+ # rerun.sh
80
+ if any(s["tool"] in ("run_command", "write_file") for s in run["steps"]):
81
+ sp = os.path.join(folder, "rerun.sh")
82
+ with open(sp, "w", encoding="utf-8") as f:
83
+ f.write(rerun_script(run))
84
+ os.chmod(sp, 0o755)
85
+ written.append(sp)
86
+ if run.get("notebook"):
87
+ np_ = os.path.join(folder, "agent-record.ipynb")
88
+ with open(np_, "w", encoding="utf-8") as f:
89
+ json.dump(notebook_record(run), f, indent=1, ensure_ascii=False)
90
+ written.append(np_)
91
+ return written
92
+
93
+
94
+ def markdown(run):
95
+ L = []
96
+ L.append("# AskTim! Agent – run %s (%s)" % (run["number"], MODE_NAMES.get(run["mode"], run["mode"])))
97
+ L.append("")
98
+ L.append("This record was written by AskTim! from what happened, not by the AI model.")
99
+ L.append("")
100
+ L.append("| | |")
101
+ L.append("|---|---|")
102
+ L.append("| Task | %s |" % run["task"].replace("|", "\\|").replace("\n", " "))
103
+ L.append("| Started | %s |" % run["started"])
104
+ L.append("| Ended | %s (%s) |" % (run.get("ended", ""), run.get("outcome", "")))
105
+ L.append("| Model | %s |" % ", ".join(run.get("models") or ["?"]))
106
+ L.append("| Folder | %s |" % run["work_dir_shown"])
107
+ L.append("| Safeguards | %s; internet %s |" % (run.get("sandbox", ""), "allowed (downloads only)" if run.get("allow_network") else "off"))
108
+ L.append("| Privacy | %s; %d line%s of output withheld from the AI as data |" % (run.get("privacy", "standard"), run.get("withheld", 0), "" if run.get("withheld", 0) == 1 else "s"))
109
+ L.append("| AskTim! | %s |" % __version__)
110
+ L.append("")
111
+ if run.get("plan"):
112
+ L.append("## The plan")
113
+ L.append("")
114
+ for i, p in enumerate(run["plan_rounds"] if run.get("plan_rounds") else [run["plan"]]):
115
+ if i:
116
+ L.append("*Changes asked for by the student:* %s" % (run.get("plan_feedback") or [""])[i - 1] if i - 1 < len(run.get("plan_feedback") or []) else "")
117
+ L.append("")
118
+ L.append(p.strip())
119
+ L.append("")
120
+ L.append("## Steps")
121
+ L.append("")
122
+ if not run["steps"]:
123
+ L.append("(none)")
124
+ for s in run["steps"]:
125
+ L.append("### %d. %s" % (s["n"], s.get("why") or s["tool"]))
126
+ L.append("")
127
+ if s["tool"] == "run_command":
128
+ L.append(_fence(s.get("command", ""), "bash"))
129
+ elif s["tool"] == "run_python":
130
+ L.append(_fence(s.get("code", ""), "python"))
131
+ elif s["tool"] in ("write_file",):
132
+ L.append("Wrote `%s` (%s):" % (s.get("path"), "%d lines" % (s.get("content", "").count("\n") + 1)))
133
+ L.append("")
134
+ L.append(_fence(s.get("content", ""), _lang_of(s.get("path", ""))))
135
+ elif s["tool"] in ("add_code_cell",):
136
+ L.append("Added a code cell to the notebook:")
137
+ L.append("")
138
+ L.append(_fence(s.get("code", ""), "python"))
139
+ elif s["tool"] in ("add_markdown_cell",):
140
+ L.append("Added a Markdown cell to the notebook:")
141
+ L.append("")
142
+ L.append(_fence(s.get("text", ""), "markdown"))
143
+ else:
144
+ L.append("`%s` %s" % (s["tool"], json.dumps(s.get("input", {}), ensure_ascii=False)[:300]))
145
+ L.append("")
146
+ bits = []
147
+ if s.get("decision"):
148
+ bits.append({"run": "approved by the student", "auto": "run without asking (autonomous)", "all": "approved (and the rest of the run without asking)",
149
+ "edit": "changed by the student before it ran", "refuse": "refused by the student", "blocked": "refused by AskTim!'s safeguards"}.get(s["decision"], s["decision"]))
150
+ if s.get("comment"):
151
+ bits.append("the student said: “%s”" % s["comment"])
152
+ if s.get("original") and s.get("decision") == "edit":
153
+ bits.append("the agent had proposed: `%s`" % s["original"].replace("`", "'")[:300])
154
+ if s.get("blocked"):
155
+ bits.append("why: " + "; ".join(s["blocked"]))
156
+ if s.get("exit") is not None:
157
+ bits.append("exit status %s" % s["exit"])
158
+ if s.get("seconds") is not None:
159
+ bits.append("%.1f s" % s["seconds"])
160
+ if s.get("timed_out"):
161
+ bits.append("stopped: it ran longer than the time limit")
162
+ if s.get("interrupted"):
163
+ bits.append("stopped by the student (Ctrl+C)")
164
+ if s.get("lines") is not None:
165
+ bits.append("%d line%s of output" % (s["lines"], "" if s["lines"] == 1 else "s"))
166
+ if s.get("withheld"):
167
+ bits.append("%d withheld from the AI as data" % s["withheld"])
168
+ if bits:
169
+ L.append("*" + "; ".join(bits) + ".*")
170
+ L.append("")
171
+ if s.get("outside_changes"):
172
+ L.append("**Files outside the agent's folder changed during this step:** " + ", ".join("`%s`" % x for x in s["outside_changes"][:20]))
173
+ L.append("")
174
+ if s.get("output_tail"):
175
+ L.append("The end of what it printed (as you saw it):")
176
+ L.append("")
177
+ L.append(_fence(s["output_tail"]))
178
+ L.append("")
179
+ if s.get("sent") and s.get("sent") != s.get("output_tail"):
180
+ L.append("<details><summary>What the AI was shown of this step</summary>")
181
+ L.append("")
182
+ L.append(_fence(s["sent"]))
183
+ L.append("")
184
+ L.append("</details>")
185
+ L.append("")
186
+ L.append("## The agent's report")
187
+ L.append("")
188
+ rep = (run.get("report") or "(no report)").strip()
189
+ L.append("\n".join("> " + ln if ln.strip() else ">" for ln in rep.splitlines()))
190
+ L.append("")
191
+ L.append("The report is the model's own text: check it against the steps above.")
192
+ L.append("")
193
+ if run.get("files"):
194
+ L.append("## Files in the folder")
195
+ L.append("")
196
+ L.append("| File | Size | MD5 |")
197
+ L.append("|---|---|---|")
198
+ for f in run["files"][:200]:
199
+ L.append("| %s | %s | `%s` |" % (f["path"], f["bytes"], f["md5"]))
200
+ L.append("")
201
+ if any(s["tool"] in ("run_command", "write_file") for s in run["steps"]):
202
+ L.append("## Repeat it")
203
+ L.append("")
204
+ L.append("`rerun.sh` holds the commands that worked, in order, with the files the agent wrote. Read it before you run it: `bash rerun.sh`.")
205
+ L.append("")
206
+ L.append("## Statement on the use of AI (a draft)")
207
+ L.append("")
208
+ n_run = sum(1 for s in run["steps"] if s.get("exit") is not None)
209
+ n_ref = sum(1 for s in run["steps"] if s.get("decision") in ("refuse", "blocked"))
210
+ n_edit = sum(1 for s in run["steps"] if s.get("decision") == "edit")
211
+ L.append(
212
+ "On %s I used AskTim! Agent (%s), an AI agent, in “%s” mode for this task: “%s”. It proposed %d step%s; %d command%s ran, "
213
+ "%d step%s %s refused (by me or by AskTim!'s safeguards) and %d changed by me. The AI did not see the contents of my data files: the output of each command "
214
+ "reached it with lines that looked like data withheld. I checked the results myself (say how), and the conclusions are mine."
215
+ % (run["started"][:10], ", ".join(run.get("models") or ["?"]), MODE_NAMES.get(run["mode"], run["mode"]), run["task"].replace("\n", " ")[:200],
216
+ len(run["steps"]), "" if len(run["steps"]) == 1 else "s", n_run, "" if n_run == 1 else "s", n_ref, "" if n_ref == 1 else "s", "was" if n_ref == 1 else "were", n_edit)
217
+ )
218
+ L.append("")
219
+ return "\n".join(L)
220
+
221
+
222
+ def _lang_of(path):
223
+ ext = os.path.splitext(path)[1].lower()
224
+ return {".sh": "bash", ".py": "python", ".r": "r", ".rmd": "markdown", ".md": "markdown", ".smk": "python", ".nf": "groovy", ".yaml": "yaml", ".yml": "yaml", ".json": "json"}.get(ext, "text")
225
+
226
+
227
+ def rerun_script(run):
228
+ L = [
229
+ "#!/usr/bin/env bash",
230
+ "# Made by AskTim! from agent run %s (%s), %s." % (run["number"], MODE_NAMES.get(run["mode"], run["mode"]), run["started"][:16].replace("T", " ")),
231
+ "# Task: %s" % run["task"].replace("\n", " ")[:300],
232
+ "#",
233
+ "# The commands that worked, in order, and the files the agent wrote. Commands that failed or",
234
+ "# were refused are here as comments. It runs in its own folder (as the agent did), so read the",
235
+ "# paths before you run it somewhere else. Read the whole script before you run it: bash rerun.sh",
236
+ "set -eu",
237
+ 'cd "$(dirname "$0")"',
238
+ "",
239
+ ]
240
+ if run.get("here"):
241
+ L[-2] = 'cd "$(dirname "$0")/../.." # the agent worked in your folder'
242
+ for s in run["steps"]:
243
+ why = (s.get("why") or "").replace("\n", " ")
244
+ if s["tool"] == "run_command":
245
+ cmd = s.get("command", "")
246
+ if s.get("exit") == 0 and s.get("decision") not in ("refuse", "blocked"):
247
+ L.append("# %d. %s" % (s["n"], why))
248
+ L.append(cmd)
249
+ else:
250
+ state = "refused" if s.get("decision") in ("refuse", "blocked") else "failed (exit %s)" % s.get("exit")
251
+ L.append("# %d. %s – %s, so left out:" % (s["n"], why, state))
252
+ L.extend("# " + ln for ln in cmd.splitlines())
253
+ L.append("")
254
+ elif s["tool"] == "write_file" and s.get("written"):
255
+ body = s.get("content", "")
256
+ tag = "ASKTIM_EOF"
257
+ while tag in body:
258
+ tag += "_"
259
+ L.append("# %d. %s (the file the agent wrote)" % (s["n"], why))
260
+ L.append("cat > %s <<'%s'" % (shlex.quote(s.get("path", "file")), tag))
261
+ L.append(body.rstrip("\n"))
262
+ L.append(tag)
263
+ L.append("")
264
+ elif s["tool"] == "run_python" and s.get("ok"):
265
+ body = s.get("code", "")
266
+ tag = "ASKTIM_EOF"
267
+ while tag in body:
268
+ tag += "_"
269
+ L.append("# %d. %s (Python that ran in the notebook; it needs the notebook's variables)" % (s["n"], why))
270
+ L.append("python3 - <<'%s'" % tag)
271
+ L.append(body.rstrip("\n"))
272
+ L.append(tag)
273
+ L.append("")
274
+ L.append('echo "Done. Compare the results with RUN.md."')
275
+ return "\n".join(L) + "\n"
276
+
277
+
278
+ def notebook_record(run):
279
+ cells = []
280
+
281
+ def md(text):
282
+ cells.append({"cell_type": "markdown", "metadata": {}, "source": text})
283
+
284
+ def code(text):
285
+ cells.append({"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": text})
286
+
287
+ md("# AskTim! Agent – run %s\n\n**Task:** %s\n\nModel: %s · mode: %s · %s\n\nWritten by AskTim! from what happened (not by the model). Run the cells to repeat the work." % (
288
+ run["number"], run["task"], ", ".join(run.get("models") or ["?"]), MODE_NAMES.get(run["mode"], run["mode"]), run["started"][:16].replace("T", " ")))
289
+ for s in run["steps"]:
290
+ why = s.get("why") or ""
291
+ if s["tool"] == "run_python":
292
+ md("**%d.** %s%s" % (s["n"], why, "" if s.get("ok") else " *(this step failed or was refused)*"))
293
+ code(s.get("code", "") if s.get("ok") else "# " + s.get("code", "").replace("\n", "\n# "))
294
+ elif s["tool"] == "run_command":
295
+ md("**%d.** %s%s" % (s["n"], why, "" if s.get("exit") == 0 else " *(this step failed or was refused)*"))
296
+ code(("%%%%bash\ncd %s\n%s" % (shlex.quote(run["work_dir"]), s.get("command", ""))) if s.get("exit") == 0 else "# " + s.get("command", "").replace("\n", "\n# "))
297
+ elif s["tool"] == "add_markdown_cell":
298
+ md(s.get("text", ""))
299
+ elif s["tool"] == "add_code_cell":
300
+ code(s.get("code", ""))
301
+ if run.get("report"):
302
+ md("## The agent's report\n\n" + run["report"])
303
+ return {"cells": cells, "metadata": {"kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"}, "language_info": {"name": "python"}}, "nbformat": 4, "nbformat_minor": 5}
304
+
305
+
306
+ def next_run_number(runs_dir):
307
+ n = 0
308
+ try:
309
+ for name in os.listdir(runs_dir):
310
+ head = name.split("-", 1)[0]
311
+ if head.isdigit():
312
+ n = max(n, int(head))
313
+ except OSError:
314
+ pass
315
+ return n + 1
316
+
317
+
318
+ def now():
319
+ return time.strftime("%Y-%m-%dT%H:%M:%S")