nini-service 0.4.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nini contributors
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,46 @@
1
+ Metadata-Version: 2.5
2
+ Name: nini-service
3
+ Version: 0.4.1
4
+ Summary: Nini daemon: the single source of truth for sessions, events and tools
5
+ Project-URL: Homepage, https://nini.flygpt.cc
6
+ Project-URL: Repository, https://github.com/xusai2014/Nini
7
+ Author-email: Jerry xu <jerryxu521@gmail.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Classifier: Environment :: Console
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Requires-Dist: aiosqlite>=0.20
16
+ Requires-Dist: cryptography>=51.0.0
17
+ Requires-Dist: fastapi>=0.115
18
+ Requires-Dist: nini-adapter==0.4.1
19
+ Requires-Dist: nini-client==0.4.1
20
+ Requires-Dist: nini-core==0.4.1
21
+ Requires-Dist: nini-protocol==0.4.1
22
+ Requires-Dist: uvicorn[standard]>=0.32
23
+ Requires-Dist: watchfiles>=1.0
24
+ Requires-Dist: websockets>=13
25
+ Description-Content-Type: text/markdown
26
+
27
+ # nini-service
28
+
29
+ The Nini daemon: the single source of truth for sessions, messages, events, files
30
+ and PTYs. It exposes the frozen v1 contract over REST + WebSocket and is normally
31
+ started for you by `nini serve`.
32
+
33
+ ```bash
34
+ pip install nini-service
35
+ nini-service --port 4096 # loopback only; prints the token URL
36
+ ```
37
+
38
+ - First start writes `~/.nini/token` (32 random bytes, mode 0600); rotate it by
39
+ rewriting the file — the daemon re-reads it without a restart.
40
+ `/health` is the only unauthenticated route.
41
+ - `--workspace` scopes the file API and PTYs; `--home` moves the state dir.
42
+ - State is sqlite; events replay from any `seq`, so clients reconnect cheaply.
43
+
44
+ Most users install the meta package instead: `pipx install nini` (CLI + daemon).
45
+
46
+ Docs: <https://github.com/xusai2014/Nini> · License: MIT
@@ -0,0 +1,248 @@
1
+ # nini-service
2
+
3
+ The daemon: single source of truth for sessions, messages, events, files and PTYs.
4
+ It speaks the frozen contract in
5
+ `docs/nini/protocol/20261202-nini-contract-v1.md` (v1.1) over REST and WebSocket.
6
+
7
+ ```bash
8
+ uv run python -m nini_service --port 4096 # loopback only
9
+ uv run python -m nini_service --host 0.0.0.0 --port 4096 # prints a warning + token URL
10
+ ```
11
+
12
+ `--workspace` scopes the file API and PTYs (default: cwd). `--home` moves the
13
+ state dir (default `~/.nini`). `NINI_HOME`, `NINI_WORKSPACE`, `NINI_NO_WATCH`,
14
+ `NINI_WATCH_SUBDIRS` and `NINI_RUNTIME=stub` are the environment equivalents.
15
+
16
+ ## Auth
17
+
18
+ First start writes `~/.nini/token` (32 random bytes, urlsafe, mode 0600). The file
19
+ is re-read when it changes, so a rotated token takes effect without a restart.
20
+
21
+ - `Authorization: Bearer <token>` or `?token=<token>`
22
+ - `/health` is the only unauthenticated route
23
+ - failures are `401 {"code":"unauthorized","message":...}`; a WS handshake without
24
+ a valid token is rejected before `accept`
25
+
26
+ ## REST
27
+
28
+ | method | path | body / query | response |
29
+ | ------ | ----------------------------- | --------------------------------- | ------------------------------------------------------------------ |
30
+ | GET | `/health` | – | `{ok,name,version}` |
31
+ | GET | `/api/info` | – | `{server_id,name,version,protocol,workspace,capabilities,runtime}` |
32
+ | GET | `/api/sessions` | `limit=50` | `{items: Session[]}` |
33
+ | POST | `/api/sessions` | `{title?,cwd?,model?}` | `201 Session` |
34
+ | GET | `/api/sessions/{id}` | – | `Session` |
35
+ | DELETE | `/api/sessions/{id}` | – | `{ok,session_id}` |
36
+ | GET | `/api/sessions/{id}/messages` | `limit=200` | `{items: Message[]}` (with `parts`) |
37
+ | GET | `/api/sessions/{id}/snapshot` | – | `{session, messages, last_seq}` |
38
+ | POST | `/api/sessions/{id}/prompt` | `{text,attachments?,client_request_id?}` | `{session,message_id}` (same id for a replayed `client_request_id`) |
39
+ | POST | `/api/sessions/{id}/abort` | – | `{ok,session_id,aborted}` (`aborted:false` ⇒ nothing was running, no event) |
40
+ | POST | `/api/permissions/{id}` | `{decision:"allow"\|"deny", by?}` | `{ok,request_id,decision,status,by}` (the *effective* state) |
41
+ | GET | `/api/files/tree` | `path=.&depth=2` | `{path, children\|entries: FileNode[]}` |
42
+ | GET | `/api/files/content` | `path=` | `{path,content,hash,size}` |
43
+ | PUT | `/api/files/content` | `{path,content,expected_hash?}` | `{path,hash,size,created}` |
44
+ | GET | `/api/files/diff` | `path=` | `{path,diff,is_git}` |
45
+ | POST | `/api/pty` | `{cwd?,cols,rows}` | `{pty_id,pid,cwd,cols,rows}` |
46
+ | POST | `/api/relay/pair` | `{ttl?, single_use?}` | `{code,expires_at,relay_url,machine_id,single_use}` |
47
+ | POST | `/api/relay/rotate-key` | – | `{machine_key, rotated_at}` |
48
+ | GET | `/api/relay/status` | – | `{enabled,connected,relay_url,machine_id,paired_clients,source,default_url}` |
49
+ | WS | `/api/pty/{id}` | – | text = bytes, JSON = control |
50
+ | WS | `/ws` | `since=<seq>&token=` | event stream |
51
+
52
+ Errors are always `{"code": "...", "message": "..."}` with 401 / 403 / 404 / 409 / 422. Path traversal (including symlinks) is 403; a stale `expected_hash` is 409
53
+ with `details.current_hash`; non-UTF-8 or oversized files are 422.
54
+
55
+ ## WebSocket
56
+
57
+ ```
58
+ server.hello -> replay(seq > since) -> live
59
+ ```
60
+
61
+ - `since` is the last applied `seq`; `0` means "everything still on disk".
62
+ - Backlog over 5000 events is replaced by one `resync.required`; the client then
63
+ calls `/snapshot` and reconnects with the returned `last_seq`.
64
+ - Client frames: `{"type":"ping"}` → `{"type":"pong","seq":n}`;
65
+ `{"type":"prompt","session":...,"text":...}` (REST equivalent, answered with an
66
+ `ack` event carrying `message_id`).
67
+ - `server.heartbeat` every 30 s (`--heartbeat`), `seq` = current maximum. When
68
+ the file watcher had to drop events, the beat carries an additive
69
+ `file_events_dropped` (cumulative) — see [File watcher](#file-watcher).
70
+ - A client that stops reading is disconnected (bounded per-subscriber queue),
71
+ never awaited by the publisher.
72
+
73
+ `/api/pty/{id}` sends raw output as text frames and accepts input text frames;
74
+ `{"resize":{"cols":n,"rows":m}}` is the only control frame (plus `{"type":"ping"}`).
75
+ PTY output is also mirrored into the event stream as `pty.data` (base64) so a
76
+ `/ws`-only client renders the terminal; child exit is `pty.exit` with `code`.
77
+
78
+ ## File watcher
79
+
80
+ `file.changed` is a **"the tree may have changed"** signal, not a path-by-path
81
+ delta. Three layers keep a build that touches thousands of files from turning
82
+ into thousands of events:
83
+
84
+ | layer | behaviour |
85
+ | --- | --- |
86
+ | ignored directories | `.git`, `node_modules`, `.venv`, `__pycache__`, `Library`, `.nini`, `dist`, `target`, `.pytest_cache`, `.ruff_cache`, `.expo` never produce events |
87
+ | `$HOME` guard | a workspace that *is* `$HOME` is not watched at all (one warning); only `NINI_WATCH_SUBDIRS=src,packages` (relative, comma-separated) is watched |
88
+ | same-path merge | changes to one path within 1 s become a single `file.changed`; the first kind wins and `deleted` always wins |
89
+ | rate limit | at most 20 `file.changed` per rolling second; the rest are dropped and counted |
90
+
91
+ **Clients must treat `file.changed` as "re-read the tree", never as an
92
+ incremental delete/apply.** Events for one path can be merged and events can be
93
+ dropped under load, so a client that applied per-path deltas would miss changes
94
+ after a drop. The web client's `fileVersion + 1` (full tree refresh) is the
95
+ behaviour this depends on.
96
+
97
+ Drops are not silent: `server.heartbeat` carries an additive
98
+ `file_events_dropped` (cumulative, allowed by contract §7 — no new event type, no
99
+ extra persisted event), and one extra heartbeat is sent as soon as a drop burst
100
+ has been quiet for 1 s, so the counter does not wait for the 30 s timer.
101
+
102
+ `seq` is unaffected: coalescing happens *before* `stream.publish`, so every
103
+ published event still takes the bus's next `seq`, in order, **with no gaps**, and
104
+ `file.changed` stays a durable (non-ephemeral) event. Dropped changes never had a
105
+ `seq` assigned.
106
+
107
+ 5,000 writes into one directory, same machine (`tests/test_watch_burst.py`
108
+ re-measures this in CI):
109
+
110
+ | | `file.changed` | duplicate (path, kind) | peak |
111
+ | --- | --- | --- | --- |
112
+ | before (200 ms debounce only) | 5,030 | 3 | 3,123/s |
113
+ | after (merge + 20/s + drop counter) | 40–80 (≈20 × write seconds) | 0 | 20/s |
114
+
115
+ Every write is either published or counted as dropped (one run: 60 published +
116
+ 4,941 dropped = 5,001 = 5,000 files + the `src/` directory), and the dropped
117
+ total rides on the next heartbeat (`file_events_dropped`), so the client still
118
+ knows the tree changed and how noisy it was.
119
+
120
+ ## WS RPC (contract §15)
121
+
122
+ A remote client that cannot reach REST (relay mode) does its writes on the same
123
+ socket:
124
+
125
+ ```jsonc
126
+ // client -> daemon
127
+ {"type":"rpc","id":"<uuid>","method":"POST","path":"/api/sessions/ses_1/prompt","body":{"text":"hi"}}
128
+ // daemon -> client
129
+ {"type":"rpc.result","id":"<uuid>","status":200,"body":{"session":"...","message_id":"..."}}
130
+ ```
131
+
132
+ - The frame is dispatched into **this app's own ASGI stack** (`nini_service/rpc.py`),
133
+ with the daemon token attached, so validation/auth/error mapping are the REST
134
+ ones. No loopback socket is opened and no second API exists.
135
+ - `path` must start with `/api/`; `/api/pty` (and below) is 403 — PTY keeps its
136
+ own duplex websocket. `method` ∈ GET/POST/PUT/PATCH/DELETE/HEAD.
137
+ - `body` is capped at **8 MiB − 8 KiB** (8,380,416 bytes); over that the answer is
138
+ `status: 413`. The 8 KiB slack covers the RPC envelope, because the relay caps a
139
+ bridged frame at 8 MiB of decoded payload — a body at exactly the limit must still
140
+ fit through the relay instead of being killed with close `1009`.
141
+ - The status is the REST status: `201` create, `404` unknown, `409` stale
142
+ `expected_hash`, `422` validation, `502/503` relay problems.
143
+ - Events do **not** travel as RPC results: `part.delta`, `message.completed` etc.
144
+ keep streaming as normal event envelopes on the same socket.
145
+
146
+ ## Relay (contract §14)
147
+
148
+ The daemon dials **out** to `nini-relay`, so users behind NAT are reachable.
149
+
150
+ - Config is env first (`NINI_RELAY_URL`, `NINI_MACHINE_ID`, `NINI_MACHINE_KEY`,
151
+ `NINI_RELAY_ENABLED`), then `~/.nini/machine.json`. On first start the file is
152
+ created with a stable `machine_id` (`<hostname>-<6 chars>`) and a 32-byte
153
+ urlsafe `machine_key`, mode 0600.
154
+ - **The relay is on by default**: with no env and no `relay_url` in the file the
155
+ daemon dials the official relay, `wss://relay.flygpt.cc` (`/v1/agent`). The
156
+ default URL is *not* written to `machine.json`, so a later official-domain
157
+ move needs no migration and self-hosting leaves no stale URL behind.
158
+ - Turn it off with `NINI_RELAY_URL=off` (also `none` / `disabled` / empty),
159
+ `NINI_RELAY_ENABLED=0|false|no`, or `"enabled": false` / `"relay_url": null`
160
+ in `machine.json`. Self-host with an explicit URL in either place; env wins.
161
+ `GET /api/relay/status` reports `source: default|env|file|off` so callers can
162
+ label the official relay.
163
+ - The client connects to `<relay_url>/v1/agent?machine=…&key=…`, waits for
164
+ `ready`, answers relay `ping` with `pong`, and redials with **1/2/4/8/16/30 s**
165
+ backoff forever. A drop closes every virtual session (and their subscriptions).
166
+ - `POST /api/relay/pair` **generates the code itself** (contract v1.3 §16):
167
+ 10 Crockford Base32 chars (50 bits), returned as `XXXXX-XXXXX`, and registers
168
+ only `base64url(sha256(code))` with the relay
169
+ (`POST /v1/pairing/register`). `single_use` defaults to `false` here because one
170
+ code onboards CLI + web + mobile (the relay default stays `true`); a v1.2 relay
171
+ without the register route falls back to `POST /v1/pairing`. `503 relay_offline`
172
+ while the link is down, `502 relay_error` if the relay refuses.
173
+ - `POST /api/relay/rotate-key` (§19) asks the relay to swap the key (authenticated
174
+ by the old one), persists the new key to `~/.nini/machine.json` (0600) and
175
+ redials; a refused rotation leaves the old key in place so access is never lost.
176
+ - `GET /api/relay/status` reports
177
+ `{enabled,connected,relay_url,machine_id,paired_clients,source,default_url}`
178
+ (`source` = `default|env|file|off`) and `/api/info` embeds the same block.
179
+ - Every relay `open` becomes a **virtual `/ws` session**: `relay.RelayChannel`
180
+ implements the same four socket methods as a real websocket
181
+ (`send_json/send_text/receive_text/close`) and `ws.serve_stream()` runs on it,
182
+ so hello, `since` replay, heartbeat, ping/pong, the prompt shortcut and RPC are
183
+ the same code paths. A client may open with `{"type":"resume","since":n}` to
184
+ skip history instead of replaying from 0.
185
+ - Known gap: the relay caps a bridged payload at 8 MiB, so the effective RPC body
186
+ limit in relay mode is 8 MiB − 8 KiB even though the socket alone would allow
187
+ 8 MiB of body.
188
+
189
+ ## Runtime seam
190
+
191
+ `create_app()` resolves the engine in this order:
192
+
193
+ 1. `NINI_RUNTIME=stub` → `nini_service.runtime_stub.MemoryRuntime`
194
+ 2. `from nini_core.api import SqliteRuntime` → core (`/api/info` says
195
+ `"runtime":"nini_core"`). Its constructor kwargs are filtered by signature.
196
+ 3. anything missing → the stub, with a warning log.
197
+
198
+ When core is present, **core owns the event bus**: `/ws` reads `runtime.replay()`
199
+ / `runtime.subscribe()` / `runtime.latest_seq`, and PTY/file events are published
200
+ through `runtime.bus.publish()` so there is exactly one `seq` space and one
201
+ database. With the stub, the service keeps an equivalent local log in
202
+ `~/.nini/service-events.db` (separate file on purpose: core's `events` table has a
203
+ different schema) and relays stub events into it.
204
+
205
+ `GET /api/sessions/{id}/snapshot` reads `last_seq` **before** the state so a
206
+ client that reconnects with `?since=last_seq` can only see duplicates (dedupe by
207
+ seq), never a gap. If the runtime exposes `snapshot()` it is used, otherwise the
208
+ service falls back to `get_session + list_messages`. `last_seq` is always the
209
+ service's wire sequence, even if core returns its own.
210
+
211
+ ## Idempotency and deduplication(幂等与去重)
212
+
213
+ **P0: a retried request must never create a second row.** The full contract lives
214
+ in [`docs/API.md`](../../docs/API.md); the short version:
215
+
216
+ - `POST /api/sessions/{id}/prompt` accepts `client_request_id` (body) or
217
+ `Idempotency-Key` (header). Same session + same key within 24 h ⇒ the **same
218
+ `message_id`**, no new message, no new agent turn. The guarantee is the sqlite
219
+ primary key `prompt_keys(session, key)` (schema v2), so it holds across
220
+ concurrent requests and across restarts; a key reused for *different* text is
221
+ `409 prompt_key_conflict`.
222
+ - `?since=N` on `/ws` returns `seq > N` only, and `snapshot.last_seq` is read
223
+ before the state, so `snapshot` → `?since=last_seq` can only duplicate (clients
224
+ dedupe by `seq`), never gap.
225
+ - A repeated `seq` in `events` is refused with `409 duplicate_event`, never
226
+ overwritten.
227
+ - `POST /api/permissions/{id}` applies once and then reports the **stored**
228
+ decision; `POST …/abort` with nothing running appends no event.
229
+ - The TS SDK retries *only* idempotent calls (`retry.ts`): `GET`, prompt-with-key,
230
+ permission decisions. `scripts/e2e_dedupe.py` proves all of it against a real
231
+ daemon.
232
+
233
+ ## Tests
234
+
235
+ ```bash
236
+ uv run pytest apps/nini-service -q # 171 tests
237
+ uv run python apps/nini-service/scripts/e2e_relay_service.py # real relay + service
238
+ bash scripts/smoke_service.sh # real daemon on :4096, falls back to a free port
239
+ ```
240
+
241
+ `tests/test_watch_burst.py` pins the watcher contract (merge / rate limit / drop
242
+ counter / `$HOME` guard / dense `seq`). `tests/test_core_integration.py` runs
243
+ against the real `nini_core.api.SqliteRuntime` (echo provider, no network); the
244
+ rest of the suite uses the in-repo stub so it
245
+ runs in milliseconds. `scripts/ws_probe.py` is the tiny WS listener the smoke
246
+ script uses. `scripts/e2e_relay_service.py` starts `nini_relay` and
247
+ `nini_service` on random 47xxx/49xxx ports, pairs, attaches through the relay and
248
+ asserts RPC + event streaming + teardown (exit code 0 = pass).
@@ -0,0 +1,20 @@
1
+ # nini-service
2
+
3
+ The Nini daemon: the single source of truth for sessions, messages, events, files
4
+ and PTYs. It exposes the frozen v1 contract over REST + WebSocket and is normally
5
+ started for you by `nini serve`.
6
+
7
+ ```bash
8
+ pip install nini-service
9
+ nini-service --port 4096 # loopback only; prints the token URL
10
+ ```
11
+
12
+ - First start writes `~/.nini/token` (32 random bytes, mode 0600); rotate it by
13
+ rewriting the file — the daemon re-reads it without a restart.
14
+ `/health` is the only unauthenticated route.
15
+ - `--workspace` scopes the file API and PTYs; `--home` moves the state dir.
16
+ - State is sqlite; events replay from any `seq`, so clients reconnect cheaply.
17
+
18
+ Most users install the meta package instead: `pipx install nini` (CLI + daemon).
19
+
20
+ Docs: <https://github.com/xusai2014/Nini> · License: MIT
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "nini-service"
3
+ version = "0.4.1"
4
+ description = "Nini daemon: the single source of truth for sessions, events and tools"
5
+ readme = "README.pypi.md"
6
+ license = { text = "MIT" }
7
+ authors = [{ name = "Jerry xu", email = "jerryxu521@gmail.com" }]
8
+ classifiers = [
9
+ "Programming Language :: Python :: 3.12",
10
+ "License :: OSI Approved :: MIT License",
11
+ "Operating System :: OS Independent",
12
+ "Environment :: Console",
13
+ ]
14
+ requires-python = ">=3.12"
15
+ dependencies = [
16
+ "fastapi>=0.115",
17
+ "uvicorn[standard]>=0.32",
18
+ "websockets>=13",
19
+ "watchfiles>=1.0",
20
+ "aiosqlite>=0.20",
21
+ "nini-protocol==0.4.1",
22
+ "nini-core==0.4.1",
23
+ "nini-client==0.4.1",
24
+ "nini-adapter==0.4.1",
25
+ "cryptography>=51.0.0",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://nini.flygpt.cc"
30
+ Repository = "https://github.com/xusai2014/Nini"
31
+
32
+ [project.scripts]
33
+ nini-service = "nini_service.__main__:main"
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["nini_service"]