@bakers-build/addon-grok 0.5.1-next.850 → 0.5.1-next.852

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.
package/dist/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readdir, readFile, stat } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
- import { join } from 'node:path';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { resolveAgentCliOptions, resolveSecurityOptions, systemSandboxHost, validateOptionalString, } from '@bakers-build/conductor/contract';
5
6
  import { shellQuote } from '@bakers-build/core';
6
7
  import { parseGrokTranscript } from './footprint.js';
@@ -101,10 +102,8 @@ function rejectUnsupportedSandbox(sandbox) {
101
102
  if (sandbox.trusted_commands.length > 0) {
102
103
  throw new Error("Grok has no command exception narrowed to executable, arguments and directory for sandbox.trusted_commands; use security: 'system' with your own sandbox.toml profile");
103
104
  }
104
- for (const key of ['deny_read', 'allow_write']) {
105
- if (sandbox[key].length > 0) {
106
- throw new Error(`Grok needs a sandbox.toml profile for sandbox.${key}, which bakers.build does not write; use security: 'system' with args: ['--sandbox', '<profile>']`);
107
- }
105
+ if (sandbox.deny_read.length > 0) {
106
+ throw new Error('Grok sandbox.deny_read is unsupported; leave deny_read empty');
108
107
  }
109
108
  }
110
109
  const GROK_KNOWN = [
@@ -150,9 +149,29 @@ export class GrokAgent {
150
149
  throw new Error("Grok has no config flags for security: 'custom'; use security: 'system' with args: ['--sandbox', '<profile>'] for your own sandbox.toml profile");
151
150
  }
152
151
  rejectUnsupportedSandbox(this.security.sandbox);
152
+ for (const path of this.security.sandbox.allow_write) {
153
+ if ((!isAbsolute(path) && !path.startsWith('~/')) ||
154
+ path.trim() !== path ||
155
+ /[?*[]/.test(path) ||
156
+ [...path].some((c) => c.charCodeAt(0) < 32)) {
157
+ throw new Error('sandbox.allow_write requires literal absolute or ~/ directory paths without whitespace edges or glob characters');
158
+ }
159
+ }
153
160
  const reserved = this.security.mode === 'sandbox' ? GROK_SANDBOX_RESERVED : GROK_RESERVED;
154
- const cli = resolveAgentCliOptions(options, reserved, GROK_KNOWN);
155
- rejectClusteredReserved(cli.args, reserved);
161
+ const launchReserved = this.security.sandbox.allow_write.length
162
+ ? [
163
+ ...reserved,
164
+ '--continue',
165
+ '-c',
166
+ '--resume',
167
+ '-r',
168
+ '--fork-session',
169
+ '--restore-code',
170
+ '--leader-socket',
171
+ ]
172
+ : reserved;
173
+ const cli = resolveAgentCliOptions(options, launchReserved, GROK_KNOWN);
174
+ rejectClusteredReserved(cli.args, launchReserved);
156
175
  if (this.security.mode === 'sandbox')
157
176
  rejectBareArgs(cli.args);
158
177
  this.args = cli.args;
@@ -188,6 +207,18 @@ export class GrokAgent {
188
207
  if (prompt !== '') {
189
208
  parts.push(...this.args.map(shellQuote));
190
209
  }
210
+ if (this.security.sandbox.allow_write.length) {
211
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith('.ts')
212
+ ? './managed-launch.ts'
213
+ : './managed-launch.js', import.meta.url));
214
+ return [
215
+ shellQuote(process.execPath),
216
+ shellQuote(launcher),
217
+ shellQuote(join(this.home, '.grok')),
218
+ shellQuote(JSON.stringify(this.security.sandbox.allow_write)),
219
+ ...parts,
220
+ ].join(' ');
221
+ }
191
222
  return parts.join(' ');
192
223
  }
193
224
  /** The launch flags a security mode owns (`docs/addons/grok.md`). */
@@ -199,7 +230,7 @@ export class GrokAgent {
199
230
  }
200
231
  return [
201
232
  '--sandbox',
202
- 'workspace',
233
+ this.security.sandbox.allow_write.length ? 'bakers-managed' : 'workspace',
203
234
  '--permission-mode',
204
235
  'acceptEdits',
205
236
  '--allow',
@@ -221,6 +252,13 @@ export class GrokAgent {
221
252
  fix: fallback,
222
253
  };
223
254
  }
255
+ if (this.security.sandbox.allow_write.length && !host.onPath('bwrap')) {
256
+ return {
257
+ ok: false,
258
+ cause: 'Managed Grok profiles need bubblewrap to protect sandbox.toml',
259
+ fix: 'install bubblewrap and keep security: sandbox',
260
+ };
261
+ }
224
262
  const probe = await host.run('grep', [
225
263
  '-qw',
226
264
  'landlock',
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,149 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { lstat, open, readFile, realpath, unlink } from 'node:fs/promises';
5
+ import { homedir, constants as osConstants } from 'node:os';
6
+ import { isAbsolute, join, resolve } from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ const marker = '# bakers.build managed Grok profile';
9
+ async function main() {
10
+ const [requestedHome, encoded, executable, ...args] = process.argv.slice(2);
11
+ if (!requestedHome || !encoded || executable !== 'grok')
12
+ throw new Error('Invalid managed Grok invocation');
13
+ const home = await realpath(requestedHome);
14
+ if (home !== resolve(requestedHome) ||
15
+ (process.env.GROK_HOME && resolve(process.env.GROK_HOME) !== home)) {
16
+ throw new Error('Managed Grok profiles require the default, non-symlinked Grok home for session attribution');
17
+ }
18
+ for (const policy of [
19
+ '/etc/grok/requirements.toml',
20
+ join(home, 'requirements.toml'),
21
+ ]) {
22
+ try {
23
+ if (!(await readFile(policy, 'utf8')).trim())
24
+ continue;
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ continue;
29
+ throw error;
30
+ }
31
+ throw new Error(`Cannot select a managed profile while ${policy} may pin another sandbox; preserve that policy and resolve the conflict first`);
32
+ }
33
+ const paths = JSON.parse(encoded);
34
+ if (!Array.isArray(paths) ||
35
+ !paths.length ||
36
+ paths.some((path) => typeof path !== 'string' ||
37
+ (!isAbsolute(path) && !path.startsWith('~/')) ||
38
+ path.trim() !== path ||
39
+ /[?*[]/.test(path) ||
40
+ [...path].some((c) => c.charCodeAt(0) < 32))) {
41
+ throw new Error('sandbox.allow_write requires literal absolute or ~/ directory paths');
42
+ }
43
+ const grants = [];
44
+ for (const path of paths) {
45
+ const expanded = path.startsWith('~/')
46
+ ? join(homedir(), path.slice(2))
47
+ : path;
48
+ const canonical = await realpath(expanded);
49
+ if (!(await lstat(canonical)).isDirectory())
50
+ throw new Error(`sandbox.allow_write is not a directory: ${path}`);
51
+ if (/[?*[]/.test(canonical) || canonical.trim() !== canonical)
52
+ throw new Error(`Grok cannot grant the resolved literal directory: ${canonical}`);
53
+ grants.push(canonical);
54
+ }
55
+ const { stdout } = await promisify(execFile)('grok', ['--version'], {
56
+ timeout: 15000,
57
+ });
58
+ const version = /^grok (\d+)\.(\d+)\.(\d+)\b/.exec(stdout);
59
+ if (!version ||
60
+ Number(version[1]) < 1 ||
61
+ (Number(version[1]) === 1 &&
62
+ Number(version[2]) === 0 &&
63
+ Number(version[3]) < 70)) {
64
+ throw new Error('Managed profiles require Grok 1.0.70 or newer with native profile write protection');
65
+ }
66
+ const flag = args.indexOf('--sandbox');
67
+ if (flag < 0 || args[flag + 1] !== 'bakers-managed')
68
+ throw new Error('Missing managed sandbox selection');
69
+ const name = `bakers_${randomUUID().replaceAll('-', '_')}`;
70
+ args[flag + 1] = name;
71
+ const lockPath = join(home, '.bakers-profile.lock');
72
+ // shortcut: one managed run per Grok home; use transactional profile updates when parallel runs are required.
73
+ const lock = await open(lockPath, 'wx', 0o600).catch((error) => {
74
+ if (error.code !== 'EEXIST')
75
+ throw error;
76
+ throw new Error(`Managed Grok profile busy: ${lockPath}. Wait for its run; after a crash inspect the recorded PID and profile before removing the lock`);
77
+ });
78
+ try {
79
+ await lock.writeFile(JSON.stringify({ pid: process.pid, profile: name }));
80
+ const profilePath = join(home, 'sandbox.toml');
81
+ const profile = await open(profilePath, constants.O_RDWR |
82
+ constants.O_APPEND |
83
+ constants.O_CREAT |
84
+ constants.O_NOFOLLOW, 0o600);
85
+ try {
86
+ const identity = await profile.stat();
87
+ if (!identity.isFile() || identity.nlink !== 1)
88
+ throw new Error('sandbox.toml must be a regular file without hard links');
89
+ const original = await profile.readFile();
90
+ if (original.includes(marker))
91
+ throw new Error('sandbox.toml contains an unfinished Bakers profile; recover that run before starting another');
92
+ const block = Buffer.from(`\n${marker} ${name}\n[profiles.${name}]\nextends = "workspace"\nread_write = ${JSON.stringify(grants)}\n`);
93
+ await profile.writeFile(block);
94
+ await profile.sync();
95
+ try {
96
+ const child = spawn('grok', args, {
97
+ stdio: 'inherit',
98
+ env: { ...process.env, GROK_HOME: home },
99
+ });
100
+ const handlers = ['SIGINT', 'SIGTERM', 'SIGHUP'].map((signal) => {
101
+ const forward = () => {
102
+ child.kill(signal);
103
+ };
104
+ process.on(signal, forward);
105
+ return { signal, forward };
106
+ });
107
+ try {
108
+ process.exitCode = await new Promise((resolveExit, reject) => {
109
+ child.once('error', reject);
110
+ child.once('exit', (code, signal) => resolveExit(code ?? (signal ? 128 + osConstants.signals[signal] : 1)));
111
+ });
112
+ }
113
+ finally {
114
+ for (const { signal, forward } of handlers)
115
+ process.off(signal, forward);
116
+ }
117
+ }
118
+ finally {
119
+ const current = await lstat(profilePath);
120
+ const expected = Buffer.concat([original, block]);
121
+ const actual = Buffer.alloc(expected.length + 1);
122
+ const { bytesRead } = await profile.read(actual, 0, actual.length, 0);
123
+ if (current.ino !== identity.ino ||
124
+ current.dev !== identity.dev ||
125
+ bytesRead !== expected.length ||
126
+ !actual.subarray(0, bytesRead).equals(expected)) {
127
+ console.error(`sandbox.toml changed during the run; preserved it unchanged. Inspect and remove only profile ${name}`);
128
+ process.exitCode = 1;
129
+ }
130
+ else {
131
+ // Only remove our appended bytes; never rewrite the operator's original configuration.
132
+ await profile.truncate(original.length);
133
+ await profile.sync();
134
+ }
135
+ }
136
+ }
137
+ finally {
138
+ await profile.close();
139
+ }
140
+ }
141
+ finally {
142
+ await lock.close();
143
+ await unlink(lockPath);
144
+ }
145
+ }
146
+ main().catch((error) => {
147
+ console.error(`Cannot run Grok with sandbox.allow_write: ${error instanceof Error ? error.message : String(error)}`);
148
+ process.exitCode = 1;
149
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-grok",
3
- "version": "0.5.1-next.850",
3
+ "version": "0.5.1-next.852",
4
4
  "description": "bakers.build agent plugin for xAI Grok Build, with a real session footprint.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,11 +20,11 @@
20
20
  "directory": "bakers-cli/addons/grok"
21
21
  },
22
22
  "peerDependencies": {
23
- "@bakers-build/conductor": "^0.5.1-next.850",
24
- "@bakers-build/core": "^0.5.1-next.850"
23
+ "@bakers-build/conductor": "^0.5.1-next.852",
24
+ "@bakers-build/core": "^0.5.1-next.852"
25
25
  },
26
26
  "bakersBuild": {
27
- "commit": "5f928492b2ed78efe1f782a9618ecf8bde49be3d",
27
+ "commit": "11ac39f9f194501ed439fbc34b2f8d3f4f6addca",
28
28
  "channel": "next"
29
29
  }
30
30
  }