@lukstei/dsh-client-review-git 0.0.0-stage → 0.2.2-rc.5.11

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/src/index.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { CommandId } from "@deepseek-ai/dsh-commands";
3
+ import type { Session } from "@deepseek-ai/dsh-session";
4
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
5
+ import type { ReviewTarget } from "@lukstei/util-review-ui/types";
6
+ import { createGitReviewTool } from "./review-tool.ts";
7
+ import { WorkspaceReviewService } from "./workspace-review-service.ts";
8
+
9
+ export type { GitReviewToolOptions } from "./review-tool.ts";
10
+ export { createGitReviewTool } from "./review-tool.ts";
11
+ export { WorkspaceReviewService } from "./workspace-review-service.ts";
12
+
13
+ export const name = "dsh-client-git-diff";
14
+ export const inject = [
15
+ "sessionController",
16
+ "workingDirectory",
17
+ "sessions",
18
+ "sessionPersistence",
19
+ ] as const;
20
+
21
+ export function apply(ctx: Context): void {
22
+ ctx.plugin(WorkspaceReviewService);
23
+ ctx.plugin({
24
+ inject: ["tools", "agents"],
25
+ apply: (toolCtx) => {
26
+ const pending = new WeakMap<
27
+ ToolExecution,
28
+ { session: Session; turn: number; target: ReviewTarget }
29
+ >();
30
+ toolCtx.tools.register(
31
+ createGitReviewTool({
32
+ onPresented: (exec, target) => {
33
+ if (exec.agent === undefined) return;
34
+ const boundary = toolCtx.agents.turnBoundaryOf(exec.agent.session);
35
+ const turn =
36
+ boundary.openTurnStartSeq !== null
37
+ ? boundary.lastTurn
38
+ : boundary.lastTurn || 1;
39
+ pending.set(exec, {
40
+ session: exec.agent.session,
41
+ turn,
42
+ target,
43
+ });
44
+ },
45
+ }),
46
+ );
47
+ toolCtx.on("tools/result", (exec, result) => {
48
+ const delivery = pending.get(exec);
49
+ pending.delete(exec);
50
+ if (delivery === undefined || result.isError) return;
51
+ const { session, turn, target } = delivery;
52
+ const commandId = `git-review-${exec.callId}` as CommandId;
53
+ session.append("command/run", {
54
+ commandId,
55
+ name: "git-review",
56
+ args: JSON.stringify({ turn, callId: exec.callId, target }),
57
+ source: { kind: "user" },
58
+ });
59
+ session.append("command/done", {
60
+ commandId,
61
+ kind: "success",
62
+ text: `Git review presented: ${target.branch}`,
63
+ });
64
+ });
65
+ },
66
+ });
67
+ }
@@ -0,0 +1,85 @@
1
+ import type {} from "@deepseek-ai/dsh-agent";
2
+ import type {} from "@deepseek-ai/dsh-session/types";
3
+ import { defineTool, type ToolExecution } from "@deepseek-ai/dsh-tools";
4
+ import { workspaceTitleOf } from "@deepseek-ai/dsh-util-workspace-path";
5
+ import {
6
+ branchLabel,
7
+ GIT_REVIEW_TOOL,
8
+ reviewTargetSchema,
9
+ shortSha,
10
+ } from "@lukstei/util-review-ui/review";
11
+ import type { ReviewTarget } from "@lukstei/util-review-ui/types";
12
+
13
+ /** Callback options for presentation tool lifecycle. */
14
+ export interface GitReviewToolOptions {
15
+ onPresented?: (exec: ToolExecution, target: ReviewTarget) => void;
16
+ }
17
+
18
+ /**
19
+ * Build the presentation tool for Git reviews.
20
+ * @param options - optional presentation lifecycle callbacks.
21
+ * @returns the registered tool definition.
22
+ */
23
+ export function createGitReviewTool(options?: GitReviewToolOptions) {
24
+ return defineTool({
25
+ name: GIT_REVIEW_TOOL,
26
+ description:
27
+ "Present a Git review card in the transcript. Always use it instead of writing the branch and commit into the reply when the user should inspect them.",
28
+ parameters: {
29
+ repository: {
30
+ type: "string",
31
+ description:
32
+ "Absolute path, or a path relative to the session working directory (a file or directory inside the repository). Defaults to the session working directory.",
33
+ },
34
+ branch: {
35
+ type: "string",
36
+ required: true,
37
+ description:
38
+ "Local branch name or full ref, e.g. `feature/x` or `refs/heads/feature/x`.",
39
+ },
40
+ commit: {
41
+ type: "string",
42
+ description:
43
+ "Commit SHA or ref on `branch`. Reviews that commit alone instead of every commit on the branch.",
44
+ },
45
+ },
46
+ output: {
47
+ schema: {
48
+ type: "object",
49
+ properties: {
50
+ repository: { type: "string", required: true },
51
+ branch: { type: "string", required: true },
52
+ commit: { type: "string" },
53
+ },
54
+ additionalProperties: false,
55
+ },
56
+ render: (_args, value) => {
57
+ const commit =
58
+ value.commit === undefined ? "" : ` @ ${shortSha(value.commit)}`;
59
+ const repo =
60
+ value.repository === ""
61
+ ? ""
62
+ : ` (${workspaceTitleOf(value.repository)})`;
63
+ return [
64
+ {
65
+ type: "text",
66
+ text: `Git review ready: ${branchLabel(value.branch)}${commit}${repo}`,
67
+ },
68
+ ];
69
+ },
70
+ presentationMeta: (_args, value) => value,
71
+ },
72
+ async execute(args, exec) {
73
+ if (exec.agent === undefined)
74
+ throw new Error("git_review_present requires an agent Session");
75
+ exec.signal.throwIfAborted();
76
+ const target = reviewTargetSchema.parse(args);
77
+ options?.onPresented?.(exec, target);
78
+ return {
79
+ repository: target.repository,
80
+ branch: target.branch,
81
+ ...(target.commit !== undefined ? { commit: target.commit } : {}),
82
+ };
83
+ },
84
+ });
85
+ }
@@ -0,0 +1,400 @@
1
+ import assert from "node:assert/strict";
2
+ import { realpath, stat } from "node:fs/promises";
3
+ import { dirname, isAbsolute, resolve } from "node:path";
4
+ import type { Context } from "@deepseek-ai/cordis";
5
+ import type {} from "@deepseek-ai/dsh-api-session-controller";
6
+ import type {} from "@deepseek-ai/dsh-session";
7
+ import {
8
+ type SessionEvent,
9
+ type SessionHeader,
10
+ SessionId,
11
+ } from "@deepseek-ai/dsh-session/types";
12
+ import type {} from "@deepseek-ai/dsh-session-persistence";
13
+ import type {} from "@deepseek-ai/dsh-tool-executor-ptc/types";
14
+ import type {} from "@deepseek-ai/dsh-tools";
15
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
16
+ import type {} from "@deepseek-ai/dsh-working-directory";
17
+ import type {
18
+ GitCommitPage,
19
+ GitFileContents,
20
+ GitRepository,
21
+ GitSnapshot,
22
+ ResolvedReviewScope,
23
+ ReviewCatalog,
24
+ ReviewSelection,
25
+ ReviewTarget,
26
+ ReviewView,
27
+ } from "@lukstei/util-review-ui/types";
28
+ import { z } from "zod";
29
+ import {
30
+ compare,
31
+ listCommits,
32
+ readFileContents,
33
+ readRepository,
34
+ repositoryRoot,
35
+ resolveReviewScope,
36
+ } from "./git-service.ts";
37
+
38
+ const editedPathSchema = z.object({ path: z.string().refine(isAbsolute) });
39
+
40
+ export class WorkspaceReviewService extends TypertRemoteService {
41
+ static inject = [
42
+ "sessionController",
43
+ "workingDirectory",
44
+ "sessions",
45
+ "sessionPersistence",
46
+ ] as const;
47
+
48
+ private locationsCache = new Map<
49
+ string,
50
+ | { kind: "git"; cwd: string; repositories: string[] }
51
+ | { kind: "unavailable"; cwd: string; error: unknown }
52
+ >();
53
+
54
+ constructor(ctx: Context) {
55
+ super(ctx, "workspaceReview");
56
+ }
57
+
58
+ private async inspectSession(
59
+ sessionId: string,
60
+ signal?: AbortSignal,
61
+ ): Promise<{ meta: SessionHeader; events: readonly SessionEvent[] }> {
62
+ const sid = SessionId(sessionId);
63
+ const attached = this.ctx.sessions.get(sid);
64
+ if (attached !== undefined) {
65
+ return {
66
+ meta: attached.header,
67
+ events: attached.snapshotEvents(),
68
+ };
69
+ }
70
+ const handle = await this.ctx.sessionPersistence.open(
71
+ sid,
72
+ "read",
73
+ signal ? { signal } : undefined,
74
+ );
75
+ try {
76
+ const result = await handle.read(
77
+ undefined,
78
+ undefined,
79
+ signal ? { signal } : undefined,
80
+ );
81
+ return {
82
+ meta: handle.header,
83
+ events: result.events,
84
+ };
85
+ } finally {
86
+ await handle.close();
87
+ }
88
+ }
89
+
90
+ private async sessionLocations(sessionId: string, signal: AbortSignal) {
91
+ const cached = this.locationsCache.get(sessionId);
92
+ const locations =
93
+ cached !== undefined ? cached : await this.locations(sessionId, signal);
94
+ if (locations.kind === "unavailable") throw locations.error;
95
+ return locations;
96
+ }
97
+
98
+ private assertSessionRepository(
99
+ locations: { repositories: string[] },
100
+ repository: string,
101
+ ): void {
102
+ assert(
103
+ locations.repositories.includes(repository),
104
+ "Repository is not part of this session",
105
+ );
106
+ }
107
+
108
+ private async directory(
109
+ sessionId: string,
110
+ signal: AbortSignal,
111
+ target: string,
112
+ ): Promise<string> {
113
+ const locations = await this.sessionLocations(sessionId, signal);
114
+ this.assertSessionRepository(locations, target);
115
+ return target;
116
+ }
117
+
118
+ private async repositoryFor(
119
+ sessionId: string,
120
+ signal: AbortSignal,
121
+ repository: string,
122
+ ): Promise<string> {
123
+ const locations = await this.sessionLocations(sessionId, signal);
124
+ let cwd =
125
+ repository.trim() === ""
126
+ ? locations.cwd
127
+ : resolve(locations.cwd, repository);
128
+ const info = await stat(cwd);
129
+ if (info.isFile()) cwd = dirname(cwd);
130
+ const root = await repositoryRoot(cwd, signal);
131
+ if (root === null) throw new Error(`No Git repository at ${cwd}`);
132
+ this.assertSessionRepository(locations, root);
133
+ return root;
134
+ }
135
+
136
+ private async locations(
137
+ sessionId: string,
138
+ signal: AbortSignal,
139
+ ): Promise<
140
+ | { kind: "git"; cwd: string; repositories: string[] }
141
+ | { kind: "unavailable"; cwd: string; error: unknown }
142
+ > {
143
+ const cached = this.locationsCache.get(sessionId);
144
+ if (cached !== undefined) return cached;
145
+ const inspection = await this.inspectSession(sessionId, signal);
146
+ assert(inspection.meta.cwd, "Review requires a Session workspace");
147
+ const changeIndex = inspection.events.findLastIndex(
148
+ (event: SessionEvent) => event.type === "working-directory/change",
149
+ );
150
+ const change = inspection.events[changeIndex];
151
+ let cwd =
152
+ change === undefined || change.type !== "working-directory/change"
153
+ ? inspection.meta.cwd
154
+ : change.data.cwd;
155
+ try {
156
+ signal.throwIfAborted();
157
+ try {
158
+ await stat(cwd);
159
+ } catch (error) {
160
+ signal.throwIfAborted();
161
+ if (
162
+ error instanceof Error &&
163
+ "code" in error &&
164
+ error.code === "ENOENT"
165
+ ) {
166
+ const result = await this.ctx.sessionController.resolveAgent(
167
+ SessionId(sessionId),
168
+ );
169
+ if ("error" in result) throw result.error;
170
+ cwd = await this.ctx.workingDirectory.ensure(result.agent, signal);
171
+ } else throw error;
172
+ }
173
+ signal.throwIfAborted();
174
+ const repositories: string[] = [];
175
+ const root = await repositoryRoot(cwd, signal);
176
+ if (root !== null) repositories.push(root);
177
+
178
+ const calls = new Set<string>();
179
+ const files = new Set<string>();
180
+ const dirCache = new Map<string, string | null>();
181
+ if (root !== null) dirCache.set(root, root);
182
+
183
+ for (const event of inspection.events.slice(changeIndex + 1)) {
184
+ if (
185
+ event.type === "tool/call" &&
186
+ (event.data.name === "write" || event.data.name === "edit")
187
+ )
188
+ calls.add(event.data.callId);
189
+ let meta: SessionEvent<"tool/result">["data"]["meta"];
190
+ if (event.type === "tool/ptc-dispatch") {
191
+ if (
192
+ event.data.isError ||
193
+ (event.data.name !== "write" && event.data.name !== "edit")
194
+ )
195
+ continue;
196
+ meta = event.data.meta;
197
+ } else if (
198
+ event.type === "tool/result" &&
199
+ !event.data.message.isError &&
200
+ calls.has(event.data.message.toolCallId)
201
+ ) {
202
+ meta = event.data.meta;
203
+ } else continue;
204
+ const parsed = editedPathSchema.safeParse(meta);
205
+ if (!parsed.success || files.has(parsed.data.path)) continue;
206
+ files.add(parsed.data.path);
207
+ const directory = dirname(parsed.data.path);
208
+
209
+ let repository: string | null;
210
+ const cached = dirCache.get(directory);
211
+ if (cached !== undefined) {
212
+ repository = cached;
213
+ } else {
214
+ let canonicalDir = directory;
215
+ try {
216
+ await stat(directory);
217
+ canonicalDir = await realpath(directory);
218
+ } catch (error) {
219
+ signal.throwIfAborted();
220
+ if (
221
+ error instanceof Error &&
222
+ "code" in error &&
223
+ error.code === "ENOENT"
224
+ ) {
225
+ dirCache.set(directory, null);
226
+ continue;
227
+ }
228
+ throw error;
229
+ }
230
+ repository = await repositoryRoot(directory, signal);
231
+ dirCache.set(directory, repository);
232
+ if (canonicalDir !== directory) {
233
+ dirCache.set(canonicalDir, repository);
234
+ }
235
+ if (repository !== null) {
236
+ let current = canonicalDir;
237
+ while (
238
+ current !== repository &&
239
+ current.startsWith(repository) &&
240
+ current !== dirname(current)
241
+ ) {
242
+ current = dirname(current);
243
+ dirCache.set(current, repository);
244
+ }
245
+ }
246
+ }
247
+ if (repository !== null && !repositories.includes(repository)) {
248
+ repositories.push(repository);
249
+ }
250
+ }
251
+
252
+ let result:
253
+ | { kind: "git"; cwd: string; repositories: string[] }
254
+ | { kind: "unavailable"; cwd: string; error: unknown };
255
+ if (repositories.length > 0) {
256
+ result = { kind: "git", cwd, repositories };
257
+ } else {
258
+ result = {
259
+ kind: "unavailable",
260
+ cwd,
261
+ error: new Error(
262
+ "No Git repository found in the working directory or edited files",
263
+ ),
264
+ };
265
+ }
266
+ this.locationsCache.set(sessionId, result);
267
+ return result;
268
+ } catch (error) {
269
+ signal.throwIfAborted();
270
+ const failure = { kind: "unavailable" as const, cwd, error };
271
+ this.locationsCache.set(sessionId, failure);
272
+ return failure;
273
+ }
274
+ }
275
+
276
+ @Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })
277
+ async catalog(
278
+ sessionId: string,
279
+ signal: AbortSignal,
280
+ ): Promise<ReviewCatalog> {
281
+ this.locationsCache.delete(sessionId);
282
+ const locations = await this.locations(sessionId, signal);
283
+ if (locations.kind === "unavailable")
284
+ return {
285
+ kind: "unavailable",
286
+ cwd: locations.cwd,
287
+ message: String(locations.error),
288
+ };
289
+ try {
290
+ const settled = await Promise.allSettled(
291
+ locations.repositories.map((cwd) => readRepository(cwd, signal)),
292
+ );
293
+ const repositories: GitRepository[] = [];
294
+ for (const result of settled) {
295
+ if (result.status === "fulfilled") {
296
+ repositories.push(result.value);
297
+ }
298
+ }
299
+ if (repositories.length === 0) {
300
+ return {
301
+ kind: "unavailable",
302
+ cwd: locations.cwd,
303
+ message: "No repositories could be read",
304
+ };
305
+ }
306
+ return {
307
+ kind: "git",
308
+ repository: repositories[0],
309
+ repositories,
310
+ };
311
+ } catch (error) {
312
+ signal.throwIfAborted();
313
+ return {
314
+ kind: "unavailable",
315
+ cwd: locations.cwd,
316
+ message: String(error),
317
+ };
318
+ }
319
+ }
320
+
321
+ @Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })
322
+ async resolve(
323
+ sessionId: string,
324
+ target: ReviewTarget,
325
+ signal: AbortSignal,
326
+ ): Promise<ResolvedReviewScope> {
327
+ return resolveReviewScope(
328
+ await this.repositoryFor(sessionId, signal, target.repository),
329
+ target,
330
+ signal,
331
+ );
332
+ }
333
+
334
+ @Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })
335
+ async commits(
336
+ sessionId: string,
337
+ repository: string,
338
+ branch: string,
339
+ base: string,
340
+ offset: number,
341
+ signal: AbortSignal,
342
+ ): Promise<GitCommitPage> {
343
+ const cwd = await this.directory(sessionId, signal, repository);
344
+ return listCommits(cwd, branch, base, offset, signal);
345
+ }
346
+
347
+ @Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })
348
+ async view(
349
+ sessionId: string,
350
+ selection: ReviewSelection,
351
+ signal: AbortSignal,
352
+ ): Promise<ReviewView> {
353
+ switch (selection.kind) {
354
+ case "branch":
355
+ return {
356
+ kind: "diff",
357
+ view: await compare(
358
+ await this.directory(sessionId, signal, selection.repository),
359
+ selection.revision.kind === "all-commits"
360
+ ? { kind: "branch", branch: selection.ref, base: selection.base }
361
+ : {
362
+ kind: "commit",
363
+ branch: selection.ref,
364
+ commit: selection.revision.commit.sha,
365
+ },
366
+ signal,
367
+ ),
368
+ };
369
+ case "uncommitted":
370
+ return {
371
+ kind: "diff",
372
+ view: await compare(
373
+ await this.directory(sessionId, signal, selection.repository),
374
+ { kind: selection.stage },
375
+ signal,
376
+ ),
377
+ };
378
+ default:
379
+ selection satisfies never;
380
+ throw new Error("Unknown review scope");
381
+ }
382
+ }
383
+
384
+ @Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })
385
+ async file(
386
+ sessionId: string,
387
+ snapshot: GitSnapshot,
388
+ path: string,
389
+ signal: AbortSignal,
390
+ ): Promise<GitFileContents> {
391
+ const cwd = await this.directory(sessionId, signal, snapshot.repository);
392
+ return readFileContents(cwd, snapshot, path, signal);
393
+ }
394
+ }
395
+
396
+ declare module "@deepseek-ai/cordis" {
397
+ interface Context {
398
+ workspaceReview: WorkspaceReviewService;
399
+ }
400
+ }