@getpaseo/server 0.16.1 → 0.16.2

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 (41) hide show
  1. package/dist/server/builtin-plugins/package.json +1 -1
  2. package/dist/server/builtin-plugins/worktree-include/server/copy.ts +162 -16
  3. package/dist/server/server/agent/agent-manager.js +2 -1
  4. package/dist/server/server/agent/providers/claude/agent.js +34 -2
  5. package/dist/server/server/agent/providers/omp/agent.d.ts +1 -0
  6. package/dist/server/server/agent/providers/omp/agent.js +22 -0
  7. package/dist/server/server/agent/providers/omp/rpc-types.d.ts +4 -0
  8. package/dist/server/server/agent/providers/omp/rpc-types.js +8 -0
  9. package/dist/server/server/agent/tools/paseo-tools.js +8 -2
  10. package/dist/server/server/bootstrap.js +2 -2
  11. package/dist/server/server/file-observer/index.d.ts +1 -0
  12. package/dist/server/server/file-observer/index.js +14 -1
  13. package/dist/server/server/file-observer/internal/observation.js +4 -0
  14. package/dist/server/server/hub/relationship-controller.js +26 -15
  15. package/dist/server/server/hub/relationship-remote.d.ts +1 -1
  16. package/dist/server/server/hub/relationship-remote.js +2 -2
  17. package/dist/server/server/resolve-worktree-creation-intent.d.ts +1 -1
  18. package/dist/server/server/session/workspace-recovery/workspace-recovery-service.js +30 -4
  19. package/dist/server/server/test-fixtures/reconciliation-registries.d.ts +1 -0
  20. package/dist/server/server/websocket-server.d.ts +5 -0
  21. package/dist/server/server/websocket-server.js +10 -2
  22. package/dist/server/server/workspace-archive-service.js +10 -2
  23. package/dist/server/server/workspace-git-service.d.ts +1 -0
  24. package/dist/server/server/workspace-git-service.js +31 -5
  25. package/dist/server/server/workspace-registry.d.ts +2 -0
  26. package/dist/server/server/workspace-registry.js +2 -0
  27. package/dist/server/terminal/terminal-worker-process.js +16 -14
  28. package/dist/server/terminal/terminal-worker-socket-path.d.ts +15 -1
  29. package/dist/server/terminal/terminal-worker-socket-path.js +57 -9
  30. package/dist/server/terminal-worker/terminal-worker.mjs +51 -23
  31. package/dist/server/utils/worktree.d.ts +14 -1
  32. package/dist/server/utils/worktree.js +58 -7
  33. package/dist/server/web-ui/_expo/static/js/web/{index-6de36f49f1c767e50d1cf95ae05eb46a.js → index-3d51f4c450eeff5bd838a646e9c611f2.js} +16 -16
  34. package/dist/server/web-ui/_expo/static/js/web/index-3d51f4c450eeff5bd838a646e9c611f2.js.br +0 -0
  35. package/dist/server/web-ui/_expo/static/js/web/index-3d51f4c450eeff5bd838a646e9c611f2.js.gz +0 -0
  36. package/dist/server/web-ui/index.html +1 -1
  37. package/dist/server/web-ui/index.html.br +0 -0
  38. package/dist/server/web-ui/index.html.gz +0 -0
  39. package/package.json +6 -6
  40. package/dist/server/web-ui/_expo/static/js/web/index-6de36f49f1c767e50d1cf95ae05eb46a.js.br +0 -0
  41. package/dist/server/web-ui/_expo/static/js/web/index-6de36f49f1c767e50d1cf95ae05eb46a.js.gz +0 -0
@@ -74,13 +74,29 @@ export function createWorkspaceRecoveryService(deps) {
74
74
  return { workspaceId, action: resolved.kind };
75
75
  }
76
76
  async function recreateArchivedWorktree(workspace, sourceRepoRoot) {
77
- const source = workspace.branch
78
- ? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }
79
- : {
77
+ let source;
78
+ const checkout = parseWorkspaceHead(workspace);
79
+ if (checkout.kind === "branch") {
80
+ source = {
81
+ kind: "restore",
82
+ branchName: checkout.branch,
83
+ baseRef: workspace.baseBranch,
84
+ };
85
+ }
86
+ else if (checkout.kind === "commit") {
87
+ source = {
88
+ kind: "restore-commit",
89
+ commit: checkout.commit,
90
+ baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
91
+ };
92
+ }
93
+ else {
94
+ source = {
80
95
  kind: "restore-from-base",
81
96
  branchName: `restored/${randomUUID().slice(0, 8)}`,
82
97
  baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
83
98
  };
99
+ }
84
100
  try {
85
101
  await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30000 });
86
102
  }
@@ -166,12 +182,22 @@ async function resolveRecoveryBase(repoRoot, recordedBase) {
166
182
  }
167
183
  return defaultBranch;
168
184
  }
185
+ function parseWorkspaceHead(workspace) {
186
+ if (workspace.head) {
187
+ const prefix = "refs/heads/";
188
+ return workspace.head.startsWith(prefix)
189
+ ? { kind: "branch", branch: workspace.head.slice(prefix.length) }
190
+ : { kind: "commit", commit: workspace.head };
191
+ }
192
+ return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" };
193
+ }
169
194
  function createRecoveryPlan(input) {
195
+ const checkout = parseWorkspaceHead(input.workspace);
170
196
  const state = {
171
197
  kind: "recoverable",
172
198
  workspaceId: input.workspace.workspaceId,
173
199
  workspaceName: resolveWorkspaceDisplayName(input.workspace),
174
- branch: input.workspace.branch,
200
+ branch: checkout.kind === "branch" ? checkout.branch : null,
175
201
  };
176
202
  if (input.action === "restore") {
177
203
  return {
@@ -33,6 +33,7 @@ export declare function createTestRegistries(): {
33
33
  metadata: Record<string, import("@getpaseo/protocol/agent-types").JsonValue>;
34
34
  background: boolean;
35
35
  parentWorkspaceId?: string | undefined;
36
+ head?: string | undefined;
36
37
  labels?: string[] | undefined;
37
38
  untrustedSource?: {
38
39
  kind: "change_request";
@@ -227,6 +227,11 @@ export declare class VoiceAssistantWebSocketServer {
227
227
  private broadcastAgentAttention;
228
228
  private broadcastTerminalAttention;
229
229
  }
230
+ /**
231
+ * Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
232
+ * upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
233
+ */
234
+ export declare function isDaemonOriginAllowed(origin: string, requestHost: string | null, allowedOrigins: Set<string>): boolean;
230
235
  export declare function isWebSocketSameOrigin(origin: string | undefined, requestHost: string | null): boolean;
231
236
  export {};
232
237
  //# sourceMappingURL=websocket-server.d.ts.map
@@ -562,8 +562,7 @@ export class VoiceAssistantWebSocketServer {
562
562
  callback(false, 403, "Host not allowed");
563
563
  return;
564
564
  }
565
- const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
566
- if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
565
+ if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
567
566
  callback(true);
568
567
  }
569
568
  else {
@@ -2426,6 +2425,15 @@ function isLoopbackAlias(hostname) {
2426
2425
  }
2427
2426
  return /^127(?:\.\d{1,3}){3}$/.test(normalized);
2428
2427
  }
2428
+ /**
2429
+ * Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
2430
+ * upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
2431
+ */
2432
+ export function isDaemonOriginAllowed(origin, requestHost, allowedOrigins) {
2433
+ return (allowedOrigins.has("*") ||
2434
+ allowedOrigins.has(origin) ||
2435
+ isWebSocketSameOrigin(origin, requestHost));
2436
+ }
2429
2437
  export function isWebSocketSameOrigin(origin, requestHost) {
2430
2438
  if (!origin || !requestHost) {
2431
2439
  return false;
@@ -1,5 +1,5 @@
1
1
  import { resolve } from "node:path";
2
- import { deletePaseoWorktree, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, } from "../utils/worktree.js";
2
+ import { deletePaseoWorktree, readWorktreeHeadReference, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, } from "../utils/worktree.js";
3
3
  import { createRealpathAwarePathMatcher } from "../utils/path.js";
4
4
  import { runWithGitCommandPriority } from "../utils/run-git-command.js";
5
5
  import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
@@ -418,7 +418,15 @@ export async function archivePersistedWorkspaceRecord(input) {
418
418
  return existingWorkspace;
419
419
  }
420
420
  const archivedAt = input.archivedAt ?? new Date().toISOString();
421
- await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
421
+ let head = null;
422
+ if (existingWorkspace.kind === "worktree") {
423
+ const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
424
+ head = await readWorktreeHeadReference(cwd);
425
+ }
426
+ await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
427
+ ...input.context,
428
+ ...(head ? { head } : {}),
429
+ });
422
430
  return existingWorkspace;
423
431
  }
424
432
  export async function unarchiveWorkspaceAgents(input) {
@@ -323,6 +323,7 @@ export declare class WorkspaceGitServiceImpl implements WorkspaceGitService {
323
323
  * rule.
324
324
  */
325
325
  private advanceWatchRecoveryLadder;
326
+ private noteWatchSetupFailure;
326
327
  private scheduleWorkingTreeWatchRecovery;
327
328
  private recoverWorkingTreeWatch;
328
329
  private promoteWorkingTreeWatchTarget;
@@ -65,6 +65,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30000;
65
65
  // restart, which kills running agents. Back off, but keep trying.
66
66
  const WATCH_RECOVERY_MAX_DELAY_MS = 300000;
67
67
  const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4;
68
+ // A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the
69
+ // next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore
70
+ // keep doubling the recovery delay past the ladder cap, up to an hour.
71
+ const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3600000;
72
+ const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7;
68
73
  // Auxiliary reads may reuse cached values within this window; snapshots do not expire on read.
69
74
  const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15000;
70
75
  // Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it.
@@ -854,7 +859,7 @@ export class WorkspaceGitServiceImpl {
854
859
  fallbackPolling: false,
855
860
  fallbackPollTimer: null,
856
861
  fallbackPollQuietTickCount: 0,
857
- recovery: { attemptCount: 0, timer: null, establishedAt: null },
862
+ recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
858
863
  listeners: new Set(),
859
864
  closed: false,
860
865
  };
@@ -875,9 +880,12 @@ export class WorkspaceGitServiceImpl {
875
880
  let removeAbortListener = () => { };
876
881
  let unsubscribePromise = null;
877
882
  let subscriptionPromise;
883
+ // Abandoning the race is not enough: the observer's startup scan would keep walking the
884
+ // tree after the deadline. Abort it so a timed-out attempt stops costing CPU.
885
+ const setupController = new AbortController();
878
886
  try {
879
887
  subscriptionPromise = this.deps
880
- .subscribe(watchPath, callback, options)
888
+ .subscribe(watchPath, callback, { ...options, signal: setupController.signal })
881
889
  .finally(onSubscribeSettled);
882
890
  }
883
891
  catch (error) {
@@ -894,12 +902,15 @@ export class WorkspaceGitServiceImpl {
894
902
  const timeoutPromise = new Promise((_resolve, reject) => {
895
903
  timeout = setTimeout(() => {
896
904
  outcome = "expired";
897
- reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath));
905
+ const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
906
+ setupController.abort(error);
907
+ reject(error);
898
908
  }, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
899
909
  });
900
910
  const disposalPromise = new Promise((_resolve, reject) => {
901
911
  const rejectForDisposal = () => {
902
912
  outcome = "expired";
913
+ setupController.abort(signal.reason);
903
914
  reject(signal.reason);
904
915
  };
905
916
  if (signal.aborted) {
@@ -1016,6 +1027,7 @@ export class WorkspaceGitServiceImpl {
1016
1027
  // `scheduleWorkingTreeWatchRecovery` only resets the ladder once this
1017
1028
  // one has survived long enough to prove itself durable.
1018
1029
  target.recovery.establishedAt = this.deps.now().getTime();
1030
+ target.recovery.setupTimeoutCount = 0;
1019
1031
  if (options?.replaceFallback && target.repoRoot !== null) {
1020
1032
  target.fallbackPolling = false;
1021
1033
  if (target.fallbackPollTimer) {
@@ -1034,6 +1046,7 @@ export class WorkspaceGitServiceImpl {
1034
1046
  return false;
1035
1047
  }
1036
1048
  this.logger.warn({ err: error, cwd: target.cwd }, "Failed to start working tree watcher; using degraded polling");
1049
+ this.noteWatchSetupFailure(target.recovery, error);
1037
1050
  if (!options?.replaceFallback) {
1038
1051
  this.startWorkingTreeWatchFallback(target, "watcher_setup_failed");
1039
1052
  }
@@ -1220,8 +1233,19 @@ export class WorkspaceGitServiceImpl {
1220
1233
  }
1221
1234
  recovery.establishedAt = null;
1222
1235
  recovery.attemptCount += 1;
1223
- return Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1236
+ const ladderDelayMs = Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1224
1237
  2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS), WATCH_RECOVERY_MAX_DELAY_MS);
1238
+ if (recovery.setupTimeoutCount === 0) {
1239
+ return ladderDelayMs;
1240
+ }
1241
+ const setupTimeoutDelayMs = Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1242
+ 2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS), WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS);
1243
+ return Math.max(ladderDelayMs, setupTimeoutDelayMs);
1244
+ }
1245
+ noteWatchSetupFailure(recovery, error) {
1246
+ if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) {
1247
+ recovery.setupTimeoutCount += 1;
1248
+ }
1225
1249
  }
1226
1250
  scheduleWorkingTreeWatchRecovery(target) {
1227
1251
  if (target.closed || target.subscription || target.recovery.timer) {
@@ -1648,7 +1672,7 @@ export class WorkspaceGitServiceImpl {
1648
1672
  fallbackPolling: false,
1649
1673
  fallbackPollTimer: null,
1650
1674
  fallbackPollQuietTickCount: 0,
1651
- recovery: { attemptCount: 0, timer: null, establishedAt: null },
1675
+ recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
1652
1676
  intervalId: null,
1653
1677
  fetchInFlight: false,
1654
1678
  bufferedFetchMetadataEvents: [],
@@ -1765,6 +1789,7 @@ export class WorkspaceGitServiceImpl {
1765
1789
  // subscribe success alone, only record when this subscription was
1766
1790
  // established.
1767
1791
  target.recovery.establishedAt = this.deps.now().getTime();
1792
+ target.recovery.setupTimeoutCount = 0;
1768
1793
  if (options?.replaceFallback) {
1769
1794
  target.fallbackPolling = false;
1770
1795
  if (target.fallbackPollTimer) {
@@ -1786,6 +1811,7 @@ export class WorkspaceGitServiceImpl {
1786
1811
  return false;
1787
1812
  }
1788
1813
  this.logger.warn({ err: error, repoGitRoot: target.repoGitRoot }, "Failed to start repository metadata watcher; using degraded polling");
1814
+ this.noteWatchSetupFailure(target.recovery, error);
1789
1815
  if (!options?.replaceFallback) {
1790
1816
  this.startRepoMetadataFallback(target);
1791
1817
  }
@@ -31,6 +31,7 @@ declare const PersistedWorkspaceRecordSchema: z.ZodObject<{
31
31
  displayName: z.ZodString;
32
32
  title: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
33
33
  branch: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
34
+ head: z.ZodOptional<z.ZodString>;
34
35
  worktreeRoot: z.ZodDefault<z.ZodNullable<z.ZodString>>;
35
36
  baseBranch: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
36
37
  isPaseoOwnedWorktree: z.ZodDefault<z.ZodBoolean>;
@@ -63,6 +64,7 @@ export interface WorkspaceMutationContext {
63
64
  }
64
65
  export interface WorkspaceArchiveContext {
65
66
  autoArchivedChangeRequestUrl?: string;
67
+ head?: string;
66
68
  }
67
69
  export interface ProjectMutation {
68
70
  kind: "upsert" | "archive" | "remove";
@@ -60,6 +60,7 @@ const PersistedWorkspaceRecordSchema = z.object({
60
60
  .nullable()
61
61
  .optional()
62
62
  .transform((value) => value ?? null),
63
+ head: z.string().optional(),
63
64
  // Exact checkout/worktree root backing cwd. This differs from cwd when the
64
65
  // selected project is a subdirectory inside a repository. Persist it so
65
66
  // archive and recovery do not need the directory to still exist in order to
@@ -395,6 +396,7 @@ export class FileBackedWorkspaceRegistry extends FileBackedRegistry {
395
396
  ...existing,
396
397
  updatedAt: archivedAt,
397
398
  archivedAt,
399
+ head: context?.head,
398
400
  ...(context?.autoArchivedChangeRequestUrl
399
401
  ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
400
402
  : {}),
@@ -12,7 +12,7 @@ import { attachFramedSocket } from "./terminal-worker-frames.js";
12
12
  import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js";
13
13
  import { TERMINAL_WORKER_MARKER_ARG, terminalWorkerLogPath, terminalWorkerRecordPath, writeTerminalWorkerRecord, } from "./terminal-worker-record.js";
14
14
  import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
15
- import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
15
+ import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
16
16
  import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, TERMINAL_WORKER_PROTOCOL_VERSION, } from "./terminal-worker-protocol.js";
17
17
  // The terminal worker owns every PTY. It runs detached from the daemon (re-parented by the
18
18
  // launcher below) so a daemon restart, crash or forced kill of the daemon's process tree does
@@ -613,23 +613,25 @@ function runWorker(argv) {
613
613
  }
614
614
  }
615
615
  async function start() {
616
- const socketPath = resolveTerminalWorkerSocketPath({
616
+ const { socketPath, listener } = await listenOnTerminalWorkerSocket({
617
617
  paseoHome: args.paseoHome,
618
618
  workerPid: process.pid,
619
619
  recordId: args.recordId,
620
+ listen: (candidatePath) => {
621
+ if (process.platform !== "win32") {
622
+ rmSync(candidatePath, { force: true });
623
+ }
624
+ const listening = createServer(handleConnection);
625
+ return new Promise((resolve, reject) => {
626
+ listening.once("error", reject);
627
+ listening.listen(candidatePath, () => {
628
+ listening.off("error", reject);
629
+ resolve(listening);
630
+ });
631
+ });
632
+ },
620
633
  });
621
- if (process.platform !== "win32") {
622
- rmSync(socketPath, { force: true });
623
- }
624
- const listening = createServer(handleConnection);
625
- await new Promise((resolve, reject) => {
626
- listening.once("error", reject);
627
- listening.listen(socketPath, () => {
628
- listening.off("error", reject);
629
- resolve();
630
- });
631
- });
632
- server = listening;
634
+ server = listener;
633
635
  if (process.platform !== "win32") {
634
636
  chmodSync(socketPath, PRIVATE_FILE_MODE);
635
637
  }
@@ -6,6 +6,14 @@ export interface TerminalWorkerSocketPathInput {
6
6
  tmpDir?: string;
7
7
  uid?: number;
8
8
  }
9
+ export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
10
+ /** Binds a fresh listener at the path, removing any stale socket there first. */
11
+ listen: (socketPath: string) => Promise<T>;
12
+ }
13
+ export interface TerminalWorkerSocketListener<T> {
14
+ socketPath: string;
15
+ listener: T;
16
+ }
9
17
  export interface RejectedSocketCandidate {
10
18
  path: string;
11
19
  byteLength: number;
@@ -21,7 +29,13 @@ export declare function terminalWorkerSocketId(paseoHome: string, workerPid: num
21
29
  * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
22
30
  * tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
23
31
  * A shared root is never chmodded: an existing directory there is used only when it is a real
24
- * directory owned by this user with mode 0700.
32
+ * directory owned by this user with mode 0700. It does not bind; the worker listens through
33
+ * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
25
34
  */
26
35
  export declare function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string;
36
+ /**
37
+ * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
38
+ * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
39
+ */
40
+ export declare function listenOnTerminalWorkerSocket<T>(input: TerminalWorkerSocketListenInput<T>): Promise<TerminalWorkerSocketListener<T>>;
27
41
  //# sourceMappingURL=terminal-worker-socket-path.d.ts.map
@@ -13,10 +13,13 @@ const SOCKET_PATH_BYTE_BUDGET = {
13
13
  };
14
14
  const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
15
15
  const OWNER_ONLY_MODE = 0o700;
16
+ // Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
17
+ // network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
18
+ const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
16
19
  export class TerminalWorkerSocketPathError extends Error {
17
20
  constructor(rejected, budget) {
18
21
  super([
19
- `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
22
+ `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
20
23
  ...rejected.map((candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`),
21
24
  ].join("\n"));
22
25
  this.name = "TerminalWorkerSocketPathError";
@@ -32,17 +35,64 @@ export function terminalWorkerSocketId(paseoHome, workerPid) {
32
35
  * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
33
36
  * tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
34
37
  * A shared root is never chmodded: an existing directory there is used only when it is a real
35
- * directory owned by this user with mode 0700.
38
+ * directory owned by this user with mode 0700. It does not bind; the worker listens through
39
+ * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
36
40
  */
37
41
  export function resolveTerminalWorkerSocketPath(input) {
38
42
  const platform = input.platform ?? process.platform;
39
- const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
40
43
  if (platform === "win32") {
41
- return `\\\\.\\pipe\\paseo-tw-${id}`;
44
+ return windowsPipePath(input);
42
45
  }
46
+ const budget = socketPathByteBudget(platform);
47
+ const rejected = [];
48
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
49
+ return candidate.path;
50
+ }
51
+ throw new TerminalWorkerSocketPathError(rejected, budget);
52
+ }
53
+ /**
54
+ * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
55
+ * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
56
+ */
57
+ export async function listenOnTerminalWorkerSocket(input) {
58
+ const { listen } = input;
59
+ const platform = input.platform ?? process.platform;
60
+ if (platform === "win32") {
61
+ const socketPath = windowsPipePath(input);
62
+ return { socketPath, listener: await listen(socketPath) };
63
+ }
64
+ const budget = socketPathByteBudget(platform);
65
+ const rejected = [];
66
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
67
+ try {
68
+ return { socketPath: candidate.path, listener: await listen(candidate.path) };
69
+ }
70
+ catch (error) {
71
+ const code = error.code;
72
+ if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code))
73
+ throw error;
74
+ rejected.push({
75
+ path: candidate.path,
76
+ byteLength: candidate.byteLength,
77
+ reason: `cannot bind a socket here (${code})`,
78
+ });
79
+ }
80
+ }
81
+ throw new TerminalWorkerSocketPathError(rejected, budget);
82
+ }
83
+ function windowsPipePath(input) {
84
+ return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
85
+ }
86
+ function socketFileId(input) {
87
+ return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
88
+ }
89
+ function socketPathByteBudget(platform) {
90
+ return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
91
+ }
92
+ /** Yields each candidate that fits the budget in an owner-only directory, in order. */
93
+ function* eligibleUnixSocketPaths(input, budget, rejected) {
43
94
  const uid = input.uid ?? process.getuid?.() ?? 0;
44
- const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
45
- const fileName = `tw-${id}.sock`;
95
+ const fileName = `tw-${socketFileId(input)}.sock`;
46
96
  const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
47
97
  const candidates = [
48
98
  {
@@ -60,7 +110,6 @@ export function resolveTerminalWorkerSocketPath(input) {
60
110
  };
61
111
  }),
62
112
  ];
63
- const rejected = [];
64
113
  const seen = new Set();
65
114
  for (const candidate of candidates) {
66
115
  const socketPath = path.join(candidate.directory, fileName);
@@ -83,9 +132,8 @@ export function resolveTerminalWorkerSocketPath(input) {
83
132
  rejected.push({ path: socketPath, byteLength, reason: problem });
84
133
  continue;
85
134
  }
86
- return socketPath;
135
+ yield { path: socketPath, byteLength };
87
136
  }
88
- throw new TerminalWorkerSocketPathError(rejected, budget);
89
137
  }
90
138
  function prepareSharedRootDirectory(directory, uid) {
91
139
  try {
@@ -22006,11 +22006,12 @@ var SOCKET_PATH_BYTE_BUDGET = {
22006
22006
  };
22007
22007
  var DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
22008
22008
  var OWNER_ONLY_MODE = 448;
22009
+ var SOCKET_UNSUPPORTED_BIND_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
22009
22010
  var TerminalWorkerSocketPathError = class extends Error {
22010
22011
  constructor(rejected, budget) {
22011
22012
  super(
22012
22013
  [
22013
- `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
22014
+ `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
22014
22015
  ...rejected.map(
22015
22016
  (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`
22016
22017
  )
@@ -22024,15 +22025,42 @@ function terminalWorkerSocketId(paseoHome, workerPid) {
22024
22025
  const digest = createHash("sha256").update(path4.resolve(paseoHome)).digest("hex");
22025
22026
  return `${digest.slice(0, 16)}-${workerPid}`;
22026
22027
  }
22027
- function resolveTerminalWorkerSocketPath(input) {
22028
+ async function listenOnTerminalWorkerSocket(input) {
22029
+ const { listen } = input;
22028
22030
  const platform = input.platform ?? process.platform;
22029
- const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
22030
22031
  if (platform === "win32") {
22031
- return `\\\\.\\pipe\\paseo-tw-${id}`;
22032
+ const socketPath = windowsPipePath(input);
22033
+ return { socketPath, listener: await listen(socketPath) };
22032
22034
  }
22035
+ const budget = socketPathByteBudget(platform);
22036
+ const rejected = [];
22037
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
22038
+ try {
22039
+ return { socketPath: candidate.path, listener: await listen(candidate.path) };
22040
+ } catch (error51) {
22041
+ const code = error51.code;
22042
+ if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error51;
22043
+ rejected.push({
22044
+ path: candidate.path,
22045
+ byteLength: candidate.byteLength,
22046
+ reason: `cannot bind a socket here (${code})`
22047
+ });
22048
+ }
22049
+ }
22050
+ throw new TerminalWorkerSocketPathError(rejected, budget);
22051
+ }
22052
+ function windowsPipePath(input) {
22053
+ return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
22054
+ }
22055
+ function socketFileId(input) {
22056
+ return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
22057
+ }
22058
+ function socketPathByteBudget(platform) {
22059
+ return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
22060
+ }
22061
+ function* eligibleUnixSocketPaths(input, budget, rejected) {
22033
22062
  const uid = input.uid ?? process.getuid?.() ?? 0;
22034
- const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
22035
- const fileName = `tw-${id}.sock`;
22063
+ const fileName = `tw-${socketFileId(input)}.sock`;
22036
22064
  const homeSocketDirectory = path4.join(terminalWorkerDirectory(input.paseoHome), "sock");
22037
22065
  const candidates = [
22038
22066
  {
@@ -22050,7 +22078,6 @@ function resolveTerminalWorkerSocketPath(input) {
22050
22078
  };
22051
22079
  })
22052
22080
  ];
22053
- const rejected = [];
22054
22081
  const seen = /* @__PURE__ */ new Set();
22055
22082
  for (const candidate of candidates) {
22056
22083
  const socketPath = path4.join(candidate.directory, fileName);
@@ -22071,9 +22098,8 @@ function resolveTerminalWorkerSocketPath(input) {
22071
22098
  rejected.push({ path: socketPath, byteLength, reason: problem });
22072
22099
  continue;
22073
22100
  }
22074
- return socketPath;
22101
+ yield { path: socketPath, byteLength };
22075
22102
  }
22076
- throw new TerminalWorkerSocketPathError(rejected, budget);
22077
22103
  }
22078
22104
  function prepareSharedRootDirectory(directory, uid) {
22079
22105
  try {
@@ -22651,23 +22677,25 @@ function runWorker(argv) {
22651
22677
  }
22652
22678
  }
22653
22679
  async function start() {
22654
- const socketPath = resolveTerminalWorkerSocketPath({
22680
+ const { socketPath, listener } = await listenOnTerminalWorkerSocket({
22655
22681
  paseoHome: args.paseoHome,
22656
22682
  workerPid: process.pid,
22657
- recordId: args.recordId
22658
- });
22659
- if (process.platform !== "win32") {
22660
- rmSync2(socketPath, { force: true });
22661
- }
22662
- const listening = createServer(handleConnection);
22663
- await new Promise((resolve4, reject) => {
22664
- listening.once("error", reject);
22665
- listening.listen(socketPath, () => {
22666
- listening.off("error", reject);
22667
- resolve4();
22668
- });
22683
+ recordId: args.recordId,
22684
+ listen: (candidatePath) => {
22685
+ if (process.platform !== "win32") {
22686
+ rmSync2(candidatePath, { force: true });
22687
+ }
22688
+ const listening = createServer(handleConnection);
22689
+ return new Promise((resolve4, reject) => {
22690
+ listening.once("error", reject);
22691
+ listening.listen(candidatePath, () => {
22692
+ listening.off("error", reject);
22693
+ resolve4(listening);
22694
+ });
22695
+ });
22696
+ }
22669
22697
  });
22670
- server = listening;
22698
+ server = listener;
22671
22699
  if (process.platform !== "win32") {
22672
22700
  chmodSync3(socketPath, PRIVATE_FILE_MODE);
22673
22701
  }
@@ -108,6 +108,10 @@ export type WorktreeSource = {
108
108
  kind: "restore";
109
109
  branchName: string;
110
110
  baseRef: string | null;
111
+ } | {
112
+ kind: "restore-commit";
113
+ commit: string;
114
+ baseRef: string;
111
115
  } | {
112
116
  kind: "restore-from-base";
113
117
  baseRef: string;
@@ -226,6 +230,8 @@ export interface DeletePaseoWorktreeOptions {
226
230
  worktreesBaseRoot?: string;
227
231
  registryProven?: boolean;
228
232
  }
233
+ export declare function readWorktreeHead(worktreePath: string): Promise<string | null>;
234
+ export declare function readWorktreeHeadReference(worktreePath: string): Promise<string | null>;
229
235
  export declare function deletePaseoWorktree({ cwd, worktreePath, teardownCwds, worktreeSlug, worktreesRoot, paseoHome, worktreesBaseRoot, registryProven, }: DeletePaseoWorktreeOptions): Promise<void>;
230
236
  export declare function rollbackCreatedPaseoWorktree(options: DeletePaseoWorktreeOptions, cause: unknown): Promise<never>;
231
237
  /** Resolve the default placement once, before presenting it to creation hooks. */
@@ -233,5 +239,12 @@ export declare function resolveDefaultWorktreePath(options: Pick<CreateWorktreeO
233
239
  /**
234
240
  * Create a git worktree with proper naming conventions
235
241
  */
236
- export declare const createWorktree: ({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, }: CreateWorktreeOptions) => Promise<CreatedWorktree>;
242
+ export declare function createWorktree(options: CreateWorktreeOptions & {
243
+ source: Exclude<WorktreeSource, {
244
+ kind: "restore-commit";
245
+ }>;
246
+ }): Promise<CreatedWorktree>;
247
+ export declare function createWorktree(options: CreateWorktreeOptions): Promise<Omit<CreatedWorktree, "branchName"> & {
248
+ branchName: string | null;
249
+ }>;
237
250
  //# sourceMappingURL=worktree.d.ts.map