dint-cli 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.
- dint/__init__.py +7 -0
- dint/__main__.py +4 -0
- dint/cli.py +313 -0
- dint/engines/__init__.py +30 -0
- dint/engines/base.py +63 -0
- dint/engines/claude.py +83 -0
- dint/engines/codex.py +95 -0
- dint/engines/copilot.py +79 -0
- dint/engines/grok.py +76 -0
- dint/envfile.py +60 -0
- dint/jobs.py +316 -0
- dint/logbook/__init__.py +200 -0
- dint/logbook/mcp.py +149 -0
- dint/logbook/rest.py +85 -0
- dint/proc.py +113 -0
- dint/router.py +100 -0
- dint/runtime.py +197 -0
- dint/status.py +58 -0
- dint/types.py +59 -0
- dint_cli-0.1.0.dist-info/METADATA +155 -0
- dint_cli-0.1.0.dist-info/RECORD +25 -0
- dint_cli-0.1.0.dist-info/WHEEL +5 -0
- dint_cli-0.1.0.dist-info/entry_points.txt +2 -0
- dint_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- dint_cli-0.1.0.dist-info/top_level.txt +1 -0
dint/__init__.py
ADDED
dint/__main__.py
ADDED
dint/cli.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from dint import __version__
|
|
10
|
+
from dint.envfile import load_dotenv
|
|
11
|
+
from dint.router import ENGINES, Router
|
|
12
|
+
from dint.runtime import ensure_runtime, pick_engine, serve_running
|
|
13
|
+
|
|
14
|
+
COMMANDS = {
|
|
15
|
+
"start",
|
|
16
|
+
"send",
|
|
17
|
+
"cancel",
|
|
18
|
+
"list",
|
|
19
|
+
"show",
|
|
20
|
+
"chats",
|
|
21
|
+
"status",
|
|
22
|
+
"job",
|
|
23
|
+
"serve",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main(argv: list[str] | None = None) -> int:
|
|
28
|
+
env_path = load_dotenv()
|
|
29
|
+
if env_path:
|
|
30
|
+
os.environ.setdefault("DINT_ENV_FILE", str(env_path))
|
|
31
|
+
|
|
32
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
33
|
+
if _is_chat_argv(argv):
|
|
34
|
+
return run_chat_argv(argv)
|
|
35
|
+
|
|
36
|
+
p = argparse.ArgumentParser(
|
|
37
|
+
prog="dint",
|
|
38
|
+
description=(
|
|
39
|
+
"Chat router over Claude, Codex, Grok, and Copilot. "
|
|
40
|
+
"Run `dint` or `dint grok` in a folder to start logbook + serve and chat."
|
|
41
|
+
),
|
|
42
|
+
)
|
|
43
|
+
p.add_argument("--version", action="version", version=f"dint {__version__}")
|
|
44
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
45
|
+
|
|
46
|
+
s = sub.add_parser("start")
|
|
47
|
+
s.add_argument("engine", choices=sorted(ENGINES))
|
|
48
|
+
s.add_argument("cwd", nargs="?", default=".")
|
|
49
|
+
|
|
50
|
+
s = sub.add_parser("send")
|
|
51
|
+
s.add_argument("chat_id")
|
|
52
|
+
s.add_argument("prompt", nargs="+")
|
|
53
|
+
|
|
54
|
+
s = sub.add_parser("cancel")
|
|
55
|
+
s.add_argument("chat_id")
|
|
56
|
+
|
|
57
|
+
s = sub.add_parser("list")
|
|
58
|
+
s.add_argument("chat_id")
|
|
59
|
+
|
|
60
|
+
s = sub.add_parser("show")
|
|
61
|
+
s.add_argument("chat_id")
|
|
62
|
+
|
|
63
|
+
sub.add_parser("chats", help="list conversations in Logbook")
|
|
64
|
+
sub.add_parser("status", help="check Logbook and engine CLIs")
|
|
65
|
+
|
|
66
|
+
s = sub.add_parser("job", help="enqueue a #job in Logbook (dint serve runs it)")
|
|
67
|
+
s.add_argument("engine", choices=sorted(ENGINES))
|
|
68
|
+
s.add_argument("args", nargs="+", help="optional cwd, then prompt")
|
|
69
|
+
|
|
70
|
+
s = sub.add_parser("serve", help="run #job webhooks from Logbook")
|
|
71
|
+
s.add_argument("--host", default=os.environ.get("DINT_JOBS_HOST", "127.0.0.1"))
|
|
72
|
+
s.add_argument("--port", type=int, default=int(os.environ.get("DINT_JOBS_PORT", "8787")))
|
|
73
|
+
s.add_argument("--no-register", action="store_true", help="do not call Logbook register_webhook")
|
|
74
|
+
|
|
75
|
+
args = p.parse_args(argv)
|
|
76
|
+
|
|
77
|
+
if args.cmd == "status":
|
|
78
|
+
from dint.status import run_status
|
|
79
|
+
|
|
80
|
+
return run_status()
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
if args.cmd == "serve":
|
|
84
|
+
return _run_serve(args.host, args.port, register=not args.no_register)
|
|
85
|
+
ensure_runtime(serve=args.cmd == "job")
|
|
86
|
+
router = Router()
|
|
87
|
+
if args.cmd == "start":
|
|
88
|
+
print(router.start_chat(args.engine, os.path.abspath(args.cwd)))
|
|
89
|
+
return 0
|
|
90
|
+
if args.cmd == "send":
|
|
91
|
+
try:
|
|
92
|
+
printer = EventPrinter()
|
|
93
|
+
for event in router.send(args.chat_id, " ".join(args.prompt)):
|
|
94
|
+
printer.emit(event)
|
|
95
|
+
printer.finish()
|
|
96
|
+
except KeyboardInterrupt:
|
|
97
|
+
router.cancel(args.chat_id)
|
|
98
|
+
print("cancelled", file=sys.stderr)
|
|
99
|
+
return 130
|
|
100
|
+
return 0
|
|
101
|
+
if args.cmd == "cancel":
|
|
102
|
+
router.cancel(args.chat_id)
|
|
103
|
+
return 0
|
|
104
|
+
if args.cmd == "list":
|
|
105
|
+
for t in router.list_turns(args.chat_id):
|
|
106
|
+
text = (t.get("text") or "").replace("\n", " ")
|
|
107
|
+
print(f"{t.get('ts')}\t{t.get('role')}\t{text[:120]}")
|
|
108
|
+
return 0
|
|
109
|
+
if args.cmd == "show":
|
|
110
|
+
chat = router.get_chat(args.chat_id)
|
|
111
|
+
print(json.dumps({
|
|
112
|
+
"chatId": chat.chat_id,
|
|
113
|
+
"engine": chat.engine,
|
|
114
|
+
"cwd": chat.cwd,
|
|
115
|
+
"externalSessionId": chat.external_session_id,
|
|
116
|
+
}, indent=2))
|
|
117
|
+
return 0
|
|
118
|
+
if args.cmd == "chats":
|
|
119
|
+
for c in router.list_chats():
|
|
120
|
+
preview = (c.get("preview") or "").replace("\n", " ")[:60]
|
|
121
|
+
print(
|
|
122
|
+
f"{c.get('ts')}\t{c.get('chatId')}\t{c.get('engine')}\t{preview}"
|
|
123
|
+
)
|
|
124
|
+
return 0
|
|
125
|
+
if args.cmd == "job":
|
|
126
|
+
from dint.jobs import post_job, wait_for_job_chat
|
|
127
|
+
|
|
128
|
+
cwd, prompt = _job_cwd_prompt(args.args)
|
|
129
|
+
job_id = post_job(router, args.engine, prompt, cwd)
|
|
130
|
+
print(f"job\t{job_id}")
|
|
131
|
+
chat_id = wait_for_job_chat(router, job_id)
|
|
132
|
+
if chat_id:
|
|
133
|
+
print(f"chat\t{chat_id}")
|
|
134
|
+
print(f"dint list {chat_id}")
|
|
135
|
+
else:
|
|
136
|
+
print("waiting for dint serve... try: dint chats", file=sys.stderr)
|
|
137
|
+
return 0 if chat_id else 2
|
|
138
|
+
except (KeyError, NotImplementedError, RuntimeError, ValueError) as e:
|
|
139
|
+
print(str(e), file=sys.stderr)
|
|
140
|
+
return 1
|
|
141
|
+
return 1
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _is_chat_argv(argv: list[str]) -> bool:
|
|
145
|
+
if not argv:
|
|
146
|
+
return True
|
|
147
|
+
if argv[0].startswith("-"):
|
|
148
|
+
return False
|
|
149
|
+
return argv[0] not in COMMANDS
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def run_chat_argv(argv: list[str]) -> int:
|
|
153
|
+
engine = None
|
|
154
|
+
rest = argv
|
|
155
|
+
if argv and argv[0].lower() in ENGINES:
|
|
156
|
+
engine = argv[0].lower()
|
|
157
|
+
rest = argv[1:]
|
|
158
|
+
prompt = " ".join(rest).strip() or None
|
|
159
|
+
try:
|
|
160
|
+
return run_chat(engine, prompt)
|
|
161
|
+
except (KeyError, NotImplementedError, RuntimeError, ValueError) as e:
|
|
162
|
+
print(str(e), file=sys.stderr)
|
|
163
|
+
return 1
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run_chat(engine: str | None, prompt: str | None) -> int:
|
|
167
|
+
ensure_runtime(serve=True)
|
|
168
|
+
cwd = os.path.abspath(".")
|
|
169
|
+
if engine and shutil.which(engine) is None:
|
|
170
|
+
raise RuntimeError(f"{engine} is not on PATH")
|
|
171
|
+
if prompt is None and not sys.stdin.isatty():
|
|
172
|
+
prompt = sys.stdin.read().strip() or None
|
|
173
|
+
if prompt is None:
|
|
174
|
+
print("dint: pass a prompt, or run in a terminal", file=sys.stderr)
|
|
175
|
+
return 2
|
|
176
|
+
router = Router()
|
|
177
|
+
engine, chat_id = _resume_or_start(router, engine, cwd)
|
|
178
|
+
print(f"{engine} {cwd} {chat_id}", file=sys.stderr)
|
|
179
|
+
if prompt:
|
|
180
|
+
return _send(router, chat_id, prompt)
|
|
181
|
+
return _repl(router, engine, cwd, chat_id)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _resume_or_start(router: Router, engine: str | None, cwd: str) -> tuple[str, str]:
|
|
185
|
+
key = _cwd_key(cwd)
|
|
186
|
+
if engine is None:
|
|
187
|
+
for row in router.list_chats():
|
|
188
|
+
name = str(row.get("engine") or "").lower()
|
|
189
|
+
if name not in ENGINES or shutil.which(name) is None:
|
|
190
|
+
continue
|
|
191
|
+
if _cwd_key(str(row.get("cwd") or "")) == key:
|
|
192
|
+
return name, str(row["chatId"])
|
|
193
|
+
engine = pick_engine()
|
|
194
|
+
if not engine:
|
|
195
|
+
raise RuntimeError(
|
|
196
|
+
"no engine CLI on PATH. Install grok, claude, copilot, or codex."
|
|
197
|
+
)
|
|
198
|
+
return engine, router.start_chat(engine, cwd)
|
|
199
|
+
for row in router.list_chats():
|
|
200
|
+
if str(row.get("engine") or "").lower() != engine:
|
|
201
|
+
continue
|
|
202
|
+
if _cwd_key(str(row.get("cwd") or "")) == key:
|
|
203
|
+
return engine, str(row["chatId"])
|
|
204
|
+
return engine, router.start_chat(engine, cwd)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _repl(router: Router, engine: str, cwd: str, chat_id: str) -> int:
|
|
208
|
+
print("message, /new, /quit", file=sys.stderr)
|
|
209
|
+
while True:
|
|
210
|
+
try:
|
|
211
|
+
line = input()
|
|
212
|
+
except (EOFError, KeyboardInterrupt):
|
|
213
|
+
print(file=sys.stderr)
|
|
214
|
+
return 0
|
|
215
|
+
text = line.strip()
|
|
216
|
+
if not text:
|
|
217
|
+
continue
|
|
218
|
+
if text in {"/quit", "/exit", "/q"}:
|
|
219
|
+
return 0
|
|
220
|
+
if text == "/new":
|
|
221
|
+
chat_id = router.start_chat(engine, cwd)
|
|
222
|
+
print(f"{engine} {cwd} {chat_id}", file=sys.stderr)
|
|
223
|
+
continue
|
|
224
|
+
if text.startswith("/"):
|
|
225
|
+
print("commands: /new /quit", file=sys.stderr)
|
|
226
|
+
continue
|
|
227
|
+
code = _send(router, chat_id, text, quiet_done=True)
|
|
228
|
+
if code != 0:
|
|
229
|
+
return code
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _send(router: Router, chat_id: str, prompt: str, *, quiet_done: bool = False) -> int:
|
|
233
|
+
printer = EventPrinter(quiet_done=quiet_done)
|
|
234
|
+
try:
|
|
235
|
+
for event in router.send(chat_id, prompt):
|
|
236
|
+
printer.emit(event)
|
|
237
|
+
printer.finish()
|
|
238
|
+
except KeyboardInterrupt:
|
|
239
|
+
router.cancel(chat_id)
|
|
240
|
+
print("cancelled", file=sys.stderr)
|
|
241
|
+
return 130
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _run_serve(host: str, port: int, *, register: bool) -> int:
|
|
246
|
+
os.environ["DINT_JOBS_HOST"] = host
|
|
247
|
+
os.environ["DINT_JOBS_PORT"] = str(port)
|
|
248
|
+
ensure_runtime(serve=False)
|
|
249
|
+
if serve_running():
|
|
250
|
+
print(f"dint serve already running at http://{host}:{port}/webhook")
|
|
251
|
+
return 0
|
|
252
|
+
os.environ["DINT_ROLE"] = "serve"
|
|
253
|
+
from dint.jobs import serve
|
|
254
|
+
|
|
255
|
+
try:
|
|
256
|
+
serve(host, port, register=register)
|
|
257
|
+
except OSError as e:
|
|
258
|
+
if serve_running():
|
|
259
|
+
print(f"dint serve already running at http://{host}:{port}/webhook")
|
|
260
|
+
return 0
|
|
261
|
+
print(str(e), file=sys.stderr)
|
|
262
|
+
return 1
|
|
263
|
+
return 0
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _cwd_key(cwd: str) -> str:
|
|
267
|
+
try:
|
|
268
|
+
return os.path.normcase(os.path.abspath(cwd or "."))
|
|
269
|
+
except (OSError, ValueError):
|
|
270
|
+
return os.path.normcase(cwd or "")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _job_cwd_prompt(args: list[str]) -> tuple[str, str]:
|
|
274
|
+
if len(args) >= 2 and os.path.isdir(args[0]):
|
|
275
|
+
return os.path.abspath(args[0]), " ".join(args[1:])
|
|
276
|
+
return os.path.abspath("."), " ".join(args)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class EventPrinter:
|
|
280
|
+
"""Stream token chunks inline; only start a new line for tools/done/errors."""
|
|
281
|
+
|
|
282
|
+
def __init__(self, *, quiet_done: bool = False) -> None:
|
|
283
|
+
self._mid_line = False
|
|
284
|
+
self.quiet_done = quiet_done
|
|
285
|
+
|
|
286
|
+
def emit(self, event: object) -> None:
|
|
287
|
+
kind = getattr(event, "type", None)
|
|
288
|
+
text = getattr(event, "text", "") or ""
|
|
289
|
+
if kind == "text" and text:
|
|
290
|
+
sys.stdout.write(text)
|
|
291
|
+
sys.stdout.flush()
|
|
292
|
+
self._mid_line = not text.endswith("\n")
|
|
293
|
+
return
|
|
294
|
+
self._break()
|
|
295
|
+
if kind == "tool":
|
|
296
|
+
print(f"[tool] {getattr(event, 'tool', None) or text}", flush=True)
|
|
297
|
+
elif kind == "error":
|
|
298
|
+
print(f"[error] {text}", file=sys.stderr, flush=True)
|
|
299
|
+
elif kind == "done" and not self.quiet_done:
|
|
300
|
+
sid = getattr(event, "session_id", None)
|
|
301
|
+
print(f"[done]{f' session={sid}' if sid else ''}", flush=True)
|
|
302
|
+
|
|
303
|
+
def finish(self) -> None:
|
|
304
|
+
self._break()
|
|
305
|
+
|
|
306
|
+
def _break(self) -> None:
|
|
307
|
+
if self._mid_line:
|
|
308
|
+
print(flush=True)
|
|
309
|
+
self._mid_line = False
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
if __name__ == "__main__":
|
|
313
|
+
raise SystemExit(main())
|
dint/engines/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from dint.engines.base import CliEngine, StubEngine
|
|
2
|
+
from dint.engines.claude import ClaudeEngine, parse_claude_line
|
|
3
|
+
from dint.engines.codex import CodexEngine, parse_codex_line
|
|
4
|
+
from dint.engines.copilot import CopilotEngine, parse_copilot_line
|
|
5
|
+
from dint.engines.grok import GrokEngine, parse_grok_line
|
|
6
|
+
from dint.types import Engine
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def default_engines() -> dict[str, Engine]:
|
|
10
|
+
return {
|
|
11
|
+
"claude": ClaudeEngine(),
|
|
12
|
+
"codex": CodexEngine(),
|
|
13
|
+
"grok": GrokEngine(),
|
|
14
|
+
"copilot": CopilotEngine(),
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ClaudeEngine",
|
|
20
|
+
"CliEngine",
|
|
21
|
+
"CodexEngine",
|
|
22
|
+
"CopilotEngine",
|
|
23
|
+
"GrokEngine",
|
|
24
|
+
"StubEngine",
|
|
25
|
+
"default_engines",
|
|
26
|
+
"parse_claude_line",
|
|
27
|
+
"parse_codex_line",
|
|
28
|
+
"parse_copilot_line",
|
|
29
|
+
"parse_grok_line",
|
|
30
|
+
]
|
dint/engines/base.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""JSONL CLI runner. Adapters only supply argv + line parser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
|
|
7
|
+
from dint.proc import CancelledError, RunningProcess, spawn
|
|
8
|
+
from dint.types import Event
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CliEngine:
|
|
12
|
+
"""Spawn a CLI, stream JSONL stdout into Event, cancel the process tree."""
|
|
13
|
+
|
|
14
|
+
name: str
|
|
15
|
+
|
|
16
|
+
def __init__(self, binary: str) -> None:
|
|
17
|
+
self.binary = binary
|
|
18
|
+
self._running: RunningProcess | None = None
|
|
19
|
+
|
|
20
|
+
def argv(self, prompt: str, cwd: str, session_id: str | None) -> list[str]:
|
|
21
|
+
raise NotImplementedError
|
|
22
|
+
|
|
23
|
+
def parse_line(self, line: str, session_id: str | None) -> list[Event]:
|
|
24
|
+
raise NotImplementedError
|
|
25
|
+
|
|
26
|
+
def send(self, prompt: str, *, cwd: str, session_id: str | None) -> Iterator[Event]:
|
|
27
|
+
running = spawn(self.argv(prompt, cwd, session_id), cwd=cwd)
|
|
28
|
+
self._running = running
|
|
29
|
+
sid = session_id
|
|
30
|
+
done = False
|
|
31
|
+
try:
|
|
32
|
+
for line in running.lines():
|
|
33
|
+
for event in self.parse_line(line, sid):
|
|
34
|
+
if event.session_id:
|
|
35
|
+
sid = event.session_id
|
|
36
|
+
if event.type == "done":
|
|
37
|
+
done = True
|
|
38
|
+
yield event
|
|
39
|
+
code = running.proc.returncode
|
|
40
|
+
if code not in (0, None) and not done:
|
|
41
|
+
yield Event(type="error", text=f"{self.name} exited {code}", session_id=sid)
|
|
42
|
+
if not done:
|
|
43
|
+
yield Event(type="done", session_id=sid)
|
|
44
|
+
except CancelledError:
|
|
45
|
+
yield Event(type="error", text="cancelled", session_id=sid)
|
|
46
|
+
finally:
|
|
47
|
+
if self._running is running:
|
|
48
|
+
self._running = None
|
|
49
|
+
|
|
50
|
+
def cancel(self) -> None:
|
|
51
|
+
if self._running is not None:
|
|
52
|
+
self._running.cancel()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StubEngine:
|
|
56
|
+
def __init__(self, name: str) -> None:
|
|
57
|
+
self.name = name
|
|
58
|
+
|
|
59
|
+
def send(self, prompt: str, *, cwd: str, session_id: str | None) -> Iterator[Event]:
|
|
60
|
+
raise NotImplementedError(f"{self.name} adapter is a stub")
|
|
61
|
+
|
|
62
|
+
def cancel(self) -> None:
|
|
63
|
+
return
|
dint/engines/claude.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Claude Code CLI: `claude -p --resume <id>`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from dint.engines.base import CliEngine
|
|
11
|
+
from dint.types import Event
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ClaudeEngine(CliEngine):
|
|
15
|
+
name = "claude"
|
|
16
|
+
|
|
17
|
+
def __init__(self, binary: str | None = None) -> None:
|
|
18
|
+
super().__init__(binary or os.environ.get("DINT_CLAUDE_BIN") or shutil.which("claude") or "claude")
|
|
19
|
+
|
|
20
|
+
def argv(self, prompt: str, cwd: str, session_id: str | None) -> list[str]:
|
|
21
|
+
cmd = [
|
|
22
|
+
self.binary,
|
|
23
|
+
"--print",
|
|
24
|
+
"--verbose",
|
|
25
|
+
"--output-format",
|
|
26
|
+
"stream-json",
|
|
27
|
+
"--permission-mode",
|
|
28
|
+
os.environ.get("DINT_CLAUDE_PERMISSION_MODE", "acceptEdits"),
|
|
29
|
+
]
|
|
30
|
+
if session_id:
|
|
31
|
+
cmd.extend(["--resume", session_id])
|
|
32
|
+
cmd.append(prompt)
|
|
33
|
+
return cmd
|
|
34
|
+
|
|
35
|
+
def parse_line(self, line: str, session_id: str | None) -> list[Event]:
|
|
36
|
+
return parse_claude_line(line, session_id=session_id)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_claude_line(line: str, *, session_id: str | None = None) -> list[Event]:
|
|
40
|
+
obj = _json(line)
|
|
41
|
+
if not obj:
|
|
42
|
+
return []
|
|
43
|
+
sid = obj.get("session_id") or obj.get("sessionId") or session_id
|
|
44
|
+
kind = obj.get("type")
|
|
45
|
+
if kind == "system" and sid:
|
|
46
|
+
return [Event(type="session", session_id=sid)]
|
|
47
|
+
if kind == "assistant":
|
|
48
|
+
return _assistant(obj.get("message") or {}, sid)
|
|
49
|
+
if kind == "result":
|
|
50
|
+
if obj.get("is_error") or obj.get("subtype") not in {None, "success"}:
|
|
51
|
+
return [Event(type="error", text=str(obj.get("result") or obj.get("error") or "error"), session_id=sid)]
|
|
52
|
+
return [Event(type="done", session_id=sid)]
|
|
53
|
+
return []
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _assistant(message: Any, sid: str | None) -> list[Event]:
|
|
57
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
58
|
+
if not isinstance(content, list):
|
|
59
|
+
return []
|
|
60
|
+
events: list[Event] = []
|
|
61
|
+
texts: list[str] = []
|
|
62
|
+
for block in content:
|
|
63
|
+
if not isinstance(block, dict):
|
|
64
|
+
continue
|
|
65
|
+
if block.get("type") == "text" and block.get("text"):
|
|
66
|
+
texts.append(str(block["text"]))
|
|
67
|
+
elif block.get("type") == "tool_use":
|
|
68
|
+
name = str(block.get("name") or "tool")
|
|
69
|
+
events.append(Event(type="tool", text=name, tool=name, session_id=sid))
|
|
70
|
+
if texts:
|
|
71
|
+
events.append(Event(type="text", text="".join(texts), session_id=sid))
|
|
72
|
+
return events
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _json(line: str) -> dict[str, Any] | None:
|
|
76
|
+
line = line.strip()
|
|
77
|
+
if not line:
|
|
78
|
+
return None
|
|
79
|
+
try:
|
|
80
|
+
obj = json.loads(line)
|
|
81
|
+
except json.JSONDecodeError:
|
|
82
|
+
return None
|
|
83
|
+
return obj if isinstance(obj, dict) else None
|
dint/engines/codex.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Codex CLI: `codex exec` / `codex exec resume <id>`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from dint.engines.base import CliEngine
|
|
11
|
+
from dint.types import Event
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CodexEngine(CliEngine):
|
|
15
|
+
name = "codex"
|
|
16
|
+
|
|
17
|
+
def __init__(self, binary: str | None = None) -> None:
|
|
18
|
+
super().__init__(binary or os.environ.get("DINT_CODEX_BIN") or shutil.which("codex") or "codex")
|
|
19
|
+
|
|
20
|
+
def argv(self, prompt: str, cwd: str, session_id: str | None) -> list[str]:
|
|
21
|
+
# `codex exec resume` does not accept -C / -s; cwd is the subprocess cwd.
|
|
22
|
+
if session_id:
|
|
23
|
+
return [
|
|
24
|
+
self.binary,
|
|
25
|
+
"exec",
|
|
26
|
+
"resume",
|
|
27
|
+
session_id,
|
|
28
|
+
"--json",
|
|
29
|
+
"--skip-git-repo-check",
|
|
30
|
+
prompt,
|
|
31
|
+
]
|
|
32
|
+
return [
|
|
33
|
+
self.binary,
|
|
34
|
+
"exec",
|
|
35
|
+
"--json",
|
|
36
|
+
"--skip-git-repo-check",
|
|
37
|
+
"-C",
|
|
38
|
+
cwd,
|
|
39
|
+
"-s",
|
|
40
|
+
os.environ.get("DINT_CODEX_SANDBOX", "workspace-write"),
|
|
41
|
+
prompt,
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
def parse_line(self, line: str, session_id: str | None) -> list[Event]:
|
|
45
|
+
return parse_codex_line(line, session_id=session_id)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse_codex_line(line: str, *, session_id: str | None = None) -> list[Event]:
|
|
49
|
+
obj = _json(line)
|
|
50
|
+
if not obj:
|
|
51
|
+
return []
|
|
52
|
+
msg = obj["msg"] if isinstance(obj.get("msg"), dict) else obj
|
|
53
|
+
sid = (
|
|
54
|
+
obj.get("thread_id")
|
|
55
|
+
or msg.get("thread_id")
|
|
56
|
+
or obj.get("session_id")
|
|
57
|
+
or msg.get("session_id")
|
|
58
|
+
or session_id
|
|
59
|
+
)
|
|
60
|
+
kind = str(msg.get("type") or obj.get("type") or "")
|
|
61
|
+
if kind in {"thread.started", "thread_started", "session_created"} and sid:
|
|
62
|
+
return [Event(type="session", session_id=sid)]
|
|
63
|
+
if kind in {"item.completed", "item_completed", "item.started", "agent_message"}:
|
|
64
|
+
return _item(msg.get("item") or msg, sid)
|
|
65
|
+
if kind in {"turn.completed", "turn_complete", "task_complete"}:
|
|
66
|
+
return [Event(type="done", session_id=sid)]
|
|
67
|
+
if kind in {"turn.failed", "error", "turn_failed"}:
|
|
68
|
+
return [Event(type="error", text=str(msg.get("message") or msg.get("error") or "error"), session_id=sid)]
|
|
69
|
+
if "approval" in kind:
|
|
70
|
+
return [Event(type="need_approval", text=str(msg.get("command") or kind), session_id=sid)]
|
|
71
|
+
return []
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _item(item: Any, sid: str | None) -> list[Event]:
|
|
75
|
+
if not isinstance(item, dict):
|
|
76
|
+
return []
|
|
77
|
+
itype = str(item.get("type") or "")
|
|
78
|
+
if itype in {"command_execution", "command", "mcp_tool_call", "file_change", "patch", "tool"}:
|
|
79
|
+
name = str(item.get("command") or item.get("name") or itype)
|
|
80
|
+
return [Event(type="tool", text=name, tool=itype, session_id=sid)]
|
|
81
|
+
text = item.get("text") or item.get("content") or item.get("message")
|
|
82
|
+
if isinstance(text, str) and text:
|
|
83
|
+
return [Event(type="text", text=text, session_id=sid)]
|
|
84
|
+
return []
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _json(line: str) -> dict[str, Any] | None:
|
|
88
|
+
line = line.strip()
|
|
89
|
+
if not line:
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
obj = json.loads(line)
|
|
93
|
+
except json.JSONDecodeError:
|
|
94
|
+
return None
|
|
95
|
+
return obj if isinstance(obj, dict) else None
|
dint/engines/copilot.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""GitHub Copilot CLI: `copilot -p --resume=<id> --output-format json`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from dint.engines.base import CliEngine
|
|
11
|
+
from dint.types import Event
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CopilotEngine(CliEngine):
|
|
15
|
+
name = "copilot"
|
|
16
|
+
|
|
17
|
+
def __init__(self, binary: str | None = None) -> None:
|
|
18
|
+
super().__init__(
|
|
19
|
+
binary or os.environ.get("DINT_COPILOT_BIN") or shutil.which("copilot") or "copilot"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
def argv(self, prompt: str, cwd: str, session_id: str | None) -> list[str]:
|
|
23
|
+
cmd = [
|
|
24
|
+
self.binary,
|
|
25
|
+
"-C",
|
|
26
|
+
cwd,
|
|
27
|
+
"--output-format",
|
|
28
|
+
"json",
|
|
29
|
+
"--allow-all",
|
|
30
|
+
"-p",
|
|
31
|
+
prompt,
|
|
32
|
+
]
|
|
33
|
+
if session_id:
|
|
34
|
+
cmd.append(f"--resume={session_id}")
|
|
35
|
+
return cmd
|
|
36
|
+
|
|
37
|
+
def parse_line(self, line: str, session_id: str | None) -> list[Event]:
|
|
38
|
+
return parse_copilot_line(line, session_id=session_id)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_copilot_line(line: str, *, session_id: str | None = None) -> list[Event]:
|
|
42
|
+
obj = _json(line)
|
|
43
|
+
if not obj:
|
|
44
|
+
return []
|
|
45
|
+
sid = obj.get("sessionId") or obj.get("session_id") or session_id
|
|
46
|
+
kind = str(obj.get("type") or "")
|
|
47
|
+
data = obj.get("data") if isinstance(obj.get("data"), dict) else {}
|
|
48
|
+
|
|
49
|
+
if kind == "result":
|
|
50
|
+
if obj.get("exitCode") not in {None, 0}:
|
|
51
|
+
return [Event(type="error", text=f"copilot exit {obj.get('exitCode')}", session_id=sid)]
|
|
52
|
+
return [Event(type="done", session_id=sid)]
|
|
53
|
+
if kind == "assistant.message":
|
|
54
|
+
events: list[Event] = []
|
|
55
|
+
for req in data.get("toolRequests") or []:
|
|
56
|
+
if isinstance(req, dict):
|
|
57
|
+
name = str(req.get("name") or "tool")
|
|
58
|
+
events.append(Event(type="tool", text=name, tool=name, session_id=sid))
|
|
59
|
+
text = data.get("content")
|
|
60
|
+
if isinstance(text, str) and text.strip():
|
|
61
|
+
events.append(Event(type="text", text=text, session_id=sid))
|
|
62
|
+
return events
|
|
63
|
+
if kind == "tool.execution_start":
|
|
64
|
+
name = str(data.get("toolName") or "tool")
|
|
65
|
+
return [Event(type="tool", text=name, tool=name, session_id=sid)]
|
|
66
|
+
if kind in {"session.start", "user.message"} and sid:
|
|
67
|
+
return [Event(type="session", session_id=sid)]
|
|
68
|
+
return []
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _json(line: str) -> dict[str, Any] | None:
|
|
72
|
+
line = line.strip()
|
|
73
|
+
if not line:
|
|
74
|
+
return None
|
|
75
|
+
try:
|
|
76
|
+
obj = json.loads(line)
|
|
77
|
+
except json.JSONDecodeError:
|
|
78
|
+
return None
|
|
79
|
+
return obj if isinstance(obj, dict) else None
|