nini-cli 0.4.1__tar.gz → 0.4.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.
- {nini_cli-0.4.1 → nini_cli-0.4.2}/PKG-INFO +4 -4
- nini_cli-0.4.2/nini_cli/__init__.py +16 -0
- nini_cli-0.4.2/nini_cli/__main__.py +6 -0
- nini_cli-0.4.2/nini_cli/app.py +197 -0
- nini_cli-0.4.2/nini_cli/cli_util.py +177 -0
- nini_cli-0.4.2/nini_cli/commands/__init__.py +1 -0
- nini_cli-0.4.2/nini_cli/commands/attach.py +279 -0
- nini_cli-0.4.2/nini_cli/commands/config_cmd.py +164 -0
- nini_cli-0.4.2/nini_cli/commands/doctor.py +249 -0
- nini_cli-0.4.2/nini_cli/commands/import_cmd.py +403 -0
- nini_cli-0.4.2/nini_cli/commands/mcp.py +387 -0
- nini_cli-0.4.2/nini_cli/commands/pair.py +149 -0
- nini_cli-0.4.2/nini_cli/commands/provider_cmd.py +411 -0
- nini_cli-0.4.2/nini_cli/commands/run.py +191 -0
- nini_cli-0.4.2/nini_cli/commands/serve.py +299 -0
- nini_cli-0.4.2/nini_cli/commands/sessions.py +132 -0
- nini_cli-0.4.2/nini_cli/commands/status.py +268 -0
- nini_cli-0.4.2/nini_cli/commands/token.py +154 -0
- nini_cli-0.4.2/nini_cli/commands/workspace.py +541 -0
- nini_cli-0.4.2/nini_cli/config.py +359 -0
- nini_cli-0.4.2/nini_cli/events.py +280 -0
- nini_cli-0.4.2/nini_cli/i18n.py +1463 -0
- nini_cli-0.4.2/nini_cli/import_api.py +467 -0
- nini_cli-0.4.2/nini_cli/mcp_api.py +426 -0
- nini_cli-0.4.2/nini_cli/permissions.py +231 -0
- nini_cli-0.4.2/nini_cli/policy.py +90 -0
- nini_cli-0.4.2/nini_cli/projects.py +1259 -0
- nini_cli-0.4.2/nini_cli/relay_api.py +96 -0
- nini_cli-0.4.2/nini_cli/roots.py +49 -0
- nini_cli-0.4.2/nini_cli/service_boot.py +610 -0
- nini_cli-0.4.2/nini_cli/startup.py +62 -0
- nini_cli-0.4.2/nini_cli/tui/__init__.py +21 -0
- nini_cli-0.4.2/nini_cli/tui/app.py +3351 -0
- nini_cli-0.4.2/nini_cli/tui/app.tcss +224 -0
- nini_cli-0.4.2/nini_cli/tui/client.py +572 -0
- nini_cli-0.4.2/nini_cli/tui/clipboard.py +85 -0
- nini_cli-0.4.2/nini_cli/tui/keymap.py +829 -0
- nini_cli-0.4.2/nini_cli/tui/mark_art.py +1002 -0
- nini_cli-0.4.2/nini_cli/tui/markdown.py +370 -0
- nini_cli-0.4.2/nini_cli/tui/models.py +426 -0
- nini_cli-0.4.2/nini_cli/tui/palette.py +307 -0
- nini_cli-0.4.2/nini_cli/tui/pointer.py +108 -0
- nini_cli-0.4.2/nini_cli/tui/render.py +879 -0
- nini_cli-0.4.2/nini_cli/tui/session_timeline.py +526 -0
- nini_cli-0.4.2/nini_cli/tui/splash.py +659 -0
- nini_cli-0.4.2/nini_cli/tui/status_line.py +478 -0
- nini_cli-0.4.2/nini_cli/tui/store.py +1647 -0
- nini_cli-0.4.2/nini_cli/tui/stream.py +155 -0
- nini_cli-0.4.2/nini_cli/tui/widgets.py +4394 -0
- nini_cli-0.4.2/nini_cli/tui_main.py +111 -0
- nini_cli-0.4.2/nini_cli/turn.py +329 -0
- nini_cli-0.4.2/nini_cli/ui.py +223 -0
- nini_cli-0.4.2/nini_cli/workspace.py +556 -0
- {nini_cli-0.4.1 → nini_cli-0.4.2}/pyproject.toml +4 -4
- {nini_cli-0.4.1 → nini_cli-0.4.2}/LICENSE +0 -0
- {nini_cli-0.4.1 → nini_cli-0.4.2}/README.md +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: nini-cli
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: Nini command line interface: start the daemon, stream a session, answer approvals
|
|
5
5
|
Project-URL: Homepage, https://nini.flygpt.cc
|
|
6
6
|
Project-URL: Repository, https://github.com/xusai2014/Nini
|
|
@@ -13,9 +13,9 @@ Classifier: Operating System :: OS Independent
|
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.12
|
|
14
14
|
Requires-Python: >=3.12
|
|
15
15
|
Requires-Dist: httpx>=0.28
|
|
16
|
-
Requires-Dist: nini-client==0.4.
|
|
17
|
-
Requires-Dist: nini-core==0.4.
|
|
18
|
-
Requires-Dist: nini-protocol==0.4.
|
|
16
|
+
Requires-Dist: nini-client==0.4.2
|
|
17
|
+
Requires-Dist: nini-core==0.4.2
|
|
18
|
+
Requires-Dist: nini-protocol==0.4.2
|
|
19
19
|
Requires-Dist: rich>=13.9
|
|
20
20
|
Requires-Dist: textual>=0.89
|
|
21
21
|
Requires-Dist: typer>=0.15
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Nini CLI package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
# iTerm2 submits an IME candidate with a kitty-keyboard CSI-u sequence (for
|
|
8
|
+
# example ``ESC[13;;100:102:115:102u`` when the candidate is "dfs"). Textual
|
|
9
|
+
# 8.2.8 enables the kitty protocol on startup and does not parse that
|
|
10
|
+
# associated-text form, so the raw sequence lands in the TextArea as literal
|
|
11
|
+
# ``^[[13;;…u``. Disable the protocol at the earliest import point: Textual
|
|
12
|
+
# reads this flag once, in ``textual.constants``, when it is first imported.
|
|
13
|
+
# ``setdefault`` keeps a user's explicit ``TEXTUAL_DISABLE_KITTY_KEY=0``.
|
|
14
|
+
os.environ.setdefault("TEXTUAL_DISABLE_KITTY_KEY", "1")
|
|
15
|
+
|
|
16
|
+
__version__ = "0.4.2"
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Typer entrypoint: ``nini`` assembles every subcommand.
|
|
2
|
+
|
|
3
|
+
``nini_cli/__init__`` is imported first (``from nini_cli import __version__``
|
|
4
|
+
below), and that package sets ``TEXTUAL_DISABLE_KITTY_KEY`` before any Textual
|
|
5
|
+
import: iTerm2 + IME sends kitty CSI-u on candidate commit that Textual 8.2.8
|
|
6
|
+
would otherwise insert as literal ``^[[13;;…u``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Annotated
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
|
|
15
|
+
from nini_cli import __version__
|
|
16
|
+
from nini_cli.startup import apply_config_language, apply_startup_language
|
|
17
|
+
|
|
18
|
+
# `nini --lang zh --help` has to answer in Chinese *before* the helps below are
|
|
19
|
+
# registered: Typer renders them from the string captured at import time.
|
|
20
|
+
apply_startup_language()
|
|
21
|
+
|
|
22
|
+
from nini_cli.commands import attach as attach_cmd # noqa: E402
|
|
23
|
+
from nini_cli.commands import config_cmd, import_cmd, provider_cmd # noqa: E402
|
|
24
|
+
from nini_cli.commands import doctor as doctor_cmd # noqa: E402
|
|
25
|
+
from nini_cli.commands import mcp as mcp_cmd # noqa: E402
|
|
26
|
+
from nini_cli.commands import pair as pair_cmd # noqa: E402
|
|
27
|
+
from nini_cli.commands import run as run_cmd # noqa: E402
|
|
28
|
+
from nini_cli.commands import serve as serve_cmd # noqa: E402
|
|
29
|
+
from nini_cli.commands import sessions as sessions_cmd # noqa: E402
|
|
30
|
+
from nini_cli.commands import status as status_cmd # noqa: E402
|
|
31
|
+
from nini_cli.commands import token as token_cmd # noqa: E402
|
|
32
|
+
from nini_cli.commands import workspace as workspace_cmd # noqa: E402
|
|
33
|
+
from nini_cli.i18n import SOURCE_FLAG, clear_language, set_language, t # noqa: E402
|
|
34
|
+
|
|
35
|
+
app = typer.Typer(
|
|
36
|
+
# Second paragraph is COPY.md `onboard.tui.body`: `nini` with no subcommand
|
|
37
|
+
# opens the TUI, so the help text is where a new user meets that fact.
|
|
38
|
+
help=f"{t('cli.help.root')}\n\n{t('onboard.tui.body')}",
|
|
39
|
+
no_args_is_help=False,
|
|
40
|
+
add_completion=False,
|
|
41
|
+
rich_markup_mode=None,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _version_callback(value: bool) -> None:
|
|
46
|
+
if value:
|
|
47
|
+
typer.echo(__version__)
|
|
48
|
+
raise typer.Exit()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _lang_callback(ctx: typer.Context, value: str | None) -> str | None:
|
|
52
|
+
"""``--lang zh|en``: this process only — the config file is never written."""
|
|
53
|
+
|
|
54
|
+
if not value:
|
|
55
|
+
return None
|
|
56
|
+
if not set_language(value, source=SOURCE_FLAG):
|
|
57
|
+
raise typer.BadParameter(t("cli.lang.invalid", value=value))
|
|
58
|
+
# A CLI invocation may run several commands in one process (`CliRunner`);
|
|
59
|
+
# hand the previous language back when this context closes.
|
|
60
|
+
ctx.call_on_close(clear_language)
|
|
61
|
+
return value.strip().lower()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_tty() -> bool:
|
|
65
|
+
import sys
|
|
66
|
+
|
|
67
|
+
return bool(sys.stdin.isatty() and sys.stdout.isatty())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _apply_configured_language(ctx: typer.Context) -> None:
|
|
71
|
+
"""Apply ``[appearance] language`` for the duration of this invocation.
|
|
72
|
+
|
|
73
|
+
Read here, once per process — never from :func:`nini_cli.i18n.t`. The
|
|
74
|
+
preference is dropped again when the context closes so one ``CliRunner``
|
|
75
|
+
call cannot leak a language into the next.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
from nini_cli.config import ConfigError, load_config
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
config = load_config()
|
|
82
|
+
except ConfigError:
|
|
83
|
+
return
|
|
84
|
+
apply_config_language(config)
|
|
85
|
+
ctx.call_on_close(lambda: apply_config_language(None))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@app.callback(invoke_without_command=True)
|
|
89
|
+
def main(
|
|
90
|
+
ctx: typer.Context,
|
|
91
|
+
version: Annotated[
|
|
92
|
+
bool,
|
|
93
|
+
typer.Option(
|
|
94
|
+
"--version", callback=_version_callback, is_eager=True, help=t("cli.help.version")
|
|
95
|
+
),
|
|
96
|
+
] = False,
|
|
97
|
+
lang: Annotated[
|
|
98
|
+
str | None,
|
|
99
|
+
typer.Option(
|
|
100
|
+
"--lang",
|
|
101
|
+
callback=_lang_callback,
|
|
102
|
+
is_eager=True,
|
|
103
|
+
help=t("cli.help.lang"),
|
|
104
|
+
metavar="<zh|en>",
|
|
105
|
+
),
|
|
106
|
+
] = None,
|
|
107
|
+
project: Annotated[
|
|
108
|
+
str | None,
|
|
109
|
+
typer.Option(
|
|
110
|
+
"--project",
|
|
111
|
+
help=t("cli.help.project"),
|
|
112
|
+
metavar="<name|id>",
|
|
113
|
+
),
|
|
114
|
+
] = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Nini command line interface.
|
|
117
|
+
|
|
118
|
+
With no subcommand (and a real terminal) this opens the full-screen TUI.
|
|
119
|
+
"""
|
|
120
|
+
from nini_cli.projects import set_requested_project
|
|
121
|
+
|
|
122
|
+
_apply_configured_language(ctx)
|
|
123
|
+
set_requested_project(project)
|
|
124
|
+
if ctx.invoked_subcommand is not None:
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
if not _is_tty():
|
|
128
|
+
typer.echo(ctx.get_help())
|
|
129
|
+
raise typer.Exit(code=2)
|
|
130
|
+
from nini_cli.service_boot import ensure_service_or_exit, last_target
|
|
131
|
+
|
|
132
|
+
ensure_service_or_exit("nini(TUI)")
|
|
133
|
+
target = last_target()
|
|
134
|
+
from nini_cli.tui_main import run_tui
|
|
135
|
+
|
|
136
|
+
raise typer.Exit(
|
|
137
|
+
code=run_tui(
|
|
138
|
+
service_url=target.url if target is not None else None,
|
|
139
|
+
project=target.project_name if target is not None else "",
|
|
140
|
+
workspace_root=(target.root or "") if target is not None else "",
|
|
141
|
+
)
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
app.command("serve", help=t("cli.help.serve"))(serve_cmd.serve)
|
|
146
|
+
app.command("status", help=t("cli.help.status"))(status_cmd.status)
|
|
147
|
+
app.command("ls", help=t("cli.help.ls"))(sessions_cmd.ls)
|
|
148
|
+
app.command("new", help=t("cli.help.new"))(sessions_cmd.new)
|
|
149
|
+
app.command("run", help=t("cli.help.run"))(run_cmd.run)
|
|
150
|
+
app.command("attach", help=t("cli.help.attach"))(attach_cmd.attach)
|
|
151
|
+
app.command("token", help=t("cli.help.token"))(token_cmd.token)
|
|
152
|
+
app.command("pair", help=t("cli.help.pair"))(pair_cmd.pair)
|
|
153
|
+
app.command("doctor", help=t("cli.help.doctor"))(doctor_cmd.doctor)
|
|
154
|
+
app.add_typer(
|
|
155
|
+
workspace_cmd.workspace_app,
|
|
156
|
+
name="workspace",
|
|
157
|
+
help=t("cli.help.workspace"),
|
|
158
|
+
)
|
|
159
|
+
app.add_typer(
|
|
160
|
+
workspace_cmd.identity_app,
|
|
161
|
+
name="identity",
|
|
162
|
+
help=t("cli.help.identity"),
|
|
163
|
+
)
|
|
164
|
+
app.add_typer(
|
|
165
|
+
mcp_cmd.app,
|
|
166
|
+
name="mcp",
|
|
167
|
+
help=t("cli.help.mcp"),
|
|
168
|
+
)
|
|
169
|
+
app.add_typer(
|
|
170
|
+
import_cmd.app,
|
|
171
|
+
name="import",
|
|
172
|
+
help=t("cli.help.import"),
|
|
173
|
+
)
|
|
174
|
+
app.add_typer(
|
|
175
|
+
provider_cmd.app,
|
|
176
|
+
name="provider",
|
|
177
|
+
help=t("cli.help.provider"),
|
|
178
|
+
)
|
|
179
|
+
app.add_typer(
|
|
180
|
+
provider_cmd.model_app,
|
|
181
|
+
name="model",
|
|
182
|
+
help=t("cli.help.model"),
|
|
183
|
+
)
|
|
184
|
+
app.add_typer(
|
|
185
|
+
config_cmd.app,
|
|
186
|
+
name="config",
|
|
187
|
+
help=t("cli.help.config"),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def run() -> None:
|
|
192
|
+
"""Console-script entrypoint (`nini`)."""
|
|
193
|
+
app()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
if __name__ == "__main__":
|
|
197
|
+
run()
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Small helpers shared by the command modules (config loading, friendly exits).
|
|
2
|
+
|
|
3
|
+
Service connection is **single-host** by default (`docs/IDENTITY.md`): every
|
|
4
|
+
command talks to one endpoint and one token, and the cwd only decides the
|
|
5
|
+
project context. ``NINI_PROJECTS=1`` restores the retired per-project daemons
|
|
6
|
+
(`docs/PROJECTS.md`); the resolution itself lives in :mod:`nini_cli.projects`,
|
|
7
|
+
this module only asks it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TextIO
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
from nini_client import NiniClient
|
|
19
|
+
|
|
20
|
+
from nini_cli import ui
|
|
21
|
+
from nini_cli.config import Config, ConfigError, load_config
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def config() -> Config:
|
|
25
|
+
"""Load config or exit with the documented code 2 (bad config)."""
|
|
26
|
+
try:
|
|
27
|
+
return load_config()
|
|
28
|
+
except ConfigError as exc:
|
|
29
|
+
ui.error(f"config error: {exc}")
|
|
30
|
+
raise typer.Exit(2) from exc
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _maybe_config() -> Config | None:
|
|
34
|
+
try:
|
|
35
|
+
return load_config()
|
|
36
|
+
except ConfigError:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def client_for(cfg: Config, *, timeout: float = 30.0) -> NiniClient:
|
|
41
|
+
"""Client bound to the one host (or the legacy per-project daemon).
|
|
42
|
+
|
|
43
|
+
In project mode (``NINI_PROJECTS=1``) the project's token is passed
|
|
44
|
+
explicitly, so one project's token can never reach another daemon. On the
|
|
45
|
+
default single-host path the host token is used for every directory.
|
|
46
|
+
"""
|
|
47
|
+
from nini_cli import projects
|
|
48
|
+
|
|
49
|
+
if projects.project_mode(cfg):
|
|
50
|
+
target = project_target(cfg)
|
|
51
|
+
if target is not None:
|
|
52
|
+
# `or ""` keeps NiniClient from falling back to ~/.nini/token: in
|
|
53
|
+
# project mode one project's token must never reach another daemon.
|
|
54
|
+
return NiniClient(target.url, token=target.token or "", timeout=timeout)
|
|
55
|
+
return NiniClient(cfg.service_url, token=service_token(cfg) or "", timeout=timeout)
|
|
56
|
+
|
|
57
|
+
return NiniClient(cfg.service_url, token=service_token(cfg), timeout=timeout)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def project_target(cfg: Config | None = None):
|
|
61
|
+
"""The project context this shell is in, plus the endpoint it talks to.
|
|
62
|
+
|
|
63
|
+
Read-only: it never registers, creates or starts anything. Project mode
|
|
64
|
+
returns the project's own daemon; the default single-host path returns the
|
|
65
|
+
shared endpoint with the cwd's project row for display (``--project`` wins
|
|
66
|
+
over the cwd).
|
|
67
|
+
"""
|
|
68
|
+
from nini_cli import projects
|
|
69
|
+
|
|
70
|
+
active = cfg if cfg is not None else _maybe_config()
|
|
71
|
+
if active is None:
|
|
72
|
+
return None
|
|
73
|
+
try:
|
|
74
|
+
if projects.project_mode(active):
|
|
75
|
+
return projects.peek_target(active)
|
|
76
|
+
return projects.host_target(active)
|
|
77
|
+
except projects.ProjectError as exc:
|
|
78
|
+
ui.error(str(exc))
|
|
79
|
+
raise typer.Exit(exc.exit_code) from exc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def resolve_service(cfg: Config) -> Config:
|
|
83
|
+
"""Point ``cfg.service_url`` at the endpoint this shell talks to (no start).
|
|
84
|
+
|
|
85
|
+
Commands that talk HTTP through helpers taking a ``Config`` (relay, mcp,
|
|
86
|
+
import) use this so they address the same daemon as ``client_for``. On the
|
|
87
|
+
single-host path the configured URL is already the answer; project mode
|
|
88
|
+
swaps in the project's port.
|
|
89
|
+
"""
|
|
90
|
+
target = project_target(cfg)
|
|
91
|
+
if target is not None:
|
|
92
|
+
cfg.service_url = target.url
|
|
93
|
+
return cfg
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def token_path(cfg: Config | None = None) -> Path:
|
|
97
|
+
"""The token file the running host uses (one per host on the default path).
|
|
98
|
+
|
|
99
|
+
Project mode: the project's state-dir token. Single host: the file
|
|
100
|
+
:func:`nini_cli.projects.host_token` resolves (``~/.nini/token``, else
|
|
101
|
+
``~/.nini/workspaces/<active>/token``), which is what every command sends.
|
|
102
|
+
"""
|
|
103
|
+
from nini_cli import projects
|
|
104
|
+
|
|
105
|
+
active = cfg if cfg is not None else _maybe_config()
|
|
106
|
+
if active is not None and projects.project_mode(active):
|
|
107
|
+
state = projects.current_state_dir(active)
|
|
108
|
+
if state is not None:
|
|
109
|
+
return state / "token"
|
|
110
|
+
return projects.host_home() / "token"
|
|
111
|
+
|
|
112
|
+
service_url = active.service_url if active is not None else None
|
|
113
|
+
return projects.host_token_source(service_url)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def service_token(cfg: Config | None = None, *, service_url: str | None = None) -> str | None:
|
|
117
|
+
"""Token for raw HTTP calls: ``NINI_TOKEN`` > project token > host token."""
|
|
118
|
+
env = os.environ.get("NINI_TOKEN")
|
|
119
|
+
if env:
|
|
120
|
+
return env
|
|
121
|
+
from nini_cli import projects
|
|
122
|
+
|
|
123
|
+
active = cfg if cfg is not None else _maybe_config()
|
|
124
|
+
if active is not None and projects.project_mode(active):
|
|
125
|
+
target = project_target(active)
|
|
126
|
+
return target.token if target is not None else None
|
|
127
|
+
target = project_target(active) if active is not None else None
|
|
128
|
+
if target is not None:
|
|
129
|
+
return target.token
|
|
130
|
+
url = service_url or (active.service_url if active is not None else None)
|
|
131
|
+
return projects.host_token(url)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def read_line(prompt: str, timeout: float = 0.0, *, stream: TextIO | None = None) -> str | None:
|
|
135
|
+
"""Print ``prompt`` and read one line; ``None`` when ``timeout`` expires.
|
|
136
|
+
|
|
137
|
+
The prompt is written to stdout (not handed to ``input``) so it still shows
|
|
138
|
+
when the answer is typed piped. ``timeout <= 0`` waits forever; a stdin
|
|
139
|
+
without a usable file descriptor also falls back to a blocking read.
|
|
140
|
+
|
|
141
|
+
Returns ``""`` on EOF so callers see "no answer" rather than an exception.
|
|
142
|
+
"""
|
|
143
|
+
ui.write(prompt)
|
|
144
|
+
if timeout > 0 and _wait_readable(stream or sys.stdin, timeout) is False:
|
|
145
|
+
return None
|
|
146
|
+
try:
|
|
147
|
+
return input("")
|
|
148
|
+
except EOFError:
|
|
149
|
+
return ""
|
|
150
|
+
except KeyboardInterrupt:
|
|
151
|
+
return ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _wait_readable(stream: TextIO, timeout: float) -> bool | None:
|
|
155
|
+
"""``True``/``False`` from ``select``; ``None`` when the stream has no fd."""
|
|
156
|
+
try:
|
|
157
|
+
import select
|
|
158
|
+
|
|
159
|
+
fd = stream.fileno()
|
|
160
|
+
except (AttributeError, ImportError, OSError, ValueError):
|
|
161
|
+
return None
|
|
162
|
+
try:
|
|
163
|
+
ready, _, _ = select.select([fd], [], [], timeout)
|
|
164
|
+
except (OSError, ValueError):
|
|
165
|
+
return None
|
|
166
|
+
return bool(ready)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
__all__ = [
|
|
170
|
+
"client_for",
|
|
171
|
+
"config",
|
|
172
|
+
"project_target",
|
|
173
|
+
"read_line",
|
|
174
|
+
"resolve_service",
|
|
175
|
+
"service_token",
|
|
176
|
+
"token_path",
|
|
177
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Typer entrypoint: `nini` assembles every subcommand."""
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""``nini attach [session]`` — interactive REPL over the event stream."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextvars
|
|
7
|
+
from typing import Annotated, Any
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from nini_client import NiniClientError, NiniConnectionError, NiniHTTPError
|
|
11
|
+
|
|
12
|
+
from nini_cli import ui
|
|
13
|
+
from nini_cli.cli_util import client_for
|
|
14
|
+
from nini_cli.cli_util import config as load_cli_config
|
|
15
|
+
from nini_cli.commands import sessions as sessions_cmd
|
|
16
|
+
from nini_cli.config import Config
|
|
17
|
+
from nini_cli.events import EventPrinter
|
|
18
|
+
from nini_cli.i18n import t
|
|
19
|
+
from nini_cli.permissions import DEFAULT_PROMPT_TIMEOUT, PermissionBroker
|
|
20
|
+
from nini_cli.service_boot import ensure_service_or_exit, start_hint
|
|
21
|
+
from nini_cli.turn import run_turn, with_interrupt_guard
|
|
22
|
+
|
|
23
|
+
PROMPT = "nini> "
|
|
24
|
+
HELP_LINE = "commands: /new [title] /ls /stop /files [path] /exit"
|
|
25
|
+
|
|
26
|
+
_BROKER: contextvars.ContextVar[PermissionBroker | None] = contextvars.ContextVar(
|
|
27
|
+
"nini_attach_permissions", default=None
|
|
28
|
+
)
|
|
29
|
+
"""One broker for the whole REPL: ``a`` (always) only lives as long as we attach."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def attach(
|
|
33
|
+
session: Annotated[
|
|
34
|
+
str | None, typer.Argument(help="Session id (defaults to the most recent one).")
|
|
35
|
+
] = None,
|
|
36
|
+
yes: Annotated[
|
|
37
|
+
bool,
|
|
38
|
+
typer.Option("--yes", "-y", help="Approve every tool call without asking (use with care)."),
|
|
39
|
+
] = False,
|
|
40
|
+
no_input: Annotated[
|
|
41
|
+
bool,
|
|
42
|
+
typer.Option("--no-input", help="Never prompt; deny any tool call that needs approval."),
|
|
43
|
+
] = False,
|
|
44
|
+
permission_timeout: Annotated[
|
|
45
|
+
float,
|
|
46
|
+
typer.Option(
|
|
47
|
+
"--permission-timeout",
|
|
48
|
+
help="Seconds to wait for a y/N/a answer before denying (0 = wait forever).",
|
|
49
|
+
),
|
|
50
|
+
] = DEFAULT_PROMPT_TIMEOUT,
|
|
51
|
+
no_auto_start: Annotated[
|
|
52
|
+
bool,
|
|
53
|
+
typer.Option("--no-auto-start", help="Do not start nini-service automatically."),
|
|
54
|
+
] = False,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Attach to a session and chat; Ctrl-C interrupts the turn, /exit leaves."""
|
|
57
|
+
if yes and no_input:
|
|
58
|
+
ui.error("--yes and --no-input contradict each other")
|
|
59
|
+
raise typer.Exit(2)
|
|
60
|
+
|
|
61
|
+
cfg = load_cli_config()
|
|
62
|
+
ensure_service_or_exit("nini attach", no_auto_start=no_auto_start, config=cfg)
|
|
63
|
+
try:
|
|
64
|
+
current = asyncio.run(_open(cfg, session))
|
|
65
|
+
except NiniConnectionError as exc:
|
|
66
|
+
ui.unreachable(cfg.service_url, exc)
|
|
67
|
+
ui.hint(start_hint())
|
|
68
|
+
raise typer.Exit(1) from exc
|
|
69
|
+
except NiniHTTPError as exc:
|
|
70
|
+
if exc.status_code == 404 and session:
|
|
71
|
+
ui.error(f"unknown session {session}")
|
|
72
|
+
raise typer.Exit(3) from exc
|
|
73
|
+
ui.error(f"cannot attach: {exc}")
|
|
74
|
+
raise typer.Exit(1) from exc
|
|
75
|
+
except NiniClientError as exc:
|
|
76
|
+
ui.error(f"cannot attach: {exc}")
|
|
77
|
+
raise typer.Exit(1) from exc
|
|
78
|
+
|
|
79
|
+
# The REPL is line-driven, so approvals read from the same stdin unless the
|
|
80
|
+
# caller explicitly asked for no input.
|
|
81
|
+
_BROKER.set(
|
|
82
|
+
PermissionBroker(
|
|
83
|
+
interactive=not no_input,
|
|
84
|
+
allow_all=yes,
|
|
85
|
+
timeout=permission_timeout,
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
sid = str(current.get("id") or "")
|
|
89
|
+
_header(current)
|
|
90
|
+
_history(cfg, sid)
|
|
91
|
+
raise typer.Exit(_repl(cfg, sid))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _header(session: dict[str, Any]) -> None:
|
|
95
|
+
label = session.get("model") or t("cli.run.defaultModel")
|
|
96
|
+
ui.line(
|
|
97
|
+
t(
|
|
98
|
+
"cli.attach.header",
|
|
99
|
+
session=session.get("id"),
|
|
100
|
+
title=session.get("title") or t("tui.newSession"),
|
|
101
|
+
model=label,
|
|
102
|
+
),
|
|
103
|
+
style="bold",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _repl(cfg: Config, sid: str) -> int:
|
|
108
|
+
while True:
|
|
109
|
+
try:
|
|
110
|
+
raw = input(PROMPT)
|
|
111
|
+
except EOFError:
|
|
112
|
+
ui.write("\n")
|
|
113
|
+
return 0
|
|
114
|
+
except KeyboardInterrupt:
|
|
115
|
+
ui.write("\n")
|
|
116
|
+
continue
|
|
117
|
+
text = raw.strip()
|
|
118
|
+
if not text:
|
|
119
|
+
continue
|
|
120
|
+
if text.startswith("/"):
|
|
121
|
+
done, sid = _slash(cfg, text, sid)
|
|
122
|
+
if done:
|
|
123
|
+
return 0
|
|
124
|
+
continue
|
|
125
|
+
_turn(cfg, sid, text)
|
|
126
|
+
return 0 # pragma: no cover - loop only exits through return
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _slash(cfg: Config, line: str, sid: str) -> tuple[bool, str]:
|
|
130
|
+
head, _, tail = line.partition(" ")
|
|
131
|
+
command = head.lower()
|
|
132
|
+
argument = tail.strip()
|
|
133
|
+
|
|
134
|
+
if command in {"/exit", "/quit"}:
|
|
135
|
+
return True, sid
|
|
136
|
+
if command == "/help":
|
|
137
|
+
ui.line(HELP_LINE)
|
|
138
|
+
return False, sid
|
|
139
|
+
if command == "/new":
|
|
140
|
+
session = _safe(cfg, _create(cfg, argument or None))
|
|
141
|
+
if session:
|
|
142
|
+
sid = str(session.get("id") or sid)
|
|
143
|
+
ui.ok(
|
|
144
|
+
t(
|
|
145
|
+
"cli.attach.newSession",
|
|
146
|
+
session=sid,
|
|
147
|
+
title=session.get("title") or t("tui.newSession"),
|
|
148
|
+
)
|
|
149
|
+
)
|
|
150
|
+
return False, sid
|
|
151
|
+
if command == "/ls":
|
|
152
|
+
_safe(cfg, sessions_cmd.render_session_list(cfg, 20))
|
|
153
|
+
return False, sid
|
|
154
|
+
if command == "/stop":
|
|
155
|
+
if _safe(cfg, _abort(cfg, sid)) is not None:
|
|
156
|
+
ui.line("aborted", style="yellow")
|
|
157
|
+
return False, sid
|
|
158
|
+
if command == "/files":
|
|
159
|
+
_safe(cfg, _print_files(cfg, argument or "."))
|
|
160
|
+
return False, sid
|
|
161
|
+
ui.warn(f"unknown command {command}; {HELP_LINE}")
|
|
162
|
+
return False, sid
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _turn(cfg: Config, sid: str, text: str) -> None:
|
|
166
|
+
printer = EventPrinter(mode="live", theme=cfg.theme)
|
|
167
|
+
broker = _BROKER.get() or PermissionBroker(interactive=True)
|
|
168
|
+
broker.notice = printer.notice # type: ignore[method-assign]
|
|
169
|
+
|
|
170
|
+
async def go():
|
|
171
|
+
async with client_for(cfg) as client:
|
|
172
|
+
|
|
173
|
+
async def turn():
|
|
174
|
+
return await run_turn(client, sid, text, printer, permissions=broker)
|
|
175
|
+
|
|
176
|
+
return await with_interrupt_guard(turn)()
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
result = asyncio.run(go())
|
|
180
|
+
except KeyboardInterrupt:
|
|
181
|
+
printer.finish()
|
|
182
|
+
ui.line("interrupted", style="yellow")
|
|
183
|
+
return
|
|
184
|
+
except (NiniConnectionError, NiniClientError) as exc:
|
|
185
|
+
printer.finish()
|
|
186
|
+
ui.error(f"turn failed: {exc}")
|
|
187
|
+
return
|
|
188
|
+
printer.finish()
|
|
189
|
+
if result.status == "interrupted":
|
|
190
|
+
ui.line("interrupted", style="yellow")
|
|
191
|
+
return
|
|
192
|
+
if result.status == "error":
|
|
193
|
+
ui.error(result.error or "turn failed")
|
|
194
|
+
return
|
|
195
|
+
if result.refusals:
|
|
196
|
+
ui.warn("permission refused — the tool call did not run")
|
|
197
|
+
printer.summary(result, sid)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# --------------------------------------------------------------------- async bits
|
|
201
|
+
async def _open(cfg: Config, session_id: str | None) -> dict[str, Any]:
|
|
202
|
+
async with client_for(cfg) as client:
|
|
203
|
+
if session_id:
|
|
204
|
+
return await client.get_session(session_id)
|
|
205
|
+
sessions = await client.list_sessions(limit=1)
|
|
206
|
+
if sessions:
|
|
207
|
+
return sessions[0]
|
|
208
|
+
return await client.create_session(title="attach")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
async def _create(cfg: Config, title: str | None) -> dict[str, Any]:
|
|
212
|
+
async with client_for(cfg) as client:
|
|
213
|
+
return await client.create_session(title=title or "New session")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def _abort(cfg: Config, session_id: str) -> bool:
|
|
217
|
+
async with client_for(cfg) as client:
|
|
218
|
+
await client.abort(session_id)
|
|
219
|
+
return True
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
async def _print_files(cfg: Config, path: str) -> None:
|
|
223
|
+
async with client_for(cfg) as client:
|
|
224
|
+
tree = await client.files_tree(path=path, depth=2)
|
|
225
|
+
if isinstance(tree, list):
|
|
226
|
+
entries = tree
|
|
227
|
+
else:
|
|
228
|
+
entries = tree.get("children") or tree.get("entries") or tree.get("items") or []
|
|
229
|
+
if not entries:
|
|
230
|
+
ui.line("(empty)")
|
|
231
|
+
return
|
|
232
|
+
for entry in entries:
|
|
233
|
+
if not isinstance(entry, dict):
|
|
234
|
+
continue
|
|
235
|
+
kind = "d" if entry.get("type") == "dir" else "f"
|
|
236
|
+
ui.line(f"{kind} {entry.get('path') or entry.get('name')}")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _history(cfg: Config, session_id: str, limit: int = 6) -> None:
|
|
240
|
+
try:
|
|
241
|
+
messages = asyncio.run(_snapshot_messages(cfg, session_id))
|
|
242
|
+
except (NiniConnectionError, NiniClientError):
|
|
243
|
+
return
|
|
244
|
+
for message in messages[-limit:]:
|
|
245
|
+
role = message.get("role")
|
|
246
|
+
parts = message.get("parts") or []
|
|
247
|
+
text = "".join(
|
|
248
|
+
part.get("text") or ""
|
|
249
|
+
for part in parts
|
|
250
|
+
if isinstance(part, dict) and part.get("type") == "text"
|
|
251
|
+
)
|
|
252
|
+
if not text.strip():
|
|
253
|
+
continue
|
|
254
|
+
who = "you" if role == "user" else "nini"
|
|
255
|
+
ui.line(f"{who}: {_ellipsis(text, 160)}", style="dim")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
async def _snapshot_messages(cfg: Config, session_id: str) -> list[dict[str, Any]]:
|
|
259
|
+
async with client_for(cfg) as client:
|
|
260
|
+
snapshot = await client.snapshot(session_id)
|
|
261
|
+
return list(snapshot.get("messages") or [])
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _safe(cfg: Config, coroutine) -> Any:
|
|
265
|
+
try:
|
|
266
|
+
return asyncio.run(coroutine)
|
|
267
|
+
except NiniConnectionError as exc:
|
|
268
|
+
ui.unreachable(cfg.service_url, exc)
|
|
269
|
+
except NiniClientError as exc:
|
|
270
|
+
ui.error(str(exc))
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _ellipsis(value: str, width: int) -> str:
|
|
275
|
+
cleaned = " ".join(value.split())
|
|
276
|
+
return cleaned if len(cleaned) <= width else cleaned[: width - 1] + "…"
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
__all__ = ["attach"]
|