@bakers-build/addon-claude 0.7.1-next.6 → 0.8.0

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.
@@ -1,4 +1,4 @@
1
- import { type AgentFootprint, type AgentPlugin, type AgentRunIdentity, type BbAgent, type ResolvedSecurity, type RunEnvPolicy, type SandboxHost, type SandboxPreflight, type SecurityOptions } from '@bakers-build/conductor/contract';
1
+ import { type AgentFootprint, type AgentPlugin, type AgentRunIdentity, type BbAgent, type MarketplaceDeclaration, type PluginLaunch, type ResolvedSecurity, type RunEnvPolicy, type SandboxHost, type SandboxPreflight, type SecurityOptions } from '@bakers-build/conductor/contract';
2
2
  export { parseClaudeTranscript } from './footprint.js';
3
3
  /**
4
4
  * Encode an absolute cwd the way Claude Code names its per-project transcript
@@ -15,6 +15,8 @@ export interface ClaudeAgentOptions extends SecurityOptions {
15
15
  * applies the state-group settings shipped with the addon.
16
16
  */
17
17
  measure?: boolean;
18
+ /** False runs this agent in the user's own `~/.claude`, without the project's plugins. */
19
+ plugins?: boolean;
18
20
  }
19
21
  export declare class ClaudeAgent implements BbAgent {
20
22
  private readonly home;
@@ -31,13 +33,20 @@ export declare class ClaudeAgent implements BbAgent {
31
33
  private replacedBakersServer;
32
34
  private readonly measure;
33
35
  private readonly overrides;
36
+ readonly pluginsDisabled: boolean;
37
+ /** The Claude config dir runs read and write: the agent home while plugins are on. */
38
+ configDir: string;
39
+ private pluginsOn;
34
40
  constructor(options?: ClaudeAgentOptions, home?: string);
41
+ /** Point this agent at the agent home of the project's declared marketplaces. */
42
+ useMarketplaces(marketplaces: readonly MarketplaceDeclaration[]): void;
43
+ installPlugins(marketplaces: readonly MarketplaceDeclaration[], home: string): Promise<PluginLaunch>;
35
44
  get launchWarnings(): readonly string[];
36
45
  /** A measured run stays without the conductor's tools, MCP or bridge. */
37
46
  get withoutConductorTools(): boolean;
38
47
  launchCommand(prompt: string, run?: AgentRunIdentity, workspacePath?: string, tools?: {
39
48
  url: string;
40
- }): string;
49
+ }, _env?: Readonly<Record<string, string>>, pluginArgs?: readonly string[]): string;
41
50
  /**
42
51
  * The sandbox's strict MCP config, plus the conductor's tool server when
43
52
  * the run has one. A measured run stays without MCP servers. The token is
package/dist/src/index.js CHANGED
@@ -1,8 +1,11 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
1
3
  import { readdir, readFile, stat } from 'node:fs/promises';
2
4
  import { homedir } from 'node:os';
3
5
  import { join } from 'node:path';
4
6
  import { fileURLToPath } from 'node:url';
5
- import { CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, installCommand, lastLine, resolveAgentCliOptions, resolveSecurityOptions, systemSandboxHost, validateOptionalBoolean, } from '@bakers-build/conductor/contract';
7
+ import { promisify } from 'node:util';
8
+ import { CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, ensureHome, homeKey, homePath, installCommand, lastLine, resolveAgentCliOptions, resolveSecurityOptions, systemSandboxHost, validateOptionalBoolean, } from '@bakers-build/conductor/contract';
6
9
  import { gitSandboxPaths, shellQuote, withoutGitDirs, } from '@bakers-build/core';
7
10
  import { parseClaudeTranscript } from './footprint.js';
8
11
  export { parseClaudeTranscript } from './footprint.js';
@@ -29,7 +32,7 @@ const SANDBOX_DEFAULTS = {
29
32
  mcp_servers: {},
30
33
  };
31
34
  /** The launch flags a security mode owns (`docs/addons/claude.md`). */
32
- function securityFlags({ mode, sandbox, config }, workspacePath) {
35
+ function securityFlags({ mode, sandbox, config }, workspacePath, pluginsOn = false) {
33
36
  if (mode === 'system')
34
37
  return [];
35
38
  if (mode === 'yolo')
@@ -80,8 +83,9 @@ function securityFlags({ mode, sandbox, config }, workspacePath) {
80
83
  return [
81
84
  '--permission-mode',
82
85
  'default',
86
+ // The agent home's user settings enable its plugins; the person's own stay out.
83
87
  '--setting-sources',
84
- 'project,local',
88
+ pluginsOn ? 'user,project,local' : 'project,local',
85
89
  '--settings',
86
90
  JSON.stringify(settings),
87
91
  ];
@@ -93,6 +97,20 @@ function securityFlags({ mode, sandbox, config }, workspacePath) {
93
97
  export function encodeClaudeProjectDir(cwd) {
94
98
  return cwd.replace(/[^a-zA-Z0-9]/g, '-');
95
99
  }
100
+ const run = promisify(execFile);
101
+ /** Run `claude <args> --json` in `configDir`; a failure names `what` and the CLI's output. */
102
+ async function claudeJson(configDir, what, args) {
103
+ try {
104
+ const { stdout } = await run('claude', [...args, '--json'], {
105
+ env: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
106
+ });
107
+ return JSON.parse(lastLine(stdout) || '{}');
108
+ }
109
+ catch (error) {
110
+ const { stderr, stdout, message } = error;
111
+ throw new Error(`${what}: claude ${args.join(' ')} failed: ${(stderr || stdout || message).trim()}`);
112
+ }
113
+ }
96
114
  const CLAUDE_RESERVED = [
97
115
  '--session-id',
98
116
  '--dangerously-skip-permissions',
@@ -122,6 +140,10 @@ export class ClaudeAgent {
122
140
  replacedBakersServer = false;
123
141
  measure;
124
142
  overrides;
143
+ pluginsDisabled;
144
+ /** The Claude config dir runs read and write: the agent home while plugins are on. */
145
+ configDir;
146
+ pluginsOn = false;
125
147
  constructor(options = {}, home = homedir()) {
126
148
  this.home = home;
127
149
  const cli = resolveAgentCliOptions(options, CLAUDE_RESERVED, CLAUDE_KNOWN);
@@ -142,6 +164,45 @@ export class ClaudeAgent {
142
164
  this.securityMode = security.mode;
143
165
  this.runEnvPolicy = security.runEnvPolicy;
144
166
  this.measure = validateOptionalBoolean(options.measure, 'measure') ?? false;
167
+ this.pluginsDisabled =
168
+ validateOptionalBoolean(options.plugins, 'plugins') === false;
169
+ this.configDir = join(home, '.claude');
170
+ }
171
+ /** Point this agent at the agent home of the project's declared marketplaces. */
172
+ useMarketplaces(marketplaces) {
173
+ if (this.pluginsDisabled || marketplaces.length === 0)
174
+ return;
175
+ this.pluginsOn = true;
176
+ this.configDir = homePath(this.id, homeKey([...marketplaces]));
177
+ }
178
+ async installPlugins(marketplaces, home) {
179
+ const outcome = await ensureHome(home, async (dir) => {
180
+ const credentials = join(this.home, '.claude', '.credentials.json');
181
+ if (!existsSync(credentials))
182
+ throw new Error(`claude: no credential file at ${credentials} (a keychain login cannot be shared with an agent home); log in with a file-based credential`);
183
+ symlinkSync(credentials, join(dir, '.credentials.json'));
184
+ for (const { url, ref, plugins } of marketplaces) {
185
+ const added = await claudeJson(dir, url, [
186
+ 'plugin',
187
+ 'marketplace',
188
+ 'add',
189
+ `${url}#${ref}`,
190
+ ]);
191
+ for (const plugin of plugins)
192
+ await claudeJson(dir, plugin, [
193
+ 'plugin',
194
+ 'install',
195
+ `${plugin}@${String(added.marketplace)}`,
196
+ ]);
197
+ }
198
+ // Skip the first-run onboarding; the CLI wrote the rest of this file.
199
+ const state = join(dir, '.claude.json');
200
+ const seeded = existsSync(state)
201
+ ? JSON.parse(readFileSync(state, 'utf8'))
202
+ : {};
203
+ writeFileSync(state, `${JSON.stringify({ ...seeded, hasCompletedOnboarding: true }, null, 2)}\n`, { mode: 0o600 });
204
+ });
205
+ return { env: { CLAUDE_CONFIG_DIR: home }, args: [], home: outcome };
145
206
  }
146
207
  get launchWarnings() {
147
208
  return this.replacedBakersServer
@@ -154,15 +215,16 @@ export class ClaudeAgent {
154
215
  get withoutConductorTools() {
155
216
  return this.measure;
156
217
  }
157
- launchCommand(prompt, run, workspacePath, tools) {
218
+ launchCommand(prompt, run, workspacePath, tools, _env, pluginArgs = []) {
158
219
  if (prompt === '') {
159
220
  return 'claude';
160
221
  }
161
222
  // Wait for project-declared plugins (extraKnownMarketplaces) to install
162
223
  // before the first turn; a fresh worktree otherwise starts without them.
163
224
  // A new worktree path would stop the run at Claude Code's trust dialog.
225
+ // With plugins on, the agent home already holds the installed plugins.
164
226
  const parts = [
165
- 'CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1',
227
+ ...(this.pluginsOn ? [] : ['CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1']),
166
228
  ...(workspacePath
167
229
  ? ['node', shellQuote(TRUST_WRAPPER), shellQuote(workspacePath)]
168
230
  : []),
@@ -178,7 +240,7 @@ export class ClaudeAgent {
178
240
  }
179
241
  // The flags are constants; only their generated values need quoting.
180
242
  parts.push(...[
181
- ...securityFlags(this.security, workspacePath),
243
+ ...securityFlags(this.security, workspacePath, this.pluginsOn),
182
244
  ...this.mcpFlags(tools),
183
245
  ].map((t) => (t.startsWith('--') ? t : shellQuote(t))));
184
246
  // Pin the transcript's own session id to the run's UUID (BB-473), so
@@ -188,7 +250,7 @@ export class ClaudeAgent {
188
250
  if (run?.sessionId) {
189
251
  parts.push('--session-id', run.sessionId);
190
252
  }
191
- parts.push(...this.args.map(shellQuote));
253
+ parts.push(...pluginArgs.map(shellQuote), ...this.args.map(shellQuote));
192
254
  if (this.measure) {
193
255
  // The wrapper folds an inline --settings JSON into its profile file.
194
256
  for (const pair of MEASURE_FLAGS) {
@@ -236,7 +298,7 @@ export class ClaudeAgent {
236
298
  * launch at all, silently (`claude` exits 0 on that error).
237
299
  */
238
300
  async sessionExists(worktreePath, sessionId) {
239
- const dir = join(this.home, '.claude', 'projects', encodeClaudeProjectDir(worktreePath));
301
+ const dir = join(this.configDir, 'projects', encodeClaudeProjectDir(worktreePath));
240
302
  try {
241
303
  await stat(join(dir, `${sessionId}.jsonl`));
242
304
  return true;
@@ -246,7 +308,7 @@ export class ClaudeAgent {
246
308
  }
247
309
  }
248
310
  async getRunLog(worktreePath, run) {
249
- const dir = join(this.home, '.claude', 'projects', encodeClaudeProjectDir(worktreePath));
311
+ const dir = join(this.configDir, 'projects', encodeClaudeProjectDir(worktreePath));
250
312
  const startedAtMs = run?.startedAt !== undefined ? new Date(run.startedAt).getTime() : null;
251
313
  // BB-473: when the run's own session id is known (pinned at launch via
252
314
  // `--session-id`), read that file directly — no directory scan, so a
@@ -382,7 +444,8 @@ export function claudeAgent(options = {}) {
382
444
  id: 'claude',
383
445
  requiredModules: [],
384
446
  permissions: agent.security.report,
385
- async createAgent() {
447
+ async createAgent(config) {
448
+ agent.useMarketplaces(config.marketplaces ?? []);
386
449
  return agent;
387
450
  },
388
451
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-claude",
3
- "version": "0.7.1-next.6",
3
+ "version": "0.8.0",
4
4
  "description": "bakers.build agent plugin for the Claude CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,11 +24,11 @@
24
24
  "directory": "bakers-cli/addons/claude"
25
25
  },
26
26
  "peerDependencies": {
27
- "@bakers-build/conductor": "^0.7.1-next.6",
28
- "@bakers-build/core": "^0.7.1-next.6"
27
+ "@bakers-build/conductor": "^0.8.0",
28
+ "@bakers-build/core": "^0.8.0"
29
29
  },
30
30
  "bakersBuild": {
31
- "commit": "269bb0ea2c27fca3b5ff3ac553df9c81b6179f5f",
32
- "channel": "next"
31
+ "commit": "082d8c57436f78e751f5a9a26a4446cec42209ce",
32
+ "channel": "latest"
33
33
  }
34
34
  }
@@ -3,11 +3,13 @@
3
3
  *
4
4
  * node claude-trust.mjs <worktree> <command> [args…]
5
5
  *
6
- * Marks exactly <worktree> as trusted in `~/.claude.json`
6
+ * Marks exactly <worktree> as trusted in `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`
7
+ * when the run has an agent home
7
8
  * (`projects[<worktree>].hasTrustDialogAccepted`), so Claude Code does not stop the run at
8
9
  * its workspace trust dialog, then runs the command. Every other key is kept; an already
9
10
  * trusted worktree is not written. The write goes to a temporary file that is renamed over
10
- * the original. When the file cannot be read or parsed, it is left untouched: the command
11
+ * the original, under a `<file>.lock` so concurrent runs sharing one agent home keep each
12
+ * other's entries. When the file cannot be read or parsed, it is left untouched: the command
11
13
  * still runs and shows the dialog, with a warning on stderr.
12
14
  */
13
15
 
@@ -22,11 +24,42 @@ if (!worktree || !command) {
22
24
  process.exit(2);
23
25
  }
24
26
 
27
+ /** Holds `<file>.lock` while `write` runs; after 10 s of waiting the lock counts as left over. */
28
+ function locked(file, write) {
29
+ const lock = `${file}.lock`;
30
+ const until = Date.now() + 10_000;
31
+ for (;;) {
32
+ try {
33
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' });
34
+ break;
35
+ } catch (err) {
36
+ if (err.code !== 'EEXIST') throw err;
37
+ if (Date.now() > until) {
38
+ fs.rmSync(lock, { force: true });
39
+ continue;
40
+ }
41
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
42
+ }
43
+ }
44
+ try {
45
+ write();
46
+ } finally {
47
+ fs.rmSync(lock, { force: true });
48
+ }
49
+ }
50
+
25
51
  function trust() {
26
52
  if (!path.isAbsolute(worktree)) {
27
53
  throw new Error(`not an absolute path: ${worktree}`);
28
54
  }
29
- const file = path.join(os.homedir(), '.claude.json');
55
+ const file = path.join(
56
+ process.env.CLAUDE_CONFIG_DIR || os.homedir(),
57
+ '.claude.json',
58
+ );
59
+ locked(file, () => trustIn(file));
60
+ }
61
+
62
+ function trustIn(file) {
30
63
  let config = {};
31
64
  let mode = 0o600;
32
65
  try {
@@ -41,7 +74,7 @@ function trust() {
41
74
  ...config.projects[worktree],
42
75
  hasTrustDialogAccepted: true,
43
76
  };
44
- // shortcut: no lock; a Claude Code write in the same moment can be lost. Lock if one is.
77
+ // shortcut: Claude Code itself does not take this lock; its own write in the same moment can be lost.
45
78
  const tmp = `${file}.${process.pid}.tmp`;
46
79
  fs.writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, { mode });
47
80
  fs.chmodSync(tmp, mode);