@agimon-ai/po-git 0.0.0-alpha.2 → 0.0.0-alpha.200

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 (37) hide show
  1. package/LICENSE +97 -8
  2. package/README.md +91 -21
  3. package/dist/apiContracts.cjs +82 -16
  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 +82 -16
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2255 -544
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1562 -514
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts +2 -2
  14. package/dist/extensions/server.d.mts.map +1 -1
  15. package/dist/extensions/server.mjs +1525 -477
  16. package/dist/extensions/server.mjs.map +1 -1
  17. package/dist/extensions/web.mjs +1761 -1388
  18. package/dist/extensions/web.mjs.map +1 -1
  19. package/dist/gitDependencies-D8bKxZSc.cjs +2690 -0
  20. package/dist/gitDependencies-D8bKxZSc.cjs.map +1 -0
  21. package/dist/gitDependencies-Delu4xip.mjs +2432 -0
  22. package/dist/gitDependencies-Delu4xip.mjs.map +1 -0
  23. package/dist/index.cjs +13 -22
  24. package/dist/index.d.mts +266 -14
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +3 -22
  27. package/dist/po-runtime-identity.json +1 -0
  28. package/llms.txt +3 -3
  29. package/package.json +104 -26
  30. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  31. package/dist/index.cjs.map +0 -1
  32. package/dist/index.mjs.map +0 -1
  33. package/dist/worktreeOperations-CaqwGsD_.mjs +0 -1065
  34. package/dist/worktreeOperations-CaqwGsD_.mjs.map +0 -1
  35. package/dist/worktreeOperations-MgIVDDu3.cjs +0 -1221
  36. package/dist/worktreeOperations-MgIVDDu3.cjs.map +0 -1
  37. 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-MgIVDDu3.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);
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");
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");
10
12
  let node_path = require("node:path");
11
- node_path = require_worktreeOperations.__toESM(node_path, 1);
12
- let _agimon_ai_po_core_serverFacet = require("@agimon-ai/po-core/serverFacet");
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 }) {
313
- if (serverHost.context.directEvents === void 0) throw new Error("Git headless facet requires the session direct event bus.");
314
- if (serverHost.context.sessionId === void 0) throw new Error("Git headless facet requires a session identity.");
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 }) {
1029
+ if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
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
- sessionDelivery: () => (0, _agimon_ai_po_session.readDoomSessionDelivery)(context)
1049
+ sessionDelivery: () => (0, _agimon_ai_po_session.readPoSessionDelivery)(context)
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
+ }
323
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_serverFacet.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_serverFacet.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,47 @@ 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 = [{
1115
+ event: "tool_execution_end",
1116
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
1117
+ }, {
1118
+ event: "agent_settled",
1119
+ handle: changed
1120
+ }];
1121
+ if (agent) {
1122
+ const namespace = createWorktreeNamespace({
1123
+ operations,
1124
+ workflows: () => workflows,
1125
+ execution: agent.context,
1126
+ assertAvailable: () => {
1127
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
1128
+ }
1129
+ });
1130
+ context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (scoped) => {
1131
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(scoped);
1132
+ if (!codemode) return void 0;
1133
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
1134
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
1135
+ return () => {
1136
+ restriction.dispose();
1137
+ registration.dispose();
1138
+ };
1139
+ });
1140
+ }
358
1141
  return {
359
1142
  value: {
360
1143
  resources,
361
1144
  tool,
362
- hooks: [{
363
- event: "tool_execution_end",
364
- handle: changed
365
- }, {
366
- event: "agent_settled",
367
- handle: changed
368
- }]
1145
+ hooks
369
1146
  },
370
- onDispose: () => messageInbox.close()
1147
+ onDispose: async () => {
1148
+ await workflowServices.dispose();
1149
+ await workflowProvider.dispose();
1150
+ await setupReceiver.dispose();
1151
+ messageInbox.close();
1152
+ }
371
1153
  };
372
1154
  }
373
1155
  const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createGitSession);
@@ -403,15 +1185,15 @@ const BINARY_PROBE_BYTES = 8192;
403
1185
  const SHORT_SHA = 7;
404
1186
  const DEFAULT_BRANCHES = ["main", "master"];
405
1187
  async function read(cwd, args) {
406
- const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1188
+ const result = await require_gitDependencies.runGit(cwd, args, { timeout: require_gitDependencies.READ_TIMEOUT_MS });
407
1189
  return result.code === 0 ? result.stdout : void 0;
408
1190
  }
409
- async function readLine$1(cwd, args) {
1191
+ async function readLine(cwd, args) {
410
1192
  const out = (await read(cwd, args))?.trim();
411
1193
  return out === void 0 || out === "" ? void 0 : out;
412
1194
  }
413
1195
  async function commitExists(cwd, ref) {
414
- return await readLine$1(cwd, [
1196
+ return await readLine(cwd, [
415
1197
  "rev-parse",
416
1198
  "--verify",
417
1199
  "--quiet",
@@ -420,7 +1202,7 @@ async function commitExists(cwd, ref) {
420
1202
  }
421
1203
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
422
1204
  async function upstreamOf(cwd, ref) {
423
- return readLine$1(cwd, [
1205
+ return readLine(cwd, [
424
1206
  "rev-parse",
425
1207
  "--abbrev-ref",
426
1208
  "--symbolic-full-name",
@@ -429,13 +1211,13 @@ async function upstreamOf(cwd, ref) {
429
1211
  }
430
1212
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
431
1213
  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, [
1214
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
433
1215
  "rev-parse",
434
1216
  "--verify",
435
1217
  "--quiet",
436
1218
  `refs/heads/${recordedBaseRef}`
437
1219
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
438
- const originHead = await readLine$1(cwd, [
1220
+ const originHead = await readLine(cwd, [
439
1221
  "symbolic-ref",
440
1222
  "--quiet",
441
1223
  "--short",
@@ -449,7 +1231,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
449
1231
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
450
1232
  const head = await commitExists(cwd, "HEAD");
451
1233
  if (ref !== void 0 && head) {
452
- const mergeBase = await readLine$1(cwd, [
1234
+ const mergeBase = await readLine(cwd, [
453
1235
  "merge-base",
454
1236
  ref,
455
1237
  "HEAD"
@@ -476,11 +1258,11 @@ const NAME_STATUS = {
476
1258
  T: "modified"
477
1259
  };
478
1260
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
479
- function untrackedLines(root, relPath) {
1261
+ async function untrackedLines(root, relPath) {
480
1262
  const absolute = node_path.default.join(root, relPath);
481
1263
  let stat;
482
1264
  try {
483
- stat = node_fs.default.lstatSync(absolute);
1265
+ stat = await node_fs_promises.default.lstat(absolute);
484
1266
  } catch {
485
1267
  return;
486
1268
  }
@@ -489,7 +1271,7 @@ function untrackedLines(root, relPath) {
489
1271
  binary: false
490
1272
  };
491
1273
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
492
- const content = node_fs.default.readFileSync(absolute);
1274
+ const content = await node_fs_promises.default.readFile(absolute);
493
1275
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
494
1276
  lines: 0,
495
1277
  binary: true
@@ -561,9 +1343,9 @@ function parseUnifiedDiff(diff) {
561
1343
  function createBranchDiff() {
562
1344
  return {
563
1345
  async review(cwd, options = {}) {
564
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1346
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
565
1347
  if (root === void 0) return void 0;
566
- const branch = await readLine$1(root, [
1348
+ const branch = await readLine(root, [
567
1349
  "symbolic-ref",
568
1350
  "--quiet",
569
1351
  "--short",
@@ -612,8 +1394,8 @@ function createBranchDiff() {
612
1394
  "--exclude-standard",
613
1395
  "-z"
614
1396
  ]));
615
- untracked.forEach((relPath, index) => {
616
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
1397
+ for (const [index, relPath] of untracked.entries()) {
1398
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
617
1399
  entries.push({
618
1400
  path: relPath,
619
1401
  status: "untracked",
@@ -621,22 +1403,24 @@ function createBranchDiff() {
621
1403
  removed: 0,
622
1404
  ...counted?.binary ? { binary: true } : {}
623
1405
  });
624
- });
1406
+ }
625
1407
  entries.sort((left, right) => left.path.localeCompare(right.path));
626
1408
  const conflicts = [...unmerged];
627
- const rebasing = [await readLine$1(root, [
1409
+ const rebaseMerge = await readLine(root, [
628
1410
  "rev-parse",
629
1411
  "--git-path",
630
1412
  "rebase-merge"
631
- ]), await readLine$1(root, [
1413
+ ]);
1414
+ const rebaseApply = await readLine(root, [
632
1415
  "rev-parse",
633
1416
  "--git-path",
634
1417
  "rebase-apply"
635
- ])].some((gitPath) => gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath)));
1418
+ ]);
1419
+ 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
1420
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
637
1421
  let upstream;
638
1422
  if (upstreamRef !== void 0) {
639
- const [behind, ahead] = (await readLine$1(root, [
1423
+ const [behind, ahead] = (await readLine(root, [
640
1424
  "rev-list",
641
1425
  "--left-right",
642
1426
  "--count",
@@ -677,7 +1461,7 @@ function createBranchDiff() {
677
1461
  if (entry === void 0) throw new Error("That path is not in this review.");
678
1462
  if (entry.status === "untracked") {
679
1463
  const absolute = node_path.default.join(review.root, entry.path);
680
- const stat = node_fs.default.lstatSync(absolute);
1464
+ const stat = await node_fs_promises.default.lstat(absolute);
681
1465
  if (stat.isSymbolicLink()) return {
682
1466
  path: entry.path,
683
1467
  hunks: [{
@@ -685,7 +1469,7 @@ function createBranchDiff() {
685
1469
  rows: [{
686
1470
  marker: "+",
687
1471
  line: 1,
688
- content: node_fs.default.readlinkSync(absolute)
1472
+ content: await node_fs_promises.default.readlink(absolute)
689
1473
  }]
690
1474
  }]
691
1475
  };
@@ -694,7 +1478,7 @@ function createBranchDiff() {
694
1478
  hunks: [],
695
1479
  tooLarge: true
696
1480
  };
697
- const content = node_fs.default.readFileSync(absolute);
1481
+ const content = await node_fs_promises.default.readFile(absolute);
698
1482
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
699
1483
  path: entry.path,
700
1484
  hunks: [],
@@ -719,7 +1503,7 @@ function createBranchDiff() {
719
1503
  }]
720
1504
  };
721
1505
  }
722
- const result = await require_worktreeOperations.runGit(review.root, [
1506
+ const result = await require_gitDependencies.runGit(review.root, [
723
1507
  "diff",
724
1508
  "-U3",
725
1509
  "--no-color",
@@ -730,7 +1514,7 @@ function createBranchDiff() {
730
1514
  "--",
731
1515
  `:(top,literal)${entry.path}`
732
1516
  ], {
733
- timeout: require_worktreeOperations.READ_TIMEOUT_MS,
1517
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
734
1518
  maxBuffer: MAX_FILE_BYTES
735
1519
  });
736
1520
  if (result.overflow) return {
@@ -783,7 +1567,6 @@ const LOOSE_BITS = 63;
783
1567
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
784
1568
  const MAX_USERNAME = 256;
785
1569
  const MAX_TOKEN = 4096;
786
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
787
1570
  /** Environment that would make git log or skip what this module relies on. */
788
1571
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
789
1572
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -811,9 +1594,9 @@ function isRecord(value) {
811
1594
  return typeof value === "object" && value !== null && !Array.isArray(value);
812
1595
  }
813
1596
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
814
- function workspaceKey(workspaceRoot) {
1597
+ async function workspaceKey(workspaceRoot) {
815
1598
  try {
816
- return node_fs.default.realpathSync(workspaceRoot);
1599
+ return await node_fs_promises.default.realpath(workspaceRoot);
817
1600
  } catch {
818
1601
  return node_path.default.resolve(workspaceRoot);
819
1602
  }
@@ -862,21 +1645,21 @@ function publicView(config) {
862
1645
  * the saved one, and only for the same host: a token never follows a host it
863
1646
  * was not entered for.
864
1647
  */
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.");
1648
+ async function parseGitAuthSave(request, current, homeDir) {
1649
+ if (!isRecord(request)) throw require_gitDependencies.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
867
1650
  if (request.method === "none") return { method: "none" };
868
1651
  if (request.method === "ssh") {
869
1652
  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 ~/.");
1653
+ 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
1654
  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 ~/.");
1655
+ 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
1656
  let isFile = false;
874
1657
  try {
875
- isFile = node_fs.default.statSync(expandHome(keyPath, homeDir)).isFile();
1658
+ isFile = (await node_fs_promises.default.stat(expandHome(keyPath, homeDir))).isFile();
876
1659
  } catch {
877
1660
  isFile = false;
878
1661
  }
879
- if (!isFile) throw require_worktreeOperations.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
1662
+ if (!isFile) throw require_gitDependencies.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
880
1663
  return {
881
1664
  method: "ssh",
882
1665
  keyPath
@@ -884,11 +1667,11 @@ function parseGitAuthSave(request, current, homeDir) {
884
1667
  }
885
1668
  if (request.method === "https") {
886
1669
  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.");
1670
+ 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
1671
  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.");
1672
+ 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
1673
  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.");
1674
+ 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
1675
  return {
893
1676
  method: "https",
894
1677
  host,
@@ -902,21 +1685,21 @@ function parseGitAuthSave(request, current, homeDir) {
902
1685
  username,
903
1686
  token: current.token
904
1687
  };
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.");
1688
+ 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
1689
  }
907
- throw require_worktreeOperations.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
1690
+ throw require_gitDependencies.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
908
1691
  }
909
1692
  /** Tightens a file or folder something left readable by group or others. */
910
- function tighten(target, mode) {
1693
+ async function tighten(target, mode) {
911
1694
  try {
912
- if ((node_fs.default.statSync(target).mode & LOOSE_BITS) !== 0) node_fs.default.chmodSync(target, mode);
1695
+ if (((await node_fs_promises.default.stat(target)).mode & LOOSE_BITS) !== 0) await node_fs_promises.default.chmod(target, mode);
913
1696
  } catch {}
914
1697
  }
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);
1698
+ function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {}) {
1699
+ const file = require_gitDependencies.credentialsFile(homeDir, environment);
1700
+ const readFile = async () => {
1701
+ await tighten(file, OWNER_ONLY_FILE);
1702
+ const raw = await require_gitDependencies.readJson(file);
920
1703
  const workspaces = {};
921
1704
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
922
1705
  const config = parseConfig(value);
@@ -927,28 +1710,28 @@ function createGitAuthStore(homeDir = node_os.default.homedir()) {
927
1710
  workspaces
928
1711
  };
929
1712
  };
930
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1713
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
931
1714
  return {
932
1715
  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.doomGitRoot(homeDir);
939
- node_fs.default.mkdirSync(root, {
1716
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1717
+ async save(workspaceRoot, request) {
1718
+ const key = await workspaceKey(workspaceRoot);
1719
+ const current = await readFile();
1720
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1721
+ const root = require_gitDependencies.poGitRoot(homeDir, environment);
1722
+ await node_fs_promises.default.mkdir(root, {
940
1723
  recursive: true,
941
1724
  mode: OWNER_ONLY_DIRECTORY
942
1725
  });
943
- node_fs.default.chmodSync(root, OWNER_ONLY_DIRECTORY);
1726
+ await node_fs_promises.default.chmod(root, OWNER_ONLY_DIRECTORY);
944
1727
  const workspaces = { ...current.workspaces };
945
1728
  if (next.method === "none") delete workspaces[key];
946
1729
  else workspaces[key] = next;
947
- require_worktreeOperations.writeJsonAtomic(file, {
1730
+ await require_gitDependencies.writeJsonAtomic(file, {
948
1731
  version: 1,
949
1732
  workspaces
950
1733
  });
951
- node_fs.default.chmodSync(file, OWNER_ONLY_FILE);
1734
+ await node_fs_promises.default.chmod(file, OWNER_ONLY_FILE);
952
1735
  return publicView(next);
953
1736
  }
954
1737
  };
@@ -1047,252 +1830,14 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1047
1830
  };
1048
1831
  }
1049
1832
  //#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.DoomGitExpectedError) 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.DoomGitExpectedError && 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
1833
  //#region src/services/gitFailure/index.ts
1834
+ const english = (_key, fallback, vars) => (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars);
1290
1835
  const RULES = [
1291
1836
  {
1292
1837
  code: "host_key_changed",
1293
1838
  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.",
1839
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1840
+ 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
1841
  retryable: false
1297
1842
  },
1298
1843
  {
@@ -1302,8 +1847,8 @@ const RULES = [
1302
1847
  "no ed25519 host key is known",
1303
1848
  "no rsa host key is known"
1304
1849
  ],
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.",
1850
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1851
+ 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
1852
  retryable: false
1308
1853
  },
1309
1854
  {
@@ -1320,15 +1865,15 @@ const RULES = [
1320
1865
  "unprotected private key",
1321
1866
  "invalid format"
1322
1867
  ],
1323
- message: "The remote refused the credentials.",
1324
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1868
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1869
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1325
1870
  retryable: false
1326
1871
  },
1327
1872
  {
1328
1873
  code: "repository_not_found",
1329
1874
  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}`,
1875
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1876
+ 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
1877
  retryable: false
1333
1878
  },
1334
1879
  {
@@ -1341,22 +1886,22 @@ const RULES = [
1341
1886
  "unable to access",
1342
1887
  "network is unreachable"
1343
1888
  ],
1344
- message: "The remote could not be reached.",
1345
- recovery: "Check the network and the remote URL, then try again.",
1889
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1890
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1346
1891
  retryable: true
1347
1892
  },
1348
1893
  {
1349
1894
  code: "push_lease_rejected",
1350
1895
  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.",
1896
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1897
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1353
1898
  retryable: false
1354
1899
  },
1355
1900
  {
1356
1901
  code: "push_needs_force",
1357
1902
  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.",
1903
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1904
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1360
1905
  retryable: false
1361
1906
  },
1362
1907
  {
@@ -1367,18 +1912,21 @@ const RULES = [
1367
1912
  "would be overwritten",
1368
1913
  "your index contains uncommitted changes"
1369
1914
  ],
1370
- message: "There are uncommitted changes in the way.",
1371
- recovery: "Commit or stash your changes first.",
1915
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1916
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1372
1917
  retryable: false
1373
1918
  }
1374
1919
  ];
1375
- function classifyGitFailure(operation, result, mismatch) {
1376
- if (result.timedOut) return new require_worktreeOperations.DoomGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1920
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1921
+ 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
1922
  const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1378
1923
  const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1379
- if (rule === void 0) return new require_worktreeOperations.DoomGitExpectedError("git_failed", `git ${operation} failed (exit ${String(result.code)}).`, false, "Run the same command in a terminal in this checkout to see what git says.");
1380
- const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1381
- return new require_worktreeOperations.DoomGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1924
+ if (rule === void 0) return new require_gitDependencies.PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1925
+ operation,
1926
+ code: String(result.code)
1927
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1928
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1929
+ return new require_gitDependencies.PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1382
1930
  }
1383
1931
  //#endregion
1384
1932
  //#region src/services/gitSync/index.ts
@@ -1401,61 +1949,68 @@ function classifyGitFailure(operation, result, mismatch) {
1401
1949
  */
1402
1950
  const DONE = { outcome: "done" };
1403
1951
  function expected(code, message, recovery) {
1404
- return new require_worktreeOperations.DoomGitExpectedError(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;
1410
- }
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;
1952
+ return new require_gitDependencies.PoGitExpectedError(code, message, false, recovery);
1415
1953
  }
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
1954
+ function createGitSync(options) {
1955
+ const baseEnv = options.baseEnv ?? {};
1956
+ async function readLine(cwd, args) {
1957
+ const result = await require_gitDependencies.runGit(cwd, args, {
1958
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1959
+ env: baseEnv
1960
+ });
1961
+ const out = result.stdout.trim();
1962
+ return result.code === 0 && out !== "" ? out : void 0;
1963
+ }
1964
+ async function toplevel(cwd) {
1965
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1966
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1967
+ return root;
1968
+ }
1969
+ async function rebasing(root) {
1970
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1971
+ const gitPath = await readLine(root, [
1972
+ "rev-parse",
1973
+ "--git-path",
1974
+ name
1975
+ ]);
1976
+ if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1977
+ }
1978
+ return false;
1979
+ }
1980
+ async function conflicts(root) {
1981
+ return (await require_gitDependencies.runGit(root, [
1982
+ "diff",
1983
+ "--name-only",
1984
+ "--diff-filter=U",
1985
+ "-z"
1986
+ ], {
1987
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1988
+ env: baseEnv
1989
+ })).stdout.split("\0").filter((file) => file !== "");
1990
+ }
1991
+ async function currentBranch(root) {
1992
+ const branch = await readLine(root, [
1993
+ "symbolic-ref",
1994
+ "--quiet",
1995
+ "--short",
1996
+ "HEAD"
1422
1997
  ]);
1423
- if (gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath))) return true;
1998
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1999
+ return branch;
1424
2000
  }
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.");
2001
+ async function guard(root, needsCleanTree) {
2002
+ 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.");
2003
+ const branch = await currentBranch(root);
2004
+ if (needsCleanTree) {
2005
+ if (await readLine(root, [
2006
+ "status",
2007
+ "--porcelain",
2008
+ "--untracked-files=no"
2009
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2010
+ }
2011
+ return branch;
1454
2012
  }
1455
- return branch;
1456
- }
1457
- function createGitSync(options) {
1458
- const baseEnv = options.baseEnv ?? process.env;
2013
+ const baselines = /* @__PURE__ */ new Map();
1459
2014
  /** One credentialed network command against `remote`, classified on failure. */
1460
2015
  const network = async (root, context, remote, operation, args, urlArgs = []) => {
1461
2016
  const url = await readLine(root, [
@@ -1466,28 +2021,44 @@ function createGitSync(options) {
1466
2021
  ]);
1467
2022
  if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1468
2023
  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
2024
+ const result = await require_gitDependencies.runGit(root, args, {
2025
+ timeout: require_gitDependencies.NETWORK_TIMEOUT_MS,
2026
+ env: prepared.env,
2027
+ ...context.signal ? { signal: context.signal } : {}
1472
2028
  });
1473
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
2029
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
1474
2030
  };
1475
2031
  /** 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,
2032
+ const rebaseOnto = async (root, onto, context) => {
2033
+ context.signal?.throwIfAborted();
2034
+ const before = baselines.get(root) ?? await require_gitDependencies.revision(root, "HEAD", {
2035
+ env: baseEnv,
2036
+ ...context.signal ? { signal: context.signal } : {}
2037
+ });
2038
+ baselines.set(root, before);
2039
+ const result = await require_gitDependencies.runGit(root, ["rebase", onto], {
2040
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2041
+ ...context.signal ? { signal: context.signal } : {},
1479
2042
  env: {
1480
2043
  ...baseEnv,
1481
2044
  GIT_EDITOR: "true",
1482
2045
  GIT_TERMINAL_PROMPT: "0"
1483
2046
  }
1484
2047
  });
1485
- if (result.code === 0) return DONE;
2048
+ if (result.code === 0) {
2049
+ if (before !== await require_gitDependencies.revision(root, "HEAD", {
2050
+ env: baseEnv,
2051
+ ...context.signal ? { signal: context.signal } : {}
2052
+ })) await options.reapplySparse?.(root, context.signal);
2053
+ baselines.delete(root);
2054
+ return DONE;
2055
+ }
1486
2056
  if (await rebasing(root)) return {
1487
2057
  outcome: "paused",
1488
2058
  conflicts: await conflicts(root)
1489
2059
  };
1490
- throw classifyGitFailure("rebase", result);
2060
+ baselines.delete(root);
2061
+ throw classifyGitFailure("rebase", result, void 0, context.t);
1491
2062
  };
1492
2063
  /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1493
2064
  const remoteOfRef = async (root, ref) => {
@@ -1518,7 +2089,7 @@ function createGitSync(options) {
1518
2089
  "--prune",
1519
2090
  remote
1520
2091
  ]);
1521
- return rebaseOnto(root, upstream);
2092
+ return rebaseOnto(root, upstream, context);
1522
2093
  },
1523
2094
  async push(context, force) {
1524
2095
  const root = await toplevel(context.cwd);
@@ -1550,18 +2121,409 @@ function createGitSync(options) {
1550
2121
  "--prune",
1551
2122
  remote
1552
2123
  ]);
1553
- return rebaseOnto(root, base);
2124
+ return rebaseOnto(root, base, context);
1554
2125
  },
1555
2126
  async abortRebase(context) {
1556
2127
  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);
2128
+ if (!await rebasing(root)) {
2129
+ baselines.delete(root);
2130
+ return DONE;
2131
+ }
2132
+ const result = await require_gitDependencies.runGit(root, ["rebase", "--abort"], {
2133
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2134
+ env: baseEnv,
2135
+ ...context.signal ? { signal: context.signal } : {}
2136
+ });
2137
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2138
+ baselines.delete(root);
1560
2139
  return DONE;
1561
2140
  }
1562
2141
  };
1563
2142
  }
1564
2143
  //#endregion
2144
+ //#region src/services/newSessionRequest/index.ts
2145
+ const MAX_NAME_LENGTH = 120;
2146
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2147
+ function optionalText(value) {
2148
+ if (value === void 0) return void 0;
2149
+ if (typeof value !== "string") return false;
2150
+ const trimmed = value.trim();
2151
+ return trimmed === "" ? void 0 : trimmed;
2152
+ }
2153
+ /**
2154
+ * Validates a new-session dialog request for a worktree session. Every ref is
2155
+ * checked here, before it can reach git as a positional argument.
2156
+ */
2157
+ function newSessionRequest(body) {
2158
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2159
+ const record = body;
2160
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2161
+ const branch = optionalText(record.branch);
2162
+ if (branch === void 0 || branch === false || !require_gitDependencies.validRefName(branch)) return { error: "A valid branch name is required." };
2163
+ const name = optionalText(record.name);
2164
+ 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.` };
2165
+ if (Object.hasOwn(record, "sparseProfile") && !require_gitDependencies.validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2166
+ const chosen = record.selection === void 0 ? {} : (0, _agimon_ai_po_core_hubChannel.parseLaunchSelection)(record.selection);
2167
+ if ("error" in chosen) return chosen;
2168
+ const profile = chosen.selection?.profile;
2169
+ const named = {
2170
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2171
+ ...name === void 0 ? {} : { name },
2172
+ ...profile === void 0 ? {} : { selection: { profile } }
2173
+ };
2174
+ if (record.mode === "existing-branch") {
2175
+ const remote = optionalText(record.remote);
2176
+ if (remote === false || remote !== void 0 && !require_gitDependencies.validRefName(remote)) return { error: "That remote name is not valid." };
2177
+ return {
2178
+ mode: "existing-branch",
2179
+ branch,
2180
+ ...remote === void 0 ? {} : { remote },
2181
+ ...named
2182
+ };
2183
+ }
2184
+ if (record.mode === "new-branch") {
2185
+ const baseRef = optionalText(record.baseRef);
2186
+ if (baseRef === false || baseRef !== void 0 && !require_gitDependencies.validRefName(baseRef)) return { error: "That base branch is not valid." };
2187
+ return {
2188
+ mode: "new-branch",
2189
+ branch,
2190
+ ...baseRef === void 0 ? {} : { baseRef },
2191
+ ...named
2192
+ };
2193
+ }
2194
+ return { error: "The mode must be existing-branch or new-branch." };
2195
+ }
2196
+ //#endregion
2197
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2198
+ /**
2199
+ * The worktree surface the cockpit panel calls.
2200
+ *
2201
+ * Hub-scoped because worktrees are a property of a repository, not of one
2202
+ * session: the panel lists and creates them whether or not the session that
2203
+ * made them is focused, and a session-scoped API would disappear with it.
2204
+ *
2205
+ * The panel names a repository by the hub's opaque id and never by path.
2206
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2207
+ * point this at a directory the cockpit was never given.
2208
+ */
2209
+ function badRequest(message) {
2210
+ return Response.json({ error: message }, { status: 400 });
2211
+ }
2212
+ function failed(error) {
2213
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return Response.json({
2214
+ error: error.message,
2215
+ code: error.code
2216
+ }, { status: error.retryable ? 503 : 409 });
2217
+ return Response.json({ error: "The worktree operation failed." }, { status: 500 });
2218
+ }
2219
+ function createGitApi(openDirectory, dependencies = {}, translate) {
2220
+ return {
2221
+ basePath: "git",
2222
+ start(context) {
2223
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
2224
+ const directEvents = context.directEvents;
2225
+ const publishLifecycle = (sessionId, repositoryRoot) => {
2226
+ directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
2227
+ version: 1,
2228
+ repositoryRoot
2229
+ });
2230
+ };
2231
+ const git = require_gitDependencies.createWorktreeGit();
2232
+ const operations = require_gitDependencies.createWorktreeOperations({
2233
+ ...dependencies,
2234
+ git,
2235
+ sessionService: context.sessionService,
2236
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
2237
+ ...context.environment === void 0 ? {} : { environment: context.environment }
2238
+ });
2239
+ const sync = createGitSync({
2240
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2241
+ baseEnv: context.environment ?? {},
2242
+ async reapplySparse(cwd, signal) {
2243
+ 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);
2244
+ if (record?.sparseProfile) await operations.reapply({
2245
+ cwd,
2246
+ sessionId: context.sessionId
2247
+ }, record.id, { signal });
2248
+ }
2249
+ });
2250
+ const sessionCommand = async (request, url) => {
2251
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2252
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2253
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2254
+ const caller = {
2255
+ cwd: context.cwd,
2256
+ sessionId: context.sessionId
2257
+ };
2258
+ const body = await request.json().catch(() => void 0);
2259
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2260
+ const command = body;
2261
+ if (url.pathname === "/sync") {
2262
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2263
+ const recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2264
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2265
+ const syncContext = {
2266
+ ...caller,
2267
+ auth,
2268
+ recordedBaseRef,
2269
+ signal: request.signal,
2270
+ ...translate ? { t: translate } : {}
2271
+ };
2272
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2273
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2274
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2275
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2276
+ return badRequest("Unknown sync command.");
2277
+ }
2278
+ if (Object.keys(command).some((key) => ![
2279
+ "action",
2280
+ "branch",
2281
+ "baseRef",
2282
+ "sparseProfile",
2283
+ "reservationId",
2284
+ "id",
2285
+ "force",
2286
+ "folders"
2287
+ ].includes(key))) return badRequest("Unknown command field.");
2288
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2289
+ if (command.action === "create") {
2290
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2291
+ const result = await operations.spawn(caller, {
2292
+ branch: command.branch,
2293
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2294
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2295
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2296
+ }, { signal: request.signal });
2297
+ return Response.json({ worktree: result });
2298
+ }
2299
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2300
+ if (![
2301
+ "profiles",
2302
+ "expand",
2303
+ "reapply"
2304
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2305
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2306
+ return Response.json(result.details);
2307
+ };
2308
+ /**
2309
+ * The new-session dialog's routes: the workspace's branches, and a top-level
2310
+ * worktree session on one. Workspace-mounted only, and always rooted at the
2311
+ * mount's own workspace, so a request can never name another directory.
2312
+ */
2313
+ const newSession = async (request, url) => {
2314
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
2315
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
2316
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
2317
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
2318
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
2319
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
2320
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2321
+ if (isBranches) {
2322
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2323
+ const branches = repositoryRoot === void 0 ? {
2324
+ repository: false,
2325
+ local: [],
2326
+ remote: []
2327
+ } : {
2328
+ repository: true,
2329
+ ...await git.listBranches(repositoryRoot),
2330
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
2331
+ };
2332
+ return Response.json(branches);
2333
+ }
2334
+ if (isDelete || isOpen) {
2335
+ 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 });
2336
+ const body = await request.json().catch(() => void 0);
2337
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
2338
+ if (typeof branch !== "string" || !require_gitDependencies.validRefName(branch)) return badRequest("A valid branch name is required.");
2339
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2340
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
2341
+ const branches = await git.listBranches(repositoryRoot);
2342
+ const local = branches.local.find((item) => item.name === branch);
2343
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
2344
+ if (isOpen) {
2345
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
2346
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
2347
+ try {
2348
+ await openDirectory(local.checkedOutAt);
2349
+ return Response.json({ opened: true });
2350
+ } catch {
2351
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
2352
+ }
2353
+ }
2354
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
2355
+ if (!await git.deleteBranch({
2356
+ repositoryRoot,
2357
+ branch
2358
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
2359
+ return Response.json({ deleted: true });
2360
+ }
2361
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
2362
+ if ("error" in parsed) return badRequest(parsed.error);
2363
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
2364
+ branch: parsed.branch,
2365
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
2366
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
2367
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
2368
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
2369
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
2370
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
2371
+ }, { signal: request.signal });
2372
+ publishLifecycle(record.sessionId, record.repositoryRoot);
2373
+ const created = {
2374
+ sessionId: record.sessionId,
2375
+ worktreeId: record.id
2376
+ };
2377
+ return Response.json(created, { status: 201 });
2378
+ };
2379
+ /** The admitted root for a request, or a response explaining why not. */
2380
+ const rootOf = (url) => {
2381
+ const repositoryId = url.searchParams.get("repositoryId");
2382
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
2383
+ const root = context.resolveRepository?.(repositoryId);
2384
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
2385
+ return root;
2386
+ };
2387
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
2388
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir, context.environment);
2389
+ const branchDiff = createBranchDiff();
2390
+ const pendingReviews = /* @__PURE__ */ new Map();
2391
+ /**
2392
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
2393
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
2394
+ * The view never carries the token.
2395
+ */
2396
+ const auth = async (request, url) => {
2397
+ if (url.pathname !== "/auth") return void 0;
2398
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2399
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
2400
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
2401
+ const root = rootOf(url);
2402
+ if (root instanceof Response) return root;
2403
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
2404
+ try {
2405
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
2406
+ } catch (error) {
2407
+ if (error instanceof require_gitDependencies.PoGitExpectedError && error.code === "invalid_request") {
2408
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2409
+ return Response.json({
2410
+ error: text,
2411
+ code: error.code
2412
+ }, { status: 400 });
2413
+ }
2414
+ throw error;
2415
+ }
2416
+ };
2417
+ /**
2418
+ * The session's change against its base. Session mounts only, rooted at the
2419
+ * session's own checkout; a file is served only when it is in the change set
2420
+ * computed for the request. Overlapping requests share an in-flight snapshot.
2421
+ */
2422
+ const review = async (request, url) => {
2423
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
2424
+ const cwd = context.scope === "session" ? context.cwd : void 0;
2425
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2426
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
2427
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
2428
+ let recordedBaseRef;
2429
+ try {
2430
+ recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
2431
+ } catch {
2432
+ recordedBaseRef = void 0;
2433
+ }
2434
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
2435
+ let pending = pendingReviews.get(key);
2436
+ if (pending === void 0) {
2437
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
2438
+ pendingReviews.set(key, pending);
2439
+ }
2440
+ const result = await pending;
2441
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
2442
+ repository: false,
2443
+ files: []
2444
+ });
2445
+ const filePath = url.searchParams.get("path") ?? "";
2446
+ 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 });
2447
+ return Response.json(await branchDiff.fileDiff(result, filePath));
2448
+ };
2449
+ return {
2450
+ async fetch(request) {
2451
+ const url = new URL(request.url);
2452
+ try {
2453
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2454
+ if (answered !== void 0) return answered;
2455
+ } catch (error) {
2456
+ context.onNotice(`git request failed: ${error.name}`);
2457
+ return failed(error);
2458
+ }
2459
+ const root = rootOf(url);
2460
+ if (root instanceof Response) return root;
2461
+ const callerContext = {
2462
+ cwd: root,
2463
+ sessionId: url.searchParams.get("sessionId") ?? ""
2464
+ };
2465
+ 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.");
2466
+ try {
2467
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
2468
+ if (request.method === "POST" && url.pathname === "/worktrees") {
2469
+ const body = await request.json();
2470
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
2471
+ const record = await operations.spawn(callerContext, {
2472
+ branch: body.branch,
2473
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
2474
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
2475
+ ...body.name === void 0 ? {} : { name: body.name }
2476
+ });
2477
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2478
+ return Response.json({ worktree: record }, { status: 201 });
2479
+ }
2480
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
2481
+ if (request.method === "DELETE" && closing) {
2482
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
2483
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2484
+ return Response.json({ worktree: record });
2485
+ }
2486
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
2487
+ } catch (error) {
2488
+ context.onNotice(`worktree request failed: ${error.name}`);
2489
+ return failed(error);
2490
+ }
2491
+ },
2492
+ close() {}
2493
+ };
2494
+ }
2495
+ };
2496
+ }
2497
+ //#endregion
2498
+ //#region src/extensions/(backend)/api/git/route.server.ts
2499
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)((plugin) => {
2500
+ const { context, host, signal } = plugin;
2501
+ let openDirectory;
2502
+ context.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
2503
+ const shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
2504
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
2505
+ openDirectory = async (path) => {
2506
+ const result = await shell.exec([
2507
+ "/usr/bin/open",
2508
+ "-a",
2509
+ "Finder",
2510
+ path
2511
+ ], {
2512
+ env,
2513
+ inheritEnv: false
2514
+ }, (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
2515
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
2516
+ };
2517
+ return () => {
2518
+ openDirectory = void 0;
2519
+ };
2520
+ });
2521
+ return createGitApi(async (path) => {
2522
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
2523
+ await openDirectory(path);
2524
+ }, 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));
2525
+ });
2526
+ //#endregion
1565
2527
  //#region src/types/gitReview.ts
1566
2528
  /**
1567
2529
  * The cockpit's view of what this session changed against its base: the counts
@@ -1590,9 +2552,10 @@ const GIT_CHANGES_TYPE = "git_changes";
1590
2552
  * DESIGN PATTERNS:
1591
2553
  * - Apart from the worktrees channel. Worktrees are repository management;
1592
2554
  * this is the session's own code change.
1593
- * - Push, not poll. The session facet publishes a "changed" event after every
1594
- * tool call and settled turn; recounts are coalesced to one in flight plus
1595
- * one rerun, so a burst of tool calls costs at most two.
2555
+ * - Push, not poll. The session's server plugin publishes a "changed" event
2556
+ * after every tool call that can write and every settled turn; a recount
2557
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
2558
+ * in flight plus one rerun.
1596
2559
  * - One sync command per session. A rebase and a push must never overlap.
1597
2560
  * - Auth is read fresh for each command from the session's workspace, and goes
1598
2561
  * only into that command's git child.
@@ -1601,6 +2564,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1601
2564
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1602
2565
  * stderr and drops it, because a remote URL in it can carry a token.
1603
2566
  */
2567
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
2568
+ const REFRESH_DELAY_MS = 1500;
1604
2569
  function payloadOf$1(state) {
1605
2570
  return {
1606
2571
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1628,13 +2593,13 @@ const PENDING = {
1628
2593
  /** The error target a failure maps to: a rejected plain push asks for a confirmed lease force. */
1629
2594
  function errorTargetFor$1(command, error) {
1630
2595
  if (command.action !== "push") return { action: command.action };
1631
- return error instanceof require_worktreeOperations.DoomGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
2596
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
1632
2597
  action: "push",
1633
2598
  forceRequired: true
1634
2599
  } : { action: "push" };
1635
2600
  }
1636
2601
  function failureText$1(error) {
1637
- if (error instanceof require_worktreeOperations.DoomGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2602
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1638
2603
  return "The git command failed.";
1639
2604
  }
1640
2605
  function createGitChangesChannel(options = {}) {
@@ -1645,17 +2610,19 @@ function createGitChangesChannel(options = {}) {
1645
2610
  const homeDir = options.homeDir ?? node_os.default.homedir();
1646
2611
  const diff = options.diff ?? createBranchDiff();
1647
2612
  const sync = options.sync ?? createGitSync({ homeDir });
1648
- const auth = options.auth ?? createGitAuthStore(homeDir);
2613
+ const auth = options.auth ?? createGitAuthStore(homeDir, options.environment);
1649
2614
  const latest = /* @__PURE__ */ new Map();
1650
2615
  const subscriptions = /* @__PURE__ */ new Map();
1651
2616
  const scopes = /* @__PURE__ */ new Map();
1652
2617
  const inFlight = /* @__PURE__ */ new Set();
1653
2618
  const rerun = /* @__PURE__ */ new Set();
1654
2619
  const busy = /* @__PURE__ */ new Set();
2620
+ const delayed = /* @__PURE__ */ new Map();
2621
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1655
2622
  /** The base the session's own worktree was created from, when it has one. */
1656
- const recordedBaseRef = (scope) => {
2623
+ const recordedBaseRef = async (scope) => {
1657
2624
  try {
1658
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
2625
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1659
2626
  } catch {
1660
2627
  return;
1661
2628
  }
@@ -1688,8 +2655,7 @@ function createGitChangesChannel(options = {}) {
1688
2655
  return;
1689
2656
  }
1690
2657
  inFlight.add(sessionId);
1691
- const base = recordedBaseRef(scope);
1692
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
2658
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1693
2659
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1694
2660
  }).catch((error) => {
1695
2661
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1698,18 +2664,41 @@ function createGitChangesChannel(options = {}) {
1698
2664
  if (rerun.delete(sessionId)) refresh(sessionId);
1699
2665
  });
1700
2666
  };
1701
- const run = (scope, command) => {
2667
+ /** Recounts once the session has been quiet for a moment. */
2668
+ const refreshSoon = (sessionId) => {
2669
+ clearTimeout(delayed.get(sessionId));
2670
+ const timer = setTimeout(() => {
2671
+ delayed.delete(sessionId);
2672
+ refresh(sessionId);
2673
+ }, refreshDelayMs);
2674
+ timer.unref?.();
2675
+ delayed.set(sessionId, timer);
2676
+ };
2677
+ const run = async (scope, command) => {
2678
+ if (options.scopedCommands) {
2679
+ const response = await host.requestSessionApi(scope, {
2680
+ basePath: "git",
2681
+ path: "/sync",
2682
+ method: "POST",
2683
+ body: JSON.stringify(command)
2684
+ });
2685
+ const result = await response.json();
2686
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2687
+ return result;
2688
+ }
1702
2689
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1703
- const base = recordedBaseRef(scope);
2690
+ const base = await recordedBaseRef(scope);
1704
2691
  const context = {
1705
2692
  cwd: scope.cwd,
1706
- auth: auth.read(workspaceRoot),
2693
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
2694
+ auth: await auth.read(workspaceRoot),
1707
2695
  ...base === void 0 ? {} : { recordedBaseRef: base }
1708
2696
  };
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);
2697
+ const sessionSync = sync;
2698
+ if (command.action === "pull") return sessionSync.pull(context);
2699
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2700
+ if (command.action === "rebase") return sessionSync.rebase(context);
2701
+ return sessionSync.abortRebase(context);
1713
2702
  };
1714
2703
  const source = {
1715
2704
  payloadFor(scope) {
@@ -1719,13 +2708,15 @@ function createGitChangesChannel(options = {}) {
1719
2708
  sessionAdded(scope) {
1720
2709
  scopes.set(scope.sessionId, scope);
1721
2710
  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);
2711
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
2712
+ if (require_gitDependencies.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1724
2713
  });
1725
2714
  subscriptions.set(scope.sessionId, unsubscribe);
1726
2715
  },
1727
2716
  sessionRemoved(sessionId) {
1728
2717
  subscriptions.get(sessionId)?.();
2718
+ clearTimeout(delayed.get(sessionId));
2719
+ delayed.delete(sessionId);
1729
2720
  subscriptions.delete(sessionId);
1730
2721
  scopes.delete(sessionId);
1731
2722
  latest.delete(sessionId);
@@ -1734,6 +2725,8 @@ function createGitChangesChannel(options = {}) {
1734
2725
  },
1735
2726
  close() {
1736
2727
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2728
+ for (const timer of delayed.values()) clearTimeout(timer);
2729
+ delayed.clear();
1737
2730
  subscriptions.clear();
1738
2731
  scopes.clear();
1739
2732
  latest.clear();
@@ -1752,7 +2745,7 @@ function createGitChangesChannel(options = {}) {
1752
2745
  errorTarget: void 0
1753
2746
  });
1754
2747
  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.DoomGitExpectedError ? error.code : "unexpected"})`);
2748
+ host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_gitDependencies.PoGitExpectedError ? error.code : "unexpected"})`);
1756
2749
  update(scope.sessionId, {
1757
2750
  pending: void 0,
1758
2751
  error: failureText$1(error),
@@ -1772,7 +2765,12 @@ function createGitChangesChannel(options = {}) {
1772
2765
  }
1773
2766
  //#endregion
1774
2767
  //#region src/extensions/(backend)/channel/git-changes.server.ts
1775
- var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createGitChangesChannel);
2768
+ var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(({ context, host }) => createGitChangesChannel({
2769
+ homeDir: host.context.homeDirectory,
2770
+ environment: host.context.environment,
2771
+ scopedCommands: true,
2772
+ 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)
2773
+ }), { context: true });
1776
2774
  //#endregion
1777
2775
  //#region src/types/webWorktrees.ts
1778
2776
  /**
@@ -1801,9 +2799,9 @@ function payloadOf(state) {
1801
2799
  };
1802
2800
  }
1803
2801
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1804
- function viewsFor(scope, deps) {
2802
+ async function viewsFor(scope, deps) {
1805
2803
  try {
1806
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2804
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
1807
2805
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1808
2806
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1809
2807
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1828,11 +2826,15 @@ function sameList(left, right) {
1828
2826
  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
2827
  });
1830
2828
  }
1831
- function errorTargetFor(command) {
1832
- return command.action === "create" ? { action: "create" } : {
2829
+ function errorTargetFor(command, error) {
2830
+ if (command.action === "close") return {
1833
2831
  action: "close",
1834
2832
  id: command.id
1835
2833
  };
2834
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "rift_missing" ? {
2835
+ action: "create",
2836
+ riftMissing: true
2837
+ } : { action: "create" };
1836
2838
  }
1837
2839
  /** A command the page sent, or undefined when the frame was not one. */
1838
2840
  function parseCommand(payload) {
@@ -1841,7 +2843,9 @@ function parseCommand(payload) {
1841
2843
  if (value.action === "create") {
1842
2844
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
1843
2845
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2846
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
1844
2847
  return {
2848
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
1845
2849
  action: "create",
1846
2850
  branch: value.branch.trim(),
1847
2851
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -1860,11 +2864,15 @@ function parseCommand(payload) {
1860
2864
  /**
1861
2865
  * What the reader is told when a command fails.
1862
2866
  *
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.
2867
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2868
+ * written for the agent's tool result. A dirty close is said in the person's
2869
+ * terms, because its message tells the agent to pass `force`. Anything else is
2870
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1865
2871
  */
1866
2872
  function failureText(error) {
1867
- return error instanceof require_worktreeOperations.DoomGitExpectedError ? error.message : "The worktree operation failed.";
2873
+ if (!(error instanceof require_gitDependencies.PoGitExpectedError)) return "The worktree operation failed.";
2874
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2875
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1868
2876
  }
1869
2877
  /** Starts one direct-event subscription per managed session. */
1870
2878
  function createWorktreesChannel(options = {}) {
@@ -1873,14 +2881,16 @@ function createWorktreesChannel(options = {}) {
1873
2881
  frameType: GIT_WORKTREES_TYPE,
1874
2882
  start(host) {
1875
2883
  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
2884
+ if (sessionService === void 0) throw new require_gitDependencies.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
2885
+ const worktrees = options.operations ?? require_gitDependencies.createWorktreeOperations({
2886
+ git: require_gitDependencies.createWorktreeGit(),
2887
+ sessionService,
2888
+ ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2889
+ ...options.environment === void 0 ? {} : { environment: options.environment }
1880
2890
  });
1881
2891
  /** Announces a successful mutation to this session's lifecycle subscribers. */
1882
2892
  const publishLifecycle = (scope, repositoryRoot) => {
1883
- host.directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
2893
+ host.directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
1884
2894
  version: 1,
1885
2895
  repositoryRoot
1886
2896
  });
@@ -1889,6 +2899,22 @@ function createWorktreesChannel(options = {}) {
1889
2899
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
1890
2900
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
1891
2901
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2902
+ if (options.scopedCommands) {
2903
+ if (!(await host.requestSessionApi(parent, {
2904
+ basePath: "git",
2905
+ path: "/session-worktrees",
2906
+ method: "POST",
2907
+ body: JSON.stringify({
2908
+ action: "create",
2909
+ branch,
2910
+ reservationId
2911
+ }),
2912
+ ...signal ? { signal } : {}
2913
+ })).ok) throw new Error("The conversation worktree could not be created.");
2914
+ const reservations = sessionService.reservations;
2915
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2916
+ return reservations.complete(reservationId, parentSessionId);
2917
+ }
1892
2918
  const record = await worktrees.spawn({
1893
2919
  cwd: parent.cwd,
1894
2920
  sessionId: parent.sessionId
@@ -1905,6 +2931,7 @@ function createWorktreesChannel(options = {}) {
1905
2931
  });
1906
2932
  const views = {
1907
2933
  homeDir: options.homeDir,
2934
+ environment: options.environment,
1908
2935
  sessionService
1909
2936
  };
1910
2937
  const latest = /* @__PURE__ */ new Map();
@@ -1917,10 +2944,13 @@ function createWorktreesChannel(options = {}) {
1917
2944
  return generation;
1918
2945
  };
1919
2946
  /** Republishes a session, skipping a frame that would say nothing new. */
1920
- const publish = (scope, force) => {
2947
+ const publish = async (scope, force) => {
2948
+ const generation = generations.get(scope.sessionId);
2949
+ const worktreeViews = await viewsFor(scope, views);
2950
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1921
2951
  const previous = latest.get(scope.sessionId);
1922
2952
  const next = {
1923
- worktrees: viewsFor(scope, views),
2953
+ worktrees: worktreeViews,
1924
2954
  pending: previous?.pending,
1925
2955
  error: previous?.error,
1926
2956
  errorTarget: previous?.errorTarget
@@ -1932,7 +2962,7 @@ function createWorktreesChannel(options = {}) {
1932
2962
  const mark = (scope, pending, error, errorTarget) => {
1933
2963
  const previous = latest.get(scope.sessionId);
1934
2964
  latest.set(scope.sessionId, {
1935
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2965
+ worktrees: previous?.worktrees ?? [],
1936
2966
  pending,
1937
2967
  error,
1938
2968
  errorTarget
@@ -1948,10 +2978,24 @@ function createWorktreesChannel(options = {}) {
1948
2978
  if (generations.get(scope.sessionId) !== generation) return;
1949
2979
  mark(scope, pending, error, errorTarget);
1950
2980
  };
2981
+ if (options.scopedCommands) {
2982
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2983
+ const response = await host.requestSessionApi(scope, {
2984
+ basePath: "git",
2985
+ path: "/session-worktrees",
2986
+ method: "POST",
2987
+ body: JSON.stringify(command)
2988
+ });
2989
+ const result = await response.json();
2990
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2991
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2992
+ return;
2993
+ }
1951
2994
  if (command.action === "create") {
1952
2995
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
1953
2996
  const record = await worktrees.spawn(context, {
1954
2997
  branch: command.branch,
2998
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
1955
2999
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
1956
3000
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
1957
3001
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -1972,15 +3016,15 @@ function createWorktreesChannel(options = {}) {
1972
3016
  sessionAdded(scope) {
1973
3017
  newGeneration(scope.sessionId);
1974
3018
  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;
3019
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
3020
+ if (!require_gitDependencies.isWorktreeLifecycleEvent(payload)) return;
1977
3021
  let sameRepository = false;
1978
3022
  try {
1979
- sameRepository = require_worktreeOperations.registryFile(scope.cwd, options.homeDir) === require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir);
3023
+ sameRepository = await require_gitDependencies.registryFile(scope.cwd, options.homeDir, options.environment) === await require_gitDependencies.registryFile(payload.repositoryRoot, options.homeDir, options.environment);
1980
3024
  } catch {
1981
3025
  sameRepository = false;
1982
3026
  }
1983
- if (sameRepository) publish(scope, false);
3027
+ if (sameRepository) await publish(scope, false);
1984
3028
  });
1985
3029
  subscriptions.set(scope.sessionId, unsubscribe);
1986
3030
  },
@@ -2013,7 +3057,7 @@ function createWorktreesChannel(options = {}) {
2013
3057
  }).catch((error) => {
2014
3058
  if (generations.get(scope.sessionId) !== generation) return;
2015
3059
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2016
- mark(scope, void 0, failureText(error), errorTargetFor(command));
3060
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2017
3061
  }).finally(() => {
2018
3062
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2019
3063
  });
@@ -2027,7 +3071,11 @@ function createWorktreesChannel(options = {}) {
2027
3071
  }
2028
3072
  //#endregion
2029
3073
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2030
- var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createWorktreesChannel);
3074
+ var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)((plugin) => createWorktreesChannel({
3075
+ homeDir: plugin.host.context.homeDirectory,
3076
+ environment: plugin.host.context.environment,
3077
+ scopedCommands: true
3078
+ }), { context: true });
2031
3079
  //#endregion
2032
3080
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2033
3081
  var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[1]);
@@ -2035,20 +3083,8 @@ var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHo
2035
3083
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2036
3084
  var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
2037
3085
  //#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);
2049
- //#endregion
2050
3086
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2051
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
3087
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2052
3088
  //#endregion
2053
3089
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2054
3090
  var poUseGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poUseGit_server_default$1);
@@ -2058,65 +3094,77 @@ var runWorktree_server_default = (0, _agimon_ai_po_core_extensionFile.defineServ
2058
3094
  //#endregion
2059
3095
  //#region generated/server.ts
2060
3096
  const at = (value, context) => typeof value === "function" ? value(context) : value;
3097
+ /* v8 ignore next -- generated normalization branch */
3098
+ const defined = (values) => values.filter((value) => value !== void 0);
2061
3099
  const via = (identity, value) => value === void 0 ? void 0 : {
2062
3100
  ...identity,
2063
3101
  ...value
2064
3102
  };
2065
- const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
3103
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2066
3104
  name: "@agimon-ai/po-git",
2067
- providerOverrides: (0, _agimon_ai_po_core_serverFacet.composeServerProviderOverrides)(root_server_default),
2068
- global: (context) => ({
2069
- get api() {
2070
- return [at(route_server_default, context)];
2071
- },
2072
- get channels() {
2073
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2074
- }
3105
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
3106
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
3107
+ workspace: [root_server_default$1],
3108
+ session: [root_server_default$1, root_server_default]
2075
3109
  }),
2076
- workspace: (context) => ({
3110
+ host: (context) => ({
2077
3111
  get api() {
2078
3112
  return [at(route_server_default, context)];
2079
3113
  },
2080
3114
  get channels() {
2081
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
3115
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2082
3116
  }
2083
3117
  }),
3118
+ workspace: async (context) => {
3119
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3120
+ return {
3121
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace),
3122
+ get api() {
3123
+ return [at(route_server_default, context)];
3124
+ },
3125
+ get channels() {
3126
+ 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))]);
3127
+ },
3128
+ services: [...scopeWorkspace.services ?? []]
3129
+ };
3130
+ },
2084
3131
  session: async (context) => {
2085
- const scopeSession = await root_server_default(context);
2086
- const contextSession = {
3132
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3133
+ const contextWorkspace = {
2087
3134
  ...context,
3135
+ root: scopeWorkspace.value
3136
+ };
3137
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3138
+ const contextSession = {
3139
+ ...contextWorkspace,
2088
3140
  root: scopeSession.value
2089
3141
  };
2090
3142
  return {
2091
- ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
3143
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace, scopeSession),
2092
3144
  get api() {
2093
3145
  return [at(route_server_default, context)];
2094
3146
  },
2095
3147
  get channels() {
2096
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
3148
+ 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))]);
2097
3149
  },
2098
3150
  get hooks() {
2099
3151
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2100
3152
  },
2101
3153
  get resources() {
2102
- return [
2103
- at(poGit_server_default, contextSession),
2104
- at(poGitReadme_server_default, contextSession),
2105
- at(poUseGit_server_default, contextSession)
2106
- ];
3154
+ return [at(poUseGit_server_default, contextSession)];
2107
3155
  },
2108
3156
  get tools() {
2109
3157
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2110
3158
  },
2111
- services: [...scopeSession.services ?? []],
3159
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2112
3160
  get activities() {
2113
- return [...scopeSession.activities ?? []];
3161
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2114
3162
  }
2115
3163
  };
2116
3164
  }
2117
3165
  });
2118
3166
  //#endregion
2119
- exports.default = facet;
2120
- exports.facet = facet;
3167
+ exports.default = serverPlugin;
3168
+ exports.serverPlugin = serverPlugin;
2121
3169
 
2122
3170
  //# sourceMappingURL=server.cjs.map