dsh-git-desk 0.18.1 → 0.20.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.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The shapes the Git channel exchanges. The host route and the browser client
3
+ * both read this file, so the wire contract has one definition.
4
+ */
5
+ export {};
@@ -1,16 +1,15 @@
1
1
  import { createRuntime } from './lib/exec.js';
2
2
  import { registerGitRoute } from './lib/http.js';
3
3
  import { createHandler } from './lib/rpc.js';
4
-
5
4
  export const inject = ['subprocess', 'workspaceRegistry', 'connection', 'webServer'];
6
-
7
5
  /**
8
6
  * Expose one authenticated HTTP channel. The browser half owns no Git state;
9
7
  * every read and every write goes through this channel and returns a fresh
10
8
  * status snapshot.
9
+ * @param ctx the plugin context.
11
10
  */
12
11
  export function apply(ctx) {
13
- const runtime = createRuntime(ctx.subprocess);
14
- const handler = createHandler(ctx, runtime);
15
- ctx.effect(() => registerGitRoute(ctx, handler), 'dsh-git: authenticated Git channel');
12
+ const runtime = createRuntime(ctx.subprocess);
13
+ const handler = createHandler(ctx, runtime);
14
+ ctx.effect(() => registerGitRoute(ctx, handler), 'dsh-git: authenticated Git channel');
16
15
  }
@@ -0,0 +1,266 @@
1
+ import { GitError } from './exec.js';
2
+ const MAX_PATCH_CHARS = 60_000;
3
+ const MAX_TITLE_CHARS = 120;
4
+ const MAX_MESSAGE_CHARS = 2_000;
5
+ const MAX_INSTRUCTION_CHARS = 4_000;
6
+ /**
7
+ * The default wording, also shown in Settings so the field starts populated.
8
+ * Reply format stays separate: a user instruction may not break the title
9
+ * line the log and the parser rely on.
10
+ */
11
+ const DEFAULT_INSTRUCTION = [
12
+ 'You write Git commit messages for a developer.',
13
+ 'The type is one of feat, fix, refactor, chore, docs, test, perf, style, ci, build.',
14
+ 'The scope is one lowercase noun, even when recent commits omit it.',
15
+ 'Write the summary in the imperative, lowercase, with no trailing period.',
16
+ 'Add a short body that explains why the change was made and which behavior it affects.',
17
+ 'Describe the change as a whole; never list files one by one.',
18
+ 'Match the style of the recent commit subjects.',
19
+ ].join(' ');
20
+ const FORMAT = [
21
+ 'Reply with a title line, then one blank line, then a short body.',
22
+ 'Title format: type(scope): summary.',
23
+ 'Keep the title on one line and under 100 characters.',
24
+ 'Never use a code fence, quotes, or a label such as "Commit message:".',
25
+ 'Add no trailers, such as Co-Authored-By.',
26
+ ].join(' ');
27
+ /**
28
+ * Read a stored instruction, falling back to the shipped wording.
29
+ * @param value the stored value.
30
+ * @returns the instruction.
31
+ */
32
+ export function instructionOf(value) {
33
+ if (typeof value !== 'string')
34
+ return DEFAULT_INSTRUCTION;
35
+ const text = value.trim();
36
+ return text === '' ? DEFAULT_INSTRUCTION : text.slice(0, MAX_INSTRUCTION_CHARS);
37
+ }
38
+ /**
39
+ * Tell one model selection apart from any other value.
40
+ * @param value the candidate.
41
+ * @returns whether it is a complete pair.
42
+ */
43
+ function isModelPair(value) {
44
+ if (value === null || typeof value !== 'object')
45
+ return false;
46
+ const candidate = value;
47
+ return (typeof candidate.provider === 'string' &&
48
+ candidate.provider !== '' &&
49
+ typeof candidate.model === 'string' &&
50
+ candidate.model !== '');
51
+ }
52
+ /**
53
+ * Tell the model selection service apart from any other value.
54
+ * @param value the candidate service.
55
+ * @returns whether it exposes a selection.
56
+ */
57
+ function isAgentModelService(value) {
58
+ return (value !== null &&
59
+ typeof value === 'object' &&
60
+ typeof value.currentSelection === 'function');
61
+ }
62
+ /**
63
+ * Tell the model service apart from any other value.
64
+ * @param value the candidate service.
65
+ * @returns whether it lists providers, lists models, and streams.
66
+ */
67
+ function isLlmService(value) {
68
+ if (value === null || typeof value !== 'object')
69
+ return false;
70
+ const candidate = value;
71
+ return (typeof candidate.listProviders === 'function' &&
72
+ typeof candidate.listModels === 'function' &&
73
+ typeof candidate.stream === 'function');
74
+ }
75
+ /**
76
+ * Read one string field from an unknown value.
77
+ * @param value the candidate.
78
+ * @param key the field name.
79
+ * @returns the field, or an empty string.
80
+ */
81
+ function stringField(value, key) {
82
+ if (value === null || typeof value !== 'object')
83
+ return '';
84
+ const field = value[key];
85
+ return typeof field === 'string' ? field : '';
86
+ }
87
+ /**
88
+ * Read the model the user picked in Settings. The plugin never stores a
89
+ * provider or a key of its own, so AI actions follow the harness selection
90
+ * unless the panel sends an explicit override.
91
+ *
92
+ * @param ctx the plugin context.
93
+ * @returns the selection, or null.
94
+ */
95
+ export function selectedModel(ctx) {
96
+ const service = ctx.get('agentDefaultModel');
97
+ if (!isAgentModelService(service))
98
+ return null;
99
+ const selection = service.currentSelection();
100
+ return isModelPair(selection) ? { provider: selection.provider, model: selection.model } : null;
101
+ }
102
+ /**
103
+ * Accept only a complete provider/model pair from the client.
104
+ * @param value the client value.
105
+ * @returns the pair, or null.
106
+ */
107
+ function overrideModel(value) {
108
+ return isModelPair(value) ? { provider: value.provider, model: value.model } : null;
109
+ }
110
+ /**
111
+ * Models the settings page may offer, grouped by provider. A provider that
112
+ * cannot answer contributes no group rather than failing the whole read.
113
+ *
114
+ * @param ctx the plugin context.
115
+ * @returns the instruction and the provider groups.
116
+ */
117
+ export async function preferences(ctx) {
118
+ const llm = ctx.get('llm');
119
+ const groups = [];
120
+ if (isLlmService(llm)) {
121
+ for (const provider of llm.listProviders()) {
122
+ const id = stringField(provider, 'id');
123
+ if (id === '')
124
+ continue;
125
+ let listed;
126
+ try {
127
+ listed = await llm.listModels(id);
128
+ }
129
+ catch {
130
+ // An unconfigured provider refuses its catalog; it offers no choice.
131
+ listed = null;
132
+ }
133
+ if (!Array.isArray(listed))
134
+ continue;
135
+ const items = listed;
136
+ const models = [];
137
+ for (const model of items) {
138
+ const modelId = stringField(model, 'id');
139
+ if (modelId === '')
140
+ continue;
141
+ const rawName = stringField(model, 'name');
142
+ models.push({ id: modelId, name: rawName === '' ? modelId : rawName });
143
+ }
144
+ if (models.length === 0)
145
+ continue;
146
+ const rawLabel = stringField(provider, 'name');
147
+ const label = rawLabel === '' ? id : rawLabel;
148
+ groups.push({ id, label, models });
149
+ }
150
+ }
151
+ return { instruction: DEFAULT_INSTRUCTION, groups };
152
+ }
153
+ /**
154
+ * Reduce a model reply to a title line and an optional body. The title is
155
+ * normalized the way a Git log reads it; the body keeps its paragraph breaks.
156
+ *
157
+ * @param text the raw reply.
158
+ * @returns the cleaned message, or an empty string.
159
+ */
160
+ export function cleanMessage(text) {
161
+ const lines = text
162
+ .replace(/```[a-z]*\r?\n?/gi, '')
163
+ .replace(/```/g, '')
164
+ .replace(/^\s*commit message\s*:\s*/i, '')
165
+ .split(/\r?\n/)
166
+ .map((line) => line.replace(/[ \t]+$/, ''));
167
+ while (lines.length > 0 && (lines[0] ?? '').trim() === '')
168
+ lines.shift();
169
+ while (lines.length > 0 && (lines[lines.length - 1] ?? '').trim() === '')
170
+ lines.pop();
171
+ if (lines.length === 0)
172
+ return '';
173
+ const title = (lines[0] ?? '')
174
+ .replace(/^["'`]+|["'`]+$/g, '')
175
+ .replace(/\s+/g, ' ')
176
+ .replace(/[.。]+$/, '')
177
+ .trim()
178
+ .slice(0, MAX_TITLE_CHARS);
179
+ if (title === '')
180
+ return '';
181
+ const body = [];
182
+ for (const line of lines.slice(1)) {
183
+ if (line.trim() === '') {
184
+ if (body.length > 0 && body[body.length - 1] !== '')
185
+ body.push('');
186
+ continue;
187
+ }
188
+ body.push(line.trim());
189
+ }
190
+ while (body.length > 0 && body[body.length - 1] === '')
191
+ body.pop();
192
+ if (body.length === 0)
193
+ return title;
194
+ const message = `${title}\n\n${body.join('\n').trim()}`;
195
+ return message.slice(0, MAX_MESSAGE_CHARS).trim();
196
+ }
197
+ /**
198
+ * Build the user prompt from recent subjects and the staged patch.
199
+ * @param recent the recent subjects.
200
+ * @param patch the staged patch.
201
+ * @returns the prompt.
202
+ */
203
+ function promptFor(recent, patch) {
204
+ const body = patch.length > MAX_PATCH_CHARS ? `${patch.slice(0, MAX_PATCH_CHARS)}\n[diff truncated]` : patch;
205
+ const style = recent.length === 0 ? '(none)' : recent.map((subject) => `- ${subject}`).join('\n');
206
+ return `Recent commit subjects:\n${style}\n\nStaged changes:\n${body}`;
207
+ }
208
+ /**
209
+ * One model call over the staged patch. The caller owns cancellation and
210
+ * passes a signal that also covers the request timeout. `model` overrides the
211
+ * Composer selection; `instruction` replaces the default wording.
212
+ *
213
+ * @param ctx the plugin context.
214
+ * @param request the patch, recent subjects, signal, and overrides.
215
+ * @returns the generated message and the model that wrote it.
216
+ */
217
+ export async function writeCommitMessage(ctx, request) {
218
+ const llm = ctx.get('llm');
219
+ if (!isLlmService(llm)) {
220
+ throw new GitError('git/ai-unavailable', 'AI is not available in this build.');
221
+ }
222
+ const model = overrideModel(request.model) ?? selectedModel(ctx);
223
+ if (model === null) {
224
+ throw new GitError('git/ai-unavailable', 'Select a model in Settings before using AI actions.');
225
+ }
226
+ const system = `${instructionOf(request.instruction)} ${FORMAT}`;
227
+ let text = '';
228
+ let failure = null;
229
+ try {
230
+ const chunks = llm.stream({
231
+ provider: model.provider,
232
+ model: model.model,
233
+ system,
234
+ messages: [{ role: 'user', content: [{ type: 'text', text: promptFor(request.recent, request.patch) }] }],
235
+ temperature: 0.2,
236
+ maxTokens: 200,
237
+ signal: request.signal,
238
+ });
239
+ for await (const chunk of chunks) {
240
+ if (chunk.type === 'text-delta')
241
+ text += chunk.text ?? '';
242
+ else if (chunk.type === 'finish' && chunk.reason !== undefined && chunk.reason.kind !== 'stop') {
243
+ failure = chunk.reason;
244
+ }
245
+ }
246
+ }
247
+ catch (error) {
248
+ if (request.signal.aborted) {
249
+ throw new GitError('git/ai-timeout', 'The model request timed out. Try again.');
250
+ }
251
+ throw new GitError('git/ai-failed', 'The model request failed.', {
252
+ cause: error instanceof Error ? error.message : String(error),
253
+ });
254
+ }
255
+ if (failure !== null) {
256
+ if (failure.kind === 'aborted') {
257
+ throw new GitError('git/ai-timeout', 'The model request timed out. Try again.');
258
+ }
259
+ const message = failure.failure?.message;
260
+ throw new GitError('git/ai-failed', typeof message === 'string' && message !== '' ? message : 'The model request failed.');
261
+ }
262
+ const message = cleanMessage(text);
263
+ if (message === '')
264
+ throw new GitError('git/ai-empty', 'The model returned an empty message. Try again.');
265
+ return { message, provider: model.provider, model: model.model };
266
+ }
@@ -0,0 +1,193 @@
1
+ import { lstat, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
2
+ const DEFAULT_TIMEOUT_MS = 30_000;
3
+ const NETWORK_TIMEOUT_MS = 180_000;
4
+ /** One Git failure with a stable code. */
5
+ export class GitError extends Error {
6
+ code;
7
+ details;
8
+ constructor(code, message, details = {}) {
9
+ super(message);
10
+ this.name = 'GitError';
11
+ this.code = code;
12
+ this.details = details;
13
+ }
14
+ }
15
+ /**
16
+ * Read the `code` of a filesystem failure.
17
+ * @param error the thrown value.
18
+ * @returns the errno name, or undefined when it is not an errno failure.
19
+ */
20
+ function errnoCode(error) {
21
+ if (!(error instanceof Error) || !('code' in error))
22
+ return undefined;
23
+ const { code } = error;
24
+ return typeof code === 'string' ? code : undefined;
25
+ }
26
+ /**
27
+ * Tell a missing path apart from a real failure.
28
+ * @param error the thrown value.
29
+ * @returns whether the path is simply absent.
30
+ */
31
+ function isMissing(error) {
32
+ const code = errnoCode(error);
33
+ return code === 'ENOENT' || code === 'EISDIR' || code === 'ENOTDIR';
34
+ }
35
+ /**
36
+ * Run one managed child process and collect both streams.
37
+ * The provider owns cancellation. This wrapper only adds a wall clock and
38
+ * folds a spawn failure into a normal command result so callers can show it.
39
+ * @param subprocess the harness subprocess service.
40
+ * @returns the runtime helpers.
41
+ */
42
+ export function createRuntime(subprocess) {
43
+ let gitPath;
44
+ let gitPathError;
45
+ async function resolveGit() {
46
+ if (gitPath !== undefined)
47
+ return gitPath;
48
+ if (gitPathError !== undefined)
49
+ throw gitPathError;
50
+ try {
51
+ gitPath = await subprocess.resolveExecutable('git');
52
+ return gitPath;
53
+ }
54
+ catch (error) {
55
+ gitPathError = new GitError('git/not-installed', 'Git is not installed or is not on PATH.', {
56
+ cause: error instanceof Error ? error.message : String(error),
57
+ });
58
+ throw gitPathError;
59
+ }
60
+ }
61
+ async function run(cwd, args, options = {}) {
62
+ const executable = await resolveGit();
63
+ const timeoutMs = options.timeoutMs ?? (options.network === true ? NETWORK_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);
64
+ const timeout = AbortSignal.timeout(timeoutMs);
65
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([timeout, options.signal]);
66
+ const env = {
67
+ ...process.env,
68
+ LC_ALL: 'C',
69
+ LANG: 'C',
70
+ GIT_TERMINAL_PROMPT: '0',
71
+ GIT_OPTIONAL_LOCKS: '0',
72
+ GIT_PAGER: 'cat',
73
+ PAGER: 'cat',
74
+ };
75
+ let handle;
76
+ try {
77
+ handle = subprocess.spawn({
78
+ argv: [executable, ...args],
79
+ cwd,
80
+ stdio: {
81
+ stdin: options.input === undefined ? 'ignore' : { data: options.input },
82
+ stdout: { maxBytes: 64 * 1024 * 1024, spill: { maxBytes: 128 * 1024 * 1024 } },
83
+ stderr: { maxBytes: 8 * 1024 * 1024 },
84
+ },
85
+ graceMs: 2000,
86
+ signal,
87
+ env,
88
+ });
89
+ }
90
+ catch (error) {
91
+ if (signal.aborted)
92
+ throw new GitError('git/cancelled', 'The Git command was cancelled.', { args });
93
+ throw new GitError('git/spawn-failed', 'Git could not start.', {
94
+ args,
95
+ cause: error instanceof Error ? error.message : String(error),
96
+ });
97
+ }
98
+ let outcome;
99
+ try {
100
+ outcome = await handle.done;
101
+ }
102
+ catch (error) {
103
+ if (timeout.aborted) {
104
+ throw new GitError('git/timeout', `Git did not finish within ${Math.round(timeoutMs / 1000)} seconds.`, {
105
+ args,
106
+ });
107
+ }
108
+ if (options.signal?.aborted === true) {
109
+ throw new GitError('git/cancelled', 'The Git command was cancelled.', { args });
110
+ }
111
+ throw new GitError('git/failed', 'Git failed to run.', {
112
+ args,
113
+ cause: error instanceof Error ? error.message : String(error),
114
+ });
115
+ }
116
+ const stdout = handle.collected.stdout?.readFrom(0);
117
+ const stderr = handle.collected.stderr?.readFrom(0);
118
+ if (stdout?.lossy === true) {
119
+ throw new GitError('git/output-too-large', 'Git returned more output than the panel can read.', {
120
+ args,
121
+ spillPath: stdout.spillPath,
122
+ });
123
+ }
124
+ return {
125
+ code: outcome.exitCode ?? (outcome.signal === null ? 0 : 1),
126
+ stdout: stdout?.text ?? '',
127
+ stderr: stderr?.text ?? '',
128
+ };
129
+ }
130
+ async function readText(path) {
131
+ try {
132
+ const bytes = await readFile(path);
133
+ const text = bytes.toString('utf8');
134
+ return {
135
+ text,
136
+ binary: bytes.includes(0) || !Buffer.from(text, 'utf8').equals(bytes),
137
+ size: bytes.length,
138
+ };
139
+ }
140
+ catch (error) {
141
+ if (isMissing(error))
142
+ return null;
143
+ throw new GitError('git/read-failed', `Could not read ${path}.`, {
144
+ path,
145
+ cause: error instanceof Error ? error.message : String(error),
146
+ });
147
+ }
148
+ }
149
+ async function readBuffer(path) {
150
+ try {
151
+ return await readFile(path);
152
+ }
153
+ catch (error) {
154
+ if (isMissing(error))
155
+ return null;
156
+ throw new GitError('git/read-failed', `Could not read ${path}.`, {
157
+ path,
158
+ cause: error instanceof Error ? error.message : String(error),
159
+ });
160
+ }
161
+ }
162
+ async function writeText(path, text) {
163
+ await writeFile(path, text, 'utf8');
164
+ }
165
+ async function statPath(path) {
166
+ try {
167
+ return await stat(path);
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ }
173
+ async function lstatPath(path) {
174
+ try {
175
+ return await lstat(path);
176
+ }
177
+ catch {
178
+ return null;
179
+ }
180
+ }
181
+ async function readdirPath(path) {
182
+ try {
183
+ return await readdir(path, { withFileTypes: true });
184
+ }
185
+ catch {
186
+ return [];
187
+ }
188
+ }
189
+ async function realpathPath(path) {
190
+ return realpath(path);
191
+ }
192
+ return { run, readText, readBuffer, writeText, statPath, lstatPath, readdir: readdirPath, realpath: realpathPath };
193
+ }