@bakers-build/addon-claude 0.7.1-next.5 → 0.7.1-next.7

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';
@@ -21,14 +24,15 @@ const MEASURE_FLAGS = [
21
24
  ['--mcp-config', '{"mcpServers":{}}'],
22
25
  ];
23
26
  const SANDBOX_DEFAULTS = {
24
- trusted_commands: ['bakers', 'git'],
27
+ // No global tools: whatever a sandboxed run needs beyond its worktree comes through addon tools.
28
+ trusted_commands: [],
25
29
  deny_read: ['~/.ssh', '~/.bakers'],
26
30
  allow_write: [],
27
31
  network: ['*'],
28
32
  mcp_servers: {},
29
33
  };
30
34
  /** The launch flags a security mode owns (`docs/addons/claude.md`). */
31
- function securityFlags({ mode, sandbox, config }, workspacePath) {
35
+ function securityFlags({ mode, sandbox, config }, workspacePath, pluginsOn = false) {
32
36
  if (mode === 'system')
33
37
  return [];
34
38
  if (mode === 'yolo')
@@ -79,8 +83,9 @@ function securityFlags({ mode, sandbox, config }, workspacePath) {
79
83
  return [
80
84
  '--permission-mode',
81
85
  'default',
86
+ // The agent home's user settings enable its plugins; the person's own stay out.
82
87
  '--setting-sources',
83
- 'project,local',
88
+ pluginsOn ? 'user,project,local' : 'project,local',
84
89
  '--settings',
85
90
  JSON.stringify(settings),
86
91
  ];
@@ -92,6 +97,20 @@ function securityFlags({ mode, sandbox, config }, workspacePath) {
92
97
  export function encodeClaudeProjectDir(cwd) {
93
98
  return cwd.replace(/[^a-zA-Z0-9]/g, '-');
94
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
+ }
95
114
  const CLAUDE_RESERVED = [
96
115
  '--session-id',
97
116
  '--dangerously-skip-permissions',
@@ -121,6 +140,10 @@ export class ClaudeAgent {
121
140
  replacedBakersServer = false;
122
141
  measure;
123
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;
124
147
  constructor(options = {}, home = homedir()) {
125
148
  this.home = home;
126
149
  const cli = resolveAgentCliOptions(options, CLAUDE_RESERVED, CLAUDE_KNOWN);
@@ -141,6 +164,45 @@ export class ClaudeAgent {
141
164
  this.securityMode = security.mode;
142
165
  this.runEnvPolicy = security.runEnvPolicy;
143
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 };
144
206
  }
145
207
  get launchWarnings() {
146
208
  return this.replacedBakersServer
@@ -153,15 +215,16 @@ export class ClaudeAgent {
153
215
  get withoutConductorTools() {
154
216
  return this.measure;
155
217
  }
156
- launchCommand(prompt, run, workspacePath, tools) {
218
+ launchCommand(prompt, run, workspacePath, tools, _env, pluginArgs = []) {
157
219
  if (prompt === '') {
158
220
  return 'claude';
159
221
  }
160
222
  // Wait for project-declared plugins (extraKnownMarketplaces) to install
161
223
  // before the first turn; a fresh worktree otherwise starts without them.
162
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.
163
226
  const parts = [
164
- 'CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1',
227
+ ...(this.pluginsOn ? [] : ['CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1']),
165
228
  ...(workspacePath
166
229
  ? ['node', shellQuote(TRUST_WRAPPER), shellQuote(workspacePath)]
167
230
  : []),
@@ -177,7 +240,7 @@ export class ClaudeAgent {
177
240
  }
178
241
  // The flags are constants; only their generated values need quoting.
179
242
  parts.push(...[
180
- ...securityFlags(this.security, workspacePath),
243
+ ...securityFlags(this.security, workspacePath, this.pluginsOn),
181
244
  ...this.mcpFlags(tools),
182
245
  ].map((t) => (t.startsWith('--') ? t : shellQuote(t))));
183
246
  // Pin the transcript's own session id to the run's UUID (BB-473), so
@@ -187,7 +250,7 @@ export class ClaudeAgent {
187
250
  if (run?.sessionId) {
188
251
  parts.push('--session-id', run.sessionId);
189
252
  }
190
- parts.push(...this.args.map(shellQuote));
253
+ parts.push(...pluginArgs.map(shellQuote), ...this.args.map(shellQuote));
191
254
  if (this.measure) {
192
255
  // The wrapper folds an inline --settings JSON into its profile file.
193
256
  for (const pair of MEASURE_FLAGS) {
@@ -235,7 +298,7 @@ export class ClaudeAgent {
235
298
  * launch at all, silently (`claude` exits 0 on that error).
236
299
  */
237
300
  async sessionExists(worktreePath, sessionId) {
238
- const dir = join(this.home, '.claude', 'projects', encodeClaudeProjectDir(worktreePath));
301
+ const dir = join(this.configDir, 'projects', encodeClaudeProjectDir(worktreePath));
239
302
  try {
240
303
  await stat(join(dir, `${sessionId}.jsonl`));
241
304
  return true;
@@ -245,7 +308,7 @@ export class ClaudeAgent {
245
308
  }
246
309
  }
247
310
  async getRunLog(worktreePath, run) {
248
- const dir = join(this.home, '.claude', 'projects', encodeClaudeProjectDir(worktreePath));
311
+ const dir = join(this.configDir, 'projects', encodeClaudeProjectDir(worktreePath));
249
312
  const startedAtMs = run?.startedAt !== undefined ? new Date(run.startedAt).getTime() : null;
250
313
  // BB-473: when the run's own session id is known (pinned at launch via
251
314
  // `--session-id`), read that file directly — no directory scan, so a
@@ -380,8 +443,9 @@ export function claudeAgent(options = {}) {
380
443
  kind: 'agent',
381
444
  id: 'claude',
382
445
  requiredModules: [],
383
- security: agent.security.report,
384
- async createAgent() {
446
+ permissions: agent.security.report,
447
+ async createAgent(config) {
448
+ agent.useMarketplaces(config.marketplaces ?? []);
385
449
  return agent;
386
450
  },
387
451
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-claude",
3
- "version": "0.7.1-next.5",
3
+ "version": "0.7.1-next.7",
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.5",
28
- "@bakers-build/core": "^0.7.1-next.5"
27
+ "@bakers-build/conductor": "^0.7.1-next.7",
28
+ "@bakers-build/core": "^0.7.1-next.7"
29
29
  },
30
30
  "bakersBuild": {
31
- "commit": "b34bd900ef0293024de7b5a956af08e67d407e29",
31
+ "commit": "082d8c57436f78e751f5a9a26a4446cec42209ce",
32
32
  "channel": "next"
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);