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/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ """AskTim! - an AI helper for bioinformatics students.
2
+
3
+ At the command line::
4
+
5
+ AskTim! Claude # once: store an API key (asked for, not typed on the command line)
6
+ AskTim! "how do I sort a BAM file?"
7
+ AskTim! Agent "map the reads in data/ to ref.fa and count the mapped reads"
8
+
9
+ In a Jupyter or Colab notebook::
10
+
11
+ import asktim # then, in any cell:
12
+ AskTim! "why did my last cell fail?"
13
+ AskTim! Agent "load counts.csv and plot the library sizes"
14
+
15
+ AskTim! keeps your data out of the AI: it sends your question, the names of the programs
16
+ that are installed, your recent commands (with secrets removed) and descriptions of files
17
+ (format, size, columns) - not the data in them. `AskTim! privacy` says exactly what is sent.
18
+ """
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = ["ask", "agent", "load_ipython_extension", "unload_ipython_extension", "__version__"]
23
+
24
+
25
+ def ask(question, **options):
26
+ """Ask AskTim! a question (chat mode: it explains and suggests, and runs nothing).
27
+
28
+ In a notebook the answer is shown under the cell; elsewhere it is printed.
29
+ Returns the answer text.
30
+ """
31
+ from .api import ask as _ask
32
+
33
+ return _ask(question, **options)
34
+
35
+
36
+ def agent(task, mode="approve", **options):
37
+ """Give AskTim! Agent a task. mode: "approve" (default), "plan", "auto" or "script"."""
38
+ from .api import agent as _agent
39
+
40
+ return _agent(task, mode=mode, **options)
41
+
42
+
43
+ def load_ipython_extension(ipython):
44
+ """``%load_ext asktim`` - lets you type ``AskTim! ...`` in notebook cells."""
45
+ from .notebook import load
46
+
47
+ load(ipython)
48
+
49
+
50
+ def unload_ipython_extension(ipython):
51
+ from .notebook import unload
52
+
53
+ unload(ipython)
54
+
55
+
56
+ def _autoload():
57
+ # `import asktim` in a notebook is enough: register the extension when IPython is running.
58
+ try:
59
+ import sys
60
+
61
+ if "IPython" not in sys.modules:
62
+ return
63
+ from IPython import get_ipython
64
+
65
+ ip = get_ipython()
66
+ if ip is not None:
67
+ load_ipython_extension(ip)
68
+ except Exception: # never break an import because of the notebook integration
69
+ pass
70
+
71
+
72
+ _autoload()
asktim/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """python -m asktim - the same as the AskTim! command."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
asktim/agent.py ADDED
@@ -0,0 +1,490 @@
1
+ """AskTim! Agent: the model works through tools, one step at a time, with the student watching.
2
+
3
+ The ways of working are those of the AI agents practical:
4
+
5
+ approve (default) nothing runs until the student allows it; they can change or refuse a step
6
+ plan the agent writes a plan first; the student approves it (or asks for changes), then it works
7
+ auto the agent works alone; the student watches and can press Ctrl+C
8
+ script the agent writes one script and gets it to run
9
+
10
+ Whatever the mode, AskTim! - not the model - decides what may run (safety.py), runs it
11
+ (runner.py, in a sandbox where possible), decides what the model may see of the output
12
+ (privacy.py), and writes the record of the run (records.py).
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ import time
19
+
20
+ from . import config as _config
21
+ from . import context, fileinfo, history, inventory, logbook, paths, privacy, prompts, records, runner, safety, viewers
22
+ from .providers import Conversation, ProviderError, ToolResult
23
+
24
+ QUESTION_END = re.compile(r"\?\s*(\*\*|_|\))?\s*$")
25
+
26
+
27
+ class Stop(Exception):
28
+ """The student stopped the run."""
29
+
30
+
31
+ class Agent(object):
32
+ def __init__(self, cfg, provider, ui, task, mode="approve", here=False, allow_network=None, max_steps=None, timeout=None,
33
+ script_name="analysis.sh", notebook=None, student_dir=None):
34
+ self.cfg = cfg
35
+ self.provider = provider
36
+ self.ui = ui
37
+ self.task = task.strip()
38
+ self.mode = mode if mode in ("approve", "plan", "auto", "script") else "approve"
39
+ self.here = here
40
+ self.allow_network = bool(cfg.get("agent.allow_network")) if allow_network is None else bool(allow_network)
41
+ if cfg.is_locked("agent.allow_network"):
42
+ self.allow_network = bool(cfg.get("agent.allow_network"))
43
+ self.max_steps = self._limit(cfg, "agent.max_steps", max_steps, 25)
44
+ self.timeout = self._limit(cfg, "agent.command_timeout", timeout, 600)
45
+ self.out_chars = int(cfg.get("agent.output_chars") or 4000)
46
+ self.script_name = script_name
47
+ self.nb = notebook # the notebook side (notebook.NotebookTools), or None at the command line
48
+ self.strict = cfg.strict
49
+ self.student_dir = os.path.realpath(student_dir or os.getcwd())
50
+ self.ask_each = self.mode == "approve"
51
+ self.withheld = 0
52
+ self.steps = []
53
+ self.models = []
54
+
55
+ # -- set-up ---------------------------------------------------------------------------------
56
+
57
+ def _prepare(self):
58
+ runs_dir = os.path.join(self.student_dir, self.cfg.get("agent.runs_dir") or "asktim-runs")
59
+ n = records.next_run_number(runs_dir)
60
+ self.number = n
61
+ self.record_dir = os.path.join(runs_dir, "%d-%s" % (n, self.mode))
62
+ paths.ensure(self.record_dir)
63
+ self.work_dir = self.student_dir if self.here else self.record_dir
64
+ self.sandbox, why_not = (None, "you asked the agent to work in your folder (--here)") if self.here else runner.make_sandbox(
65
+ self.cfg.get("agent.sandbox") or "auto", self.work_dir, self.student_dir, self.allow_network)
66
+ self.sandbox_why = why_not
67
+ self.sandbox_note = self.sandbox.describe() if self.sandbox else "no sandbox (%s): AskTim! checks each command, and reports files that change outside the agent's folder" % why_not
68
+ self.protect = None
69
+ if self.here:
70
+ self.sandbox_note = "no sandbox: the agent works in your folder (--here); AskTim! checks each command and asks before it changes a file that is already there"
71
+ snap = runner.snapshot(self.student_dir, self.record_dir)
72
+ self.protect = set(snap) if snap is not None else True
73
+
74
+ def _rel(self, p):
75
+ try:
76
+ r = os.path.relpath(p, self.work_dir)
77
+ except ValueError:
78
+ return p
79
+ return r if not r.startswith("../../../..") else paths.pretty(p)
80
+
81
+ def _first_message(self):
82
+ g = context.Gathered()
83
+ task, _n, pasted = privacy.clean_question(self.task, strict=self.strict) # data pasted into the task are withheld too
84
+ self.withheld += pasted
85
+ lines = ["The student's task:", task, ""]
86
+ listing = fileinfo.listing(self.student_dir, max_entries=60, strict=self.strict)
87
+ txt, n = privacy.clean(listing, strict=self.strict)
88
+ lines += ["The files in the student's folder (%s, which is %s from your folder):" % (paths.pretty(self.student_dir), self._rel(self.student_dir) or "."), txt, ""]
89
+ # files that the task names: describe their structure
90
+ for word in re.findall(r"[\w./~\-]+\.[A-Za-z0-9]{1,8}(?:\.gz)?", self.task):
91
+ for base in (self.student_dir, self.work_dir):
92
+ p = os.path.join(base, os.path.expanduser(word))
93
+ if os.path.exists(p) and not os.path.isdir(p):
94
+ d, _ = privacy.clean(fileinfo.describe(p, strict=self.strict, base=self.work_dir), strict=self.strict)
95
+ lines.append("About a file the task names: " + d)
96
+ break
97
+ n_hist = self.cfg.get("history_lines")
98
+ n_hist = 10 if n_hist is None else min(10, int(n_hist))
99
+ if self.cfg.get("send_history", True) and n_hist > 0:
100
+ cmds, _src = history.recent(n_hist)
101
+ if cmds:
102
+ lines += ["", "The student's last shell commands (for context; oldest first):"]
103
+ for c in cmds:
104
+ t, _ = privacy.clean(c.line, strict=self.strict)
105
+ lines.append(" $ %s%s" % (t, " [exit %d]" % c.status if c.status else ""))
106
+ lines += ["", viewers.describe()]
107
+ if self.nb is not None:
108
+ lines += ["", self.nb.state_text()]
109
+ if self.mode == "plan":
110
+ lines += ["", "Write your plan now (no tool calls)."]
111
+ return "\n".join(lines)
112
+
113
+ # -- the run --------------------------------------------------------------------------------
114
+
115
+ @staticmethod
116
+ def _limit(cfg, name, asked, default):
117
+ """A limit from --steps/--timeout, never above the course's value when the course has locked it."""
118
+ base = int(cfg.get(name) or default)
119
+ try:
120
+ asked = int(asked) if asked else None
121
+ except (TypeError, ValueError):
122
+ asked = None
123
+ if asked is None or asked < 1:
124
+ return base
125
+ return min(asked, base) if cfg.is_locked(name) else asked
126
+
127
+ def run(self):
128
+ self._prepare()
129
+ if (self.cfg.get("agent.sandbox") or "auto") == "on" and self.sandbox is None:
130
+ # the course requires the sandbox: without it, the agent does not start
131
+ why = "--here works in your folder without one" if self.here else self.sandbox_why
132
+ self.ui.error("The agent can only run in its sandbox here (the settings say \"sandbox\": \"on\"), and there is none: %s." % why)
133
+ for d in (self.record_dir, os.path.dirname(self.record_dir)):
134
+ try:
135
+ os.rmdir(d) # only if empty
136
+ except OSError:
137
+ pass
138
+ return {"outcome": "no sandbox", "steps": [], "task": self.task, "mode": self.mode}
139
+ inv = inventory.gather()
140
+ inv_lines = inventory.describe(inv, notebook_packages=self.nb.packages() if self.nb is not None else None)
141
+ system = prompts.agent_system(inv_lines, self.cfg, self.mode, self._rel(self.work_dir) or ".", self._rel(self.student_dir) or ".",
142
+ notebook=self.nb is not None, sandbox_note=(self.sandbox_note + ".") if self.sandbox else "", script_name=self.script_name)
143
+ tools = prompts.tool_specs(notebook=self.nb is not None)
144
+ self.conv = Conversation()
145
+ self.conv.user(self._first_message())
146
+ rec = {
147
+ "number": self.number, "mode": self.mode, "task": self.task, "started": records.now(), "work_dir": self.work_dir,
148
+ "work_dir_shown": paths.pretty(self.work_dir), "student_dir": paths.pretty(self.student_dir), "here": self.here,
149
+ "sandbox": self.sandbox_note, "allow_network": self.allow_network, "privacy": self.cfg.get("privacy"),
150
+ "provider": self.provider.name, "steps": self.steps, "notebook": self.nb is not None,
151
+ }
152
+ self.ui.start({"number": self.number, "mode": self.mode, "task": self.task, "folder": paths.pretty(self.work_dir),
153
+ "sandbox": self.sandbox_note, "model": self.provider.describe(), "network": self.allow_network, "max_steps": self.max_steps})
154
+ outcome = "done"
155
+ report = ""
156
+ try:
157
+ if self.mode == "plan":
158
+ self._plan_phase(system, tools, rec)
159
+ report = self._loop(system, tools)
160
+ except Stop:
161
+ outcome = "stopped by the student"
162
+ report = "(The student stopped the run.)"
163
+ except KeyboardInterrupt:
164
+ outcome = "stopped by the student"
165
+ report = "(The student stopped the run with Ctrl+C.)"
166
+ except ProviderError as e:
167
+ outcome = "error"
168
+ report = "(The run ended because of an error of the AI service: %s)" % e
169
+ self.ui.error(str(e))
170
+ finally:
171
+ if self.sandbox is not None:
172
+ self.sandbox.cleanup()
173
+ if outcome == "done" and len(self.steps) >= self.max_steps:
174
+ outcome = "step limit reached"
175
+ rec.update({"ended": records.now(), "outcome": outcome, "report": report, "models": self.models, "withheld": self.withheld})
176
+ written = records.write(rec, self.record_dir)
177
+ if self.nb is not None:
178
+ self.nb.finish_run(rec)
179
+ self.ui.report(report, outcome)
180
+ self.ui.finish([paths.pretty(p) for p in written], rec)
181
+ logbook.add({"mode": "agent-" + self.mode, "question": privacy.clean(self.task, strict=self.strict)[0], "model": ", ".join(self.models), "provider": self.provider.name,
182
+ "outcome": outcome, "folder": paths.pretty(self.record_dir), "steps": len(self.steps), "cwd": paths.pretty(self.student_dir)}, self.cfg)
183
+ return rec
184
+
185
+ def _ask_model(self, system, tools):
186
+ self.ui.thinking()
187
+ turn = self.provider.complete(system, self.conv, tools=tools, purpose="agent", on_text=self.ui.stream_text, on_status=self.ui.status)
188
+ self.ui.end_text()
189
+ if turn.tool_calls:
190
+ self.ui.agent_says(turn.text)
191
+ if turn.model and turn.model not in self.models:
192
+ self.models.append(turn.model)
193
+ self.conv.assistant(turn)
194
+ return turn
195
+
196
+ def _plan_phase(self, system, tools, rec):
197
+ rec["plan_rounds"] = []
198
+ rec["plan_feedback"] = []
199
+ nudges = 0
200
+ while True:
201
+ turn = self._ask_model(system, tools)
202
+ if turn.tool_calls:
203
+ nudges += 1
204
+ self.conv.results([ToolResult(c.id, c.name, "Not run: write the plan first. Tools can be used once the student has approved it.", True) for c in turn.tool_calls],
205
+ text="Send the plan now, without tool calls." if nudges < 3 else None)
206
+ if nudges >= 3:
207
+ raise ProviderError("The model kept calling tools instead of writing a plan.", kind="other")
208
+ continue
209
+ plan = turn.text.strip()
210
+ rec["plan"] = plan
211
+ rec["plan_rounds"].append(plan)
212
+ choice, feedback = self.ui.plan_review(plan)
213
+ if choice == "cancel":
214
+ raise Stop()
215
+ if choice == "change":
216
+ rec["plan_feedback"].append(feedback)
217
+ self.conv.user("The student asks for changes to the plan: %s\nSend the whole plan again, changed, without tool calls." % feedback)
218
+ continue
219
+ self.ask_each = choice == "approve-steps"
220
+ self.conv.user("The student approved the plan%s. Carry it out now, step by step." % (" and will approve each step" if self.ask_each else ""))
221
+ return
222
+
223
+ def _loop(self, system, tools):
224
+ asked_for_script = False
225
+ nudges = 0
226
+ while True:
227
+ if len(self.steps) >= self.max_steps:
228
+ self.conv.user("You have used all %d steps. Write your report now, without tool calls: what you did, the files you made, the result as far as "
229
+ "you know it, and what is not finished." % self.max_steps)
230
+ turn = self._ask_model(system, tools)
231
+ if turn.tool_calls:
232
+ self.conv.results([ToolResult(c.id, c.name, "Not run: the step limit is reached.", True) for c in turn.tool_calls], text="Write the report now.")
233
+ turn = self._ask_model(system, tools)
234
+ return turn.text
235
+ turn = self._ask_model(system, tools)
236
+ if not turn.tool_calls:
237
+ if turn.stop_reason == "max_tokens" and nudges < 2:
238
+ nudges += 1
239
+ self.conv.user("Your reply was cut off (it was too long). Go on, in shorter steps.")
240
+ continue
241
+ if turn.stop_reason == "malformed" and nudges < 2:
242
+ nudges += 1
243
+ self.conv.user("Your last tool call could not be read. Send it again.")
244
+ continue
245
+ if self.mode == "script" and not asked_for_script and not os.path.exists(os.path.join(self.work_dir, self.script_name)) and len(self.steps) < self.max_steps - 1:
246
+ asked_for_script = True
247
+ self.conv.user("There is no %s in your folder. The student asked for one script that does the whole task. Write it now with write_file, "
248
+ "run it, and report when it has run without an error." % self.script_name)
249
+ continue
250
+ if QUESTION_END.search(turn.text or "") and self.ui.interactive and self.mode != "auto":
251
+ reply = self.ui.reply_to_question(turn.text)
252
+ if reply:
253
+ self.conv.user(reply)
254
+ continue
255
+ return turn.text
256
+ nudges = 0
257
+ results = []
258
+ for call in turn.tool_calls:
259
+ if len(self.steps) >= self.max_steps:
260
+ results.append(ToolResult(call.id, call.name, "Not run: the step limit is reached.", True))
261
+ continue
262
+ results.append(self._handle(call))
263
+ left = self.max_steps - len(self.steps)
264
+ note = "(%d step%s left.)" % (left, "" if left == 1 else "s") if 0 < left <= 3 else None
265
+ self.conv.results(results, text=note)
266
+
267
+ # -- one tool call ------------------------------------------------------------------------
268
+
269
+ def _handle(self, call):
270
+ res = self._handle_inner(call)
271
+ # a last line of defence: nothing goes back to the model without the identity and secret cleaning
272
+ res.content, _ = privacy.clean(res.content or "", strict=self.strict)
273
+ return res
274
+
275
+ def _handle_inner(self, call):
276
+ n = len(self.steps) + 1
277
+ step = {"n": n, "tool": call.name, "why": str(call.input.get("why") or "").strip(), "input": {k: v for k, v in call.input.items() if k not in ("content", "code")}}
278
+ self.steps.append(step)
279
+ if "_incomplete" in call.input:
280
+ step["decision"] = "blocked"
281
+ step["blocked"] = ["the request was cut off"]
282
+ self.ui.warn("The agent's request was cut off; it is asked to send it again.")
283
+ return ToolResult(call.id, call.name, "Your tool call was cut off before it was complete. Send it again (shorter).", True)
284
+ try:
285
+ if call.name == "run_command":
286
+ return self._run_command(call, step)
287
+ if call.name == "write_file":
288
+ return self._write_file(call, step)
289
+ if call.name == "inspect_file":
290
+ return self._inspect(call, step)
291
+ if call.name == "open_file":
292
+ return self._open(call, step)
293
+ if self.nb is not None and call.name in ("run_python", "describe_variable", "add_markdown_cell", "add_code_cell"):
294
+ return self.nb.handle(self, call, step)
295
+ except Stop:
296
+ raise
297
+ step["decision"] = "blocked"
298
+ step["blocked"] = ["unknown tool"]
299
+ return ToolResult(call.id, call.name, "There is no tool called %s." % call.name, True)
300
+
301
+ def decide(self, step, kind, verdict, show):
302
+ """Ask the student when needed. Returns (decision, new_text_or_None, comment)."""
303
+ if verdict is not None and verdict.level == "block":
304
+ step["decision"] = "blocked"
305
+ step["blocked"] = list(verdict.reasons)
306
+ self.ui.blocked(step, verdict)
307
+ return "blocked", None, None
308
+ must_ask = self.ask_each or (verdict is not None and verdict.level == "confirm") or kind == "open"
309
+ if not must_ask:
310
+ self.ui.show_step(step, kind, show, verdict, asking=False)
311
+ step["decision"] = "auto"
312
+ return "auto", None, None
313
+ if not self.ui.interactive:
314
+ step["decision"] = "refuse"
315
+ step["comment"] = "nobody could be asked (no terminal)"
316
+ return "refuse", None, "Nobody is at the keyboard to approve this step, so it was not run."
317
+ d = self.ui.approve(step, kind, show, verdict)
318
+ if d.choice == "stop":
319
+ raise Stop()
320
+ if d.choice == "all":
321
+ self.ask_each = False
322
+ step["decision"] = "all"
323
+ return "run", None, d.comment
324
+ step["decision"] = {"run": "run", "edit": "edit", "refuse": "refuse"}[d.choice]
325
+ if d.comment:
326
+ step["comment"] = d.comment
327
+ return d.choice, d.text, d.comment
328
+
329
+ def _run_command(self, call, step):
330
+ cmd = str(call.input.get("command") or "").replace("\r\n", "\n").strip()
331
+ step["command"] = cmd
332
+ verdict = safety.check(cmd, self.work_dir, allow_network=self.allow_network, student_dir=self.student_dir, protect=self.protect)
333
+ decision, new, comment = self.decide(step, "command", verdict, cmd)
334
+ if decision == "blocked":
335
+ return ToolResult(call.id, call.name, "Not run: AskTim! does not allow this command – %s." % "; ".join(verdict.reasons), True)
336
+ if decision == "refuse":
337
+ return ToolResult(call.id, call.name, "Not run: the student refused this step." + (" Their reason: %s" % comment if comment else ""), True)
338
+ prefix = ""
339
+ if decision == "edit" and new is not None and new.strip() != cmd:
340
+ step["original"] = cmd
341
+ cmd = new.strip()
342
+ step["command"] = cmd
343
+ verdict = safety.check(cmd, self.work_dir, allow_network=self.allow_network, student_dir=self.student_dir, protect=self.protect)
344
+ if verdict.level == "block":
345
+ step["decision"] = "blocked"
346
+ step["blocked"] = list(verdict.reasons)
347
+ self.ui.blocked(step, verdict)
348
+ return ToolResult(call.id, call.name, "The student changed the command, but AskTim! does not allow the new one either – %s." % "; ".join(verdict.reasons), True)
349
+ prefix = "The student changed the command before it ran; this ran instead:\n%s\n" % cmd + ("Their comment: %s\n" % comment if comment else "")
350
+ elif comment:
351
+ prefix = "The student allowed this step, with a comment: %s\n" % comment
352
+ before = None if self.sandbox else runner.snapshot(self.student_dir, self.record_dir)
353
+ self.ui.running(step)
354
+ res = runner.run(cmd, self.work_dir, timeout=self.timeout, sandbox=self.sandbox, on_output=self.ui.output)
355
+ if res.interrupted:
356
+ step["interrupted"] = True
357
+ if self.ui.ask_stop():
358
+ step["exit"] = res.exit_code
359
+ raise Stop()
360
+ after = None if before is None else runner.snapshot(self.student_dir, self.record_dir)
361
+ ch = runner.changes(before, after)
362
+ step.update({"exit": res.exit_code, "seconds": round(res.duration, 2), "timed_out": res.timed_out, "lines": res.lines})
363
+ raw = res.text()
364
+ step["output_tail"] = privacy.mask_identity(res.last_lines(30))
365
+ fr = privacy.filter_output(raw, kind=verdict.output_kind, strict=self.strict)
366
+ self.withheld += fr.withheld
367
+ step["withheld"] = fr.withheld
368
+ body = privacy.shorten(fr.text, self.out_chars)
369
+ parts = [prefix + "exit status %s (%.1f s, %d line%s of output%s)" % (res.exit_code, res.duration, res.lines, "" if res.lines == 1 else "s",
370
+ "; %d withheld as data" % fr.withheld if fr.withheld else "")]
371
+ if res.error:
372
+ parts.append(res.error)
373
+ if res.timed_out:
374
+ parts.append("The command was stopped: it ran longer than %d seconds. Work on less at a time, or split the work into steps." % self.timeout)
375
+ if res.interrupted:
376
+ parts.append("The student stopped this command with Ctrl+C.")
377
+ if body.strip():
378
+ parts.append("Output (stdout and stderr together):\n" + body)
379
+ else:
380
+ parts.append("It printed nothing.")
381
+ if ch and self.here:
382
+ # in the student's folder, new files are expected; changes to their own files are reported
383
+ own = [paths.pretty(p) for p in ch["changed"] + ch["deleted"]]
384
+ if own:
385
+ step["outside_changes"] = own
386
+ parts.append("Note: this step changed or deleted files that were already in the student's folder: %s." % ", ".join(own[:10]))
387
+ self.ui.warn("This step changed or deleted files that were already in your folder: %s" % ", ".join(own[:6]))
388
+ elif ch:
389
+ outside = [paths.pretty(p) for p in ch["created"] + ch["changed"] + ch["deleted"]]
390
+ if outside:
391
+ step["outside_changes"] = outside
392
+ parts.append("Warning: files outside your folder changed during this step: %s. Write only inside your folder." % ", ".join(outside[:10]))
393
+ self.ui.warn("Files outside the agent's folder changed during this step: %s" % ", ".join(outside[:6]))
394
+ if verdict.notes:
395
+ parts.append("Note: " + "; ".join(verdict.notes))
396
+ sent = "\n".join(parts)
397
+ step["sent"] = sent
398
+ self.ui.result(step, res, fr)
399
+ return ToolResult(call.id, call.name, sent, res.exit_code != 0)
400
+
401
+ def _write_file(self, call, step):
402
+ path = str(call.input.get("path") or "").strip()
403
+ content = call.input.get("content")
404
+ if not isinstance(content, str):
405
+ content = "" if content is None else json.dumps(content, indent=2)
406
+ step["path"] = path
407
+ step["content"] = content
408
+ verdict, full = safety.check_file_write(path, self.work_dir, content, student_dir=None if self.here else self.student_dir, protect=self.protect)
409
+ decision, new, comment = self.decide(step, "file", verdict, content)
410
+ if decision == "blocked":
411
+ return ToolResult(call.id, call.name, "Not written: %s." % "; ".join(verdict.reasons), True)
412
+ if decision == "refuse":
413
+ return ToolResult(call.id, call.name, "Not written: the student refused this step." + (" Their reason: %s" % comment if comment else ""), True)
414
+ if decision == "edit" and new is not None:
415
+ step["original"] = "(the file as the agent wrote it)"
416
+ content = new
417
+ step["content"] = content
418
+ try:
419
+ os.makedirs(os.path.dirname(full) or ".", exist_ok=True)
420
+ existed = os.path.exists(full)
421
+ with open(full, "w", encoding="utf-8") as f:
422
+ f.write(content)
423
+ if full.endswith((".sh", ".bash")):
424
+ os.chmod(full, 0o755)
425
+ except OSError as e:
426
+ return ToolResult(call.id, call.name, "Could not write %s: %s" % (path, e), True)
427
+ step["written"] = True
428
+ lines = content.count("\n") + (0 if content.endswith("\n") or not content else 1)
429
+ msg = "%s %s (%d line%s, %d bytes)." % ("Replaced" if existed else "Wrote", self._rel(full), lines, "" if lines == 1 else "s", len(content.encode("utf-8")))
430
+ if decision == "edit":
431
+ msg = "The student changed the file before it was written. " + msg + " It now holds:\n" + privacy.shorten(content, 3000)
432
+ if comment:
433
+ msg += " The student's comment: %s" % comment
434
+ if verdict.notes:
435
+ msg += " Note: " + "; ".join(verdict.notes)
436
+ step["sent"] = msg
437
+ self.ui.note(" " + msg.split(" It now holds")[0])
438
+ return ToolResult(call.id, call.name, msg)
439
+
440
+ def _resolve_read(self, path):
441
+ p = os.path.expanduser(path)
442
+ if not os.path.isabs(p):
443
+ p = os.path.join(self.work_dir, p)
444
+ p = os.path.realpath(p)
445
+ ctx = safety.Context(self.work_dir, student_dir=self.student_dir)
446
+ return p, safety._sensitive(p, ctx)
447
+
448
+ def _inspect(self, call, step):
449
+ path = str(call.input.get("path") or "").strip()
450
+ p, sens = self._resolve_read(path)
451
+ step["path"] = path
452
+ if sens:
453
+ step["decision"] = "blocked"
454
+ step["blocked"] = ["%s holds credentials or private history" % sens]
455
+ return ToolResult(call.id, call.name, "Not allowed: %s holds credentials or private history." % sens, True)
456
+ desc = fileinfo.describe(p, strict=self.strict, base=self.work_dir)
457
+ desc, _ = privacy.clean(desc, strict=self.strict)
458
+ step["decision"] = "auto"
459
+ step["sent"] = desc
460
+ self.ui.inspected(step, desc)
461
+ return ToolResult(call.id, call.name, desc)
462
+
463
+ def _open(self, call, step):
464
+ path = str(call.input.get("path") or "").strip()
465
+ program = str(call.input.get("program") or "").strip() or None
466
+ p, sens = self._resolve_read(path)
467
+ step["path"] = path
468
+ if program:
469
+ step["program"] = program
470
+ if sens:
471
+ step["decision"] = "blocked"
472
+ step["blocked"] = ["%s holds credentials" % sens]
473
+ return ToolResult(call.id, call.name, "Not allowed.", True)
474
+ if not os.path.exists(p):
475
+ return ToolResult(call.id, call.name, "There is no file %s." % path, True)
476
+ if program:
477
+ argv, why_not = viewers.find(program)
478
+ shows, no_screen = viewers.can_show_windows()
479
+ if argv is None or not shows:
480
+ return ToolResult(call.id, call.name, "Cannot open it in %s: %s. Installed programs with windows: %s." % (
481
+ program, why_not or no_screen, ", ".join(viewers.installed()) or "none"), True)
482
+ show = paths.pretty(p) + (" in %s" % program if program else "")
483
+ decision, _new, comment = self.decide(step, "open", None, show)
484
+ if decision in ("refuse", "blocked"):
485
+ return ToolResult(call.id, call.name, "Not opened: the student said no." + (" Their reason: %s" % comment if comment else ""), True)
486
+ ok, how = self.ui.open_file(p, program=program)
487
+ step["exit"] = 0 if ok else 1
488
+ msg = ("Opened %s for the student (%s). Nothing of it was sent to you." % (self._rel(p), how)) if ok else ("Could not open it: %s" % how)
489
+ step["sent"] = msg
490
+ return ToolResult(call.id, call.name, msg, not ok)
asktim/api.py ADDED
@@ -0,0 +1,41 @@
1
+ """asktim.ask() and asktim.agent() for scripts and notebooks."""
2
+
3
+ from . import config as _config
4
+
5
+
6
+ def _in_notebook():
7
+ try:
8
+ from IPython import get_ipython
9
+
10
+ ip = get_ipython()
11
+ return ip is not None and getattr(ip, "kernel", None) is not None
12
+ except Exception:
13
+ return False
14
+
15
+
16
+ def ask(question, **options):
17
+ if _in_notebook():
18
+ from .notebook import nb_ask
19
+
20
+ return nb_ask(question, **options)
21
+ from . import chat
22
+ from .ui import TerminalUI
23
+
24
+ cfg = _config.Config()
25
+ return chat.ask(cfg, TerminalUI(cfg), question, files=options.get("files", ()), new=options.get("new", False), model=options.get("model"))
26
+
27
+
28
+ def agent(task, mode="approve", **options):
29
+ if _in_notebook():
30
+ from .notebook import nb_agent
31
+
32
+ return nb_agent(task, mode=mode, **options)
33
+ from .agent import Agent
34
+ from .providers import make_provider
35
+ from .ui import TerminalUI
36
+
37
+ cfg = _config.Config()
38
+ ui = TerminalUI(cfg)
39
+ ag = Agent(cfg, make_provider(cfg, model=options.get("model")), ui, task, mode=mode, here=options.get("here", False),
40
+ allow_network=options.get("web"), max_steps=options.get("steps"), timeout=options.get("timeout"))
41
+ return ag.run()