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 +72 -0
- asktim/__main__.py +6 -0
- asktim/agent.py +490 -0
- asktim/api.py +41 -0
- asktim/chat.py +106 -0
- asktim/cli.py +577 -0
- asktim/config.py +316 -0
- asktim/context.py +156 -0
- asktim/fileinfo.py +593 -0
- asktim/history.py +214 -0
- asktim/inventory.py +379 -0
- asktim/logbook.py +159 -0
- asktim/net.py +151 -0
- asktim/notebook.py +1010 -0
- asktim/offline.py +110 -0
- asktim/paths.py +81 -0
- asktim/privacy.py +804 -0
- asktim/prompts.py +226 -0
- asktim/providers/__init__.py +173 -0
- asktim/providers/anthropic.py +227 -0
- asktim/providers/gemini.py +215 -0
- asktim/providers/openai.py +135 -0
- asktim/records.py +319 -0
- asktim/render.py +511 -0
- asktim/runner.py +308 -0
- asktim/safety.py +1495 -0
- asktim/shell_setup.py +183 -0
- asktim/ui.py +303 -0
- asktim/viewers.py +97 -0
- asktim-0.1.0.data/scripts/AskTim! +8 -0
- asktim-0.1.0.dist-info/METADATA +458 -0
- asktim-0.1.0.dist-info/RECORD +36 -0
- asktim-0.1.0.dist-info/WHEEL +5 -0
- asktim-0.1.0.dist-info/entry_points.txt +2 -0
- asktim-0.1.0.dist-info/licenses/LICENSE +21 -0
- asktim-0.1.0.dist-info/top_level.txt +1 -0
asktim/shell_setup.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""`AskTim! setup-shell`: a few lines in ~/.bashrc, ~/.zshrc or fish's config.
|
|
2
|
+
|
|
3
|
+
They do two things, and nothing else:
|
|
4
|
+
- after each command, append "time, exit status, folder, command" to
|
|
5
|
+
~/.local/state/asktim/commands.tsv, so that AskTim! sees your latest commands and knows
|
|
6
|
+
which one failed (the output of commands is never recorded);
|
|
7
|
+
- Alt+A puts the next command from AskTim!'s last answer on your command line, for you to
|
|
8
|
+
read, change and run yourself (bash and zsh);
|
|
9
|
+
- in zsh, ? and * in a question are not read as wildcards, so questions need no quotes.
|
|
10
|
+
|
|
11
|
+
`AskTim! setup-shell --remove` takes the lines out again.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
from . import paths
|
|
18
|
+
|
|
19
|
+
BEGIN = "# >>> AskTim! shell integration >>>"
|
|
20
|
+
END = "# <<< AskTim! shell integration <<<"
|
|
21
|
+
|
|
22
|
+
BASH = r'''# >>> AskTim! shell integration >>>
|
|
23
|
+
# AskTim! sees the commands you type (never their output) and which ones failed.
|
|
24
|
+
# A command that starts with a space is not recorded.
|
|
25
|
+
# Alt+A puts the next command from AskTim!'s last answer on your command line.
|
|
26
|
+
# To turn this off: AskTim! setup-shell --remove (or delete these lines)
|
|
27
|
+
if [ -n "$BASH_VERSION" ] && [ -z "$__ASKTIM_HOOKED" ]; then
|
|
28
|
+
__ASKTIM_HOOKED=1
|
|
29
|
+
__asktim_log="${ASKTIM_HOME:+$ASKTIM_HOME/state}"; __asktim_log="${__asktim_log:-${XDG_STATE_HOME:-$HOME/.local/state}/asktim}/commands.tsv"
|
|
30
|
+
__asktim_last_n=""
|
|
31
|
+
__asktim_prompt() {
|
|
32
|
+
local s=$? h n c
|
|
33
|
+
h=$(HISTTIMEFORMAT= builtin history 1 2>/dev/null)
|
|
34
|
+
h="${h#"${h%%[![:space:]]*}"}"; n="${h%%[[:space:]]*}"; c="${h#"$n"}"; c="${c#"${c%%[![:space:]]*}"}"
|
|
35
|
+
if [ -n "$c" ] && [ "$n" != "$__asktim_last_n" ]; then
|
|
36
|
+
__asktim_last_n=$n
|
|
37
|
+
c=${c//$'\t'/ }; c=${c//$'\n'/$'\x1e'}
|
|
38
|
+
if [ "${BASH_VERSINFO[0]}" -ge 4 ] 2>/dev/null; then
|
|
39
|
+
printf '%(%s)T\t%s\t%s\t%s\n' -1 "$s" "$PWD" "$c" >> "$__asktim_log" 2>/dev/null
|
|
40
|
+
else
|
|
41
|
+
printf '%s\t%s\t%s\t%s\n' "$(date +%s)" "$s" "$PWD" "$c" >> "$__asktim_log" 2>/dev/null
|
|
42
|
+
fi
|
|
43
|
+
fi
|
|
44
|
+
return $s
|
|
45
|
+
}
|
|
46
|
+
case ";${PROMPT_COMMAND:-};" in *";__asktim_prompt;"*) ;; *) PROMPT_COMMAND="__asktim_prompt${PROMPT_COMMAND:+;$PROMPT_COMMAND}";; esac
|
|
47
|
+
__asktim_insert() {
|
|
48
|
+
local f="${ASKTIM_HOME:+$ASKTIM_HOME/cache}"; f="${f:-${XDG_CACHE_HOME:-$HOME/.cache}/asktim}/suggested.txt"
|
|
49
|
+
[ -s "$f" ] || return 0
|
|
50
|
+
local i=0 line idxf="$f.next"; [ -s "$idxf" ] && i=$(cat "$idxf")
|
|
51
|
+
line=$(sed -n "$((i + 1))p" "$f")
|
|
52
|
+
[ -z "$line" ] && { i=0; line=$(sed -n '1p' "$f"); }
|
|
53
|
+
echo $((i + 1)) > "$idxf"
|
|
54
|
+
READLINE_LINE="$line"; READLINE_POINT=${#line}
|
|
55
|
+
}
|
|
56
|
+
[[ $- == *i* ]] && [ "${BASH_VERSINFO[0]}" -ge 4 ] 2>/dev/null && bind -x '"\ea": __asktim_insert' 2>/dev/null
|
|
57
|
+
fi
|
|
58
|
+
# <<< AskTim! shell integration <<<
|
|
59
|
+
'''
|
|
60
|
+
|
|
61
|
+
ZSH = r'''# >>> AskTim! shell integration >>>
|
|
62
|
+
# AskTim! sees the commands you type (never their output) and which ones failed.
|
|
63
|
+
# A command that starts with a space is not recorded.
|
|
64
|
+
# Alt+A puts the next command from AskTim!'s last answer on your command line.
|
|
65
|
+
# To turn this off: AskTim! setup-shell --remove (or delete these lines)
|
|
66
|
+
if [ -n "$ZSH_VERSION" ] && [ -z "$__ASKTIM_HOOKED" ]; then
|
|
67
|
+
typeset -g __ASKTIM_HOOKED=1
|
|
68
|
+
typeset -g __asktim_log="${ASKTIM_HOME:+$ASKTIM_HOME/state}"; __asktim_log="${__asktim_log:-${XDG_STATE_HOME:-$HOME/.local/state}/asktim}/commands.tsv"
|
|
69
|
+
typeset -g __asktim_cmd=""
|
|
70
|
+
zmodload zsh/datetime 2>/dev/null
|
|
71
|
+
__asktim_preexec() { [[ "$1" == " "* ]] && __asktim_cmd="" || __asktim_cmd="$1" }
|
|
72
|
+
__asktim_precmd() {
|
|
73
|
+
local s=$?
|
|
74
|
+
if [[ -n "$__asktim_cmd" ]]; then
|
|
75
|
+
local c="${__asktim_cmd//$'\t'/ }"; c="${c//$'\n'/$'\x1e'}"
|
|
76
|
+
print -r -- "${EPOCHSECONDS:-0}"$'\t'"$s"$'\t'"$PWD"$'\t'"$c" >> "$__asktim_log" 2>/dev/null
|
|
77
|
+
__asktim_cmd=""
|
|
78
|
+
fi
|
|
79
|
+
return $s
|
|
80
|
+
}
|
|
81
|
+
autoload -Uz add-zsh-hook
|
|
82
|
+
add-zsh-hook preexec __asktim_preexec
|
|
83
|
+
add-zsh-hook precmd __asktim_precmd
|
|
84
|
+
__asktim_insert() {
|
|
85
|
+
local f="${ASKTIM_HOME:+$ASKTIM_HOME/cache}"; f="${f:-${XDG_CACHE_HOME:-$HOME/.cache}/asktim}/suggested.txt"
|
|
86
|
+
[[ -s "$f" ]] || return 0
|
|
87
|
+
local i=0 line idxf="$f.next"; [[ -s "$idxf" ]] && i=$(<"$idxf")
|
|
88
|
+
line=$(sed -n "$((i + 1))p" "$f")
|
|
89
|
+
[[ -z "$line" ]] && { i=0; line=$(sed -n '1p' "$f"); }
|
|
90
|
+
print -r -- $((i + 1)) > "$idxf"
|
|
91
|
+
BUFFER="$line"; CURSOR=${#BUFFER}
|
|
92
|
+
}
|
|
93
|
+
zle -N __asktim_insert
|
|
94
|
+
bindkey '\ea' __asktim_insert
|
|
95
|
+
# questions need no quotes: zsh does not read ? and * in them as wildcards
|
|
96
|
+
alias 'AskTim!'='noglob AskTim!'
|
|
97
|
+
alias asktim='noglob asktim'
|
|
98
|
+
fi
|
|
99
|
+
# <<< AskTim! shell integration <<<
|
|
100
|
+
'''
|
|
101
|
+
|
|
102
|
+
FISH = r'''# >>> AskTim! shell integration >>>
|
|
103
|
+
# AskTim! sees the commands you type (never their output) and which ones failed.
|
|
104
|
+
# To turn this off: AskTim! setup-shell --remove (or delete this file)
|
|
105
|
+
set -l __asktim_state (set -q ASKTIM_HOME; and echo $ASKTIM_HOME/state; or begin; set -q XDG_STATE_HOME; and echo $XDG_STATE_HOME/asktim; or echo $HOME/.local/state/asktim; end)
|
|
106
|
+
set -g __asktim_log $__asktim_state/commands.tsv
|
|
107
|
+
function __asktim_postexec --on-event fish_postexec
|
|
108
|
+
set -l s $status
|
|
109
|
+
string match -q -r '^ ' -- $argv[1]; and return
|
|
110
|
+
set -l c (string join \x1e -- $argv[1] | string replace -a \t ' ')
|
|
111
|
+
printf '%s\t%s\t%s\t%s\n' (date +%s) $s $PWD "$c" >> $__asktim_log 2>/dev/null
|
|
112
|
+
end
|
|
113
|
+
# <<< AskTim! shell integration <<<
|
|
114
|
+
'''
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def rc_file(shell):
|
|
118
|
+
home = os.path.expanduser("~")
|
|
119
|
+
if shell == "zsh":
|
|
120
|
+
return os.path.join(os.environ.get("ZDOTDIR", home), ".zshrc")
|
|
121
|
+
if shell == "fish":
|
|
122
|
+
cfg = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
|
|
123
|
+
return os.path.join(cfg, "fish", "conf.d", "asktim.fish")
|
|
124
|
+
return os.path.join(home, ".bashrc")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def snippet(shell):
|
|
128
|
+
return {"zsh": ZSH, "fish": FISH}.get(shell, BASH)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _strip_block(text):
|
|
132
|
+
return re.sub(re.escape(BEGIN) + r".*?" + re.escape(END) + r"\n?", "", text, flags=re.S)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def install(shell):
|
|
136
|
+
"""Add (or update) the lines. Returns (file, already_there)."""
|
|
137
|
+
paths.ensure(paths.state_dir(), private=True)
|
|
138
|
+
paths.ensure(paths.cache_dir(), private=True)
|
|
139
|
+
f = rc_file(shell)
|
|
140
|
+
try:
|
|
141
|
+
with open(f, encoding="utf-8") as fh:
|
|
142
|
+
text = fh.read()
|
|
143
|
+
except FileNotFoundError:
|
|
144
|
+
text = ""
|
|
145
|
+
had = BEGIN in text
|
|
146
|
+
text = _strip_block(text)
|
|
147
|
+
if text and not text.endswith("\n"):
|
|
148
|
+
text += "\n"
|
|
149
|
+
text += ("\n" if text and not had else "") + snippet(shell)
|
|
150
|
+
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
|
|
151
|
+
with open(f, "w", encoding="utf-8") as fh:
|
|
152
|
+
fh.write(text)
|
|
153
|
+
# start the log, so that `AskTim! status` can tell the hook is there
|
|
154
|
+
log = paths.commands_log()
|
|
155
|
+
if not os.path.exists(log):
|
|
156
|
+
os.close(os.open(log, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)) # readable by you only, like your shell history
|
|
157
|
+
return f, had
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def remove(shell):
|
|
161
|
+
f = rc_file(shell)
|
|
162
|
+
try:
|
|
163
|
+
with open(f, encoding="utf-8") as fh:
|
|
164
|
+
text = fh.read()
|
|
165
|
+
except FileNotFoundError:
|
|
166
|
+
return f, False
|
|
167
|
+
if BEGIN not in text:
|
|
168
|
+
return f, False
|
|
169
|
+
new = _strip_block(text)
|
|
170
|
+
if shell == "fish" and not new.strip():
|
|
171
|
+
os.remove(f)
|
|
172
|
+
else:
|
|
173
|
+
with open(f, "w", encoding="utf-8") as fh:
|
|
174
|
+
fh.write(new)
|
|
175
|
+
return f, True
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def installed(shell):
|
|
179
|
+
try:
|
|
180
|
+
with open(rc_file(shell), encoding="utf-8") as fh:
|
|
181
|
+
return BEGIN in fh.read()
|
|
182
|
+
except OSError:
|
|
183
|
+
return False
|
asktim/ui.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""The command-line face of AskTim!: chat answers and the agent's steps."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from . import paths
|
|
10
|
+
from .render import Term, visible
|
|
11
|
+
|
|
12
|
+
MODE_LABEL = {"approve": "approve each step", "plan": "plan first", "auto": "autonomous", "script": "write a script"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Decision(object):
|
|
16
|
+
def __init__(self, choice, text=None, comment=None):
|
|
17
|
+
self.choice = choice # run | edit | refuse | all | stop
|
|
18
|
+
self.text = text
|
|
19
|
+
self.comment = comment
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TerminalUI(object):
|
|
23
|
+
def __init__(self, cfg=None, term=None, show_ai_view=True):
|
|
24
|
+
self.t = term or Term((cfg.get("color") if cfg else "auto") or "auto")
|
|
25
|
+
self.md = None
|
|
26
|
+
self.show_ai_view = show_ai_view
|
|
27
|
+
self._streamed = False
|
|
28
|
+
self._last_was_output = False
|
|
29
|
+
self.agent_mode = False # in agent runs the model's text is held until it is known what it is
|
|
30
|
+
self._held = []
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def interactive(self):
|
|
34
|
+
return self.t.interactive()
|
|
35
|
+
|
|
36
|
+
# -- general --------------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
def note(self, text):
|
|
39
|
+
self.t.note(text)
|
|
40
|
+
|
|
41
|
+
def warn(self, text):
|
|
42
|
+
self.t.warn(text)
|
|
43
|
+
|
|
44
|
+
def error(self, text):
|
|
45
|
+
self.t.error(text)
|
|
46
|
+
|
|
47
|
+
def status(self, text):
|
|
48
|
+
if self.md is not None and self._streamed:
|
|
49
|
+
self.t.write("\n")
|
|
50
|
+
self.t.note("… " + text)
|
|
51
|
+
|
|
52
|
+
# -- streaming text of the model ------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
def thinking(self):
|
|
55
|
+
self._held = []
|
|
56
|
+
self.md = None if self.agent_mode else self.t.markdown()
|
|
57
|
+
self._streamed = False
|
|
58
|
+
if self.t.color and self.t.interactive():
|
|
59
|
+
self.t.write(self.t.s("thinking…", "gray"))
|
|
60
|
+
self._thinking_shown = True
|
|
61
|
+
else:
|
|
62
|
+
self._thinking_shown = False
|
|
63
|
+
|
|
64
|
+
def _clear_thinking(self):
|
|
65
|
+
if getattr(self, "_thinking_shown", False):
|
|
66
|
+
self.t.write("\r\x1b[K")
|
|
67
|
+
self._thinking_shown = False
|
|
68
|
+
|
|
69
|
+
def stream_text(self, delta):
|
|
70
|
+
if not delta:
|
|
71
|
+
return
|
|
72
|
+
if self.agent_mode:
|
|
73
|
+
self._held.append(delta)
|
|
74
|
+
return
|
|
75
|
+
self._clear_thinking()
|
|
76
|
+
self._streamed = True
|
|
77
|
+
if self.md is None:
|
|
78
|
+
self.md = self.t.markdown()
|
|
79
|
+
self.md.feed(delta)
|
|
80
|
+
|
|
81
|
+
def end_text(self):
|
|
82
|
+
self._clear_thinking()
|
|
83
|
+
if self.md is not None:
|
|
84
|
+
self.md.close()
|
|
85
|
+
self.md = None
|
|
86
|
+
|
|
87
|
+
def agent_says(self, text):
|
|
88
|
+
"""What the model wrote before its tool calls: shown above the step."""
|
|
89
|
+
text = (text or "").strip()
|
|
90
|
+
if text:
|
|
91
|
+
md = self.t.markdown()
|
|
92
|
+
md.feed(text)
|
|
93
|
+
md.close()
|
|
94
|
+
|
|
95
|
+
# -- the agent ------------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
def start(self, info):
|
|
98
|
+
self.agent_mode = True
|
|
99
|
+
t = self.t
|
|
100
|
+
t.line()
|
|
101
|
+
t.rule("AskTim! Agent · run %d · %s" % (info["number"], MODE_LABEL.get(info["mode"], info["mode"])), "cyan")
|
|
102
|
+
t.line(t.s("Task: ", "bold") + info["task"])
|
|
103
|
+
t.note("Folder: %s · %s" % (info["folder"], info["model"]))
|
|
104
|
+
t.note("Safeguards: %s; internet %s; at most %d steps." % (info["sandbox"], "allowed for downloads" if info["network"] else "off", info["max_steps"]))
|
|
105
|
+
t.note("The AI never sees your data: what your commands print reaches it with data lines withheld. Ctrl+C stops at any time.")
|
|
106
|
+
t.line()
|
|
107
|
+
|
|
108
|
+
def _step_header(self, step, kind):
|
|
109
|
+
what = {"command": "run a command", "file": "write a file", "open": "open a file", "python": "run Python code", "cell": "add a cell"}.get(kind, kind)
|
|
110
|
+
self.t.rule("Step %d · %s" % (step["n"], what), "blue")
|
|
111
|
+
if step.get("why"):
|
|
112
|
+
self.t.line(self.t.s("Why: ", "bold") + visible(step["why"]))
|
|
113
|
+
|
|
114
|
+
def show_step(self, step, kind, show, verdict, asking=False):
|
|
115
|
+
self._step_header(step, kind)
|
|
116
|
+
show = visible(show or "")
|
|
117
|
+
if kind == "command":
|
|
118
|
+
for i, ln in enumerate(show.splitlines() or [""]):
|
|
119
|
+
self.t.line(self.t.s(("$ " if i == 0 else " ") + ln, "green"))
|
|
120
|
+
elif kind == "file":
|
|
121
|
+
lines = show.splitlines()
|
|
122
|
+
self.t.line(self.t.s("File: %s (%d lines)" % (visible(str(step.get("path"))), len(lines)), "bold"))
|
|
123
|
+
for ln in lines[:40]:
|
|
124
|
+
self.t.line(self.t.s(" " + ln, "green"))
|
|
125
|
+
if len(lines) > 40:
|
|
126
|
+
self.t.note(" … %d more lines (press v to see them all)" % (len(lines) - 40))
|
|
127
|
+
elif kind == "python":
|
|
128
|
+
for ln in show.splitlines():
|
|
129
|
+
self.t.line(self.t.s(" " + ln, "green"))
|
|
130
|
+
elif kind == "open":
|
|
131
|
+
self.t.line("Open %s" % show)
|
|
132
|
+
if verdict is not None and verdict.level == "confirm":
|
|
133
|
+
self.t.warn("AskTim! asks you to check this one: " + visible("; ".join(verdict.reasons)))
|
|
134
|
+
|
|
135
|
+
def approve(self, step, kind, show, verdict):
|
|
136
|
+
self.show_step(step, kind, show, verdict, asking=True)
|
|
137
|
+
if kind == "open":
|
|
138
|
+
ans = self.t.ask("Open it? [y/N] ", "n").lower()
|
|
139
|
+
return Decision("run" if ans.startswith("y") else "refuse")
|
|
140
|
+
extra = " [v]iew all" if kind == "file" and show.count("\n") > 40 else ""
|
|
141
|
+
prompt = "Run it? [Enter/y] yes · [n]o · [e]dit · [a]ll (stop asking)%s · [q]uit: " % extra if kind != "file" else "Write it? [Enter/y] yes · [n]o · [e]dit · [a]ll (stop asking)%s · [q]uit: " % extra
|
|
142
|
+
if verdict is not None and verdict.level == "confirm":
|
|
143
|
+
prompt = prompt.replace(" · [a]ll (stop asking)", "")
|
|
144
|
+
while True:
|
|
145
|
+
ans = self.t.ask(prompt, "y")
|
|
146
|
+
if ans is None:
|
|
147
|
+
return Decision("stop")
|
|
148
|
+
a = ans.lower()
|
|
149
|
+
if a in ("y", "yes", ""):
|
|
150
|
+
return Decision("run")
|
|
151
|
+
if a.startswith("v") and kind == "file":
|
|
152
|
+
for ln in visible(show).splitlines():
|
|
153
|
+
self.t.line(self.t.s(" " + ln, "green"))
|
|
154
|
+
continue
|
|
155
|
+
if a in ("a", "all") and not (verdict is not None and verdict.level == "confirm"):
|
|
156
|
+
self.t.note("From now on the agent's steps run without asking (blocked commands stay blocked; risky ones still ask).")
|
|
157
|
+
return Decision("all")
|
|
158
|
+
if a in ("q", "quit", "stop"):
|
|
159
|
+
return Decision("stop")
|
|
160
|
+
if a in ("n", "no"):
|
|
161
|
+
why = self.t.ask("Why not? (the agent is told; Enter to skip): ", "")
|
|
162
|
+
return Decision("refuse", comment=why or None)
|
|
163
|
+
if a in ("e", "edit"):
|
|
164
|
+
if kind == "file":
|
|
165
|
+
new = self._edit_file(step.get("path"), show)
|
|
166
|
+
else:
|
|
167
|
+
new = self.t.edit("$ ", show)
|
|
168
|
+
if new is None:
|
|
169
|
+
continue
|
|
170
|
+
note = self.t.ask("A note for the agent about your change? (Enter to skip): ", "")
|
|
171
|
+
return Decision("edit", text=new, comment=note or None)
|
|
172
|
+
self.t.note("Type y, n, e, a or q.")
|
|
173
|
+
|
|
174
|
+
def _edit_file(self, path, content):
|
|
175
|
+
editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or ("nano" if shutil.which("nano") else "vi")
|
|
176
|
+
import tempfile
|
|
177
|
+
|
|
178
|
+
suffix = os.path.splitext(path or "")[1] or ".txt"
|
|
179
|
+
with tempfile.NamedTemporaryFile("w", suffix=suffix, delete=False) as f:
|
|
180
|
+
f.write(content)
|
|
181
|
+
tmp = f.name
|
|
182
|
+
try:
|
|
183
|
+
subprocess.call(editor.split() + [tmp])
|
|
184
|
+
with open(tmp) as f:
|
|
185
|
+
return f.read()
|
|
186
|
+
except OSError:
|
|
187
|
+
self.t.warn("Could not start an editor (%s). Set EDITOR, or refuse the step and say what to change." % editor)
|
|
188
|
+
return None
|
|
189
|
+
finally:
|
|
190
|
+
os.unlink(tmp)
|
|
191
|
+
|
|
192
|
+
def blocked(self, step, verdict):
|
|
193
|
+
self._step_header(step, "command" if step["tool"] == "run_command" else "file")
|
|
194
|
+
if step.get("command"):
|
|
195
|
+
for i, ln in enumerate(visible(step["command"]).splitlines()):
|
|
196
|
+
self.t.line(self.t.s(("$ " if i == 0 else " ") + ln, "gray"))
|
|
197
|
+
self.t.error("Not allowed – " + visible("; ".join(verdict.reasons)))
|
|
198
|
+
self.t.note("The agent is told why, and has to find another way.")
|
|
199
|
+
|
|
200
|
+
def running(self, step):
|
|
201
|
+
self._last_was_output = False
|
|
202
|
+
|
|
203
|
+
def output(self, stream, text):
|
|
204
|
+
# what the command prints goes straight to the student's terminal
|
|
205
|
+
if stream == "stderr":
|
|
206
|
+
self.t.write(self.t.s(text, "yellow") if self.t.color else text)
|
|
207
|
+
else:
|
|
208
|
+
self.t.write(text)
|
|
209
|
+
self._last_was_output = True
|
|
210
|
+
|
|
211
|
+
def result(self, step, res, fr):
|
|
212
|
+
t = self.t
|
|
213
|
+
if res.exit_code == 0:
|
|
214
|
+
st = t.s("✓ exit 0" if t.uni else "ok: exit 0", "green")
|
|
215
|
+
else:
|
|
216
|
+
st = t.s(("✗ exit %s" if t.uni else "failed: exit %s") % res.exit_code, "red")
|
|
217
|
+
extra = []
|
|
218
|
+
if res.timed_out:
|
|
219
|
+
extra.append("stopped after the time limit")
|
|
220
|
+
if fr.withheld:
|
|
221
|
+
extra.append("the AI was shown %d of %d lines; %d withheld as data" % (fr.kept, fr.total, fr.withheld))
|
|
222
|
+
elif res.lines:
|
|
223
|
+
extra.append("the AI was shown the output (no data found in it)")
|
|
224
|
+
t.line("%s %s" % (st, t.s("· %.1f s%s" % (res.duration, (" · " + "; ".join(extra)) if extra else ""), "gray")))
|
|
225
|
+
|
|
226
|
+
def inspected(self, step, desc):
|
|
227
|
+
self.t.rule("Step %d · look at a file" % step["n"], "blue")
|
|
228
|
+
self.t.note("AskTim! described %s to the AI (its structure, not its contents):" % visible(str(step.get("path"))))
|
|
229
|
+
self.t.line(" " + desc)
|
|
230
|
+
|
|
231
|
+
def ask_stop(self):
|
|
232
|
+
ans = self.t.ask("\nStop the agent? [y/N] ", "n")
|
|
233
|
+
return bool(ans) and ans.lower().startswith("y")
|
|
234
|
+
|
|
235
|
+
def plan_review(self, plan):
|
|
236
|
+
t = self.t
|
|
237
|
+
t.line()
|
|
238
|
+
t.rule("The agent's plan", "cyan")
|
|
239
|
+
t.line(visible(plan or ""))
|
|
240
|
+
t.rule("", "cyan")
|
|
241
|
+
if not self.interactive:
|
|
242
|
+
return "cancel", None
|
|
243
|
+
while True:
|
|
244
|
+
ans = t.ask("Approve the plan? [Enter/y] yes, run the steps · [s] yes, but ask before each step · [c] ask for changes · [q] cancel: ", "y").lower()
|
|
245
|
+
if ans in ("y", "yes", ""):
|
|
246
|
+
return "approve-auto", None
|
|
247
|
+
if ans.startswith("s"):
|
|
248
|
+
return "approve-steps", None
|
|
249
|
+
if ans.startswith("c"):
|
|
250
|
+
fb = t.ask("What should change? ", "")
|
|
251
|
+
if fb:
|
|
252
|
+
return "change", fb
|
|
253
|
+
continue
|
|
254
|
+
if ans.startswith("q"):
|
|
255
|
+
return "cancel", None
|
|
256
|
+
|
|
257
|
+
def reply_to_question(self, text):
|
|
258
|
+
return self.t.ask("\nThe agent asked you something. Your answer (Enter to end the run): ", "")
|
|
259
|
+
|
|
260
|
+
def open_file(self, path, program=None):
|
|
261
|
+
if program:
|
|
262
|
+
from . import viewers
|
|
263
|
+
|
|
264
|
+
return viewers.launch(path, program)
|
|
265
|
+
if sys.platform == "darwin":
|
|
266
|
+
cmd = ["open", path]
|
|
267
|
+
elif os.name == "nt":
|
|
268
|
+
try:
|
|
269
|
+
os.startfile(path) # type: ignore[attr-defined]
|
|
270
|
+
return True, "with its default program"
|
|
271
|
+
except OSError as e:
|
|
272
|
+
return False, str(e)
|
|
273
|
+
else:
|
|
274
|
+
if not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
|
|
275
|
+
return False, "this computer has no screen to show it on (no DISPLAY); the student can open %s themselves" % paths.pretty(path)
|
|
276
|
+
if not shutil.which("xdg-open"):
|
|
277
|
+
return False, "xdg-open is not installed"
|
|
278
|
+
cmd = ["xdg-open", path]
|
|
279
|
+
try:
|
|
280
|
+
subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
|
281
|
+
return True, "with its default program"
|
|
282
|
+
except OSError as e:
|
|
283
|
+
return False, str(e)
|
|
284
|
+
|
|
285
|
+
def report(self, text, outcome):
|
|
286
|
+
t = self.t
|
|
287
|
+
t.line()
|
|
288
|
+
t.rule("The agent's report" + ("" if outcome == "done" else " (%s)" % outcome), "cyan")
|
|
289
|
+
md = t.markdown()
|
|
290
|
+
md.feed(text or "(no report)")
|
|
291
|
+
md.close()
|
|
292
|
+
|
|
293
|
+
def finish(self, written, rec):
|
|
294
|
+
t = self.t
|
|
295
|
+
t.rule("", "cyan")
|
|
296
|
+
t.note("AskTim! wrote the record of this run: %s" % ", ".join(written))
|
|
297
|
+
t.note("Read RUN.md to check what happened, and rerun.sh before you run it. The report above is the model's own words: check it.")
|
|
298
|
+
|
|
299
|
+
# -- chat -----------------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
def chat_header(self, summary, model):
|
|
302
|
+
self.t.note(summary)
|
|
303
|
+
self.t.note("(%s · AskTim! show \"…\" prints everything that would be sent)" % model)
|
asktim/viewers.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Programs with windows that the agent may start to show the student a file (open_file).
|
|
2
|
+
|
|
3
|
+
Only programs that are installed can be used, and the student is asked first every time. They run
|
|
4
|
+
outside the sandbox, as programs the student starts themselves do (they need the screen, and some -
|
|
5
|
+
IGV, for example - fetch genomes from the internet); their environment has no API keys or tokens.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import glob
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
# name the agent uses -> name of the macOS app (in /Applications), where it differs
|
|
15
|
+
VIEWERS = {
|
|
16
|
+
# genomes, alignments, trees, networks
|
|
17
|
+
"igv": "IGV", "igv.sh": "IGV", "jalview": "Jalview", "aliview": "AliView", "seaview": "SeaView", "ugene": "Unipro UGENE",
|
|
18
|
+
"tablet": "Tablet", "artemis": "Artemis", "act": "ACT", "figtree": "FigTree", "dendroscope": "Dendroscope",
|
|
19
|
+
"cytoscape": "Cytoscape", "pymol": "PyMOL", "chimerax": "ChimeraX", "jmol": "Jmol",
|
|
20
|
+
# browsers, documents, images, text
|
|
21
|
+
"firefox": "Firefox", "google-chrome": "Google Chrome", "chromium": "Chromium", "chromium-browser": "Chromium",
|
|
22
|
+
"evince": None, "okular": None, "zathura": None, "eog": None, "feh": None, "gimp": "GIMP", "inkscape": "Inkscape",
|
|
23
|
+
"libreoffice": "LibreOffice", "soffice": "LibreOffice", "gedit": None, "kate": None, "mousepad": None, "xed": None,
|
|
24
|
+
"pluma": None, "geany": None, "code": "Visual Studio Code", "rstudio": "RStudio",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def can_show_windows():
|
|
29
|
+
"""(yes or no, why not)"""
|
|
30
|
+
if sys.platform == "darwin":
|
|
31
|
+
if os.environ.get("SSH_CONNECTION") and not os.environ.get("DISPLAY"):
|
|
32
|
+
return False, "you are logged in over SSH, so there is no screen to open windows on"
|
|
33
|
+
return True, ""
|
|
34
|
+
if os.name == "nt":
|
|
35
|
+
return True, ""
|
|
36
|
+
if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
|
|
37
|
+
return True, ""
|
|
38
|
+
return False, "this computer has no screen for windows (no DISPLAY)"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _mac_app(name):
|
|
42
|
+
app = VIEWERS.get(name)
|
|
43
|
+
if sys.platform != "darwin" or not app:
|
|
44
|
+
return None
|
|
45
|
+
for root in ("/Applications", os.path.expanduser("~/Applications")):
|
|
46
|
+
hits = sorted(glob.glob(os.path.join(root, app + "*.app")))
|
|
47
|
+
if hits:
|
|
48
|
+
return hits[0]
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def find(name):
|
|
53
|
+
"""(the command to start it with a file, or None; why not)"""
|
|
54
|
+
name = (name or "").strip()
|
|
55
|
+
base = os.path.basename(name)
|
|
56
|
+
if base not in VIEWERS:
|
|
57
|
+
return None, "%s is not a program AskTim! starts (it can start: %s)" % (name, ", ".join(sorted(VIEWERS)))
|
|
58
|
+
exe = shutil.which(base)
|
|
59
|
+
if exe:
|
|
60
|
+
return [exe], ""
|
|
61
|
+
app = _mac_app(base)
|
|
62
|
+
if app:
|
|
63
|
+
return ["open", "-a", app], ""
|
|
64
|
+
return None, "%s is not installed here" % base
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def installed():
|
|
68
|
+
return [n for n in sorted(VIEWERS) if shutil.which(n) or _mac_app(n)]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def describe():
|
|
72
|
+
"""A line for the agent: which programs it could start, if any."""
|
|
73
|
+
ok, why = can_show_windows()
|
|
74
|
+
if not ok:
|
|
75
|
+
return "open_file cannot start programs here: %s. Tell the student which file to open instead." % why
|
|
76
|
+
progs = installed()
|
|
77
|
+
if not progs:
|
|
78
|
+
return "No programs with windows that AskTim! can start are installed; open_file uses the computer's default program for the file."
|
|
79
|
+
return "Programs with windows installed here (open_file can name one, e.g. IGV for a BAM or VCF file): %s." % ", ".join(progs)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def launch(path, name):
|
|
83
|
+
"""Start a program on a file without waiting for it. (ok, how)"""
|
|
84
|
+
ok, why = can_show_windows()
|
|
85
|
+
if not ok:
|
|
86
|
+
return False, why
|
|
87
|
+
argv, why = find(name)
|
|
88
|
+
if argv is None:
|
|
89
|
+
return False, why
|
|
90
|
+
from .runner import clean_env
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
subprocess.Popen(argv + [path], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
94
|
+
start_new_session=True, env=clean_env())
|
|
95
|
+
except OSError as e:
|
|
96
|
+
return False, str(e)
|
|
97
|
+
return True, "in %s" % os.path.basename(name)
|