@mindmux/cli 0.1.2 → 0.1.4
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 +1 -0
- package/bin/mmx.mjs +2 -1
- package/docs/README.md +1 -0
- package/docs/agent-install.md +92 -0
- package/docs/setup.md +4 -2
- package/package.json +1 -1
- package/src/clean.mjs +29 -4
- package/src/cli.mjs +23 -2
- package/src/integrations.mjs +29 -5
- package/src/login-lock.mjs +60 -0
- package/src/login-session.mjs +62 -0
- package/src/login-worker.mjs +20 -0
- package/src/prompts.mjs +2 -1
- package/src/setup.mjs +45 -10
- package/src/update.mjs +1 -1
package/README.md
CHANGED
|
@@ -50,6 +50,7 @@ To start setup again, `mmx clean` resets local integration, binding, local Brain
|
|
|
50
50
|
- [Installation](docs/installation.md) — npm, pnpm and requirements.
|
|
51
51
|
- [Setup and maintenance](docs/setup.md) — agent trust, upgrades, repair and cleanup.
|
|
52
52
|
- [Brain commands](docs/brain.md) — query, write and index operations.
|
|
53
|
+
- [Agent-assisted installation](docs/agent-install.md) — non-interactive setup for agents.
|
|
53
54
|
- [Cloud login](docs/cloud.md) — authentication and binding.
|
|
54
55
|
- [Agent behavior](docs/agents.md) — hooks, memory reviews and limits.
|
|
55
56
|
- [Development](docs/development.md) — tests and verification.
|
package/bin/mmx.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { notifyUpdate } from '../src/update.mjs';
|
|
|
3
3
|
import { main } from '../src/cli.mjs';
|
|
4
4
|
await notifyUpdate();
|
|
5
5
|
await main().catch(error => {
|
|
6
|
-
console.
|
|
6
|
+
if (process.argv.some(arg => ['--non-interactive', '-agent'].includes(arg))) console.log(JSON.stringify({ status: 'error', installed: false, error: error.message }));
|
|
7
|
+
else console.error(`mmx: ${error.message}`);
|
|
7
8
|
process.exitCode = 1;
|
|
8
9
|
});
|
package/docs/README.md
CHANGED
|
@@ -8,6 +8,7 @@ Start with `mmx setup` in your project. Use these guides when you need more deta
|
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| [Installation](installation.md) | Requirements, pnpm/npm source installation, path changes |
|
|
10
10
|
| [Setup and maintenance](setup.md) | Setup options, Codex trust, status, repair, switching, migration and reset |
|
|
11
|
+
| [Agent-assisted installation](agent-install.md) | Non-interactive setup protocol, authorization, user choices and verification |
|
|
11
12
|
| [Cloud login](cloud.md) | Authentication, Workspaces, Projects and explicit binding |
|
|
12
13
|
| [Brain commands](brain.md) | Reading, writing, indexing, concurrency and low-level MCP access |
|
|
13
14
|
| [Agent behavior](agents.md) | Retrieval, language, hooks, Codex reviews and known limits |
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Agent-assisted installation
|
|
2
|
+
|
|
3
|
+
[Documentation](README.md)
|
|
4
|
+
|
|
5
|
+
Instructions for an agent installing MindMux in the user's current project. The user can delegate this workflow in one message. Browser authorization, Workspace/Project selection, creation consent and host trust still belong to the user. Never treat a successful configuration check as proof that the host loaded the new tools.
|
|
6
|
+
|
|
7
|
+
## Install once
|
|
8
|
+
|
|
9
|
+
1. Identify the intended project directory and current host agent (`codex` or `claude-code`). If unclear, ask. Do not configure the user's home directory or unrelated hosts.
|
|
10
|
+
2. Check Node.js >=22 and macOS/Linux. Native Windows shells are not supported.
|
|
11
|
+
3. Check `command -v mmx` and `mmx --version`. Respect an existing installation's manager and source. Do not replace a source checkout or install a second global copy automatically.
|
|
12
|
+
4. For a new installation, use `npm install -g @mindmux/cli@latest` or `pnpm add -g @mindmux/cli@latest`. Do not install a project dependency or use a temporary `npx` installation: generated launchers need a persistent executable path. Do not use `sudo` automatically. Resolve missing global bin/PATH configuration before continuing.
|
|
13
|
+
5. An older installation without the protocol below needs an upgrade through its existing package manager. Newer installations can use `mmx update`.
|
|
14
|
+
|
|
15
|
+
## Drive setup without a terminal menu
|
|
16
|
+
|
|
17
|
+
Run commands in the intended project (or provide an explicit `--project PATH`). Start with:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
mmx setup -agent --agent codex
|
|
21
|
+
# For Claude Code, use --agent claude-code instead.
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`-agent` is shorthand for `--non-interactive --json` and never opens a terminal menu. It is distinct from `--agent NAME`, which selects the host integration. Plain `mmx setup` retains its interactive wizard. The long form remains supported. Inspect `status` and `step` after every invocation. Input-required responses exit zero and always report `installed: false`; they are not success. Errors exit nonzero with `status: "error"`. Preserve the selected agent/server/project flags across retries. Pass IDs as separate, properly quoted process arguments; never build executable shell text from returned names or URLs.
|
|
25
|
+
|
|
26
|
+
| Response | Next action |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| `input_required / select_agent` | Identify the current host, or ask the user, then pass `--agent`. |
|
|
29
|
+
| `input_required / authorize` | Inspect `authorization.status`. For `starting`, poll the same setup after a short delay. For `authorization_required`, show/open `authorizationUrl` and ask the user to approve in their browser; poll after approval. Never request tokens in chat. |
|
|
30
|
+
| `input_required / select_workspace` | Multiple Workspaces are available. Present `choices` through the host choice tool when available, then rerun with the selected `--workspace-id`. With exactly one accessible Workspace, CLI skips this step and includes its ID/name in the Project response. Do not ask again. |
|
|
31
|
+
| `input_required / select_project` | Present existing Projects first and the create option last, including its `suggestedName`. For an existing Project, rerun with its `--brain-id` and **omit `--workspace-id`**. Even one existing Project still needs a choice, because creating a different Project is valid. |
|
|
32
|
+
| `input_required / name_project` | There are no Projects. Ask for a name directly, offering `suggestedName` as an editable default. Do not display an empty Project selector or create automatically. |
|
|
33
|
+
| `input_required / confirm_project_creation` | Ask the user to approve the Workspace and new Project name; all Workspace members can access it. Only after approval pass `--workspace-id ID --name NAME --confirm`. `--yes` does not grant creation consent. |
|
|
34
|
+
| `input_required / confirm_migration` | Explain the configuration conflict and obtain consent before adding `--migrate`. Do not delete unrelated MCP servers or uninstall global brain.md integrations. |
|
|
35
|
+
| `error` | Inspect `stage`, `error`, `next`, and optional `recovery`. Resolve the cause. Never convert network/server failures into repeated login or project creation. |
|
|
36
|
+
| `ready` | Check `installed` and `mcp.connected`/`mcp.recall`, then run online doctor below. Configuration is ready; host restart/trust remain outstanding. |
|
|
37
|
+
|
|
38
|
+
### Prefer native choices, keep conversation as fallback
|
|
39
|
+
|
|
40
|
+
Read `interaction` in input-required responses. Prefer an actually available, permitted question tool: Claude Code's `AskUserQuestion`, or Codex's `request_user_input` / `request_user_input_async`. Tool names are hints, not a promise that a client exposes them. Follow the host's restrictions, especially for confirmations; never invent a tool call, switch into Plan mode, or edit global host configuration just to get a menu. CLI JSON cannot itself draw a native host dialog.
|
|
41
|
+
|
|
42
|
+
Use the user's language for questions, descriptions and the create-option label; preserve Workspace/Project names exactly. Show the suggested new name after the create label, for example “新建项目:my-project”. A suggested name is not a confirmed target. Offer the suggested name and a way to enter another name, using the host's custom-answer support where available. Creation still requires the separate shared-Workspace confirmation.
|
|
43
|
+
|
|
44
|
+
Respect the question tool's option-count limits. Paginate long lists while retaining every choice, or use a conversational selector when pagination is unsuitable; never silently drop Workspaces/Projects or map two identically displayed names to an arbitrary ID. Disambiguate duplicate names with IDs in descriptions when needed. Do not add unsupported free-text-only questions to a tool that requires predefined options.
|
|
45
|
+
|
|
46
|
+
If no suitable native tool is exposed, ask one concise conversational question, accepting a name or number. Present it once: do not ask through a tool and then repeat the same numbered list in the final response. While waiting for an asynchronous question, do not select on the user's behalf. Cancellation or dismissal does not authorize a target or creation.
|
|
47
|
+
|
|
48
|
+
Codex availability varies by version, mode and client. On the locally checked Codex CLI 0.167.1, `codex features list` reports `default_mode_request_user_input` as under development and disabled by default. A user can explicitly opt into that experimental feature, but it is not required for MindMux setup and installers must not enable it silently. For that checked CLI version, a user can start a new session with `codex --enable default_mode_request_user_input`; this is a per-invocation experimental opt-in, not a required global setting. Recheck the actual tool surface; do not assume every Codex app or embedded client behaves like the CLI.
|
|
49
|
+
|
|
50
|
+
Workspace edge cases: no accessible Workspaces is an error requiring the user to resolve Cloud access; one is selected automatically and named in the next step; multiple require choice. An explicitly supplied unavailable Workspace must fail rather than fall back to a different one. An existing binding is reused unless an explicit target is supplied. The CLI derives a new-name suggestion from the project directory, avoids existing names case-insensitively, and caps it at 200 characters; the directory never selects an existing Cloud Brain.
|
|
51
|
+
|
|
52
|
+
After starting authorization, open/show its URL once. Respect `pollAfterMs`; after the user says approval is complete, allow a few delayed polls for the callback and token exchange before claiming it failed. Do not repeatedly ask for approval while the same live authorization is pending. Report failed/expired authorization and explicitly retry instead of polling forever.
|
|
53
|
+
|
|
54
|
+
For new Projects, first call setup with `--workspace-id ID --name NAME` to obtain the confirmation response. For existing bindings, setup reuses the binding unless a new explicit target is supplied; do not silently switch it.
|
|
55
|
+
|
|
56
|
+
## Authorization survives tool-call completion
|
|
57
|
+
|
|
58
|
+
The CLI starts a detached worker to hold the loopback callback and OAuth lock for up to three minutes. Repeated setup calls reuse that pending session. The worker stores private status and credentials under `MINDMUX_HOME` with mode `0600`, outside the project. Only the authorization URL and public status are returned; no tokens or PKCE verifier appear in the response.
|
|
59
|
+
|
|
60
|
+
For explicit inspection:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
mmx login --non-interactive --status check --json
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
If the session fails/expires or its worker is terminated, explain the failure and explicitly retry:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
mmx login --non-interactive --json
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Then resume the same setup. Poll with a delay, never in a tight loop. A runtime that kills every background child cannot preserve the callback; use a persistent terminal session with `mmx login` in that environment. SSH/container/remote environments must also make the loopback callback reachable from the approving browser. Do not claim remote authorization is complete when it is not.
|
|
73
|
+
|
|
74
|
+
The same `--server URL` must be supplied when using a non-default server. Background login intentionally does not open a browser automatically. Pending authorization prevents logout or clean from erasing credentials while the worker is active; `clean --keep-login` can still reset only the project.
|
|
75
|
+
|
|
76
|
+
## Validate and hand back
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
mmx doctor --online --json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Require `healthy: true`, accessible Brain and successful MCP recall. Report the selected Project and host briefly. Ask the user to restart that host and approve project/MCP/hook trust; Codex hook trust is reviewed in `/hooks`. The installing conversation may not load new MCP tools until restart.
|
|
83
|
+
|
|
84
|
+
Setup retries reuse a known created Project. If creation returned an unknown outcome, list Projects and reconcile the target before retrying; do not blindly recreate it. Failed configuration/probes roll back project configuration while retaining a created Cloud Project and recovery information.
|
|
85
|
+
|
|
86
|
+
## Local protocol test
|
|
87
|
+
|
|
88
|
+
Only when the user explicitly requests a local Brain, add `--local` and omit Cloud selection flags. This uses the same non-interactive protocol without browser login.
|
|
89
|
+
|
|
90
|
+
For release validation, run `node scripts/verify-agent-install.mjs`. It packs and globally installs the current source in an isolated temporary prefix, drives OAuth against a local fixture, selects a Cloud Project, installs both host integrations, and runs online doctor. It simulates user approval/selection and makes no production Cloud changes. This is protocol validation, not a live-model or production OAuth test.
|
|
91
|
+
|
|
92
|
+
Question-tool reference: [Claude Code approvals and user input](https://code.claude.com/docs/en/agent-sdk/user-input). Codex experiment availability above was checked with the local CLI feature list, not assumed from a stable cross-client API.
|
package/docs/setup.md
CHANGED
|
@@ -120,8 +120,10 @@ mmx clean --keep-login
|
|
|
120
120
|
mmx clean --yes --json
|
|
121
121
|
```
|
|
122
122
|
|
|
123
|
-
Cleanup removes managed MCP entries, instructions and hooks, project binding, session caches, local Brain data, and this project's configuration backups. By default, it also removes **all CLI login credentials and the saved server setting** from the current `MINDMUX_HOME`, which signs out other projects sharing that CLI login. `--keep-login` retains both. This removes local credentials; it does not revoke server grants or end a browser session.
|
|
123
|
+
Cleanup removes managed MCP entries, instructions and hooks, project binding, session caches, local Brain data, the shared update-check cache, and this project's configuration backups. By default, it also removes **all CLI login credentials and the saved server setting** from the current `MINDMUX_HOME`, which signs out other projects sharing that CLI login. `--keep-login` retains both. This removes local credentials; it does not revoke server grants or end a browser session.
|
|
124
124
|
|
|
125
125
|
**Cloud Projects and Brains are always kept.** Existing cloud Projects can be selected in the next setup. Unrelated agent configuration, custom instructions, unknown preference fields, and other projects' backups are preserved. Empty generated files are removed, and an unchanged brain.md scaffold is removed with local Brain data. Git ignore rules are retained.
|
|
126
126
|
|
|
127
|
-
Cleanup
|
|
127
|
+
Cleanup removes only CLI-owned commands from mixed hook groups, preserving user handlers and group settings. Hook ownership can be recovered from the saved setup launcher if the integration receipt is missing. If the MCP setup ownership record is missing, cleanup stops before deleting data instead of guessing the original configuration.
|
|
128
|
+
|
|
129
|
+
Cleanup refuses modified managed MCP entries, unsafe paths, symbolic links, pending browser authorization, and active setup/write/authentication/update locks. Stop active agents before resetting. A configured local Brain outside the project requires `--include-external-data`; its path is shown in the confirmation. Local data deletion cannot be undone by `remove`.
|
package/package.json
CHANGED
package/src/clean.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { removeStaleLoginLaunchLock } from './login-lock.mjs';
|
|
2
|
+
import { pendingLogin } from './login-session.mjs';
|
|
1
3
|
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, rmSync, rmdirSync, realpathSync } from 'node:fs';
|
|
2
4
|
import { dirname, join, resolve, relative, isAbsolute } from 'node:path';
|
|
3
5
|
import { homedir } from 'node:os';
|
|
4
6
|
import { createHash } from 'node:crypto';
|
|
5
7
|
import { homeDir, preferences, preferencesPath, readJson, writeJson } from './storage.mjs';
|
|
6
8
|
import { AGENTS, connect, integrationFiles, managedBlock } from './integrations.mjs';
|
|
7
|
-
import { guardPath, planHost } from './host-config.mjs';
|
|
9
|
+
import { guardPath, planHost, hostState } from './host-config.mjs';
|
|
8
10
|
import { removeSetup } from './setup.mjs';
|
|
9
11
|
import { brainPackage } from './brain.mjs';
|
|
10
12
|
import { createSetupPrompts } from './prompts.mjs';
|
|
@@ -27,9 +29,19 @@ function cleanPlan(root, flags) {
|
|
|
27
29
|
const prefs = preferences(root);
|
|
28
30
|
const setup = readJson(join(runtime, 'setup.json'), {});
|
|
29
31
|
const integrations = readJson(join(runtime, 'integrations.json'), {});
|
|
30
|
-
const
|
|
32
|
+
const markedAgents = AGENTS.filter(agent => {
|
|
33
|
+
const { rules } = integrationFiles(root, agent); guardPath(root, rules);
|
|
34
|
+
return existsSync(rules) && readFileSync(rules, 'utf8').includes('<!-- BEGIN mindmux-cli -->');
|
|
35
|
+
});
|
|
36
|
+
const agents = [...new Set([...Object.keys(setup.agents || {}), ...Object.keys(integrations), ...markedAgents])];
|
|
31
37
|
for (const agent of agents) {
|
|
32
38
|
if (!AGENTS.includes(agent)) throw new Error(`Unknown integration in cleanup manifest: ${agent}`);
|
|
39
|
+
if (agent !== 'cursor' && !setup.agents?.[agent]) {
|
|
40
|
+
const state = hostState(root, agent), args = state.entry?.args;
|
|
41
|
+
if (state.text.includes('# BEGIN mindmux-cli MCP') || (Array.isArray(args) && args.length === 5 && args[1] === '--project' && args[2] === root && args[3] === 'mcp' && args[4] === 'serve')) {
|
|
42
|
+
throw new Error(`Setup ownership record is missing for ${state.path}. Restore .mindmux/cli/setup.json from its configuration backup before cleaning; the original MCP configuration cannot be inferred safely.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
33
45
|
if (setup.agents?.[agent]) planHost(root, agent, setup.agents[agent], { remove: true });
|
|
34
46
|
const files = integrationFiles(root, agent);
|
|
35
47
|
for (const file of Object.values(files)) guardPath(root, file);
|
|
@@ -47,7 +59,7 @@ function cleanPlan(root, flags) {
|
|
|
47
59
|
if (!existsSync(join(path, 'index.md')) || !readFileSync(join(path, 'index.md'), 'utf8').startsWith('# Brain Index')) throw new Error(`Refusing to delete an unrecognized Brain directory: ${path}`);
|
|
48
60
|
}
|
|
49
61
|
const backup = join(home, 'backups', createHash('sha256').update(root).digest('hex'));
|
|
50
|
-
const paths = [preferencesPath(root), runtime, backup, ...data];
|
|
62
|
+
const paths = [preferencesPath(root), runtime, backup, join(home, 'update-check.json'), ...data];
|
|
51
63
|
if (!flags['keep-login']) paths.push(join(home, 'auth'), join(home, 'config.json'));
|
|
52
64
|
for (const path of paths) noSymlinks(path);
|
|
53
65
|
return { root, home, runtime, prefs, setup, agents, data, backup };
|
|
@@ -55,6 +67,7 @@ function cleanPlan(root, flags) {
|
|
|
55
67
|
|
|
56
68
|
export async function clean(root, flags = {}, dependencies = {}) {
|
|
57
69
|
const plan = cleanPlan(root, flags);
|
|
70
|
+
if (!flags['keep-login'] && pendingLogin()) throw new Error('Browser authorization is pending. Complete it or wait for it to expire before clearing login.');
|
|
58
71
|
const interactive = Boolean(dependencies.prompts || (process.stdin.isTTY && process.stderr.isTTY));
|
|
59
72
|
if (!flags.yes) {
|
|
60
73
|
if (!interactive) throw new Error('clean deletes local data. Run interactively or pass --yes to confirm.');
|
|
@@ -73,7 +86,18 @@ export async function clean(root, flags = {}, dependencies = {}) {
|
|
|
73
86
|
const current = cleanPlan(root, flags);
|
|
74
87
|
if (JSON.stringify(current) !== JSON.stringify(plan)) throw new Error('Configuration changed during confirmation. Run clean again.');
|
|
75
88
|
if (existsSync(join(plan.runtime, 'write.lock'))) throw new Error('A local Brain write is active. Finish it before running clean.');
|
|
76
|
-
if (
|
|
89
|
+
if (existsSync(join(plan.home, 'update.lock'))) throw new Error('A CLI update is active. Finish it before running clean.');
|
|
90
|
+
if (!flags['keep-login']) {
|
|
91
|
+
// Authorization may have started while the confirmation prompt was open.
|
|
92
|
+
if (pendingLogin()) throw new Error('Browser authorization is pending. Complete it or wait for it to expire before clearing login.');
|
|
93
|
+
const auth = join(plan.home, 'auth');
|
|
94
|
+
if (existsSync(auth)) {
|
|
95
|
+
for (const name of readdirSync(auth)) {
|
|
96
|
+
if (/^login-[a-f0-9]{64}\.json\.launch\.lock$/.test(name)) removeStaleLoginLaunchLock(join(auth, name));
|
|
97
|
+
}
|
|
98
|
+
if (readdirSync(auth).some(name => name.endsWith('.lock'))) throw new Error('CLI authentication is busy. Stop active agents or finish login before running clean.');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
77
101
|
mkdirSync(plan.runtime, { recursive: true, mode: 0o700 });
|
|
78
102
|
const lock = join(plan.runtime, 'setup.lock');
|
|
79
103
|
try { mkdirSync(lock); } catch { throw new Error(`Another setup/remove/clean is active: ${lock}`); }
|
|
@@ -104,6 +128,7 @@ export async function clean(root, flags = {}, dependencies = {}) {
|
|
|
104
128
|
if (plan.data.length && existsSync(scaffold) && readFileSync(scaffold, 'utf8') === readFileSync(original, 'utf8')) rmSync(scaffold);
|
|
105
129
|
for (const path of plan.data) rmSync(path, { recursive: true, force: true });
|
|
106
130
|
rmSync(plan.backup, { recursive: true, force: true });
|
|
131
|
+
rmSync(join(plan.home, 'update-check.json'), { force: true });
|
|
107
132
|
if (!flags['keep-login']) {
|
|
108
133
|
rmSync(join(plan.home, 'auth'), { recursive: true, force: true });
|
|
109
134
|
rmSync(join(plan.home, 'config.json'), { force: true });
|
package/src/cli.mjs
CHANGED
|
@@ -16,6 +16,9 @@ Setup:
|
|
|
16
16
|
mmx setup [--agent claude-code,codex] login, choose Brain, install MCP + rules/hooks
|
|
17
17
|
mmx setup --local --agent codex --yes local Brain without Cloud login
|
|
18
18
|
mmx setup --json return detailed setup results as JSON
|
|
19
|
+
mmx setup -agent resumable Agent setup (alias: --non-interactive --json)
|
|
20
|
+
mmx login --non-interactive --json start/reuse background browser authorization
|
|
21
|
+
mmx login --status check --non-interactive --json inspect background authorization
|
|
19
22
|
mmx update [--check] [--yes] [--json] check for releases or upgrade this global installation
|
|
20
23
|
mmx status [--online] [--json] show configuration and observed activity
|
|
21
24
|
mmx switch [--brain-id ID | --local] choose another Brain; keep login and data
|
|
@@ -80,8 +83,18 @@ function cloudVersion(value) {
|
|
|
80
83
|
|
|
81
84
|
export async function main(argv = process.argv.slice(2)) {
|
|
82
85
|
const options = Object.fromEntries(['project', 'agent', 'brain-id', 'server', 'workspace-id', 'name', 'description', 'id', 'title', 'category', 'status', 'source', 'expected-version', 'change-kind', 'summary', 'kind', 'args', 'review-token', 'outcome', 'reason', 'manager'].map(key => [key, { type: 'string' }]));
|
|
83
|
-
for (const key of ['local', 'online', 'no-open', 'confirm', 'help', 'version', 'yes', 'migrate', 'json', 'keep-login', 'include-external-data', 'fix', 'check', 'refresh-integrations']) options[key] = { type: 'boolean' };
|
|
84
|
-
|
|
86
|
+
for (const key of ['local', 'online', 'no-open', 'confirm', 'help', 'version', 'yes', 'migrate', 'json', 'keep-login', 'include-external-data', 'fix', 'check', 'refresh-integrations', 'non-interactive']) options[key] = { type: 'boolean' };
|
|
87
|
+
// -agent is an exact single-dash alias, distinct from --agent NAME.
|
|
88
|
+
// Do not rewrite option values or positional content after --.
|
|
89
|
+
const args = [];
|
|
90
|
+
for (let i = 0; i < argv.length; i++) {
|
|
91
|
+
const arg = argv[i];
|
|
92
|
+
if (arg === '--') { args.push(...argv.slice(i)); break; }
|
|
93
|
+
args.push(arg === '-agent' ? '--non-interactive' : arg);
|
|
94
|
+
if (arg.startsWith('--') && options[arg.slice(2)]?.type === 'string' && i + 1 < argv.length) args.push(argv[++i]);
|
|
95
|
+
}
|
|
96
|
+
const { values: flags, positionals: pos } = parseArgs({ args, options, allowPositionals: true, strict: true });
|
|
97
|
+
if (flags['non-interactive']) flags.json = true;
|
|
85
98
|
if (flags.version) { console.log(VERSION); return; }
|
|
86
99
|
if (flags.help || pos[0] === 'help' || (!pos.length && (!process.stdin.isTTY || !process.stderr.isTTY || flags.json || flags.yes))) { console.log(HELP); return; }
|
|
87
100
|
const root = realpathSync(flags.project ? resolve(flags.project) : projectRoot());
|
|
@@ -126,6 +139,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
126
139
|
if (command === 'setup' || command === 'remove' || command === 'switch') {
|
|
127
140
|
const { setup, removeSetup, switchBrain } = await import('./setup.mjs');
|
|
128
141
|
const result = await (command === 'switch' ? switchBrain(root, flags) : command === 'setup' ? setup(root, flags) : removeSetup(root, flags));
|
|
142
|
+
if (result.status === 'error') process.exitCode = 1;
|
|
129
143
|
if (flags.json) output(result);
|
|
130
144
|
else if (command === 'remove') console.log(result.removed.length ? `Removed connections for ${result.removed.join(', ')}. Brain data, binding and login are kept.` : result.note);
|
|
131
145
|
else {
|
|
@@ -148,10 +162,17 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
148
162
|
}
|
|
149
163
|
if (command === 'login') {
|
|
150
164
|
const server = selectedServer();
|
|
165
|
+
if (flags['non-interactive']) {
|
|
166
|
+
const { startLoginSession, loginSession, publicLoginState } = await import('./login-session.mjs');
|
|
167
|
+
output(publicLoginState(flags.status === 'check' ? loginSession(server) : await startLoginSession(server, { retry: true })));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
151
170
|
await login(server, { open: !flags['no-open'] });
|
|
152
171
|
writeJson(join(homeDir(), 'config.json'), { server }); return;
|
|
153
172
|
}
|
|
154
173
|
if (command === 'logout') {
|
|
174
|
+
const { pendingLogin } = await import('./login-session.mjs');
|
|
175
|
+
if (pendingLogin()) throw new Error('Browser authorization is pending. Complete it or wait for it to expire before signing out.');
|
|
155
176
|
rmSync(credentialPath(selectedServer()), { force: true });
|
|
156
177
|
output({ signedOut: true, note: 'Removed this CLI’s local credentials. This does not revoke other clients or server grants.' }); return;
|
|
157
178
|
}
|
package/src/integrations.mjs
CHANGED
|
@@ -33,9 +33,9 @@ function ruleText(root) {
|
|
|
33
33
|
const command = `env ${shellQuote("MINDMUX_HOME=" + homeDir())} ${shellQuote(process.execPath)} ${shellQuote(CLI_BIN)} --project ${shellQuote(root)}`;
|
|
34
34
|
return `MindMux Project Brain\n\n${MEMORY_POLICY}\n\nUse the following CLI command prefix from any working directory:\n\n\`${command}\`\n\nAt the start of every new task (including discussion), run \`<prefix> brain recall "task keywords"\` if relevant context has not arrived via a hook.\nOperations: \`brain index\` (page summaries and root navigation), \`brain reindex\` (regenerate the derived index), \`brain list\`, \`brain search "keywords"\`, \`brain read <id>\`, \`brain roots\`, \`brain read-root <slug>\`. Results are JSON.\nCapture a confirmed decision: pipe its body to \`<prefix> brain create --id <id> --title "Title" --category decision --source "user confirmed ..."\`.\nUpdate: read the complete Page first, then pipe the full replacement body to \`<prefix> brain update <id> --expected-version <version> --summary "Why it changed"\`.\nFor a Cloud correction of typos, formatting or erroneous initial content, use \`<prefix> brain update <id> --expected-version <version> --change-kind correction\` without --summary or --source. Other updates default to substantive and require --summary.\nPreserve unchanged values exactly, including code, quotes and backslashes. JSON output escapes are serialization, not literal Markdown content: decode the string before reusing it. Send body text through stdin using a quoted heredoc or a file, without adding shell/JSON escaping to the body. After creating or updating, read the page back and verify the intended changes and unchanged values before reporting success. If correction is needed, use the newly read version and record the reason.\nAppend evidence: \`<prefix> brain append <id> --kind evidence --summary "Evidence" --source "Source"\`.\nUse \`brain create --status draft\` for explicitly requested proposals; never present drafts as settled facts.\nThe CLI resolves the explicit project binding. For Cloud, do not fall back to local tools after an error. An authenticated MCP can also be used only with the same bound brainId shown by \`brain status\`.\nWhen another Brain guide documents local file commands, retain its data-format contract and route this project's operations through the binding above.\nIf unbound, ask the user to select/create a Brain; never infer a cloud Brain from a folder name.\nBefore finishing, check whether any confirmed durable knowledge remains uncaptured. If none, finish without creating a page.\n`;
|
|
35
35
|
}
|
|
36
|
-
function definitions(root, agent) {
|
|
36
|
+
function definitions(root, agent, { home = homeDir(), node = process.execPath, bin = CLI_BIN } = {}) {
|
|
37
37
|
root = realpathSync(root);
|
|
38
|
-
const prefix = `env ${shellQuote("MINDMUX_HOME=" +
|
|
38
|
+
const prefix = `env ${shellQuote("MINDMUX_HOME=" + home)} ${shellQuote(node)} ${shellQuote(bin)} --project ${shellQuote(root)} hook --agent ${agent}`;
|
|
39
39
|
if (agent === 'cursor') return Object.fromEntries([
|
|
40
40
|
['sessionStart', 'session-start'], ['beforeSubmitPrompt', 'prompt'], ['preToolUse', 'pre-tool'], ['stop', 'stop'],
|
|
41
41
|
].map(([event, operation]) => [event, [{ command: `${prefix} ${operation}`, ...(event === 'stop' ? { loop_limit: 1 } : {}) }]]));
|
|
@@ -50,12 +50,36 @@ function definitions(root, agent) {
|
|
|
50
50
|
return {};
|
|
51
51
|
}
|
|
52
52
|
const commandOf = definition => definition.command || definition.hooks?.[0]?.command;
|
|
53
|
+
const commandsOf = definition => definition.hooks?.map(hook => hook.command).filter(Boolean) || [definition.command].filter(Boolean);
|
|
54
|
+
|
|
55
|
+
// Match exact recorded/generated commands, never an arbitrary command containing "mindmux".
|
|
56
|
+
// The setup launcher can recover ownership if only the integration receipt was lost.
|
|
57
|
+
function ownedCommands(root, agent, manifest) {
|
|
58
|
+
const launcher = readJson(join(root, '.mindmux/cli/setup.json'), {}).agents?.[agent]?.installed;
|
|
59
|
+
const args = launcher?.args;
|
|
60
|
+
const known = Object.values(definitions(root, agent)).flat().flatMap(commandsOf);
|
|
61
|
+
if (Array.isArray(args) && args.length === 5 && args[1] === '--project' && args[2] === realpathSync(root) && args[3] === 'mcp' && args[4] === 'serve'
|
|
62
|
+
&& typeof launcher.command === 'string' && typeof args[0] === 'string') {
|
|
63
|
+
known.push(...Object.values(definitions(root, agent, { node: launcher.command, bin: args[0], home: launcher.env?.MINDMUX_HOME || homeDir() })).flat().flatMap(commandsOf));
|
|
64
|
+
}
|
|
65
|
+
return new Set([...(manifest[agent]?.commands || []), ...known]);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function withoutOwnedCommands(items, owned) {
|
|
69
|
+
return items.flatMap(item => {
|
|
70
|
+
if (item.command && owned.has(item.command)) return [];
|
|
71
|
+
if (!Array.isArray(item.hooks)) return [item];
|
|
72
|
+
const hooks = item.hooks.filter(hook => !owned.has(hook.command));
|
|
73
|
+
if (hooks.length === item.hooks.length) return [item];
|
|
74
|
+
return hooks.length ? [{ ...item, hooks }] : [];
|
|
75
|
+
});
|
|
76
|
+
}
|
|
53
77
|
|
|
54
78
|
export function connect(root, agent, { remove = false } = {}) {
|
|
55
79
|
const files = integrationFiles(root, agent);
|
|
56
80
|
const manifestPath = join(root, '.mindmux/cli/integrations.json');
|
|
57
81
|
const manifest = readJson(manifestPath, {});
|
|
58
|
-
const previous =
|
|
82
|
+
const previous = ownedCommands(root, agent, manifest);
|
|
59
83
|
let text = existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '';
|
|
60
84
|
// Recognize an empty skeleton left by v0.1's old uninstaller as well as owned rules.
|
|
61
85
|
if (agent === 'cursor' && text && !text.includes(BEGIN) && !text.includes(CURSOR_OWNER) && text.trim() !== CURSOR_HEADER.trim()) throw new Error(`Refusing to overwrite foreign rule: ${files.rules}`);
|
|
@@ -76,7 +100,7 @@ export function connect(root, agent, { remove = false } = {}) {
|
|
|
76
100
|
for (const event of new Set([...Object.keys(settings.hooks), ...Object.keys(defs)])) {
|
|
77
101
|
const current = settings.hooks[event] || [];
|
|
78
102
|
if (!Array.isArray(current)) throw new Error(`Invalid hook array ${event}: ${files.hooks}`);
|
|
79
|
-
const kept = current
|
|
103
|
+
const kept = withoutOwnedCommands(current, previous);
|
|
80
104
|
const desired = defs[event] || [];
|
|
81
105
|
settings.hooks[event] = [...kept, ...desired.filter(item => !kept.some(old => commandOf(old) === commandOf(item)))];
|
|
82
106
|
if (!settings.hooks[event].length) delete settings.hooks[event];
|
|
@@ -100,7 +124,7 @@ export function inspectIntegrations(root) {
|
|
|
100
124
|
const files = integrationFiles(root, agent);
|
|
101
125
|
const text = existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '';
|
|
102
126
|
const hooks = files.hooks ? readJson(files.hooks, {}).hooks || {} : {};
|
|
103
|
-
const actualCommands = Object.values(hooks).filter(Array.isArray).flat().
|
|
127
|
+
const actualCommands = Object.values(hooks).filter(Array.isArray).flat().flatMap(commandsOf);
|
|
104
128
|
const expected = Object.values(definitions(root, agent)).flat().map(commandOf);
|
|
105
129
|
return { agent, mode: installed.mode, rulesPresent: text.includes(BEGIN) && text.includes(END),
|
|
106
130
|
hookCommandsPresent: installed.commands.length > 0 && installed.commands.every(command => actualCommands.includes(command))
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readdirSync, statSync, writeFileSync, unlinkSync, rmdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
function alive(pid) {
|
|
6
|
+
try { process.kill(pid, 0); return true; }
|
|
7
|
+
catch (error) { return error.code !== 'ESRCH'; }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Delete only a dead owner's unique marker. Never recursively remove a lock:
|
|
11
|
+
// another process may already have acquired a replacement directory.
|
|
12
|
+
export function removeStaleLoginLaunchLock(lock) {
|
|
13
|
+
try {
|
|
14
|
+
const names = readdirSync(lock);
|
|
15
|
+
if (!names.length && Date.now() - statSync(lock).mtimeMs < 5000) return false;
|
|
16
|
+
for (const name of names) {
|
|
17
|
+
const match = /^(\d+)-[a-f0-9-]+\.owner$/.exec(name);
|
|
18
|
+
if (!match || alive(Number(match[1]))) return false;
|
|
19
|
+
}
|
|
20
|
+
for (const name of names) {
|
|
21
|
+
try { unlinkSync(join(lock, name)); }
|
|
22
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
23
|
+
}
|
|
24
|
+
rmdirSync(lock);
|
|
25
|
+
return true;
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error.code === 'ENOENT') return true;
|
|
28
|
+
if (['ENOTEMPTY', 'EEXIST'].includes(error.code)) return false;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function acquireLoginLaunchLock(lock) {
|
|
34
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
35
|
+
try { mkdirSync(lock, { mode: 0o700 }); }
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== 'EEXIST') throw error;
|
|
38
|
+
if (removeStaleLoginLaunchLock(lock)) continue;
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
const owner = join(lock, `${process.pid}-${randomUUID()}.owner`);
|
|
42
|
+
const release = () => {
|
|
43
|
+
try { unlinkSync(owner); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
44
|
+
try { rmdirSync(lock); } catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; }
|
|
45
|
+
};
|
|
46
|
+
try {
|
|
47
|
+
const before = statSync(lock);
|
|
48
|
+
writeFileSync(owner, '', { flag: 'wx', mode: 0o600 });
|
|
49
|
+
const after = statSync(lock);
|
|
50
|
+
// A reaper may remove an empty directory just before our owner marker is
|
|
51
|
+
// written. Validate identity before entering the protected section.
|
|
52
|
+
if (before.dev === after.dev && before.ino === after.ino) return release;
|
|
53
|
+
release();
|
|
54
|
+
} catch (error) {
|
|
55
|
+
release();
|
|
56
|
+
if (error.code !== 'ENOENT') throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, existsSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { acquireLoginLaunchLock } from './login-lock.mjs';
|
|
7
|
+
import { homeDir, readJson, writeJson, serverUrl } from './storage.mjs';
|
|
8
|
+
|
|
9
|
+
export const loginSessionPath = server => join(homeDir(), 'auth', `login-${createHash('sha256').update(serverUrl(server)).digest('hex')}.json`);
|
|
10
|
+
export function loginSession(server) {
|
|
11
|
+
const session = readJson(loginSessionPath(server), {});
|
|
12
|
+
if (['starting', 'authorization_required'].includes(session.status)) {
|
|
13
|
+
let alive = false;
|
|
14
|
+
try { if (session.pid) { process.kill(session.pid, 0); alive = true; } } catch {}
|
|
15
|
+
if (Date.now() > session.expiresAt || (!alive && Date.now() - session.startedAt > 5000)) {
|
|
16
|
+
return { ...session, status: 'failed', authorizationUrl: undefined, error: 'Authorization expired or its worker stopped. Run login again.' };
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return session;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function pendingLogin() {
|
|
23
|
+
const dir = join(homeDir(), 'auth');
|
|
24
|
+
if (!existsSync(dir)) return false;
|
|
25
|
+
return readdirSync(dir).filter(name => /^login-[a-f0-9]{64}\.json$/.test(name)).some(name => {
|
|
26
|
+
const saved = readJson(join(dir, name), {});
|
|
27
|
+
return saved.server && ['starting', 'authorization_required'].includes(loginSession(saved.server).status);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The detached worker owns the OAuth callback and auth lock, not the short-lived agent tool call.
|
|
32
|
+
export async function startLoginSession(server, { open = false, retry = false } = {}) {
|
|
33
|
+
server = serverUrl(server);
|
|
34
|
+
const path = loginSessionPath(server), lock = `${path}.launch.lock`;
|
|
35
|
+
mkdirSync(join(homeDir(), 'auth'), { recursive: true, mode: 0o700 });
|
|
36
|
+
const unlock = acquireLoginLaunchLock(lock);
|
|
37
|
+
if (!unlock) return loginSession(server);
|
|
38
|
+
try {
|
|
39
|
+
const previous = loginSession(server);
|
|
40
|
+
if (['starting', 'authorization_required'].includes(previous.status) || (previous.status === 'failed' && !retry)) return previous;
|
|
41
|
+
const session = { id: randomUUID(), server, status: 'starting', startedAt: Date.now(), expiresAt: Date.now() + 180000 };
|
|
42
|
+
writeJson(path, session);
|
|
43
|
+
const worker = spawn(process.execPath, [fileURLToPath(new URL('./login-worker.mjs', import.meta.url)), server, session.id, open ? 'open' : 'no-open'],
|
|
44
|
+
{ detached: true, stdio: 'ignore', env: process.env });
|
|
45
|
+
await new Promise((resolve, reject) => { worker.once('spawn', resolve); worker.once('error', reject); });
|
|
46
|
+
worker.unref();
|
|
47
|
+
} finally { unlock(); }
|
|
48
|
+
// Usually return the URL on the first call, but never wait for user authorization.
|
|
49
|
+
for (let i = 0; i < 10; i++) {
|
|
50
|
+
const state = loginSession(server);
|
|
51
|
+
if (state.status !== 'starting') return state;
|
|
52
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
53
|
+
}
|
|
54
|
+
return loginSession(server);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function publicLoginState(session) {
|
|
58
|
+
return { status: session.status || 'not_started', server: session.server,
|
|
59
|
+
...(session.authorizationUrl ? { authorizationUrl: session.authorizationUrl } : {}),
|
|
60
|
+
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
|
61
|
+
...(session.error ? { error: session.error } : {}) };
|
|
62
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { login } from './cloud.mjs';
|
|
2
|
+
import { loginSessionPath } from './login-session.mjs';
|
|
3
|
+
import { readJson, writeJson } from './storage.mjs';
|
|
4
|
+
|
|
5
|
+
const [server, id, mode] = process.argv.slice(2);
|
|
6
|
+
const path = loginSessionPath(server);
|
|
7
|
+
const update = patch => {
|
|
8
|
+
const state = readJson(path, {});
|
|
9
|
+
if (state.id !== id) throw new Error('Login session was replaced.');
|
|
10
|
+
writeJson(path, { ...state, pid: process.pid, ...patch });
|
|
11
|
+
};
|
|
12
|
+
try {
|
|
13
|
+
update({ status: 'starting' });
|
|
14
|
+
await login(server, { open: mode === 'open', output: () => {},
|
|
15
|
+
onAuthorization: url => update({ status: 'authorization_required', authorizationUrl: url.href }) });
|
|
16
|
+
update({ status: 'authorized', authorizationUrl: undefined });
|
|
17
|
+
} catch (error) {
|
|
18
|
+
try { update({ status: 'failed', authorizationUrl: undefined, error: error.message }); } catch {}
|
|
19
|
+
process.exitCode = 1;
|
|
20
|
+
}
|
package/src/prompts.mjs
CHANGED
|
@@ -14,8 +14,9 @@ export function createSetupPrompts(context = { input: process.stdin, output: pro
|
|
|
14
14
|
{ name: 'Cancel', value: false },
|
|
15
15
|
{ name: 'Confirm', value: true },
|
|
16
16
|
], false),
|
|
17
|
-
projectName: projects => input({
|
|
17
|
+
projectName: (projects, suggestedName) => input({
|
|
18
18
|
message: 'New Project name:',
|
|
19
|
+
...(suggestedName ? { default: suggestedName } : {}),
|
|
19
20
|
theme: { validationFailureMode: 'clear' },
|
|
20
21
|
validate: value => {
|
|
21
22
|
const name = value.trim();
|
package/src/setup.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, readFileSync, mkdirSync, rmSync, statSync, chmodSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
2
|
+
import { join, basename } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { randomUUID, createHash } from 'node:crypto';
|
|
5
5
|
import { execFileSync } from 'node:child_process';
|
|
@@ -12,9 +12,19 @@ import { planHost, hostState, guardPath } from './host-config.mjs';
|
|
|
12
12
|
import { probeMcp } from './mcp-server.mjs';
|
|
13
13
|
import { inspectCodexHooks } from './codex-hooks.mjs';
|
|
14
14
|
import { createSetupPrompts } from './prompts.mjs';
|
|
15
|
+
import { startLoginSession, publicLoginState } from './login-session.mjs';
|
|
15
16
|
|
|
16
17
|
const supported = ['claude-code', 'codex'];
|
|
17
18
|
const setupPath = root => join(root, '.mindmux/cli/setup.json');
|
|
19
|
+
export function suggestedProjectName(root, projects = []) {
|
|
20
|
+
const base = (basename(root).replace(/[\x00-\x1f\x7f]/g, ' ').trim() || 'My Project').slice(0, 200);
|
|
21
|
+
const names = new Set(projects.map(project => project.name.trim().toLowerCase()));
|
|
22
|
+
if (!names.has(base.toLowerCase())) return base;
|
|
23
|
+
for (let n = 2; ; n++) {
|
|
24
|
+
const suffix = ` (${n})`, candidate = base.slice(0, 200 - suffix.length).trimEnd() + suffix;
|
|
25
|
+
if (!names.has(candidate.toLowerCase())) return candidate;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
18
28
|
function agentsFrom(value) {
|
|
19
29
|
const agents = [...new Set((value || '').split(',').map(x => x.trim()).filter(Boolean))];
|
|
20
30
|
if (agents.some(x => !supported.includes(x))) throw new Error('setup supports --agent claude-code,codex.');
|
|
@@ -149,7 +159,11 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
149
159
|
stage = message;
|
|
150
160
|
if (!flags.json) process.stderr.write(`• ${message}…\n`);
|
|
151
161
|
};
|
|
152
|
-
const
|
|
162
|
+
const machine = Boolean(flags['non-interactive']);
|
|
163
|
+
const inputRequired = (step, extra = {}) => ({ status: 'input_required', installed: false, step, project: root,
|
|
164
|
+
interaction: { preferred: 'host-native-choice', fallback: 'conversation',
|
|
165
|
+
guidance: 'Use an available and permitted host question tool (Claude Code: AskUserQuestion; Codex: request_user_input or request_user_input_async). Respect tool option limits; paginate long lists without hiding choices. If unavailable or unsuitable, ask one concise conversational question. Do not change host settings or modes automatically. Do not repeat a question already presented by the tool.' }, ...extra });
|
|
166
|
+
const interactive = !machine && !flags.yes && Boolean(dependencies.prompts || (process.stdin.isTTY && process.stderr.isTTY));
|
|
153
167
|
const prompts = dependencies.prompts || createSetupPrompts();
|
|
154
168
|
const cloud = dependencies.cloud || withCloud;
|
|
155
169
|
const runtime = join(root, '.mindmux/cli'); guardPath(root, runtime);
|
|
@@ -163,6 +177,7 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
163
177
|
try {
|
|
164
178
|
let agents = agentsFrom(flags.agent);
|
|
165
179
|
if (!agents.length) {
|
|
180
|
+
if (machine) return inputRequired('select_agent', { choices: supported.map(id => ({ id, name: id })), next: 'Rerun setup with --agent using the current host agent; do not configure unrelated hosts.' });
|
|
166
181
|
if (!interactive) throw new Error('Specify --agent claude-code,codex in a non-interactive terminal.');
|
|
167
182
|
const installed = supported.filter(name => { try { execFileSync('/usr/bin/which', [name === 'claude-code' ? 'claude' : name], { stdio: 'ignore' }); return true; } catch { return false; } });
|
|
168
183
|
agents = agentsFrom(await prompts.agents(installed));
|
|
@@ -176,6 +191,7 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
176
191
|
let plans;
|
|
177
192
|
try { plans = preflight(root, agents, manifest, migrate, false, Boolean(dependencies.repair)); }
|
|
178
193
|
catch (error) {
|
|
194
|
+
if (machine && !migrate && error.message.includes('--migrate')) return inputRequired('confirm_migration', { message: error.message, next: 'Ask the user before retrying with --migrate. Existing configuration will be backed up.' });
|
|
179
195
|
if (!interactive || migrate || !error.message.includes('--migrate')) throw error;
|
|
180
196
|
migrate = await prompts.confirm(`${error.message}\nReplace and back up the existing MCP configuration?`);
|
|
181
197
|
if (!migrate) throw error;
|
|
@@ -212,11 +228,17 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
212
228
|
};
|
|
213
229
|
if (!flags.local) {
|
|
214
230
|
step('Checking Cloud login');
|
|
215
|
-
|
|
231
|
+
const authorization = async () => inputRequired('authorize', { authorization: publicLoginState(await (dependencies.startLogin || startLoginSession)(server)), pollAfterMs: 1000,
|
|
232
|
+
next: 'Open/show the authorization URL once. While pending, wait before polling the same setup command; after the user approves, allow callback processing time before asking again. Retry with login --non-interactive --json only after failure. Never request tokens in chat.' });
|
|
233
|
+
if (!readJson(credentialPath(server), {}).tokens) {
|
|
234
|
+
if (machine) return await authorization();
|
|
235
|
+
await (dependencies.login || login)(server, { open: !flags['no-open'] });
|
|
236
|
+
}
|
|
216
237
|
// Authenticate/refresh through a harmless real request. Do not start browser auth after arbitrary network errors.
|
|
217
238
|
try { await cloud(server, call => call.listTools()); }
|
|
218
239
|
catch (error) {
|
|
219
240
|
if (error instanceof UnauthorizedError || ['InvalidGrantError', 'InvalidTokenError'].includes(error.name) || error.message.startsWith('Cloud login required.')) {
|
|
241
|
+
if (machine) return await authorization();
|
|
220
242
|
await (dependencies.login || login)(server, { open: !flags['no-open'] });
|
|
221
243
|
await cloud(server, call => call.listTools());
|
|
222
244
|
} else throw error;
|
|
@@ -224,27 +246,39 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
224
246
|
if (flags['brain-id']) selected = { brainId: flags['brain-id'] };
|
|
225
247
|
else if (flags.name) {
|
|
226
248
|
if (!flags['workspace-id']) throw new Error('--workspace-id is required with --name.');
|
|
249
|
+
if (machine && !flags.confirm) return inputRequired('confirm_project_creation', { name: flags.name, workspaceId: flags['workspace-id'], next: 'Ask the user to confirm the name and Workspace. All Workspace members can access the new Project. Only then rerun with --confirm.' });
|
|
227
250
|
if (!flags.confirm && !(interactive && await prompts.confirm(`Create Project ${flags.name}? All Workspace members can access it.`))) throw new Error('Project creation requires --confirm.');
|
|
228
251
|
selected = await createOrReuse(flags['workspace-id'], flags.name, flags.description || '');
|
|
229
252
|
} else if (current.kind === 'cloud' && current.server === server && !flags['workspace-id'] && !dependencies.reselect) selected = { ...preferences(root).cloudBrain, ...current };
|
|
230
253
|
else {
|
|
231
|
-
if (!interactive) throw new Error('Select --brain-id, or --workspace-id plus --name --confirm; no Brain is inferred from directory names.');
|
|
254
|
+
if (!interactive && !machine) throw new Error('Select --brain-id, or --workspace-id plus --name --confirm; no Brain is inferred from directory names.');
|
|
232
255
|
step('Loading Workspaces');
|
|
233
256
|
const workspaces = (await cloud(server, call => call('list_workspaces'))).workspaces;
|
|
234
257
|
if (!workspaces.length) throw new Error('No accessible Workspaces. Check Workspace membership and subscription.');
|
|
235
|
-
|
|
258
|
+
if (machine && !flags['workspace-id'] && workspaces.length > 1) return inputRequired('select_workspace', { choices: workspaces.map(w => ({ id: w.id || w.workspaceId, name: w.name })),
|
|
259
|
+
next: 'Ask the user to select a Workspace, then rerun with --workspace-id. Never infer selection from a directory name.' });
|
|
260
|
+
const workspace = flags['workspace-id'] ? workspaces.find(w => (w.id || w.workspaceId) === flags['workspace-id'])
|
|
261
|
+
: workspaces.length === 1 ? workspaces[0] : await prompts.choose('Select a Workspace:', workspaces.map(w => ({ name: w.name, value: w })));
|
|
236
262
|
if (!workspace) throw new Error('Workspace is unavailable.');
|
|
237
263
|
const workspaceId = workspace.id || workspace.workspaceId;
|
|
238
264
|
step('Loading Projects');
|
|
239
265
|
const projects = (await cloud(server, call => call('list_projects', { workspaceId }))).projects;
|
|
266
|
+
const suggestedName = suggestedProjectName(root, projects);
|
|
267
|
+
if (machine) return inputRequired(projects.length ? 'select_project' : 'name_project', { workspaceId, workspaceName: workspace.name,
|
|
268
|
+
workspaceAutomaticallySelected: !flags['workspace-id'] && workspaces.length === 1, suggestedName,
|
|
269
|
+
choices: [...projects.map(p => ({ kind: 'existing', brainId: p.brainId, name: p.name })),
|
|
270
|
+
{ kind: 'create', name: `+ Create a new Project: ${suggestedName}`, suggestedName }],
|
|
271
|
+
next: projects.length
|
|
272
|
+
? 'Present existing Projects followed by the create option with its suggested name, using the host choice tool when available. Existing: rerun with --brain-id, omitting --workspace-id. Create: let the user accept/edit suggestedName, then request creation confirmation with --workspace-id and --name (without --confirm).'
|
|
273
|
+
: 'This Workspace has no Projects. Ask for a new Project name directly, offering suggestedName as an editable default. Do not ask the user to select from an empty list. Then request creation confirmation with --workspace-id and --name (without --confirm).' });
|
|
240
274
|
while (!selected) {
|
|
241
|
-
const choice = await prompts.choose('Select a Project or create a new one:', [
|
|
242
|
-
{ name: '+ Create a new Project', value: { kind: 'create' } },
|
|
275
|
+
const choice = projects.length ? await prompts.choose('Select a Project or create a new one:', [
|
|
243
276
|
...projects.map(project => ({ name: project.name, value: { kind: 'existing', project } })),
|
|
244
|
-
|
|
277
|
+
{ name: `+ Create a new Project: ${suggestedName}`, value: { kind: 'create' } },
|
|
278
|
+
]) : { kind: 'create' };
|
|
245
279
|
if (choice.kind === 'existing') selected = { ...choice.project, workspaceId, workspaceName: workspace.name };
|
|
246
280
|
else {
|
|
247
|
-
const name = await prompts.projectName(projects);
|
|
281
|
+
const name = await prompts.projectName(projects, suggestedName);
|
|
248
282
|
if (await prompts.confirm(`Create Project "${name}"? All Workspace members can access it.`)) {
|
|
249
283
|
selected = { ...await createOrReuse(workspaceId, name), workspaceName: workspace.name };
|
|
250
284
|
}
|
|
@@ -284,7 +318,7 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
284
318
|
const probe = await (dependencies.probe || probeMcp)(root);
|
|
285
319
|
const pending = readJson(pendingPath, {});
|
|
286
320
|
if (pending.brainId && pending.brainId === selected?.brainId) rmSync(pendingPath, { force: true });
|
|
287
|
-
return { installed: true, project: root, binding: binding(root), agents, mcp: probe, codexHooks, warnings,
|
|
321
|
+
return { ...(machine ? { status: 'ready', restartRequired: true, trustRequired: true } : {}), installed: true, project: root, binding: binding(root), agents, mcp: probe, codexHooks, warnings,
|
|
288
322
|
next: 'Restart the selected Agent in this project and approve its MCP/project/hook trust prompts. For Codex, trust the project and review the installed hooks with /hooks.' };
|
|
289
323
|
});
|
|
290
324
|
} catch (error) {
|
|
@@ -293,6 +327,7 @@ export async function setup(root, flags = {}, dependencies = {}) {
|
|
|
293
327
|
const retry = recovery?.brainId
|
|
294
328
|
? `Cloud Project was created and retained. Resume without creating it again: mmx --project ${quote(root)} setup --brain-id ${quote(recovery.brainId)} --server ${quote(recovery.server)} --agent ${quote(selectedAgents)}`
|
|
295
329
|
: 'Check the error above, then rerun the command. If Project creation has an unknown outcome, list Projects before retrying creation.';
|
|
330
|
+
if (machine) return { status: 'error', installed: false, stage, error: error.message, next: retry, ...(recovery?.brainId ? { recovery: { brainId: recovery.brainId, server: recovery.server } } : {}) };
|
|
296
331
|
throw new Error(`${stage} failed: ${error.message}\n${retry}`);
|
|
297
332
|
} finally {
|
|
298
333
|
process.removeListener('exit', cleanup);
|
package/src/update.mjs
CHANGED
|
@@ -65,7 +65,7 @@ export async function checkUpdate({ current = VERSION, fetcher = fetch, now = Da
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
export async function notifyUpdate({ argv = process.argv.slice(2), stdin = process.stdin, stderr = process.stderr, env = process.env, check = checkUpdate } = {}) {
|
|
68
|
-
if (!stdin.isTTY || !stderr.isTTY || env.CI || env.NO_UPDATE_NOTIFIER || env.MINDMUX_NO_UPDATE_CHECK || argv.some(arg => ['--json', '--help', '--version', '--yes'].includes(arg))) return;
|
|
68
|
+
if (!stdin.isTTY || !stderr.isTTY || env.CI || env.NO_UPDATE_NOTIFIER || env.MINDMUX_NO_UPDATE_CHECK || argv.some(arg => ['--json', '--help', '--version', '--yes', '--non-interactive', '-agent'].includes(arg))) return;
|
|
69
69
|
// Only these exact human-facing commands may contact the registry or print notices.
|
|
70
70
|
const commands = [...argv];
|
|
71
71
|
while (commands[0] === '--project' || commands[0]?.startsWith('--project=')) {
|