@agimon-ai/po-git 0.0.0-alpha.196 → 0.0.0-alpha.197

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.
@@ -2,21 +2,93 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_worktreeOperations = require("../worktreeOperations-BEk4VEj3.cjs");
5
+ const require_gitDependencies = require("../gitDependencies-BnNuImZi.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");
6
9
  let node_fs_promises = require("node:fs/promises");
7
- node_fs_promises = require_worktreeOperations.__toESM(node_fs_promises, 1);
10
+ node_fs_promises = require_gitDependencies.__toESM(node_fs_promises, 1);
11
+ let node_crypto = require("node:crypto");
8
12
  let node_path = require("node:path");
9
- node_path = require_worktreeOperations.__toESM(node_path, 1);
13
+ node_path = require_gitDependencies.__toESM(node_path, 1);
10
14
  let node_os = require("node:os");
11
- node_os = require_worktreeOperations.__toESM(node_os, 1);
12
- let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
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");
14
20
  let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
15
21
  let _agimon_ai_po_session = require("@agimon-ai/po-session");
16
- let typebox = require("typebox");
17
- let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
22
+ let _agimon_ai_po_core_locale = require("@agimon-ai/po-core/locale");
18
23
  let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
19
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
20
92
  //#region src/schemas/runWorktreeTool.ts
21
93
  /**
22
94
  * The tool's action vocabulary.
@@ -33,7 +105,10 @@ const WORKTREE_ACTIONS = {
33
105
  merge: "merge",
34
106
  prune: "prune",
35
107
  send: "send",
36
- messages: "messages"
108
+ messages: "messages",
109
+ profiles: "profiles",
110
+ expand: "expand",
111
+ reapply: "reapply"
37
112
  };
38
113
  /**
39
114
  * Which fields each action accepts.
@@ -48,7 +123,8 @@ const WORKTREE_ACTION_FIELDS = {
48
123
  "branch",
49
124
  "baseRef",
50
125
  "task",
51
- "name"
126
+ "name",
127
+ "sparseProfile"
52
128
  ],
53
129
  close_worktree: [
54
130
  "action",
@@ -68,12 +144,20 @@ const WORKTREE_ACTION_FIELDS = {
68
144
  "id",
69
145
  "message"
70
146
  ],
71
- messages: ["action", "id"]
147
+ messages: ["action", "id"],
148
+ profiles: ["action", "baseRef"],
149
+ expand: [
150
+ "action",
151
+ "id",
152
+ "folders"
153
+ ],
154
+ reapply: ["action", "id"]
72
155
  };
73
156
  const SpawnParams = typebox.Type.Object({
74
157
  action: typebox.Type.Literal(WORKTREE_ACTIONS.spawn_worktree),
75
158
  branch: typebox.Type.String({ minLength: 1 }),
76
159
  baseRef: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
160
+ sparseProfile: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
77
161
  task: typebox.Type.Optional(typebox.Type.String({ minLength: 1 })),
78
162
  name: typebox.Type.Optional(typebox.Type.String({ minLength: 1 }))
79
163
  }, { additionalProperties: false });
@@ -113,7 +197,20 @@ typebox.Type.Union([
113
197
  MergeParams,
114
198
  PruneParams,
115
199
  SendParams,
116
- 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 })
117
214
  ]);
118
215
  /** The actions that accept `field`, so the declared docs cannot drift from the validator. */
119
216
  function acceptingActions(field) {
@@ -143,6 +240,14 @@ const RunWorktreeToolSchema = typebox.Type.Object({
143
240
  minLength: 1,
144
241
  description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions("baseRef")}.`
145
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
+ })),
146
251
  task: typebox.Type.Optional(typebox.Type.String({
147
252
  minLength: 1,
148
253
  description: `First message for the new session. Actions: ${acceptingActions("task")}.`
@@ -170,6 +275,9 @@ const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its
170
275
 
171
276
  Actions:
172
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'.
173
281
  - close_worktree: stop a worktree's session and delete its checkout. Requires 'id'. Refuses a dirty tree unless 'force' is true.
174
282
  - list: every worktree for this repository, with status and relationship to the calling session.
175
283
  - status: one worktree, its relationship to the calling session, and its uncommitted files. Requires 'id'.
@@ -182,27 +290,29 @@ For a nested worktree session, use the record labelled 'child' in list to report
182
290
  Worktrees live outside the repository, under ~/.po/git/worktrees.`;
183
291
  /** Rejects calls that do not match one documented action shape. */
184
292
  function validateParams(input) {
185
- 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.");
186
294
  const record = input;
187
295
  const action = record.action;
188
- 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(", ")}.`);
189
297
  const allowed = WORKTREE_ACTION_FIELDS[action];
190
298
  const unexpected = Object.keys(record).filter((key) => !allowed.includes(key));
191
- 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(", ")}.`);
192
300
  for (const field of ["branch", "id"]) if (allowed.includes(field) && field in record) {
193
301
  const value = record[field];
194
- 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}.`);
195
303
  }
196
304
  for (const field of [
197
305
  "baseRef",
198
306
  "name",
199
307
  "task",
200
- "message"
201
- ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw require_worktreeOperations.invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
202
- 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}.`);
203
- if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw require_worktreeOperations.invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
204
- if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw require_worktreeOperations.invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
205
- 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.");
206
316
  return record;
207
317
  }
208
318
  function describe(record, sessionId) {
@@ -217,9 +327,31 @@ function text(...lines) {
217
327
  }
218
328
  async function executeRunWorktreeTool(params, operations, context, options = {}) {
219
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
+ }
220
351
  case WORKTREE_ACTIONS.spawn_worktree: {
221
352
  const record = await operations.spawn(context, {
222
353
  branch: params.branch,
354
+ ...params.sparseProfile === void 0 ? {} : { sparseProfile: params.sparseProfile },
223
355
  ...params.baseRef === void 0 ? {} : { baseRef: params.baseRef },
224
356
  ...params.name === void 0 ? {} : { name: params.name },
225
357
  ...params.task === void 0 ? {} : { task: params.task }
@@ -317,14 +449,19 @@ interface Worktree {
317
449
  id: string;
318
450
  branch: string;
319
451
  baseRef: string;
320
- /** Absolute path of the checkout, under ~/.po/git/worktrees. */
452
+ /** Absolute path of the checkout. Imported worktrees stay at their original path. */
321
453
  path: string;
322
454
  repositoryRoot: string;
323
455
  /** The session running inside the worktree. */
324
456
  sessionId: string;
325
457
  parentSessionId?: string;
326
458
  status: WorktreeStatus;
459
+ /** started confirms runner launch only; unconfirmed handoffs must not be blindly retried. */
460
+ setupStage?: 'none' | 'started' | 'failed' | 'unconfirmed';
327
461
  createdAt: string;
462
+ sparseProfile?: string;
463
+ extraFolders?: string[];
464
+ sparseFingerprint?: string;
328
465
  /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
329
466
  relationship: 'parent' | 'child' | 'other';
330
467
  }
@@ -357,7 +494,12 @@ declare const worktrees: {
357
494
  * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
358
495
  * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
359
496
  */
360
- spawn(request: { branch: string; baseRef?: string; name?: string; task?: string }): Promise<Worktree>;
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>;
361
503
  /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
362
504
  close(id: string, options?: { force?: boolean }): Promise<Worktree>;
363
505
  /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
@@ -377,7 +519,7 @@ const json = (value) => JSON.parse(JSON.stringify(value));
377
519
  function createWorktreeNamespace(options) {
378
520
  return {
379
521
  name: "worktrees",
380
- summary: "Git worktrees, each with its own Po session nested under this one: worktrees.list, status, spawn, close, merge, prune, send and messages.",
522
+ summary: "Create and manage Git worktree sessions, select or expand a sparse checkout, and start isolated repository workflows.",
381
523
  declarations: DECLARATIONS,
382
524
  bind(run) {
383
525
  if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
@@ -390,13 +532,15 @@ function createWorktreeNamespace(options) {
390
532
  relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
391
533
  });
392
534
  /** One `run_worktree` action through the tool's own code, so the tool and the namespace cannot drift. */
393
- const act = async (name, action, input) => {
535
+ const act = async (name, action, input = {}, target) => {
394
536
  run.signal.throwIfAborted();
395
537
  if (disposed) throw new Error("Worktrees namespace run is disposed.");
396
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.");
397
540
  const params = validateParams({
398
- action,
399
- ...typeof input === "object" && input !== null ? input : {}
541
+ ...input,
542
+ ...target,
543
+ action
400
544
  });
401
545
  const context = {
402
546
  cwd: options.execution.cwd,
@@ -429,6 +573,15 @@ function createWorktreeNamespace(options) {
429
573
  };
430
574
  const record = (result) => view(result.details.records[0]);
431
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 })));
432
585
  members.list = async () => json((await act("list", "list", {})).details.records.map(view));
433
586
  members.status = async (id) => {
434
587
  const { details } = await act("status", "status", { id });
@@ -438,14 +591,36 @@ function createWorktreeNamespace(options) {
438
591
  });
439
592
  };
440
593
  members.spawn = async (request) => json(record(await act("spawn", "spawn_worktree", request)));
441
- members.close = async (id, settings) => json(record(await act("close", "close_worktree", {
442
- ...settings,
443
- id
444
- })));
445
- members.merge = async (id, settings) => json(record(await act("merge", "merge", {
446
- ...settings,
447
- id
448
- })));
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 })));
449
624
  members.prune = async (settings) => {
450
625
  const { plan } = (await act("prune", "prune", settings)).details;
451
626
  return json({
@@ -467,6 +642,368 @@ function createWorktreeNamespace(options) {
467
642
  };
468
643
  }
469
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
+ if (report.errors.length || report.allocation && JSON.stringify(canonical(report.allocation)) !== JSON.stringify(canonical(input.overrides?.allocation))) {
901
+ await update({
902
+ ...attempt,
903
+ state: "rejected"
904
+ }, signal);
905
+ throw new WorktreeWorkflowError("not_started", "Workflow validation failed or its prepared allocation changed.");
906
+ }
907
+ operation(signal).signal.throwIfAborted();
908
+ try {
909
+ record = await options.operations.spawn(context, {
910
+ branch,
911
+ ...input.sparseProfile ? { sparseProfile: input.sparseProfile } : {}
912
+ }, {
913
+ workflow: {
914
+ attemptId: input.attemptId,
915
+ fingerprint
916
+ },
917
+ ...input.preset ? { preset: input.preset } : {},
918
+ signal: operation(signal).signal
919
+ });
920
+ await update({
921
+ ...attempt,
922
+ worktreeId: record.id,
923
+ sessionId: record.sessionId,
924
+ state: "spawned"
925
+ });
926
+ const base = remoteBase(record);
927
+ if (!base) throw new WorktreeWorkflowError("not_started", "The workflow base is not a verifiable remote branch. The checkout was kept.");
928
+ const pending = {
929
+ ...attempt,
930
+ worktreeId: record.id,
931
+ sessionId: record.sessionId,
932
+ state: "admitting"
933
+ };
934
+ await update(pending);
935
+ const admission = await admissions.launch(input.attemptId, input.definition, {
936
+ ...input.overrides,
937
+ env: {
938
+ ...input.overrides?.env,
939
+ SPARO_BASE_REMOTE: base.remote,
940
+ SPARO_BASE_BRANCH: base.branch,
941
+ SPARO_BASE_SHA: base.sha,
942
+ SPARO_BRANCH: record.branch,
943
+ PO_GIT_BASE_REMOTE: base.remote,
944
+ PO_GIT_BASE_BRANCH: base.branch,
945
+ PO_GIT_BASE_SHA: base.sha,
946
+ PO_GIT_BRANCH: record.branch
947
+ },
948
+ targetSessionId: record.sessionId
949
+ });
950
+ return await link(record, pending, admission);
951
+ } catch (error) {
952
+ if (error instanceof WorktreeWorkflowError) throw error;
953
+ throw new WorktreeWorkflowError("unknown", "The workflow launch outcome is uncertain. Inspect the saved attempt before retrying.", { cause: error });
954
+ }
955
+ };
956
+ return {
957
+ start(input, signal) {
958
+ options.signal.throwIfAborted();
959
+ signal?.throwIfAborted();
960
+ 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."));
961
+ const snapshot = structuredClone(input);
962
+ const branch = snapshot.branch ?? defaultBranch(snapshot);
963
+ if (!require_gitDependencies.validRefName(branch)) return Promise.reject(new WorktreeWorkflowError("not_started", "The workflow branch is invalid."));
964
+ const fingerprint = (0, node_crypto.createHash)("sha256").update(JSON.stringify(canonical({
965
+ definition: snapshot.definition,
966
+ branch,
967
+ profile: snapshot.sparseProfile,
968
+ preset: snapshot.preset,
969
+ overrides: snapshot.overrides
970
+ }))).digest("hex");
971
+ const existing = inFlight.get(snapshot.attemptId);
972
+ if (existing) return existing.fingerprint === fingerprint ? existing.promise : Promise.reject(new WorktreeWorkflowError("attempt_conflict", "This workflow attempt is already starting with different arguments."));
973
+ const promise = start(snapshot, branch, fingerprint, signal).finally(() => {
974
+ inFlight.delete(snapshot.attemptId);
975
+ });
976
+ inFlight.set(snapshot.attemptId, {
977
+ fingerprint,
978
+ promise
979
+ });
980
+ return promise;
981
+ },
982
+ async reconcile(signal) {
983
+ operation(signal).signal.throwIfAborted();
984
+ const admissions = options.admissions();
985
+ if (!admissions) return;
986
+ const records = await ownRecords();
987
+ const registry = await store();
988
+ const attempts = await registry.transaction(() => registry.workflowAttempts(), operation(signal).signal);
989
+ for (const attempt of attempts.filter((entry) => entry.launcherSessionId === options.sessionId && ![
990
+ "closed",
991
+ "rejected",
992
+ "retained"
993
+ ].includes(entry.state))) {
994
+ const record = records.find((entry) => entry.id === attempt.worktreeId || entry.workflow.attemptId === attempt.attemptId);
995
+ if (!record || record.status === "orphaned") continue;
996
+ try {
997
+ const admission = await admissions.read(attempt.attemptId);
998
+ if (admission) await link(record, attempt, admission);
999
+ } catch (error) {
1000
+ options.onError(error);
1001
+ }
1002
+ }
1003
+ }
1004
+ };
1005
+ }
1006
+ //#endregion
470
1007
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
471
1008
  function progressResult(action, label) {
472
1009
  return {
@@ -486,18 +1023,66 @@ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
486
1023
  "discover",
487
1024
  "load_skill"
488
1025
  ]);
489
- function createGitSession({ context, host: serverHost, agent, signal }) {
1026
+ async function createGitSession({ context, host: serverHost, agent, signal }) {
490
1027
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
491
1028
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
492
1029
  const sessionId = serverHost.context.sessionId;
493
1030
  const directEvents = serverHost.context.directEvents;
494
- const messageInbox = require_worktreeOperations.createWorktreeMessageInbox(directEvents, sessionId);
495
- const operations = require_worktreeOperations.createWorktreeOperations({
496
- git: require_worktreeOperations.createWorktreeGit(),
1031
+ const messageInbox = require_gitDependencies.createWorktreeMessageInbox(directEvents, sessionId);
1032
+ const setupReceiver = context.inject(["po/runner-launch"], (child) => {
1033
+ const runner = child.get("po/runner-launch");
1034
+ const cwd = serverHost.context.cwd;
1035
+ if (!runner || !cwd) return void 0;
1036
+ return require_gitDependencies.receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal);
1037
+ });
1038
+ const operations = require_gitDependencies.createWorktreeOperations({
1039
+ git: require_gitDependencies.createWorktreeGit(),
1040
+ ...require_gitDependencies.createGitOperationDependencies({
1041
+ context,
1042
+ host: serverHost,
1043
+ signal
1044
+ }),
497
1045
  sessionService: serverHost.context.sessionService,
498
1046
  messageInbox,
499
1047
  sessionDelivery: () => (0, _agimon_ai_po_session.readPoSessionDelivery)(context)
500
1048
  });
1049
+ const homeDirectory = serverHost.context.homeDirectory ?? serverHost.context.environment?.HOME;
1050
+ let workflows;
1051
+ const workflowProvider = context.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], async (scoped) => {
1052
+ if (!homeDirectory || !serverHost.context.cwd) return void 0;
1053
+ const lifetime = new AbortController();
1054
+ const service = createWorktreeWorkflows({
1055
+ sessionId,
1056
+ cwd: serverHost.context.cwd,
1057
+ homeDirectory,
1058
+ environment: serverHost.context.environment ?? {},
1059
+ signal: AbortSignal.any([signal, lifetime.signal]),
1060
+ operations,
1061
+ git: {
1062
+ ...require_gitDependencies.createWorktreeGit(),
1063
+ revision: require_gitDependencies.revision,
1064
+ remoteBranchHead: require_gitDependencies.remoteBranchHead
1065
+ },
1066
+ admissions: () => (0, _agimon_ai_po_core_workflow.readPoWorkflowAdmissionsService)(scoped),
1067
+ runs: () => (0, _agimon_ai_po_core_workflow.readPoWorkflowRunsService)(scoped),
1068
+ onError: (error) => serverHost.context.onNotice(`Workflow checkout retained (${error instanceof Error ? error.name : "unknown error"}).`)
1069
+ });
1070
+ const release = await (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(scoped).provide(require_gitDependencies.GIT_WORKFLOWS_CONTRACT, service);
1071
+ workflows = service;
1072
+ return async () => {
1073
+ if (workflows === service) workflows = void 0;
1074
+ lifetime.abort();
1075
+ await release();
1076
+ };
1077
+ });
1078
+ if (context.get(_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE) !== void 0) await workflowProvider.await();
1079
+ const workflowServices = context.inject([_agimon_ai_po_core_workflow.PO_WORKFLOW_ADMISSIONS_SERVICE, _agimon_ai_po_core_workflow.PO_WORKFLOW_RUNS_SERVICE], async () => {
1080
+ try {
1081
+ await workflows?.reconcile();
1082
+ } catch (error) {
1083
+ serverHost.context.onNotice(`Workflow reconciliation deferred (${error instanceof Error ? error.name : "unknown error"}).`);
1084
+ }
1085
+ });
501
1086
  const resources = [{
502
1087
  name: "codemode-how-to-git",
503
1088
  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.",
@@ -522,7 +1107,7 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
522
1107
  }
523
1108
  };
524
1109
  const changed = (_event, execution) => {
525
- directEvents.publish(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
1110
+ directEvents.publish(require_gitDependencies.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
526
1111
  };
527
1112
  const hooks = [{
528
1113
  event: "tool_execution_end",
@@ -534,6 +1119,7 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
534
1119
  if (agent) {
535
1120
  const namespace = createWorktreeNamespace({
536
1121
  operations,
1122
+ workflows: () => workflows,
537
1123
  execution: agent.context,
538
1124
  assertAvailable: () => {
539
1125
  if (signal?.aborted) throw new Error("Git session is unavailable.");
@@ -556,7 +1142,12 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
556
1142
  tool,
557
1143
  hooks
558
1144
  },
559
- onDispose: () => messageInbox.close()
1145
+ onDispose: async () => {
1146
+ await workflowServices.dispose();
1147
+ await workflowProvider.dispose();
1148
+ await setupReceiver.dispose();
1149
+ messageInbox.close();
1150
+ }
560
1151
  };
561
1152
  }
562
1153
  const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createGitSession);
@@ -592,15 +1183,15 @@ const BINARY_PROBE_BYTES = 8192;
592
1183
  const SHORT_SHA = 7;
593
1184
  const DEFAULT_BRANCHES = ["main", "master"];
594
1185
  async function read(cwd, args) {
595
- const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1186
+ const result = await require_gitDependencies.runGit(cwd, args, { timeout: require_gitDependencies.READ_TIMEOUT_MS });
596
1187
  return result.code === 0 ? result.stdout : void 0;
597
1188
  }
598
- async function readLine$1(cwd, args) {
1189
+ async function readLine(cwd, args) {
599
1190
  const out = (await read(cwd, args))?.trim();
600
1191
  return out === void 0 || out === "" ? void 0 : out;
601
1192
  }
602
1193
  async function commitExists(cwd, ref) {
603
- return await readLine$1(cwd, [
1194
+ return await readLine(cwd, [
604
1195
  "rev-parse",
605
1196
  "--verify",
606
1197
  "--quiet",
@@ -609,7 +1200,7 @@ async function commitExists(cwd, ref) {
609
1200
  }
610
1201
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
611
1202
  async function upstreamOf(cwd, ref) {
612
- return readLine$1(cwd, [
1203
+ return readLine(cwd, [
613
1204
  "rev-parse",
614
1205
  "--abbrev-ref",
615
1206
  "--symbolic-full-name",
@@ -618,13 +1209,13 @@ async function upstreamOf(cwd, ref) {
618
1209
  }
619
1210
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
620
1211
  async function resolveBaseRef(cwd, branch, recordedBaseRef) {
621
- if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
1212
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
622
1213
  "rev-parse",
623
1214
  "--verify",
624
1215
  "--quiet",
625
1216
  `refs/heads/${recordedBaseRef}`
626
1217
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
627
- const originHead = await readLine$1(cwd, [
1218
+ const originHead = await readLine(cwd, [
628
1219
  "symbolic-ref",
629
1220
  "--quiet",
630
1221
  "--short",
@@ -638,7 +1229,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
638
1229
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
639
1230
  const head = await commitExists(cwd, "HEAD");
640
1231
  if (ref !== void 0 && head) {
641
- const mergeBase = await readLine$1(cwd, [
1232
+ const mergeBase = await readLine(cwd, [
642
1233
  "merge-base",
643
1234
  ref,
644
1235
  "HEAD"
@@ -750,9 +1341,9 @@ function parseUnifiedDiff(diff) {
750
1341
  function createBranchDiff() {
751
1342
  return {
752
1343
  async review(cwd, options = {}) {
753
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1344
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
754
1345
  if (root === void 0) return void 0;
755
- const branch = await readLine$1(root, [
1346
+ const branch = await readLine(root, [
756
1347
  "symbolic-ref",
757
1348
  "--quiet",
758
1349
  "--short",
@@ -813,12 +1404,12 @@ function createBranchDiff() {
813
1404
  }
814
1405
  entries.sort((left, right) => left.path.localeCompare(right.path));
815
1406
  const conflicts = [...unmerged];
816
- const rebaseMerge = await readLine$1(root, [
1407
+ const rebaseMerge = await readLine(root, [
817
1408
  "rev-parse",
818
1409
  "--git-path",
819
1410
  "rebase-merge"
820
1411
  ]);
821
- const rebaseApply = await readLine$1(root, [
1412
+ const rebaseApply = await readLine(root, [
822
1413
  "rev-parse",
823
1414
  "--git-path",
824
1415
  "rebase-apply"
@@ -827,7 +1418,7 @@ function createBranchDiff() {
827
1418
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
828
1419
  let upstream;
829
1420
  if (upstreamRef !== void 0) {
830
- const [behind, ahead] = (await readLine$1(root, [
1421
+ const [behind, ahead] = (await readLine(root, [
831
1422
  "rev-list",
832
1423
  "--left-right",
833
1424
  "--count",
@@ -910,7 +1501,7 @@ function createBranchDiff() {
910
1501
  }]
911
1502
  };
912
1503
  }
913
- const result = await require_worktreeOperations.runGit(review.root, [
1504
+ const result = await require_gitDependencies.runGit(review.root, [
914
1505
  "diff",
915
1506
  "-U3",
916
1507
  "--no-color",
@@ -921,7 +1512,7 @@ function createBranchDiff() {
921
1512
  "--",
922
1513
  `:(top,literal)${entry.path}`
923
1514
  ], {
924
- timeout: require_worktreeOperations.READ_TIMEOUT_MS,
1515
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
925
1516
  maxBuffer: MAX_FILE_BYTES
926
1517
  });
927
1518
  if (result.overflow) return {
@@ -974,7 +1565,6 @@ const LOOSE_BITS = 63;
974
1565
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
975
1566
  const MAX_USERNAME = 256;
976
1567
  const MAX_TOKEN = 4096;
977
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
978
1568
  /** Environment that would make git log or skip what this module relies on. */
979
1569
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
980
1570
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -1054,20 +1644,20 @@ function publicView(config) {
1054
1644
  * was not entered for.
1055
1645
  */
1056
1646
  async function parseGitAuthSave(request, current, homeDir) {
1057
- if (!isRecord(request)) throw require_worktreeOperations.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
1647
+ if (!isRecord(request)) throw require_gitDependencies.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
1058
1648
  if (request.method === "none") return { method: "none" };
1059
1649
  if (request.method === "ssh") {
1060
1650
  if (request.keyPath === void 0 || request.keyPath === "") return { method: "ssh" };
1061
- 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 ~/.");
1651
+ 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 ~/.");
1062
1652
  const keyPath = request.keyPath.trim();
1063
- 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 ~/.");
1653
+ 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 ~/.");
1064
1654
  let isFile = false;
1065
1655
  try {
1066
1656
  isFile = (await node_fs_promises.default.stat(expandHome(keyPath, homeDir))).isFile();
1067
1657
  } catch {
1068
1658
  isFile = false;
1069
1659
  }
1070
- if (!isFile) throw require_worktreeOperations.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
1660
+ if (!isFile) throw require_gitDependencies.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
1071
1661
  return {
1072
1662
  method: "ssh",
1073
1663
  keyPath
@@ -1075,11 +1665,11 @@ async function parseGitAuthSave(request, current, homeDir) {
1075
1665
  }
1076
1666
  if (request.method === "https") {
1077
1667
  const host = typeof request.host === "string" ? request.host.trim().toLowerCase() : "";
1078
- 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.");
1668
+ 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.");
1079
1669
  const username = typeof request.username === "string" ? request.username.trim() : "";
1080
- 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.");
1670
+ 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.");
1081
1671
  if (request.token !== void 0 && request.token !== "") {
1082
- 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.");
1672
+ 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.");
1083
1673
  return {
1084
1674
  method: "https",
1085
1675
  host,
@@ -1093,9 +1683,9 @@ async function parseGitAuthSave(request, current, homeDir) {
1093
1683
  username,
1094
1684
  token: current.token
1095
1685
  };
1096
- 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.");
1686
+ 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.");
1097
1687
  }
1098
- throw require_worktreeOperations.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
1688
+ throw require_gitDependencies.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
1099
1689
  }
1100
1690
  /** Tightens a file or folder something left readable by group or others. */
1101
1691
  async function tighten(target, mode) {
@@ -1104,10 +1694,10 @@ async function tighten(target, mode) {
1104
1694
  } catch {}
1105
1695
  }
1106
1696
  function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {}) {
1107
- const file = require_worktreeOperations.credentialsFile(homeDir, environment);
1697
+ const file = require_gitDependencies.credentialsFile(homeDir, environment);
1108
1698
  const readFile = async () => {
1109
1699
  await tighten(file, OWNER_ONLY_FILE);
1110
- const raw = await require_worktreeOperations.readJson(file);
1700
+ const raw = await require_gitDependencies.readJson(file);
1111
1701
  const workspaces = {};
1112
1702
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
1113
1703
  const config = parseConfig(value);
@@ -1126,7 +1716,7 @@ function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {
1126
1716
  const key = await workspaceKey(workspaceRoot);
1127
1717
  const current = await readFile();
1128
1718
  const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1129
- const root = require_worktreeOperations.poGitRoot(homeDir, environment);
1719
+ const root = require_gitDependencies.poGitRoot(homeDir, environment);
1130
1720
  await node_fs_promises.default.mkdir(root, {
1131
1721
  recursive: true,
1132
1722
  mode: OWNER_ONLY_DIRECTORY
@@ -1135,7 +1725,7 @@ function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {
1135
1725
  const workspaces = { ...current.workspaces };
1136
1726
  if (next.method === "none") delete workspaces[key];
1137
1727
  else workspaces[key] = next;
1138
- await require_worktreeOperations.writeJsonAtomic(file, {
1728
+ await require_gitDependencies.writeJsonAtomic(file, {
1139
1729
  version: 1,
1140
1730
  workspaces
1141
1731
  });
@@ -1238,97 +1828,481 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1238
1828
  };
1239
1829
  }
1240
1830
  //#endregion
1241
- //#region src/services/newSessionRequest/index.ts
1242
- const MAX_NAME_LENGTH = 120;
1243
- /** Trimmed text, undefined when absent or blank, false when not text at all. */
1244
- function optionalText(value) {
1245
- if (value === void 0) return void 0;
1246
- if (typeof value !== "string") return false;
1247
- const trimmed = value.trim();
1248
- return trimmed === "" ? void 0 : trimmed;
1249
- }
1250
- /**
1251
- * Validates a new-session dialog request for a worktree session. Every ref is
1252
- * checked here, before it can reach git as a positional argument.
1253
- */
1254
- function newSessionRequest(body) {
1255
- if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
1256
- const record = body;
1257
- const branch = optionalText(record.branch);
1258
- if (branch === void 0 || branch === false || !require_worktreeOperations.validRefName(branch)) return { error: "A valid branch name is required." };
1259
- const name = optionalText(record.name);
1260
- 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.` };
1261
- const chosen = record.selection === void 0 ? {} : (0, _agimon_ai_po_core_hubChannel.parseLaunchSelection)(record.selection);
1262
- if ("error" in chosen) return chosen;
1263
- const profile = chosen.selection?.profile;
1264
- const named = {
1265
- ...name === void 0 ? {} : { name },
1266
- ...profile === void 0 ? {} : { selection: { profile } }
1267
- };
1268
- if (record.mode === "existing-branch") {
1269
- const remote = optionalText(record.remote);
1270
- if (remote === false || remote !== void 0 && !require_worktreeOperations.validRefName(remote)) return { error: "That remote name is not valid." };
1271
- return {
1272
- mode: "existing-branch",
1273
- branch,
1274
- ...remote === void 0 ? {} : { remote },
1275
- ...named
1276
- };
1277
- }
1278
- if (record.mode === "new-branch") {
1279
- const baseRef = optionalText(record.baseRef);
1280
- if (baseRef === false || baseRef !== void 0 && !require_worktreeOperations.validRefName(baseRef)) return { error: "That base branch is not valid." };
1281
- return {
1282
- mode: "new-branch",
1283
- branch,
1284
- ...baseRef === void 0 ? {} : { baseRef },
1285
- ...named
1286
- };
1831
+ //#region src/services/gitFailure/index.ts
1832
+ const english = (_key, fallback, vars) => (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars);
1833
+ const RULES = [
1834
+ {
1835
+ code: "host_key_changed",
1836
+ phrases: ["remote host identification has changed"],
1837
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1838
+ 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."),
1839
+ retryable: false
1840
+ },
1841
+ {
1842
+ code: "host_key_unknown",
1843
+ phrases: [
1844
+ "host key verification failed",
1845
+ "no ed25519 host key is known",
1846
+ "no rsa host key is known"
1847
+ ],
1848
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1849
+ 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."),
1850
+ retryable: false
1851
+ },
1852
+ {
1853
+ code: "auth_failed",
1854
+ phrases: [
1855
+ "authentication failed",
1856
+ "could not read username",
1857
+ "could not read password",
1858
+ "permission denied (publickey",
1859
+ "returned error: 401",
1860
+ "returned error: 403",
1861
+ "terminal prompts disabled",
1862
+ "load key",
1863
+ "unprotected private key",
1864
+ "invalid format"
1865
+ ],
1866
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1867
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1868
+ retryable: false
1869
+ },
1870
+ {
1871
+ code: "repository_not_found",
1872
+ phrases: ["repository not found", "does not appear to be a git repository"],
1873
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1874
+ 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."),
1875
+ retryable: false
1876
+ },
1877
+ {
1878
+ code: "remote_unreachable",
1879
+ phrases: [
1880
+ "could not resolve host",
1881
+ "connection refused",
1882
+ "connection timed out",
1883
+ "operation timed out",
1884
+ "unable to access",
1885
+ "network is unreachable"
1886
+ ],
1887
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1888
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1889
+ retryable: true
1890
+ },
1891
+ {
1892
+ code: "push_lease_rejected",
1893
+ phrases: ["(stale info)"],
1894
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1895
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1896
+ retryable: false
1897
+ },
1898
+ {
1899
+ code: "push_needs_force",
1900
+ phrases: ["(non-fast-forward)", "(fetch first)"],
1901
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1902
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1903
+ retryable: false
1904
+ },
1905
+ {
1906
+ code: "worktree_dirty",
1907
+ phrases: [
1908
+ "unstaged changes",
1909
+ "uncommitted changes",
1910
+ "would be overwritten",
1911
+ "your index contains uncommitted changes"
1912
+ ],
1913
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1914
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1915
+ retryable: false
1287
1916
  }
1288
- return { error: "The mode must be existing-branch or new-branch." };
1917
+ ];
1918
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1919
+ 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."));
1920
+ const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1921
+ const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1922
+ if (rule === void 0) return new require_gitDependencies.PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1923
+ operation,
1924
+ code: String(result.code)
1925
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1926
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1927
+ return new require_gitDependencies.PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1289
1928
  }
1290
1929
  //#endregion
1291
- //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1930
+ //#region src/services/gitSync/index.ts
1292
1931
  /**
1293
- * The worktree surface the cockpit panel calls.
1294
- *
1295
- * Hub-scoped because worktrees are a property of a repository, not of one
1296
- * session: the panel lists and creates them whether or not the session that
1297
- * made them is focused, and a session-scoped API would disappear with it.
1932
+ * Manual pull, push and rebase for a session's checkout.
1298
1933
  *
1299
- * The panel names a repository by the hub's opaque id and never by path.
1300
- * `resolveRepository` turns that into an admitted root, so a browser cannot
1301
- * point this at a directory the cockpit was never given.
1302
- */
1303
- function badRequest(message) {
1934
+ * DESIGN PATTERNS:
1935
+ * - The workspace's auth goes into the environment of the one fetch or push
1936
+ * that needs it, built fresh per call. Rebase itself runs locally and never
1937
+ * sees a credential.
1938
+ * - Fetch and rebase are separate commands, so a hung network can never leave a
1939
+ * rebase half applied.
1940
+ * - A conflicted rebase is not an error. It is left paused for the reader to
1941
+ * hand to the agent or abort, and git's own state reports it from then on.
1942
+ * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1943
+ * Untracked files only block when git says they would be overwritten.
1944
+ * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1945
+ * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1946
+ * which git refuses if the remote holds commits this branch never integrated.
1947
+ */
1948
+ const DONE = { outcome: "done" };
1949
+ function expected(code, message, recovery) {
1950
+ return new require_gitDependencies.PoGitExpectedError(code, message, false, recovery);
1951
+ }
1952
+ function createGitSync(options) {
1953
+ const baseEnv = options.baseEnv ?? {};
1954
+ async function readLine(cwd, args) {
1955
+ const result = await require_gitDependencies.runGit(cwd, args, {
1956
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1957
+ env: baseEnv
1958
+ });
1959
+ const out = result.stdout.trim();
1960
+ return result.code === 0 && out !== "" ? out : void 0;
1961
+ }
1962
+ async function toplevel(cwd) {
1963
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1964
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1965
+ return root;
1966
+ }
1967
+ async function rebasing(root) {
1968
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1969
+ const gitPath = await readLine(root, [
1970
+ "rev-parse",
1971
+ "--git-path",
1972
+ name
1973
+ ]);
1974
+ if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1975
+ }
1976
+ return false;
1977
+ }
1978
+ async function conflicts(root) {
1979
+ return (await require_gitDependencies.runGit(root, [
1980
+ "diff",
1981
+ "--name-only",
1982
+ "--diff-filter=U",
1983
+ "-z"
1984
+ ], {
1985
+ timeout: require_gitDependencies.READ_TIMEOUT_MS,
1986
+ env: baseEnv
1987
+ })).stdout.split("\0").filter((file) => file !== "");
1988
+ }
1989
+ async function currentBranch(root) {
1990
+ const branch = await readLine(root, [
1991
+ "symbolic-ref",
1992
+ "--quiet",
1993
+ "--short",
1994
+ "HEAD"
1995
+ ]);
1996
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1997
+ return branch;
1998
+ }
1999
+ async function guard(root, needsCleanTree) {
2000
+ 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.");
2001
+ const branch = await currentBranch(root);
2002
+ if (needsCleanTree) {
2003
+ if (await readLine(root, [
2004
+ "status",
2005
+ "--porcelain",
2006
+ "--untracked-files=no"
2007
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2008
+ }
2009
+ return branch;
2010
+ }
2011
+ const baselines = /* @__PURE__ */ new Map();
2012
+ /** One credentialed network command against `remote`, classified on failure. */
2013
+ const network = async (root, context, remote, operation, args, urlArgs = []) => {
2014
+ const url = await readLine(root, [
2015
+ "remote",
2016
+ "get-url",
2017
+ ...urlArgs,
2018
+ remote
2019
+ ]);
2020
+ if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
2021
+ const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
2022
+ const result = await require_gitDependencies.runGit(root, args, {
2023
+ timeout: require_gitDependencies.NETWORK_TIMEOUT_MS,
2024
+ env: prepared.env,
2025
+ ...context.signal ? { signal: context.signal } : {}
2026
+ });
2027
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
2028
+ };
2029
+ /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
2030
+ const rebaseOnto = async (root, onto, context) => {
2031
+ context.signal?.throwIfAborted();
2032
+ const before = baselines.get(root) ?? await require_gitDependencies.revision(root, "HEAD", {
2033
+ env: baseEnv,
2034
+ ...context.signal ? { signal: context.signal } : {}
2035
+ });
2036
+ baselines.set(root, before);
2037
+ const result = await require_gitDependencies.runGit(root, ["rebase", onto], {
2038
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2039
+ ...context.signal ? { signal: context.signal } : {},
2040
+ env: {
2041
+ ...baseEnv,
2042
+ GIT_EDITOR: "true",
2043
+ GIT_TERMINAL_PROMPT: "0"
2044
+ }
2045
+ });
2046
+ if (result.code === 0) {
2047
+ if (before !== await require_gitDependencies.revision(root, "HEAD", {
2048
+ env: baseEnv,
2049
+ ...context.signal ? { signal: context.signal } : {}
2050
+ })) await options.reapplySparse?.(root, context.signal);
2051
+ baselines.delete(root);
2052
+ return DONE;
2053
+ }
2054
+ if (await rebasing(root)) return {
2055
+ outcome: "paused",
2056
+ conflicts: await conflicts(root)
2057
+ };
2058
+ baselines.delete(root);
2059
+ throw classifyGitFailure("rebase", result, void 0, context.t);
2060
+ };
2061
+ /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
2062
+ const remoteOfRef = async (root, ref) => {
2063
+ const full = await readLine(root, [
2064
+ "rev-parse",
2065
+ "--symbolic-full-name",
2066
+ ref
2067
+ ]);
2068
+ if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
2069
+ const rest = full.slice(13);
2070
+ const cut = rest.indexOf("/");
2071
+ return cut > 0 ? rest.slice(0, cut) : void 0;
2072
+ };
2073
+ return {
2074
+ async pull(context) {
2075
+ const root = await toplevel(context.cwd);
2076
+ const branch = await guard(root, true);
2077
+ const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
2078
+ const upstream = await readLine(root, [
2079
+ "rev-parse",
2080
+ "--abbrev-ref",
2081
+ "--symbolic-full-name",
2082
+ `${branch}@{upstream}`
2083
+ ]);
2084
+ if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
2085
+ if (remote !== ".") await network(root, context, remote, "fetch", [
2086
+ "fetch",
2087
+ "--prune",
2088
+ remote
2089
+ ]);
2090
+ return rebaseOnto(root, upstream, context);
2091
+ },
2092
+ async push(context, force) {
2093
+ const root = await toplevel(context.cwd);
2094
+ const branch = await guard(root, false);
2095
+ const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
2096
+ const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
2097
+ let remote = configuredRemote;
2098
+ let target = merge;
2099
+ const args = ["push", "--porcelain"];
2100
+ if (remote === void 0 || target === void 0 || remote === ".") {
2101
+ const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
2102
+ remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
2103
+ if (remote === void 0) throw expected("no_remote", "There is no remote to push to.", remotes.length === 0 ? "Add a remote in a terminal first." : "Push once from a terminal to choose the remote.");
2104
+ target = `refs/heads/${branch}`;
2105
+ args.push("--set-upstream");
2106
+ }
2107
+ if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
2108
+ args.push(remote, `HEAD:${target}`);
2109
+ await network(root, context, remote, "push", args, ["--push"]);
2110
+ return DONE;
2111
+ },
2112
+ async rebase(context) {
2113
+ const root = await toplevel(context.cwd);
2114
+ const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
2115
+ if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
2116
+ const remote = await remoteOfRef(root, base);
2117
+ if (remote !== void 0) await network(root, context, remote, "fetch", [
2118
+ "fetch",
2119
+ "--prune",
2120
+ remote
2121
+ ]);
2122
+ return rebaseOnto(root, base, context);
2123
+ },
2124
+ async abortRebase(context) {
2125
+ const root = await toplevel(context.cwd);
2126
+ if (!await rebasing(root)) {
2127
+ baselines.delete(root);
2128
+ return DONE;
2129
+ }
2130
+ const result = await require_gitDependencies.runGit(root, ["rebase", "--abort"], {
2131
+ timeout: require_gitDependencies.REBASE_TIMEOUT_MS,
2132
+ env: baseEnv,
2133
+ ...context.signal ? { signal: context.signal } : {}
2134
+ });
2135
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2136
+ baselines.delete(root);
2137
+ return DONE;
2138
+ }
2139
+ };
2140
+ }
2141
+ //#endregion
2142
+ //#region src/services/newSessionRequest/index.ts
2143
+ const MAX_NAME_LENGTH = 120;
2144
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2145
+ function optionalText(value) {
2146
+ if (value === void 0) return void 0;
2147
+ if (typeof value !== "string") return false;
2148
+ const trimmed = value.trim();
2149
+ return trimmed === "" ? void 0 : trimmed;
2150
+ }
2151
+ /**
2152
+ * Validates a new-session dialog request for a worktree session. Every ref is
2153
+ * checked here, before it can reach git as a positional argument.
2154
+ */
2155
+ function newSessionRequest(body) {
2156
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2157
+ const record = body;
2158
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2159
+ const branch = optionalText(record.branch);
2160
+ if (branch === void 0 || branch === false || !require_gitDependencies.validRefName(branch)) return { error: "A valid branch name is required." };
2161
+ const name = optionalText(record.name);
2162
+ 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.` };
2163
+ if (Object.hasOwn(record, "sparseProfile") && !require_gitDependencies.validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2164
+ const chosen = record.selection === void 0 ? {} : (0, _agimon_ai_po_core_hubChannel.parseLaunchSelection)(record.selection);
2165
+ if ("error" in chosen) return chosen;
2166
+ const profile = chosen.selection?.profile;
2167
+ const named = {
2168
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2169
+ ...name === void 0 ? {} : { name },
2170
+ ...profile === void 0 ? {} : { selection: { profile } }
2171
+ };
2172
+ if (record.mode === "existing-branch") {
2173
+ const remote = optionalText(record.remote);
2174
+ if (remote === false || remote !== void 0 && !require_gitDependencies.validRefName(remote)) return { error: "That remote name is not valid." };
2175
+ return {
2176
+ mode: "existing-branch",
2177
+ branch,
2178
+ ...remote === void 0 ? {} : { remote },
2179
+ ...named
2180
+ };
2181
+ }
2182
+ if (record.mode === "new-branch") {
2183
+ const baseRef = optionalText(record.baseRef);
2184
+ if (baseRef === false || baseRef !== void 0 && !require_gitDependencies.validRefName(baseRef)) return { error: "That base branch is not valid." };
2185
+ return {
2186
+ mode: "new-branch",
2187
+ branch,
2188
+ ...baseRef === void 0 ? {} : { baseRef },
2189
+ ...named
2190
+ };
2191
+ }
2192
+ return { error: "The mode must be existing-branch or new-branch." };
2193
+ }
2194
+ //#endregion
2195
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2196
+ /**
2197
+ * The worktree surface the cockpit panel calls.
2198
+ *
2199
+ * Hub-scoped because worktrees are a property of a repository, not of one
2200
+ * session: the panel lists and creates them whether or not the session that
2201
+ * made them is focused, and a session-scoped API would disappear with it.
2202
+ *
2203
+ * The panel names a repository by the hub's opaque id and never by path.
2204
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2205
+ * point this at a directory the cockpit was never given.
2206
+ */
2207
+ function badRequest(message) {
1304
2208
  return Response.json({ error: message }, { status: 400 });
1305
2209
  }
1306
2210
  function failed(error) {
1307
- if (error instanceof require_worktreeOperations.PoGitExpectedError) return Response.json({
2211
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return Response.json({
1308
2212
  error: error.message,
1309
2213
  code: error.code
1310
2214
  }, { status: error.retryable ? 503 : 409 });
1311
2215
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1312
2216
  }
1313
- function createGitApi(openDirectory) {
2217
+ function createGitApi(openDirectory, dependencies = {}, translate) {
1314
2218
  return {
1315
2219
  basePath: "git",
1316
2220
  start(context) {
1317
2221
  if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1318
2222
  const directEvents = context.directEvents;
1319
2223
  const publishLifecycle = (sessionId, repositoryRoot) => {
1320
- directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
2224
+ directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1321
2225
  version: 1,
1322
2226
  repositoryRoot
1323
2227
  });
1324
2228
  };
1325
- const git = require_worktreeOperations.createWorktreeGit();
1326
- const operations = require_worktreeOperations.createWorktreeOperations({
2229
+ const git = require_gitDependencies.createWorktreeGit();
2230
+ const operations = require_gitDependencies.createWorktreeOperations({
2231
+ ...dependencies,
1327
2232
  git,
1328
2233
  sessionService: context.sessionService,
1329
2234
  ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
1330
2235
  ...context.environment === void 0 ? {} : { environment: context.environment }
1331
2236
  });
2237
+ const sync = createGitSync({
2238
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2239
+ baseEnv: context.environment ?? {},
2240
+ async reapplySparse(cwd, signal) {
2241
+ 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);
2242
+ if (record?.sparseProfile) await operations.reapply({
2243
+ cwd,
2244
+ sessionId: context.sessionId
2245
+ }, record.id, { signal });
2246
+ }
2247
+ });
2248
+ const sessionCommand = async (request, url) => {
2249
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2250
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2251
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2252
+ const caller = {
2253
+ cwd: context.cwd,
2254
+ sessionId: context.sessionId
2255
+ };
2256
+ const body = await request.json().catch(() => void 0);
2257
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2258
+ const command = body;
2259
+ if (url.pathname === "/sync") {
2260
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2261
+ const recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2262
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2263
+ const syncContext = {
2264
+ ...caller,
2265
+ auth,
2266
+ recordedBaseRef,
2267
+ signal: request.signal,
2268
+ ...translate ? { t: translate } : {}
2269
+ };
2270
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2271
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2272
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2273
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2274
+ return badRequest("Unknown sync command.");
2275
+ }
2276
+ if (Object.keys(command).some((key) => ![
2277
+ "action",
2278
+ "branch",
2279
+ "baseRef",
2280
+ "sparseProfile",
2281
+ "reservationId",
2282
+ "id",
2283
+ "force",
2284
+ "folders"
2285
+ ].includes(key))) return badRequest("Unknown command field.");
2286
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2287
+ if (command.action === "create") {
2288
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2289
+ const result = await operations.spawn(caller, {
2290
+ branch: command.branch,
2291
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2292
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2293
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2294
+ }, { signal: request.signal });
2295
+ return Response.json({ worktree: result });
2296
+ }
2297
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2298
+ if (![
2299
+ "profiles",
2300
+ "expand",
2301
+ "reapply"
2302
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2303
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2304
+ return Response.json(result.details);
2305
+ };
1332
2306
  /**
1333
2307
  * The new-session dialog's routes: the workspace's branches, and a top-level
1334
2308
  * worktree session on one. Workspace-mounted only, and always rooted at the
@@ -1350,7 +2324,8 @@ function createGitApi(openDirectory) {
1350
2324
  remote: []
1351
2325
  } : {
1352
2326
  repository: true,
1353
- ...await git.listBranches(repositoryRoot)
2327
+ ...await git.listBranches(repositoryRoot),
2328
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
1354
2329
  };
1355
2330
  return Response.json(branches);
1356
2331
  }
@@ -1358,7 +2333,7 @@ function createGitApi(openDirectory) {
1358
2333
  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 });
1359
2334
  const body = await request.json().catch(() => void 0);
1360
2335
  const branch = typeof body === "object" && body !== null ? body.branch : void 0;
1361
- if (typeof branch !== "string" || !require_worktreeOperations.validRefName(branch)) return badRequest("A valid branch name is required.");
2336
+ if (typeof branch !== "string" || !require_gitDependencies.validRefName(branch)) return badRequest("A valid branch name is required.");
1362
2337
  const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1363
2338
  if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
1364
2339
  const branches = await git.listBranches(repositoryRoot);
@@ -1385,12 +2360,13 @@ function createGitApi(openDirectory) {
1385
2360
  if ("error" in parsed) return badRequest(parsed.error);
1386
2361
  const record = await operations.spawn({ cwd: workspaceRoot }, {
1387
2362
  branch: parsed.branch,
2363
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
1388
2364
  checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1389
2365
  ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1390
2366
  ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1391
2367
  ...parsed.name === void 0 ? {} : { name: parsed.name },
1392
2368
  ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1393
- });
2369
+ }, { signal: request.signal });
1394
2370
  publishLifecycle(record.sessionId, record.repositoryRoot);
1395
2371
  const created = {
1396
2372
  sessionId: record.sessionId,
@@ -1426,7 +2402,7 @@ function createGitApi(openDirectory) {
1426
2402
  try {
1427
2403
  return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
1428
2404
  } catch (error) {
1429
- if (error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "invalid_request") {
2405
+ if (error instanceof require_gitDependencies.PoGitExpectedError && error.code === "invalid_request") {
1430
2406
  const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1431
2407
  return Response.json({
1432
2408
  error: text,
@@ -1449,7 +2425,7 @@ function createGitApi(openDirectory) {
1449
2425
  if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
1450
2426
  let recordedBaseRef;
1451
2427
  try {
1452
- recordedBaseRef = (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
2428
+ recordedBaseRef = (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
1453
2429
  } catch {
1454
2430
  recordedBaseRef = void 0;
1455
2431
  }
@@ -1472,7 +2448,7 @@ function createGitApi(openDirectory) {
1472
2448
  async fetch(request) {
1473
2449
  const url = new URL(request.url);
1474
2450
  try {
1475
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2451
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1476
2452
  if (answered !== void 0) return answered;
1477
2453
  } catch (error) {
1478
2454
  context.onNotice(`git request failed: ${error.name}`);
@@ -1492,6 +2468,7 @@ function createGitApi(openDirectory) {
1492
2468
  if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1493
2469
  const record = await operations.spawn(callerContext, {
1494
2470
  branch: body.branch,
2471
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
1495
2472
  ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1496
2473
  ...body.name === void 0 ? {} : { name: body.name }
1497
2474
  });
@@ -1517,7 +2494,8 @@ function createGitApi(openDirectory) {
1517
2494
  }
1518
2495
  //#endregion
1519
2496
  //#region src/extensions/(backend)/api/git/route.server.ts
1520
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ context, host, signal }) => {
2497
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)((plugin) => {
2498
+ const { context, host, signal } = plugin;
1521
2499
  let openDirectory;
1522
2500
  context.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
1523
2501
  const shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
@@ -1541,285 +2519,9 @@ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({
1541
2519
  return createGitApi(async (path) => {
1542
2520
  if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1543
2521
  await openDirectory(path);
1544
- });
2522
+ }, 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));
1545
2523
  });
1546
2524
  //#endregion
1547
- //#region src/services/gitFailure/index.ts
1548
- const RULES = [
1549
- {
1550
- code: "host_key_changed",
1551
- phrases: ["remote host identification has changed"],
1552
- message: "The remote's SSH host key changed since this machine last saw it.",
1553
- recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1554
- retryable: false
1555
- },
1556
- {
1557
- code: "host_key_unknown",
1558
- phrases: [
1559
- "host key verification failed",
1560
- "no ed25519 host key is known",
1561
- "no rsa host key is known"
1562
- ],
1563
- message: "This machine does not trust the remote's SSH host key yet.",
1564
- recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1565
- retryable: false
1566
- },
1567
- {
1568
- code: "auth_failed",
1569
- phrases: [
1570
- "authentication failed",
1571
- "could not read username",
1572
- "could not read password",
1573
- "permission denied (publickey",
1574
- "returned error: 401",
1575
- "returned error: 403",
1576
- "terminal prompts disabled",
1577
- "load key",
1578
- "unprotected private key",
1579
- "invalid format"
1580
- ],
1581
- message: "The remote refused the credentials.",
1582
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1583
- retryable: false
1584
- },
1585
- {
1586
- code: "repository_not_found",
1587
- phrases: ["repository not found", "does not appear to be a git repository"],
1588
- message: "The remote repository was not found, or these credentials cannot see it.",
1589
- recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1590
- retryable: false
1591
- },
1592
- {
1593
- code: "remote_unreachable",
1594
- phrases: [
1595
- "could not resolve host",
1596
- "connection refused",
1597
- "connection timed out",
1598
- "operation timed out",
1599
- "unable to access",
1600
- "network is unreachable"
1601
- ],
1602
- message: "The remote could not be reached.",
1603
- recovery: "Check the network and the remote URL, then try again.",
1604
- retryable: true
1605
- },
1606
- {
1607
- code: "push_lease_rejected",
1608
- phrases: ["(stale info)"],
1609
- message: "The remote branch moved since your last fetch, so the force push was refused.",
1610
- recovery: "Pull to see the new commits, then decide whether to push again.",
1611
- retryable: false
1612
- },
1613
- {
1614
- code: "push_needs_force",
1615
- phrases: ["(non-fast-forward)", "(fetch first)"],
1616
- message: "The remote branch has commits yours replaced, usually after a rebase.",
1617
- recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1618
- retryable: false
1619
- },
1620
- {
1621
- code: "worktree_dirty",
1622
- phrases: [
1623
- "unstaged changes",
1624
- "uncommitted changes",
1625
- "would be overwritten",
1626
- "your index contains uncommitted changes"
1627
- ],
1628
- message: "There are uncommitted changes in the way.",
1629
- recovery: "Commit or stash your changes first.",
1630
- retryable: false
1631
- }
1632
- ];
1633
- function classifyGitFailure(operation, result, mismatch) {
1634
- if (result.timedOut) return new require_worktreeOperations.PoGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1635
- const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1636
- const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1637
- if (rule === void 0) return new require_worktreeOperations.PoGitExpectedError("git_failed", `git ${operation} failed (exit ${String(result.code)}).`, false, "Run the same command in a terminal in this checkout to see what git says.");
1638
- const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1639
- return new require_worktreeOperations.PoGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1640
- }
1641
- //#endregion
1642
- //#region src/services/gitSync/index.ts
1643
- /**
1644
- * Manual pull, push and rebase for a session's checkout.
1645
- *
1646
- * DESIGN PATTERNS:
1647
- * - The workspace's auth goes into the environment of the one fetch or push
1648
- * that needs it, built fresh per call. Rebase itself runs locally and never
1649
- * sees a credential.
1650
- * - Fetch and rebase are separate commands, so a hung network can never leave a
1651
- * rebase half applied.
1652
- * - A conflicted rebase is not an error. It is left paused for the reader to
1653
- * hand to the agent or abort, and git's own state reports it from then on.
1654
- * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1655
- * Untracked files only block when git says they would be overwritten.
1656
- * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1657
- * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1658
- * which git refuses if the remote holds commits this branch never integrated.
1659
- */
1660
- const DONE = { outcome: "done" };
1661
- function expected(code, message, recovery) {
1662
- return new require_worktreeOperations.PoGitExpectedError(code, message, false, recovery);
1663
- }
1664
- async function readLine(cwd, args) {
1665
- const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1666
- const out = result.stdout.trim();
1667
- return result.code === 0 && out !== "" ? out : void 0;
1668
- }
1669
- async function toplevel(cwd) {
1670
- const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1671
- if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1672
- return root;
1673
- }
1674
- async function rebasing(root) {
1675
- for (const name of ["rebase-merge", "rebase-apply"]) {
1676
- const gitPath = await readLine(root, [
1677
- "rev-parse",
1678
- "--git-path",
1679
- name
1680
- ]);
1681
- if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1682
- }
1683
- return false;
1684
- }
1685
- async function conflicts(root) {
1686
- return (await require_worktreeOperations.runGit(root, [
1687
- "diff",
1688
- "--name-only",
1689
- "--diff-filter=U",
1690
- "-z"
1691
- ], { timeout: require_worktreeOperations.READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1692
- }
1693
- async function currentBranch(root) {
1694
- const branch = await readLine(root, [
1695
- "symbolic-ref",
1696
- "--quiet",
1697
- "--short",
1698
- "HEAD"
1699
- ]);
1700
- if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1701
- return branch;
1702
- }
1703
- async function guard(root, needsCleanTree) {
1704
- 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.");
1705
- const branch = await currentBranch(root);
1706
- if (needsCleanTree) {
1707
- if (await readLine(root, [
1708
- "status",
1709
- "--porcelain",
1710
- "--untracked-files=no"
1711
- ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
1712
- }
1713
- return branch;
1714
- }
1715
- function createGitSync(options) {
1716
- const baseEnv = options.baseEnv ?? process.env;
1717
- /** One credentialed network command against `remote`, classified on failure. */
1718
- const network = async (root, context, remote, operation, args, urlArgs = []) => {
1719
- const url = await readLine(root, [
1720
- "remote",
1721
- "get-url",
1722
- ...urlArgs,
1723
- remote
1724
- ]);
1725
- if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1726
- const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1727
- const result = await require_worktreeOperations.runGit(root, args, {
1728
- timeout: require_worktreeOperations.NETWORK_TIMEOUT_MS,
1729
- env: prepared.env
1730
- });
1731
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
1732
- };
1733
- /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1734
- const rebaseOnto = async (root, onto) => {
1735
- const result = await require_worktreeOperations.runGit(root, ["rebase", onto], {
1736
- timeout: require_worktreeOperations.REBASE_TIMEOUT_MS,
1737
- env: {
1738
- ...baseEnv,
1739
- GIT_EDITOR: "true",
1740
- GIT_TERMINAL_PROMPT: "0"
1741
- }
1742
- });
1743
- if (result.code === 0) return DONE;
1744
- if (await rebasing(root)) return {
1745
- outcome: "paused",
1746
- conflicts: await conflicts(root)
1747
- };
1748
- throw classifyGitFailure("rebase", result);
1749
- };
1750
- /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1751
- const remoteOfRef = async (root, ref) => {
1752
- const full = await readLine(root, [
1753
- "rev-parse",
1754
- "--symbolic-full-name",
1755
- ref
1756
- ]);
1757
- if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
1758
- const rest = full.slice(13);
1759
- const cut = rest.indexOf("/");
1760
- return cut > 0 ? rest.slice(0, cut) : void 0;
1761
- };
1762
- return {
1763
- async pull(context) {
1764
- const root = await toplevel(context.cwd);
1765
- const branch = await guard(root, true);
1766
- const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
1767
- const upstream = await readLine(root, [
1768
- "rev-parse",
1769
- "--abbrev-ref",
1770
- "--symbolic-full-name",
1771
- `${branch}@{upstream}`
1772
- ]);
1773
- if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
1774
- if (remote !== ".") await network(root, context, remote, "fetch", [
1775
- "fetch",
1776
- "--prune",
1777
- remote
1778
- ]);
1779
- return rebaseOnto(root, upstream);
1780
- },
1781
- async push(context, force) {
1782
- const root = await toplevel(context.cwd);
1783
- const branch = await guard(root, false);
1784
- const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
1785
- const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
1786
- let remote = configuredRemote;
1787
- let target = merge;
1788
- const args = ["push", "--porcelain"];
1789
- if (remote === void 0 || target === void 0 || remote === ".") {
1790
- const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
1791
- remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
1792
- if (remote === void 0) throw expected("no_remote", "There is no remote to push to.", remotes.length === 0 ? "Add a remote in a terminal first." : "Push once from a terminal to choose the remote.");
1793
- target = `refs/heads/${branch}`;
1794
- args.push("--set-upstream");
1795
- }
1796
- if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
1797
- args.push(remote, `HEAD:${target}`);
1798
- await network(root, context, remote, "push", args, ["--push"]);
1799
- return DONE;
1800
- },
1801
- async rebase(context) {
1802
- const root = await toplevel(context.cwd);
1803
- const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
1804
- if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
1805
- const remote = await remoteOfRef(root, base);
1806
- if (remote !== void 0) await network(root, context, remote, "fetch", [
1807
- "fetch",
1808
- "--prune",
1809
- remote
1810
- ]);
1811
- return rebaseOnto(root, base);
1812
- },
1813
- async abortRebase(context) {
1814
- const root = await toplevel(context.cwd);
1815
- if (!await rebasing(root)) return DONE;
1816
- const result = await require_worktreeOperations.runGit(root, ["rebase", "--abort"], { timeout: require_worktreeOperations.REBASE_TIMEOUT_MS });
1817
- if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
1818
- return DONE;
1819
- }
1820
- };
1821
- }
1822
- //#endregion
1823
2525
  //#region src/types/gitReview.ts
1824
2526
  /**
1825
2527
  * The cockpit's view of what this session changed against its base: the counts
@@ -1889,13 +2591,13 @@ const PENDING = {
1889
2591
  /** The error target a failure maps to: a rejected plain push asks for a confirmed lease force. */
1890
2592
  function errorTargetFor$1(command, error) {
1891
2593
  if (command.action !== "push") return { action: command.action };
1892
- return error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
2594
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
1893
2595
  action: "push",
1894
2596
  forceRequired: true
1895
2597
  } : { action: "push" };
1896
2598
  }
1897
2599
  function failureText$1(error) {
1898
- if (error instanceof require_worktreeOperations.PoGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2600
+ if (error instanceof require_gitDependencies.PoGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1899
2601
  return "The git command failed.";
1900
2602
  }
1901
2603
  function createGitChangesChannel(options = {}) {
@@ -1918,7 +2620,7 @@ function createGitChangesChannel(options = {}) {
1918
2620
  /** The base the session's own worktree was created from, when it has one. */
1919
2621
  const recordedBaseRef = async (scope) => {
1920
2622
  try {
1921
- return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
2623
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1922
2624
  } catch {
1923
2625
  return;
1924
2626
  }
@@ -1971,17 +2673,30 @@ function createGitChangesChannel(options = {}) {
1971
2673
  delayed.set(sessionId, timer);
1972
2674
  };
1973
2675
  const run = async (scope, command) => {
2676
+ if (options.scopedCommands) {
2677
+ const response = await host.requestSessionApi(scope, {
2678
+ basePath: "git",
2679
+ path: "/sync",
2680
+ method: "POST",
2681
+ body: JSON.stringify(command)
2682
+ });
2683
+ const result = await response.json();
2684
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2685
+ return result;
2686
+ }
1974
2687
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1975
2688
  const base = await recordedBaseRef(scope);
1976
2689
  const context = {
1977
2690
  cwd: scope.cwd,
2691
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
1978
2692
  auth: await auth.read(workspaceRoot),
1979
2693
  ...base === void 0 ? {} : { recordedBaseRef: base }
1980
2694
  };
1981
- if (command.action === "pull") return sync.pull(context);
1982
- if (command.action === "push") return sync.push(context, command.force === true);
1983
- if (command.action === "rebase") return sync.rebase(context);
1984
- return sync.abortRebase(context);
2695
+ const sessionSync = sync;
2696
+ if (command.action === "pull") return sessionSync.pull(context);
2697
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2698
+ if (command.action === "rebase") return sessionSync.rebase(context);
2699
+ return sessionSync.abortRebase(context);
1985
2700
  };
1986
2701
  const source = {
1987
2702
  payloadFor(scope) {
@@ -1991,8 +2706,8 @@ function createGitChangesChannel(options = {}) {
1991
2706
  sessionAdded(scope) {
1992
2707
  scopes.set(scope.sessionId, scope);
1993
2708
  refresh(scope.sessionId);
1994
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1995
- if (require_worktreeOperations.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
2709
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
2710
+ if (require_gitDependencies.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1996
2711
  });
1997
2712
  subscriptions.set(scope.sessionId, unsubscribe);
1998
2713
  },
@@ -2028,7 +2743,7 @@ function createGitChangesChannel(options = {}) {
2028
2743
  errorTarget: void 0
2029
2744
  });
2030
2745
  run(scope, command).then(() => update(scope.sessionId, { pending: void 0 })).catch((error) => {
2031
- host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_worktreeOperations.PoGitExpectedError ? error.code : "unexpected"})`);
2746
+ host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_gitDependencies.PoGitExpectedError ? error.code : "unexpected"})`);
2032
2747
  update(scope.sessionId, {
2033
2748
  pending: void 0,
2034
2749
  error: failureText$1(error),
@@ -2048,7 +2763,12 @@ function createGitChangesChannel(options = {}) {
2048
2763
  }
2049
2764
  //#endregion
2050
2765
  //#region src/extensions/(backend)/channel/git-changes.server.ts
2051
- var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createGitChangesChannel);
2766
+ var git_changes_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(({ context, host }) => createGitChangesChannel({
2767
+ homeDir: host.context.homeDirectory,
2768
+ environment: host.context.environment,
2769
+ scopedCommands: true,
2770
+ 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)
2771
+ }), { context: true });
2052
2772
  //#endregion
2053
2773
  //#region src/types/webWorktrees.ts
2054
2774
  /**
@@ -2079,7 +2799,7 @@ function payloadOf(state) {
2079
2799
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
2080
2800
  async function viewsFor(scope, deps) {
2081
2801
  try {
2082
- return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
2802
+ return (await require_gitDependencies.createWorktreeRegistry(await require_gitDependencies.registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
2083
2803
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
2084
2804
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
2085
2805
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -2109,7 +2829,7 @@ function errorTargetFor(command, error) {
2109
2829
  action: "close",
2110
2830
  id: command.id
2111
2831
  };
2112
- return error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "rift_missing" ? {
2832
+ return error instanceof require_gitDependencies.PoGitExpectedError && error.code === "rift_missing" ? {
2113
2833
  action: "create",
2114
2834
  riftMissing: true
2115
2835
  } : { action: "create" };
@@ -2121,7 +2841,9 @@ function parseCommand(payload) {
2121
2841
  if (value.action === "create") {
2122
2842
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
2123
2843
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2844
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
2124
2845
  return {
2846
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
2125
2847
  action: "create",
2126
2848
  branch: value.branch.trim(),
2127
2849
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -2146,7 +2868,7 @@ function parseCommand(payload) {
2146
2868
  * summarised, never echoed: a git error can carry a remote URL with a token in it.
2147
2869
  */
2148
2870
  function failureText(error) {
2149
- if (!(error instanceof require_worktreeOperations.PoGitExpectedError)) return "The worktree operation failed.";
2871
+ if (!(error instanceof require_gitDependencies.PoGitExpectedError)) return "The worktree operation failed.";
2150
2872
  if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2151
2873
  return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
2152
2874
  }
@@ -2157,16 +2879,16 @@ function createWorktreesChannel(options = {}) {
2157
2879
  frameType: GIT_WORKTREES_TYPE,
2158
2880
  start(host) {
2159
2881
  const sessionService = host.sessionService;
2160
- if (sessionService === void 0) throw new require_worktreeOperations.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
2161
- const worktrees = options.operations ?? require_worktreeOperations.createWorktreeOperations({
2162
- git: require_worktreeOperations.createWorktreeGit(),
2882
+ if (sessionService === void 0) throw new require_gitDependencies.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
2883
+ const worktrees = options.operations ?? require_gitDependencies.createWorktreeOperations({
2884
+ git: require_gitDependencies.createWorktreeGit(),
2163
2885
  sessionService,
2164
2886
  ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2165
2887
  ...options.environment === void 0 ? {} : { environment: options.environment }
2166
2888
  });
2167
2889
  /** Announces a successful mutation to this session's lifecycle subscribers. */
2168
2890
  const publishLifecycle = (scope, repositoryRoot) => {
2169
- host.directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
2891
+ host.directEvents.publish(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, {
2170
2892
  version: 1,
2171
2893
  repositoryRoot
2172
2894
  });
@@ -2175,6 +2897,22 @@ function createWorktreesChannel(options = {}) {
2175
2897
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
2176
2898
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
2177
2899
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2900
+ if (options.scopedCommands) {
2901
+ if (!(await host.requestSessionApi(parent, {
2902
+ basePath: "git",
2903
+ path: "/session-worktrees",
2904
+ method: "POST",
2905
+ body: JSON.stringify({
2906
+ action: "create",
2907
+ branch,
2908
+ reservationId
2909
+ }),
2910
+ ...signal ? { signal } : {}
2911
+ })).ok) throw new Error("The conversation worktree could not be created.");
2912
+ const reservations = sessionService.reservations;
2913
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2914
+ return reservations.complete(reservationId, parentSessionId);
2915
+ }
2178
2916
  const record = await worktrees.spawn({
2179
2917
  cwd: parent.cwd,
2180
2918
  sessionId: parent.sessionId
@@ -2238,10 +2976,24 @@ function createWorktreesChannel(options = {}) {
2238
2976
  if (generations.get(scope.sessionId) !== generation) return;
2239
2977
  mark(scope, pending, error, errorTarget);
2240
2978
  };
2979
+ if (options.scopedCommands) {
2980
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2981
+ const response = await host.requestSessionApi(scope, {
2982
+ basePath: "git",
2983
+ path: "/session-worktrees",
2984
+ method: "POST",
2985
+ body: JSON.stringify(command)
2986
+ });
2987
+ const result = await response.json();
2988
+ if (!response.ok) throw new require_gitDependencies.PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2989
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2990
+ return;
2991
+ }
2241
2992
  if (command.action === "create") {
2242
2993
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
2243
2994
  const record = await worktrees.spawn(context, {
2244
2995
  branch: command.branch,
2996
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2245
2997
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2246
2998
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2247
2999
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -2262,11 +3014,11 @@ function createWorktreesChannel(options = {}) {
2262
3014
  sessionAdded(scope) {
2263
3015
  newGeneration(scope.sessionId);
2264
3016
  publish(scope, false);
2265
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
2266
- if (!require_worktreeOperations.isWorktreeLifecycleEvent(payload)) return;
3017
+ const unsubscribe = host.directEvents.subscribe(require_gitDependencies.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
3018
+ if (!require_gitDependencies.isWorktreeLifecycleEvent(payload)) return;
2267
3019
  let sameRepository = false;
2268
3020
  try {
2269
- sameRepository = await require_worktreeOperations.registryFile(scope.cwd, options.homeDir, options.environment) === await require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir, options.environment);
3021
+ sameRepository = await require_gitDependencies.registryFile(scope.cwd, options.homeDir, options.environment) === await require_gitDependencies.registryFile(payload.repositoryRoot, options.homeDir, options.environment);
2270
3022
  } catch {
2271
3023
  sameRepository = false;
2272
3024
  }
@@ -2317,7 +3069,11 @@ function createWorktreesChannel(options = {}) {
2317
3069
  }
2318
3070
  //#endregion
2319
3071
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2320
- var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createWorktreesChannel);
3072
+ var git_worktrees_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)((plugin) => createWorktreesChannel({
3073
+ homeDir: plugin.host.context.homeDirectory,
3074
+ environment: plugin.host.context.environment,
3075
+ scopedCommands: true
3076
+ }), { context: true });
2321
3077
  //#endregion
2322
3078
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2323
3079
  var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[1]);
@@ -2344,8 +3100,11 @@ const via = (identity, value) => value === void 0 ? void 0 : {
2344
3100
  };
2345
3101
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2346
3102
  name: "@agimon-ai/po-git",
2347
- providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
2348
- injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
3103
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
3104
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
3105
+ workspace: [root_server_default$1],
3106
+ session: [root_server_default$1, root_server_default]
3107
+ }),
2349
3108
  host: (context) => ({
2350
3109
  get api() {
2351
3110
  return [at(route_server_default, context)];
@@ -2354,22 +3113,32 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2354
3113
  return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2355
3114
  }
2356
3115
  }),
2357
- workspace: (context) => ({
2358
- get api() {
2359
- return [at(route_server_default, context)];
2360
- },
2361
- get channels() {
2362
- 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))]);
2363
- }
2364
- }),
3116
+ workspace: async (context) => {
3117
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3118
+ return {
3119
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace),
3120
+ get api() {
3121
+ return [at(route_server_default, context)];
3122
+ },
3123
+ get channels() {
3124
+ 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))]);
3125
+ },
3126
+ services: [...scopeWorkspace.services ?? []]
3127
+ };
3128
+ },
2365
3129
  session: async (context) => {
2366
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2367
- const contextSession = {
3130
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3131
+ const contextWorkspace = {
2368
3132
  ...context,
3133
+ root: scopeWorkspace.value
3134
+ };
3135
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3136
+ const contextSession = {
3137
+ ...contextWorkspace,
2369
3138
  root: scopeSession.value
2370
3139
  };
2371
3140
  return {
2372
- ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
3141
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeWorkspace, scopeSession),
2373
3142
  get api() {
2374
3143
  return [at(route_server_default, context)];
2375
3144
  },
@@ -2385,9 +3154,9 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2385
3154
  get tools() {
2386
3155
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2387
3156
  },
2388
- services: [...scopeSession.services ?? []],
3157
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2389
3158
  get activities() {
2390
- return [...scopeSession.activities ?? []];
3159
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2391
3160
  }
2392
3161
  };
2393
3162
  }