@agimon-ai/po-git 0.0.0-alpha.19 → 0.0.0-alpha.190

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,17 +2,21 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_worktreeOperations = require("../worktreeOperations-Dxs3txKL.cjs");
6
- let node_fs = require("node:fs");
7
- node_fs = require_worktreeOperations.__toESM(node_fs, 1);
8
- let node_os = require("node:os");
9
- node_os = require_worktreeOperations.__toESM(node_os, 1);
5
+ const require_worktreeOperations = require("../worktreeOperations-BEk4VEj3.cjs");
6
+ let node_fs_promises = require("node:fs/promises");
7
+ node_fs_promises = require_worktreeOperations.__toESM(node_fs_promises, 1);
10
8
  let node_path = require("node:path");
11
9
  node_path = require_worktreeOperations.__toESM(node_path, 1);
10
+ let node_os = require("node:os");
11
+ node_os = require_worktreeOperations.__toESM(node_os, 1);
12
12
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
13
13
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
14
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
14
15
  let _agimon_ai_po_session = require("@agimon-ai/po-session");
15
16
  let typebox = require("typebox");
17
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
18
+ let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
19
+ let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
16
20
  //#region src/schemas/runWorktreeTool.ts
17
21
  /**
18
22
  * The tool's action vocabulary.
@@ -254,7 +258,8 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
254
258
  content: text(describe(record, context.sessionId), `Session: ${record.sessionId}`, dirtyFiles.length === 0 ? "Clean." : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(", ")}`),
255
259
  details: {
256
260
  action: params.action,
257
- records: [record]
261
+ records: [record],
262
+ dirtyFiles
258
263
  }
259
264
  };
260
265
  }
@@ -278,7 +283,10 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
278
283
  const waiting = await operations.messages(context, params.id);
279
284
  return {
280
285
  content: waiting.length === 0 ? text("No messages.") : text(`${String(waiting.length)} message(s):`, ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`)),
281
- details: { action: params.action }
286
+ details: {
287
+ action: params.action,
288
+ messages: waiting
289
+ }
282
290
  };
283
291
  }
284
292
  case WORKTREE_ACTIONS.prune: {
@@ -293,12 +301,172 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
293
301
  `Untracked directories, left alone: ${plan.untracked.length === 0 ? "none" : plan.untracked.join(", ")}`,
294
302
  ...plan.keptBranches.length === 0 ? [] : [`Branches kept, they hold commits: ${plan.keptBranches.join(", ")}`]
295
303
  ]),
296
- details: { action: params.action }
304
+ details: {
305
+ action: params.action,
306
+ plan
307
+ }
297
308
  };
298
309
  }
299
310
  }
300
311
  }
301
312
  //#endregion
313
+ //#region src/services/worktreeNamespace/index.ts
314
+ const DECLARATIONS = `type WorktreeStatus = 'spawning' | 'running' | 'closing' | 'orphaned';
315
+
316
+ interface Worktree {
317
+ id: string;
318
+ branch: string;
319
+ baseRef: string;
320
+ /** Absolute path of the checkout, under ~/.po/git/worktrees. */
321
+ path: string;
322
+ repositoryRoot: string;
323
+ /** The session running inside the worktree. */
324
+ sessionId: string;
325
+ parentSessionId?: string;
326
+ status: WorktreeStatus;
327
+ createdAt: string;
328
+ /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
329
+ relationship: 'parent' | 'child' | 'other';
330
+ }
331
+
332
+ interface WorktreeMessage {
333
+ worktreeId: string;
334
+ fromSessionId: string;
335
+ from: 'parent' | 'child';
336
+ text: string;
337
+ sentAt: string;
338
+ }
339
+
340
+ interface PrunePlan {
341
+ remove: Worktree[];
342
+ forget: Worktree[];
343
+ /** Kept because they hold uncommitted work. */
344
+ keptDirty: Worktree[];
345
+ untracked: string[];
346
+ /** Branches kept because they hold commits. */
347
+ keptBranches: string[];
348
+ }
349
+
350
+ declare const worktrees: {
351
+ /** Every worktree for this repository. */
352
+ list(): Promise<Worktree[]>;
353
+ /** One worktree and its uncommitted files. */
354
+ status(id: string): Promise<{ worktree: Worktree; dirtyFiles: string[] }>;
355
+ /**
356
+ * Create a worktree on a new branch and start a Po session in it, nested under this one. baseRef defaults to
357
+ * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
358
+ * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
359
+ */
360
+ spawn(request: { branch: string; baseRef?: string; name?: string; task?: string }): Promise<Worktree>;
361
+ /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
362
+ close(id: string, options?: { force?: boolean }): Promise<Worktree>;
363
+ /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
364
+ merge(id: string, options?: { message?: string }): Promise<Worktree>;
365
+ /** Remove orphaned worktrees. With dryRun, only return the plan. */
366
+ prune(options?: { dryRun?: boolean }): Promise<PrunePlan>;
367
+ /**
368
+ * Message the other side of a worktree. Use the record with relationship 'child' to report to your parent,
369
+ * and 'parent' to reach your own children. 'other' records are not communication edges.
370
+ */
371
+ send(id: string, message: string): Promise<void>;
372
+ /** Messages waiting for you from a worktree. */
373
+ messages(id: string): Promise<WorktreeMessage[]>;
374
+ };`;
375
+ const json = (value) => JSON.parse(JSON.stringify(value));
376
+ /** Git worktrees for code mode: the actions of `run_worktree` as methods, returning records instead of text. */
377
+ function createWorktreeNamespace(options) {
378
+ return {
379
+ 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.",
381
+ declarations: DECLARATIONS,
382
+ bind(run) {
383
+ if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
384
+ let disposed = false;
385
+ run.onDispose(() => {
386
+ disposed = true;
387
+ });
388
+ const view = (record) => ({
389
+ ...record,
390
+ relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
391
+ });
392
+ /** 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) => {
394
+ run.signal.throwIfAborted();
395
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
396
+ options.assertAvailable();
397
+ const params = validateParams({
398
+ action,
399
+ ...typeof input === "object" && input !== null ? input : {}
400
+ });
401
+ const context = {
402
+ cwd: options.execution.cwd,
403
+ sessionId: options.execution.sessionId
404
+ };
405
+ const started = Date.now();
406
+ try {
407
+ const result = await executeRunWorktreeTool(params, options.operations, context, { signal: run.signal });
408
+ options.assertAvailable();
409
+ run.record?.({
410
+ name: `worktrees.${name}`,
411
+ tool: RUN_WORKTREE_TOOL_NAME,
412
+ args: params,
413
+ ok: true,
414
+ ms: Date.now() - started,
415
+ result
416
+ });
417
+ return result;
418
+ } catch (error) {
419
+ run.record?.({
420
+ name: `worktrees.${name}`,
421
+ tool: RUN_WORKTREE_TOOL_NAME,
422
+ args: params,
423
+ ok: false,
424
+ ms: Date.now() - started,
425
+ error: error instanceof Error ? error.message : String(error)
426
+ });
427
+ throw error;
428
+ }
429
+ };
430
+ const record = (result) => view(result.details.records[0]);
431
+ const members = Object.create(null);
432
+ members.list = async () => json((await act("list", "list", {})).details.records.map(view));
433
+ members.status = async (id) => {
434
+ const { details } = await act("status", "status", { id });
435
+ return json({
436
+ worktree: view(details.records[0]),
437
+ dirtyFiles: details.dirtyFiles ?? []
438
+ });
439
+ };
440
+ 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
+ })));
449
+ members.prune = async (settings) => {
450
+ const { plan } = (await act("prune", "prune", settings)).details;
451
+ return json({
452
+ ...plan,
453
+ remove: plan.remove.map(view),
454
+ forget: plan.forget.map(view),
455
+ keptDirty: plan.keptDirty.map(view)
456
+ });
457
+ };
458
+ members.send = async (id, message) => {
459
+ await act("send", "send", {
460
+ id,
461
+ message
462
+ });
463
+ };
464
+ members.messages = async (id) => json((await act("messages", "messages", { id })).details.messages);
465
+ return members;
466
+ }
467
+ };
468
+ }
469
+ //#endregion
302
470
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
303
471
  function progressResult(action, label) {
304
472
  return {
@@ -309,7 +477,16 @@ function progressResult(action, label) {
309
477
  details: { action }
310
478
  };
311
479
  }
312
- function createGitSession({ context, host: serverHost }) {
480
+ /** Tools that only read, so the checkout cannot have moved under them. */
481
+ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
482
+ "read",
483
+ "grep",
484
+ "find",
485
+ "ls",
486
+ "discover",
487
+ "load_skill"
488
+ ]);
489
+ function createGitSession({ context, host: serverHost, agent, signal }) {
313
490
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
314
491
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
315
492
  const sessionId = serverHost.context.sessionId;
@@ -322,20 +499,12 @@ function createGitSession({ context, host: serverHost }) {
322
499
  sessionDelivery: () => (0, _agimon_ai_po_session.readPoSessionDelivery)(context)
323
500
  });
324
501
  const resources = [{
325
- when: {
326
- state: { "minor-mode": "help" },
327
- attribution: {
328
- kind: "minor",
329
- mode: "help"
330
- }
331
- },
332
- name: "po-git",
333
- kind: "context",
334
- read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "llms.txt")
335
- }, {
336
- name: "po-use-git",
502
+ name: "codemode-how-to-git",
503
+ description: "Hand a branch of work to a separate session in its own checkout, keeping the current checkout untouched. Use for a long refactor, a risky migration, or parallel features that touch the same files; not for parallel work on one branch.",
337
504
  kind: "skill",
338
- read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/po-use-git/SKILL.md")
505
+ pinned: true,
506
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-git/SKILL.md"),
507
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-git/SKILL.md")
339
508
  }];
340
509
  const tool = {
341
510
  name: RUN_WORKTREE_TOOL_NAME,
@@ -355,17 +524,37 @@ function createGitSession({ context, host: serverHost }) {
355
524
  const changed = (_event, execution) => {
356
525
  directEvents.publish(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
357
526
  };
527
+ const hooks = [{
528
+ event: "tool_execution_end",
529
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
530
+ }, {
531
+ event: "agent_settled",
532
+ handle: changed
533
+ }];
534
+ if (agent) {
535
+ const namespace = createWorktreeNamespace({
536
+ operations,
537
+ execution: agent.context,
538
+ assertAvailable: () => {
539
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
540
+ }
541
+ });
542
+ context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (scoped) => {
543
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(scoped);
544
+ if (!codemode) return void 0;
545
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
546
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
547
+ return () => {
548
+ restriction.dispose();
549
+ registration.dispose();
550
+ };
551
+ });
552
+ }
358
553
  return {
359
554
  value: {
360
555
  resources,
361
556
  tool,
362
- hooks: [{
363
- event: "tool_execution_end",
364
- handle: changed
365
- }, {
366
- event: "agent_settled",
367
- handle: changed
368
- }]
557
+ hooks
369
558
  },
370
559
  onDispose: () => messageInbox.close()
371
560
  };
@@ -476,11 +665,11 @@ const NAME_STATUS = {
476
665
  T: "modified"
477
666
  };
478
667
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
479
- function untrackedLines(root, relPath) {
668
+ async function untrackedLines(root, relPath) {
480
669
  const absolute = node_path.default.join(root, relPath);
481
670
  let stat;
482
671
  try {
483
- stat = node_fs.default.lstatSync(absolute);
672
+ stat = await node_fs_promises.default.lstat(absolute);
484
673
  } catch {
485
674
  return;
486
675
  }
@@ -489,7 +678,7 @@ function untrackedLines(root, relPath) {
489
678
  binary: false
490
679
  };
491
680
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
492
- const content = node_fs.default.readFileSync(absolute);
681
+ const content = await node_fs_promises.default.readFile(absolute);
493
682
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
494
683
  lines: 0,
495
684
  binary: true
@@ -612,8 +801,8 @@ function createBranchDiff() {
612
801
  "--exclude-standard",
613
802
  "-z"
614
803
  ]));
615
- untracked.forEach((relPath, index) => {
616
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
804
+ for (const [index, relPath] of untracked.entries()) {
805
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
617
806
  entries.push({
618
807
  path: relPath,
619
808
  status: "untracked",
@@ -621,18 +810,20 @@ function createBranchDiff() {
621
810
  removed: 0,
622
811
  ...counted?.binary ? { binary: true } : {}
623
812
  });
624
- });
813
+ }
625
814
  entries.sort((left, right) => left.path.localeCompare(right.path));
626
815
  const conflicts = [...unmerged];
627
- const rebasing = [await readLine$1(root, [
816
+ const rebaseMerge = await readLine$1(root, [
628
817
  "rev-parse",
629
818
  "--git-path",
630
819
  "rebase-merge"
631
- ]), await readLine$1(root, [
820
+ ]);
821
+ const rebaseApply = await readLine$1(root, [
632
822
  "rev-parse",
633
823
  "--git-path",
634
824
  "rebase-apply"
635
- ])].some((gitPath) => gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath)));
825
+ ]);
826
+ const rebasing = (await Promise.all([rebaseMerge, rebaseApply].map(async (gitPath) => gitPath === void 0 ? false : node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)))).some(Boolean);
636
827
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
637
828
  let upstream;
638
829
  if (upstreamRef !== void 0) {
@@ -677,7 +868,7 @@ function createBranchDiff() {
677
868
  if (entry === void 0) throw new Error("That path is not in this review.");
678
869
  if (entry.status === "untracked") {
679
870
  const absolute = node_path.default.join(review.root, entry.path);
680
- const stat = node_fs.default.lstatSync(absolute);
871
+ const stat = await node_fs_promises.default.lstat(absolute);
681
872
  if (stat.isSymbolicLink()) return {
682
873
  path: entry.path,
683
874
  hunks: [{
@@ -685,7 +876,7 @@ function createBranchDiff() {
685
876
  rows: [{
686
877
  marker: "+",
687
878
  line: 1,
688
- content: node_fs.default.readlinkSync(absolute)
879
+ content: await node_fs_promises.default.readlink(absolute)
689
880
  }]
690
881
  }]
691
882
  };
@@ -694,7 +885,7 @@ function createBranchDiff() {
694
885
  hunks: [],
695
886
  tooLarge: true
696
887
  };
697
- const content = node_fs.default.readFileSync(absolute);
888
+ const content = await node_fs_promises.default.readFile(absolute);
698
889
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
699
890
  path: entry.path,
700
891
  hunks: [],
@@ -811,9 +1002,9 @@ function isRecord(value) {
811
1002
  return typeof value === "object" && value !== null && !Array.isArray(value);
812
1003
  }
813
1004
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
814
- function workspaceKey(workspaceRoot) {
1005
+ async function workspaceKey(workspaceRoot) {
815
1006
  try {
816
- return node_fs.default.realpathSync(workspaceRoot);
1007
+ return await node_fs_promises.default.realpath(workspaceRoot);
817
1008
  } catch {
818
1009
  return node_path.default.resolve(workspaceRoot);
819
1010
  }
@@ -862,7 +1053,7 @@ function publicView(config) {
862
1053
  * the saved one, and only for the same host: a token never follows a host it
863
1054
  * was not entered for.
864
1055
  */
865
- function parseGitAuthSave(request, current, homeDir) {
1056
+ async function parseGitAuthSave(request, current, homeDir) {
866
1057
  if (!isRecord(request)) throw require_worktreeOperations.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
867
1058
  if (request.method === "none") return { method: "none" };
868
1059
  if (request.method === "ssh") {
@@ -872,7 +1063,7 @@ function parseGitAuthSave(request, current, homeDir) {
872
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 ~/.");
873
1064
  let isFile = false;
874
1065
  try {
875
- isFile = node_fs.default.statSync(expandHome(keyPath, homeDir)).isFile();
1066
+ isFile = (await node_fs_promises.default.stat(expandHome(keyPath, homeDir))).isFile();
876
1067
  } catch {
877
1068
  isFile = false;
878
1069
  }
@@ -907,16 +1098,16 @@ function parseGitAuthSave(request, current, homeDir) {
907
1098
  throw require_worktreeOperations.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
908
1099
  }
909
1100
  /** Tightens a file or folder something left readable by group or others. */
910
- function tighten(target, mode) {
1101
+ async function tighten(target, mode) {
911
1102
  try {
912
- if ((node_fs.default.statSync(target).mode & LOOSE_BITS) !== 0) node_fs.default.chmodSync(target, mode);
1103
+ if (((await node_fs_promises.default.stat(target)).mode & LOOSE_BITS) !== 0) await node_fs_promises.default.chmod(target, mode);
913
1104
  } catch {}
914
1105
  }
915
- function createGitAuthStore(homeDir = node_os.default.homedir()) {
916
- const file = require_worktreeOperations.credentialsFile(homeDir);
917
- const readFile = () => {
918
- tighten(file, OWNER_ONLY_FILE);
919
- const raw = require_worktreeOperations.readJson(file);
1106
+ function createGitAuthStore(homeDir = node_os.default.homedir(), environment = {}) {
1107
+ const file = require_worktreeOperations.credentialsFile(homeDir, environment);
1108
+ const readFile = async () => {
1109
+ await tighten(file, OWNER_ONLY_FILE);
1110
+ const raw = await require_worktreeOperations.readJson(file);
920
1111
  const workspaces = {};
921
1112
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
922
1113
  const config = parseConfig(value);
@@ -927,28 +1118,28 @@ function createGitAuthStore(homeDir = node_os.default.homedir()) {
927
1118
  workspaces
928
1119
  };
929
1120
  };
930
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1121
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
931
1122
  return {
932
1123
  read,
933
- view: (workspaceRoot) => publicView(read(workspaceRoot)),
934
- save(workspaceRoot, request) {
935
- const key = workspaceKey(workspaceRoot);
936
- const current = readFile();
937
- const next = parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
938
- const root = require_worktreeOperations.poGitRoot(homeDir);
939
- node_fs.default.mkdirSync(root, {
1124
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1125
+ async save(workspaceRoot, request) {
1126
+ const key = await workspaceKey(workspaceRoot);
1127
+ const current = await readFile();
1128
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1129
+ const root = require_worktreeOperations.poGitRoot(homeDir, environment);
1130
+ await node_fs_promises.default.mkdir(root, {
940
1131
  recursive: true,
941
1132
  mode: OWNER_ONLY_DIRECTORY
942
1133
  });
943
- node_fs.default.chmodSync(root, OWNER_ONLY_DIRECTORY);
1134
+ await node_fs_promises.default.chmod(root, OWNER_ONLY_DIRECTORY);
944
1135
  const workspaces = { ...current.workspaces };
945
1136
  if (next.method === "none") delete workspaces[key];
946
1137
  else workspaces[key] = next;
947
- require_worktreeOperations.writeJsonAtomic(file, {
1138
+ await require_worktreeOperations.writeJsonAtomic(file, {
948
1139
  version: 1,
949
1140
  workspaces
950
1141
  });
951
- node_fs.default.chmodSync(file, OWNER_ONLY_FILE);
1142
+ await node_fs_promises.default.chmod(file, OWNER_ONLY_FILE);
952
1143
  return publicView(next);
953
1144
  }
954
1145
  };
@@ -1067,7 +1258,13 @@ function newSessionRequest(body) {
1067
1258
  if (branch === void 0 || branch === false || !require_worktreeOperations.validRefName(branch)) return { error: "A valid branch name is required." };
1068
1259
  const name = optionalText(record.name);
1069
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.` };
1070
- const named = name === void 0 ? {} : { name };
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
+ };
1071
1268
  if (record.mode === "existing-branch") {
1072
1269
  const remote = optionalText(record.remote);
1073
1270
  if (remote === false || remote !== void 0 && !require_worktreeOperations.validRefName(remote)) return { error: "That remote name is not valid." };
@@ -1113,177 +1310,238 @@ function failed(error) {
1113
1310
  }, { status: error.retryable ? 503 : 409 });
1114
1311
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1115
1312
  }
1116
- //#endregion
1117
- //#region src/extensions/(backend)/api/git/route.server.ts
1118
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)({
1119
- basePath: "git",
1120
- start(context) {
1121
- if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1122
- const directEvents = context.directEvents;
1123
- const publishLifecycle = (sessionId, repositoryRoot) => {
1124
- directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1125
- version: 1,
1126
- repositoryRoot
1313
+ function createGitApi(openDirectory) {
1314
+ return {
1315
+ basePath: "git",
1316
+ start(context) {
1317
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1318
+ const directEvents = context.directEvents;
1319
+ const publishLifecycle = (sessionId, repositoryRoot) => {
1320
+ directEvents.publish(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1321
+ version: 1,
1322
+ repositoryRoot
1323
+ });
1324
+ };
1325
+ const git = require_worktreeOperations.createWorktreeGit();
1326
+ const operations = require_worktreeOperations.createWorktreeOperations({
1327
+ git,
1328
+ sessionService: context.sessionService,
1329
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
1330
+ ...context.environment === void 0 ? {} : { environment: context.environment }
1127
1331
  });
1128
- };
1129
- const git = require_worktreeOperations.createWorktreeGit();
1130
- const operations = require_worktreeOperations.createWorktreeOperations({
1131
- git,
1132
- sessionService: context.sessionService,
1133
- ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory }
1134
- });
1135
- /**
1136
- * The new-session dialog's routes: the workspace's branches, and a top-level
1137
- * worktree session on one. Workspace-mounted only, and always rooted at the
1138
- * mount's own workspace, so a request can never name another directory.
1139
- */
1140
- const newSession = async (request, url) => {
1141
- const isBranches = request.method === "GET" && url.pathname === "/branches";
1142
- const isCreate = request.method === "POST" && url.pathname === "/sessions";
1143
- if (!isBranches && !isCreate) return void 0;
1144
- const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1145
- if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1146
- if (isBranches) {
1147
- const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1148
- const branches = repositoryRoot === void 0 ? {
1149
- repository: false,
1150
- local: [],
1151
- remote: []
1152
- } : {
1153
- repository: true,
1154
- ...await git.listBranches(repositoryRoot)
1332
+ /**
1333
+ * The new-session dialog's routes: the workspace's branches, and a top-level
1334
+ * worktree session on one. Workspace-mounted only, and always rooted at the
1335
+ * mount's own workspace, so a request can never name another directory.
1336
+ */
1337
+ const newSession = async (request, url) => {
1338
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
1339
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
1340
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
1341
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
1342
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
1343
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1344
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1345
+ if (isBranches) {
1346
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1347
+ const branches = repositoryRoot === void 0 ? {
1348
+ repository: false,
1349
+ local: [],
1350
+ remote: []
1351
+ } : {
1352
+ repository: true,
1353
+ ...await git.listBranches(repositoryRoot)
1354
+ };
1355
+ return Response.json(branches);
1356
+ }
1357
+ if (isDelete || isOpen) {
1358
+ 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
+ const body = await request.json().catch(() => void 0);
1360
+ 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.");
1362
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1363
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
1364
+ const branches = await git.listBranches(repositoryRoot);
1365
+ const local = branches.local.find((item) => item.name === branch);
1366
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
1367
+ if (isOpen) {
1368
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
1369
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
1370
+ try {
1371
+ await openDirectory(local.checkedOutAt);
1372
+ return Response.json({ opened: true });
1373
+ } catch {
1374
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
1375
+ }
1376
+ }
1377
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
1378
+ if (!await git.deleteBranch({
1379
+ repositoryRoot,
1380
+ branch
1381
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
1382
+ return Response.json({ deleted: true });
1383
+ }
1384
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
1385
+ if ("error" in parsed) return badRequest(parsed.error);
1386
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
1387
+ branch: parsed.branch,
1388
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1389
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1390
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1391
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
1392
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1393
+ });
1394
+ publishLifecycle(record.sessionId, record.repositoryRoot);
1395
+ const created = {
1396
+ sessionId: record.sessionId,
1397
+ worktreeId: record.id
1155
1398
  };
1156
- return Response.json(branches);
1157
- }
1158
- const parsed = newSessionRequest(await request.json().catch(() => void 0));
1159
- if ("error" in parsed) return badRequest(parsed.error);
1160
- const record = await operations.spawn({ cwd: workspaceRoot }, {
1161
- branch: parsed.branch,
1162
- checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1163
- ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1164
- ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1165
- ...parsed.name === void 0 ? {} : { name: parsed.name }
1166
- });
1167
- publishLifecycle(record.sessionId, record.repositoryRoot);
1168
- const created = {
1169
- sessionId: record.sessionId,
1170
- worktreeId: record.id
1399
+ return Response.json(created, { status: 201 });
1171
1400
  };
1172
- return Response.json(created, { status: 201 });
1173
- };
1174
- /** The admitted root for a request, or a response explaining why not. */
1175
- const rootOf = (url) => {
1176
- const repositoryId = url.searchParams.get("repositoryId");
1177
- if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1178
- const root = context.resolveRepository?.(repositoryId);
1179
- if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1180
- return root;
1181
- };
1182
- const homeDir = context.homeDirectory ?? node_os.default.homedir();
1183
- const gitAuth = createGitAuthStore(homeDir);
1184
- const branchDiff = createBranchDiff();
1185
- const pendingReviews = /* @__PURE__ */ new Map();
1186
- /**
1187
- * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1188
- * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1189
- * The view never carries the token.
1190
- */
1191
- const auth = async (request, url) => {
1192
- if (url.pathname !== "/auth") return void 0;
1193
- if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1194
- if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1195
- const root = rootOf(url);
1196
- if (root instanceof Response) return root;
1197
- if (request.method === "GET") return Response.json(gitAuth.view(root));
1198
- try {
1199
- return Response.json(gitAuth.save(root, await request.json().catch(() => void 0)));
1200
- } catch (error) {
1201
- if (error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "invalid_request") {
1202
- const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1203
- return Response.json({
1204
- error: text,
1205
- code: error.code
1206
- }, { status: 400 });
1207
- }
1208
- throw error;
1209
- }
1210
- };
1211
- /**
1212
- * The session's change against its base. Session mounts only, rooted at the
1213
- * session's own checkout; a file is served only when it is in the change set
1214
- * computed for the request. Overlapping requests share an in-flight snapshot.
1215
- */
1216
- const review = async (request, url) => {
1217
- if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1218
- const cwd = context.scope === "session" ? context.cwd : void 0;
1219
- if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1220
- if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1221
- let recordedBaseRef;
1222
- try {
1223
- recordedBaseRef = require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(cwd, homeDir)).list().find((record) => record.sessionId === context.sessionId)?.baseRef;
1224
- } catch {
1225
- recordedBaseRef = void 0;
1226
- }
1227
- const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1228
- let pending = pendingReviews.get(key);
1229
- if (pending === void 0) {
1230
- pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1231
- pendingReviews.set(key, pending);
1232
- }
1233
- const result = await pending;
1234
- if (url.pathname === "/review") return Response.json(result?.summary ?? {
1235
- repository: false,
1236
- files: []
1237
- });
1238
- const filePath = url.searchParams.get("path") ?? "";
1239
- if (result === void 0 || !result.summary.files.some((file) => file.path === filePath)) return Response.json({ error: "That file is not part of this review." }, { status: 404 });
1240
- return Response.json(await branchDiff.fileDiff(result, filePath));
1241
- };
1242
- return {
1243
- async fetch(request) {
1244
- const url = new URL(request.url);
1401
+ /** The admitted root for a request, or a response explaining why not. */
1402
+ const rootOf = (url) => {
1403
+ const repositoryId = url.searchParams.get("repositoryId");
1404
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1405
+ const root = context.resolveRepository?.(repositoryId);
1406
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1407
+ return root;
1408
+ };
1409
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
1410
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir, context.environment);
1411
+ const branchDiff = createBranchDiff();
1412
+ const pendingReviews = /* @__PURE__ */ new Map();
1413
+ /**
1414
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1415
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1416
+ * The view never carries the token.
1417
+ */
1418
+ const auth = async (request, url) => {
1419
+ if (url.pathname !== "/auth") return void 0;
1420
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1421
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1422
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
1423
+ const root = rootOf(url);
1424
+ if (root instanceof Response) return root;
1425
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
1245
1426
  try {
1246
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1247
- if (answered !== void 0) return answered;
1427
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
1248
1428
  } catch (error) {
1249
- context.onNotice(`git request failed: ${error.name}`);
1250
- return failed(error);
1429
+ if (error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "invalid_request") {
1430
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1431
+ return Response.json({
1432
+ error: text,
1433
+ code: error.code
1434
+ }, { status: 400 });
1435
+ }
1436
+ throw error;
1251
1437
  }
1252
- const root = rootOf(url);
1253
- if (root instanceof Response) return root;
1254
- const callerContext = {
1255
- cwd: root,
1256
- sessionId: url.searchParams.get("sessionId") ?? ""
1257
- };
1258
- if ((request.method === "POST" && url.pathname === "/worktrees" || request.method === "DELETE" && /^\/worktrees\/[^/]+$/u.test(url.pathname)) && callerContext.sessionId === "") return badRequest("A sessionId is required for worktree mutations.");
1438
+ };
1439
+ /**
1440
+ * The session's change against its base. Session mounts only, rooted at the
1441
+ * session's own checkout; a file is served only when it is in the change set
1442
+ * computed for the request. Overlapping requests share an in-flight snapshot.
1443
+ */
1444
+ const review = async (request, url) => {
1445
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1446
+ const cwd = context.scope === "session" ? context.cwd : void 0;
1447
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1448
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1449
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
1450
+ let recordedBaseRef;
1259
1451
  try {
1260
- if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1261
- if (request.method === "POST" && url.pathname === "/worktrees") {
1262
- const body = await request.json();
1263
- if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1264
- const record = await operations.spawn(callerContext, {
1265
- branch: body.branch,
1266
- ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1267
- ...body.name === void 0 ? {} : { name: body.name }
1268
- });
1269
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1270
- return Response.json({ worktree: record }, { status: 201 });
1452
+ recordedBaseRef = (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
1453
+ } catch {
1454
+ recordedBaseRef = void 0;
1455
+ }
1456
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1457
+ let pending = pendingReviews.get(key);
1458
+ if (pending === void 0) {
1459
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1460
+ pendingReviews.set(key, pending);
1461
+ }
1462
+ const result = await pending;
1463
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
1464
+ repository: false,
1465
+ files: []
1466
+ });
1467
+ const filePath = url.searchParams.get("path") ?? "";
1468
+ if (result === void 0 || !result.summary.files.some((file) => file.path === filePath)) return Response.json({ error: "That file is not part of this review." }, { status: 404 });
1469
+ return Response.json(await branchDiff.fileDiff(result, filePath));
1470
+ };
1471
+ return {
1472
+ async fetch(request) {
1473
+ const url = new URL(request.url);
1474
+ try {
1475
+ const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1476
+ if (answered !== void 0) return answered;
1477
+ } catch (error) {
1478
+ context.onNotice(`git request failed: ${error.name}`);
1479
+ return failed(error);
1271
1480
  }
1272
- const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1273
- if (request.method === "DELETE" && closing) {
1274
- const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1275
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1276
- return Response.json({ worktree: record });
1481
+ const root = rootOf(url);
1482
+ if (root instanceof Response) return root;
1483
+ const callerContext = {
1484
+ cwd: root,
1485
+ sessionId: url.searchParams.get("sessionId") ?? ""
1486
+ };
1487
+ if ((request.method === "POST" && url.pathname === "/worktrees" || request.method === "DELETE" && /^\/worktrees\/[^/]+$/u.test(url.pathname)) && callerContext.sessionId === "") return badRequest("A sessionId is required for worktree mutations.");
1488
+ try {
1489
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1490
+ if (request.method === "POST" && url.pathname === "/worktrees") {
1491
+ const body = await request.json();
1492
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1493
+ const record = await operations.spawn(callerContext, {
1494
+ branch: body.branch,
1495
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1496
+ ...body.name === void 0 ? {} : { name: body.name }
1497
+ });
1498
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1499
+ return Response.json({ worktree: record }, { status: 201 });
1500
+ }
1501
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1502
+ if (request.method === "DELETE" && closing) {
1503
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1504
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1505
+ return Response.json({ worktree: record });
1506
+ }
1507
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
1508
+ } catch (error) {
1509
+ context.onNotice(`worktree request failed: ${error.name}`);
1510
+ return failed(error);
1277
1511
  }
1278
- return Response.json({ error: "No such worktree route." }, { status: 404 });
1279
- } catch (error) {
1280
- context.onNotice(`worktree request failed: ${error.name}`);
1281
- return failed(error);
1282
- }
1283
- },
1284
- close() {}
1512
+ },
1513
+ close() {}
1514
+ };
1515
+ }
1516
+ };
1517
+ }
1518
+ //#endregion
1519
+ //#region src/extensions/(backend)/api/git/route.server.ts
1520
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ context, host, signal }) => {
1521
+ let openDirectory;
1522
+ context.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
1523
+ const shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
1524
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
1525
+ openDirectory = async (path) => {
1526
+ const result = await shell.exec([
1527
+ "/usr/bin/open",
1528
+ "-a",
1529
+ "Finder",
1530
+ path
1531
+ ], {
1532
+ env,
1533
+ inheritEnv: false
1534
+ }, (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
1535
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
1285
1536
  };
1286
- }
1537
+ return () => {
1538
+ openDirectory = void 0;
1539
+ };
1540
+ });
1541
+ return createGitApi(async (path) => {
1542
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1543
+ await openDirectory(path);
1544
+ });
1287
1545
  });
1288
1546
  //#endregion
1289
1547
  //#region src/services/gitFailure/index.ts
@@ -1420,7 +1678,7 @@ async function rebasing(root) {
1420
1678
  "--git-path",
1421
1679
  name
1422
1680
  ]);
1423
- if (gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath))) return true;
1681
+ if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1424
1682
  }
1425
1683
  return false;
1426
1684
  }
@@ -1591,8 +1849,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1591
1849
  * - Apart from the worktrees channel. Worktrees are repository management;
1592
1850
  * this is the session's own code change.
1593
1851
  * - Push, not poll. The session's server plugin publishes a "changed" event
1594
- * after every tool call and settled turn; recounts are coalesced to one in
1595
- * flight plus one rerun, so a burst of tool calls costs at most two.
1852
+ * after every tool call that can write and every settled turn; a recount
1853
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
1854
+ * in flight plus one rerun.
1596
1855
  * - One sync command per session. A rebase and a push must never overlap.
1597
1856
  * - Auth is read fresh for each command from the session's workspace, and goes
1598
1857
  * only into that command's git child.
@@ -1601,6 +1860,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1601
1860
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1602
1861
  * stderr and drops it, because a remote URL in it can carry a token.
1603
1862
  */
1863
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
1864
+ const REFRESH_DELAY_MS = 1500;
1604
1865
  function payloadOf$1(state) {
1605
1866
  return {
1606
1867
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1645,17 +1906,19 @@ function createGitChangesChannel(options = {}) {
1645
1906
  const homeDir = options.homeDir ?? node_os.default.homedir();
1646
1907
  const diff = options.diff ?? createBranchDiff();
1647
1908
  const sync = options.sync ?? createGitSync({ homeDir });
1648
- const auth = options.auth ?? createGitAuthStore(homeDir);
1909
+ const auth = options.auth ?? createGitAuthStore(homeDir, options.environment);
1649
1910
  const latest = /* @__PURE__ */ new Map();
1650
1911
  const subscriptions = /* @__PURE__ */ new Map();
1651
1912
  const scopes = /* @__PURE__ */ new Map();
1652
1913
  const inFlight = /* @__PURE__ */ new Set();
1653
1914
  const rerun = /* @__PURE__ */ new Set();
1654
1915
  const busy = /* @__PURE__ */ new Set();
1916
+ const delayed = /* @__PURE__ */ new Map();
1917
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1655
1918
  /** The base the session's own worktree was created from, when it has one. */
1656
- const recordedBaseRef = (scope) => {
1919
+ const recordedBaseRef = async (scope) => {
1657
1920
  try {
1658
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
1921
+ return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1659
1922
  } catch {
1660
1923
  return;
1661
1924
  }
@@ -1688,8 +1951,7 @@ function createGitChangesChannel(options = {}) {
1688
1951
  return;
1689
1952
  }
1690
1953
  inFlight.add(sessionId);
1691
- const base = recordedBaseRef(scope);
1692
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
1954
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1693
1955
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1694
1956
  }).catch((error) => {
1695
1957
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1698,12 +1960,22 @@ function createGitChangesChannel(options = {}) {
1698
1960
  if (rerun.delete(sessionId)) refresh(sessionId);
1699
1961
  });
1700
1962
  };
1701
- const run = (scope, command) => {
1963
+ /** Recounts once the session has been quiet for a moment. */
1964
+ const refreshSoon = (sessionId) => {
1965
+ clearTimeout(delayed.get(sessionId));
1966
+ const timer = setTimeout(() => {
1967
+ delayed.delete(sessionId);
1968
+ refresh(sessionId);
1969
+ }, refreshDelayMs);
1970
+ timer.unref?.();
1971
+ delayed.set(sessionId, timer);
1972
+ };
1973
+ const run = async (scope, command) => {
1702
1974
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1703
- const base = recordedBaseRef(scope);
1975
+ const base = await recordedBaseRef(scope);
1704
1976
  const context = {
1705
1977
  cwd: scope.cwd,
1706
- auth: auth.read(workspaceRoot),
1978
+ auth: await auth.read(workspaceRoot),
1707
1979
  ...base === void 0 ? {} : { recordedBaseRef: base }
1708
1980
  };
1709
1981
  if (command.action === "pull") return sync.pull(context);
@@ -1720,12 +1992,14 @@ function createGitChangesChannel(options = {}) {
1720
1992
  scopes.set(scope.sessionId, scope);
1721
1993
  refresh(scope.sessionId);
1722
1994
  const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1723
- if (require_worktreeOperations.isSessionChangedEvent(payload)) refresh(scope.sessionId);
1995
+ if (require_worktreeOperations.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1724
1996
  });
1725
1997
  subscriptions.set(scope.sessionId, unsubscribe);
1726
1998
  },
1727
1999
  sessionRemoved(sessionId) {
1728
2000
  subscriptions.get(sessionId)?.();
2001
+ clearTimeout(delayed.get(sessionId));
2002
+ delayed.delete(sessionId);
1729
2003
  subscriptions.delete(sessionId);
1730
2004
  scopes.delete(sessionId);
1731
2005
  latest.delete(sessionId);
@@ -1734,6 +2008,8 @@ function createGitChangesChannel(options = {}) {
1734
2008
  },
1735
2009
  close() {
1736
2010
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2011
+ for (const timer of delayed.values()) clearTimeout(timer);
2012
+ delayed.clear();
1737
2013
  subscriptions.clear();
1738
2014
  scopes.clear();
1739
2015
  latest.clear();
@@ -1801,9 +2077,9 @@ function payloadOf(state) {
1801
2077
  };
1802
2078
  }
1803
2079
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1804
- function viewsFor(scope, deps) {
2080
+ async function viewsFor(scope, deps) {
1805
2081
  try {
1806
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2082
+ return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
1807
2083
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1808
2084
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1809
2085
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1828,11 +2104,15 @@ function sameList(left, right) {
1828
2104
  return other !== void 0 && entry.id === other.id && entry.branch === other.branch && entry.sessionId === other.sessionId && entry.orphaned === other.orphaned && entry.unowned === other.unowned;
1829
2105
  });
1830
2106
  }
1831
- function errorTargetFor(command) {
1832
- return command.action === "create" ? { action: "create" } : {
2107
+ function errorTargetFor(command, error) {
2108
+ if (command.action === "close") return {
1833
2109
  action: "close",
1834
2110
  id: command.id
1835
2111
  };
2112
+ return error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "rift_missing" ? {
2113
+ action: "create",
2114
+ riftMissing: true
2115
+ } : { action: "create" };
1836
2116
  }
1837
2117
  /** A command the page sent, or undefined when the frame was not one. */
1838
2118
  function parseCommand(payload) {
@@ -1860,11 +2140,15 @@ function parseCommand(payload) {
1860
2140
  /**
1861
2141
  * What the reader is told when a command fails.
1862
2142
  *
1863
- * An expected failure explains itself. Anything else is summarised, never
1864
- * echoed: a git error can carry a remote URL with a token in it.
2143
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2144
+ * written for the agent's tool result. A dirty close is said in the person's
2145
+ * terms, because its message tells the agent to pass `force`. Anything else is
2146
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1865
2147
  */
1866
2148
  function failureText(error) {
1867
- return error instanceof require_worktreeOperations.PoGitExpectedError ? error.message : "The worktree operation failed.";
2149
+ if (!(error instanceof require_worktreeOperations.PoGitExpectedError)) return "The worktree operation failed.";
2150
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2151
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1868
2152
  }
1869
2153
  /** Starts one direct-event subscription per managed session. */
1870
2154
  function createWorktreesChannel(options = {}) {
@@ -1876,7 +2160,9 @@ function createWorktreesChannel(options = {}) {
1876
2160
  if (sessionService === void 0) throw new require_worktreeOperations.HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1877
2161
  const worktrees = options.operations ?? require_worktreeOperations.createWorktreeOperations({
1878
2162
  git: require_worktreeOperations.createWorktreeGit(),
1879
- sessionService
2163
+ sessionService,
2164
+ ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2165
+ ...options.environment === void 0 ? {} : { environment: options.environment }
1880
2166
  });
1881
2167
  /** Announces a successful mutation to this session's lifecycle subscribers. */
1882
2168
  const publishLifecycle = (scope, repositoryRoot) => {
@@ -1905,6 +2191,7 @@ function createWorktreesChannel(options = {}) {
1905
2191
  });
1906
2192
  const views = {
1907
2193
  homeDir: options.homeDir,
2194
+ environment: options.environment,
1908
2195
  sessionService
1909
2196
  };
1910
2197
  const latest = /* @__PURE__ */ new Map();
@@ -1917,10 +2204,13 @@ function createWorktreesChannel(options = {}) {
1917
2204
  return generation;
1918
2205
  };
1919
2206
  /** Republishes a session, skipping a frame that would say nothing new. */
1920
- const publish = (scope, force) => {
2207
+ const publish = async (scope, force) => {
2208
+ const generation = generations.get(scope.sessionId);
2209
+ const worktreeViews = await viewsFor(scope, views);
2210
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1921
2211
  const previous = latest.get(scope.sessionId);
1922
2212
  const next = {
1923
- worktrees: viewsFor(scope, views),
2213
+ worktrees: worktreeViews,
1924
2214
  pending: previous?.pending,
1925
2215
  error: previous?.error,
1926
2216
  errorTarget: previous?.errorTarget
@@ -1932,7 +2222,7 @@ function createWorktreesChannel(options = {}) {
1932
2222
  const mark = (scope, pending, error, errorTarget) => {
1933
2223
  const previous = latest.get(scope.sessionId);
1934
2224
  latest.set(scope.sessionId, {
1935
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2225
+ worktrees: previous?.worktrees ?? [],
1936
2226
  pending,
1937
2227
  error,
1938
2228
  errorTarget
@@ -1972,15 +2262,15 @@ function createWorktreesChannel(options = {}) {
1972
2262
  sessionAdded(scope) {
1973
2263
  newGeneration(scope.sessionId);
1974
2264
  publish(scope, false);
1975
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
2265
+ const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
1976
2266
  if (!require_worktreeOperations.isWorktreeLifecycleEvent(payload)) return;
1977
2267
  let sameRepository = false;
1978
2268
  try {
1979
- sameRepository = require_worktreeOperations.registryFile(scope.cwd, options.homeDir) === require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir);
2269
+ sameRepository = await require_worktreeOperations.registryFile(scope.cwd, options.homeDir, options.environment) === await require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir, options.environment);
1980
2270
  } catch {
1981
2271
  sameRepository = false;
1982
2272
  }
1983
- if (sameRepository) publish(scope, false);
2273
+ if (sameRepository) await publish(scope, false);
1984
2274
  });
1985
2275
  subscriptions.set(scope.sessionId, unsubscribe);
1986
2276
  },
@@ -2013,7 +2303,7 @@ function createWorktreesChannel(options = {}) {
2013
2303
  }).catch((error) => {
2014
2304
  if (generations.get(scope.sessionId) !== generation) return;
2015
2305
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2016
- mark(scope, void 0, failureText(error), errorTargetFor(command));
2306
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2017
2307
  }).finally(() => {
2018
2308
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2019
2309
  });
@@ -2035,20 +2325,8 @@ var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHo
2035
2325
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2036
2326
  var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
2037
2327
  //#endregion
2038
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGit.server.ts
2039
- var poGit_server_default$1 = (context) => context.root.resources[0];
2040
- //#endregion
2041
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGit.server.ts
2042
- var poGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poGit_server_default$1);
2043
- //#endregion
2044
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGitReadme.server.ts
2045
- var poGitReadme_server_default$1 = (context) => context.root.resources[2];
2046
- //#endregion
2047
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGitReadme.server.ts
2048
- var poGitReadme_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poGitReadme_server_default$1);
2049
- //#endregion
2050
2328
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2051
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
2329
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2052
2330
  //#endregion
2053
2331
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2054
2332
  var poUseGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poUseGit_server_default$1);
@@ -2068,12 +2346,12 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2068
2346
  name: "@agimon-ai/po-git",
2069
2347
  providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
2070
2348
  injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
2071
- global: (context) => ({
2349
+ host: (context) => ({
2072
2350
  get api() {
2073
2351
  return [at(route_server_default, context)];
2074
2352
  },
2075
2353
  get channels() {
2076
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2354
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2077
2355
  }
2078
2356
  }),
2079
2357
  workspace: (context) => ({
@@ -2081,7 +2359,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2081
2359
  return [at(route_server_default, context)];
2082
2360
  },
2083
2361
  get channels() {
2084
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "git_changes" }, git_changes_server_default()), context.hosted("global") ? void 0 : () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())]);
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))]);
2085
2363
  }
2086
2364
  }),
2087
2365
  session: async (context) => {
@@ -2096,17 +2374,13 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2096
2374
  return [at(route_server_default, context)];
2097
2375
  },
2098
2376
  get channels() {
2099
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "git_changes" }, git_changes_server_default()), context.hosted("global") ? void 0 : () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())]);
2377
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), context.hosted("host") ? void 0 : () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))]);
2100
2378
  },
2101
2379
  get hooks() {
2102
2380
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2103
2381
  },
2104
2382
  get resources() {
2105
- return [
2106
- at(poGit_server_default, contextSession),
2107
- at(poGitReadme_server_default, contextSession),
2108
- at(poUseGit_server_default, contextSession)
2109
- ];
2383
+ return [at(poUseGit_server_default, contextSession)];
2110
2384
  },
2111
2385
  get tools() {
2112
2386
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];