dsh-git-desk 0.0.0-stage → 0.18.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,4 @@
1
+ - insert:
2
+ - id: dsh-git-desk
3
+ name: 'dsh-git-desk'
4
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
2
+ <rect width="64" height="64" rx="14" fill="#0F172A"/>
3
+ <path d="M32 15v34" stroke="#94A3B8" stroke-width="3" stroke-linecap="round"/>
4
+ <path d="M32 31c0-7 5-12 12-12h4" stroke="#94A3B8" stroke-width="3" stroke-linecap="round"/>
5
+ <circle cx="32" cy="14" r="6" fill="#F8FAFC"/>
6
+ <circle cx="32" cy="32" r="6" fill="#38BDF8"/>
7
+ <circle cx="32" cy="50" r="6" fill="#F8FAFC"/>
8
+ <circle cx="50" cy="19" r="5" fill="#F8FAFC"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ import { createRuntime } from './lib/exec.js';
2
+ import { registerGitRoute } from './lib/http.js';
3
+ import { createHandler } from './lib/rpc.js';
4
+
5
+ export const inject = ['subprocess', 'workspaceRegistry', 'connection', 'webServer'];
6
+
7
+ /**
8
+ * Expose one authenticated HTTP channel. The browser half owns no Git state;
9
+ * every read and every write goes through this channel and returns a fresh
10
+ * status snapshot.
11
+ */
12
+ 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');
16
+ }
package/lib/ai.js ADDED
@@ -0,0 +1,187 @@
1
+ import { GitError } from './exec.js';
2
+
3
+ const MAX_PATCH_CHARS = 60_000;
4
+ const MAX_TITLE_CHARS = 120;
5
+ const MAX_MESSAGE_CHARS = 2_000;
6
+ const MAX_INSTRUCTION_CHARS = 4_000;
7
+
8
+ /**
9
+ * The default wording, also shown in Settings so the field starts populated.
10
+ * Reply format stays separate: a user instruction may not break the title
11
+ * line the log and the parser rely on.
12
+ */
13
+ const DEFAULT_INSTRUCTION = [
14
+ 'You write Git commit messages for a developer.',
15
+ 'The type is one of feat, fix, refactor, chore, docs, test, perf, style, ci, build.',
16
+ 'The scope is one lowercase noun, even when recent commits omit it.',
17
+ 'Write the summary in the imperative, lowercase, with no trailing period.',
18
+ 'Add a short body that explains why the change was made and which behavior it affects.',
19
+ 'Describe the change as a whole; never list files one by one.',
20
+ 'Match the style of the recent commit subjects.',
21
+ ].join(' ');
22
+
23
+ const FORMAT = [
24
+ 'Reply with a title line, then one blank line, then a short body.',
25
+ 'Title format: type(scope): summary.',
26
+ 'Keep the title on one line and under 100 characters.',
27
+ 'Never use a code fence, quotes, or a label such as "Commit message:".',
28
+ 'Add no trailers, such as Co-Authored-By.',
29
+ ].join(' ');
30
+
31
+ /** Read a stored instruction, falling back to the shipped wording. */
32
+ export function instructionOf(value) {
33
+ if (typeof value !== 'string') return DEFAULT_INSTRUCTION;
34
+ const text = value.trim();
35
+ return text === '' ? DEFAULT_INSTRUCTION : text.slice(0, MAX_INSTRUCTION_CHARS);
36
+ }
37
+
38
+ /**
39
+ * Read the model the user picked in Settings. The plugin never stores a
40
+ * provider or a key of its own, so AI actions follow the harness selection
41
+ * unless the panel sends an explicit override.
42
+ */
43
+ export function selectedModel(ctx) {
44
+ const service = typeof ctx.get === 'function' ? ctx.get('agentDefaultModel') : undefined;
45
+ if (service === undefined || typeof service.currentSelection !== 'function') return null;
46
+ const selection = service.currentSelection();
47
+ if (selection === null || typeof selection !== 'object') return null;
48
+ if (typeof selection.provider !== 'string' || typeof selection.model !== 'string') return null;
49
+ if (selection.provider === '' || selection.model === '') return null;
50
+ return { provider: selection.provider, model: selection.model };
51
+ }
52
+
53
+ /** Accept only a complete provider/model pair from the client. */
54
+ function overrideModel(value) {
55
+ if (value === null || typeof value !== 'object') return null;
56
+ const provider = value.provider;
57
+ const model = value.model;
58
+ if (typeof provider !== 'string' || typeof model !== 'string') return null;
59
+ if (provider === '' || model === '') return null;
60
+ return { provider, model };
61
+ }
62
+
63
+ /**
64
+ * Models the settings page may offer, grouped by provider. A provider that
65
+ * cannot answer contributes no group rather than failing the whole read.
66
+ */
67
+ export async function preferences(ctx) {
68
+ const llm = typeof ctx.get === 'function' ? ctx.get('llm') : undefined;
69
+ const groups = [];
70
+ if (llm !== undefined && typeof llm.listProviders === 'function' && typeof llm.listModels === 'function') {
71
+ for (const provider of llm.listProviders()) {
72
+ const id = typeof provider?.id === 'string' ? provider.id : '';
73
+ if (id === '') continue;
74
+ let listed;
75
+ try {
76
+ listed = await llm.listModels(id);
77
+ } catch {
78
+ // An unconfigured provider refuses its catalog; it offers no choice.
79
+ listed = null;
80
+ }
81
+ if (!Array.isArray(listed)) continue;
82
+ const models = listed.flatMap((model) =>
83
+ typeof model?.id === 'string' && model.id !== ''
84
+ ? [{ id: model.id, name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id }]
85
+ : [],
86
+ );
87
+ if (models.length === 0) continue;
88
+ const label = typeof provider.name === 'string' && provider.name !== '' ? provider.name : id;
89
+ groups.push({ id, label, models });
90
+ }
91
+ }
92
+ return { instruction: DEFAULT_INSTRUCTION, groups };
93
+ }
94
+
95
+ /**
96
+ * Reduce a model reply to a title line and an optional body. The title is
97
+ * normalized the way a Git log reads it; the body keeps its paragraph breaks.
98
+ */
99
+ export function cleanMessage(text) {
100
+ const lines = text
101
+ .replace(/```[a-z]*\r?\n?/gi, '')
102
+ .replace(/```/g, '')
103
+ .replace(/^\s*commit message\s*:\s*/i, '')
104
+ .split(/\r?\n/)
105
+ .map((line) => line.replace(/[ \t]+$/, ''));
106
+ while (lines.length > 0 && lines[0].trim() === '') lines.shift();
107
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();
108
+ if (lines.length === 0) return '';
109
+ const title = lines[0]
110
+ .replace(/^["'`]+|["'`]+$/g, '')
111
+ .replace(/\s+/g, ' ')
112
+ .replace(/[.。]+$/, '')
113
+ .trim()
114
+ .slice(0, MAX_TITLE_CHARS);
115
+ if (title === '') return '';
116
+ const body = [];
117
+ for (const line of lines.slice(1)) {
118
+ if (line.trim() === '') {
119
+ if (body.length > 0 && body[body.length - 1] !== '') body.push('');
120
+ continue;
121
+ }
122
+ body.push(line.trim());
123
+ }
124
+ while (body.length > 0 && body[body.length - 1] === '') body.pop();
125
+ if (body.length === 0) return title;
126
+ const message = `${title}\n\n${body.join('\n').trim()}`;
127
+ return message.slice(0, MAX_MESSAGE_CHARS).trim();
128
+ }
129
+
130
+ function promptFor(recent, patch) {
131
+ const body =
132
+ patch.length > MAX_PATCH_CHARS ? `${patch.slice(0, MAX_PATCH_CHARS)}\n[diff truncated]` : patch;
133
+ const style =
134
+ recent.length === 0 ? '(none)' : recent.map((subject) => `- ${subject}`).join('\n');
135
+ return `Recent commit subjects:\n${style}\n\nStaged changes:\n${body}`;
136
+ }
137
+
138
+ /**
139
+ * One model call over the staged patch. The caller owns cancellation and
140
+ * passes a signal that also covers the request timeout. `model` overrides the
141
+ * Composer selection; `instruction` replaces the default wording.
142
+ */
143
+ export async function writeCommitMessage(ctx, { patch, recent, signal, model: requested, instruction }) {
144
+ const llm = typeof ctx.get === 'function' ? ctx.get('llm') : undefined;
145
+ if (llm === undefined || typeof llm.stream !== 'function') {
146
+ throw new GitError('git/ai-unavailable', 'AI is not available in this build.');
147
+ }
148
+ const model = overrideModel(requested) ?? selectedModel(ctx);
149
+ if (model === null) {
150
+ throw new GitError('git/ai-unavailable', 'Select a model in Settings before using AI actions.');
151
+ }
152
+ const system = `${instructionOf(instruction)} ${FORMAT}`;
153
+ let text = '';
154
+ let failure = null;
155
+ try {
156
+ const chunks = llm.stream({
157
+ provider: model.provider,
158
+ model: model.model,
159
+ system,
160
+ messages: [{ role: 'user', content: [{ type: 'text', text: promptFor(recent, patch) }] }],
161
+ temperature: 0.2,
162
+ maxTokens: 200,
163
+ signal,
164
+ });
165
+ for await (const chunk of chunks) {
166
+ if (chunk.type === 'text-delta') text += chunk.text;
167
+ else if (chunk.type === 'finish' && chunk.reason.kind !== 'stop') failure = chunk.reason;
168
+ }
169
+ } catch (error) {
170
+ if (signal !== undefined && signal.aborted) {
171
+ throw new GitError('git/ai-timeout', 'The model request timed out. Try again.');
172
+ }
173
+ throw new GitError('git/ai-failed', 'The model request failed.', {
174
+ cause: error instanceof Error ? error.message : String(error),
175
+ });
176
+ }
177
+ if (failure !== null) {
178
+ if (failure.kind === 'aborted') {
179
+ throw new GitError('git/ai-timeout', 'The model request timed out. Try again.');
180
+ }
181
+ const message = failure.failure?.message;
182
+ throw new GitError('git/ai-failed', typeof message === 'string' && message !== '' ? message : 'The model request failed.');
183
+ }
184
+ const message = cleanMessage(text);
185
+ if (message === '') throw new GitError('git/ai-empty', 'The model returned an empty message. Try again.');
186
+ return { message, provider: model.provider, model: model.model };
187
+ }
package/lib/exec.js ADDED
@@ -0,0 +1,168 @@
1
+ import { lstat, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
2
+
3
+ const DEFAULT_TIMEOUT_MS = 30_000;
4
+ const NETWORK_TIMEOUT_MS = 180_000;
5
+
6
+ export class GitError extends Error {
7
+ constructor(code, message, details = {}) {
8
+ super(message);
9
+ this.name = 'GitError';
10
+ this.code = code;
11
+ this.details = details;
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Run one managed child process and collect both streams.
17
+ * The provider owns cancellation. This wrapper only adds a wall clock and
18
+ * folds a spawn failure into a normal command result so callers can show it.
19
+ */
20
+ export function createRuntime(subprocess) {
21
+ let gitPath;
22
+ let gitPathError;
23
+
24
+ async function resolveGit() {
25
+ if (gitPath !== undefined) return gitPath;
26
+ if (gitPathError !== undefined) throw gitPathError;
27
+ try {
28
+ gitPath = await subprocess.resolveExecutable('git');
29
+ return gitPath;
30
+ } catch (error) {
31
+ gitPathError = new GitError('git/not-installed', 'Git is not installed or is not on PATH.', {
32
+ cause: error instanceof Error ? error.message : String(error),
33
+ });
34
+ throw gitPathError;
35
+ }
36
+ }
37
+
38
+ async function run(cwd, args, options = {}) {
39
+ const executable = await resolveGit();
40
+ const timeoutMs = options.timeoutMs ?? (options.network ? NETWORK_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);
41
+ const timeout = AbortSignal.timeout(timeoutMs);
42
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([timeout, options.signal]);
43
+ const env = {
44
+ ...process.env,
45
+ LC_ALL: 'C',
46
+ LANG: 'C',
47
+ GIT_TERMINAL_PROMPT: '0',
48
+ GIT_OPTIONAL_LOCKS: '0',
49
+ GIT_PAGER: 'cat',
50
+ PAGER: 'cat',
51
+ };
52
+ let handle;
53
+ try {
54
+ handle = subprocess.spawn({
55
+ argv: [executable, ...args],
56
+ cwd,
57
+ stdio: {
58
+ stdin: options.input === undefined ? 'ignore' : { data: options.input },
59
+ stdout: { maxBytes: 64 * 1024 * 1024, spill: { maxBytes: 128 * 1024 * 1024 } },
60
+ stderr: { maxBytes: 8 * 1024 * 1024 },
61
+ },
62
+ graceMs: 2000,
63
+ signal,
64
+ env,
65
+ });
66
+ } catch (error) {
67
+ if (signal.aborted) throw new GitError('git/cancelled', 'The Git command was cancelled.', { args });
68
+ throw new GitError('git/spawn-failed', 'Git could not start.', {
69
+ args,
70
+ cause: error instanceof Error ? error.message : String(error),
71
+ });
72
+ }
73
+
74
+ let outcome;
75
+ try {
76
+ outcome = await handle.done;
77
+ } catch (error) {
78
+ if (timeout.aborted) {
79
+ throw new GitError('git/timeout', `Git did not finish within ${Math.round(timeoutMs / 1000)} seconds.`, {
80
+ args,
81
+ });
82
+ }
83
+ if (options.signal?.aborted) throw new GitError('git/cancelled', 'The Git command was cancelled.', { args });
84
+ throw new GitError('git/failed', 'Git failed to run.', {
85
+ args,
86
+ cause: error instanceof Error ? error.message : String(error),
87
+ });
88
+ }
89
+
90
+ const stdout = handle.collected.stdout?.readFrom(0);
91
+ const stderr = handle.collected.stderr?.readFrom(0);
92
+ if (stdout?.lossy) {
93
+ throw new GitError('git/output-too-large', 'Git returned more output than the panel can read.', {
94
+ args,
95
+ spillPath: stdout.spillPath,
96
+ });
97
+ }
98
+ return {
99
+ code: outcome.exitCode ?? (outcome.signal === null ? 0 : 1),
100
+ stdout: stdout?.text ?? '',
101
+ stderr: stderr?.text ?? '',
102
+ };
103
+ }
104
+
105
+ async function readText(path) {
106
+ try {
107
+ const bytes = await readFile(path);
108
+ const text = bytes.toString('utf8');
109
+ return {
110
+ text,
111
+ binary: bytes.includes(0) || !Buffer.from(text, 'utf8').equals(bytes),
112
+ size: bytes.length,
113
+ };
114
+ } catch (error) {
115
+ if (error && (error.code === 'ENOENT' || error.code === 'EISDIR' || error.code === 'ENOTDIR')) return null;
116
+ throw new GitError('git/read-failed', `Could not read ${path}.`, {
117
+ path,
118
+ cause: error instanceof Error ? error.message : String(error),
119
+ });
120
+ }
121
+ }
122
+
123
+ async function readBuffer(path) {
124
+ try {
125
+ return await readFile(path);
126
+ } catch (error) {
127
+ if (error && (error.code === 'ENOENT' || error.code === 'EISDIR' || error.code === 'ENOTDIR')) return null;
128
+ throw new GitError('git/read-failed', `Could not read ${path}.`, {
129
+ path,
130
+ cause: error instanceof Error ? error.message : String(error),
131
+ });
132
+ }
133
+ }
134
+
135
+ async function writeText(path, text) {
136
+ await writeFile(path, text, 'utf8');
137
+ }
138
+
139
+ async function statPath(path) {
140
+ try {
141
+ return await stat(path);
142
+ } catch {
143
+ return null;
144
+ }
145
+ }
146
+
147
+ async function lstatPath(path) {
148
+ try {
149
+ return await lstat(path);
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+
155
+ async function readdirPath(path) {
156
+ try {
157
+ return await readdir(path, { withFileTypes: true });
158
+ } catch {
159
+ return [];
160
+ }
161
+ }
162
+
163
+ async function realpathPath(path) {
164
+ return realpath(path);
165
+ }
166
+
167
+ return { run, readText, readBuffer, writeText, statPath, lstatPath, readdir: readdirPath, realpath: realpathPath };
168
+ }