@odysx/codemind 0.0.0-stage → 0.1.1

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.
Files changed (108) hide show
  1. package/README.md +293 -2
  2. package/dist/commands/agents.d.ts +2 -0
  3. package/dist/commands/agents.js +91 -0
  4. package/dist/commands/auth.d.ts +2 -0
  5. package/dist/commands/auth.js +35 -0
  6. package/dist/commands/chat.d.ts +2 -0
  7. package/dist/commands/chat.js +180 -0
  8. package/dist/commands/keys.d.ts +2 -0
  9. package/dist/commands/keys.js +81 -0
  10. package/dist/commands/local.d.ts +2 -0
  11. package/dist/commands/local.js +325 -0
  12. package/dist/commands/mcp.d.ts +2 -0
  13. package/dist/commands/mcp.js +73 -0
  14. package/dist/commands/prompts.d.ts +2 -0
  15. package/dist/commands/prompts.js +59 -0
  16. package/dist/commands/skills.d.ts +2 -0
  17. package/dist/commands/skills.js +41 -0
  18. package/dist/core/auth/index.d.ts +10 -0
  19. package/dist/core/auth/index.js +82 -0
  20. package/dist/core/config/index.d.ts +47 -0
  21. package/dist/core/config/index.js +118 -0
  22. package/dist/core/history.d.ts +14 -0
  23. package/dist/core/history.js +80 -0
  24. package/dist/core/markdown-renderer.d.ts +47 -0
  25. package/dist/core/markdown-renderer.js +385 -0
  26. package/dist/core/permissions/index.d.ts +31 -0
  27. package/dist/core/permissions/index.js +64 -0
  28. package/dist/core/provider/external.d.ts +28 -0
  29. package/dist/core/provider/external.js +248 -0
  30. package/dist/core/provider/index.d.ts +138 -0
  31. package/dist/core/provider/index.js +510 -0
  32. package/dist/core/registry/index.d.ts +25 -0
  33. package/dist/core/registry/index.js +216 -0
  34. package/dist/core/schema/types.d.ts +93 -0
  35. package/dist/core/schema/types.js +12 -0
  36. package/dist/core/terminal.d.ts +40 -0
  37. package/dist/core/terminal.js +134 -0
  38. package/dist/core/workspace/index.d.ts +35 -0
  39. package/dist/core/workspace/index.js +194 -0
  40. package/dist/index.d.ts +10 -0
  41. package/dist/index.js +393 -0
  42. package/dist/ui/app.d.ts +3 -0
  43. package/dist/ui/app.js +554 -0
  44. package/dist/ui/commands/cases/catalog.d.ts +11 -0
  45. package/dist/ui/commands/cases/catalog.js +62 -0
  46. package/dist/ui/commands/cases/misc.d.ts +35 -0
  47. package/dist/ui/commands/cases/misc.js +245 -0
  48. package/dist/ui/commands/cases/tasks.d.ts +13 -0
  49. package/dist/ui/commands/cases/tasks.js +91 -0
  50. package/dist/ui/commands/runCommand.d.ts +22 -0
  51. package/dist/ui/commands/runCommand.js +136 -0
  52. package/dist/ui/components/AgentPicker.d.ts +11 -0
  53. package/dist/ui/components/AgentPicker.js +7 -0
  54. package/dist/ui/components/AuthPicker.d.ts +14 -0
  55. package/dist/ui/components/AuthPicker.js +7 -0
  56. package/dist/ui/components/Banner.d.ts +8 -0
  57. package/dist/ui/components/Banner.js +24 -0
  58. package/dist/ui/components/CommandMenu.d.ts +17 -0
  59. package/dist/ui/components/CommandMenu.js +21 -0
  60. package/dist/ui/components/ErrorBoundary.d.ts +24 -0
  61. package/dist/ui/components/ErrorBoundary.js +51 -0
  62. package/dist/ui/components/InputBar.d.ts +28 -0
  63. package/dist/ui/components/InputBar.js +108 -0
  64. package/dist/ui/components/KeysPanel.d.ts +12 -0
  65. package/dist/ui/components/KeysPanel.js +25 -0
  66. package/dist/ui/components/MessageView.d.ts +29 -0
  67. package/dist/ui/components/MessageView.js +107 -0
  68. package/dist/ui/components/PermissionPrompt.d.ts +10 -0
  69. package/dist/ui/components/PermissionPrompt.js +4 -0
  70. package/dist/ui/components/Pickers.d.ts +43 -0
  71. package/dist/ui/components/Pickers.js +33 -0
  72. package/dist/ui/components/SearchOverlay.d.ts +21 -0
  73. package/dist/ui/components/SearchOverlay.js +14 -0
  74. package/dist/ui/components/SessionPicker.d.ts +12 -0
  75. package/dist/ui/components/SessionPicker.js +8 -0
  76. package/dist/ui/components/WorkingIndicator.d.ts +10 -0
  77. package/dist/ui/components/WorkingIndicator.js +23 -0
  78. package/dist/ui/controls/ApiKeyEntry.d.ts +8 -0
  79. package/dist/ui/controls/ApiKeyEntry.js +5 -0
  80. package/dist/ui/controls/MultiSelect.d.ts +18 -0
  81. package/dist/ui/controls/MultiSelect.js +9 -0
  82. package/dist/ui/hooks/useAgentPicker.d.ts +14 -0
  83. package/dist/ui/hooks/useAgentPicker.js +53 -0
  84. package/dist/ui/hooks/useAuthFlow.d.ts +14 -0
  85. package/dist/ui/hooks/useAuthFlow.js +31 -0
  86. package/dist/ui/hooks/useKeysFlow.d.ts +17 -0
  87. package/dist/ui/hooks/useKeysFlow.js +130 -0
  88. package/dist/ui/hooks/useSessionPicker.d.ts +29 -0
  89. package/dist/ui/hooks/useSessionPicker.js +58 -0
  90. package/dist/ui/hooks/useTerminalSize.d.ts +6 -0
  91. package/dist/ui/hooks/useTerminalSize.js +29 -0
  92. package/dist/ui/input/keyRouter.d.ts +125 -0
  93. package/dist/ui/input/keyRouter.js +574 -0
  94. package/dist/ui/layouts/ScreenLayout.d.ts +98 -0
  95. package/dist/ui/layouts/ScreenLayout.js +56 -0
  96. package/dist/ui/shared/types.d.ts +143 -0
  97. package/dist/ui/shared/types.js +38 -0
  98. package/dist/ui/theme.d.ts +29 -0
  99. package/dist/ui/theme.js +54 -0
  100. package/dist/ui/utils/markdown.d.ts +74 -0
  101. package/dist/ui/utils/markdown.js +187 -0
  102. package/dist/ui/utils/mentions.d.ts +12 -0
  103. package/dist/ui/utils/mentions.js +28 -0
  104. package/dist/ui/utils/terminal-text.d.ts +33 -0
  105. package/dist/ui/utils/terminal-text.js +123 -0
  106. package/dist/ui/utils/text.d.ts +72 -0
  107. package/dist/ui/utils/text.js +171 -0
  108. package/package.json +50 -6
@@ -0,0 +1,56 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Static } from "ink";
3
+ import { Banner } from "../components/Banner.js";
4
+ import { MessageView, StreamingMessage } from "../components/MessageView.js";
5
+ import { WorkingIndicator } from "../components/WorkingIndicator.js";
6
+ import { CommandMenu } from "../components/CommandMenu.js";
7
+ import { InputBar } from "../components/InputBar.js";
8
+ import { SearchOverlay } from "../components/SearchOverlay.js";
9
+ import { AgentPicker, AuthPicker, SessionPicker, PermissionPrompt, TrustPrompt } from "../components/Pickers.js";
10
+ import { KeysPanel } from "../components/KeysPanel.js";
11
+ import { MultiSelect } from "../controls/MultiSelect.js";
12
+ import { ApiKeyEntry } from "../controls/ApiKeyEntry.js";
13
+ import { AUTH_OPTIONS, KEY_SCOPES } from "../shared/types.js";
14
+ /**
15
+ * The last message is live only while it is an assistant reply at the tail.
16
+ *
17
+ * <Static> writes each item once and tracks a high-water-mark index
18
+ * (`items.slice(index)`), so `settled` MUST be a growing prefix. Pulling an
19
+ * assistant message out of the middle — the old behavior — re-indexed the
20
+ * array when the next user prompt arrived: the completed reply was either
21
+ * emitted below the newer prompt or skipped past the cursor and vanished.
22
+ * Keeping the live item strictly at the tail makes every append a prefix
23
+ * extension, so a reply is committed exactly when the next message lands.
24
+ */
25
+ export const splitTranscript = (messages) => {
26
+ const last = messages[messages.length - 1];
27
+ if (last && last.role === "assistant") {
28
+ return { settled: messages.slice(0, -1), live: last };
29
+ }
30
+ // System notices (errors, interrupts, approvals) settle immediately, and
31
+ // they also settle the reply they follow.
32
+ return { settled: messages, live: null };
33
+ };
34
+ export const ScreenLayout = (p) => {
35
+ const { settled, live } = splitTranscript(p.messages);
36
+ // Keep the last `limit` settled messages visible; <Static> still receives
37
+ // every item exactly once, so nothing is lost from scrollback.
38
+ const menuLimit = Math.max(4, Math.min(10, (p.rows ?? 24) - 8));
39
+ // The window scrolls with the selection. Clamping the *index* instead (the
40
+ // old behavior) parked the pointer on the last visible row while Enter ran
41
+ // a different command from the full list.
42
+ const menuStart = Math.max(0, Math.min(p.clampedMenuIndex - Math.floor(menuLimit / 2), Math.max(0, p.filteredCommands.length - menuLimit)));
43
+ const visibleCommands = p.filteredCommands.slice(menuStart, menuStart + menuLimit);
44
+ const overlayOpen = p.trust.pending ||
45
+ Boolean(p.search.mode) ||
46
+ p.authMode !== "closed" ||
47
+ p.keys.mode !== "closed" ||
48
+ p.agentPick.open ||
49
+ p.sessionPick.open ||
50
+ Boolean(p.pendingOp);
51
+ if (p.trust.pending) {
52
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Banner, {}), _jsx(TrustPrompt, { folder: p.trust.folder, selected: p.trust.index, mode: p.permissionMode })] }));
53
+ }
54
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: settled, children: (msg, i) => _jsx(MessageView, { msg: msg }, i) }), settled.length === 0 && _jsx(Banner, {}), live && (p.streaming ? _jsx(StreamingMessage, { msg: live }) : _jsx(MessageView, { msg: live })), p.streaming && _jsx(WorkingIndicator, { elapsed: p.elapsed, agent: p.agentName }), p.search.mode && (_jsx(SearchOverlay, { title: p.search.mode === "commands" ? "Commands" : "Prompt history", query: p.search.query, rows: p.search.mode === "commands" ? p.commandRows : p.historyRows, selected: p.search.index, hint: "\u2191/\u2193 move \u00B7 Enter use \u00B7 esc close" })), p.agentPick.open && (_jsx(AgentPicker, { options: p.agentPick.options, selected: p.agentPick.index, busy: p.agentPick.busy })), p.authMode === "picker" && (_jsx(AuthPicker, { options: AUTH_OPTIONS, selected: p.authIndex, busy: p.authBusy })), p.sessionPick.open && (_jsx(SessionPicker, { rows: p.sessionPick.rows, selected: p.sessionPick.index, busy: p.sessionPick.busy })), p.pendingOp && _jsx(PermissionPrompt, { op: p.pendingOp }), p.authMode === "api-key" && _jsx(ApiKeyEntry, { draft: p.apiKeyDraft }), p.keys.mode === "create-scopes" ? (_jsx(MultiSelect, { title: "Create API key \u2014 scopes", options: [...KEY_SCOPES], selectedIds: p.keys.scopeSelection, cursorIndex: p.keys.scopeCursor, busy: p.keys.busy })) : (p.keys.mode !== "closed" && _jsx(KeysPanel, { state: p.keys })), p.menuOpen && visibleCommands.length > 0 && (_jsx(CommandMenu, { commands: visibleCommands, selected: p.clampedMenuIndex - menuStart, total: p.filteredCommands.length, above: menuStart })), !overlayOpen && (_jsx(InputBar, { value: p.input, cursor: p.cursor, agent: p.agentName, model: p.model, authed: p.authed, provider: p.provider, turns: p.messages.length, cwd: p.cwd, mode: p.permissionMode }))] }));
55
+ };
56
+ //# sourceMappingURL=ScreenLayout.js.map
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Shared types for the REPL UI components.
3
+ */
4
+ import type { Dispatch, MutableRefObject, SetStateAction } from "react";
5
+ export interface SlashCommand {
6
+ name: string;
7
+ args?: string;
8
+ description: string;
9
+ }
10
+ /** A selectable row in the /agent switcher. */
11
+ export interface AgentOption {
12
+ id: string;
13
+ label: string;
14
+ description: string;
15
+ }
16
+ /** A selectable row in the /sessions switcher. */
17
+ export interface SessionRow {
18
+ session_id: string;
19
+ title?: string;
20
+ agent_name?: string;
21
+ agent_id?: string;
22
+ model?: string;
23
+ updated_at?: string;
24
+ }
25
+ /** Risky local op awaiting y/N approval in the permission prompt. */
26
+ export interface PendingOp {
27
+ /** Must stay in sync with `GATED` in commands/local.ts. */
28
+ kind: "write" | "exec" | "delete" | "move";
29
+ summary: string;
30
+ cliArgs: string[];
31
+ /** For writes: unified-ish before/after snippet shown in the prompt. */
32
+ diff?: {
33
+ file: string;
34
+ before: string;
35
+ after: string;
36
+ };
37
+ /** Callback-based approval for operations that cannot be re-dispatched as a
38
+ * `local --yes` command (e.g. /export). One of these resolves the caller's
39
+ * promise; omit both for the normal CLI-command approval path. */
40
+ onApproved?: () => void;
41
+ onDenied?: () => void;
42
+ }
43
+ export type KeysMode = "closed" | "menu" | "create-name" | "create-scopes" | "confirm-revoke" | "created";
44
+ /** Scopes a user API key can carry (must match backend ApiKeyGate). */
45
+ export declare const KEY_SCOPES: readonly [{
46
+ readonly id: "chat";
47
+ readonly label: "chat";
48
+ readonly description: "Send chat messages (/llm/chat)";
49
+ }, {
50
+ readonly id: "agents:read";
51
+ readonly label: "agents:read";
52
+ readonly description: "List agents, skills, prompt templates";
53
+ }, {
54
+ readonly id: "keys";
55
+ readonly label: "keys";
56
+ readonly description: "Manage API keys";
57
+ }];
58
+ export interface ApiKeyRow {
59
+ id: string;
60
+ name: string;
61
+ key_prefix: string;
62
+ is_active: boolean;
63
+ scopes?: string[];
64
+ rate_limit_rpm?: number;
65
+ daily_token_limit?: number;
66
+ last_used_at?: string | null;
67
+ created_at?: string;
68
+ }
69
+ export interface KeysState {
70
+ mode: KeysMode;
71
+ busy: boolean;
72
+ rows: ApiKeyRow[];
73
+ selectedIndex: number;
74
+ draftName: string;
75
+ /** Scopes multi-select state (create-scopes mode). */
76
+ scopeCursor: number;
77
+ scopeSelection: Set<string>;
78
+ createdKey: {
79
+ key: string;
80
+ name: string;
81
+ } | null;
82
+ /** Persisted local label (key prefix) of the selected active key. */
83
+ activeKeyLabel: string | null;
84
+ }
85
+ export type Role = "user" | "assistant" | "system";
86
+ export interface ChatMessage {
87
+ role: Role;
88
+ text: string;
89
+ agentName?: string;
90
+ }
91
+ /** Per-session token accounting, filled from stream/chat responses. */
92
+ export interface UsageAccumulator {
93
+ requests: number;
94
+ promptTokens: number;
95
+ completionTokens: number;
96
+ }
97
+ /** Everything a slash-command handler may touch from the REPL shell. */
98
+ export interface CommandCtx {
99
+ addMessage: (text: string) => void;
100
+ setMessages: Dispatch<SetStateAction<ChatMessage[]>>;
101
+ /** Session id getter (lives in a ref in app.tsx, not a module mutable). */
102
+ sessionId: () => string;
103
+ agentId: string;
104
+ config: {
105
+ apiKey?: string;
106
+ token?: string;
107
+ apiUrl: string;
108
+ };
109
+ openAgentPicker: () => void;
110
+ setAgentId: (id: string) => void;
111
+ resumeSession: (sid: string) => void;
112
+ openSessionPicker: () => void;
113
+ openKeysPanel: () => Promise<void>;
114
+ setPendingOp: (op: PendingOp | null) => void;
115
+ /** Wipe the transcript and remount the static region (/clear, /compact). */
116
+ resetTranscript: () => void;
117
+ /** Start a fresh server-side session (/new); clears the local transcript too. */
118
+ newSession: () => void;
119
+ usageRef: MutableRefObject<UsageAccumulator>;
120
+ /** Aborts an in-flight stream (used by /clear so tokens stop appending). */
121
+ abortStream: () => void;
122
+ requestExit: () => void;
123
+ /** Auth picker setters, so /signin can open the sign-in menu from runCommand. */
124
+ setAuthMode: (mode: "closed" | "picker" | "api-key") => void;
125
+ setAuthIndex: (index: number) => void;
126
+ }
127
+ /** Slash-command list shown in /help and the suggestion menu. */
128
+ export declare const SLASH_COMMANDS: SlashCommand[];
129
+ /** Sign-in menu choices. */
130
+ export declare const AUTH_OPTIONS: readonly [{
131
+ readonly id: "api-key";
132
+ readonly label: "Use an API key";
133
+ readonly description: "Paste an existing OdysX API key";
134
+ }, {
135
+ readonly id: "keys";
136
+ readonly label: "Manage API keys";
137
+ readonly description: "Create, list, or revoke keys";
138
+ }, {
139
+ readonly id: "account";
140
+ readonly label: "Sign in with account";
141
+ readonly description: "Username & password (coming soon)";
142
+ }];
143
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,38 @@
1
+ /** Scopes a user API key can carry (must match backend ApiKeyGate). */
2
+ export const KEY_SCOPES = [
3
+ { id: "chat", label: "chat", description: "Send chat messages (/llm/chat)" },
4
+ { id: "agents:read", label: "agents:read", description: "List agents, skills, prompt templates" },
5
+ { id: "keys", label: "keys", description: "Manage API keys" },
6
+ ];
7
+ /** Slash-command list shown in /help and the suggestion menu. */
8
+ export const SLASH_COMMANDS = [
9
+ { name: "help", description: "Show help" },
10
+ { name: "clear", description: "Clear screen (server conversation is kept)" },
11
+ { name: "new", description: "Start a fresh session (new server conversation)" },
12
+ { name: "status", description: "Session info (auth, agent, model)" },
13
+ { name: "signin", description: "Authenticate — API key or account sign-in" },
14
+ { name: "keys", description: "Manage API keys (list / new / revoke / usage)" },
15
+ { name: "agent", args: "<id>", description: "Switch agent" },
16
+ { name: "model", args: "<id>", description: "Switch model" },
17
+ { name: "provider", args: "[name]", description: "List external providers / switch (odysx = platform)" },
18
+ { name: "sessions", args: "[id]", description: "List and resume past sessions" },
19
+ { name: "tasks", args: "[id|retry <id>|cancel <id>|follow <id>]", description: "Background agent tasks — list, inspect, retry, cancel" },
20
+ { name: "ralph", args: "<objective>", description: "Autonomous improve-until-done run (opt-in)" },
21
+ { name: "mcp", description: "List registered MCP servers" },
22
+ { name: "prompts", description: "List prompt templates (/prompts <slug> to view)" },
23
+ { name: "skills", description: "List installed skills" },
24
+ { name: "usage", description: "Token usage summary this session" },
25
+ { name: "local", args: "<read|write|exec|ls|pwd|delete>", description: "Workspace file/shell ops (gated)" },
26
+ { name: "mode", args: "[auto|plan|manual|guide]", description: "Permission mode — read-only, guide, ask, or auto" },
27
+ { name: "trust", args: "[forget <path>]", description: "Trusted folders — list them, or forget one" },
28
+ { name: "compact", description: "Clear conversation context" },
29
+ { name: "export", description: "Export session transcript to JSON" },
30
+ { name: "quit", description: "Exit OdysX" },
31
+ ];
32
+ /** Sign-in menu choices. */
33
+ export const AUTH_OPTIONS = [
34
+ { id: "api-key", label: "Use an API key", description: "Paste an existing OdysX API key" },
35
+ { id: "keys", label: "Manage API keys", description: "Create, list, or revoke keys" },
36
+ { id: "account", label: "Sign in with account", description: "Username & password (coming soon)" },
37
+ ];
38
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,29 @@
1
+ export declare const theme: {
2
+ readonly color: {
3
+ readonly brand: string | undefined;
4
+ readonly accent: string | undefined;
5
+ readonly user: string | undefined;
6
+ readonly success: string | undefined;
7
+ readonly warning: string | undefined;
8
+ readonly error: string | undefined;
9
+ readonly muted: string | undefined;
10
+ readonly info: string | undefined;
11
+ readonly code: string | undefined;
12
+ readonly link: string | undefined;
13
+ };
14
+ readonly glyph: {
15
+ readonly pointer: "❯";
16
+ readonly bullet: "•";
17
+ readonly check: "✓";
18
+ readonly cross: "✗";
19
+ readonly warn: "⚠";
20
+ readonly info: "·";
21
+ readonly bar: "│";
22
+ readonly rule: "─";
23
+ readonly arrowUp: "↑";
24
+ readonly arrowDown: "↓";
25
+ };
26
+ };
27
+ /** Severity → color, used by system lines so errors look like errors. */
28
+ export declare const systemColor: (text: string) => string | undefined;
29
+ //# sourceMappingURL=theme.d.ts.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Theme — the single source of color and glyph choices for the Ink UI.
3
+ *
4
+ * Components must not hardcode ANSI names or box-drawing characters: keeping
5
+ * them here means a palette change is one edit, and the transcript, overlays,
6
+ * and footer stay visually coherent.
7
+ *
8
+ * When colour is off (`--no-color`, NO_COLOR, piped stdout, TERM=dumb) every
9
+ * entry becomes `undefined`. Ink treats a missing colour as "no escape", so
10
+ * the UI goes monochrome *without* losing bold/dim/inverse. That matters:
11
+ * Ink routes those attributes through the same chalk instance, so turning
12
+ * chalk off wholesale would also erase the input caret (`inverse`) and every
13
+ * selection marker. Colour and text attributes are separate decisions.
14
+ */
15
+ import { colorEnabled } from "../core/terminal.js";
16
+ /** A named colour, or undefined when colour is disabled. */
17
+ const c = (name) => (colorEnabled() ? name : undefined);
18
+ export const theme = {
19
+ color: {
20
+ brand: c("cyan"),
21
+ accent: c("magenta"),
22
+ user: c("blue"),
23
+ success: c("green"),
24
+ warning: c("yellow"),
25
+ error: c("red"),
26
+ muted: c("gray"),
27
+ info: c("cyan"),
28
+ code: c("yellow"),
29
+ link: c("blue"),
30
+ },
31
+ glyph: {
32
+ pointer: "❯",
33
+ bullet: "•",
34
+ check: "✓",
35
+ cross: "✗",
36
+ warn: "⚠",
37
+ info: "·",
38
+ bar: "│",
39
+ rule: "─",
40
+ arrowUp: "↑",
41
+ arrowDown: "↓",
42
+ },
43
+ };
44
+ /** Severity → color, used by system lines so errors look like errors. */
45
+ export const systemColor = (text) => {
46
+ if (text.startsWith("✗") || /^Error\b/i.test(text))
47
+ return theme.color.error;
48
+ if (text.startsWith("⚠"))
49
+ return theme.color.warning;
50
+ if (text.startsWith("✓"))
51
+ return theme.color.success;
52
+ return theme.color.muted;
53
+ };
54
+ //# sourceMappingURL=theme.js.map
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Line-oriented markdown → style model for the Ink transcript.
3
+ *
4
+ * Ink renders React nodes, not ANSI strings, so the previous approach (parse
5
+ * markdown to HTML, then regex the HTML back to text) threw away every style.
6
+ * This parser walks the raw markdown once and returns typed lines that
7
+ * MessageView maps to <Text> props. It is deliberately line-based: streaming
8
+ * replies arrive as an ever-growing string and we re-render on every token, so
9
+ * parsing must be cheap and allocation-light.
10
+ *
11
+ * Supported: ATX headings, fenced code (with a language label), ordered and
12
+ * unordered lists (nested by indent), blockquotes, rules, tables, and inline
13
+ * **bold**, *italic*, `code`, ~~strike~~, [links](url).
14
+ */
15
+ /** An inline run: text plus the styles that apply to it. */
16
+ export interface InlineRun {
17
+ text: string;
18
+ bold?: boolean;
19
+ italic?: boolean;
20
+ code?: boolean;
21
+ strike?: boolean;
22
+ underline?: boolean;
23
+ link?: string;
24
+ }
25
+ export type MdLine = {
26
+ kind: "blank";
27
+ } | {
28
+ kind: "heading";
29
+ level: number;
30
+ runs: InlineRun[];
31
+ } | {
32
+ kind: "text";
33
+ runs: InlineRun[];
34
+ } | {
35
+ kind: "bullet";
36
+ depth: number;
37
+ marker: string;
38
+ runs: InlineRun[];
39
+ } | {
40
+ kind: "quote";
41
+ runs: InlineRun[];
42
+ } | {
43
+ kind: "rule";
44
+ } | {
45
+ kind: "code";
46
+ lang: string;
47
+ lines: string[];
48
+ open: boolean;
49
+ } | {
50
+ kind: "table";
51
+ header: string[];
52
+ rows: string[][];
53
+ align: Array<"left" | "center" | "right">;
54
+ };
55
+ /**
56
+ * Split inline markdown into styled runs. Unmatched delimiters stay literal,
57
+ * so a half-streamed `**bold` simply renders as text until it completes.
58
+ */
59
+ export declare function parseInline(text: string): InlineRun[];
60
+ /** Fence state carried across lines when streaming a partially received reply. */
61
+ interface ParseState {
62
+ inCode: boolean;
63
+ lang: string;
64
+ codeLines: string[];
65
+ }
66
+ /** Parse a full markdown string during streaming (an unclosed fence stays open). */
67
+ export declare function parseMarkdown(markdown: string): MdLine[];
68
+ /** Internal: parse and expose residual fence state for incremental callers. */
69
+ export declare function parseWithState(markdown: string, initial: ParseState): {
70
+ lines: MdLine[];
71
+ state: ParseState;
72
+ };
73
+ export {};
74
+ //# sourceMappingURL=markdown.d.ts.map
@@ -0,0 +1,187 @@
1
+ import { sanitize } from "./terminal-text.js";
2
+ const FENCE = /^\s*(```|~~~)\s*([\w+-]*)\s*$/;
3
+ const HEADING = /^\s{0,3}(#{1,6})\s+(.*)$/;
4
+ const BULLET = /^(\s*)([-*+]|\d{1,3}[.)])\s+(.*)$/;
5
+ const QUOTE = /^\s{0,3}>\s?(.*)$/;
6
+ const RULE = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
7
+ // GFM allows a single dash per column (`|:-:|` is a centered column), so the
8
+ // minimum is one, not two.
9
+ const TABLE_DIVIDER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
10
+ /**
11
+ * Split inline markdown into styled runs. Unmatched delimiters stay literal,
12
+ * so a half-streamed `**bold` simply renders as text until it completes.
13
+ */
14
+ export function parseInline(text) {
15
+ const runs = [];
16
+ let buffer = "";
17
+ const flush = () => {
18
+ if (buffer) {
19
+ runs.push({ text: buffer });
20
+ buffer = "";
21
+ }
22
+ };
23
+ for (let i = 0; i < text.length; i++) {
24
+ const ch = text[i];
25
+ // `code` — highest precedence, no nested formatting inside.
26
+ if (ch === "`") {
27
+ const end = text.indexOf("`", i + 1);
28
+ if (end !== -1) {
29
+ flush();
30
+ runs.push({ text: text.slice(i + 1, end), code: true });
31
+ i = end;
32
+ continue;
33
+ }
34
+ }
35
+ // **bold** / __bold__
36
+ if ((ch === "*" || ch === "_") && text[i + 1] === ch) {
37
+ const marker = ch + ch;
38
+ const end = text.indexOf(marker, i + 2);
39
+ if (end !== -1 && end > i + 2) {
40
+ flush();
41
+ for (const inner of parseInline(text.slice(i + 2, end))) {
42
+ runs.push({ ...inner, bold: true });
43
+ }
44
+ i = end + 1;
45
+ continue;
46
+ }
47
+ }
48
+ // *italic* / _italic_ — a single marker, not part of a word for `_`.
49
+ if (ch === "*" || ch === "_") {
50
+ const prev = text[i - 1] ?? " ";
51
+ const next = text[i + 1] ?? " ";
52
+ const wordBoundary = ch === "*" || (!/\w/.test(prev) && !/\w/.test(next));
53
+ if (wordBoundary && next !== " ") {
54
+ const end = text.indexOf(ch, i + 1);
55
+ if (end !== -1 && end > i + 1) {
56
+ flush();
57
+ for (const inner of parseInline(text.slice(i + 1, end))) {
58
+ runs.push({ ...inner, italic: true });
59
+ }
60
+ i = end;
61
+ continue;
62
+ }
63
+ }
64
+ }
65
+ // ~~strike~~
66
+ if (ch === "~" && text[i + 1] === "~") {
67
+ const end = text.indexOf("~~", i + 2);
68
+ if (end !== -1 && end > i + 2) {
69
+ flush();
70
+ for (const inner of parseInline(text.slice(i + 2, end))) {
71
+ runs.push({ ...inner, strike: true });
72
+ }
73
+ i = end + 1;
74
+ continue;
75
+ }
76
+ }
77
+ // [label](url)
78
+ if (ch === "[") {
79
+ const close = text.indexOf("](", i + 1);
80
+ if (close !== -1) {
81
+ const urlEnd = text.indexOf(")", close + 2);
82
+ if (urlEnd !== -1) {
83
+ flush();
84
+ const label = text.slice(i + 1, close);
85
+ const url = text.slice(close + 2, urlEnd);
86
+ runs.push({ text: label || url, link: url, underline: true });
87
+ i = urlEnd;
88
+ continue;
89
+ }
90
+ }
91
+ }
92
+ buffer += ch;
93
+ }
94
+ flush();
95
+ return runs;
96
+ }
97
+ /** Parse a full markdown string during streaming (an unclosed fence stays open). */
98
+ export function parseMarkdown(markdown) {
99
+ // Strip control sequences before parsing: model output is untrusted, and a
100
+ // raw `\x1b[2J` reaching Ink's output would clear or corrupt the screen.
101
+ return parseWithState(sanitize(markdown), { inCode: false, lang: "", codeLines: [] }).lines;
102
+ }
103
+ /** Internal: parse and expose residual fence state for incremental callers. */
104
+ export function parseWithState(markdown, initial) {
105
+ const out = [];
106
+ const state = { ...initial, codeLines: [...initial.codeLines] };
107
+ const lines = markdown.split("\n");
108
+ for (let i = 0; i < lines.length; i++) {
109
+ const line = lines[i];
110
+ const fence = line.match(FENCE);
111
+ if (state.inCode) {
112
+ if (fence) {
113
+ out.push({ kind: "code", lang: state.lang, lines: state.codeLines, open: false });
114
+ state.inCode = false;
115
+ state.lang = "";
116
+ state.codeLines = [];
117
+ }
118
+ else {
119
+ state.codeLines.push(line);
120
+ }
121
+ continue;
122
+ }
123
+ if (fence) {
124
+ state.inCode = true;
125
+ state.lang = fence[2] ?? "";
126
+ state.codeLines = [];
127
+ continue;
128
+ }
129
+ // Table: a header row followed by a divider row.
130
+ if (line.includes("|") && i + 1 < lines.length && TABLE_DIVIDER.test(lines[i + 1])) {
131
+ const splitRow = (row) => row.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
132
+ const header = splitRow(line);
133
+ const divider = splitRow(lines[i + 1]);
134
+ const align = divider.map((cell) => cell.startsWith(":") && cell.endsWith(":") ? "center" : cell.endsWith(":") ? "right" : "left");
135
+ const rows = [];
136
+ i += 2;
137
+ while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
138
+ rows.push(splitRow(lines[i]));
139
+ i++;
140
+ }
141
+ i--;
142
+ out.push({ kind: "table", header, rows, align });
143
+ continue;
144
+ }
145
+ if (!line.trim()) {
146
+ out.push({ kind: "blank" });
147
+ continue;
148
+ }
149
+ const heading = line.match(HEADING);
150
+ if (heading) {
151
+ out.push({ kind: "heading", level: heading[1].length, runs: parseInline(heading[2]) });
152
+ continue;
153
+ }
154
+ if (RULE.test(line)) {
155
+ out.push({ kind: "rule" });
156
+ continue;
157
+ }
158
+ const quote = line.match(QUOTE);
159
+ if (quote) {
160
+ out.push({ kind: "quote", runs: parseInline(quote[1]) });
161
+ continue;
162
+ }
163
+ const bullet = line.match(BULLET);
164
+ if (bullet) {
165
+ const indent = bullet[1].replace(/\t/g, " ").length;
166
+ out.push({
167
+ kind: "bullet",
168
+ depth: Math.min(3, Math.floor(indent / 2)),
169
+ marker: /^\d/.test(bullet[2]) ? bullet[2] : "•",
170
+ runs: parseInline(bullet[3]),
171
+ });
172
+ continue;
173
+ }
174
+ out.push({ kind: "text", runs: parseInline(line) });
175
+ }
176
+ // A fence that hasn't closed yet is still rendered live while streaming.
177
+ // The final newline produces one empty trailing line — it is the line break
178
+ // after the last code row, not a blank row, so drop it.
179
+ if (state.inCode) {
180
+ const codeLines = state.codeLines;
181
+ if (codeLines.length > 0 && codeLines[codeLines.length - 1] === "")
182
+ codeLines.pop();
183
+ out.push({ kind: "code", lang: state.lang, lines: codeLines, open: true });
184
+ }
185
+ return { lines: out, state };
186
+ }
187
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @file mention handling for submitted prompts.
3
+ * `@path/to/file` tokens are replaced with inline content blocks (capped at
4
+ * 20KB per file) so the agent sees the file contents as context.
5
+ */
6
+ export interface MentionResult {
7
+ effective: string;
8
+ unreadable: string[];
9
+ }
10
+ /** Synchronous variant used by the REPL (node fs). */
11
+ export declare const expandMentions: (msg: string, readFileSync: (path: string, enc: "utf-8") => string, existsSync: (path: string) => boolean) => MentionResult;
12
+ //# sourceMappingURL=mentions.d.ts.map
@@ -0,0 +1,28 @@
1
+ const MAX_FILE_CHARS = 20_000;
2
+ /** Synchronous variant used by the REPL (node fs). */
3
+ export const expandMentions = (msg, readFileSync, existsSync) => {
4
+ const mentions = [...msg.matchAll(/(?:^|\s)@([^\s]+)/g)].map((m) => m[1]);
5
+ if (mentions.length === 0)
6
+ return { effective: msg, unreadable: [] };
7
+ const blocks = [];
8
+ const unreadable = [];
9
+ for (const mention of mentions) {
10
+ try {
11
+ if (!existsSync(mention))
12
+ throw new Error("not found");
13
+ const content = readFileSync(mention, "utf-8");
14
+ blocks.push(`--- @${mention} ---\n${content.slice(0, MAX_FILE_CHARS)}\n`);
15
+ }
16
+ catch {
17
+ unreadable.push(mention);
18
+ }
19
+ }
20
+ if (blocks.length === 0)
21
+ return { effective: msg, unreadable };
22
+ const stripped = msg.replace(/(?:^|\s)@[^\s]+/g, (m) => (m.startsWith(" ") ? " " : "")).trim();
23
+ return {
24
+ effective: `${stripped || "Review the attached file(s)."}\n\n${blocks.join("\n")}`,
25
+ unreadable,
26
+ };
27
+ };
28
+ //# sourceMappingURL=mentions.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Terminal-text hygiene: sanitization and display width.
3
+ *
4
+ * Two properties matter when rendering untrusted text (model output, file
5
+ * contents pulled in through @mentions, error messages from a remote server)
6
+ * into a terminal:
7
+ *
8
+ * 1. Escape sequences must never reach the terminal. A model reply
9
+ * containing `\x1b[2J` can clear the screen, `\x1b[?1049l` can drop the
10
+ * user out of the alternate buffer, and OSC 8/52 can rewrite the title or
11
+ * the clipboard. Ink has no sanitizer of its own.
12
+ * 2. Display width is not string length. Emoji and CJK glyphs occupy two
13
+ * columns; combining marks and zero-width joiners occupy none. Padding a
14
+ * table cell by `.length` misaligns every column after the first wide
15
+ * glyph, and a border drawn to a width computed in code units wraps.
16
+ */
17
+ /**
18
+ * Strip control sequences that could alter terminal state.
19
+ *
20
+ * Newlines and tabs are preserved (they are layout, not control), and so are
21
+ * carriage returns *only* when asked — a lone CR can overwrite the current
22
+ * line, so it is normalized away by default.
23
+ */
24
+ export declare const sanitize: (text: string, keepNewlines?: boolean) => string;
25
+ /** True when the text contains something `sanitize` would remove. */
26
+ export declare const hasControlSequences: (text: string) => boolean;
27
+ /** Terminal columns occupied by `text` (assumes no escape sequences). */
28
+ export declare const displayWidth: (text: string) => number;
29
+ /** Truncate to `max` columns, appending `…` when anything was dropped. */
30
+ export declare const truncateToWidth: (text: string, max: number, ellipsis?: string) => string;
31
+ /** Pad to exactly `columns` display columns (left/right/center). */
32
+ export declare const padToWidth: (text: string, columns: number, align?: "left" | "right" | "center", fill?: string) => string;
33
+ //# sourceMappingURL=terminal-text.d.ts.map