@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,245 @@
1
+ import { SLASH_COMMANDS } from "../../shared/types.js";
2
+ import { getConfig } from "../../../core/config/index.js";
3
+ /** /help — the command table. */
4
+ export const runHelp = (ctx) => {
5
+ ctx.addMessage("Commands:\n" +
6
+ SLASH_COMMANDS.map((c) => ` /${c.name}${c.args ? " " + c.args : ""}`.padEnd(18) + c.description).join("\n"));
7
+ };
8
+ /** /status — session info block. */
9
+ export const runStatus = async (ctx) => {
10
+ const { getWorkspaceRoot, isFolderTrusted } = await import("../../../core/workspace/index.js");
11
+ const { getPermissionMode } = await import("../../../core/permissions/index.js");
12
+ ctx.addMessage(`Session: ${ctx.sessionId().slice(0, 8)}\nAgent: ${ctx.agentId}\n` +
13
+ `Auth: ${ctx.config.apiKey ? "api-key" : ctx.config.token ? "jwt" : "none"}\n` +
14
+ `API: ${ctx.config.apiUrl}\nWorkspace: ${getWorkspaceRoot()}\n` +
15
+ `Permissions: ${getPermissionMode()}\nTrusted: ${isFolderTrusted() ? "yes" : "no"}`);
16
+ };
17
+ /** /mode — show or switch the permission posture for workspace operations. */
18
+ export const runMode = async (arg, ctx) => {
19
+ const { PERMISSION_MODES, getPermissionMode, setPermissionMode, isPermissionMode } = await import("../../../core/permissions/index.js");
20
+ const wanted = arg.trim().toLowerCase();
21
+ if (!wanted) {
22
+ const current = getPermissionMode();
23
+ ctx.addMessage(`Permission mode: ${current}\n\n` +
24
+ PERMISSION_MODES.map((m) => ` ${m.id === current ? "❯" : " "} ${m.id.padEnd(8)}${m.summary}`).join("\n") +
25
+ `\n\nSwitch with /mode <${PERMISSION_MODES.map((m) => m.id).join("|")}>`);
26
+ return;
27
+ }
28
+ if (!isPermissionMode(wanted)) {
29
+ ctx.addMessage(`Unknown mode '${arg.trim()}'. Choose one of: ${PERMISSION_MODES.map((m) => m.id).join(", ")}`);
30
+ return;
31
+ }
32
+ setPermissionMode(wanted);
33
+ ctx.addMessage(`✓ Permission mode: ${wanted}`);
34
+ // A mode that blocks or defers the very command being typed deserves a
35
+ // word, since it stays in effect for every later turn too.
36
+ if (wanted === "plan")
37
+ ctx.addMessage("Writes, deletes, moves, and exec are now refused.");
38
+ if (wanted === "guide")
39
+ ctx.addMessage("Mutating commands will be printed for you to run, not executed.");
40
+ };
41
+ /** /trust — list trusted folders, or forget one. */
42
+ export const runTrust = async (arg, ctx) => {
43
+ const { listTrustedFolders, untrustFolder, getWorkspaceRoot, isFolderTrusted } = await import("../../../core/workspace/index.js");
44
+ const [verb, ...rest] = arg.trim().split(/\s+/).filter(Boolean);
45
+ if (verb?.toLowerCase() === "forget") {
46
+ const target = rest.join(" ") || getWorkspaceRoot();
47
+ ctx.addMessage(untrustFolder(target)
48
+ ? `✓ No longer trusted: ${target}\nThe next launch in that folder will ask again.`
49
+ : `Not a trusted folder: ${target}`);
50
+ return;
51
+ }
52
+ const folders = listTrustedFolders();
53
+ ctx.addMessage(`Workspace: ${getWorkspaceRoot()} (${isFolderTrusted() ? "trusted" : "NOT trusted"})\n\n` +
54
+ (folders.length === 0
55
+ ? "No trusted folders yet."
56
+ : `Trusted folders:\n${folders.map((f) => ` ${f}`).join("\n")}`) +
57
+ `\n\nForget one with /trust forget <path>`);
58
+ };
59
+ /** /model <id> — persist a model override. */
60
+ export const runModel = async (arg, ctx) => {
61
+ if (!arg) {
62
+ ctx.addMessage("Usage: /model <id>");
63
+ return;
64
+ }
65
+ const { updateConfig } = await import("../../../core/config/index.js");
66
+ updateConfig({ model: arg });
67
+ ctx.addMessage(`Model updated: ${arg}`);
68
+ };
69
+ /** /provider — list configured external providers or switch the active one. */
70
+ export const runProvider = async (arg, ctx) => {
71
+ const { getConfig, updateConfig } = await import("../../../core/config/index.js");
72
+ const config = getConfig();
73
+ const providers = config.providers ?? {};
74
+ // No arg → show what's configured and which is active.
75
+ if (!arg) {
76
+ const active = config.provider && config.provider !== "odysx" ? config.provider : null;
77
+ const names = Object.keys(providers);
78
+ if (names.length === 0) {
79
+ ctx.addMessage(`No external providers configured. Add to ~/.odysx/config.json:\n\n` +
80
+ ` "providers": {\n` +
81
+ ` "openai": { "type": "openai", "apiKey": "sk-…", "model": "gpt-4o" },\n` +
82
+ ` "ollama": { "type": "openai", "baseUrl": "http://localhost:11434/v1", "model": "llama3.2" },\n` +
83
+ ` "claude": { "type": "anthropic", "apiKey": "sk-ant-…", "model": "claude-sonnet-5" },\n` +
84
+ ` "gemini": { "type": "gemini", "apiKey": "AIza…", "model": "gemini-2.0-flash" }\n` +
85
+ ` }\n\n` +
86
+ `Then /provider openai — or /provider odysx to stay on the platform.`);
87
+ return;
88
+ }
89
+ const lines = names.map((name) => {
90
+ const p = providers[name];
91
+ const mark = name === active ? "›" : " ";
92
+ return `${mark} ${name} (${p.type} · ${p.model}${p.baseUrl ? ` · ${p.baseUrl}` : ""})`;
93
+ });
94
+ ctx.addMessage(`Providers${active ? ` — active: ${active}` : " — active: odysx (platform)"}:\n${lines.join("\n")}\n\n/provider <name> to switch · /provider odysx for the platform`);
95
+ return;
96
+ }
97
+ // Arg → switch.
98
+ const target = arg.trim().toLowerCase();
99
+ if (target === "odysx") {
100
+ updateConfig({ provider: null });
101
+ ctx.addMessage("Provider → odysx platform");
102
+ return;
103
+ }
104
+ if (!providers[target]) {
105
+ ctx.addMessage(`✗ Unknown provider '${target}'. Configured: ${Object.keys(providers).join(", ") || "(none)"} · odysx`);
106
+ return;
107
+ }
108
+ updateConfig({ provider: target });
109
+ ctx.addMessage(`Provider → ${target} (${providers[target].model}). New messages now use it.`);
110
+ };
111
+ /** /usage — per-session token totals. */
112
+ export const runUsage = (ctx) => {
113
+ const u = ctx.usageRef.current;
114
+ const external = getConfig().provider;
115
+ const source = external && external !== "odysx" ? external : "the platform";
116
+ ctx.addMessage(`Usage this session (approximate — ~4 characters ≈ 1 token):\n` +
117
+ ` requests: ${u.requests}\n` +
118
+ ` prompt tokens: ${u.promptTokens}\n` +
119
+ ` completion tokens: ${u.completionTokens}\n` +
120
+ ` total tokens: ${u.promptTokens + u.completionTokens}\n` +
121
+ `Source: ${source}. These are client-side estimates, not billing figures.`);
122
+ };
123
+ /** /export — dump transcript JSON next to cwd, through the permission gate. */
124
+ export const runExport = async (messages, ctx) => {
125
+ const fn = `odysx-session-${ctx.sessionId().slice(0, 8)}.json`;
126
+ const { decideLocal, getPermissionMode } = await import("../../../core/permissions/index.js");
127
+ const { confinePath } = await import("../../../core/workspace/index.js");
128
+ const mode = getPermissionMode();
129
+ const decision = decideLocal("write", mode);
130
+ if (decision === "refuse" || decision === "guide") {
131
+ ctx.addMessage(decision === "refuse"
132
+ ? `✗ Export is a write and is not allowed in ${mode} mode.`
133
+ : `[guide] nothing was written. To export yourself, run /export in manual or auto mode.`);
134
+ return;
135
+ }
136
+ const target = confinePath(fn);
137
+ if (!target.ok || !target.resolved) {
138
+ ctx.addMessage(`✗ ${target.error ?? "Cannot export outside the workspace"}`);
139
+ return;
140
+ }
141
+ try {
142
+ const { writeFileSync } = await import("node:fs");
143
+ // The path was confined above; only the write itself is gated. Approval
144
+ // lives in the shared PendingOp flow, so manual mode can't quietly skip it.
145
+ if (decision === "ask") {
146
+ await new Promise((resolve) => {
147
+ ctx.setPendingOp({
148
+ kind: "write",
149
+ summary: `export transcript to ${fn}`,
150
+ cliArgs: [], // no re-dispatch: the approved write happens in the callback below
151
+ diff: { file: fn, before: "", after: JSON.stringify({
152
+ sessionId: ctx.sessionId(), agentId: ctx.agentId, messages,
153
+ }, null, 2).slice(0, 200) },
154
+ onApproved: () => {
155
+ try {
156
+ writeFileSync(target.resolved, JSON.stringify({
157
+ sessionId: ctx.sessionId(), agentId: ctx.agentId, messages,
158
+ }, null, 2));
159
+ ctx.addMessage(`Exported to: ${fn}`);
160
+ }
161
+ catch (err) {
162
+ ctx.addMessage(`✗ Export failed: ${err instanceof Error ? err.message : String(err)}`);
163
+ }
164
+ resolve();
165
+ },
166
+ onDenied: () => {
167
+ ctx.addMessage("Export cancelled.");
168
+ resolve();
169
+ },
170
+ });
171
+ });
172
+ return;
173
+ }
174
+ writeFileSync(target.resolved, JSON.stringify({
175
+ sessionId: ctx.sessionId(), agentId: ctx.agentId, messages,
176
+ }, null, 2));
177
+ ctx.addMessage(`Exported to: ${fn}`);
178
+ }
179
+ catch (err) {
180
+ ctx.addMessage(`✗ Export failed: ${err instanceof Error ? err.message : String(err)}`);
181
+ }
182
+ };
183
+ /**
184
+ * /local <read|write|exec|...> — mutating ops are put to the permission mode
185
+ * before anything is shown or run.
186
+ *
187
+ * Returns true when the caller must NOT run the command itself: either the
188
+ * prompt is now on screen, or the mode already answered (refused, or printed
189
+ * the command in guide mode). Read-only subcommands and `allow` decisions
190
+ * return false so the handler runs normally.
191
+ */
192
+ export const runLocalGate = async (arg, ctx) => {
193
+ const parts = arg.trim().split(/\s+/).filter(Boolean);
194
+ const sub = (parts[0] ?? "").toLowerCase();
195
+ if (sub !== "write" && sub !== "exec" && sub !== "delete" && sub !== "move")
196
+ return false;
197
+ const { decideLocal, getPermissionMode } = await import("../../../core/permissions/index.js");
198
+ const mode = getPermissionMode();
199
+ const decision = decideLocal(sub, mode);
200
+ if (decision === "refuse") {
201
+ ctx.addMessage(`✗ /local ${sub} is not allowed in ${mode} mode — switch with /mode manual or /mode auto.`);
202
+ return true;
203
+ }
204
+ if (decision === "guide") {
205
+ ctx.addMessage(`[guide] nothing was run. To do it yourself:\n\n odysx local ${parts.join(" ")}\n`);
206
+ return true;
207
+ }
208
+ // `auto` acts on ordinary writes; everything else reaches the prompt.
209
+ if (decision === "allow")
210
+ return false;
211
+ const buildOp = (diff) => ctx.setPendingOp({
212
+ kind: sub,
213
+ summary: sub === "exec"
214
+ ? `run \`${arg.replace(/^exec\s*/i, "")}\` in the workspace`
215
+ : `${sub} ${parts.slice(1).filter((p) => !p.startsWith("-")).join(" ") || "(target)"} in the workspace`,
216
+ cliArgs: parts,
217
+ diff,
218
+ });
219
+ // For writes, read the *current* file so the prompt can show a real diff.
220
+ // The read is confined exactly like the write itself — otherwise the prompt
221
+ // could display an arbitrary file outside the workspace while the handler
222
+ // writes a different one in it.
223
+ if (sub === "write") {
224
+ const target = parts[1];
225
+ const contentFlagIdx = parts.indexOf("--content");
226
+ const after = contentFlagIdx !== -1 ? (parts[contentFlagIdx + 1] ?? "") : "";
227
+ try {
228
+ const { existsSync, readFileSync } = await import("node:fs");
229
+ const { confinePath } = await import("../../../core/workspace/index.js");
230
+ const decision = target ? confinePath(target) : null;
231
+ const before = decision?.ok && decision.resolved && existsSync(decision.resolved)
232
+ ? readFileSync(decision.resolved, "utf-8")
233
+ : "";
234
+ buildOp({ file: target ?? "(target)", before: before.slice(0, 200), after });
235
+ }
236
+ catch {
237
+ buildOp(undefined);
238
+ }
239
+ }
240
+ else {
241
+ buildOp(undefined);
242
+ }
243
+ return true;
244
+ };
245
+ //# sourceMappingURL=misc.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * /tasks and /ralph case bodies — background agent task inspection & enqueue.
3
+ *
4
+ * Task verbs mirror the backend routes: `retry` re-enqueues a failed/cancelled
5
+ * task, `cancel` requests cancellation, `follow` prints one status snapshot
6
+ * (the caller can repeat it, or watch the task in the web UI).
7
+ */
8
+ import type { CommandCtx } from "../../shared/types.js";
9
+ /** /tasks [id] — list recent tasks, or show one task's status/steps/result. */
10
+ export declare const runTasks: (arg: string, ctx: CommandCtx) => Promise<void>;
11
+ /** /ralph <objective> — opt-in autonomous loop: enqueue a ralph-flagged chat task. */
12
+ export declare const runRalph: (arg: string, ctx: CommandCtx) => Promise<void>;
13
+ //# sourceMappingURL=tasks.d.ts.map
@@ -0,0 +1,91 @@
1
+ /** Split the first word of a task verb from its id. */
2
+ const verbArg = (arg) => {
3
+ const [verb = "", ...rest] = arg.trim().split(/\s+/).filter(Boolean);
4
+ return { verb: verb.toLowerCase(), id: rest.join(" ").trim() };
5
+ };
6
+ /** Detail lines shared by /tasks <id> and /tasks follow <id>. */
7
+ const formatTask = (t) => {
8
+ const steps = (t.metadata?.steps ?? []);
9
+ const stepLines = steps
10
+ .slice(-8)
11
+ .map((s) => ` · ${s.stage}${s.agent ? ` (${s.agent})` : ""}${s.done === false ? " ✗" : ""}`)
12
+ .join("\n");
13
+ return (`Task ${t.id.slice(0, 12)} — ${t.name}\n` +
14
+ ` status: ${t.status}${t.mode ? ` · mode ${t.mode}` : ""}\n` +
15
+ (stepLines ? ` steps:\n${stepLines}\n` : "") +
16
+ (t.error ? ` error: ${t.error.slice(0, 200)}\n` : "") +
17
+ (t.result?.answer ? `\n${t.result.answer.slice(0, 800)}` : ""));
18
+ };
19
+ /** /tasks [id] — list recent tasks, or show one task's status/steps/result. */
20
+ export const runTasks = async (arg, ctx) => {
21
+ const { apiCall } = await import("../../../core/provider/index.js");
22
+ const { verb, id: rest } = verbArg(arg);
23
+ if (verb === "retry" || verb === "cancel" || verb === "follow") {
24
+ if (!rest) {
25
+ ctx.addMessage(`Usage: /tasks ${verb} <task-id>`);
26
+ return;
27
+ }
28
+ const taskId = encodeURIComponent(rest);
29
+ if (verb === "retry") {
30
+ const res = await apiCall(`/api/v1/tasks/${taskId}/retry`, { method: "POST" });
31
+ ctx.addMessage(res.ok
32
+ ? `↻ Task ${rest.slice(0, 12)} re-queued — /tasks ${rest} to watch it.`
33
+ : `✗ Retry failed: ${res.error}`);
34
+ return;
35
+ }
36
+ if (verb === "cancel") {
37
+ const res = await apiCall(`/api/v1/tasks/${taskId}`, { method: "DELETE" });
38
+ ctx.addMessage(res.ok
39
+ ? `■ Task ${rest.slice(0, 12)} cancelled.`
40
+ : `✗ Cancel failed: ${res.error}`);
41
+ return;
42
+ }
43
+ // follow: one snapshot. Repeat, or poll with /watch later.
44
+ const res = await apiCall(`/api/v1/tasks/${taskId}`);
45
+ ctx.addMessage(res.ok && res.data ? formatTask(res.data) : `✗ ${res.error ?? "Task not found"}`);
46
+ return;
47
+ }
48
+ const id = arg.trim();
49
+ if (id) {
50
+ const res = await apiCall(`/api/v1/tasks/${encodeURIComponent(id)}`);
51
+ ctx.addMessage(res.ok && res.data ? formatTask(res.data) : `✗ ${res.error ?? "Task not found"}`);
52
+ }
53
+ else {
54
+ const res = await apiCall("/api/v1/tasks?limit=15");
55
+ if (!res.ok) {
56
+ ctx.addMessage(`✗ ${res.error}`);
57
+ return;
58
+ }
59
+ if (!res.data.length) {
60
+ ctx.addMessage("No tasks yet. /ralph <objective> or /tasks create runs one.");
61
+ return;
62
+ }
63
+ ctx.addMessage(`Tasks (${res.data.length}) — inspect with /tasks <id>:\n` +
64
+ res.data
65
+ .map((t) => ` ${t.id.slice(0, 12).padEnd(14)} ${t.status.padEnd(10)} ${t.name.slice(0, 40)}`)
66
+ .join("\n"));
67
+ }
68
+ };
69
+ /** /ralph <objective> — opt-in autonomous loop: enqueue a ralph-flagged chat task. */
70
+ export const runRalph = async (arg, ctx) => {
71
+ if (!arg.trim()) {
72
+ ctx.addMessage("Usage: /ralph <objective>");
73
+ return;
74
+ }
75
+ const { apiCall } = await import("../../../core/provider/index.js");
76
+ const res = await apiCall("/api/v1/tasks", {
77
+ method: "POST",
78
+ headers: { "Content-Type": "application/json" },
79
+ body: {
80
+ name: arg.trim().slice(0, 60),
81
+ payload: { message: arg.trim(), session_id: ctx.sessionId(), ralph: true, ralph_iterations: 3 },
82
+ metadata: { mode: "chat", ralph_enabled: true },
83
+ },
84
+ });
85
+ if (!res.ok) {
86
+ ctx.addMessage(`✗ /ralph failed: ${res.error}`);
87
+ return;
88
+ }
89
+ ctx.addMessage(`⚙ Ralph run queued (${res.data.id.slice(0, 12)}) — poll with /tasks ${res.data.id}`);
90
+ };
91
+ //# sourceMappingURL=tasks.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Slash-command dispatcher.
3
+ *
4
+ * The command surface is declared once in `SLASH_COMMANDS` (shared/types.ts);
5
+ * this file maps each declared name to its body. Anything missing from the
6
+ * table falls through to the unknown-command notice, and
7
+ * `test/commands.test.mjs` asserts the two lists agree — so a command added to
8
+ * the menu but not implemented (or vice versa) fails CI instead of shipping.
9
+ *
10
+ * Handlers receive the raw argument string and a CommandCtx, and never reach
11
+ * into component state directly.
12
+ */
13
+ import type { ChatMessage, CommandCtx } from "../shared/types.js";
14
+ /** Every dispatchable slash name, including hidden aliases. Used by tests. */
15
+ export declare const DISPATCHABLE_COMMANDS: readonly string[];
16
+ /**
17
+ * Dispatch a slash command. Resolves once the handler's async work is done,
18
+ * so a non-interactive caller can await it before exiting. Rejections are
19
+ * reported into the transcript rather than escaping to the process.
20
+ */
21
+ export declare const runCommand: (raw: string, ctx: CommandCtx, messages: ChatMessage[]) => Promise<void>;
22
+ //# sourceMappingURL=runCommand.d.ts.map
@@ -0,0 +1,136 @@
1
+ import { runTasks, runRalph } from "./cases/tasks.js";
2
+ import { runMcp, runPrompts, runSkills } from "./cases/catalog.js";
3
+ import { runHelp, runStatus, runModel, runProvider, runUsage, runExport, runLocalGate, runMode, runTrust, } from "./cases/misc.js";
4
+ /** Run a registered `local` command handler and print its result (non-gated ops). */
5
+ const runLocal = async (cliArgs, ctx) => {
6
+ try {
7
+ // Import registers the command, then fetch it from the registry.
8
+ await import("../../commands/local.js");
9
+ const { getAllCommands } = await import("../../core/registry/index.js");
10
+ const entry = getAllCommands().get("local");
11
+ if (!entry)
12
+ throw new Error("local command not registered");
13
+ const result = await entry.handler({}, { args: cliArgs });
14
+ // Keep the command's own output even when it failed: `local exec` reports
15
+ // a non-zero status *and* carries the compiler/test output the user needs.
16
+ // Showing only the error phrase discarded it.
17
+ const output = typeof result.data === "string"
18
+ ? result.data
19
+ : result.data === undefined
20
+ ? ""
21
+ : JSON.stringify(result.data);
22
+ const body = [
23
+ result.error ? `✗ ${result.error}` : result.message,
24
+ output.trim(),
25
+ ].filter(Boolean).join("\n");
26
+ ctx.addMessage((body || "(no output)").slice(0, 1500));
27
+ }
28
+ catch (err) {
29
+ const text = err instanceof Error ? err.message : String(err);
30
+ ctx.addMessage(`✗ ${text}`);
31
+ }
32
+ };
33
+ /**
34
+ * Slash name → body. Keys must stay in sync with SLASH_COMMANDS.
35
+ * A handler may ignore `arg` (no-argument commands) or parse it.
36
+ */
37
+ const HANDLERS = {
38
+ help: (_a, ctx) => runHelp(ctx),
39
+ clear: (_a, ctx, messages) => {
40
+ // Wipe the transcript; if a reply is mid-stream, stop it too so its
41
+ // tokens don't keep appending after the wipe. resetTranscript also
42
+ // remounts the <Static> region, which otherwise keeps old lines.
43
+ ctx.abortStream();
44
+ const had = messages.length > 0;
45
+ ctx.resetTranscript();
46
+ if (!had) {
47
+ // Nothing to wipe — still confirm so Enter visibly did something.
48
+ ctx.addMessage("✓ conversation already empty");
49
+ }
50
+ },
51
+ // /compact is the historical alias for a context wipe; same behavior.
52
+ compact: (_a, ctx, messages) => HANDLERS.clear("", ctx, messages),
53
+ new: (_a, ctx) => ctx.newSession(),
54
+ status: (_a, ctx) => runStatus(ctx),
55
+ agent: (arg, ctx) => {
56
+ if (!arg) {
57
+ ctx.openAgentPicker();
58
+ }
59
+ else {
60
+ ctx.setAgentId(arg);
61
+ ctx.addMessage(`Agent set to: ${arg}`);
62
+ }
63
+ },
64
+ model: (arg, ctx) => runModel(arg, ctx),
65
+ provider: (arg, ctx) => runProvider(arg, ctx),
66
+ // Open the sign-in menu (auth picker). Shareable between the base path and
67
+ // the slash-menu's Enter handler since both route through here.
68
+ signin: (_a, ctx) => {
69
+ ctx.setAuthIndex(0);
70
+ ctx.setAuthMode("picker");
71
+ },
72
+ // /keys and /keys new both open the panel; creation starts from a keystroke
73
+ // there, because the flow needs the keys state owned by app.tsx.
74
+ keys: (_a, ctx) => ctx.openKeysPanel(),
75
+ sessions: (arg, ctx) => {
76
+ // /sessions <id> → resume directly; bare /sessions → interactive picker
77
+ const sid = arg.trim();
78
+ return sid ? ctx.resumeSession(sid) : ctx.openSessionPicker();
79
+ },
80
+ tasks: (arg, ctx) => runTasks(arg, ctx),
81
+ ralph: (arg, ctx) => runRalph(arg, ctx),
82
+ mcp: (_a, ctx) => runMcp(ctx),
83
+ prompts: (arg, ctx) => runPrompts(arg, ctx),
84
+ skills: (_a, ctx) => runSkills(ctx),
85
+ usage: (_a, ctx) => runUsage(ctx),
86
+ export: (_a, ctx, messages) => runExport(messages, ctx),
87
+ // Who decides whether a workspace operation may run, and which folders this
88
+ // session is allowed to touch at all.
89
+ mode: (arg, ctx) => runMode(arg, ctx),
90
+ trust: (arg, ctx) => runTrust(arg, ctx),
91
+ local: async (arg, ctx) => {
92
+ // Risky ops (write/exec/delete/move) go through the permission prompt
93
+ // first. The gate is async because it reads the current file for the diff.
94
+ const cliArgs = arg.trim().split(/\s+/).filter(Boolean);
95
+ // Awaited, not fire-and-forget: a rejection here used to escape as an
96
+ // unhandledRejection, and the piped path would exit before the op ran.
97
+ const gated = await runLocalGate(arg, ctx);
98
+ if (!gated)
99
+ await runLocal(cliArgs, ctx);
100
+ },
101
+ quit: (_a, ctx) => ctx.requestExit(),
102
+ // /exit is a documented alias of /quit; aliases are declared in the handler
103
+ // table rather than duplicated in the menu so /help stays one row each.
104
+ exit: (_a, ctx) => ctx.requestExit(),
105
+ };
106
+ /** Alternate names that dispatch to the same body but are hidden from /help. */
107
+ const ALIASES = {
108
+ q: "quit",
109
+ };
110
+ /** Every dispatchable slash name, including hidden aliases. Used by tests. */
111
+ export const DISPATCHABLE_COMMANDS = [
112
+ ...Object.keys(HANDLERS),
113
+ ...Object.keys(ALIASES),
114
+ ];
115
+ /**
116
+ * Dispatch a slash command. Resolves once the handler's async work is done,
117
+ * so a non-interactive caller can await it before exiting. Rejections are
118
+ * reported into the transcript rather than escaping to the process.
119
+ */
120
+ export const runCommand = async (raw, ctx, messages) => {
121
+ const [name, ...rest] = raw.replace(/^\//, "").split(" ");
122
+ const arg = rest.join(" ");
123
+ const key = (ALIASES[name.toLowerCase()] ?? name.toLowerCase());
124
+ const handler = HANDLERS[key];
125
+ if (!handler) {
126
+ ctx.addMessage(`Unknown command: /${name}. Try /help.`);
127
+ return;
128
+ }
129
+ try {
130
+ await handler(arg, ctx, messages);
131
+ }
132
+ catch (err) {
133
+ ctx.addMessage(`✗ ${err instanceof Error ? err.message : String(err)}`);
134
+ }
135
+ };
136
+ //# sourceMappingURL=runCommand.js.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Agent picker (/agent with no args → select from your agents)
3
+ */
4
+ import React from "react";
5
+ import type { AgentOption } from "../shared/types.js";
6
+ export declare const AgentPicker: ({ options, selected, busy, }: {
7
+ options: AgentOption[];
8
+ selected: number;
9
+ busy?: boolean;
10
+ }) => React.JSX.Element;
11
+ //# sourceMappingURL=AgentPicker.d.ts.map
@@ -0,0 +1,7 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text } from "ink";
3
+ export const AgentPicker = ({ options, selected, busy, }) => (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "magenta", paddingX: 1, marginBottom: 1, children: [_jsx(Text, { bold: true, color: "magenta", children: "Select an agent" }), _jsx(Text, { dimColor: true, children: "\u2191/\u2193 to move \u00B7 Enter to switch \u00B7 esc to cancel" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: busy && options.length === 0 ? (_jsx(Text, { dimColor: true, children: "Loading your agents\u2026" })) : (options.map((opt, idx) => {
4
+ const isSelected = idx === selected && !busy;
5
+ return (_jsx(Box, { children: _jsxs(Text, { color: isSelected ? "magenta" : "gray", bold: isSelected, children: [isSelected ? "❯ " : " ", opt.label, _jsxs(Text, { dimColor: true, children: [" \u2014 ", opt.description] })] }) }, opt.id));
6
+ })) })] }));
7
+ //# sourceMappingURL=AgentPicker.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Auth picker (two options: API key / account sign-in)
3
+ */
4
+ import React from "react";
5
+ export declare const AuthPicker: ({ options, selected, busy, }: {
6
+ options: readonly {
7
+ id: string;
8
+ label: string;
9
+ description: string;
10
+ }[];
11
+ selected: number;
12
+ busy?: boolean;
13
+ }) => React.JSX.Element;
14
+ //# sourceMappingURL=AuthPicker.d.ts.map
@@ -0,0 +1,7 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text } from "ink";
3
+ export const AuthPicker = ({ options, selected, busy, }) => (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, marginBottom: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "Sign in to OdysX" }), _jsx(Text, { dimColor: true, children: "\u2191/\u2193 to move \u00B7 Enter to select \u00B7 esc to cancel" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: options.map((opt, idx) => {
4
+ const isSelected = idx === selected && !busy;
5
+ return (_jsx(Box, { children: _jsxs(Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: [isSelected ? "❯ " : " ", opt.label, _jsxs(Text, { dimColor: true, children: [" \u2014 ", opt.description] })] }) }, opt.id));
6
+ }) })] }));
7
+ //# sourceMappingURL=AuthPicker.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Welcome banner — shown once, above the first exchange, then scrolled into
3
+ * the static transcript. Intentionally compact: the logo, one line of
4
+ * orientation, and the three keys a new user needs.
5
+ */
6
+ import React from "react";
7
+ export declare const Banner: () => React.JSX.Element;
8
+ //# sourceMappingURL=Banner.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useStdout } from "ink";
3
+ import { theme } from "../theme.js";
4
+ /** Full logo, used when the terminal is wide enough. */
5
+ const LOGO = `██████╗ ██████╗ ██╗ ██╗███████╗██╗ ██╗
6
+ ██╔═══██╗██╔══██╗╚██╗ ██╔╝██╔════╝╚██╗██╔╝
7
+ ██║ ██║██║ ██║ ╚████╔╝ ███████╗ ╚███╔╝
8
+ ██║ ██║██║ ██║ ╚██╔╝ ╚════██║ ██╔██╗
9
+ ╚██████╔╝██████╔╝ ██║ ███████║██╔╝ ██╗
10
+ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝`;
11
+ const LOGO_MIN_COLUMNS = LOGO.split("\n")[0].length + 4;
12
+ const Hint = ({ keys, label }) => (_jsxs(Text, { dimColor: true, children: [_jsx(Text, { color: theme.color.accent, children: keys }), " ", label] }));
13
+ export const Banner = () => {
14
+ const { stdout } = useStdout();
15
+ const columns = stdout?.columns ?? 80;
16
+ const wide = columns >= LOGO_MIN_COLUMNS;
17
+ // Below ~60 columns the tagline and the hints wrapped into each other,
18
+ // producing a sentence that could not be read. Drop the tagline and let the
19
+ // hints wrap as whole units (each Hint is one Text node, so a wrap falls
20
+ // between hints, never inside one).
21
+ const roomy = columns >= 60;
22
+ return (_jsxs(Box, { flexDirection: "column", marginTop: wide ? 1 : 0, marginBottom: 1, children: [wide && (_jsx(Box, { flexDirection: "column", children: _jsx(Text, { color: theme.color.brand, children: LOGO }) })), _jsxs(Box, { marginTop: wide ? 1 : 0, columnGap: 2, flexWrap: "wrap", children: [_jsxs(Text, { children: [_jsx(Text, { bold: true, color: theme.color.brand, children: "Codemind" }), _jsx(Text, { dimColor: true, children: " v0.1.0" })] }), roomy && _jsx(Text, { dimColor: true, children: "build, run, and orchestrate agents from your terminal" })] }), _jsxs(Box, { marginTop: 1, columnGap: 2, flexWrap: "wrap", children: [_jsx(Hint, { keys: "/", label: "commands" }), _jsx(Hint, { keys: "/help", label: "everything" }), _jsx(Hint, { keys: "@file", label: "attach context" }), _jsx(Hint, { keys: "\u21E7\u23CE", label: "new line" }), _jsx(Hint, { keys: "ctrl+c", label: "exit" })] })] }));
23
+ };
24
+ //# sourceMappingURL=Banner.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Slash-command suggestion menu (bottom, above input).
3
+ *
4
+ * Bounded by the terminal height and truncated to the width, so a long
5
+ * command list can never push the input bar off-screen. A "+N more" line
6
+ * keeps it obvious that filtering narrows the list.
7
+ */
8
+ import React from "react";
9
+ import type { SlashCommand } from "../shared/types.js";
10
+ export declare const CommandMenu: ({ commands, selected, total, above, }: {
11
+ commands: SlashCommand[];
12
+ selected: number;
13
+ total?: number;
14
+ /** Commands scrolled off the top of the window. */
15
+ above?: number;
16
+ }) => React.JSX.Element;
17
+ //# sourceMappingURL=CommandMenu.d.ts.map
@@ -0,0 +1,21 @@
1
+ import { jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useStdout } from "ink";
3
+ import { theme } from "../theme.js";
4
+ import { displayWidth, truncateToWidth } from "../utils/terminal-text.js";
5
+ export const CommandMenu = ({ commands, selected, total, above = 0, }) => {
6
+ const { stdout } = useStdout();
7
+ // Row chrome: paddingLeft={2} + the 2-column pointer column.
8
+ const width = (stdout?.columns ?? 80) - 4;
9
+ const hidden = Math.max(0, (total ?? commands.length) - above - commands.length);
10
+ return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, marginBottom: 0, children: [above > 0 && (_jsxs(Text, { dimColor: true, children: [" ", "\u2026 ", above, " above"] })), commands.map((cmd, idx) => {
11
+ const isSelected = idx === selected;
12
+ const head = `${cmd.args ? `/${cmd.name} ${cmd.args}` : `/${cmd.name}`}`;
13
+ // Measure in display columns and truncate `head` itself: a long
14
+ // argument list used to overflow the budget and wrap the row.
15
+ const headShown = truncateToWidth(head, Math.max(8, Math.floor(width * 0.6)));
16
+ const room = Math.max(6, width - displayWidth(headShown) - 2);
17
+ const description = truncateToWidth(cmd.description, room);
18
+ return (_jsxs(Box, { children: [_jsxs(Text, { color: isSelected ? theme.color.brand : theme.color.muted, bold: isSelected, children: [isSelected ? "› " : " ", headShown] }), _jsxs(Text, { dimColor: true, children: [" ", description] })] }, cmd.name));
19
+ }), hidden > 0 && (_jsxs(Text, { dimColor: true, children: [" ", "\u2026 ", hidden, " more \u2014 keep typing to narrow"] }))] }));
20
+ };
21
+ //# sourceMappingURL=CommandMenu.js.map