@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11423 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,1493 @@
1
+ #!/usr/bin/env node
2
+ // Oil Slide workspace connector CLI & MCP stdio server. Node 22+, zero dependencies.
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ const DEFAULT_API_ROOT = 'https://slide.oiloil.org';
11
+ const LOGIN_CMD = 'node <skill>/scripts/oiloil-image.mjs login';
12
+ export const MAX_READ_BYTES = 25 * 1024 * 1024; // 25 MB per file
13
+ export const MAX_LIST_ENTRIES = 2000;
14
+ export const MAX_LIST_DEPTH = 2;
15
+ export const BULK_DELETE_LIMIT = 0;
16
+
17
+ export function formatDeleteConfirmationMessage(paths) {
18
+ const list = Array.isArray(paths) ? paths : [];
19
+ const count = list.length;
20
+ if (count === 0) return 'Agent 想删除 0 个文件';
21
+ const names = list.map((p) => String(p || '').replace(/\\/g, '/').split('/').filter(Boolean).pop() || String(p || ''));
22
+ const preview = names.slice(0, 3).join('、');
23
+ const suffix = count > 3 ? ` 等 ${count} 个` : '';
24
+ return `Agent 想删除 ${count} 个文件:${preview}${suffix}`;
25
+ }
26
+
27
+ const HELP = `用法:
28
+ node <skill>/scripts/oiloil-connect.mjs connect <folder>
29
+ node <skill>/scripts/oiloil-connect.mjs connect [folder] --mcp-stdio
30
+
31
+ 将本机文件夹作为工作区连接到 Oil Slide 网页工作台(slide.oiloil.org),或作为本地 MCP stdio 服务运行。
32
+ 需要 Node 22+,无第三方依赖;复用 oiloil-image.mjs 的登录凭据。
33
+
34
+ 命令与选项:
35
+ connect <folder> 连接本机工作区文件夹(仅出站长轮询,不监听任何本地端口)
36
+ --mcp-stdio 以本地 MCP stdio 模式暴露 oil_list_files、oil_read_file、oil_write_file、oil_delete_file、oil_move_file 五个工具
37
+ --once 仅执行一轮轮询后退出(供测试使用)
38
+ --help, -h 打印帮助
39
+
40
+ 安全边界:
41
+ - 严格沙箱:解析真实路径(realpath),拒绝任何目录越界或符号链接逃逸
42
+ - 自动跳过隐藏与系统目录(.git、node_modules、.env*、Keychains 等)及私钥/凭据文件(*.pem、*.key、id_rsa 等)
43
+ - 单文件读写上限 25 MB,单次目录列举上限 2,000 条
44
+ - 删除确认:删除文件前始终暂停并等待用户确认
45
+
46
+ 未登录时请先运行:
47
+ ${LOGIN_CMD}`;
48
+
49
+ export class ConnectorError extends Error {
50
+ constructor(code, message, exitCode = 1) {
51
+ super(message);
52
+ this.code = code;
53
+ this.exitCode = exitCode;
54
+ }
55
+ }
56
+
57
+ const BLOCKED_DIR_NAMES = new Set([
58
+ '.git',
59
+ '.hg',
60
+ '.svn',
61
+ 'node_modules',
62
+ '__pycache__',
63
+ '.venv',
64
+ 'venv',
65
+ '.tox',
66
+ '.nox',
67
+ '.mypy_cache',
68
+ '.pytest_cache',
69
+ '.next',
70
+ '.nuxt',
71
+ '.turbo',
72
+ 'keychains',
73
+ 'system',
74
+ ]);
75
+
76
+ const SYSTEM_EXACT_NAMES = new Set([
77
+ '.ds_store',
78
+ 'thumbs.db',
79
+ 'desktop.ini',
80
+ ]);
81
+
82
+ const SECRET_EXACT_NAMES = new Set([
83
+ '.env',
84
+ '.netrc',
85
+ '_netrc',
86
+ '.npmrc',
87
+ '.pypirc',
88
+ '.dockercfg',
89
+ 'id_rsa',
90
+ 'id_dsa',
91
+ 'id_ecdsa',
92
+ 'id_ed25519',
93
+ 'id_xmss',
94
+ 'authorized_keys',
95
+ 'known_hosts',
96
+ 'credentials',
97
+ 'credentials.json',
98
+ 'client_secret.json',
99
+ 'client_secrets.json',
100
+ 'service-account.json',
101
+ 'service_account.json',
102
+ 'secrets.json',
103
+ 'secret.json',
104
+ 'wallet.dat',
105
+ 'key3.db',
106
+ 'key4.db',
107
+ 'cert9.db',
108
+ 'cookies.sqlite',
109
+ 'login data',
110
+ ]);
111
+
112
+ const SECRET_EXT_RE = /\.(?:pem|key|p12|pfx|kdbx|keychain(?:-db)?|jks|keystore|ovpn|cred|credentials|der|CSR|crt|cer|pgp|gpg|asc)$/i;
113
+ const SECRET_NAME_RE = /^(?:\.env(?:\..+)?|id_(?:rsa|dsa|ecdsa|ed25519|xmss)(?:\..+)?|.*(?:_rsa|_ed25519|_ecdsa|_dsa)|.*secret.*\.(?:json|ya?ml|toml|ini|conf)|.*credential.*\.(?:json|ya?ml|toml|ini|conf))$/i;
114
+
115
+ const EXT_CONTENT_TYPES = {
116
+ '.png': 'image/png',
117
+ '.jpg': 'image/jpeg',
118
+ '.jpeg': 'image/jpeg',
119
+ '.webp': 'image/webp',
120
+ '.gif': 'image/gif',
121
+ '.svg': 'image/svg+xml',
122
+ '.bmp': 'image/bmp',
123
+ '.ico': 'image/x-icon',
124
+ '.pdf': 'application/pdf',
125
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
126
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
127
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
128
+ '.txt': 'text/plain; charset=utf-8',
129
+ '.md': 'text/markdown; charset=utf-8',
130
+ '.markdown': 'text/markdown; charset=utf-8',
131
+ '.json': 'application/json; charset=utf-8',
132
+ '.csv': 'text/csv; charset=utf-8',
133
+ '.tsv': 'text/tab-separated-values; charset=utf-8',
134
+ '.srt': 'text/plain; charset=utf-8',
135
+ '.vtt': 'text/vtt; charset=utf-8',
136
+ '.html': 'text/html; charset=utf-8',
137
+ '.htm': 'text/html; charset=utf-8',
138
+ '.xml': 'application/xml; charset=utf-8',
139
+ '.yaml': 'text/yaml; charset=utf-8',
140
+ '.yml': 'text/yaml; charset=utf-8',
141
+ };
142
+
143
+ const TEXT_EXTENSIONS = new Set([
144
+ '.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.srt', '.vtt',
145
+ '.html', '.htm', '.xml', '.yaml', '.yml', '.css', '.rst', '.tex', '.log',
146
+ ]);
147
+
148
+ export function guessContentType(filePath) {
149
+ const ext = path.extname(String(filePath || '')).toLowerCase();
150
+ return EXT_CONTENT_TYPES[ext] || 'application/octet-stream';
151
+ }
152
+
153
+ export function isTextFilePath(filePath) {
154
+ const ext = path.extname(String(filePath || '')).toLowerCase();
155
+ return TEXT_EXTENSIONS.has(ext);
156
+ }
157
+
158
+ export function isBlockedSegment(segment) {
159
+ const name = String(segment || '').trim();
160
+ if (!name || name === '.' || name === '..') return true;
161
+ if (name.startsWith('.')) return true;
162
+ const lower = name.toLowerCase();
163
+ if (BLOCKED_DIR_NAMES.has(lower)) return true;
164
+ if (SYSTEM_EXACT_NAMES.has(lower)) return true;
165
+ if (SECRET_EXACT_NAMES.has(lower)) return true;
166
+ if (SECRET_EXT_RE.test(lower)) return true;
167
+ if (SECRET_NAME_RE.test(lower)) return true;
168
+ return false;
169
+ }
170
+
171
+ function configRootDir(env = process.env, platform = process.platform, home = os.homedir()) {
172
+ const p = platform === 'win32' ? path.win32 : path.posix;
173
+ return platform === 'win32'
174
+ ? env.APPDATA || p.join(home, 'AppData', 'Roaming')
175
+ : env.XDG_CONFIG_HOME || p.join(home, '.config');
176
+ }
177
+
178
+ export function tokenConfigPath(env = process.env, platform = process.platform, home = os.homedir()) {
179
+ const p = platform === 'win32' ? path.win32 : path.posix;
180
+ return p.join(configRootDir(env, platform, home), 'oil-slide', 'config.json');
181
+ }
182
+
183
+ export async function readOilToken(env = process.env, platform = process.platform, home = os.homedir()) {
184
+ if (env.OIL_SLIDE_TOKEN?.trim()) return env.OIL_SLIDE_TOKEN.trim();
185
+ if (env.OIL_TOKEN?.trim()) return env.OIL_TOKEN.trim();
186
+ try {
187
+ const config = JSON.parse(await fs.readFile(tokenConfigPath(env, platform, home), 'utf8'));
188
+ return typeof config?.token === 'string' ? config.token.trim() : '';
189
+ } catch {
190
+ return '';
191
+ }
192
+ }
193
+
194
+ export function resolveApiRoot(env = process.env) {
195
+ const raw = env.OIL_SLIDE_API?.trim() || env.OIL_IMAGE_API?.trim() || DEFAULT_API_ROOT;
196
+ let url;
197
+ try {
198
+ url = new URL(raw);
199
+ } catch {
200
+ throw new ConnectorError('invalid_args', 'API 根地址格式无效,应为 HTTP(S) URL', 2);
201
+ }
202
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
203
+ throw new ConnectorError('invalid_args', 'API 根地址不应包含凭据、查询参数或片段', 2);
204
+ }
205
+ return url.href.replace(/\/+$/, '');
206
+ }
207
+
208
+ export function parseConnectArgs(argv) {
209
+ if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
210
+ return { help: true };
211
+ }
212
+ let command = null;
213
+ let folder = null;
214
+ let mcpStdio = false;
215
+ let once = false;
216
+ let pollTimeoutSec = 25;
217
+
218
+ for (let i = 0; i < argv.length; i++) {
219
+ const arg = argv[i];
220
+ if (arg === '--allow-write' || arg === '--read-only' || arg === '--readonly') {
221
+ // Accepted and ignored: connected workspace is always full access
222
+ } else if (arg === '--mcp-stdio') {
223
+ mcpStdio = true;
224
+ } else if (arg === '--once') {
225
+ once = true;
226
+ } else if (arg.startsWith('--poll-timeout=')) {
227
+ pollTimeoutSec = Math.max(1, Math.min(30, Number(arg.slice('--poll-timeout='.length)) || 25));
228
+ } else if (arg === '--poll-timeout') {
229
+ pollTimeoutSec = Math.max(1, Math.min(30, Number(argv[++i]) || 25));
230
+ } else if (arg.startsWith('-')) {
231
+ throw new ConnectorError('invalid_args', `不支持的选项 ${arg}。使用 --help 查看用法。`, 2);
232
+ } else if (!command && arg === 'connect') {
233
+ command = 'connect';
234
+ } else if (!folder) {
235
+ if (!command) command = 'connect';
236
+ folder = arg;
237
+ } else {
238
+ throw new ConnectorError('invalid_args', `多余的参数 ${arg}。使用 --help 查看用法。`, 2);
239
+ }
240
+ }
241
+
242
+ if (command !== 'connect') {
243
+ throw new ConnectorError('invalid_args', '缺少 connect 子命令。使用 --help 查看用法。', 2);
244
+ }
245
+ if (!folder) {
246
+ if (mcpStdio) {
247
+ folder = '.';
248
+ } else {
249
+ throw new ConnectorError('invalid_args', '请指定要连接的本地文件夹路径:connect <folder>', 2);
250
+ }
251
+ }
252
+ return {
253
+ help: false,
254
+ command,
255
+ folder: path.resolve(folder),
256
+ allowWrite: true,
257
+ mcpStdio,
258
+ once,
259
+ pollTimeoutSec,
260
+ };
261
+ }
262
+
263
+ function isInsideRoot(targetReal, rootReal) {
264
+ if (targetReal === rootReal) return true;
265
+ const prefix = rootReal.endsWith(path.sep) ? rootReal : `${rootReal}${path.sep}`;
266
+ return targetReal.startsWith(prefix);
267
+ }
268
+
269
+ export function splitAndValidateRelativePath(rawRelPath, { allowEmpty = false } = {}) {
270
+ if (rawRelPath === undefined || rawRelPath === null) {
271
+ if (allowEmpty) return [];
272
+ throw new ConnectorError('invalid_path', 'Path is required', 2);
273
+ }
274
+ if (typeof rawRelPath !== 'string' || rawRelPath.includes('\0')) {
275
+ throw new ConnectorError('invalid_path', 'Invalid path', 2);
276
+ }
277
+ const trimmed = rawRelPath.trim().replace(/\\/g, '/');
278
+ if (!trimmed || trimmed === '.') {
279
+ if (allowEmpty) return [];
280
+ throw new ConnectorError('invalid_path', 'File path cannot be empty', 2);
281
+ }
282
+ if (trimmed.startsWith('/') || /^[A-Za-z]:\//.test(trimmed)) {
283
+ throw new ConnectorError('outside_root', 'Absolute paths are not allowed; use a path relative to the connected root folder', 1);
284
+ }
285
+ const rawSegments = trimmed.split('/');
286
+ const segments = [];
287
+ for (const seg of rawSegments) {
288
+ if (!seg || seg === '.') continue;
289
+ if (seg === '..') {
290
+ throw new ConnectorError('outside_root', 'Path traversal (..) is not allowed', 1);
291
+ }
292
+ if (isBlockedSegment(seg)) {
293
+ throw new ConnectorError('forbidden_path', `Access to hidden, system, or secret file/folder "${seg}" is blocked`, 1);
294
+ }
295
+ segments.push(seg);
296
+ }
297
+ if (!allowEmpty && segments.length === 0) {
298
+ throw new ConnectorError('invalid_path', 'File path cannot be empty', 2);
299
+ }
300
+ return segments;
301
+ }
302
+
303
+ export class LocalSandbox {
304
+ constructor(
305
+ rootReal,
306
+ {
307
+ maxReadBytes = MAX_READ_BYTES,
308
+ maxListEntries = MAX_LIST_ENTRIES,
309
+ maxDeletesPerTurn = BULK_DELETE_LIMIT,
310
+ } = {},
311
+ ) {
312
+ this.rootReal = rootReal;
313
+ this.rootName = path.basename(rootReal) || 'folder';
314
+ this.writable = true;
315
+ this.maxReadBytes = maxReadBytes;
316
+ this.maxListEntries = maxListEntries;
317
+ this.maxDeletesPerTurn = maxDeletesPerTurn;
318
+ this.turnDeleteCount = 0;
319
+ this.bulkDeleteApproved = false;
320
+ this.bulkDeleteCancelled = false;
321
+ this.pendingConfirmation = null;
322
+ }
323
+
324
+ static async create(folderPath, options = {}) {
325
+ let stat;
326
+ try {
327
+ stat = await fs.stat(folderPath);
328
+ } catch {
329
+ throw new ConnectorError(
330
+ 'invalid_root',
331
+ `找不到这个文件夹:${folderPath}。把命令里的路径换成你自己的文件夹,或者先 cd 进去再运行 connect .`,
332
+ 1,
333
+ );
334
+ }
335
+ if (!stat.isDirectory()) {
336
+ throw new ConnectorError('invalid_root', `指定路径不是文件夹:${folderPath}`, 1);
337
+ }
338
+ const rootReal = await fs.realpath(folderPath);
339
+ return new LocalSandbox(rootReal, options);
340
+ }
341
+
342
+ getPendingConfirmation() {
343
+ if (!this.pendingConfirmation) return null;
344
+ return {
345
+ id: this.pendingConfirmation.id,
346
+ kind: 'delete',
347
+ count: this.pendingConfirmation.count,
348
+ paths: [...this.pendingConfirmation.paths],
349
+ message: this.pendingConfirmation.message,
350
+ };
351
+ }
352
+
353
+ resetTurnCounters() {
354
+ this.turnDeleteCount = 0;
355
+ this.bulkDeleteApproved = false;
356
+ this.bulkDeleteCancelled = false;
357
+ this.pendingConfirmation = null;
358
+ }
359
+
360
+ async confirmBulkOperation() {
361
+ const pending = this.pendingConfirmation;
362
+ if (!pending) {
363
+ return { ok: true, executed: 0, results: [] };
364
+ }
365
+ this.pendingConfirmation = null;
366
+ this.bulkDeleteApproved = true;
367
+ this.bulkDeleteCancelled = false;
368
+ const results = [];
369
+ for (const action of pending.actions) {
370
+ results.push(await action());
371
+ }
372
+ return {
373
+ ok: true,
374
+ kind: 'delete',
375
+ executed: results.length,
376
+ results,
377
+ };
378
+ }
379
+
380
+ cancelBulkOperation() {
381
+ const pending = this.pendingConfirmation;
382
+ this.pendingConfirmation = null;
383
+ this.bulkDeleteCancelled = true;
384
+ return {
385
+ ok: false,
386
+ cancelled: true,
387
+ error_code: 'bulk_cancelled',
388
+ error: pending
389
+ ? `User cancelled delete of ${pending.count} file(s); nothing was deleted`
390
+ : 'User cancelled delete; nothing was deleted',
391
+ };
392
+ }
393
+
394
+ _queuePendingBulkDelete(count, relPath, actionFn) {
395
+ if (!this.pendingConfirmation) {
396
+ const paths = [relPath];
397
+ this.pendingConfirmation = {
398
+ id: `confirm_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
399
+ kind: 'delete',
400
+ count: 1,
401
+ paths,
402
+ actions: [actionFn],
403
+ message: formatDeleteConfirmationMessage(paths),
404
+ };
405
+ } else {
406
+ if (!this.pendingConfirmation.paths.includes(relPath)) {
407
+ this.pendingConfirmation.paths.push(relPath);
408
+ this.pendingConfirmation.actions.push(actionFn);
409
+ }
410
+ this.pendingConfirmation.count = this.pendingConfirmation.paths.length;
411
+ this.pendingConfirmation.message = formatDeleteConfirmationMessage(this.pendingConfirmation.paths);
412
+ }
413
+ return {
414
+ ok: false,
415
+ path: relPath,
416
+ status: 'pending_confirmation',
417
+ pending_confirmation: true,
418
+ needs_confirmation: true,
419
+ error_code: 'pending_confirmation',
420
+ confirmation_id: this.pendingConfirmation.id,
421
+ kind: 'delete',
422
+ count: this.pendingConfirmation.count,
423
+ paths: [...this.pendingConfirmation.paths],
424
+ message: this.pendingConfirmation.message,
425
+ error: `${this.pendingConfirmation.message} (needs confirmation in Oil Slide)`,
426
+ };
427
+ }
428
+
429
+ async _resolveExistingInsideRoot(segments) {
430
+ let current = this.rootReal;
431
+ for (const seg of segments) {
432
+ const nextCandidate = path.join(current, seg);
433
+ let lstat;
434
+ try {
435
+ lstat = await fs.lstat(nextCandidate);
436
+ } catch (err) {
437
+ if (err && err.code === 'ENOENT') {
438
+ throw new ConnectorError('not_found', `File or directory not found: ${segments.join('/')}`, 1);
439
+ }
440
+ throw err;
441
+ }
442
+ const nextReal = await fs.realpath(nextCandidate).catch(() => {
443
+ throw new ConnectorError('outside_root', `Broken or inaccessible symlink: ${segments.join('/')}`, 1);
444
+ });
445
+ if (!isInsideRoot(nextReal, this.rootReal)) {
446
+ throw new ConnectorError('outside_root', `Path escapes connected root folder: ${segments.join('/')}`, 1);
447
+ }
448
+ const resolvedBase = path.basename(nextReal);
449
+ if (nextReal !== this.rootReal && isBlockedSegment(resolvedBase)) {
450
+ throw new ConnectorError('forbidden_path', `Access to hidden or secret target "${resolvedBase}" is blocked`, 1);
451
+ }
452
+ current = nextReal;
453
+ if (lstat.isSymbolicLink() && !isInsideRoot(current, this.rootReal)) {
454
+ throw new ConnectorError('outside_root', `Symlink escapes connected root folder: ${segments.join('/')}`, 1);
455
+ }
456
+ }
457
+ return current;
458
+ }
459
+
460
+ async _ensureParentDirectoryInsideRoot(parentSegments, fullPathForErr) {
461
+ let parentReal = this.rootReal;
462
+ for (const seg of parentSegments) {
463
+ const nextDir = path.join(parentReal, seg);
464
+ let lstat = null;
465
+ try {
466
+ lstat = await fs.lstat(nextDir);
467
+ } catch (err) {
468
+ if (!err || err.code !== 'ENOENT') throw err;
469
+ }
470
+ if (!lstat) {
471
+ await fs.mkdir(nextDir);
472
+ }
473
+ const resolvedNext = await fs.realpath(nextDir).catch(() => {
474
+ throw new ConnectorError('outside_root', `Invalid directory symlink in path: ${fullPathForErr}`, 1);
475
+ });
476
+ if (!isInsideRoot(resolvedNext, this.rootReal)) {
477
+ throw new ConnectorError('outside_root', `Directory escapes connected root folder: ${fullPathForErr}`, 1);
478
+ }
479
+ const nextSt = await fs.stat(resolvedNext);
480
+ if (!nextSt.isDirectory()) {
481
+ throw new ConnectorError('not_a_directory', `Parent path segment "${seg}" is not a directory`, 1);
482
+ }
483
+ parentReal = resolvedNext;
484
+ }
485
+ return parentReal;
486
+ }
487
+
488
+ async list(relPath = '', depth = 2) {
489
+ const segments = splitAndValidateRelativePath(relPath, { allowEmpty: true });
490
+ const clampedDepth = Math.max(1, Math.min(MAX_LIST_DEPTH, Number(depth ?? 2) || 2));
491
+ const startReal = await this._resolveExistingInsideRoot(segments);
492
+ const startStat = await fs.stat(startReal);
493
+ if (!startStat.isDirectory()) {
494
+ throw new ConnectorError('not_a_directory', `Not a directory: ${segments.join('/') || '.'}`, 1);
495
+ }
496
+
497
+ const entries = [];
498
+ let truncated = false;
499
+
500
+ const walk = async (dirReal, relPrefixSegments, currentDepth) => {
501
+ if (currentDepth > clampedDepth || entries.length >= this.maxListEntries) return;
502
+ let dirents;
503
+ try {
504
+ dirents = await fs.readdir(dirReal, { withFileTypes: true });
505
+ } catch {
506
+ return;
507
+ }
508
+ dirents.sort((a, b) => a.name.localeCompare(b.name, 'en'));
509
+
510
+ for (const dirent of dirents) {
511
+ if (entries.length >= this.maxListEntries) {
512
+ truncated = true;
513
+ return;
514
+ }
515
+ if (isBlockedSegment(dirent.name)) continue;
516
+
517
+ const fullCandidate = path.join(dirReal, dirent.name);
518
+ let targetReal;
519
+ try {
520
+ targetReal = await fs.realpath(fullCandidate);
521
+ } catch {
522
+ continue;
523
+ }
524
+ if (!isInsideRoot(targetReal, this.rootReal)) {
525
+ continue;
526
+ }
527
+ if (targetReal !== this.rootReal && isBlockedSegment(path.basename(targetReal))) {
528
+ continue;
529
+ }
530
+
531
+ let st;
532
+ try {
533
+ st = await fs.stat(targetReal);
534
+ } catch {
535
+ continue;
536
+ }
537
+ if (!st.isFile() && !st.isDirectory()) continue;
538
+
539
+ const entrySegments = [...relPrefixSegments, dirent.name];
540
+ const entryRelPath = entrySegments.join('/');
541
+ const isDir = st.isDirectory();
542
+
543
+ entries.push({
544
+ name: dirent.name,
545
+ path: entryRelPath,
546
+ type: isDir ? 'dir' : 'file',
547
+ size: isDir ? 0 : st.size,
548
+ mtime: st.mtime.toISOString(),
549
+ });
550
+
551
+ if (isDir && currentDepth < clampedDepth) {
552
+ await walk(targetReal, entrySegments, currentDepth + 1);
553
+ }
554
+ }
555
+ };
556
+
557
+ await walk(startReal, segments, 1);
558
+ return {
559
+ ok: true,
560
+ path: segments.join('/') || '.',
561
+ root_name: this.rootName,
562
+ writable: true,
563
+ entries,
564
+ truncated,
565
+ };
566
+ }
567
+
568
+ async read(relPath) {
569
+ const segments = splitAndValidateRelativePath(relPath, { allowEmpty: false });
570
+ const targetReal = await this._resolveExistingInsideRoot(segments);
571
+ const st = await fs.stat(targetReal);
572
+ if (st.isDirectory()) {
573
+ throw new ConnectorError('is_directory', `Path is a directory, not a file: ${segments.join('/')}`, 1);
574
+ }
575
+ if (!st.isFile()) {
576
+ throw new ConnectorError('not_found', `Not a regular file: ${segments.join('/')}`, 1);
577
+ }
578
+ if (st.size > this.maxReadBytes) {
579
+ throw new ConnectorError(
580
+ 'too_large',
581
+ `File "${segments.join('/')}" (${st.size} bytes) exceeds the 25 MB limit`,
582
+ 1,
583
+ );
584
+ }
585
+ const bytes = await fs.readFile(targetReal);
586
+ if (bytes.byteLength > this.maxReadBytes) {
587
+ throw new ConnectorError(
588
+ 'too_large',
589
+ `File "${segments.join('/')}" (${bytes.byteLength} bytes) exceeds the 25 MB limit`,
590
+ 1,
591
+ );
592
+ }
593
+ const relPosix = segments.join('/');
594
+ return {
595
+ ok: true,
596
+ path: relPosix,
597
+ name: segments[segments.length - 1],
598
+ size: bytes.byteLength,
599
+ mtime: st.mtime.toISOString(),
600
+ contentType: guessContentType(relPosix),
601
+ bytes,
602
+ };
603
+ }
604
+
605
+ async write(relPath, inputBytes) {
606
+ const segments = splitAndValidateRelativePath(relPath, { allowEmpty: false });
607
+ const relPosix = segments.join('/');
608
+ const bytes = Buffer.isBuffer(inputBytes)
609
+ ? inputBytes
610
+ : inputBytes instanceof Uint8Array
611
+ ? Buffer.from(inputBytes.buffer, inputBytes.byteOffset, inputBytes.byteLength)
612
+ : Buffer.from(String(inputBytes ?? ''), 'utf8');
613
+
614
+ if (bytes.byteLength > this.maxReadBytes) {
615
+ throw new ConnectorError(
616
+ 'too_large',
617
+ `Write payload (${bytes.byteLength} bytes) exceeds the 25 MB limit`,
618
+ 1,
619
+ );
620
+ }
621
+
622
+ const parentReal = await this._ensureParentDirectoryInsideRoot(
623
+ segments.slice(0, -1),
624
+ relPosix,
625
+ );
626
+
627
+ const fileName = segments[segments.length - 1];
628
+ const targetPath = path.join(parentReal, fileName);
629
+ let existingLstat = null;
630
+ try {
631
+ existingLstat = await fs.lstat(targetPath);
632
+ } catch (err) {
633
+ if (!err || err.code !== 'ENOENT') throw err;
634
+ }
635
+
636
+ if (existingLstat) {
637
+ if (existingLstat.isSymbolicLink()) {
638
+ throw new ConnectorError('outside_root', `Refusing to write through symbolic link: ${relPosix}`, 1);
639
+ }
640
+ if (existingLstat.isDirectory()) {
641
+ throw new ConnectorError('is_directory', `Cannot overwrite directory with file: ${relPosix}`, 1);
642
+ }
643
+ const existingReal = await fs.realpath(targetPath);
644
+ if (!isInsideRoot(existingReal, this.rootReal)) {
645
+ throw new ConnectorError('outside_root', `Target escapes connected root folder: ${relPosix}`, 1);
646
+ }
647
+ await fs.writeFile(existingReal, bytes);
648
+ return {
649
+ ok: true,
650
+ path: relPosix,
651
+ size: bytes.byteLength,
652
+ overwritten: true,
653
+ };
654
+ }
655
+
656
+ const handle = await fs.open(targetPath, 'wx', 0o644);
657
+ try {
658
+ await handle.writeFile(bytes);
659
+ await handle.sync();
660
+ } finally {
661
+ await handle.close();
662
+ }
663
+ const createdReal = await fs.realpath(targetPath);
664
+ if (!isInsideRoot(createdReal, this.rootReal)) {
665
+ await fs.rm(targetPath, { force: true }).catch(() => {});
666
+ throw new ConnectorError('outside_root', `Target escaped connected root folder: ${relPosix}`, 1);
667
+ }
668
+ return {
669
+ ok: true,
670
+ path: relPosix,
671
+ size: bytes.byteLength,
672
+ overwritten: false,
673
+ };
674
+ }
675
+
676
+ async delete(relPath, { bypassBulkGuard = false } = {}) {
677
+ const segments = splitAndValidateRelativePath(relPath, { allowEmpty: false });
678
+ const relPosix = segments.join('/');
679
+ const parentReal = await this._resolveExistingInsideRoot(segments.slice(0, -1));
680
+ const leafName = segments[segments.length - 1];
681
+ const candidatePath = path.join(parentReal, leafName);
682
+
683
+ let lstat;
684
+ try {
685
+ lstat = await fs.lstat(candidatePath);
686
+ } catch (err) {
687
+ if (err && err.code === 'ENOENT') {
688
+ throw new ConnectorError('not_found', `File or directory not found: ${relPosix}`, 1);
689
+ }
690
+ throw err;
691
+ }
692
+ if (lstat.isSymbolicLink()) {
693
+ throw new ConnectorError('outside_root', `Refusing to delete symbolic link: ${relPosix}`, 1);
694
+ }
695
+
696
+ const targetReal = await fs.realpath(candidatePath);
697
+ if (!isInsideRoot(targetReal, this.rootReal) || targetReal === this.rootReal) {
698
+ throw new ConnectorError('outside_root', `Path escapes connected root folder: ${relPosix}`, 1);
699
+ }
700
+ if (isBlockedSegment(path.basename(targetReal))) {
701
+ throw new ConnectorError('forbidden_path', `Access to "${relPosix}" is blocked`, 1);
702
+ }
703
+
704
+ const st = await fs.stat(targetReal);
705
+ if (st.isDirectory()) {
706
+ const children = await fs.readdir(targetReal);
707
+ if (children.length > 0) {
708
+ throw new ConnectorError(
709
+ 'dir_not_empty',
710
+ `Directory "${relPosix}" is not empty; recursive directory delete is not allowed`,
711
+ 1,
712
+ );
713
+ }
714
+ if (!bypassBulkGuard) {
715
+ if (this.bulkDeleteCancelled) {
716
+ throw new ConnectorError('bulk_cancelled', 'User cancelled delete in this turn; nothing was deleted', 1);
717
+ }
718
+ const nextCount = this.turnDeleteCount + 1;
719
+ if (nextCount > this.maxDeletesPerTurn && !this.bulkDeleteApproved) {
720
+ return this._queuePendingBulkDelete(nextCount, relPosix, () =>
721
+ this.delete(relPosix, { bypassBulkGuard: true }),
722
+ );
723
+ }
724
+ }
725
+ this.turnDeleteCount += 1;
726
+ await fs.rmdir(targetReal);
727
+ return {
728
+ ok: true,
729
+ path: relPosix,
730
+ deleted_type: 'dir',
731
+ };
732
+ }
733
+
734
+ if (!st.isFile()) {
735
+ throw new ConnectorError('not_found', `Not a regular file: ${relPosix}`, 1);
736
+ }
737
+
738
+ if (!bypassBulkGuard) {
739
+ if (this.bulkDeleteCancelled) {
740
+ throw new ConnectorError('bulk_cancelled', 'User cancelled delete in this turn; nothing was deleted', 1);
741
+ }
742
+ const nextCount = this.turnDeleteCount + 1;
743
+ if (nextCount > this.maxDeletesPerTurn && !this.bulkDeleteApproved) {
744
+ return this._queuePendingBulkDelete(nextCount, relPosix, () =>
745
+ this.delete(relPosix, { bypassBulkGuard: true }),
746
+ );
747
+ }
748
+ }
749
+
750
+ this.turnDeleteCount += 1;
751
+ await fs.unlink(targetReal);
752
+ return {
753
+ ok: true,
754
+ path: relPosix,
755
+ deleted_type: 'file',
756
+ };
757
+ }
758
+
759
+ async move(fromRelPath, toRelPath) {
760
+ const rawTo = typeof toRelPath === 'string' ? toRelPath.trim() : '';
761
+ if (!rawTo || rawTo === '/dev/null' || rawTo === 'dev/null' || rawTo.toUpperCase() === 'NUL') {
762
+ return this.delete(fromRelPath);
763
+ }
764
+ const fromSegments = splitAndValidateRelativePath(fromRelPath, { allowEmpty: false });
765
+ const toSegments = splitAndValidateRelativePath(toRelPath, { allowEmpty: false });
766
+ const fromPosix = fromSegments.join('/');
767
+ const toPosix = toSegments.join('/');
768
+
769
+ if (fromPosix === toPosix) {
770
+ return { ok: true, from: fromPosix, to: toPosix, path: toPosix };
771
+ }
772
+
773
+ const fromParentReal = await this._resolveExistingInsideRoot(fromSegments.slice(0, -1));
774
+ const fromCandidate = path.join(fromParentReal, fromSegments[fromSegments.length - 1]);
775
+ let fromLstat;
776
+ try {
777
+ fromLstat = await fs.lstat(fromCandidate);
778
+ } catch (err) {
779
+ if (err && err.code === 'ENOENT') {
780
+ throw new ConnectorError('not_found', `Source file not found: ${fromPosix}`, 1);
781
+ }
782
+ throw err;
783
+ }
784
+ if (fromLstat.isSymbolicLink()) {
785
+ throw new ConnectorError('outside_root', `Refusing to move symbolic link: ${fromPosix}`, 1);
786
+ }
787
+ const fromReal = await fs.realpath(fromCandidate);
788
+ if (!isInsideRoot(fromReal, this.rootReal) || fromReal === this.rootReal) {
789
+ throw new ConnectorError('outside_root', `Source escapes connected root folder: ${fromPosix}`, 1);
790
+ }
791
+ const fromStat = await fs.stat(fromReal);
792
+ if (fromStat.isDirectory()) {
793
+ throw new ConnectorError('is_directory', `Moving directories is not supported: ${fromPosix}`, 1);
794
+ }
795
+
796
+ const toParentReal = await this._ensureParentDirectoryInsideRoot(
797
+ toSegments.slice(0, -1),
798
+ toPosix,
799
+ );
800
+ const toTargetPath = path.join(toParentReal, toSegments[toSegments.length - 1]);
801
+
802
+ let toLstat = null;
803
+ try {
804
+ toLstat = await fs.lstat(toTargetPath);
805
+ } catch (err) {
806
+ if (!err || err.code !== 'ENOENT') throw err;
807
+ }
808
+
809
+ if (toLstat) {
810
+ if (toLstat.isSymbolicLink()) {
811
+ throw new ConnectorError('outside_root', `Refusing to overwrite symbolic link: ${toPosix}`, 1);
812
+ }
813
+ if (toLstat.isDirectory()) {
814
+ throw new ConnectorError('is_directory', `Cannot overwrite directory with file: ${toPosix}`, 1);
815
+ }
816
+ const toReal = await fs.realpath(toTargetPath);
817
+ if (!isInsideRoot(toReal, this.rootReal)) {
818
+ throw new ConnectorError('outside_root', `Destination escapes connected root folder: ${toPosix}`, 1);
819
+ }
820
+ }
821
+
822
+ await fs.rename(fromReal, toTargetPath);
823
+ return {
824
+ ok: true,
825
+ from: fromPosix,
826
+ to: toPosix,
827
+ path: toPosix,
828
+ };
829
+ }
830
+ }
831
+
832
+ // ---------------------------------------------------------------------------
833
+ // MCP Stdio Server (JSON-RPC 2.0 over newline-delimited JSON or Content-Length)
834
+ // ---------------------------------------------------------------------------
835
+
836
+ export const MCP_TOOLS = [
837
+ {
838
+ name: 'oil_list_files',
839
+ description: 'List files and directories inside the connected workspace folder (depth <= 2, max 2,000 entries, skips hidden/secret files).',
840
+ inputSchema: {
841
+ type: 'object',
842
+ properties: {
843
+ path: {
844
+ type: 'string',
845
+ description: 'Relative subdirectory path inside the connected workspace folder (default ".")',
846
+ },
847
+ depth: {
848
+ type: 'integer',
849
+ description: 'Traversal depth from 1 to 2 (default 2)',
850
+ minimum: 1,
851
+ maximum: 2,
852
+ },
853
+ },
854
+ additionalProperties: false,
855
+ },
856
+ },
857
+ {
858
+ name: 'oil_read_file',
859
+ description: 'Read a file inside the connected workspace folder (up to 25 MB). Returns UTF-8 text for text files or base64 for binary files.',
860
+ inputSchema: {
861
+ type: 'object',
862
+ properties: {
863
+ path: {
864
+ type: 'string',
865
+ description: 'Relative file path inside the connected workspace folder',
866
+ },
867
+ },
868
+ required: ['path'],
869
+ additionalProperties: false,
870
+ },
871
+ },
872
+ {
873
+ name: 'oil_write_file',
874
+ description: 'Create or overwrite a file inside the connected workspace folder.',
875
+ inputSchema: {
876
+ type: 'object',
877
+ properties: {
878
+ path: {
879
+ type: 'string',
880
+ description: 'Relative file path to write inside the connected workspace folder',
881
+ },
882
+ content: {
883
+ type: 'string',
884
+ description: 'File content (UTF-8 text by default, or base64 when encoding="base64")',
885
+ },
886
+ encoding: {
887
+ type: 'string',
888
+ enum: ['utf8', 'base64'],
889
+ description: 'Content encoding: "utf8" (default) or "base64"',
890
+ },
891
+ },
892
+ required: ['path', 'content'],
893
+ additionalProperties: false,
894
+ },
895
+ },
896
+ {
897
+ name: 'oil_delete_file',
898
+ description: 'Delete a file or an empty directory inside the connected workspace folder. Requires user confirmation (returns a "needs confirmation in Oil Slide" result unless confirmed; a local MCP client\'s own approval prompt counts as confirmation via confirmed=true).',
899
+ inputSchema: {
900
+ type: 'object',
901
+ properties: {
902
+ path: {
903
+ type: 'string',
904
+ description: 'Relative file or empty directory path to delete inside the connected workspace folder',
905
+ },
906
+ confirmed: {
907
+ type: 'boolean',
908
+ description: 'Set to true when approved by the local MCP client approval prompt or user confirmation',
909
+ },
910
+ },
911
+ required: ['path'],
912
+ additionalProperties: false,
913
+ },
914
+ },
915
+ {
916
+ name: 'oil_move_file',
917
+ description: 'Move or rename a file within the connected workspace folder.',
918
+ inputSchema: {
919
+ type: 'object',
920
+ properties: {
921
+ from: {
922
+ type: 'string',
923
+ description: 'Source relative file path inside the connected workspace folder',
924
+ },
925
+ to: {
926
+ type: 'string',
927
+ description: 'Destination relative file path inside the connected workspace folder',
928
+ },
929
+ },
930
+ required: ['from', 'to'],
931
+ additionalProperties: false,
932
+ },
933
+ },
934
+ ];
935
+
936
+ export async function handleMcpJsonRpc(sandbox, message) {
937
+ if (!message || typeof message !== 'object') return null;
938
+ const { id, method, params } = message;
939
+ const isNotification = id === undefined;
940
+
941
+ try {
942
+ if (method === 'initialize') {
943
+ if (isNotification) return null;
944
+ return {
945
+ jsonrpc: '2.0',
946
+ id,
947
+ result: {
948
+ protocolVersion: typeof params?.protocolVersion === 'string' ? params.protocolVersion : '2024-11-05',
949
+ capabilities: { tools: {} },
950
+ serverInfo: {
951
+ name: 'oil-slide-local-connector',
952
+ version: '1.2.0',
953
+ },
954
+ },
955
+ };
956
+ }
957
+ if (method === 'notifications/initialized' || method === 'initialized') {
958
+ return null;
959
+ }
960
+ if (method === 'ping') {
961
+ return isNotification ? null : { jsonrpc: '2.0', id, result: {} };
962
+ }
963
+ if (method === 'tools/list') {
964
+ return isNotification ? null : { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
965
+ }
966
+ if (method === 'tools/call') {
967
+ const toolName = params?.name;
968
+ const args = (params?.arguments && typeof params.arguments === 'object') ? params.arguments : {};
969
+ try {
970
+ if (toolName === 'oil_list_files') {
971
+ const res = await sandbox.list(args.path ?? '', args.depth ?? 2);
972
+ return {
973
+ jsonrpc: '2.0',
974
+ id,
975
+ result: {
976
+ content: [{ type: 'text', text: JSON.stringify(res) }],
977
+ isError: false,
978
+ },
979
+ };
980
+ }
981
+ if (toolName === 'oil_read_file') {
982
+ const res = await sandbox.read(args.path);
983
+ const isText = isTextFilePath(res.path);
984
+ const payload = {
985
+ ok: true,
986
+ path: res.path,
987
+ name: res.name,
988
+ size: res.size,
989
+ mtime: res.mtime,
990
+ contentType: res.contentType,
991
+ encoding: isText ? 'utf8' : 'base64',
992
+ content: isText ? res.bytes.toString('utf8') : res.bytes.toString('base64'),
993
+ };
994
+ return {
995
+ jsonrpc: '2.0',
996
+ id,
997
+ result: {
998
+ content: [{ type: 'text', text: JSON.stringify(payload) }],
999
+ isError: false,
1000
+ },
1001
+ };
1002
+ }
1003
+ if (toolName === 'oil_write_file') {
1004
+ const encoding = args.encoding === 'base64' ? 'base64' : 'utf8';
1005
+ const bytes = Buffer.from(String(args.content ?? ''), encoding);
1006
+ const res = await sandbox.write(args.path, bytes);
1007
+ return {
1008
+ jsonrpc: '2.0',
1009
+ id,
1010
+ result: {
1011
+ content: [{ type: 'text', text: JSON.stringify(res) }],
1012
+ isError: !res.ok,
1013
+ },
1014
+ };
1015
+ }
1016
+ if (toolName === 'oil_delete_file') {
1017
+ let res;
1018
+ if (args.confirmed === true) {
1019
+ const pending = sandbox.getPendingConfirmation();
1020
+ if (pending && pending.paths.includes(args.path)) {
1021
+ const batchRes = await sandbox.confirmBulkOperation();
1022
+ res = batchRes.results.find((r) => r && r.path === args.path) || {
1023
+ ok: true,
1024
+ path: args.path,
1025
+ deleted_type: 'file',
1026
+ batch_executed: batchRes.executed,
1027
+ };
1028
+ } else {
1029
+ if (pending) {
1030
+ await sandbox.confirmBulkOperation();
1031
+ }
1032
+ res = await sandbox.delete(args.path, { bypassBulkGuard: true });
1033
+ }
1034
+ } else {
1035
+ res = await sandbox.delete(args.path);
1036
+ }
1037
+ return {
1038
+ jsonrpc: '2.0',
1039
+ id,
1040
+ result: {
1041
+ content: [{ type: 'text', text: JSON.stringify(res) }],
1042
+ isError: !res.ok,
1043
+ },
1044
+ };
1045
+ }
1046
+ if (toolName === 'oil_move_file') {
1047
+ const res = await sandbox.move(args.from ?? args.from_path, args.to ?? args.to_path);
1048
+ return {
1049
+ jsonrpc: '2.0',
1050
+ id,
1051
+ result: {
1052
+ content: [{ type: 'text', text: JSON.stringify(res) }],
1053
+ isError: !res.ok,
1054
+ },
1055
+ };
1056
+ }
1057
+ return {
1058
+ jsonrpc: '2.0',
1059
+ id,
1060
+ result: {
1061
+ content: [{ type: 'text', text: JSON.stringify({ ok: false, error_code: 'unknown_tool', error: `Unknown tool: ${toolName}` }) }],
1062
+ isError: true,
1063
+ },
1064
+ };
1065
+ } catch (toolErr) {
1066
+ const errPayload = {
1067
+ ok: false,
1068
+ error_code: toolErr instanceof ConnectorError ? toolErr.code : 'tool_error',
1069
+ error: toolErr instanceof Error ? toolErr.message : String(toolErr),
1070
+ };
1071
+ return {
1072
+ jsonrpc: '2.0',
1073
+ id,
1074
+ result: {
1075
+ content: [{ type: 'text', text: JSON.stringify(errPayload) }],
1076
+ isError: true,
1077
+ },
1078
+ };
1079
+ }
1080
+ }
1081
+
1082
+ if (isNotification) return null;
1083
+ return {
1084
+ jsonrpc: '2.0',
1085
+ id,
1086
+ error: { code: -32601, message: `Method not found: ${method}` },
1087
+ };
1088
+ } catch (err) {
1089
+ if (isNotification) return null;
1090
+ return {
1091
+ jsonrpc: '2.0',
1092
+ id,
1093
+ error: { code: -32603, message: err instanceof Error ? err.message : 'Internal error' },
1094
+ };
1095
+ }
1096
+ }
1097
+
1098
+ export async function runMcpStdioServer(sandbox, input = process.stdin, output = process.stdout) {
1099
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
1100
+ for await (const line of rl) {
1101
+ const trimmed = line.trim();
1102
+ if (!trimmed || trimmed.toLowerCase().startsWith('content-length:')) continue;
1103
+ let msg;
1104
+ try {
1105
+ msg = JSON.parse(trimmed);
1106
+ } catch {
1107
+ continue;
1108
+ }
1109
+ const resp = await handleMcpJsonRpc(sandbox, msg);
1110
+ if (resp) {
1111
+ output.write(`${JSON.stringify(resp)}\n`);
1112
+ }
1113
+ }
1114
+ }
1115
+
1116
+ // ---------------------------------------------------------------------------
1117
+ // Outbound Cloud Relay Execution Loop
1118
+ // ---------------------------------------------------------------------------
1119
+
1120
+ export async function executeRelayRequest(sandbox, reqItem, { apiRoot, token, fetchImpl = fetch } = {}) {
1121
+ const reqId = reqItem?.id;
1122
+ const op = reqItem?.op;
1123
+ const payload = (reqItem?.payload && typeof reqItem.payload === 'object') ? reqItem.payload : {};
1124
+
1125
+ const postResult = async (bodyObj) => {
1126
+ const resp = await fetchImpl(`${apiRoot}/api/local/result/${encodeURIComponent(reqId)}`, {
1127
+ method: 'POST',
1128
+ headers: {
1129
+ Authorization: `Bearer ${token}`,
1130
+ 'Content-Type': 'application/json',
1131
+ },
1132
+ body: JSON.stringify(bodyObj),
1133
+ signal: AbortSignal.timeout(30000),
1134
+ });
1135
+ if (!resp.ok) {
1136
+ const text = await resp.text().catch(() => '');
1137
+ throw new Error(`POST result/${reqId} failed (HTTP ${resp.status}): ${text.slice(0, 200)}`);
1138
+ }
1139
+ return resp.json().catch(() => ({ ok: true }));
1140
+ };
1141
+
1142
+ try {
1143
+ if (op === 'list') {
1144
+ const listed = await sandbox.list(payload.path ?? '', payload.depth ?? 2);
1145
+ await postResult({
1146
+ status: 'done',
1147
+ result: {
1148
+ path: listed.path,
1149
+ root_name: listed.root_name,
1150
+ writable: true,
1151
+ entries: listed.entries,
1152
+ truncated: listed.truncated,
1153
+ },
1154
+ });
1155
+ return { ok: true, op, id: reqId };
1156
+ }
1157
+
1158
+ if (op === 'read') {
1159
+ const fileRes = await sandbox.read(payload.path);
1160
+ let upload = reqItem?.upload;
1161
+ if (!upload || !upload.url || !upload.key) {
1162
+ const presignResp = await postResult({
1163
+ action: 'presign',
1164
+ filename: fileRes.name,
1165
+ content_type: fileRes.contentType,
1166
+ size: fileRes.size,
1167
+ });
1168
+ upload = presignResp?.upload;
1169
+ }
1170
+ if (!upload || !upload.url || !upload.key) {
1171
+ throw new ConnectorError('relay_error', 'Studio relay did not return a presigned upload target', 7);
1172
+ }
1173
+
1174
+ const uploadUrl = upload.url.startsWith('http://') || upload.url.startsWith('https://')
1175
+ ? upload.url
1176
+ : `${apiRoot}${upload.url.startsWith('/') ? '' : '/'}${upload.url}`;
1177
+ const putHeaders = { ...(upload.headers || {}) };
1178
+ if (!putHeaders['Content-Type'] && !putHeaders['content-type']) {
1179
+ putHeaders['Content-Type'] = fileRes.contentType;
1180
+ }
1181
+ if (upload.provider === 'local' && !putHeaders.Authorization && !putHeaders.authorization) {
1182
+ putHeaders.Authorization = `Bearer ${token}`;
1183
+ }
1184
+
1185
+ const putResp = await fetchImpl(uploadUrl, {
1186
+ method: upload.method || 'PUT',
1187
+ headers: putHeaders,
1188
+ body: fileRes.bytes,
1189
+ signal: AbortSignal.timeout(60000),
1190
+ });
1191
+ if (!putResp.ok) {
1192
+ const errText = await putResp.text().catch(() => '');
1193
+ throw new ConnectorError('upload_failed', `Failed uploading file bytes (HTTP ${putResp.status}): ${errText.slice(0, 160)}`, 7);
1194
+ }
1195
+
1196
+ await postResult({
1197
+ status: 'done',
1198
+ result_storage_key: upload.key,
1199
+ result: {
1200
+ path: fileRes.path,
1201
+ name: fileRes.name,
1202
+ size: fileRes.size,
1203
+ mtime: fileRes.mtime,
1204
+ content_type: fileRes.contentType,
1205
+ },
1206
+ });
1207
+ return { ok: true, op, id: reqId };
1208
+ }
1209
+
1210
+ if (op === 'write') {
1211
+ let fileBytes;
1212
+ const downloadUrlRaw = reqItem?.download_url || payload.download_url;
1213
+ if (typeof downloadUrlRaw === 'string' && downloadUrlRaw.trim()) {
1214
+ const downloadUrl = downloadUrlRaw.startsWith('http://') || downloadUrlRaw.startsWith('https://')
1215
+ ? downloadUrlRaw
1216
+ : `${apiRoot}${downloadUrlRaw.startsWith('/') ? '' : '/'}${downloadUrlRaw}`;
1217
+ const dlHeaders = {};
1218
+ if (downloadUrl.startsWith(apiRoot)) {
1219
+ dlHeaders.Authorization = `Bearer ${token}`;
1220
+ }
1221
+ const dlResp = await fetchImpl(downloadUrl, {
1222
+ method: 'GET',
1223
+ headers: dlHeaders,
1224
+ signal: AbortSignal.timeout(60000),
1225
+ });
1226
+ if (!dlResp.ok) {
1227
+ throw new ConnectorError('download_failed', `Failed downloading export bytes (HTTP ${dlResp.status})`, 7);
1228
+ }
1229
+ fileBytes = Buffer.from(await dlResp.arrayBuffer());
1230
+ } else if (typeof payload.content_base64 === 'string') {
1231
+ fileBytes = Buffer.from(payload.content_base64, 'base64');
1232
+ } else if (typeof payload.content === 'string') {
1233
+ fileBytes = Buffer.from(payload.content, 'utf8');
1234
+ } else {
1235
+ throw new ConnectorError('invalid_payload', 'Write request missing download_url or content', 2);
1236
+ }
1237
+
1238
+ const written = await sandbox.write(payload.path, fileBytes);
1239
+ await postResult({
1240
+ status: 'done',
1241
+ result: {
1242
+ path: written.path,
1243
+ size: written.size,
1244
+ overwritten: Boolean(written.overwritten),
1245
+ },
1246
+ });
1247
+ return { ok: true, op, id: reqId };
1248
+ }
1249
+
1250
+ if (op === 'delete') {
1251
+ const deleted = await sandbox.delete(payload.path);
1252
+ if (deleted.pending_confirmation) {
1253
+ await postResult({
1254
+ status: 'done',
1255
+ result: deleted,
1256
+ });
1257
+ return { ok: false, pending_confirmation: true, op, id: reqId };
1258
+ }
1259
+ await postResult({
1260
+ status: 'done',
1261
+ result: {
1262
+ path: deleted.path,
1263
+ deleted_type: deleted.deleted_type,
1264
+ },
1265
+ });
1266
+ return { ok: true, op, id: reqId };
1267
+ }
1268
+
1269
+ if (op === 'move') {
1270
+ const moved = await sandbox.move(
1271
+ payload.from ?? payload.from_path,
1272
+ payload.to ?? payload.to_path,
1273
+ );
1274
+ await postResult({
1275
+ status: 'done',
1276
+ result: {
1277
+ from: moved.from,
1278
+ to: moved.to,
1279
+ path: moved.path,
1280
+ },
1281
+ });
1282
+ return { ok: true, op, id: reqId };
1283
+ }
1284
+
1285
+ throw new ConnectorError('unsupported_op', `Unsupported local connector operation: ${op}`, 2);
1286
+ } catch (err) {
1287
+ const errorCode = err instanceof ConnectorError ? err.code : 'execution_failed';
1288
+ const errorMsg = err instanceof Error ? err.message : String(err);
1289
+ await postResult({
1290
+ status: 'failed',
1291
+ error_code: errorCode,
1292
+ error: errorMsg,
1293
+ }).catch(() => {});
1294
+ return { ok: false, op, id: reqId, error_code: errorCode, error: errorMsg };
1295
+ }
1296
+ }
1297
+
1298
+ export async function runCloudConnector(sandbox, opts, { apiRoot, token, fetchImpl = fetch, signal } = {}) {
1299
+ const hostLabel = os.hostname() || 'local';
1300
+ const label = `${sandbox.rootName} (${hostLabel})`;
1301
+
1302
+ let connectionId = null;
1303
+ let backoffMs = 1000;
1304
+ let printedBanner = false;
1305
+
1306
+ const registerOrHeartbeat = async () => {
1307
+ const resp = await fetchImpl(`${apiRoot}/api/local/connect`, {
1308
+ method: 'POST',
1309
+ headers: {
1310
+ Authorization: `Bearer ${token}`,
1311
+ 'Content-Type': 'application/json',
1312
+ },
1313
+ body: JSON.stringify({
1314
+ connection_id: connectionId,
1315
+ root_name: sandbox.rootName,
1316
+ label,
1317
+ writable: true,
1318
+ }),
1319
+ signal: AbortSignal.timeout(15000),
1320
+ });
1321
+ if (resp.status === 401 || resp.status === 403) {
1322
+ throw new ConnectorError(
1323
+ 'unauthorized',
1324
+ `Oil Slide 登录凭据无效或已过期。请先运行:${LOGIN_CMD}`,
1325
+ 3,
1326
+ );
1327
+ }
1328
+ if (!resp.ok) {
1329
+ const txt = await resp.text().catch(() => '');
1330
+ throw new Error(`注册连接失败 (HTTP ${resp.status}): ${txt.slice(0, 160)}`);
1331
+ }
1332
+ const data = await resp.json();
1333
+ connectionId = data?.connection?.id || connectionId;
1334
+ return data?.connection;
1335
+ };
1336
+
1337
+ const closeConnection = async () => {
1338
+ if (!connectionId) return;
1339
+ await fetchImpl(`${apiRoot}/api/local/connect`, {
1340
+ method: 'POST',
1341
+ headers: {
1342
+ Authorization: `Bearer ${token}`,
1343
+ 'Content-Type': 'application/json',
1344
+ },
1345
+ body: JSON.stringify({
1346
+ action: 'disconnect',
1347
+ connection_id: connectionId,
1348
+ }),
1349
+ signal: AbortSignal.timeout(5000),
1350
+ }).catch(() => {});
1351
+ };
1352
+
1353
+ while (!signal?.aborted) {
1354
+ try {
1355
+ await registerOrHeartbeat();
1356
+ backoffMs = 1000;
1357
+ if (!printedBanner) {
1358
+ printedBanner = true;
1359
+ console.log(
1360
+ `工作区:${sandbox.rootName}(路径:${sandbox.rootReal})— 按 Ctrl-C 断开并退出`,
1361
+ );
1362
+ }
1363
+
1364
+ const pollUrl = new URL(`${apiRoot}/api/local/poll`);
1365
+ if (connectionId) pollUrl.searchParams.set('connection_id', connectionId);
1366
+ pollUrl.searchParams.set('timeout', String(opts.pollTimeoutSec ?? 25));
1367
+
1368
+ const pollResp = await fetchImpl(pollUrl.href, {
1369
+ method: 'GET',
1370
+ headers: {
1371
+ Authorization: `Bearer ${token}`,
1372
+ },
1373
+ signal: signal
1374
+ ? AbortSignal.any([signal, AbortSignal.timeout(((opts.pollTimeoutSec ?? 25) + 10) * 1000)])
1375
+ : AbortSignal.timeout(((opts.pollTimeoutSec ?? 25) + 10) * 1000),
1376
+ });
1377
+
1378
+ if (pollResp.status === 401 || pollResp.status === 403) {
1379
+ throw new ConnectorError(
1380
+ 'unauthorized',
1381
+ `Oil Slide 登录状态已失效。请运行:${LOGIN_CMD}`,
1382
+ 3,
1383
+ );
1384
+ }
1385
+ if (pollResp.status === 409 || pollResp.status === 404) {
1386
+ const errData = await pollResp.json().catch(() => ({}));
1387
+ if (errData?.error === 'connection_replaced') {
1388
+ console.error('当前连接已被同账号的新连接替换,正在退出。');
1389
+ return 0;
1390
+ }
1391
+ connectionId = null;
1392
+ continue;
1393
+ }
1394
+ if (!pollResp.ok) {
1395
+ throw new Error(`轮询请求异常 (HTTP ${pollResp.status})`);
1396
+ }
1397
+
1398
+ const pollData = await pollResp.json();
1399
+ const requests = Array.isArray(pollData?.requests)
1400
+ ? pollData.requests
1401
+ : pollData?.request
1402
+ ? [pollData.request]
1403
+ : [];
1404
+
1405
+ for (const reqItem of requests) {
1406
+ if (!reqItem || !reqItem.id) continue;
1407
+ await executeRelayRequest(sandbox, reqItem, { apiRoot, token, fetchImpl });
1408
+ }
1409
+
1410
+ if (opts.once) {
1411
+ return 0;
1412
+ }
1413
+ } catch (err) {
1414
+ if (signal?.aborted) break;
1415
+ if (err instanceof ConnectorError && err.exitCode === 3) {
1416
+ throw err;
1417
+ }
1418
+ if (opts.once) {
1419
+ throw err;
1420
+ }
1421
+ console.error(`[oiloil-connect] 连接中断(${err instanceof Error ? err.message : String(err)}),${Math.round(backoffMs / 1000)}s 后重连...`);
1422
+ await delay(backoffMs, undefined, { signal }).catch(() => {});
1423
+ backoffMs = Math.min(30000, backoffMs * 2);
1424
+ }
1425
+ }
1426
+
1427
+ await closeConnection();
1428
+ return 0;
1429
+ }
1430
+
1431
+ export async function main(argv = process.argv.slice(2)) {
1432
+ try {
1433
+ const parsed = parseConnectArgs(argv);
1434
+ if (parsed.help) {
1435
+ console.log(HELP);
1436
+ return 0;
1437
+ }
1438
+
1439
+ const sandbox = await LocalSandbox.create(parsed.folder);
1440
+
1441
+ if (parsed.mcpStdio) {
1442
+ await runMcpStdioServer(sandbox);
1443
+ return 0;
1444
+ }
1445
+
1446
+ const apiRoot = resolveApiRoot();
1447
+ let token = await readOilToken();
1448
+ if (!token) {
1449
+ console.log('首次使用需要登录 Oil Slide,正在打开登录流程…');
1450
+ const { main: imageMain } = await import('./oiloil-image.mjs');
1451
+ const loginCode = await imageMain(['login']);
1452
+ token = loginCode ? null : await readOilToken();
1453
+ }
1454
+ if (!token) {
1455
+ throw new ConnectorError(
1456
+ 'not_logged_in',
1457
+ `尚未登录 Oil Slide,无法连接工作区文件夹。请先运行:\n ${LOGIN_CMD}`,
1458
+ 3,
1459
+ );
1460
+ }
1461
+
1462
+ const abortController = new AbortController();
1463
+ const onSignal = () => {
1464
+ if (!abortController.signal.aborted) {
1465
+ console.log('\n正在断开工作区连接...');
1466
+ abortController.abort();
1467
+ }
1468
+ };
1469
+ process.once('SIGINT', onSignal);
1470
+ process.once('SIGTERM', onSignal);
1471
+ try {
1472
+ return await runCloudConnector(sandbox, parsed, {
1473
+ apiRoot,
1474
+ token,
1475
+ signal: abortController.signal,
1476
+ });
1477
+ } finally {
1478
+ process.removeListener('SIGINT', onSignal);
1479
+ process.removeListener('SIGTERM', onSignal);
1480
+ }
1481
+ } catch (error) {
1482
+ if (error instanceof ConnectorError) {
1483
+ console.error(error.message);
1484
+ return error.exitCode || 1;
1485
+ }
1486
+ console.error('运行工作区连接器时发生意外错误,请检查目录权限与网络后重试。');
1487
+ return 1;
1488
+ }
1489
+ }
1490
+
1491
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
1492
+ process.exitCode = await main();
1493
+ }