@agimon-ai/po-git 0.0.0-alpha.21 → 0.0.0-alpha.210

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.
Files changed (38) hide show
  1. package/LICENSE +110 -149
  2. package/README.md +91 -21
  3. package/dist/apiContracts.cjs +78 -12
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +78 -12
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2300 -548
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1578 -513
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1537 -472
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +1791 -1376
  17. package/dist/extensions/web.mjs.map +1 -1
  18. package/dist/gitDependencies-D8bKxZSc.cjs +2690 -0
  19. package/dist/gitDependencies-D8bKxZSc.cjs.map +1 -0
  20. package/dist/gitDependencies-Delu4xip.mjs +2432 -0
  21. package/dist/gitDependencies-Delu4xip.mjs.map +1 -0
  22. package/dist/index.cjs +13 -22
  23. package/dist/index.d.mts +266 -14
  24. package/dist/index.d.mts.map +1 -1
  25. package/dist/index.mjs +3 -22
  26. package/dist/po-runtime-identity.json +1 -0
  27. package/llms.txt +3 -3
  28. package/locales/vi.json +325 -0
  29. package/locales/zh-CN.json +325 -0
  30. package/package.json +115 -22
  31. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  32. package/dist/index.cjs.map +0 -1
  33. package/dist/index.mjs.map +0 -1
  34. package/dist/worktreeOperations-Cd8Q12L4.mjs +0 -1064
  35. package/dist/worktreeOperations-Cd8Q12L4.mjs.map +0 -1
  36. package/dist/worktreeOperations-Dxs3txKL.cjs +0 -1220
  37. package/dist/worktreeOperations-Dxs3txKL.cjs.map +0 -1
  38. package/src/prompts/po-use-git/SKILL.md +0 -87
@@ -2,17 +2,93 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_worktreeOperations = require("../worktreeOperations-Dxs3txKL.cjs");
6
- let node_fs = require("node:fs");
7
- node_fs = require_worktreeOperations.__toESM(node_fs, 1);
8
- let node_os = require("node:os");
9
- node_os = require_worktreeOperations.__toESM(node_os, 1);
10
- let node_path = require("node:path");
11
- node_path = require_worktreeOperations.__toESM(node_path, 1);
5
+ const require_gitDependencies = require("../gitDependencies-D8bKxZSc.cjs");
6
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
7
+ let _agimon_ai_po_sparo = require("@agimon-ai/po-sparo");
12
8
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
9
+ let node_fs_promises = require("node:fs/promises");
10
+ node_fs_promises = require_gitDependencies.__toESM(node_fs_promises, 1);
11
+ let node_crypto = require("node:crypto");
12
+ let node_path = require("node:path");
13
+ node_path = require_gitDependencies.__toESM(node_path, 1);
14
+ let node_os = require("node:os");
15
+ node_os = require_gitDependencies.__toESM(node_os, 1);
16
+ let typebox_value = require("typebox/value");
17
+ let typebox = require("typebox");
18
+ let _agimon_ai_po_core_workflow = require("@agimon-ai/po-core/workflow");
13
19
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
20
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
14
21
  let _agimon_ai_po_session = require("@agimon-ai/po-session");
15
- let typebox = require("typebox");
22
+ let _agimon_ai_po_core_locale = require("@agimon-ai/po-core/locale");
23
+ let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
24
+ let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
25
+ //#region src/extensions/workspaces/(backend)/root.server.ts
26
+ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ context, signal }) => {
27
+ context.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE, _agimon_ai_po_core_platform.PO_FS_SERVICE], (scoped) => {
28
+ let shell;
29
+ let shellSignal = AbortSignal.abort(/* @__PURE__ */ new Error("Git engine requires the host shell (po/shell)."));
30
+ scoped.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
31
+ const lifetime = new AbortController();
32
+ shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
33
+ shellSignal = lifetime.signal;
34
+ return () => {
35
+ shell = void 0;
36
+ lifetime.abort(/* @__PURE__ */ new Error("Git engine host shell was disposed."));
37
+ };
38
+ });
39
+ const engine = (0, _agimon_ai_po_sparo.createGitEngineService)({
40
+ fs: (0, _agimon_ai_po_sparo.createPoFsAdapter)((0, _agimon_ai_po_core_platform.requirePoFs)(scoped), (operationSignal) => (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([signal, operationSignal]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT)),
41
+ exec: ({ environment }) => {
42
+ const env = Object.fromEntries(Object.entries(environment).filter((entry) => entry[1] !== void 0));
43
+ return { async run(command, args, options) {
44
+ if (shell === void 0) throw new Error("Git engine requires the host shell (po/shell).");
45
+ const operationSignal = AbortSignal.any([
46
+ signal,
47
+ shellSignal,
48
+ options.signal ?? signal,
49
+ AbortSignal.timeout(12e4)
50
+ ]);
51
+ operationSignal.throwIfAborted();
52
+ let stdout = "";
53
+ let stderr = "";
54
+ let bytes = 0;
55
+ const outputLimit = new AbortController();
56
+ const result = await shell.exec([command, ...args], {
57
+ cwd: options.cwd,
58
+ env,
59
+ inheritEnv: false,
60
+ timeout: 12e4,
61
+ onOutput(text, _context, info) {
62
+ bytes += new TextEncoder().encode(text).byteLength;
63
+ if (bytes > 4194304) {
64
+ outputLimit.abort(/* @__PURE__ */ new Error("Git engine command output exceeded 4 MiB."));
65
+ return;
66
+ }
67
+ if (info.stream === "stdout") stdout += text;
68
+ else stderr += text;
69
+ }
70
+ }, (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([operationSignal, outputLimit.signal]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
71
+ outputLimit.signal.throwIfAborted();
72
+ operationSignal.throwIfAborted();
73
+ if (!result.ok) throw result.error;
74
+ return {
75
+ exitCode: result.value.exitCode,
76
+ stdout,
77
+ stderr
78
+ };
79
+ } };
80
+ },
81
+ logger: {
82
+ info: (message) => console.info(message),
83
+ warn: (message) => console.warn(message),
84
+ error: (message) => console.error(message)
85
+ }
86
+ });
87
+ return (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(scoped).provide(require_gitDependencies.GIT_ENGINE_CONTRACT, engine);
88
+ });
89
+ return { value: void 0 };
90
+ });
91
+ //#endregion
16
92
  //#region src/schemas/runWorktreeTool.ts
17
93
  /**
18
94
  * The tool's action vocabulary.
@@ -29,7 +105,10 @@ const WORKTREE_ACTIONS = {
29
105
  merge: "merge",
30
106
  prune: "prune",
31
107
  send: "send",
32
- messages: "messages"
108
+ messages: "messages",
109
+ profiles: "profiles",
110
+ expand: "expand",
111
+ reapply: "reapply"
33
112
  };
34
113
  /**
35
114
  * Which fields each action accepts.
@@ -44,7 +123,8 @@ const WORKTREE_ACTION_FIELDS = {
44
123
  "branch",
45
124
  "baseRef",
46
125
  "task",
47
- "name"
126
+ "name",
127
+ "sparseProfile"
48
128
  ],
49
129
  close_worktree: [
50
130
  "action",
@@ -64,12 +144,20 @@ const WORKTREE_ACTION_FIELDS = {
64
144
  "id",
65
145
  "message"
66
146
  ],
67
- messages: ["action", "id"]
147
+ messages: ["action", "id"],
148
+ profiles: ["action", "baseRef"],
149
+ expand: [
150
+ "action",
151
+ "id",
152
+ "folders"
153
+ ],
154
+ reapply: ["action", "id"]
68
155
  };
69
156
  const SpawnParams = typebox.Type.Object({
70
157
  action: typebox.Type.Literal(WORKTREE_ACTIONS.spawn_worktree),
71
158
  branch: typebox.Type.String({ minLength: 1 }),
72
159
  baseRef: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
160
+ sparseProfile: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
73
161
  task: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
74
162
  name: typebox.Type.Optional(typebox.Type.String({ minLength: 1 }))
75
163
  }, { additionalProperties: false });
@@ -109,7 +197,20 @@ typebox.Type.Union([
109
197
  MergeParams,
110
198
  PruneParams,
111
199
  SendParams,
112
- MessagesParams
200
+ MessagesParams,
201
+ typebox.Type.Object({
202
+ action: typebox.Type.Literal("profiles"),
203
+ baseRef: typebox.Type.Optional(typebox.Type.String({ minLength: 1 }))
204
+ }, { additionalProperties: false }),
205
+ typebox.Type.Object({
206
+ action: typebox.Type.Literal("expand"),
207
+ id: typebox.Type.String({ minLength: 1 }),
208
+ folders: typebox.Type.Array(typebox.Type.String({ minLength: 1 }), { minItems: 1 })
209
+ }, { additionalProperties: false }),
210
+ typebox.Type.Object({
211
+ action: typebox.Type.Literal("reapply"),
212
+ id: typebox.Type.String({ minLength: 1 })
213
+ }, { additionalProperties: false })
113
214
  ]);
114
215
  /** The actions that accept `field`, so the declared docs cannot drift from the validator. */
115
216
  function acceptingActions(field) {
@@ -139,6 +240,14 @@ const RunWorktreeToolSchema = typebox.Type.Object({
139
240
  minLength: 1,
140
241
  description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions("baseRef")}.`
141
242
  })),
243
+ sparseProfile: typebox.Type.Optional(typebox.Type.String({
244
+ minLength: 1,
245
+ description: "Sparse checkout profile, independent of the launch profile."
246
+ })),
247
+ folders: typebox.Type.Optional(typebox.Type.Array(typebox.Type.String({ minLength: 1 }), {
248
+ minItems: 1,
249
+ description: "Relative cone folders for expand."
250
+ })),
142
251
  task: typebox.Type.Optional(typebox.Type.String({
143
252
  minLength: 1,
144
253
  description: `First message for the new session. Actions: ${acceptingActions("task")}.`
@@ -166,6 +275,9 @@ const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its
166
275
 
167
276
  Actions:
168
277
  - 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.
278
+ - profiles: list sparse checkout profiles at baseRef.
279
+ - expand: add folders to a sparse worktree. Requires 'id' and 'folders'.
280
+ - reapply: refresh a sparse worktree from HEAD. Requires 'id'.
169
281
  - close_worktree: stop a worktree's session and delete its checkout. Requires 'id'. Refuses a dirty tree unless 'force' is true.
170
282
  - list: every worktree for this repository, with status and relationship to the calling session.
171
283
  - status: one worktree, its relationship to the calling session, and its uncommitted files. Requires 'id'.
@@ -178,27 +290,29 @@ For a nested worktree session, use the record labelled 'child' in list to report
178
290
  Worktrees live outside the repository, under ~/.po/git/worktrees.`;
179
291
  /** Rejects calls that do not match one documented action shape. */
180
292
  function validateParams(input) {
181
- if (typeof input !== "object" || input === null || Array.isArray(input)) throw require_worktreeOperations.invalidRequest("run_worktree parameters must be an object.", "Call it with one documented action shape.");
293
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw require_gitDependencies.invalidRequest("run_worktree parameters must be an object.", "Call it with one documented action shape.");
182
294
  const record = input;
183
295
  const action = record.action;
184
- if (typeof action !== "string" || !IMPLEMENTED_ACTIONS.has(action)) throw require_worktreeOperations.invalidRequest(`Unknown action ${typeof action === "string" ? `'${action}'` : "value"}.`, `Use one of: ${[...IMPLEMENTED_ACTIONS].join(", ")}.`);
296
+ if (typeof action !== "string" || !IMPLEMENTED_ACTIONS.has(action)) throw require_gitDependencies.invalidRequest(`Unknown action ${typeof action === "string" ? `'${action}'` : "value"}.`, `Use one of: ${[...IMPLEMENTED_ACTIONS].join(", ")}.`);
185
297
  const allowed = WORKTREE_ACTION_FIELDS[action];
186
298
  const unexpected = Object.keys(record).filter((key) => !allowed.includes(key));
187
- if (unexpected.length > 0) throw require_worktreeOperations.invalidRequest(`action='${action}' does not accept: ${unexpected.join(", ")}.`, `Fields for '${action}': ${allowed.join(", ")}.`);
299
+ if (unexpected.length > 0) throw require_gitDependencies.invalidRequest(`action='${action}' does not accept: ${unexpected.join(", ")}.`, `Fields for '${action}': ${allowed.join(", ")}.`);
188
300
  for (const field of ["branch", "id"]) if (allowed.includes(field) && field in record) {
189
301
  const value = record[field];
190
- if (typeof value !== "string" || value.trim() === "") throw require_worktreeOperations.invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
302
+ if (typeof value !== "string" || value.trim() === "") throw require_gitDependencies.invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
191
303
  }
192
304
  for (const field of [
193
305
  "baseRef",
194
306
  "name",
195
307
  "task",
196
- "message"
197
- ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw require_worktreeOperations.invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
198
- for (const field of ["force", "dryRun"]) if (field in record && typeof record[field] !== "boolean") throw require_worktreeOperations.invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);
199
- if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw require_worktreeOperations.invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
200
- if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw require_worktreeOperations.invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
201
- 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 require_worktreeOperations.invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
308
+ "message",
309
+ "sparseProfile"
310
+ ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw require_gitDependencies.invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
311
+ if (action === "expand" && (!Array.isArray(record.folders) || record.folders.length === 0 || !record.folders.every((folder) => typeof folder === "string" && folder.trim() !== ""))) throw require_gitDependencies.invalidRequest("expand requires nonempty folders.", "Pass relative cone folders.");
312
+ for (const field of ["force", "dryRun"]) if (field in record && typeof record[field] !== "boolean") throw require_gitDependencies.invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);
313
+ if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw require_gitDependencies.invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
314
+ if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw require_gitDependencies.invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
315
+ if ((action === WORKTREE_ACTIONS.expand || action === WORKTREE_ACTIONS.reapply || 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 require_gitDependencies.invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
202
316
  return record;
203
317
  }
204
318
  function describe(record, sessionId) {
@@ -213,9 +327,31 @@ function text(...lines) {
213
327
  }
214
328
  async function executeRunWorktreeTool(params, operations, context, options = {}) {
215
329
  switch (params.action) {
330
+ case WORKTREE_ACTIONS.profiles: {
331
+ const profiles = await operations.profiles(context, params.baseRef, options);
332
+ return {
333
+ content: text(profiles.sparseProfiles?.join(", ") ?? "Sparse checkout is not configured."),
334
+ details: {
335
+ action: params.action,
336
+ ...profiles
337
+ }
338
+ };
339
+ }
340
+ case WORKTREE_ACTIONS.expand:
341
+ case WORKTREE_ACTIONS.reapply: {
342
+ const record = params.action === "expand" ? await operations.expand(context, params.id, params.folders, options) : await operations.reapply(context, params.id, options);
343
+ return {
344
+ content: text(`Worktree ${record.id} sparse checkout updated.`),
345
+ details: {
346
+ action: params.action,
347
+ records: [record]
348
+ }
349
+ };
350
+ }
216
351
  case WORKTREE_ACTIONS.spawn_worktree: {
217
352
  const record = await operations.spawn(context, {
218
353
  branch: params.branch,
354
+ ...params.sparseProfile === void 0 ? {} : { sparseProfile: params.sparseProfile },
219
355
  ...params.baseRef === void 0 ? {} : { baseRef: params.baseRef },
220
356
  ...params.name === void 0 ? {} : { name: params.name },
221
357
  ...params.task === void 0 ? {} : { task: params.task }
@@ -254,7 +390,8 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
254
390
  content: text(describe(record, context.sessionId), `Session: ${record.sessionId}`, dirtyFiles.length === 0 ? "Clean." : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(", ")}`),
255
391
  details: {
256
392
  action: params.action,
257
- records: [record]
393
+ records: [record],
394
+ dirtyFiles
258
395
  }
259
396
  };
260
397
  }
@@ -278,7 +415,10 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
278
415
  const waiting = await operations.messages(context, params.id);
279
416
  return {
280
417
  content: waiting.length === 0 ? text("No messages.") : text(`${String(waiting.length)} message(s):`, ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`)),
281
- details: { action: params.action }
418
+ details: {
419
+ action: params.action,
420
+ messages: waiting
421
+ }
282
422
  };
283
423
  }
284
424
  case WORKTREE_ACTIONS.prune: {
@@ -293,12 +433,579 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
293
433
  `Untracked directories, left alone: ${plan.untracked.length === 0 ? "none" : plan.untracked.join(", ")}`,
294
434
  ...plan.keptBranches.length === 0 ? [] : [`Branches kept, they hold commits: ${plan.keptBranches.join(", ")}`]
295
435
  ]),
296
- details: { action: params.action }
436
+ details: {
437
+ action: params.action,
438
+ plan
439
+ }
297
440
  };
298
441
  }
299
442
  }
300
443
  }
301
444
  //#endregion
445
+ //#region src/services/worktreeNamespace/index.ts
446
+ const DECLARATIONS = `type WorktreeStatus = 'spawning' | 'running' | 'closing' | 'orphaned';
447
+
448
+ interface Worktree {
449
+ id: string;
450
+ branch: string;
451
+ baseRef: string;
452
+ /** Absolute path of the checkout. Imported worktrees stay at their original path. */
453
+ path: string;
454
+ repositoryRoot: string;
455
+ /** The session running inside the worktree. */
456
+ sessionId: string;
457
+ parentSessionId?: string;
458
+ status: WorktreeStatus;
459
+ /** started confirms runner launch only; unconfirmed handoffs must not be blindly retried. */
460
+ setupStage?: 'none' | 'started' | 'failed' | 'unconfirmed';
461
+ createdAt: string;
462
+ sparseProfile?: string;
463
+ extraFolders?: string[];
464
+ sparseFingerprint?: string;
465
+ /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
466
+ relationship: 'parent' | 'child' | 'other';
467
+ }
468
+
469
+ interface WorktreeMessage {
470
+ worktreeId: string;
471
+ fromSessionId: string;
472
+ from: 'parent' | 'child';
473
+ text: string;
474
+ sentAt: string;
475
+ }
476
+
477
+ interface PrunePlan {
478
+ remove: Worktree[];
479
+ forget: Worktree[];
480
+ /** Kept because they hold uncommitted work. */
481
+ keptDirty: Worktree[];
482
+ untracked: string[];
483
+ /** Branches kept because they hold commits. */
484
+ keptBranches: string[];
485
+ }
486
+
487
+ declare const worktrees: {
488
+ /** Every worktree for this repository. */
489
+ list(): Promise<Worktree[]>;
490
+ /** One worktree and its uncommitted files. */
491
+ status(id: string): Promise<{ worktree: Worktree; dirtyFiles: string[] }>;
492
+ /**
493
+ * Create a worktree on a new branch and start a Po session in it, nested under this one. baseRef defaults to
494
+ * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
495
+ * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
496
+ */
497
+ spawn(request: { branch: string; baseRef?: string; name?: string; task?: string; sparseProfile?: string }): Promise<Worktree>;
498
+ /** Run a repository workflow in its own checkout. Retrying the same attemptId never recreates uncertain work. */
499
+ startWorkflow(request: { key: string; attemptId?: string; branch?: string; sparseProfile?: string; inputs?: Record<string, string> }): Promise<{ attemptId: string; worktreeId: string; sessionId: string; branch: string; runId?: string; admission: 'pending' | 'registered' }>;
500
+ profiles(options?: { baseRef?: string }): Promise<{ sparseProfiles?: string[]; defaultSparseProfile?: string }>;
501
+ expand(id: string, folders: string[]): Promise<Worktree>;
502
+ reapply(id: string): Promise<Worktree>;
503
+ /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
504
+ close(id: string, options?: { force?: boolean }): Promise<Worktree>;
505
+ /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
506
+ merge(id: string, options?: { message?: string }): Promise<Worktree>;
507
+ /** Remove orphaned worktrees. With dryRun, only return the plan. */
508
+ prune(options?: { dryRun?: boolean }): Promise<PrunePlan>;
509
+ /**
510
+ * Message the other side of a worktree. Use the record with relationship 'child' to report to your parent,
511
+ * and 'parent' to reach your own children. 'other' records are not communication edges.
512
+ */
513
+ send(id: string, message: string): Promise<void>;
514
+ /** Messages waiting for you from a worktree. */
515
+ messages(id: string): Promise<WorktreeMessage[]>;
516
+ };`;
517
+ const json = (value) => JSON.parse(JSON.stringify(value));
518
+ /** Git worktrees for code mode: the actions of `run_worktree` as methods, returning records instead of text. */
519
+ function createWorktreeNamespace(options) {
520
+ return {
521
+ name: "worktrees",
522
+ summary: "Create and manage Git worktree sessions, select or expand a sparse checkout, and start isolated repository workflows.",
523
+ declarations: DECLARATIONS,
524
+ bind(run) {
525
+ if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
526
+ let disposed = false;
527
+ run.onDispose(() => {
528
+ disposed = true;
529
+ });
530
+ const view = (record) => ({
531
+ ...record,
532
+ relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
533
+ });
534
+ /** One `run_worktree` action through the tool's own code, so the tool and the namespace cannot drift. */
535
+ const act = async (name, action, input = {}, target) => {
536
+ run.signal.throwIfAborted();
537
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
538
+ options.assertAvailable();
539
+ if (typeof input !== "object" || input === null || Array.isArray(input) || "action" in input) throw require_gitDependencies.invalidRequest(`Invalid options for worktrees.${name}.`, "Pass the documented fields without an action.");
540
+ const params = validateParams({
541
+ ...input,
542
+ ...target,
543
+ action
544
+ });
545
+ const context = {
546
+ cwd: options.execution.cwd,
547
+ sessionId: options.execution.sessionId
548
+ };
549
+ const started = Date.now();
550
+ try {
551
+ const result = await executeRunWorktreeTool(params, options.operations, context, { signal: run.signal });
552
+ options.assertAvailable();
553
+ run.record?.({
554
+ name: `worktrees.${name}`,
555
+ tool: RUN_WORKTREE_TOOL_NAME,
556
+ args: params,
557
+ ok: true,
558
+ ms: Date.now() - started,
559
+ result
560
+ });
561
+ return result;
562
+ } catch (error) {
563
+ run.record?.({
564
+ name: `worktrees.${name}`,
565
+ tool: RUN_WORKTREE_TOOL_NAME,
566
+ args: params,
567
+ ok: false,
568
+ ms: Date.now() - started,
569
+ error: error instanceof Error ? error.message : String(error)
570
+ });
571
+ throw error;
572
+ }
573
+ };
574
+ const record = (result) => view(result.details.records[0]);
575
+ const members = Object.create(null);
576
+ members.profiles = async (settings) => {
577
+ const { action: _action, ...profiles } = (await act("profiles", "profiles", settings)).details;
578
+ return json(profiles);
579
+ };
580
+ members.expand = async (id, folders) => json(record(await act("expand", "expand", {
581
+ id,
582
+ folders
583
+ })));
584
+ members.reapply = async (id) => json(record(await act("reapply", "reapply", { id })));
585
+ members.list = async () => json((await act("list", "list", {})).details.records.map(view));
586
+ members.status = async (id) => {
587
+ const { details } = await act("status", "status", { id });
588
+ return json({
589
+ worktree: view(details.records[0]),
590
+ dirtyFiles: details.dirtyFiles ?? []
591
+ });
592
+ };
593
+ members.spawn = async (request) => json(record(await act("spawn", "spawn_worktree", request)));
594
+ members.startWorkflow = async (request) => {
595
+ run.signal.throwIfAborted();
596
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
597
+ options.assertAvailable();
598
+ if (!(0, typebox_value.Check)(require_gitDependencies.StartWorktreeWorkflowSchema, request)) throw new Error("A repository workflow key and valid launch fields are required.");
599
+ const workflows = options.workflows?.();
600
+ if (!workflows) throw new Error("Isolated workflow admissions are unavailable in this session.");
601
+ const attemptId = request.attemptId ?? `git-${(0, node_crypto.randomUUID)()}`;
602
+ const started = await workflows.start({
603
+ attemptId,
604
+ definition: {
605
+ source: "repo",
606
+ key: request.key
607
+ },
608
+ ...request.branch === void 0 ? {} : { branch: request.branch },
609
+ ...request.sparseProfile === void 0 ? {} : { sparseProfile: request.sparseProfile },
610
+ ...request.inputs === void 0 ? {} : { overrides: { inputs: request.inputs } }
611
+ }, run.signal);
612
+ options.assertAvailable();
613
+ return json({
614
+ attemptId,
615
+ worktreeId: started.worktreeId,
616
+ sessionId: started.sessionId,
617
+ branch: started.branch,
618
+ admission: started.admission.state,
619
+ ...started.admission.state === "registered" ? { runId: started.admission.run.runId } : {}
620
+ });
621
+ };
622
+ members.close = async (id, settings) => json(record(await act("close", "close_worktree", settings, { id })));
623
+ members.merge = async (id, settings) => json(record(await act("merge", "merge", settings, { id })));
624
+ members.prune = async (settings) => {
625
+ const { plan } = (await act("prune", "prune", settings)).details;
626
+ return json({
627
+ ...plan,
628
+ remove: plan.remove.map(view),
629
+ forget: plan.forget.map(view),
630
+ keptDirty: plan.keptDirty.map(view)
631
+ });
632
+ };
633
+ members.send = async (id, message) => {
634
+ await act("send", "send", {
635
+ id,
636
+ message
637
+ });
638
+ };
639
+ members.messages = async (id) => json((await act("messages", "messages", { id })).details.messages);
640
+ return members;
641
+ }
642
+ };
643
+ }
644
+ //#endregion
645
+ //#region src/services/worktreeWorkflows/index.ts
646
+ var WorktreeWorkflowError = class extends Error {
647
+ code;
648
+ constructor(code, message, options) {
649
+ super(message, options);
650
+ this.code = code;
651
+ this.name = "WorktreeWorkflowError";
652
+ }
653
+ };
654
+ function canonical(value) {
655
+ if (Array.isArray(value)) return value.map(canonical);
656
+ if (value === null || typeof value !== "object") return value;
657
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
658
+ }
659
+ function defaultBranch(input) {
660
+ const safe = (value) => value.replace(/[^A-Za-z0-9._-]+/gu, "-").replace(/^[.-]+|[.-]+$/gu, "") || "run";
661
+ return `wf/${safe(node_path.default.basename(input.definition.key, node_path.default.extname(input.definition.key)))}/${safe(input.attemptId)}`;
662
+ }
663
+ function remoteBase(record) {
664
+ const ref = record.baseRef.replace(/^refs\/remotes\//u, "");
665
+ const slash = ref.indexOf("/");
666
+ if (slash < 1 || !record.baseCommit) return void 0;
667
+ const remote = ref.slice(0, slash);
668
+ const branch = ref.slice(slash + 1);
669
+ return require_gitDependencies.validRefName(remote) && require_gitDependencies.validRefName(branch) ? {
670
+ remote,
671
+ branch,
672
+ sha: record.baseCommit
673
+ } : void 0;
674
+ }
675
+ /** One coordinator over the existing admissions/runs services, never a second workflow engine. */
676
+ function createWorktreeWorkflows(options) {
677
+ if (!options.sessionId.trim()) throw new Error("A workflow launcher session is required.");
678
+ const context = {
679
+ cwd: options.cwd,
680
+ sessionId: options.sessionId
681
+ };
682
+ const watching = /* @__PURE__ */ new Map();
683
+ const inFlight = /* @__PURE__ */ new Map();
684
+ options.signal.addEventListener("abort", () => {
685
+ for (const stop of watching.values()) stop();
686
+ watching.clear();
687
+ }, { once: true });
688
+ const operation = (signal) => ({
689
+ env: options.environment,
690
+ signal: AbortSignal.any([options.signal, ...signal ? [signal] : []])
691
+ });
692
+ const store = async () => {
693
+ const root = await options.git.repositoryRoot(options.cwd);
694
+ if (!root) throw new WorktreeWorkflowError("not_started", "A repository checkout is required.");
695
+ return options.registry ? options.registry(root) : require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(root, options.homeDirectory, options.environment));
696
+ };
697
+ const mutate = async (fn, signal) => {
698
+ const registry = await store();
699
+ return registry.transaction(async () => {
700
+ const attempts = await registry.workflowAttempts();
701
+ const result = await fn(attempts);
702
+ await registry.replaceWorkflowAttempts(attempts);
703
+ return result;
704
+ }, operation(signal).signal);
705
+ };
706
+ const update = (attempt, signal) => mutate((attempts) => {
707
+ const index = attempts.findIndex((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === attempt.attemptId);
708
+ if (index < 0 || attempts[index].fingerprint !== attempt.fingerprint) throw new WorktreeWorkflowError("unknown", "The durable workflow intent changed.");
709
+ attempts[index] = structuredClone(attempt);
710
+ }, signal);
711
+ const ownRecords = async () => (await options.operations.list(context)).filter((record) => record.parentSessionId === options.sessionId && record.workflow);
712
+ const retain = async (record, reason) => {
713
+ await options.operations.linkWorkflow(context, record.id, {
714
+ ...record.workflow,
715
+ state: "retained",
716
+ reason
717
+ });
718
+ };
719
+ const settle = async (record, attempt, state) => {
720
+ try {
721
+ const admission = attempt.admission;
722
+ if (admission?.state !== "registered" || JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run)) || state.run.ownerSessionId !== record.sessionId) return;
723
+ const current = (await ownRecords()).find((entry) => entry.id === record.id);
724
+ if (!current || current.sessionId !== record.sessionId || current.path !== record.path || current.status !== "running" || current.workflow?.state !== "admitted" || current.workflow?.runId !== state.run.runId || current.workflow.admissionId !== admission.admissionId || current.workflow.attemptId !== attempt.attemptId || current.workflow.fingerprint !== attempt.fingerprint) return;
725
+ let reason;
726
+ let verifiedHead;
727
+ if (state.stage !== "completed" || state.outcome !== "success") reason = `The run ended ${state.outcome ?? state.stage}.`;
728
+ else if (await options.git.repositoryRoot(current.path) !== current.path || await options.git.currentBranch(current.path) !== current.branch || !(await options.git.listWorktreePaths(current.repositoryRoot)).includes(current.path)) reason = "The exact linked checkout could not be verified.";
729
+ else if ((await options.git.dirtyFiles(current.path)).length > 0) reason = "Uncommitted files remain.";
730
+ else {
731
+ const head = await options.git.revision(current.path, "HEAD", operation());
732
+ verifiedHead = head;
733
+ if (!current.baseCommit) reason = "The original commit is unknown.";
734
+ else if (head !== current.baseCommit) {
735
+ const base = remoteBase(current);
736
+ if (!base || await options.git.remoteBranchHead(current.path, base.remote, current.branch, operation()) !== head) reason = "Delivery of this exact branch HEAD could not be verified.";
737
+ }
738
+ }
739
+ if (reason) {
740
+ await retain(current, reason);
741
+ await update({
742
+ ...attempt,
743
+ state: "retained"
744
+ });
745
+ } else {
746
+ await options.operations.close(context, current.id, false, {
747
+ ...current.workflow,
748
+ sessionId: current.sessionId,
749
+ path: current.path,
750
+ head: verifiedHead
751
+ });
752
+ await update({
753
+ ...attempt,
754
+ state: "closed"
755
+ });
756
+ }
757
+ } catch (error) {
758
+ options.onError(error);
759
+ }
760
+ };
761
+ const watch = (record, attempt) => {
762
+ const admission = attempt.admission;
763
+ if (admission?.state !== "registered" || watching.has(record.id) || options.signal.aborted) return;
764
+ const runs = options.runs();
765
+ if (!runs) return;
766
+ let stopped = false;
767
+ let unsubscribe;
768
+ const stop = () => {
769
+ stopped = true;
770
+ unsubscribe?.();
771
+ watching.delete(record.id);
772
+ };
773
+ watching.set(record.id, stop);
774
+ unsubscribe = runs.subscribe(admission.run.runId, (state) => {
775
+ if (stopped || state.stage === "running") return;
776
+ if (JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run))) return;
777
+ stop();
778
+ settle(record, attempt, state);
779
+ });
780
+ if (stopped) unsubscribe();
781
+ };
782
+ const link = async (record, attempt, admission) => {
783
+ if (admission.attemptId !== attempt.attemptId || admission.state === "registered" && admission.run.ownerSessionId !== record.sessionId) throw new WorktreeWorkflowError("unknown", "The admission does not belong to this checkout session.");
784
+ if (record.workflow?.admissionId && record.workflow.admissionId !== admission.admissionId || record.workflow?.runId && (admission.state !== "registered" || record.workflow.runId !== admission.run.runId) || attempt.admission && attempt.admission.admissionId !== admission.admissionId) throw new WorktreeWorkflowError("unknown", "The recorded workflow admission identity changed. The checkout was kept.");
785
+ if (record.workflow?.state === "retained" || [
786
+ "retained",
787
+ "closed",
788
+ "rejected"
789
+ ].includes(attempt.state)) {
790
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "This rejected attempt remains retained.");
791
+ return {
792
+ worktreeId: record.id,
793
+ sessionId: record.sessionId,
794
+ branch: record.branch,
795
+ admission
796
+ };
797
+ }
798
+ const linked = {
799
+ attemptId: attempt.attemptId,
800
+ fingerprint: attempt.fingerprint,
801
+ state: admission.state === "rejected" ? "retained" : "admitted",
802
+ admissionId: admission.admissionId,
803
+ ...admission.state === "registered" ? { runId: admission.run.runId } : {},
804
+ ...admission.state === "rejected" ? { reason: `Admission rejected: ${admission.errors.join("; ")}` } : {}
805
+ };
806
+ await options.operations.linkWorkflow(context, record.id, linked);
807
+ const updated = {
808
+ ...attempt,
809
+ admission,
810
+ state: admission.state === "rejected" ? "rejected" : "admitted",
811
+ worktreeId: record.id,
812
+ sessionId: record.sessionId
813
+ };
814
+ await update(updated);
815
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "The workflow admission was rejected. The checkout was kept.");
816
+ watch({
817
+ ...record,
818
+ workflow: linked
819
+ }, updated);
820
+ return {
821
+ worktreeId: record.id,
822
+ sessionId: record.sessionId,
823
+ branch: record.branch,
824
+ admission
825
+ };
826
+ };
827
+ const start = async (input, branch, fingerprint, signal) => {
828
+ const admissions = options.admissions();
829
+ if (!admissions) throw new WorktreeWorkflowError("not_started", "Workflow admissions are unavailable.");
830
+ const records = await ownRecords();
831
+ const legacy = records.find((record) => record.workflow.attemptId === input.attemptId);
832
+ const { attempt, created } = await mutate((attempts) => {
833
+ let attempt = attempts.find((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === input.attemptId);
834
+ if (!attempt && legacy) {
835
+ attempt = {
836
+ attemptId: input.attemptId,
837
+ fingerprint: legacy.workflow.fingerprint,
838
+ launcherSessionId: options.sessionId,
839
+ branch: legacy.branch,
840
+ definition: input.definition,
841
+ createdAt: legacy.createdAt,
842
+ state: "spawned",
843
+ worktreeId: legacy.id,
844
+ sessionId: legacy.sessionId
845
+ };
846
+ attempts.push(attempt);
847
+ }
848
+ if (attempt) {
849
+ if (attempt.fingerprint !== fingerprint) throw new WorktreeWorkflowError("attempt_conflict", "This workflow attempt was started with different arguments.");
850
+ return {
851
+ attempt: structuredClone(attempt),
852
+ created: false
853
+ };
854
+ }
855
+ attempt = {
856
+ attemptId: input.attemptId,
857
+ fingerprint,
858
+ launcherSessionId: options.sessionId,
859
+ branch,
860
+ definition: input.definition,
861
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
862
+ state: "reserved"
863
+ };
864
+ attempts.push(attempt);
865
+ return {
866
+ attempt: structuredClone(attempt),
867
+ created: true
868
+ };
869
+ }, signal);
870
+ let record = records.find((entry) => entry.id === attempt.worktreeId) ?? legacy;
871
+ if (!created) {
872
+ if (!record || record.status === "orphaned") {
873
+ if (attempt.state === "rejected" && !record) throw new WorktreeWorkflowError("not_started", "This attempt was rejected before checkout creation. Use a new attempt identity after fixing it.");
874
+ if (attempt.state === "closed" && attempt.admission && attempt.worktreeId && attempt.sessionId) return {
875
+ worktreeId: attempt.worktreeId,
876
+ sessionId: attempt.sessionId,
877
+ branch: attempt.branch,
878
+ admission: attempt.admission
879
+ };
880
+ throw new WorktreeWorkflowError("unknown", "This attempt may have created work. Its checkout is absent or orphaned and will not be recreated.");
881
+ }
882
+ const admission = await admissions.read(input.attemptId);
883
+ if (!admission) throw new WorktreeWorkflowError("unknown", "This attempt has no authoritative admission outcome. Its checkout was kept.");
884
+ return link(record, attempt, admission);
885
+ }
886
+ let report;
887
+ try {
888
+ report = await admissions.validate({
889
+ kind: "launch",
890
+ definition: input.definition,
891
+ ...input.overrides ? { overrides: input.overrides } : {}
892
+ });
893
+ } catch (error) {
894
+ await update({
895
+ ...attempt,
896
+ state: "rejected"
897
+ }, signal);
898
+ throw new WorktreeWorkflowError("not_started", "Workflow validation failed before checkout creation.", { cause: error });
899
+ }
900
+ const frozen = input.overrides?.allocation;
901
+ const refusal = report.errors.length ? `The workflow is not valid: ${report.errors.map((issue) => issue.message).join("; ")}` : report.allocation === void 0 ? void 0 : frozen === void 0 ? "This role-bound workflow needs an allocation prepared before the checkout, and none was supplied." : JSON.stringify(canonical(report.allocation)) !== JSON.stringify(canonical(frozen)) ? "The workflow allocation changed since it was prepared." : void 0;
902
+ if (refusal) {
903
+ await update({
904
+ ...attempt,
905
+ state: "rejected"
906
+ }, signal);
907
+ throw new WorktreeWorkflowError("not_started", refusal);
908
+ }
909
+ operation(signal).signal.throwIfAborted();
910
+ try {
911
+ record = await options.operations.spawn(context, {
912
+ branch,
913
+ ...input.sparseProfile ? { sparseProfile: input.sparseProfile } : {}
914
+ }, {
915
+ workflow: {
916
+ attemptId: input.attemptId,
917
+ fingerprint
918
+ },
919
+ ...input.preset ? { preset: input.preset } : {},
920
+ signal: operation(signal).signal
921
+ });
922
+ await update({
923
+ ...attempt,
924
+ worktreeId: record.id,
925
+ sessionId: record.sessionId,
926
+ state: "spawned"
927
+ });
928
+ const base = remoteBase(record);
929
+ if (!base) throw new WorktreeWorkflowError("not_started", "The workflow base is not a verifiable remote branch. The checkout was kept.");
930
+ const pending = {
931
+ ...attempt,
932
+ worktreeId: record.id,
933
+ sessionId: record.sessionId,
934
+ state: "admitting"
935
+ };
936
+ await update(pending);
937
+ const admission = await admissions.launch(input.attemptId, input.definition, {
938
+ ...input.overrides,
939
+ env: {
940
+ ...input.overrides?.env,
941
+ SPARO_BASE_REMOTE: base.remote,
942
+ SPARO_BASE_BRANCH: base.branch,
943
+ SPARO_BASE_SHA: base.sha,
944
+ SPARO_BRANCH: record.branch,
945
+ PO_GIT_BASE_REMOTE: base.remote,
946
+ PO_GIT_BASE_BRANCH: base.branch,
947
+ PO_GIT_BASE_SHA: base.sha,
948
+ PO_GIT_BRANCH: record.branch
949
+ },
950
+ targetSessionId: record.sessionId
951
+ });
952
+ return await link(record, pending, admission);
953
+ } catch (error) {
954
+ if (error instanceof WorktreeWorkflowError) throw error;
955
+ throw new WorktreeWorkflowError("unknown", "The workflow launch outcome is uncertain. Inspect the saved attempt before retrying.", { cause: error });
956
+ }
957
+ };
958
+ return {
959
+ start(input, signal) {
960
+ options.signal.throwIfAborted();
961
+ signal?.throwIfAborted();
962
+ if (!input || typeof input.attemptId !== "string" || !input.attemptId.trim() || !(0, typebox_value.Check)(_agimon_ai_po_core_workflow.PoWorkflowDefinitionRefSchema, input.definition) || input.definition.source !== "repo" || input.sparseProfile !== void 0 && !require_gitDependencies.validSparseProfile(input.sparseProfile)) return Promise.reject(new WorktreeWorkflowError("not_started", "A valid repository workflow and attempt identity are required."));
963
+ const snapshot = structuredClone(input);
964
+ const branch = snapshot.branch ?? defaultBranch(snapshot);
965
+ if (!require_gitDependencies.validRefName(branch)) return Promise.reject(new WorktreeWorkflowError("not_started", "The workflow branch is invalid."));
966
+ const fingerprint = (0, node_crypto.createHash)("sha256").update(JSON.stringify(canonical({
967
+ definition: snapshot.definition,
968
+ branch,
969
+ profile: snapshot.sparseProfile,
970
+ preset: snapshot.preset,
971
+ overrides: snapshot.overrides
972
+ }))).digest("hex");
973
+ const existing = inFlight.get(snapshot.attemptId);
974
+ if (existing) return existing.fingerprint === fingerprint ? existing.promise : Promise.reject(new WorktreeWorkflowError("attempt_conflict", "This workflow attempt is already starting with different arguments."));
975
+ const promise = start(snapshot, branch, fingerprint, signal).finally(() => {
976
+ inFlight.delete(snapshot.attemptId);
977
+ });
978
+ inFlight.set(snapshot.attemptId, {
979
+ fingerprint,
980
+ promise
981
+ });
982
+ return promise;
983
+ },
984
+ async reconcile(signal) {
985
+ operation(signal).signal.throwIfAborted();
986
+ const admissions = options.admissions();
987
+ if (!admissions) return;
988
+ const records = await ownRecords();
989
+ const registry = await store();
990
+ const attempts = await registry.transaction(() => registry.workflowAttempts(), operation(signal).signal);
991
+ for (const attempt of attempts.filter((entry) => entry.launcherSessionId === options.sessionId && ![
992
+ "closed",
993
+ "rejected",
994
+ "retained"
995
+ ].includes(entry.state))) {
996
+ const record = records.find((entry) => entry.id === attempt.worktreeId || entry.workflow.attemptId === attempt.attemptId);
997
+ if (!record || record.status === "orphaned") continue;
998
+ try {
999
+ const admission = await admissions.read(attempt.attemptId);
1000
+ if (admission) await link(record, attempt, admission);
1001
+ } catch (error) {
1002
+ options.onError(error);
1003
+ }
1004
+ }
1005
+ }
1006
+ };
1007
+ }
1008
+ //#endregion
302
1009
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
303
1010
  function progressResult(action, label) {
304
1011
  return {
@@ -309,33 +1016,82 @@ function progressResult(action, label) {
309
1016
  details: { action }
310
1017
  };
311
1018
  }
312
- function createGitSession({ context, host: serverHost }) {
1019
+ /** Tools that only read, so the checkout cannot have moved under them. */
1020
+ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
1021
+ "read",
1022
+ "grep",
1023
+ "find",
1024
+ "ls",
1025
+ "discover",
1026
+ "load_skill"
1027
+ ]);
1028
+ async function createGitSession({ context, host: serverHost, agent, signal }) {
313
1029
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
314
1030
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
315
1031
  const sessionId = serverHost.context.sessionId;
316
1032
  const directEvents = serverHost.context.directEvents;
317
- const messageInbox = require_worktreeOperations.createWorktreeMessageInbox(directEvents, sessionId);
318
- const operations = require_worktreeOperations.createWorktreeOperations({
319
- git: require_worktreeOperations.createWorktreeGit(),
1033
+ const messageInbox = require_gitDependencies.createWorktreeMessageInbox(directEvents, sessionId);
1034
+ const setupReceiver = context.inject(["po/runner-launch"], (child) => {
1035
+ const runner = child.get("po/runner-launch");
1036
+ const cwd = serverHost.context.cwd;
1037
+ if (!runner || !cwd) return void 0;
1038
+ return require_gitDependencies.receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal);
1039
+ });
1040
+ const operations = require_gitDependencies.createWorktreeOperations({
1041
+ git: require_gitDependencies.createWorktreeGit(),
1042
+ ...require_gitDependencies.createGitOperationDependencies({
1043
+ context,
1044
+ host: serverHost,
1045
+ signal
1046
+ }),
320
1047
  sessionService: serverHost.context.sessionService,
321
1048
  messageInbox,
322
1049
  sessionDelivery: () => (0, _agimon_ai_po_session.readPoSessionDelivery)(context)
323
1050
  });
1051
+ const homeDirectory = serverHost.context.homeDirectory ?? serverHost.context.environment?.HOME;
1052
+ let workflows;
1053
+ const workflowProvider = context.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], async (scoped) => {
1054
+ if (!homeDirectory || !serverHost.context.cwd) return void 0;
1055
+ const lifetime = new AbortController();
1056
+ const service = createWorktreeWorkflows({
1057
+ sessionId,
1058
+ cwd: serverHost.context.cwd,
1059
+ homeDirectory,
1060
+ environment: serverHost.context.environment ?? {},
1061
+ signal: AbortSignal.any([signal, lifetime.signal]),
1062
+ operations,
1063
+ git: {
1064
+ ...require_gitDependencies.createWorktreeGit(),
1065
+ revision: require_gitDependencies.revision,
1066
+ remoteBranchHead: require_gitDependencies.remoteBranchHead
1067
+ },
1068
+ admissions: () => (0, _agimon_ai_po_core_workflow.readPoWorkflowAdmissionsService)(scoped),
1069
+ runs: () => (0, _agimon_ai_po_core_workflow.readPoWorkflowRunsService)(scoped),
1070
+ onError: (error) => serverHost.context.onNotice(`Workflow checkout retained (${error instanceof Error ? error.name : "unknown error"}).`)
1071
+ });
1072
+ const release = await (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(scoped).provide(require_gitDependencies.GIT_WORKFLOWS_CONTRACT, service);
1073
+ workflows = service;
1074
+ return async () => {
1075
+ if (workflows === service) workflows = void 0;
1076
+ lifetime.abort();
1077
+ await release();
1078
+ };
1079
+ });
1080
+ if (context.get(_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE) !== void 0) await workflowProvider.await();
1081
+ const workflowServices = context.inject([_agimon_ai_po_core_workflow.PO_WORKFLOW_ADMISSIONS_SERVICE, _agimon_ai_po_core_workflow.PO_WORKFLOW_RUNS_SERVICE], async () => {
1082
+ try {
1083
+ await workflows?.reconcile();
1084
+ } catch (error) {
1085
+ serverHost.context.onNotice(`Workflow reconciliation deferred (${error instanceof Error ? error.name : "unknown error"}).`);
1086
+ }
1087
+ });
324
1088
  const resources = [{
325
- when: {
326
- state: { "minor-mode": "help" },
327
- attribution: {
328
- kind: "minor",
329
- mode: "help"
330
- }
331
- },
332
- name: "po-git",
333
- kind: "context",
334
- read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "llms.txt")
335
- }, {
336
- name: "po-use-git",
1089
+ name: "codemode-how-to-git",
1090
+ description: "Hand a branch of work to a separate session in its own checkout, keeping the current checkout untouched. Use for a long refactor, a risky migration, or parallel features that touch the same files; not for parallel work on one branch.",
337
1091
  kind: "skill",
338
- read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/po-use-git/SKILL.md")
1092
+ pinned: true,
1093
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-git/SKILL.md"),
1094
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-git/SKILL.md")
339
1095
  }];
340
1096
  const tool = {
341
1097
  name: RUN_WORKTREE_TOOL_NAME,
@@ -353,21 +1109,51 @@ function createGitSession({ context, host: serverHost }) {
353
1109
  }
354
1110
  };
355
1111
  const changed = (_event, execution) => {
356
- directEvents.publish(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
1112
+ directEvents.publish(require_gitDependencies.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
357
1113
  };
1114
+ const hooks = [(0, _agimon_ai_po_core_extensionFile.defineHook)({
1115
+ name: "git-notify-checkout-after-tool",
1116
+ description: "Notify the session diff channel after tools that may change the checkout.",
1117
+ event: "tool_execution_end",
1118
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
1119
+ }), (0, _agimon_ai_po_core_extensionFile.defineHook)({
1120
+ name: "git-notify-checkout-when-settled",
1121
+ description: "Notify the session diff channel when the agent settles to refresh checkout changes.",
1122
+ event: "agent_settled",
1123
+ handle: changed
1124
+ })];
1125
+ if (agent) {
1126
+ const namespace = createWorktreeNamespace({
1127
+ operations,
1128
+ workflows: () => workflows,
1129
+ execution: agent.context,
1130
+ assertAvailable: () => {
1131
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
1132
+ }
1133
+ });
1134
+ context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (scoped) => {
1135
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(scoped);
1136
+ if (!codemode) return void 0;
1137
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
1138
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
1139
+ return () => {
1140
+ restriction.dispose();
1141
+ registration.dispose();
1142
+ };
1143
+ });
1144
+ }
358
1145
  return {
359
1146
  value: {
360
1147
  resources,
361
1148
  tool,
362
- hooks: [{
363
- event: "tool_execution_end",
364
- handle: changed
365
- }, {
366
- event: "agent_settled",
367
- handle: changed
368
- }]
1149
+ hooks
369
1150
  },
370
- onDispose: () => messageInbox.close()
1151
+ onDispose: async () => {
1152
+ await workflowServices.dispose();
1153
+ await workflowProvider.dispose();
1154
+ await setupReceiver.dispose();
1155
+ messageInbox.close();
1156
+ }
371
1157
  };
372
1158
  }
373
1159
  const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createGitSession);
@@ -403,15 +1189,15 @@ const BINARY_PROBE_BYTES = 8192;
403
1189
  const SHORT_SHA = 7;
404
1190
  const DEFAULT_BRANCHES = ["main", "master"];
405
1191
  async function read(cwd, args) {
406
- const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1192
+ const result = await require_gitDependencies.runGit(cwd, args, { timeout: require_gitDependencies.READ_TIMEOUT_MS });
407
1193
  return result.code === 0 ? result.stdout : void 0;
408
1194
  }
409
- async function readLine$1(cwd, args) {
1195
+ async function readLine(cwd, args) {
410
1196
  const out = (await read(cwd, args))?.trim();
411
1197
  return out === void 0 || out === "" ? void 0 : out;
412
1198
  }
413
1199
  async function commitExists(cwd, ref) {
414
- return await readLine$1(cwd, [
1200
+ return await readLine(cwd, [
415
1201
  "rev-parse",
416
1202
  "--verify",
417
1203
  "--quiet",
@@ -420,7 +1206,7 @@ async function commitExists(cwd, ref) {
420
1206
  }
421
1207
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
422
1208
  async function upstreamOf(cwd, ref) {
423
- return readLine$1(cwd, [
1209
+ return readLine(cwd, [
424
1210
  "rev-parse",
425
1211
  "--abbrev-ref",
426
1212
  "--symbolic-full-name",
@@ -429,13 +1215,13 @@ async function upstreamOf(cwd, ref) {
429
1215
  }
430
1216
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
431
1217
  async function resolveBaseRef(cwd, branch, recordedBaseRef) {
432
- if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
1218
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
433
1219
  "rev-parse",
434
1220
  "--verify",
435
1221
  "--quiet",
436
1222
  `refs/heads/${recordedBaseRef}`
437
1223
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
438
- const originHead = await readLine$1(cwd, [
1224
+ const originHead = await readLine(cwd, [
439
1225
  "symbolic-ref",
440
1226
  "--quiet",
441
1227
  "--short",
@@ -449,7 +1235,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
449
1235
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
450
1236
  const head = await commitExists(cwd, "HEAD");
451
1237
  if (ref !== void 0 && head) {
452
- const mergeBase = await readLine$1(cwd, [
1238
+ const mergeBase = await readLine(cwd, [
453
1239
  "merge-base",
454
1240
  ref,
455
1241
  "HEAD"
@@ -476,11 +1262,11 @@ const NAME_STATUS = {
476
1262
  T: "modified"
477
1263
  };
478
1264
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
479
- function untrackedLines(root, relPath) {
1265
+ async function untrackedLines(root, relPath) {
480
1266
  const absolute = node_path.default.join(root, relPath);
481
1267
  let stat;
482
1268
  try {
483
- stat = node_fs.default.lstatSync(absolute);
1269
+ stat = await node_fs_promises.default.lstat(absolute);
484
1270
  } catch {
485
1271
  return;
486
1272
  }
@@ -489,7 +1275,7 @@ function untrackedLines(root, relPath) {
489
1275
  binary: false
490
1276
  };
491
1277
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
492
- const content = node_fs.default.readFileSync(absolute);
1278
+ const content = await node_fs_promises.default.readFile(absolute);
493
1279
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
494
1280
  lines: 0,
495
1281
  binary: true
@@ -561,9 +1347,9 @@ function parseUnifiedDiff(diff) {
561
1347
  function createBranchDiff() {
562
1348
  return {
563
1349
  async review(cwd, options = {}) {
564
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1350
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
565
1351
  if (root === void 0) return void 0;
566
- const branch = await readLine$1(root, [
1352
+ const branch = await readLine(root, [
567
1353
  "symbolic-ref",
568
1354
  "--quiet",
569
1355
  "--short",
@@ -612,8 +1398,8 @@ function createBranchDiff() {
612
1398
  "--exclude-standard",
613
1399
  "-z"
614
1400
  ]));
615
- untracked.forEach((relPath, index) => {
616
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
1401
+ for (const [index, relPath] of untracked.entries()) {
1402
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
617
1403
  entries.push({
618
1404
  path: relPath,
619
1405
  status: "untracked",
@@ -621,22 +1407,24 @@ function createBranchDiff() {
621
1407
  removed: 0,
622
1408
  ...counted?.binary ? { binary: true } : {}
623
1409
  });
624
- });
1410
+ }
625
1411
  entries.sort((left, right) => left.path.localeCompare(right.path));
626
1412
  const conflicts = [...unmerged];
627
- const rebasing = [await readLine$1(root, [
1413
+ const rebaseMerge = await readLine(root, [
628
1414
  "rev-parse",
629
1415
  "--git-path",
630
1416
  "rebase-merge"
631
- ]), await readLine$1(root, [
1417
+ ]);
1418
+ const rebaseApply = await readLine(root, [
632
1419
  "rev-parse",
633
1420
  "--git-path",
634
1421
  "rebase-apply"
635
- ])].some((gitPath) => gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath)));
1422
+ ]);
1423
+ const rebasing = (await Promise.all([rebaseMerge, rebaseApply].map(async (gitPath) => gitPath === void 0 ? false : node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)))).some(Boolean);
636
1424
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
637
1425
  let upstream;
638
1426
  if (upstreamRef !== void 0) {
639
- const [behind, ahead] = (await readLine$1(root, [
1427
+ const [behind, ahead] = (await readLine(root, [
640
1428
  "rev-list",
641
1429
  "--left-right",
642
1430
  "--count",
@@ -677,7 +1465,7 @@ function createBranchDiff() {
677
1465
  if (entry === void 0) throw new Error("That path is not in this review.");
678
1466
  if (entry.status === "untracked") {
679
1467
  const absolute = node_path.default.join(review.root, entry.path);
680
- const stat = node_fs.default.lstatSync(absolute);
1468
+ const stat = await node_fs_promises.default.lstat(absolute);
681
1469
  if (stat.isSymbolicLink()) return {
682
1470
  path: entry.path,
683
1471
  hunks: [{
@@ -685,7 +1473,7 @@ function createBranchDiff() {
685
1473
  rows: [{
686
1474
  marker: "+",
687
1475
  line: 1,
688
- content: node_fs.default.readlinkSync(absolute)
1476
+ content: await node_fs_promises.default.readlink(absolute)
689
1477
  }]
690
1478
  }]
691
1479
  };
@@ -694,7 +1482,7 @@ function createBranchDiff() {
694
1482
  hunks: [],
695
1483
  tooLarge: true
696
1484
  };
697
- const content = node_fs.default.readFileSync(absolute);
1485
+ const content = await node_fs_promises.default.readFile(absolute);
698
1486
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
699
1487
  path: entry.path,
700
1488
  hunks: [],
@@ -719,7 +1507,7 @@ function createBranchDiff() {
719
1507
  }]
720
1508
  };
721
1509
  }
722
- const result = await require_worktreeOperations.runGit(review.root, [
1510
+ const result = await require_gitDependencies.runGit(review.root, [
723
1511
  "diff",
724
1512
  "-U3",
725
1513
  "--no-color",
@@ -730,7 +1518,7 @@ function createBranchDiff() {
730
1518
  "--",
731
1519
  `:(top,literal)${entry.path}`
732
1520
  ], {
733
- timeout: require_worktreeOperations.READ_TIMEOUT_MS,
1521
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
734
1522
  maxBuffer: MAX_FILE_BYTES
735
1523
  });
736
1524
  if (result.overflow) return {
@@ -783,7 +1571,6 @@ const LOOSE_BITS = 63;
783
1571
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
784
1572
  const MAX_USERNAME = 256;
785
1573
  const MAX_TOKEN = 4096;
786
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
787
1574
  /** Environment that would make git log or skip what this module relies on. */
788
1575
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
789
1576
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -811,9 +1598,9 @@ function isRecord(value) {
811
1598
  return typeof value === "object" && value !== null && !Array.isArray(value);
812
1599
  }
813
1600
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
814
- function workspaceKey(workspaceRoot) {
1601
+ async function workspaceKey(workspaceRoot) {
815
1602
  try {
816
- return node_fs.default.realpathSync(workspaceRoot);
1603
+ return await node_fs_promises.default.realpath(workspaceRoot);
817
1604
  } catch {
818
1605
  return node_path.default.resolve(workspaceRoot);
819
1606
  }
@@ -862,21 +1649,21 @@ function publicView(config) {
862
1649
  * the saved one, and only for the same host: a token never follows a host it
863
1650
  * was not entered for.
864
1651
  */
865
- function parseGitAuthSave(request, current, homeDir) {
866
- if (!isRecord(request)) throw require_worktreeOperations.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
1652
+ async function parseGitAuthSave(request, current, homeDir) {
1653
+ if (!isRecord(request)) throw require_gitDependencies.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
867
1654
  if (request.method === "none") return { method: "none" };
868
1655
  if (request.method === "ssh") {
869
1656
  if (request.keyPath === void 0 || request.keyPath === "") return { method: "ssh" };
870
- if (typeof request.keyPath !== "string" || hasControl(request.keyPath)) throw require_worktreeOperations.invalidRequest("The key path is not a plain path.", "Give the key as an absolute path or one under ~/.");
1657
+ if (typeof request.keyPath !== "string" || hasControl(request.keyPath)) throw require_gitDependencies.invalidRequest("The key path is not a plain path.", "Give the key as an absolute path or one under ~/.");
871
1658
  const keyPath = request.keyPath.trim();
872
- if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw require_worktreeOperations.invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
1659
+ if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw require_gitDependencies.invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
873
1660
  let isFile = false;
874
1661
  try {
875
- isFile = node_fs.default.statSync(expandHome(keyPath, homeDir)).isFile();
1662
+ isFile = (await node_fs_promises.default.stat(expandHome(keyPath, homeDir))).isFile();
876
1663
  } catch {
877
1664
  isFile = false;
878
1665
  }
879
- if (!isFile) throw require_worktreeOperations.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
1666
+ if (!isFile) throw require_gitDependencies.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
880
1667
  return {
881
1668
  method: "ssh",
882
1669
  keyPath
@@ -884,11 +1671,11 @@ function parseGitAuthSave(request, current, homeDir) {
884
1671
  }
885
1672
  if (request.method === "https") {
886
1673
  const host = typeof request.host === "string" ? request.host.trim().toLowerCase() : "";
887
- if (!HOST_PATTERN.test(host)) throw require_worktreeOperations.invalidRequest("The host is not a host name.", "Use a host like github.com, with an optional :port.");
1674
+ if (!HOST_PATTERN.test(host)) throw require_gitDependencies.invalidRequest("The host is not a host name.", "Use a host like github.com, with an optional :port.");
888
1675
  const username = typeof request.username === "string" ? request.username.trim() : "";
889
- if (username === "" || username.length > MAX_USERNAME || hasControl(username)) throw require_worktreeOperations.invalidRequest("The username is empty or not plain text.", "Enter the username the host knows you by.");
1676
+ if (username === "" || username.length > MAX_USERNAME || hasControl(username)) throw require_gitDependencies.invalidRequest("The username is empty or not plain text.", "Enter the username the host knows you by.");
890
1677
  if (request.token !== void 0 && request.token !== "") {
891
- if (typeof request.token !== "string" || request.token.length > MAX_TOKEN || hasControl(request.token)) throw require_worktreeOperations.invalidRequest("The token is not plain text.", "Paste the token again without line breaks.");
1678
+ if (typeof request.token !== "string" || request.token.length > MAX_TOKEN || hasControl(request.token)) throw require_gitDependencies.invalidRequest("The token is not plain text.", "Paste the token again without line breaks.");
892
1679
  return {
893
1680
  method: "https",
894
1681
  host,
@@ -902,21 +1689,21 @@ function parseGitAuthSave(request, current, homeDir) {
902
1689
  username,
903
1690
  token: current.token
904
1691
  };
905
- throw require_worktreeOperations.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.");
1692
+ throw require_gitDependencies.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.");
906
1693
  }
907
- throw require_worktreeOperations.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
1694
+ throw require_gitDependencies.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
908
1695
  }
909
1696
  /** Tightens a file or folder something left readable by group or others. */
910
- function tighten(target, mode) {
1697
+ async function tighten(target, mode) {
911
1698
  try {
912
- if ((node_fs.default.statSync(target).mode & LOOSE_BITS) !== 0) node_fs.default.chmodSync(target, mode);
1699
+ if (((await node_fs_promises.default.stat(target)).mode & LOOSE_BITS) !== 0) await node_fs_promises.default.chmod(target, mode);
913
1700
  } catch {}
914
1701
  }
915
- function createGitAuthStore(homeDir = node_os.default.homedir()) {
916
- const file = require_worktreeOperations.credentialsFile(homeDir);
917
- const readFile = () => {
918
- tighten(file, OWNER_ONLY_FILE);
919
- const raw = require_worktreeOperations.readJson(file);
1702
+ function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {}) {
1703
+ const file = require_gitDependencies.credentialsFile(homeDir, environment);
1704
+ const readFile = async () => {
1705
+ await tighten(file, OWNER_ONLY_FILE);
1706
+ const raw = await require_gitDependencies.readJson(file);
920
1707
  const workspaces = {};
921
1708
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
922
1709
  const config = parseConfig(value);
@@ -927,28 +1714,28 @@ function createGitAuthStore(homeDir = node_os.default.homedir()) {
927
1714
  workspaces
928
1715
  };
929
1716
  };
930
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1717
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
931
1718
  return {
932
1719
  read,
933
- view: (workspaceRoot) => publicView(read(workspaceRoot)),
934
- save(workspaceRoot, request) {
935
- const key = workspaceKey(workspaceRoot);
936
- const current = readFile();
937
- const next = parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
938
- const root = require_worktreeOperations.poGitRoot(homeDir);
939
- node_fs.default.mkdirSync(root, {
1720
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1721
+ async save(workspaceRoot, request) {
1722
+ const key = await workspaceKey(workspaceRoot);
1723
+ const current = await readFile();
1724
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1725
+ const root = require_gitDependencies.poGitRoot(homeDir, environment);
1726
+ await node_fs_promises.default.mkdir(root, {
940
1727
  recursive: true,
941
1728
  mode: OWNER_ONLY_DIRECTORY
942
1729
  });
943
- node_fs.default.chmodSync(root, OWNER_ONLY_DIRECTORY);
1730
+ await node_fs_promises.default.chmod(root, OWNER_ONLY_DIRECTORY);
944
1731
  const workspaces = { ...current.workspaces };
945
1732
  if (next.method === "none") delete workspaces[key];
946
1733
  else workspaces[key] = next;
947
- require_worktreeOperations.writeJsonAtomic(file, {
1734
+ await require_gitDependencies.writeJsonAtomic(file, {
948
1735
  version: 1,
949
1736
  workspaces
950
1737
  });
951
- node_fs.default.chmodSync(file, OWNER_ONLY_FILE);
1738
+ await node_fs_promises.default.chmod(file, OWNER_ONLY_FILE);
952
1739
  return publicView(next);
953
1740
  }
954
1741
  };
@@ -1047,252 +1834,14 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1047
1834
  };
1048
1835
  }
1049
1836
  //#endregion
1050
- //#region src/services/newSessionRequest/index.ts
1051
- const MAX_NAME_LENGTH = 120;
1052
- /** Trimmed text, undefined when absent or blank, false when not text at all. */
1053
- function optionalText(value) {
1054
- if (value === void 0) return void 0;
1055
- if (typeof value !== "string") return false;
1056
- const trimmed = value.trim();
1057
- return trimmed === "" ? void 0 : trimmed;
1058
- }
1059
- /**
1060
- * Validates a new-session dialog request for a worktree session. Every ref is
1061
- * checked here, before it can reach git as a positional argument.
1062
- */
1063
- function newSessionRequest(body) {
1064
- if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
1065
- const record = body;
1066
- const branch = optionalText(record.branch);
1067
- if (branch === void 0 || branch === false || !require_worktreeOperations.validRefName(branch)) return { error: "A valid branch name is required." };
1068
- const name = optionalText(record.name);
1069
- 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.` };
1070
- const named = name === void 0 ? {} : { name };
1071
- if (record.mode === "existing-branch") {
1072
- const remote = optionalText(record.remote);
1073
- if (remote === false || remote !== void 0 && !require_worktreeOperations.validRefName(remote)) return { error: "That remote name is not valid." };
1074
- return {
1075
- mode: "existing-branch",
1076
- branch,
1077
- ...remote === void 0 ? {} : { remote },
1078
- ...named
1079
- };
1080
- }
1081
- if (record.mode === "new-branch") {
1082
- const baseRef = optionalText(record.baseRef);
1083
- if (baseRef === false || baseRef !== void 0 && !require_worktreeOperations.validRefName(baseRef)) return { error: "That base branch is not valid." };
1084
- return {
1085
- mode: "new-branch",
1086
- branch,
1087
- ...baseRef === void 0 ? {} : { baseRef },
1088
- ...named
1089
- };
1090
- }
1091
- return { error: "The mode must be existing-branch or new-branch." };
1092
- }
1093
- //#endregion
1094
- //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1095
- /**
1096
- * The worktree surface the cockpit panel calls.
1097
- *
1098
- * Hub-scoped because worktrees are a property of a repository, not of one
1099
- * session: the panel lists and creates them whether or not the session that
1100
- * made them is focused, and a session-scoped API would disappear with it.
1101
- *
1102
- * The panel names a repository by the hub's opaque id and never by path.
1103
- * `resolveRepository` turns that into an admitted root, so a browser cannot
1104
- * point this at a directory the cockpit was never given.
1105
- */
1106
- function badRequest(message) {
1107
- return Response.json({ error: message }, { status: 400 });
1108
- }
1109
- function failed(error) {
1110
- if (error instanceof require_worktreeOperations.PoGitExpectedError) return Response.json({
1111
- error: error.message,
1112
- code: error.code
1113
- }, { status: error.retryable ? 503 : 409 });
1114
- return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1115
- }
1116
- //#endregion
1117
- //#region src/extensions/(backend)/api/git/route.server.ts
1118
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)({
1119
- basePath: "git",
1120
- start(context) {
1121
- if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1122
- const directEvents = context.directEvents;
1123
- const publishLifecycle = (sessionId, repositoryRoot) => {
1124
- directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1125
- version: 1,
1126
- repositoryRoot
1127
- });
1128
- };
1129
- const git = require_worktreeOperations.createWorktreeGit();
1130
- const operations = require_worktreeOperations.createWorktreeOperations({
1131
- git,
1132
- sessionService: context.sessionService,
1133
- ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory }
1134
- });
1135
- /**
1136
- * The new-session dialog's routes: the workspace's branches, and a top-level
1137
- * worktree session on one. Workspace-mounted only, and always rooted at the
1138
- * mount's own workspace, so a request can never name another directory.
1139
- */
1140
- const newSession = async (request, url) => {
1141
- const isBranches = request.method === "GET" && url.pathname === "/branches";
1142
- const isCreate = request.method === "POST" && url.pathname === "/sessions";
1143
- if (!isBranches && !isCreate) return void 0;
1144
- const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1145
- if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1146
- if (isBranches) {
1147
- const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1148
- const branches = repositoryRoot === void 0 ? {
1149
- repository: false,
1150
- local: [],
1151
- remote: []
1152
- } : {
1153
- repository: true,
1154
- ...await git.listBranches(repositoryRoot)
1155
- };
1156
- return Response.json(branches);
1157
- }
1158
- const parsed = newSessionRequest(await request.json().catch(() => void 0));
1159
- if ("error" in parsed) return badRequest(parsed.error);
1160
- const record = await operations.spawn({ cwd: workspaceRoot }, {
1161
- branch: parsed.branch,
1162
- checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1163
- ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1164
- ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1165
- ...parsed.name === void 0 ? {} : { name: parsed.name }
1166
- });
1167
- publishLifecycle(record.sessionId, record.repositoryRoot);
1168
- const created = {
1169
- sessionId: record.sessionId,
1170
- worktreeId: record.id
1171
- };
1172
- return Response.json(created, { status: 201 });
1173
- };
1174
- /** The admitted root for a request, or a response explaining why not. */
1175
- const rootOf = (url) => {
1176
- const repositoryId = url.searchParams.get("repositoryId");
1177
- if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1178
- const root = context.resolveRepository?.(repositoryId);
1179
- if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1180
- return root;
1181
- };
1182
- const homeDir = context.homeDirectory ?? node_os.default.homedir();
1183
- const gitAuth = createGitAuthStore(homeDir);
1184
- const branchDiff = createBranchDiff();
1185
- const pendingReviews = /* @__PURE__ */ new Map();
1186
- /**
1187
- * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1188
- * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1189
- * The view never carries the token.
1190
- */
1191
- const auth = async (request, url) => {
1192
- if (url.pathname !== "/auth") return void 0;
1193
- if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1194
- if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1195
- const root = rootOf(url);
1196
- if (root instanceof Response) return root;
1197
- if (request.method === "GET") return Response.json(gitAuth.view(root));
1198
- try {
1199
- return Response.json(gitAuth.save(root, await request.json().catch(() => void 0)));
1200
- } catch (error) {
1201
- if (error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "invalid_request") {
1202
- const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1203
- return Response.json({
1204
- error: text,
1205
- code: error.code
1206
- }, { status: 400 });
1207
- }
1208
- throw error;
1209
- }
1210
- };
1211
- /**
1212
- * The session's change against its base. Session mounts only, rooted at the
1213
- * session's own checkout; a file is served only when it is in the change set
1214
- * computed for the request. Overlapping requests share an in-flight snapshot.
1215
- */
1216
- const review = async (request, url) => {
1217
- if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1218
- const cwd = context.scope === "session" ? context.cwd : void 0;
1219
- if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1220
- if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1221
- let recordedBaseRef;
1222
- try {
1223
- recordedBaseRef = require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(cwd, homeDir)).list().find((record) => record.sessionId === context.sessionId)?.baseRef;
1224
- } catch {
1225
- recordedBaseRef = void 0;
1226
- }
1227
- const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1228
- let pending = pendingReviews.get(key);
1229
- if (pending === void 0) {
1230
- pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1231
- pendingReviews.set(key, pending);
1232
- }
1233
- const result = await pending;
1234
- if (url.pathname === "/review") return Response.json(result?.summary ?? {
1235
- repository: false,
1236
- files: []
1237
- });
1238
- const filePath = url.searchParams.get("path") ?? "";
1239
- 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 });
1240
- return Response.json(await branchDiff.fileDiff(result, filePath));
1241
- };
1242
- return {
1243
- async fetch(request) {
1244
- const url = new URL(request.url);
1245
- try {
1246
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1247
- if (answered !== void 0) return answered;
1248
- } catch (error) {
1249
- context.onNotice(`git request failed: ${error.name}`);
1250
- return failed(error);
1251
- }
1252
- const root = rootOf(url);
1253
- if (root instanceof Response) return root;
1254
- const callerContext = {
1255
- cwd: root,
1256
- sessionId: url.searchParams.get("sessionId") ?? ""
1257
- };
1258
- 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.");
1259
- try {
1260
- if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1261
- if (request.method === "POST" && url.pathname === "/worktrees") {
1262
- const body = await request.json();
1263
- if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1264
- const record = await operations.spawn(callerContext, {
1265
- branch: body.branch,
1266
- ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1267
- ...body.name === void 0 ? {} : { name: body.name }
1268
- });
1269
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1270
- return Response.json({ worktree: record }, { status: 201 });
1271
- }
1272
- const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1273
- if (request.method === "DELETE" && closing) {
1274
- const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1275
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1276
- return Response.json({ worktree: record });
1277
- }
1278
- return Response.json({ error: "No such worktree route." }, { status: 404 });
1279
- } catch (error) {
1280
- context.onNotice(`worktree request failed: ${error.name}`);
1281
- return failed(error);
1282
- }
1283
- },
1284
- close() {}
1285
- };
1286
- }
1287
- });
1288
- //#endregion
1289
1837
  //#region src/services/gitFailure/index.ts
1838
+ const english = (_key, fallback, vars) => (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars);
1290
1839
  const RULES = [
1291
1840
  {
1292
1841
  code: "host_key_changed",
1293
1842
  phrases: ["remote host identification has changed"],
1294
- message: "The remote's SSH host key changed since this machine last saw it.",
1295
- recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1843
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1844
+ recovery: (t) => t("git.failure.host_key_changed.recovery", "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal."),
1296
1845
  retryable: false
1297
1846
  },
1298
1847
  {
@@ -1302,8 +1851,8 @@ const RULES = [
1302
1851
  "no ed25519 host key is known",
1303
1852
  "no rsa host key is known"
1304
1853
  ],
1305
- message: "This machine does not trust the remote's SSH host key yet.",
1306
- recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1854
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1855
+ recovery: (t) => t("git.failure.host_key_unknown.recovery", "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again."),
1307
1856
  retryable: false
1308
1857
  },
1309
1858
  {
@@ -1320,15 +1869,15 @@ const RULES = [
1320
1869
  "unprotected private key",
1321
1870
  "invalid format"
1322
1871
  ],
1323
- message: "The remote refused the credentials.",
1324
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1872
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1873
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1325
1874
  retryable: false
1326
1875
  },
1327
1876
  {
1328
1877
  code: "repository_not_found",
1329
1878
  phrases: ["repository not found", "does not appear to be a git repository"],
1330
- message: "The remote repository was not found, or these credentials cannot see it.",
1331
- recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1879
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1880
+ recovery: (t) => t("git.failure.repository_not_found.recovery", "Check the remote URL and that the credentials have access. Open settings, then repository, then git remote."),
1332
1881
  retryable: false
1333
1882
  },
1334
1883
  {
@@ -1341,22 +1890,22 @@ const RULES = [
1341
1890
  "unable to access",
1342
1891
  "network is unreachable"
1343
1892
  ],
1344
- message: "The remote could not be reached.",
1345
- recovery: "Check the network and the remote URL, then try again.",
1893
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1894
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1346
1895
  retryable: true
1347
1896
  },
1348
1897
  {
1349
1898
  code: "push_lease_rejected",
1350
1899
  phrases: ["(stale info)"],
1351
- message: "The remote branch moved since your last fetch, so the force push was refused.",
1352
- recovery: "Pull to see the new commits, then decide whether to push again.",
1900
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1901
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1353
1902
  retryable: false
1354
1903
  },
1355
1904
  {
1356
1905
  code: "push_needs_force",
1357
1906
  phrases: ["(non-fast-forward)", "(fetch first)"],
1358
- message: "The remote branch has commits yours replaced, usually after a rebase.",
1359
- recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1907
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1908
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1360
1909
  retryable: false
1361
1910
  },
1362
1911
  {
@@ -1367,18 +1916,21 @@ const RULES = [
1367
1916
  "would be overwritten",
1368
1917
  "your index contains uncommitted changes"
1369
1918
  ],
1370
- message: "There are uncommitted changes in the way.",
1371
- recovery: "Commit or stash your changes first.",
1919
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1920
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1372
1921
  retryable: false
1373
1922
  }
1374
1923
  ];
1375
- function classifyGitFailure(operation, result, mismatch) {
1376
- if (result.timedOut) return new require_worktreeOperations.PoGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1924
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1925
+ if (result.timedOut) return new require_gitDependencies.PoGitExpectedError("git_timeout", t("git.failure.timeout", "git {operation} took too long and was stopped.", { operation }), true, t("git.failure.timeoutRecovery", "Check the network, then try again."));
1377
1926
  const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1378
1927
  const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1379
- if (rule === void 0) return new require_worktreeOperations.PoGitExpectedError("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.");
1380
- const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1381
- return new require_worktreeOperations.PoGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1928
+ if (rule === void 0) return new require_gitDependencies.PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1929
+ operation,
1930
+ code: String(result.code)
1931
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1932
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1933
+ return new require_gitDependencies.PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1382
1934
  }
1383
1935
  //#endregion
1384
1936
  //#region src/services/gitSync/index.ts
@@ -1401,61 +1953,68 @@ function classifyGitFailure(operation, result, mismatch) {
1401
1953
  */
1402
1954
  const DONE = { outcome: "done" };
1403
1955
  function expected(code, message, recovery) {
1404
- return new require_worktreeOperations.PoGitExpectedError(code, message, false, recovery);
1405
- }
1406
- async function readLine(cwd, args) {
1407
- const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1408
- const out = result.stdout.trim();
1409
- return result.code === 0 && out !== "" ? out : void 0;
1956
+ return new require_gitDependencies.PoGitExpectedError(code, message, false, recovery);
1410
1957
  }
1411
- async function toplevel(cwd) {
1412
- const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1413
- if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1414
- return root;
1415
- }
1416
- async function rebasing(root) {
1417
- for (const name of ["rebase-merge", "rebase-apply"]) {
1418
- const gitPath = await readLine(root, [
1419
- "rev-parse",
1420
- "--git-path",
1421
- name
1958
+ function createGitSync(options) {
1959
+ const baseEnv = options.baseEnv ?? {};
1960
+ async function readLine(cwd, args) {
1961
+ const result = await require_gitDependencies.runGit(cwd, args, {
1962
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1963
+ env: baseEnv
1964
+ });
1965
+ const out = result.stdout.trim();
1966
+ return result.code === 0 && out !== "" ? out : void 0;
1967
+ }
1968
+ async function toplevel(cwd) {
1969
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1970
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1971
+ return root;
1972
+ }
1973
+ async function rebasing(root) {
1974
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1975
+ const gitPath = await readLine(root, [
1976
+ "rev-parse",
1977
+ "--git-path",
1978
+ name
1979
+ ]);
1980
+ if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1981
+ }
1982
+ return false;
1983
+ }
1984
+ async function conflicts(root) {
1985
+ return (await require_gitDependencies.runGit(root, [
1986
+ "diff",
1987
+ "--name-only",
1988
+ "--diff-filter=U",
1989
+ "-z"
1990
+ ], {
1991
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1992
+ env: baseEnv
1993
+ })).stdout.split("\0").filter((file) => file !== "");
1994
+ }
1995
+ async function currentBranch(root) {
1996
+ const branch = await readLine(root, [
1997
+ "symbolic-ref",
1998
+ "--quiet",
1999
+ "--short",
2000
+ "HEAD"
1422
2001
  ]);
1423
- if (gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath))) return true;
2002
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
2003
+ return branch;
1424
2004
  }
1425
- return false;
1426
- }
1427
- async function conflicts(root) {
1428
- return (await require_worktreeOperations.runGit(root, [
1429
- "diff",
1430
- "--name-only",
1431
- "--diff-filter=U",
1432
- "-z"
1433
- ], { timeout: require_worktreeOperations.READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1434
- }
1435
- async function currentBranch(root) {
1436
- const branch = await readLine(root, [
1437
- "symbolic-ref",
1438
- "--quiet",
1439
- "--short",
1440
- "HEAD"
1441
- ]);
1442
- if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1443
- return branch;
1444
- }
1445
- async function guard(root, needsCleanTree) {
1446
- 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.");
1447
- const branch = await currentBranch(root);
1448
- if (needsCleanTree) {
1449
- if (await readLine(root, [
1450
- "status",
1451
- "--porcelain",
1452
- "--untracked-files=no"
1453
- ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2005
+ async function guard(root, needsCleanTree) {
2006
+ 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.");
2007
+ const branch = await currentBranch(root);
2008
+ if (needsCleanTree) {
2009
+ if (await readLine(root, [
2010
+ "status",
2011
+ "--porcelain",
2012
+ "--untracked-files=no"
2013
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2014
+ }
2015
+ return branch;
1454
2016
  }
1455
- return branch;
1456
- }
1457
- function createGitSync(options) {
1458
- const baseEnv = options.baseEnv ?? process.env;
2017
+ const baselines = /* @__PURE__ */ new Map();
1459
2018
  /** One credentialed network command against `remote`, classified on failure. */
1460
2019
  const network = async (root, context, remote, operation, args, urlArgs = []) => {
1461
2020
  const url = await readLine(root, [
@@ -1466,28 +2025,44 @@ function createGitSync(options) {
1466
2025
  ]);
1467
2026
  if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1468
2027
  const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1469
- const result = await require_worktreeOperations.runGit(root, args, {
1470
- timeout: require_worktreeOperations.NETWORK_TIMEOUT_MS,
1471
- env: prepared.env
2028
+ const result = await require_gitDependencies.runGit(root, args, {
2029
+ timeout: require_gitDependencies.NETWORK_TIMEOUT_MS,
2030
+ env: prepared.env,
2031
+ ...context.signal ? { signal: context.signal } : {}
1472
2032
  });
1473
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
2033
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
1474
2034
  };
1475
2035
  /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1476
- const rebaseOnto = async (root, onto) => {
1477
- const result = await require_worktreeOperations.runGit(root, ["rebase", onto], {
1478
- timeout: require_worktreeOperations.REBASE_TIMEOUT_MS,
2036
+ const rebaseOnto = async (root, onto, context) => {
2037
+ context.signal?.throwIfAborted();
2038
+ const before = baselines.get(root) ?? await require_gitDependencies.revision(root, "HEAD", {
2039
+ env: baseEnv,
2040
+ ...context.signal ? { signal: context.signal } : {}
2041
+ });
2042
+ baselines.set(root, before);
2043
+ const result = await require_gitDependencies.runGit(root, ["rebase", onto], {
2044
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2045
+ ...context.signal ? { signal: context.signal } : {},
1479
2046
  env: {
1480
2047
  ...baseEnv,
1481
2048
  GIT_EDITOR: "true",
1482
2049
  GIT_TERMINAL_PROMPT: "0"
1483
2050
  }
1484
2051
  });
1485
- if (result.code === 0) return DONE;
2052
+ if (result.code === 0) {
2053
+ if (before !== await require_gitDependencies.revision(root, "HEAD", {
2054
+ env: baseEnv,
2055
+ ...context.signal ? { signal: context.signal } : {}
2056
+ })) await options.reapplySparse?.(root, context.signal);
2057
+ baselines.delete(root);
2058
+ return DONE;
2059
+ }
1486
2060
  if (await rebasing(root)) return {
1487
2061
  outcome: "paused",
1488
2062
  conflicts: await conflicts(root)
1489
2063
  };
1490
- throw classifyGitFailure("rebase", result);
2064
+ baselines.delete(root);
2065
+ throw classifyGitFailure("rebase", result, void 0, context.t);
1491
2066
  };
1492
2067
  /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1493
2068
  const remoteOfRef = async (root, ref) => {
@@ -1518,7 +2093,7 @@ function createGitSync(options) {
1518
2093
  "--prune",
1519
2094
  remote
1520
2095
  ]);
1521
- return rebaseOnto(root, upstream);
2096
+ return rebaseOnto(root, upstream, context);
1522
2097
  },
1523
2098
  async push(context, force) {
1524
2099
  const root = await toplevel(context.cwd);
@@ -1550,18 +2125,409 @@ function createGitSync(options) {
1550
2125
  "--prune",
1551
2126
  remote
1552
2127
  ]);
1553
- return rebaseOnto(root, base);
2128
+ return rebaseOnto(root, base, context);
1554
2129
  },
1555
2130
  async abortRebase(context) {
1556
2131
  const root = await toplevel(context.cwd);
1557
- if (!await rebasing(root)) return DONE;
1558
- const result = await require_worktreeOperations.runGit(root, ["rebase", "--abort"], { timeout: require_worktreeOperations.REBASE_TIMEOUT_MS });
1559
- if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
2132
+ if (!await rebasing(root)) {
2133
+ baselines.delete(root);
2134
+ return DONE;
2135
+ }
2136
+ const result = await require_gitDependencies.runGit(root, ["rebase", "--abort"], {
2137
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2138
+ env: baseEnv,
2139
+ ...context.signal ? { signal: context.signal } : {}
2140
+ });
2141
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2142
+ baselines.delete(root);
1560
2143
  return DONE;
1561
2144
  }
1562
2145
  };
1563
2146
  }
1564
2147
  //#endregion
2148
+ //#region src/services/newSessionRequest/index.ts
2149
+ const MAX_NAME_LENGTH = 120;
2150
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2151
+ function optionalText(value) {
2152
+ if (value === void 0) return void 0;
2153
+ if (typeof value !== "string") return false;
2154
+ const trimmed = value.trim();
2155
+ return trimmed === "" ? void 0 : trimmed;
2156
+ }
2157
+ /**
2158
+ * Validates a new-session dialog request for a worktree session. Every ref is
2159
+ * checked here, before it can reach git as a positional argument.
2160
+ */
2161
+ function newSessionRequest(body) {
2162
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2163
+ const record = body;
2164
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2165
+ const branch = optionalText(record.branch);
2166
+ if (branch === void 0 || branch === false || !require_gitDependencies.validRefName(branch)) return { error: "A valid branch name is required." };
2167
+ const name = optionalText(record.name);
2168
+ 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.` };
2169
+ if (Object.hasOwn(record, "sparseProfile") && !require_gitDependencies.validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2170
+ const chosen = record.selection === void 0 ? {} : (0, _agimon_ai_po_core_hubChannel.parseLaunchSelection)(record.selection);
2171
+ if ("error" in chosen) return chosen;
2172
+ const profile = chosen.selection?.profile;
2173
+ const named = {
2174
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2175
+ ...name === void 0 ? {} : { name },
2176
+ ...profile === void 0 ? {} : { selection: { profile } }
2177
+ };
2178
+ if (record.mode === "existing-branch") {
2179
+ const remote = optionalText(record.remote);
2180
+ if (remote === false || remote !== void 0 && !require_gitDependencies.validRefName(remote)) return { error: "That remote name is not valid." };
2181
+ return {
2182
+ mode: "existing-branch",
2183
+ branch,
2184
+ ...remote === void 0 ? {} : { remote },
2185
+ ...named
2186
+ };
2187
+ }
2188
+ if (record.mode === "new-branch") {
2189
+ const baseRef = optionalText(record.baseRef);
2190
+ if (baseRef === false || baseRef !== void 0 && !require_gitDependencies.validRefName(baseRef)) return { error: "That base branch is not valid." };
2191
+ return {
2192
+ mode: "new-branch",
2193
+ branch,
2194
+ ...baseRef === void 0 ? {} : { baseRef },
2195
+ ...named
2196
+ };
2197
+ }
2198
+ return { error: "The mode must be existing-branch or new-branch." };
2199
+ }
2200
+ //#endregion
2201
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2202
+ /**
2203
+ * The worktree surface the cockpit panel calls.
2204
+ *
2205
+ * Hub-scoped because worktrees are a property of a repository, not of one
2206
+ * session: the panel lists and creates them whether or not the session that
2207
+ * made them is focused, and a session-scoped API would disappear with it.
2208
+ *
2209
+ * The panel names a repository by the hub's opaque id and never by path.
2210
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2211
+ * point this at a directory the cockpit was never given.
2212
+ */
2213
+ function badRequest(message) {
2214
+ return Response.json({ error: message }, { status: 400 });
2215
+ }
2216
+ function failed(error) {
2217
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return Response.json({
2218
+ error: error.message,
2219
+ code: error.code
2220
+ }, { status: error.retryable ? 503 : 409 });
2221
+ return Response.json({ error: "The worktree operation failed." }, { status: 500 });
2222
+ }
2223
+ function createGitApi(openDirectory, dependencies = {}, translate) {
2224
+ return {
2225
+ basePath: "git",
2226
+ start(context) {
2227
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
2228
+ const directEvents = context.directEvents;
2229
+ const publishLifecycle = (sessionId, repositoryRoot) => {
2230
+ directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
2231
+ version: 1,
2232
+ repositoryRoot
2233
+ });
2234
+ };
2235
+ const git = require_gitDependencies.createWorktreeGit();
2236
+ const operations = require_gitDependencies.createWorktreeOperations({
2237
+ ...dependencies,
2238
+ git,
2239
+ sessionService: context.sessionService,
2240
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
2241
+ ...context.environment === void 0 ? {} : { environment: context.environment }
2242
+ });
2243
+ const sync = createGitSync({
2244
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2245
+ baseEnv: context.environment ?? {},
2246
+ async reapplySparse(cwd, signal) {
2247
+ const record = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.path === cwd && entry.sessionId === context.sessionId);
2248
+ if (record?.sparseProfile) await operations.reapply({
2249
+ cwd,
2250
+ sessionId: context.sessionId
2251
+ }, record.id, { signal });
2252
+ }
2253
+ });
2254
+ const sessionCommand = async (request, url) => {
2255
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2256
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2257
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2258
+ const caller = {
2259
+ cwd: context.cwd,
2260
+ sessionId: context.sessionId
2261
+ };
2262
+ const body = await request.json().catch(() => void 0);
2263
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2264
+ const command = body;
2265
+ if (url.pathname === "/sync") {
2266
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2267
+ const recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2268
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2269
+ const syncContext = {
2270
+ ...caller,
2271
+ auth,
2272
+ recordedBaseRef,
2273
+ signal: request.signal,
2274
+ ...translate ? { t: translate } : {}
2275
+ };
2276
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2277
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2278
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2279
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2280
+ return badRequest("Unknown sync command.");
2281
+ }
2282
+ if (Object.keys(command).some((key) => ![
2283
+ "action",
2284
+ "branch",
2285
+ "baseRef",
2286
+ "sparseProfile",
2287
+ "reservationId",
2288
+ "id",
2289
+ "force",
2290
+ "folders"
2291
+ ].includes(key))) return badRequest("Unknown command field.");
2292
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2293
+ if (command.action === "create") {
2294
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2295
+ const result = await operations.spawn(caller, {
2296
+ branch: command.branch,
2297
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2298
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2299
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2300
+ }, { signal: request.signal });
2301
+ return Response.json({ worktree: result });
2302
+ }
2303
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2304
+ if (![
2305
+ "profiles",
2306
+ "expand",
2307
+ "reapply"
2308
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2309
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2310
+ return Response.json(result.details);
2311
+ };
2312
+ /**
2313
+ * The new-session dialog's routes: the workspace's branches, and a top-level
2314
+ * worktree session on one. Workspace-mounted only, and always rooted at the
2315
+ * mount's own workspace, so a request can never name another directory.
2316
+ */
2317
+ const newSession = async (request, url) => {
2318
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
2319
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
2320
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
2321
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
2322
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
2323
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
2324
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2325
+ if (isBranches) {
2326
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2327
+ const branches = repositoryRoot === void 0 ? {
2328
+ repository: false,
2329
+ local: [],
2330
+ remote: []
2331
+ } : {
2332
+ repository: true,
2333
+ ...await git.listBranches(repositoryRoot),
2334
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
2335
+ };
2336
+ return Response.json(branches);
2337
+ }
2338
+ if (isDelete || isOpen) {
2339
+ if (isOpen && (0, _agimon_ai_po_core_packageApi.poApiCallerFrom)(request.headers)?.locality !== "local") return Response.json({ error: "Opening Finder is only available on the host." }, { status: 403 });
2340
+ const body = await request.json().catch(() => void 0);
2341
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
2342
+ if (typeof branch !== "string" || !require_gitDependencies.validRefName(branch)) return badRequest("A valid branch name is required.");
2343
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2344
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
2345
+ const branches = await git.listBranches(repositoryRoot);
2346
+ const local = branches.local.find((item) => item.name === branch);
2347
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
2348
+ if (isOpen) {
2349
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
2350
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
2351
+ try {
2352
+ await openDirectory(local.checkedOutAt);
2353
+ return Response.json({ opened: true });
2354
+ } catch {
2355
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
2356
+ }
2357
+ }
2358
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
2359
+ if (!await git.deleteBranch({
2360
+ repositoryRoot,
2361
+ branch
2362
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
2363
+ return Response.json({ deleted: true });
2364
+ }
2365
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
2366
+ if ("error" in parsed) return badRequest(parsed.error);
2367
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
2368
+ branch: parsed.branch,
2369
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
2370
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
2371
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
2372
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
2373
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
2374
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
2375
+ }, { signal: request.signal });
2376
+ publishLifecycle(record.sessionId, record.repositoryRoot);
2377
+ const created = {
2378
+ sessionId: record.sessionId,
2379
+ worktreeId: record.id
2380
+ };
2381
+ return Response.json(created, { status: 201 });
2382
+ };
2383
+ /** The admitted root for a request, or a response explaining why not. */
2384
+ const rootOf = (url) => {
2385
+ const repositoryId = url.searchParams.get("repositoryId");
2386
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
2387
+ const root = context.resolveRepository?.(repositoryId);
2388
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
2389
+ return root;
2390
+ };
2391
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
2392
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir, context.environment);
2393
+ const branchDiff = createBranchDiff();
2394
+ const pendingReviews = /* @__PURE__ */ new Map();
2395
+ /**
2396
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
2397
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
2398
+ * The view never carries the token.
2399
+ */
2400
+ const auth = async (request, url) => {
2401
+ if (url.pathname !== "/auth") return void 0;
2402
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2403
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
2404
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
2405
+ const root = rootOf(url);
2406
+ if (root instanceof Response) return root;
2407
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
2408
+ try {
2409
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
2410
+ } catch (error) {
2411
+ if (error instanceof require_gitDependencies.PoGitExpectedError && error.code === "invalid_request") {
2412
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2413
+ return Response.json({
2414
+ error: text,
2415
+ code: error.code
2416
+ }, { status: 400 });
2417
+ }
2418
+ throw error;
2419
+ }
2420
+ };
2421
+ /**
2422
+ * The session's change against its base. Session mounts only, rooted at the
2423
+ * session's own checkout; a file is served only when it is in the change set
2424
+ * computed for the request. Overlapping requests share an in-flight snapshot.
2425
+ */
2426
+ const review = async (request, url) => {
2427
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
2428
+ const cwd = context.scope === "session" ? context.cwd : void 0;
2429
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2430
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
2431
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
2432
+ let recordedBaseRef;
2433
+ try {
2434
+ recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
2435
+ } catch {
2436
+ recordedBaseRef = void 0;
2437
+ }
2438
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
2439
+ let pending = pendingReviews.get(key);
2440
+ if (pending === void 0) {
2441
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
2442
+ pendingReviews.set(key, pending);
2443
+ }
2444
+ const result = await pending;
2445
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
2446
+ repository: false,
2447
+ files: []
2448
+ });
2449
+ const filePath = url.searchParams.get("path") ?? "";
2450
+ 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 });
2451
+ return Response.json(await branchDiff.fileDiff(result, filePath));
2452
+ };
2453
+ return {
2454
+ async fetch(request) {
2455
+ const url = new URL(request.url);
2456
+ try {
2457
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2458
+ if (answered !== void 0) return answered;
2459
+ } catch (error) {
2460
+ context.onNotice(`git request failed: ${error.name}`);
2461
+ return failed(error);
2462
+ }
2463
+ const root = rootOf(url);
2464
+ if (root instanceof Response) return root;
2465
+ const callerContext = {
2466
+ cwd: root,
2467
+ sessionId: url.searchParams.get("sessionId") ?? ""
2468
+ };
2469
+ 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.");
2470
+ try {
2471
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
2472
+ if (request.method === "POST" && url.pathname === "/worktrees") {
2473
+ const body = await request.json();
2474
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
2475
+ const record = await operations.spawn(callerContext, {
2476
+ branch: body.branch,
2477
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
2478
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
2479
+ ...body.name === void 0 ? {} : { name: body.name }
2480
+ });
2481
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2482
+ return Response.json({ worktree: record }, { status: 201 });
2483
+ }
2484
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
2485
+ if (request.method === "DELETE" && closing) {
2486
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
2487
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2488
+ return Response.json({ worktree: record });
2489
+ }
2490
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
2491
+ } catch (error) {
2492
+ context.onNotice(`worktree request failed: ${error.name}`);
2493
+ return failed(error);
2494
+ }
2495
+ },
2496
+ close() {}
2497
+ };
2498
+ }
2499
+ };
2500
+ }
2501
+ //#endregion
2502
+ //#region src/extensions/(backend)/api/git/route.server.ts
2503
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)((plugin) => {
2504
+ const { context, host, signal } = plugin;
2505
+ let openDirectory;
2506
+ context.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
2507
+ const shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
2508
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
2509
+ openDirectory = async (path) => {
2510
+ const result = await shell.exec([
2511
+ "/usr/bin/open",
2512
+ "-a",
2513
+ "Finder",
2514
+ path
2515
+ ], {
2516
+ env,
2517
+ inheritEnv: false
2518
+ }, (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
2519
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
2520
+ };
2521
+ return () => {
2522
+ openDirectory = void 0;
2523
+ };
2524
+ });
2525
+ return createGitApi(async (path) => {
2526
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
2527
+ await openDirectory(path);
2528
+ }, require_gitDependencies.createGitOperationDependencies(plugin), (key, fallback, vars) => (0, _agimon_ai_po_core_locale.readPoLang)(context)?.t((0, _agimon_ai_po_core_locale.readPoPersonLocale)(context)?.read() ?? (0, _agimon_ai_po_core_locale.canonicalLocale)(host.context.environment?.PO_LANG), key, fallback, vars) ?? (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars));
2529
+ });
2530
+ //#endregion
1565
2531
  //#region src/types/gitReview.ts
1566
2532
  /**
1567
2533
  * The cockpit's view of what this session changed against its base: the counts
@@ -1591,8 +2557,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1591
2557
  * - Apart from the worktrees channel. Worktrees are repository management;
1592
2558
  * this is the session's own code change.
1593
2559
  * - Push, not poll. The session's server plugin publishes a "changed" event
1594
- * after every tool call and settled turn; recounts are coalesced to one in
1595
- * flight plus one rerun, so a burst of tool calls costs at most two.
2560
+ * after every tool call that can write and every settled turn; a recount
2561
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
2562
+ * in flight plus one rerun.
1596
2563
  * - One sync command per session. A rebase and a push must never overlap.
1597
2564
  * - Auth is read fresh for each command from the session's workspace, and goes
1598
2565
  * only into that command's git child.
@@ -1601,6 +2568,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1601
2568
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1602
2569
  * stderr and drops it, because a remote URL in it can carry a token.
1603
2570
  */
2571
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
2572
+ const REFRESH_DELAY_MS = 1500;
1604
2573
  function payloadOf$1(state) {
1605
2574
  return {
1606
2575
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1628,13 +2597,13 @@ const PENDING = {
1628
2597
  /** The error target a failure maps to: a rejected plain push asks for a confirmed lease force. */
1629
2598
  function errorTargetFor$1(command, error) {
1630
2599
  if (command.action !== "push") return { action: command.action };
1631
- return error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
2600
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
1632
2601
  action: "push",
1633
2602
  forceRequired: true
1634
2603
  } : { action: "push" };
1635
2604
  }
1636
2605
  function failureText$1(error) {
1637
- if (error instanceof require_worktreeOperations.PoGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2606
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1638
2607
  return "The git command failed.";
1639
2608
  }
1640
2609
  function createGitChangesChannel(options = {}) {
@@ -1645,17 +2614,19 @@ function createGitChangesChannel(options = {}) {
1645
2614
  const homeDir = options.homeDir ?? node_os.default.homedir();
1646
2615
  const diff = options.diff ?? createBranchDiff();
1647
2616
  const sync = options.sync ?? createGitSync({ homeDir });
1648
- const auth = options.auth ?? createGitAuthStore(homeDir);
2617
+ const auth = options.auth ?? createGitAuthStore(homeDir, options.environment);
1649
2618
  const latest = /* @__PURE__ */ new Map();
1650
2619
  const subscriptions = /* @__PURE__ */ new Map();
1651
2620
  const scopes = /* @__PURE__ */ new Map();
1652
2621
  const inFlight = /* @__PURE__ */ new Set();
1653
2622
  const rerun = /* @__PURE__ */ new Set();
1654
2623
  const busy = /* @__PURE__ */ new Set();
2624
+ const delayed = /* @__PURE__ */ new Map();
2625
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1655
2626
  /** The base the session's own worktree was created from, when it has one. */
1656
- const recordedBaseRef = (scope) => {
2627
+ const recordedBaseRef = async (scope) => {
1657
2628
  try {
1658
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
2629
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1659
2630
  } catch {
1660
2631
  return;
1661
2632
  }
@@ -1688,8 +2659,7 @@ function createGitChangesChannel(options = {}) {
1688
2659
  return;
1689
2660
  }
1690
2661
  inFlight.add(sessionId);
1691
- const base = recordedBaseRef(scope);
1692
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
2662
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1693
2663
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1694
2664
  }).catch((error) => {
1695
2665
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1698,18 +2668,41 @@ function createGitChangesChannel(options = {}) {
1698
2668
  if (rerun.delete(sessionId)) refresh(sessionId);
1699
2669
  });
1700
2670
  };
1701
- const run = (scope, command) => {
2671
+ /** Recounts once the session has been quiet for a moment. */
2672
+ const refreshSoon = (sessionId) => {
2673
+ clearTimeout(delayed.get(sessionId));
2674
+ const timer = setTimeout(() => {
2675
+ delayed.delete(sessionId);
2676
+ refresh(sessionId);
2677
+ }, refreshDelayMs);
2678
+ timer.unref?.();
2679
+ delayed.set(sessionId, timer);
2680
+ };
2681
+ const run = async (scope, command) => {
2682
+ if (options.scopedCommands) {
2683
+ const response = await host.requestSessionApi(scope, {
2684
+ basePath: "git",
2685
+ path: "/sync",
2686
+ method: "POST",
2687
+ body: JSON.stringify(command)
2688
+ });
2689
+ const result = await response.json();
2690
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2691
+ return result;
2692
+ }
1702
2693
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1703
- const base = recordedBaseRef(scope);
2694
+ const base = await recordedBaseRef(scope);
1704
2695
  const context = {
1705
2696
  cwd: scope.cwd,
1706
- auth: auth.read(workspaceRoot),
2697
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
2698
+ auth: await auth.read(workspaceRoot),
1707
2699
  ...base === void 0 ? {} : { recordedBaseRef: base }
1708
2700
  };
1709
- if (command.action === "pull") return sync.pull(context);
1710
- if (command.action === "push") return sync.push(context, command.force === true);
1711
- if (command.action === "rebase") return sync.rebase(context);
1712
- return sync.abortRebase(context);
2701
+ const sessionSync = sync;
2702
+ if (command.action === "pull") return sessionSync.pull(context);
2703
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2704
+ if (command.action === "rebase") return sessionSync.rebase(context);
2705
+ return sessionSync.abortRebase(context);
1713
2706
  };
1714
2707
  const source = {
1715
2708
  payloadFor(scope) {
@@ -1719,13 +2712,15 @@ function createGitChangesChannel(options = {}) {
1719
2712
  sessionAdded(scope) {
1720
2713
  scopes.set(scope.sessionId, scope);
1721
2714
  refresh(scope.sessionId);
1722
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1723
- if (require_worktreeOperations.isSessionChangedEvent(payload)) refresh(scope.sessionId);
2715
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
2716
+ if (require_gitDependencies.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1724
2717
  });
1725
2718
  subscriptions.set(scope.sessionId, unsubscribe);
1726
2719
  },
1727
2720
  sessionRemoved(sessionId) {
1728
2721
  subscriptions.get(sessionId)?.();
2722
+ clearTimeout(delayed.get(sessionId));
2723
+ delayed.delete(sessionId);
1729
2724
  subscriptions.delete(sessionId);
1730
2725
  scopes.delete(sessionId);
1731
2726
  latest.delete(sessionId);
@@ -1734,6 +2729,8 @@ function createGitChangesChannel(options = {}) {
1734
2729
  },
1735
2730
  close() {
1736
2731
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2732
+ for (const timer of delayed.values()) clearTimeout(timer);
2733
+ delayed.clear();
1737
2734
  subscriptions.clear();
1738
2735
  scopes.clear();
1739
2736
  latest.clear();
@@ -1752,7 +2749,7 @@ function createGitChangesChannel(options = {}) {
1752
2749
  errorTarget: void 0
1753
2750
  });
1754
2751
  run(scope, command).then(() => update(scope.sessionId, { pending: void 0 })).catch((error) => {
1755
- host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_worktreeOperations.PoGitExpectedError ? error.code : "unexpected"})`);
2752
+ host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_gitDependencies.PoGitExpectedError ? error.code : "unexpected"})`);
1756
2753
  update(scope.sessionId, {
1757
2754
  pending: void 0,
1758
2755
  error: failureText$1(error),
@@ -1772,7 +2769,12 @@ function createGitChangesChannel(options = {}) {
1772
2769
  }
1773
2770
  //#endregion
1774
2771
  //#region src/extensions/(backend)/channel/git-changes.server.ts
1775
- var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createGitChangesChannel);
2772
+ var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(({ context, host }) => createGitChangesChannel({
2773
+ homeDir: host.context.homeDirectory,
2774
+ environment: host.context.environment,
2775
+ scopedCommands: true,
2776
+ t: (scope, key, fallback, vars) => (0, _agimon_ai_po_core_locale.readPoLang)(context)?.t((0, _agimon_ai_po_core_locale.readPoPersonLocale)(context)?.read() ?? (0, _agimon_ai_po_core_locale.canonicalLocale)(scope.environment?.PO_LANG), key, fallback, vars) ?? (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars)
2777
+ }), { context: true });
1776
2778
  //#endregion
1777
2779
  //#region src/types/webWorktrees.ts
1778
2780
  /**
@@ -1801,9 +2803,9 @@ function payloadOf(state) {
1801
2803
  };
1802
2804
  }
1803
2805
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1804
- function viewsFor(scope, deps) {
2806
+ async function viewsFor(scope, deps) {
1805
2807
  try {
1806
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2808
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
1807
2809
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1808
2810
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1809
2811
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1828,11 +2830,15 @@ function sameList(left, right) {
1828
2830
  return other !== void 0 && entry.id === other.id && entry.branch === other.branch && entry.sessionId === other.sessionId && entry.orphaned === other.orphaned && entry.unowned === other.unowned;
1829
2831
  });
1830
2832
  }
1831
- function errorTargetFor(command) {
1832
- return command.action === "create" ? { action: "create" } : {
2833
+ function errorTargetFor(command, error) {
2834
+ if (command.action === "close") return {
1833
2835
  action: "close",
1834
2836
  id: command.id
1835
2837
  };
2838
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "rift_missing" ? {
2839
+ action: "create",
2840
+ riftMissing: true
2841
+ } : { action: "create" };
1836
2842
  }
1837
2843
  /** A command the page sent, or undefined when the frame was not one. */
1838
2844
  function parseCommand(payload) {
@@ -1841,7 +2847,9 @@ function parseCommand(payload) {
1841
2847
  if (value.action === "create") {
1842
2848
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
1843
2849
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2850
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
1844
2851
  return {
2852
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
1845
2853
  action: "create",
1846
2854
  branch: value.branch.trim(),
1847
2855
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -1860,11 +2868,15 @@ function parseCommand(payload) {
1860
2868
  /**
1861
2869
  * What the reader is told when a command fails.
1862
2870
  *
1863
- * An expected failure explains itself. Anything else is summarised, never
1864
- * echoed: a git error can carry a remote URL with a token in it.
2871
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2872
+ * written for the agent's tool result. A dirty close is said in the person's
2873
+ * terms, because its message tells the agent to pass `force`. Anything else is
2874
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1865
2875
  */
1866
2876
  function failureText(error) {
1867
- return error instanceof require_worktreeOperations.PoGitExpectedError ? error.message : "The worktree operation failed.";
2877
+ if (!(error instanceof require_gitDependencies.PoGitExpectedError)) return "The worktree operation failed.";
2878
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2879
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1868
2880
  }
1869
2881
  /** Starts one direct-event subscription per managed session. */
1870
2882
  function createWorktreesChannel(options = {}) {
@@ -1873,14 +2885,16 @@ function createWorktreesChannel(options = {}) {
1873
2885
  frameType: GIT_WORKTREES_TYPE,
1874
2886
  start(host) {
1875
2887
  const sessionService = host.sessionService;
1876
- if (sessionService === void 0) throw new require_worktreeOperations.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1877
- const worktrees = options.operations ?? require_worktreeOperations.createWorktreeOperations({
1878
- git: require_worktreeOperations.createWorktreeGit(),
1879
- sessionService
2888
+ if (sessionService === void 0) throw new require_gitDependencies.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
2889
+ const worktrees = options.operations ?? require_gitDependencies.createWorktreeOperations({
2890
+ git: require_gitDependencies.createWorktreeGit(),
2891
+ sessionService,
2892
+ ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2893
+ ...options.environment === void 0 ? {} : { environment: options.environment }
1880
2894
  });
1881
2895
  /** Announces a successful mutation to this session's lifecycle subscribers. */
1882
2896
  const publishLifecycle = (scope, repositoryRoot) => {
1883
- host.directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
2897
+ host.directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
1884
2898
  version: 1,
1885
2899
  repositoryRoot
1886
2900
  });
@@ -1889,6 +2903,22 @@ function createWorktreesChannel(options = {}) {
1889
2903
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
1890
2904
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
1891
2905
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2906
+ if (options.scopedCommands) {
2907
+ if (!(await host.requestSessionApi(parent, {
2908
+ basePath: "git",
2909
+ path: "/session-worktrees",
2910
+ method: "POST",
2911
+ body: JSON.stringify({
2912
+ action: "create",
2913
+ branch,
2914
+ reservationId
2915
+ }),
2916
+ ...signal ? { signal } : {}
2917
+ })).ok) throw new Error("The conversation worktree could not be created.");
2918
+ const reservations = sessionService.reservations;
2919
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2920
+ return reservations.complete(reservationId, parentSessionId);
2921
+ }
1892
2922
  const record = await worktrees.spawn({
1893
2923
  cwd: parent.cwd,
1894
2924
  sessionId: parent.sessionId
@@ -1905,6 +2935,7 @@ function createWorktreesChannel(options = {}) {
1905
2935
  });
1906
2936
  const views = {
1907
2937
  homeDir: options.homeDir,
2938
+ environment: options.environment,
1908
2939
  sessionService
1909
2940
  };
1910
2941
  const latest = /* @__PURE__ */ new Map();
@@ -1917,10 +2948,13 @@ function createWorktreesChannel(options = {}) {
1917
2948
  return generation;
1918
2949
  };
1919
2950
  /** Republishes a session, skipping a frame that would say nothing new. */
1920
- const publish = (scope, force) => {
2951
+ const publish = async (scope, force) => {
2952
+ const generation = generations.get(scope.sessionId);
2953
+ const worktreeViews = await viewsFor(scope, views);
2954
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1921
2955
  const previous = latest.get(scope.sessionId);
1922
2956
  const next = {
1923
- worktrees: viewsFor(scope, views),
2957
+ worktrees: worktreeViews,
1924
2958
  pending: previous?.pending,
1925
2959
  error: previous?.error,
1926
2960
  errorTarget: previous?.errorTarget
@@ -1932,7 +2966,7 @@ function createWorktreesChannel(options = {}) {
1932
2966
  const mark = (scope, pending, error, errorTarget) => {
1933
2967
  const previous = latest.get(scope.sessionId);
1934
2968
  latest.set(scope.sessionId, {
1935
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2969
+ worktrees: previous?.worktrees ?? [],
1936
2970
  pending,
1937
2971
  error,
1938
2972
  errorTarget
@@ -1948,10 +2982,24 @@ function createWorktreesChannel(options = {}) {
1948
2982
  if (generations.get(scope.sessionId) !== generation) return;
1949
2983
  mark(scope, pending, error, errorTarget);
1950
2984
  };
2985
+ if (options.scopedCommands) {
2986
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2987
+ const response = await host.requestSessionApi(scope, {
2988
+ basePath: "git",
2989
+ path: "/session-worktrees",
2990
+ method: "POST",
2991
+ body: JSON.stringify(command)
2992
+ });
2993
+ const result = await response.json();
2994
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2995
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2996
+ return;
2997
+ }
1951
2998
  if (command.action === "create") {
1952
2999
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
1953
3000
  const record = await worktrees.spawn(context, {
1954
3001
  branch: command.branch,
3002
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
1955
3003
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
1956
3004
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
1957
3005
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -1972,15 +3020,15 @@ function createWorktreesChannel(options = {}) {
1972
3020
  sessionAdded(scope) {
1973
3021
  newGeneration(scope.sessionId);
1974
3022
  publish(scope, false);
1975
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
1976
- if (!require_worktreeOperations.isWorktreeLifecycleEvent(payload)) return;
3023
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
3024
+ if (!require_gitDependencies.isWorktreeLifecycleEvent(payload)) return;
1977
3025
  let sameRepository = false;
1978
3026
  try {
1979
- sameRepository = require_worktreeOperations.registryFile(scope.cwd, options.homeDir) === require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir);
3027
+ sameRepository = await require_gitDependencies.registryFile(scope.cwd, options.homeDir, options.environment) === await require_gitDependencies.registryFile(payload.repositoryRoot, options.homeDir, options.environment);
1980
3028
  } catch {
1981
3029
  sameRepository = false;
1982
3030
  }
1983
- if (sameRepository) publish(scope, false);
3031
+ if (sameRepository) await publish(scope, false);
1984
3032
  });
1985
3033
  subscriptions.set(scope.sessionId, unsubscribe);
1986
3034
  },
@@ -2013,7 +3061,7 @@ function createWorktreesChannel(options = {}) {
2013
3061
  }).catch((error) => {
2014
3062
  if (generations.get(scope.sessionId) !== generation) return;
2015
3063
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2016
- mark(scope, void 0, failureText(error), errorTargetFor(command));
3064
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2017
3065
  }).finally(() => {
2018
3066
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2019
3067
  });
@@ -2027,28 +3075,28 @@ function createWorktreesChannel(options = {}) {
2027
3075
  }
2028
3076
  //#endregion
2029
3077
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2030
- var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createWorktreesChannel);
3078
+ var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)((plugin) => createWorktreesChannel({
3079
+ homeDir: plugin.host.context.homeDirectory,
3080
+ environment: plugin.host.context.environment,
3081
+ scopedCommands: true
3082
+ }), { context: true });
2031
3083
  //#endregion
2032
3084
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2033
- var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[1]);
3085
+ var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => ({
3086
+ ...context.root.hooks[1],
3087
+ name: "git-notify-checkout-when-settled",
3088
+ description: "Notify the session diff channel when the agent settles to refresh checkout changes."
3089
+ }));
2034
3090
  //#endregion
2035
3091
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2036
- var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
2037
- //#endregion
2038
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGit.server.ts
2039
- var poGit_server_default$1 = (context) => context.root.resources[0];
2040
- //#endregion
2041
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGit.server.ts
2042
- var poGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poGit_server_default$1);
2043
- //#endregion
2044
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGitReadme.server.ts
2045
- var poGitReadme_server_default$1 = (context) => context.root.resources[2];
2046
- //#endregion
2047
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGitReadme.server.ts
2048
- var poGitReadme_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poGitReadme_server_default$1);
3092
+ var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => ({
3093
+ ...context.root.hooks[0],
3094
+ name: "git-notify-checkout-after-tool",
3095
+ description: "Notify the session diff channel after tools that may change the checkout."
3096
+ }));
2049
3097
  //#endregion
2050
3098
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2051
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
3099
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2052
3100
  //#endregion
2053
3101
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2054
3102
  var poUseGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poUseGit_server_default$1);
@@ -2060,60 +3108,77 @@ var runWorktree_server_default = (0, _agimon_ai_po_core_extensionFile.defineServ
2060
3108
  const at = (value, context) => typeof value === "function" ? value(context) : value;
2061
3109
  /* v8 ignore next -- generated normalization branch */
2062
3110
  const defined = (values) => values.filter((value) => value !== void 0);
2063
- const via = (identity, value) => value === void 0 ? void 0 : {
2064
- ...identity,
2065
- ...value
3111
+ const via = (identity, value) => {
3112
+ if (value === void 0) return void 0;
3113
+ const declaration = value;
3114
+ return {
3115
+ ...identity,
3116
+ ...declaration,
3117
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
3118
+ evidence: "declared",
3119
+ ...relation
3120
+ })) }
3121
+ };
2066
3122
  };
2067
3123
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2068
3124
  name: "@agimon-ai/po-git",
2069
- providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
2070
- injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
2071
- global: (context) => ({
2072
- get api() {
2073
- return [at(route_server_default, context)];
2074
- },
2075
- get channels() {
2076
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2077
- }
3125
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
3126
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
3127
+ workspace: [root_server_default$1],
3128
+ session: [root_server_default$1, root_server_default]
2078
3129
  }),
2079
- workspace: (context) => ({
3130
+ host: (context) => ({
2080
3131
  get api() {
2081
3132
  return [at(route_server_default, context)];
2082
3133
  },
2083
3134
  get channels() {
2084
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "git_changes" }, git_changes_server_default()), context.hosted("global") ? void 0 : () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())]);
3135
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2085
3136
  }
2086
3137
  }),
3138
+ workspace: async (context) => {
3139
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3140
+ return {
3141
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace),
3142
+ get api() {
3143
+ return [at(route_server_default, context)];
3144
+ },
3145
+ get channels() {
3146
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), context.hosted("host") ? void 0 : () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))]);
3147
+ },
3148
+ services: [...scopeWorkspace.services ?? []]
3149
+ };
3150
+ },
2087
3151
  session: async (context) => {
2088
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2089
- const contextSession = {
3152
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3153
+ const contextWorkspace = {
2090
3154
  ...context,
3155
+ root: scopeWorkspace.value
3156
+ };
3157
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3158
+ const contextSession = {
3159
+ ...contextWorkspace,
2091
3160
  root: scopeSession.value
2092
3161
  };
2093
3162
  return {
2094
- ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
3163
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace, scopeSession),
2095
3164
  get api() {
2096
3165
  return [at(route_server_default, context)];
2097
3166
  },
2098
3167
  get channels() {
2099
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "git_changes" }, git_changes_server_default()), context.hosted("global") ? void 0 : () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())]);
3168
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), context.hosted("host") ? void 0 : () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))]);
2100
3169
  },
2101
3170
  get hooks() {
2102
3171
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2103
3172
  },
2104
3173
  get resources() {
2105
- return [
2106
- at(poGit_server_default, contextSession),
2107
- at(poGitReadme_server_default, contextSession),
2108
- at(poUseGit_server_default, contextSession)
2109
- ];
3174
+ return [at(poUseGit_server_default, contextSession)];
2110
3175
  },
2111
3176
  get tools() {
2112
3177
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2113
3178
  },
2114
- services: [...scopeSession.services ?? []],
3179
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2115
3180
  get activities() {
2116
- return [...scopeSession.activities ?? []];
3181
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2117
3182
  }
2118
3183
  };
2119
3184
  }