@agimon-ai/po-git 0.0.0-alpha.20 → 0.0.0-alpha.200

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 (36) hide show
  1. package/LICENSE +97 -8
  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 +2255 -544
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1553 -508
  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 +1512 -467
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +1747 -1374
  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/package.json +99 -21
  29. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  30. package/dist/index.cjs.map +0 -1
  31. package/dist/index.mjs.map +0 -1
  32. package/dist/worktreeOperations-Cd8Q12L4.mjs +0 -1064
  33. package/dist/worktreeOperations-Cd8Q12L4.mjs.map +0 -1
  34. package/dist/worktreeOperations-Dxs3txKL.cjs +0 -1220
  35. package/dist/worktreeOperations-Dxs3txKL.cjs.map +0 -1
  36. 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,45 @@ 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 = [{
1108
+ event: "tool_execution_end",
1109
+ handle: (event, execution) => READ_ONLY_TOOLS.has(event.toolName) ? void 0 : changed(event, execution)
1110
+ }, {
1111
+ event: "agent_settled",
1112
+ handle: changed
1113
+ }];
1114
+ if (agent) {
1115
+ const namespace = createWorktreeNamespace({
1116
+ operations,
1117
+ workflows: () => workflows,
1118
+ execution: agent.context,
1119
+ assertAvailable: () => {
1120
+ if (signal?.aborted) throw new Error("Git session is unavailable.");
1121
+ }
1122
+ });
1123
+ context.inject([PO_CODEMODE_SERVICE], (scoped) => {
1124
+ const codemode = readPoCodemode(scoped);
1125
+ if (!codemode) return void 0;
1126
+ const registration = codemode.register("@agimon-ai/po-git", namespace);
1127
+ const restriction = agent.registerToolRestriction({ excludedTools: [RUN_WORKTREE_TOOL_NAME] });
1128
+ return () => {
1129
+ restriction.dispose();
1130
+ registration.dispose();
1131
+ };
1132
+ });
1133
+ }
351
1134
  return {
352
1135
  value: {
353
1136
  resources,
354
1137
  tool,
355
- hooks: [{
356
- event: "tool_execution_end",
357
- handle: changed
358
- }, {
359
- event: "agent_settled",
360
- handle: changed
361
- }]
1138
+ hooks
362
1139
  },
363
- onDispose: () => messageInbox.close()
1140
+ onDispose: async () => {
1141
+ await workflowServices.dispose();
1142
+ await workflowProvider.dispose();
1143
+ await setupReceiver.dispose();
1144
+ messageInbox.close();
1145
+ }
364
1146
  };
365
1147
  }
366
1148
  const root = defineRoot(createGitSession);
@@ -399,12 +1181,12 @@ async function read(cwd, args) {
399
1181
  const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
400
1182
  return result.code === 0 ? result.stdout : void 0;
401
1183
  }
402
- async function readLine$1(cwd, args) {
1184
+ async function readLine(cwd, args) {
403
1185
  const out = (await read(cwd, args))?.trim();
404
1186
  return out === void 0 || out === "" ? void 0 : out;
405
1187
  }
406
1188
  async function commitExists(cwd, ref) {
407
- return await readLine$1(cwd, [
1189
+ return await readLine(cwd, [
408
1190
  "rev-parse",
409
1191
  "--verify",
410
1192
  "--quiet",
@@ -413,7 +1195,7 @@ async function commitExists(cwd, ref) {
413
1195
  }
414
1196
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
415
1197
  async function upstreamOf(cwd, ref) {
416
- return readLine$1(cwd, [
1198
+ return readLine(cwd, [
417
1199
  "rev-parse",
418
1200
  "--abbrev-ref",
419
1201
  "--symbolic-full-name",
@@ -422,13 +1204,13 @@ async function upstreamOf(cwd, ref) {
422
1204
  }
423
1205
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
424
1206
  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, [
1207
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
426
1208
  "rev-parse",
427
1209
  "--verify",
428
1210
  "--quiet",
429
1211
  `refs/heads/${recordedBaseRef}`
430
1212
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
431
- const originHead = await readLine$1(cwd, [
1213
+ const originHead = await readLine(cwd, [
432
1214
  "symbolic-ref",
433
1215
  "--quiet",
434
1216
  "--short",
@@ -442,7 +1224,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
442
1224
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
443
1225
  const head = await commitExists(cwd, "HEAD");
444
1226
  if (ref !== void 0 && head) {
445
- const mergeBase = await readLine$1(cwd, [
1227
+ const mergeBase = await readLine(cwd, [
446
1228
  "merge-base",
447
1229
  ref,
448
1230
  "HEAD"
@@ -469,11 +1251,11 @@ const NAME_STATUS = {
469
1251
  T: "modified"
470
1252
  };
471
1253
  /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
472
- function untrackedLines(root, relPath) {
1254
+ async function untrackedLines(root, relPath) {
473
1255
  const absolute = path.join(root, relPath);
474
1256
  let stat;
475
1257
  try {
476
- stat = fs.lstatSync(absolute);
1258
+ stat = await fs.lstat(absolute);
477
1259
  } catch {
478
1260
  return;
479
1261
  }
@@ -482,7 +1264,7 @@ function untrackedLines(root, relPath) {
482
1264
  binary: false
483
1265
  };
484
1266
  if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
485
- const content = fs.readFileSync(absolute);
1267
+ const content = await fs.readFile(absolute);
486
1268
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
487
1269
  lines: 0,
488
1270
  binary: true
@@ -554,9 +1336,9 @@ function parseUnifiedDiff(diff) {
554
1336
  function createBranchDiff() {
555
1337
  return {
556
1338
  async review(cwd, options = {}) {
557
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1339
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
558
1340
  if (root === void 0) return void 0;
559
- const branch = await readLine$1(root, [
1341
+ const branch = await readLine(root, [
560
1342
  "symbolic-ref",
561
1343
  "--quiet",
562
1344
  "--short",
@@ -605,8 +1387,8 @@ function createBranchDiff() {
605
1387
  "--exclude-standard",
606
1388
  "-z"
607
1389
  ]));
608
- untracked.forEach((relPath, index) => {
609
- const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
1390
+ for (const [index, relPath] of untracked.entries()) {
1391
+ const counted = index < MAX_UNTRACKED_COUNTED ? await untrackedLines(root, relPath) : void 0;
610
1392
  entries.push({
611
1393
  path: relPath,
612
1394
  status: "untracked",
@@ -614,22 +1396,24 @@ function createBranchDiff() {
614
1396
  removed: 0,
615
1397
  ...counted?.binary ? { binary: true } : {}
616
1398
  });
617
- });
1399
+ }
618
1400
  entries.sort((left, right) => left.path.localeCompare(right.path));
619
1401
  const conflicts = [...unmerged];
620
- const rebasing = [await readLine$1(root, [
1402
+ const rebaseMerge = await readLine(root, [
621
1403
  "rev-parse",
622
1404
  "--git-path",
623
1405
  "rebase-merge"
624
- ]), await readLine$1(root, [
1406
+ ]);
1407
+ const rebaseApply = await readLine(root, [
625
1408
  "rev-parse",
626
1409
  "--git-path",
627
1410
  "rebase-apply"
628
- ])].some((gitPath) => gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath)));
1411
+ ]);
1412
+ 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
1413
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
630
1414
  let upstream;
631
1415
  if (upstreamRef !== void 0) {
632
- const [behind, ahead] = (await readLine$1(root, [
1416
+ const [behind, ahead] = (await readLine(root, [
633
1417
  "rev-list",
634
1418
  "--left-right",
635
1419
  "--count",
@@ -670,7 +1454,7 @@ function createBranchDiff() {
670
1454
  if (entry === void 0) throw new Error("That path is not in this review.");
671
1455
  if (entry.status === "untracked") {
672
1456
  const absolute = path.join(review.root, entry.path);
673
- const stat = fs.lstatSync(absolute);
1457
+ const stat = await fs.lstat(absolute);
674
1458
  if (stat.isSymbolicLink()) return {
675
1459
  path: entry.path,
676
1460
  hunks: [{
@@ -678,7 +1462,7 @@ function createBranchDiff() {
678
1462
  rows: [{
679
1463
  marker: "+",
680
1464
  line: 1,
681
- content: fs.readlinkSync(absolute)
1465
+ content: await fs.readlink(absolute)
682
1466
  }]
683
1467
  }]
684
1468
  };
@@ -687,7 +1471,7 @@ function createBranchDiff() {
687
1471
  hunks: [],
688
1472
  tooLarge: true
689
1473
  };
690
- const content = fs.readFileSync(absolute);
1474
+ const content = await fs.readFile(absolute);
691
1475
  if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
692
1476
  path: entry.path,
693
1477
  hunks: [],
@@ -776,7 +1560,6 @@ const LOOSE_BITS = 63;
776
1560
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
777
1561
  const MAX_USERNAME = 256;
778
1562
  const MAX_TOKEN = 4096;
779
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
780
1563
  /** Environment that would make git log or skip what this module relies on. */
781
1564
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
782
1565
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -804,9 +1587,9 @@ function isRecord(value) {
804
1587
  return typeof value === "object" && value !== null && !Array.isArray(value);
805
1588
  }
806
1589
  /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
807
- function workspaceKey(workspaceRoot) {
1590
+ async function workspaceKey(workspaceRoot) {
808
1591
  try {
809
- return fs.realpathSync(workspaceRoot);
1592
+ return await fs.realpath(workspaceRoot);
810
1593
  } catch {
811
1594
  return path.resolve(workspaceRoot);
812
1595
  }
@@ -855,7 +1638,7 @@ function publicView(config) {
855
1638
  * the saved one, and only for the same host: a token never follows a host it
856
1639
  * was not entered for.
857
1640
  */
858
- function parseGitAuthSave(request, current, homeDir) {
1641
+ async function parseGitAuthSave(request, current, homeDir) {
859
1642
  if (!isRecord(request)) throw invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
860
1643
  if (request.method === "none") return { method: "none" };
861
1644
  if (request.method === "ssh") {
@@ -865,7 +1648,7 @@ function parseGitAuthSave(request, current, homeDir) {
865
1648
  if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
866
1649
  let isFile = false;
867
1650
  try {
868
- isFile = fs.statSync(expandHome(keyPath, homeDir)).isFile();
1651
+ isFile = (await fs.stat(expandHome(keyPath, homeDir))).isFile();
869
1652
  } catch {
870
1653
  isFile = false;
871
1654
  }
@@ -900,16 +1683,16 @@ function parseGitAuthSave(request, current, homeDir) {
900
1683
  throw invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
901
1684
  }
902
1685
  /** Tightens a file or folder something left readable by group or others. */
903
- function tighten(target, mode) {
1686
+ async function tighten(target, mode) {
904
1687
  try {
905
- if ((fs.statSync(target).mode & LOOSE_BITS) !== 0) fs.chmodSync(target, mode);
1688
+ if (((await fs.stat(target)).mode & LOOSE_BITS) !== 0) await fs.chmod(target, mode);
906
1689
  } catch {}
907
1690
  }
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);
1691
+ function createGitAuthStore(homeDir = os.homedir(), environment = {}) {
1692
+ const file = credentialsFile(homeDir, environment);
1693
+ const readFile = async () => {
1694
+ await tighten(file, OWNER_ONLY_FILE);
1695
+ const raw = await readJson(file);
913
1696
  const workspaces = {};
914
1697
  if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
915
1698
  const config = parseConfig(value);
@@ -920,28 +1703,28 @@ function createGitAuthStore(homeDir = os.homedir()) {
920
1703
  workspaces
921
1704
  };
922
1705
  };
923
- const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
1706
+ const read = async (workspaceRoot) => (await readFile()).workspaces[await workspaceKey(workspaceRoot)] ?? { method: "none" };
924
1707
  return {
925
1708
  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, {
1709
+ view: async (workspaceRoot) => publicView(await read(workspaceRoot)),
1710
+ async save(workspaceRoot, request) {
1711
+ const key = await workspaceKey(workspaceRoot);
1712
+ const current = await readFile();
1713
+ const next = await parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
1714
+ const root = poGitRoot(homeDir, environment);
1715
+ await fs.mkdir(root, {
933
1716
  recursive: true,
934
1717
  mode: OWNER_ONLY_DIRECTORY
935
1718
  });
936
- fs.chmodSync(root, OWNER_ONLY_DIRECTORY);
1719
+ await fs.chmod(root, OWNER_ONLY_DIRECTORY);
937
1720
  const workspaces = { ...current.workspaces };
938
1721
  if (next.method === "none") delete workspaces[key];
939
1722
  else workspaces[key] = next;
940
- writeJsonAtomic(file, {
1723
+ await writeJsonAtomic(file, {
941
1724
  version: 1,
942
1725
  workspaces
943
1726
  });
944
- fs.chmodSync(file, OWNER_ONLY_FILE);
1727
+ await fs.chmod(file, OWNER_ONLY_FILE);
945
1728
  return publicView(next);
946
1729
  }
947
1730
  };
@@ -1040,252 +1823,14 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1040
1823
  };
1041
1824
  }
1042
1825
  //#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
1826
  //#region src/services/gitFailure/index.ts
1827
+ const english = (_key, fallback, vars) => formatMessage(fallback, vars);
1283
1828
  const RULES = [
1284
1829
  {
1285
1830
  code: "host_key_changed",
1286
1831
  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.",
1832
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1833
+ 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
1834
  retryable: false
1290
1835
  },
1291
1836
  {
@@ -1295,8 +1840,8 @@ const RULES = [
1295
1840
  "no ed25519 host key is known",
1296
1841
  "no rsa host key is known"
1297
1842
  ],
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.",
1843
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1844
+ 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
1845
  retryable: false
1301
1846
  },
1302
1847
  {
@@ -1313,15 +1858,15 @@ const RULES = [
1313
1858
  "unprotected private key",
1314
1859
  "invalid format"
1315
1860
  ],
1316
- message: "The remote refused the credentials.",
1317
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1861
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1862
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1318
1863
  retryable: false
1319
1864
  },
1320
1865
  {
1321
1866
  code: "repository_not_found",
1322
1867
  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}`,
1868
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1869
+ 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
1870
  retryable: false
1326
1871
  },
1327
1872
  {
@@ -1334,22 +1879,22 @@ const RULES = [
1334
1879
  "unable to access",
1335
1880
  "network is unreachable"
1336
1881
  ],
1337
- message: "The remote could not be reached.",
1338
- recovery: "Check the network and the remote URL, then try again.",
1882
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1883
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1339
1884
  retryable: true
1340
1885
  },
1341
1886
  {
1342
1887
  code: "push_lease_rejected",
1343
1888
  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.",
1889
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1890
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1346
1891
  retryable: false
1347
1892
  },
1348
1893
  {
1349
1894
  code: "push_needs_force",
1350
1895
  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.",
1896
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1897
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1353
1898
  retryable: false
1354
1899
  },
1355
1900
  {
@@ -1360,18 +1905,21 @@ const RULES = [
1360
1905
  "would be overwritten",
1361
1906
  "your index contains uncommitted changes"
1362
1907
  ],
1363
- message: "There are uncommitted changes in the way.",
1364
- recovery: "Commit or stash your changes first.",
1908
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1909
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1365
1910
  retryable: false
1366
1911
  }
1367
1912
  ];
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.");
1913
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1914
+ 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
1915
  const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1371
1916
  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);
1917
+ if (rule === void 0) return new PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1918
+ operation,
1919
+ code: String(result.code)
1920
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1921
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1922
+ return new PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1375
1923
  }
1376
1924
  //#endregion
1377
1925
  //#region src/services/gitSync/index.ts
@@ -1396,59 +1944,66 @@ const DONE = { outcome: "done" };
1396
1944
  function expected(code, message, recovery) {
1397
1945
  return new PoGitExpectedError(code, message, false, recovery);
1398
1946
  }
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
1947
+ function createGitSync(options) {
1948
+ const baseEnv = options.baseEnv ?? {};
1949
+ async function readLine(cwd, args) {
1950
+ const result = await runGit(cwd, args, {
1951
+ timeout: READ_TIMEOUT_MS,
1952
+ env: baseEnv
1953
+ });
1954
+ const out = result.stdout.trim();
1955
+ return result.code === 0 && out !== "" ? out : void 0;
1956
+ }
1957
+ async function toplevel(cwd) {
1958
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1959
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1960
+ return root;
1961
+ }
1962
+ async function rebasing(root) {
1963
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1964
+ const gitPath = await readLine(root, [
1965
+ "rev-parse",
1966
+ "--git-path",
1967
+ name
1968
+ ]);
1969
+ if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1970
+ }
1971
+ return false;
1972
+ }
1973
+ async function conflicts(root) {
1974
+ return (await runGit(root, [
1975
+ "diff",
1976
+ "--name-only",
1977
+ "--diff-filter=U",
1978
+ "-z"
1979
+ ], {
1980
+ timeout: READ_TIMEOUT_MS,
1981
+ env: baseEnv
1982
+ })).stdout.split("\0").filter((file) => file !== "");
1983
+ }
1984
+ async function currentBranch(root) {
1985
+ const branch = await readLine(root, [
1986
+ "symbolic-ref",
1987
+ "--quiet",
1988
+ "--short",
1989
+ "HEAD"
1415
1990
  ]);
1416
- if (gitPath !== void 0 && fs.existsSync(path.resolve(root, gitPath))) return true;
1991
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1992
+ return branch;
1417
1993
  }
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.");
1994
+ async function guard(root, needsCleanTree) {
1995
+ 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.");
1996
+ const branch = await currentBranch(root);
1997
+ if (needsCleanTree) {
1998
+ if (await readLine(root, [
1999
+ "status",
2000
+ "--porcelain",
2001
+ "--untracked-files=no"
2002
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2003
+ }
2004
+ return branch;
1447
2005
  }
1448
- return branch;
1449
- }
1450
- function createGitSync(options) {
1451
- const baseEnv = options.baseEnv ?? process.env;
2006
+ const baselines = /* @__PURE__ */ new Map();
1452
2007
  /** One credentialed network command against `remote`, classified on failure. */
1453
2008
  const network = async (root, context, remote, operation, args, urlArgs = []) => {
1454
2009
  const url = await readLine(root, [
@@ -1461,26 +2016,42 @@ function createGitSync(options) {
1461
2016
  const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1462
2017
  const result = await runGit(root, args, {
1463
2018
  timeout: NETWORK_TIMEOUT_MS,
1464
- env: prepared.env
2019
+ env: prepared.env,
2020
+ ...context.signal ? { signal: context.signal } : {}
1465
2021
  });
1466
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
2022
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
1467
2023
  };
1468
2024
  /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1469
- const rebaseOnto = async (root, onto) => {
2025
+ const rebaseOnto = async (root, onto, context) => {
2026
+ context.signal?.throwIfAborted();
2027
+ const before = baselines.get(root) ?? await revision(root, "HEAD", {
2028
+ env: baseEnv,
2029
+ ...context.signal ? { signal: context.signal } : {}
2030
+ });
2031
+ baselines.set(root, before);
1470
2032
  const result = await runGit(root, ["rebase", onto], {
1471
2033
  timeout: REBASE_TIMEOUT_MS,
2034
+ ...context.signal ? { signal: context.signal } : {},
1472
2035
  env: {
1473
2036
  ...baseEnv,
1474
2037
  GIT_EDITOR: "true",
1475
2038
  GIT_TERMINAL_PROMPT: "0"
1476
2039
  }
1477
2040
  });
1478
- if (result.code === 0) return DONE;
2041
+ if (result.code === 0) {
2042
+ if (before !== await revision(root, "HEAD", {
2043
+ env: baseEnv,
2044
+ ...context.signal ? { signal: context.signal } : {}
2045
+ })) await options.reapplySparse?.(root, context.signal);
2046
+ baselines.delete(root);
2047
+ return DONE;
2048
+ }
1479
2049
  if (await rebasing(root)) return {
1480
2050
  outcome: "paused",
1481
2051
  conflicts: await conflicts(root)
1482
2052
  };
1483
- throw classifyGitFailure("rebase", result);
2053
+ baselines.delete(root);
2054
+ throw classifyGitFailure("rebase", result, void 0, context.t);
1484
2055
  };
1485
2056
  /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1486
2057
  const remoteOfRef = async (root, ref) => {
@@ -1511,7 +2082,7 @@ function createGitSync(options) {
1511
2082
  "--prune",
1512
2083
  remote
1513
2084
  ]);
1514
- return rebaseOnto(root, upstream);
2085
+ return rebaseOnto(root, upstream, context);
1515
2086
  },
1516
2087
  async push(context, force) {
1517
2088
  const root = await toplevel(context.cwd);
@@ -1543,18 +2114,409 @@ function createGitSync(options) {
1543
2114
  "--prune",
1544
2115
  remote
1545
2116
  ]);
1546
- return rebaseOnto(root, base);
2117
+ return rebaseOnto(root, base, context);
1547
2118
  },
1548
2119
  async abortRebase(context) {
1549
2120
  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);
2121
+ if (!await rebasing(root)) {
2122
+ baselines.delete(root);
2123
+ return DONE;
2124
+ }
2125
+ const result = await runGit(root, ["rebase", "--abort"], {
2126
+ timeout: REBASE_TIMEOUT_MS,
2127
+ env: baseEnv,
2128
+ ...context.signal ? { signal: context.signal } : {}
2129
+ });
2130
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2131
+ baselines.delete(root);
1553
2132
  return DONE;
1554
2133
  }
1555
2134
  };
1556
2135
  }
1557
2136
  //#endregion
2137
+ //#region src/services/newSessionRequest/index.ts
2138
+ const MAX_NAME_LENGTH = 120;
2139
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2140
+ function optionalText(value) {
2141
+ if (value === void 0) return void 0;
2142
+ if (typeof value !== "string") return false;
2143
+ const trimmed = value.trim();
2144
+ return trimmed === "" ? void 0 : trimmed;
2145
+ }
2146
+ /**
2147
+ * Validates a new-session dialog request for a worktree session. Every ref is
2148
+ * checked here, before it can reach git as a positional argument.
2149
+ */
2150
+ function newSessionRequest(body) {
2151
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2152
+ const record = body;
2153
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2154
+ const branch = optionalText(record.branch);
2155
+ if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
2156
+ const name = optionalText(record.name);
2157
+ 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.` };
2158
+ if (Object.hasOwn(record, "sparseProfile") && !validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2159
+ const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
2160
+ if ("error" in chosen) return chosen;
2161
+ const profile = chosen.selection?.profile;
2162
+ const named = {
2163
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2164
+ ...name === void 0 ? {} : { name },
2165
+ ...profile === void 0 ? {} : { selection: { profile } }
2166
+ };
2167
+ if (record.mode === "existing-branch") {
2168
+ const remote = optionalText(record.remote);
2169
+ if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
2170
+ return {
2171
+ mode: "existing-branch",
2172
+ branch,
2173
+ ...remote === void 0 ? {} : { remote },
2174
+ ...named
2175
+ };
2176
+ }
2177
+ if (record.mode === "new-branch") {
2178
+ const baseRef = optionalText(record.baseRef);
2179
+ if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
2180
+ return {
2181
+ mode: "new-branch",
2182
+ branch,
2183
+ ...baseRef === void 0 ? {} : { baseRef },
2184
+ ...named
2185
+ };
2186
+ }
2187
+ return { error: "The mode must be existing-branch or new-branch." };
2188
+ }
2189
+ //#endregion
2190
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2191
+ /**
2192
+ * The worktree surface the cockpit panel calls.
2193
+ *
2194
+ * Hub-scoped because worktrees are a property of a repository, not of one
2195
+ * session: the panel lists and creates them whether or not the session that
2196
+ * made them is focused, and a session-scoped API would disappear with it.
2197
+ *
2198
+ * The panel names a repository by the hub's opaque id and never by path.
2199
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2200
+ * point this at a directory the cockpit was never given.
2201
+ */
2202
+ function badRequest(message) {
2203
+ return Response.json({ error: message }, { status: 400 });
2204
+ }
2205
+ function failed(error) {
2206
+ if (error instanceof PoGitExpectedError) return Response.json({
2207
+ error: error.message,
2208
+ code: error.code
2209
+ }, { status: error.retryable ? 503 : 409 });
2210
+ return Response.json({ error: "The worktree operation failed." }, { status: 500 });
2211
+ }
2212
+ function createGitApi(openDirectory, dependencies = {}, translate) {
2213
+ return {
2214
+ basePath: "git",
2215
+ start(context) {
2216
+ if (context.directEvents === void 0) throw new Error("Git hub API requires the direct event bus.");
2217
+ const directEvents = context.directEvents;
2218
+ const publishLifecycle = (sessionId, repositoryRoot) => {
2219
+ directEvents.publish(GIT_WORKTREE_LIFECYCLE_EVENT, sessionId, {
2220
+ version: 1,
2221
+ repositoryRoot
2222
+ });
2223
+ };
2224
+ const git = createWorktreeGit();
2225
+ const operations = createWorktreeOperations({
2226
+ ...dependencies,
2227
+ git,
2228
+ sessionService: context.sessionService,
2229
+ ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
2230
+ ...context.environment === void 0 ? {} : { environment: context.environment }
2231
+ });
2232
+ const sync = createGitSync({
2233
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2234
+ baseEnv: context.environment ?? {},
2235
+ async reapplySparse(cwd, signal) {
2236
+ const record = (await createWorktreeRegistry(await registryFile(cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.path === cwd && entry.sessionId === context.sessionId);
2237
+ if (record?.sparseProfile) await operations.reapply({
2238
+ cwd,
2239
+ sessionId: context.sessionId
2240
+ }, record.id, { signal });
2241
+ }
2242
+ });
2243
+ const sessionCommand = async (request, url) => {
2244
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2245
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2246
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2247
+ const caller = {
2248
+ cwd: context.cwd,
2249
+ sessionId: context.sessionId
2250
+ };
2251
+ const body = await request.json().catch(() => void 0);
2252
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2253
+ const command = body;
2254
+ if (url.pathname === "/sync") {
2255
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2256
+ const recordedBaseRef = (await createWorktreeRegistry(await registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2257
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2258
+ const syncContext = {
2259
+ ...caller,
2260
+ auth,
2261
+ recordedBaseRef,
2262
+ signal: request.signal,
2263
+ ...translate ? { t: translate } : {}
2264
+ };
2265
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2266
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2267
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2268
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2269
+ return badRequest("Unknown sync command.");
2270
+ }
2271
+ if (Object.keys(command).some((key) => ![
2272
+ "action",
2273
+ "branch",
2274
+ "baseRef",
2275
+ "sparseProfile",
2276
+ "reservationId",
2277
+ "id",
2278
+ "force",
2279
+ "folders"
2280
+ ].includes(key))) return badRequest("Unknown command field.");
2281
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2282
+ if (command.action === "create") {
2283
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2284
+ const result = await operations.spawn(caller, {
2285
+ branch: command.branch,
2286
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2287
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2288
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2289
+ }, { signal: request.signal });
2290
+ return Response.json({ worktree: result });
2291
+ }
2292
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2293
+ if (![
2294
+ "profiles",
2295
+ "expand",
2296
+ "reapply"
2297
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2298
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2299
+ return Response.json(result.details);
2300
+ };
2301
+ /**
2302
+ * The new-session dialog's routes: the workspace's branches, and a top-level
2303
+ * worktree session on one. Workspace-mounted only, and always rooted at the
2304
+ * mount's own workspace, so a request can never name another directory.
2305
+ */
2306
+ const newSession = async (request, url) => {
2307
+ const isBranches = request.method === "GET" && url.pathname === "/branches";
2308
+ const isCreate = request.method === "POST" && url.pathname === "/sessions";
2309
+ const isDelete = request.method === "DELETE" && url.pathname === "/branches";
2310
+ const isOpen = request.method === "POST" && url.pathname === `/branches/open`;
2311
+ if (!isBranches && !isCreate && !isDelete && !isOpen) return void 0;
2312
+ const workspaceRoot = context.scope === "workspace" ? context.workspaceRoot : void 0;
2313
+ if (workspaceRoot === void 0) return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2314
+ if (isBranches) {
2315
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2316
+ const branches = repositoryRoot === void 0 ? {
2317
+ repository: false,
2318
+ local: [],
2319
+ remote: []
2320
+ } : {
2321
+ repository: true,
2322
+ ...await git.listBranches(repositoryRoot),
2323
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
2324
+ };
2325
+ return Response.json(branches);
2326
+ }
2327
+ if (isDelete || isOpen) {
2328
+ if (isOpen && poApiCallerFrom(request.headers)?.locality !== "local") return Response.json({ error: "Opening Finder is only available on the host." }, { status: 403 });
2329
+ const body = await request.json().catch(() => void 0);
2330
+ const branch = typeof body === "object" && body !== null ? body.branch : void 0;
2331
+ if (typeof branch !== "string" || !validRefName(branch)) return badRequest("A valid branch name is required.");
2332
+ const repositoryRoot = await git.repositoryRoot(workspaceRoot);
2333
+ if (repositoryRoot === void 0) return badRequest("This workspace is not a git checkout.");
2334
+ const branches = await git.listBranches(repositoryRoot);
2335
+ const local = branches.local.find((item) => item.name === branch);
2336
+ if (local === void 0) return Response.json({ error: "That local branch no longer exists." }, { status: 404 });
2337
+ if (isOpen) {
2338
+ if (local.checkedOutAt === void 0) return Response.json({ error: "This branch has no checked-out folder." }, { status: 409 });
2339
+ if (openDirectory === void 0) return Response.json({ error: "Finder is not available on this host." }, { status: 409 });
2340
+ try {
2341
+ await openDirectory(local.checkedOutAt);
2342
+ return Response.json({ opened: true });
2343
+ } catch {
2344
+ return Response.json({ error: "The branch folder could not be opened in Finder." }, { status: 409 });
2345
+ }
2346
+ }
2347
+ if (local.checkedOutAt !== void 0 || branches.current === branch) return Response.json({ error: "Close this branch’s worktree before deleting it." }, { status: 409 });
2348
+ if (!await git.deleteBranch({
2349
+ repositoryRoot,
2350
+ branch
2351
+ })) return Response.json({ error: "Git refused to delete this branch. It may contain unmerged commits or be checked out." }, { status: 409 });
2352
+ return Response.json({ deleted: true });
2353
+ }
2354
+ const parsed = newSessionRequest(await request.json().catch(() => void 0));
2355
+ if ("error" in parsed) return badRequest(parsed.error);
2356
+ const record = await operations.spawn({ cwd: workspaceRoot }, {
2357
+ branch: parsed.branch,
2358
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
2359
+ checkout: parsed.mode === "existing-branch" ? "existing" : "new",
2360
+ ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
2361
+ ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
2362
+ ...parsed.name === void 0 ? {} : { name: parsed.name },
2363
+ ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
2364
+ }, { signal: request.signal });
2365
+ publishLifecycle(record.sessionId, record.repositoryRoot);
2366
+ const created = {
2367
+ sessionId: record.sessionId,
2368
+ worktreeId: record.id
2369
+ };
2370
+ return Response.json(created, { status: 201 });
2371
+ };
2372
+ /** The admitted root for a request, or a response explaining why not. */
2373
+ const rootOf = (url) => {
2374
+ const repositoryId = url.searchParams.get("repositoryId");
2375
+ if (repositoryId === null || repositoryId === "") return badRequest("A repositoryId is required.");
2376
+ const root = context.resolveRepository?.(repositoryId);
2377
+ if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
2378
+ return root;
2379
+ };
2380
+ const homeDir = context.homeDirectory ?? context.environment?.HOME;
2381
+ const gitAuth = homeDir === void 0 ? void 0 : createGitAuthStore(homeDir, context.environment);
2382
+ const branchDiff = createBranchDiff();
2383
+ const pendingReviews = /* @__PURE__ */ new Map();
2384
+ /**
2385
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
2386
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
2387
+ * The view never carries the token.
2388
+ */
2389
+ const auth = async (request, url) => {
2390
+ if (url.pathname !== "/auth") return void 0;
2391
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
2392
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
2393
+ if (gitAuth === void 0) throw new Error("Git auth requires the admitted host home directory.");
2394
+ const root = rootOf(url);
2395
+ if (root instanceof Response) return root;
2396
+ if (request.method === "GET") return Response.json(await gitAuth.view(root));
2397
+ try {
2398
+ return Response.json(await gitAuth.save(root, await request.json().catch(() => void 0)));
2399
+ } catch (error) {
2400
+ if (error instanceof PoGitExpectedError && error.code === "invalid_request") {
2401
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
2402
+ return Response.json({
2403
+ error: text,
2404
+ code: error.code
2405
+ }, { status: 400 });
2406
+ }
2407
+ throw error;
2408
+ }
2409
+ };
2410
+ /**
2411
+ * The session's change against its base. Session mounts only, rooted at the
2412
+ * session's own checkout; a file is served only when it is in the change set
2413
+ * computed for the request. Overlapping requests share an in-flight snapshot.
2414
+ */
2415
+ const review = async (request, url) => {
2416
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
2417
+ const cwd = context.scope === "session" ? context.cwd : void 0;
2418
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2419
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
2420
+ if (homeDir === void 0) throw new Error("Git review requires the admitted host home directory.");
2421
+ let recordedBaseRef;
2422
+ try {
2423
+ recordedBaseRef = (await createWorktreeRegistry(await registryFile(cwd, homeDir, context.environment)).list()).find((record) => record.sessionId === context.sessionId)?.baseRef;
2424
+ } catch {
2425
+ recordedBaseRef = void 0;
2426
+ }
2427
+ const key = JSON.stringify([cwd, recordedBaseRef ?? null]);
2428
+ let pending = pendingReviews.get(key);
2429
+ if (pending === void 0) {
2430
+ pending = branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef }).finally(() => pendingReviews.delete(key));
2431
+ pendingReviews.set(key, pending);
2432
+ }
2433
+ const result = await pending;
2434
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
2435
+ repository: false,
2436
+ files: []
2437
+ });
2438
+ const filePath = url.searchParams.get("path") ?? "";
2439
+ 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 });
2440
+ return Response.json(await branchDiff.fileDiff(result, filePath));
2441
+ };
2442
+ return {
2443
+ async fetch(request) {
2444
+ const url = new URL(request.url);
2445
+ try {
2446
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2447
+ if (answered !== void 0) return answered;
2448
+ } catch (error) {
2449
+ context.onNotice(`git request failed: ${error.name}`);
2450
+ return failed(error);
2451
+ }
2452
+ const root = rootOf(url);
2453
+ if (root instanceof Response) return root;
2454
+ const callerContext = {
2455
+ cwd: root,
2456
+ sessionId: url.searchParams.get("sessionId") ?? ""
2457
+ };
2458
+ 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.");
2459
+ try {
2460
+ if (request.method === "GET" && url.pathname === "/worktrees") return Response.json({ worktrees: await operations.list(callerContext) });
2461
+ if (request.method === "POST" && url.pathname === "/worktrees") {
2462
+ const body = await request.json();
2463
+ if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
2464
+ const record = await operations.spawn(callerContext, {
2465
+ branch: body.branch,
2466
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
2467
+ ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
2468
+ ...body.name === void 0 ? {} : { name: body.name }
2469
+ });
2470
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2471
+ return Response.json({ worktree: record }, { status: 201 });
2472
+ }
2473
+ const closing = /^\/worktrees\/([^/]+)$/u.exec(url.pathname);
2474
+ if (request.method === "DELETE" && closing) {
2475
+ const record = await operations.close(callerContext, decodeURIComponent(String(closing[1])), url.searchParams.get("force") === "true");
2476
+ publishLifecycle(callerContext.sessionId, record.repositoryRoot);
2477
+ return Response.json({ worktree: record });
2478
+ }
2479
+ return Response.json({ error: "No such worktree route." }, { status: 404 });
2480
+ } catch (error) {
2481
+ context.onNotice(`worktree request failed: ${error.name}`);
2482
+ return failed(error);
2483
+ }
2484
+ },
2485
+ close() {}
2486
+ };
2487
+ }
2488
+ };
2489
+ }
2490
+ //#endregion
2491
+ //#region src/extensions/(backend)/api/git/route.server.ts
2492
+ var route_server_default = defineRoute((plugin) => {
2493
+ const { context, host, signal } = plugin;
2494
+ let openDirectory;
2495
+ context.inject([PO_SHELL_SERVICE], (child) => {
2496
+ const shell = requirePoShell(child);
2497
+ const env = Object.fromEntries(Object.entries(host.context.environment ?? {}).filter((entry) => entry[1] !== void 0));
2498
+ openDirectory = async (path) => {
2499
+ const result = await shell.exec([
2500
+ "/usr/bin/open",
2501
+ "-a",
2502
+ "Finder",
2503
+ path
2504
+ ], {
2505
+ env,
2506
+ inheritEnv: false
2507
+ }, withAbortSignal(AbortSignal.any([signal, AbortSignal.timeout(5e3)]), BACKGROUND_CONTEXT));
2508
+ if (!result.ok || result.value.exitCode !== 0) throw new Error("Finder could not be opened.");
2509
+ };
2510
+ return () => {
2511
+ openDirectory = void 0;
2512
+ };
2513
+ });
2514
+ return createGitApi(async (path) => {
2515
+ if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
2516
+ await openDirectory(path);
2517
+ }, createGitOperationDependencies(plugin), (key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(host.context.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars));
2518
+ });
2519
+ //#endregion
1558
2520
  //#region src/types/gitReview.ts
1559
2521
  /**
1560
2522
  * The cockpit's view of what this session changed against its base: the counts
@@ -1584,8 +2546,9 @@ const GIT_CHANGES_TYPE = "git_changes";
1584
2546
  * - Apart from the worktrees channel. Worktrees are repository management;
1585
2547
  * this is the session's own code change.
1586
2548
  * - 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.
2549
+ * after every tool call that can write and every settled turn; a recount
2550
+ * waits for a quiet moment, so a burst of tool calls costs one, and runs one
2551
+ * in flight plus one rerun.
1589
2552
  * - One sync command per session. A rebase and a push must never overlap.
1590
2553
  * - Auth is read fresh for each command from the session's workspace, and goes
1591
2554
  * only into that command's git child.
@@ -1594,6 +2557,8 @@ const GIT_CHANGES_TYPE = "git_changes";
1594
2557
  * - Echoing git output. Failures go through classifyGitFailure, which matches
1595
2558
  * stderr and drops it, because a remote URL in it can carry a token.
1596
2559
  */
2560
+ /** Each recount spawns several git processes and walks the worktree for untracked files. */
2561
+ const REFRESH_DELAY_MS = 1500;
1597
2562
  function payloadOf$1(state) {
1598
2563
  return {
1599
2564
  ...state.changes === void 0 ? {} : { changes: state.changes },
@@ -1638,17 +2603,19 @@ function createGitChangesChannel(options = {}) {
1638
2603
  const homeDir = options.homeDir ?? os.homedir();
1639
2604
  const diff = options.diff ?? createBranchDiff();
1640
2605
  const sync = options.sync ?? createGitSync({ homeDir });
1641
- const auth = options.auth ?? createGitAuthStore(homeDir);
2606
+ const auth = options.auth ?? createGitAuthStore(homeDir, options.environment);
1642
2607
  const latest = /* @__PURE__ */ new Map();
1643
2608
  const subscriptions = /* @__PURE__ */ new Map();
1644
2609
  const scopes = /* @__PURE__ */ new Map();
1645
2610
  const inFlight = /* @__PURE__ */ new Set();
1646
2611
  const rerun = /* @__PURE__ */ new Set();
1647
2612
  const busy = /* @__PURE__ */ new Set();
2613
+ const delayed = /* @__PURE__ */ new Map();
2614
+ const refreshDelayMs = options.refreshDelayMs ?? REFRESH_DELAY_MS;
1648
2615
  /** The base the session's own worktree was created from, when it has one. */
1649
- const recordedBaseRef = (scope) => {
2616
+ const recordedBaseRef = async (scope) => {
1650
2617
  try {
1651
- return createWorktreeRegistry(registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
2618
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, homeDir, options.environment)).list()).find((record) => record.sessionId === scope.sessionId)?.baseRef;
1652
2619
  } catch {
1653
2620
  return;
1654
2621
  }
@@ -1681,8 +2648,7 @@ function createGitChangesChannel(options = {}) {
1681
2648
  return;
1682
2649
  }
1683
2650
  inFlight.add(sessionId);
1684
- const base = recordedBaseRef(scope);
1685
- diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
2651
+ recordedBaseRef(scope).then((base) => diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base })).then((review) => {
1686
2652
  if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1687
2653
  }).catch((error) => {
1688
2654
  host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
@@ -1691,18 +2657,41 @@ function createGitChangesChannel(options = {}) {
1691
2657
  if (rerun.delete(sessionId)) refresh(sessionId);
1692
2658
  });
1693
2659
  };
1694
- const run = (scope, command) => {
2660
+ /** Recounts once the session has been quiet for a moment. */
2661
+ const refreshSoon = (sessionId) => {
2662
+ clearTimeout(delayed.get(sessionId));
2663
+ const timer = setTimeout(() => {
2664
+ delayed.delete(sessionId);
2665
+ refresh(sessionId);
2666
+ }, refreshDelayMs);
2667
+ timer.unref?.();
2668
+ delayed.set(sessionId, timer);
2669
+ };
2670
+ const run = async (scope, command) => {
2671
+ if (options.scopedCommands) {
2672
+ const response = await host.requestSessionApi(scope, {
2673
+ basePath: "git",
2674
+ path: "/sync",
2675
+ method: "POST",
2676
+ body: JSON.stringify(command)
2677
+ });
2678
+ const result = await response.json();
2679
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2680
+ return result;
2681
+ }
1695
2682
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1696
- const base = recordedBaseRef(scope);
2683
+ const base = await recordedBaseRef(scope);
1697
2684
  const context = {
1698
2685
  cwd: scope.cwd,
1699
- auth: auth.read(workspaceRoot),
2686
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
2687
+ auth: await auth.read(workspaceRoot),
1700
2688
  ...base === void 0 ? {} : { recordedBaseRef: base }
1701
2689
  };
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);
2690
+ const sessionSync = sync;
2691
+ if (command.action === "pull") return sessionSync.pull(context);
2692
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2693
+ if (command.action === "rebase") return sessionSync.rebase(context);
2694
+ return sessionSync.abortRebase(context);
1706
2695
  };
1707
2696
  const source = {
1708
2697
  payloadFor(scope) {
@@ -1713,12 +2702,14 @@ function createGitChangesChannel(options = {}) {
1713
2702
  scopes.set(scope.sessionId, scope);
1714
2703
  refresh(scope.sessionId);
1715
2704
  const unsubscribe = host.directEvents.subscribe(GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1716
- if (isSessionChangedEvent(payload)) refresh(scope.sessionId);
2705
+ if (isSessionChangedEvent(payload)) refreshSoon(scope.sessionId);
1717
2706
  });
1718
2707
  subscriptions.set(scope.sessionId, unsubscribe);
1719
2708
  },
1720
2709
  sessionRemoved(sessionId) {
1721
2710
  subscriptions.get(sessionId)?.();
2711
+ clearTimeout(delayed.get(sessionId));
2712
+ delayed.delete(sessionId);
1722
2713
  subscriptions.delete(sessionId);
1723
2714
  scopes.delete(sessionId);
1724
2715
  latest.delete(sessionId);
@@ -1727,6 +2718,8 @@ function createGitChangesChannel(options = {}) {
1727
2718
  },
1728
2719
  close() {
1729
2720
  for (const unsubscribe of subscriptions.values()) unsubscribe();
2721
+ for (const timer of delayed.values()) clearTimeout(timer);
2722
+ delayed.clear();
1730
2723
  subscriptions.clear();
1731
2724
  scopes.clear();
1732
2725
  latest.clear();
@@ -1765,7 +2758,12 @@ function createGitChangesChannel(options = {}) {
1765
2758
  }
1766
2759
  //#endregion
1767
2760
  //#region src/extensions/(backend)/channel/git-changes.server.ts
1768
- var git_changes_server_default = defineChannel(createGitChangesChannel);
2761
+ var git_changes_server_default = defineChannel(({ context, host }) => createGitChangesChannel({
2762
+ homeDir: host.context.homeDirectory,
2763
+ environment: host.context.environment,
2764
+ scopedCommands: true,
2765
+ t: (scope, key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(scope.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars)
2766
+ }), { context: true });
1769
2767
  //#endregion
1770
2768
  //#region src/types/webWorktrees.ts
1771
2769
  /**
@@ -1794,9 +2792,9 @@ function payloadOf(state) {
1794
2792
  };
1795
2793
  }
1796
2794
  /** Worktrees visible to this session, using the hub's live session table for ownership. */
1797
- function viewsFor(scope, deps) {
2795
+ async function viewsFor(scope, deps) {
1798
2796
  try {
1799
- return createWorktreeRegistry(registryFile(scope.cwd, deps.homeDir)).list().flatMap((record) => {
2797
+ return (await createWorktreeRegistry(await registryFile(scope.cwd, deps.homeDir, deps.environment)).list()).flatMap((record) => {
1800
2798
  if (record.parentSessionId === void 0 && record.sessionId !== scope.sessionId) return [];
1801
2799
  const owned = record.parentSessionId === void 0 || record.parentSessionId === scope.sessionId;
1802
2800
  const unowned = !owned && !deps.sessionService.isLive(record.parentSessionId);
@@ -1821,11 +2819,15 @@ function sameList(left, right) {
1821
2819
  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
2820
  });
1823
2821
  }
1824
- function errorTargetFor(command) {
1825
- return command.action === "create" ? { action: "create" } : {
2822
+ function errorTargetFor(command, error) {
2823
+ if (command.action === "close") return {
1826
2824
  action: "close",
1827
2825
  id: command.id
1828
2826
  };
2827
+ return error instanceof PoGitExpectedError && error.code === "rift_missing" ? {
2828
+ action: "create",
2829
+ riftMissing: true
2830
+ } : { action: "create" };
1829
2831
  }
1830
2832
  /** A command the page sent, or undefined when the frame was not one. */
1831
2833
  function parseCommand(payload) {
@@ -1834,7 +2836,9 @@ function parseCommand(payload) {
1834
2836
  if (value.action === "create") {
1835
2837
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
1836
2838
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2839
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
1837
2840
  return {
2841
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
1838
2842
  action: "create",
1839
2843
  branch: value.branch.trim(),
1840
2844
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -1853,11 +2857,15 @@ function parseCommand(payload) {
1853
2857
  /**
1854
2858
  * What the reader is told when a command fails.
1855
2859
  *
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.
2860
+ * An expected failure explains itself, minus the `[code]` tag and recovery line
2861
+ * written for the agent's tool result. A dirty close is said in the person's
2862
+ * terms, because its message tells the agent to pass `force`. Anything else is
2863
+ * summarised, never echoed: a git error can carry a remote URL with a token in it.
1858
2864
  */
1859
2865
  function failureText(error) {
1860
- return error instanceof PoGitExpectedError ? error.message : "The worktree operation failed.";
2866
+ if (!(error instanceof PoGitExpectedError)) return "The worktree operation failed.";
2867
+ if (error.code === "worktree_dirty") return "The worktree has uncommitted changes.";
2868
+ return error.message.replace(/^\[[a-z_]+\] /u, "").split("\nRecovery:")[0] ?? error.message;
1861
2869
  }
1862
2870
  /** Starts one direct-event subscription per managed session. */
1863
2871
  function createWorktreesChannel(options = {}) {
@@ -1869,7 +2877,9 @@ function createWorktreesChannel(options = {}) {
1869
2877
  if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1870
2878
  const worktrees = options.operations ?? createWorktreeOperations({
1871
2879
  git: createWorktreeGit(),
1872
- sessionService
2880
+ sessionService,
2881
+ ...options.homeDir === void 0 ? {} : { homeDir: options.homeDir },
2882
+ ...options.environment === void 0 ? {} : { environment: options.environment }
1873
2883
  });
1874
2884
  /** Announces a successful mutation to this session's lifecycle subscribers. */
1875
2885
  const publishLifecycle = (scope, repositoryRoot) => {
@@ -1882,6 +2892,22 @@ function createWorktreesChannel(options = {}) {
1882
2892
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
1883
2893
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
1884
2894
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2895
+ if (options.scopedCommands) {
2896
+ if (!(await host.requestSessionApi(parent, {
2897
+ basePath: "git",
2898
+ path: "/session-worktrees",
2899
+ method: "POST",
2900
+ body: JSON.stringify({
2901
+ action: "create",
2902
+ branch,
2903
+ reservationId
2904
+ }),
2905
+ ...signal ? { signal } : {}
2906
+ })).ok) throw new Error("The conversation worktree could not be created.");
2907
+ const reservations = sessionService.reservations;
2908
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2909
+ return reservations.complete(reservationId, parentSessionId);
2910
+ }
1885
2911
  const record = await worktrees.spawn({
1886
2912
  cwd: parent.cwd,
1887
2913
  sessionId: parent.sessionId
@@ -1898,6 +2924,7 @@ function createWorktreesChannel(options = {}) {
1898
2924
  });
1899
2925
  const views = {
1900
2926
  homeDir: options.homeDir,
2927
+ environment: options.environment,
1901
2928
  sessionService
1902
2929
  };
1903
2930
  const latest = /* @__PURE__ */ new Map();
@@ -1910,10 +2937,13 @@ function createWorktreesChannel(options = {}) {
1910
2937
  return generation;
1911
2938
  };
1912
2939
  /** Republishes a session, skipping a frame that would say nothing new. */
1913
- const publish = (scope, force) => {
2940
+ const publish = async (scope, force) => {
2941
+ const generation = generations.get(scope.sessionId);
2942
+ const worktreeViews = await viewsFor(scope, views);
2943
+ if (generation === void 0 || generations.get(scope.sessionId) !== generation) return;
1914
2944
  const previous = latest.get(scope.sessionId);
1915
2945
  const next = {
1916
- worktrees: viewsFor(scope, views),
2946
+ worktrees: worktreeViews,
1917
2947
  pending: previous?.pending,
1918
2948
  error: previous?.error,
1919
2949
  errorTarget: previous?.errorTarget
@@ -1925,7 +2955,7 @@ function createWorktreesChannel(options = {}) {
1925
2955
  const mark = (scope, pending, error, errorTarget) => {
1926
2956
  const previous = latest.get(scope.sessionId);
1927
2957
  latest.set(scope.sessionId, {
1928
- worktrees: previous?.worktrees ?? viewsFor(scope, views),
2958
+ worktrees: previous?.worktrees ?? [],
1929
2959
  pending,
1930
2960
  error,
1931
2961
  errorTarget
@@ -1941,10 +2971,24 @@ function createWorktreesChannel(options = {}) {
1941
2971
  if (generations.get(scope.sessionId) !== generation) return;
1942
2972
  mark(scope, pending, error, errorTarget);
1943
2973
  };
2974
+ if (options.scopedCommands) {
2975
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2976
+ const response = await host.requestSessionApi(scope, {
2977
+ basePath: "git",
2978
+ path: "/session-worktrees",
2979
+ method: "POST",
2980
+ body: JSON.stringify(command)
2981
+ });
2982
+ const result = await response.json();
2983
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2984
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2985
+ return;
2986
+ }
1944
2987
  if (command.action === "create") {
1945
2988
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
1946
2989
  const record = await worktrees.spawn(context, {
1947
2990
  branch: command.branch,
2991
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
1948
2992
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
1949
2993
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
1950
2994
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -1965,15 +3009,15 @@ function createWorktreesChannel(options = {}) {
1965
3009
  sessionAdded(scope) {
1966
3010
  newGeneration(scope.sessionId);
1967
3011
  publish(scope, false);
1968
- const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, (payload) => {
3012
+ const unsubscribe = host.directEvents.subscribe(GIT_WORKTREE_LIFECYCLE_EVENT, scope.sessionId, async (payload) => {
1969
3013
  if (!isWorktreeLifecycleEvent(payload)) return;
1970
3014
  let sameRepository = false;
1971
3015
  try {
1972
- sameRepository = registryFile(scope.cwd, options.homeDir) === registryFile(payload.repositoryRoot, options.homeDir);
3016
+ sameRepository = await registryFile(scope.cwd, options.homeDir, options.environment) === await registryFile(payload.repositoryRoot, options.homeDir, options.environment);
1973
3017
  } catch {
1974
3018
  sameRepository = false;
1975
3019
  }
1976
- if (sameRepository) publish(scope, false);
3020
+ if (sameRepository) await publish(scope, false);
1977
3021
  });
1978
3022
  subscriptions.set(scope.sessionId, unsubscribe);
1979
3023
  },
@@ -2006,7 +3050,7 @@ function createWorktreesChannel(options = {}) {
2006
3050
  }).catch((error) => {
2007
3051
  if (generations.get(scope.sessionId) !== generation) return;
2008
3052
  host.onNotice(`worktree command failed for ${scope.sessionId} (${failureText(error)})`);
2009
- mark(scope, void 0, failureText(error), errorTargetFor(command));
3053
+ mark(scope, void 0, failureText(error), errorTargetFor(command, error));
2010
3054
  }).finally(() => {
2011
3055
  if (generations.get(scope.sessionId) === generation) busy.delete(scope.sessionId);
2012
3056
  });
@@ -2020,7 +3064,11 @@ function createWorktreesChannel(options = {}) {
2020
3064
  }
2021
3065
  //#endregion
2022
3066
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2023
- var git_worktrees_server_default = defineChannel(createWorktreesChannel);
3067
+ var git_worktrees_server_default = defineChannel((plugin) => createWorktreesChannel({
3068
+ homeDir: plugin.host.context.homeDirectory,
3069
+ environment: plugin.host.context.environment,
3070
+ scopedCommands: true
3071
+ }), { context: true });
2024
3072
  //#endregion
2025
3073
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2026
3074
  var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
@@ -2028,20 +3076,8 @@ var agent_settled_server_default = defineHook((context) => context.root.hooks[1]
2028
3076
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2029
3077
  var tool_execution_end_server_default = defineHook((context) => context.root.hooks[0]);
2030
3078
  //#endregion
2031
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGit.server.ts
2032
- var poGit_server_default$1 = (context) => context.root.resources[0];
2033
- //#endregion
2034
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGit.server.ts
2035
- var poGit_server_default = defineResource(poGit_server_default$1);
2036
- //#endregion
2037
- //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poGitReadme.server.ts
2038
- var poGitReadme_server_default$1 = (context) => context.root.resources[2];
2039
- //#endregion
2040
- //#region src/extensions/workspaces/sessions/(backend)/resource/poGitReadme.server.ts
2041
- var poGitReadme_server_default = defineResource(poGitReadme_server_default$1);
2042
- //#endregion
2043
3079
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/poUseGit.server.ts
2044
- var poUseGit_server_default$1 = (context) => context.root.resources[1];
3080
+ var poUseGit_server_default$1 = (context) => context.root.resources[0];
2045
3081
  //#endregion
2046
3082
  //#region src/extensions/workspaces/sessions/(backend)/resource/poUseGit.server.ts
2047
3083
  var poUseGit_server_default = defineResource(poUseGit_server_default$1);
@@ -2059,54 +3095,63 @@ const via = (identity, value) => value === void 0 ? void 0 : {
2059
3095
  };
2060
3096
  const serverPlugin = defineServerPlugin({
2061
3097
  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
- }
3098
+ providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
3099
+ injects: composeRootInjects({
3100
+ workspace: [root_server_default$1],
3101
+ session: [root_server_default$1, root_server_default]
2071
3102
  }),
2072
- workspace: (context) => ({
3103
+ host: (context) => ({
2073
3104
  get api() {
2074
3105
  return [at(route_server_default, context)];
2075
3106
  },
2076
3107
  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())]);
3108
+ return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2078
3109
  }
2079
3110
  }),
3111
+ workspace: async (context) => {
3112
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3113
+ return {
3114
+ ...composeRootHooks(scopeWorkspace),
3115
+ get api() {
3116
+ return [at(route_server_default, context)];
3117
+ },
3118
+ get channels() {
3119
+ 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))]);
3120
+ },
3121
+ services: [...scopeWorkspace.services ?? []]
3122
+ };
3123
+ },
2080
3124
  session: async (context) => {
2081
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2082
- const contextSession = {
3125
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3126
+ const contextWorkspace = {
2083
3127
  ...context,
3128
+ root: scopeWorkspace.value
3129
+ };
3130
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3131
+ const contextSession = {
3132
+ ...contextWorkspace,
2084
3133
  root: scopeSession.value
2085
3134
  };
2086
3135
  return {
2087
- ...composeRootHooks(scopeSession),
3136
+ ...composeRootHooks(scopeWorkspace, scopeSession),
2088
3137
  get api() {
2089
3138
  return [at(route_server_default, context)];
2090
3139
  },
2091
3140
  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())]);
3141
+ 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
3142
  },
2094
3143
  get hooks() {
2095
3144
  return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
2096
3145
  },
2097
3146
  get resources() {
2098
- return [
2099
- at(poGit_server_default, contextSession),
2100
- at(poGitReadme_server_default, contextSession),
2101
- at(poUseGit_server_default, contextSession)
2102
- ];
3147
+ return [at(poUseGit_server_default, contextSession)];
2103
3148
  },
2104
3149
  get tools() {
2105
3150
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2106
3151
  },
2107
- services: [...scopeSession.services ?? []],
3152
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2108
3153
  get activities() {
2109
- return [...scopeSession.activities ?? []];
3154
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2110
3155
  }
2111
3156
  };
2112
3157
  }