dsh-worktree-workspace 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/client.js +521 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +13 -0
- package/index.js +403 -0
- package/lib/typert.host.js +287 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +55 -4
package/index.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git Worktree 插件 · 宿主半边(v6)
|
|
3
|
+
*
|
|
4
|
+
* 形态与官方 @deepseek-ai/dsh-command-feedback 完全同构:
|
|
5
|
+
* export const name / inject + export async function apply(ctx)
|
|
6
|
+
* apply 内 await loadProtocol() 拿到 typert 三件套后定义并注册服务类。
|
|
7
|
+
*
|
|
8
|
+
* 提供两个 Remote 方法(namespace 'worktreeWorkspace',与 client.js 端点前缀一致):
|
|
9
|
+
* - inspect({cwd}) 读取仓库信息(分支/worktree 清单/上次位置)
|
|
10
|
+
* - create({cwd, from?, branch?, directory?, parentDir?}) 按 DSH 官方序列建树
|
|
11
|
+
*
|
|
12
|
+
* 工作区注册由客户端调用原生 workspaces.create({path}) 完成。
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID, randomBytes } from 'node:crypto';
|
|
15
|
+
import { mkdir, lstat, readFile, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { statSync } from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const POOL_DIRECTORY = '.agents/worktrees';
|
|
21
|
+
const NAME_PREFIX = 'dsh-';
|
|
22
|
+
const COMMAND_TIMEOUT_MS = 120_000;
|
|
23
|
+
const COMMAND_GRACE_MS = 3_000;
|
|
24
|
+
const MAX_OUTPUT_BYTES = 65_536;
|
|
25
|
+
const PREFS_FILE_NAME = 'dsh-worktree-prefs.json';
|
|
26
|
+
|
|
27
|
+
/** 清除宿主进程的 git 选择器变量,避免 git 命令打错仓库。 */
|
|
28
|
+
const GIT_SELECTOR_ENV_KEYS = [
|
|
29
|
+
'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE',
|
|
30
|
+
'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG',
|
|
31
|
+
'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_CEILING_DIRECTORIES',
|
|
32
|
+
'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE', 'GIT_REPLACE_REF_BASE',
|
|
33
|
+
'GIT_ATTR_SOURCE',
|
|
34
|
+
];
|
|
35
|
+
const GIT_BASE_ENV = {
|
|
36
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
37
|
+
GIT_LFS_SKIP_SMUDGE: '1',
|
|
38
|
+
GIT_NO_LAZY_FETCH: '1',
|
|
39
|
+
};
|
|
40
|
+
const GIT_GLOBAL_ARGS = ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false'];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 定位 ASAR 内 @deepseek-ai/dsh-typert-protocol 入口。
|
|
44
|
+
* 本插件在 profiles 树的链接 checkout 里,不在宿主 ESM 拦截层内,裸导入不可用;
|
|
45
|
+
* 通过锚点回溯找到 ASAR 内真实路径后动态 import,命中宿主已加载的同一实例。
|
|
46
|
+
*/
|
|
47
|
+
function findProtocolEntry() {
|
|
48
|
+
const candidates = [];
|
|
49
|
+
if (process.env.DSH_INSTALL_DIR) candidates.push(process.env.DSH_INSTALL_DIR);
|
|
50
|
+
try {
|
|
51
|
+
candidates.push(path.join(path.dirname(process.execPath), 'resources', 'app.asar', 'dsh'));
|
|
52
|
+
} catch {
|
|
53
|
+
/* execPath 不可用时跳过 */
|
|
54
|
+
}
|
|
55
|
+
if (process.env.DSH_NODE_EXECUTABLE) {
|
|
56
|
+
candidates.push(path.join(path.dirname(process.env.DSH_NODE_EXECUTABLE), 'resources', 'app.asar', 'dsh'));
|
|
57
|
+
}
|
|
58
|
+
candidates.push('C:\\Users\\admin\\AppData\\Local\\Programs\\DeepSeek Harness\\resources\\app.asar\\dsh');
|
|
59
|
+
|
|
60
|
+
for (const anchor of candidates) {
|
|
61
|
+
if (!anchor) continue;
|
|
62
|
+
let dir = path.resolve(anchor);
|
|
63
|
+
for (let hop = 0; hop < 8 && dir; hop += 1) {
|
|
64
|
+
const candidate = path.join(dir, 'node_modules', '@deepseek-ai', 'dsh-typert-protocol', 'lib', 'index.js');
|
|
65
|
+
try {
|
|
66
|
+
if (statSync(candidate).isFile()) return candidate;
|
|
67
|
+
} catch {
|
|
68
|
+
/* 向上继续 */
|
|
69
|
+
}
|
|
70
|
+
const parent = path.dirname(dir);
|
|
71
|
+
if (parent === dir) break;
|
|
72
|
+
dir = parent;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let protocolPromise;
|
|
79
|
+
function loadProtocol() {
|
|
80
|
+
protocolPromise ??= (async () => {
|
|
81
|
+
const found = findProtocolEntry();
|
|
82
|
+
if (!found) throw new Error('无法定位 @deepseek-ai/dsh-typert-protocol');
|
|
83
|
+
return await import(pathToFileURL(found).href);
|
|
84
|
+
})();
|
|
85
|
+
return protocolPromise;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const name = 'worktree-workspace';
|
|
89
|
+
export const inject = [];
|
|
90
|
+
|
|
91
|
+
export async function apply(ctx) {
|
|
92
|
+
const { Remote, RemoteError, TypertRemoteService } = await loadProtocol();
|
|
93
|
+
|
|
94
|
+
const failed = (code, message) => new RemoteError(`worktree-workspace/${code}`, message, {});
|
|
95
|
+
|
|
96
|
+
/** 目录/分支「名称段」合法性:禁分隔符与盘符(用于分支名与落盘目录名)。 */
|
|
97
|
+
const validName = (value) => {
|
|
98
|
+
const trimmed = value?.trim();
|
|
99
|
+
if (!trimmed || trimmed.length > 120) return null;
|
|
100
|
+
if (trimmed.includes('\\') || trimmed.includes(':')) return null;
|
|
101
|
+
if (trimmed === '.' || trimmed === '..') return null;
|
|
102
|
+
return trimmed;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 工作目录(cwd)合法性:跨平台绝对路径校验。
|
|
107
|
+
* Windows:`D:\repo` 或 `D:/repo`(盘符 + 分隔符均可);POSIX:以 `/` 开头。
|
|
108
|
+
* UNC 路径 `\\server\share` 也接受。拒绝相对路径与空值。
|
|
109
|
+
*/
|
|
110
|
+
const validCwd = (value) => {
|
|
111
|
+
const trimmed = value?.trim();
|
|
112
|
+
if (!trimmed) return null;
|
|
113
|
+
// Windows 盘符路径:C:\ 或 C:/(大小写不限)
|
|
114
|
+
if (/^[A-Za-z]:[/\\]/.test(trimmed)) return trimmed;
|
|
115
|
+
// Windows UNC:\\server\share 或 //server/share
|
|
116
|
+
if (/^[/\\]{2}[^/\\]/.test(trimmed)) return trimmed;
|
|
117
|
+
// POSIX 绝对路径
|
|
118
|
+
if (trimmed.startsWith('/')) return trimmed;
|
|
119
|
+
return null;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const generatedBranchName = () => {
|
|
123
|
+
const short = randomUUID().replaceAll('-', '').slice(0, 8);
|
|
124
|
+
return `${NAME_PREFIX}${short}-${randomBytes(2).toString('hex')}`;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 是否跳过沙箱 confine:
|
|
129
|
+
* worktree add / reset 是「写主仓库 .git 元数据」的命令(创建 refs、注册 worktree),
|
|
130
|
+
* 沙箱写入白名单通常只覆盖会话 cwd,不含主仓库 .git —— confine 会导致
|
|
131
|
+
* "Unable to create .git/refs/heads/xxx.lock: Permission denied"。
|
|
132
|
+
* 这些命令与官方 worktree 服务一样直跑;只读探测命令仍走 confine。
|
|
133
|
+
* 注意:git 的全局选项(--work-tree 等)可以出现在子命令之前,
|
|
134
|
+
* 所以必须扫描整个 args 而不是只看 args[0]。
|
|
135
|
+
*/
|
|
136
|
+
const WRITE_COMMANDS = new Set(['worktree', 'reset']);
|
|
137
|
+
|
|
138
|
+
/** args 里任意位置(跳过 -c/--work-tree 等选项的值)出现写子命令即为写操作。 */
|
|
139
|
+
function isWriteCommand(args) {
|
|
140
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
141
|
+
const token = args[index];
|
|
142
|
+
if (token === '--work-tree' || token === '-C') {
|
|
143
|
+
index += 1;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (token.startsWith('--work-tree=')) continue;
|
|
147
|
+
if (WRITE_COMMANDS.has(token)) return true;
|
|
148
|
+
// 遇到第一个真正的子命令(非选项)后停止扫描
|
|
149
|
+
if (!token.startsWith('-')) return false;
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function runGit(ctx2, policy, cwd, args, allowedExitCodes = [0], extraEnv = {}) {
|
|
155
|
+
const signal = AbortSignal.timeout(COMMAND_TIMEOUT_MS);
|
|
156
|
+
const git = await ctx2.subprocess.resolveExecutable('git', undefined, signal);
|
|
157
|
+
const argv = [git, ...GIT_GLOBAL_ARGS, ...args];
|
|
158
|
+
// 写主仓库 .git 的命令跳过沙箱(官方 worktree 服务对写操作同样绕过 confine);
|
|
159
|
+
// 策略本身已是宿主级的 danger-full-access 或经 sandboxPolicy 授权。
|
|
160
|
+
const isWrite = isWriteCommand(args);
|
|
161
|
+
const wrapped = policy?.mode === 'danger-full-access' || isWrite
|
|
162
|
+
? argv
|
|
163
|
+
: (await ctx2.sandbox.confine(argv, policy, signal)).argv;
|
|
164
|
+
const env = { ...process.env };
|
|
165
|
+
for (const key of GIT_SELECTOR_ENV_KEYS) env[key] = undefined;
|
|
166
|
+
Object.assign(env, GIT_BASE_ENV, extraEnv);
|
|
167
|
+
const child = ctx2.subprocess.spawn({
|
|
168
|
+
argv: wrapped,
|
|
169
|
+
cwd,
|
|
170
|
+
env,
|
|
171
|
+
signal,
|
|
172
|
+
graceMs: COMMAND_GRACE_MS,
|
|
173
|
+
stdio: {
|
|
174
|
+
stdin: 'ignore',
|
|
175
|
+
stdout: { maxBytes: MAX_OUTPUT_BYTES },
|
|
176
|
+
stderr: { maxBytes: MAX_OUTPUT_BYTES },
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
try {
|
|
180
|
+
const done = await child.done;
|
|
181
|
+
if (signal.aborted) throw failed('git-timeout', `git ${args[0]} 超时`);
|
|
182
|
+
const stdout = await child.collected.stdout.readFrom(0);
|
|
183
|
+
if (stdout.lossy) throw failed('git-output-overflow', `git ${args[0]} 输出超限`);
|
|
184
|
+
if (!allowedExitCodes.includes(done.exitCode)) {
|
|
185
|
+
const stderr = (await child.collected.stderr.readFrom(0)).text.trim();
|
|
186
|
+
throw failed('git-failed', `git ${args[0]} 退出码 ${done.exitCode}${stderr ? `:${stderr}` : ''}`);
|
|
187
|
+
}
|
|
188
|
+
return { exitCode: done.exitCode, text: stdout.text };
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
child.terminate();
|
|
192
|
+
await child.waitForExit();
|
|
193
|
+
} catch { /* 收尾失败不掩盖主流程 */ }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function filterOverrides(ctx2, policy, root) {
|
|
198
|
+
const probe = await runGit(ctx2, policy, root,
|
|
199
|
+
['config', '--null', '--name-only', '--get-regexp', '^filter\\.'], [0, 1]);
|
|
200
|
+
if (!probe.text) return {};
|
|
201
|
+
const drivers = new Set();
|
|
202
|
+
for (const raw of probe.text.split('\0')) {
|
|
203
|
+
const key = raw.trim();
|
|
204
|
+
const match = /^filter\.(.+)\.(clean|smudge|process|required)$/.exec(key);
|
|
205
|
+
if (match) drivers.add(match[1]);
|
|
206
|
+
}
|
|
207
|
+
if (drivers.size === 0) return {};
|
|
208
|
+
const overrides = { GIT_CONFIG_COUNT: String(drivers.size * 4) };
|
|
209
|
+
let index = 0;
|
|
210
|
+
for (const driver of drivers) {
|
|
211
|
+
for (const attr of ['clean', 'smudge', 'process', 'required']) {
|
|
212
|
+
overrides[`GIT_CONFIG_KEY_${index}`] = `filter.${driver}.${attr}`;
|
|
213
|
+
overrides[`GIT_CONFIG_VALUE_${index}`] = attr === 'required' ? 'false' : '';
|
|
214
|
+
index += 1;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return overrides;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** @Remote 装饰器的纯 JS shim(与官方标准装饰器语义一致)。 */
|
|
221
|
+
function applyRemoteDecorator(serviceClass, methodName, exportName) {
|
|
222
|
+
const initializers = [];
|
|
223
|
+
const context = {
|
|
224
|
+
kind: 'method',
|
|
225
|
+
name: methodName,
|
|
226
|
+
static: false,
|
|
227
|
+
private: false,
|
|
228
|
+
access: {
|
|
229
|
+
has: (instance) => methodName in instance,
|
|
230
|
+
get: (instance) => instance[methodName],
|
|
231
|
+
},
|
|
232
|
+
addInitializer: (fn) => initializers.push(fn),
|
|
233
|
+
};
|
|
234
|
+
Remote(exportName)(serviceClass.prototype[methodName], context);
|
|
235
|
+
for (const fn of initializers) fn.call(serviceClass);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function resolvePolicy(ctx2, request) {
|
|
239
|
+
try {
|
|
240
|
+
const session = typeof request?.sessionId === 'string' && request.sessionId.length > 0
|
|
241
|
+
? ctx2.sessions.get(request.sessionId)
|
|
242
|
+
: undefined;
|
|
243
|
+
return ctx2.sandboxPolicy.resolve({ session });
|
|
244
|
+
} catch {
|
|
245
|
+
return { mode: 'danger-full-access' };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function parseWorktreeList(text, repositoryRoot) {
|
|
250
|
+
const normalized = path.resolve(repositoryRoot);
|
|
251
|
+
const worktrees = [];
|
|
252
|
+
let current = null;
|
|
253
|
+
for (const line of text.split('\n')) {
|
|
254
|
+
if (line.startsWith('worktree ')) {
|
|
255
|
+
if (current) worktrees.push(current);
|
|
256
|
+
current = { path: path.resolve(line.slice(9).trim()), branch: '', head: '', isMain: false };
|
|
257
|
+
} else if (current && line.startsWith('HEAD ')) {
|
|
258
|
+
current.head = line.slice(5).trim();
|
|
259
|
+
} else if (current && line.startsWith('branch ')) {
|
|
260
|
+
current.branch = line.slice(7).trim().replace(/^refs\/heads\//, '');
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (current) worktrees.push(current);
|
|
264
|
+
return worktrees.map((item, index) => ({ ...item, isMain: index === 0 || item.path === normalized }));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function readPrefs(commonDir) {
|
|
268
|
+
try {
|
|
269
|
+
const parsed = JSON.parse(await readFile(path.join(commonDir, PREFS_FILE_NAME), 'utf8'));
|
|
270
|
+
return typeof parsed?.lastParentDir === 'string' && parsed.lastParentDir.length > 0 ? parsed : null;
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function writePrefs(commonDir, patch) {
|
|
277
|
+
const previous = (await readPrefs(commonDir)) ?? {};
|
|
278
|
+
try {
|
|
279
|
+
await writeFile(path.join(commonDir, PREFS_FILE_NAME), `${JSON.stringify({ ...previous, ...patch }, null, 2)}\n`, 'utf8');
|
|
280
|
+
} catch { /* 偏好写入失败忽略 */ }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function resolveCommonDir(ctx2, policy, root) {
|
|
284
|
+
const result = await runGit(ctx2, policy, root, ['rev-parse', '--git-common-dir']);
|
|
285
|
+
return path.resolve(root, result.text.trim());
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function resolveRepositoryRoot(ctx2, policy, cwd) {
|
|
289
|
+
const result = await runGit(ctx2, policy, cwd, ['rev-parse', '--show-toplevel'], [0, 128]);
|
|
290
|
+
const topLevel = result.text.trim();
|
|
291
|
+
if (!topLevel) throw failed('not-git', '当前目录不是 git 仓库');
|
|
292
|
+
return path.resolve(topLevel);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function inspectRepository(ctx2, policy, root) {
|
|
296
|
+
const branchResult = await runGit(ctx2, policy, root, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
297
|
+
const rawBranch = branchResult.text.trim();
|
|
298
|
+
const currentBranch = rawBranch && rawBranch !== 'HEAD' ? rawBranch : '';
|
|
299
|
+
|
|
300
|
+
const heads = await runGit(ctx2, policy, root, ['for-each-ref', '--format', '%(refname:short)', 'refs/heads']);
|
|
301
|
+
const remotes = await runGit(ctx2, policy, root, ['for-each-ref', '--format', '%(refname:short)', 'refs/remotes']);
|
|
302
|
+
const branches = [...new Set([...heads.text.split('\n'), ...remotes.text.split('\n')]
|
|
303
|
+
.map((line) => line.trim()).filter(Boolean))];
|
|
304
|
+
|
|
305
|
+
let defaultBase = branches.find((n) => n === 'origin/main')
|
|
306
|
+
?? branches.find((n) => n === 'origin/master')
|
|
307
|
+
?? branches.find((n) => n === 'main')
|
|
308
|
+
?? branches.find((n) => n === 'master')
|
|
309
|
+
?? branches[0];
|
|
310
|
+
if (!defaultBase) defaultBase = 'main';
|
|
311
|
+
|
|
312
|
+
const listing = await runGit(ctx2, policy, root, ['worktree', 'list', '--porcelain']);
|
|
313
|
+
const worktrees = parseWorktreeList(listing.text, root);
|
|
314
|
+
|
|
315
|
+
return { currentBranch, defaultBase, branches, worktrees };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function createWorktree(ctx2, policy, root, request, prefs) {
|
|
319
|
+
const branch = validName(request.branch ?? '') ?? generatedBranchName();
|
|
320
|
+
const branchCheck = await runGit(ctx2, policy, root, ['check-ref-format', `refs/heads/${branch}`], [0, 1]);
|
|
321
|
+
if (branchCheck.exitCode !== 0) throw failed('invalid-branch', `分支名不合法:${branch}`);
|
|
322
|
+
|
|
323
|
+
const from = request.from?.trim() || 'HEAD';
|
|
324
|
+
const baseResult = await runGit(ctx2, policy, root,
|
|
325
|
+
['rev-parse', '--verify', '--end-of-options', `${from}^{commit}`], [0, 1]);
|
|
326
|
+
if (baseResult.exitCode !== 0) throw failed('invalid-from', `基线不可解析:${from}`);
|
|
327
|
+
const baseCommit = baseResult.text.trim();
|
|
328
|
+
|
|
329
|
+
const exists = await runGit(ctx2, policy, root,
|
|
330
|
+
['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]);
|
|
331
|
+
if (exists.exitCode === 0) throw failed('branch-exists', `分支已存在:${branch}`);
|
|
332
|
+
|
|
333
|
+
const directory = validName(request.directory ?? '') ?? validName(branch.split('/').pop() ?? '');
|
|
334
|
+
if (!directory) throw failed('invalid-name', `目录名不合法:${request.directory ?? branch}`);
|
|
335
|
+
// 位置:显式传入 → 上次记忆 → 仓库默认池目录;必须是跨平台绝对路径。
|
|
336
|
+
const parentDirInput = request.parentDir?.trim() || prefs?.lastParentDir || path.join(root, POOL_DIRECTORY);
|
|
337
|
+
if (!validCwd(parentDirInput)) throw failed('invalid-parent', `位置必须是绝对路径:${parentDirInput}`);
|
|
338
|
+
const parentDir = path.resolve(parentDirInput);
|
|
339
|
+
const target = path.join(parentDir, directory);
|
|
340
|
+
|
|
341
|
+
let existing = null;
|
|
342
|
+
try {
|
|
343
|
+
existing = await lstat(target);
|
|
344
|
+
} catch {
|
|
345
|
+
existing = null;
|
|
346
|
+
}
|
|
347
|
+
if (existing) throw failed('path-exists', `目标目录已存在:${target}`);
|
|
348
|
+
|
|
349
|
+
await mkdir(path.resolve(parentDir), { recursive: true });
|
|
350
|
+
const overrides = await filterOverrides(ctx2, policy, root);
|
|
351
|
+
await runGit(ctx2, policy, root,
|
|
352
|
+
['--work-tree', root, 'worktree', 'add', '--no-checkout', '-b', branch, '--', target, baseCommit],
|
|
353
|
+
[0], overrides);
|
|
354
|
+
await runGit(ctx2, policy, target,
|
|
355
|
+
['--work-tree', target, 'reset', '--hard', '--no-recurse-submodules', baseCommit],
|
|
356
|
+
[0], overrides);
|
|
357
|
+
|
|
358
|
+
await writePrefs(await resolveCommonDir(ctx2, policy, root), { lastParentDir: path.resolve(parentDir) });
|
|
359
|
+
return { path: target, branch, baseCommit, repositoryRoot: root };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** 服务类:static inject 与官方 command-feedback 一致(仅声明真正必需的服务)。 */
|
|
363
|
+
class WorktreeWorkspaceService extends TypertRemoteService {
|
|
364
|
+
static inject = ['sessions', 'subprocess', 'sandbox', 'sandboxPolicy', 'typert'];
|
|
365
|
+
|
|
366
|
+
constructor(ctx2) {
|
|
367
|
+
// 命名空间必须与 client.js 端点前缀 'worktreeWorkspace' 完全一致(网关按此路由)。
|
|
368
|
+
super(ctx2, 'worktreeWorkspace');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async inspect(request) {
|
|
372
|
+
const cwd = validCwd(request?.cwd) ? request.cwd : '';
|
|
373
|
+
if (!cwd) throw failed('invalid-cwd', '缺少有效的工作目录(cwd)——需要绝对路径');
|
|
374
|
+
const policy = resolvePolicy(this.ctx, request);
|
|
375
|
+
const repositoryRoot = await resolveRepositoryRoot(this.ctx, policy, path.resolve(cwd));
|
|
376
|
+
const commonDir = await resolveCommonDir(this.ctx, policy, repositoryRoot);
|
|
377
|
+
const prefs = await readPrefs(commonDir);
|
|
378
|
+
const info = await inspectRepository(this.ctx, policy, repositoryRoot);
|
|
379
|
+
return {
|
|
380
|
+
repositoryRoot,
|
|
381
|
+
currentBranch: info.currentBranch,
|
|
382
|
+
defaultBase: info.defaultBase,
|
|
383
|
+
branches: info.branches,
|
|
384
|
+
worktrees: info.worktrees,
|
|
385
|
+
lastParentDir: prefs?.lastParentDir ?? null,
|
|
386
|
+
defaultParentDir: path.join(repositoryRoot, POOL_DIRECTORY),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async create(request) {
|
|
391
|
+
const cwd = validCwd(request?.cwd) ? request.cwd : '';
|
|
392
|
+
if (!cwd) throw failed('invalid-cwd', '缺少有效的工作目录(cwd)——需要绝对路径');
|
|
393
|
+
const policy = resolvePolicy(this.ctx, request);
|
|
394
|
+
const repositoryRoot = await resolveRepositoryRoot(this.ctx, policy, path.resolve(cwd));
|
|
395
|
+
const commonDir = await resolveCommonDir(this.ctx, policy, repositoryRoot);
|
|
396
|
+
const prefs = await readPrefs(commonDir);
|
|
397
|
+
return createWorktree(this.ctx, policy, repositoryRoot, request ?? {}, prefs);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
applyRemoteDecorator(WorktreeWorkspaceService, 'inspect', 'inspect');
|
|
401
|
+
applyRemoteDecorator(WorktreeWorkspaceService, 'create', 'create');
|
|
402
|
+
ctx.plugin(WorktreeWorkspaceService);
|
|
403
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git Worktree 插件 · Typert 宿主清单(./typert)
|
|
3
|
+
*
|
|
4
|
+
* 由 dsh-typert-loader 自动发现:package.json exports['./typert'] 指向本文件。
|
|
5
|
+
* loader 通过 pathToFileURL(path) 直接 import 本文件,并把 TYPERT 清单注册进
|
|
6
|
+
* ctx.typert——使网关 strict 路由表包含本插件的端点(HTTP /api/worktreeWorkspace/*)。
|
|
7
|
+
*
|
|
8
|
+
* 稳定性约束(v7 修复):之前版本在模块顶层 await import(zod) 且 zod 路径找不到时
|
|
9
|
+
* 直接 throw,导致 typert-loader 激活期 AggregateError → 宿主启动崩溃
|
|
10
|
+
* ("desktop welcome: Web RPC failed")。本版本:
|
|
11
|
+
* - zod 定位失败时导出空 manifest(schemas/invocations/model 全空),
|
|
12
|
+
* strict 路由不可用但宿主照常启动,服务回退到 SRC 路径;
|
|
13
|
+
* - 永不在模块顶层抛错。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { existsSync, statSync } from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const PACKAGE_NAME = '@local/worktree-workspace';
|
|
21
|
+
|
|
22
|
+
/** 空 manifest:typert-loader 校验通过但不贡献任何端点。 */
|
|
23
|
+
function emptyManifest(reason) {
|
|
24
|
+
try { console.warn('[worktree-workspace] typert.host: ' + reason); } catch { /* ignore */ }
|
|
25
|
+
return {
|
|
26
|
+
package: PACKAGE_NAME,
|
|
27
|
+
face: 'host',
|
|
28
|
+
schemas: [],
|
|
29
|
+
invocations: [],
|
|
30
|
+
model: { services: [], events: [], objects: [] },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 在 DSH 安装根 node_modules 下定位 zod 的 ESM 入口文件。 */
|
|
35
|
+
function findZodEntry() {
|
|
36
|
+
const anchors = [];
|
|
37
|
+
if (process.env.DSH_INSTALL_DIR) anchors.push(process.env.DSH_INSTALL_DIR);
|
|
38
|
+
try {
|
|
39
|
+
anchors.push(path.join(path.dirname(process.execPath), 'resources', 'app.asar', 'dsh'));
|
|
40
|
+
} catch { /* ignore */ }
|
|
41
|
+
if (process.env.DSH_NODE_EXECUTABLE) {
|
|
42
|
+
anchors.push(path.join(path.dirname(process.env.DSH_NODE_EXECUTABLE), 'resources', 'app.asar', 'dsh'));
|
|
43
|
+
}
|
|
44
|
+
anchors.push('C:\\Users\\admin\\AppData\\Local\\Programs\\DeepSeek Harness\\resources\\app.asar\\dsh');
|
|
45
|
+
anchors.push(process.env.WTW_STUB ?? '');
|
|
46
|
+
|
|
47
|
+
for (const anchor of anchors) {
|
|
48
|
+
if (!anchor) continue;
|
|
49
|
+
let dir = path.resolve(anchor);
|
|
50
|
+
for (let hop = 0; hop < 8 && dir; hop += 1) {
|
|
51
|
+
const zodEntry = path.join(dir, 'node_modules', 'zod', 'index.js');
|
|
52
|
+
try {
|
|
53
|
+
if (statSync(zodEntry).isFile()) return zodEntry;
|
|
54
|
+
} catch { /* 向上继续 */ }
|
|
55
|
+
const parent = path.dirname(dir);
|
|
56
|
+
if (parent === dir) break;
|
|
57
|
+
dir = parent;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// 模块顶层:加载 zod(失败不抛错,走空 manifest 兜底)
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
let z = null;
|
|
68
|
+
let loadError = null;
|
|
69
|
+
try {
|
|
70
|
+
const zodEntry = findZodEntry();
|
|
71
|
+
if (!zodEntry) throw new Error('未找到宿主 zod(zod/index.js)');
|
|
72
|
+
const mod = await import(pathToFileURL(zodEntry).href);
|
|
73
|
+
// zod 的 ESM 入口(v4.6.6)把 CJS module.exports 挂在 default 上,两种形态都兜住。
|
|
74
|
+
const lib = mod.z ?? mod.default?.z ?? mod.default;
|
|
75
|
+
if (typeof lib?.object !== 'function') throw new Error('zod.object 不可用');
|
|
76
|
+
z = lib;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
loadError = String(error?.message ?? error);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// 内联 @deepseek-ai/dsh-typert-protocol/lib/types/remote-info.js(自包含实现)
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
function createTypertRemoteInfo(spec, zod) {
|
|
86
|
+
return new RemoteInfo(spec, zod);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
class RemoteInfo {
|
|
90
|
+
spec; zod; index;
|
|
91
|
+
constructor(spec, zod) { this.spec = spec; this.zod = zod; }
|
|
92
|
+
get package() { return this.spec.package; }
|
|
93
|
+
get descriptors() { return this.resolve().descriptors; }
|
|
94
|
+
get methods() { return this.resolve().methods; }
|
|
95
|
+
resolve() {
|
|
96
|
+
if (this.index !== undefined) return this.index;
|
|
97
|
+
const zod = this.zod;
|
|
98
|
+
const descriptors = [];
|
|
99
|
+
const methods = Object.create(null);
|
|
100
|
+
for (const [endpoint, definition] of Object.entries(this.spec.methods)) {
|
|
101
|
+
const separator = endpoint.indexOf('/');
|
|
102
|
+
const namespace = endpoint.slice(0, separator);
|
|
103
|
+
const method = endpoint.slice(separator + 1);
|
|
104
|
+
const parameters = definition.parameters.map(parameter => ({ ...parameter, wire: parameter.wire ?? parameter.name }));
|
|
105
|
+
const descriptor = {
|
|
106
|
+
...definition,
|
|
107
|
+
id: `${this.spec.package}#${endpoint}`,
|
|
108
|
+
namespace,
|
|
109
|
+
method,
|
|
110
|
+
parameters,
|
|
111
|
+
result: definition.result.description === undefined ? definition.result : new ResultValue(definition.result),
|
|
112
|
+
};
|
|
113
|
+
if (definition.invocation.kind === 'direct') {
|
|
114
|
+
const inputs = [];
|
|
115
|
+
const direct = Object.assign(descriptor, {
|
|
116
|
+
input(options) {
|
|
117
|
+
const strict = options?.strict === true;
|
|
118
|
+
return inputs[strict ? 1 : 0] ??= new NamedInput(parameters, strict, zod);
|
|
119
|
+
},
|
|
120
|
+
invoke(remote, input, signal) {
|
|
121
|
+
const named = input;
|
|
122
|
+
const values = parameters.map(parameter => named[parameter.wire]);
|
|
123
|
+
if (definition.cancellation !== undefined) values.push(signal);
|
|
124
|
+
const receiver = Reflect.get(remote, namespace);
|
|
125
|
+
const call = Reflect.get(receiver, method);
|
|
126
|
+
return call.apply(receiver, values);
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
methods[endpoint] = direct;
|
|
130
|
+
}
|
|
131
|
+
descriptors.push(descriptor);
|
|
132
|
+
}
|
|
133
|
+
return this.index = { descriptors, methods };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function optional(parameter) {
|
|
138
|
+
return parameter.source === 'json' && parameter.acceptsUndefined === true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
class NamedInput {
|
|
142
|
+
parameters; strict; zod; schema; projection;
|
|
143
|
+
constructor(parameters, strict, zod) { this.parameters = parameters; this.strict = strict; this.zod = zod; }
|
|
144
|
+
codec(parameter) { return this.strict ? parameter.strictCodec : parameter.codec; }
|
|
145
|
+
create = () => this.schema ??= this.zod.strictObject(Object.fromEntries(this.parameters.map((parameter) => {
|
|
146
|
+
const value = this.codec(parameter).create();
|
|
147
|
+
return [parameter.wire, optional(parameter) ? value.optional() : value.nonoptional()];
|
|
148
|
+
})));
|
|
149
|
+
get jsonSchema() { return this.project().jsonSchema; }
|
|
150
|
+
get jsonSchemaError() { return this.project().jsonSchemaError; }
|
|
151
|
+
project() {
|
|
152
|
+
if (this.projection !== undefined) return this.projection;
|
|
153
|
+
const unavailable = this.parameters.find(parameter => this.codec(parameter).jsonSchema === undefined);
|
|
154
|
+
if (unavailable !== undefined) {
|
|
155
|
+
return this.projection = { jsonSchemaError: this.codec(unavailable).jsonSchemaError ?? `No JSON Schema for parameter ${unavailable.wire}` };
|
|
156
|
+
}
|
|
157
|
+
return this.projection = {
|
|
158
|
+
jsonSchema: {
|
|
159
|
+
type: 'object',
|
|
160
|
+
properties: Object.fromEntries(this.parameters.map(parameter => [parameter.wire, {
|
|
161
|
+
...this.codec(parameter).jsonSchema,
|
|
162
|
+
...(parameter.description === undefined ? {} : { description: parameter.description }),
|
|
163
|
+
}])),
|
|
164
|
+
required: this.parameters.filter(parameter => !optional(parameter)).map(parameter => parameter.wire),
|
|
165
|
+
additionalProperties: false,
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
class ResultValue {
|
|
172
|
+
spec; projection;
|
|
173
|
+
constructor(spec) { this.spec = spec; }
|
|
174
|
+
get mode() { return this.spec.mode; }
|
|
175
|
+
get typeSymbol() { return this.spec.typeSymbol; }
|
|
176
|
+
get create() { return this.spec.create; }
|
|
177
|
+
get decode() { return this.spec.decode; }
|
|
178
|
+
get encode() { return this.spec.encode; }
|
|
179
|
+
get description() { return this.spec.description; }
|
|
180
|
+
get jsonSchemaError() { return this.spec.jsonSchemaError; }
|
|
181
|
+
get jsonSchema() {
|
|
182
|
+
if (this.projection === undefined) {
|
|
183
|
+
const schema = this.spec.jsonSchema;
|
|
184
|
+
this.projection = { value: schema === undefined ? undefined : { ...schema, description: this.spec.description } };
|
|
185
|
+
}
|
|
186
|
+
return this.projection.value;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ---------------------------------------------------------------------------
|
|
191
|
+
// 清单构建
|
|
192
|
+
// ---------------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
function buildManifest() {
|
|
195
|
+
if (z === null) return emptyManifest('zod 加载失败:' + loadError);
|
|
196
|
+
|
|
197
|
+
const INSPECT_SCHEMA = z.object({ cwd: z.string() }).readonly();
|
|
198
|
+
const INSPECT_RESULT = z.object({
|
|
199
|
+
repositoryRoot: z.string(),
|
|
200
|
+
currentBranch: z.string(),
|
|
201
|
+
defaultBase: z.string(),
|
|
202
|
+
branches: z.array(z.string()),
|
|
203
|
+
worktrees: z.array(z.object({
|
|
204
|
+
path: z.string(),
|
|
205
|
+
head: z.string().optional(),
|
|
206
|
+
branch: z.string().optional(),
|
|
207
|
+
isMain: z.boolean(),
|
|
208
|
+
})),
|
|
209
|
+
lastParentDir: z.string().nullable(),
|
|
210
|
+
}).readonly();
|
|
211
|
+
|
|
212
|
+
const CREATE_SCHEMA = z.object({
|
|
213
|
+
cwd: z.string(),
|
|
214
|
+
from: z.string().optional(),
|
|
215
|
+
branch: z.string().optional(),
|
|
216
|
+
directory: z.string().optional(),
|
|
217
|
+
parentDir: z.string().optional(),
|
|
218
|
+
sessionId: z.string().optional(),
|
|
219
|
+
}).readonly();
|
|
220
|
+
|
|
221
|
+
const CREATE_RESULT = z.object({
|
|
222
|
+
path: z.string(),
|
|
223
|
+
branch: z.string(),
|
|
224
|
+
baseCommit: z.string(),
|
|
225
|
+
repositoryRoot: z.string(),
|
|
226
|
+
}).readonly();
|
|
227
|
+
|
|
228
|
+
const codec = (schema) => ({
|
|
229
|
+
mode: 'strict',
|
|
230
|
+
typeSymbol: 'worktree-workspace',
|
|
231
|
+
create: () => schema,
|
|
232
|
+
jsonSchema: { type: 'object' },
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
const $remote = createTypertRemoteInfo({
|
|
236
|
+
package: PACKAGE_NAME,
|
|
237
|
+
methods: {
|
|
238
|
+
'worktreeWorkspace/inspect': {
|
|
239
|
+
service: 'worktreeWorkspace',
|
|
240
|
+
description: '读取 git 仓库信息(分支/工作树/上次位置)',
|
|
241
|
+
invocation: { kind: 'direct' },
|
|
242
|
+
parameters: [{
|
|
243
|
+
name: 'request', source: 'json',
|
|
244
|
+
codec: codec(INSPECT_SCHEMA), strictCodec: codec(INSPECT_SCHEMA),
|
|
245
|
+
jsonSchema: { type: 'object' },
|
|
246
|
+
}],
|
|
247
|
+
result: { mode: 'strict', typeSymbol: 'worktree-workspace.inspect', create: () => INSPECT_RESULT, jsonSchema: { type: 'object' } },
|
|
248
|
+
},
|
|
249
|
+
'worktreeWorkspace/create': {
|
|
250
|
+
service: 'worktreeWorkspace',
|
|
251
|
+
description: '创建 git 工作树(官方序列,不切会话不建工作区)',
|
|
252
|
+
invocation: { kind: 'direct' },
|
|
253
|
+
parameters: [{
|
|
254
|
+
name: 'request', source: 'json',
|
|
255
|
+
codec: codec(CREATE_SCHEMA), strictCodec: codec(CREATE_SCHEMA),
|
|
256
|
+
jsonSchema: { type: 'object' },
|
|
257
|
+
}],
|
|
258
|
+
result: { mode: 'strict', typeSymbol: 'worktree-workspace.create', create: () => CREATE_RESULT, jsonSchema: { type: 'object' } },
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
}, z);
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
package: PACKAGE_NAME,
|
|
265
|
+
face: 'host',
|
|
266
|
+
schemas: [],
|
|
267
|
+
get invocations() { return $remote.descriptors; },
|
|
268
|
+
model: {
|
|
269
|
+
services: [{
|
|
270
|
+
description: '创建/切换 git 工作树并配合客户端注册为独立工作区。',
|
|
271
|
+
summary: '创建/切换 git 工作树并注册为独立工作区。',
|
|
272
|
+
tags: [],
|
|
273
|
+
key: 'worktreeWorkspace',
|
|
274
|
+
exportName: 'WorktreeWorkspaceService',
|
|
275
|
+
members: [
|
|
276
|
+
{ kind: 'method', name: 'inspect', signature: 'inspect(request): Promise<repo info>', summary: '读取仓库信息' },
|
|
277
|
+
{ kind: 'method', name: 'create', signature: 'create(request): Promise<{ path, branch, baseCommit, repositoryRoot }>', summary: '创建工作树' },
|
|
278
|
+
],
|
|
279
|
+
types: [],
|
|
280
|
+
}],
|
|
281
|
+
events: [],
|
|
282
|
+
objects: [],
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export const TYPERT = buildManifest();
|