@agimon-ai/po-git 0.0.0-alpha.18 → 0.0.0-alpha.181

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-0Jrjcbg7.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
1106
  function createGitAuthStore(homeDir = node_os.default.homedir()) {
916
1107
  const file = require_worktreeOperations.credentialsFile(homeDir);
917
- const readFile = () => {
918
- tighten(file, OWNER_ONLY_FILE);
919
- const raw = require_worktreeOperations.readJson(file);
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);
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);
938
1129
  const root = require_worktreeOperations.poGitRoot(homeDir);
939
- node_fs.default.mkdirSync(root, {
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,237 @@ 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 }
1127
1330
  });
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)
1331
+ /**
1332
+ * The new-session dialog's routes: the workspace's branches, and a top-level
1333
+ * worktree session on one. Workspace-mounted only, and always rooted at the
1334
+ * mount's own workspace, so a request can never name another directory.
1335
+ */
1336
+ const newSession = async (request, url) => {
1337
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
1338
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
1339
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
1340
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
1341
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
1342
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1343
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1344
+ if (isBranches) {
1345
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1346
+ const branches = repositoryRoot === void 0 ? {
1347
+ repository: false,
1348
+ local: [],
1349
+ remote: []
1350
+ } : {
1351
+ repository: true,
1352
+ ...await git.listBranches(repositoryRoot)
1353
+ };
1354
+ return Response.json(branches);
1355
+ }
1356
+ if (isDelete || isOpen) {
1357
+ 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 });
1358
+ const body = await request.json().catch(() => void 0);
1359
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
1360
+ if (typeof branch !== "string" || !require_worktreeOperations.validRefName(branch)) return badRequest("A valid branch name is required.");
1361
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1362
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
1363
+ const branches = await git.listBranches(repositoryRoot);
1364
+ const local = branches.local.find((item) => item.name === branch);
1365
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
1366
+ if (isOpen) {
1367
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
1368
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
1369
+ try {
1370
+ await openDirectory(local.checkedOutAt);
1371
+ return Response.json({ opened: true });
1372
+ } catch {
1373
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
1374
+ }
1375
+ }
1376
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
1377
+ if (!await git.deleteBranch({
1378
+ repositoryRoot,
1379
+ branch
1380
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
1381
+ return Response.json({ deleted: true });
1382
+ }
1383
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
1384
+ if ("error" in parsed) return badRequest(parsed.error);
1385
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
1386
+ branch: parsed.branch,
1387
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1388
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1389
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1390
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
1391
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1392
+ });
1393
+ publishLifecycle(record.sessionId, record.repositoryRoot);
1394
+ const created = {
1395
+ sessionId: record.sessionId,
1396
+ worktreeId: record.id
1155
1397
  };
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
1398
+ return Response.json(created, { status: 201 });
1171
1399
  };
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);
1400
+ /** The admitted root for a request, or a response explaining why not. */
1401
+ const rootOf = (url) => {
1402
+ const repositoryId = url.searchParams.get("repositoryId");
1403
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1404
+ const root = context.resolveRepository?.(repositoryId);
1405
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1406
+ return root;
1407
+ };
1408
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
1409
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir);
1410
+ const branchDiff = createBranchDiff();
1411
+ const pendingReviews = /* @__PURE__ */ new Map();
1412
+ /**
1413
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1414
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1415
+ * The view never carries the token.
1416
+ */
1417
+ const auth = async (request, url) => {
1418
+ if (url.pathname !== "/auth") return void 0;
1419
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1420
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1421
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
1422
+ const root = rootOf(url);
1423
+ if (root instanceof Response) return root;
1424
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
1245
1425
  try {
1246
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1247
- if (answered !== void 0) return answered;
1426
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
1248
1427
  } catch (error) {
1249
- context.onNotice(`git request failed: ${error.name}`);
1250
- return failed(error);
1428
+ if (error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "invalid_request") {
1429
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1430
+ return Response.json({
1431
+ error: text,
1432
+ code: error.code
1433
+ }, { status: 400 });
1434
+ }
1435
+ throw error;
1251
1436
  }
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.");
1437
+ };
1438
+ /**
1439
+ * The session's change against its base. Session mounts only, rooted at the
1440
+ * session's own checkout; a file is served only when it is in the change set
1441
+ * computed for the request. Overlapping requests share an in-flight snapshot.
1442
+ */
1443
+ const review = async (request, url) => {
1444
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1445
+ const cwd = context.scope === "session" ? context.cwd : void 0;
1446
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1447
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1448
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
1449
+ let recordedBaseRef;
1259
1450
  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 });
1451
+ recordedBaseRef = (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(cwd, homeDir)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
1452
+ } catch {
1453
+ recordedBaseRef = void 0;
1454
+ }
1455
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1456
+ let pending = pendingReviews.get(key);
1457
+ if (pending === void 0) {
1458
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1459
+ pendingReviews.set(key, pending);
1460
+ }
1461
+ const result = await pending;
1462
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
1463
+ repository: false,
1464
+ files: []
1465
+ });
1466
+ const filePath = url.searchParams.get("path") ?? "";
1467
+ 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 });
1468
+ return Response.json(await branchDiff.fileDiff(result, filePath));
1469
+ };
1470
+ return {
1471
+ async fetch(request) {
1472
+ const url = new URL(request.url);
1473
+ try {
1474
+ const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1475
+ if (answered !== void 0) return answered;
1476
+ } catch (error) {
1477
+ context.onNotice(`git request failed: ${error.name}`);
1478
+ return failed(error);
1271
1479
  }
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 });
1480
+ const root = rootOf(url);
1481
+ if (root instanceof Response) return root;
1482
+ const callerContext = {
1483
+ cwd: root,
1484
+ sessionId: url.searchParams.get("sessionId") ?? ""
1485
+ };
1486
+ 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.");
1487
+ try {
1488
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1489
+ if (request.method === "POST" && url.pathname === "/worktrees") {
1490
+ const body = await request.json();
1491
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1492
+ const record = await operations.spawn(callerContext, {
1493
+ branch: body.branch,
1494
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1495
+ ...body.name === void 0 ? {} : { name: body.name }
1496
+ });
1497
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1498
+ return Response.json({ worktree: record }, { status: 201 });
1499
+ }
1500
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1501
+ if (request.method === "DELETE" && closing) {
1502
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1503
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1504
+ return Response.json({ worktree: record });
1505
+ }
1506
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
1507
+ } catch (error) {
1508
+ context.onNotice(`worktree request failed: ${error.name}`);
1509
+ return failed(error);
1277
1510
  }
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() {}
1511
+ },
1512
+ close() {}
1513
+ };
1514
+ }
1515
+ };
1516
+ }
1517
+ //#endregion
1518
+ //#region src/extensions/(backend)/api/git/route.server.ts
1519
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ context, host, signal }) => {
1520
+ let openDirectory;
1521
+ context.inject([_agimon_ai_po_core_platform.PO_SHELL_SERVICE], (child) => {
1522
+ const shell = (0, _agimon_ai_po_core_platform.requirePoShell)(child);
1523
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
1524
+ openDirectory = async (path) => {
1525
+ const result = await shell.exec([
1526
+ "/usr/bin/open",
1527
+ "-a",
1528
+ "Finder",
1529
+ path
1530
+ ], {
1531
+ env,
1532
+ inheritEnv: false
1533
+ }, (0, _agimon_ai_po_core_platform.withAbortSignal)(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
1534
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
1285
1535
  };
1286
- }
1536
+ return () => {
1537
+ openDirectory = void 0;
1538
+ };
1539
+ });
1540
+ return createGitApi(async (path) => {
1541
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1542
+ await openDirectory(path);
1543
+ });
1287
1544
  });
1288
1545
  //#endregion
1289
1546
  //#region src/services/gitFailure/index.ts
@@ -1420,7 +1677,7 @@ async function rebasing(root) {
1420
1677
  "--git-path",
1421
1678
  name
1422
1679
  ]);
1423
- if (gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath))) return true;
1680
+ if (gitPath !== void 0 && await node_fs_promises.default.access(node_path.default.resolve(root, gitPath)).then(() => true, () => false)) return true;
1424
1681
  }
1425
1682
  return false;
1426
1683
  }
@@ -1591,8 +1848,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1591
1848
  * - Apart from the worktrees channel. Worktrees are repository management;
1592
1849
  * this is the session's own code change.
1593
1850
  * - 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.
1851
+ * after every tool call that can write and every settled turn; a recount
1852
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
1853
+ * in flight plus one rerun.
1596
1854
  * - One sync command per session. A rebase and a push must never overlap.
1597
1855
  * - Auth is read fresh for each command from the session's workspace, and goes
1598
1856
  * only into that command's git child.
@@ -1601,6 +1859,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1601
1859
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1602
1860
  * stderr and drops it, because a remote URL in it can carry a token.
1603
1861
  */
1862
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
1863
+ const REFRESH_DELAY_MS = 1500;
1604
1864
  function payloadOf$1(state) {
1605
1865
  return {
1606
1866
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1652,10 +1912,12 @@ function createGitChangesChannel(options = {}) {
1652
1912
  const inFlight = /* @__PURE__ */ new Set();
1653
1913
  const rerun = /* @__PURE__ */ new Set();
1654
1914
  const busy = /* @__PURE__ */ new Set();
1915
+ const delayed = /* @__PURE__ */ new Map();
1916
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1655
1917
  /** The base the session's own worktree was created from, when it has one. */
1656
- const recordedBaseRef = (scope) => {
1918
+ const recordedBaseRef = async (scope) => {
1657
1919
  try {
1658
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
1920
+ return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, homeDir)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1659
1921
  } catch {
1660
1922
  return;
1661
1923
  }
@@ -1688,8 +1950,7 @@ function createGitChangesChannel(options = {}) {
1688
1950
  return;
1689
1951
  }
1690
1952
  inFlight.add(sessionId);
1691
- const base = recordedBaseRef(scope);
1692
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
1953
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1693
1954
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1694
1955
  }).catch((error) => {
1695
1956
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1698,12 +1959,22 @@ function createGitChangesChannel(options = {}) {
1698
1959
  if (rerun.delete(sessionId)) refresh(sessionId);
1699
1960
  });
1700
1961
  };
1701
- const run = (scope, command) => {
1962
+ /** Recounts once the session has been quiet for a moment. */
1963
+ const refreshSoon = (sessionId) => {
1964
+ clearTimeout(delayed.get(sessionId));
1965
+ const timer = setTimeout(() => {
1966
+ delayed.delete(sessionId);
1967
+ refresh(sessionId);
1968
+ }, refreshDelayMs);
1969
+ timer.unref?.();
1970
+ delayed.set(sessionId, timer);
1971
+ };
1972
+ const run = async (scope, command) => {
1702
1973
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1703
- const base = recordedBaseRef(scope);
1974
+ const base = await recordedBaseRef(scope);
1704
1975
  const context = {
1705
1976
  cwd: scope.cwd,
1706
- auth: auth.read(workspaceRoot),
1977
+ auth: await auth.read(workspaceRoot),
1707
1978
  ...base === void 0 ? {} : { recordedBaseRef: base }
1708
1979
  };
1709
1980
  if (command.action === "pull") return sync.pull(context);
@@ -1720,12 +1991,14 @@ function createGitChangesChannel(options = {}) {
1720
1991
  scopes.set(scope.sessionId, scope);
1721
1992
  refresh(scope.sessionId);
1722
1993
  const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1723
- if (require_worktreeOperations.isSessionChangedEvent(payload)) refresh(scope.sessionId);
1994
+ if (require_worktreeOperations.isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1724
1995
  });
1725
1996
  subscriptions.set(scope.sessionId, unsubscribe);
1726
1997
  },
1727
1998
  sessionRemoved(sessionId) {
1728
1999
  subscriptions.get(sessionId)?.();
2000
+ clearTimeout(delayed.get(sessionId));
2001
+ delayed.delete(sessionId);
1729
2002
  subscriptions.delete(sessionId);
1730
2003
  scopes.delete(sessionId);
1731
2004
  latest.delete(sessionId);
@@ -1734,6 +2007,8 @@ function createGitChangesChannel(options = {}) {
1734
2007
  },
1735
2008
  close() {
1736
2009
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2010
+ for (const timer of delayed.values()) clearTimeout(timer);
2011
+ delayed.clear();
1737
2012
  subscriptions.clear();
1738
2013
  scopes.clear();
1739
2014
  latest.clear();
@@ -1801,9 +2076,9 @@ function payloadOf(state) {
1801
2076
  };
1802
2077
  }
1803
2078
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1804
- function viewsFor(scope, deps) {
2079
+ async function viewsFor(scope, deps) {
1805
2080
  try {
1806
- return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2081
+ return (await require_worktreeOperations.createWorktreeRegistry(await require_worktreeOperations.registryFile(scope.cwd, deps.homeDir)).list()).flatMap((record) => {
1807
2082
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1808
2083
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1809
2084
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1828,11 +2103,15 @@ function sameList(left, right) {
1828
2103
  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
2104
  });
1830
2105
  }
1831
- function errorTargetFor(command) {
1832
- return command.action === "create" ? { action: "create" } : {
2106
+ function errorTargetFor(command, error) {
2107
+ if (command.action === "close") return {
1833
2108
  action: "close",
1834
2109
  id: command.id
1835
2110
  };
2111
+ return error instanceof require_worktreeOperations.PoGitExpectedError && error.code === "rift_missing" ? {
2112
+ action: "create",
2113
+ riftMissing: true
2114
+ } : { action: "create" };
1836
2115
  }
1837
2116
  /** A command the page sent, or undefined when the frame was not one. */
1838
2117
  function parseCommand(payload) {
@@ -1860,11 +2139,15 @@ function parseCommand(payload) {
1860
2139
  /**
1861
2140
  * What the reader is told when a command fails.
1862
2141
  *
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.
2142
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2143
+ * written for the agent's tool result. A dirty close is said in the person's
2144
+ * terms, because its message tells the agent to pass `force`. Anything else is
2145
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1865
2146
  */
1866
2147
  function failureText(error) {
1867
- return error instanceof require_worktreeOperations.PoGitExpectedError ? error.message : "The worktree operation failed.";
2148
+ if (!(error instanceof require_worktreeOperations.PoGitExpectedError)) return "The worktree operation failed.";
2149
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2150
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1868
2151
  }
1869
2152
  /** Starts one direct-event subscription per managed session. */
1870
2153
  function createWorktreesChannel(options = {}) {
@@ -1917,10 +2200,13 @@ function createWorktreesChannel(options = {}) {
1917
2200
  return generation;
1918
2201
  };
1919
2202
  /** Republishes a session, skipping a frame that would say nothing new. */
1920
- const publish = (scope, force) => {
2203
+ const publish = async (scope, force) => {
2204
+ const generation = generations.get(scope.sessionId);
2205
+ const worktreeViews = await viewsFor(scope, views);
2206
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1921
2207
  const previous = latest.get(scope.sessionId);
1922
2208
  const next = {
1923
- worktrees: viewsFor(scope, views),
2209
+ worktrees: worktreeViews,
1924
2210
  pending: previous?.pending,
1925
2211
  error: previous?.error,
1926
2212
  errorTarget: previous?.errorTarget
@@ -1932,7 +2218,7 @@ function createWorktreesChannel(options = {}) {
1932
2218
  const mark = (scope, pending, error, errorTarget) => {
1933
2219
  const previous = latest.get(scope.sessionId);
1934
2220
  latest.set(scope.sessionId, {
1935
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2221
+ worktrees: previous?.worktrees ?? [],
1936
2222
  pending,
1937
2223
  error,
1938
2224
  errorTarget
@@ -1972,15 +2258,15 @@ function createWorktreesChannel(options = {}) {
1972
2258
  sessionAdded(scope) {
1973
2259
  newGeneration(scope.sessionId);
1974
2260
  publish(scope, false);
1975
- const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
2261
+ const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
1976
2262
  if (!require_worktreeOperations.isWorktreeLifecycleEvent(payload)) return;
1977
2263
  let sameRepository = false;
1978
2264
  try {
1979
- sameRepository = require_worktreeOperations.registryFile(scope.cwd, options.homeDir) === require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir);
2265
+ sameRepository = await require_worktreeOperations.registryFile(scope.cwd, options.homeDir) === await require_worktreeOperations.registryFile(payload.repositoryRoot, options.homeDir);
1980
2266
  } catch {
1981
2267
  sameRepository = false;
1982
2268
  }
1983
- if (sameRepository) publish(scope, false);
2269
+ if (sameRepository) await publish(scope, false);
1984
2270
  });
1985
2271
  subscriptions.set(scope.sessionId, unsubscribe);
1986
2272
  },
@@ -2013,7 +2299,7 @@ function createWorktreesChannel(options = {}) {
2013
2299
  }).catch((error) => {
2014
2300
  if (generations.get(scope.sessionId) !== generation) return;
2015
2301
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2016
- mark(scope, void 0, failureText(error), errorTargetFor(command));
2302
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2017
2303
  }).finally(() => {
2018
2304
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2019
2305
  });
@@ -2035,20 +2321,8 @@ var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHo
2035
2321
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2036
2322
  var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
2037
2323
  //#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
2324
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2051
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
2325
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2052
2326
  //#endregion
2053
2327
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2054
2328
  var poUseGit_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)(poUseGit_server_default$1);
@@ -2068,12 +2342,12 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2068
2342
  name: "@agimon-ai/po-git",
2069
2343
  providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
2070
2344
  injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
2071
- global: (context) => ({
2345
+ host: (context) => ({
2072
2346
  get api() {
2073
2347
  return [at(route_server_default, context)];
2074
2348
  },
2075
2349
  get channels() {
2076
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2350
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2077
2351
  }
2078
2352
  }),
2079
2353
  workspace: (context) => ({
@@ -2081,7 +2355,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2081
2355
  return [at(route_server_default, context)];
2082
2356
  },
2083
2357
  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())]);
2358
+ 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
2359
  }
2086
2360
  }),
2087
2361
  session: async (context) => {
@@ -2096,17 +2370,13 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2096
2370
  return [at(route_server_default, context)];
2097
2371
  },
2098
2372
  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())]);
2373
+ 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
2374
  },
2101
2375
  get hooks() {
2102
2376
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2103
2377
  },
2104
2378
  get resources() {
2105
- return [
2106
- at(poGit_server_default, contextSession),
2107
- at(poGitReadme_server_default, contextSession),
2108
- at(poUseGit_server_default, contextSession)
2109
- ];
2379
+ return [at(poUseGit_server_default, contextSession)];
2110
2380
  },
2111
2381
  get tools() {
2112
2382
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];