@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/dist/host.js ADDED
@@ -0,0 +1,1101 @@
1
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2
+ import { workspaceTitleOf } from "@deepseek-ai/dsh-util-workspace-path";
3
+ import { z } from "zod";
4
+ import assert from "node:assert/strict";
5
+ import { lstat, readFile, readlink, realpath, stat } from "node:fs/promises";
6
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
+ import { SessionId } from "@deepseek-ai/dsh-session/types";
8
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
9
+ import { execFile } from "node:child_process";
10
+ import { createHash } from "node:crypto";
11
+ import { promisify } from "node:util";
12
+ // ../util-review-ui/src/review.ts
13
+ const commit = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/);
14
+ const commitRecord = z.object({
15
+ sha: commit,
16
+ subject: z.string(),
17
+ author: z.string(),
18
+ date: z.string()
19
+ });
20
+ const reviewTargetSchema = z.object({
21
+ repository: z.string().default(""),
22
+ branch: z.string().min(1),
23
+ commit: z.string().min(1).optional()
24
+ });
25
+ /** Wire name of the presentation tool whose calls publish a review card. */
26
+ const GIT_REVIEW_TOOL = "git_review_present";
27
+ z.object({
28
+ kind: z.literal("branch"),
29
+ repository: z.string().min(1),
30
+ ref: z.string().min(1),
31
+ base: z.discriminatedUnion("kind", [z.object({ kind: z.literal("automatic") }), z.object({
32
+ kind: z.literal("manual"),
33
+ ref: z.string().min(1)
34
+ })]),
35
+ revision: z.discriminatedUnion("kind", [z.object({ kind: z.literal("all-commits") }), z.object({
36
+ kind: z.literal("commit"),
37
+ commit: commitRecord
38
+ })])
39
+ });
40
+ function branchLabel(ref) {
41
+ return ref.startsWith("refs/heads/") ? ref.slice(11) : ref;
42
+ }
43
+ function shortSha(sha) {
44
+ return sha.slice(0, 7);
45
+ }
46
+ const snapshotSchema = z.object({
47
+ kind: z.enum([
48
+ "revision",
49
+ "staged",
50
+ "unstaged"
51
+ ]),
52
+ repository: z.string().min(1),
53
+ before: commit.nullable(),
54
+ after: commit
55
+ });
56
+ // src/review-tool.ts
57
+ /**
58
+ * Build the presentation tool for Git reviews.
59
+ * @param options - optional presentation lifecycle callbacks.
60
+ * @returns the registered tool definition.
61
+ */
62
+ function createGitReviewTool(options) {
63
+ return defineTool({
64
+ name: GIT_REVIEW_TOOL,
65
+ description: "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.",
66
+ parameters: {
67
+ repository: {
68
+ type: "string",
69
+ description: "Absolute path, or a path relative to the session working directory (a file or directory inside the repository). Defaults to the session working directory."
70
+ },
71
+ branch: {
72
+ type: "string",
73
+ required: true,
74
+ description: "Local branch name or full ref, e.g. `feature/x` or `refs/heads/feature/x`."
75
+ },
76
+ commit: {
77
+ type: "string",
78
+ description: "Commit SHA or ref on `branch`. Reviews that commit alone instead of every commit on the branch."
79
+ }
80
+ },
81
+ output: {
82
+ schema: {
83
+ type: "object",
84
+ properties: {
85
+ repository: {
86
+ type: "string",
87
+ required: true
88
+ },
89
+ branch: {
90
+ type: "string",
91
+ required: true
92
+ },
93
+ commit: { type: "string" }
94
+ },
95
+ additionalProperties: false
96
+ },
97
+ render: (_args, value) => {
98
+ const commit = value.commit === void 0 ? "" : ` @ ${shortSha(value.commit)}`;
99
+ const repo = value.repository === "" ? "" : ` (${workspaceTitleOf(value.repository)})`;
100
+ return [{
101
+ type: "text",
102
+ text: `Git review ready: ${branchLabel(value.branch)}${commit}${repo}`
103
+ }];
104
+ },
105
+ presentationMeta: (_args, value) => value
106
+ },
107
+ async execute(args, exec) {
108
+ if (exec.agent === void 0) throw new Error("git_review_present requires an agent Session");
109
+ exec.signal.throwIfAborted();
110
+ const target = reviewTargetSchema.parse(args);
111
+ options?.onPresented?.(exec, target);
112
+ return {
113
+ repository: target.repository,
114
+ branch: target.branch,
115
+ ...target.commit !== void 0 ? { commit: target.commit } : {}
116
+ };
117
+ }
118
+ });
119
+ }
120
+ // src/git-service.ts
121
+ const execute = promisify(execFile);
122
+ const targetSchema = z.object({ branch: z.string().min(1) });
123
+ const statusSchema = z.object({ stacks: z.array(z.object({ branches: z.array(z.object({
124
+ name: z.string(),
125
+ commits: z.array(z.object({
126
+ commitId: z.string(),
127
+ message: z.string(),
128
+ authorName: z.string(),
129
+ createdAt: z.string()
130
+ }))
131
+ })) })) });
132
+ const diffOptions = [
133
+ "--no-ext-diff",
134
+ "--no-textconv",
135
+ "--no-color",
136
+ "--no-renames",
137
+ "--no-relative"
138
+ ];
139
+ async function git(cwd, args, signal) {
140
+ const { stdout } = await execute("git", [
141
+ "--no-optional-locks",
142
+ "-c",
143
+ "core.quotePath=false",
144
+ "-c",
145
+ "diff.autoRefreshIndex=false",
146
+ ...args
147
+ ], {
148
+ cwd,
149
+ signal,
150
+ maxBuffer: 0xa00000
151
+ });
152
+ return stdout;
153
+ }
154
+ async function repositoryRoot(cwd, signal) {
155
+ try {
156
+ const { stdout } = await execute("git", ["rev-parse", "--show-toplevel"], {
157
+ cwd,
158
+ signal,
159
+ env: {
160
+ ...process.env,
161
+ LC_ALL: "C"
162
+ }
163
+ });
164
+ return stdout.trim();
165
+ } catch (error) {
166
+ signal.throwIfAborted();
167
+ if (error instanceof Error && "stderr" in error && typeof error.stderr === "string" && error.stderr.includes("fatal: not a git repository")) return null;
168
+ throw error;
169
+ }
170
+ }
171
+ async function resolveCommit(cwd, ref, signal) {
172
+ return (await git(cwd, [
173
+ "rev-parse",
174
+ "--verify",
175
+ "--end-of-options",
176
+ `${ref}^{commit}`
177
+ ], signal)).trim();
178
+ }
179
+ async function head(cwd, signal) {
180
+ try {
181
+ return (await git(cwd, [
182
+ "rev-parse",
183
+ "--verify",
184
+ "--quiet",
185
+ "HEAD"
186
+ ], signal)).trim();
187
+ } catch (error) {
188
+ if (error instanceof Error && "code" in error && error.code === 1) return null;
189
+ throw error;
190
+ }
191
+ }
192
+ async function targetBranch(cwd, signal) {
193
+ const { stdout } = await execute("but", [
194
+ "--json",
195
+ "config",
196
+ "target"
197
+ ], {
198
+ cwd,
199
+ signal
200
+ });
201
+ const value = JSON.parse(stdout);
202
+ return targetSchema.parse(value).branch;
203
+ }
204
+ async function readStacks(cwd, signal) {
205
+ const { stdout } = await execute("but", ["--json", "status"], {
206
+ cwd,
207
+ signal,
208
+ maxBuffer: 0xa00000
209
+ });
210
+ const value = JSON.parse(stdout);
211
+ return statusSchema.parse(value).stacks;
212
+ }
213
+ async function readButler(cwd, signal) {
214
+ try {
215
+ const commonDir = (await git(cwd, ["rev-parse", "--git-common-dir"], signal)).trim();
216
+ const marker = resolve(cwd, commonDir, "gitbutler");
217
+ if (!(await stat(marker)).isDirectory()) return { kind: "unconfigured" };
218
+ } catch {
219
+ signal.throwIfAborted();
220
+ return { kind: "unconfigured" };
221
+ }
222
+ try {
223
+ const [target, stacks] = await Promise.all([targetBranch(cwd, signal), readStacks(cwd, signal)]);
224
+ return {
225
+ kind: "ready",
226
+ target,
227
+ stacks
228
+ };
229
+ } catch (error) {
230
+ signal.throwIfAborted();
231
+ const output = error instanceof Error ? `${error.message} ${"stdout" in error ? String(error.stdout) : ""} ${"stderr" in error ? String(error.stderr) : ""}` : String(error);
232
+ if ((error instanceof Error && "code" in error ? String(error.code) : "") === "ENOENT" || output.includes("ENOENT") || output.includes("not installed") || output.includes("setup_required") || output.includes("No GitButler project found") || output.includes("not a GitButler project")) return { kind: "unconfigured" };
233
+ return {
234
+ kind: "unavailable",
235
+ message: error instanceof Error ? error.message : String(error)
236
+ };
237
+ }
238
+ }
239
+ function branchBase(stacks, ref, target) {
240
+ const name = ref.startsWith("refs/heads/") ? ref.slice(11) : ref;
241
+ for (const { branches } of stacks) {
242
+ const index = branches.findIndex((branch) => branch.name === name);
243
+ if (index !== -1 && index + 1 < branches.length) return `refs/heads/${branches[index + 1].name}`;
244
+ }
245
+ return target;
246
+ }
247
+ async function readRepository(cwd, signal) {
248
+ const [refs, butler] = await Promise.all([git(cwd, [
249
+ "for-each-ref",
250
+ "--sort=refname",
251
+ "--format=%(refname)%09%(symref)%09%(committerdate:unix)",
252
+ "refs/heads",
253
+ "refs/remotes"
254
+ ], signal), readButler(cwd, signal)]);
255
+ const entries = refs.split("\n").filter(Boolean).map((line) => {
256
+ const [ref, symbolic, committed] = line.split(" ");
257
+ return {
258
+ ref,
259
+ symbolic,
260
+ modifiedAt: Number(committed) * 1e3
261
+ };
262
+ });
263
+ const defaults = [...new Set(entries.filter((item) => item.ref.startsWith("refs/remotes/") && item.ref.endsWith("/HEAD") && item.symbolic !== "").map((item) => item.symbolic))];
264
+ const label = (ref) => ref.replace(/^refs\/(?:heads|remotes)\//, "");
265
+ const target = defaults.length === 1 ? defaults[0] : null;
266
+ const baselines = entries.filter((item) => item.symbolic === "").map(({ ref }) => ({
267
+ ref,
268
+ label: label(ref)
269
+ }));
270
+ let managedTarget = null;
271
+ let gitbutlerError = null;
272
+ if (butler.kind === "unavailable") gitbutlerError = butler.message;
273
+ else if (butler.kind === "ready") {
274
+ const exact = baselines.find((entry) => entry.ref === butler.target);
275
+ const matches = exact === void 0 ? baselines.filter((entry) => entry.label === butler.target) : [exact];
276
+ if (matches.length === 1) managedTarget = matches[0].ref;
277
+ else gitbutlerError = `GitButler target "${butler.target}" ${matches.length === 0 ? "was not found" : "is ambiguous"}; configure an explicit branch ref.`;
278
+ }
279
+ return {
280
+ cwd,
281
+ target,
282
+ baselines,
283
+ branches: entries.filter((item) => item.ref.startsWith("refs/heads/") && item.symbolic === "" && Date.now() - item.modifiedAt <= 6048e5 && (butler.kind !== "ready" || ![
284
+ "refs/heads/gitbutler/workspace",
285
+ "refs/heads/gitbutler/target",
286
+ "refs/heads/main"
287
+ ].includes(item.ref))).sort((a, b) => b.modifiedAt - a.modifiedAt).map(({ ref, modifiedAt }) => {
288
+ const name = label(ref);
289
+ const managed = butler.kind === "ready" && butler.stacks.some((stack) => stack.branches.some((branch) => branch.name === name));
290
+ return {
291
+ ref,
292
+ label: name,
293
+ modifiedAt,
294
+ base: managed && butler.kind === "ready" ? branchBase(butler.stacks, ref, managedTarget) : target,
295
+ kind: managed ? "gitbutler" : "git"
296
+ };
297
+ }),
298
+ gitbutlerError
299
+ };
300
+ }
301
+ const commitFormat = "%H%x00%s%x00%an%x00%aI";
302
+ function parseCommitRecord(entry) {
303
+ const [sha, subject, author, date] = entry.split("\0");
304
+ assert(sha !== void 0 && subject !== void 0);
305
+ assert(author !== void 0 && date !== void 0);
306
+ return {
307
+ sha,
308
+ subject,
309
+ author,
310
+ date
311
+ };
312
+ }
313
+ async function readCommit(cwd, rev, signal) {
314
+ return parseCommitRecord((await git(cwd, [
315
+ "show",
316
+ "-s",
317
+ `--format=${commitFormat}`,
318
+ rev
319
+ ], signal)).trimEnd());
320
+ }
321
+ async function isAncestor(cwd, ancestor, descendant, signal) {
322
+ try {
323
+ await git(cwd, [
324
+ "merge-base",
325
+ "--is-ancestor",
326
+ ancestor,
327
+ descendant
328
+ ], signal);
329
+ return true;
330
+ } catch (error) {
331
+ signal.throwIfAborted();
332
+ if (error instanceof Error && "code" in error && error.code === 1) return false;
333
+ throw error;
334
+ }
335
+ }
336
+ /**
337
+ * Turn a repository path and branch/commit request into the scope the review pane renders.
338
+ * @param cwd - repository root, or a directory inside it.
339
+ * @param target - requested repository, branch, and optional commit.
340
+ * @param signal - cancellation for every Git read.
341
+ * @returns the branch scope with a resolved baseline and commit page entry.
342
+ */
343
+ async function resolveReviewScope(cwd, target, signal) {
344
+ const repository = (await git(cwd, ["rev-parse", "--show-toplevel"], signal)).trim();
345
+ const repo = await readRepository(repository, signal);
346
+ const known = repo.branches.find((item) => item.ref === target.branch || item.label === target.branch);
347
+ let ref;
348
+ let label;
349
+ let base;
350
+ if (known === void 0) {
351
+ ref = target.branch.startsWith("refs/heads/") ? target.branch : `refs/heads/${target.branch}`;
352
+ label = branchLabel(ref);
353
+ try {
354
+ await resolveCommit(repository, ref, signal);
355
+ } catch {
356
+ signal.throwIfAborted();
357
+ const names = repo.branches.slice(0, 20).map((item) => item.label);
358
+ throw new Error(`Unknown branch "${target.branch}" in ${repository}. Available: ${names.length === 0 ? "none" : names.join(", ")}`);
359
+ }
360
+ base = repo.target ?? "";
361
+ } else {
362
+ ref = known.ref;
363
+ label = known.label;
364
+ base = known.base ?? repo.target ?? "";
365
+ }
366
+ if (base === "") throw new Error(`Cannot compare "${label}" without a baseline; set a remote HEAD or choose a baseline in the review toolbar`);
367
+ const scope = {
368
+ kind: "branch",
369
+ repository,
370
+ ref,
371
+ base: {
372
+ kind: "manual",
373
+ ref: base
374
+ }
375
+ };
376
+ if (target.commit === void 0) return {
377
+ ...scope,
378
+ revision: { kind: "all-commits" }
379
+ };
380
+ const sha = await resolveCommit(repository, target.commit, signal);
381
+ if (!await isAncestor(repository, sha, ref, signal)) throw new Error(`Commit "${target.commit}" is not an ancestor of "${label}"`);
382
+ return {
383
+ ...scope,
384
+ revision: {
385
+ kind: "commit",
386
+ commit: await readCommit(repository, sha, signal)
387
+ }
388
+ };
389
+ }
390
+ async function listCommits(cwd, branch, base, offset, signal) {
391
+ assert(Number.isSafeInteger(offset) && offset >= 0, "Invalid commit offset");
392
+ const butler = await readButler(cwd, signal);
393
+ const name = branch.startsWith("refs/heads/") ? branch.slice(11) : branch;
394
+ if (butler.kind === "ready") {
395
+ const owned = butler.stacks.flatMap((stack) => stack.branches).find((item) => item.name === name);
396
+ if (owned !== void 0) return {
397
+ commits: owned.commits.slice(offset, offset + 50).map((commit) => ({
398
+ sha: commit.commitId,
399
+ subject: commit.message.split("\n")[0],
400
+ author: commit.authorName,
401
+ date: commit.createdAt
402
+ })),
403
+ hasMore: owned.commits.length > offset + 50
404
+ };
405
+ }
406
+ const [sha, baseline] = await Promise.all([resolveCommit(cwd, branch, signal), resolveCommit(cwd, base, signal)]);
407
+ const entries = (await git(cwd, [
408
+ "log",
409
+ `--format=${commitFormat}`,
410
+ `--skip=${offset}`,
411
+ `--max-count=51`,
412
+ `${baseline}..${sha}`,
413
+ "--"
414
+ ], signal)).trimEnd().split("\n").filter(Boolean);
415
+ return {
416
+ commits: entries.slice(0, 50).map(parseCommitRecord),
417
+ hasMore: entries.length > 50
418
+ };
419
+ }
420
+ function revisionArgs(snapshot) {
421
+ return snapshot.before === null ? [
422
+ "diff-tree",
423
+ "--root",
424
+ "--no-commit-id",
425
+ "-r",
426
+ snapshot.after
427
+ ] : [
428
+ "diff",
429
+ snapshot.before,
430
+ snapshot.after
431
+ ];
432
+ }
433
+ async function fileMetadata(cwd, args, signal) {
434
+ const [names, stats] = await Promise.all([git(cwd, [
435
+ ...args,
436
+ ...diffOptions,
437
+ "--name-status",
438
+ "-z",
439
+ "--"
440
+ ], signal), git(cwd, [
441
+ ...args,
442
+ ...diffOptions,
443
+ "--numstat",
444
+ "-z",
445
+ "--"
446
+ ], signal)]);
447
+ const counts = new Map(stats.split("\0").filter(Boolean).map((record) => {
448
+ const first = record.indexOf(" ");
449
+ const second = record.indexOf(" ", first + 1);
450
+ assert(first > 0 && second > first, "Invalid Git numstat record");
451
+ const added = record.slice(0, first);
452
+ const deleted = record.slice(first + 1, second);
453
+ return [record.slice(second + 1), {
454
+ addedLines: added === "-" ? 0 : Number(added),
455
+ deletedLines: deleted === "-" ? 0 : Number(deleted)
456
+ }];
457
+ }));
458
+ const records = names.split("\0");
459
+ assert.equal(records.pop(), "", "Git filenames must be NUL-terminated");
460
+ const diffs = [];
461
+ for (let i = 0; i < records.length; i += 2) {
462
+ const status = records[i];
463
+ const path = records[i + 1];
464
+ assert.notEqual(status, "U", "Unresolved index conflicts cannot be displayed as a two-sided diff");
465
+ assert([
466
+ "A",
467
+ "D",
468
+ "M",
469
+ "T"
470
+ ].includes(status), `Unsupported Git change: ${status}`);
471
+ const count = counts.get(path);
472
+ if (count === void 0 && status === "M") continue;
473
+ assert(count, "Git change is missing its numstat record");
474
+ diffs.push({
475
+ path,
476
+ status: status === "A" ? "added" : status === "D" ? "deleted" : "modified",
477
+ ...count
478
+ });
479
+ }
480
+ return diffs;
481
+ }
482
+ function summary(diffs) {
483
+ return {
484
+ files: diffs.length,
485
+ added: diffs.reduce((sum, file) => sum + file.addedLines, 0),
486
+ deleted: diffs.reduce((sum, file) => sum + file.deletedLines, 0)
487
+ };
488
+ }
489
+ function digest(value) {
490
+ return createHash("sha256").update(value).digest("hex");
491
+ }
492
+ async function worktreeFile(repository, path) {
493
+ const filename = resolve(repository, path);
494
+ const inside = relative(repository, filename);
495
+ assert(inside !== "" && !isAbsolute(inside) && inside !== ".." && !inside.startsWith(`..${sep}`), "File must stay inside the repository");
496
+ const parent = relative(await realpath(repository), await realpath(dirname(filename)));
497
+ assert(!isAbsolute(parent) && parent !== ".." && !parent.startsWith(`..${sep}`), "File parent must stay inside the repository");
498
+ const stat = await lstat(filename);
499
+ if (stat.isSymbolicLink()) return {
500
+ contents: await readlink(filename, { encoding: "buffer" }),
501
+ mode: stat.mode
502
+ };
503
+ if (!stat.isFile()) return {
504
+ contents: null,
505
+ mode: stat.mode
506
+ };
507
+ return {
508
+ contents: await readFile(filename),
509
+ mode: stat.mode
510
+ };
511
+ }
512
+ async function workingChanges(repository, kind, signal) {
513
+ const index = await git(repository, [
514
+ "ls-files",
515
+ "--stage",
516
+ "-z"
517
+ ], signal);
518
+ const conflicts = await git(repository, [
519
+ "ls-files",
520
+ "--unmerged",
521
+ "-z"
522
+ ], signal);
523
+ assert.equal(conflicts, "", "Unresolved index conflicts cannot be displayed as a two-sided diff");
524
+ const before = kind === "staged" ? await head(repository, signal) : digest(index);
525
+ const diffs = await fileMetadata(repository, kind === "staged" ? [
526
+ "diff",
527
+ "--cached",
528
+ ...before === null ? [] : [before]
529
+ ] : ["diff"], signal);
530
+ const contents = /* @__PURE__ */ new Map();
531
+ const identities = [];
532
+ if (kind === "unstaged") {
533
+ const untracked = (await git(repository, [
534
+ "ls-files",
535
+ "--others",
536
+ "--exclude-standard",
537
+ "-z"
538
+ ], signal)).split("\0").filter(Boolean);
539
+ const untrackedPaths = new Set(untracked);
540
+ for (const path of untracked) diffs.push({
541
+ path,
542
+ status: "added",
543
+ addedLines: 0,
544
+ deletedLines: 0
545
+ });
546
+ await Promise.all(diffs.map(async (file) => {
547
+ if (file.status === "deleted") {
548
+ contents.set(file.path, null);
549
+ return;
550
+ }
551
+ const value = await worktreeFile(repository, file.path);
552
+ contents.set(file.path, value.contents);
553
+ identities.push([
554
+ file.path,
555
+ value.mode,
556
+ value.contents === null ? null : digest(value.contents)
557
+ ]);
558
+ const supportsLineCounting = value.contents !== null && !value.contents.includes(0);
559
+ if (untrackedPaths.has(file.path) && supportsLineCounting) file.addedLines = value.contents.length === 0 ? 0 : value.contents.toString("utf8").split("\n").length - (value.contents.at(-1) === 10 ? 1 : 0);
560
+ }));
561
+ }
562
+ assert.equal(await git(repository, [
563
+ "ls-files",
564
+ "--stage",
565
+ "-z"
566
+ ], signal), index, "Index changed; refresh the comparison");
567
+ return {
568
+ snapshot: {
569
+ kind,
570
+ repository,
571
+ before,
572
+ after: kind === "staged" ? digest(index) : digest(JSON.stringify([diffs, identities.sort(([a], [b]) => a.localeCompare(b))]))
573
+ },
574
+ diffs,
575
+ index,
576
+ contents
577
+ };
578
+ }
579
+ async function compare(cwd, comparison, signal) {
580
+ const repository = (await git(cwd, ["rev-parse", "--show-toplevel"], signal)).trim();
581
+ if (comparison.kind === "staged" || comparison.kind === "unstaged") {
582
+ const { snapshot, diffs } = await workingChanges(repository, comparison.kind, signal);
583
+ return {
584
+ target: comparison.kind === "staged" ? "HEAD → Index" : "Index → Working tree",
585
+ snapshot,
586
+ diffs,
587
+ summary: summary(diffs)
588
+ };
589
+ }
590
+ const branch = await resolveCommit(repository, comparison.branch, signal);
591
+ let before;
592
+ let after;
593
+ let target;
594
+ if (comparison.kind === "branch") {
595
+ before = (await git(repository, [
596
+ "merge-base",
597
+ await resolveCommit(repository, comparison.base, signal),
598
+ branch
599
+ ], signal)).trim();
600
+ after = branch;
601
+ target = comparison.base;
602
+ } else {
603
+ after = await resolveCommit(repository, comparison.commit, signal);
604
+ await git(repository, [
605
+ "merge-base",
606
+ "--is-ancestor",
607
+ after,
608
+ branch
609
+ ], signal);
610
+ const parents = (await git(repository, [
611
+ "rev-list",
612
+ "--parents",
613
+ "-n",
614
+ "1",
615
+ after,
616
+ "--"
617
+ ], signal)).trim().split(" ");
618
+ before = parents.length === 1 ? null : parents[1];
619
+ target = before === null ? "Initial commit" : before;
620
+ }
621
+ const snapshot = {
622
+ kind: "revision",
623
+ repository,
624
+ before,
625
+ after
626
+ };
627
+ const diffs = await fileMetadata(repository, revisionArgs(snapshot), signal);
628
+ return {
629
+ target,
630
+ snapshot,
631
+ diffs,
632
+ summary: summary(diffs)
633
+ };
634
+ }
635
+ async function blob(repository, object, signal) {
636
+ const { stdout } = await execute("git", [
637
+ "cat-file",
638
+ "blob",
639
+ object
640
+ ], {
641
+ cwd: repository,
642
+ signal,
643
+ encoding: "buffer",
644
+ maxBuffer: 0xa00000
645
+ });
646
+ return stdout;
647
+ }
648
+ async function revisionFile(repository, revision, path, signal) {
649
+ if (revision === null) return null;
650
+ const entry = await git(repository, [
651
+ "--literal-pathspecs",
652
+ "ls-tree",
653
+ "-z",
654
+ revision,
655
+ "--",
656
+ path
657
+ ], signal);
658
+ if (entry === "") return null;
659
+ const separator = entry.indexOf(" ");
660
+ const [, type, object] = entry.slice(0, separator).split(" ");
661
+ assert.equal(entry.slice(separator + 1, -1), path, "Expected an exact file path");
662
+ assert.equal(type, "blob", "Only file blobs can be displayed");
663
+ return blob(repository, object, signal);
664
+ }
665
+ async function readFileContents(cwd, snapshot, path, signal) {
666
+ snapshotSchema.parse(snapshot);
667
+ const repository = (await git(cwd, ["rev-parse", "--show-toplevel"], signal)).trim();
668
+ assert.equal(snapshot.repository, repository, "Comparison belongs to another repository");
669
+ let before;
670
+ let after;
671
+ if (snapshot.kind === "revision") {
672
+ const diffs = await fileMetadata(repository, revisionArgs(snapshot), signal);
673
+ assert(diffs.some((file) => file.path === path), "File must belong to this comparison");
674
+ [before, after] = await Promise.all([revisionFile(repository, snapshot.before, path, signal), revisionFile(repository, snapshot.after, path, signal)]);
675
+ } else {
676
+ const current = await workingChanges(repository, snapshot.kind, signal);
677
+ assert.deepEqual(current.snapshot, snapshot, "Contents changed; refresh the comparison");
678
+ const file = current.diffs.find((file) => file.path === path);
679
+ assert(file, "File must belong to this comparison");
680
+ const entry = current.index.split("\0").find((entry) => entry.slice(entry.indexOf(" ") + 1) === path);
681
+ let staged = null;
682
+ if (entry !== void 0) {
683
+ const [mode, object] = entry.slice(0, entry.indexOf(" ")).split(" ");
684
+ if (mode === "160000") return {
685
+ kind: "unavailable",
686
+ message: "Submodule change; no text display or line comments."
687
+ };
688
+ staged = await blob(repository, object, signal);
689
+ }
690
+ if (snapshot.kind === "staged") {
691
+ before = await revisionFile(repository, snapshot.before, path, signal);
692
+ after = staged;
693
+ } else {
694
+ before = staged;
695
+ const content = current.contents.get(path);
696
+ assert(content !== void 0, "Working-tree content must belong to this comparison");
697
+ if (content === null && file.status !== "deleted") return {
698
+ kind: "unavailable",
699
+ message: "Only files and symlinks can be displayed."
700
+ };
701
+ after = content;
702
+ }
703
+ }
704
+ if ([before, after].filter((content) => content !== null).some((content) => content.includes(0))) return {
705
+ kind: "unavailable",
706
+ message: "Files containing NUL bytes cannot be displayed or annotated."
707
+ };
708
+ try {
709
+ const decoder = new TextDecoder("utf-8", {
710
+ fatal: true,
711
+ ignoreBOM: true
712
+ });
713
+ return {
714
+ kind: "text",
715
+ before: before === null ? null : decoder.decode(before),
716
+ after: after === null ? null : decoder.decode(after)
717
+ };
718
+ } catch {
719
+ return {
720
+ kind: "unavailable",
721
+ message: "Only UTF-8 text files can be displayed."
722
+ };
723
+ }
724
+ }
725
+ // src/workspace-review-service.ts
726
+ var __runInitializers = function(thisArg, initializers, value) {
727
+ var useValue = arguments.length > 2;
728
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
729
+ return useValue ? value : void 0;
730
+ };
731
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
732
+ function accept(f) {
733
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
734
+ return f;
735
+ }
736
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
737
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
738
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
739
+ var _, done = false;
740
+ for (var i = decorators.length - 1; i >= 0; i--) {
741
+ var context = {};
742
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
743
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
744
+ context.addInitializer = function(f) {
745
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
746
+ extraInitializers.push(accept(f || null));
747
+ };
748
+ var result = (0, decorators[i])(kind === "accessor" ? {
749
+ get: descriptor.get,
750
+ set: descriptor.set
751
+ } : descriptor[key], context);
752
+ if (kind === "accessor") {
753
+ if (result === void 0) continue;
754
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
755
+ if (_ = accept(result.get)) descriptor.get = _;
756
+ if (_ = accept(result.set)) descriptor.set = _;
757
+ if (_ = accept(result.init)) initializers.unshift(_);
758
+ } else if (_ = accept(result)) {
759
+ if (kind === "field") initializers.unshift(_);
760
+ else descriptor[key] = _;
761
+ }
762
+ }
763
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
764
+ done = true;
765
+ };
766
+ const editedPathSchema = z.object({ path: z.string().refine(isAbsolute) });
767
+ let WorkspaceReviewService = (() => {
768
+ let _classSuper = TypertRemoteService;
769
+ let _instanceExtraInitializers = [];
770
+ let _catalog_decorators;
771
+ let _resolve_decorators;
772
+ let _commits_decorators;
773
+ let _view_decorators;
774
+ let _file_decorators;
775
+ return class WorkspaceReviewService extends _classSuper {
776
+ static {
777
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
778
+ _catalog_decorators = [Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })];
779
+ _resolve_decorators = [Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })];
780
+ _commits_decorators = [Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })];
781
+ _view_decorators = [Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })];
782
+ _file_decorators = [Remote({ resources: { session: (sessionId) => SessionId(sessionId) } })];
783
+ __esDecorate(this, null, _catalog_decorators, {
784
+ kind: "method",
785
+ name: "catalog",
786
+ static: false,
787
+ private: false,
788
+ access: {
789
+ has: (obj) => "catalog" in obj,
790
+ get: (obj) => obj.catalog
791
+ },
792
+ metadata: _metadata
793
+ }, null, _instanceExtraInitializers);
794
+ __esDecorate(this, null, _resolve_decorators, {
795
+ kind: "method",
796
+ name: "resolve",
797
+ static: false,
798
+ private: false,
799
+ access: {
800
+ has: (obj) => "resolve" in obj,
801
+ get: (obj) => obj.resolve
802
+ },
803
+ metadata: _metadata
804
+ }, null, _instanceExtraInitializers);
805
+ __esDecorate(this, null, _commits_decorators, {
806
+ kind: "method",
807
+ name: "commits",
808
+ static: false,
809
+ private: false,
810
+ access: {
811
+ has: (obj) => "commits" in obj,
812
+ get: (obj) => obj.commits
813
+ },
814
+ metadata: _metadata
815
+ }, null, _instanceExtraInitializers);
816
+ __esDecorate(this, null, _view_decorators, {
817
+ kind: "method",
818
+ name: "view",
819
+ static: false,
820
+ private: false,
821
+ access: {
822
+ has: (obj) => "view" in obj,
823
+ get: (obj) => obj.view
824
+ },
825
+ metadata: _metadata
826
+ }, null, _instanceExtraInitializers);
827
+ __esDecorate(this, null, _file_decorators, {
828
+ kind: "method",
829
+ name: "file",
830
+ static: false,
831
+ private: false,
832
+ access: {
833
+ has: (obj) => "file" in obj,
834
+ get: (obj) => obj.file
835
+ },
836
+ metadata: _metadata
837
+ }, null, _instanceExtraInitializers);
838
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
839
+ enumerable: true,
840
+ configurable: true,
841
+ writable: true,
842
+ value: _metadata
843
+ });
844
+ }
845
+ static inject = [
846
+ "sessionController",
847
+ "workingDirectory",
848
+ "sessions",
849
+ "sessionPersistence"
850
+ ];
851
+ locationsCache = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
852
+ constructor(ctx) {
853
+ super(ctx, "workspaceReview");
854
+ }
855
+ async inspectSession(sessionId, signal) {
856
+ const sid = SessionId(sessionId);
857
+ const attached = this.ctx.sessions.get(sid);
858
+ if (attached !== void 0) return {
859
+ meta: attached.header,
860
+ events: attached.snapshotEvents()
861
+ };
862
+ const handle = await this.ctx.sessionPersistence.open(sid, "read", signal ? { signal } : void 0);
863
+ try {
864
+ const result = await handle.read(void 0, void 0, signal ? { signal } : void 0);
865
+ return {
866
+ meta: handle.header,
867
+ events: result.events
868
+ };
869
+ } finally {
870
+ await handle.close();
871
+ }
872
+ }
873
+ async sessionLocations(sessionId, signal) {
874
+ const cached = this.locationsCache.get(sessionId);
875
+ const locations = cached !== void 0 ? cached : await this.locations(sessionId, signal);
876
+ if (locations.kind === "unavailable") throw locations.error;
877
+ return locations;
878
+ }
879
+ assertSessionRepository(locations, repository) {
880
+ assert(locations.repositories.includes(repository), "Repository is not part of this session");
881
+ }
882
+ async directory(sessionId, signal, target) {
883
+ const locations = await this.sessionLocations(sessionId, signal);
884
+ this.assertSessionRepository(locations, target);
885
+ return target;
886
+ }
887
+ async repositoryFor(sessionId, signal, repository) {
888
+ const locations = await this.sessionLocations(sessionId, signal);
889
+ let cwd = repository.trim() === "" ? locations.cwd : resolve(locations.cwd, repository);
890
+ if ((await stat(cwd)).isFile()) cwd = dirname(cwd);
891
+ const root = await repositoryRoot(cwd, signal);
892
+ if (root === null) throw new Error(`No Git repository at ${cwd}`);
893
+ this.assertSessionRepository(locations, root);
894
+ return root;
895
+ }
896
+ async locations(sessionId, signal) {
897
+ const cached = this.locationsCache.get(sessionId);
898
+ if (cached !== void 0) return cached;
899
+ const inspection = await this.inspectSession(sessionId, signal);
900
+ assert(inspection.meta.cwd, "Review requires a Session workspace");
901
+ const changeIndex = inspection.events.findLastIndex((event) => event.type === "working-directory/change");
902
+ const change = inspection.events[changeIndex];
903
+ let cwd = change === void 0 || change.type !== "working-directory/change" ? inspection.meta.cwd : change.data.cwd;
904
+ try {
905
+ signal.throwIfAborted();
906
+ try {
907
+ await stat(cwd);
908
+ } catch (error) {
909
+ signal.throwIfAborted();
910
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
911
+ const result = await this.ctx.sessionController.resolveAgent(SessionId(sessionId));
912
+ if ("error" in result) throw result.error;
913
+ cwd = await this.ctx.workingDirectory.ensure(result.agent, signal);
914
+ } else throw error;
915
+ }
916
+ signal.throwIfAborted();
917
+ const repositories = [];
918
+ const root = await repositoryRoot(cwd, signal);
919
+ if (root !== null) repositories.push(root);
920
+ const calls = /* @__PURE__ */ new Set();
921
+ const files = /* @__PURE__ */ new Set();
922
+ const dirCache = /* @__PURE__ */ new Map();
923
+ if (root !== null) dirCache.set(root, root);
924
+ for (const event of inspection.events.slice(changeIndex + 1)) {
925
+ if (event.type === "tool/call" && (event.data.name === "write" || event.data.name === "edit")) calls.add(event.data.callId);
926
+ let meta;
927
+ if (event.type === "tool/ptc-dispatch") {
928
+ if (event.data.isError || event.data.name !== "write" && event.data.name !== "edit") continue;
929
+ meta = event.data.meta;
930
+ } else if (event.type === "tool/result" && !event.data.message.isError && calls.has(event.data.message.toolCallId)) meta = event.data.meta;
931
+ else continue;
932
+ const parsed = editedPathSchema.safeParse(meta);
933
+ if (!parsed.success || files.has(parsed.data.path)) continue;
934
+ files.add(parsed.data.path);
935
+ const directory = dirname(parsed.data.path);
936
+ let repository;
937
+ const cached = dirCache.get(directory);
938
+ if (cached !== void 0) repository = cached;
939
+ else {
940
+ let canonicalDir = directory;
941
+ try {
942
+ await stat(directory);
943
+ canonicalDir = await realpath(directory);
944
+ } catch (error) {
945
+ signal.throwIfAborted();
946
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
947
+ dirCache.set(directory, null);
948
+ continue;
949
+ }
950
+ throw error;
951
+ }
952
+ repository = await repositoryRoot(directory, signal);
953
+ dirCache.set(directory, repository);
954
+ if (canonicalDir !== directory) dirCache.set(canonicalDir, repository);
955
+ if (repository !== null) {
956
+ let current = canonicalDir;
957
+ while (current !== repository && current.startsWith(repository) && current !== dirname(current)) {
958
+ current = dirname(current);
959
+ dirCache.set(current, repository);
960
+ }
961
+ }
962
+ }
963
+ if (repository !== null && !repositories.includes(repository)) repositories.push(repository);
964
+ }
965
+ let result;
966
+ if (repositories.length > 0) result = {
967
+ kind: "git",
968
+ cwd,
969
+ repositories
970
+ };
971
+ else result = {
972
+ kind: "unavailable",
973
+ cwd,
974
+ error: /* @__PURE__ */ new Error("No Git repository found in the working directory or edited files")
975
+ };
976
+ this.locationsCache.set(sessionId, result);
977
+ return result;
978
+ } catch (error) {
979
+ signal.throwIfAborted();
980
+ const failure = {
981
+ kind: "unavailable",
982
+ cwd,
983
+ error
984
+ };
985
+ this.locationsCache.set(sessionId, failure);
986
+ return failure;
987
+ }
988
+ }
989
+ async catalog(sessionId, signal) {
990
+ this.locationsCache.delete(sessionId);
991
+ const locations = await this.locations(sessionId, signal);
992
+ if (locations.kind === "unavailable") return {
993
+ kind: "unavailable",
994
+ cwd: locations.cwd,
995
+ message: String(locations.error)
996
+ };
997
+ try {
998
+ const settled = await Promise.allSettled(locations.repositories.map((cwd) => readRepository(cwd, signal)));
999
+ const repositories = [];
1000
+ for (const result of settled) if (result.status === "fulfilled") repositories.push(result.value);
1001
+ if (repositories.length === 0) return {
1002
+ kind: "unavailable",
1003
+ cwd: locations.cwd,
1004
+ message: "No repositories could be read"
1005
+ };
1006
+ return {
1007
+ kind: "git",
1008
+ repository: repositories[0],
1009
+ repositories
1010
+ };
1011
+ } catch (error) {
1012
+ signal.throwIfAborted();
1013
+ return {
1014
+ kind: "unavailable",
1015
+ cwd: locations.cwd,
1016
+ message: String(error)
1017
+ };
1018
+ }
1019
+ }
1020
+ async resolve(sessionId, target, signal) {
1021
+ return resolveReviewScope(await this.repositoryFor(sessionId, signal, target.repository), target, signal);
1022
+ }
1023
+ async commits(sessionId, repository, branch, base, offset, signal) {
1024
+ return listCommits(await this.directory(sessionId, signal, repository), branch, base, offset, signal);
1025
+ }
1026
+ async view(sessionId, selection, signal) {
1027
+ switch (selection.kind) {
1028
+ case "branch": return {
1029
+ kind: "diff",
1030
+ view: await compare(await this.directory(sessionId, signal, selection.repository), selection.revision.kind === "all-commits" ? {
1031
+ kind: "branch",
1032
+ branch: selection.ref,
1033
+ base: selection.base
1034
+ } : {
1035
+ kind: "commit",
1036
+ branch: selection.ref,
1037
+ commit: selection.revision.commit.sha
1038
+ }, signal)
1039
+ };
1040
+ case "uncommitted": return {
1041
+ kind: "diff",
1042
+ view: await compare(await this.directory(sessionId, signal, selection.repository), { kind: selection.stage }, signal)
1043
+ };
1044
+ default: throw new Error("Unknown review scope");
1045
+ }
1046
+ }
1047
+ async file(sessionId, snapshot, path, signal) {
1048
+ return readFileContents(await this.directory(sessionId, signal, snapshot.repository), snapshot, path, signal);
1049
+ }
1050
+ };
1051
+ })();
1052
+ // src/index.ts
1053
+ const name = "dsh-client-git-diff";
1054
+ const inject = [
1055
+ "sessionController",
1056
+ "workingDirectory",
1057
+ "sessions",
1058
+ "sessionPersistence"
1059
+ ];
1060
+ function apply(ctx) {
1061
+ ctx.plugin(WorkspaceReviewService);
1062
+ ctx.plugin({
1063
+ inject: ["tools", "agents"],
1064
+ apply: (toolCtx) => {
1065
+ const pending = /* @__PURE__ */ new WeakMap();
1066
+ toolCtx.tools.register(createGitReviewTool({ onPresented: (exec, target) => {
1067
+ if (exec.agent === void 0) return;
1068
+ const boundary = toolCtx.agents.turnBoundaryOf(exec.agent.session);
1069
+ const turn = boundary.openTurnStartSeq !== null ? boundary.lastTurn : boundary.lastTurn || 1;
1070
+ pending.set(exec, {
1071
+ session: exec.agent.session,
1072
+ turn,
1073
+ target
1074
+ });
1075
+ } }));
1076
+ toolCtx.on("tools/result", (exec, result) => {
1077
+ const delivery = pending.get(exec);
1078
+ pending.delete(exec);
1079
+ if (delivery === void 0 || result.isError) return;
1080
+ const { session, turn, target } = delivery;
1081
+ const commandId = `git-review-${exec.callId}`;
1082
+ session.append("command/run", {
1083
+ commandId,
1084
+ name: "git-review",
1085
+ args: JSON.stringify({
1086
+ turn,
1087
+ callId: exec.callId,
1088
+ target
1089
+ }),
1090
+ source: { kind: "user" }
1091
+ });
1092
+ session.append("command/done", {
1093
+ commandId,
1094
+ kind: "success",
1095
+ text: `Git review presented: ${target.branch}`
1096
+ });
1097
+ });
1098
+ }
1099
+ });
1100
+ }
1101
+ export { WorkspaceReviewService, apply, createGitReviewTool, inject, name };