@agimon-ai/po-git 0.0.0-alpha.17 → 0.0.0-alpha.171

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.
@@ -1,11 +1,15 @@
1
- import { _ as NETWORK_TIMEOUT_MS, a as GIT_WORKTREE_LIFECYCLE_EVENT, b as createWorktreeGit, c as isWorktreeLifecycleEvent, d as registryFile, f as readJson, g as invalidRequest, h as PoGitExpectedError, i as GIT_SESSION_CHANGED_EVENT, l as credentialsFile, m as HubUnavailableError, n as createWorktreeRegistry, o as createWorktreeMessageInbox, p as writeJsonAtomic, r as validRefName, s as isSessionChangedEvent, t as createWorktreeOperations, u as poGitRoot, v as READ_TIMEOUT_MS, x as runGit, y as REBASE_TIMEOUT_MS } from "../worktreeOperations-Cd8Q12L4.mjs";
2
- import fs from "node:fs";
3
- import os from "node:os";
1
+ import { C as READ_TIMEOUT_MS, E as runGit, S as NETWORK_TIMEOUT_MS, T as createWorktreeGit, a as GIT_WORKTREE_LIFECYCLE_EVENT, c as isWorktreeLifecycleEvent, d as registryFile, f as readJson, g as invalidRequest, h as PoGitExpectedError, i as GIT_SESSION_CHANGED_EVENT, l as credentialsFile, m as HubUnavailableError, n as createWorktreeRegistry, o as createWorktreeMessageInbox, p as writeJsonAtomic, r as validRefName, s as isSessionChangedEvent, t as createWorktreeOperations, u as poGitRoot, w as REBASE_TIMEOUT_MS } from "../worktreeOperations-DA_dbDv8.mjs";
2
+ import fs from "node:fs/promises";
4
3
  import path from "node:path";
5
- import { composeServerProviderOverrides, defineServerPlugin, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
4
+ import os from "node:os";
5
+ import { composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
6
6
  import { composeRootHooks, composeRootInjects, defineChannel, defineHook, defineResource, defineRoot, defineRoute, defineServerTool } from "@agimon-ai/po-core/extensionFile";
7
+ import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
7
8
  import { readPoSessionDelivery } from "@agimon-ai/po-session";
8
9
  import { Type } from "typebox";
10
+ import { BACKGROUND_CONTEXT, PO_SHELL_SERVICE, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
11
+ import { poApiCallerFrom } from "@agimon-ai/po-core/packageApi";
12
+ import { parseLaunchSelection } from "@agimon-ai/po-core/hubChannel";
9
13
  //#region src/schemas/runWorktreeTool.ts
10
14
  /**
11
15
  * The tool's action vocabulary.
@@ -247,7 +251,8 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
247
251
  content: text(describe(record, context.sessionId), `Session: ${record.sessionId}`, dirtyFiles.length === 0 ? "Clean." : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(", ")}`),
248
252
  details: {
249
253
  action: params.action,
250
- records: [record]
254
+ records: [record],
255
+ dirtyFiles
251
256
  }
252
257
  };
253
258
  }
@@ -271,7 +276,10 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
271
276
  const waiting = await operations.messages(context, params.id);
272
277
  return {
273
278
  content: waiting.length === 0 ? text("No messages.") : text(`${String(waiting.length)} message(s):`, ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`)),
274
- details: { action: params.action }
279
+ details: {
280
+ action: params.action,
281
+ messages: waiting
282
+ }
275
283
  };
276
284
  }
277
285
  case WORKTREE_ACTIONS.prune: {
@@ -286,12 +294,172 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
286
294
  `Untracked directories, left alone: ${plan.untracked.length === 0 ? "none" : plan.untracked.join(", ")}`,
287
295
  ...plan.keptBranches.length === 0 ? [] : [`Branches kept, they hold commits: ${plan.keptBranches.join(", ")}`]
288
296
  ]),
289
- details: { action: params.action }
297
+ details: {
298
+ action: params.action,
299
+ plan
300
+ }
290
301
  };
291
302
  }
292
303
  }
293
304
  }
294
305
  //#endregion
306
+ //#region src/services/worktreeNamespace/index.ts
307
+ const DECLARATIONS = `type WorktreeStatus = 'spawning' | 'running' | 'closing' | 'orphaned';
308
+
309
+ interface Worktree {
310
+ id: string;
311
+ branch: string;
312
+ baseRef: string;
313
+ /** Absolute path of the checkout, under ~/.po/git/worktrees. */
314
+ path: string;
315
+ repositoryRoot: string;
316
+ /** The session running inside the worktree. */
317
+ sessionId: string;
318
+ parentSessionId?: string;
319
+ status: WorktreeStatus;
320
+ createdAt: string;
321
+ /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
322
+ relationship: 'parent' | 'child' | 'other';
323
+ }
324
+
325
+ interface WorktreeMessage {
326
+ worktreeId: string;
327
+ fromSessionId: string;
328
+ from: 'parent' | 'child';
329
+ text: string;
330
+ sentAt: string;
331
+ }
332
+
333
+ interface PrunePlan {
334
+ remove: Worktree[];
335
+ forget: Worktree[];
336
+ /** Kept because they hold uncommitted work. */
337
+ keptDirty: Worktree[];
338
+ untracked: string[];
339
+ /** Branches kept because they hold commits. */
340
+ keptBranches: string[];
341
+ }
342
+
343
+ declare const worktrees: {
344
+ /** Every worktree for this repository. */
345
+ list(): Promise<Worktree[]>;
346
+ /** One worktree and its uncommitted files. */
347
+ status(id: string): Promise<{ worktree: Worktree; dirtyFiles: string[] }>;
348
+ /**
349
+ * Create a worktree on a new branch and start a Po session in it, nested under this one. baseRef defaults to
350
+ * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
351
+ * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
352
+ */
353
+ spawn(request: { branch: string; baseRef?: string; name?: string; task?: string }): Promise<Worktree>;
354
+ /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
355
+ close(id: string, options?: { force?: boolean }): Promise<Worktree>;
356
+ /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
357
+ merge(id: string, options?: { message?: string }): Promise<Worktree>;
358
+ /** Remove orphaned worktrees. With dryRun, only return the plan. */
359
+ prune(options?: { dryRun?: boolean }): Promise<PrunePlan>;
360
+ /**
361
+ * Message the other side of a worktree. Use the record with relationship 'child' to report to your parent,
362
+ * and 'parent' to reach your own children. 'other' records are not communication edges.
363
+ */
364
+ send(id: string, message: string): Promise<void>;
365
+ /** Messages waiting for you from a worktree. */
366
+ messages(id: string): Promise<WorktreeMessage[]>;
367
+ };`;
368
+ const json = (value) => JSON.parse(JSON.stringify(value));
369
+ /** Git worktrees for code mode: the actions of `run_worktree` as methods, returning records instead of text. */
370
+ function createWorktreeNamespace(options) {
371
+ return {
372
+ name: "worktrees",
373
+ summary: "Git worktrees, each with its own Po session nested under this one: worktrees.list, status, spawn, close, merge, prune, send and messages.",
374
+ declarations: DECLARATIONS,
375
+ bind(run) {
376
+ if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
377
+ let disposed = false;
378
+ run.onDispose(() => {
379
+ disposed = true;
380
+ });
381
+ const view = (record) => ({
382
+ ...record,
383
+ relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
384
+ });
385
+ /** One `run_worktree` action through the tool's own code, so the tool and the namespace cannot drift. */
386
+ const act = async (name, action, input) => {
387
+ run.signal.throwIfAborted();
388
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
389
+ options.assertAvailable();
390
+ const params = validateParams({
391
+ action,
392
+ ...typeof input === "object" && input !== null ? input : {}
393
+ });
394
+ const context = {
395
+ cwd: options.execution.cwd,
396
+ sessionId: options.execution.sessionId
397
+ };
398
+ const started = Date.now();
399
+ try {
400
+ const result = await executeRunWorktreeTool(params, options.operations, context, { signal: run.signal });
401
+ options.assertAvailable();
402
+ run.record?.({
403
+ name: `worktrees.${name}`,
404
+ tool: RUN_WORKTREE_TOOL_NAME,
405
+ args: params,
406
+ ok: true,
407
+ ms: Date.now() - started,
408
+ result
409
+ });
410
+ return result;
411
+ } catch (error) {
412
+ run.record?.({
413
+ name: `worktrees.${name}`,
414
+ tool: RUN_WORKTREE_TOOL_NAME,
415
+ args: params,
416
+ ok: false,
417
+ ms: Date.now() - started,
418
+ error: error instanceof Error ? error.message : String(error)
419
+ });
420
+ throw error;
421
+ }
422
+ };
423
+ const record = (result) => view(result.details.records[0]);
424
+ const members = Object.create(null);
425
+ members.list = async () => json((await act("list", "list", {})).details.records.map(view));
426
+ members.status = async (id) => {
427
+ const { details } = await act("status", "status", { id });
428
+ return json({
429
+ worktree: view(details.records[0]),
430
+ dirtyFiles: details.dirtyFiles ?? []
431
+ });
432
+ };
433
+ members.spawn = async (request) => json(record(await act("spawn", "spawn_worktree", request)));
434
+ members.close = async (id, settings) => json(record(await act("close", "close_worktree", {
435
+ ...settings,
436
+ id
437
+ })));
438
+ members.merge = async (id, settings) => json(record(await act("merge", "merge", {
439
+ ...settings,
440
+ id
441
+ })));
442
+ members.prune = async (settings) => {
443
+ const { plan } = (await act("prune", "prune", settings)).details;
444
+ return json({
445
+ ...plan,
446
+ remove: plan.remove.map(view),
447
+ forget: plan.forget.map(view),
448
+ keptDirty: plan.keptDirty.map(view)
449
+ });
450
+ };
451
+ members.send = async (id, message) => {
452
+ await act("send", "send", {
453
+ id,
454
+ message
455
+ });
456
+ };
457
+ members.messages = async (id) => json((await act("messages", "messages", { id })).details.messages);
458
+ return members;
459
+ }
460
+ };
461
+ }
462
+ //#endregion
295
463
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
296
464
  function progressResult(action, label) {
297
465
  return {
@@ -302,7 +470,16 @@ function progressResult(action, label) {
302
470
  details: { action }
303
471
  };
304
472
  }
305
- function createGitSession({ context, host: serverHost }) {
473
+ /** Tools that only read, so the checkout cannot have moved under them. */
474
+ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
475
+ "read",
476
+ "grep",
477
+ "find",
478
+ "ls",
479
+ "discover",
480
+ "load_skill"
481
+ ]);
482
+ function createGitSession({ context, host: serverHost, agent, signal }) {
306
483
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
307
484
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
308
485
  const sessionId = serverHost.context.sessionId;
@@ -315,20 +492,12 @@ function createGitSession({ context, host: serverHost }) {
315
492
  sessionDelivery: () => readPoSessionDelivery(context)
316
493
  });
317
494
  const resources = [{
318
- when: {
319
- state: { "minor-mode": "help" },
320
- attribution: {
321
- kind: "minor",
322
- mode: "help"
323
- }
324
- },
325
- name: "po-git",
326
- kind: "context",
327
- read: () => readPackageResource(import.meta.url, "llms.txt")
328
- }, {
329
- name: "po-use-git",
495
+ name: "codemode-how-to-git",
496
+ 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.",
330
497
  kind: "skill",
331
- read: () => readPackageResource(import.meta.url, "src/prompts/po-use-git/SKILL.md")
498
+ pinned: true,
499
+ path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-git/SKILL.md"),
500
+ read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-git/SKILL.md")
332
501
  }];
333
502
  const tool = {
334
503
  name: RUN_WORKTREE_TOOL_NAME,
@@ -348,17 +517,37 @@ function createGitSession({ context, host: serverHost }) {
348
517
  const changed = (_event, execution) => {
349
518
  directEvents.publish(GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
350
519
  };
520
+ const hooks = [{
521
+ event: "tool_execution_end",
522
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
523
+ }, {
524
+ event: "agent_settled",
525
+ handle: changed
526
+ }];
527
+ if (agent) {
528
+ const namespace = createWorktreeNamespace({
529
+ operations,
530
+ execution: agent.context,
531
+ assertAvailable: () => {
532
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
533
+ }
534
+ });
535
+ context.inject([PO_CODEMODE_SERVICE], (scoped) => {
536
+ const codemode = readPoCodemode(scoped);
537
+ if (!codemode) return void 0;
538
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
539
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
540
+ return () => {
541
+ restriction.dispose();
542
+ registration.dispose();
543
+ };
544
+ });
545
+ }
351
546
  return {
352
547
  value: {
353
548
  resources,
354
549
  tool,
355
- hooks: [{
356
- event: "tool_execution_end",
357
- handle: changed
358
- }, {
359
- event: "agent_settled",
360
- handle: changed
361
- }]
550
+ hooks
362
551
  },
363
552
  onDispose: () => messageInbox.close()
364
553
  };
@@ -469,11 +658,11 @@ const NAME_STATUS = {
469
658
  T: "modified"
470
659
  };
471
660
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
472
- function untrackedLines(root, relPath) {
661
+ async function untrackedLines(root, relPath) {
473
662
  const absolute = path.join(root, relPath);
474
663
  let stat;
475
664
  try {
476
- stat = fs.lstatSync(absolute);
665
+ stat = await fs.lstat(absolute);
477
666
  } catch {
478
667
  return;
479
668
  }
@@ -482,7 +671,7 @@ function untrackedLines(root, relPath) {
482
671
  binary: false
483
672
  };
484
673
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
485
- const content = fs.readFileSync(absolute);
674
+ const content = await fs.readFile(absolute);
486
675
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
487
676
  lines: 0,
488
677
  binary: true
@@ -605,8 +794,8 @@ function createBranchDiff() {
605
794
  "--exclude-standard",
606
795
  "-z"
607
796
  ]));
608
- untracked.forEach((relPath, index) => {
609
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
797
+ for (const [index, relPath] of untracked.entries()) {
798
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
610
799
  entries.push({
611
800
  path: relPath,
612
801
  status: "untracked",
@@ -614,18 +803,20 @@ function createBranchDiff() {
614
803
  removed: 0,
615
804
  ...counted?.binary ? { binary: true } : {}
616
805
  });
617
- });
806
+ }
618
807
  entries.sort((left, right) => left.path.localeCompare(right.path));
619
808
  const conflicts = [...unmerged];
620
- const rebasing = [await readLine$1(root, [
809
+ const rebaseMerge = await readLine$1(root, [
621
810
  "rev-parse",
622
811
  "--git-path",
623
812
  "rebase-merge"
624
- ]), await readLine$1(root, [
813
+ ]);
814
+ const rebaseApply = await readLine$1(root, [
625
815
  "rev-parse",
626
816
  "--git-path",
627
817
  "rebase-apply"
628
- ])].some((gitPath) => gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath)));
818
+ ]);
819
+ const rebasing = (await Promise.all([rebaseMerge, rebaseApply].map(async (gitPath) => gitPath === void 0 ? false : fs.access(path.resolve(root, gitPath)).then(() => true, () => false)))).some(Boolean);
629
820
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
630
821
  let upstream;
631
822
  if (upstreamRef !== void 0) {
@@ -670,7 +861,7 @@ function createBranchDiff() {
670
861
  if (entry === void 0) throw new Error("That path is not in this review.");
671
862
  if (entry.status === "untracked") {
672
863
  const absolute = path.join(review.root, entry.path);
673
- const stat = fs.lstatSync(absolute);
864
+ const stat = await fs.lstat(absolute);
674
865
  if (stat.isSymbolicLink()) return {
675
866
  path: entry.path,
676
867
  hunks: [{
@@ -678,7 +869,7 @@ function createBranchDiff() {
678
869
  rows: [{
679
870
  marker: "+",
680
871
  line: 1,
681
- content: fs.readlinkSync(absolute)
872
+ content: await fs.readlink(absolute)
682
873
  }]
683
874
  }]
684
875
  };
@@ -687,7 +878,7 @@ function createBranchDiff() {
687
878
  hunks: [],
688
879
  tooLarge: true
689
880
  };
690
- const content = fs.readFileSync(absolute);
881
+ const content = await fs.readFile(absolute);
691
882
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
692
883
  path: entry.path,
693
884
  hunks: [],
@@ -804,9 +995,9 @@ function isRecord(value) {
804
995
  return typeof value === "object" && value !== null && !Array.isArray(value);
805
996
  }
806
997
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
807
- function workspaceKey(workspaceRoot) {
998
+ async function workspaceKey(workspaceRoot) {
808
999
  try {
809
- return fs.realpathSync(workspaceRoot);
1000
+ return await fs.realpath(workspaceRoot);
810
1001
  } catch {
811
1002
  return path.resolve(workspaceRoot);
812
1003
  }
@@ -855,7 +1046,7 @@ function publicView(config) {
855
1046
  * the saved one, and only for the same host: a token never follows a host it
856
1047
  * was not entered for.
857
1048
  */
858
- function parseGitAuthSave(request, current, homeDir) {
1049
+ async function parseGitAuthSave(request, current, homeDir) {
859
1050
  if (!isRecord(request)) throw invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
860
1051
  if (request.method === "none") return { method: "none" };
861
1052
  if (request.method === "ssh") {
@@ -865,7 +1056,7 @@ function parseGitAuthSave(request, current, homeDir) {
865
1056
  if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
866
1057
  let isFile = false;
867
1058
  try {
868
- isFile = fs.statSync(expandHome(keyPath, homeDir)).isFile();
1059
+ isFile = (await fs.stat(expandHome(keyPath, homeDir))).isFile();
869
1060
  } catch {
870
1061
  isFile = false;
871
1062
  }
@@ -900,16 +1091,16 @@ function parseGitAuthSave(request, current, homeDir) {
900
1091
  throw invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
901
1092
  }
902
1093
  /** Tightens a file or folder something left readable by group or others. */
903
- function tighten(target, mode) {
1094
+ async function tighten(target, mode) {
904
1095
  try {
905
- if ((fs.statSync(target).mode & LOOSE_BITS) !== 0) fs.chmodSync(target, mode);
1096
+ if (((await fs.stat(target)).mode & LOOSE_BITS) !== 0) await fs.chmod(target, mode);
906
1097
  } catch {}
907
1098
  }
908
1099
  function createGitAuthStore(homeDir = os.homedir()) {
909
1100
  const file = credentialsFile(homeDir);
910
- const readFile = () => {
911
- tighten(file, OWNER_ONLY_FILE);
912
- const raw = readJson(file);
1101
+ const readFile = async () => {
1102
+ await tighten(file, OWNER_ONLY_FILE);
1103
+ const raw = await readJson(file);
913
1104
  const workspaces = {};
914
1105
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
915
1106
  const config = parseConfig(value);
@@ -920,28 +1111,28 @@ function createGitAuthStore(homeDir = os.homedir()) {
920
1111
  workspaces
921
1112
  };
922
1113
  };
923
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1114
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
924
1115
  return {
925
1116
  read,
926
- view: (workspaceRoot) => publicView(read(workspaceRoot)),
927
- save(workspaceRoot, request) {
928
- const key = workspaceKey(workspaceRoot);
929
- const current = readFile();
930
- const next = parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1117
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1118
+ async save(workspaceRoot, request) {
1119
+ const key = await workspaceKey(workspaceRoot);
1120
+ const current = await readFile();
1121
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
931
1122
  const root = poGitRoot(homeDir);
932
- fs.mkdirSync(root, {
1123
+ await fs.mkdir(root, {
933
1124
  recursive: true,
934
1125
  mode: OWNER_ONLY_DIRECTORY
935
1126
  });
936
- fs.chmodSync(root, OWNER_ONLY_DIRECTORY);
1127
+ await fs.chmod(root, OWNER_ONLY_DIRECTORY);
937
1128
  const workspaces = { ...current.workspaces };
938
1129
  if (next.method === "none") delete workspaces[key];
939
1130
  else workspaces[key] = next;
940
- writeJsonAtomic(file, {
1131
+ await writeJsonAtomic(file, {
941
1132
  version: 1,
942
1133
  workspaces
943
1134
  });
944
- fs.chmodSync(file, OWNER_ONLY_FILE);
1135
+ await fs.chmod(file, OWNER_ONLY_FILE);
945
1136
  return publicView(next);
946
1137
  }
947
1138
  };
@@ -1060,7 +1251,13 @@ function newSessionRequest(body) {
1060
1251
  if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
1061
1252
  const name = optionalText(record.name);
1062
1253
  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.` };
1063
- const named = name === void 0 ? {} : { name };
1254
+ const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
1255
+ if ("error" in chosen) return chosen;
1256
+ const profile = chosen.selection?.profile;
1257
+ const named = {
1258
+ ...name === void 0 ? {} : { name },
1259
+ ...profile === void 0 ? {} : { selection: { profile } }
1260
+ };
1064
1261
  if (record.mode === "existing-branch") {
1065
1262
  const remote = optionalText(record.remote);
1066
1263
  if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
@@ -1106,177 +1303,237 @@ function failed(error) {
1106
1303
  }, { status: error.retryable ? 503 : 409 });
1107
1304
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1108
1305
  }
1109
- //#endregion
1110
- //#region src/extensions/(backend)/api/git/route.server.ts
1111
- var route_server_default = defineRoute({
1112
- basePath: "git",
1113
- start(context) {
1114
- if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1115
- const directEvents = context.directEvents;
1116
- const publishLifecycle = (sessionId, repositoryRoot) => {
1117
- directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1118
- version: 1,
1119
- repositoryRoot
1306
+ function createGitApi(openDirectory) {
1307
+ return {
1308
+ basePath: "git",
1309
+ start(context) {
1310
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
1311
+ const directEvents = context.directEvents;
1312
+ const publishLifecycle = (sessionId, repositoryRoot) => {
1313
+ directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
1314
+ version: 1,
1315
+ repositoryRoot
1316
+ });
1317
+ };
1318
+ const git = createWorktreeGit();
1319
+ const operations = createWorktreeOperations({
1320
+ git,
1321
+ sessionService: context.sessionService,
1322
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory }
1120
1323
  });
1121
- };
1122
- const git = createWorktreeGit();
1123
- const operations = createWorktreeOperations({
1124
- git,
1125
- sessionService: context.sessionService,
1126
- ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory }
1127
- });
1128
- /**
1129
- * The new-session dialog's routes: the workspace's branches, and a top-level
1130
- * worktree session on one. Workspace-mounted only, and always rooted at the
1131
- * mount's own workspace, so a request can never name another directory.
1132
- */
1133
- const newSession = async (request, url) => {
1134
- const isBranches = request.method === "GET" && url.pathname === "/branches";
1135
- const isCreate = request.method === "POST" && url.pathname === "/sessions";
1136
- if (!isBranches && !isCreate) return void 0;
1137
- const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1138
- if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1139
- if (isBranches) {
1140
- const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1141
- const branches = repositoryRoot === void 0 ? {
1142
- repository: false,
1143
- local: [],
1144
- remote: []
1145
- } : {
1146
- repository: true,
1147
- ...await git.listBranches(repositoryRoot)
1324
+ /**
1325
+ * The new-session dialog's routes: the workspace's branches, and a top-level
1326
+ * worktree session on one. Workspace-mounted only, and always rooted at the
1327
+ * mount's own workspace, so a request can never name another directory.
1328
+ */
1329
+ const newSession = async (request, url) => {
1330
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
1331
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
1332
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
1333
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
1334
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
1335
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
1336
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1337
+ if (isBranches) {
1338
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1339
+ const branches = repositoryRoot === void 0 ? {
1340
+ repository: false,
1341
+ local: [],
1342
+ remote: []
1343
+ } : {
1344
+ repository: true,
1345
+ ...await git.listBranches(repositoryRoot)
1346
+ };
1347
+ return Response.json(branches);
1348
+ }
1349
+ if (isDelete || isOpen) {
1350
+ if (isOpen && poApiCallerFrom(request.headers)?.locality !== "local") return Response.json({ error: "Opening Finder is only available on the host." }, { status: 403 });
1351
+ const body = await request.json().catch(() => void 0);
1352
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
1353
+ if (typeof branch !== "string" || !validRefName(branch)) return badRequest("A valid branch name is required.");
1354
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
1355
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
1356
+ const branches = await git.listBranches(repositoryRoot);
1357
+ const local = branches.local.find((item) => item.name === branch);
1358
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
1359
+ if (isOpen) {
1360
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
1361
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
1362
+ try {
1363
+ await openDirectory(local.checkedOutAt);
1364
+ return Response.json({ opened: true });
1365
+ } catch {
1366
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
1367
+ }
1368
+ }
1369
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
1370
+ if (!await git.deleteBranch({
1371
+ repositoryRoot,
1372
+ branch
1373
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
1374
+ return Response.json({ deleted: true });
1375
+ }
1376
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
1377
+ if ("error" in parsed) return badRequest(parsed.error);
1378
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
1379
+ branch: parsed.branch,
1380
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1381
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1382
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1383
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
1384
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1385
+ });
1386
+ publishLifecycle(record.sessionId, record.repositoryRoot);
1387
+ const created = {
1388
+ sessionId: record.sessionId,
1389
+ worktreeId: record.id
1148
1390
  };
1149
- return Response.json(branches);
1150
- }
1151
- const parsed = newSessionRequest(await request.json().catch(() => void 0));
1152
- if ("error" in parsed) return badRequest(parsed.error);
1153
- const record = await operations.spawn({ cwd: workspaceRoot }, {
1154
- branch: parsed.branch,
1155
- checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1156
- ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1157
- ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1158
- ...parsed.name === void 0 ? {} : { name: parsed.name }
1159
- });
1160
- publishLifecycle(record.sessionId, record.repositoryRoot);
1161
- const created = {
1162
- sessionId: record.sessionId,
1163
- worktreeId: record.id
1391
+ return Response.json(created, { status: 201 });
1164
1392
  };
1165
- return Response.json(created, { status: 201 });
1166
- };
1167
- /** The admitted root for a request, or a response explaining why not. */
1168
- const rootOf = (url) => {
1169
- const repositoryId = url.searchParams.get("repositoryId");
1170
- if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1171
- const root = context.resolveRepository?.(repositoryId);
1172
- if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1173
- return root;
1174
- };
1175
- const homeDir = context.homeDirectory ?? os.homedir();
1176
- const gitAuth = createGitAuthStore(homeDir);
1177
- const branchDiff = createBranchDiff();
1178
- const pendingReviews = /* @__PURE__ */ new Map();
1179
- /**
1180
- * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1181
- * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1182
- * The view never carries the token.
1183
- */
1184
- const auth = async (request, url) => {
1185
- if (url.pathname !== "/auth") return void 0;
1186
- if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1187
- if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1188
- const root = rootOf(url);
1189
- if (root instanceof Response) return root;
1190
- if (request.method === "GET") return Response.json(gitAuth.view(root));
1191
- try {
1192
- return Response.json(gitAuth.save(root, await request.json().catch(() => void 0)));
1193
- } catch (error) {
1194
- if (error instanceof PoGitExpectedError && error.code === "invalid_request") {
1195
- const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1196
- return Response.json({
1197
- error: text,
1198
- code: error.code
1199
- }, { status: 400 });
1200
- }
1201
- throw error;
1202
- }
1203
- };
1204
- /**
1205
- * The session's change against its base. Session mounts only, rooted at the
1206
- * session's own checkout; a file is served only when it is in the change set
1207
- * computed for the request. Overlapping requests share an in-flight snapshot.
1208
- */
1209
- const review = async (request, url) => {
1210
- if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1211
- const cwd = context.scope === "session" ? context.cwd : void 0;
1212
- if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1213
- if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1214
- let recordedBaseRef;
1215
- try {
1216
- recordedBaseRef = createWorktreeRegistry(registryFile(cwd, homeDir)).list().find((record) => record.sessionId === context.sessionId)?.baseRef;
1217
- } catch {
1218
- recordedBaseRef = void 0;
1219
- }
1220
- const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1221
- let pending = pendingReviews.get(key);
1222
- if (pending === void 0) {
1223
- pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1224
- pendingReviews.set(key, pending);
1225
- }
1226
- const result = await pending;
1227
- if (url.pathname === "/review") return Response.json(result?.summary ?? {
1228
- repository: false,
1229
- files: []
1230
- });
1231
- const filePath = url.searchParams.get("path") ?? "";
1232
- 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 });
1233
- return Response.json(await branchDiff.fileDiff(result, filePath));
1234
- };
1235
- return {
1236
- async fetch(request) {
1237
- const url = new URL(request.url);
1393
+ /** The admitted root for a request, or a response explaining why not. */
1394
+ const rootOf = (url) => {
1395
+ const repositoryId = url.searchParams.get("repositoryId");
1396
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
1397
+ const root = context.resolveRepository?.(repositoryId);
1398
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
1399
+ return root;
1400
+ };
1401
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
1402
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir);
1403
+ const branchDiff = createBranchDiff();
1404
+ const pendingReviews = /* @__PURE__ */ new Map();
1405
+ /**
1406
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
1407
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
1408
+ * The view never carries the token.
1409
+ */
1410
+ const auth = async (request, url) => {
1411
+ if (url.pathname !== "/auth") return void 0;
1412
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
1413
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
1414
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
1415
+ const root = rootOf(url);
1416
+ if (root instanceof Response) return root;
1417
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
1238
1418
  try {
1239
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1240
- if (answered !== void 0) return answered;
1419
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
1241
1420
  } catch (error) {
1242
- context.onNotice(`git request failed: ${error.name}`);
1243
- return failed(error);
1421
+ if (error instanceof PoGitExpectedError && error.code === "invalid_request") {
1422
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1423
+ return Response.json({
1424
+ error: text,
1425
+ code: error.code
1426
+ }, { status: 400 });
1427
+ }
1428
+ throw error;
1244
1429
  }
1245
- const root = rootOf(url);
1246
- if (root instanceof Response) return root;
1247
- const callerContext = {
1248
- cwd: root,
1249
- sessionId: url.searchParams.get("sessionId") ?? ""
1250
- };
1251
- 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.");
1430
+ };
1431
+ /**
1432
+ * The session's change against its base. Session mounts only, rooted at the
1433
+ * session's own checkout; a file is served only when it is in the change set
1434
+ * computed for the request. Overlapping requests share an in-flight snapshot.
1435
+ */
1436
+ const review = async (request, url) => {
1437
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
1438
+ const cwd = context.scope === "session" ? context.cwd : void 0;
1439
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
1440
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
1441
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
1442
+ let recordedBaseRef;
1252
1443
  try {
1253
- if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1254
- if (request.method === "POST" && url.pathname === "/worktrees") {
1255
- const body = await request.json();
1256
- if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1257
- const record = await operations.spawn(callerContext, {
1258
- branch: body.branch,
1259
- ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1260
- ...body.name === void 0 ? {} : { name: body.name }
1261
- });
1262
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1263
- return Response.json({ worktree: record }, { status: 201 });
1444
+ recordedBaseRef = (await createWorktreeRegistry(await registryFile(cwd, homeDir)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
1445
+ } catch {
1446
+ recordedBaseRef = void 0;
1447
+ }
1448
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
1449
+ let pending = pendingReviews.get(key);
1450
+ if (pending === void 0) {
1451
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
1452
+ pendingReviews.set(key, pending);
1453
+ }
1454
+ const result = await pending;
1455
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
1456
+ repository: false,
1457
+ files: []
1458
+ });
1459
+ const filePath = url.searchParams.get("path") ?? "";
1460
+ 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 });
1461
+ return Response.json(await branchDiff.fileDiff(result, filePath));
1462
+ };
1463
+ return {
1464
+ async fetch(request) {
1465
+ const url = new URL(request.url);
1466
+ try {
1467
+ const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1468
+ if (answered !== void 0) return answered;
1469
+ } catch (error) {
1470
+ context.onNotice(`git request failed: ${error.name}`);
1471
+ return failed(error);
1264
1472
  }
1265
- const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1266
- if (request.method === "DELETE" && closing) {
1267
- const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1268
- publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1269
- return Response.json({ worktree: record });
1473
+ const root = rootOf(url);
1474
+ if (root instanceof Response) return root;
1475
+ const callerContext = {
1476
+ cwd: root,
1477
+ sessionId: url.searchParams.get("sessionId") ?? ""
1478
+ };
1479
+ 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.");
1480
+ try {
1481
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
1482
+ if (request.method === "POST" && url.pathname === "/worktrees") {
1483
+ const body = await request.json();
1484
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1485
+ const record = await operations.spawn(callerContext, {
1486
+ branch: body.branch,
1487
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1488
+ ...body.name === void 0 ? {} : { name: body.name }
1489
+ });
1490
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1491
+ return Response.json({ worktree: record }, { status: 201 });
1492
+ }
1493
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
1494
+ if (request.method === "DELETE" && closing) {
1495
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
1496
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
1497
+ return Response.json({ worktree: record });
1498
+ }
1499
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
1500
+ } catch (error) {
1501
+ context.onNotice(`worktree request failed: ${error.name}`);
1502
+ return failed(error);
1270
1503
  }
1271
- return Response.json({ error: "No such worktree route." }, { status: 404 });
1272
- } catch (error) {
1273
- context.onNotice(`worktree request failed: ${error.name}`);
1274
- return failed(error);
1275
- }
1276
- },
1277
- close() {}
1504
+ },
1505
+ close() {}
1506
+ };
1507
+ }
1508
+ };
1509
+ }
1510
+ //#endregion
1511
+ //#region src/extensions/(backend)/api/git/route.server.ts
1512
+ var route_server_default = defineRoute(({ context, host, signal }) => {
1513
+ let openDirectory;
1514
+ context.inject([PO_SHELL_SERVICE], (child) => {
1515
+ const shell = requirePoShell(child);
1516
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
1517
+ openDirectory = async (path) => {
1518
+ const result = await shell.exec([
1519
+ "/usr/bin/open",
1520
+ "-a",
1521
+ "Finder",
1522
+ path
1523
+ ], {
1524
+ env,
1525
+ inheritEnv: false
1526
+ }, withAbortSignal(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), BACKGROUND_CONTEXT));
1527
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
1278
1528
  };
1279
- }
1529
+ return () => {
1530
+ openDirectory = void 0;
1531
+ };
1532
+ });
1533
+ return createGitApi(async (path) => {
1534
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1535
+ await openDirectory(path);
1536
+ });
1280
1537
  });
1281
1538
  //#endregion
1282
1539
  //#region src/services/gitFailure/index.ts
@@ -1413,7 +1670,7 @@ async function rebasing(root) {
1413
1670
  "--git-path",
1414
1671
  name
1415
1672
  ]);
1416
- if (gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath))) return true;
1673
+ if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1417
1674
  }
1418
1675
  return false;
1419
1676
  }
@@ -1584,8 +1841,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1584
1841
  * - Apart from the worktrees channel. Worktrees are repository management;
1585
1842
  * this is the session's own code change.
1586
1843
  * - Push, not poll. The session's server plugin publishes a "changed" event
1587
- * after every tool call and settled turn; recounts are coalesced to one in
1588
- * flight plus one rerun, so a burst of tool calls costs at most two.
1844
+ * after every tool call that can write and every settled turn; a recount
1845
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
1846
+ * in flight plus one rerun.
1589
1847
  * - One sync command per session. A rebase and a push must never overlap.
1590
1848
  * - Auth is read fresh for each command from the session's workspace, and goes
1591
1849
  * only into that command's git child.
@@ -1594,6 +1852,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1594
1852
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1595
1853
  * stderr and drops it, because a remote URL in it can carry a token.
1596
1854
  */
1855
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
1856
+ const REFRESH_DELAY_MS = 1500;
1597
1857
  function payloadOf$1(state) {
1598
1858
  return {
1599
1859
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1645,10 +1905,12 @@ function createGitChangesChannel(options = {}) {
1645
1905
  const inFlight = /* @__PURE__ */ new Set();
1646
1906
  const rerun = /* @__PURE__ */ new Set();
1647
1907
  const busy = /* @__PURE__ */ new Set();
1908
+ const delayed = /* @__PURE__ */ new Map();
1909
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1648
1910
  /** The base the session's own worktree was created from, when it has one. */
1649
- const recordedBaseRef = (scope) => {
1911
+ const recordedBaseRef = async (scope) => {
1650
1912
  try {
1651
- return createWorktreeRegistry(registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
1913
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, homeDir)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1652
1914
  } catch {
1653
1915
  return;
1654
1916
  }
@@ -1681,8 +1943,7 @@ function createGitChangesChannel(options = {}) {
1681
1943
  return;
1682
1944
  }
1683
1945
  inFlight.add(sessionId);
1684
- const base = recordedBaseRef(scope);
1685
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
1946
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1686
1947
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1687
1948
  }).catch((error) => {
1688
1949
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1691,12 +1952,22 @@ function createGitChangesChannel(options = {}) {
1691
1952
  if (rerun.delete(sessionId)) refresh(sessionId);
1692
1953
  });
1693
1954
  };
1694
- const run = (scope, command) => {
1955
+ /** Recounts once the session has been quiet for a moment. */
1956
+ const refreshSoon = (sessionId) => {
1957
+ clearTimeout(delayed.get(sessionId));
1958
+ const timer = setTimeout(() => {
1959
+ delayed.delete(sessionId);
1960
+ refresh(sessionId);
1961
+ }, refreshDelayMs);
1962
+ timer.unref?.();
1963
+ delayed.set(sessionId, timer);
1964
+ };
1965
+ const run = async (scope, command) => {
1695
1966
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1696
- const base = recordedBaseRef(scope);
1967
+ const base = await recordedBaseRef(scope);
1697
1968
  const context = {
1698
1969
  cwd: scope.cwd,
1699
- auth: auth.read(workspaceRoot),
1970
+ auth: await auth.read(workspaceRoot),
1700
1971
  ...base === void 0 ? {} : { recordedBaseRef: base }
1701
1972
  };
1702
1973
  if (command.action === "pull") return sync.pull(context);
@@ -1713,12 +1984,14 @@ function createGitChangesChannel(options = {}) {
1713
1984
  scopes.set(scope.sessionId, scope);
1714
1985
  refresh(scope.sessionId);
1715
1986
  const unsubscribe = host.directEvents.subscribe(GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1716
- if (isSessionChangedEvent(payload)) refresh(scope.sessionId);
1987
+ if (isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1717
1988
  });
1718
1989
  subscriptions.set(scope.sessionId, unsubscribe);
1719
1990
  },
1720
1991
  sessionRemoved(sessionId) {
1721
1992
  subscriptions.get(sessionId)?.();
1993
+ clearTimeout(delayed.get(sessionId));
1994
+ delayed.delete(sessionId);
1722
1995
  subscriptions.delete(sessionId);
1723
1996
  scopes.delete(sessionId);
1724
1997
  latest.delete(sessionId);
@@ -1727,6 +2000,8 @@ function createGitChangesChannel(options = {}) {
1727
2000
  },
1728
2001
  close() {
1729
2002
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2003
+ for (const timer of delayed.values()) clearTimeout(timer);
2004
+ delayed.clear();
1730
2005
  subscriptions.clear();
1731
2006
  scopes.clear();
1732
2007
  latest.clear();
@@ -1794,9 +2069,9 @@ function payloadOf(state) {
1794
2069
  };
1795
2070
  }
1796
2071
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1797
- function viewsFor(scope, deps) {
2072
+ async function viewsFor(scope, deps) {
1798
2073
  try {
1799
- return createWorktreeRegistry(registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2074
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, deps.homeDir)).list()).flatMap((record) => {
1800
2075
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1801
2076
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1802
2077
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1821,11 +2096,15 @@ function sameList(left, right) {
1821
2096
  return other !== void 0 && entry.id === other.id && entry.branch === other.branch && entry.sessionId === other.sessionId && entry.orphaned === other.orphaned && entry.unowned === other.unowned;
1822
2097
  });
1823
2098
  }
1824
- function errorTargetFor(command) {
1825
- return command.action === "create" ? { action: "create" } : {
2099
+ function errorTargetFor(command, error) {
2100
+ if (command.action === "close") return {
1826
2101
  action: "close",
1827
2102
  id: command.id
1828
2103
  };
2104
+ return error instanceof PoGitExpectedError && error.code === "rift_missing" ? {
2105
+ action: "create",
2106
+ riftMissing: true
2107
+ } : { action: "create" };
1829
2108
  }
1830
2109
  /** A command the page sent, or undefined when the frame was not one. */
1831
2110
  function parseCommand(payload) {
@@ -1853,11 +2132,15 @@ function parseCommand(payload) {
1853
2132
  /**
1854
2133
  * What the reader is told when a command fails.
1855
2134
  *
1856
- * An expected failure explains itself. Anything else is summarised, never
1857
- * echoed: a git error can carry a remote URL with a token in it.
2135
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2136
+ * written for the agent's tool result. A dirty close is said in the person's
2137
+ * terms, because its message tells the agent to pass `force`. Anything else is
2138
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1858
2139
  */
1859
2140
  function failureText(error) {
1860
- return error instanceof PoGitExpectedError ? error.message : "The worktree operation failed.";
2141
+ if (!(error instanceof PoGitExpectedError)) return "The worktree operation failed.";
2142
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2143
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1861
2144
  }
1862
2145
  /** Starts one direct-event subscription per managed session. */
1863
2146
  function createWorktreesChannel(options = {}) {
@@ -1910,10 +2193,13 @@ function createWorktreesChannel(options = {}) {
1910
2193
  return generation;
1911
2194
  };
1912
2195
  /** Republishes a session, skipping a frame that would say nothing new. */
1913
- const publish = (scope, force) => {
2196
+ const publish = async (scope, force) => {
2197
+ const generation = generations.get(scope.sessionId);
2198
+ const worktreeViews = await viewsFor(scope, views);
2199
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1914
2200
  const previous = latest.get(scope.sessionId);
1915
2201
  const next = {
1916
- worktrees: viewsFor(scope, views),
2202
+ worktrees: worktreeViews,
1917
2203
  pending: previous?.pending,
1918
2204
  error: previous?.error,
1919
2205
  errorTarget: previous?.errorTarget
@@ -1925,7 +2211,7 @@ function createWorktreesChannel(options = {}) {
1925
2211
  const mark = (scope, pending, error, errorTarget) => {
1926
2212
  const previous = latest.get(scope.sessionId);
1927
2213
  latest.set(scope.sessionId, {
1928
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2214
+ worktrees: previous?.worktrees ?? [],
1929
2215
  pending,
1930
2216
  error,
1931
2217
  errorTarget
@@ -1965,15 +2251,15 @@ function createWorktreesChannel(options = {}) {
1965
2251
  sessionAdded(scope) {
1966
2252
  newGeneration(scope.sessionId);
1967
2253
  publish(scope, false);
1968
- const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
2254
+ const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
1969
2255
  if (!isWorktreeLifecycleEvent(payload)) return;
1970
2256
  let sameRepository = false;
1971
2257
  try {
1972
- sameRepository = registryFile(scope.cwd, options.homeDir) === registryFile(payload.repositoryRoot, options.homeDir);
2258
+ sameRepository = await registryFile(scope.cwd, options.homeDir) === await registryFile(payload.repositoryRoot, options.homeDir);
1973
2259
  } catch {
1974
2260
  sameRepository = false;
1975
2261
  }
1976
- if (sameRepository) publish(scope, false);
2262
+ if (sameRepository) await publish(scope, false);
1977
2263
  });
1978
2264
  subscriptions.set(scope.sessionId, unsubscribe);
1979
2265
  },
@@ -2006,7 +2292,7 @@ function createWorktreesChannel(options = {}) {
2006
2292
  }).catch((error) => {
2007
2293
  if (generations.get(scope.sessionId) !== generation) return;
2008
2294
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2009
- mark(scope, void 0, failureText(error), errorTargetFor(command));
2295
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2010
2296
  }).finally(() => {
2011
2297
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2012
2298
  });
@@ -2028,20 +2314,8 @@ var agent_settled_server_default = defineHook((context) => context.root.hooks[1]
2028
2314
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2029
2315
  var tool_execution_end_server_default = defineHook((context) => context.root.hooks[0]);
2030
2316
  //#endregion
2031
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGit.server.ts
2032
- var poGit_server_default$1 = (context) => context.root.resources[0];
2033
- //#endregion
2034
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGit.server.ts
2035
- var poGit_server_default = defineResource(poGit_server_default$1);
2036
- //#endregion
2037
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGitReadme.server.ts
2038
- var poGitReadme_server_default$1 = (context) => context.root.resources[2];
2039
- //#endregion
2040
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGitReadme.server.ts
2041
- var poGitReadme_server_default = defineResource(poGitReadme_server_default$1);
2042
- //#endregion
2043
2317
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2044
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
2318
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2045
2319
  //#endregion
2046
2320
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2047
2321
  var poUseGit_server_default = defineResource(poUseGit_server_default$1);
@@ -2061,12 +2335,12 @@ const serverPlugin = defineServerPlugin({
2061
2335
  name: "@agimon-ai/po-git",
2062
2336
  providerOverrides: composeServerProviderOverrides(root_server_default),
2063
2337
  injects: composeRootInjects({ session: [root_server_default] }),
2064
- global: (context) => ({
2338
+ host: (context) => ({
2065
2339
  get api() {
2066
2340
  return [at(route_server_default, context)];
2067
2341
  },
2068
2342
  get channels() {
2069
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2343
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2070
2344
  }
2071
2345
  }),
2072
2346
  workspace: (context) => ({
@@ -2074,7 +2348,7 @@ const serverPlugin = defineServerPlugin({
2074
2348
  return [at(route_server_default, context)];
2075
2349
  },
2076
2350
  get channels() {
2077
- 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())]);
2351
+ 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))]);
2078
2352
  }
2079
2353
  }),
2080
2354
  session: async (context) => {
@@ -2089,17 +2363,13 @@ const serverPlugin = defineServerPlugin({
2089
2363
  return [at(route_server_default, context)];
2090
2364
  },
2091
2365
  get channels() {
2092
- 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())]);
2366
+ 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))]);
2093
2367
  },
2094
2368
  get hooks() {
2095
2369
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2096
2370
  },
2097
2371
  get resources() {
2098
- return [
2099
- at(poGit_server_default, contextSession),
2100
- at(poGitReadme_server_default, contextSession),
2101
- at(poUseGit_server_default, contextSession)
2102
- ];
2372
+ return [at(poUseGit_server_default, contextSession)];
2103
2373
  },
2104
2374
  get tools() {
2105
2375
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];