@microboxlabs/miot-chat 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Microbox Labs
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # @microboxlabs/miot-chat
2
+
3
+ A Copilot-style agentic chat CLI for the `miot-harness` SSE streaming API. Lives at `turbo-repo/packages/miot-chat`.
4
+
5
+ > Also reachable as `miot chat` from [`@microboxlabs/miot-cli`](../miot-cli) — the standalone bin and the `miot` subcommand share the same `runMiotChat()` library entry, so flag names, env vars, config files, and behavior are identical between the two.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g @microboxlabs/miot-chat
11
+ miot-chat --help
12
+
13
+ # or run without installing
14
+ npx @microboxlabs/miot-chat --help
15
+ ```
16
+
17
+ If you already have `@microboxlabs/miot-cli` installed, `miot chat` works without a second install — the standalone bin and the `miot` subcommand share the same library entry.
18
+
19
+ Inside the monorepo it's available as a workspace package. To use the built binary directly:
20
+
21
+ ```bash
22
+ cd turbo-repo/packages/miot-chat
23
+ npm run build
24
+ node ./dist/cli.js --help
25
+ ```
26
+
27
+ ## Quick start
28
+
29
+ ```bash
30
+ # 1. Install
31
+ npm install -g @microboxlabs/miot-chat
32
+
33
+ # 2. Log in through the browser (platform sign-in); saves token + org to ~/.miot-chat/config.json
34
+ miot-chat login --base-url https://<platform-host>
35
+
36
+ # 3. Ask — runs route through the platform's harness proxy for your organization
37
+ miot-chat ask "what is the ETA status for today's deliveries?"
38
+ ```
39
+
40
+ `<platform-host>` is the deployment you were given access to (there are several production environments, so there is no baked-in default — `--base-url` or `MIOT_CHAT_BASE_URL` is required).
41
+
42
+ ## Log in
43
+
44
+ `miot-chat login` opens your platform's own sign-in page in the browser. After you sign in, the CLI receives a token plus your active organization and persists them as the default profile (`platform`) in `~/.miot-chat/config.json`. Subsequent `miot-chat ask` / TUI sessions use that profile automatically and route through `{baseUrl}/api/v1/orgs/{org}/harness`.
45
+
46
+ ```bash
47
+ miot-chat login --base-url https://<platform-host>
48
+ ```
49
+
50
+ | Flag | Effect |
51
+ |---|---|
52
+ | `--login-url <url>` | Override the platform CLI login handoff endpoint (default `{baseUrl}/app/cli/auth/login`) |
53
+ | `--token-url <url>` | Override the token endpoint (default `{baseUrl}/app/api/cli/auth/token`) |
54
+ | `--auth-url <url>`, `--client-id <id>`, `--audience <a>`, `--scope <s>` | Direct OAuth/PKCE mode against an authorization server instead of the platform handoff |
55
+ | `--timeout <seconds>` | Login timeout (positive integer) |
56
+ | `--no-open` | Print the login URL instead of opening the browser |
57
+
58
+ In split-origin local dev (app and API on different ports) pass the endpoints explicitly:
59
+
60
+ ```bash
61
+ miot-chat login --base-url http://localhost:8180 \
62
+ --login-url http://localhost:3050/app/cli/auth/login \
63
+ --token-url http://localhost:3050/app/api/cli/auth/token
64
+ ```
65
+
66
+ If you previously logged in with `miot-cli`, `miot-chat` reuses that session from `~/.miotrc.json` as a fallback (baseUrl/token/org only) whenever no token is configured via flags, env, or the chat profile.
67
+
68
+ ## Other commands
69
+
70
+ The CLI talks to `miot-harness` over the Phase A SSE surface (`POST /runs:start` + `GET /runs/{id}/stream`) — directly via `--base-url`, or through the platform harness proxy when an org is set (`--org`, `MIOT_CHAT_ORG`, or the org saved by `login`).
71
+
72
+ ```bash
73
+ # Interactive TUI (default in a real terminal)
74
+ miot-chat
75
+
76
+ # One-shot against a local harness (no login needed)
77
+ miot-chat ask "what's in stock?" --base-url http://localhost:8000 --tenant demo-tenant --mode canned
78
+
79
+ # Resume — TUI mode opens the saved-sessions picker; piped stdin re-seeds the headless REPL
80
+ miot-chat resume
81
+
82
+ # Replay a past run offline
83
+ miot-chat runs run_abc123
84
+
85
+ # Help
86
+ miot-chat --help
87
+ ```
88
+
89
+ ## Interactive TUI vs headless
90
+
91
+ `miot-chat` mounts an Ink-based TUI when BOTH stdin AND stdout are TTYs and the `MIOT_CHAT_NO_TUI` env var is unset. Otherwise it falls back to a line-based REPL that reuses the existing renderer — handy for piped input (`echo "ping" | miot-chat`), CI smoke runs, and golden-output tests.
92
+
93
+ | Mode | When | What it gives you |
94
+ |---|---|---|
95
+ | **TUI** | TTY in + TTY out, no override | Multi-line editor with cursor / paste / history, persistent header bar, slash palette, modal stack (context, resume, theme, runs, approval), markdown rendering for final answers, theme support |
96
+ | **Headless** | piped stdin OR redirected stdout OR `MIOT_CHAT_NO_TUI=1` | Line-based prompt-per-newline, the legacy ANSI renderer, one-line status updates |
97
+
98
+ Force headless explicitly:
99
+
100
+ ```bash
101
+ MIOT_CHAT_NO_TUI=1 miot-chat --tenant demo-tenant
102
+ ```
103
+
104
+ ## TUI features
105
+
106
+ - **Header bar**: tenant · user · conv (short id) · mode · baseUrl · profile · pending-approvals count. Warns in yellow on `mode=agentic` + non-`mintral` tenant.
107
+ - **Multi-line input editor** with bracketed-paste support, cursor movement (arrows, ctrl-arrow word jumps, home/end), backspace + forward-delete, kill-line, and an in-memory history ring (200 entries, file-backed at `~/.miot-chat/history`). Up/Down arrows recall history when the buffer is empty; `Alt-Enter` adds a newline; plain `Enter` submits.
108
+ - **Live transcript** with structured per-event items: tool start/complete collapse to one line with a spinner, freshness warnings show inline, routes/agent turns/plans dim in. Completed turns flush into Ink's `<Static>` so they live in terminal scrollback.
109
+ - **Slash-command palette**: type `/` to filter commands by substring, Tab completes the unique match, Enter dispatches.
110
+ - **Modals**: `/context`, `/resume`, `/theme`, `/runs`, and (behind `MIOT_CHAT_APPROVALS_UI=1`) `/approve`. Esc dismisses.
111
+ - **Themes**: `dark` (default), `light`, `high-contrast` builtins, or your own token overrides via `~/.miot-chat/config.json` (see Configuration below). `/theme` opens a picker; `/theme <name>` jumps to it.
112
+ - **Markdown rendering** for final assistant answers — headings, bold/italic, fenced code blocks, lists, and links render as Ink components.
113
+
114
+ ## Slash commands
115
+
116
+ All slash commands work in the TUI palette. The headless REPL supports the legacy subset (`/exit`, `/reset`, `/mode`, `/tenant`, `/save`) for backwards compatibility.
117
+
118
+ | Command | Where | Effect |
119
+ |---|---|---|
120
+ | `/help` | both | List every registered command |
121
+ | `/exit` (or Ctrl-D) | both | Persist the session and exit |
122
+ | `/clear` | both | Clear the on-screen transcript (conversation id kept) |
123
+ | `/reset` | both | Mint a fresh `conversation_id` |
124
+ | `/mode auto\|canned\|meta\|agentic` | both | Change dispatch mode |
125
+ | `/tenant <id>` | both | Change tenant |
126
+ | `/user <id>` | TUI | Change user id |
127
+ | `/save <path>` | both | Dump `{conversation_id, transcript}` as JSON |
128
+ | `/export <path>` | TUI | Write the transcript as markdown |
129
+ | `/context` | TUI | Open a modal with the full session metadata |
130
+ | `/whoami` | TUI | Print `user=… tenant=… conv=…` |
131
+ | `/theme [name]` | TUI | Pick a color theme (modal); `/theme dark` jumps directly |
132
+ | `/resume` | TUI | Pick a saved session from `~/.miot-chat/sessions/` |
133
+ | `/runs` | TUI | Pick a run from the current session to replay |
134
+ | `/approve <approve\|deny\|later> <id>` | TUI | Resolve a pending approval from the keyboard |
135
+
136
+ `Ctrl-C` aborts the in-flight harness run and keeps the editor alive.
137
+
138
+ ## Configuration
139
+
140
+ `~/.miot-chat/config.json` (file mode 0600):
141
+
142
+ ```json
143
+ {
144
+ "defaultProfile": "local",
145
+ "profiles": {
146
+ "local": { "baseUrl": "http://localhost:8000", "token": null, "tenantId": "demo-tenant", "userId": "demo-user" },
147
+ "staging": { "baseUrl": "https://...", "token": null, "tenantId": "mintral", "userId": "ops" }
148
+ },
149
+ "theme": "dark"
150
+ }
151
+ ```
152
+
153
+ The `theme` field is optional. Valid values:
154
+
155
+ - A builtin name: `"dark"`, `"light"`, or `"high-contrast"`.
156
+ - An object: `{ "name": "dark", "tokens": { "accent": "#ff0080", "prompt": "magenta" } }`. Token keys: `accent`, `assistant`, `user`, `dim`, `warn`, `err`, `ok`, `border`, `prompt`, `spinner`. Values are anything Ink's `<Text color>` accepts (named or hex). Invalid theme names degrade to `dark` with a one-line warning rendered above the transcript.
157
+
158
+ Resolution precedence: CLI flag > env (`MIOT_CHAT_*`) > profile > defaults.
159
+
160
+ Env vars:
161
+
162
+ | Var | Effect |
163
+ |---|---|
164
+ | `MIOT_CHAT_BASE_URL` | Override `baseUrl` |
165
+ | `MIOT_CHAT_TOKEN` | Override bearer token |
166
+ | `MIOT_CHAT_TENANT_ID` | Override tenant |
167
+ | `MIOT_CHAT_USER_ID` | Override user |
168
+ | `MIOT_CHAT_MODE` | Override dispatch mode |
169
+ | `MIOT_CHAT_ORG` | Override the organization slug (routes runs through the platform harness proxy) |
170
+ | `MIOT_CHAT_PROFILE` | Pick a profile from the config file |
171
+ | `MIOT_CHAT_DEBUG` | `1` streams full tool inputs and truncated outputs (tenant must be allow-listed) |
172
+ | `MIOT_CHAT_NO_TUI` | `1` forces headless mode even in a TTY |
173
+ | `MIOT_CHAT_APPROVALS_UI` | `1` enables the `approval.requested` modal (reply transport not yet wired) |
174
+ | `NO_COLOR` | Disable ANSI output in the headless renderer |
175
+
176
+ ## Conversation memory
177
+
178
+ Each session mints a fresh `conversation_id` (UUIDv4) and sends it on every turn. Phase 13's `ConversationStore` on the harness rehydrates prior turns server-side, so the CLI carries no per-turn state.
179
+
180
+ - The **TUI** auto-persists each committed turn to `~/.miot-chat/sessions/<conv-id>.json` (mode 0600, atomic write). `/resume` lists the newest 10 and re-seeds the reducer via `LOAD_SESSION`. The 500-most-recent items are kept; older entries are summarized into a single `(elided N earlier items)` system row.
181
+ - The **headless** REPL keeps using `~/.miot-chat/last-conversation` (single id) for the legacy `miot-chat resume` flow.
182
+
183
+ ## Develop
184
+
185
+ ```bash
186
+ npm run build # tsup
187
+ npm test # vitest
188
+ npm run lint
189
+ npm run check-types
190
+ ```
191
+
192
+ ## Design notes
193
+
194
+ - Runtime deps: `commander` for arg parsing, `ink@^7` + `react@^19.2` for the TUI, `marked@^14` for the lexer used by `/export` and the assistant-turn renderer, and [`@microboxlabs/miot-harness-client`](../miot-harness-client) for the HTTP + SSE work. `readline`, `crypto.randomUUID`, `fetch`, and `ReadableStream` are native on Node ≥20.
195
+ - HTTP + SSE live in the sibling library — this package owns the **interactive UX layer**. The same library powers the non-streaming `miot harness create` / `miot harness runs get` subcommands in [`miot-cli`](../miot-cli).
196
+ - **Architecture (TUI):** a pure session reducer in `src/tui/session/reducer.ts` owns `meta`, `transcript`, `pendingApprovals`, and `currentRunId`. `STREAM_EVENT` delegates to `src/tui/transcript/project.ts`, which mirrors the field-precedence rules of the legacy `renderer.ts:statusFor` but produces typed `TranscriptItem`s. Components subscribe via `useSession` and render via Ink. The same projector is reused by `/export` markdown serialization and (eventually) the `/runs` replay panel.
197
+ - **Architecture (headless):** unchanged from earlier phases — `src/repl/loop.ts` reads lines, calls `client.runs.create` + `client.runs.stream`, and pipes events through the original `(state, event) → {state, output}` renderer. Marked deprecated in the source; future work re-implements headless mode on top of `useSession`.
198
+ - The library's SSE parser surfaces the harness `event: error` frame as a thrown `MiotHarnessApiError`. Both code paths catch and render it.
199
+ - Terminal signal is `run.completed` / `run.failed`, not `answer.completed` (which the supervisor can emit more than once when a mode is denied and a fallback runs). The projector handles the dual-emit case by upserting the in-flight assistant item.
200
+ - `approval.requested` events arrive from the harness, but no reply endpoint exists yet. The modal ships behind `MIOT_CHAT_APPROVALS_UI=1` and its resolve callback only records the decision locally — wiring will land when the harness exposes the reply transport.