@agimon-ai/po-git 0.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2114 @@
1
+ import { _ as NETWORK_TIMEOUT_MS, a as GIT_WORKTREE_LIFECYCLE_EVENT, b as createWorktreeGit, c as isWorktreeLifecycleEvent, d as registryFile, f as readJson, g as invalidRequest, h as HubUnavailableError, i as GIT_SESSION_CHANGED_EVENT, l as credentialsFile, m as DoomGitExpectedError, n as createWorktreeRegistry, o as createWorktreeMessageInbox, p as writeJsonAtomic, r as validRefName, s as isSessionChangedEvent, t as createWorktreeOperations, u as doomGitRoot, v as READ_TIMEOUT_MS, x as runGit, y as REBASE_TIMEOUT_MS } from "../worktreeOperations-CaqwGsD_.mjs";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { composeServerProviderOverrides, defineServerPlugin, readPackageResource } from "@agimon-ai/po-core/serverFacet";
6
+ import { composeRootHooks, defineChannel, defineHook, defineResource, defineRoot, defineRoute, defineServerTool } from "@agimon-ai/po-core/extensionFile";
7
+ import { readDoomSessionDelivery } from "@agimon-ai/po-session";
8
+ import { Type } from "typebox";
9
+ //#region src/schemas/runWorktreeTool.ts
10
+ /**
11
+ * The tool's action vocabulary.
12
+ *
13
+ * One tool with an action field rather than six tools, matching `subagent`:
14
+ * the actions share a subject and are meaningless apart from it, and six
15
+ * separate tools would spend six description budgets teaching the same nouns.
16
+ */
17
+ const WORKTREE_ACTIONS = {
18
+ spawn_worktree: "spawn_worktree",
19
+ close_worktree: "close_worktree",
20
+ list: "list",
21
+ status: "status",
22
+ merge: "merge",
23
+ prune: "prune",
24
+ send: "send",
25
+ messages: "messages"
26
+ };
27
+ /**
28
+ * Which fields each action accepts.
29
+ *
30
+ * Rejecting an unknown field is what stops a plausible-looking call from doing
31
+ * something other than what it reads like: `close_worktree` with `branch`
32
+ * instead of `id` would otherwise close whatever the default resolved to.
33
+ */
34
+ const WORKTREE_ACTION_FIELDS = {
35
+ spawn_worktree: [
36
+ "action",
37
+ "branch",
38
+ "baseRef",
39
+ "task",
40
+ "name"
41
+ ],
42
+ close_worktree: [
43
+ "action",
44
+ "id",
45
+ "force"
46
+ ],
47
+ list: ["action"],
48
+ status: ["action", "id"],
49
+ merge: [
50
+ "action",
51
+ "id",
52
+ "message"
53
+ ],
54
+ prune: ["action", "dryRun"],
55
+ send: [
56
+ "action",
57
+ "id",
58
+ "message"
59
+ ],
60
+ messages: ["action", "id"]
61
+ };
62
+ const SpawnParams = Type.Object({
63
+ action: Type.Literal(WORKTREE_ACTIONS.spawn_worktree),
64
+ branch: Type.String({ minLength: 1 }),
65
+ baseRef: Type.Optional(Type.String({ minLength: 1 })),
66
+ task: Type.Optional(Type.String({ minLength: 1 })),
67
+ name: Type.Optional(Type.String({ minLength: 1 }))
68
+ }, { additionalProperties: false });
69
+ const CloseParams = Type.Object({
70
+ action: Type.Literal(WORKTREE_ACTIONS.close_worktree),
71
+ id: Type.String({ minLength: 1 }),
72
+ force: Type.Optional(Type.Boolean())
73
+ }, { additionalProperties: false });
74
+ const ListParams = Type.Object({ action: Type.Literal(WORKTREE_ACTIONS.list) }, { additionalProperties: false });
75
+ const StatusParams = Type.Object({
76
+ action: Type.Literal(WORKTREE_ACTIONS.status),
77
+ id: Type.String({ minLength: 1 })
78
+ }, { additionalProperties: false });
79
+ const MergeParams = Type.Object({
80
+ action: Type.Literal(WORKTREE_ACTIONS.merge),
81
+ id: Type.String({ minLength: 1 }),
82
+ message: Type.Optional(Type.String({ minLength: 1 }))
83
+ }, { additionalProperties: false });
84
+ const PruneParams = Type.Object({
85
+ action: Type.Literal(WORKTREE_ACTIONS.prune),
86
+ dryRun: Type.Optional(Type.Boolean())
87
+ }, { additionalProperties: false });
88
+ const SendParams = Type.Object({
89
+ action: Type.Literal(WORKTREE_ACTIONS.send),
90
+ id: Type.String({ minLength: 1 }),
91
+ message: Type.String({ minLength: 1 })
92
+ }, { additionalProperties: false });
93
+ const MessagesParams = Type.Object({
94
+ action: Type.Literal(WORKTREE_ACTIONS.messages),
95
+ id: Type.String({ minLength: 1 })
96
+ }, { additionalProperties: false });
97
+ Type.Union([
98
+ SpawnParams,
99
+ CloseParams,
100
+ ListParams,
101
+ StatusParams,
102
+ MergeParams,
103
+ PruneParams,
104
+ SendParams,
105
+ MessagesParams
106
+ ]);
107
+ /** The actions that accept `field`, so the declared docs cannot drift from the validator. */
108
+ function acceptingActions(field) {
109
+ return Object.values(WORKTREE_ACTIONS).filter((action) => WORKTREE_ACTION_FIELDS[action].includes(field)).join(", ");
110
+ }
111
+ /**
112
+ * The schema declared to the model.
113
+ *
114
+ * A flat object rather than `RunWorktreeParams` itself. A top-level union is
115
+ * `{anyOf:[...]}` with no `properties`, and Pi's Anthropic Messages adapter
116
+ * rebuilds tool input as `{type:'object', properties: schema.properties ?? {},
117
+ * required: schema.required ?? []}`, so the union arrived at the model as an
118
+ * empty object while the host went on validating calls against it. Nothing here
119
+ * relaxes what is accepted: `validateParams` still rejects an unknown action, a
120
+ * field the action does not take, and a missing required one.
121
+ */
122
+ const RunWorktreeToolSchema = Type.Object({
123
+ action: Type.String({
124
+ enum: Object.values(WORKTREE_ACTIONS),
125
+ description: "The operation to run. Every other field is accepted only by the actions its description names."
126
+ }),
127
+ branch: Type.Optional(Type.String({
128
+ minLength: 1,
129
+ description: `New branch to create. Actions: ${acceptingActions("branch")}.`
130
+ })),
131
+ baseRef: Type.Optional(Type.String({
132
+ minLength: 1,
133
+ description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions("baseRef")}.`
134
+ })),
135
+ task: Type.Optional(Type.String({
136
+ minLength: 1,
137
+ description: `First message for the new session. Actions: ${acceptingActions("task")}.`
138
+ })),
139
+ name: Type.Optional(Type.String({
140
+ minLength: 1,
141
+ description: `Rail label for the worktree. Actions: ${acceptingActions("name")}.`
142
+ })),
143
+ id: Type.Optional(Type.String({
144
+ minLength: 1,
145
+ description: `Worktree id. Actions: ${acceptingActions("id")}.`
146
+ })),
147
+ force: Type.Optional(Type.Boolean({ description: `Close even when the tree is dirty. Actions: ${acceptingActions("force")}.` })),
148
+ message: Type.Optional(Type.String({
149
+ minLength: 1,
150
+ description: `Merge commit message, or the text to send. Actions: ${acceptingActions("message")}.`
151
+ })),
152
+ dryRun: Type.Optional(Type.Boolean({ description: `Report the plan without destroying anything. Actions: ${acceptingActions("dryRun")}.` }))
153
+ }, { additionalProperties: false });
154
+ //#endregion
155
+ //#region src/services/runWorktree/index.ts
156
+ const RUN_WORKTREE_TOOL_NAME = "run_worktree";
157
+ const IMPLEMENTED_ACTIONS = new Set(Object.values(WORKTREE_ACTIONS));
158
+ const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its own Po session nested under this one.
159
+
160
+ Actions:
161
+ - spawn_worktree: create a worktree on a new branch and start a session in it. Requires 'branch'. Optional 'baseRef' (defaults to the current branch's remote-tracking ref, then the remote default branch), 'name' for the rail, 'task' as the first message.
162
+ - close_worktree: stop a worktree's session and delete its checkout. Requires 'id'. Refuses a dirty tree unless 'force' is true.
163
+ - list: every worktree for this repository, with status and relationship to the calling session.
164
+ - status: one worktree, its relationship to the calling session, and its uncommitted files. Requires 'id'.
165
+ - merge: merge a worktree's branch into this checkout. Requires 'id'. Refuses when this checkout is dirty.
166
+ - prune: remove orphaned worktrees. Pass 'dryRun' to see the plan without destroying anything.
167
+ - send: send a message to the other side of a worktree. Requires 'id' and 'message'.
168
+ - messages: read messages waiting for you from a worktree. Requires 'id'.
169
+
170
+ For a nested worktree session, use the record labelled 'child' in list to report to your parent. Use records labelled 'parent' to contact your own children. Other records are not communication edges.
171
+ Worktrees live outside the repository, under ~/.po/git/worktrees.`;
172
+ /** Rejects calls that do not match one documented action shape. */
173
+ function validateParams(input) {
174
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw invalidRequest("run_worktree parameters must be an object.", "Call it with one documented action shape.");
175
+ const record = input;
176
+ const action = record.action;
177
+ if (typeof action !== "string" || !IMPLEMENTED_ACTIONS.has(action)) throw invalidRequest(`Unknown action ${typeof action === "string" ? `'${action}'` : "value"}.`, `Use one of: ${[...IMPLEMENTED_ACTIONS].join(", ")}.`);
178
+ const allowed = WORKTREE_ACTION_FIELDS[action];
179
+ const unexpected = Object.keys(record).filter((key) => !allowed.includes(key));
180
+ if (unexpected.length > 0) throw invalidRequest(`action='${action}' does not accept: ${unexpected.join(", ")}.`, `Fields for '${action}': ${allowed.join(", ")}.`);
181
+ for (const field of ["branch", "id"]) if (allowed.includes(field) && field in record) {
182
+ const value = record[field];
183
+ if (typeof value !== "string" || value.trim() === "") throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
184
+ }
185
+ for (const field of [
186
+ "baseRef",
187
+ "name",
188
+ "task",
189
+ "message"
190
+ ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
191
+ for (const field of ["force", "dryRun"]) if (field in record && typeof record[field] !== "boolean") throw invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);
192
+ if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
193
+ if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
194
+ if ((action === WORKTREE_ACTIONS.close_worktree || action === WORKTREE_ACTIONS.status || action === WORKTREE_ACTIONS.merge || action === WORKTREE_ACTIONS.send || action === WORKTREE_ACTIONS.messages) && typeof record.id !== "string") throw invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
195
+ return record;
196
+ }
197
+ function describe(record, sessionId) {
198
+ const relationship = record.parentSessionId === sessionId ? "parent" : record.sessionId === sessionId ? "child" : "other session";
199
+ return `${record.id} ${record.branch} ${record.status} (${relationship}) ${record.path}`;
200
+ }
201
+ function text(...lines) {
202
+ return [{
203
+ type: "text",
204
+ text: lines.join("\n")
205
+ }];
206
+ }
207
+ async function executeRunWorktreeTool(params, operations, context, options = {}) {
208
+ switch (params.action) {
209
+ case WORKTREE_ACTIONS.spawn_worktree: {
210
+ const record = await operations.spawn(context, {
211
+ branch: params.branch,
212
+ ...params.baseRef === void 0 ? {} : { baseRef: params.baseRef },
213
+ ...params.name === void 0 ? {} : { name: params.name },
214
+ ...params.task === void 0 ? {} : { task: params.task }
215
+ }, options);
216
+ return {
217
+ content: text(`Worktree ${record.id} created on ${record.branch} from ${record.baseRef}.`, `Path: ${record.path}`, params.task === void 0 ? `Session ${record.sessionId} is starting; it appears nested under this one in the rail.` : `Session ${record.sessionId} is starting with its task; it appears nested under this one in the rail.`),
218
+ details: {
219
+ action: params.action,
220
+ records: [record]
221
+ }
222
+ };
223
+ }
224
+ case WORKTREE_ACTIONS.close_worktree: {
225
+ const record = await operations.close(context, params.id, params.force ?? false);
226
+ return {
227
+ content: text(`Worktree ${record.id} (${record.branch}) closed and removed.`),
228
+ details: {
229
+ action: params.action,
230
+ records: [record]
231
+ }
232
+ };
233
+ }
234
+ case WORKTREE_ACTIONS.list: {
235
+ const records = await operations.list(context);
236
+ return {
237
+ content: records.length === 0 ? text("No worktrees for this repository.") : text(`${String(records.length)} worktree(s):`, ...records.map((record) => describe(record, context.sessionId))),
238
+ details: {
239
+ action: params.action,
240
+ records
241
+ }
242
+ };
243
+ }
244
+ case WORKTREE_ACTIONS.status: {
245
+ const { record, dirtyFiles } = await operations.status(context, params.id);
246
+ return {
247
+ content: text(describe(record, context.sessionId), `Session: ${record.sessionId}`, dirtyFiles.length === 0 ? "Clean." : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(", ")}`),
248
+ details: {
249
+ action: params.action,
250
+ records: [record]
251
+ }
252
+ };
253
+ }
254
+ case WORKTREE_ACTIONS.merge: {
255
+ const record = await operations.merge(context, params.id, ...params.message === void 0 ? [] : [params.message]);
256
+ return {
257
+ content: text(`Merged ${record.branch} into this checkout.`),
258
+ details: {
259
+ action: params.action,
260
+ records: [record]
261
+ }
262
+ };
263
+ }
264
+ case WORKTREE_ACTIONS.send:
265
+ await operations.send(context, params.id, params.message);
266
+ return {
267
+ content: text(`Message sent to worktree ${params.id}.`),
268
+ details: { action: params.action }
269
+ };
270
+ case WORKTREE_ACTIONS.messages: {
271
+ const waiting = await operations.messages(context, params.id);
272
+ return {
273
+ content: waiting.length === 0 ? text("No messages.") : text(`${String(waiting.length)} message(s):`, ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`)),
274
+ details: { action: params.action }
275
+ };
276
+ }
277
+ case WORKTREE_ACTIONS.prune: {
278
+ const dryRun = params.dryRun ?? false;
279
+ const plan = await operations.prune(context, dryRun);
280
+ return {
281
+ content: text(...[
282
+ dryRun ? "Prune plan (nothing was changed):" : "Pruned:",
283
+ `Remove: ${plan.remove.length === 0 ? "none" : plan.remove.map((record) => record.id).join(", ")}`,
284
+ `Forget: ${plan.forget.length === 0 ? "none" : plan.forget.map((record) => record.id).join(", ")}`,
285
+ `Kept, uncommitted work: ${plan.keptDirty.length === 0 ? "none" : plan.keptDirty.map((record) => record.id).join(", ")}`,
286
+ `Untracked directories, left alone: ${plan.untracked.length === 0 ? "none" : plan.untracked.join(", ")}`,
287
+ ...plan.keptBranches.length === 0 ? [] : [`Branches kept, they hold commits: ${plan.keptBranches.join(", ")}`]
288
+ ]),
289
+ details: { action: params.action }
290
+ };
291
+ }
292
+ }
293
+ }
294
+ //#endregion
295
+ //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
296
+ function progressResult(action, label) {
297
+ return {
298
+ content: [{
299
+ type: "text",
300
+ text: label
301
+ }],
302
+ details: { action }
303
+ };
304
+ }
305
+ function createGitSession({ context, host: serverHost }) {
306
+ if (serverHost.context.directEvents === void 0) throw new Error("Git headless facet requires the session direct event bus.");
307
+ if (serverHost.context.sessionId === void 0) throw new Error("Git headless facet requires a session identity.");
308
+ const sessionId = serverHost.context.sessionId;
309
+ const directEvents = serverHost.context.directEvents;
310
+ const messageInbox = createWorktreeMessageInbox(directEvents, sessionId);
311
+ const operations = createWorktreeOperations({
312
+ git: createWorktreeGit(),
313
+ sessionService: serverHost.context.sessionService,
314
+ messageInbox,
315
+ sessionDelivery: () => readDoomSessionDelivery(context)
316
+ });
317
+ const resources = [{
318
+ when: {
319
+ state: { "minor-mode": "help" },
320
+ attribution: {
321
+ kind: "minor",
322
+ mode: "help"
323
+ }
324
+ },
325
+ name: "po-git",
326
+ kind: "context",
327
+ read: () => readPackageResource(import.meta.url, "llms.txt")
328
+ }, {
329
+ name: "po-use-git",
330
+ kind: "skill",
331
+ read: () => readPackageResource(import.meta.url, "src/prompts/po-use-git/SKILL.md")
332
+ }];
333
+ const tool = {
334
+ name: RUN_WORKTREE_TOOL_NAME,
335
+ label: "Worktree",
336
+ description: RUN_WORKTREE_DESCRIPTION,
337
+ parameters: RunWorktreeToolSchema,
338
+ promptSnippet: "Create and manage Git worktree sessions",
339
+ executionMode: "serial",
340
+ async execute(_toolCallId, parameters, signal, onUpdate, execution) {
341
+ const params = validateParams(parameters);
342
+ return executeRunWorktreeTool(params, operations, execution, {
343
+ ...signal === void 0 ? {} : { signal },
344
+ onProgress: (label) => onUpdate?.(progressResult(params.action, label))
345
+ });
346
+ }
347
+ };
348
+ const changed = (_event, execution) => {
349
+ directEvents.publish(GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
350
+ };
351
+ return {
352
+ value: {
353
+ resources,
354
+ tool,
355
+ hooks: [{
356
+ event: "tool_execution_end",
357
+ handle: changed
358
+ }, {
359
+ event: "agent_settled",
360
+ handle: changed
361
+ }]
362
+ },
363
+ onDispose: () => messageInbox.close()
364
+ };
365
+ }
366
+ const root = defineRoot(createGitSession);
367
+ //#endregion
368
+ //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
369
+ var root_server_default = defineRoot(root);
370
+ //#endregion
371
+ //#region src/services/branchDiff/index.ts
372
+ /**
373
+ * What a session's checkout changed against its base, the way a pull request
374
+ * shows it: every commit since the branch left its base, plus staged, unstaged
375
+ * and untracked work.
376
+ *
377
+ * DESIGN PATTERNS:
378
+ * - git computes every diff. The counts come from `--numstat` and the hunks
379
+ * from the same unified diff, so the two always agree.
380
+ * - The base is the worktree's own recorded base when there is one, then the
381
+ * remote's default branch, then the branch's upstream, and with none of those
382
+ * only uncommitted work counts. It is always named in the UI.
383
+ * - Untracked files are read only when they are small regular files; a symlink
384
+ * shows its link text and is never followed.
385
+ *
386
+ * AVOID:
387
+ * - Passing a browser path to git without checking it against the change set.
388
+ */
389
+ /** git's well-known empty tree, the base of a repository with no commits. */
390
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
391
+ const MAX_LISTED_FILES = 500;
392
+ const MAX_UNTRACKED_COUNTED = 200;
393
+ const MAX_FILE_BYTES = 1048576;
394
+ const MAX_ROWS = 5e3;
395
+ const BINARY_PROBE_BYTES = 8192;
396
+ const SHORT_SHA = 7;
397
+ const DEFAULT_BRANCHES = ["main", "master"];
398
+ async function read(cwd, args) {
399
+ const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
400
+ return result.code === 0 ? result.stdout : void 0;
401
+ }
402
+ async function readLine$1(cwd, args) {
403
+ const out = (await read(cwd, args))?.trim();
404
+ return out === void 0 || out === "" ? void 0 : out;
405
+ }
406
+ async function commitExists(cwd, ref) {
407
+ return await readLine$1(cwd, [
408
+ "rev-parse",
409
+ "--verify",
410
+ "--quiet",
411
+ `${ref}^{commit}`
412
+ ]) !== void 0;
413
+ }
414
+ /** A local branch's upstream, so the review measures against what fetch keeps current. */
415
+ async function upstreamOf(cwd, ref) {
416
+ return readLine$1(cwd, [
417
+ "rev-parse",
418
+ "--abbrev-ref",
419
+ "--symbolic-full-name",
420
+ `${ref}@{upstream}`
421
+ ]);
422
+ }
423
+ /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
424
+ async function resolveBaseRef(cwd, branch, recordedBaseRef) {
425
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
426
+ "rev-parse",
427
+ "--verify",
428
+ "--quiet",
429
+ `refs/heads/${recordedBaseRef}`
430
+ ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
431
+ const originHead = await readLine$1(cwd, [
432
+ "symbolic-ref",
433
+ "--quiet",
434
+ "--short",
435
+ "refs/remotes/origin/HEAD"
436
+ ]);
437
+ if (originHead !== void 0) return originHead;
438
+ for (const name of DEFAULT_BRANCHES) if (await commitExists(cwd, `origin/${name}`)) return `origin/${name}`;
439
+ return branch === void 0 ? void 0 : upstreamOf(cwd, branch);
440
+ }
441
+ async function resolveBase(cwd, branch, recordedBaseRef) {
442
+ const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
443
+ const head = await commitExists(cwd, "HEAD");
444
+ if (ref !== void 0 && head) {
445
+ const mergeBase = await readLine$1(cwd, [
446
+ "merge-base",
447
+ ref,
448
+ "HEAD"
449
+ ]);
450
+ if (mergeBase !== void 0) return {
451
+ ref,
452
+ from: mergeBase,
453
+ mergeBase: mergeBase.slice(0, SHORT_SHA)
454
+ };
455
+ }
456
+ return { from: head ? "HEAD" : EMPTY_TREE };
457
+ }
458
+ /** NUL-separated fields from a `-z` listing, without the trailing empty one. */
459
+ function zFields(out) {
460
+ if (out === void 0 || out === "") return [];
461
+ const fields = out.split("\0");
462
+ if (fields.at(-1) === "") fields.pop();
463
+ return fields;
464
+ }
465
+ const NAME_STATUS = {
466
+ A: "added",
467
+ D: "deleted",
468
+ M: "modified",
469
+ T: "modified"
470
+ };
471
+ /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
472
+ function untrackedLines(root, relPath) {
473
+ const absolute = path.join(root, relPath);
474
+ let stat;
475
+ try {
476
+ stat = fs.lstatSync(absolute);
477
+ } catch {
478
+ return;
479
+ }
480
+ if (stat.isSymbolicLink()) return {
481
+ lines: 1,
482
+ binary: false
483
+ };
484
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
485
+ const content = fs.readFileSync(absolute);
486
+ if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
487
+ lines: 0,
488
+ binary: true
489
+ };
490
+ if (content.length === 0) return {
491
+ lines: 0,
492
+ binary: false
493
+ };
494
+ const text = content.toString("utf8");
495
+ const newlines = text.split("\n").length - 1;
496
+ return {
497
+ lines: text.endsWith("\n") ? newlines : newlines + 1,
498
+ binary: false
499
+ };
500
+ }
501
+ /** The hunks of a unified diff, numbering each row by the file it lives in. */
502
+ function parseUnifiedDiff(diff) {
503
+ const hunks = [];
504
+ let current;
505
+ let oldLine = 0;
506
+ let newLine = 0;
507
+ let rows = 0;
508
+ let binary = false;
509
+ for (const line of diff.split("\n")) {
510
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(line);
511
+ if (header !== null) {
512
+ oldLine = Number(header[1]);
513
+ newLine = Number(header[2]);
514
+ current = {
515
+ start: newLine,
516
+ rows: []
517
+ };
518
+ hunks.push(current);
519
+ continue;
520
+ }
521
+ if (current === void 0) {
522
+ if (line.startsWith("Binary files ") || line === "GIT binary patch") binary = true;
523
+ continue;
524
+ }
525
+ const marker = line[0];
526
+ let row;
527
+ if (marker === " ") row = {
528
+ marker: " ",
529
+ line: newLine,
530
+ content: line.slice(1)
531
+ };
532
+ else if (marker === "-") row = {
533
+ marker: "-",
534
+ line: oldLine,
535
+ content: line.slice(1)
536
+ };
537
+ else if (marker === "+") row = {
538
+ marker: "+",
539
+ line: newLine,
540
+ content: line.slice(1)
541
+ };
542
+ if (row === void 0) continue;
543
+ if (marker !== "+") oldLine += 1;
544
+ if (marker !== "-") newLine += 1;
545
+ current.rows.push(row);
546
+ rows += 1;
547
+ }
548
+ return {
549
+ hunks,
550
+ binary,
551
+ rows
552
+ };
553
+ }
554
+ function createBranchDiff() {
555
+ return {
556
+ async review(cwd, options = {}) {
557
+ const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
558
+ if (root === void 0) return void 0;
559
+ const branch = await readLine$1(root, [
560
+ "symbolic-ref",
561
+ "--quiet",
562
+ "--short",
563
+ "HEAD"
564
+ ]);
565
+ const base = await resolveBase(root, branch, options.recordedBaseRef);
566
+ const numstat = zFields(await read(root, [
567
+ "diff",
568
+ "--numstat",
569
+ "-z",
570
+ "--no-renames",
571
+ base.from
572
+ ]));
573
+ const nameStatus = zFields(await read(root, [
574
+ "diff",
575
+ "--name-status",
576
+ "-z",
577
+ "--no-renames",
578
+ base.from
579
+ ]));
580
+ const unmerged = new Set(zFields(await read(root, [
581
+ "diff",
582
+ "--name-only",
583
+ "--diff-filter=U",
584
+ "-z"
585
+ ])));
586
+ const statusOf = /* @__PURE__ */ new Map();
587
+ for (let index = 0; index + 1 < nameStatus.length; index += 2) statusOf.set(nameStatus[index + 1] ?? "", NAME_STATUS[(nameStatus[index] ?? "").charAt(0)] ?? "modified");
588
+ const entries = [];
589
+ for (const field of numstat) {
590
+ const [added = "", removed = "", ...rest] = field.split(" ");
591
+ const filePath = rest.join(" ");
592
+ if (filePath === "") continue;
593
+ const binary = added === "-" && removed === "-";
594
+ entries.push({
595
+ path: filePath,
596
+ status: unmerged.has(filePath) ? "conflicted" : statusOf.get(filePath) ?? "modified",
597
+ added: binary ? 0 : Number(added),
598
+ removed: binary ? 0 : Number(removed),
599
+ ...binary ? { binary: true } : {}
600
+ });
601
+ }
602
+ const untracked = zFields(await read(root, [
603
+ "ls-files",
604
+ "--others",
605
+ "--exclude-standard",
606
+ "-z"
607
+ ]));
608
+ untracked.forEach((relPath, index) => {
609
+ const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
610
+ entries.push({
611
+ path: relPath,
612
+ status: "untracked",
613
+ added: counted?.lines ?? 0,
614
+ removed: 0,
615
+ ...counted?.binary ? { binary: true } : {}
616
+ });
617
+ });
618
+ entries.sort((left, right) => left.path.localeCompare(right.path));
619
+ const conflicts = [...unmerged];
620
+ const rebasing = [await readLine$1(root, [
621
+ "rev-parse",
622
+ "--git-path",
623
+ "rebase-merge"
624
+ ]), await readLine$1(root, [
625
+ "rev-parse",
626
+ "--git-path",
627
+ "rebase-apply"
628
+ ])].some((gitPath) => gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath)));
629
+ const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
630
+ let upstream;
631
+ if (upstreamRef !== void 0) {
632
+ const [behind, ahead] = (await readLine$1(root, [
633
+ "rev-list",
634
+ "--left-right",
635
+ "--count",
636
+ `${upstreamRef}...HEAD`
637
+ ]) ?? "").split(/\s+/u).map(Number);
638
+ if (Number.isInteger(ahead) && Number.isInteger(behind)) upstream = {
639
+ ref: upstreamRef,
640
+ ahead,
641
+ behind
642
+ };
643
+ }
644
+ const truncated = entries.length > MAX_LISTED_FILES || untracked.length > MAX_UNTRACKED_COUNTED;
645
+ return {
646
+ root,
647
+ base,
648
+ changes: {
649
+ added: entries.reduce((sum, entry) => sum + entry.added, 0),
650
+ removed: entries.reduce((sum, entry) => sum + entry.removed, 0),
651
+ files: entries.length,
652
+ ...branch === void 0 ? {} : { branch },
653
+ ...base.ref === void 0 ? {} : { base: base.ref },
654
+ ...truncated ? { truncated: true } : {},
655
+ ...upstream === void 0 ? {} : { upstream },
656
+ ...rebasing ? { rebase: { conflicts } } : {}
657
+ },
658
+ summary: {
659
+ repository: true,
660
+ files: entries.slice(0, MAX_LISTED_FILES),
661
+ ...branch === void 0 ? {} : { branch },
662
+ ...base.ref === void 0 ? {} : { base: base.ref },
663
+ ...base.mergeBase === void 0 ? {} : { mergeBase: base.mergeBase },
664
+ ...truncated ? { truncated: true } : {}
665
+ }
666
+ };
667
+ },
668
+ async fileDiff(review, filePath) {
669
+ const entry = review.summary.files.find((file) => file.path === filePath);
670
+ if (entry === void 0) throw new Error("That path is not in this review.");
671
+ if (entry.status === "untracked") {
672
+ const absolute = path.join(review.root, entry.path);
673
+ const stat = fs.lstatSync(absolute);
674
+ if (stat.isSymbolicLink()) return {
675
+ path: entry.path,
676
+ hunks: [{
677
+ start: 1,
678
+ rows: [{
679
+ marker: "+",
680
+ line: 1,
681
+ content: fs.readlinkSync(absolute)
682
+ }]
683
+ }]
684
+ };
685
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return {
686
+ path: entry.path,
687
+ hunks: [],
688
+ tooLarge: true
689
+ };
690
+ const content = fs.readFileSync(absolute);
691
+ if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
692
+ path: entry.path,
693
+ hunks: [],
694
+ binary: true
695
+ };
696
+ const lines = content.toString("utf8").split("\n");
697
+ if (lines.at(-1) === "") lines.pop();
698
+ if (lines.length > MAX_ROWS) return {
699
+ path: entry.path,
700
+ hunks: [],
701
+ tooLarge: true
702
+ };
703
+ return {
704
+ path: entry.path,
705
+ hunks: lines.length === 0 ? [] : [{
706
+ start: 1,
707
+ rows: lines.map((content, index) => ({
708
+ marker: "+",
709
+ line: index + 1,
710
+ content
711
+ }))
712
+ }]
713
+ };
714
+ }
715
+ const result = await runGit(review.root, [
716
+ "diff",
717
+ "-U3",
718
+ "--no-color",
719
+ "--no-ext-diff",
720
+ "--no-textconv",
721
+ "--no-renames",
722
+ review.base.from,
723
+ "--",
724
+ `:(top,literal)${entry.path}`
725
+ ], {
726
+ timeout: READ_TIMEOUT_MS,
727
+ maxBuffer: MAX_FILE_BYTES
728
+ });
729
+ if (result.overflow) return {
730
+ path: entry.path,
731
+ hunks: [],
732
+ tooLarge: true
733
+ };
734
+ if (result.code !== 0) throw new Error(`git diff failed (exit ${String(result.code)}).`);
735
+ const parsed = parseUnifiedDiff(result.stdout);
736
+ if (parsed.binary || entry.binary === true) return {
737
+ path: entry.path,
738
+ hunks: [],
739
+ binary: true
740
+ };
741
+ if (parsed.rows > MAX_ROWS) return {
742
+ path: entry.path,
743
+ hunks: [],
744
+ tooLarge: true
745
+ };
746
+ return {
747
+ path: entry.path,
748
+ hunks: parsed.hunks
749
+ };
750
+ }
751
+ };
752
+ }
753
+ //#endregion
754
+ //#region src/services/gitAuth/index.ts
755
+ /**
756
+ * Per-workspace remote auth for po-git's own fetch, pull, push and rebase.
757
+ *
758
+ * DESIGN PATTERNS:
759
+ * - One file outside every repository, folder 0700 and file 0600, repaired on
760
+ * read if something loosened it. The token never leaves this module except
761
+ * into the environment of one git child process.
762
+ * - Config reaches git through GIT_CONFIG_COUNT environment entries, never
763
+ * argv, so nothing secret shows in `ps`. The first entry empties the
764
+ * credential helper list, which is what keeps macOS's osxkeychain helper from
765
+ * storing the token after a successful push.
766
+ * - The token is offered only to the host it was entered for. A repository
767
+ * whose remote points anywhere else gets this machine's own credentials.
768
+ *
769
+ * AVOID:
770
+ * - Touching process.env. The hub runs every session; anything set there
771
+ * would reach the agent's shell, which the user ruled out.
772
+ */
773
+ const OWNER_ONLY_DIRECTORY = 448;
774
+ const OWNER_ONLY_FILE = 384;
775
+ const LOOSE_BITS = 63;
776
+ const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
777
+ const MAX_USERNAME = 256;
778
+ const MAX_TOKEN = 4096;
779
+ const SETTINGS_HINT = "Open settings, then repository, then git remote.";
780
+ /** Environment that would make git log or skip what this module relies on. */
781
+ const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
782
+ const STRIPPED_PREFIXES = ["GIT_TRACE"];
783
+ /** Environment that could redirect or override credentials when the workspace's own are in play. */
784
+ const STRIPPED_CREDENTIALED = [
785
+ "GIT_CONFIG_PARAMETERS",
786
+ "GIT_CONFIG_COUNT",
787
+ "GIT_SSL_NO_VERIFY",
788
+ "SSH_ASKPASS",
789
+ "GIT_SSH",
790
+ "GIT_SSH_COMMAND"
791
+ ];
792
+ const CONFIG_ENTRY = /^GIT_CONFIG_(KEY|VALUE)_\d+$/u;
793
+ /** The inline helper: answers `get` from this child's environment, and ignores `store` and `erase`. */
794
+ const ENV_CREDENTIAL_HELPER = "!f(){ test \"$1\" = get && printf \"username=%s\\npassword=%s\\n\" \"$PO_GIT_USERNAME\" \"$PO_GIT_TOKEN\"; }; f";
795
+ /** Whether a value holds an ASCII control character; a newline in a credential field could add a line to git's credential protocol. */
796
+ function hasControl(value) {
797
+ for (let index = 0; index < value.length; index += 1) {
798
+ const code = value.charCodeAt(index);
799
+ if (code < 32 || code === 127) return true;
800
+ }
801
+ return false;
802
+ }
803
+ function isRecord(value) {
804
+ return typeof value === "object" && value !== null && !Array.isArray(value);
805
+ }
806
+ /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
807
+ function workspaceKey(workspaceRoot) {
808
+ try {
809
+ return fs.realpathSync(workspaceRoot);
810
+ } catch {
811
+ return path.resolve(workspaceRoot);
812
+ }
813
+ }
814
+ function expandHome(keyPath, homeDir) {
815
+ return keyPath.startsWith("~/") ? path.join(homeDir, keyPath.slice(2)) : keyPath;
816
+ }
817
+ function parseConfig(value) {
818
+ if (!isRecord(value)) return void 0;
819
+ if (value.method === "none") return { method: "none" };
820
+ if (value.method === "ssh") {
821
+ if (value.keyPath === void 0) return { method: "ssh" };
822
+ return typeof value.keyPath === "string" && value.keyPath !== "" ? {
823
+ method: "ssh",
824
+ keyPath: value.keyPath
825
+ } : void 0;
826
+ }
827
+ if (value.method === "https" && typeof value.host === "string" && typeof value.username === "string" && typeof value.token === "string" && value.token !== "") return {
828
+ method: "https",
829
+ host: value.host,
830
+ username: value.username,
831
+ token: value.token
832
+ };
833
+ }
834
+ /** What the browser may see. The token becomes a yes or no. */
835
+ function publicView(config) {
836
+ if (config.method === "ssh") return config.keyPath === void 0 ? {
837
+ method: "ssh",
838
+ ssh: {}
839
+ } : {
840
+ method: "ssh",
841
+ ssh: { keyPath: config.keyPath }
842
+ };
843
+ if (config.method === "https") return {
844
+ method: "https",
845
+ https: {
846
+ host: config.host,
847
+ username: config.username,
848
+ hasToken: config.token !== ""
849
+ }
850
+ };
851
+ return { method: "none" };
852
+ }
853
+ /**
854
+ * A browser save request, checked field by field. An absent HTTPS token keeps
855
+ * the saved one, and only for the same host: a token never follows a host it
856
+ * was not entered for.
857
+ */
858
+ function parseGitAuthSave(request, current, homeDir) {
859
+ if (!isRecord(request)) throw invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
860
+ if (request.method === "none") return { method: "none" };
861
+ if (request.method === "ssh") {
862
+ if (request.keyPath === void 0 || request.keyPath === "") return { method: "ssh" };
863
+ if (typeof request.keyPath !== "string" || hasControl(request.keyPath)) throw invalidRequest("The key path is not a plain path.", "Give the key as an absolute path or one under ~/.");
864
+ const keyPath = request.keyPath.trim();
865
+ if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
866
+ let isFile = false;
867
+ try {
868
+ isFile = fs.statSync(expandHome(keyPath, homeDir)).isFile();
869
+ } catch {
870
+ isFile = false;
871
+ }
872
+ if (!isFile) throw invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
873
+ return {
874
+ method: "ssh",
875
+ keyPath
876
+ };
877
+ }
878
+ if (request.method === "https") {
879
+ const host = typeof request.host === "string" ? request.host.trim().toLowerCase() : "";
880
+ if (!HOST_PATTERN.test(host)) throw invalidRequest("The host is not a host name.", "Use a host like github.com, with an optional :port.");
881
+ const username = typeof request.username === "string" ? request.username.trim() : "";
882
+ if (username === "" || username.length > MAX_USERNAME || hasControl(username)) throw invalidRequest("The username is empty or not plain text.", "Enter the username the host knows you by.");
883
+ if (request.token !== void 0 && request.token !== "") {
884
+ if (typeof request.token !== "string" || request.token.length > MAX_TOKEN || hasControl(request.token)) throw invalidRequest("The token is not plain text.", "Paste the token again without line breaks.");
885
+ return {
886
+ method: "https",
887
+ host,
888
+ username,
889
+ token: request.token
890
+ };
891
+ }
892
+ if (current.method === "https" && current.host === host && current.token !== "") return {
893
+ method: "https",
894
+ host,
895
+ username,
896
+ token: current.token
897
+ };
898
+ throw invalidRequest(current.method === "https" ? "The host changed, so the saved token cannot follow it." : "A token is required.", "Enter the personal access token for this host.");
899
+ }
900
+ throw invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
901
+ }
902
+ /** Tightens a file or folder something left readable by group or others. */
903
+ function tighten(target, mode) {
904
+ try {
905
+ if ((fs.statSync(target).mode & LOOSE_BITS) !== 0) fs.chmodSync(target, mode);
906
+ } catch {}
907
+ }
908
+ function createGitAuthStore(homeDir = os.homedir()) {
909
+ const file = credentialsFile(homeDir);
910
+ const readFile = () => {
911
+ tighten(file, OWNER_ONLY_FILE);
912
+ const raw = readJson(file);
913
+ const workspaces = {};
914
+ if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
915
+ const config = parseConfig(value);
916
+ if (config !== void 0) workspaces[key] = config;
917
+ }
918
+ return {
919
+ version: 1,
920
+ workspaces
921
+ };
922
+ };
923
+ const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
924
+ return {
925
+ read,
926
+ view: (workspaceRoot) => publicView(read(workspaceRoot)),
927
+ save(workspaceRoot, request) {
928
+ const key = workspaceKey(workspaceRoot);
929
+ const current = readFile();
930
+ const next = parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
931
+ const root = doomGitRoot(homeDir);
932
+ fs.mkdirSync(root, {
933
+ recursive: true,
934
+ mode: OWNER_ONLY_DIRECTORY
935
+ });
936
+ fs.chmodSync(root, OWNER_ONLY_DIRECTORY);
937
+ const workspaces = { ...current.workspaces };
938
+ if (next.method === "none") delete workspaces[key];
939
+ else workspaces[key] = next;
940
+ writeJsonAtomic(file, {
941
+ version: 1,
942
+ workspaces
943
+ });
944
+ fs.chmodSync(file, OWNER_ONLY_FILE);
945
+ return publicView(next);
946
+ }
947
+ };
948
+ }
949
+ /** The transport and host a remote URL names, or undefined for a local path or anything else. */
950
+ function remoteTransport(url) {
951
+ const trimmed = url.trim();
952
+ if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(trimmed)) try {
953
+ const parsed = new URL(trimmed);
954
+ const kind = parsed.protocol === "https:" ? "https" : parsed.protocol === "http:" ? "http" : parsed.protocol === "ssh:" ? "ssh" : void 0;
955
+ return kind === void 0 ? void 0 : {
956
+ kind,
957
+ host: parsed.host.toLowerCase()
958
+ };
959
+ } catch {
960
+ return;
961
+ }
962
+ const scp = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)/u.exec(trimmed);
963
+ if (scp !== null && scp[1] !== void 0 && scp[1].length > 1) return {
964
+ kind: "ssh",
965
+ host: scp[1].toLowerCase()
966
+ };
967
+ }
968
+ /** Quotes one word for the POSIX shell git runs GIT_SSH_COMMAND through. */
969
+ function shellQuote(value) {
970
+ return `'${value.replaceAll("'", "'\\''")}'`;
971
+ }
972
+ /**
973
+ * The environment for one fetch or push against `remoteUrl`.
974
+ *
975
+ * Every call drops tracing (which can log credentials) and turns prompts off,
976
+ * because no terminal is attached. Only when the workspace's method matches the
977
+ * remote does anything secret go in, and then only into this child's env.
978
+ */
979
+ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
980
+ const env = { ...baseEnv };
981
+ for (const key of Object.keys(env)) if (STRIPPED_ALWAYS.includes(key) || STRIPPED_PREFIXES.some((prefix) => key.startsWith(prefix))) delete env[key];
982
+ env.GIT_TERMINAL_PROMPT = "0";
983
+ env.GCM_INTERACTIVE = "never";
984
+ const transport = remoteTransport(remoteUrl);
985
+ const credentialed = () => {
986
+ for (const key of Object.keys(env)) if (STRIPPED_CREDENTIALED.includes(key) || CONFIG_ENTRY.test(key)) delete env[key];
987
+ env.GIT_ASKPASS = "true";
988
+ };
989
+ if (config.method === "https") {
990
+ if (transport?.kind !== "https" || transport.host !== config.host) return {
991
+ env,
992
+ credentialed: false,
993
+ mismatch: `This workspace's token is for https://${config.host}, and this remote is not.`
994
+ };
995
+ credentialed();
996
+ env.GIT_CONFIG_COUNT = "3";
997
+ env.GIT_CONFIG_KEY_0 = "credential.helper";
998
+ env.GIT_CONFIG_VALUE_0 = "";
999
+ env.GIT_CONFIG_KEY_1 = `credential.https://${config.host}.helper`;
1000
+ env.GIT_CONFIG_VALUE_1 = ENV_CREDENTIAL_HELPER;
1001
+ env.GIT_CONFIG_KEY_2 = "http.sslVerify";
1002
+ env.GIT_CONFIG_VALUE_2 = "true";
1003
+ env.GIT_ALLOW_PROTOCOL = "https";
1004
+ env.PO_GIT_USERNAME = config.username;
1005
+ env.PO_GIT_TOKEN = config.token;
1006
+ return {
1007
+ env,
1008
+ credentialed: true
1009
+ };
1010
+ }
1011
+ if (config.method === "ssh") {
1012
+ if (transport?.kind !== "ssh") return {
1013
+ env,
1014
+ credentialed: false,
1015
+ mismatch: "This workspace uses SSH, and this remote is not an SSH remote."
1016
+ };
1017
+ credentialed();
1018
+ env.GIT_SSH_COMMAND = [
1019
+ "ssh",
1020
+ ...config.keyPath === void 0 ? [] : [
1021
+ "-i",
1022
+ shellQuote(expandHome(config.keyPath, homeDir)),
1023
+ "-o",
1024
+ "IdentitiesOnly=yes"
1025
+ ],
1026
+ "-o",
1027
+ "BatchMode=yes",
1028
+ "-o",
1029
+ "ConnectTimeout=15"
1030
+ ].join(" ");
1031
+ env.GIT_ALLOW_PROTOCOL = "ssh";
1032
+ return {
1033
+ env,
1034
+ credentialed: true
1035
+ };
1036
+ }
1037
+ return {
1038
+ env,
1039
+ credentialed: false
1040
+ };
1041
+ }
1042
+ //#endregion
1043
+ //#region src/services/newSessionRequest/index.ts
1044
+ const MAX_NAME_LENGTH = 120;
1045
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
1046
+ function optionalText(value) {
1047
+ if (value === void 0) return void 0;
1048
+ if (typeof value !== "string") return false;
1049
+ const trimmed = value.trim();
1050
+ return trimmed === "" ? void 0 : trimmed;
1051
+ }
1052
+ /**
1053
+ * Validates a new-session dialog request for a worktree session. Every ref is
1054
+ * checked here, before it can reach git as a positional argument.
1055
+ */
1056
+ function newSessionRequest(body) {
1057
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
1058
+ const record = body;
1059
+ const branch = optionalText(record.branch);
1060
+ if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
1061
+ const name = optionalText(record.name);
1062
+ if (name === false || name !== void 0 && name.length > MAX_NAME_LENGTH) return { error: `The session name must be text of up to ${String(MAX_NAME_LENGTH)} characters.` };
1063
+ const named = name === void 0 ? {} : { name };
1064
+ if (record.mode === "existing-branch") {
1065
+ const remote = optionalText(record.remote);
1066
+ if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
1067
+ return {
1068
+ mode: "existing-branch",
1069
+ branch,
1070
+ ...remote === void 0 ? {} : { remote },
1071
+ ...named
1072
+ };
1073
+ }
1074
+ if (record.mode === "new-branch") {
1075
+ const baseRef = optionalText(record.baseRef);
1076
+ if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
1077
+ return {
1078
+ mode: "new-branch",
1079
+ branch,
1080
+ ...baseRef === void 0 ? {} : { baseRef },
1081
+ ...named
1082
+ };
1083
+ }
1084
+ return { error: "The mode must be existing-branch or new-branch." };
1085
+ }
1086
+ //#endregion
1087
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1088
+ /**
1089
+ * The worktree surface the cockpit panel calls.
1090
+ *
1091
+ * Hub-scoped because worktrees are a property of a repository, not of one
1092
+ * session: the panel lists and creates them whether or not the session that
1093
+ * made them is focused, and a session-scoped API would disappear with it.
1094
+ *
1095
+ * The panel names a repository by the hub's opaque id and never by path.
1096
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
1097
+ * point this at a directory the cockpit was never given.
1098
+ */
1099
+ function badRequest(message) {
1100
+ return Response.json({ error: message }, { status: 400 });
1101
+ }
1102
+ function failed(error) {
1103
+ if (error instanceof DoomGitExpectedError) return Response.json({
1104
+ error: error.message,
1105
+ code: error.code
1106
+ }, { status: error.retryable ? 503 : 409 });
1107
+ return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1108
+ }
1109
+ //#endregion
1110
+ //#region src/extensions/(backend)/api/git/route.server.ts
1111
+ var route_server_default = defineRoute({
1112
+ basePath: "git",
1113
+ start(context) {
1114
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1115
+ const directEvents = context.directEvents;
1116
+ const publishLifecycle = (sessionId, repositoryRoot) => {
1117
+ directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1118
+ version: 1,
1119
+ repositoryRoot
1120
+ });
1121
+ };
1122
+ const git = createWorktreeGit();
1123
+ const operations = createWorktreeOperations({
1124
+ git,
1125
+ sessionService: context.sessionService,
1126
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory }
1127
+ });
1128
+ /**
1129
+ * The new-session dialog's routes: the workspace's branches, and a top-level
1130
+ * worktree session on one. Workspace-mounted only, and always rooted at the
1131
+ * mount's own workspace, so a request can never name another directory.
1132
+ */
1133
+ const newSession = async (request, url) => {
1134
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
1135
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
1136
+ if (!isBranches && !isCreate) return void 0;
1137
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1138
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1139
+ if (isBranches) {
1140
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1141
+ const branches = repositoryRoot === void 0 ? {
1142
+ repository: false,
1143
+ local: [],
1144
+ remote: []
1145
+ } : {
1146
+ repository: true,
1147
+ ...await git.listBranches(repositoryRoot)
1148
+ };
1149
+ return Response.json(branches);
1150
+ }
1151
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
1152
+ if ("error" in parsed) return badRequest(parsed.error);
1153
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
1154
+ branch: parsed.branch,
1155
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1156
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1157
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1158
+ ...parsed.name === void 0 ? {} : { name: parsed.name }
1159
+ });
1160
+ publishLifecycle(record.sessionId, record.repositoryRoot);
1161
+ const created = {
1162
+ sessionId: record.sessionId,
1163
+ worktreeId: record.id
1164
+ };
1165
+ return Response.json(created, { status: 201 });
1166
+ };
1167
+ /** The admitted root for a request, or a response explaining why not. */
1168
+ const rootOf = (url) => {
1169
+ const repositoryId = url.searchParams.get("repositoryId");
1170
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1171
+ const root = context.resolveRepository?.(repositoryId);
1172
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1173
+ return root;
1174
+ };
1175
+ const homeDir = context.homeDirectory ?? os.homedir();
1176
+ const gitAuth = createGitAuthStore(homeDir);
1177
+ const branchDiff = createBranchDiff();
1178
+ const pendingReviews = /* @__PURE__ */ new Map();
1179
+ /**
1180
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1181
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1182
+ * The view never carries the token.
1183
+ */
1184
+ const auth = async (request, url) => {
1185
+ if (url.pathname !== "/auth") return void 0;
1186
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1187
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1188
+ const root = rootOf(url);
1189
+ if (root instanceof Response) return root;
1190
+ if (request.method === "GET") return Response.json(gitAuth.view(root));
1191
+ try {
1192
+ return Response.json(gitAuth.save(root, await request.json().catch(() => void 0)));
1193
+ } catch (error) {
1194
+ if (error instanceof DoomGitExpectedError && error.code === "invalid_request") {
1195
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1196
+ return Response.json({
1197
+ error: text,
1198
+ code: error.code
1199
+ }, { status: 400 });
1200
+ }
1201
+ throw error;
1202
+ }
1203
+ };
1204
+ /**
1205
+ * The session's change against its base. Session mounts only, rooted at the
1206
+ * session's own checkout; a file is served only when it is in the change set
1207
+ * computed for the request. Overlapping requests share an in-flight snapshot.
1208
+ */
1209
+ const review = async (request, url) => {
1210
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1211
+ const cwd = context.scope === "session" ? context.cwd : void 0;
1212
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1213
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1214
+ let recordedBaseRef;
1215
+ try {
1216
+ recordedBaseRef = createWorktreeRegistry(registryFile(cwd, homeDir)).list().find((record) => record.sessionId === context.sessionId)?.baseRef;
1217
+ } catch {
1218
+ recordedBaseRef = void 0;
1219
+ }
1220
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1221
+ let pending = pendingReviews.get(key);
1222
+ if (pending === void 0) {
1223
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1224
+ pendingReviews.set(key, pending);
1225
+ }
1226
+ const result = await pending;
1227
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
1228
+ repository: false,
1229
+ files: []
1230
+ });
1231
+ const filePath = url.searchParams.get("path") ?? "";
1232
+ if (result === void 0 || !result.summary.files.some((file) => file.path === filePath)) return Response.json({ error: "That file is not part of this review." }, { status: 404 });
1233
+ return Response.json(await branchDiff.fileDiff(result, filePath));
1234
+ };
1235
+ return {
1236
+ async fetch(request) {
1237
+ const url = new URL(request.url);
1238
+ try {
1239
+ const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1240
+ if (answered !== void 0) return answered;
1241
+ } catch (error) {
1242
+ context.onNotice(`git request failed: ${error.name}`);
1243
+ return failed(error);
1244
+ }
1245
+ const root = rootOf(url);
1246
+ if (root instanceof Response) return root;
1247
+ const callerContext = {
1248
+ cwd: root,
1249
+ sessionId: url.searchParams.get("sessionId") ?? ""
1250
+ };
1251
+ if ((request.method === "POST" && url.pathname === "/worktrees" || request.method === "DELETE" && /^\/worktrees\/[^/]+$/u.test(url.pathname)) && callerContext.sessionId === "") return badRequest("A sessionId is required for worktree mutations.");
1252
+ try {
1253
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1254
+ if (request.method === "POST" && url.pathname === "/worktrees") {
1255
+ const body = await request.json();
1256
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1257
+ const record = await operations.spawn(callerContext, {
1258
+ branch: body.branch,
1259
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1260
+ ...body.name === void 0 ? {} : { name: body.name }
1261
+ });
1262
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1263
+ return Response.json({ worktree: record }, { status: 201 });
1264
+ }
1265
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1266
+ if (request.method === "DELETE" && closing) {
1267
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1268
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1269
+ return Response.json({ worktree: record });
1270
+ }
1271
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
1272
+ } catch (error) {
1273
+ context.onNotice(`worktree request failed: ${error.name}`);
1274
+ return failed(error);
1275
+ }
1276
+ },
1277
+ close() {}
1278
+ };
1279
+ }
1280
+ });
1281
+ //#endregion
1282
+ //#region src/services/gitFailure/index.ts
1283
+ const RULES = [
1284
+ {
1285
+ code: "host_key_changed",
1286
+ phrases: ["remote host identification has changed"],
1287
+ message: "The remote's SSH host key changed since this machine last saw it.",
1288
+ recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1289
+ retryable: false
1290
+ },
1291
+ {
1292
+ code: "host_key_unknown",
1293
+ phrases: [
1294
+ "host key verification failed",
1295
+ "no ed25519 host key is known",
1296
+ "no rsa host key is known"
1297
+ ],
1298
+ message: "This machine does not trust the remote's SSH host key yet.",
1299
+ recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1300
+ retryable: false
1301
+ },
1302
+ {
1303
+ code: "auth_failed",
1304
+ phrases: [
1305
+ "authentication failed",
1306
+ "could not read username",
1307
+ "could not read password",
1308
+ "permission denied (publickey",
1309
+ "returned error: 401",
1310
+ "returned error: 403",
1311
+ "terminal prompts disabled",
1312
+ "load key",
1313
+ "unprotected private key",
1314
+ "invalid format"
1315
+ ],
1316
+ message: "The remote refused the credentials.",
1317
+ recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1318
+ retryable: false
1319
+ },
1320
+ {
1321
+ code: "repository_not_found",
1322
+ phrases: ["repository not found", "does not appear to be a git repository"],
1323
+ message: "The remote repository was not found, or these credentials cannot see it.",
1324
+ recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1325
+ retryable: false
1326
+ },
1327
+ {
1328
+ code: "remote_unreachable",
1329
+ phrases: [
1330
+ "could not resolve host",
1331
+ "connection refused",
1332
+ "connection timed out",
1333
+ "operation timed out",
1334
+ "unable to access",
1335
+ "network is unreachable"
1336
+ ],
1337
+ message: "The remote could not be reached.",
1338
+ recovery: "Check the network and the remote URL, then try again.",
1339
+ retryable: true
1340
+ },
1341
+ {
1342
+ code: "push_lease_rejected",
1343
+ phrases: ["(stale info)"],
1344
+ message: "The remote branch moved since your last fetch, so the force push was refused.",
1345
+ recovery: "Pull to see the new commits, then decide whether to push again.",
1346
+ retryable: false
1347
+ },
1348
+ {
1349
+ code: "push_needs_force",
1350
+ phrases: ["(non-fast-forward)", "(fetch first)"],
1351
+ message: "The remote branch has commits yours replaced, usually after a rebase.",
1352
+ recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1353
+ retryable: false
1354
+ },
1355
+ {
1356
+ code: "worktree_dirty",
1357
+ phrases: [
1358
+ "unstaged changes",
1359
+ "uncommitted changes",
1360
+ "would be overwritten",
1361
+ "your index contains uncommitted changes"
1362
+ ],
1363
+ message: "There are uncommitted changes in the way.",
1364
+ recovery: "Commit or stash your changes first.",
1365
+ retryable: false
1366
+ }
1367
+ ];
1368
+ function classifyGitFailure(operation, result, mismatch) {
1369
+ if (result.timedOut) return new DoomGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1370
+ const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1371
+ const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1372
+ if (rule === void 0) return new DoomGitExpectedError("git_failed", `git ${operation} failed (exit ${String(result.code)}).`, false, "Run the same command in a terminal in this checkout to see what git says.");
1373
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1374
+ return new DoomGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1375
+ }
1376
+ //#endregion
1377
+ //#region src/services/gitSync/index.ts
1378
+ /**
1379
+ * Manual pull, push and rebase for a session's checkout.
1380
+ *
1381
+ * DESIGN PATTERNS:
1382
+ * - The workspace's auth goes into the environment of the one fetch or push
1383
+ * that needs it, built fresh per call. Rebase itself runs locally and never
1384
+ * sees a credential.
1385
+ * - Fetch and rebase are separate commands, so a hung network can never leave a
1386
+ * rebase half applied.
1387
+ * - A conflicted rebase is not an error. It is left paused for the reader to
1388
+ * hand to the agent or abort, and git's own state reports it from then on.
1389
+ * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1390
+ * Untracked files only block when git says they would be overwritten.
1391
+ * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1392
+ * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1393
+ * which git refuses if the remote holds commits this branch never integrated.
1394
+ */
1395
+ const DONE = { outcome: "done" };
1396
+ function expected(code, message, recovery) {
1397
+ return new DoomGitExpectedError(code, message, false, recovery);
1398
+ }
1399
+ async function readLine(cwd, args) {
1400
+ const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
1401
+ const out = result.stdout.trim();
1402
+ return result.code === 0 && out !== "" ? out : void 0;
1403
+ }
1404
+ async function toplevel(cwd) {
1405
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1406
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1407
+ return root;
1408
+ }
1409
+ async function rebasing(root) {
1410
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1411
+ const gitPath = await readLine(root, [
1412
+ "rev-parse",
1413
+ "--git-path",
1414
+ name
1415
+ ]);
1416
+ if (gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath))) return true;
1417
+ }
1418
+ return false;
1419
+ }
1420
+ async function conflicts(root) {
1421
+ return (await runGit(root, [
1422
+ "diff",
1423
+ "--name-only",
1424
+ "--diff-filter=U",
1425
+ "-z"
1426
+ ], { timeout: READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1427
+ }
1428
+ async function currentBranch(root) {
1429
+ const branch = await readLine(root, [
1430
+ "symbolic-ref",
1431
+ "--quiet",
1432
+ "--short",
1433
+ "HEAD"
1434
+ ]);
1435
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1436
+ return branch;
1437
+ }
1438
+ async function guard(root, needsCleanTree) {
1439
+ if (await rebasing(root)) throw expected("rebase_in_progress", "A rebase is paused in this checkout.", "Ask the agent to resolve it, or abort the rebase.");
1440
+ const branch = await currentBranch(root);
1441
+ if (needsCleanTree) {
1442
+ if (await readLine(root, [
1443
+ "status",
1444
+ "--porcelain",
1445
+ "--untracked-files=no"
1446
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
1447
+ }
1448
+ return branch;
1449
+ }
1450
+ function createGitSync(options) {
1451
+ const baseEnv = options.baseEnv ?? process.env;
1452
+ /** One credentialed network command against `remote`, classified on failure. */
1453
+ const network = async (root, context, remote, operation, args, urlArgs = []) => {
1454
+ const url = await readLine(root, [
1455
+ "remote",
1456
+ "get-url",
1457
+ ...urlArgs,
1458
+ remote
1459
+ ]);
1460
+ if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1461
+ const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1462
+ const result = await runGit(root, args, {
1463
+ timeout: NETWORK_TIMEOUT_MS,
1464
+ env: prepared.env
1465
+ });
1466
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
1467
+ };
1468
+ /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1469
+ const rebaseOnto = async (root, onto) => {
1470
+ const result = await runGit(root, ["rebase", onto], {
1471
+ timeout: REBASE_TIMEOUT_MS,
1472
+ env: {
1473
+ ...baseEnv,
1474
+ GIT_EDITOR: "true",
1475
+ GIT_TERMINAL_PROMPT: "0"
1476
+ }
1477
+ });
1478
+ if (result.code === 0) return DONE;
1479
+ if (await rebasing(root)) return {
1480
+ outcome: "paused",
1481
+ conflicts: await conflicts(root)
1482
+ };
1483
+ throw classifyGitFailure("rebase", result);
1484
+ };
1485
+ /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1486
+ const remoteOfRef = async (root, ref) => {
1487
+ const full = await readLine(root, [
1488
+ "rev-parse",
1489
+ "--symbolic-full-name",
1490
+ ref
1491
+ ]);
1492
+ if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
1493
+ const rest = full.slice(13);
1494
+ const cut = rest.indexOf("/");
1495
+ return cut > 0 ? rest.slice(0, cut) : void 0;
1496
+ };
1497
+ return {
1498
+ async pull(context) {
1499
+ const root = await toplevel(context.cwd);
1500
+ const branch = await guard(root, true);
1501
+ const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
1502
+ const upstream = await readLine(root, [
1503
+ "rev-parse",
1504
+ "--abbrev-ref",
1505
+ "--symbolic-full-name",
1506
+ `${branch}@{upstream}`
1507
+ ]);
1508
+ if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
1509
+ if (remote !== ".") await network(root, context, remote, "fetch", [
1510
+ "fetch",
1511
+ "--prune",
1512
+ remote
1513
+ ]);
1514
+ return rebaseOnto(root, upstream);
1515
+ },
1516
+ async push(context, force) {
1517
+ const root = await toplevel(context.cwd);
1518
+ const branch = await guard(root, false);
1519
+ const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
1520
+ const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
1521
+ let remote = configuredRemote;
1522
+ let target = merge;
1523
+ const args = ["push", "--porcelain"];
1524
+ if (remote === void 0 || target === void 0 || remote === ".") {
1525
+ const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
1526
+ remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
1527
+ if (remote === void 0) throw expected("no_remote", "There is no remote to push to.", remotes.length === 0 ? "Add a remote in a terminal first." : "Push once from a terminal to choose the remote.");
1528
+ target = `refs/heads/${branch}`;
1529
+ args.push("--set-upstream");
1530
+ }
1531
+ if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
1532
+ args.push(remote, `HEAD:${target}`);
1533
+ await network(root, context, remote, "push", args, ["--push"]);
1534
+ return DONE;
1535
+ },
1536
+ async rebase(context) {
1537
+ const root = await toplevel(context.cwd);
1538
+ const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
1539
+ if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
1540
+ const remote = await remoteOfRef(root, base);
1541
+ if (remote !== void 0) await network(root, context, remote, "fetch", [
1542
+ "fetch",
1543
+ "--prune",
1544
+ remote
1545
+ ]);
1546
+ return rebaseOnto(root, base);
1547
+ },
1548
+ async abortRebase(context) {
1549
+ const root = await toplevel(context.cwd);
1550
+ if (!await rebasing(root)) return DONE;
1551
+ const result = await runGit(root, ["rebase", "--abort"], { timeout: REBASE_TIMEOUT_MS });
1552
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
1553
+ return DONE;
1554
+ }
1555
+ };
1556
+ }
1557
+ //#endregion
1558
+ //#region src/types/gitReview.ts
1559
+ /**
1560
+ * The cockpit's view of what this session changed against its base: the counts
1561
+ * the '# diff' group shows, what the review tab lists and draws, and the manual
1562
+ * sync that sits beside them.
1563
+ *
1564
+ * DESIGN PATTERNS:
1565
+ * - Declarations only, shared by the hub and the page.
1566
+ * - Its own channel, apart from worktrees. Worktrees are repository
1567
+ * management; the diff is this session's code change.
1568
+ * - A diff row carries one line number whose file follows from its marker: the
1569
+ * new file's for context and additions, the old file's for removals. It is
1570
+ * the same shape the shared DiffView draws.
1571
+ *
1572
+ * AVOID:
1573
+ * - Behaviour or node builtins. Browser code imports this file.
1574
+ */
1575
+ /** The session channel carrying this checkout's changes and the sync around them. */
1576
+ const GIT_CHANGES_TYPE = "git_changes";
1577
+ //#endregion
1578
+ //#region src/extensions/(backend)/channel/_lib/git-changes.server.ts
1579
+ /**
1580
+ * The '# diff' data channel: this session's change against its base, and the
1581
+ * manual sync commands the review tab sends back through it.
1582
+ *
1583
+ * DESIGN PATTERNS:
1584
+ * - Apart from the worktrees channel. Worktrees are repository management;
1585
+ * this is the session's own code change.
1586
+ * - Push, not poll. The session facet publishes a "changed" event after every
1587
+ * tool call and settled turn; recounts are coalesced to one in flight plus
1588
+ * one rerun, so a burst of tool calls costs at most two.
1589
+ * - One sync command per session. A rebase and a push must never overlap.
1590
+ * - Auth is read fresh for each command from the session's workspace, and goes
1591
+ * only into that command's git child.
1592
+ *
1593
+ * AVOID:
1594
+ * - Echoing git output. Failures go through classifyGitFailure, which matches
1595
+ * stderr and drops it, because a remote URL in it can carry a token.
1596
+ */
1597
+ function payloadOf$1(state) {
1598
+ return {
1599
+ ...state.changes === void 0 ? {} : { changes: state.changes },
1600
+ ...state.pending === void 0 ? {} : { pending: state.pending },
1601
+ ...state.error === void 0 ? {} : { error: state.error },
1602
+ ...state.errorTarget === void 0 ? {} : { errorTarget: state.errorTarget }
1603
+ };
1604
+ }
1605
+ /** A command the page sent, or undefined when the frame was not one. */
1606
+ function parseChangesCommand(payload) {
1607
+ if (typeof payload !== "object" || payload === null) return void 0;
1608
+ const value = payload;
1609
+ if (value.action === "pull" || value.action === "rebase" || value.action === "abort-rebase") return { action: value.action };
1610
+ if (value.action === "push") return value.force === true ? {
1611
+ action: "push",
1612
+ force: true
1613
+ } : { action: "push" };
1614
+ }
1615
+ const PENDING = {
1616
+ pull: "pulling…",
1617
+ push: "pushing…",
1618
+ rebase: "rebasing…",
1619
+ "abort-rebase": "aborting the rebase…"
1620
+ };
1621
+ /** The error target a failure maps to: a rejected plain push asks for a confirmed lease force. */
1622
+ function errorTargetFor$1(command, error) {
1623
+ if (command.action !== "push") return { action: command.action };
1624
+ return error instanceof DoomGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
1625
+ action: "push",
1626
+ forceRequired: true
1627
+ } : { action: "push" };
1628
+ }
1629
+ function failureText$1(error) {
1630
+ if (error instanceof DoomGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1631
+ return "The git command failed.";
1632
+ }
1633
+ function createGitChangesChannel(options = {}) {
1634
+ let receiveCommand;
1635
+ return {
1636
+ frameType: GIT_CHANGES_TYPE,
1637
+ start(host) {
1638
+ const homeDir = options.homeDir ?? os.homedir();
1639
+ const diff = options.diff ?? createBranchDiff();
1640
+ const sync = options.sync ?? createGitSync({ homeDir });
1641
+ const auth = options.auth ?? createGitAuthStore(homeDir);
1642
+ const latest = /* @__PURE__ */ new Map();
1643
+ const subscriptions = /* @__PURE__ */ new Map();
1644
+ const scopes = /* @__PURE__ */ new Map();
1645
+ const inFlight = /* @__PURE__ */ new Set();
1646
+ const rerun = /* @__PURE__ */ new Set();
1647
+ const busy = /* @__PURE__ */ new Set();
1648
+ /** The base the session's own worktree was created from, when it has one. */
1649
+ const recordedBaseRef = (scope) => {
1650
+ try {
1651
+ return createWorktreeRegistry(registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
1652
+ } catch {
1653
+ return;
1654
+ }
1655
+ };
1656
+ /** Republishes a session, skipping a frame that would say nothing new. */
1657
+ const publish = (sessionId, next) => {
1658
+ const previous = latest.get(sessionId);
1659
+ latest.set(sessionId, next);
1660
+ if (previous !== void 0 && JSON.stringify(payloadOf$1(previous)) === JSON.stringify(payloadOf$1(next))) return;
1661
+ host.publish(sessionId, payloadOf$1(next));
1662
+ };
1663
+ const update = (sessionId, patch) => {
1664
+ const previous = latest.get(sessionId) ?? {
1665
+ changes: void 0,
1666
+ pending: void 0,
1667
+ error: void 0,
1668
+ errorTarget: void 0
1669
+ };
1670
+ publish(sessionId, {
1671
+ ...previous,
1672
+ ...patch
1673
+ });
1674
+ };
1675
+ /** Recounts one session; a request while one runs schedules exactly one more. */
1676
+ const refresh = (sessionId) => {
1677
+ const scope = scopes.get(sessionId);
1678
+ if (scope === void 0) return;
1679
+ if (inFlight.has(sessionId)) {
1680
+ rerun.add(sessionId);
1681
+ return;
1682
+ }
1683
+ inFlight.add(sessionId);
1684
+ const base = recordedBaseRef(scope);
1685
+ diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
1686
+ if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1687
+ }).catch((error) => {
1688
+ host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
1689
+ }).finally(() => {
1690
+ inFlight.delete(sessionId);
1691
+ if (rerun.delete(sessionId)) refresh(sessionId);
1692
+ });
1693
+ };
1694
+ const run = (scope, command) => {
1695
+ const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1696
+ const base = recordedBaseRef(scope);
1697
+ const context = {
1698
+ cwd: scope.cwd,
1699
+ auth: auth.read(workspaceRoot),
1700
+ ...base === void 0 ? {} : { recordedBaseRef: base }
1701
+ };
1702
+ if (command.action === "pull") return sync.pull(context);
1703
+ if (command.action === "push") return sync.push(context, command.force === true);
1704
+ if (command.action === "rebase") return sync.rebase(context);
1705
+ return sync.abortRebase(context);
1706
+ };
1707
+ const source = {
1708
+ payloadFor(scope) {
1709
+ const state = latest.get(scope.sessionId);
1710
+ return state === void 0 ? void 0 : payloadOf$1(state);
1711
+ },
1712
+ sessionAdded(scope) {
1713
+ scopes.set(scope.sessionId, scope);
1714
+ refresh(scope.sessionId);
1715
+ const unsubscribe = host.directEvents.subscribe(GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1716
+ if (isSessionChangedEvent(payload)) refresh(scope.sessionId);
1717
+ });
1718
+ subscriptions.set(scope.sessionId, unsubscribe);
1719
+ },
1720
+ sessionRemoved(sessionId) {
1721
+ subscriptions.get(sessionId)?.();
1722
+ subscriptions.delete(sessionId);
1723
+ scopes.delete(sessionId);
1724
+ latest.delete(sessionId);
1725
+ rerun.delete(sessionId);
1726
+ busy.delete(sessionId);
1727
+ },
1728
+ close() {
1729
+ for (const unsubscribe of subscriptions.values()) unsubscribe();
1730
+ subscriptions.clear();
1731
+ scopes.clear();
1732
+ latest.clear();
1733
+ rerun.clear();
1734
+ busy.clear();
1735
+ }
1736
+ };
1737
+ receiveCommand = (scope, payload) => {
1738
+ const command = parseChangesCommand(payload);
1739
+ if (command === void 0 || !scopes.has(scope.sessionId)) return;
1740
+ if (busy.has(scope.sessionId)) return;
1741
+ busy.add(scope.sessionId);
1742
+ update(scope.sessionId, {
1743
+ pending: PENDING[command.action],
1744
+ error: void 0,
1745
+ errorTarget: void 0
1746
+ });
1747
+ run(scope, command).then(() => update(scope.sessionId, { pending: void 0 })).catch((error) => {
1748
+ host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof DoomGitExpectedError ? error.code : "unexpected"})`);
1749
+ update(scope.sessionId, {
1750
+ pending: void 0,
1751
+ error: failureText$1(error),
1752
+ errorTarget: errorTargetFor$1(command, error)
1753
+ });
1754
+ }).finally(() => {
1755
+ busy.delete(scope.sessionId);
1756
+ refresh(scope.sessionId);
1757
+ });
1758
+ };
1759
+ return source;
1760
+ },
1761
+ receive(scope, payload) {
1762
+ receiveCommand?.(scope, payload);
1763
+ }
1764
+ };
1765
+ }
1766
+ //#endregion
1767
+ //#region src/extensions/(backend)/channel/git-changes.server.ts
1768
+ var git_changes_server_default = defineChannel(createGitChangesChannel);
1769
+ //#endregion
1770
+ //#region src/types/webWorktrees.ts
1771
+ /**
1772
+ * The cockpit's view of this session's worktrees.
1773
+ *
1774
+ * DESIGN PATTERNS:
1775
+ * - Declarations only. The channel frame type is a constant so the hub and the
1776
+ * page cannot drift apart on a string.
1777
+ * - A view is the subset of a record the dock needs, not the record. The
1778
+ * registry may hold paths and provenance the page has no business rendering.
1779
+ *
1780
+ * AVOID:
1781
+ * - Adding behaviour here. This file is imported by browser code, so it must
1782
+ * stay free of node builtins.
1783
+ */
1784
+ /** The data channel carrying one session's worktrees to the page. */
1785
+ const GIT_WORKTREES_TYPE = "git_worktrees";
1786
+ //#endregion
1787
+ //#region src/extensions/(backend)/channel/_lib/git-worktrees.server.ts
1788
+ function payloadOf(state) {
1789
+ return {
1790
+ worktrees: state.worktrees,
1791
+ ...state.pending === void 0 ? {} : { pending: state.pending },
1792
+ ...state.error === void 0 ? {} : { error: state.error },
1793
+ ...state.errorTarget === void 0 ? {} : { errorTarget: state.errorTarget }
1794
+ };
1795
+ }
1796
+ /** Worktrees visible to this session, using the hub's live session table for ownership. */
1797
+ function viewsFor(scope, deps) {
1798
+ try {
1799
+ return createWorktreeRegistry(registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
1800
+ if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1801
+ const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1802
+ const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
1803
+ if (!owned && !unowned) return [];
1804
+ return [{
1805
+ id: record.id,
1806
+ branch: record.branch,
1807
+ path: record.path,
1808
+ sessionId: record.status === "orphaned" ? null : record.sessionId,
1809
+ orphaned: record.status === "orphaned",
1810
+ unowned
1811
+ }];
1812
+ });
1813
+ } catch {
1814
+ return [];
1815
+ }
1816
+ }
1817
+ function sameList(left, right) {
1818
+ if (left.length !== right.length) return false;
1819
+ return left.every((entry, index) => {
1820
+ const other = right[index];
1821
+ return other !== void 0 && entry.id === other.id && entry.branch === other.branch && entry.sessionId === other.sessionId && entry.orphaned === other.orphaned && entry.unowned === other.unowned;
1822
+ });
1823
+ }
1824
+ function errorTargetFor(command) {
1825
+ return command.action === "create" ? { action: "create" } : {
1826
+ action: "close",
1827
+ id: command.id
1828
+ };
1829
+ }
1830
+ /** A command the page sent, or undefined when the frame was not one. */
1831
+ function parseCommand(payload) {
1832
+ if (typeof payload !== "object" || payload === null) return void 0;
1833
+ const value = payload;
1834
+ if (value.action === "create") {
1835
+ if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
1836
+ if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
1837
+ return {
1838
+ action: "create",
1839
+ branch: value.branch.trim(),
1840
+ ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
1841
+ ...typeof value.reservationId === "string" ? { reservationId: value.reservationId } : {}
1842
+ };
1843
+ }
1844
+ if (value.action === "close") {
1845
+ if (typeof value.id !== "string" || value.id === "") return void 0;
1846
+ return {
1847
+ action: "close",
1848
+ id: value.id,
1849
+ ...value.force === true ? { force: true } : {}
1850
+ };
1851
+ }
1852
+ }
1853
+ /**
1854
+ * What the reader is told when a command fails.
1855
+ *
1856
+ * An expected failure explains itself. Anything else is summarised, never
1857
+ * echoed: a git error can carry a remote URL with a token in it.
1858
+ */
1859
+ function failureText(error) {
1860
+ return error instanceof DoomGitExpectedError ? error.message : "The worktree operation failed.";
1861
+ }
1862
+ /** Starts one direct-event subscription per managed session. */
1863
+ function createWorktreesChannel(options = {}) {
1864
+ let receiveCommand;
1865
+ return {
1866
+ frameType: GIT_WORKTREES_TYPE,
1867
+ start(host) {
1868
+ const sessionService = host.sessionService;
1869
+ if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1870
+ const worktrees = options.operations ?? createWorktreeOperations({
1871
+ git: createWorktreeGit(),
1872
+ sessionService
1873
+ });
1874
+ /** Announces a successful mutation to this session's lifecycle subscribers. */
1875
+ const publishLifecycle = (scope, repositoryRoot) => {
1876
+ host.directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
1877
+ version: 1,
1878
+ repositoryRoot
1879
+ });
1880
+ };
1881
+ const unregisterWorktreeProvisioner = sessionService.registerReservedWorktreeProvisioner?.(async ({ reservationId, parentSessionId, signal }) => {
1882
+ const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
1883
+ if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
1884
+ const branch = `po/conversation-${reservationId.slice(0, 12)}`;
1885
+ const record = await worktrees.spawn({
1886
+ cwd: parent.cwd,
1887
+ sessionId: parent.sessionId
1888
+ }, {
1889
+ branch,
1890
+ name: `conversation ${reservationId.slice(0, 8)}`,
1891
+ reservationId
1892
+ }, { signal });
1893
+ const reservations = sessionService.reservations;
1894
+ if (reservations === void 0) throw new Error("Conversation reservations are unavailable.");
1895
+ const session = await reservations.complete(reservationId, parentSessionId);
1896
+ publishLifecycle(parent, record.repositoryRoot);
1897
+ return session;
1898
+ });
1899
+ const views = {
1900
+ homeDir: options.homeDir,
1901
+ sessionService
1902
+ };
1903
+ const latest = /* @__PURE__ */ new Map();
1904
+ const subscriptions = /* @__PURE__ */ new Map();
1905
+ const busy = /* @__PURE__ */ new Set();
1906
+ const generations = /* @__PURE__ */ new Map();
1907
+ const newGeneration = (sessionId) => {
1908
+ const generation = Symbol(sessionId);
1909
+ generations.set(sessionId, generation);
1910
+ return generation;
1911
+ };
1912
+ /** Republishes a session, skipping a frame that would say nothing new. */
1913
+ const publish = (scope, force) => {
1914
+ const previous = latest.get(scope.sessionId);
1915
+ const next = {
1916
+ worktrees: viewsFor(scope, views),
1917
+ pending: previous?.pending,
1918
+ error: previous?.error,
1919
+ errorTarget: previous?.errorTarget
1920
+ };
1921
+ if (!force && previous !== void 0 && sameList(previous.worktrees, next.worktrees) && previous.pending === next.pending && previous.error === next.error && previous.errorTarget === next.errorTarget) return;
1922
+ latest.set(scope.sessionId, next);
1923
+ host.publish(scope.sessionId, payloadOf(next));
1924
+ };
1925
+ const mark = (scope, pending, error, errorTarget) => {
1926
+ const previous = latest.get(scope.sessionId);
1927
+ latest.set(scope.sessionId, {
1928
+ worktrees: previous?.worktrees ?? viewsFor(scope, views),
1929
+ pending,
1930
+ error,
1931
+ errorTarget
1932
+ });
1933
+ publish(scope, true);
1934
+ };
1935
+ const run = async (scope, command, generation) => {
1936
+ const context = {
1937
+ cwd: scope.cwd,
1938
+ sessionId: scope.sessionId
1939
+ };
1940
+ const markCurrent = (pending, error, errorTarget) => {
1941
+ if (generations.get(scope.sessionId) !== generation) return;
1942
+ mark(scope, pending, error, errorTarget);
1943
+ };
1944
+ if (command.action === "create") {
1945
+ markCurrent(`creating ${command.branch}…`, void 0, void 0);
1946
+ const record = await worktrees.spawn(context, {
1947
+ branch: command.branch,
1948
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
1949
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
1950
+ }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
1951
+ if (generations.get(scope.sessionId) !== generation) return;
1952
+ publishLifecycle(scope, record.repositoryRoot);
1953
+ return;
1954
+ }
1955
+ markCurrent(`closing ${command.id}…`, void 0, void 0);
1956
+ const record = await worktrees.close(context, command.id, command.force ?? false);
1957
+ if (generations.get(scope.sessionId) !== generation) return;
1958
+ publishLifecycle(scope, record.repositoryRoot);
1959
+ };
1960
+ const source = {
1961
+ payloadFor(scope) {
1962
+ const state = latest.get(scope.sessionId);
1963
+ return state === void 0 ? void 0 : payloadOf(state);
1964
+ },
1965
+ sessionAdded(scope) {
1966
+ newGeneration(scope.sessionId);
1967
+ publish(scope, false);
1968
+ const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
1969
+ if (!isWorktreeLifecycleEvent(payload)) return;
1970
+ let sameRepository = false;
1971
+ try {
1972
+ sameRepository = registryFile(scope.cwd, options.homeDir) === registryFile(payload.repositoryRoot, options.homeDir);
1973
+ } catch {
1974
+ sameRepository = false;
1975
+ }
1976
+ if (sameRepository) publish(scope, false);
1977
+ });
1978
+ subscriptions.set(scope.sessionId, unsubscribe);
1979
+ },
1980
+ sessionRemoved(sessionId) {
1981
+ newGeneration(sessionId);
1982
+ subscriptions.get(sessionId)?.();
1983
+ subscriptions.delete(sessionId);
1984
+ latest.delete(sessionId);
1985
+ busy.delete(sessionId);
1986
+ },
1987
+ close() {
1988
+ unregisterWorktreeProvisioner?.();
1989
+ for (const unsubscribe of subscriptions.values()) unsubscribe();
1990
+ subscriptions.clear();
1991
+ latest.clear();
1992
+ busy.clear();
1993
+ generations.clear();
1994
+ }
1995
+ };
1996
+ receiveCommand = (scope, payload) => {
1997
+ const command = parseCommand(payload);
1998
+ if (command === void 0) return;
1999
+ if (busy.has(scope.sessionId)) return;
2000
+ const generation = generations.get(scope.sessionId);
2001
+ if (generation === void 0) return;
2002
+ busy.add(scope.sessionId);
2003
+ run(scope, command, generation).then(() => {
2004
+ if (generations.get(scope.sessionId) !== generation) return;
2005
+ mark(scope, void 0, void 0, void 0);
2006
+ }).catch((error) => {
2007
+ if (generations.get(scope.sessionId) !== generation) return;
2008
+ host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2009
+ mark(scope, void 0, failureText(error), errorTargetFor(command));
2010
+ }).finally(() => {
2011
+ if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2012
+ });
2013
+ };
2014
+ return source;
2015
+ },
2016
+ receive(scope, payload) {
2017
+ receiveCommand?.(scope, payload);
2018
+ }
2019
+ };
2020
+ }
2021
+ //#endregion
2022
+ //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2023
+ var git_worktrees_server_default = defineChannel(createWorktreesChannel);
2024
+ //#endregion
2025
+ //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2026
+ var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
2027
+ //#endregion
2028
+ //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2029
+ var tool_execution_end_server_default = defineHook((context) => context.root.hooks[0]);
2030
+ //#endregion
2031
+ //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGit.server.ts
2032
+ var poGit_server_default$1 = (context) => context.root.resources[0];
2033
+ //#endregion
2034
+ //#region src/extensions/workspaces/sessions/(backend)/resource/poGit.server.ts
2035
+ var poGit_server_default = defineResource(poGit_server_default$1);
2036
+ //#endregion
2037
+ //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGitReadme.server.ts
2038
+ var poGitReadme_server_default$1 = (context) => context.root.resources[2];
2039
+ //#endregion
2040
+ //#region src/extensions/workspaces/sessions/(backend)/resource/poGitReadme.server.ts
2041
+ var poGitReadme_server_default = defineResource(poGitReadme_server_default$1);
2042
+ //#endregion
2043
+ //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2044
+ var poUseGit_server_default$1 = (context) => context.root.resources[1];
2045
+ //#endregion
2046
+ //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2047
+ var poUseGit_server_default = defineResource(poUseGit_server_default$1);
2048
+ //#endregion
2049
+ //#region src/extensions/workspaces/sessions/(backend)/tool/runWorktree.server.ts
2050
+ var runWorktree_server_default = defineServerTool((context) => context.root.tool);
2051
+ //#endregion
2052
+ //#region generated/server.ts
2053
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
2054
+ const via = (identity, value) => value === void 0 ? void 0 : {
2055
+ ...identity,
2056
+ ...value
2057
+ };
2058
+ const facet = defineServerPlugin({
2059
+ name: "@agimon-ai/po-git",
2060
+ providerOverrides: composeServerProviderOverrides(root_server_default),
2061
+ global: (context) => ({
2062
+ get api() {
2063
+ return [at(route_server_default, context)];
2064
+ },
2065
+ get channels() {
2066
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2067
+ }
2068
+ }),
2069
+ workspace: (context) => ({
2070
+ get api() {
2071
+ return [at(route_server_default, context)];
2072
+ },
2073
+ get channels() {
2074
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2075
+ }
2076
+ }),
2077
+ session: async (context) => {
2078
+ const scopeSession = await root_server_default(context);
2079
+ const contextSession = {
2080
+ ...context,
2081
+ root: scopeSession.value
2082
+ };
2083
+ return {
2084
+ ...composeRootHooks(scopeSession),
2085
+ get api() {
2086
+ return [at(route_server_default, context)];
2087
+ },
2088
+ get channels() {
2089
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2090
+ },
2091
+ get hooks() {
2092
+ return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2093
+ },
2094
+ get resources() {
2095
+ return [
2096
+ at(poGit_server_default, contextSession),
2097
+ at(poGitReadme_server_default, contextSession),
2098
+ at(poUseGit_server_default, contextSession)
2099
+ ];
2100
+ },
2101
+ get tools() {
2102
+ return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2103
+ },
2104
+ services: [...scopeSession.services ?? []],
2105
+ get activities() {
2106
+ return [...scopeSession.activities ?? []];
2107
+ }
2108
+ };
2109
+ }
2110
+ });
2111
+ //#endregion
2112
+ export { facet as default, facet };
2113
+
2114
+ //# sourceMappingURL=server.mjs.map