pi-better-server 0.7.0 → 0.7.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 (105) hide show
  1. package/package.json +1 -1
  2. package/src/codex/return.ts +3 -2
  3. package/src/detach/extension.ts +20 -3
  4. package/src/event-log.ts +40 -12
  5. package/src/hosted-session.ts +11 -5
  6. package/src/remote-client/packages.ts +1 -4
  7. package/src/runtime/background-tools.ts +2 -1
  8. package/src/runtime/domain/background/registry.mjs +3 -0
  9. package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
  10. package/src/runtime/domain/background/terminal-publication.mjs +5 -2
  11. package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
  12. package/src/runtime/domain/background-service/managed-authority.ts +16 -0
  13. package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
  14. package/src/runtime/domain/background-service/managed-client.ts +2 -2
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
  16. package/src/runtime/domain/background-service/observed-waits.ts +8 -4
  17. package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
  18. package/src/runtime/domain/background-service/registry.ts +2 -0
  19. package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
  20. package/src/runtime/domain/background-service/runtime.ts +3 -2
  21. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  22. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
  29. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  30. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  31. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
  33. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
  34. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
  35. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  37. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  38. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
  39. package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
  40. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
  41. package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
  42. package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
  43. package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
  44. package/src/runtime/domain/background-service/tools.ts +3 -2
  45. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  46. package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
  47. package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
  48. package/src/runtime/domain/coordinator/src/store.mjs +3 -0
  49. package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
  50. package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
  51. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  52. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  53. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  54. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
  55. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
  56. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  57. package/src/runtime/domain/subagents/README.md +2 -2
  58. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  59. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  60. package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
  61. package/src/runtime/domain/subagents/cleanup.ts +4 -1
  62. package/src/runtime/domain/subagents/config.ts +1 -1
  63. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  64. package/src/runtime/domain/subagents/finalization.domain.mjs +34 -30
  65. package/src/runtime/domain/subagents/finalization.ts +30 -28
  66. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  67. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  68. package/src/runtime/domain/subagents/index.domain.mjs +99 -54
  69. package/src/runtime/domain/subagents/index.ts +100 -51
  70. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +7 -14
  71. package/src/runtime/domain/subagents/isolated-workspace.ts +6 -12
  72. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
  73. package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
  74. package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
  75. package/src/runtime/domain/subagents/package.json +1 -1
  76. package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
  77. package/src/runtime/domain/subagents/registry.domain.mjs +40 -14
  78. package/src/runtime/domain/subagents/registry.ts +26 -12
  79. package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
  80. package/src/runtime/domain/subagents/settings-page.ts +10 -10
  81. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  82. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  83. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  84. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
  85. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  86. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
  87. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
  88. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
  89. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  90. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  91. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  92. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
  93. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
  94. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
  95. package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
  96. package/src/runtime/domain/subagents/stop.ts +7 -5
  97. package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
  98. package/src/runtime/domain/subagents/timing.ts +11 -4
  99. package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
  100. package/src/runtime/domain/subagents/workspace-files.ts +6 -6
  101. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  102. package/src/runtime/task-expiry.ts +52 -0
  103. package/src/server.ts +4 -0
  104. package/src/shared-ssh-core/index.ts +1 -1
  105. package/src/version.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/cleanup.ts. Do not edit directly.
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
3
  import { join, relative, sep } from "node:path";
4
- import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
4
+ import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, launchAttemptInProgress, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
5
5
  import { ConversationBusyError, ConversationLockUnavailableError, conversationLeaseDir, readConversationLease, readRetention, retainedRunIds, retainedSessionIds, withConversationMutation, } from "./continuation.domain.mjs";
6
6
  import { processExists } from "./spawn.domain.mjs";
7
7
  import { archiveCompletedAttempt, archivePublicationPending, listArchivedAttempts } from "./session-store.domain.mjs";
@@ -108,6 +108,9 @@ function safeStatMtime(path) {
108
108
  /** A metadata-less run directory, with its provenance record (#325). */
109
109
  function removeRun(id, errors) {
110
110
  try {
111
+ // A concurrent launch publishes its claim before metadata and drops it after publication.
112
+ if (launchAttemptInProgress(id) || readMeta(id))
113
+ return false;
111
114
  removeRunDirectory(id);
112
115
  return true;
113
116
  }
@@ -777,7 +780,7 @@ export function enforceRegistrySizeCapOnce(options = {}) {
777
780
  // the shortfall it reports stay honest.
778
781
  const keptBytes = plan.keptBytes + retainedBytes;
779
782
  try {
780
- writeCleanupState({ ...state, lastSizeSweepAt: now });
783
+ writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
781
784
  }
782
785
  catch (err) {
783
786
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
@@ -11,6 +11,7 @@ import { join, relative, sep } from "node:path";
11
11
  import { ABANDONED_LAUNCH_GRACE_MS,
12
12
  abandonedLaunchRecord,
13
13
  baseDir,
14
+ launchAttemptInProgress,
14
15
  listMetas,
15
16
  observeArchivePublication,
16
17
  ownedByThisParent,
@@ -236,6 +237,8 @@ function safeStatMtime(path: string): number | undefined {
236
237
  /** A metadata-less run directory, with its provenance record (#325). */
237
238
  function removeRun(id: string, errors: string[]): boolean {
238
239
  try {
240
+ // A concurrent launch publishes its claim before metadata and drops it after publication.
241
+ if (launchAttemptInProgress(id) || readMeta(id)) return false;
239
242
  removeRunDirectory(id);
240
243
  return true;
241
244
  } catch (err) {
@@ -977,7 +980,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
977
980
  const keptBytes = plan.keptBytes + retainedBytes;
978
981
 
979
982
  try {
980
- writeCleanupState({ ...state, lastSizeSweepAt: now });
983
+ writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
981
984
  } catch (err) {
982
985
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
983
986
  }
@@ -45,7 +45,7 @@ export interface SubagentConfig extends TimingSettings {
45
45
  /**
46
46
  * Provider → extension package(s) that authenticate it. Model auth is not
47
47
  * tool-shaped: `xai/grok-4.5` needs pi-xai-oauth loaded whatever the tools.
48
- * A built-in entry covers `ollama-cloud`; an entry here replaces it.
48
+ * Entries here override built-in mappings, including Ollama Cloud and LiteLLM.
49
49
  */
50
50
  providerExtensions?: Record<string, string | string[]> | null;
51
51
  /**
@@ -47,6 +47,7 @@ export const SELF_SPEC = "self";
47
47
  export const BUILTIN_PROVIDER_EXTENSIONS = {
48
48
  "router": "npm:pi-better-model-router",
49
49
  "ollama-cloud": "npm:pi-ollama-cloud",
50
+ "litellm": "npm:pi-provider-litellm",
50
51
  };
51
52
  /** Split "xai/grok-4.5" -> "xai". Returns undefined when there is no provider. */
52
53
  export function providerOf(model) {
@@ -33,15 +33,15 @@ export function reconcileInterruptedRun(meta, probe, now, hooks = {}) {
33
33
  * and builds the completion callback delivery from real log evidence.
34
34
  */
35
35
  export function finalizeRun(id, code, hooks = {}) {
36
- const meta = readMeta(id);
36
+ const initial = readMeta(id);
37
37
  // Coherent child-exit evidence may supersede provisional orphaned/lost
38
38
  // reconciliation, but never overwrites a true terminal record.
39
- if (!meta || !canExitFinalize(meta.status))
39
+ if (!initial || !canExitFinalize(initial.status))
40
40
  return { applied: false };
41
41
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
42
42
  const r = parseRunForLifecycle(id);
43
43
  const outcome = classifyChildExit(code, r);
44
- collectRunFailures(id, meta.cwd, true);
44
+ collectRunFailures(id, initial.cwd, true);
45
45
  // A run can now end exit 0 as failed (a final request the model could not
46
46
  // serve), so "not incomplete and has an exit code" no longer means success.
47
47
  const completed = outcome.status === "completed";
@@ -59,12 +59,6 @@ export function finalizeRun(id, code, hooks = {}) {
59
59
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
60
60
  category: "exit", summary }]);
61
61
  }
62
- meta.status = outcome.status;
63
- meta.lifecycleClassification = outcome.classification;
64
- if (outcome.incomplete)
65
- meta.failureReason = "incomplete-stream";
66
- meta.exitCode = code;
67
- meta.endedAt = Date.now();
68
62
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
69
63
  // with a durable park record whose saved-conversation checkpoint still
70
64
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
@@ -77,27 +71,37 @@ export function finalizeRun(id, code, hooks = {}) {
77
71
  && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
78
72
  });
79
73
  const parked = park.parked && park.record !== undefined;
80
- if (parked && park.record) {
81
- meta.park = park.record;
82
- // The rest of the attempt is complete; the assignment is still waiting.
83
- meta.status = "completed";
84
- }
74
+ const endedAt = Date.now();
75
+ const meta = writeMeta(initial, { patch: current => {
76
+ if (!canExitFinalize(current.status))
77
+ return undefined;
78
+ const patch = {
79
+ status: outcome.status,
80
+ lifecycleClassification: outcome.classification,
81
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
82
+ exitCode: code,
83
+ endedAt,
84
+ };
85
+ if (parked && park.record)
86
+ patch.park = park.record;
87
+ if (current.callback !== false
88
+ && current.completionCallbackPendingAt === undefined
89
+ && current.completionCallbackSentAt === undefined
90
+ && current.completionCallbackSuppressedAt === undefined) {
91
+ if (parked) {
92
+ // The continuation reports the assignment's result.
93
+ patch.completionCallbackSuppressedAt = endedAt;
94
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
95
+ }
96
+ else {
97
+ patch.completionCallbackPendingAt = endedAt;
98
+ }
99
+ }
100
+ return patch;
101
+ } });
102
+ if (!meta)
103
+ return { applied: false };
85
104
  const callback = meta.callback !== false;
86
- if (callback
87
- && meta.completionCallbackPendingAt === undefined
88
- && meta.completionCallbackSentAt === undefined
89
- && meta.completionCallbackSuppressedAt === undefined) {
90
- if (parked) {
91
- // A parked attempt owes no completion callback: the continuation
92
- // resumes the same conversation and reports the assignment's result.
93
- meta.completionCallbackSuppressedAt = meta.endedAt;
94
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
95
- }
96
- else {
97
- meta.completionCallbackPendingAt = meta.endedAt;
98
- }
99
- }
100
- writeMeta(meta);
101
105
  commitAssignmentTerminal(meta);
102
106
  if (!parked && park.record) {
103
107
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -112,7 +116,7 @@ export function finalizeRun(id, code, hooks = {}) {
112
116
  const verdict = parked
113
117
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
114
118
  : outcome.verdict;
115
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
119
+ const el = fmtElapsed(endedAt - meta.startedAt);
116
120
  const spend = fmtSpend(r.usage);
117
121
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
118
122
  const stat = el;
@@ -72,15 +72,15 @@ export function finalizeRun(
72
72
  code: number | null,
73
73
  hooks: FinalizeHooks = {},
74
74
  ): FinalizeResult {
75
- const meta = readMeta(id);
75
+ const initial = readMeta(id);
76
76
  // Coherent child-exit evidence may supersede provisional orphaned/lost
77
77
  // reconciliation, but never overwrites a true terminal record.
78
- if (!meta || !canExitFinalize(meta.status)) return { applied: false };
78
+ if (!initial || !canExitFinalize(initial.status)) return { applied: false };
79
79
 
80
80
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
81
81
  const r = parseRunForLifecycle(id);
82
82
  const outcome = classifyChildExit(code, r);
83
- collectRunFailures(id, meta.cwd, true);
83
+ collectRunFailures(id, initial.cwd, true);
84
84
  // A run can now end exit 0 as failed (a final request the model could not
85
85
  // serve), so "not incomplete and has an exit code" no longer means success.
86
86
  const completed = outcome.status === "completed";
@@ -98,11 +98,6 @@ export function finalizeRun(
98
98
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
99
99
  category: "exit", summary }]);
100
100
  }
101
- meta.status = outcome.status;
102
- meta.lifecycleClassification = outcome.classification;
103
- if (outcome.incomplete) meta.failureReason = "incomplete-stream";
104
- meta.exitCode = code;
105
- meta.endedAt = Date.now();
106
101
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
107
102
  // with a durable park record whose saved-conversation checkpoint still
108
103
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
@@ -115,26 +110,33 @@ export function finalizeRun(
115
110
  && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
116
111
  });
117
112
  const parked = park.parked && park.record !== undefined;
118
- if (parked && park.record) {
119
- meta.park = park.record;
120
- // The rest of the attempt is complete; the assignment is still waiting.
121
- meta.status = "completed";
122
- }
123
- const callback = meta.callback !== false;
124
- if (callback
125
- && meta.completionCallbackPendingAt === undefined
126
- && meta.completionCallbackSentAt === undefined
127
- && meta.completionCallbackSuppressedAt === undefined) {
128
- if (parked) {
129
- // A parked attempt owes no completion callback: the continuation
130
- // resumes the same conversation and reports the assignment's result.
131
- meta.completionCallbackSuppressedAt = meta.endedAt;
132
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
133
- } else {
134
- meta.completionCallbackPendingAt = meta.endedAt;
113
+ const endedAt = Date.now();
114
+ const meta = writeMeta(initial, { patch: current => {
115
+ if (!canExitFinalize(current.status)) return undefined;
116
+ const patch: Partial<RunMeta> = {
117
+ status: outcome.status,
118
+ lifecycleClassification: outcome.classification,
119
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
120
+ exitCode: code,
121
+ endedAt,
122
+ };
123
+ if (parked && park.record) patch.park = park.record;
124
+ if (current.callback !== false
125
+ && current.completionCallbackPendingAt === undefined
126
+ && current.completionCallbackSentAt === undefined
127
+ && current.completionCallbackSuppressedAt === undefined) {
128
+ if (parked) {
129
+ // The continuation reports the assignment's result.
130
+ patch.completionCallbackSuppressedAt = endedAt;
131
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
132
+ } else {
133
+ patch.completionCallbackPendingAt = endedAt;
134
+ }
135
135
  }
136
- }
137
- writeMeta(meta);
136
+ return patch;
137
+ } });
138
+ if (!meta) return { applied: false };
139
+ const callback = meta.callback !== false;
138
140
  commitAssignmentTerminal(meta);
139
141
  if (!parked && park.record) {
140
142
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -150,7 +152,7 @@ export function finalizeRun(
150
152
  const verdict = parked
151
153
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
152
154
  : outcome.verdict;
153
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
155
+ const el = fmtElapsed(endedAt - meta.startedAt);
154
156
  const spend = fmtSpend(r.usage);
155
157
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
156
158
  const stat = el;
@@ -21,21 +21,27 @@
21
21
  */
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
  import { readGitRemotes, syncGitRemotes } from "./git-remotes.domain.mjs";
26
26
  export { readGitRemotes, syncGitRemotes };
27
- function runGit(cwd, args, opts) {
27
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
28
+ function runGit(cwd, args, env) {
28
29
  try {
29
30
  return execFileSync("git", args, {
30
31
  cwd,
31
32
  encoding: "utf-8",
32
33
  stdio: ["ignore", "pipe", "pipe"],
33
- ...opts,
34
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
35
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
36
+ killSignal: "SIGKILL",
34
37
  }).trim();
35
38
  }
36
39
  catch (err) {
40
+ if (err.code === "ETIMEDOUT") {
41
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
42
+ }
37
43
  const message = err.message ?? String(err);
38
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
44
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
39
45
  }
40
46
  }
41
47
  /** Resolve `path` to an absolute, real path. Falls back to resolve() if the path does not exist. */
@@ -226,6 +232,45 @@ function hasLinkedWorktreePointer(dir) {
226
232
  return false;
227
233
  }
228
234
  }
235
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
236
+ export function isIgnoredGitSubdirectory(root, subdir) {
237
+ if (!subdir)
238
+ return false;
239
+ try {
240
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir], Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
241
+ return true;
242
+ }
243
+ catch (error) {
244
+ if (error.cause?.status === 1)
245
+ return false;
246
+ throw error;
247
+ }
248
+ }
249
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
250
+ export function linkedWorktreeGitDir(cwd) {
251
+ const workspace = realPath(cwd);
252
+ let directory = workspace;
253
+ for (;;) {
254
+ const gitMarker = join(directory, ".git");
255
+ if (existsSync(gitMarker)) {
256
+ if (!hasLinkedWorktreePointer(directory))
257
+ return undefined;
258
+ try {
259
+ const info = inspectGitWorkspace(directory);
260
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace)))
261
+ return undefined;
262
+ return info.gitDir;
263
+ }
264
+ catch {
265
+ throw linkedWorktreeError(directory);
266
+ }
267
+ }
268
+ const parent = dirname(directory);
269
+ if (parent === directory)
270
+ return undefined;
271
+ directory = parent;
272
+ }
273
+ }
229
274
  export function prepareGitCloneWorkspace(options) {
230
275
  const sourceDir = realPath(options.sourceDir);
231
276
  const targetDir = realPath(options.targetDir);
@@ -263,11 +308,11 @@ export function prepareGitCloneWorkspace(options) {
263
308
  // a normal clone. --dissociate removes the alternates link after setup.
264
309
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
265
310
  try {
266
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
311
+ runGit(dirname(targetDir), cloneArgs);
267
312
  }
268
313
  catch (err) {
269
314
  if (info.isLinkedWorktree) {
270
- throw linkedWorktreeError(sourceDir);
315
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${err.message}`);
271
316
  }
272
317
  throw err;
273
318
  }
@@ -21,7 +21,7 @@
21
21
 
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
 
26
26
  import { readGitRemotes, syncGitRemotes, type GitRemote } from "./git-remotes.ts";
27
27
 
@@ -38,17 +38,24 @@ export interface GitWorkspaceInfo {
38
38
  isLinkedWorktree: boolean;
39
39
  }
40
40
 
41
- function runGit(cwd: string, args: string[], opts?: { encoding?: BufferEncoding; stdio?: any }): string {
41
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
42
+
43
+ function runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): string {
42
44
  try {
43
45
  return execFileSync("git", args, {
44
46
  cwd,
45
47
  encoding: "utf-8",
46
48
  stdio: ["ignore", "pipe", "pipe"],
47
- ...opts,
49
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
50
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
51
+ killSignal: "SIGKILL",
48
52
  }).trim();
49
53
  } catch (err) {
54
+ if ((err as NodeJS.ErrnoException).code === "ETIMEDOUT") {
55
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
56
+ }
50
57
  const message = (err as Error).message ?? String(err);
51
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
58
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
52
59
  }
53
60
  }
54
61
 
@@ -298,6 +305,41 @@ function hasLinkedWorktreePointer(dir: string): boolean {
298
305
  }
299
306
  }
300
307
 
308
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
309
+ export function isIgnoredGitSubdirectory(root: string, subdir: string): boolean {
310
+ if (!subdir) return false;
311
+ try {
312
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir],
313
+ Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
314
+ return true;
315
+ } catch (error) {
316
+ if (((error as Error).cause as { status?: number } | undefined)?.status === 1) return false;
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
322
+ export function linkedWorktreeGitDir(cwd: string): string | undefined {
323
+ const workspace = realPath(cwd);
324
+ let directory = workspace;
325
+ for (;;) {
326
+ const gitMarker = join(directory, ".git");
327
+ if (existsSync(gitMarker)) {
328
+ if (!hasLinkedWorktreePointer(directory)) return undefined;
329
+ try {
330
+ const info = inspectGitWorkspace(directory);
331
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace))) return undefined;
332
+ return info.gitDir;
333
+ } catch {
334
+ throw linkedWorktreeError(directory);
335
+ }
336
+ }
337
+ const parent = dirname(directory);
338
+ if (parent === directory) return undefined;
339
+ directory = parent;
340
+ }
341
+ }
342
+
301
343
  export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOptions): string {
302
344
  const sourceDir = realPath(options.sourceDir);
303
345
  const targetDir = realPath(options.targetDir);
@@ -343,10 +385,10 @@ export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOption
343
385
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
344
386
 
345
387
  try {
346
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
388
+ runGit(dirname(targetDir), cloneArgs);
347
389
  } catch (err) {
348
390
  if (info.isLinkedWorktree) {
349
- throw linkedWorktreeError(sourceDir);
391
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${(err as Error).message}`);
350
392
  }
351
393
  throw err;
352
394
  }