@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.
- package/README.md +293 -2
- package/dist/commands/agents.d.ts +2 -0
- package/dist/commands/agents.js +91 -0
- package/dist/commands/auth.d.ts +2 -0
- package/dist/commands/auth.js +35 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +180 -0
- package/dist/commands/keys.d.ts +2 -0
- package/dist/commands/keys.js +81 -0
- package/dist/commands/local.d.ts +2 -0
- package/dist/commands/local.js +325 -0
- package/dist/commands/mcp.d.ts +2 -0
- package/dist/commands/mcp.js +73 -0
- package/dist/commands/prompts.d.ts +2 -0
- package/dist/commands/prompts.js +59 -0
- package/dist/commands/skills.d.ts +2 -0
- package/dist/commands/skills.js +41 -0
- package/dist/core/auth/index.d.ts +10 -0
- package/dist/core/auth/index.js +82 -0
- package/dist/core/config/index.d.ts +47 -0
- package/dist/core/config/index.js +118 -0
- package/dist/core/history.d.ts +14 -0
- package/dist/core/history.js +80 -0
- package/dist/core/markdown-renderer.d.ts +47 -0
- package/dist/core/markdown-renderer.js +385 -0
- package/dist/core/permissions/index.d.ts +31 -0
- package/dist/core/permissions/index.js +64 -0
- package/dist/core/provider/external.d.ts +28 -0
- package/dist/core/provider/external.js +248 -0
- package/dist/core/provider/index.d.ts +138 -0
- package/dist/core/provider/index.js +510 -0
- package/dist/core/registry/index.d.ts +25 -0
- package/dist/core/registry/index.js +216 -0
- package/dist/core/schema/types.d.ts +93 -0
- package/dist/core/schema/types.js +12 -0
- package/dist/core/terminal.d.ts +40 -0
- package/dist/core/terminal.js +134 -0
- package/dist/core/workspace/index.d.ts +35 -0
- package/dist/core/workspace/index.js +194 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +393 -0
- package/dist/ui/app.d.ts +3 -0
- package/dist/ui/app.js +554 -0
- package/dist/ui/commands/cases/catalog.d.ts +11 -0
- package/dist/ui/commands/cases/catalog.js +62 -0
- package/dist/ui/commands/cases/misc.d.ts +35 -0
- package/dist/ui/commands/cases/misc.js +245 -0
- package/dist/ui/commands/cases/tasks.d.ts +13 -0
- package/dist/ui/commands/cases/tasks.js +91 -0
- package/dist/ui/commands/runCommand.d.ts +22 -0
- package/dist/ui/commands/runCommand.js +136 -0
- package/dist/ui/components/AgentPicker.d.ts +11 -0
- package/dist/ui/components/AgentPicker.js +7 -0
- package/dist/ui/components/AuthPicker.d.ts +14 -0
- package/dist/ui/components/AuthPicker.js +7 -0
- package/dist/ui/components/Banner.d.ts +8 -0
- package/dist/ui/components/Banner.js +24 -0
- package/dist/ui/components/CommandMenu.d.ts +17 -0
- package/dist/ui/components/CommandMenu.js +21 -0
- package/dist/ui/components/ErrorBoundary.d.ts +24 -0
- package/dist/ui/components/ErrorBoundary.js +51 -0
- package/dist/ui/components/InputBar.d.ts +28 -0
- package/dist/ui/components/InputBar.js +108 -0
- package/dist/ui/components/KeysPanel.d.ts +12 -0
- package/dist/ui/components/KeysPanel.js +25 -0
- package/dist/ui/components/MessageView.d.ts +29 -0
- package/dist/ui/components/MessageView.js +107 -0
- package/dist/ui/components/PermissionPrompt.d.ts +10 -0
- package/dist/ui/components/PermissionPrompt.js +4 -0
- package/dist/ui/components/Pickers.d.ts +43 -0
- package/dist/ui/components/Pickers.js +33 -0
- package/dist/ui/components/SearchOverlay.d.ts +21 -0
- package/dist/ui/components/SearchOverlay.js +14 -0
- package/dist/ui/components/SessionPicker.d.ts +12 -0
- package/dist/ui/components/SessionPicker.js +8 -0
- package/dist/ui/components/WorkingIndicator.d.ts +10 -0
- package/dist/ui/components/WorkingIndicator.js +23 -0
- package/dist/ui/controls/ApiKeyEntry.d.ts +8 -0
- package/dist/ui/controls/ApiKeyEntry.js +5 -0
- package/dist/ui/controls/MultiSelect.d.ts +18 -0
- package/dist/ui/controls/MultiSelect.js +9 -0
- package/dist/ui/hooks/useAgentPicker.d.ts +14 -0
- package/dist/ui/hooks/useAgentPicker.js +53 -0
- package/dist/ui/hooks/useAuthFlow.d.ts +14 -0
- package/dist/ui/hooks/useAuthFlow.js +31 -0
- package/dist/ui/hooks/useKeysFlow.d.ts +17 -0
- package/dist/ui/hooks/useKeysFlow.js +130 -0
- package/dist/ui/hooks/useSessionPicker.d.ts +29 -0
- package/dist/ui/hooks/useSessionPicker.js +58 -0
- package/dist/ui/hooks/useTerminalSize.d.ts +6 -0
- package/dist/ui/hooks/useTerminalSize.js +29 -0
- package/dist/ui/input/keyRouter.d.ts +125 -0
- package/dist/ui/input/keyRouter.js +574 -0
- package/dist/ui/layouts/ScreenLayout.d.ts +98 -0
- package/dist/ui/layouts/ScreenLayout.js +56 -0
- package/dist/ui/shared/types.d.ts +143 -0
- package/dist/ui/shared/types.js +38 -0
- package/dist/ui/theme.d.ts +29 -0
- package/dist/ui/theme.js +54 -0
- package/dist/ui/utils/markdown.d.ts +74 -0
- package/dist/ui/utils/markdown.js +187 -0
- package/dist/ui/utils/mentions.d.ts +12 -0
- package/dist/ui/utils/mentions.js +28 -0
- package/dist/ui/utils/terminal-text.d.ts +33 -0
- package/dist/ui/utils/terminal-text.js +123 -0
- package/dist/ui/utils/text.d.ts +72 -0
- package/dist/ui/utils/text.js +171 -0
- package/package.json +50 -6
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workspace — root-directory detection + path confinement for local ops.
|
|
3
|
+
*
|
|
4
|
+
* The CLI's local file/shell commands are scoped to a "workspace": the
|
|
5
|
+
* directory `odysx` was launched from (overridable via ODYSX_WORKSPACE or
|
|
6
|
+
* ~/.odysx/config.json). Every path a command touches must resolve inside
|
|
7
|
+
* that root, so `odysx local write ../../../etc/x` can't escape it.
|
|
8
|
+
*/
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
10
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
|
+
import { getConfig } from "../config/index.js";
|
|
13
|
+
let cachedRoot = null;
|
|
14
|
+
/** Windows and macOS compare paths case-insensitively; Linux does not. */
|
|
15
|
+
const CASE_INSENSITIVE = process.platform === "win32" || process.platform === "darwin";
|
|
16
|
+
const fold = (p) => (CASE_INSENSITIVE ? p.toLowerCase() : p);
|
|
17
|
+
/** Resolve links/junctions, falling back to the input when it doesn't exist. */
|
|
18
|
+
const real = (p) => {
|
|
19
|
+
try {
|
|
20
|
+
return realpathSync.native(p);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return p;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the deepest existing ancestor of `p`, then re-append the missing
|
|
28
|
+
* tail. `real()` alone is a no-op for a path that doesn't exist yet, which
|
|
29
|
+
* would let `write linked/new.txt` escape when `linked` is a junction.
|
|
30
|
+
*/
|
|
31
|
+
const realDeep = (p) => {
|
|
32
|
+
const tail = [];
|
|
33
|
+
let current = p;
|
|
34
|
+
while (!existsSync(current)) {
|
|
35
|
+
const parent = dirname(current);
|
|
36
|
+
if (parent === current)
|
|
37
|
+
return p; // reached the root; nothing to resolve
|
|
38
|
+
tail.unshift(basename(current));
|
|
39
|
+
current = parent;
|
|
40
|
+
}
|
|
41
|
+
return tail.length > 0 ? join(real(current), ...tail) : real(current);
|
|
42
|
+
};
|
|
43
|
+
/** True when `p` is `root` itself or sits inside it. */
|
|
44
|
+
const isInside = (p, root) => {
|
|
45
|
+
const a = fold(p);
|
|
46
|
+
const b = fold(root);
|
|
47
|
+
return a === b || a.startsWith(b.endsWith(sep) ? b : b + sep);
|
|
48
|
+
};
|
|
49
|
+
/** Resolve the workspace root (once per process): config override → env → cwd. */
|
|
50
|
+
export function getWorkspaceRoot() {
|
|
51
|
+
if (cachedRoot)
|
|
52
|
+
return cachedRoot;
|
|
53
|
+
const configured = getConfig().workspace ?? process.env.ODYSX_WORKSPACE ?? null;
|
|
54
|
+
let root = configured && configured.trim() ? resolve(configured.trim()) : process.cwd();
|
|
55
|
+
// A workspace pointing at $HOME would make "inside root" meaningless.
|
|
56
|
+
if (fold(root) === fold(homedir()) || fold(root) === fold(tmpdir())) {
|
|
57
|
+
root = process.cwd();
|
|
58
|
+
}
|
|
59
|
+
if (!existsSync(root))
|
|
60
|
+
mkdirSync(root, { recursive: true });
|
|
61
|
+
cachedRoot = real(root);
|
|
62
|
+
return cachedRoot;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Confine a user-supplied path to the workspace.
|
|
66
|
+
*
|
|
67
|
+
* Absolute paths are allowed only when they already sit inside the root;
|
|
68
|
+
* relative paths are resolved against it. Both sides are resolved through
|
|
69
|
+
* links first — a lexical check alone let a junction inside the workspace
|
|
70
|
+
* (node_modules and AppData are full of them) point anywhere, so
|
|
71
|
+
* `local read linked/secret` reached outside the root. Comparison is
|
|
72
|
+
* case-folded on platforms whose filesystems are.
|
|
73
|
+
*/
|
|
74
|
+
export function confinePath(input) {
|
|
75
|
+
// Device and UNC paths have no meaningful "inside the workspace".
|
|
76
|
+
if (process.platform === "win32" && /^(\\\\|\/\/|\\.\\)/.test(input)) {
|
|
77
|
+
return { ok: false, error: `Path escapes workspace (UNC/device paths are not allowed)` };
|
|
78
|
+
}
|
|
79
|
+
const root = getWorkspaceRoot();
|
|
80
|
+
const candidate = isAbsolute(input) ? input : join(root, input);
|
|
81
|
+
const abs = realDeep(resolve(candidate));
|
|
82
|
+
if (isInside(abs, root)) {
|
|
83
|
+
return { ok: true, resolved: abs };
|
|
84
|
+
}
|
|
85
|
+
return { ok: false, error: `Path escapes workspace (${abs} is outside ${root})` };
|
|
86
|
+
}
|
|
87
|
+
/* ── Folder trust ───────────────────────────────────────────────────────── */
|
|
88
|
+
/**
|
|
89
|
+
* A folder is trusted once the user has explicitly said so.
|
|
90
|
+
*
|
|
91
|
+
* Confinement keeps operations *inside* the workspace; trust answers the
|
|
92
|
+
* different question of whether the workspace is one the user meant to hand
|
|
93
|
+
* over at all. Launching in an unfamiliar directory (a cloned repo, someone
|
|
94
|
+
* else's checkout, a shared drive) should not silently grant read, write, and
|
|
95
|
+
* execute over it, so the REPL asks once and remembers the answer.
|
|
96
|
+
*/
|
|
97
|
+
const TRUST_FILE = join(homedir(), ".odysx", "trusted-folders.json");
|
|
98
|
+
let cachedTrust = null;
|
|
99
|
+
const loadTrust = () => {
|
|
100
|
+
if (cachedTrust)
|
|
101
|
+
return cachedTrust;
|
|
102
|
+
try {
|
|
103
|
+
if (!existsSync(TRUST_FILE)) {
|
|
104
|
+
cachedTrust = [];
|
|
105
|
+
return cachedTrust;
|
|
106
|
+
}
|
|
107
|
+
const parsed = JSON.parse(readFileSync(TRUST_FILE, "utf-8"));
|
|
108
|
+
cachedTrust = Array.isArray(parsed) ? parsed.filter((p) => typeof p === "string") : [];
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// An unreadable trust file must fail closed: treat every folder as
|
|
112
|
+
// untrusted rather than silently trusting whatever is in the workspace.
|
|
113
|
+
cachedTrust = [];
|
|
114
|
+
}
|
|
115
|
+
return cachedTrust;
|
|
116
|
+
};
|
|
117
|
+
/** Persist atomically and owner-only, like the config file. */
|
|
118
|
+
const saveTrust = (folders) => {
|
|
119
|
+
const dir = dirname(TRUST_FILE);
|
|
120
|
+
if (!existsSync(dir))
|
|
121
|
+
mkdirSync(dir, { recursive: true });
|
|
122
|
+
const tmp = `${TRUST_FILE}.${process.pid}.tmp`;
|
|
123
|
+
try {
|
|
124
|
+
writeFileSync(tmp, JSON.stringify(folders, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
125
|
+
try {
|
|
126
|
+
chmodSync(tmp, 0o600);
|
|
127
|
+
}
|
|
128
|
+
catch { /* not POSIX */ }
|
|
129
|
+
renameSync(tmp, TRUST_FILE);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
try {
|
|
133
|
+
if (existsSync(tmp))
|
|
134
|
+
unlinkSync(tmp);
|
|
135
|
+
}
|
|
136
|
+
catch { /* best effort */ }
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
cachedTrust = folders;
|
|
140
|
+
};
|
|
141
|
+
export const listTrustedFolders = () => [...loadTrust()];
|
|
142
|
+
/**
|
|
143
|
+
* Is `root` trusted? A folder is trusted if it, or any ancestor of it, has
|
|
144
|
+
* been trusted — trusting a monorepo root must not mean re-answering for
|
|
145
|
+
* every package inside it.
|
|
146
|
+
*/
|
|
147
|
+
export const isFolderTrusted = (root = getWorkspaceRoot()) => {
|
|
148
|
+
const target = realDeep(resolve(root));
|
|
149
|
+
return loadTrust().some((trusted) => isInside(target, realDeep(resolve(trusted))));
|
|
150
|
+
};
|
|
151
|
+
export const trustFolder = (root = getWorkspaceRoot()) => {
|
|
152
|
+
const resolved = realDeep(resolve(root));
|
|
153
|
+
const folders = loadTrust();
|
|
154
|
+
if (!folders.some((f) => fold(f) === fold(resolved))) {
|
|
155
|
+
saveTrust([...folders, resolved]);
|
|
156
|
+
}
|
|
157
|
+
return resolved;
|
|
158
|
+
};
|
|
159
|
+
/** Forget a trusted folder. Returns false when it was not trusted. */
|
|
160
|
+
export const untrustFolder = (root) => {
|
|
161
|
+
const target = fold(realDeep(resolve(root)));
|
|
162
|
+
const folders = loadTrust();
|
|
163
|
+
const next = folders.filter((f) => fold(f) !== target);
|
|
164
|
+
if (next.length === folders.length)
|
|
165
|
+
return false;
|
|
166
|
+
saveTrust(next);
|
|
167
|
+
return true;
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* Gate a shell command before running it in the workspace.
|
|
171
|
+
*
|
|
172
|
+
* Denylist of obviously-destructive patterns; this is a seatbelt for typos,
|
|
173
|
+
* not a sandbox. Anything not matched still goes through the REPL's y/N
|
|
174
|
+
* approval prompt before executing.
|
|
175
|
+
*/
|
|
176
|
+
const DENY_PATTERNS = [
|
|
177
|
+
/\brm\s+(-[a-z]*r[a-z]*f|-[a-z]*f[a-z]*r)\b/i, // rm -rf
|
|
178
|
+
/\bformat\b/i,
|
|
179
|
+
/\bdel\s+\/[sq]/i, // Windows del /s /q
|
|
180
|
+
/\brmdir\s+\/s/i,
|
|
181
|
+
/\bRemove-Item\b.*-Recurse.*-Force/i,
|
|
182
|
+
/\bmkfs\b/,
|
|
183
|
+
/>\s*\/dev\/sd[a-z]/, // raw device writes
|
|
184
|
+
/\bshutdown\b|\breboot\b/i,
|
|
185
|
+
];
|
|
186
|
+
export function checkCommand(command) {
|
|
187
|
+
for (const re of DENY_PATTERNS) {
|
|
188
|
+
if (re.test(command)) {
|
|
189
|
+
return { ok: false, error: `Refused by safety policy: matches /${re.source}/` };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return { ok: true };
|
|
193
|
+
}
|
|
194
|
+
//# sourceMappingURL=index.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "./commands/agents.js";
|
|
3
|
+
import "./commands/auth.js";
|
|
4
|
+
import "./commands/chat.js";
|
|
5
|
+
import "./commands/keys.js";
|
|
6
|
+
import "./commands/local.js";
|
|
7
|
+
import "./commands/mcp.js";
|
|
8
|
+
import "./commands/prompts.js";
|
|
9
|
+
import "./commands/skills.js";
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* OdysX CLI — Codemind
|
|
4
|
+
* Interactive agent chat.
|
|
5
|
+
*/
|
|
6
|
+
import { Command } from "commander";
|
|
7
|
+
import { buildProgram } from "./core/registry/index.js";
|
|
8
|
+
import { getConfig, updateConfig } from "./core/config/index.js";
|
|
9
|
+
import { getPermissionMode, isPermissionMode } from "./core/permissions/index.js";
|
|
10
|
+
import { getWorkspaceRoot, isFolderTrusted, trustFolder } from "./core/workspace/index.js";
|
|
11
|
+
import { streamTurn } from "./core/provider/index.js";
|
|
12
|
+
import { writeFileSync } from "node:fs";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { enterAltScreen, exitWith } from "./core/terminal.js";
|
|
15
|
+
// Command registration is a side effect of importing each module — these must
|
|
16
|
+
// run before buildProgram() so the registry knows about every command.
|
|
17
|
+
import "./commands/agents.js";
|
|
18
|
+
import "./commands/auth.js";
|
|
19
|
+
import "./commands/chat.js";
|
|
20
|
+
import "./commands/keys.js";
|
|
21
|
+
import "./commands/local.js";
|
|
22
|
+
import "./commands/mcp.js";
|
|
23
|
+
import "./commands/prompts.js";
|
|
24
|
+
import "./commands/skills.js";
|
|
25
|
+
// ── Colour ─────────────────────────────────────────────────────────────────
|
|
26
|
+
// chalk, not literal escape codes: chalk normalizes every style to a no-op at
|
|
27
|
+
// level 0, so piped output (`odysx | tee`, CI) and NO_COLOR stay clean without
|
|
28
|
+
// a conditional at each call site. The level is set by the Ink theme, which
|
|
29
|
+
// shares this module and applies the same policy; this path may run before it
|
|
30
|
+
// (a one-shot subcommand never imports the theme), so apply it here too.
|
|
31
|
+
import chalk from "chalk";
|
|
32
|
+
import { colorEnabled, clearViewport } from "./core/terminal.js";
|
|
33
|
+
if (!colorEnabled())
|
|
34
|
+
chalk.level = 0;
|
|
35
|
+
const C = {
|
|
36
|
+
bold: chalk.bold,
|
|
37
|
+
dim: chalk.dim,
|
|
38
|
+
user: chalk.bgHex("#5f87af").white,
|
|
39
|
+
assistant: chalk.bgHex("#303030").hex("#d0d0d0"),
|
|
40
|
+
};
|
|
41
|
+
function promptStr() {
|
|
42
|
+
return "❯ ";
|
|
43
|
+
}
|
|
44
|
+
function header(config) {
|
|
45
|
+
const isAuth = config.apiKey || config.token;
|
|
46
|
+
const status = isAuth ? "✓ auth" : "○ no auth";
|
|
47
|
+
const agent = config.model ?? "master";
|
|
48
|
+
return `
|
|
49
|
+
${C.bold(`Codemind v0.1.0 • agent ${agent} | ${status} | ${getPermissionMode()} mode`)}
|
|
50
|
+
`;
|
|
51
|
+
}
|
|
52
|
+
function helpText() {
|
|
53
|
+
return `
|
|
54
|
+
${C.bold("Commands:")}
|
|
55
|
+
${C.dim("/help")} Show help
|
|
56
|
+
${C.dim("/clear")} Clear screen
|
|
57
|
+
${C.dim("/status")} Session info
|
|
58
|
+
${C.dim("/agent")} ${C.dim("<id>")} Switch agent
|
|
59
|
+
${C.dim("/model")} ${C.dim("<id>")} Switch model
|
|
60
|
+
${C.dim("/quit")} Exit
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
function formatMessage(role, text) {
|
|
64
|
+
return role === "user" ? C.user(text) : C.assistant(text);
|
|
65
|
+
}
|
|
66
|
+
const useLegacyRepl = process.argv.includes("--legacy-repl");
|
|
67
|
+
if (useLegacyRepl) {
|
|
68
|
+
// Strip the flag so commander (below) never sees an unknown option, and
|
|
69
|
+
// drop the extra argv entry so hasArgs reflects the remaining args.
|
|
70
|
+
process.argv = process.argv.filter((a) => a !== "--legacy-repl");
|
|
71
|
+
}
|
|
72
|
+
// Colour flags are consumed by terminal.ts (colorEnabled) for every writer;
|
|
73
|
+
// strip them here too so commander doesn't reject them as unknown options.
|
|
74
|
+
const COLOR_FLAGS = ["--color", "--colors", "--no-color", "--no-colors"];
|
|
75
|
+
if (process.argv.some((a) => COLOR_FLAGS.includes(a))) {
|
|
76
|
+
process.argv = process.argv.filter((a) => !COLOR_FLAGS.includes(a));
|
|
77
|
+
}
|
|
78
|
+
// --mode [plan|guide|manual|auto] sets the persisted permission posture. It is
|
|
79
|
+
// consumed here (before commander) so the flag works both with the REPL and
|
|
80
|
+
// with one-shot subcommands; an invalid value fails early with a clear list.
|
|
81
|
+
let modeFlag = null;
|
|
82
|
+
const MODE_FLAG = "--mode";
|
|
83
|
+
const modeIdx = process.argv.indexOf(MODE_FLAG);
|
|
84
|
+
if (modeIdx !== -1) {
|
|
85
|
+
const given = process.argv[modeIdx + 1] ?? null;
|
|
86
|
+
process.argv = process.argv.filter((_, i) => i !== modeIdx && i !== modeIdx + 1);
|
|
87
|
+
if (!given || !isPermissionMode(given)) {
|
|
88
|
+
process.stderr.write(`Invalid --mode. Choose: plan, guide, manual, auto.\n`);
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
modeFlag = given;
|
|
92
|
+
// Persist only after the REPL's trust gate has passed — an untrusted piped
|
|
93
|
+
// invocation must not silently change the user's saved permission mode.
|
|
94
|
+
}
|
|
95
|
+
const hasArgs = process.argv.length > 2;
|
|
96
|
+
// Ink needs a real TTY for raw-mode key handling, and it draws with cursor
|
|
97
|
+
// control that only makes sense on a screen. Require BOTH ends: a TTY stdin
|
|
98
|
+
// with redirected stdout (`odysx > transcript.txt`) used to run the full TUI
|
|
99
|
+
// and write escape sequences into the file. Piped stdin (CI, `echo "/help" |
|
|
100
|
+
// odysx`) falls back to readline instead of crashing on raw mode.
|
|
101
|
+
const canRunInk = Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
|
|
102
|
+
const interactive = !hasArgs && canRunInk;
|
|
103
|
+
// The legacy/piped path installs no handler of its own; a rejected promise in
|
|
104
|
+
// an async slash handler would otherwise terminate Node with a raw stack.
|
|
105
|
+
process.on("unhandledRejection", (reason) => {
|
|
106
|
+
const text = reason instanceof Error ? reason.message : String(reason);
|
|
107
|
+
try {
|
|
108
|
+
process.stdout.write(`\nError: ${text}\n`);
|
|
109
|
+
}
|
|
110
|
+
catch { /* stream gone */ }
|
|
111
|
+
});
|
|
112
|
+
if (!hasArgs && interactive && !useLegacyRepl) {
|
|
113
|
+
// ── Interactive Ink UI ───────────────────────────────────────────────────
|
|
114
|
+
if (modeFlag)
|
|
115
|
+
updateConfig({ permissionMode: modeFlag });
|
|
116
|
+
const { runApp } = await import("./ui/app.js");
|
|
117
|
+
runApp();
|
|
118
|
+
}
|
|
119
|
+
else if (!hasArgs) {
|
|
120
|
+
// ── Legacy readline REPL (odysx --legacy-repl, or non-TTY stdin) ────────
|
|
121
|
+
// Same alternate-screen behavior as the Ink UI: hide the tab's prior
|
|
122
|
+
// content while running, restore the primary buffer on exit. Signal
|
|
123
|
+
// handlers re-raise so Ctrl+C/kill actually terminates.
|
|
124
|
+
enterAltScreen();
|
|
125
|
+
const config = getConfig();
|
|
126
|
+
let agentId = config.model ?? "master";
|
|
127
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
128
|
+
const sessionId = randomUUID();
|
|
129
|
+
const messages = [];
|
|
130
|
+
// External providers need the transcript on every turn; the platform keeps
|
|
131
|
+
// its own history keyed by session id.
|
|
132
|
+
const wireHistory = () => messages.map((m) => ({ role: m.role, content: m.text }));
|
|
133
|
+
const readline = await import("node:readline");
|
|
134
|
+
const rl = readline.createInterface({
|
|
135
|
+
input: process.stdin,
|
|
136
|
+
output: process.stdout,
|
|
137
|
+
prompt: promptStr(),
|
|
138
|
+
historySize: 200,
|
|
139
|
+
});
|
|
140
|
+
// Piped stdin (CI, `printf … | odysx`) reaches EOF immediately. If lines are
|
|
141
|
+
// handled as they arrive, an async handler is still running when `close`
|
|
142
|
+
// fires and its output is lost. Buffer every line and drain them in order.
|
|
143
|
+
const piped = !process.stdin.isTTY;
|
|
144
|
+
const pendingLines = [];
|
|
145
|
+
if (piped)
|
|
146
|
+
rl.removeAllListeners("line");
|
|
147
|
+
// Prompt function — meaningless without a terminal, so piped mode prints a
|
|
148
|
+
// plain marker only when it is actually waiting on the user.
|
|
149
|
+
const promptUser = () => {
|
|
150
|
+
if (!piped)
|
|
151
|
+
rl.prompt();
|
|
152
|
+
};
|
|
153
|
+
// Startup — the alt-buffer switch above already gave us a clean slate, so
|
|
154
|
+
// just print the header (no \x1Bc full-terminal reset: it would re-enable
|
|
155
|
+
// the hardware cursor and clear modes).
|
|
156
|
+
process.stdout.write(header(config) + "\n\n");
|
|
157
|
+
process.stdout.write(helpText());
|
|
158
|
+
if (!config.apiKey && !config.token) {
|
|
159
|
+
messages.push({
|
|
160
|
+
role: "assistant",
|
|
161
|
+
text: "Welcome. I'm your agent. Set your API key with:\n odysx auth set-key <key>\n\nOr type /help for commands.",
|
|
162
|
+
});
|
|
163
|
+
messages.forEach(m => {
|
|
164
|
+
process.stdout.write(formatMessage(m.role, m.text) + "\n");
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
// Piped stdin delivers every buffered line at once, so handlers can overlap
|
|
168
|
+
// the async exit; `closing` stops work once a quit is in flight.
|
|
169
|
+
let closing = false;
|
|
170
|
+
// Trust gate for the legacy/piped path. Piped stdin has no one to ask, so an
|
|
171
|
+
// untrusted workspace refuses rather than silently granting access. A TTY
|
|
172
|
+
// gets the same y/N question as the Ink UI; a declined answer exits.
|
|
173
|
+
if (!isFolderTrusted()) {
|
|
174
|
+
const root = getWorkspaceRoot();
|
|
175
|
+
if (piped) {
|
|
176
|
+
process.stdout.write(`Untrusted workspace: ${root}\nRun \`odysx\` in a terminal to trust it.\n`);
|
|
177
|
+
exitWith(1);
|
|
178
|
+
}
|
|
179
|
+
const answer = await new Promise((resolve) => {
|
|
180
|
+
rl.question(`Trust this folder? Codemind can read, edit, and run commands here.\n ${root}\n[1] Yes, I trust this folder [2] No, exit (1/2): `, resolve);
|
|
181
|
+
});
|
|
182
|
+
if (answer.trim() !== "1" && answer.trim().toLowerCase() !== "y") {
|
|
183
|
+
process.stdout.write("No — exiting.\n");
|
|
184
|
+
rl.close();
|
|
185
|
+
exitWith(0);
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
trustFolder();
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
process.stdout.write(`Could not save folder trust: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
192
|
+
rl.close();
|
|
193
|
+
exitWith(1);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (modeFlag)
|
|
197
|
+
updateConfig({ permissionMode: modeFlag });
|
|
198
|
+
// Token accounting, shared with /usage.
|
|
199
|
+
const usageRef = { current: { requests: 0, promptTokens: 0, completionTokens: 0 } };
|
|
200
|
+
// Helper to handle a user line asynchronously
|
|
201
|
+
const handleLine = async (input) => {
|
|
202
|
+
if (closing)
|
|
203
|
+
return;
|
|
204
|
+
const msg = input.trim();
|
|
205
|
+
if (!msg) {
|
|
206
|
+
promptUser();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (msg === "/quit" || msg === "/exit" || msg === "/q") {
|
|
210
|
+
// `closing` guards a second "line" event racing the async flush in
|
|
211
|
+
// exitWith (piped input delivers every line at once).
|
|
212
|
+
closing = true;
|
|
213
|
+
rl.close();
|
|
214
|
+
exitWith(0);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (msg === "/help" || msg === "?") {
|
|
218
|
+
process.stdout.write(helpText() + "\n");
|
|
219
|
+
promptUser();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (msg === "/clear") {
|
|
223
|
+
clearViewport(); // viewport wipe only — no mode resets; a no-op when piped
|
|
224
|
+
process.stdout.write(header(config) + "\n\n");
|
|
225
|
+
process.stdout.write(helpText());
|
|
226
|
+
messages.length = 0;
|
|
227
|
+
if (!config.apiKey && !config.token) {
|
|
228
|
+
messages.push({ role: "assistant", text: "Welcome. Set your API key..." });
|
|
229
|
+
messages.forEach(m => process.stdout.write(formatMessage(m.role, m.text) + "\n"));
|
|
230
|
+
}
|
|
231
|
+
promptUser();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (msg === "/status") {
|
|
235
|
+
process.stdout.write(`Session: ${sessionId}\nAgent: ${agentId}\nAuth: ${config.apiKey ? "api-key" : config.token ? "jwt" : "none"}\n`);
|
|
236
|
+
promptUser();
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (msg.startsWith("/agent ")) {
|
|
240
|
+
agentId = msg.split(" ")[1];
|
|
241
|
+
process.stdout.write(`Agent set to: ${agentId}\n`);
|
|
242
|
+
promptUser();
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (msg.startsWith("/model ")) {
|
|
246
|
+
updateConfig({ model: msg.split(" ")[1] });
|
|
247
|
+
process.stdout.write(`Model updated\n`);
|
|
248
|
+
promptUser();
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (msg === "/compact") {
|
|
252
|
+
messages.length = 0;
|
|
253
|
+
process.stdout.write("Context cleared\n");
|
|
254
|
+
promptUser();
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (msg === "/export") {
|
|
258
|
+
const fn = `odysx-session-${sessionId.slice(0, 8)}.json`;
|
|
259
|
+
writeFileSync(fn, JSON.stringify({ sessionId, agentId, messages }, null, 2));
|
|
260
|
+
process.stdout.write(`Exported to: ${fn}\n`);
|
|
261
|
+
promptUser();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// Any other slash command goes through the same table the Ink UI uses, so
|
|
265
|
+
// the two frontends never drift. Commands that need an overlay say so
|
|
266
|
+
// instead of being sent to the model as prose.
|
|
267
|
+
if (msg.startsWith("/")) {
|
|
268
|
+
const { runCommand, DISPATCHABLE_COMMANDS } = await import("./ui/commands/runCommand.js");
|
|
269
|
+
const name = msg.slice(1).split(/\s+/)[0].toLowerCase();
|
|
270
|
+
if (!DISPATCHABLE_COMMANDS.includes(name)) {
|
|
271
|
+
process.stdout.write(`Unknown command: /${name}. Try /help.\n`);
|
|
272
|
+
promptUser();
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
// These render overlays or use state that lives in the Ink UI. /agent and
|
|
276
|
+
// /sessions still work with an argument, so only block the bare form.
|
|
277
|
+
// /mcp, /prompts, /skills and /tasks/ /ralph print to the transcript and
|
|
278
|
+
// work fine here.
|
|
279
|
+
const overlayOnly = ["signin", "keys"];
|
|
280
|
+
const needsUi = overlayOnly.includes(name) || (["agent", "sessions"].includes(name) && !msg.includes(" "));
|
|
281
|
+
if (needsUi) {
|
|
282
|
+
process.stdout.write(`/${name} needs the interactive UI — run \`odysx\` in a terminal.\n`);
|
|
283
|
+
promptUser();
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const ctx = {
|
|
287
|
+
addMessage: (text) => process.stdout.write(text + "\n"),
|
|
288
|
+
setMessages: () => { },
|
|
289
|
+
sessionId: () => sessionId,
|
|
290
|
+
agentId,
|
|
291
|
+
config: { apiKey: config.apiKey ?? undefined, token: config.token ?? undefined, apiUrl: config.apiUrl },
|
|
292
|
+
openAgentPicker: () => process.stdout.write("/agent needs the interactive UI\n"),
|
|
293
|
+
setAgentId: (id) => { agentId = id; },
|
|
294
|
+
resumeSession: () => process.stdout.write("/sessions needs the interactive UI\n"),
|
|
295
|
+
openSessionPicker: () => process.stdout.write("/sessions needs the interactive UI\n"),
|
|
296
|
+
openKeysPanel: async () => process.stdout.write("/keys needs the interactive UI\n"),
|
|
297
|
+
setPendingOp: () => { },
|
|
298
|
+
resetTranscript: () => { messages.length = 0; },
|
|
299
|
+
newSession: () => {
|
|
300
|
+
messages.length = 0;
|
|
301
|
+
process.stdout.write("New session requested — restart `odysx` for a fresh server conversation.\n");
|
|
302
|
+
},
|
|
303
|
+
usageRef,
|
|
304
|
+
abortStream: () => { },
|
|
305
|
+
requestExit: () => { closing = true; rl.close(); exitWith(0); },
|
|
306
|
+
setAuthMode: () => process.stdout.write("/signin needs the interactive UI\n"),
|
|
307
|
+
setAuthIndex: () => { },
|
|
308
|
+
};
|
|
309
|
+
// Awaited: the handlers hit the network, and the piped drain loop below
|
|
310
|
+
// exits the process as soon as this returns.
|
|
311
|
+
await runCommand(msg, ctx, messages.map((m) => ({ ...m })));
|
|
312
|
+
promptUser();
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (!config.apiKey && !config.token) {
|
|
316
|
+
process.stdout.write("Authentication required. Run: odysx auth set-key <key>\n");
|
|
317
|
+
promptUser();
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
messages.push({ role: "user", text: msg });
|
|
321
|
+
process.stdout.write(formatMessage("user", msg) + "\n\n");
|
|
322
|
+
process.stdout.write("Agent is typing...\n\n");
|
|
323
|
+
try {
|
|
324
|
+
usageRef.current.requests += 1;
|
|
325
|
+
let reply = "";
|
|
326
|
+
await streamTurn(msg, {
|
|
327
|
+
agentId,
|
|
328
|
+
sessionId,
|
|
329
|
+
history: wireHistory(), // before this turn's user message is appended
|
|
330
|
+
onToken: (token) => {
|
|
331
|
+
reply += token;
|
|
332
|
+
process.stdout.write(token);
|
|
333
|
+
},
|
|
334
|
+
onUsage: (u) => {
|
|
335
|
+
usageRef.current.promptTokens += u.promptTokens;
|
|
336
|
+
usageRef.current.completionTokens += u.completionTokens;
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
messages.push({ role: "assistant", text: reply });
|
|
340
|
+
process.stdout.write("\n\n");
|
|
341
|
+
promptUser();
|
|
342
|
+
}
|
|
343
|
+
catch (err) {
|
|
344
|
+
process.stdout.write(`\nError: ${err}\n\n`);
|
|
345
|
+
promptUser();
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
if (piped) {
|
|
349
|
+
rl.on("line", (line) => pendingLines.push(line));
|
|
350
|
+
rl.on("close", () => {
|
|
351
|
+
// Drain sequentially; each handler awaits its own work, so output order
|
|
352
|
+
// matches input order and nothing is truncated by the process exiting.
|
|
353
|
+
void (async () => {
|
|
354
|
+
for (const line of pendingLines) {
|
|
355
|
+
if (closing)
|
|
356
|
+
break;
|
|
357
|
+
await handleLine(line);
|
|
358
|
+
}
|
|
359
|
+
exitWith(0);
|
|
360
|
+
})();
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
rl.on("line", handleLine);
|
|
365
|
+
rl.on("close", () => exitWith(0));
|
|
366
|
+
promptUser();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
370
|
+
// ── CLI routing ──────────────────────────────────────────────────────────
|
|
371
|
+
if (modeFlag)
|
|
372
|
+
updateConfig({ permissionMode: modeFlag });
|
|
373
|
+
const program = buildProgram();
|
|
374
|
+
program.addCommand(new Command("help")
|
|
375
|
+
.description("Show help")
|
|
376
|
+
.argument("[command]", "Command to get help for")
|
|
377
|
+
.action((cmdName) => {
|
|
378
|
+
if (cmdName) {
|
|
379
|
+
const cmd = program.commands.find((c) => c.name() === cmdName || c.aliases().includes(cmdName));
|
|
380
|
+
if (cmd)
|
|
381
|
+
cmd.help();
|
|
382
|
+
else {
|
|
383
|
+
console.error("Unknown: " + cmdName);
|
|
384
|
+
exitWith(1);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
program.help();
|
|
389
|
+
}
|
|
390
|
+
}));
|
|
391
|
+
program.parse(process.argv);
|
|
392
|
+
}
|
|
393
|
+
//# sourceMappingURL=index.js.map
|
package/dist/ui/app.d.ts
ADDED