dint-cli 0.1.0__tar.gz

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.
Files changed (37) hide show
  1. dint_cli-0.1.0/LICENSE +21 -0
  2. dint_cli-0.1.0/PKG-INFO +155 -0
  3. dint_cli-0.1.0/README.md +110 -0
  4. dint_cli-0.1.0/pyproject.toml +41 -0
  5. dint_cli-0.1.0/setup.cfg +4 -0
  6. dint_cli-0.1.0/src/dint/__init__.py +7 -0
  7. dint_cli-0.1.0/src/dint/__main__.py +4 -0
  8. dint_cli-0.1.0/src/dint/cli.py +313 -0
  9. dint_cli-0.1.0/src/dint/engines/__init__.py +30 -0
  10. dint_cli-0.1.0/src/dint/engines/base.py +63 -0
  11. dint_cli-0.1.0/src/dint/engines/claude.py +83 -0
  12. dint_cli-0.1.0/src/dint/engines/codex.py +95 -0
  13. dint_cli-0.1.0/src/dint/engines/copilot.py +79 -0
  14. dint_cli-0.1.0/src/dint/engines/grok.py +76 -0
  15. dint_cli-0.1.0/src/dint/envfile.py +60 -0
  16. dint_cli-0.1.0/src/dint/jobs.py +316 -0
  17. dint_cli-0.1.0/src/dint/logbook/__init__.py +200 -0
  18. dint_cli-0.1.0/src/dint/logbook/mcp.py +149 -0
  19. dint_cli-0.1.0/src/dint/logbook/rest.py +85 -0
  20. dint_cli-0.1.0/src/dint/proc.py +113 -0
  21. dint_cli-0.1.0/src/dint/router.py +100 -0
  22. dint_cli-0.1.0/src/dint/runtime.py +197 -0
  23. dint_cli-0.1.0/src/dint/status.py +58 -0
  24. dint_cli-0.1.0/src/dint/types.py +59 -0
  25. dint_cli-0.1.0/src/dint_cli.egg-info/PKG-INFO +155 -0
  26. dint_cli-0.1.0/src/dint_cli.egg-info/SOURCES.txt +35 -0
  27. dint_cli-0.1.0/src/dint_cli.egg-info/dependency_links.txt +1 -0
  28. dint_cli-0.1.0/src/dint_cli.egg-info/entry_points.txt +2 -0
  29. dint_cli-0.1.0/src/dint_cli.egg-info/requires.txt +3 -0
  30. dint_cli-0.1.0/src/dint_cli.egg-info/top_level.txt +1 -0
  31. dint_cli-0.1.0/tests/test_cli.py +118 -0
  32. dint_cli-0.1.0/tests/test_engines.py +92 -0
  33. dint_cli-0.1.0/tests/test_envfile.py +38 -0
  34. dint_cli-0.1.0/tests/test_jobs.py +196 -0
  35. dint_cli-0.1.0/tests/test_logbook.py +152 -0
  36. dint_cli-0.1.0/tests/test_router.py +123 -0
  37. dint_cli-0.1.0/tests/test_runtime.py +103 -0
dint_cli-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Johan Isaksson / Izaxon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: dint-cli
3
+ Version: 0.1.0
4
+ Summary: One local chat API over Claude, Codex, Grok, and Copilot. Codicent Logbook is the ledger.
5
+ Author-email: Johan Isaksson <johan@izaxon.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Johan Isaksson / Izaxon
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://izaxon.github.io/dint/
29
+ Project-URL: Repository, https://github.com/izaxon/dint
30
+ Project-URL: Issues, https://github.com/izaxon/dint/issues
31
+ Keywords: claude,codex,grok,copilot,logbook,codicent
32
+ Classifier: Development Status :: 3 - Alpha
33
+ Classifier: Environment :: Console
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Topic :: Software Development
39
+ Requires-Python: >=3.11
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Provides-Extra: dev
43
+ Requires-Dist: pytest>=8.0; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ # dint
47
+
48
+ One local chat API. Engine CLIs do the work. [Codicent Logbook](https://logbook.codicent.ai) is the ledger.
49
+
50
+ Site: [izaxon.github.io/dint](https://izaxon.github.io/dint/)
51
+
52
+ ```
53
+ Router.start_chat / send / cancel
54
+ │
55
+ ├─ Engine Claude / Codex / Grok / Copilot CLI (resume via session id)
56
+ └─ Logbook post_message / get_messages / get_history
57
+ │
58
+ └─ ChatLog #user vs #bot, parentId chain, GetMessageHistory
59
+ ```
60
+
61
+ Coding agents already ship as official CLIs. Each one keeps its own sessions, transcripts, and resume ids. dint does not reimplement them. It starts a chat, streams a turn, and writes every message to Logbook as an append-only thread. A job is just a tagged Logbook message (`#job`); `dint serve` runs it.
62
+
63
+ v0: local, four engines, webhook jobs. Not a hosted product and not a desktop UI.
64
+
65
+ ## Install
66
+
67
+ Python 3.11+ and [pipx](https://pipx.pypa.io/), at least one engine CLI on PATH (`grok`, `claude`, `codex`, or `copilot`), and [logbook-server](https://logbook.codicent.ai) on PATH.
68
+
69
+ ```bash
70
+ # Windows
71
+ iwr https://logbook.codicent.ai/install.ps1 | iex
72
+ # Linux / macOS
73
+ curl -fsSL https://logbook.codicent.ai/install.sh | bash
74
+
75
+ pipx install dint-cli
76
+ ```
77
+
78
+ The PyPI name is `dint-cli` (`dint` is taken). From a checkout: `pipx install .` or `pip install -e ".[dev]"`.
79
+
80
+ Then, in any folder:
81
+
82
+ ```bash
83
+ dint
84
+ ```
85
+
86
+ That starts logbook-server and a background `dint serve` if they are not running, then opens a chat in the current directory (same idea as running `grok` in a new folder). Config lives in `~/.dint`. `dint grok "Summarize this repo"` is a one-shot; `dint status` checks Logbook, serve, and engine CLIs.
87
+
88
+ ## Chat
89
+
90
+ ```bash
91
+ dint
92
+ dint grok "Summarize this repo"
93
+ dint start grok .
94
+ dint send <chat_id> "Summarize this repo"
95
+ dint chats
96
+ dint list <chat_id>
97
+ dint show <chat_id>
98
+ ```
99
+
100
+ Bare `dint` resumes the latest chat for this folder, or starts one with the first engine CLI on PATH (`DINT_ENGINE` to pick). `/new` starts a fresh chat; `/quit` exits. Logbook and `dint serve` keep running in the background.
101
+
102
+ Python:
103
+
104
+ ```python
105
+ from dint import Router
106
+
107
+ r = Router()
108
+ chat_id = r.start_chat("claude", cwd=".")
109
+ for ev in r.send(chat_id, "Summarize this repo"):
110
+ print(ev.type, ev.text)
111
+ ```
112
+
113
+ ## Jobs
114
+
115
+ `dint` and `dint job` start a background `dint serve` if it is not running. Enqueue from the CLI or by posting a `#job` in Logbook. Run `dint serve` in the foreground if you want the webhook logs.
116
+
117
+ ```bash
118
+ dint serve
119
+ dint job grok "What can you do?"
120
+ # job <logbook-id>
121
+ # chat <chat_id>
122
+ dint list <chat_id>
123
+ ```
124
+
125
+ From Logbook:
126
+
127
+ ```
128
+ @test #job #claude
129
+ {"engine":"claude","cwd":"/src/myproj","prompt":"Summarize this repo"}
130
+ ```
131
+
132
+ or `@test #job #grok Summarize this repo`.
133
+
134
+ `dint serve` listens on `http://127.0.0.1:8787/webhook`. If register fails, start logbook-server with `LOGBOOK_WEBHOOK_URL=http://127.0.0.1:8787/webhook`. Completed turns are stored on `#chat-<id>` like a normal `send`. Ack is `#job-run` (not `#job`, so it does not loop).
135
+
136
+ Agents should use Logbook MCP (`post_message` / `get_messages`) rather than a dint MCP. The contract is in [`.grok/skills/dint-jobs/SKILL.md`](.grok/skills/dint-jobs/SKILL.md).
137
+
138
+ ## Ledger
139
+
140
+ Each chat is a Codicent-style thread: the header is the root; every later message sets `parentId` to the previous one. User turns are tagged `#user`, engine replies `#bot`. `dint list` reads `#chat-<id>` (full body) and merges `GetMessageHistory` for the parent chain — history alone can truncate long bot JSON.
141
+
142
+ | Env | Default |
143
+ | --- | --- |
144
+ | `DINT_HOME` | `~/.dint` |
145
+ | `DINT_ENGINE` | first of grok, claude, copilot, codex on PATH |
146
+ | `LOGBOOK_URL` | `http://127.0.0.1:5100` |
147
+ | `LOGBOOK_API_KEY` | generated on first run |
148
+ | `LOGBOOK_PROJECT` | `dint` |
149
+ | `LOGBOOK_TRANSPORT` | `rest` |
150
+ | `DINT_JOBS_PORT` | `8787` |
151
+ | `LOGBOOK_WEBHOOK_SECRET` | _(optional HMAC)_ |
152
+
153
+ ## License
154
+
155
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,110 @@
1
+ # dint
2
+
3
+ One local chat API. Engine CLIs do the work. [Codicent Logbook](https://logbook.codicent.ai) is the ledger.
4
+
5
+ Site: [izaxon.github.io/dint](https://izaxon.github.io/dint/)
6
+
7
+ ```
8
+ Router.start_chat / send / cancel
9
+ │
10
+ ├─ Engine Claude / Codex / Grok / Copilot CLI (resume via session id)
11
+ └─ Logbook post_message / get_messages / get_history
12
+ │
13
+ └─ ChatLog #user vs #bot, parentId chain, GetMessageHistory
14
+ ```
15
+
16
+ Coding agents already ship as official CLIs. Each one keeps its own sessions, transcripts, and resume ids. dint does not reimplement them. It starts a chat, streams a turn, and writes every message to Logbook as an append-only thread. A job is just a tagged Logbook message (`#job`); `dint serve` runs it.
17
+
18
+ v0: local, four engines, webhook jobs. Not a hosted product and not a desktop UI.
19
+
20
+ ## Install
21
+
22
+ Python 3.11+ and [pipx](https://pipx.pypa.io/), at least one engine CLI on PATH (`grok`, `claude`, `codex`, or `copilot`), and [logbook-server](https://logbook.codicent.ai) on PATH.
23
+
24
+ ```bash
25
+ # Windows
26
+ iwr https://logbook.codicent.ai/install.ps1 | iex
27
+ # Linux / macOS
28
+ curl -fsSL https://logbook.codicent.ai/install.sh | bash
29
+
30
+ pipx install dint-cli
31
+ ```
32
+
33
+ The PyPI name is `dint-cli` (`dint` is taken). From a checkout: `pipx install .` or `pip install -e ".[dev]"`.
34
+
35
+ Then, in any folder:
36
+
37
+ ```bash
38
+ dint
39
+ ```
40
+
41
+ That starts logbook-server and a background `dint serve` if they are not running, then opens a chat in the current directory (same idea as running `grok` in a new folder). Config lives in `~/.dint`. `dint grok "Summarize this repo"` is a one-shot; `dint status` checks Logbook, serve, and engine CLIs.
42
+
43
+ ## Chat
44
+
45
+ ```bash
46
+ dint
47
+ dint grok "Summarize this repo"
48
+ dint start grok .
49
+ dint send <chat_id> "Summarize this repo"
50
+ dint chats
51
+ dint list <chat_id>
52
+ dint show <chat_id>
53
+ ```
54
+
55
+ Bare `dint` resumes the latest chat for this folder, or starts one with the first engine CLI on PATH (`DINT_ENGINE` to pick). `/new` starts a fresh chat; `/quit` exits. Logbook and `dint serve` keep running in the background.
56
+
57
+ Python:
58
+
59
+ ```python
60
+ from dint import Router
61
+
62
+ r = Router()
63
+ chat_id = r.start_chat("claude", cwd=".")
64
+ for ev in r.send(chat_id, "Summarize this repo"):
65
+ print(ev.type, ev.text)
66
+ ```
67
+
68
+ ## Jobs
69
+
70
+ `dint` and `dint job` start a background `dint serve` if it is not running. Enqueue from the CLI or by posting a `#job` in Logbook. Run `dint serve` in the foreground if you want the webhook logs.
71
+
72
+ ```bash
73
+ dint serve
74
+ dint job grok "What can you do?"
75
+ # job <logbook-id>
76
+ # chat <chat_id>
77
+ dint list <chat_id>
78
+ ```
79
+
80
+ From Logbook:
81
+
82
+ ```
83
+ @test #job #claude
84
+ {"engine":"claude","cwd":"/src/myproj","prompt":"Summarize this repo"}
85
+ ```
86
+
87
+ or `@test #job #grok Summarize this repo`.
88
+
89
+ `dint serve` listens on `http://127.0.0.1:8787/webhook`. If register fails, start logbook-server with `LOGBOOK_WEBHOOK_URL=http://127.0.0.1:8787/webhook`. Completed turns are stored on `#chat-<id>` like a normal `send`. Ack is `#job-run` (not `#job`, so it does not loop).
90
+
91
+ Agents should use Logbook MCP (`post_message` / `get_messages`) rather than a dint MCP. The contract is in [`.grok/skills/dint-jobs/SKILL.md`](.grok/skills/dint-jobs/SKILL.md).
92
+
93
+ ## Ledger
94
+
95
+ Each chat is a Codicent-style thread: the header is the root; every later message sets `parentId` to the previous one. User turns are tagged `#user`, engine replies `#bot`. `dint list` reads `#chat-<id>` (full body) and merges `GetMessageHistory` for the parent chain — history alone can truncate long bot JSON.
96
+
97
+ | Env | Default |
98
+ | --- | --- |
99
+ | `DINT_HOME` | `~/.dint` |
100
+ | `DINT_ENGINE` | first of grok, claude, copilot, codex on PATH |
101
+ | `LOGBOOK_URL` | `http://127.0.0.1:5100` |
102
+ | `LOGBOOK_API_KEY` | generated on first run |
103
+ | `LOGBOOK_PROJECT` | `dint` |
104
+ | `LOGBOOK_TRANSPORT` | `rest` |
105
+ | `DINT_JOBS_PORT` | `8787` |
106
+ | `LOGBOOK_WEBHOOK_SECRET` | _(optional HMAC)_ |
107
+
108
+ ## License
109
+
110
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "dint-cli"
3
+ version = "0.1.0"
4
+ description = "One local chat API over Claude, Codex, Grok, and Copilot. Codicent Logbook is the ledger."
5
+ readme = "README.md"
6
+ license = { file = "LICENSE" }
7
+ requires-python = ">=3.11"
8
+ authors = [{ name = "Johan Isaksson", email = "johan@izaxon.com" }]
9
+ keywords = ["claude", "codex", "grok", "copilot", "logbook", "codicent"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Environment :: Console",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Topic :: Software Development",
18
+ ]
19
+ dependencies = []
20
+
21
+ [project.urls]
22
+ Homepage = "https://izaxon.github.io/dint/"
23
+ Repository = "https://github.com/izaxon/dint"
24
+ Issues = "https://github.com/izaxon/dint/issues"
25
+
26
+ [project.optional-dependencies]
27
+ dev = ["pytest>=8.0"]
28
+
29
+ [project.scripts]
30
+ dint = "dint.cli:main"
31
+
32
+ [build-system]
33
+ requires = ["setuptools>=68"]
34
+ build-backend = "setuptools.build_meta"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.pytest.ini_options]
40
+ pythonpath = ["src"]
41
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """dint — one local chat API over Claude, Codex, Grok, and Copilot."""
2
+
3
+ from dint.router import Router
4
+ from dint.types import Chat, Event
5
+
6
+ __all__ = ["Chat", "Event", "Router"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from dint.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -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())
@@ -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
+ ]