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

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