@laoyuehanni/dsh-git-worktree 0.4.14 → 0.4.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/README.zh.md +7 -2
- package/docs/DETAIL.md +4 -2
- package/docs/DETAIL.zh.md +4 -2
- package/lib/client.js +2490 -380
- package/lib/deferred-worktree.d.ts +104 -0
- package/lib/deferred-worktree.js +292 -0
- package/lib/git.d.ts +19 -0
- package/lib/git.js +81 -4
- package/lib/index.d.ts +13 -0
- package/lib/index.js +162 -4
- package/lib/normalize.d.ts +13 -0
- package/lib/normalize.js +51 -0
- package/lib/routes.d.ts +33 -2
- package/lib/routes.js +250 -79
- package/lib/wire.d.ts +99 -3
- package/lib/wire.js +11 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -7,13 +7,14 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { homedir } from 'node:os';
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
|
+
import { DeferredWorktreeCoordinator } from './deferred-worktree.js';
|
|
10
11
|
import { childProcessExec } from './git.js';
|
|
11
|
-
import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
12
|
+
import { executeCreateWorktree, handleArmDeferredWorktree, handleCreateBranch, handleCreateWorktree, handleDeferredWorktreeAction, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGetDeferredWorktree, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleSetSessionDirectory, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
12
13
|
import { validateRootDir } from './settings.js';
|
|
13
14
|
import { handleAuthors, handleHistory, handleCommit } from './routes.js';
|
|
14
15
|
import { ROUTE_AUTHORS, ROUTE_HISTORY, ROUTE_COMMIT } from './wire.js';
|
|
15
16
|
import { streamRoute } from './stream.js';
|
|
16
|
-
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
17
|
+
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_DEFERRED, ROUTE_DEFERRED_ACTION, ROUTE_DEFERRED_ARM, ROUTE_DEFERRED_EVENTS, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_SESSION_CWD, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
17
18
|
export const name = 'dsh-git-worktree';
|
|
18
19
|
export const inject = [];
|
|
19
20
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
@@ -41,10 +42,13 @@ export const Config = z.object({
|
|
|
41
42
|
autoPruneWorktrees: z.boolean().default(false).volatile(),
|
|
42
43
|
keepWorktrees: z.number().default(KEEP_WORKTREES_DEFAULT).volatile(),
|
|
43
44
|
postCreateCopyFiles: z.array(z.string()).default([]).volatile(),
|
|
45
|
+
hideOfficialWorktreeEntry: z.boolean().default(true).volatile(),
|
|
46
|
+
switchSessionDirectory: z.boolean().default(false).volatile(),
|
|
47
|
+
manageOfficialWorktrees: z.boolean().default(false).volatile(),
|
|
44
48
|
});
|
|
45
49
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
46
50
|
export function validateConfig(config) {
|
|
47
|
-
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'openGraphByDefault' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles');
|
|
51
|
+
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'openGraphByDefault' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles' && key !== 'hideOfficialWorktreeEntry' && key !== 'switchSessionDirectory' && key !== 'manageOfficialWorktrees');
|
|
48
52
|
if (unknown !== undefined) {
|
|
49
53
|
throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
|
|
50
54
|
}
|
|
@@ -68,6 +72,18 @@ export function validateConfig(config) {
|
|
|
68
72
|
if (autoPruneWorktrees !== undefined && typeof autoPruneWorktrees !== 'boolean') {
|
|
69
73
|
throw new Error('GitWorktreeConfig: "autoPruneWorktrees" must be a boolean');
|
|
70
74
|
}
|
|
75
|
+
const hideOfficialWorktreeEntry = readVolatile(config.hideOfficialWorktreeEntry);
|
|
76
|
+
if (hideOfficialWorktreeEntry !== undefined && typeof hideOfficialWorktreeEntry !== 'boolean') {
|
|
77
|
+
throw new Error('GitWorktreeConfig: "hideOfficialWorktreeEntry" must be a boolean');
|
|
78
|
+
}
|
|
79
|
+
const switchSessionDirectory = readVolatile(config.switchSessionDirectory);
|
|
80
|
+
if (switchSessionDirectory !== undefined && typeof switchSessionDirectory !== 'boolean') {
|
|
81
|
+
throw new Error('GitWorktreeConfig: "switchSessionDirectory" must be a boolean');
|
|
82
|
+
}
|
|
83
|
+
const manageOfficialWorktrees = readVolatile(config.manageOfficialWorktrees);
|
|
84
|
+
if (manageOfficialWorktrees !== undefined && typeof manageOfficialWorktrees !== 'boolean') {
|
|
85
|
+
throw new Error('GitWorktreeConfig: "manageOfficialWorktrees" must be a boolean');
|
|
86
|
+
}
|
|
71
87
|
const postCreateCopyFiles = readVolatile(config.postCreateCopyFiles);
|
|
72
88
|
if (postCreateCopyFiles !== undefined) {
|
|
73
89
|
if (!Array.isArray(postCreateCopyFiles) || !postCreateCopyFiles.every(item => typeof item === 'string')) {
|
|
@@ -103,6 +119,9 @@ export function sectionOf(config) {
|
|
|
103
119
|
const openGraphByDefault = readVolatile(config.openGraphByDefault);
|
|
104
120
|
const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
|
|
105
121
|
const keepWorktrees = readVolatile(config.keepWorktrees);
|
|
122
|
+
const hideOfficialWorktreeEntry = readVolatile(config.hideOfficialWorktreeEntry);
|
|
123
|
+
const switchSessionDirectory = readVolatile(config.switchSessionDirectory);
|
|
124
|
+
const manageOfficialWorktrees = readVolatile(config.manageOfficialWorktrees);
|
|
106
125
|
return {
|
|
107
126
|
...(rootDir === undefined ? {} : { rootDir }),
|
|
108
127
|
...(postCreateCopyFiles === undefined ? {} : { postCreateCopyFiles }),
|
|
@@ -113,8 +132,16 @@ export function sectionOf(config) {
|
|
|
113
132
|
openGraphByDefault: openGraphByDefault ?? false,
|
|
114
133
|
autoPruneWorktrees: autoPruneWorktrees ?? false,
|
|
115
134
|
keepWorktrees: keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
|
|
135
|
+
hideOfficialWorktreeEntry: hideOfficialWorktreeEntry ?? true,
|
|
136
|
+
switchSessionDirectory: switchSessionDirectory ?? false,
|
|
137
|
+
manageOfficialWorktrees: manageOfficialWorktrees ?? false,
|
|
116
138
|
};
|
|
117
139
|
}
|
|
140
|
+
const isHostAgentRegistryLike = (value) => typeof value === 'object' && value !== null && typeof value.get === 'function';
|
|
141
|
+
const isHostWorkingDirectoryLike = (value) => typeof value === 'object' && value !== null && typeof value.set === 'function';
|
|
142
|
+
function withHttpStatus(message, httpStatus) {
|
|
143
|
+
return Object.assign(new Error(message), { httpStatus });
|
|
144
|
+
}
|
|
118
145
|
/**
|
|
119
146
|
* Plugin apply: mount the settings presentation policy and HTTP routes on any
|
|
120
147
|
* webServer that comes and goes.
|
|
@@ -124,14 +151,87 @@ export function sectionOf(config) {
|
|
|
124
151
|
export function apply(ctx, config = {}) {
|
|
125
152
|
validateConfig(config);
|
|
126
153
|
const currentConfig = () => ctx.fiber?.config ?? config;
|
|
127
|
-
|
|
154
|
+
let sessionDirectorySetter;
|
|
155
|
+
let deferredWorktrees;
|
|
156
|
+
const baseDeps = () => ({
|
|
128
157
|
exec: childProcessExec,
|
|
129
158
|
sectionRootDir: () => readVolatile(currentConfig().rootDir),
|
|
130
159
|
sectionFetchBeforeCreate: () => readVolatile(currentConfig().fetchBeforeCreate),
|
|
131
160
|
sectionPostCreateCopyFiles: () => readVolatile(currentConfig().postCreateCopyFiles),
|
|
161
|
+
sectionManageOfficialWorktrees: () => readVolatile(currentConfig().manageOfficialWorktrees),
|
|
162
|
+
...(sessionDirectorySetter === undefined ? {} : { setSessionDirectory: sessionDirectorySetter }),
|
|
163
|
+
...(deferredWorktrees === undefined ? {} : { deferredWorktrees }),
|
|
132
164
|
home: () => homedir(),
|
|
133
165
|
envHome: () => process.env.DSH_HOME,
|
|
134
166
|
});
|
|
167
|
+
if (typeof ctx.inject === 'function') {
|
|
168
|
+
const injectOptional = ctx.inject.bind(ctx);
|
|
169
|
+
injectOptional(['agents', 'workingDirectory'], (hostCtx) => {
|
|
170
|
+
const agentsCandidate = hostCtx.agents;
|
|
171
|
+
const workingDirCandidate = hostCtx.workingDirectory;
|
|
172
|
+
if (!isHostAgentRegistryLike(agentsCandidate) || !isHostWorkingDirectoryLike(workingDirCandidate))
|
|
173
|
+
return;
|
|
174
|
+
const setter = async (sessionId, targetPath) => {
|
|
175
|
+
const live = agentsCandidate.get(sessionId);
|
|
176
|
+
if (live !== undefined) {
|
|
177
|
+
return await workingDirCandidate.set(live, targetPath);
|
|
178
|
+
}
|
|
179
|
+
if (typeof agentsCandidate.resume === 'function') {
|
|
180
|
+
const resumed = await agentsCandidate.resume({ resumeSessionId: sessionId });
|
|
181
|
+
try {
|
|
182
|
+
return await workingDirCandidate.set(resumed.agent, targetPath);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
await resumed.dispose?.();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
throw withHttpStatus(`Session "${sessionId}" is not loaded`, 404);
|
|
189
|
+
};
|
|
190
|
+
const coordinator = new DeferredWorktreeCoordinator({
|
|
191
|
+
createWorktree: (spec, onPhase) => executeCreateWorktree(baseDeps(), spec, onPhase),
|
|
192
|
+
setWorkingDirectory: (agent, targetPath, signal) => workingDirCandidate.set(agent, targetPath, signal),
|
|
193
|
+
});
|
|
194
|
+
sessionDirectorySetter = setter;
|
|
195
|
+
deferredWorktrees = coordinator;
|
|
196
|
+
const listen = hostCtx.on?.bind(hostCtx);
|
|
197
|
+
const unsubInbox = listen?.('agent/inbox/inserted', (payload) => {
|
|
198
|
+
const record = payload;
|
|
199
|
+
if (record?.agent !== undefined)
|
|
200
|
+
coordinator.onInboxInserted(record.agent, record.message);
|
|
201
|
+
});
|
|
202
|
+
const unsubPreStep = listen?.('agent/pre-step', async (payload, next) => {
|
|
203
|
+
const record = payload;
|
|
204
|
+
const callNext = typeof next === 'function' ? next : async () => undefined;
|
|
205
|
+
if (record?.agent !== undefined && typeof record.step === 'number') {
|
|
206
|
+
const created = await coordinator.onPreStep(record.agent, record.step, record.signal);
|
|
207
|
+
if (!created)
|
|
208
|
+
return await callNext();
|
|
209
|
+
const decision = await callNext();
|
|
210
|
+
if (decision !== undefined && decision.kind !== 'reject' && Array.isArray(decision.messages) && decision.messages.length > 0) {
|
|
211
|
+
const nextStep = record.agent.inbox?.nextStep ?? [];
|
|
212
|
+
const notices = nextStep.filter(item => item.source?.kind === 'working-directory');
|
|
213
|
+
if (notices.length > 0) {
|
|
214
|
+
for (const notice of notices)
|
|
215
|
+
record.agent.inbox?.remove?.(notice.id);
|
|
216
|
+
return { ...decision, messages: [...decision.messages, ...notices] };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return decision;
|
|
220
|
+
}
|
|
221
|
+
return await callNext();
|
|
222
|
+
});
|
|
223
|
+
hostCtx.effect(() => async () => {
|
|
224
|
+
unsubInbox?.();
|
|
225
|
+
unsubPreStep?.();
|
|
226
|
+
if (sessionDirectorySetter === setter)
|
|
227
|
+
sessionDirectorySetter = undefined;
|
|
228
|
+
if (deferredWorktrees === coordinator)
|
|
229
|
+
deferredWorktrees = undefined;
|
|
230
|
+
await coordinator.dispose();
|
|
231
|
+
}, 'git-worktree: optional workingDirectory & deferred worktree bridge');
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
const deps = () => baseDeps();
|
|
135
235
|
// In dsh 0.1.7+, the settings service projects volatile Config fields into forms.
|
|
136
236
|
// We configure auto: false to inform the host that this plugin provides its own
|
|
137
237
|
// dedicated configuration card (via `plugins.bundle.config`).
|
|
@@ -231,5 +331,63 @@ export function apply(ctx, config = {}) {
|
|
|
231
331
|
postRoute(ROUTE_ENSURE_DIRECTORY, 'ensure-directory', handleEnsureDirectory);
|
|
232
332
|
postRoute(ROUTE_WORKTREES_ALL, 'worktrees-all', handleWorktreesAll);
|
|
233
333
|
postRoute(ROUTE_PURGE, 'purge', handlePurgeDirectory);
|
|
334
|
+
postRoute(ROUTE_SESSION_CWD, 'session-cwd', handleSetSessionDirectory);
|
|
335
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_DEFERRED, handler: async (req, res) => {
|
|
336
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
337
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
338
|
+
send(res, await handleGetDeferredWorktree(deps(), query.get('sessionId') ?? undefined));
|
|
339
|
+
} }), 'git-worktree: deferred-get route');
|
|
340
|
+
const activeDeferredStreams = new Set();
|
|
341
|
+
webCtx.effect(() => () => {
|
|
342
|
+
for (const close of [...activeDeferredStreams])
|
|
343
|
+
close();
|
|
344
|
+
activeDeferredStreams.clear();
|
|
345
|
+
}, 'git-worktree: deferred-events stream teardown');
|
|
346
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_DEFERRED_EVENTS, handler: (req, res) => {
|
|
347
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
348
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
349
|
+
const sessionId = query.get('sessionId')?.trim() ?? '';
|
|
350
|
+
if (sessionId === '') {
|
|
351
|
+
send(res, { status: 400, body: { error: 'query parameter "sessionId" must be non-empty' } });
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const coordinator = deferredWorktrees;
|
|
355
|
+
if (coordinator === undefined) {
|
|
356
|
+
send(res, { status: 501, body: { error: 'Deferred worktree creation is not supported by this host' } });
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
res.writeHead(200, {
|
|
360
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
361
|
+
'cache-control': 'no-store',
|
|
362
|
+
connection: 'keep-alive',
|
|
363
|
+
});
|
|
364
|
+
const writeFrame = (payload) => {
|
|
365
|
+
if (!res.writableEnded)
|
|
366
|
+
res.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
367
|
+
};
|
|
368
|
+
writeFrame({ state: coordinator.get(sessionId) });
|
|
369
|
+
const unsubscribe = coordinator.subscribe(sessionId, writeFrame);
|
|
370
|
+
const heartbeat = setInterval(() => {
|
|
371
|
+
if (!res.writableEnded)
|
|
372
|
+
res.write(': keepalive\n\n');
|
|
373
|
+
}, 25_000);
|
|
374
|
+
heartbeat.unref?.();
|
|
375
|
+
let closed = false;
|
|
376
|
+
const cleanup = () => {
|
|
377
|
+
if (closed)
|
|
378
|
+
return;
|
|
379
|
+
closed = true;
|
|
380
|
+
activeDeferredStreams.delete(cleanup);
|
|
381
|
+
clearInterval(heartbeat);
|
|
382
|
+
unsubscribe();
|
|
383
|
+
if (!res.writableEnded)
|
|
384
|
+
res.end();
|
|
385
|
+
};
|
|
386
|
+
activeDeferredStreams.add(cleanup);
|
|
387
|
+
req.on('close', cleanup);
|
|
388
|
+
res.on('close', cleanup);
|
|
389
|
+
} }), 'git-worktree: deferred-events route');
|
|
390
|
+
postRoute(ROUTE_DEFERRED_ARM, 'deferred-arm', handleArmDeferredWorktree);
|
|
391
|
+
postRoute(ROUTE_DEFERRED_ACTION, 'deferred-action', handleDeferredWorktreeAction);
|
|
234
392
|
});
|
|
235
393
|
}
|
package/lib/normalize.d.ts
CHANGED
|
@@ -56,3 +56,16 @@ export type BranchNameIssue = 'empty' | 'leadingDash' | 'illegal';
|
|
|
56
56
|
* @returns the issue kind, or null when the name is acceptable.
|
|
57
57
|
*/
|
|
58
58
|
export declare function branchNameIssue(name: string): BranchNameIssue | null;
|
|
59
|
+
/**
|
|
60
|
+
* Default random 4-hex suffix generator (works in both Node and browser).
|
|
61
|
+
* Uses `crypto.getRandomValues` when available and falls back to `Math.random`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function defaultRandomHex4(): string;
|
|
64
|
+
/**
|
|
65
|
+
* Generate a human-readable random branch name based on `base` (`<stem>-<4hex>`),
|
|
66
|
+
* avoiding collisions with `isTaken`. Pure and shared between Host and Client.
|
|
67
|
+
* @param base - local base branch name (without remote prefix) or `HEAD`.
|
|
68
|
+
* @param isTaken - optional predicate returning true when a candidate already exists.
|
|
69
|
+
* @param randomHex - injectable 4-hex generator for deterministic testing.
|
|
70
|
+
*/
|
|
71
|
+
export declare function generateRandomBranchName(base: string, isTaken?: (candidate: string) => boolean, randomHex?: () => string): string;
|
package/lib/normalize.js
CHANGED
|
@@ -91,3 +91,54 @@ export function branchNameIssue(name) {
|
|
|
91
91
|
return 'illegal';
|
|
92
92
|
return null;
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Default random 4-hex suffix generator (works in both Node and browser).
|
|
96
|
+
* Uses `crypto.getRandomValues` when available and falls back to `Math.random`.
|
|
97
|
+
*/
|
|
98
|
+
export function defaultRandomHex4() {
|
|
99
|
+
const cryptoObj = globalThis.crypto;
|
|
100
|
+
if (cryptoObj !== undefined && typeof cryptoObj.getRandomValues === 'function') {
|
|
101
|
+
const bytes = new Uint8Array(2);
|
|
102
|
+
cryptoObj.getRandomValues(bytes);
|
|
103
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
104
|
+
}
|
|
105
|
+
return Math.floor(Math.random() * 0x10000).toString(16).padStart(4, '0');
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Normalize a base branch stem so appending `-<4hex>` always produces a valid
|
|
109
|
+
* git branch name (handles detached `HEAD`, trailing slashes/dots, or empty input).
|
|
110
|
+
*/
|
|
111
|
+
function randomBranchStem(base) {
|
|
112
|
+
const trimmed = base.trim();
|
|
113
|
+
if (trimmed === '' || trimmed === 'HEAD')
|
|
114
|
+
return 'wt';
|
|
115
|
+
const cleaned = trimmed
|
|
116
|
+
.replace(/^[-/]+/, '')
|
|
117
|
+
.replace(/[./]+$/, '')
|
|
118
|
+
.replace(/\/+/g, '/');
|
|
119
|
+
if (cleaned === '' || branchNameIssue(`${cleaned}-0000`) !== null)
|
|
120
|
+
return 'wt';
|
|
121
|
+
return cleaned;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Generate a human-readable random branch name based on `base` (`<stem>-<4hex>`),
|
|
125
|
+
* avoiding collisions with `isTaken`. Pure and shared between Host and Client.
|
|
126
|
+
* @param base - local base branch name (without remote prefix) or `HEAD`.
|
|
127
|
+
* @param isTaken - optional predicate returning true when a candidate already exists.
|
|
128
|
+
* @param randomHex - injectable 4-hex generator for deterministic testing.
|
|
129
|
+
*/
|
|
130
|
+
export function generateRandomBranchName(base, isTaken, randomHex = defaultRandomHex4) {
|
|
131
|
+
const stem = randomBranchStem(base);
|
|
132
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
133
|
+
const suffix = randomHex().toLowerCase().replace(/[^0-9a-f]/g, '').slice(0, 4).padStart(4, '0');
|
|
134
|
+
const candidate = `${stem}-${suffix}`;
|
|
135
|
+
if (!(isTaken?.(candidate) ?? false))
|
|
136
|
+
return candidate;
|
|
137
|
+
}
|
|
138
|
+
for (let i = 1;; i += 1) {
|
|
139
|
+
const suffix = randomHex().toLowerCase().replace(/[^0-9a-f]/g, '').slice(0, 4).padStart(4, '0');
|
|
140
|
+
const candidate = `${stem}-${suffix}-${i}`;
|
|
141
|
+
if (!(isTaken?.(candidate) ?? false))
|
|
142
|
+
return candidate;
|
|
143
|
+
}
|
|
144
|
+
}
|
package/lib/routes.d.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
import { type CopyFilesSeams } from './copy-files.js';
|
|
6
6
|
import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
|
|
7
7
|
import type { AuthorList, CommitHistory, CommitDetail } from './wire.js';
|
|
8
|
-
import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PushPlan, PushPreview, PushResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, SyncEvent, UpdateResult, WorktreesAllResult } from './wire.js';
|
|
8
|
+
import type { CreateBranchResult, CreateWorktreeResult, DeferredWorktreePhase, DeferredWorktreeSnapshot, DeferredWorktreeSpec, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PushPlan, PushPreview, PushResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SetSessionDirectoryResult, SwitchResult, SyncEvent, UpdateResult, WorktreesAllResult } from './wire.js';
|
|
9
|
+
import type { DeferredCreateOutcome, DeferredWorktreeCoordinator } from './deferred-worktree.js';
|
|
9
10
|
/** Everything the handlers need from the host half. */
|
|
10
11
|
export interface RouteDeps {
|
|
11
12
|
exec: Exec;
|
|
@@ -15,6 +16,8 @@ export interface RouteDeps {
|
|
|
15
16
|
sectionFetchBeforeCreate: () => boolean | undefined;
|
|
16
17
|
/** Post-create configuration files to copy when .worktreeinclude is absent. */
|
|
17
18
|
sectionPostCreateCopyFiles?: () => string[] | undefined;
|
|
19
|
+
/** Whether `/worktrees-all` and `/purge` also cover official `<repo>/.agents/worktrees`. */
|
|
20
|
+
sectionManageOfficialWorktrees?: () => boolean | undefined;
|
|
18
21
|
/** User home directory seam. */
|
|
19
22
|
home: () => string;
|
|
20
23
|
/** `$DSH_HOME` environment value seam. */
|
|
@@ -35,6 +38,12 @@ export interface RouteDeps {
|
|
|
35
38
|
listDir?: (path: string) => Promise<string[]>;
|
|
36
39
|
/** Recursive force rm seam (fs.rm with retries); tests substitute. */
|
|
37
40
|
rmRecursive?: (path: string) => Promise<void>;
|
|
41
|
+
/** Move a live session's working directory via host `agents` + `workingDirectory` services. */
|
|
42
|
+
setSessionDirectory?: (sessionId: string, path: string) => Promise<string>;
|
|
43
|
+
/** Deferred worktree creation coordinator (available when host supports workingDirectory). */
|
|
44
|
+
deferredWorktrees?: DeferredWorktreeCoordinator;
|
|
45
|
+
/** Deterministic 4-hex generator seam for random cutout branch tests. */
|
|
46
|
+
randomHex?: () => string;
|
|
38
47
|
}
|
|
39
48
|
/** Real fs-backed one-level directory listing (names only). Plain FILES are
|
|
40
49
|
* filtered out — the storage root can carry strays (a legacy settings.json
|
|
@@ -47,7 +56,9 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
|
|
|
47
56
|
/** One route outcome: HTTP status plus the JSON body. */
|
|
48
57
|
export interface RouteOutcome {
|
|
49
58
|
status: number;
|
|
50
|
-
body: AuthorList | CommitHistory | CommitDetail | PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult |
|
|
59
|
+
body: AuthorList | CommitHistory | CommitDetail | PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | SetSessionDirectoryResult | DeferredWorktreeSnapshot | {
|
|
60
|
+
ok: true;
|
|
61
|
+
} | RouteError;
|
|
51
62
|
}
|
|
52
63
|
/**
|
|
53
64
|
* POST /group — git belonging facts for a batch of workspace directories.
|
|
@@ -128,6 +139,11 @@ export declare function handleCommit(deps: RouteDeps, body: unknown): Promise<Ro
|
|
|
128
139
|
* @param deps - host dependencies.
|
|
129
140
|
* @param body - parsed request body.
|
|
130
141
|
*/
|
|
142
|
+
/**
|
|
143
|
+
* Shared worktree creation execution pipeline used by both immediate
|
|
144
|
+
* `POST /worktree` and deferred first-turn creation.
|
|
145
|
+
*/
|
|
146
|
+
export declare function executeCreateWorktree(deps: RouteDeps, spec: DeferredWorktreeSpec, onPhase?: (phase: Exclude<DeferredWorktreePhase, 'switch'>, resolvedBranch?: string) => void): Promise<DeferredCreateOutcome>;
|
|
131
147
|
export declare function handleCreateWorktree(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
132
148
|
/**
|
|
133
149
|
* POST /switch 鈥?in-place branch switch of the main checkout.
|
|
@@ -270,3 +286,18 @@ export declare function handlePathExists(deps: RouteDeps, body: unknown): Promis
|
|
|
270
286
|
* @param body - parsed request body: `{ path }`.
|
|
271
287
|
*/
|
|
272
288
|
export declare function handleEnsureDirectory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
289
|
+
/**
|
|
290
|
+
* POST /session-cwd — move a session's working directory to an existing
|
|
291
|
+
* directory via the host `workingDirectory` service. Used by the shared
|
|
292
|
+
* workspace mode (`switchSessionDirectory`) so a blank session stays under
|
|
293
|
+
* its parent repository workspace while working inside a linked worktree.
|
|
294
|
+
* @param deps - host dependencies.
|
|
295
|
+
* @param body - parsed request body: `{ sessionId, path }`.
|
|
296
|
+
*/
|
|
297
|
+
export declare function handleSetSessionDirectory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
298
|
+
/** GET /deferred?sessionId=<id> — read a session's current deferred worktree state. */
|
|
299
|
+
export declare function handleGetDeferredWorktree(deps: RouteDeps, sessionId: string | undefined): Promise<RouteOutcome>;
|
|
300
|
+
/** POST /deferred/arm — arm a deferred worktree creation for a blank session. */
|
|
301
|
+
export declare function handleArmDeferredWorktree(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
302
|
+
/** POST /deferred/action — cancel, retry, or withdraw a deferred worktree. */
|
|
303
|
+
export declare function handleDeferredWorktreeAction(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|