dint-cli 0.1.0__tar.gz → 0.1.2__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 → dint_cli-0.1.2}/PKG-INFO +3 -3
  2. {dint_cli-0.1.0 → dint_cli-0.1.2}/README.md +2 -2
  3. {dint_cli-0.1.0 → dint_cli-0.1.2}/pyproject.toml +1 -1
  4. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/__init__.py +1 -1
  5. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/cli.py +137 -14
  6. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/logbook/__init__.py +1 -1
  7. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/runtime.py +132 -11
  8. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/status.py +5 -0
  9. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/PKG-INFO +3 -3
  10. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_cli.py +67 -0
  11. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_runtime.py +83 -5
  12. {dint_cli-0.1.0 → dint_cli-0.1.2}/LICENSE +0 -0
  13. {dint_cli-0.1.0 → dint_cli-0.1.2}/setup.cfg +0 -0
  14. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/__main__.py +0 -0
  15. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/__init__.py +0 -0
  16. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/base.py +0 -0
  17. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/claude.py +0 -0
  18. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/codex.py +0 -0
  19. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/copilot.py +0 -0
  20. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/engines/grok.py +0 -0
  21. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/envfile.py +0 -0
  22. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/jobs.py +0 -0
  23. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/logbook/mcp.py +0 -0
  24. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/logbook/rest.py +0 -0
  25. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/proc.py +0 -0
  26. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/router.py +0 -0
  27. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint/types.py +0 -0
  28. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/SOURCES.txt +0 -0
  29. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/dependency_links.txt +0 -0
  30. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/entry_points.txt +0 -0
  31. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/requires.txt +0 -0
  32. {dint_cli-0.1.0 → dint_cli-0.1.2}/src/dint_cli.egg-info/top_level.txt +0 -0
  33. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_engines.py +0 -0
  34. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_envfile.py +0 -0
  35. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_jobs.py +0 -0
  36. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_logbook.py +0 -0
  37. {dint_cli-0.1.0 → dint_cli-0.1.2}/tests/test_router.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dint-cli
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: One local chat API over Claude, Codex, Grok, and Copilot. Codicent Logbook is the ledger.
5
5
  Author-email: Johan Isaksson <johan@izaxon.com>
6
6
  License: MIT License
@@ -83,7 +83,7 @@ Then, in any folder:
83
83
  dint
84
84
  ```
85
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.
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). One logbook covers every folder on the machine — chats store `cwd`; you do not get a server per repo. Config lives in `~/.dint`. If port 5100 already has someone else's logbook, dint picks the next free port and writes it to `~/.dint/.env`. `dint grok "Summarize this repo"` is a one-shot; `dint status` checks Logbook, serve, and engine CLIs.
87
87
 
88
88
  ## Chat
89
89
 
@@ -97,7 +97,7 @@ dint list <chat_id>
97
97
  dint show <chat_id>
98
98
  ```
99
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.
100
+ Bare `dint` opens a chat in this folder (starts logbook + serve). Inside: `/engine`, `/job`, `/chats`, `/new`, `/help`. `DINT_ENGINE` picks the default CLI. Logbook and `dint serve` keep running in the background.
101
101
 
102
102
  Python:
103
103
 
@@ -38,7 +38,7 @@ Then, in any folder:
38
38
  dint
39
39
  ```
40
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.
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). One logbook covers every folder on the machine — chats store `cwd`; you do not get a server per repo. Config lives in `~/.dint`. If port 5100 already has someone else's logbook, dint picks the next free port and writes it to `~/.dint/.env`. `dint grok "Summarize this repo"` is a one-shot; `dint status` checks Logbook, serve, and engine CLIs.
42
42
 
43
43
  ## Chat
44
44
 
@@ -52,7 +52,7 @@ dint list <chat_id>
52
52
  dint show <chat_id>
53
53
  ```
54
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.
55
+ Bare `dint` opens a chat in this folder (starts logbook + serve). Inside: `/engine`, `/job`, `/chats`, `/new`, `/help`. `DINT_ENGINE` picks the default CLI. Logbook and `dint serve` keep running in the background.
56
56
 
57
57
  Python:
58
58
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dint-cli"
3
- version = "0.1.0"
3
+ version = "0.1.2"
4
4
  description = "One local chat API over Claude, Codex, Grok, and Copilot. Codicent Logbook is the ledger."
5
5
  readme = "README.md"
6
6
  license = { file = "LICENSE" }
@@ -4,4 +4,4 @@ from dint.router import Router
4
4
  from dint.types import Chat, Event
5
5
 
6
6
  __all__ = ["Chat", "Event", "Router"]
7
- __version__ = "0.1.0"
7
+ __version__ = "0.1.2"
@@ -9,7 +9,7 @@ import sys
9
9
  from dint import __version__
10
10
  from dint.envfile import load_dotenv
11
11
  from dint.router import ENGINES, Router
12
- from dint.runtime import ensure_runtime, pick_engine, serve_running
12
+ from dint.runtime import ensure_runtime, jobs_url, logbook_url, pick_engine, serve_running
13
13
 
14
14
  COMMANDS = {
15
15
  "start",
@@ -35,9 +35,16 @@ def main(argv: list[str] | None = None) -> int:
35
35
 
36
36
  p = argparse.ArgumentParser(
37
37
  prog="dint",
38
+ formatter_class=argparse.RawDescriptionHelpFormatter,
38
39
  description=(
39
40
  "Chat router over Claude, Codex, Grok, and Copilot. "
40
- "Run `dint` or `dint grok` in a folder to start logbook + serve and chat."
41
+ "No command opens a chat in this folder (starts logbook + serve)."
42
+ ),
43
+ epilog=(
44
+ "examples:\n"
45
+ " dint chat REPL (/help inside)\n"
46
+ " dint grok \"Summarize this\" one-shot\n"
47
+ " dint job grok \"Summarize this\" enqueue a #job"
41
48
  ),
42
49
  )
43
50
  p.add_argument("--version", action="version", version=f"dint {__version__}")
@@ -174,11 +181,12 @@ def run_chat(engine: str | None, prompt: str | None) -> int:
174
181
  print("dint: pass a prompt, or run in a terminal", file=sys.stderr)
175
182
  return 2
176
183
  router = Router()
184
+ had = any(_cwd_key(str(c.get("cwd") or "")) == _cwd_key(cwd) for c in router.list_chats())
177
185
  engine, chat_id = _resume_or_start(router, engine, cwd)
178
- print(f"{engine} {cwd} {chat_id}", file=sys.stderr)
179
186
  if prompt:
187
+ print(f"{engine} {cwd} {chat_id}", file=sys.stderr)
180
188
  return _send(router, chat_id, prompt)
181
- return _repl(router, engine, cwd, chat_id)
189
+ return _repl(router, engine, cwd, chat_id, fresh=not had)
182
190
 
183
191
 
184
192
  def _resume_or_start(router: Router, engine: str | None, cwd: str) -> tuple[str, str]:
@@ -204,31 +212,146 @@ def _resume_or_start(router: Router, engine: str | None, cwd: str) -> tuple[str,
204
212
  return engine, router.start_chat(engine, cwd)
205
213
 
206
214
 
207
- def _repl(router: Router, engine: str, cwd: str, chat_id: str) -> int:
208
- print("message, /new, /quit", file=sys.stderr)
215
+ def _repl(router: Router, engine: str, cwd: str, chat_id: str, *, fresh: bool) -> int:
216
+ _print_banner(engine, cwd, chat_id, fresh=fresh)
209
217
  while True:
210
218
  try:
211
- line = input()
219
+ line = input(f"{engine}> ")
212
220
  except (EOFError, KeyboardInterrupt):
213
221
  print(file=sys.stderr)
214
222
  return 0
215
223
  text = line.strip()
216
224
  if not text:
217
225
  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
226
  if text.startswith("/"):
225
- print("commands: /new /quit", file=sys.stderr)
227
+ action, engine, chat_id = _slash(router, engine, cwd, chat_id, text)
228
+ if action == "quit":
229
+ return 0
226
230
  continue
227
231
  code = _send(router, chat_id, text, quiet_done=True)
228
232
  if code != 0:
229
233
  return code
230
234
 
231
235
 
236
+ def _print_banner(engine: str, cwd: str, chat_id: str, *, fresh: bool) -> None:
237
+ print(f"{engine} {cwd} chat {chat_id}", file=sys.stderr)
238
+ print(f"logbook {logbook_url()} serve {jobs_url()}", file=sys.stderr)
239
+ if fresh:
240
+ print(
241
+ f'no chats here yet — type a prompt, or: dint job {engine} "Summarize this repo"',
242
+ file=sys.stderr,
243
+ )
244
+ print("/engine /job /chats /new /help quit: Ctrl-C or /quit", file=sys.stderr)
245
+
246
+
247
+ def _print_help(engine: str) -> None:
248
+ print(
249
+ "slash:\n"
250
+ " /engine CLIs on PATH\n"
251
+ " /engine claude switch engine (new or resume in this folder)\n"
252
+ " /job [engine] text enqueue a #job (dint serve runs it)\n"
253
+ " /chats chats in this folder\n"
254
+ " /status logbook + engines\n"
255
+ " /new new chat, same engine\n"
256
+ " /help /quit\n"
257
+ "same from another shell:\n"
258
+ f' dint job {engine} "Summarize this repo"\n'
259
+ " dint chats\n"
260
+ " dint status",
261
+ file=sys.stderr,
262
+ )
263
+
264
+
265
+ def _slash(
266
+ router: Router, engine: str, cwd: str, chat_id: str, text: str
267
+ ) -> tuple[str, str, str]:
268
+ parts = text.split()
269
+ cmd = parts[0].lower()
270
+ args = parts[1:]
271
+ if cmd in {"/quit", "/exit", "/q"}:
272
+ return "quit", engine, chat_id
273
+ if cmd == "/help":
274
+ _print_help(engine)
275
+ return "ok", engine, chat_id
276
+ if cmd == "/new":
277
+ chat_id = router.start_chat(engine, cwd)
278
+ print(f"{engine} {cwd} chat {chat_id}", file=sys.stderr)
279
+ return "ok", engine, chat_id
280
+ if cmd == "/engine":
281
+ if not args:
282
+ _print_engines(engine)
283
+ return "ok", engine, chat_id
284
+ name = args[0].lower()
285
+ if name not in ENGINES:
286
+ print(f"unknown engine: {name} ({', '.join(sorted(ENGINES))})", file=sys.stderr)
287
+ return "ok", engine, chat_id
288
+ if shutil.which(name) is None:
289
+ print(f"{name} is not on PATH", file=sys.stderr)
290
+ return "ok", engine, chat_id
291
+ engine, chat_id = _resume_or_start(router, name, cwd)
292
+ print(f"{engine} {cwd} chat {chat_id}", file=sys.stderr)
293
+ return "ok", engine, chat_id
294
+ if cmd == "/chats":
295
+ _print_chats(router, cwd, chat_id)
296
+ return "ok", engine, chat_id
297
+ if cmd == "/status":
298
+ from dint.status import run_status
299
+
300
+ run_status()
301
+ return "ok", engine, chat_id
302
+ if cmd == "/job":
303
+ _slash_job(router, engine, cwd, args)
304
+ return "ok", engine, chat_id
305
+ print("commands: /engine /job /chats /status /new /help /quit", file=sys.stderr)
306
+ return "ok", engine, chat_id
307
+
308
+
309
+ def _slash_job(router: Router, engine: str, cwd: str, args: list[str]) -> None:
310
+ from dint.jobs import post_job, wait_for_job_chat
311
+
312
+ if not args:
313
+ print(f'/job [engine] prompt e.g. /job {engine} Summarize this repo', file=sys.stderr)
314
+ return
315
+ job_engine = engine
316
+ prompt_parts = args
317
+ if args[0].lower() in ENGINES:
318
+ job_engine = args[0].lower()
319
+ prompt_parts = args[1:]
320
+ prompt = " ".join(prompt_parts).strip()
321
+ if not prompt:
322
+ print("/job: prompt required", file=sys.stderr)
323
+ return
324
+ job_id = post_job(router, job_engine, prompt, cwd)
325
+ print(f"job\t{job_id}", file=sys.stderr)
326
+ new_chat = wait_for_job_chat(router, job_id)
327
+ if new_chat:
328
+ print(f"chat\t{new_chat} dint list {new_chat}", file=sys.stderr)
329
+ else:
330
+ print("waiting for dint serve... try: /chats", file=sys.stderr)
331
+
332
+
333
+ def _print_engines(current: str) -> None:
334
+ for name in sorted(ENGINES):
335
+ path = shutil.which(name)
336
+ mark = "*" if name == current else " "
337
+ print(f"{mark} {name:8} {path or 'NOT ON PATH'}", file=sys.stderr)
338
+
339
+
340
+ def _print_chats(router: Router, cwd: str, current: str) -> None:
341
+ key = _cwd_key(cwd)
342
+ rows = [c for c in router.list_chats() if _cwd_key(str(c.get("cwd") or "")) == key]
343
+ if not rows:
344
+ print("no chats in this folder dint chats", file=sys.stderr)
345
+ return
346
+ for c in rows:
347
+ mark = "*" if c.get("chatId") == current else " "
348
+ preview = (c.get("preview") or "").replace("\n", " ")[:50]
349
+ print(
350
+ f"{mark} {c.get('ts')}\t{c.get('chatId')}\t{c.get('engine')}\t{preview}",
351
+ file=sys.stderr,
352
+ )
353
+
354
+
232
355
  def _send(router: Router, chat_id: str, prompt: str, *, quiet_done: bool = False) -> int:
233
356
  printer = EventPrinter(quiet_done=quiet_done)
234
357
  try:
@@ -28,7 +28,7 @@ def _env(name: str, default: str) -> str:
28
28
 
29
29
  def default_logbook() -> Logbook:
30
30
  url = _env("LOGBOOK_URL", "http://127.0.0.1:5100")
31
- key = _env("LOGBOOK_API_KEY", "test-local-key")
31
+ key = _env("LOGBOOK_API_KEY", "")
32
32
  if _env("LOGBOOK_TRANSPORT", "rest") == "mcp":
33
33
  return McpLogbook(url, key)
34
34
  return RestLogbook(url, key)
@@ -2,9 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import os
6
7
  import secrets
7
8
  import shutil
9
+ import socket
8
10
  import subprocess
9
11
  import sys
10
12
  import time
@@ -14,6 +16,7 @@ from pathlib import Path
14
16
  from urllib.parse import urlparse
15
17
 
16
18
  from dint.envfile import home_dir, home_env_path, write_env
19
+ from dint.logbook.rest import LogbookError, RestLogbook
17
20
 
18
21
  LOGBOOK_INSTALL = "https://logbook.codicent.ai"
19
22
 
@@ -29,24 +32,37 @@ def ensure_defaults() -> None:
29
32
  home_dir().mkdir(parents=True, exist_ok=True)
30
33
  os.environ.setdefault("LOGBOOK_URL", "http://127.0.0.1:5100")
31
34
  os.environ.setdefault("LOGBOOK_PROJECT", "dint")
32
- if not os.environ.get("LOGBOOK_API_KEY", "").strip():
33
- os.environ["LOGBOOK_API_KEY"] = secrets.token_urlsafe(16)
34
35
  path = home_env_path()
35
36
  if not path.is_file():
36
- write_env(
37
- path,
38
- {
39
- "LOGBOOK_URL": os.environ["LOGBOOK_URL"],
40
- "LOGBOOK_API_KEY": os.environ["LOGBOOK_API_KEY"],
41
- "LOGBOOK_PROJECT": os.environ["LOGBOOK_PROJECT"],
42
- },
43
- )
37
+ _write_home_env()
44
38
  os.environ.setdefault("DINT_ENV_FILE", str(path))
45
39
 
46
40
 
47
41
  def ensure_logbook() -> None:
48
- if probe(logbook_url() + "/health"):
42
+ """Reuse a reachable logbook we can auth to; otherwise start one for this machine.
43
+
44
+ One logbook-server process is one project/database. dint does not start a
45
+ server per repo: chats already store cwd. If :5100 is someone else's
46
+ logbook (401), pick the next free port and persist it in ~/.dint/.env.
47
+ """
48
+ health = logbook_health()
49
+ if health is not None and _auth_ok():
50
+ running = str(health.get("project") or "")
51
+ ours = os.environ.get("LOGBOOK_PROJECT", "dint")
52
+ if running and running != ours:
53
+ _note(f"using logbook project={running} at {logbook_url()}")
49
54
  return
55
+ if health is not None:
56
+ _note(f"{logbook_url()} is another logbook; starting dint's own")
57
+ _relocate_logbook_port()
58
+ elif not can_bind(logbook_host(), logbook_port()):
59
+ _relocate_logbook_port()
60
+ _spawn_logbook()
61
+ ensure_logbook_auth(logbook_health())
62
+
63
+
64
+ def _spawn_logbook() -> None:
65
+ _ensure_own_api_key()
50
66
  binary = shutil.which("logbook-server")
51
67
  if not binary:
52
68
  raise RuntimeError(
@@ -74,11 +90,90 @@ def ensure_logbook() -> None:
74
90
  )
75
91
 
76
92
 
93
+ def _auth_ok() -> bool:
94
+ rest = RestLogbook(logbook_url(), os.environ.get("LOGBOOK_API_KEY", "").strip())
95
+ try:
96
+ rest.get_messages(length=1)
97
+ return True
98
+ except LogbookError as e:
99
+ if "401" in str(e) or "Unauthorized" in str(e):
100
+ return False
101
+ raise RuntimeError(str(e)) from e
102
+
103
+
104
+ def ensure_logbook_auth(health: dict | None = None) -> None:
105
+ if _auth_ok():
106
+ return
107
+ env_file = os.environ.get("DINT_ENV_FILE") or str(home_env_path())
108
+ running = ""
109
+ if health and health.get("project"):
110
+ running = f" Server project is {health['project']}."
111
+ raise RuntimeError(
112
+ f"logbook at {logbook_url()} rejected dint's API key.{running}\n"
113
+ f"dint read LOGBOOK_API_KEY from {env_file}."
114
+ )
115
+
116
+
117
+ def _relocate_logbook_port() -> None:
118
+ host = logbook_host()
119
+ start = logbook_port() + 1
120
+ port = find_free_port(host, start)
121
+ os.environ["LOGBOOK_URL"] = f"{logbook_scheme()}://{host}:{port}"
122
+ _write_home_env()
123
+ _note(f"logbook {os.environ['LOGBOOK_URL']}")
124
+
125
+
126
+ def find_free_port(host: str, start: int, *, count: int = 30) -> int:
127
+ bind_host = "127.0.0.1" if host in {"localhost", "127.0.0.1", "::1"} else host
128
+ for port in range(start, start + count):
129
+ if probe(f"http://{bind_host}:{port}/health"):
130
+ continue
131
+ if can_bind(bind_host, port):
132
+ return port
133
+ raise RuntimeError(f"no free port in {start}-{start + count - 1} for logbook-server")
134
+
135
+
136
+ def can_bind(host: str, port: int) -> bool:
137
+ bind_host = "127.0.0.1" if host in {"localhost", ""} else host
138
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
139
+ try:
140
+ sock.bind((bind_host, port))
141
+ return True
142
+ except OSError:
143
+ return False
144
+ finally:
145
+ sock.close()
146
+
147
+
148
+ def _ensure_own_api_key() -> None:
149
+ if os.environ.get("LOGBOOK_API_KEY", "").strip():
150
+ return
151
+ os.environ["LOGBOOK_API_KEY"] = secrets.token_urlsafe(16)
152
+ _write_home_env()
153
+
154
+
155
+ def _write_home_env() -> None:
156
+ values = {
157
+ "LOGBOOK_URL": os.environ.get("LOGBOOK_URL", "http://127.0.0.1:5100"),
158
+ "LOGBOOK_PROJECT": os.environ.get("LOGBOOK_PROJECT", "dint"),
159
+ }
160
+ key = os.environ.get("LOGBOOK_API_KEY", "").strip()
161
+ if key:
162
+ values["LOGBOOK_API_KEY"] = key
163
+ values["DINT_JOBS_PORT"] = str(jobs_port())
164
+ write_env(home_env_path(), values)
165
+
166
+
77
167
  def ensure_serve() -> None:
78
168
  if os.environ.get("DINT_ROLE") == "serve":
79
169
  return
80
170
  if probe(jobs_url() + "/health"):
81
171
  return
172
+ if not can_bind(jobs_host(), jobs_port()):
173
+ port = find_free_port(jobs_host(), jobs_port() + 1)
174
+ os.environ["DINT_JOBS_PORT"] = str(port)
175
+ _write_home_env()
176
+ _note(f"dint serve {jobs_url()}")
82
177
  env = os.environ.copy()
83
178
  env["DINT_ROLE"] = "serve"
84
179
  pid = spawn_detached(
@@ -123,6 +218,18 @@ def logbook_url() -> str:
123
218
  return os.environ.get("LOGBOOK_URL", "http://127.0.0.1:5100").rstrip("/")
124
219
 
125
220
 
221
+ def logbook_scheme() -> str:
222
+ return urlparse(logbook_url()).scheme or "http"
223
+
224
+
225
+ def logbook_host() -> str:
226
+ return urlparse(logbook_url()).hostname or "127.0.0.1"
227
+
228
+
229
+ def logbook_port() -> int:
230
+ return urlparse(logbook_url()).port or 5100
231
+
232
+
126
233
  def jobs_host() -> str:
127
234
  return os.environ.get("DINT_JOBS_HOST", "127.0.0.1")
128
235
 
@@ -141,6 +248,20 @@ def logbook_install_cmd() -> str:
141
248
  return "curl -fsSL https://logbook.codicent.ai/install.sh | bash"
142
249
 
143
250
 
251
+ def logbook_health(*, timeout: float = 1.5) -> dict | None:
252
+ try:
253
+ req = urllib.request.Request(
254
+ logbook_url() + "/health",
255
+ method="GET",
256
+ headers={"Accept": "application/json"},
257
+ )
258
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
259
+ data = json.loads(resp.read().decode("utf-8") or "{}")
260
+ return data if isinstance(data, dict) else {"raw": data}
261
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError, json.JSONDecodeError):
262
+ return None
263
+
264
+
144
265
  def probe(url: str, timeout: float = 1.5) -> bool:
145
266
  try:
146
267
  req = urllib.request.Request(url, method="GET", headers={"Accept": "application/json"})
@@ -36,6 +36,11 @@ def run_status() -> int:
36
36
  print("auth: OK")
37
37
  except LogbookError as e:
38
38
  print(f"auth: FAIL {e}")
39
+ if "401" in str(e) or "Unauthorized" in str(e):
40
+ print(
41
+ "note: this URL is another logbook's key. Run `dint` and it will "
42
+ "start its own on the next free port, or put the server's key in ~/.dint/.env."
43
+ )
39
44
  failed += 1
40
45
 
41
46
  hook = jobs_url()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dint-cli
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: One local chat API over Claude, Codex, Grok, and Copilot. Codicent Logbook is the ledger.
5
5
  Author-email: Johan Isaksson <johan@izaxon.com>
6
6
  License: MIT License
@@ -83,7 +83,7 @@ Then, in any folder:
83
83
  dint
84
84
  ```
85
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.
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). One logbook covers every folder on the machine — chats store `cwd`; you do not get a server per repo. Config lives in `~/.dint`. If port 5100 already has someone else's logbook, dint picks the next free port and writes it to `~/.dint/.env`. `dint grok "Summarize this repo"` is a one-shot; `dint status` checks Logbook, serve, and engine CLIs.
87
87
 
88
88
  ## Chat
89
89
 
@@ -97,7 +97,7 @@ dint list <chat_id>
97
97
  dint show <chat_id>
98
98
  ```
99
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.
100
+ Bare `dint` opens a chat in this folder (starts logbook + serve). Inside: `/engine`, `/job`, `/chats`, `/new`, `/help`. `DINT_ENGINE` picks the default CLI. Logbook and `dint serve` keep running in the background.
101
101
 
102
102
  Python:
103
103
 
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import os
4
+ import sys
4
5
 
5
6
  from dint.cli import EventPrinter, _job_cwd_prompt, main
6
7
  from dint.logbook import ChatLog
@@ -108,6 +109,72 @@ def test_dint_resumes_same_cwd(monkeypatch, capsys, tmp_path) -> None:
108
109
  assert [t.get("text") for t in turns if t.get("role") == "user"] == ["first", "second"]
109
110
 
110
111
 
112
+ def test_repl_help_engine_quit(monkeypatch, capsys, tmp_path) -> None:
113
+ monkeypatch.chdir(tmp_path)
114
+ monkeypatch.setattr("dint.cli.ensure_runtime", lambda **k: None)
115
+ monkeypatch.setattr("dint.cli.pick_engine", lambda: "grok")
116
+ monkeypatch.setattr("dint.cli.shutil.which", lambda name: f"/bin/{name}" if name != "codex" else None)
117
+ monkeypatch.setattr("dint.cli.logbook_url", lambda: "http://127.0.0.1:5101")
118
+ monkeypatch.setattr("dint.cli.jobs_url", lambda: "http://127.0.0.1:8787")
119
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
120
+ router = Router(
121
+ store=ChatLog(MemoryLogbook(), project="dint"),
122
+ engines={"grok": FakeEngine("grok", []), "claude": FakeEngine("claude", [])},
123
+ )
124
+ monkeypatch.setattr("dint.cli.Router", lambda: router)
125
+ lines = iter(["/help", "/engine", "/quit"])
126
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(lines))
127
+ assert main([]) == 0
128
+ err = capsys.readouterr().err
129
+ assert "/job" in err and "dint job" in err
130
+ assert "* grok" in err
131
+ assert "NOT ON PATH" in err
132
+ assert "no chats here yet" in err
133
+ assert "grok " in err or "chat " in err
134
+
135
+
136
+ def test_repl_engine_switch(monkeypatch, capsys, tmp_path) -> None:
137
+ monkeypatch.chdir(tmp_path)
138
+ monkeypatch.setattr("dint.cli.ensure_runtime", lambda **k: None)
139
+ monkeypatch.setattr("dint.cli.pick_engine", lambda: "grok")
140
+ monkeypatch.setattr("dint.cli.shutil.which", lambda name: f"/bin/{name}")
141
+ monkeypatch.setattr("dint.cli.logbook_url", lambda: "http://127.0.0.1:5100")
142
+ monkeypatch.setattr("dint.cli.jobs_url", lambda: "http://127.0.0.1:8787")
143
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
144
+ router = Router(
145
+ store=ChatLog(MemoryLogbook(), project="dint"),
146
+ engines={"grok": FakeEngine("grok", []), "claude": FakeEngine("claude", [])},
147
+ )
148
+ monkeypatch.setattr("dint.cli.Router", lambda: router)
149
+ lines = iter(["/engine claude", "/quit"])
150
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(lines))
151
+ assert main([]) == 0
152
+ engines = {c["engine"] for c in router.list_chats()}
153
+ assert "claude" in engines
154
+
155
+
156
+ def test_repl_job(monkeypatch, capsys, tmp_path) -> None:
157
+ monkeypatch.chdir(tmp_path)
158
+ monkeypatch.setattr("dint.cli.ensure_runtime", lambda **k: None)
159
+ monkeypatch.setattr("dint.cli.pick_engine", lambda: "grok")
160
+ monkeypatch.setattr("dint.cli.shutil.which", lambda name: f"/bin/{name}")
161
+ monkeypatch.setattr("dint.cli.logbook_url", lambda: "http://127.0.0.1:5100")
162
+ monkeypatch.setattr("dint.cli.jobs_url", lambda: "http://127.0.0.1:8787")
163
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
164
+ router = Router(
165
+ store=ChatLog(MemoryLogbook(), project="dint"),
166
+ engines={"grok": FakeEngine("grok", [])},
167
+ )
168
+ monkeypatch.setattr("dint.cli.Router", lambda: router)
169
+ monkeypatch.setattr("dint.jobs.post_job", lambda router, engine, prompt, cwd: "job-1")
170
+ monkeypatch.setattr("dint.jobs.wait_for_job_chat", lambda router, job_id, timeout=20: "chatjob")
171
+ lines = iter(["/job Summarize this repo", "/quit"])
172
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(lines))
173
+ assert main([]) == 0
174
+ err = capsys.readouterr().err
175
+ assert "job-1" in err and "chatjob" in err
176
+
177
+
111
178
  def test_cli_streams_tokens_inline(capsys) -> None:
112
179
  printer = EventPrinter()
113
180
  printer.emit(Event(type="text", text="He"))
@@ -5,14 +5,33 @@ from pathlib import Path
5
5
 
6
6
  import pytest
7
7
 
8
+ from dint.logbook.rest import LogbookError
8
9
  from dint.runtime import (
10
+ can_bind,
9
11
  ensure_defaults,
10
12
  ensure_logbook,
11
13
  ensure_serve,
14
+ find_free_port,
12
15
  pick_engine,
13
16
  )
14
17
 
15
18
 
19
+ class _OkRest:
20
+ def __init__(self, *_a, **_k) -> None:
21
+ pass
22
+
23
+ def get_messages(self, length: int = 1) -> list:
24
+ return []
25
+
26
+
27
+ class _UnauthorizedRest:
28
+ def __init__(self, *_a, **_k) -> None:
29
+ pass
30
+
31
+ def get_messages(self, length: int = 1) -> list:
32
+ raise LogbookError('HTTP 401 GET /api/messages: {"error":"Unauthorized"}')
33
+
34
+
16
35
  def test_ensure_defaults_writes_home_env(tmp_path, monkeypatch) -> None:
17
36
  monkeypatch.setenv("DINT_HOME", str(tmp_path))
18
37
  monkeypatch.delenv("LOGBOOK_API_KEY", raising=False)
@@ -22,12 +41,16 @@ def test_ensure_defaults_writes_home_env(tmp_path, monkeypatch) -> None:
22
41
  text = (tmp_path / ".env").read_text(encoding="utf-8")
23
42
  assert "LOGBOOK_PROJECT=dint" in text
24
43
  assert "LOGBOOK_URL=http://127.0.0.1:5100" in text
25
- assert os.environ["LOGBOOK_API_KEY"]
44
+ assert "LOGBOOK_API_KEY" not in text
26
45
  assert os.environ["LOGBOOK_PROJECT"] == "dint"
27
46
 
28
47
 
29
48
  def test_ensure_logbook_skips_when_healthy(monkeypatch) -> None:
30
- monkeypatch.setattr("dint.runtime.probe", lambda url, timeout=1.5: True)
49
+ monkeypatch.setattr(
50
+ "dint.runtime.logbook_health",
51
+ lambda **k: {"status": "healthy", "project": "test"},
52
+ )
53
+ monkeypatch.setattr("dint.runtime.RestLogbook", _OkRest)
31
54
 
32
55
  def boom(*_a, **_k):
33
56
  raise AssertionError("should not spawn")
@@ -36,9 +59,37 @@ def test_ensure_logbook_skips_when_healthy(monkeypatch) -> None:
36
59
  ensure_logbook()
37
60
 
38
61
 
62
+ def test_ensure_logbook_foreign_starts_on_new_port(tmp_path, monkeypatch) -> None:
63
+ monkeypatch.setenv("DINT_HOME", str(tmp_path))
64
+ monkeypatch.setenv("LOGBOOK_URL", "http://127.0.0.1:5100")
65
+ monkeypatch.setenv("LOGBOOK_API_KEY", "dint-key")
66
+ monkeypatch.setenv("LOGBOOK_PROJECT", "dint")
67
+
68
+ def health(**_k):
69
+ if os.environ.get("LOGBOOK_URL", "").endswith(":5100"):
70
+ return {"status": "healthy", "project": "test"}
71
+ return None
72
+
73
+ monkeypatch.setattr("dint.runtime.logbook_health", health)
74
+ monkeypatch.setattr("dint.runtime.RestLogbook", _UnauthorizedRest)
75
+ monkeypatch.setattr("dint.runtime.find_free_port", lambda host, start, count=30: 5101)
76
+ monkeypatch.setattr("dint.runtime.ensure_logbook_auth", lambda health=None: None)
77
+ monkeypatch.setattr("dint.runtime.wait_for", lambda url, timeout=12: True)
78
+ monkeypatch.setattr(
79
+ "dint.runtime.shutil.which",
80
+ lambda name: "/bin/logbook-server" if name == "logbook-server" else None,
81
+ )
82
+ monkeypatch.setattr("dint.runtime.spawn_detached", lambda argv, **k: 9)
83
+ ensure_logbook()
84
+ assert os.environ["LOGBOOK_URL"] == "http://127.0.0.1:5101"
85
+ assert "5101" in (tmp_path / ".env").read_text(encoding="utf-8")
86
+
87
+
39
88
  def test_ensure_logbook_spawns(monkeypatch, tmp_path) -> None:
40
89
  monkeypatch.setenv("DINT_HOME", str(tmp_path))
41
- monkeypatch.setattr("dint.runtime.probe", lambda url, timeout=1.5: False)
90
+ monkeypatch.delenv("LOGBOOK_API_KEY", raising=False)
91
+ monkeypatch.setattr("dint.runtime.logbook_health", lambda **k: None)
92
+ monkeypatch.setattr("dint.runtime.ensure_logbook_auth", lambda health=None: None)
42
93
  monkeypatch.setattr("dint.runtime.wait_for", lambda url, timeout=12: True)
43
94
  monkeypatch.setattr(
44
95
  "dint.runtime.shutil.which",
@@ -52,10 +103,13 @@ def test_ensure_logbook_spawns(monkeypatch, tmp_path) -> None:
52
103
  ensure_defaults()
53
104
  ensure_logbook()
54
105
  assert calls[0] == ["/bin/logbook-server"]
106
+ assert os.environ["LOGBOOK_API_KEY"]
55
107
 
56
108
 
57
- def test_ensure_logbook_missing_binary(monkeypatch) -> None:
58
- monkeypatch.setattr("dint.runtime.probe", lambda url, timeout=1.5: False)
109
+ def test_ensure_logbook_missing_binary(monkeypatch, tmp_path) -> None:
110
+ monkeypatch.setenv("DINT_HOME", str(tmp_path))
111
+ monkeypatch.delenv("LOGBOOK_API_KEY", raising=False)
112
+ monkeypatch.setattr("dint.runtime.logbook_health", lambda **k: None)
59
113
  monkeypatch.setattr("dint.runtime.shutil.which", lambda name: None)
60
114
  with pytest.raises(RuntimeError, match="logbook-server"):
61
115
  ensure_logbook()
@@ -94,6 +148,30 @@ def test_pick_engine_prefers_grok(monkeypatch) -> None:
94
148
  assert pick_engine() == "grok"
95
149
 
96
150
 
151
+ def test_find_free_port_skips_occupied(monkeypatch) -> None:
152
+ busy = {5101}
153
+
154
+ monkeypatch.setattr(
155
+ "dint.runtime.probe",
156
+ lambda url, timeout=1.5: ":5101" in url,
157
+ )
158
+ monkeypatch.setattr(
159
+ "dint.runtime.can_bind",
160
+ lambda host, port: port not in busy,
161
+ )
162
+ assert find_free_port("127.0.0.1", 5101) == 5102
163
+
164
+
165
+ def test_can_bind_occupied() -> None:
166
+ sock = __import__("socket").socket()
167
+ sock.bind(("127.0.0.1", 0))
168
+ port = sock.getsockname()[1]
169
+ try:
170
+ assert can_bind("127.0.0.1", port) is False
171
+ finally:
172
+ sock.close()
173
+
174
+
97
175
  def test_pick_engine_env_override(monkeypatch) -> None:
98
176
  monkeypatch.setenv("DINT_ENGINE", "codex")
99
177
  monkeypatch.setattr(
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes