@chantier/tui 0.3.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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ All notable changes are documented in the root
4
+ [CHANGELOG.md](../../CHANGELOG.md).
5
+
6
+ ## 0.3.0 — 2026-09-16
7
+
8
+ - Approval card with inline diff previews before every mutation.
9
+ - Remembered grants ("always allow") persist for the session.
10
+ - Screen-reader mode, labeled lines, NO_COLOR, and an ASCII fallback.
11
+
12
+ See the root changelog for the full list.
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 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 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
+ 4. (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 those 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 DASHLEA × MLC
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,11 @@
1
+ # @chantier/tui
2
+
3
+ Ink-based interactive terminal UI for the [chantier](https://github.com/mlcassociation/chantier)
4
+ coding agent: streaming transcript, approval cards with diff previews,
5
+ remembered grants, screen-reader mode, and NO_COLOR/ASCII fallbacks.
6
+
7
+ ```ts
8
+ import { createTuiStore, startTui } from "@chantier/tui";
9
+ ```
10
+
11
+ License: Apache-2.0.
@@ -0,0 +1,387 @@
1
+ import { ApprovalDecision, ApprovalRequest } from "@chantier/permissions";
2
+ //#region ../../node_modules/cli-boxes/index.d.ts
3
+ /**
4
+ Style of the box border.
5
+ */
6
+ type BoxStyle = {
7
+ readonly topLeft: string;
8
+ readonly top: string;
9
+ readonly topRight: string;
10
+ readonly right: string;
11
+ readonly bottomRight: string;
12
+ readonly bottom: string;
13
+ readonly bottomLeft: string;
14
+ readonly left: string;
15
+ };
16
+ /**
17
+ All box styles.
18
+ */
19
+ type Boxes = {
20
+ /**
21
+ @example
22
+ ```
23
+ ┌────┐
24
+ │ │
25
+ └────┘
26
+ ```
27
+ */
28
+ readonly single: BoxStyle;
29
+ /**
30
+ @example
31
+ ```
32
+ ╔════╗
33
+ ║ ║
34
+ ╚════╝
35
+ ```
36
+ */
37
+ readonly double: BoxStyle;
38
+ /**
39
+ @example
40
+ ```
41
+ ╭────╮
42
+ │ │
43
+ ╰────╯
44
+ ```
45
+ */
46
+ readonly round: BoxStyle;
47
+ /**
48
+ @example
49
+ ```
50
+ ┏━━━━┓
51
+ ┃ ┃
52
+ ┗━━━━┛
53
+ ```
54
+ */
55
+ readonly bold: BoxStyle;
56
+ /**
57
+ @example
58
+ ```
59
+ ╓────╖
60
+ ║ ║
61
+ ╙────╜
62
+ ```
63
+ */
64
+ readonly singleDouble: BoxStyle;
65
+ /**
66
+ @example
67
+ ```
68
+ ╒════╕
69
+ │ │
70
+ ╘════╛
71
+ ```
72
+ */
73
+ readonly doubleSingle: BoxStyle;
74
+ /**
75
+ @example
76
+ ```
77
+ +----+
78
+ | |
79
+ +----+
80
+ ```
81
+ */
82
+ readonly classic: BoxStyle;
83
+ /**
84
+ @example
85
+ ```
86
+ ↘↓↓↓↓↙
87
+ → ←
88
+ ↗↑↑↑↑↖
89
+ ```
90
+ */
91
+ readonly arrow: BoxStyle;
92
+ };
93
+ //#endregion
94
+ //#region ../../node_modules/ansi-styles/index.d.ts
95
+ type CSPair = {
96
+ // eslint-disable-line @typescript-eslint/naming-convention
97
+ /**
98
+ The ANSI terminal control sequence for starting this style.
99
+ */
100
+ readonly open: string;
101
+ /**
102
+ The ANSI terminal control sequence for ending this style.
103
+ */
104
+ readonly close: string;
105
+ };
106
+ type ForegroundColor = {
107
+ readonly black: CSPair;
108
+ readonly red: CSPair;
109
+ readonly green: CSPair;
110
+ readonly yellow: CSPair;
111
+ readonly blue: CSPair;
112
+ readonly cyan: CSPair;
113
+ readonly magenta: CSPair;
114
+ readonly white: CSPair;
115
+ /**
116
+ Alias for `blackBright`.
117
+ */
118
+ readonly gray: CSPair;
119
+ /**
120
+ Alias for `blackBright`.
121
+ */
122
+ readonly grey: CSPair;
123
+ readonly blackBright: CSPair;
124
+ readonly redBright: CSPair;
125
+ readonly greenBright: CSPair;
126
+ readonly yellowBright: CSPair;
127
+ readonly blueBright: CSPair;
128
+ readonly cyanBright: CSPair;
129
+ readonly magentaBright: CSPair;
130
+ readonly whiteBright: CSPair;
131
+ };
132
+ /**
133
+ Basic foreground color names.
134
+
135
+ [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
136
+ */
137
+ type ForegroundColorName = keyof ForegroundColor;
138
+ //#endregion
139
+ //#region ../../node_modules/type-fest/source/primitive.d.ts
140
+ /**
141
+ Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
142
+
143
+ @category Type
144
+ */
145
+ type Primitive = null | undefined | string | number | boolean | symbol | bigint;
146
+ //#endregion
147
+ //#region ../../node_modules/type-fest/source/literal-union.d.ts
148
+ /**
149
+ Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.
150
+
151
+ Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals.
152
+
153
+ This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore.
154
+
155
+ @example
156
+ ```
157
+ import type {LiteralUnion} from 'type-fest';
158
+
159
+ // Before
160
+
161
+ type Pet = 'dog' | 'cat' | string;
162
+
163
+ const petWithoutAutocomplete: Pet = '';
164
+ // Start typing in your TypeScript-enabled IDE.
165
+ // You **will not** get auto-completion for `dog` and `cat` literals.
166
+
167
+ // After
168
+
169
+ type Pet2 = LiteralUnion<'dog' | 'cat', string>;
170
+
171
+ const petWithAutoComplete: Pet2 = '';
172
+ // You **will** get auto-completion for `dog` and `cat` literals.
173
+ ```
174
+
175
+ @category Type
176
+ */
177
+ type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
178
+ //#endregion
179
+ //#region src/store.d.ts
180
+ type TuiMode = "input" | "running";
181
+ /** Optional attachment for an approval ask; pre-wired for diff previews. */
182
+ interface TuiPromptDetail {
183
+ readonly diff?: string;
184
+ }
185
+ interface TuiState {
186
+ readonly mode: TuiMode;
187
+ /** Finalized transcript lines (rendered once, never re-rendered). */
188
+ readonly lines: readonly string[];
189
+ /** In-progress model text, replaced by lines once finalized. */
190
+ readonly streamText: string;
191
+ /** Transient status line (e.g. "thinking…"); "" hides it. */
192
+ readonly status: string;
193
+ /** Pending approval request; null while the model is streaming. */
194
+ readonly prompt: ApprovalRequest | null;
195
+ /** Optional diff attachment for the pending ask; null when absent. */
196
+ readonly promptDetail: TuiPromptDetail | null;
197
+ /** Text typed at the task prompt (input mode only). */
198
+ readonly inputText: string;
199
+ /** True once the owner called finish(); App exits after the final render. */
200
+ readonly finished: boolean;
201
+ }
202
+ type TuiStore = {
203
+ readonly state: TuiState;
204
+ /** React-side subscription; returns an unsubscribe function. */
205
+ subscribe(listener: () => void): () => void;
206
+ /** Appends one finalized transcript line. */
207
+ pushLine(line: string): void;
208
+ /** Appends in-flight model text; flushStream() finalizes it. */
209
+ appendStream(text: string): void;
210
+ /** Moves buffered stream text (if any) into finalized lines. */
211
+ flushStream(): void;
212
+ /** Shows a transient status (e.g. "thinking…"); "" hides it. */
213
+ setStatus(status: string): void;
214
+ /** Enters task-input mode; resolves the previous task signal if still open. */
215
+ awaitTask(defaultText?: string): Promise<string | null>;
216
+ /** Submits the typed task text; null = user quit. */
217
+ submitTask(text: string): void;
218
+ /** Backspace one character at the task prompt. */
219
+ backspaceInput(): void;
220
+ /** Types one printable character at the task prompt. */
221
+ typeInput(char: string): void;
222
+ /** Renders the approval prompt and waits for a keypress decision. */
223
+ ask(req: ApprovalRequest, detail?: TuiPromptDetail): Promise<ApprovalDecision>;
224
+ decide(decision: ApprovalDecision): void;
225
+ /**
226
+ * Esc aborts the current work (deny pending prompt + notify); Ctrl-C quits
227
+ * the app with a nonzero exit signal.
228
+ */
229
+ abort(kind: AbortKind): void;
230
+ /** Marks the store finished; App unmounts on the next render. */
231
+ finish(): void;
232
+ };
233
+ type AbortKind = "escape" | "ctrl-c";
234
+ export declare function createTuiStore(handlers: {
235
+ onAbort: (kind: AbortKind) => void;
236
+ }, isQuitCommand?: (text: string) => boolean): TuiStore;
237
+ //#endregion
238
+ //#region src/app.d.ts
239
+ export declare function TuiApp({ store }: {
240
+ store: TuiStore;
241
+ }): import("react").FunctionComponentElement<{
242
+ readonly position?: "absolute" | "relative" | "static" | undefined;
243
+ readonly top?: number | string | undefined;
244
+ readonly right?: number | string | undefined;
245
+ readonly bottom?: number | string | undefined;
246
+ readonly left?: number | string | undefined;
247
+ readonly columnGap?: number | undefined;
248
+ readonly rowGap?: number | undefined;
249
+ readonly gap?: number | undefined;
250
+ readonly margin?: number | undefined;
251
+ readonly marginX?: number | undefined;
252
+ readonly marginY?: number | undefined;
253
+ readonly marginTop?: number | undefined;
254
+ readonly marginBottom?: number | undefined;
255
+ readonly marginLeft?: number | undefined;
256
+ readonly marginRight?: number | undefined;
257
+ readonly padding?: number | undefined;
258
+ readonly paddingX?: number | undefined;
259
+ readonly paddingY?: number | undefined;
260
+ readonly paddingTop?: number | undefined;
261
+ readonly paddingBottom?: number | undefined;
262
+ readonly paddingLeft?: number | undefined;
263
+ readonly paddingRight?: number | undefined;
264
+ readonly flexGrow?: number | undefined;
265
+ readonly flexShrink?: number | undefined;
266
+ readonly flexDirection?: "row" | "column" | "row-reverse" | "column-reverse" | undefined;
267
+ readonly flexBasis?: number | string | undefined;
268
+ readonly flexWrap?: "nowrap" | "wrap" | "wrap-reverse" | undefined;
269
+ readonly alignItems?: "flex-start" | "center" | "flex-end" | "stretch" | "baseline" | undefined;
270
+ readonly alignSelf?: "flex-start" | "center" | "flex-end" | "auto" | "stretch" | "baseline" | undefined;
271
+ readonly alignContent?: "flex-start" | "flex-end" | "center" | "stretch" | "space-between" | "space-around" | "space-evenly" | undefined;
272
+ readonly justifyContent?: "flex-start" | "flex-end" | "space-between" | "space-around" | "space-evenly" | "center" | undefined;
273
+ readonly width?: number | string | undefined;
274
+ readonly height?: number | string | undefined;
275
+ readonly minWidth?: number | string | undefined;
276
+ readonly minHeight?: number | string | undefined;
277
+ readonly maxWidth?: number | string | undefined;
278
+ readonly maxHeight?: number | string | undefined;
279
+ readonly aspectRatio?: number | undefined;
280
+ readonly display?: "flex" | "none" | undefined;
281
+ readonly borderStyle?: (keyof Boxes | BoxStyle) | undefined;
282
+ readonly borderTop?: boolean | undefined;
283
+ readonly borderBottom?: boolean | undefined;
284
+ readonly borderLeft?: boolean | undefined;
285
+ readonly borderRight?: boolean | undefined;
286
+ readonly borderColor?: LiteralUnion<ForegroundColorName, string> | undefined;
287
+ readonly borderTopColor?: LiteralUnion<ForegroundColorName, string> | undefined;
288
+ readonly borderBottomColor?: LiteralUnion<ForegroundColorName, string> | undefined;
289
+ readonly borderLeftColor?: LiteralUnion<ForegroundColorName, string> | undefined;
290
+ readonly borderRightColor?: LiteralUnion<ForegroundColorName, string> | undefined;
291
+ readonly borderDimColor?: boolean | undefined;
292
+ readonly borderTopDimColor?: boolean | undefined;
293
+ readonly borderBottomDimColor?: boolean | undefined;
294
+ readonly borderLeftDimColor?: boolean | undefined;
295
+ readonly borderRightDimColor?: boolean | undefined;
296
+ readonly borderBackgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
297
+ readonly borderTopBackgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
298
+ readonly borderBottomBackgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
299
+ readonly borderLeftBackgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
300
+ readonly borderRightBackgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
301
+ readonly overflow?: "visible" | "hidden" | undefined;
302
+ readonly overflowX?: "visible" | "hidden" | undefined;
303
+ readonly overflowY?: "visible" | "hidden" | undefined;
304
+ readonly backgroundColor?: LiteralUnion<ForegroundColorName, string> | undefined;
305
+ } & {
306
+ readonly 'aria-label'?: string;
307
+ readonly 'aria-hidden'?: boolean;
308
+ readonly 'aria-role'?: "button" | "checkbox" | "combobox" | "list" | "listbox" | "listitem" | "menu" | "menuitem" | "option" | "progressbar" | "radio" | "radiogroup" | "tab" | "tablist" | "table" | "textbox" | "timer" | "toolbar";
309
+ readonly 'aria-state'?: {
310
+ readonly busy?: boolean;
311
+ readonly checked?: boolean;
312
+ readonly disabled?: boolean;
313
+ readonly expanded?: boolean;
314
+ readonly multiline?: boolean;
315
+ readonly multiselectable?: boolean;
316
+ readonly readonly?: boolean;
317
+ readonly required?: boolean;
318
+ readonly selected?: boolean;
319
+ };
320
+ } & {
321
+ children?: React.ReactNode | undefined;
322
+ } & import("react").RefAttributes<import("ink").DOMElement>>;
323
+ /** Screen-reader label for the approval card (ink serializes it as the button name). */
324
+ export declare function approvalLabel(tool: string, input: unknown): string;
325
+ /** Maps a prompt keypress to a decision; null = key not handled by the prompt. */
326
+ export declare function keypressToDecision(key: string): ApprovalDecision | null;
327
+ interface TuiOptions {
328
+ /** Opt-in screen-reader rendering (also honored: CHANTIER_SCREEN_READER=1). */
329
+ readonly screenReader?: boolean;
330
+ }
331
+ interface TuiInstance {
332
+ waitUntilExit(): Promise<void>;
333
+ }
334
+ /** Mounts the TUI. The store drives everything; the caller drives the agent. */
335
+ export declare function startTui(store: TuiStore, options?: TuiOptions): TuiInstance;
336
+ //#endregion
337
+ //#region src/diff.d.ts
338
+ /**
339
+ * Minimal unified-diff summarization for approval prompts. The TUI shows a
340
+ * capped preview with add/del coloring and announces the change size to
341
+ * screen readers via an aria-label, so raw diffs never reach the buffer
342
+ * unbounded.
343
+ */
344
+ type DiffLineKind = "add" | "del" | "meta" | "context";
345
+ /** Classifies one unified-diff line for rendering (add=green, del=red, meta=dim). */
346
+ export declare function classifyUnifiedDiffLine(line: string): DiffLineKind;
347
+ interface DiffPreview {
348
+ /** Lines to display, capped at maxLines. */
349
+ readonly lines: readonly string[];
350
+ readonly additions: number;
351
+ readonly deletions: number;
352
+ /** Lines beyond the display cap; the "+N more lines" tail count. */
353
+ readonly hiddenLines: number;
354
+ }
355
+ /** Counts add/del lines across the whole diff and caps the displayed lines. */
356
+ export declare function summarizeUnifiedDiff(diff: string, maxLines?: number): DiffPreview;
357
+ //#endregion
358
+ //#region src/screen-reader.d.ts
359
+ /**
360
+ * Screen-reader mode: ink serializes the tree to plain linear text (no
361
+ * borders, no colors), keeps `<Static>` append-only, and rewrites the dynamic
362
+ * region only when it changes. Enabled by the `--screen-reader` flag or the
363
+ * CHANTIER_SCREEN_READER=1 environment alias.
364
+ */
365
+ export declare function resolveScreenReader(flag: boolean | undefined, env: string | undefined): boolean;
366
+ //#endregion
367
+ //#region src/symbols.d.ts
368
+ /**
369
+ * Decorative characters and box borders used by the TUI. Screen readers skip
370
+ * or garble ornamental unicode (arrows, checkmarks, middle dots), and border
371
+ * glyphs pollute magnified review, so everything resolves to ASCII-safe
372
+ * variants when ASCII mode is requested. All TUI call sites gate through
373
+ * `resolveSymbols` so the fallback can never leak (gemini-cli #18298).
374
+ */
375
+ interface TuiSymbols {
376
+ /** Box border style: "round" normally, "single" in ASCII mode. */
377
+ readonly border: "round" | "single";
378
+ /** Separator inside hint lines: "·" normally, "|" in ASCII mode. */
379
+ readonly hintSeparator: string;
380
+ /** Truncation ellipsis: "…" normally, "..." in ASCII mode. */
381
+ readonly ellipsis: string;
382
+ }
383
+ export declare function resolveSymbols(ascii: boolean): TuiSymbols;
384
+ /** CHANTIER_ASCII=1 requests the ASCII-safe rendering. */
385
+ export declare function isAsciiEnv(env: string | undefined): boolean;
386
+ //#endregion
387
+ export type { AbortKind, DiffLineKind, DiffPreview, TuiInstance, TuiOptions, TuiPromptDetail, TuiState, TuiStore, TuiSymbols };
package/dist/index.mjs ADDED
@@ -0,0 +1,373 @@
1
+ import { Box, Static, Text, render, useApp, useInput, useIsScreenReaderEnabled } from "ink";
2
+ import { createElement, useEffect, useSyncExternalStore } from "react";
3
+ //#region src/diff.ts
4
+ const META_PREFIXES = [
5
+ "diff --git ",
6
+ "--- ",
7
+ "+++ ",
8
+ "index ",
9
+ "@@"
10
+ ];
11
+ /** Classifies one unified-diff line for rendering (add=green, del=red, meta=dim). */
12
+ function classifyUnifiedDiffLine(line) {
13
+ for (const prefix of META_PREFIXES) if (line.startsWith(prefix)) return "meta";
14
+ if (line.startsWith("+")) return "add";
15
+ if (line.startsWith("-")) return "del";
16
+ return "context";
17
+ }
18
+ /** Counts add/del lines across the whole diff and caps the displayed lines. */
19
+ function summarizeUnifiedDiff(diff, maxLines = 10) {
20
+ const split = diff.split("\n");
21
+ if (split.length > 0 && split[split.length - 1] === "") split.pop();
22
+ let additions = 0;
23
+ let deletions = 0;
24
+ for (const line of split) {
25
+ const kind = classifyUnifiedDiffLine(line);
26
+ if (kind === "add") additions += 1;
27
+ else if (kind === "del") deletions += 1;
28
+ }
29
+ return {
30
+ lines: split.slice(0, maxLines),
31
+ additions,
32
+ deletions,
33
+ hiddenLines: Math.max(0, split.length - maxLines)
34
+ };
35
+ }
36
+ //#endregion
37
+ //#region src/screen-reader.ts
38
+ /**
39
+ * Screen-reader mode: ink serializes the tree to plain linear text (no
40
+ * borders, no colors), keeps `<Static>` append-only, and rewrites the dynamic
41
+ * region only when it changes. Enabled by the `--screen-reader` flag or the
42
+ * CHANTIER_SCREEN_READER=1 environment alias.
43
+ */
44
+ function resolveScreenReader(flag, env) {
45
+ return flag === true || env === "1";
46
+ }
47
+ //#endregion
48
+ //#region src/symbols.ts
49
+ const UNICODE_SYMBOLS = {
50
+ border: "round",
51
+ hintSeparator: "·",
52
+ ellipsis: "…"
53
+ };
54
+ const ASCII_SYMBOLS = {
55
+ border: "single",
56
+ hintSeparator: "|",
57
+ ellipsis: "..."
58
+ };
59
+ function resolveSymbols(ascii) {
60
+ return ascii ? ASCII_SYMBOLS : UNICODE_SYMBOLS;
61
+ }
62
+ /** CHANTIER_ASCII=1 requests the ASCII-safe rendering. */
63
+ function isAsciiEnv(env) {
64
+ return env === "1";
65
+ }
66
+ //#endregion
67
+ //#region src/app.ts
68
+ const PROMPT_HINT_PARTS = [
69
+ "y allow",
70
+ "a always",
71
+ "n deny",
72
+ "esc abort"
73
+ ];
74
+ const INPUT_HINT_PARTS = [
75
+ "type a task",
76
+ "enter run",
77
+ "q quit"
78
+ ];
79
+ function TuiApp({ store }) {
80
+ const state = useSyncExternalStore(store.subscribe, () => store.state);
81
+ const screenReader = useIsScreenReaderEnabled();
82
+ const symbols = resolveSymbols(screenReader || isAsciiEnv(process.env.CHANTIER_ASCII));
83
+ const { exit } = useApp();
84
+ useInput((input, key) => {
85
+ const { mode, prompt } = store.state;
86
+ if (key.ctrl) {
87
+ store.abort("ctrl-c");
88
+ return;
89
+ }
90
+ if (key.escape) {
91
+ store.abort("escape");
92
+ return;
93
+ }
94
+ if (mode === "input" && prompt === null) {
95
+ if (key.backspace || key.delete) {
96
+ store.backspaceInput();
97
+ return;
98
+ }
99
+ const bundledReturn = /[\r\n]/.test(input ?? "");
100
+ if (input !== void 0 && input.length > 0) {
101
+ for (const char of input) if (char !== "\r" && char !== "\n") store.typeInput(char);
102
+ }
103
+ if (key.return || bundledReturn) store.submitTask(store.state.inputText);
104
+ return;
105
+ }
106
+ if (prompt !== null) {
107
+ const decision = keypressToDecision(input.replace(/[\r\n]/g, ""));
108
+ if (decision !== null) store.decide(decision);
109
+ }
110
+ });
111
+ useEffect(() => {
112
+ if (!store.state.finished) return;
113
+ const timer = setTimeout(exit, 50);
114
+ return () => clearTimeout(timer);
115
+ });
116
+ const children = [createElement(Static, {
117
+ items: [...state.lines],
118
+ children: (item, index) => createElement(Text, { key: index }, String(item))
119
+ })];
120
+ if (state.streamText.length > 0) children.push(createElement(Text, {
121
+ color: "cyan",
122
+ "aria-hidden": screenReader
123
+ }, state.streamText));
124
+ if (state.status.length > 0) children.push(createElement(Text, { dimColor: true }, state.status));
125
+ if (state.prompt !== null) {
126
+ const { tool, input } = state.prompt;
127
+ children.push(createElement(Box, {
128
+ flexDirection: "column",
129
+ borderStyle: symbols.border,
130
+ borderColor: "yellow",
131
+ paddingX: 1,
132
+ "aria-role": "button"
133
+ }, createElement(Text, {
134
+ bold: true,
135
+ color: "yellow",
136
+ "aria-label": approvalLabel(tool, input)
137
+ }, `approve ${tool}?`), createElement(Text, { dimColor: true }, summarizeInput(input, symbols.ellipsis)), diffCard(state.promptDetail, symbols), createElement(Text, null, PROMPT_HINT_PARTS.join(` ${symbols.hintSeparator} `))));
138
+ }
139
+ if (state.mode === "input" && !state.finished) children.push(createElement(Box, {
140
+ borderStyle: symbols.border,
141
+ borderColor: "green",
142
+ paddingX: 1
143
+ }, createElement(Text, { color: "green" }, "> "), createElement(Text, null, state.inputText), createElement(Text, { dimColor: true }, ` ${INPUT_HINT_PARTS.join(` ${symbols.hintSeparator} `)}`)));
144
+ return createElement(Box, { flexDirection: "column" }, ...children);
145
+ }
146
+ /** The unified-diff attachment card, or null when the ask carries no diff. */
147
+ function diffCard(detail, symbols) {
148
+ if (detail === null) return null;
149
+ if (typeof detail.diff !== "string" || detail.diff.length === 0) return null;
150
+ const preview = summarizeUnifiedDiff(detail.diff);
151
+ return createElement(Box, {
152
+ flexDirection: "column",
153
+ borderStyle: symbols.border,
154
+ borderColor: "cyan",
155
+ paddingX: 1,
156
+ "aria-label": `proposed change: ${preview.additions} ${preview.additions === 1 ? "addition" : "additions"}, ${preview.deletions} ${preview.deletions === 1 ? "deletion" : "deletions"}`
157
+ }, createElement(Text, { dimColor: true }, "proposed change"), ...preview.lines.map((line, index) => createElement(Text, {
158
+ key: index,
159
+ ...diffTextStyle(classifyUnifiedDiffLine(line))
160
+ }, line)), preview.hiddenLines > 0 ? createElement(Text, { dimColor: true }, `+${preview.hiddenLines} more lines`) : null);
161
+ }
162
+ function diffTextStyle(kind) {
163
+ if (kind === "add") return { color: "green" };
164
+ if (kind === "del") return { color: "red" };
165
+ if (kind === "meta") return { dimColor: true };
166
+ return {};
167
+ }
168
+ function summarizeInput(input, ellipsis) {
169
+ const json = JSON.stringify(input);
170
+ return json.length > 160 ? `${json.slice(0, 160)}${ellipsis}` : json;
171
+ }
172
+ /** Screen-reader label for the approval card (ink serializes it as the button name). */
173
+ function approvalLabel(tool, input) {
174
+ const subject = inputSubject(input);
175
+ return subject.length > 0 ? `approve ${tool} of ${subject}` : `approve ${tool}`;
176
+ }
177
+ function inputSubject(input) {
178
+ if (typeof input !== "object" || input === null) return "";
179
+ const record = input;
180
+ for (const key of [
181
+ "path",
182
+ "file_path",
183
+ "file"
184
+ ]) {
185
+ const value = record[key];
186
+ if (typeof value === "string" && value.length > 0) return value;
187
+ }
188
+ return "";
189
+ }
190
+ /** Maps a prompt keypress to a decision; null = key not handled by the prompt. */
191
+ function keypressToDecision(key) {
192
+ const clean = key.replace(/[\r\n]/g, "");
193
+ if (clean === "y") return { approved: true };
194
+ if (clean === "a") return {
195
+ approved: true,
196
+ remember: true
197
+ };
198
+ if (clean === "n") return {
199
+ approved: false,
200
+ reason: "user denied"
201
+ };
202
+ return null;
203
+ }
204
+ /** Mounts the TUI. The store drives everything; the caller drives the agent. */
205
+ function startTui(store, options = {}) {
206
+ const screenReader = resolveScreenReader(options.screenReader, process.env.CHANTIER_SCREEN_READER);
207
+ const instance = render(createElement(TuiApp, { store }), {
208
+ exitOnCtrlC: false,
209
+ ...screenReader ? { isScreenReaderEnabled: true } : {}
210
+ });
211
+ return { waitUntilExit: () => instance.waitUntilExit().then(() => void 0) };
212
+ }
213
+ //#endregion
214
+ //#region src/store.ts
215
+ function createTuiStore(handlers, isQuitCommand = (text) => /^(q|exit|quit)$/i.test(text.trim())) {
216
+ let state = {
217
+ mode: "input",
218
+ lines: [],
219
+ streamText: "",
220
+ status: "",
221
+ prompt: null,
222
+ promptDetail: null,
223
+ inputText: "",
224
+ finished: false
225
+ };
226
+ const listeners = /* @__PURE__ */ new Set();
227
+ const pendingTasks = [];
228
+ let pendingPrompt = null;
229
+ const set = (patch) => {
230
+ state = {
231
+ ...state,
232
+ ...patch
233
+ };
234
+ for (const listener of listeners) listener();
235
+ };
236
+ const STREAM_COALESCE_MS = 20;
237
+ let pendingStream = "";
238
+ let streamTimer = null;
239
+ const disarmStreamTimer = () => {
240
+ if (streamTimer !== null) {
241
+ clearTimeout(streamTimer);
242
+ streamTimer = null;
243
+ }
244
+ };
245
+ const armStreamTimer = () => {
246
+ if (streamTimer !== null) return;
247
+ streamTimer = setTimeout(() => {
248
+ streamTimer = null;
249
+ if (pendingStream.length === 0) return;
250
+ const chunk = pendingStream;
251
+ pendingStream = "";
252
+ set({ streamText: state.streamText + chunk });
253
+ }, STREAM_COALESCE_MS);
254
+ };
255
+ /** Normalizes an ask detail: only a non-empty string diff survives. */
256
+ const normalizeDetail = (detail) => {
257
+ if (typeof detail?.diff === "string" && detail.diff.length > 0) return { diff: detail.diff };
258
+ return null;
259
+ };
260
+ return {
261
+ get state() {
262
+ return state;
263
+ },
264
+ subscribe(listener) {
265
+ listeners.add(listener);
266
+ return () => listeners.delete(listener);
267
+ },
268
+ pushLine(line) {
269
+ set({ lines: [...state.lines, line] });
270
+ },
271
+ appendStream(text) {
272
+ pendingStream += text;
273
+ if (pendingStream.length > 0) armStreamTimer();
274
+ },
275
+ flushStream() {
276
+ disarmStreamTimer();
277
+ const buffered = `${state.streamText}${pendingStream}`;
278
+ pendingStream = "";
279
+ if (buffered.length === 0) return;
280
+ set({
281
+ lines: [...state.lines, ...buffered.split("\n")],
282
+ streamText: ""
283
+ });
284
+ },
285
+ setStatus(status) {
286
+ set({ status });
287
+ },
288
+ backspaceInput() {
289
+ set({ inputText: state.inputText.slice(0, -1) });
290
+ },
291
+ typeInput(char) {
292
+ set({ inputText: state.inputText + char });
293
+ },
294
+ awaitTask() {
295
+ const { promise, resolve } = Promise.withResolvers();
296
+ pendingTasks.push({ resolve });
297
+ set({
298
+ mode: "input",
299
+ inputText: "",
300
+ status: "",
301
+ prompt: null,
302
+ promptDetail: null
303
+ });
304
+ return promise;
305
+ },
306
+ submitTask(text) {
307
+ if (state.mode !== "input") return;
308
+ if (isQuitCommand(text)) {
309
+ for (const task of pendingTasks.splice(0)) task.resolve(null);
310
+ set({
311
+ finished: true,
312
+ inputText: ""
313
+ });
314
+ return;
315
+ }
316
+ for (const task of pendingTasks.splice(0)) task.resolve(text);
317
+ set({
318
+ mode: "running",
319
+ inputText: ""
320
+ });
321
+ },
322
+ async ask(req, detail) {
323
+ const { promise, resolve } = Promise.withResolvers();
324
+ pendingPrompt = { resolve };
325
+ set({
326
+ prompt: req,
327
+ promptDetail: normalizeDetail(detail)
328
+ });
329
+ return promise;
330
+ },
331
+ decide(decision) {
332
+ const pending = pendingPrompt;
333
+ if (pending === null) return;
334
+ pendingPrompt = null;
335
+ set({
336
+ prompt: null,
337
+ promptDetail: null
338
+ });
339
+ pending.resolve(decision);
340
+ },
341
+ abort(kind) {
342
+ if (pendingPrompt !== null) {
343
+ const pending = pendingPrompt;
344
+ pendingPrompt = null;
345
+ set({
346
+ prompt: null,
347
+ promptDetail: null
348
+ });
349
+ pending.resolve({
350
+ approved: false,
351
+ reason: "user aborted"
352
+ });
353
+ }
354
+ if (kind === "ctrl-c") {
355
+ set({
356
+ finished: true,
357
+ mode: "input"
358
+ });
359
+ for (const task of pendingTasks.splice(0)) task.resolve(null);
360
+ }
361
+ handlers.onAbort(kind);
362
+ },
363
+ finish() {
364
+ set({
365
+ finished: true,
366
+ mode: "input"
367
+ });
368
+ for (const task of pendingTasks.splice(0)) task.resolve(null);
369
+ }
370
+ };
371
+ }
372
+ //#endregion
373
+ export { TuiApp, approvalLabel, classifyUnifiedDiffLine, createTuiStore, isAsciiEnv, keypressToDecision, resolveScreenReader, resolveSymbols, startTui, summarizeUnifiedDiff };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@chantier/tui",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "description": "Ink-based interactive terminal UI for the chantier coding agent",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/mlcassociation/chantier.git"
26
+ },
27
+ "homepage": "https://github.com/mlcassociation/chantier#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/mlcassociation/chantier/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown src/index.ts --format esm --dts --clean --out-dir dist",
36
+ "prepublishOnly": "npm run build"
37
+ },
38
+ "dependencies": {
39
+ "@chantier/core": "^0.3.0",
40
+ "@chantier/permissions": "^0.3.0",
41
+ "ink": "7.1.1",
42
+ "react": "^19.2.0"
43
+ },
44
+ "devDependencies": {
45
+ "ink-testing-library": "4.0.0",
46
+ "tsdown": "0.23.0",
47
+ "@types/react": "^19.2.0"
48
+ }
49
+ }