@1xops/command-center 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @1xops/command-center might be problematic. Click here for more details.

package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 1xOps (nnthanh101@gmail.com)
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # 1xOps Command Center
2
+
3
+ An MCP server that gives Claude and OpenAI agents **persistent terminal sessions** (tests, builds, logs, REPLs, SSH) and **text-file tools**, limited to the folders a person allows, with one command blocklist. It runs on your machine with your permissions and sends nothing anywhere.
4
+
5
+ - **Clients:** Claude Code, Claude Desktop, OpenAI Codex CLI, Gemini CLI, Cursor, VS Code, and any other MCP client that starts a stdio server.
6
+ - **Platforms:** macOS, Linux and Windows. macOS and Linux are tested locally before each push; all three run in CI on every release pull request to `main`.
7
+ - **Requires:** Node.js 24 or later (Claude Code, Codex). Claude Desktop installs it from one file.
8
+ - **Package:** `@1xops/command-center` · MCP Registry name `io.github.1xOps/command-center` · Apache-2.0.
9
+
10
+ ## Install (always pin the version)
11
+
12
+ Replace `/path/to/project` with the folders the agent may use. Folders given at launch become `allowedDirectories` for that session.
13
+
14
+ **Claude Code: plugin (server plus usage skills)**
15
+
16
+ ```
17
+ /plugin marketplace add 1xOps/command-center-mcp
18
+ /plugin install command-center@command-center
19
+ ```
20
+
21
+ **Claude Code: server only**
22
+
23
+ ```bash
24
+ claude mcp add command-center -- npx -y @1xops/command-center@0.4.0 /path/to/project
25
+ ```
26
+
27
+ **OpenAI Codex CLI**
28
+
29
+ ```bash
30
+ codex mcp add command-center -- npx -y @1xops/command-center@0.4.0 /path/to/project
31
+ ```
32
+
33
+ **Gemini CLI**
34
+
35
+ ```bash
36
+ gemini extensions install https://github.com/1xOps/command-center-mcp
37
+ ```
38
+
39
+ The extension (`gemini-extension.json`) runs the pinned server with the current folder allowed. To choose folders, add it to `~/.gemini/settings.json` instead:
40
+
41
+ ```json
42
+ { "mcpServers": { "command-center": { "command": "npx", "args": ["-y", "@1xops/command-center@0.4.0", "/path/to/project"] } } }
43
+ ```
44
+
45
+ **Cursor:** add to `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project):
46
+
47
+ ```json
48
+ { "mcpServers": { "command-center": { "command": "npx", "args": ["-y", "@1xops/command-center@0.4.0", "/path/to/project"] } } }
49
+ ```
50
+
51
+ **VS Code (agent mode):** add to `.vscode/mcp.json`:
52
+
53
+ ```json
54
+ { "servers": { "command-center": { "type": "stdio", "command": "npx", "args": ["-y", "@1xops/command-center@0.4.0", "${workspaceFolder}"] } } }
55
+ ```
56
+
57
+ On Windows, if a client cannot start `npx`, use `"command": "npx.cmd"`.
58
+
59
+ **Claude Desktop (macOS, Windows):** download `command-center-0.4.0.mcpb` from the [release](https://github.com/1xOps/command-center-mcp/releases) and open it. The installer asks which folders Command Center may use.
60
+
61
+ **Container (any OS with Docker):** it sees only the folder you mount.
62
+
63
+ ```bash
64
+ docker build -t command-center:0.4.0 mcp-server
65
+ claude mcp add command-center -- docker run -i --rm -v "/path/to/project:/workspace" command-center:0.4.0
66
+ ```
67
+
68
+ ## Team configuration (one approved setup for every seat)
69
+
70
+ Commit this to the project as `.mcp.json` (Claude Code). Every engineer then runs the same pinned version with the same folders:
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "command-center": {
76
+ "command": "npx",
77
+ "args": ["-y", "@1xops/command-center@0.4.0", "."]
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ The Codex equivalent, in `~/.codex/config.toml`:
84
+
85
+ ```toml
86
+ [mcp_servers.command-center]
87
+ command = "npx"
88
+ args = ["-y", "@1xops/command-center@0.4.0", "/path/to/project"]
89
+ ```
90
+
91
+ Check what a seat runs with `npm view @1xops/command-center@0.4.0 dist.attestations`. It shows the build provenance npm recorded at publish.
92
+
93
+ ## Tools (20)
94
+
95
+ | Area | Tools |
96
+ |---|---|
97
+ | Processes | `start_process`, `interact_with_process`, `read_process_output`, `force_terminate`, `list_sessions` |
98
+ | Files (text; images returned as images) | `read_file`, `read_multiple_files`, `write_file`, `edit_block`, `list_directory`, `get_file_info`, `create_directory`, `move_file` |
99
+ | Search (ripgrep when installed) | `search`; for large result sets, paged: `start_search`, `get_more_search_results`, `stop_search` (up to 10 kept, each freed 10 minutes after its last read) |
100
+ | System (read-only) | `list_processes`: the OS process list with memory, on macOS, Linux and Windows |
101
+ | Settings | `get_config`, `set_config_value` |
102
+
103
+ PDF, Word, Excel and PowerPoint files are handled by the official document skills: `pdf`, `docx`, `xlsx` and `pptx` from Anthropic's skills repository. They work in Claude and, as Agent Skills, in Codex (`.agents/skills`). Each lists the tools it needs, for example LibreOffice or Python packages.
104
+
105
+ ## Settings
106
+
107
+ Settings live in `~/.command-center/config.json` (on Windows, `%USERPROFILE%\.command-center\config.json`). The file is created with defaults on first start.
108
+
109
+ | Key | Purpose | Who can change it |
110
+ |---|---|---|
111
+ | `allowedDirectories` | Folders every file tool and working directory must be inside. Folders given at launch override this. **Empty means no folder limit.** | a person only |
112
+ | `blockedCommands` | Programs refused wherever they start a command (defaults include `sudo`, `dd`, `mount`, `diskpart`, `reg`) | a person only |
113
+ | `defaultShell` | Shell for sessions (default: your login shell; PowerShell on Windows) | a person only |
114
+ | `fileReadLineLimit` | Lines per `read_file` (default 1000) | person or agent |
115
+ | `fileWriteLineLimit` | Lines per `write_file` call (default 50) | person or agent |
116
+
117
+ An agent cannot widen its own access: `set_config_value` refuses the first three keys.
118
+
119
+ ## Security
120
+
121
+ Command Center runs commands with your permissions. `allowedDirectories` and `blockedCommands` are guardrails against mistakes, **not a sandbox**: a program started in a session can reach anything you can. For untrusted work, use the container. See [SECURITY.md](SECURITY.md).
122
+
123
+ ## Development
124
+
125
+ ```bash
126
+ npm ci
127
+ npm test # build + all tests (node:test)
128
+ task setup # once per clone: turns on the git-standard hooks
129
+ task check # every local gate before the owner commits develop
130
+ task mcp:verify # from the repo root: timed end-to-end check with evidence
131
+ task mcp:act # the real CI workflow's macOS job on this Mac (act, no runner image)
132
+ task mcp:ci-local # the Linux CI job in the pinned Wolfi image
133
+ task mcp:supply-chain # SBOM and the signed dependency register
134
+ task mcp:release-rehearsal # what would be published, publishing nothing
135
+ ```
136
+
137
+ Releases run in CI from a tag `mcp-server-vX.Y.Z`. They publish only after the owner approves, through the `release` environment (see `.github/workflows/mcp-server-release.yml`).
138
+
139
+ ## Licence
140
+
141
+ Apache-2.0 © 2026 1xOps (nnthanh101, nnthanh101@gmail.com). See [LICENSE](LICENSE). The npm packages it depends on keep their own licences; the list is in the supply-chain register.
package/dist/config.js ADDED
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, open, readFile, rename, rm } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { z } from 'zod';
6
+ export const DEFAULT_BLOCKED_COMMANDS = [
7
+ // Disks and filesystems
8
+ 'mkfs', 'format', 'mount', 'umount', 'fdisk', 'dd', 'parted', 'diskpart',
9
+ // Privilege and accounts
10
+ 'sudo', 'su', 'doas', 'passwd', 'adduser', 'useradd', 'usermod', 'userdel', 'groupadd', 'chsh', 'visudo',
11
+ // System state
12
+ 'shutdown', 'reboot', 'halt', 'poweroff', 'init', 'systemctl', 'launchctl',
13
+ // Network and firewall
14
+ 'iptables', 'nft', 'ufw', 'firewall-cmd', 'pfctl',
15
+ // Windows (matched without .exe, ignoring case)
16
+ 'bcdedit', 'reg', 'net', 'sc', 'takeown', 'icacls', 'cipher', 'runas', 'netsh', 'sfc',
17
+ ];
18
+ /** macOS and Linux: the login shell. Windows: Windows PowerShell, present on every supported version. */
19
+ export function defaultShell() {
20
+ if (process.platform === 'win32')
21
+ return 'powershell.exe';
22
+ return process.env.SHELL || '/bin/sh';
23
+ }
24
+ const ConfigSchema = z.object({
25
+ allowedDirectories: z.array(z.string().min(1)).default([]),
26
+ blockedCommands: z.array(z.string().min(1)).default([...DEFAULT_BLOCKED_COMMANDS]),
27
+ defaultShell: z.string().min(1).default(defaultShell),
28
+ fileReadLineLimit: z.number().int().min(1).max(100_000).default(1000),
29
+ fileWriteLineLimit: z.number().int().min(1).max(100_000).default(50),
30
+ });
31
+ /** Keys an agent may change through `set_config_value`. Security keys are file-only. */
32
+ export const AGENT_SETTABLE_KEYS = ['fileReadLineLimit', 'fileWriteLineLimit'];
33
+ /** Keys only a person can change, by editing the config file. */
34
+ export const FILE_ONLY_KEYS = ['allowedDirectories', 'blockedCommands', 'defaultShell'];
35
+ export function configDir() {
36
+ return process.env.COMMAND_CENTER_CONFIG_DIR || path.join(os.homedir(), '.command-center');
37
+ }
38
+ export function configPath() {
39
+ return path.join(configDir(), 'config.json');
40
+ }
41
+ let current;
42
+ /** Folders given as launch arguments (Claude Desktop's folder picker, or a team's MCP config). */
43
+ let launchDirectories;
44
+ /**
45
+ * Launch arguments set allowedDirectories for this session and take precedence over the file:
46
+ * they were chosen by the person who installed or configured the client, not by the agent.
47
+ */
48
+ export function setLaunchDirectories(dirs) {
49
+ launchDirectories = dirs.length ? dirs.map((d) => path.resolve(d)) : undefined;
50
+ }
51
+ /** Where allowedDirectories comes from, for refusal messages and get_config. */
52
+ export function allowedDirectoriesSource() {
53
+ return launchDirectories
54
+ ? 'the server launch arguments (the folders chosen when the MCP client was installed or configured)'
55
+ : configPath();
56
+ }
57
+ /**
58
+ * Loads the config file. A missing file means defaults (written once, so a person can edit them).
59
+ * An invalid file stops the server (fail closed): falling back to defaults would replace a
60
+ * person's locked-down allowedDirectories with "no folder limit". The file is left untouched so
61
+ * the person can fix it.
62
+ */
63
+ export async function loadConfig() {
64
+ const file = configPath();
65
+ let raw;
66
+ try {
67
+ raw = await readFile(file, 'utf8');
68
+ }
69
+ catch (error) {
70
+ if (error.code !== 'ENOENT')
71
+ throw error;
72
+ }
73
+ if (raw === undefined) {
74
+ current = ConfigSchema.parse({});
75
+ await saveConfig(current);
76
+ return current;
77
+ }
78
+ try {
79
+ current = ConfigSchema.parse(JSON.parse(raw));
80
+ }
81
+ catch (error) {
82
+ throw new Error(`config ${file} is not valid, so Command Center will not start (fail closed): ${error.message}. Fix the file, or delete it to recreate the defaults.`);
83
+ }
84
+ return current;
85
+ }
86
+ export function getConfig() {
87
+ if (!current)
88
+ throw new Error('config not loaded: call loadConfig() first');
89
+ return launchDirectories ? { ...current, allowedDirectories: launchDirectories } : current;
90
+ }
91
+ /** Atomic write: a private temp file in the same folder, flushed, then renamed over the target. */
92
+ export async function saveConfig(config) {
93
+ const dir = configDir();
94
+ await mkdir(dir, { recursive: true, mode: 0o700 });
95
+ const tmp = path.join(dir, `config.json.${randomUUID()}.tmp`);
96
+ const handle = await open(tmp, 'wx', 0o600);
97
+ try {
98
+ await handle.writeFile(`${JSON.stringify(config, null, 2)}\n`, 'utf8');
99
+ await handle.sync();
100
+ }
101
+ finally {
102
+ await handle.close();
103
+ }
104
+ try {
105
+ await rename(tmp, configPath());
106
+ }
107
+ catch (error) {
108
+ await rm(tmp, { force: true });
109
+ throw error;
110
+ }
111
+ current = config;
112
+ }
113
+ export async function setConfigValue(key, value) {
114
+ if (FILE_ONLY_KEYS.includes(key)) {
115
+ throw new Error(`${key} can only be changed by a person, in ${configPath()}; agents cannot widen their own access`);
116
+ }
117
+ if (!AGENT_SETTABLE_KEYS.includes(key)) {
118
+ throw new Error(`unknown setting ${key}; settable keys: ${AGENT_SETTABLE_KEYS.join(', ')}`);
119
+ }
120
+ if (!current)
121
+ throw new Error('config not loaded: call loadConfig() first');
122
+ // Built from the file's values, so launch-argument folders are never written to the file.
123
+ const next = ConfigSchema.parse({ ...current, [key]: value });
124
+ await saveConfig(next);
125
+ return next;
126
+ }
package/dist/files.js ADDED
@@ -0,0 +1,200 @@
1
+ import { appendFile, lstat, mkdir, open, readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { getConfig } from './config.js';
4
+ import { validatePath } from './policy.js';
5
+ const MAX_READ_BYTES = 64 * 1024 * 1024; // larger files: use start_process with tail/head/grep
6
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
7
+ const MAX_LIST_ENTRIES = 1000;
8
+ const FUZZY_MAX_LINES = 5000;
9
+ const IMAGE_TYPES = {
10
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
11
+ };
12
+ async function isBinary(file) {
13
+ const handle = await open(file, 'r');
14
+ try {
15
+ const buffer = Buffer.alloc(8192);
16
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
17
+ return buffer.subarray(0, bytesRead).includes(0);
18
+ }
19
+ finally {
20
+ await handle.close();
21
+ }
22
+ }
23
+ /**
24
+ * Reads lines `offset`..`offset+length` (0-based). A negative offset reads from the end, so
25
+ * `offset: -100` is the last 100 lines of a log.
26
+ */
27
+ export async function readTextOrImage(requested, offset = 0, length) {
28
+ const file = await validatePath(requested);
29
+ const info = await stat(file);
30
+ if (info.isDirectory())
31
+ throw new Error(`${requested} is a directory; use list_directory`);
32
+ const mimeType = IMAGE_TYPES[path.extname(file).toLowerCase()];
33
+ if (mimeType) {
34
+ if (info.size > MAX_IMAGE_BYTES)
35
+ throw new Error(`${requested} is ${info.size} bytes; images up to ${MAX_IMAGE_BYTES} bytes are returned`);
36
+ return { kind: 'image', path: file, data: (await readFile(file)).toString('base64'), mimeType };
37
+ }
38
+ if (info.size > MAX_READ_BYTES) {
39
+ throw new Error(`${requested} is ${info.size} bytes, over the ${MAX_READ_BYTES}-byte read limit; use start_process with tail, head or grep`);
40
+ }
41
+ if (await isBinary(file))
42
+ throw new Error(`${requested} is a binary file; only text and images (png, jpg, gif, webp) are read`);
43
+ const lines = (await readFile(file, 'utf8')).split('\n');
44
+ if (lines.length > 1 && lines.at(-1) === '')
45
+ lines.pop();
46
+ const limit = Math.min(length ?? getConfig().fileReadLineLimit, getConfig().fileReadLineLimit);
47
+ const from = offset < 0 ? Math.max(lines.length + offset, 0) : Math.min(offset, lines.length);
48
+ const to = Math.min(from + limit, lines.length);
49
+ return { kind: 'text', path: file, text: lines.slice(from, to).join('\n'), fromLine: from + 1, toLine: to, totalLines: lines.length };
50
+ }
51
+ export async function writeText(requested, content, mode) {
52
+ const file = await validatePath(requested);
53
+ const lines = content.split('\n').length;
54
+ const limit = getConfig().fileWriteLineLimit;
55
+ if (lines > limit) {
56
+ throw new Error(`content is ${lines} lines, over fileWriteLineLimit (${limit}); write the first ${limit} lines with mode "rewrite", then the rest with mode "append"`);
57
+ }
58
+ await mkdir(path.dirname(file), { recursive: true });
59
+ if (mode === 'append')
60
+ await appendFile(file, content, 'utf8');
61
+ else
62
+ await writeFile(file, content, 'utf8');
63
+ return { path: file, lines };
64
+ }
65
+ function countOccurrences(text, search) {
66
+ let count = 0;
67
+ for (let at = text.indexOf(search); at !== -1; at = text.indexOf(search, at + search.length))
68
+ count++;
69
+ return count;
70
+ }
71
+ /** Levenshtein distance with two rows: O(a·b) time, O(b) memory. */
72
+ export function levenshtein(a, b) {
73
+ if (a === b)
74
+ return 0;
75
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
76
+ let row = new Array(b.length + 1);
77
+ for (let i = 1; i <= a.length; i++) {
78
+ row[0] = i;
79
+ for (let j = 1; j <= b.length; j++) {
80
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
81
+ row[j] = Math.min((prev[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + cost);
82
+ }
83
+ [prev, row] = [row, prev];
84
+ }
85
+ return prev[b.length] ?? 0;
86
+ }
87
+ function closestWindow(text, search) {
88
+ const lines = text.split('\n');
89
+ const span = search.split('\n').length;
90
+ if (lines.length > FUZZY_MAX_LINES || span > lines.length)
91
+ return undefined;
92
+ let best;
93
+ for (let i = 0; i + span <= lines.length; i++) {
94
+ const snippet = lines.slice(i, i + span).join('\n');
95
+ const longest = Math.max(snippet.length, search.length) || 1;
96
+ const similarity = 1 - levenshtein(snippet, search) / longest;
97
+ if (!best || similarity > best.similarity)
98
+ best = { fromLine: i + 1, toLine: i + span, similarity, snippet };
99
+ }
100
+ return best;
101
+ }
102
+ /**
103
+ * Replaces `oldString` with `newString` only when it occurs exactly `expected` times. With no
104
+ * exact match it changes nothing and reports the closest passage, so the caller can retry with
105
+ * the file's real text.
106
+ */
107
+ export async function editBlock(requested, oldString, newString, expected = 1) {
108
+ if (oldString === '')
109
+ throw new Error('old_string is empty; use write_file to create or replace a whole file');
110
+ const file = await validatePath(requested);
111
+ const text = await readFile(file, 'utf8');
112
+ const count = countOccurrences(text, oldString);
113
+ if (count === expected) {
114
+ await writeFile(file, text.split(oldString).join(newString), 'utf8');
115
+ return `replaced ${count} occurrence${count === 1 ? '' : 's'} in ${file}`;
116
+ }
117
+ if (count > 0) {
118
+ throw new Error(`old_string occurs ${count} times in ${file}, expected ${expected}; set expected_replacements to ${count} or add surrounding lines to make it unique`);
119
+ }
120
+ const near = closestWindow(text, oldString);
121
+ if (!near)
122
+ throw new Error(`old_string was not found in ${file}; nothing changed`);
123
+ throw new Error(`old_string was not found in ${file}; nothing changed. Closest passage, lines ${near.fromLine}-${near.toLine} ` +
124
+ `(${Math.round(near.similarity * 100)}% similar):\n${near.snippet}`);
125
+ }
126
+ export async function listDirectory(requested, depth) {
127
+ const root = await validatePath(requested);
128
+ const entries = [];
129
+ let truncated = false;
130
+ async function walk(dir, level) {
131
+ let items;
132
+ try {
133
+ items = await readdir(dir, { withFileTypes: true });
134
+ }
135
+ catch (error) {
136
+ const code = error.code;
137
+ // The folder that was asked for must exist and be readable; say so instead of listing nothing.
138
+ if (dir === root)
139
+ throw new Error(`cannot list ${requested}: ${code === 'ENOTDIR' ? 'it is a file' : error.message}`);
140
+ const label = code === 'EACCES' || code === 'EPERM' ? 'DENIED' : `ERROR ${code}`;
141
+ entries.push(`[${label}] ${path.relative(root, dir)}/`);
142
+ return;
143
+ }
144
+ items.sort((a, b) => a.name.localeCompare(b.name));
145
+ for (const item of items) {
146
+ if (entries.length >= MAX_LIST_ENTRIES) {
147
+ truncated = true;
148
+ return;
149
+ }
150
+ const rel = path.relative(root, path.join(dir, item.name));
151
+ if (item.isDirectory()) {
152
+ entries.push(`[DIR] ${rel}/`);
153
+ if (level < depth)
154
+ await walk(path.join(dir, item.name), level + 1);
155
+ }
156
+ else {
157
+ entries.push(`[${item.isSymbolicLink() ? 'LINK' : 'FILE'}] ${rel}`);
158
+ }
159
+ }
160
+ }
161
+ await walk(root, 1);
162
+ return { path: root, entries, truncated };
163
+ }
164
+ export async function fileInfo(requested) {
165
+ const file = await validatePath(requested);
166
+ const info = await stat(file);
167
+ const result = {
168
+ path: file,
169
+ type: info.isDirectory() ? 'directory' : info.isFile() ? 'file' : 'other',
170
+ size: info.size,
171
+ modified: info.mtime.toISOString(),
172
+ created: info.birthtime.toISOString(),
173
+ mode: (info.mode & 0o777).toString(8).padStart(3, '0'),
174
+ };
175
+ if (info.isFile() && info.size <= MAX_READ_BYTES && !(await isBinary(file))) {
176
+ result.lines = (await readFile(file, 'utf8')).split('\n').length;
177
+ }
178
+ return result;
179
+ }
180
+ export async function createDirectory(requested) {
181
+ const dir = await validatePath(requested);
182
+ await mkdir(dir, { recursive: true });
183
+ return dir;
184
+ }
185
+ /** The entry itself (a link stays a link): its folder is resolved and checked, its name kept. */
186
+ async function validateEntry(requested) {
187
+ const absolute = path.resolve(requested);
188
+ return path.join(await validatePath(path.dirname(absolute)), path.basename(absolute));
189
+ }
190
+ export async function moveFile(source, destination) {
191
+ const from = await validateEntry(source);
192
+ const to = await validateEntry(destination);
193
+ const [fromInfo, toInfo] = await Promise.all([lstat(from), lstat(to).catch(() => undefined)]);
194
+ // On a case-insensitive filesystem `Foo` -> `foo` finds the source itself; that rename is fine.
195
+ const sameEntry = toInfo && toInfo.ino === fromInfo.ino && toInfo.dev === fromInfo.dev;
196
+ if (toInfo && !sameEntry)
197
+ throw new Error(`${destination} already exists; nothing moved`);
198
+ await rename(from, to);
199
+ return { from, to };
200
+ }