@mistriwork/agent-ui 0.0.0-stage → 1.4.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/dist/shell.js ADDED
@@ -0,0 +1,191 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Workbench shell & navigation primitives for `@mistriwork/agent-ui`:
4
+ * - `<WorkbenchLayout>`: resizable multi-pane IDE/orchestrator frame
5
+ * - `<TabStrip>`: open-file / session / diff tab bar
6
+ * - `<StatusBar>`: compact bottom IDE status strip
7
+ * - `<CommandPalette>`: keyboard-first filterable command / file / session launcher
8
+ */
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
10
+ import { Badge, Button, EmptyState, StatusDot, TextField } from '@mistriwork/mistri/ui';
11
+ import './workbench.css';
12
+ function clamp(value, min, max) {
13
+ return Math.min(max, Math.max(min, value));
14
+ }
15
+ export function WorkbenchLayout({ header, sidebar, main, inspector, bottom, statusBar, defaultSidebarWidth = 260, defaultInspectorWidth = 360, defaultBottomHeight = 200, minSidebarWidth = 160, maxSidebarWidth = 520, minInspectorWidth = 220, maxInspectorWidth = 640, minBottomHeight = 100, maxBottomHeight = 480, sidebarCollapsed = false, inspectorCollapsed = false, bottomCollapsed = false, onLayoutChange, className, }) {
16
+ const [sidebarWidth, setSidebarWidth] = useState(defaultSidebarWidth);
17
+ const [inspectorWidth, setInspectorWidth] = useState(defaultInspectorWidth);
18
+ const [bottomHeight, setBottomHeight] = useState(defaultBottomHeight);
19
+ const sizesRef = useRef({
20
+ sidebarWidth: defaultSidebarWidth,
21
+ inspectorWidth: defaultInspectorWidth,
22
+ bottomHeight: defaultBottomHeight,
23
+ });
24
+ const emitSizes = useCallback((next) => {
25
+ sizesRef.current = next;
26
+ onLayoutChange?.(next);
27
+ }, [onLayoutChange]);
28
+ const startDrag = useCallback((axis, event) => {
29
+ event.preventDefault();
30
+ const startX = event.clientX;
31
+ const startY = event.clientY;
32
+ const initial = sizesRef.current;
33
+ const onMove = (moveEvent) => {
34
+ if (axis === 'sidebar') {
35
+ const nextWidth = clamp(initial.sidebarWidth + (moveEvent.clientX - startX), minSidebarWidth, maxSidebarWidth);
36
+ setSidebarWidth(nextWidth);
37
+ emitSizes({ ...sizesRef.current, sidebarWidth: nextWidth });
38
+ }
39
+ else if (axis === 'inspector') {
40
+ const nextWidth = clamp(initial.inspectorWidth - (moveEvent.clientX - startX), minInspectorWidth, maxInspectorWidth);
41
+ setInspectorWidth(nextWidth);
42
+ emitSizes({ ...sizesRef.current, inspectorWidth: nextWidth });
43
+ }
44
+ else {
45
+ const nextHeight = clamp(initial.bottomHeight - (moveEvent.clientY - startY), minBottomHeight, maxBottomHeight);
46
+ setBottomHeight(nextHeight);
47
+ emitSizes({ ...sizesRef.current, bottomHeight: nextHeight });
48
+ }
49
+ };
50
+ const onUp = () => {
51
+ globalThis.removeEventListener('pointermove', onMove);
52
+ globalThis.removeEventListener('pointerup', onUp);
53
+ };
54
+ globalThis.addEventListener('pointermove', onMove);
55
+ globalThis.addEventListener('pointerup', onUp);
56
+ }, [emitSizes, maxBottomHeight, maxInspectorWidth, maxSidebarWidth, minBottomHeight, minInspectorWidth, minSidebarWidth]);
57
+ const onHandleKeyDown = useCallback((axis, event) => {
58
+ const step = event.shiftKey ? 48 : 16;
59
+ if (axis === 'sidebar' && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
60
+ event.preventDefault();
61
+ const delta = event.key === 'ArrowRight' ? step : -step;
62
+ const nextWidth = clamp(sizesRef.current.sidebarWidth + delta, minSidebarWidth, maxSidebarWidth);
63
+ setSidebarWidth(nextWidth);
64
+ emitSizes({ ...sizesRef.current, sidebarWidth: nextWidth });
65
+ }
66
+ else if (axis === 'inspector' && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
67
+ event.preventDefault();
68
+ const delta = event.key === 'ArrowLeft' ? step : -step;
69
+ const nextWidth = clamp(sizesRef.current.inspectorWidth + delta, minInspectorWidth, maxInspectorWidth);
70
+ setInspectorWidth(nextWidth);
71
+ emitSizes({ ...sizesRef.current, inspectorWidth: nextWidth });
72
+ }
73
+ else if (axis === 'bottom' && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
74
+ event.preventDefault();
75
+ const delta = event.key === 'ArrowUp' ? step : -step;
76
+ const nextHeight = clamp(sizesRef.current.bottomHeight + delta, minBottomHeight, maxBottomHeight);
77
+ setBottomHeight(nextHeight);
78
+ emitSizes({ ...sizesRef.current, bottomHeight: nextHeight });
79
+ }
80
+ }, [emitSizes, maxBottomHeight, maxInspectorWidth, maxSidebarWidth, minBottomHeight, minInspectorWidth, minSidebarWidth]);
81
+ const showSidebar = Boolean(sidebar) && !sidebarCollapsed;
82
+ const showInspector = Boolean(inspector) && !inspectorCollapsed;
83
+ const showBottom = Boolean(bottom) && !bottomCollapsed;
84
+ return (_jsxs("div", { className: className ? `aui-workbench ${className}` : 'aui-workbench', children: [header ? _jsx("header", { className: "aui-workbench-header", children: header }) : null, _jsxs("div", { className: "aui-workbench-body", children: [showSidebar ? (_jsxs(_Fragment, { children: [_jsx("aside", { className: "aui-workbench-pane", "data-slot": "sidebar", style: { width: `${sidebarWidth}px` }, "aria-label": "Sidebar", children: sidebar }), _jsx("div", { className: "aui-workbench-handle", role: "separator", tabIndex: 0, "aria-label": "Resize sidebar", "aria-orientation": "vertical", "aria-valuemin": minSidebarWidth, "aria-valuemax": maxSidebarWidth, "aria-valuenow": sidebarWidth, onPointerDown: (e) => startDrag('sidebar', e), onKeyDown: (e) => onHandleKeyDown('sidebar', e) })] })) : null, _jsxs("div", { className: "aui-workbench-center", children: [_jsx("main", { className: "aui-workbench-main", children: main }), showBottom ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "aui-workbench-handle", role: "separator", tabIndex: 0, "aria-label": "Resize bottom panel", "aria-orientation": "horizontal", "aria-valuemin": minBottomHeight, "aria-valuemax": maxBottomHeight, "aria-valuenow": bottomHeight, onPointerDown: (e) => startDrag('bottom', e), onKeyDown: (e) => onHandleKeyDown('bottom', e) }), _jsx("section", { className: "aui-workbench-bottom", style: { height: `${bottomHeight}px` }, "aria-label": "Bottom panel", children: bottom })] })) : null] }), showInspector ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "aui-workbench-handle", role: "separator", tabIndex: 0, "aria-label": "Resize inspector", "aria-orientation": "vertical", "aria-valuemin": minInspectorWidth, "aria-valuemax": maxInspectorWidth, "aria-valuenow": inspectorWidth, onPointerDown: (e) => startDrag('inspector', e), onKeyDown: (e) => onHandleKeyDown('inspector', e) }), _jsx("aside", { className: "aui-workbench-pane", "data-slot": "inspector", style: { width: `${inspectorWidth}px` }, "aria-label": "Inspector", children: inspector })] })) : null] }), statusBar] }));
85
+ }
86
+ export function TabStrip({ tabs, activeId, onSelect, onClose, actions, ariaLabel = 'Open views', className }) {
87
+ const handleKeyDown = (index, event) => {
88
+ if (tabs.length === 0)
89
+ return;
90
+ if (event.key === 'ArrowRight') {
91
+ event.preventDefault();
92
+ const next = tabs[(index + 1) % tabs.length];
93
+ if (next)
94
+ onSelect(next.id);
95
+ }
96
+ else if (event.key === 'ArrowLeft') {
97
+ event.preventDefault();
98
+ const prev = tabs[(index - 1 + tabs.length) % tabs.length];
99
+ if (prev)
100
+ onSelect(prev.id);
101
+ }
102
+ };
103
+ return (_jsxs("div", { className: className ? `aui-tabstrip ${className}` : 'aui-tabstrip', children: [_jsx("div", { className: "aui-tabstrip-list", role: "tablist", "aria-label": ariaLabel, children: tabs.map((tab, idx) => {
104
+ const selected = tab.id === activeId;
105
+ const canClose = onClose && tab.closable !== false;
106
+ return (_jsxs("div", { style: { display: 'inline-flex', alignItems: 'center' }, children: [_jsxs("button", { type: "button", role: "tab", className: "aui-tab", "aria-selected": selected, title: tab.title ?? tab.label, tabIndex: selected ? 0 : -1, onClick: () => onSelect(tab.id), onKeyDown: (e) => handleKeyDown(idx, e), children: [_jsx("span", { className: "aui-tab-label", children: tab.label }), tab.badge ? _jsx(Badge, { tone: tab.tone ?? 'neutral', children: tab.badge }) : null, tab.dirty ? _jsx("span", { className: "aui-tab-dirty", "aria-label": "Unsaved changes" }) : null] }), canClose ? (_jsx(Button, { size: "sm", variant: "ghost", ariaLabel: `Close ${tab.label}`, onClick: () => onClose(tab.id), children: "\u00D7" })) : null] }, tab.id));
107
+ }) }), actions ? _jsx("div", { className: "aui-tab-actions", children: actions }) : null] }));
108
+ }
109
+ function renderStatusItem(item) {
110
+ const content = (_jsxs("span", { className: "aui-statusbar-item", children: [item.tone ? _jsx(StatusDot, { tone: item.tone, pulse: item.pulse }) : null, _jsx("span", { children: item.value !== undefined ? `${item.label}: ${item.value}` : item.label })] }));
111
+ if (item.onClick) {
112
+ return (_jsx(Button, { size: "sm", variant: "ghost", onClick: item.onClick, children: content }, item.id));
113
+ }
114
+ return _jsx("span", { children: content }, item.id);
115
+ }
116
+ export function StatusBar({ items = [], left, right, className }) {
117
+ const leftItems = items.filter((item) => item.align !== 'right');
118
+ const rightItems = items.filter((item) => item.align === 'right');
119
+ return (_jsxs("footer", { className: className ? `aui-statusbar ${className}` : 'aui-statusbar', role: "status", "aria-label": "Workbench status", children: [_jsxs("div", { className: "aui-statusbar-group", children: [leftItems.map(renderStatusItem), left] }), _jsxs("div", { className: "aui-statusbar-group", children: [rightItems.map(renderStatusItem), right] })] }));
120
+ }
121
+ export function CommandPalette({ open, onOpenChange, items, onSelect, placeholder = 'Jump to file, session, or command…', emptyTitle = 'No matching commands', bindHotkey = false, className, }) {
122
+ const [query, setQuery] = useState('');
123
+ const [activeIndex, setActiveIndex] = useState(0);
124
+ useEffect(() => {
125
+ if (!bindHotkey)
126
+ return;
127
+ const onGlobalKey = (event) => {
128
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
129
+ event.preventDefault();
130
+ onOpenChange(!open);
131
+ }
132
+ };
133
+ globalThis.addEventListener('keydown', onGlobalKey);
134
+ return () => globalThis.removeEventListener('keydown', onGlobalKey);
135
+ }, [bindHotkey, open, onOpenChange]);
136
+ const filtered = useMemo(() => {
137
+ const q = query.trim().toLowerCase();
138
+ if (!q)
139
+ return items;
140
+ return items.filter((item) => {
141
+ const hay = [item.label, item.description ?? '', item.group ?? '', ...(item.keywords ?? [])].join(' ').toLowerCase();
142
+ return hay.includes(q);
143
+ });
144
+ }, [items, query]);
145
+ const clampedIndex = filtered.length === 0 ? 0 : Math.min(activeIndex, filtered.length - 1);
146
+ const grouped = useMemo(() => {
147
+ const map = new Map();
148
+ filtered.forEach((item, index) => {
149
+ const key = item.group ?? '';
150
+ const bucket = map.get(key) ?? [];
151
+ bucket.push({ item, index });
152
+ map.set(key, bucket);
153
+ });
154
+ return [...map.entries()];
155
+ }, [filtered]);
156
+ if (!open)
157
+ return null;
158
+ const choose = (item) => {
159
+ if (item.disabled)
160
+ return;
161
+ onSelect(item);
162
+ setQuery('');
163
+ setActiveIndex(0);
164
+ onOpenChange(false);
165
+ };
166
+ const handleKeyDown = (event) => {
167
+ if (event.key === 'Escape') {
168
+ event.preventDefault();
169
+ onOpenChange(false);
170
+ }
171
+ else if (event.key === 'ArrowDown' && filtered.length > 0) {
172
+ event.preventDefault();
173
+ setActiveIndex((clampedIndex + 1) % filtered.length);
174
+ }
175
+ else if (event.key === 'ArrowUp' && filtered.length > 0) {
176
+ event.preventDefault();
177
+ setActiveIndex((clampedIndex - 1 + filtered.length) % filtered.length);
178
+ }
179
+ else if (event.key === 'Enter' && filtered[clampedIndex]) {
180
+ event.preventDefault();
181
+ choose(filtered[clampedIndex]);
182
+ }
183
+ };
184
+ return (_jsx("div", { className: "aui-palette-backdrop", role: "presentation", onClick: (e) => {
185
+ if (e.target === e.currentTarget)
186
+ onOpenChange(false);
187
+ }, children: _jsxs("div", { className: className ? `aui-palette ${className}` : 'aui-palette', role: "dialog", "aria-modal": "true", "aria-label": "Command palette", onKeyDown: handleKeyDown, children: [_jsx("div", { className: "aui-palette-head", children: _jsx(TextField, { label: "Search commands", labelHidden: true, reserve: false, value: query, onValueChange: (next) => {
188
+ setQuery(next);
189
+ setActiveIndex(0);
190
+ }, placeholder: placeholder }) }), _jsx("div", { className: "aui-palette-list", role: "listbox", "aria-label": "Commands", children: filtered.length === 0 ? (_jsx(EmptyState, { compact: true, title: emptyTitle })) : (grouped.map(([group, entries]) => (_jsxs("div", { children: [group ? _jsx("div", { className: "aui-palette-group", children: group }) : null, entries.map(({ item, index }) => (_jsxs("button", { type: "button", role: "option", "aria-selected": index === clampedIndex, "data-active": index === clampedIndex ? 'true' : undefined, disabled: item.disabled, className: "aui-palette-item", onMouseEnter: () => setActiveIndex(index), onClick: () => choose(item), children: [_jsxs("span", { className: "aui-palette-item-main", children: [_jsx("span", { children: item.label }), item.description ? _jsx("span", { className: "aui-palette-item-desc", children: item.description }) : null] }), item.shortcut ? _jsx("span", { className: "aui-palette-shortcut", children: item.shortcut }) : null] }, item.id)))] }, group || '__default')))) })] }) }));
191
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Pure reducers/bridges connecting Mistri's `page.useAgentStream()` state
3
+ * (`AgentStreamState` / `AgentStreamEvent`) directly to `@mistriwork/agent-ui`
4
+ * primitives (`<AgentThread>`, `<ToolCallInspector>`, `<ApprovalQueue>`,
5
+ * `<DiffSurface>`).
6
+ */
7
+ import type { AgentThreadApproval, AgentThreadMessage, AgentThreadToolCall, DiffFile } from './agentIde.js';
8
+ export type AgentStreamStatusLike = 'idle' | 'connecting' | 'streaming' | 'done' | 'error';
9
+ export interface AgentStreamToolCallLike {
10
+ readonly id: string;
11
+ readonly name: string;
12
+ readonly label?: string;
13
+ readonly status: 'running' | 'completed' | 'failed';
14
+ readonly input?: Readonly<Record<string, unknown>>;
15
+ readonly output?: string;
16
+ }
17
+ export interface AgentStreamApprovalLike {
18
+ readonly id: string;
19
+ readonly tool: string;
20
+ readonly risk?: 'low' | 'medium' | 'high';
21
+ readonly summary: string;
22
+ readonly input?: Readonly<Record<string, unknown>>;
23
+ }
24
+ export interface AgentStreamDiffLike {
25
+ readonly path: string;
26
+ readonly patch: string;
27
+ }
28
+ /** Structural subset of Mistri's `AgentStreamState` returned by `page.useAgentStream(sessionId)`. */
29
+ export interface AgentStreamSnapshot {
30
+ readonly status: AgentStreamStatusLike;
31
+ readonly text: string;
32
+ readonly reasoning: string;
33
+ readonly toolCalls: readonly AgentStreamToolCallLike[];
34
+ readonly pendingApprovals: readonly AgentStreamApprovalLike[];
35
+ readonly diffs: readonly AgentStreamDiffLike[];
36
+ readonly error: string | null;
37
+ }
38
+ export interface StreamToMessageOptions {
39
+ /** Stable message id for the streaming assistant turn. Defaults to `'streaming-turn'`. */
40
+ readonly id?: string;
41
+ /** Optional model badge displayed in the message header. */
42
+ readonly model?: string;
43
+ /** Optional timestamp string displayed in the message header. */
44
+ readonly timestamp?: string;
45
+ }
46
+ export interface ApprovalQueueItem extends AgentThreadApproval {
47
+ readonly sessionId?: string;
48
+ readonly agentLabel?: string;
49
+ readonly createdAt?: string;
50
+ }
51
+ export interface ToolCallRecord extends AgentThreadToolCall {
52
+ readonly input?: Readonly<Record<string, unknown>>;
53
+ readonly durationMs?: number;
54
+ readonly error?: string;
55
+ }
56
+ /** Convert an `AgentStreamState` snapshot into an `AgentThreadMessage`, or `null` when idle and empty. */
57
+ export declare function streamStateToThreadMessage(stream: AgentStreamSnapshot, options?: StreamToMessageOptions): AgentThreadMessage | null;
58
+ /** Merge a live `AgentStreamState` onto persisted `AgentThreadMessage[]` history without duplicating by id. */
59
+ export declare function mergeStreamingTurn(messages: readonly AgentThreadMessage[], stream: AgentStreamSnapshot, options?: StreamToMessageOptions): AgentThreadMessage[];
60
+ /** Map `AgentStreamState.toolCalls` to `ToolCallRecord[]` for `<ToolCallInspector>`. */
61
+ export declare function streamStateToToolCalls(stream: AgentStreamSnapshot): ToolCallRecord[];
62
+ /** Map `AgentStreamState.pendingApprovals` to `ApprovalQueueItem[]` for `<ApprovalQueue>`. */
63
+ export declare function streamStateToApprovals(stream: AgentStreamSnapshot, meta?: {
64
+ readonly sessionId?: string;
65
+ readonly agentLabel?: string;
66
+ }): ApprovalQueueItem[];
67
+ /** Parse `AgentStreamState.diffs` into `DiffFile[]` ready for `<DiffView>` or `<DiffSurface>`. */
68
+ export declare function streamStateToDiffFiles(stream: AgentStreamSnapshot): DiffFile[];
@@ -0,0 +1,93 @@
1
+ import { parseUnifiedDiff } from './agentIde.js';
2
+ /** Convert an `AgentStreamState` snapshot into an `AgentThreadMessage`, or `null` when idle and empty. */
3
+ export function streamStateToThreadMessage(stream, options) {
4
+ const hasPayload = stream.text.length > 0 ||
5
+ stream.reasoning.length > 0 ||
6
+ stream.toolCalls.length > 0 ||
7
+ stream.pendingApprovals.length > 0 ||
8
+ stream.error !== null;
9
+ if (!hasPayload && stream.status !== 'streaming' && stream.status !== 'connecting')
10
+ return null;
11
+ const content = stream.error ? (stream.text ? `${stream.text}\n\nError: ${stream.error}` : `Error: ${stream.error}`) : stream.text;
12
+ return {
13
+ id: options?.id ?? 'streaming-turn',
14
+ role: 'assistant',
15
+ content,
16
+ ...(stream.reasoning ? { reasoning: stream.reasoning } : {}),
17
+ ...(stream.toolCalls.length > 0
18
+ ? {
19
+ toolCalls: stream.toolCalls.map((tc) => ({
20
+ id: tc.id,
21
+ name: tc.name,
22
+ ...(tc.label !== undefined ? { label: tc.label } : {}),
23
+ status: tc.status,
24
+ ...(tc.input !== undefined ? { input: tc.input } : {}),
25
+ ...(tc.output !== undefined ? { output: tc.output } : {}),
26
+ })),
27
+ }
28
+ : {}),
29
+ ...(stream.pendingApprovals.length > 0
30
+ ? {
31
+ approvals: stream.pendingApprovals.map((ap) => ({
32
+ id: ap.id,
33
+ tool: ap.tool,
34
+ ...(ap.risk !== undefined ? { risk: ap.risk } : {}),
35
+ summary: ap.summary,
36
+ ...(ap.input !== undefined ? { input: ap.input } : {}),
37
+ })),
38
+ }
39
+ : {}),
40
+ ...(options?.model !== undefined ? { model: options.model } : {}),
41
+ ...(options?.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
42
+ streaming: stream.status === 'streaming' || stream.status === 'connecting',
43
+ };
44
+ }
45
+ /** Merge a live `AgentStreamState` onto persisted `AgentThreadMessage[]` history without duplicating by id. */
46
+ export function mergeStreamingTurn(messages, stream, options) {
47
+ const live = streamStateToThreadMessage(stream, options);
48
+ if (!live)
49
+ return [...messages];
50
+ const idx = messages.findIndex((msg) => msg.id === live.id);
51
+ if (idx === -1)
52
+ return [...messages, live];
53
+ const next = [...messages];
54
+ next[idx] = live;
55
+ return next;
56
+ }
57
+ /** Map `AgentStreamState.toolCalls` to `ToolCallRecord[]` for `<ToolCallInspector>`. */
58
+ export function streamStateToToolCalls(stream) {
59
+ return stream.toolCalls.map((tc) => ({
60
+ id: tc.id,
61
+ name: tc.name,
62
+ ...(tc.label !== undefined ? { label: tc.label } : {}),
63
+ status: tc.status,
64
+ ...(tc.input !== undefined ? { input: tc.input } : {}),
65
+ ...(tc.output !== undefined ? { output: tc.output } : {}),
66
+ }));
67
+ }
68
+ /** Map `AgentStreamState.pendingApprovals` to `ApprovalQueueItem[]` for `<ApprovalQueue>`. */
69
+ export function streamStateToApprovals(stream, meta) {
70
+ return stream.pendingApprovals.map((ap) => ({
71
+ id: ap.id,
72
+ tool: ap.tool,
73
+ ...(ap.risk !== undefined ? { risk: ap.risk } : {}),
74
+ summary: ap.summary,
75
+ ...(ap.input !== undefined ? { input: ap.input } : {}),
76
+ ...(meta?.sessionId !== undefined ? { sessionId: meta.sessionId } : {}),
77
+ ...(meta?.agentLabel !== undefined ? { agentLabel: meta.agentLabel } : {}),
78
+ }));
79
+ }
80
+ /** Parse `AgentStreamState.diffs` into `DiffFile[]` ready for `<DiffView>` or `<DiffSurface>`. */
81
+ export function streamStateToDiffFiles(stream) {
82
+ const out = [];
83
+ for (const entry of stream.diffs) {
84
+ const parsed = parseUnifiedDiff(entry.patch);
85
+ if (parsed.length > 0) {
86
+ out.push(...parsed);
87
+ }
88
+ else {
89
+ out.push({ path: entry.path, patch: entry.patch, status: 'M' });
90
+ }
91
+ }
92
+ return out;
93
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Pluggable Code, Diff, and FileTree surface primitives + `<AgentUiProvider>`:
3
+ * - Zero-dep fallbacks work immediately out of the box.
4
+ * - Registering `@mistriwork/agent-ui/pierre` (or CodeMirror/Monaco) via
5
+ * `<AgentUiProvider surfaces={...}>` transparently upgrades every surface
6
+ * in the workbench.
7
+ */
8
+ import { type ComponentType, type ReactNode } from 'react';
9
+ import { type DiffFile } from './agentIde.js';
10
+ import { type FileTreeProps } from './fileTree.js';
11
+ import './workbench.css';
12
+ export interface CodeMarker {
13
+ readonly line: number;
14
+ readonly column?: number;
15
+ readonly endLine?: number;
16
+ readonly endColumn?: number;
17
+ readonly severity: 'error' | 'warning' | 'info';
18
+ readonly message: string;
19
+ readonly source?: string;
20
+ }
21
+ export interface CodeAnnotation {
22
+ readonly id?: string;
23
+ readonly line: number;
24
+ readonly body: ReactNode;
25
+ }
26
+ export interface DiffAnnotation {
27
+ readonly id?: string;
28
+ readonly side: 'additions' | 'deletions';
29
+ readonly line: number;
30
+ readonly body: ReactNode;
31
+ }
32
+ export interface CodeSelectionSnippet {
33
+ readonly path: string;
34
+ readonly startLine: number;
35
+ readonly endLine: number;
36
+ readonly text: string;
37
+ }
38
+ export interface CodeSurfaceProps {
39
+ readonly path: string;
40
+ readonly content: string;
41
+ readonly language?: string;
42
+ readonly editable?: boolean;
43
+ readonly onChange?: (nextContent: string) => void;
44
+ readonly markers?: readonly CodeMarker[];
45
+ readonly annotations?: readonly CodeAnnotation[];
46
+ readonly onAddToChat?: (snippet: CodeSelectionSnippet) => void;
47
+ readonly className?: string;
48
+ }
49
+ export interface DiffSurfaceFileInput {
50
+ readonly name: string;
51
+ readonly contents: string;
52
+ readonly lang?: string;
53
+ }
54
+ export interface DiffSurfaceProps {
55
+ /** Raw unified diff text (e.g. `git diff`). */
56
+ readonly patch?: string;
57
+ /** Structured file list (compatible with `<DiffView>`). */
58
+ readonly files?: readonly DiffFile[];
59
+ /** Explicit old/new file pair for file-to-file diffing (used natively by Pierre `FileDiff`). */
60
+ readonly oldFile?: DiffSurfaceFileInput;
61
+ readonly newFile?: DiffSurfaceFileInput;
62
+ readonly diffStyle?: 'unified' | 'split';
63
+ readonly editable?: boolean;
64
+ readonly onChange?: (nextNewContent: string) => void;
65
+ readonly selectedFile?: string;
66
+ readonly onSelectFile?: (path: string) => void;
67
+ readonly annotations?: readonly DiffAnnotation[];
68
+ readonly onLineComment?: (file: string, line: number, content: string) => void;
69
+ readonly onAddToChat?: (snippet: CodeSelectionSnippet) => void;
70
+ readonly empty?: ReactNode;
71
+ readonly className?: string;
72
+ }
73
+ export interface AgentUiSurfaces {
74
+ readonly code?: ComponentType<CodeSurfaceProps>;
75
+ readonly diff?: ComponentType<DiffSurfaceProps>;
76
+ readonly fileTree?: ComponentType<FileTreeProps>;
77
+ }
78
+ export interface AgentUiProviderProps {
79
+ readonly surfaces?: AgentUiSurfaces;
80
+ readonly children: ReactNode;
81
+ }
82
+ /** Register optional custom code/diff/file-tree renderers (such as `createPierreSurfaces()`) for the workbench. */
83
+ export declare function AgentUiProvider({ surfaces, children }: AgentUiProviderProps): import("react").JSX.Element;
84
+ /** Read the currently registered code/diff/file-tree surface renderers. */
85
+ export declare function useAgentUiSurfaces(): AgentUiSurfaces;
86
+ export declare function DefaultCodeSurface({ path, content, language, editable, onChange, markers, annotations, onAddToChat, className, }: CodeSurfaceProps): import("react").JSX.Element;
87
+ export declare function DefaultDiffSurface({ patch, files, oldFile, newFile, selectedFile, onSelectFile, onLineComment, empty, className, }: DiffSurfaceProps): import("react").JSX.Element;
88
+ /** Code viewer/editor surface: delegates to registered `surfaces.code` (e.g. Pierre) or uses the built-in fallback. */
89
+ export declare function CodeSurface(props: CodeSurfaceProps): import("react").JSX.Element;
90
+ /** Diff viewer/editor surface: delegates to registered `surfaces.diff` (e.g. Pierre) or uses `<DiffView>`. */
91
+ export declare function DiffSurface(props: DiffSurfaceProps): import("react").JSX.Element;
92
+ /** Path-first file explorer: delegates to registered `surfaces.fileTree` (e.g. `@pierre/trees`) or uses `<DefaultFileTree>`. */
93
+ export declare function FileTree(props: FileTreeProps): import("react").JSX.Element;
@@ -0,0 +1,127 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Pluggable Code, Diff, and FileTree surface primitives + `<AgentUiProvider>`:
4
+ * - Zero-dep fallbacks work immediately out of the box.
5
+ * - Registering `@mistriwork/agent-ui/pierre` (or CodeMirror/Monaco) via
6
+ * `<AgentUiProvider surfaces={...}>` transparently upgrades every surface
7
+ * in the workbench.
8
+ */
9
+ import { createContext, useContext, useMemo, useState } from 'react';
10
+ import { Badge, Button, TextArea } from '@mistriwork/mistri/ui';
11
+ import { DiffView } from './agentIde.js';
12
+ import { DefaultFileTree } from './fileTree.js';
13
+ import './workbench.css';
14
+ const AgentUiSurfacesContext = createContext({});
15
+ /** Register optional custom code/diff/file-tree renderers (such as `createPierreSurfaces()`) for the workbench. */
16
+ export function AgentUiProvider({ surfaces, children }) {
17
+ const parent = useContext(AgentUiSurfacesContext);
18
+ const merged = useMemo(() => ({ ...parent, ...surfaces }), [parent, surfaces]);
19
+ return _jsx(AgentUiSurfacesContext.Provider, { value: merged, children: children });
20
+ }
21
+ /** Read the currently registered code/diff/file-tree surface renderers. */
22
+ export function useAgentUiSurfaces() {
23
+ return useContext(AgentUiSurfacesContext);
24
+ }
25
+ /* ============================================================================
26
+ * 2. Built-in Zero-Dep Fallbacks & Delegating Primitives
27
+ * ========================================================================== */
28
+ export function DefaultCodeSurface({ path, content, language, editable = false, onChange, markers = [], annotations = [], onAddToChat, className, }) {
29
+ const [selectedRange, setSelectedRange] = useState(null);
30
+ const lines = useMemo(() => content.split('\n'), [content]);
31
+ const markersByLine = useMemo(() => {
32
+ const map = new Map();
33
+ for (const marker of markers) {
34
+ const list = map.get(marker.line) ?? [];
35
+ list.push(marker);
36
+ map.set(marker.line, list);
37
+ }
38
+ return map;
39
+ }, [markers]);
40
+ const annotationsByLine = useMemo(() => {
41
+ const map = new Map();
42
+ for (const annotation of annotations) {
43
+ const list = map.get(annotation.line) ?? [];
44
+ list.push(annotation);
45
+ map.set(annotation.line, list);
46
+ }
47
+ return map;
48
+ }, [annotations]);
49
+ const handleLineClick = (lineNo, shiftKey) => {
50
+ if (shiftKey && selectedRange) {
51
+ setSelectedRange({ start: Math.min(selectedRange.start, lineNo), end: Math.max(selectedRange.end, lineNo) });
52
+ }
53
+ else {
54
+ setSelectedRange({ start: lineNo, end: lineNo });
55
+ }
56
+ };
57
+ const triggerAddToChat = () => {
58
+ if (!onAddToChat || !selectedRange)
59
+ return;
60
+ const text = lines.slice(selectedRange.start - 1, selectedRange.end).join('\n');
61
+ onAddToChat({ path, startLine: selectedRange.start, endLine: selectedRange.end, text });
62
+ };
63
+ return (_jsxs("section", { className: className ? `aui-code-surface ${className}` : 'aui-code-surface', "aria-label": path, children: [_jsxs("header", { className: "aui-code-head", children: [_jsx("span", { children: path }), _jsxs("div", { style: { display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)' }, children: [language ? _jsx(Badge, { tone: "neutral", children: language }) : null, editable ? _jsx(Badge, { tone: "info", children: "Editable" }) : null, onAddToChat && selectedRange ? (_jsx(Button, { size: "sm", variant: "secondary", onClick: triggerAddToChat, children: selectedRange.start === selectedRange.end
64
+ ? `Add L${selectedRange.start} to chat`
65
+ : `Add L${selectedRange.start}–${selectedRange.end} to chat` })) : null] })] }), editable ? (_jsx("div", { className: "aui-code-edit-wrap", children: _jsx(TextArea, { label: `Edit ${path}`, labelHidden: true, reserve: false, monospace: true, rows: Math.max(8, Math.min(30, lines.length + 1)), value: content, onValueChange: (next) => onChange?.(next) }) })) : (_jsx("div", { style: { overflowX: 'auto' }, children: _jsx("table", { className: "aui-code-table", children: _jsx("tbody", { children: lines.map((line, idx) => {
66
+ const lineNo = idx + 1;
67
+ const lineMarkers = markersByLine.get(lineNo);
68
+ const lineAnnotations = annotationsByLine.get(lineNo);
69
+ const severity = lineMarkers?.some((m) => m.severity === 'error')
70
+ ? 'error'
71
+ : lineMarkers?.some((m) => m.severity === 'warning')
72
+ ? 'warning'
73
+ : undefined;
74
+ const isSelected = Boolean(selectedRange && lineNo >= selectedRange.start && lineNo <= selectedRange.end);
75
+ return (_jsxs("tr", { className: "aui-code-row", "data-selected": isSelected ? 'true' : undefined, "data-severity": severity, children: [_jsx("td", { className: "aui-code-ln", onClick: (e) => handleLineClick(lineNo, e.shiftKey), children: lineNo }), _jsxs("td", { className: "aui-code-text", children: [line, lineMarkers?.map((m, mi) => (_jsx("div", { className: "aui-code-marker", children: `${m.severity.toUpperCase()}: ${m.message}` }, mi))), lineAnnotations?.map((a, ai) => (_jsx("div", { className: "aui-code-marker", children: a.body }, a.id ?? ai)))] })] }, lineNo));
76
+ }) }) }) }))] }));
77
+ }
78
+ function buildFallbackPatchFromPair(oldFile, newFile) {
79
+ const oldLines = oldFile.contents === '' ? [] : oldFile.contents.split('\n');
80
+ const newLines = newFile.contents === '' ? [] : newFile.contents.split('\n');
81
+ const out = [
82
+ `diff --git a/${oldFile.name} b/${newFile.name}`,
83
+ `--- a/${oldFile.name}`,
84
+ `+++ b/${newFile.name}`,
85
+ `@@ -1,${oldLines.length} +1,${newLines.length} @@`,
86
+ ];
87
+ const max = Math.max(oldLines.length, newLines.length);
88
+ for (let i = 0; i < max; i += 1) {
89
+ const o = oldLines[i];
90
+ const n = newLines[i];
91
+ if (o === n && o !== undefined) {
92
+ out.push(` ${o}`);
93
+ }
94
+ else {
95
+ if (o !== undefined)
96
+ out.push(`-${o}`);
97
+ if (n !== undefined)
98
+ out.push(`+${n}`);
99
+ }
100
+ }
101
+ return out.join('\n');
102
+ }
103
+ export function DefaultDiffSurface({ patch, files, oldFile, newFile, selectedFile, onSelectFile, onLineComment, empty, className, }) {
104
+ const resolvedPatch = useMemo(() => {
105
+ if (patch)
106
+ return patch;
107
+ if (oldFile && newFile)
108
+ return buildFallbackPatchFromPair(oldFile, newFile);
109
+ return undefined;
110
+ }, [patch, oldFile, newFile]);
111
+ return (_jsx(DiffView, { diff: resolvedPatch, files: files, selectedFile: selectedFile, onSelectFile: onSelectFile, onLineComment: onLineComment, empty: empty, className: className }));
112
+ }
113
+ /** Code viewer/editor surface: delegates to registered `surfaces.code` (e.g. Pierre) or uses the built-in fallback. */
114
+ export function CodeSurface(props) {
115
+ const { code: CustomCode } = useAgentUiSurfaces();
116
+ return CustomCode ? _jsx(CustomCode, { ...props }) : _jsx(DefaultCodeSurface, { ...props });
117
+ }
118
+ /** Diff viewer/editor surface: delegates to registered `surfaces.diff` (e.g. Pierre) or uses `<DiffView>`. */
119
+ export function DiffSurface(props) {
120
+ const { diff: CustomDiff } = useAgentUiSurfaces();
121
+ return CustomDiff ? _jsx(CustomDiff, { ...props }) : _jsx(DefaultDiffSurface, { ...props });
122
+ }
123
+ /** Path-first file explorer: delegates to registered `surfaces.fileTree` (e.g. `@pierre/trees`) or uses `<DefaultFileTree>`. */
124
+ export function FileTree(props) {
125
+ const { fileTree: CustomTree } = useAgentUiSurfaces();
126
+ return CustomTree ? _jsx(CustomTree, { ...props }) : _jsx(DefaultFileTree, { ...props });
127
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Agent inspection, terminal, and control primitives for `@mistriwork/agent-ui`:
3
+ * - `<ToolCallInspector>`: filterable tool call execution inspector
4
+ * - `<TerminalOutput>` + `parseAnsiLine`: safe ANSI SGR streaming console
5
+ * - `<ModeSwitcher>`: compact agent mode selector (`Ask` / `Plan` / `Agent` / `Review`)
6
+ * - `<ModelPicker>`: compact model / ACP provider selector
7
+ */
8
+ import { type ReactNode } from 'react';
9
+ import type { ToolCallRecord } from './streamBridge.js';
10
+ import './workbench.css';
11
+ export type ToolCallFilter = 'all' | 'running' | 'completed' | 'failed';
12
+ export interface ToolCallInspectorProps {
13
+ readonly calls: readonly ToolCallRecord[];
14
+ readonly selectedId?: string;
15
+ readonly onSelect?: (id: string) => void;
16
+ readonly title?: string;
17
+ readonly empty?: ReactNode;
18
+ readonly className?: string;
19
+ }
20
+ export declare function ToolCallInspector({ calls, selectedId, onSelect, title, empty, className }: ToolCallInspectorProps): import("react").JSX.Element;
21
+ export interface AnsiSegment {
22
+ readonly text: string;
23
+ readonly className?: string;
24
+ }
25
+ /** Parse ANSI SGR escape sequences into safe styled text segments (no raw HTML injection). */
26
+ export declare function parseAnsiLine(line: string): AnsiSegment[];
27
+ export interface TerminalOutputProps {
28
+ /** Raw text output (newlines split automatically). */
29
+ readonly text?: string;
30
+ /** Structured output lines (alternative to `text`). */
31
+ readonly lines?: readonly string[];
32
+ readonly title?: string;
33
+ readonly running?: boolean;
34
+ readonly searchable?: boolean;
35
+ readonly autoFollow?: boolean;
36
+ readonly defaultWrap?: boolean;
37
+ readonly onClear?: () => void;
38
+ readonly className?: string;
39
+ }
40
+ export declare function TerminalOutput({ text, lines, title, running, searchable, autoFollow, defaultWrap, onClear, className, }: TerminalOutputProps): import("react").JSX.Element;
41
+ export interface AgentModeOption<T extends string = string> {
42
+ readonly value: T;
43
+ readonly label: string;
44
+ readonly disabled?: boolean;
45
+ }
46
+ export interface ModeSwitcherProps<T extends string = string> {
47
+ readonly value: T;
48
+ readonly onValueChange: (value: T) => void;
49
+ readonly options?: readonly AgentModeOption<T>[];
50
+ readonly ariaLabel?: string;
51
+ readonly disabled?: boolean;
52
+ readonly className?: string;
53
+ }
54
+ export declare function ModeSwitcher<T extends string = string>({ value, onValueChange, options, ariaLabel, disabled, className, }: ModeSwitcherProps<T>): import("react").JSX.Element;
55
+ export interface ModelOption<T extends string = string> {
56
+ readonly id: T;
57
+ readonly label: string;
58
+ readonly provider?: string;
59
+ readonly tier?: string;
60
+ readonly disabled?: boolean;
61
+ }
62
+ export interface ModelPickerProps<T extends string = string> {
63
+ readonly value: T;
64
+ readonly onValueChange: (value: T) => void;
65
+ readonly models: readonly ModelOption<T>[];
66
+ readonly ariaLabel?: string;
67
+ readonly placeholder?: string;
68
+ readonly disabled?: boolean;
69
+ readonly className?: string;
70
+ }
71
+ export declare function ModelPicker<T extends string = string>({ value, onValueChange, models, ariaLabel, placeholder, disabled, className, }: ModelPickerProps<T>): import("react").JSX.Element;