@agimon-ai/po-git 0.0.0-alpha.21 → 0.0.0-alpha.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +110 -149
  2. package/README.md +91 -21
  3. package/dist/apiContracts.cjs +78 -12
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +78 -12
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2300 -548
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1578 -513
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1537 -472
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +1791 -1376
  17. package/dist/extensions/web.mjs.map +1 -1
  18. package/dist/gitDependencies-D8bKxZSc.cjs +2690 -0
  19. package/dist/gitDependencies-D8bKxZSc.cjs.map +1 -0
  20. package/dist/gitDependencies-Delu4xip.mjs +2432 -0
  21. package/dist/gitDependencies-Delu4xip.mjs.map +1 -0
  22. package/dist/index.cjs +13 -22
  23. package/dist/index.d.mts +266 -14
  24. package/dist/index.d.mts.map +1 -1
  25. package/dist/index.mjs +3 -22
  26. package/dist/po-runtime-identity.json +1 -0
  27. package/llms.txt +3 -3
  28. package/locales/vi.json +325 -0
  29. package/locales/zh-CN.json +325 -0
  30. package/package.json +115 -22
  31. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  32. package/dist/index.cjs.map +0 -1
  33. package/dist/index.mjs.map +0 -1
  34. package/dist/worktreeOperations-Cd8Q12L4.mjs +0 -1064
  35. package/dist/worktreeOperations-Cd8Q12L4.mjs.map +0 -1
  36. package/dist/worktreeOperations-Dxs3txKL.cjs +0 -1220
  37. package/dist/worktreeOperations-Dxs3txKL.cjs.map +0 -1
  38. package/src/prompts/po-use-git/SKILL.md +0 -87
@@ -1,11 +1,87 @@
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 { A as NETWORK_TIMEOUT_MS, C as PoGitExpectedError, F as revision, I as runGit, L as GIT_ENGINE_CONTRACT, M as REBASE_TIMEOUT_MS, N as createWorktreeGit, P as remoteBranchHead, S as HubUnavailableError, _ as createWorktreeMessageInbox, a as credentialsFile, b as receiveWorktreeSetup, c as registryFile, f as StartWorktreeWorkflowSchema, g as GIT_WORKTREE_LIFECYCLE_EVENT, h as GIT_SESSION_CHANGED_EVENT, i as validRefName, j as READ_TIMEOUT_MS, l as createWorktreeRegistry, m as writeJsonAtomic, n as createGitOperationDependencies, p as readJson, r as createWorktreeOperations, s as poGitRoot, u as GIT_WORKFLOWS_CONTRACT, v as isSessionChangedEvent, w as invalidRequest, x as validSparseProfile, y as isWorktreeLifecycleEvent } from "../gitDependencies-Delu4xip.mjs";
2
+ import { BACKGROUND_CONTEXT, PO_FS_SERVICE, PO_SHELL_SERVICE, requirePoFs, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
3
+ import { createGitEngineService, createPoFsAdapter } from "@agimon-ai/po-sparo";
4
+ import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
5
+ import fs from "node:fs/promises";
6
+ import { createHash, randomUUID } from "node:crypto";
4
7
  import path from "node:path";
5
- import { composeServerProviderOverrides, defineServerPlugin, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
8
+ import os from "node:os";
9
+ import { Check } from "typebox/value";
10
+ import { Type } from "typebox";
11
+ import { PO_WORKFLOW_ADMISSIONS_SERVICE, PO_WORKFLOW_RUNS_SERVICE, PoWorkflowDefinitionRefSchema, readPoWorkflowAdmissionsService, readPoWorkflowRunsService } from "@agimon-ai/po-core/workflow";
6
12
  import { composeRootHooks, composeRootInjects, defineChannel, defineHook, defineResource, defineRoot, defineRoute, defineServerTool } from "@agimon-ai/po-core/extensionFile";
13
+ import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
7
14
  import { readPoSessionDelivery } from "@agimon-ai/po-session";
8
- import { Type } from "typebox";
15
+ import { canonicalLocale, formatMessage, readPoLang, readPoPersonLocale } from "@agimon-ai/po-core/locale";
16
+ import { poApiCallerFrom } from "@agimon-ai/po-core/packageApi";
17
+ import { parseLaunchSelection } from "@agimon-ai/po-core/hubChannel";
18
+ //#region src/extensions/workspaces/(backend)/root.server.ts
19
+ var root_server_default$1 = defineRoot(({ context, signal }) => {
20
+ context.inject([PO_SERVER_SCOPE_SERVICE, PO_FS_SERVICE], (scoped) => {
21
+ let shell;
22
+ let shellSignal = AbortSignal.abort(/* @__PURE__ */ new Error("Git engine requires the host shell (po/shell)."));
23
+ scoped.inject([PO_SHELL_SERVICE], (child) => {
24
+ const lifetime = new AbortController();
25
+ shell = requirePoShell(child);
26
+ shellSignal = lifetime.signal;
27
+ return () => {
28
+ shell = void 0;
29
+ lifetime.abort(/* @__PURE__ */ new Error("Git engine host shell was disposed."));
30
+ };
31
+ });
32
+ const engine = createGitEngineService({
33
+ fs: createPoFsAdapter(requirePoFs(scoped), (operationSignal) => withAbortSignal(AbortSignal.any([signal, operationSignal]), BACKGROUND_CONTEXT)),
34
+ exec: ({ environment }) => {
35
+ const env = Object.fromEntries(Object.entries(environment).filter((entry) => entry[1] !== void 0));
36
+ return { async run(command, args, options) {
37
+ if (shell === void 0) throw new Error("Git engine requires the host shell (po/shell).");
38
+ const operationSignal = AbortSignal.any([
39
+ signal,
40
+ shellSignal,
41
+ options.signal ?? signal,
42
+ AbortSignal.timeout(12e4)
43
+ ]);
44
+ operationSignal.throwIfAborted();
45
+ let stdout = "";
46
+ let stderr = "";
47
+ let bytes = 0;
48
+ const outputLimit = new AbortController();
49
+ const result = await shell.exec([command, ...args], {
50
+ cwd: options.cwd,
51
+ env,
52
+ inheritEnv: false,
53
+ timeout: 12e4,
54
+ onOutput(text, _context, info) {
55
+ bytes += new TextEncoder().encode(text).byteLength;
56
+ if (bytes > 4194304) {
57
+ outputLimit.abort(/* @__PURE__ */ new Error("Git engine command output exceeded 4 MiB."));
58
+ return;
59
+ }
60
+ if (info.stream === "stdout") stdout += text;
61
+ else stderr += text;
62
+ }
63
+ }, withAbortSignal(AbortSignal.any([operationSignal, outputLimit.signal]), BACKGROUND_CONTEXT));
64
+ outputLimit.signal.throwIfAborted();
65
+ operationSignal.throwIfAborted();
66
+ if (!result.ok) throw result.error;
67
+ return {
68
+ exitCode: result.value.exitCode,
69
+ stdout,
70
+ stderr
71
+ };
72
+ } };
73
+ },
74
+ logger: {
75
+ info: (message) => console.info(message),
76
+ warn: (message) => console.warn(message),
77
+ error: (message) => console.error(message)
78
+ }
79
+ });
80
+ return requirePoServerScope(scoped).provide(GIT_ENGINE_CONTRACT, engine);
81
+ });
82
+ return { value: void 0 };
83
+ });
84
+ //#endregion
9
85
  //#region src/schemas/runWorktreeTool.ts
10
86
  /**
11
87
  * The tool's action vocabulary.
@@ -22,7 +98,10 @@ const WORKTREE_ACTIONS = {
22
98
  merge: "merge",
23
99
  prune: "prune",
24
100
  send: "send",
25
- messages: "messages"
101
+ messages: "messages",
102
+ profiles: "profiles",
103
+ expand: "expand",
104
+ reapply: "reapply"
26
105
  };
27
106
  /**
28
107
  * Which fields each action accepts.
@@ -37,7 +116,8 @@ const WORKTREE_ACTION_FIELDS = {
37
116
  "branch",
38
117
  "baseRef",
39
118
  "task",
40
- "name"
119
+ "name",
120
+ "sparseProfile"
41
121
  ],
42
122
  close_worktree: [
43
123
  "action",
@@ -57,12 +137,20 @@ const WORKTREE_ACTION_FIELDS = {
57
137
  "id",
58
138
  "message"
59
139
  ],
60
- messages: ["action", "id"]
140
+ messages: ["action", "id"],
141
+ profiles: ["action", "baseRef"],
142
+ expand: [
143
+ "action",
144
+ "id",
145
+ "folders"
146
+ ],
147
+ reapply: ["action", "id"]
61
148
  };
62
149
  const SpawnParams = Type.Object({
63
150
  action: Type.Literal(WORKTREE_ACTIONS.spawn_worktree),
64
151
  branch: Type.String({ minLength: 1 }),
65
152
  baseRef: Type.Optional(Type.String({ minLength: 1 })),
153
+ sparseProfile: Type.Optional(Type.String({ minLength: 1 })),
66
154
  task: Type.Optional(Type.String({ minLength: 1 })),
67
155
  name: Type.Optional(Type.String({ minLength: 1 }))
68
156
  }, { additionalProperties: false });
@@ -102,7 +190,20 @@ Type.Union([
102
190
  MergeParams,
103
191
  PruneParams,
104
192
  SendParams,
105
- MessagesParams
193
+ MessagesParams,
194
+ Type.Object({
195
+ action: Type.Literal("profiles"),
196
+ baseRef: Type.Optional(Type.String({ minLength: 1 }))
197
+ }, { additionalProperties: false }),
198
+ Type.Object({
199
+ action: Type.Literal("expand"),
200
+ id: Type.String({ minLength: 1 }),
201
+ folders: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })
202
+ }, { additionalProperties: false }),
203
+ Type.Object({
204
+ action: Type.Literal("reapply"),
205
+ id: Type.String({ minLength: 1 })
206
+ }, { additionalProperties: false })
106
207
  ]);
107
208
  /** The actions that accept `field`, so the declared docs cannot drift from the validator. */
108
209
  function acceptingActions(field) {
@@ -132,6 +233,14 @@ const RunWorktreeToolSchema = Type.Object({
132
233
  minLength: 1,
133
234
  description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions("baseRef")}.`
134
235
  })),
236
+ sparseProfile: Type.Optional(Type.String({
237
+ minLength: 1,
238
+ description: "Sparse checkout profile, independent of the launch profile."
239
+ })),
240
+ folders: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
241
+ minItems: 1,
242
+ description: "Relative cone folders for expand."
243
+ })),
135
244
  task: Type.Optional(Type.String({
136
245
  minLength: 1,
137
246
  description: `First message for the new session. Actions: ${acceptingActions("task")}.`
@@ -159,6 +268,9 @@ const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its
159
268
 
160
269
  Actions:
161
270
  - spawn_worktree: create a worktree on a new branch and start a session in it. Requires 'branch'. Optional 'baseRef' (defaults to the current branch's remote-tracking ref, then the remote default branch), 'name' for the rail, 'task' as the first message.
271
+ - profiles: list sparse checkout profiles at baseRef.
272
+ - expand: add folders to a sparse worktree. Requires 'id' and 'folders'.
273
+ - reapply: refresh a sparse worktree from HEAD. Requires 'id'.
162
274
  - close_worktree: stop a worktree's session and delete its checkout. Requires 'id'. Refuses a dirty tree unless 'force' is true.
163
275
  - list: every worktree for this repository, with status and relationship to the calling session.
164
276
  - status: one worktree, its relationship to the calling session, and its uncommitted files. Requires 'id'.
@@ -186,12 +298,14 @@ function validateParams(input) {
186
298
  "baseRef",
187
299
  "name",
188
300
  "task",
189
- "message"
301
+ "message",
302
+ "sparseProfile"
190
303
  ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
304
+ if (action === "expand" && (!Array.isArray(record.folders) || record.folders.length === 0 || !record.folders.every((folder) => typeof folder === "string" && folder.trim() !== ""))) throw invalidRequest("expand requires nonempty folders.", "Pass relative cone folders.");
191
305
  for (const field of ["force", "dryRun"]) if (field in record && typeof record[field] !== "boolean") throw invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);
192
306
  if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
193
307
  if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
194
- if ((action === WORKTREE_ACTIONS.close_worktree || action === WORKTREE_ACTIONS.status || action === WORKTREE_ACTIONS.merge || action === WORKTREE_ACTIONS.send || action === WORKTREE_ACTIONS.messages) && typeof record.id !== "string") throw invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
308
+ if ((action === WORKTREE_ACTIONS.expand || action === WORKTREE_ACTIONS.reapply || action === WORKTREE_ACTIONS.close_worktree || action === WORKTREE_ACTIONS.status || action === WORKTREE_ACTIONS.merge || action === WORKTREE_ACTIONS.send || action === WORKTREE_ACTIONS.messages) && typeof record.id !== "string") throw invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
195
309
  return record;
196
310
  }
197
311
  function describe(record, sessionId) {
@@ -206,9 +320,31 @@ function text(...lines) {
206
320
  }
207
321
  async function executeRunWorktreeTool(params, operations, context, options = {}) {
208
322
  switch (params.action) {
323
+ case WORKTREE_ACTIONS.profiles: {
324
+ const profiles = await operations.profiles(context, params.baseRef, options);
325
+ return {
326
+ content: text(profiles.sparseProfiles?.join(", ") ?? "Sparse checkout is not configured."),
327
+ details: {
328
+ action: params.action,
329
+ ...profiles
330
+ }
331
+ };
332
+ }
333
+ case WORKTREE_ACTIONS.expand:
334
+ case WORKTREE_ACTIONS.reapply: {
335
+ const record = params.action === "expand" ? await operations.expand(context, params.id, params.folders, options) : await operations.reapply(context, params.id, options);
336
+ return {
337
+ content: text(`Worktree ${record.id} sparse checkout updated.`),
338
+ details: {
339
+ action: params.action,
340
+ records: [record]
341
+ }
342
+ };
343
+ }
209
344
  case WORKTREE_ACTIONS.spawn_worktree: {
210
345
  const record = await operations.spawn(context, {
211
346
  branch: params.branch,
347
+ ...params.sparseProfile === void 0 ? {} : { sparseProfile: params.sparseProfile },
212
348
  ...params.baseRef === void 0 ? {} : { baseRef: params.baseRef },
213
349
  ...params.name === void 0 ? {} : { name: params.name },
214
350
  ...params.task === void 0 ? {} : { task: params.task }
@@ -247,7 +383,8 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
247
383
  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
384
  details: {
249
385
  action: params.action,
250
- records: [record]
386
+ records: [record],
387
+ dirtyFiles
251
388
  }
252
389
  };
253
390
  }
@@ -271,7 +408,10 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
271
408
  const waiting = await operations.messages(context, params.id);
272
409
  return {
273
410
  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 }
411
+ details: {
412
+ action: params.action,
413
+ messages: waiting
414
+ }
275
415
  };
276
416
  }
277
417
  case WORKTREE_ACTIONS.prune: {
@@ -286,12 +426,579 @@ async function executeRunWorktreeTool(params, operations, context, options = {})
286
426
  `Untracked directories, left alone: ${plan.untracked.length === 0 ? "none" : plan.untracked.join(", ")}`,
287
427
  ...plan.keptBranches.length === 0 ? [] : [`Branches kept, they hold commits: ${plan.keptBranches.join(", ")}`]
288
428
  ]),
289
- details: { action: params.action }
429
+ details: {
430
+ action: params.action,
431
+ plan
432
+ }
290
433
  };
291
434
  }
292
435
  }
293
436
  }
294
437
  //#endregion
438
+ //#region src/services/worktreeNamespace/index.ts
439
+ const DECLARATIONS = `type WorktreeStatus = 'spawning' | 'running' | 'closing' | 'orphaned';
440
+
441
+ interface Worktree {
442
+ id: string;
443
+ branch: string;
444
+ baseRef: string;
445
+ /** Absolute path of the checkout. Imported worktrees stay at their original path. */
446
+ path: string;
447
+ repositoryRoot: string;
448
+ /** The session running inside the worktree. */
449
+ sessionId: string;
450
+ parentSessionId?: string;
451
+ status: WorktreeStatus;
452
+ /** started confirms runner launch only; unconfirmed handoffs must not be blindly retried. */
453
+ setupStage?: 'none' | 'started' | 'failed' | 'unconfirmed';
454
+ createdAt: string;
455
+ sparseProfile?: string;
456
+ extraFolders?: string[];
457
+ sparseFingerprint?: string;
458
+ /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
459
+ relationship: 'parent' | 'child' | 'other';
460
+ }
461
+
462
+ interface WorktreeMessage {
463
+ worktreeId: string;
464
+ fromSessionId: string;
465
+ from: 'parent' | 'child';
466
+ text: string;
467
+ sentAt: string;
468
+ }
469
+
470
+ interface PrunePlan {
471
+ remove: Worktree[];
472
+ forget: Worktree[];
473
+ /** Kept because they hold uncommitted work. */
474
+ keptDirty: Worktree[];
475
+ untracked: string[];
476
+ /** Branches kept because they hold commits. */
477
+ keptBranches: string[];
478
+ }
479
+
480
+ declare const worktrees: {
481
+ /** Every worktree for this repository. */
482
+ list(): Promise<Worktree[]>;
483
+ /** One worktree and its uncommitted files. */
484
+ status(id: string): Promise<{ worktree: Worktree; dirtyFiles: string[] }>;
485
+ /**
486
+ * Create a worktree on a new branch and start a Po session in it, nested under this one. baseRef defaults to
487
+ * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
488
+ * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
489
+ */
490
+ spawn(request: { branch: string; baseRef?: string; name?: string; task?: string; sparseProfile?: string }): Promise<Worktree>;
491
+ /** Run a repository workflow in its own checkout. Retrying the same attemptId never recreates uncertain work. */
492
+ startWorkflow(request: { key: string; attemptId?: string; branch?: string; sparseProfile?: string; inputs?: Record<string, string> }): Promise<{ attemptId: string; worktreeId: string; sessionId: string; branch: string; runId?: string; admission: 'pending' | 'registered' }>;
493
+ profiles(options?: { baseRef?: string }): Promise<{ sparseProfiles?: string[]; defaultSparseProfile?: string }>;
494
+ expand(id: string, folders: string[]): Promise<Worktree>;
495
+ reapply(id: string): Promise<Worktree>;
496
+ /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
497
+ close(id: string, options?: { force?: boolean }): Promise<Worktree>;
498
+ /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
499
+ merge(id: string, options?: { message?: string }): Promise<Worktree>;
500
+ /** Remove orphaned worktrees. With dryRun, only return the plan. */
501
+ prune(options?: { dryRun?: boolean }): Promise<PrunePlan>;
502
+ /**
503
+ * Message the other side of a worktree. Use the record with relationship 'child' to report to your parent,
504
+ * and 'parent' to reach your own children. 'other' records are not communication edges.
505
+ */
506
+ send(id: string, message: string): Promise<void>;
507
+ /** Messages waiting for you from a worktree. */
508
+ messages(id: string): Promise<WorktreeMessage[]>;
509
+ };`;
510
+ const json = (value) => JSON.parse(JSON.stringify(value));
511
+ /** Git worktrees for code mode: the actions of `run_worktree` as methods, returning records instead of text. */
512
+ function createWorktreeNamespace(options) {
513
+ return {
514
+ name: "worktrees",
515
+ summary: "Create and manage Git worktree sessions, select or expand a sparse checkout, and start isolated repository workflows.",
516
+ declarations: DECLARATIONS,
517
+ bind(run) {
518
+ if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
519
+ let disposed = false;
520
+ run.onDispose(() => {
521
+ disposed = true;
522
+ });
523
+ const view = (record) => ({
524
+ ...record,
525
+ relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
526
+ });
527
+ /** One `run_worktree` action through the tool's own code, so the tool and the namespace cannot drift. */
528
+ const act = async (name, action, input = {}, target) => {
529
+ run.signal.throwIfAborted();
530
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
531
+ options.assertAvailable();
532
+ if (typeof input !== "object" || input === null || Array.isArray(input) || "action" in input) throw invalidRequest(`Invalid options for worktrees.${name}.`, "Pass the documented fields without an action.");
533
+ const params = validateParams({
534
+ ...input,
535
+ ...target,
536
+ action
537
+ });
538
+ const context = {
539
+ cwd: options.execution.cwd,
540
+ sessionId: options.execution.sessionId
541
+ };
542
+ const started = Date.now();
543
+ try {
544
+ const result = await executeRunWorktreeTool(params, options.operations, context, { signal: run.signal });
545
+ options.assertAvailable();
546
+ run.record?.({
547
+ name: `worktrees.${name}`,
548
+ tool: RUN_WORKTREE_TOOL_NAME,
549
+ args: params,
550
+ ok: true,
551
+ ms: Date.now() - started,
552
+ result
553
+ });
554
+ return result;
555
+ } catch (error) {
556
+ run.record?.({
557
+ name: `worktrees.${name}`,
558
+ tool: RUN_WORKTREE_TOOL_NAME,
559
+ args: params,
560
+ ok: false,
561
+ ms: Date.now() - started,
562
+ error: error instanceof Error ? error.message : String(error)
563
+ });
564
+ throw error;
565
+ }
566
+ };
567
+ const record = (result) => view(result.details.records[0]);
568
+ const members = Object.create(null);
569
+ members.profiles = async (settings) => {
570
+ const { action: _action, ...profiles } = (await act("profiles", "profiles", settings)).details;
571
+ return json(profiles);
572
+ };
573
+ members.expand = async (id, folders) => json(record(await act("expand", "expand", {
574
+ id,
575
+ folders
576
+ })));
577
+ members.reapply = async (id) => json(record(await act("reapply", "reapply", { id })));
578
+ members.list = async () => json((await act("list", "list", {})).details.records.map(view));
579
+ members.status = async (id) => {
580
+ const { details } = await act("status", "status", { id });
581
+ return json({
582
+ worktree: view(details.records[0]),
583
+ dirtyFiles: details.dirtyFiles ?? []
584
+ });
585
+ };
586
+ members.spawn = async (request) => json(record(await act("spawn", "spawn_worktree", request)));
587
+ members.startWorkflow = async (request) => {
588
+ run.signal.throwIfAborted();
589
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
590
+ options.assertAvailable();
591
+ if (!Check(StartWorktreeWorkflowSchema, request)) throw new Error("A repository workflow key and valid launch fields are required.");
592
+ const workflows = options.workflows?.();
593
+ if (!workflows) throw new Error("Isolated workflow admissions are unavailable in this session.");
594
+ const attemptId = request.attemptId ?? `git-${randomUUID()}`;
595
+ const started = await workflows.start({
596
+ attemptId,
597
+ definition: {
598
+ source: "repo",
599
+ key: request.key
600
+ },
601
+ ...request.branch === void 0 ? {} : { branch: request.branch },
602
+ ...request.sparseProfile === void 0 ? {} : { sparseProfile: request.sparseProfile },
603
+ ...request.inputs === void 0 ? {} : { overrides: { inputs: request.inputs } }
604
+ }, run.signal);
605
+ options.assertAvailable();
606
+ return json({
607
+ attemptId,
608
+ worktreeId: started.worktreeId,
609
+ sessionId: started.sessionId,
610
+ branch: started.branch,
611
+ admission: started.admission.state,
612
+ ...started.admission.state === "registered" ? { runId: started.admission.run.runId } : {}
613
+ });
614
+ };
615
+ members.close = async (id, settings) => json(record(await act("close", "close_worktree", settings, { id })));
616
+ members.merge = async (id, settings) => json(record(await act("merge", "merge", settings, { id })));
617
+ members.prune = async (settings) => {
618
+ const { plan } = (await act("prune", "prune", settings)).details;
619
+ return json({
620
+ ...plan,
621
+ remove: plan.remove.map(view),
622
+ forget: plan.forget.map(view),
623
+ keptDirty: plan.keptDirty.map(view)
624
+ });
625
+ };
626
+ members.send = async (id, message) => {
627
+ await act("send", "send", {
628
+ id,
629
+ message
630
+ });
631
+ };
632
+ members.messages = async (id) => json((await act("messages", "messages", { id })).details.messages);
633
+ return members;
634
+ }
635
+ };
636
+ }
637
+ //#endregion
638
+ //#region src/services/worktreeWorkflows/index.ts
639
+ var WorktreeWorkflowError = class extends Error {
640
+ code;
641
+ constructor(code, message, options) {
642
+ super(message, options);
643
+ this.code = code;
644
+ this.name = "WorktreeWorkflowError";
645
+ }
646
+ };
647
+ function canonical(value) {
648
+ if (Array.isArray(value)) return value.map(canonical);
649
+ if (value === null || typeof value !== "object") return value;
650
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
651
+ }
652
+ function defaultBranch(input) {
653
+ const safe = (value) => value.replace(/[^A-Za-z0-9._-]+/gu, "-").replace(/^[.-]+|[.-]+$/gu, "") || "run";
654
+ return `wf/${safe(path.basename(input.definition.key, path.extname(input.definition.key)))}/${safe(input.attemptId)}`;
655
+ }
656
+ function remoteBase(record) {
657
+ const ref = record.baseRef.replace(/^refs\/remotes\//u, "");
658
+ const slash = ref.indexOf("/");
659
+ if (slash < 1 || !record.baseCommit) return void 0;
660
+ const remote = ref.slice(0, slash);
661
+ const branch = ref.slice(slash + 1);
662
+ return validRefName(remote) && validRefName(branch) ? {
663
+ remote,
664
+ branch,
665
+ sha: record.baseCommit
666
+ } : void 0;
667
+ }
668
+ /** One coordinator over the existing admissions/runs services, never a second workflow engine. */
669
+ function createWorktreeWorkflows(options) {
670
+ if (!options.sessionId.trim()) throw new Error("A workflow launcher session is required.");
671
+ const context = {
672
+ cwd: options.cwd,
673
+ sessionId: options.sessionId
674
+ };
675
+ const watching = /* @__PURE__ */ new Map();
676
+ const inFlight = /* @__PURE__ */ new Map();
677
+ options.signal.addEventListener("abort", () => {
678
+ for (const stop of watching.values()) stop();
679
+ watching.clear();
680
+ }, { once: true });
681
+ const operation = (signal) => ({
682
+ env: options.environment,
683
+ signal: AbortSignal.any([options.signal, ...signal ? [signal] : []])
684
+ });
685
+ const store = async () => {
686
+ const root = await options.git.repositoryRoot(options.cwd);
687
+ if (!root) throw new WorktreeWorkflowError("not_started", "A repository checkout is required.");
688
+ return options.registry ? options.registry(root) : createWorktreeRegistry(await registryFile(root, options.homeDirectory, options.environment));
689
+ };
690
+ const mutate = async (fn, signal) => {
691
+ const registry = await store();
692
+ return registry.transaction(async () => {
693
+ const attempts = await registry.workflowAttempts();
694
+ const result = await fn(attempts);
695
+ await registry.replaceWorkflowAttempts(attempts);
696
+ return result;
697
+ }, operation(signal).signal);
698
+ };
699
+ const update = (attempt, signal) => mutate((attempts) => {
700
+ const index = attempts.findIndex((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === attempt.attemptId);
701
+ if (index < 0 || attempts[index].fingerprint !== attempt.fingerprint) throw new WorktreeWorkflowError("unknown", "The durable workflow intent changed.");
702
+ attempts[index] = structuredClone(attempt);
703
+ }, signal);
704
+ const ownRecords = async () => (await options.operations.list(context)).filter((record) => record.parentSessionId === options.sessionId && record.workflow);
705
+ const retain = async (record, reason) => {
706
+ await options.operations.linkWorkflow(context, record.id, {
707
+ ...record.workflow,
708
+ state: "retained",
709
+ reason
710
+ });
711
+ };
712
+ const settle = async (record, attempt, state) => {
713
+ try {
714
+ const admission = attempt.admission;
715
+ if (admission?.state !== "registered" || JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run)) || state.run.ownerSessionId !== record.sessionId) return;
716
+ const current = (await ownRecords()).find((entry) => entry.id === record.id);
717
+ if (!current || current.sessionId !== record.sessionId || current.path !== record.path || current.status !== "running" || current.workflow?.state !== "admitted" || current.workflow?.runId !== state.run.runId || current.workflow.admissionId !== admission.admissionId || current.workflow.attemptId !== attempt.attemptId || current.workflow.fingerprint !== attempt.fingerprint) return;
718
+ let reason;
719
+ let verifiedHead;
720
+ if (state.stage !== "completed" || state.outcome !== "success") reason = `The run ended ${state.outcome ?? state.stage}.`;
721
+ else if (await options.git.repositoryRoot(current.path) !== current.path || await options.git.currentBranch(current.path) !== current.branch || !(await options.git.listWorktreePaths(current.repositoryRoot)).includes(current.path)) reason = "The exact linked checkout could not be verified.";
722
+ else if ((await options.git.dirtyFiles(current.path)).length > 0) reason = "Uncommitted files remain.";
723
+ else {
724
+ const head = await options.git.revision(current.path, "HEAD", operation());
725
+ verifiedHead = head;
726
+ if (!current.baseCommit) reason = "The original commit is unknown.";
727
+ else if (head !== current.baseCommit) {
728
+ const base = remoteBase(current);
729
+ if (!base || await options.git.remoteBranchHead(current.path, base.remote, current.branch, operation()) !== head) reason = "Delivery of this exact branch HEAD could not be verified.";
730
+ }
731
+ }
732
+ if (reason) {
733
+ await retain(current, reason);
734
+ await update({
735
+ ...attempt,
736
+ state: "retained"
737
+ });
738
+ } else {
739
+ await options.operations.close(context, current.id, false, {
740
+ ...current.workflow,
741
+ sessionId: current.sessionId,
742
+ path: current.path,
743
+ head: verifiedHead
744
+ });
745
+ await update({
746
+ ...attempt,
747
+ state: "closed"
748
+ });
749
+ }
750
+ } catch (error) {
751
+ options.onError(error);
752
+ }
753
+ };
754
+ const watch = (record, attempt) => {
755
+ const admission = attempt.admission;
756
+ if (admission?.state !== "registered" || watching.has(record.id) || options.signal.aborted) return;
757
+ const runs = options.runs();
758
+ if (!runs) return;
759
+ let stopped = false;
760
+ let unsubscribe;
761
+ const stop = () => {
762
+ stopped = true;
763
+ unsubscribe?.();
764
+ watching.delete(record.id);
765
+ };
766
+ watching.set(record.id, stop);
767
+ unsubscribe = runs.subscribe(admission.run.runId, (state) => {
768
+ if (stopped || state.stage === "running") return;
769
+ if (JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run))) return;
770
+ stop();
771
+ settle(record, attempt, state);
772
+ });
773
+ if (stopped) unsubscribe();
774
+ };
775
+ const link = async (record, attempt, admission) => {
776
+ if (admission.attemptId !== attempt.attemptId || admission.state === "registered" && admission.run.ownerSessionId !== record.sessionId) throw new WorktreeWorkflowError("unknown", "The admission does not belong to this checkout session.");
777
+ if (record.workflow?.admissionId && record.workflow.admissionId !== admission.admissionId || record.workflow?.runId && (admission.state !== "registered" || record.workflow.runId !== admission.run.runId) || attempt.admission && attempt.admission.admissionId !== admission.admissionId) throw new WorktreeWorkflowError("unknown", "The recorded workflow admission identity changed. The checkout was kept.");
778
+ if (record.workflow?.state === "retained" || [
779
+ "retained",
780
+ "closed",
781
+ "rejected"
782
+ ].includes(attempt.state)) {
783
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "This rejected attempt remains retained.");
784
+ return {
785
+ worktreeId: record.id,
786
+ sessionId: record.sessionId,
787
+ branch: record.branch,
788
+ admission
789
+ };
790
+ }
791
+ const linked = {
792
+ attemptId: attempt.attemptId,
793
+ fingerprint: attempt.fingerprint,
794
+ state: admission.state === "rejected" ? "retained" : "admitted",
795
+ admissionId: admission.admissionId,
796
+ ...admission.state === "registered" ? { runId: admission.run.runId } : {},
797
+ ...admission.state === "rejected" ? { reason: `Admission rejected: ${admission.errors.join("; ")}` } : {}
798
+ };
799
+ await options.operations.linkWorkflow(context, record.id, linked);
800
+ const updated = {
801
+ ...attempt,
802
+ admission,
803
+ state: admission.state === "rejected" ? "rejected" : "admitted",
804
+ worktreeId: record.id,
805
+ sessionId: record.sessionId
806
+ };
807
+ await update(updated);
808
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "The workflow admission was rejected. The checkout was kept.");
809
+ watch({
810
+ ...record,
811
+ workflow: linked
812
+ }, updated);
813
+ return {
814
+ worktreeId: record.id,
815
+ sessionId: record.sessionId,
816
+ branch: record.branch,
817
+ admission
818
+ };
819
+ };
820
+ const start = async (input, branch, fingerprint, signal) => {
821
+ const admissions = options.admissions();
822
+ if (!admissions) throw new WorktreeWorkflowError("not_started", "Workflow admissions are unavailable.");
823
+ const records = await ownRecords();
824
+ const legacy = records.find((record) => record.workflow.attemptId === input.attemptId);
825
+ const { attempt, created } = await mutate((attempts) => {
826
+ let attempt = attempts.find((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === input.attemptId);
827
+ if (!attempt && legacy) {
828
+ attempt = {
829
+ attemptId: input.attemptId,
830
+ fingerprint: legacy.workflow.fingerprint,
831
+ launcherSessionId: options.sessionId,
832
+ branch: legacy.branch,
833
+ definition: input.definition,
834
+ createdAt: legacy.createdAt,
835
+ state: "spawned",
836
+ worktreeId: legacy.id,
837
+ sessionId: legacy.sessionId
838
+ };
839
+ attempts.push(attempt);
840
+ }
841
+ if (attempt) {
842
+ if (attempt.fingerprint !== fingerprint) throw new WorktreeWorkflowError("attempt_conflict", "This workflow attempt was started with different arguments.");
843
+ return {
844
+ attempt: structuredClone(attempt),
845
+ created: false
846
+ };
847
+ }
848
+ attempt = {
849
+ attemptId: input.attemptId,
850
+ fingerprint,
851
+ launcherSessionId: options.sessionId,
852
+ branch,
853
+ definition: input.definition,
854
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
855
+ state: "reserved"
856
+ };
857
+ attempts.push(attempt);
858
+ return {
859
+ attempt: structuredClone(attempt),
860
+ created: true
861
+ };
862
+ }, signal);
863
+ let record = records.find((entry) => entry.id === attempt.worktreeId) ?? legacy;
864
+ if (!created) {
865
+ if (!record || record.status === "orphaned") {
866
+ if (attempt.state === "rejected" && !record) throw new WorktreeWorkflowError("not_started", "This attempt was rejected before checkout creation. Use a new attempt identity after fixing it.");
867
+ if (attempt.state === "closed" && attempt.admission && attempt.worktreeId && attempt.sessionId) return {
868
+ worktreeId: attempt.worktreeId,
869
+ sessionId: attempt.sessionId,
870
+ branch: attempt.branch,
871
+ admission: attempt.admission
872
+ };
873
+ throw new WorktreeWorkflowError("unknown", "This attempt may have created work. Its checkout is absent or orphaned and will not be recreated.");
874
+ }
875
+ const admission = await admissions.read(input.attemptId);
876
+ if (!admission) throw new WorktreeWorkflowError("unknown", "This attempt has no authoritative admission outcome. Its checkout was kept.");
877
+ return link(record, attempt, admission);
878
+ }
879
+ let report;
880
+ try {
881
+ report = await admissions.validate({
882
+ kind: "launch",
883
+ definition: input.definition,
884
+ ...input.overrides ? { overrides: input.overrides } : {}
885
+ });
886
+ } catch (error) {
887
+ await update({
888
+ ...attempt,
889
+ state: "rejected"
890
+ }, signal);
891
+ throw new WorktreeWorkflowError("not_started", "Workflow validation failed before checkout creation.", { cause: error });
892
+ }
893
+ const frozen = input.overrides?.allocation;
894
+ const refusal = report.errors.length ? `The workflow is not valid: ${report.errors.map((issue) => issue.message).join("; ")}` : report.allocation === void 0 ? void 0 : frozen === void 0 ? "This role-bound workflow needs an allocation prepared before the checkout, and none was supplied." : JSON.stringify(canonical(report.allocation)) !== JSON.stringify(canonical(frozen)) ? "The workflow allocation changed since it was prepared." : void 0;
895
+ if (refusal) {
896
+ await update({
897
+ ...attempt,
898
+ state: "rejected"
899
+ }, signal);
900
+ throw new WorktreeWorkflowError("not_started", refusal);
901
+ }
902
+ operation(signal).signal.throwIfAborted();
903
+ try {
904
+ record = await options.operations.spawn(context, {
905
+ branch,
906
+ ...input.sparseProfile ? { sparseProfile: input.sparseProfile } : {}
907
+ }, {
908
+ workflow: {
909
+ attemptId: input.attemptId,
910
+ fingerprint
911
+ },
912
+ ...input.preset ? { preset: input.preset } : {},
913
+ signal: operation(signal).signal
914
+ });
915
+ await update({
916
+ ...attempt,
917
+ worktreeId: record.id,
918
+ sessionId: record.sessionId,
919
+ state: "spawned"
920
+ });
921
+ const base = remoteBase(record);
922
+ if (!base) throw new WorktreeWorkflowError("not_started", "The workflow base is not a verifiable remote branch. The checkout was kept.");
923
+ const pending = {
924
+ ...attempt,
925
+ worktreeId: record.id,
926
+ sessionId: record.sessionId,
927
+ state: "admitting"
928
+ };
929
+ await update(pending);
930
+ const admission = await admissions.launch(input.attemptId, input.definition, {
931
+ ...input.overrides,
932
+ env: {
933
+ ...input.overrides?.env,
934
+ SPARO_BASE_REMOTE: base.remote,
935
+ SPARO_BASE_BRANCH: base.branch,
936
+ SPARO_BASE_SHA: base.sha,
937
+ SPARO_BRANCH: record.branch,
938
+ PO_GIT_BASE_REMOTE: base.remote,
939
+ PO_GIT_BASE_BRANCH: base.branch,
940
+ PO_GIT_BASE_SHA: base.sha,
941
+ PO_GIT_BRANCH: record.branch
942
+ },
943
+ targetSessionId: record.sessionId
944
+ });
945
+ return await link(record, pending, admission);
946
+ } catch (error) {
947
+ if (error instanceof WorktreeWorkflowError) throw error;
948
+ throw new WorktreeWorkflowError("unknown", "The workflow launch outcome is uncertain. Inspect the saved attempt before retrying.", { cause: error });
949
+ }
950
+ };
951
+ return {
952
+ start(input, signal) {
953
+ options.signal.throwIfAborted();
954
+ signal?.throwIfAborted();
955
+ if (!input || typeof input.attemptId !== "string" || !input.attemptId.trim() || !Check(PoWorkflowDefinitionRefSchema, input.definition) || input.definition.source !== "repo" || input.sparseProfile !== void 0 && !validSparseProfile(input.sparseProfile)) return Promise.reject(new WorktreeWorkflowError("not_started", "A valid repository workflow and attempt identity are required."));
956
+ const snapshot = structuredClone(input);
957
+ const branch = snapshot.branch ?? defaultBranch(snapshot);
958
+ if (!validRefName(branch)) return Promise.reject(new WorktreeWorkflowError("not_started", "The workflow branch is invalid."));
959
+ const fingerprint = createHash("sha256").update(JSON.stringify(canonical({
960
+ definition: snapshot.definition,
961
+ branch,
962
+ profile: snapshot.sparseProfile,
963
+ preset: snapshot.preset,
964
+ overrides: snapshot.overrides
965
+ }))).digest("hex");
966
+ const existing = inFlight.get(snapshot.attemptId);
967
+ if (existing) return existing.fingerprint === fingerprint ? existing.promise : Promise.reject(new WorktreeWorkflowError("attempt_conflict", "This workflow attempt is already starting with different arguments."));
968
+ const promise = start(snapshot, branch, fingerprint, signal).finally(() => {
969
+ inFlight.delete(snapshot.attemptId);
970
+ });
971
+ inFlight.set(snapshot.attemptId, {
972
+ fingerprint,
973
+ promise
974
+ });
975
+ return promise;
976
+ },
977
+ async reconcile(signal) {
978
+ operation(signal).signal.throwIfAborted();
979
+ const admissions = options.admissions();
980
+ if (!admissions) return;
981
+ const records = await ownRecords();
982
+ const registry = await store();
983
+ const attempts = await registry.transaction(() => registry.workflowAttempts(), operation(signal).signal);
984
+ for (const attempt of attempts.filter((entry) => entry.launcherSessionId === options.sessionId && ![
985
+ "closed",
986
+ "rejected",
987
+ "retained"
988
+ ].includes(entry.state))) {
989
+ const record = records.find((entry) => entry.id === attempt.worktreeId || entry.workflow.attemptId === attempt.attemptId);
990
+ if (!record || record.status === "orphaned") continue;
991
+ try {
992
+ const admission = await admissions.read(attempt.attemptId);
993
+ if (admission) await link(record, attempt, admission);
994
+ } catch (error) {
995
+ options.onError(error);
996
+ }
997
+ }
998
+ }
999
+ };
1000
+ }
1001
+ //#endregion
295
1002
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
296
1003
  function progressResult(action, label) {
297
1004
  return {
@@ -302,33 +1009,82 @@ function progressResult(action, label) {
302
1009
  details: { action }
303
1010
  };
304
1011
  }
305
- function createGitSession({ context, host: serverHost }) {
1012
+ /** Tools that only read, so the checkout cannot have moved under them. */
1013
+ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
1014
+ "read",
1015
+ "grep",
1016
+ "find",
1017
+ "ls",
1018
+ "discover",
1019
+ "load_skill"
1020
+ ]);
1021
+ async function createGitSession({ context, host: serverHost, agent, signal }) {
306
1022
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
307
1023
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
308
1024
  const sessionId = serverHost.context.sessionId;
309
1025
  const directEvents = serverHost.context.directEvents;
310
1026
  const messageInbox = createWorktreeMessageInbox(directEvents, sessionId);
1027
+ const setupReceiver = context.inject(["po/runner-launch"], (child) => {
1028
+ const runner = child.get("po/runner-launch");
1029
+ const cwd = serverHost.context.cwd;
1030
+ if (!runner || !cwd) return void 0;
1031
+ return receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal);
1032
+ });
311
1033
  const operations = createWorktreeOperations({
312
1034
  git: createWorktreeGit(),
1035
+ ...createGitOperationDependencies({
1036
+ context,
1037
+ host: serverHost,
1038
+ signal
1039
+ }),
313
1040
  sessionService: serverHost.context.sessionService,
314
1041
  messageInbox,
315
1042
  sessionDelivery: () => readPoSessionDelivery(context)
316
1043
  });
1044
+ const homeDirectory = serverHost.context.homeDirectory ?? serverHost.context.environment?.HOME;
1045
+ let workflows;
1046
+ const workflowProvider = context.inject([PO_SERVER_SCOPE_SERVICE], async (scoped) => {
1047
+ if (!homeDirectory || !serverHost.context.cwd) return void 0;
1048
+ const lifetime = new AbortController();
1049
+ const service = createWorktreeWorkflows({
1050
+ sessionId,
1051
+ cwd: serverHost.context.cwd,
1052
+ homeDirectory,
1053
+ environment: serverHost.context.environment ?? {},
1054
+ signal: AbortSignal.any([signal, lifetime.signal]),
1055
+ operations,
1056
+ git: {
1057
+ ...createWorktreeGit(),
1058
+ revision,
1059
+ remoteBranchHead
1060
+ },
1061
+ admissions: () => readPoWorkflowAdmissionsService(scoped),
1062
+ runs: () => readPoWorkflowRunsService(scoped),
1063
+ onError: (error) => serverHost.context.onNotice(`Workflow checkout retained (${error instanceof Error ? error.name : "unknown error"}).`)
1064
+ });
1065
+ const release = await requirePoServerScope(scoped).provide(GIT_WORKFLOWS_CONTRACT, service);
1066
+ workflows = service;
1067
+ return async () => {
1068
+ if (workflows === service) workflows = void 0;
1069
+ lifetime.abort();
1070
+ await release();
1071
+ };
1072
+ });
1073
+ if (context.get(PO_SERVER_SCOPE_SERVICE) !== void 0) await workflowProvider.await();
1074
+ const workflowServices = context.inject([PO_WORKFLOW_ADMISSIONS_SERVICE, PO_WORKFLOW_RUNS_SERVICE], async () => {
1075
+ try {
1076
+ await workflows?.reconcile();
1077
+ } catch (error) {
1078
+ serverHost.context.onNotice(`Workflow reconciliation deferred (${error instanceof Error ? error.name : "unknown error"}).`);
1079
+ }
1080
+ });
317
1081
  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",
1082
+ name: "codemode-how-to-git",
1083
+ 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
1084
  kind: "skill",
331
- read: () => readPackageResource(import.meta.url, "src/prompts/po-use-git/SKILL.md")
1085
+ pinned: true,
1086
+ path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-git/SKILL.md"),
1087
+ read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-git/SKILL.md")
332
1088
  }];
333
1089
  const tool = {
334
1090
  name: RUN_WORKTREE_TOOL_NAME,
@@ -348,19 +1104,49 @@ function createGitSession({ context, host: serverHost }) {
348
1104
  const changed = (_event, execution) => {
349
1105
  directEvents.publish(GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
350
1106
  };
1107
+ const hooks = [defineHook({
1108
+ name: "git-notify-checkout-after-tool",
1109
+ description: "Notify the session diff channel after tools that may change the checkout.",
1110
+ event: "tool_execution_end",
1111
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
1112
+ }), defineHook({
1113
+ name: "git-notify-checkout-when-settled",
1114
+ description: "Notify the session diff channel when the agent settles to refresh checkout changes.",
1115
+ event: "agent_settled",
1116
+ handle: changed
1117
+ })];
1118
+ if (agent) {
1119
+ const namespace = createWorktreeNamespace({
1120
+ operations,
1121
+ workflows: () => workflows,
1122
+ execution: agent.context,
1123
+ assertAvailable: () => {
1124
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
1125
+ }
1126
+ });
1127
+ context.inject([PO_CODEMODE_SERVICE], (scoped) => {
1128
+ const codemode = readPoCodemode(scoped);
1129
+ if (!codemode) return void 0;
1130
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
1131
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
1132
+ return () => {
1133
+ restriction.dispose();
1134
+ registration.dispose();
1135
+ };
1136
+ });
1137
+ }
351
1138
  return {
352
1139
  value: {
353
1140
  resources,
354
1141
  tool,
355
- hooks: [{
356
- event: "tool_execution_end",
357
- handle: changed
358
- }, {
359
- event: "agent_settled",
360
- handle: changed
361
- }]
1142
+ hooks
362
1143
  },
363
- onDispose: () => messageInbox.close()
1144
+ onDispose: async () => {
1145
+ await workflowServices.dispose();
1146
+ await workflowProvider.dispose();
1147
+ await setupReceiver.dispose();
1148
+ messageInbox.close();
1149
+ }
364
1150
  };
365
1151
  }
366
1152
  const root = defineRoot(createGitSession);
@@ -399,12 +1185,12 @@ async function read(cwd, args) {
399
1185
  const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
400
1186
  return result.code === 0 ? result.stdout : void 0;
401
1187
  }
402
- async function readLine$1(cwd, args) {
1188
+ async function readLine(cwd, args) {
403
1189
  const out = (await read(cwd, args))?.trim();
404
1190
  return out === void 0 || out === "" ? void 0 : out;
405
1191
  }
406
1192
  async function commitExists(cwd, ref) {
407
- return await readLine$1(cwd, [
1193
+ return await readLine(cwd, [
408
1194
  "rev-parse",
409
1195
  "--verify",
410
1196
  "--quiet",
@@ -413,7 +1199,7 @@ async function commitExists(cwd, ref) {
413
1199
  }
414
1200
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
415
1201
  async function upstreamOf(cwd, ref) {
416
- return readLine$1(cwd, [
1202
+ return readLine(cwd, [
417
1203
  "rev-parse",
418
1204
  "--abbrev-ref",
419
1205
  "--symbolic-full-name",
@@ -422,13 +1208,13 @@ async function upstreamOf(cwd, ref) {
422
1208
  }
423
1209
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
424
1210
  async function resolveBaseRef(cwd, branch, recordedBaseRef) {
425
- if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
1211
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
426
1212
  "rev-parse",
427
1213
  "--verify",
428
1214
  "--quiet",
429
1215
  `refs/heads/${recordedBaseRef}`
430
1216
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
431
- const originHead = await readLine$1(cwd, [
1217
+ const originHead = await readLine(cwd, [
432
1218
  "symbolic-ref",
433
1219
  "--quiet",
434
1220
  "--short",
@@ -442,7 +1228,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
442
1228
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
443
1229
  const head = await commitExists(cwd, "HEAD");
444
1230
  if (ref !== void 0 && head) {
445
- const mergeBase = await readLine$1(cwd, [
1231
+ const mergeBase = await readLine(cwd, [
446
1232
  "merge-base",
447
1233
  ref,
448
1234
  "HEAD"
@@ -469,11 +1255,11 @@ const NAME_STATUS = {
469
1255
  T: "modified"
470
1256
  };
471
1257
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
472
- function untrackedLines(root, relPath) {
1258
+ async function untrackedLines(root, relPath) {
473
1259
  const absolute = path.join(root, relPath);
474
1260
  let stat;
475
1261
  try {
476
- stat = fs.lstatSync(absolute);
1262
+ stat = await fs.lstat(absolute);
477
1263
  } catch {
478
1264
  return;
479
1265
  }
@@ -482,7 +1268,7 @@ function untrackedLines(root, relPath) {
482
1268
  binary: false
483
1269
  };
484
1270
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
485
- const content = fs.readFileSync(absolute);
1271
+ const content = await fs.readFile(absolute);
486
1272
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
487
1273
  lines: 0,
488
1274
  binary: true
@@ -554,9 +1340,9 @@ function parseUnifiedDiff(diff) {
554
1340
  function createBranchDiff() {
555
1341
  return {
556
1342
  async review(cwd, options = {}) {
557
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1343
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
558
1344
  if (root === void 0) return void 0;
559
- const branch = await readLine$1(root, [
1345
+ const branch = await readLine(root, [
560
1346
  "symbolic-ref",
561
1347
  "--quiet",
562
1348
  "--short",
@@ -605,8 +1391,8 @@ function createBranchDiff() {
605
1391
  "--exclude-standard",
606
1392
  "-z"
607
1393
  ]));
608
- untracked.forEach((relPath, index) => {
609
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
1394
+ for (const [index, relPath] of untracked.entries()) {
1395
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
610
1396
  entries.push({
611
1397
  path: relPath,
612
1398
  status: "untracked",
@@ -614,22 +1400,24 @@ function createBranchDiff() {
614
1400
  removed: 0,
615
1401
  ...counted?.binary ? { binary: true } : {}
616
1402
  });
617
- });
1403
+ }
618
1404
  entries.sort((left, right) => left.path.localeCompare(right.path));
619
1405
  const conflicts = [...unmerged];
620
- const rebasing = [await readLine$1(root, [
1406
+ const rebaseMerge = await readLine(root, [
621
1407
  "rev-parse",
622
1408
  "--git-path",
623
1409
  "rebase-merge"
624
- ]), await readLine$1(root, [
1410
+ ]);
1411
+ const rebaseApply = await readLine(root, [
625
1412
  "rev-parse",
626
1413
  "--git-path",
627
1414
  "rebase-apply"
628
- ])].some((gitPath) => gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath)));
1415
+ ]);
1416
+ 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
1417
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
630
1418
  let upstream;
631
1419
  if (upstreamRef !== void 0) {
632
- const [behind, ahead] = (await readLine$1(root, [
1420
+ const [behind, ahead] = (await readLine(root, [
633
1421
  "rev-list",
634
1422
  "--left-right",
635
1423
  "--count",
@@ -670,7 +1458,7 @@ function createBranchDiff() {
670
1458
  if (entry === void 0) throw new Error("That path is not in this review.");
671
1459
  if (entry.status === "untracked") {
672
1460
  const absolute = path.join(review.root, entry.path);
673
- const stat = fs.lstatSync(absolute);
1461
+ const stat = await fs.lstat(absolute);
674
1462
  if (stat.isSymbolicLink()) return {
675
1463
  path: entry.path,
676
1464
  hunks: [{
@@ -678,7 +1466,7 @@ function createBranchDiff() {
678
1466
  rows: [{
679
1467
  marker: "+",
680
1468
  line: 1,
681
- content: fs.readlinkSync(absolute)
1469
+ content: await fs.readlink(absolute)
682
1470
  }]
683
1471
  }]
684
1472
  };
@@ -687,7 +1475,7 @@ function createBranchDiff() {
687
1475
  hunks: [],
688
1476
  tooLarge: true
689
1477
  };
690
- const content = fs.readFileSync(absolute);
1478
+ const content = await fs.readFile(absolute);
691
1479
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
692
1480
  path: entry.path,
693
1481
  hunks: [],
@@ -776,7 +1564,6 @@ const LOOSE_BITS = 63;
776
1564
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
777
1565
  const MAX_USERNAME = 256;
778
1566
  const MAX_TOKEN = 4096;
779
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
780
1567
  /** Environment that would make git log or skip what this module relies on. */
781
1568
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
782
1569
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -804,9 +1591,9 @@ function isRecord(value) {
804
1591
  return typeof value === "object" && value !== null && !Array.isArray(value);
805
1592
  }
806
1593
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
807
- function workspaceKey(workspaceRoot) {
1594
+ async function workspaceKey(workspaceRoot) {
808
1595
  try {
809
- return fs.realpathSync(workspaceRoot);
1596
+ return await fs.realpath(workspaceRoot);
810
1597
  } catch {
811
1598
  return path.resolve(workspaceRoot);
812
1599
  }
@@ -855,7 +1642,7 @@ function publicView(config) {
855
1642
  * the saved one, and only for the same host: a token never follows a host it
856
1643
  * was not entered for.
857
1644
  */
858
- function parseGitAuthSave(request, current, homeDir) {
1645
+ async function parseGitAuthSave(request, current, homeDir) {
859
1646
  if (!isRecord(request)) throw invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
860
1647
  if (request.method === "none") return { method: "none" };
861
1648
  if (request.method === "ssh") {
@@ -865,7 +1652,7 @@ function parseGitAuthSave(request, current, homeDir) {
865
1652
  if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
866
1653
  let isFile = false;
867
1654
  try {
868
- isFile = fs.statSync(expandHome(keyPath, homeDir)).isFile();
1655
+ isFile = (await fs.stat(expandHome(keyPath, homeDir))).isFile();
869
1656
  } catch {
870
1657
  isFile = false;
871
1658
  }
@@ -900,16 +1687,16 @@ function parseGitAuthSave(request, current, homeDir) {
900
1687
  throw invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
901
1688
  }
902
1689
  /** Tightens a file or folder something left readable by group or others. */
903
- function tighten(target, mode) {
1690
+ async function tighten(target, mode) {
904
1691
  try {
905
- if ((fs.statSync(target).mode & LOOSE_BITS) !== 0) fs.chmodSync(target, mode);
1692
+ if (((await fs.stat(target)).mode & LOOSE_BITS) !== 0) await fs.chmod(target, mode);
906
1693
  } catch {}
907
1694
  }
908
- function createGitAuthStore(homeDir = os.homedir()) {
909
- const file = credentialsFile(homeDir);
910
- const readFile = () => {
911
- tighten(file, OWNER_ONLY_FILE);
912
- const raw = readJson(file);
1695
+ function createGitAuthStore(homeDir = os.homedir(), environment = {}) {
1696
+ const file = credentialsFile(homeDir, environment);
1697
+ const readFile = async () => {
1698
+ await tighten(file, OWNER_ONLY_FILE);
1699
+ const raw = await readJson(file);
913
1700
  const workspaces = {};
914
1701
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
915
1702
  const config = parseConfig(value);
@@ -920,28 +1707,28 @@ function createGitAuthStore(homeDir = os.homedir()) {
920
1707
  workspaces
921
1708
  };
922
1709
  };
923
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1710
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
924
1711
  return {
925
1712
  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);
931
- const root = poGitRoot(homeDir);
932
- fs.mkdirSync(root, {
1713
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1714
+ async save(workspaceRoot, request) {
1715
+ const key = await workspaceKey(workspaceRoot);
1716
+ const current = await readFile();
1717
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1718
+ const root = poGitRoot(homeDir, environment);
1719
+ await fs.mkdir(root, {
933
1720
  recursive: true,
934
1721
  mode: OWNER_ONLY_DIRECTORY
935
1722
  });
936
- fs.chmodSync(root, OWNER_ONLY_DIRECTORY);
1723
+ await fs.chmod(root, OWNER_ONLY_DIRECTORY);
937
1724
  const workspaces = { ...current.workspaces };
938
1725
  if (next.method === "none") delete workspaces[key];
939
1726
  else workspaces[key] = next;
940
- writeJsonAtomic(file, {
1727
+ await writeJsonAtomic(file, {
941
1728
  version: 1,
942
1729
  workspaces
943
1730
  });
944
- fs.chmodSync(file, OWNER_ONLY_FILE);
1731
+ await fs.chmod(file, OWNER_ONLY_FILE);
945
1732
  return publicView(next);
946
1733
  }
947
1734
  };
@@ -1040,252 +1827,14 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1040
1827
  };
1041
1828
  }
1042
1829
  //#endregion
1043
- //#region src/services/newSessionRequest/index.ts
1044
- const MAX_NAME_LENGTH = 120;
1045
- /** Trimmed text, undefined when absent or blank, false when not text at all. */
1046
- function optionalText(value) {
1047
- if (value === void 0) return void 0;
1048
- if (typeof value !== "string") return false;
1049
- const trimmed = value.trim();
1050
- return trimmed === "" ? void 0 : trimmed;
1051
- }
1052
- /**
1053
- * Validates a new-session dialog request for a worktree session. Every ref is
1054
- * checked here, before it can reach git as a positional argument.
1055
- */
1056
- function newSessionRequest(body) {
1057
- if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
1058
- const record = body;
1059
- const branch = optionalText(record.branch);
1060
- if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
1061
- const name = optionalText(record.name);
1062
- 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 };
1064
- if (record.mode === "existing-branch") {
1065
- const remote = optionalText(record.remote);
1066
- if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
1067
- return {
1068
- mode: "existing-branch",
1069
- branch,
1070
- ...remote === void 0 ? {} : { remote },
1071
- ...named
1072
- };
1073
- }
1074
- if (record.mode === "new-branch") {
1075
- const baseRef = optionalText(record.baseRef);
1076
- if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
1077
- return {
1078
- mode: "new-branch",
1079
- branch,
1080
- ...baseRef === void 0 ? {} : { baseRef },
1081
- ...named
1082
- };
1083
- }
1084
- return { error: "The mode must be existing-branch or new-branch." };
1085
- }
1086
- //#endregion
1087
- //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1088
- /**
1089
- * The worktree surface the cockpit panel calls.
1090
- *
1091
- * Hub-scoped because worktrees are a property of a repository, not of one
1092
- * session: the panel lists and creates them whether or not the session that
1093
- * made them is focused, and a session-scoped API would disappear with it.
1094
- *
1095
- * The panel names a repository by the hub's opaque id and never by path.
1096
- * `resolveRepository` turns that into an admitted root, so a browser cannot
1097
- * point this at a directory the cockpit was never given.
1098
- */
1099
- function badRequest(message) {
1100
- return Response.json({ error: message }, { status: 400 });
1101
- }
1102
- function failed(error) {
1103
- if (error instanceof PoGitExpectedError) return Response.json({
1104
- error: error.message,
1105
- code: error.code
1106
- }, { status: error.retryable ? 503 : 409 });
1107
- return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1108
- }
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
1120
- });
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)
1148
- };
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
1164
- };
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);
1238
- try {
1239
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1240
- if (answered !== void 0) return answered;
1241
- } catch (error) {
1242
- context.onNotice(`git request failed: ${error.name}`);
1243
- return failed(error);
1244
- }
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.");
1252
- 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 });
1264
- }
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 });
1270
- }
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() {}
1278
- };
1279
- }
1280
- });
1281
- //#endregion
1282
1830
  //#region src/services/gitFailure/index.ts
1831
+ const english = (_key, fallback, vars) => formatMessage(fallback, vars);
1283
1832
  const RULES = [
1284
1833
  {
1285
1834
  code: "host_key_changed",
1286
1835
  phrases: ["remote host identification has changed"],
1287
- message: "The remote's SSH host key changed since this machine last saw it.",
1288
- recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1836
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1837
+ recovery: (t) => t("git.failure.host_key_changed.recovery", "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal."),
1289
1838
  retryable: false
1290
1839
  },
1291
1840
  {
@@ -1295,8 +1844,8 @@ const RULES = [
1295
1844
  "no ed25519 host key is known",
1296
1845
  "no rsa host key is known"
1297
1846
  ],
1298
- message: "This machine does not trust the remote's SSH host key yet.",
1299
- recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1847
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1848
+ recovery: (t) => t("git.failure.host_key_unknown.recovery", "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again."),
1300
1849
  retryable: false
1301
1850
  },
1302
1851
  {
@@ -1313,15 +1862,15 @@ const RULES = [
1313
1862
  "unprotected private key",
1314
1863
  "invalid format"
1315
1864
  ],
1316
- message: "The remote refused the credentials.",
1317
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1865
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1866
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1318
1867
  retryable: false
1319
1868
  },
1320
1869
  {
1321
1870
  code: "repository_not_found",
1322
1871
  phrases: ["repository not found", "does not appear to be a git repository"],
1323
- message: "The remote repository was not found, or these credentials cannot see it.",
1324
- recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1872
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1873
+ recovery: (t) => t("git.failure.repository_not_found.recovery", "Check the remote URL and that the credentials have access. Open settings, then repository, then git remote."),
1325
1874
  retryable: false
1326
1875
  },
1327
1876
  {
@@ -1334,22 +1883,22 @@ const RULES = [
1334
1883
  "unable to access",
1335
1884
  "network is unreachable"
1336
1885
  ],
1337
- message: "The remote could not be reached.",
1338
- recovery: "Check the network and the remote URL, then try again.",
1886
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1887
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1339
1888
  retryable: true
1340
1889
  },
1341
1890
  {
1342
1891
  code: "push_lease_rejected",
1343
1892
  phrases: ["(stale info)"],
1344
- message: "The remote branch moved since your last fetch, so the force push was refused.",
1345
- recovery: "Pull to see the new commits, then decide whether to push again.",
1893
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1894
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1346
1895
  retryable: false
1347
1896
  },
1348
1897
  {
1349
1898
  code: "push_needs_force",
1350
1899
  phrases: ["(non-fast-forward)", "(fetch first)"],
1351
- message: "The remote branch has commits yours replaced, usually after a rebase.",
1352
- recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1900
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1901
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1353
1902
  retryable: false
1354
1903
  },
1355
1904
  {
@@ -1360,18 +1909,21 @@ const RULES = [
1360
1909
  "would be overwritten",
1361
1910
  "your index contains uncommitted changes"
1362
1911
  ],
1363
- message: "There are uncommitted changes in the way.",
1364
- recovery: "Commit or stash your changes first.",
1912
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1913
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1365
1914
  retryable: false
1366
1915
  }
1367
1916
  ];
1368
- function classifyGitFailure(operation, result, mismatch) {
1369
- if (result.timedOut) return new PoGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1917
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1918
+ if (result.timedOut) return new PoGitExpectedError("git_timeout", t("git.failure.timeout", "git {operation} took too long and was stopped.", { operation }), true, t("git.failure.timeoutRecovery", "Check the network, then try again."));
1370
1919
  const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1371
1920
  const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1372
- if (rule === void 0) return new PoGitExpectedError("git_failed", `git ${operation} failed (exit ${String(result.code)}).`, false, "Run the same command in a terminal in this checkout to see what git says.");
1373
- const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1374
- return new PoGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1921
+ if (rule === void 0) return new PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1922
+ operation,
1923
+ code: String(result.code)
1924
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1925
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1926
+ return new PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1375
1927
  }
1376
1928
  //#endregion
1377
1929
  //#region src/services/gitSync/index.ts
@@ -1396,59 +1948,66 @@ const DONE = { outcome: "done" };
1396
1948
  function expected(code, message, recovery) {
1397
1949
  return new PoGitExpectedError(code, message, false, recovery);
1398
1950
  }
1399
- async function readLine(cwd, args) {
1400
- const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
1401
- const out = result.stdout.trim();
1402
- return result.code === 0 && out !== "" ? out : void 0;
1403
- }
1404
- async function toplevel(cwd) {
1405
- const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1406
- if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1407
- return root;
1408
- }
1409
- async function rebasing(root) {
1410
- for (const name of ["rebase-merge", "rebase-apply"]) {
1411
- const gitPath = await readLine(root, [
1412
- "rev-parse",
1413
- "--git-path",
1414
- name
1951
+ function createGitSync(options) {
1952
+ const baseEnv = options.baseEnv ?? {};
1953
+ async function readLine(cwd, args) {
1954
+ const result = await runGit(cwd, args, {
1955
+ timeout: READ_TIMEOUT_MS,
1956
+ env: baseEnv
1957
+ });
1958
+ const out = result.stdout.trim();
1959
+ return result.code === 0 && out !== "" ? out : void 0;
1960
+ }
1961
+ async function toplevel(cwd) {
1962
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1963
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1964
+ return root;
1965
+ }
1966
+ async function rebasing(root) {
1967
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1968
+ const gitPath = await readLine(root, [
1969
+ "rev-parse",
1970
+ "--git-path",
1971
+ name
1972
+ ]);
1973
+ if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1974
+ }
1975
+ return false;
1976
+ }
1977
+ async function conflicts(root) {
1978
+ return (await runGit(root, [
1979
+ "diff",
1980
+ "--name-only",
1981
+ "--diff-filter=U",
1982
+ "-z"
1983
+ ], {
1984
+ timeout: READ_TIMEOUT_MS,
1985
+ env: baseEnv
1986
+ })).stdout.split("\0").filter((file) => file !== "");
1987
+ }
1988
+ async function currentBranch(root) {
1989
+ const branch = await readLine(root, [
1990
+ "symbolic-ref",
1991
+ "--quiet",
1992
+ "--short",
1993
+ "HEAD"
1415
1994
  ]);
1416
- if (gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath))) return true;
1995
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1996
+ return branch;
1417
1997
  }
1418
- return false;
1419
- }
1420
- async function conflicts(root) {
1421
- return (await runGit(root, [
1422
- "diff",
1423
- "--name-only",
1424
- "--diff-filter=U",
1425
- "-z"
1426
- ], { timeout: READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1427
- }
1428
- async function currentBranch(root) {
1429
- const branch = await readLine(root, [
1430
- "symbolic-ref",
1431
- "--quiet",
1432
- "--short",
1433
- "HEAD"
1434
- ]);
1435
- if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1436
- return branch;
1437
- }
1438
- async function guard(root, needsCleanTree) {
1439
- if (await rebasing(root)) throw expected("rebase_in_progress", "A rebase is paused in this checkout.", "Ask the agent to resolve it, or abort the rebase.");
1440
- const branch = await currentBranch(root);
1441
- if (needsCleanTree) {
1442
- if (await readLine(root, [
1443
- "status",
1444
- "--porcelain",
1445
- "--untracked-files=no"
1446
- ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
1998
+ async function guard(root, needsCleanTree) {
1999
+ if (await rebasing(root)) throw expected("rebase_in_progress", "A rebase is paused in this checkout.", "Ask the agent to resolve it, or abort the rebase.");
2000
+ const branch = await currentBranch(root);
2001
+ if (needsCleanTree) {
2002
+ if (await readLine(root, [
2003
+ "status",
2004
+ "--porcelain",
2005
+ "--untracked-files=no"
2006
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2007
+ }
2008
+ return branch;
1447
2009
  }
1448
- return branch;
1449
- }
1450
- function createGitSync(options) {
1451
- const baseEnv = options.baseEnv ?? process.env;
2010
+ const baselines = /* @__PURE__ */ new Map();
1452
2011
  /** One credentialed network command against `remote`, classified on failure. */
1453
2012
  const network = async (root, context, remote, operation, args, urlArgs = []) => {
1454
2013
  const url = await readLine(root, [
@@ -1461,26 +2020,42 @@ function createGitSync(options) {
1461
2020
  const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1462
2021
  const result = await runGit(root, args, {
1463
2022
  timeout: NETWORK_TIMEOUT_MS,
1464
- env: prepared.env
2023
+ env: prepared.env,
2024
+ ...context.signal ? { signal: context.signal } : {}
1465
2025
  });
1466
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
2026
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
1467
2027
  };
1468
2028
  /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1469
- const rebaseOnto = async (root, onto) => {
2029
+ const rebaseOnto = async (root, onto, context) => {
2030
+ context.signal?.throwIfAborted();
2031
+ const before = baselines.get(root) ?? await revision(root, "HEAD", {
2032
+ env: baseEnv,
2033
+ ...context.signal ? { signal: context.signal } : {}
2034
+ });
2035
+ baselines.set(root, before);
1470
2036
  const result = await runGit(root, ["rebase", onto], {
1471
2037
  timeout: REBASE_TIMEOUT_MS,
2038
+ ...context.signal ? { signal: context.signal } : {},
1472
2039
  env: {
1473
2040
  ...baseEnv,
1474
2041
  GIT_EDITOR: "true",
1475
2042
  GIT_TERMINAL_PROMPT: "0"
1476
2043
  }
1477
2044
  });
1478
- if (result.code === 0) return DONE;
2045
+ if (result.code === 0) {
2046
+ if (before !== await revision(root, "HEAD", {
2047
+ env: baseEnv,
2048
+ ...context.signal ? { signal: context.signal } : {}
2049
+ })) await options.reapplySparse?.(root, context.signal);
2050
+ baselines.delete(root);
2051
+ return DONE;
2052
+ }
1479
2053
  if (await rebasing(root)) return {
1480
2054
  outcome: "paused",
1481
2055
  conflicts: await conflicts(root)
1482
2056
  };
1483
- throw classifyGitFailure("rebase", result);
2057
+ baselines.delete(root);
2058
+ throw classifyGitFailure("rebase", result, void 0, context.t);
1484
2059
  };
1485
2060
  /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1486
2061
  const remoteOfRef = async (root, ref) => {
@@ -1511,7 +2086,7 @@ function createGitSync(options) {
1511
2086
  "--prune",
1512
2087
  remote
1513
2088
  ]);
1514
- return rebaseOnto(root, upstream);
2089
+ return rebaseOnto(root, upstream, context);
1515
2090
  },
1516
2091
  async push(context, force) {
1517
2092
  const root = await toplevel(context.cwd);
@@ -1543,18 +2118,409 @@ function createGitSync(options) {
1543
2118
  "--prune",
1544
2119
  remote
1545
2120
  ]);
1546
- return rebaseOnto(root, base);
2121
+ return rebaseOnto(root, base, context);
1547
2122
  },
1548
2123
  async abortRebase(context) {
1549
2124
  const root = await toplevel(context.cwd);
1550
- if (!await rebasing(root)) return DONE;
1551
- const result = await runGit(root, ["rebase", "--abort"], { timeout: REBASE_TIMEOUT_MS });
1552
- if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
2125
+ if (!await rebasing(root)) {
2126
+ baselines.delete(root);
2127
+ return DONE;
2128
+ }
2129
+ const result = await runGit(root, ["rebase", "--abort"], {
2130
+ timeout: REBASE_TIMEOUT_MS,
2131
+ env: baseEnv,
2132
+ ...context.signal ? { signal: context.signal } : {}
2133
+ });
2134
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2135
+ baselines.delete(root);
1553
2136
  return DONE;
1554
2137
  }
1555
2138
  };
1556
2139
  }
1557
2140
  //#endregion
2141
+ //#region src/services/newSessionRequest/index.ts
2142
+ const MAX_NAME_LENGTH = 120;
2143
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2144
+ function optionalText(value) {
2145
+ if (value === void 0) return void 0;
2146
+ if (typeof value !== "string") return false;
2147
+ const trimmed = value.trim();
2148
+ return trimmed === "" ? void 0 : trimmed;
2149
+ }
2150
+ /**
2151
+ * Validates a new-session dialog request for a worktree session. Every ref is
2152
+ * checked here, before it can reach git as a positional argument.
2153
+ */
2154
+ function newSessionRequest(body) {
2155
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2156
+ const record = body;
2157
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2158
+ const branch = optionalText(record.branch);
2159
+ if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
2160
+ const name = optionalText(record.name);
2161
+ 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.` };
2162
+ if (Object.hasOwn(record, "sparseProfile") && !validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2163
+ const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
2164
+ if ("error" in chosen) return chosen;
2165
+ const profile = chosen.selection?.profile;
2166
+ const named = {
2167
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2168
+ ...name === void 0 ? {} : { name },
2169
+ ...profile === void 0 ? {} : { selection: { profile } }
2170
+ };
2171
+ if (record.mode === "existing-branch") {
2172
+ const remote = optionalText(record.remote);
2173
+ if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
2174
+ return {
2175
+ mode: "existing-branch",
2176
+ branch,
2177
+ ...remote === void 0 ? {} : { remote },
2178
+ ...named
2179
+ };
2180
+ }
2181
+ if (record.mode === "new-branch") {
2182
+ const baseRef = optionalText(record.baseRef);
2183
+ if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
2184
+ return {
2185
+ mode: "new-branch",
2186
+ branch,
2187
+ ...baseRef === void 0 ? {} : { baseRef },
2188
+ ...named
2189
+ };
2190
+ }
2191
+ return { error: "The mode must be existing-branch or new-branch." };
2192
+ }
2193
+ //#endregion
2194
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2195
+ /**
2196
+ * The worktree surface the cockpit panel calls.
2197
+ *
2198
+ * Hub-scoped because worktrees are a property of a repository, not of one
2199
+ * session: the panel lists and creates them whether or not the session that
2200
+ * made them is focused, and a session-scoped API would disappear with it.
2201
+ *
2202
+ * The panel names a repository by the hub's opaque id and never by path.
2203
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2204
+ * point this at a directory the cockpit was never given.
2205
+ */
2206
+ function badRequest(message) {
2207
+ return Response.json({ error: message }, { status: 400 });
2208
+ }
2209
+ function failed(error) {
2210
+ if (error instanceof PoGitExpectedError) return Response.json({
2211
+ error: error.message,
2212
+ code: error.code
2213
+ }, { status: error.retryable ? 503 : 409 });
2214
+ return Response.json({ error: "The worktree operation failed." }, { status: 500 });
2215
+ }
2216
+ function createGitApi(openDirectory, dependencies = {}, translate) {
2217
+ return {
2218
+ basePath: "git",
2219
+ start(context) {
2220
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
2221
+ const directEvents = context.directEvents;
2222
+ const publishLifecycle = (sessionId, repositoryRoot) => {
2223
+ directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
2224
+ version: 1,
2225
+ repositoryRoot
2226
+ });
2227
+ };
2228
+ const git = createWorktreeGit();
2229
+ const operations = createWorktreeOperations({
2230
+ ...dependencies,
2231
+ git,
2232
+ sessionService: context.sessionService,
2233
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
2234
+ ...context.environment === void 0 ? {} : { environment: context.environment }
2235
+ });
2236
+ const sync = createGitSync({
2237
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2238
+ baseEnv: context.environment ?? {},
2239
+ async reapplySparse(cwd, signal) {
2240
+ const record = (await createWorktreeRegistry(await registryFile(cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.path === cwd && entry.sessionId === context.sessionId);
2241
+ if (record?.sparseProfile) await operations.reapply({
2242
+ cwd,
2243
+ sessionId: context.sessionId
2244
+ }, record.id, { signal });
2245
+ }
2246
+ });
2247
+ const sessionCommand = async (request, url) => {
2248
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2249
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2250
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2251
+ const caller = {
2252
+ cwd: context.cwd,
2253
+ sessionId: context.sessionId
2254
+ };
2255
+ const body = await request.json().catch(() => void 0);
2256
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2257
+ const command = body;
2258
+ if (url.pathname === "/sync") {
2259
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2260
+ const recordedBaseRef = (await createWorktreeRegistry(await registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2261
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2262
+ const syncContext = {
2263
+ ...caller,
2264
+ auth,
2265
+ recordedBaseRef,
2266
+ signal: request.signal,
2267
+ ...translate ? { t: translate } : {}
2268
+ };
2269
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2270
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2271
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2272
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2273
+ return badRequest("Unknown sync command.");
2274
+ }
2275
+ if (Object.keys(command).some((key) => ![
2276
+ "action",
2277
+ "branch",
2278
+ "baseRef",
2279
+ "sparseProfile",
2280
+ "reservationId",
2281
+ "id",
2282
+ "force",
2283
+ "folders"
2284
+ ].includes(key))) return badRequest("Unknown command field.");
2285
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2286
+ if (command.action === "create") {
2287
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2288
+ const result = await operations.spawn(caller, {
2289
+ branch: command.branch,
2290
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2291
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2292
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2293
+ }, { signal: request.signal });
2294
+ return Response.json({ worktree: result });
2295
+ }
2296
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2297
+ if (![
2298
+ "profiles",
2299
+ "expand",
2300
+ "reapply"
2301
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2302
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2303
+ return Response.json(result.details);
2304
+ };
2305
+ /**
2306
+ * The new-session dialog's routes: the workspace's branches, and a top-level
2307
+ * worktree session on one. Workspace-mounted only, and always rooted at the
2308
+ * mount's own workspace, so a request can never name another directory.
2309
+ */
2310
+ const newSession = async (request, url) => {
2311
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
2312
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
2313
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
2314
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
2315
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
2316
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
2317
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2318
+ if (isBranches) {
2319
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2320
+ const branches = repositoryRoot === void 0 ? {
2321
+ repository: false,
2322
+ local: [],
2323
+ remote: []
2324
+ } : {
2325
+ repository: true,
2326
+ ...await git.listBranches(repositoryRoot),
2327
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
2328
+ };
2329
+ return Response.json(branches);
2330
+ }
2331
+ if (isDelete || isOpen) {
2332
+ if (isOpen && poApiCallerFrom(request.headers)?.locality !== "local") return Response.json({ error: "Opening Finder is only available on the host." }, { status: 403 });
2333
+ const body = await request.json().catch(() => void 0);
2334
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
2335
+ if (typeof branch !== "string" || !validRefName(branch)) return badRequest("A valid branch name is required.");
2336
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2337
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
2338
+ const branches = await git.listBranches(repositoryRoot);
2339
+ const local = branches.local.find((item) => item.name === branch);
2340
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
2341
+ if (isOpen) {
2342
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
2343
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
2344
+ try {
2345
+ await openDirectory(local.checkedOutAt);
2346
+ return Response.json({ opened: true });
2347
+ } catch {
2348
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
2349
+ }
2350
+ }
2351
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
2352
+ if (!await git.deleteBranch({
2353
+ repositoryRoot,
2354
+ branch
2355
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
2356
+ return Response.json({ deleted: true });
2357
+ }
2358
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
2359
+ if ("error" in parsed) return badRequest(parsed.error);
2360
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
2361
+ branch: parsed.branch,
2362
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
2363
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
2364
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
2365
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
2366
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
2367
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
2368
+ }, { signal: request.signal });
2369
+ publishLifecycle(record.sessionId, record.repositoryRoot);
2370
+ const created = {
2371
+ sessionId: record.sessionId,
2372
+ worktreeId: record.id
2373
+ };
2374
+ return Response.json(created, { status: 201 });
2375
+ };
2376
+ /** The admitted root for a request, or a response explaining why not. */
2377
+ const rootOf = (url) => {
2378
+ const repositoryId = url.searchParams.get("repositoryId");
2379
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
2380
+ const root = context.resolveRepository?.(repositoryId);
2381
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
2382
+ return root;
2383
+ };
2384
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
2385
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir, context.environment);
2386
+ const branchDiff = createBranchDiff();
2387
+ const pendingReviews = /* @__PURE__ */ new Map();
2388
+ /**
2389
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
2390
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
2391
+ * The view never carries the token.
2392
+ */
2393
+ const auth = async (request, url) => {
2394
+ if (url.pathname !== "/auth") return void 0;
2395
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2396
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
2397
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
2398
+ const root = rootOf(url);
2399
+ if (root instanceof Response) return root;
2400
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
2401
+ try {
2402
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
2403
+ } catch (error) {
2404
+ if (error instanceof PoGitExpectedError && error.code === "invalid_request") {
2405
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2406
+ return Response.json({
2407
+ error: text,
2408
+ code: error.code
2409
+ }, { status: 400 });
2410
+ }
2411
+ throw error;
2412
+ }
2413
+ };
2414
+ /**
2415
+ * The session's change against its base. Session mounts only, rooted at the
2416
+ * session's own checkout; a file is served only when it is in the change set
2417
+ * computed for the request. Overlapping requests share an in-flight snapshot.
2418
+ */
2419
+ const review = async (request, url) => {
2420
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
2421
+ const cwd = context.scope === "session" ? context.cwd : void 0;
2422
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2423
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
2424
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
2425
+ let recordedBaseRef;
2426
+ try {
2427
+ recordedBaseRef = (await createWorktreeRegistry(await registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
2428
+ } catch {
2429
+ recordedBaseRef = void 0;
2430
+ }
2431
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
2432
+ let pending = pendingReviews.get(key);
2433
+ if (pending === void 0) {
2434
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
2435
+ pendingReviews.set(key, pending);
2436
+ }
2437
+ const result = await pending;
2438
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
2439
+ repository: false,
2440
+ files: []
2441
+ });
2442
+ const filePath = url.searchParams.get("path") ?? "";
2443
+ 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 });
2444
+ return Response.json(await branchDiff.fileDiff(result, filePath));
2445
+ };
2446
+ return {
2447
+ async fetch(request) {
2448
+ const url = new URL(request.url);
2449
+ try {
2450
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2451
+ if (answered !== void 0) return answered;
2452
+ } catch (error) {
2453
+ context.onNotice(`git request failed: ${error.name}`);
2454
+ return failed(error);
2455
+ }
2456
+ const root = rootOf(url);
2457
+ if (root instanceof Response) return root;
2458
+ const callerContext = {
2459
+ cwd: root,
2460
+ sessionId: url.searchParams.get("sessionId") ?? ""
2461
+ };
2462
+ 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.");
2463
+ try {
2464
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
2465
+ if (request.method === "POST" && url.pathname === "/worktrees") {
2466
+ const body = await request.json();
2467
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
2468
+ const record = await operations.spawn(callerContext, {
2469
+ branch: body.branch,
2470
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
2471
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
2472
+ ...body.name === void 0 ? {} : { name: body.name }
2473
+ });
2474
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2475
+ return Response.json({ worktree: record }, { status: 201 });
2476
+ }
2477
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
2478
+ if (request.method === "DELETE" && closing) {
2479
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
2480
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2481
+ return Response.json({ worktree: record });
2482
+ }
2483
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
2484
+ } catch (error) {
2485
+ context.onNotice(`worktree request failed: ${error.name}`);
2486
+ return failed(error);
2487
+ }
2488
+ },
2489
+ close() {}
2490
+ };
2491
+ }
2492
+ };
2493
+ }
2494
+ //#endregion
2495
+ //#region src/extensions/(backend)/api/git/route.server.ts
2496
+ var route_server_default = defineRoute((plugin) => {
2497
+ const { context, host, signal } = plugin;
2498
+ let openDirectory;
2499
+ context.inject([PO_SHELL_SERVICE], (child) => {
2500
+ const shell = requirePoShell(child);
2501
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
2502
+ openDirectory = async (path) => {
2503
+ const result = await shell.exec([
2504
+ "/usr/bin/open",
2505
+ "-a",
2506
+ "Finder",
2507
+ path
2508
+ ], {
2509
+ env,
2510
+ inheritEnv: false
2511
+ }, withAbortSignal(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), BACKGROUND_CONTEXT));
2512
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
2513
+ };
2514
+ return () => {
2515
+ openDirectory = void 0;
2516
+ };
2517
+ });
2518
+ return createGitApi(async (path) => {
2519
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
2520
+ await openDirectory(path);
2521
+ }, createGitOperationDependencies(plugin), (key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(host.context.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars));
2522
+ });
2523
+ //#endregion
1558
2524
  //#region src/types/gitReview.ts
1559
2525
  /**
1560
2526
  * The cockpit's view of what this session changed against its base: the counts
@@ -1584,8 +2550,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1584
2550
  * - Apart from the worktrees channel. Worktrees are repository management;
1585
2551
  * this is the session's own code change.
1586
2552
  * - 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.
2553
+ * after every tool call that can write and every settled turn; a recount
2554
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
2555
+ * in flight plus one rerun.
1589
2556
  * - One sync command per session. A rebase and a push must never overlap.
1590
2557
  * - Auth is read fresh for each command from the session's workspace, and goes
1591
2558
  * only into that command's git child.
@@ -1594,6 +2561,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1594
2561
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1595
2562
  * stderr and drops it, because a remote URL in it can carry a token.
1596
2563
  */
2564
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
2565
+ const REFRESH_DELAY_MS = 1500;
1597
2566
  function payloadOf$1(state) {
1598
2567
  return {
1599
2568
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1638,17 +2607,19 @@ function createGitChangesChannel(options = {}) {
1638
2607
  const homeDir = options.homeDir ?? os.homedir();
1639
2608
  const diff = options.diff ?? createBranchDiff();
1640
2609
  const sync = options.sync ?? createGitSync({ homeDir });
1641
- const auth = options.auth ?? createGitAuthStore(homeDir);
2610
+ const auth = options.auth ?? createGitAuthStore(homeDir, options.environment);
1642
2611
  const latest = /* @__PURE__ */ new Map();
1643
2612
  const subscriptions = /* @__PURE__ */ new Map();
1644
2613
  const scopes = /* @__PURE__ */ new Map();
1645
2614
  const inFlight = /* @__PURE__ */ new Set();
1646
2615
  const rerun = /* @__PURE__ */ new Set();
1647
2616
  const busy = /* @__PURE__ */ new Set();
2617
+ const delayed = /* @__PURE__ */ new Map();
2618
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1648
2619
  /** The base the session's own worktree was created from, when it has one. */
1649
- const recordedBaseRef = (scope) => {
2620
+ const recordedBaseRef = async (scope) => {
1650
2621
  try {
1651
- return createWorktreeRegistry(registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
2622
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1652
2623
  } catch {
1653
2624
  return;
1654
2625
  }
@@ -1681,8 +2652,7 @@ function createGitChangesChannel(options = {}) {
1681
2652
  return;
1682
2653
  }
1683
2654
  inFlight.add(sessionId);
1684
- const base = recordedBaseRef(scope);
1685
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
2655
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1686
2656
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1687
2657
  }).catch((error) => {
1688
2658
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1691,18 +2661,41 @@ function createGitChangesChannel(options = {}) {
1691
2661
  if (rerun.delete(sessionId)) refresh(sessionId);
1692
2662
  });
1693
2663
  };
1694
- const run = (scope, command) => {
2664
+ /** Recounts once the session has been quiet for a moment. */
2665
+ const refreshSoon = (sessionId) => {
2666
+ clearTimeout(delayed.get(sessionId));
2667
+ const timer = setTimeout(() => {
2668
+ delayed.delete(sessionId);
2669
+ refresh(sessionId);
2670
+ }, refreshDelayMs);
2671
+ timer.unref?.();
2672
+ delayed.set(sessionId, timer);
2673
+ };
2674
+ const run = async (scope, command) => {
2675
+ if (options.scopedCommands) {
2676
+ const response = await host.requestSessionApi(scope, {
2677
+ basePath: "git",
2678
+ path: "/sync",
2679
+ method: "POST",
2680
+ body: JSON.stringify(command)
2681
+ });
2682
+ const result = await response.json();
2683
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2684
+ return result;
2685
+ }
1695
2686
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1696
- const base = recordedBaseRef(scope);
2687
+ const base = await recordedBaseRef(scope);
1697
2688
  const context = {
1698
2689
  cwd: scope.cwd,
1699
- auth: auth.read(workspaceRoot),
2690
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
2691
+ auth: await auth.read(workspaceRoot),
1700
2692
  ...base === void 0 ? {} : { recordedBaseRef: base }
1701
2693
  };
1702
- if (command.action === "pull") return sync.pull(context);
1703
- if (command.action === "push") return sync.push(context, command.force === true);
1704
- if (command.action === "rebase") return sync.rebase(context);
1705
- return sync.abortRebase(context);
2694
+ const sessionSync = sync;
2695
+ if (command.action === "pull") return sessionSync.pull(context);
2696
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2697
+ if (command.action === "rebase") return sessionSync.rebase(context);
2698
+ return sessionSync.abortRebase(context);
1706
2699
  };
1707
2700
  const source = {
1708
2701
  payloadFor(scope) {
@@ -1713,12 +2706,14 @@ function createGitChangesChannel(options = {}) {
1713
2706
  scopes.set(scope.sessionId, scope);
1714
2707
  refresh(scope.sessionId);
1715
2708
  const unsubscribe = host.directEvents.subscribe(GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1716
- if (isSessionChangedEvent(payload)) refresh(scope.sessionId);
2709
+ if (isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1717
2710
  });
1718
2711
  subscriptions.set(scope.sessionId, unsubscribe);
1719
2712
  },
1720
2713
  sessionRemoved(sessionId) {
1721
2714
  subscriptions.get(sessionId)?.();
2715
+ clearTimeout(delayed.get(sessionId));
2716
+ delayed.delete(sessionId);
1722
2717
  subscriptions.delete(sessionId);
1723
2718
  scopes.delete(sessionId);
1724
2719
  latest.delete(sessionId);
@@ -1727,6 +2722,8 @@ function createGitChangesChannel(options = {}) {
1727
2722
  },
1728
2723
  close() {
1729
2724
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2725
+ for (const timer of delayed.values()) clearTimeout(timer);
2726
+ delayed.clear();
1730
2727
  subscriptions.clear();
1731
2728
  scopes.clear();
1732
2729
  latest.clear();
@@ -1765,7 +2762,12 @@ function createGitChangesChannel(options = {}) {
1765
2762
  }
1766
2763
  //#endregion
1767
2764
  //#region src/extensions/(backend)/channel/git-changes.server.ts
1768
- var git_changes_server_default = defineChannel(createGitChangesChannel);
2765
+ var git_changes_server_default = defineChannel(({ context, host }) => createGitChangesChannel({
2766
+ homeDir: host.context.homeDirectory,
2767
+ environment: host.context.environment,
2768
+ scopedCommands: true,
2769
+ t: (scope, key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(scope.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars)
2770
+ }), { context: true });
1769
2771
  //#endregion
1770
2772
  //#region src/types/webWorktrees.ts
1771
2773
  /**
@@ -1794,9 +2796,9 @@ function payloadOf(state) {
1794
2796
  };
1795
2797
  }
1796
2798
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1797
- function viewsFor(scope, deps) {
2799
+ async function viewsFor(scope, deps) {
1798
2800
  try {
1799
- return createWorktreeRegistry(registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2801
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
1800
2802
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1801
2803
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1802
2804
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1821,11 +2823,15 @@ function sameList(left, right) {
1821
2823
  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
2824
  });
1823
2825
  }
1824
- function errorTargetFor(command) {
1825
- return command.action === "create" ? { action: "create" } : {
2826
+ function errorTargetFor(command, error) {
2827
+ if (command.action === "close") return {
1826
2828
  action: "close",
1827
2829
  id: command.id
1828
2830
  };
2831
+ return error instanceof PoGitExpectedError && error.code === "rift_missing" ? {
2832
+ action: "create",
2833
+ riftMissing: true
2834
+ } : { action: "create" };
1829
2835
  }
1830
2836
  /** A command the page sent, or undefined when the frame was not one. */
1831
2837
  function parseCommand(payload) {
@@ -1834,7 +2840,9 @@ function parseCommand(payload) {
1834
2840
  if (value.action === "create") {
1835
2841
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
1836
2842
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2843
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
1837
2844
  return {
2845
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
1838
2846
  action: "create",
1839
2847
  branch: value.branch.trim(),
1840
2848
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -1853,11 +2861,15 @@ function parseCommand(payload) {
1853
2861
  /**
1854
2862
  * What the reader is told when a command fails.
1855
2863
  *
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.
2864
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2865
+ * written for the agent's tool result. A dirty close is said in the person's
2866
+ * terms, because its message tells the agent to pass `force`. Anything else is
2867
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1858
2868
  */
1859
2869
  function failureText(error) {
1860
- return error instanceof PoGitExpectedError ? error.message : "The worktree operation failed.";
2870
+ if (!(error instanceof PoGitExpectedError)) return "The worktree operation failed.";
2871
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2872
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1861
2873
  }
1862
2874
  /** Starts one direct-event subscription per managed session. */
1863
2875
  function createWorktreesChannel(options = {}) {
@@ -1869,7 +2881,9 @@ function createWorktreesChannel(options = {}) {
1869
2881
  if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1870
2882
  const worktrees = options.operations ?? createWorktreeOperations({
1871
2883
  git: createWorktreeGit(),
1872
- sessionService
2884
+ sessionService,
2885
+ ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2886
+ ...options.environment === void 0 ? {} : { environment: options.environment }
1873
2887
  });
1874
2888
  /** Announces a successful mutation to this session's lifecycle subscribers. */
1875
2889
  const publishLifecycle = (scope, repositoryRoot) => {
@@ -1882,6 +2896,22 @@ function createWorktreesChannel(options = {}) {
1882
2896
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
1883
2897
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
1884
2898
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2899
+ if (options.scopedCommands) {
2900
+ if (!(await host.requestSessionApi(parent, {
2901
+ basePath: "git",
2902
+ path: "/session-worktrees",
2903
+ method: "POST",
2904
+ body: JSON.stringify({
2905
+ action: "create",
2906
+ branch,
2907
+ reservationId
2908
+ }),
2909
+ ...signal ? { signal } : {}
2910
+ })).ok) throw new Error("The conversation worktree could not be created.");
2911
+ const reservations = sessionService.reservations;
2912
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2913
+ return reservations.complete(reservationId, parentSessionId);
2914
+ }
1885
2915
  const record = await worktrees.spawn({
1886
2916
  cwd: parent.cwd,
1887
2917
  sessionId: parent.sessionId
@@ -1898,6 +2928,7 @@ function createWorktreesChannel(options = {}) {
1898
2928
  });
1899
2929
  const views = {
1900
2930
  homeDir: options.homeDir,
2931
+ environment: options.environment,
1901
2932
  sessionService
1902
2933
  };
1903
2934
  const latest = /* @__PURE__ */ new Map();
@@ -1910,10 +2941,13 @@ function createWorktreesChannel(options = {}) {
1910
2941
  return generation;
1911
2942
  };
1912
2943
  /** Republishes a session, skipping a frame that would say nothing new. */
1913
- const publish = (scope, force) => {
2944
+ const publish = async (scope, force) => {
2945
+ const generation = generations.get(scope.sessionId);
2946
+ const worktreeViews = await viewsFor(scope, views);
2947
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1914
2948
  const previous = latest.get(scope.sessionId);
1915
2949
  const next = {
1916
- worktrees: viewsFor(scope, views),
2950
+ worktrees: worktreeViews,
1917
2951
  pending: previous?.pending,
1918
2952
  error: previous?.error,
1919
2953
  errorTarget: previous?.errorTarget
@@ -1925,7 +2959,7 @@ function createWorktreesChannel(options = {}) {
1925
2959
  const mark = (scope, pending, error, errorTarget) => {
1926
2960
  const previous = latest.get(scope.sessionId);
1927
2961
  latest.set(scope.sessionId, {
1928
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2962
+ worktrees: previous?.worktrees ?? [],
1929
2963
  pending,
1930
2964
  error,
1931
2965
  errorTarget
@@ -1941,10 +2975,24 @@ function createWorktreesChannel(options = {}) {
1941
2975
  if (generations.get(scope.sessionId) !== generation) return;
1942
2976
  mark(scope, pending, error, errorTarget);
1943
2977
  };
2978
+ if (options.scopedCommands) {
2979
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2980
+ const response = await host.requestSessionApi(scope, {
2981
+ basePath: "git",
2982
+ path: "/session-worktrees",
2983
+ method: "POST",
2984
+ body: JSON.stringify(command)
2985
+ });
2986
+ const result = await response.json();
2987
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2988
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2989
+ return;
2990
+ }
1944
2991
  if (command.action === "create") {
1945
2992
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
1946
2993
  const record = await worktrees.spawn(context, {
1947
2994
  branch: command.branch,
2995
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
1948
2996
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
1949
2997
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
1950
2998
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -1965,15 +3013,15 @@ function createWorktreesChannel(options = {}) {
1965
3013
  sessionAdded(scope) {
1966
3014
  newGeneration(scope.sessionId);
1967
3015
  publish(scope, false);
1968
- const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
3016
+ const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
1969
3017
  if (!isWorktreeLifecycleEvent(payload)) return;
1970
3018
  let sameRepository = false;
1971
3019
  try {
1972
- sameRepository = registryFile(scope.cwd, options.homeDir) === registryFile(payload.repositoryRoot, options.homeDir);
3020
+ sameRepository = await registryFile(scope.cwd, options.homeDir, options.environment) === await registryFile(payload.repositoryRoot, options.homeDir, options.environment);
1973
3021
  } catch {
1974
3022
  sameRepository = false;
1975
3023
  }
1976
- if (sameRepository) publish(scope, false);
3024
+ if (sameRepository) await publish(scope, false);
1977
3025
  });
1978
3026
  subscriptions.set(scope.sessionId, unsubscribe);
1979
3027
  },
@@ -2006,7 +3054,7 @@ function createWorktreesChannel(options = {}) {
2006
3054
  }).catch((error) => {
2007
3055
  if (generations.get(scope.sessionId) !== generation) return;
2008
3056
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2009
- mark(scope, void 0, failureText(error), errorTargetFor(command));
3057
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2010
3058
  }).finally(() => {
2011
3059
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2012
3060
  });
@@ -2020,28 +3068,28 @@ function createWorktreesChannel(options = {}) {
2020
3068
  }
2021
3069
  //#endregion
2022
3070
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2023
- var git_worktrees_server_default = defineChannel(createWorktreesChannel);
3071
+ var git_worktrees_server_default = defineChannel((plugin) => createWorktreesChannel({
3072
+ homeDir: plugin.host.context.homeDirectory,
3073
+ environment: plugin.host.context.environment,
3074
+ scopedCommands: true
3075
+ }), { context: true });
2024
3076
  //#endregion
2025
3077
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2026
- var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
3078
+ var agent_settled_server_default = defineHook((context) => ({
3079
+ ...context.root.hooks[1],
3080
+ name: "git-notify-checkout-when-settled",
3081
+ description: "Notify the session diff channel when the agent settles to refresh checkout changes."
3082
+ }));
2027
3083
  //#endregion
2028
3084
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2029
- var tool_execution_end_server_default = defineHook((context) => context.root.hooks[0]);
2030
- //#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);
3085
+ var tool_execution_end_server_default = defineHook((context) => ({
3086
+ ...context.root.hooks[0],
3087
+ name: "git-notify-checkout-after-tool",
3088
+ description: "Notify the session diff channel after tools that may change the checkout."
3089
+ }));
2042
3090
  //#endregion
2043
3091
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2044
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
3092
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2045
3093
  //#endregion
2046
3094
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2047
3095
  var poUseGit_server_default = defineResource(poUseGit_server_default$1);
@@ -2053,60 +3101,77 @@ var runWorktree_server_default = defineServerTool((context) => context.root.tool
2053
3101
  const at = (value, context) => typeof value === "function" ? value(context) : value;
2054
3102
  /* v8 ignore next -- generated normalization branch */
2055
3103
  const defined = (values) => values.filter((value) => value !== void 0);
2056
- const via = (identity, value) => value === void 0 ? void 0 : {
2057
- ...identity,
2058
- ...value
3104
+ const via = (identity, value) => {
3105
+ if (value === void 0) return void 0;
3106
+ const declaration = value;
3107
+ return {
3108
+ ...identity,
3109
+ ...declaration,
3110
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
3111
+ evidence: "declared",
3112
+ ...relation
3113
+ })) }
3114
+ };
2059
3115
  };
2060
3116
  const serverPlugin = defineServerPlugin({
2061
3117
  name: "@agimon-ai/po-git",
2062
- providerOverrides: composeServerProviderOverrides(root_server_default),
2063
- injects: composeRootInjects({ session: [root_server_default] }),
2064
- global: (context) => ({
2065
- get api() {
2066
- return [at(route_server_default, context)];
2067
- },
2068
- get channels() {
2069
- return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
2070
- }
3118
+ providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
3119
+ injects: composeRootInjects({
3120
+ workspace: [root_server_default$1],
3121
+ session: [root_server_default$1, root_server_default]
2071
3122
  }),
2072
- workspace: (context) => ({
3123
+ host: (context) => ({
2073
3124
  get api() {
2074
3125
  return [at(route_server_default, context)];
2075
3126
  },
2076
3127
  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())]);
3128
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2078
3129
  }
2079
3130
  }),
3131
+ workspace: async (context) => {
3132
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3133
+ return {
3134
+ ...composeRootHooks(scopeWorkspace),
3135
+ get api() {
3136
+ return [at(route_server_default, context)];
3137
+ },
3138
+ get channels() {
3139
+ 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))]);
3140
+ },
3141
+ services: [...scopeWorkspace.services ?? []]
3142
+ };
3143
+ },
2080
3144
  session: async (context) => {
2081
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2082
- const contextSession = {
3145
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3146
+ const contextWorkspace = {
2083
3147
  ...context,
3148
+ root: scopeWorkspace.value
3149
+ };
3150
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3151
+ const contextSession = {
3152
+ ...contextWorkspace,
2084
3153
  root: scopeSession.value
2085
3154
  };
2086
3155
  return {
2087
- ...composeRootHooks(scopeSession),
3156
+ ...composeRootHooks(scopeWorkspace, scopeSession),
2088
3157
  get api() {
2089
3158
  return [at(route_server_default, context)];
2090
3159
  },
2091
3160
  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())]);
3161
+ 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
3162
  },
2094
3163
  get hooks() {
2095
3164
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2096
3165
  },
2097
3166
  get resources() {
2098
- return [
2099
- at(poGit_server_default, contextSession),
2100
- at(poGitReadme_server_default, contextSession),
2101
- at(poUseGit_server_default, contextSession)
2102
- ];
3167
+ return [at(poUseGit_server_default, contextSession)];
2103
3168
  },
2104
3169
  get tools() {
2105
3170
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2106
3171
  },
2107
- services: [...scopeSession.services ?? []],
3172
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2108
3173
  get activities() {
2109
- return [...scopeSession.activities ?? []];
3174
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2110
3175
  }
2111
3176
  };
2112
3177
  }