@myrialabs/clopen 0.4.41 → 0.4.42

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 (61) hide show
  1. package/backend/chat/stream-manager.ts +8 -0
  2. package/backend/database/crypto/secret-columns.ts +5 -1
  3. package/backend/database/index.ts +18 -0
  4. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  5. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/git-identity-queries.ts +290 -0
  8. package/backend/database/queries/index.ts +2 -0
  9. package/backend/engine/adapters/claude/environment.ts +11 -1
  10. package/backend/engine/adapters/claude/stream.ts +1 -1
  11. package/backend/engine/adapters/codex/stream.ts +35 -3
  12. package/backend/engine/adapters/opencode/server.ts +26 -2
  13. package/backend/engine/adapters/opencode/stream.ts +4 -1
  14. package/backend/engine/adapters/qwen/stream.ts +3 -1
  15. package/backend/engine/types.ts +10 -0
  16. package/backend/git/git-executor.ts +28 -2
  17. package/backend/git/git-service.ts +59 -40
  18. package/backend/git/identity/cli.test.ts +58 -0
  19. package/backend/git/identity/cli.ts +201 -0
  20. package/backend/git/identity/credential-helper.test.ts +242 -0
  21. package/backend/git/identity/env.test.ts +214 -0
  22. package/backend/git/identity/env.ts +193 -0
  23. package/backend/git/identity/import-local.test.ts +199 -0
  24. package/backend/git/identity/import-local.ts +141 -0
  25. package/backend/git/identity/index.ts +78 -0
  26. package/backend/git/identity/keys.ts +183 -0
  27. package/backend/git/identity/resolve.ts +140 -0
  28. package/backend/git/identity/scope-config.test.ts +145 -0
  29. package/backend/git/identity/scope-config.ts +175 -0
  30. package/backend/git/identity/service.ts +297 -0
  31. package/backend/index.ts +16 -0
  32. package/backend/preview/browser/browser-console-manager.ts +214 -34
  33. package/backend/preview/browser/browser-pool.ts +526 -123
  34. package/backend/preview/browser/browser-preview-service.ts +192 -8
  35. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  36. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  37. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  38. package/backend/preview/browser/capture-profile.ts +15 -1
  39. package/backend/preview/browser/types.ts +26 -1
  40. package/backend/terminal/ptykit.ts +24 -0
  41. package/backend/ws/git/branch.ts +17 -6
  42. package/backend/ws/git/commit.ts +6 -5
  43. package/backend/ws/git/conflict.ts +3 -2
  44. package/backend/ws/git/identity-context.ts +91 -0
  45. package/backend/ws/git/identity.ts +200 -0
  46. package/backend/ws/git/index.ts +3 -1
  47. package/backend/ws/git/remote.ts +57 -11
  48. package/backend/ws/preview/browser/data.ts +60 -0
  49. package/backend/ws/preview/browser/interact.ts +6 -0
  50. package/backend/ws/preview/browser/tab-info.ts +9 -1
  51. package/backend/ws/preview/browser/tab.ts +64 -8
  52. package/backend/ws/preview/index.ts +21 -0
  53. package/bin/clopen.ts +9 -0
  54. package/dist/assets/{index-CeNKKSDR.js → index-BynqyvF4.js} +1 -1
  55. package/dist/assets/{index-DW89566K.js → index-DLoJsmNQ.js} +1 -1
  56. package/dist/assets/{main-Cy5DXWPT.js → main-CUyZAmqt.js} +591 -584
  57. package/dist/assets/main-DVCW3cfr.css +1 -0
  58. package/dist/index.html +2 -2
  59. package/package.json +2 -2
  60. package/shared/types/git-identity.ts +112 -0
  61. package/dist/assets/main-DJKj_4By.css +0 -1
@@ -57,8 +57,16 @@ export async function setupEnvironmentOnce(): Promise<void> {
57
57
  *
58
58
  * When accountId is provided, overrides the OAuth token with that
59
59
  * specific account's token instead of the globally active account.
60
+ *
61
+ * `extraEnv` is applied last and carries per-turn values the caller resolved —
62
+ * in practice the requester's git identity, so a `git commit` the agent runs
63
+ * through its shell tool is authored by the same person the Git panel would
64
+ * attribute it to.
60
65
  */
61
- export function getEngineEnv(accountId?: number): Record<string, string> {
66
+ export function getEngineEnv(
67
+ accountId?: number,
68
+ extraEnv?: Record<string, string>
69
+ ): Record<string, string> {
62
70
  // Start from clean env (no Bun/npm/Vite pollution)
63
71
  const env = getCleanSpawnEnv();
64
72
  // Apply our overrides
@@ -77,6 +85,8 @@ export function getEngineEnv(accountId?: number): Record<string, string> {
77
85
  }
78
86
  }
79
87
 
88
+ if (extraEnv) Object.assign(env, extraEnv);
89
+
80
90
  return env;
81
91
  }
82
92
 
@@ -226,7 +226,7 @@ export class ClaudeCodeEngine implements AIEngine {
226
226
  permissionMode: 'bypassPermissions' as PermissionMode,
227
227
  allowDangerouslySkipPermissions: true,
228
228
  cwd: resolvedProjectPath,
229
- env: getEngineEnv(accountId),
229
+ env: getEngineEnv(accountId, options.gitIdentityEnv),
230
230
  systemPrompt: { type: "preset", preset: "claude_code" },
231
231
  settingSources: ["user", "project", "local"],
232
232
  forkSession: true,
@@ -64,6 +64,17 @@ interface CodexRun {
64
64
  thread: Thread | null;
65
65
  }
66
66
 
67
+ /**
68
+ * A stable key for an identity environment, so "same identity?" is a string
69
+ * compare rather than a deep object compare. Sorted because the builder's key
70
+ * order is an implementation detail, not a difference.
71
+ */
72
+ function gitIdentityKey(env: Record<string, string>): string {
73
+ const keys = Object.keys(env).sort();
74
+ if (keys.length === 0) return '';
75
+ return keys.map((k) => `${k}=${env[k]}`).join('\u0000');
76
+ }
77
+
67
78
  export class CodexEngine implements AIEngine {
68
79
  readonly name = 'codex' as const;
69
80
 
@@ -104,6 +115,17 @@ export class CodexEngine implements AIEngine {
104
115
  * satisfying that type.
105
116
  */
106
117
  private pendingProjectId: string | null = null;
118
+ /**
119
+ * Git identity baked into the current client, as a comparable key.
120
+ *
121
+ * The SDK takes `env` at construction and does not re-read it, so the
122
+ * identity is part of what the client IS — exactly like the account and the
123
+ * MCP set. Stored as a stable string so a turn can ask "is this still the
124
+ * right client" without deep-comparing the environment.
125
+ */
126
+ private currentGitIdentityKey: string | null = null;
127
+ /** Identity for the client `initialize()` is about to build. */
128
+ private pendingGitIdentityEnv: Record<string, string> = {};
107
129
 
108
130
  get isInitialized(): boolean {
109
131
  return this._isInitialized;
@@ -161,7 +183,7 @@ export class CodexEngine implements AIEngine {
161
183
  this.codex = new Codex({
162
184
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
163
185
  ...(codexCli ? { codexPathOverride: codexCli.path } : {}),
164
- env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir() },
186
+ env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir(), ...this.pendingGitIdentityEnv },
165
187
  config: {
166
188
  show_raw_agent_reasoning: true,
167
189
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
@@ -170,6 +192,7 @@ export class CodexEngine implements AIEngine {
170
192
  this.currentAccountId = account.id;
171
193
  this.currentMcpFilterKey = mcpKey;
172
194
  this.currentProjectId = projectId;
195
+ this.currentGitIdentityKey = gitIdentityKey(this.pendingGitIdentityEnv);
173
196
  this._isInitialized = true;
174
197
  debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey}, project=${projectId ?? 'none'})`);
175
198
  }
@@ -180,6 +203,7 @@ export class CodexEngine implements AIEngine {
180
203
  this.currentAccountId = null;
181
204
  this.currentMcpFilterKey = null;
182
205
  this.currentProjectId = null;
206
+ this.currentGitIdentityKey = null;
183
207
  this._isInitialized = false;
184
208
  debug.log('engine', 'Codex engine disposed');
185
209
  }
@@ -219,11 +243,19 @@ export class CodexEngine implements AIEngine {
219
243
  // ended up opening tabs in another.
220
244
  const streamProjectId = options.mcpContext?.projectId ?? null;
221
245
  const projectChanged = this._isInitialized && streamProjectId !== null && streamProjectId !== this.currentProjectId;
222
- if (accountChanged || mcpChanged || projectChanged) {
223
- debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged}, projectChanged=${projectChanged})`);
246
+ // One client serves every turn, so a turn requested by a different user —
247
+ // or in a project bound to a different identity — must not inherit the
248
+ // previous requester's git identity. Re-creating the client is the only
249
+ // way to change an env the SDK already baked.
250
+ const streamGitIdentityEnv = options.gitIdentityEnv ?? {};
251
+ const identityChanged =
252
+ this._isInitialized && gitIdentityKey(streamGitIdentityEnv) !== this.currentGitIdentityKey;
253
+ if (accountChanged || mcpChanged || projectChanged || identityChanged) {
254
+ debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged}, projectChanged=${projectChanged}, identityChanged=${identityChanged})`);
224
255
  await this.dispose();
225
256
  }
226
257
  this.pendingProjectId = streamProjectId;
258
+ this.pendingGitIdentityEnv = streamGitIdentityEnv;
227
259
  if (!this._isInitialized || !this.codex) {
228
260
  await this.initialize(accountId, mcpProfileFilter);
229
261
  }
@@ -142,6 +142,19 @@ export interface ServerConfigSpec {
142
142
  subagentFilter?: Set<string>;
143
143
  /** Inline agent definitions (undefined/empty = the engine's default set). */
144
144
  inlineAgents?: Record<string, OpenCodeInlineAgent>;
145
+ /**
146
+ * Git identity of whoever asked for this turn, as a `GIT_CONFIG_*` block.
147
+ *
148
+ * Folded into the signature for the same reason the connector set and the
149
+ * provider credentials are: the server process is spawned with it and cannot
150
+ * re-read it. One server serves every turn routed to it, so without this a
151
+ * second user's turn would reuse a server carrying the FIRST user's identity
152
+ * and commit under their name.
153
+ *
154
+ * In the ordinary case — one person, one identity — the block is identical
155
+ * every turn and the signature does not move, so no extra server is spawned.
156
+ */
157
+ gitIdentityEnv?: Record<string, string>;
145
158
  }
146
159
 
147
160
  /** Everything needed to spawn a server, plus the key derived from it. */
@@ -150,6 +163,7 @@ interface SpawnPlan {
150
163
  scopeKey: string;
151
164
  configContent: string;
152
165
  envVars: Record<string, string>;
166
+ gitIdentityEnv: Record<string, string>;
153
167
  }
154
168
 
155
169
  /**
@@ -653,13 +667,20 @@ async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
653
667
  // models.dev catalog it reads lives in `settings`, which bumps no revision.
654
668
  const providerConfig = generateOpenCodeProviderConfig();
655
669
  const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents);
670
+ // Sorted so the key order the builder happens to emit is not mistaken for a
671
+ // different identity.
672
+ const gitIdentityEnv = spec.gitIdentityEnv ?? {};
673
+ const gitIdentityKey = Object.keys(gitIdentityEnv)
674
+ .sort()
675
+ .map((k) => `${k}=${gitIdentityEnv[k]}`)
676
+ .join('\u0000');
656
677
  const signature = hashConfig(
657
- `${configContent}‖${JSON.stringify(providerConfig.envVars)}‖${fingerprint}‖${internalBridgeExposure()}`
678
+ `${configContent}‖${JSON.stringify(providerConfig.envVars)}‖${fingerprint}‖${internalBridgeExposure()}‖${gitIdentityKey}`
658
679
  );
659
680
  const key = `${scopeKey}#${signature}`;
660
681
 
661
682
  currentKeyByScope.set(scopeKey, key);
662
- return { key, scopeKey, configContent, envVars: providerConfig.envVars };
683
+ return { key, scopeKey, configContent, envVars: providerConfig.envVars, gitIdentityEnv };
663
684
  }
664
685
 
665
686
  // ============================================================================
@@ -955,6 +976,9 @@ async function spawnServerOnce(
955
976
  env: {
956
977
  ...process.env,
957
978
  ...plan.envVars,
979
+ // The identity this server was keyed on, so a `git commit` the agent
980
+ // runs is authored by the person whose turn spawned it.
981
+ ...plan.gitIdentityEnv,
958
982
  XDG_CONFIG_HOME: configDir,
959
983
  XDG_DATA_HOME: dataDir,
960
984
  XDG_STATE_HOME: dataDir,
@@ -228,7 +228,10 @@ export class OpenCodeEngine implements AIEngine {
228
228
  // stream keeps running until that stream is done. Holding the server by
229
229
  // stream id is what makes that safe: a held server is never reaped.
230
230
  const holderId = options.mcpContext?.streamId;
231
- const server = await acquireServer({ mcpProfileFilter, subagentFilter, inlineAgents }, holderId);
231
+ const server = await acquireServer(
232
+ { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv },
233
+ holderId
234
+ );
232
235
  run.server = server;
233
236
  run.holder = holderId ? { key: server.key, holderId } : null;
234
237
  const client = server.client;
@@ -150,7 +150,9 @@ export class QwenEngine implements AIEngine {
150
150
  if (!resolution) {
151
151
  throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
152
152
  }
153
- const { env } = resolution;
153
+ // Layered here rather than inside `getEngineEnv` because the identity is a
154
+ // property of the turn, while that function answers "which account".
155
+ const env = { ...resolution.env, ...(options.gitIdentityEnv ?? {}) };
154
156
 
155
157
  const controller = abortController || new AbortController();
156
158
  const run: QwenRun = { controller, query: null, converter: null, pendingAskUserQuestion: null };
@@ -46,6 +46,16 @@ export interface EngineQueryOptions {
46
46
  accountId?: number;
47
47
  /** Context bound to MCP tool handlers for project isolation */
48
48
  mcpContext?: McpExecutionContext;
49
+ /**
50
+ * `GIT_CONFIG_*` block for the git identity of whoever asked for this turn
51
+ * (see `backend/git/identity`). Adapters merge it into the environment of
52
+ * the process they spawn, so a `git commit` the agent runs through its shell
53
+ * tool is authored by the same identity as one made from the Git panel.
54
+ *
55
+ * Resolved once per turn by the stream manager rather than by each adapter:
56
+ * the adapter knows how to spawn its engine, not who is driving it.
57
+ */
58
+ gitIdentityEnv?: Record<string, string>;
49
59
  }
50
60
 
51
61
  /** Options for one-shot structured generation (no tools, no streaming) */
@@ -7,6 +7,15 @@ import { debug } from '$shared/utils/logger';
7
7
  import { getCleanSpawnEnv } from '../utils/env';
8
8
  import { resolveBinary } from '../utils/cli';
9
9
 
10
+ /**
11
+ * The environment fragment carrying a caller's git identity.
12
+ *
13
+ * An alias rather than a bare `Record<string, string>` so the operations that
14
+ * accept one say so in their signature — which is how a reader tells the
15
+ * commands that care who is running them from the ones that do not.
16
+ */
17
+ export type GitIdentityEnv = Record<string, string>;
18
+
10
19
  export interface GitExecResult {
11
20
  stdout: string;
12
21
  stderr: string;
@@ -23,6 +32,21 @@ export interface GitExecOptions {
23
32
  * not logged as one — `check-ignore` exits 1 to say "nothing matched".
24
33
  */
25
34
  okExitCodes?: number[];
35
+ /**
36
+ * Extra environment for this invocation — in practice the `GIT_CONFIG_*`
37
+ * block that carries the caller's git identity (see
38
+ * `backend/git/identity/env.ts`).
39
+ *
40
+ * Passed per command rather than resolved here because resolving an identity
41
+ * costs a database read, and `git status` runs many times a second. Commands
42
+ * that create an object or talk to a remote ask for it; the read-only ones
43
+ * never pay for it.
44
+ *
45
+ * Applied last, so an identity can override the fixed variables below. That
46
+ * ordering matters for `core.sshCommand`, which nothing else here sets but a
47
+ * future variable might.
48
+ */
49
+ env?: Record<string, string>;
26
50
  }
27
51
 
28
52
  /**
@@ -36,7 +60,7 @@ export async function execGit(
36
60
  ): Promise<GitExecResult> {
37
61
  const options: GitExecOptions =
38
62
  typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
39
- const { timeout = 30000, stdin, okExitCodes = [] } = options;
63
+ const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv } = options;
40
64
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
41
65
 
42
66
  const gitPath = resolveBinary('git');
@@ -70,7 +94,9 @@ export async function execGit(
70
94
  GIT_SEQUENCE_EDITOR: 'true',
71
95
  // Use English output for consistent parsing
72
96
  LANG: 'en_US.UTF-8',
73
- LC_ALL: 'en_US.UTF-8'
97
+ LC_ALL: 'en_US.UTF-8',
98
+ // The caller's git identity, last so it wins.
99
+ ...extraEnv
74
100
  }
75
101
  });
76
102
 
@@ -3,7 +3,7 @@
3
3
  * High-level git operations built on top of executor and parser
4
4
  */
5
5
 
6
- import { execGit, isGitRepo, getGitRoot, type GitExecResult } from './git-executor';
6
+ import { execGit, isGitRepo, getGitRoot, type GitExecResult, type GitIdentityEnv } from './git-executor';
7
7
  import { resolveBinary } from '../utils/cli';
8
8
  import { getCleanSpawnEnv } from '../utils/env';
9
9
  import {
@@ -241,9 +241,18 @@ export class GitService {
241
241
  // Commit
242
242
  // ============================================
243
243
 
244
- async commit(cwd: string, message: string): Promise<string> {
244
+ /**
245
+ * Create a commit.
246
+ *
247
+ * `identityEnv` carries who is committing (see `backend/git/identity`). It is
248
+ * threaded explicitly through the operations that create a git object or talk
249
+ * to a remote, rather than resolved inside `execGit`, because resolving it
250
+ * reads the database and the read-only commands run constantly. Anything
251
+ * added here that writes an object or authenticates needs the same parameter.
252
+ */
253
+ async commit(cwd: string, message: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
245
254
  assertSafeGitCommitMessage(message);
246
- const result = await execGit(['commit', '-m', message], cwd);
255
+ const result = await execGit(['commit', '-m', message], cwd, { env: identityEnv });
247
256
  if (result.exitCode !== 0) {
248
257
  throw new Error(`git commit failed: ${result.stderr}`);
249
258
  }
@@ -252,7 +261,7 @@ export class GitService {
252
261
  return hashResult.stdout.trim();
253
262
  }
254
263
 
255
- async amendCommit(cwd: string, message?: string): Promise<string> {
264
+ async amendCommit(cwd: string, message?: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
256
265
  const args = ['commit', '--amend'];
257
266
  if (message) {
258
267
  assertSafeGitCommitMessage(message);
@@ -260,7 +269,7 @@ export class GitService {
260
269
  } else {
261
270
  args.push('--no-edit');
262
271
  }
263
- const result = await execGit(args, cwd);
272
+ const result = await execGit(args, cwd, { env: identityEnv });
264
273
  if (result.exitCode !== 0) {
265
274
  // Unborn HEAD — git says "You have nothing to amend", which reads like a
266
275
  // failure rather than "commit normally instead".
@@ -535,10 +544,10 @@ export class GitService {
535
544
  }
536
545
  }
537
546
 
538
- async deleteRemoteBranch(cwd: string, remote: string, branch: string): Promise<void> {
547
+ async deleteRemoteBranch(cwd: string, remote: string, branch: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
539
548
  assertSafeGitRevish(remote, 'remote name');
540
549
  assertSafeGitRevish(branch, 'branch name');
541
- const result = await execGit(['push', remote, '--delete', branch], cwd);
550
+ const result = await execGit(['push', remote, '--delete', branch], cwd, { env: identityEnv });
542
551
  if (result.exitCode !== 0) {
543
552
  throw new Error(`git push --delete failed: ${result.stderr}`);
544
553
  }
@@ -555,7 +564,8 @@ export class GitService {
555
564
  async mergeBranch(
556
565
  cwd: string,
557
566
  branchName: string,
558
- options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false
567
+ options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false,
568
+ identityEnv: GitIdentityEnv = {}
559
569
  ): Promise<{ success: boolean; message: string }> {
560
570
  assertSafeGitRevish(branchName, 'merge branch');
561
571
  const opts = typeof options === 'boolean' ? { noFastForward: options } : options;
@@ -564,7 +574,7 @@ export class GitService {
564
574
  else if (opts.ffOnly) args.push('--ff-only');
565
575
  else if (opts.noFastForward) args.push('--no-ff');
566
576
  args.push(branchName);
567
- const result = await execGit(args, cwd, 120000);
577
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
568
578
  return {
569
579
  success: result.exitCode === 0,
570
580
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -627,10 +637,10 @@ export class GitService {
627
637
  return parseRemotes(result.stdout);
628
638
  }
629
639
 
630
- async fetch(cwd: string, remote = 'origin'): Promise<string> {
640
+ async fetch(cwd: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<string> {
631
641
  assertSafeGitRemoteName(remote);
632
642
  // Use explicit refspec to ensure all branches are fetched regardless of clone config
633
- const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, 60000);
643
+ const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, { timeout: 60000, env: identityEnv });
634
644
  if (result.exitCode !== 0) {
635
645
  throw new Error(`git fetch failed: ${result.stderr}`);
636
646
  }
@@ -645,7 +655,7 @@ export class GitService {
645
655
  * differently-named branch, which is the normal state of a fork PR under
646
656
  * review. A tracked branch pulls from its own upstream.
647
657
  */
648
- async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
658
+ async pull(cwd: string, remote = 'origin', branch?: string, rebase = false, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
649
659
  const args = ['pull'];
650
660
  if (rebase) args.push('--rebase');
651
661
 
@@ -659,7 +669,9 @@ export class GitService {
659
669
  }
660
670
  }
661
671
 
662
- const result = await execGit(args, cwd, 60000);
672
+ // A pull can create a merge commit, so it needs both halves of the
673
+ // identity: the credential to fetch, the name to author the merge.
674
+ const result = await execGit(args, cwd, { timeout: 60000, env: identityEnv });
663
675
  return {
664
676
  success: result.exitCode === 0,
665
677
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -794,7 +806,8 @@ export class GitService {
794
806
  remote = 'origin',
795
807
  branch?: string,
796
808
  force = false,
797
- options: { useUpstream?: boolean } = {}
809
+ options: { useUpstream?: boolean } = {},
810
+ identityEnv: GitIdentityEnv = {}
798
811
  ): Promise<{ success: boolean; message: string }> {
799
812
  const { useUpstream = true } = options;
800
813
  const target = await this.getPushTarget(cwd, branch);
@@ -802,7 +815,7 @@ export class GitService {
802
815
  if (useUpstream && target.hasUpstream) {
803
816
  const args = ['push'];
804
817
  if (force) args.push('--force-with-lease');
805
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
818
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
806
819
  }
807
820
 
808
821
  assertSafeGitRemoteName(remote);
@@ -815,7 +828,7 @@ export class GitService {
815
828
  // Only safe here: the branch tracks nothing, so there is no upstream to
816
829
  // overwrite and recording one is the point of a first push.
817
830
  args.push('-u');
818
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
831
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
819
832
  }
820
833
 
821
834
  /** Point a branch at a different upstream — the way back from a wrong push. */
@@ -857,7 +870,8 @@ export class GitService {
857
870
  cwd: string,
858
871
  mode: 'with-tags' | 'all-tags' | 'force-lease' | 'force',
859
872
  remote = 'origin',
860
- branch?: string
873
+ branch?: string,
874
+ identityEnv: GitIdentityEnv = {}
861
875
  ): Promise<{ success: boolean; message: string }> {
862
876
  // `--tags` is about the tag namespace, not this branch, so it always needs
863
877
  // an explicit remote.
@@ -865,7 +879,7 @@ export class GitService {
865
879
  assertSafeGitRemoteName(remote);
866
880
  return this.describePushResult(
867
881
  cwd,
868
- await execGit(['push', remote, '--tags'], cwd, 60000)
882
+ await execGit(['push', remote, '--tags'], cwd, { timeout: 60000, env: identityEnv })
869
883
  );
870
884
  }
871
885
 
@@ -879,7 +893,7 @@ export class GitService {
879
893
  // Same rule as `push`: a tracked branch goes where git says it goes.
880
894
  const target = await this.getPushTarget(cwd, branch);
881
895
  if (target.hasUpstream) {
882
- return this.describePushResult(cwd, await execGit(['push', flag], cwd, 60000));
896
+ return this.describePushResult(cwd, await execGit(['push', flag], cwd, { timeout: 60000, env: identityEnv }));
883
897
  }
884
898
 
885
899
  assertSafeGitRemoteName(remote);
@@ -889,12 +903,12 @@ export class GitService {
889
903
  args.push(branch);
890
904
  }
891
905
  args.push(flag, '-u');
892
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
906
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
893
907
  }
894
908
 
895
909
  /** Fetch every configured remote and prune deleted remote-tracking refs. */
896
- async fetchAll(cwd: string): Promise<string> {
897
- const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, 60000);
910
+ async fetchAll(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
911
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, { timeout: 60000, env: identityEnv });
898
912
  if (result.exitCode !== 0) {
899
913
  throw new Error(`git fetch --all failed: ${result.stderr}`);
900
914
  }
@@ -950,7 +964,7 @@ export class GitService {
950
964
  return parseStashList(result.stdout);
951
965
  }
952
966
 
953
- async stashSave(cwd: string, message?: string, stagedOnly = false): Promise<void> {
967
+ async stashSave(cwd: string, message?: string, stagedOnly = false, identityEnv: GitIdentityEnv = {}): Promise<void> {
954
968
  const args = ['stash', 'push'];
955
969
  // `--staged` stashes exactly the index (works at hunk level, so partially
956
970
  // staged files are handled precisely). Requires Git >= 2.35.
@@ -959,7 +973,7 @@ export class GitService {
959
973
  assertSafeGitCommitMessage(message);
960
974
  args.push('-m', message);
961
975
  }
962
- const result = await execGit(args, cwd);
976
+ const result = await execGit(args, cwd, { env: identityEnv });
963
977
  if (result.exitCode !== 0) {
964
978
  // Git < 2.35 doesn't know `--staged`; surface an actionable message
965
979
  // instead of the raw "unknown option" / "usage:" noise.
@@ -1073,7 +1087,7 @@ export class GitService {
1073
1087
  return tags;
1074
1088
  }
1075
1089
 
1076
- async createTag(cwd: string, name: string, message?: string, commitHash?: string): Promise<void> {
1090
+ async createTag(cwd: string, name: string, message?: string, commitHash?: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
1077
1091
  assertSafeGitRevish(name, 'tag name');
1078
1092
  const args = ['tag'];
1079
1093
  if (message) {
@@ -1086,7 +1100,7 @@ export class GitService {
1086
1100
  assertSafeGitRevish(commitHash, 'tag target');
1087
1101
  args.push(commitHash);
1088
1102
  }
1089
- const result = await execGit(args, cwd);
1103
+ const result = await execGit(args, cwd, { env: identityEnv });
1090
1104
  if (result.exitCode !== 0) {
1091
1105
  throw new Error(`git tag failed: ${result.stderr}`);
1092
1106
  }
@@ -1100,10 +1114,10 @@ export class GitService {
1100
1114
  }
1101
1115
  }
1102
1116
 
1103
- async pushTag(cwd: string, name: string, remote = 'origin'): Promise<{ success: boolean; message: string }> {
1117
+ async pushTag(cwd: string, name: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1104
1118
  assertSafeGitRemoteName(remote);
1105
1119
  assertSafeGitRevish(name, 'tag name');
1106
- const result = await execGit(['push', remote, name], cwd, 60000);
1120
+ const result = await execGit(['push', remote, name], cwd, { timeout: 60000, env: identityEnv });
1107
1121
  return {
1108
1122
  success: result.exitCode === 0,
1109
1123
  message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
@@ -1422,7 +1436,7 @@ export class GitService {
1422
1436
  * on failure, because the common failures here are instructions rather than
1423
1437
  * errors — "nothing to commit, use --skip" is something the user must read.
1424
1438
  */
1425
- async continueOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1439
+ async continueOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1426
1440
  const operation = await this.detectGitOperation(cwd);
1427
1441
  const unmerged = await this.getUnmergedPaths(cwd);
1428
1442
  if (unmerged.length > 0) {
@@ -1449,7 +1463,7 @@ export class GitService {
1449
1463
  throw new Error('There is no operation to continue.');
1450
1464
  }
1451
1465
 
1452
- const result = await execGit(args, cwd, 120000);
1466
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1453
1467
  return {
1454
1468
  success: result.exitCode === 0,
1455
1469
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1457,7 +1471,7 @@ export class GitService {
1457
1471
  }
1458
1472
 
1459
1473
  /** Drop the commit git is currently stuck on and move to the next one. */
1460
- async skipOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1474
+ async skipOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1461
1475
  const operation = await this.detectGitOperation(cwd);
1462
1476
  let args: string[];
1463
1477
  switch (operation) {
@@ -1474,7 +1488,7 @@ export class GitService {
1474
1488
  throw new Error('This operation cannot be skipped.');
1475
1489
  }
1476
1490
 
1477
- const result = await execGit(args, cwd, 120000);
1491
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1478
1492
  return {
1479
1493
  success: result.exitCode === 0,
1480
1494
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1531,14 +1545,15 @@ export class GitService {
1531
1545
  async rebaseOnto(
1532
1546
  cwd: string,
1533
1547
  upstream: string,
1534
- autostash = true
1548
+ autostash = true,
1549
+ identityEnv: GitIdentityEnv = {}
1535
1550
  ): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
1536
1551
  assertSafeGitRevish(upstream, 'rebase upstream');
1537
1552
  const args = ['rebase'];
1538
1553
  if (autostash) args.push('--autostash');
1539
1554
  args.push(upstream);
1540
1555
 
1541
- const result = await execGit(args, cwd, 120000);
1556
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1542
1557
  const combined = `${result.stdout}\n${result.stderr}`;
1543
1558
  const hasConflicts = /CONFLICT \(/.test(combined) || /could not apply/i.test(combined);
1544
1559
  if (result.exitCode !== 0 && !hasConflicts) {
@@ -1644,9 +1659,9 @@ export class GitService {
1644
1659
  }
1645
1660
 
1646
1661
  /** Create a new commit that reverses a previous one (default: HEAD). */
1647
- async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
1662
+ async revertCommit(cwd: string, ref = 'HEAD', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1648
1663
  assertSafeGitRevish(ref, 'revert ref');
1649
- const result = await execGit(['revert', '--no-edit', ref], cwd);
1664
+ const result = await execGit(['revert', '--no-edit', ref], cwd, { env: identityEnv });
1650
1665
  if (result.exitCode !== 0 && !(await this.hasCommits(cwd))) {
1651
1666
  // Unborn HEAD — git only reports `bad revision 'HEAD'`.
1652
1667
  return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
@@ -1658,14 +1673,14 @@ export class GitService {
1658
1673
  }
1659
1674
 
1660
1675
  /** Cherry-pick one or more commits onto the current branch (`git cherry-pick <hash>...`). */
1661
- async cherryPick(cwd: string, refs: string[]): Promise<{ success: boolean; message: string }> {
1676
+ async cherryPick(cwd: string, refs: string[], identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1662
1677
  if (refs.length === 0) {
1663
1678
  return { success: false, message: 'No commits provided' };
1664
1679
  }
1665
1680
  for (const ref of refs) {
1666
1681
  assertSafeGitRevish(ref, 'cherry-pick ref');
1667
1682
  }
1668
- const result = await execGit(['cherry-pick', ...refs], cwd);
1683
+ const result = await execGit(['cherry-pick', ...refs], cwd, { env: identityEnv });
1669
1684
  return {
1670
1685
  success: result.exitCode === 0,
1671
1686
  message: result.exitCode === 0 ? (result.stdout || result.stderr || 'Cherry-pick succeeded') : result.stderr
@@ -1705,17 +1720,21 @@ export class GitService {
1705
1720
  */
1706
1721
  async npmVersion(
1707
1722
  cwd: string,
1708
- bump: 'patch' | 'minor' | 'major'
1723
+ bump: 'patch' | 'minor' | 'major',
1724
+ identityEnv: GitIdentityEnv = {}
1709
1725
  ): Promise<{ success: boolean; version: string; message: string }> {
1710
1726
  const npmPath = resolveBinary('npm');
1711
1727
  if (!npmPath) {
1712
1728
  throw new Error('npm binary not found on PATH');
1713
1729
  }
1730
+ // npm runs git itself for the bump commit and tag, so the identity has to
1731
+ // travel in the environment — there is no `execGit` call here to attach it
1732
+ // to, and this is precisely why the mechanism is environment-based.
1714
1733
  const proc = Bun.spawn([npmPath, 'version', bump], {
1715
1734
  cwd,
1716
1735
  stdout: 'pipe',
1717
1736
  stderr: 'pipe',
1718
- env: { ...getCleanSpawnEnv() }
1737
+ env: { ...getCleanSpawnEnv(), ...identityEnv }
1719
1738
  });
1720
1739
  const [stdout, stderr] = await Promise.all([
1721
1740
  new Response(proc.stdout).text(),