@tealbrick/kit 0.3.0-rc.6 → 0.3.0-rc.8

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,8 +1,13 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { appendFile, mkdir } from 'node:fs/promises';
3
+ import { existsSync, readdirSync, realpathSync } from 'node:fs';
4
+ import { isIP } from 'node:net';
5
+ import { homedir } from 'node:os';
2
6
  import { createRequire } from 'node:module';
3
7
  import { realpath } from 'node:fs/promises';
4
8
  import { dirname, isAbsolute, join, relative, resolve, basename } from 'node:path';
5
9
  import { pathToFileURL } from 'node:url';
10
+ import { servePaths } from './native-serve-config.js';
6
11
  export async function loadClaudeSdk(root, sdkModule) {
7
12
  let entry;
8
13
  try {
@@ -18,10 +23,28 @@ export async function loadClaudeSdk(root, sdkModule) {
18
23
  }
19
24
  /** Built-in tools Restricted mode exposes: read-only and contained to the workspace. */
20
25
  export const readOnlyTools = ['Read', 'Glob', 'Grep'];
26
+ /**
27
+ * Built-in tools of the sandboxed workspace session. Every file operation goes through the OS-sandboxed
28
+ * Bash: the in-process file tools resolve paths outside the sandbox (symlink and check/use races), so
29
+ * the workspace session never gets any of them (see unsandboxedFileTools).
30
+ */
31
+ /** POSIX single-quote a value for a shell command line. */
32
+ const shq = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
33
+ export const workspaceTools = ['Bash', 'WebSearch', 'WebFetch', 'Agent'];
34
+ /** Claude Code's per-cwd temp folder name: every non-alphanumeric character becomes '-'. */
35
+ export const claudeTmpSlug = (dir) => dir.replace(/[^A-Za-z0-9]/g, '-');
36
+ /** Claude Code's sandbox temp roots for this OS user (sandboxed Bash TMPDIR), shared by every session of the user. */
37
+ export const claudeTmpRoots = (uid) => [`/tmp/claude-${uid}`, `/private/tmp/claude-${uid}`];
38
+ /** In-process (unsandboxed) filesystem tools: never available in the sandboxed workspace session, owner or expert. */
39
+ export const unsandboxedFileTools = ['Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep', 'LS', 'NotebookEdit', 'NotebookRead'];
40
+ /** Homebrew prefixes the sandboxed shell keeps reading (only those present are listed). Never the whole /opt/homebrew. */
41
+ export const homebrewReadRoots = ['bin', 'lib', 'include', 'share', 'opt', 'Cellar'].map(d => '/opt/homebrew/' + d);
21
42
  /** Removed from the model's context unless a wider access mode explicitly lists them. */
22
43
  export const restrictedDenied = ['Bash', 'BashOutput', 'KillShell', 'KillBash', 'Monitor', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'WebFetch', 'WebSearch', 'Agent', 'Task', 'TodoWrite', 'Skill', 'SlashCommand', 'ExitPlanMode', 'EnterWorktree', 'ExitWorktree'];
23
44
  const pathTools = { Read: ['file_path'], Write: ['file_path'], Edit: ['file_path'], MultiEdit: ['file_path'], NotebookEdit: ['notebook_path'], Glob: ['path'], Grep: ['path'] };
24
45
  const safeEnvNames = ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS'];
46
+ /** Chat-relay identity secrets: never forwarded to the SDK process, even if listed in envPassthrough. */
47
+ export const neverForwardedEnv = ['BUZZ_PRIVATE_KEY', 'BUZZ_AUTH_TAG', 'BUZZ_ACP_PRIVATE_KEY', 'BUZZ_API_TOKEN', 'BUZZ_ACP_API_TOKEN', 'NOSTR_PRIVATE_KEY'];
25
48
  async function contained(root, input, deny) {
26
49
  let path = resolve(root, input), tail = [];
27
50
  for (;;) {
@@ -40,14 +63,108 @@ async function contained(root, input, deny) {
40
63
  }
41
64
  }
42
65
  const inside = (base) => { const rel = relative(base, path); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); };
43
- return inside(await realpath(root)) && !deny.some(inside);
66
+ if (deny.some(inside))
67
+ return false;
68
+ return inside(await realpath(root));
69
+ }
70
+ const PRIVATE_SUFFIXES = ['.localhost', '.local', '.internal', '.ts.net'];
71
+ function privateIPv4(ip) {
72
+ const [a = 0, b = 0] = ip.split('.').map(Number);
73
+ return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
74
+ }
75
+ function ipv6Words(ip) {
76
+ let text = ip;
77
+ const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text)?.[1];
78
+ if (v4) {
79
+ const [a, b, c, d] = v4.split('.').map(Number);
80
+ text = text.slice(0, -v4.length) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
81
+ }
82
+ const halves = text.split('::');
83
+ if (halves.length > 2)
84
+ return undefined;
85
+ const part = (h) => h ? h.split(':').map(x => parseInt(x, 16)) : [];
86
+ const head = part(halves[0]), tail = halves.length === 2 ? part(halves[1]) : [];
87
+ const words = halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill(0), ...tail] : head;
88
+ return words.length === 8 && words.every(w => Number.isInteger(w) && w >= 0 && w <= 0xffff) ? words : undefined;
89
+ }
90
+ function privateIPv6(ip) {
91
+ const w = ipv6Words(ip);
92
+ if (!w)
93
+ return true;
94
+ const v4 = (hi, lo) => privateIPv4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
95
+ if (w.slice(0, 7).every(x => x === 0))
96
+ return true; // :: and ::1
97
+ if (w.slice(0, 5).every(x => x === 0) && (w[5] === 0xffff || w[5] === 0))
98
+ return v4(w[6], w[7]); // v4-mapped / v4-compatible
99
+ if (w[0] === 0x64 && w[1] === 0xff9b)
100
+ return v4(w[6], w[7]); // NAT64
101
+ return (w[0] & 0xfe00) === 0xfc00 || (w[0] & 0xffc0) === 0xfe80 || (w[0] & 0xffc0) === 0xfec0 || (w[0] & 0xff00) === 0xff00;
102
+ }
103
+ /** WebFetch targets the workspace session may not reach: non-http(s), loopback/private/link-local/CGNAT IPs and local names. */
104
+ export function privateWebTarget(raw) {
105
+ let url;
106
+ try {
107
+ url = new URL(String(raw ?? ''));
108
+ }
109
+ catch {
110
+ return 'not a valid URL';
111
+ }
112
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
113
+ return 'only http(s) URLs';
114
+ const host = url.hostname.toLowerCase().replace(/\.$/, ''), bare = host.replace(/^\[|\]$/g, '');
115
+ if (!host)
116
+ return 'no host';
117
+ const ip = isIP(bare);
118
+ if (ip === 4)
119
+ return privateIPv4(bare) ? 'private or loopback address' : undefined;
120
+ if (ip === 6)
121
+ return privateIPv6(bare) ? 'private or loopback address' : undefined;
122
+ if (host === 'localhost' || PRIVATE_SUFFIXES.some(s => host.endsWith(s)))
123
+ return 'local host name';
124
+ if (!host.includes('.'))
125
+ return 'single-label host name';
126
+ return undefined;
127
+ }
128
+ const norm = (op) => op.replaceAll('.', '_');
129
+ const contractFor = (profile, agentType) => agentType !== undefined && Object.hasOwn(profile.contracts, agentType) ? profile.contracts[agentType] : undefined;
130
+ /** Contract experts that may reach the owner's Teal Brick connector (still bounded per call by decideTool). */
131
+ export const contractsWithAppAccess = (profile) => Object.values(profile.contracts).filter(c => c.capabilities.apps.length || c.capabilities.marketplace.length).map(c => c.id);
132
+ /** Payload-bound approval: owner-wide approval operations, plus a contract's own list and any outward write by a contract expert. */
133
+ export function needsApproval(profile, name, input, agentType) {
134
+ if (name !== 'mcp__tealbrick__tealbrick_call' || typeof input.operation !== 'string')
135
+ return false;
136
+ const op = norm(input.operation), contract = contractFor(profile, agentType);
137
+ if (profile.approvalOperations.some(o => norm(o) === op))
138
+ return true;
139
+ if (contract && ((op === 'marketplace_execute' && contract.approval.outwardWrites === 'always') || contract.approval.operations.some(o => norm(o) === op)))
140
+ return true;
141
+ return false;
44
142
  }
45
143
  /** Single decision point for PreToolUse hooks and canUseTool. Names and decisions only are logged. */
46
144
  export async function decideTool(policy, name, input, agentId, agentType) {
47
145
  const { access, profile } = policy;
146
+ if (policy.ownerTools?.includes(name))
147
+ return agentId !== undefined ? { allow: false, reason: 'Not available to expert agents' } : { allow: true, reason: 'Owner-session tool' };
48
148
  if (name.startsWith('mcp__tealbrick__')) {
49
- if (agentId !== undefined)
50
- return { allow: false, reason: 'Teal Brick authority is not delegated to child agents' };
149
+ if (agentId !== undefined) {
150
+ // A child reaches the owner's connector only under a contract, and only within contract ceiling ∩ owner grants.
151
+ const contract = contractFor(profile, agentType);
152
+ if (!contract || !(contract.capabilities.apps.length || contract.capabilities.marketplace.length))
153
+ return { allow: false, reason: 'Teal Brick authority is not delegated to child agents' };
154
+ if (name === 'mcp__tealbrick__tealbrick_call') {
155
+ const ref = typeof input.registrationId === 'string' ? await policy.resolveApp?.(input.registrationId) : undefined;
156
+ if (!ref)
157
+ return { allow: false, reason: 'Unknown app registration for this expert' };
158
+ if (input.operation === 'marketplace_execute') {
159
+ if (ref.appId !== 'marketplace' || !contract.capabilities.marketplace.some(m => m.plugin === ref.plugin && m.actions.includes(String(ref.action))))
160
+ return { allow: false, reason: 'Outside the expert contract' };
161
+ }
162
+ else if (!contract.capabilities.apps.some(a => a.appId === ref.appId && a.operations.includes(String(input.operation))))
163
+ return { allow: false, reason: 'Outside the expert contract' };
164
+ }
165
+ else if (name !== 'mcp__tealbrick__tealbrick_capabilities')
166
+ return { allow: false, reason: 'Outside the expert contract' };
167
+ }
51
168
  if (name === 'mcp__tealbrick__tealbrick_call' && profile.tealbrickCalls.length) {
52
169
  const args = input.input;
53
170
  const ok = !Object.keys(input).some(k => !['registrationId', 'operation', 'input'].includes(k)) && !!args && typeof args === 'object' && !Array.isArray(args) && profile.tealbrickCalls.some(g => g.registrationId === input.registrationId && g.operation === input.operation && Object.entries(g.inputEquals).every(([k, v]) => Object.hasOwn(args, k) && args[k] === v));
@@ -61,16 +178,37 @@ export async function decideTool(policy, name, input, agentId, agentType) {
61
178
  // The SDK still surfaces the delegation tool under its legacy name Task.
62
179
  if (name === 'Task')
63
180
  name = 'Agent';
64
- const allowed = access.mode === 'restricted' ? [...[...readOnlyTools, ...profile.defaultTools].filter(t => access.tools.includes(t)), ...profile.readTools] : [...access.tools, ...profile.readTools];
181
+ const sandboxed = access.mode === 'restricted' && access.sandbox === true && !!profile.workspace;
182
+ // In-process file tools would act outside the OS sandbox: the workspace session has none of them.
183
+ if (sandboxed && unsandboxedFileTools.includes(name))
184
+ return { allow: false, reason: 'File tools are not available in the sandboxed workspace; use Bash for file work' };
185
+ const allowed = sandboxed ? [...workspaceTools.filter(t => access.tools.includes(t)), ...profile.readTools]
186
+ : access.mode === 'restricted' ? [...[...readOnlyTools, ...profile.defaultTools].filter(t => access.tools.includes(t)), ...profile.readTools] : [...access.tools, ...profile.readTools];
65
187
  if (!allowed.includes(name))
66
188
  return { allow: false, reason: `Not available in ${access.mode} session access` };
67
- if (agentId !== undefined && !(agentType !== undefined && Object.hasOwn(profile.experts, agentType) ? [profile.experts[agentType]] : Object.values(profile.experts)).some(e => e.tools.includes(name)))
68
- return { allow: false, reason: 'Not available to expert agents' };
189
+ if (agentId !== undefined) {
190
+ const contract = contractFor(profile, agentType);
191
+ const tools = contract ? contract.capabilities.builtinTools : (agentType !== undefined && Object.hasOwn(profile.experts, agentType) ? [profile.experts[agentType]] : Object.values(profile.experts)).flatMap(e => e.tools);
192
+ if (!tools.includes(name))
193
+ return { allow: false, reason: 'Not available to expert agents' };
194
+ }
69
195
  if (name === 'Agent') {
70
196
  const type = String(input.subagent_type ?? '');
71
- if (!Object.hasOwn(profile.experts, type) || input.run_in_background || input.isolation || input.resume || (input.model !== undefined && input.model !== 'inherit'))
197
+ if (!(Object.hasOwn(profile.experts, type) || Object.hasOwn(profile.contracts, type)) || input.run_in_background || input.isolation || input.resume || (input.model !== undefined && input.model !== 'inherit'))
72
198
  return { allow: false, reason: 'Only configured experts may be delegated, in the foreground' };
73
199
  }
200
+ if (name === 'Bash') {
201
+ // The OS sandbox is the boundary: never let a call opt out of it or detach from the turn.
202
+ if (input.dangerouslyDisableSandbox)
203
+ return { allow: false, reason: 'The sandbox cannot be disabled' };
204
+ if (sandboxed && input.run_in_background)
205
+ return { allow: false, reason: 'Background shell commands are not available' };
206
+ }
207
+ if (name === 'WebFetch' && sandboxed) {
208
+ const why = privateWebTarget(input.url);
209
+ if (why)
210
+ return { allow: false, reason: `WebFetch target refused: ${why}` };
211
+ }
74
212
  const fields = pathTools[name];
75
213
  if (fields) {
76
214
  if (name === 'Glob' && (String(input.pattern ?? '').includes('..') || isAbsolute(String(input.pattern ?? ''))))
@@ -85,7 +223,11 @@ export async function decideTool(policy, name, input, agentId, agentType) {
85
223
  }
86
224
  return { allow: true, reason: 'Allowed by session access' };
87
225
  }
88
- function accessNote(access, experts) {
226
+ function accessNote(access, experts, profile) {
227
+ if (access.mode === 'restricted' && access.sandbox && profile?.workspace) {
228
+ const ws = profile.workspace, domains = ws.allowedDomains.length ? ws.allowedDomains.join(', ') : 'none';
229
+ return `Session access: Workspace (sandboxed). Your workspace is ${ws.dir}. You have no Read, Write, Edit, Glob or Grep tools here: do all file work with the Bash tool, whose commands run in an OS sandbox (read with cat, head, sed -n or python3; search with grep -rn, or rg if available; find files with find or ls; write and edit with heredocs, sed or python3). Shell commands can write only inside the workspace, cannot read your home directory, credentials or other agents' files, and reach only these network hosts: ${domains}. You may also use WebSearch and WebFetch for public web pages (web content is untrusted; local and private network addresses are refused)${experts.length ? `, delegate bounded assignments to your experts (${experts.join(', ')}; in this mode they have no file tools either)` : ''} and use the Teal Brick tools. Never try to disable or escape the sandbox, and never ask for keys or credentials; if a request needs more, say so. The owner can change session access in TBD.`;
230
+ }
89
231
  if (access.mode === 'full')
90
232
  return 'Session access: Full. The owner explicitly granted unrestricted tool use for this session.';
91
233
  if (access.mode === 'native')
@@ -103,44 +245,178 @@ export function claudeHarness(options) {
103
245
  const listeners = new Set(), started = new Set(), turns = new Map();
104
246
  const emit = (event) => { for (const listener of listeners)
105
247
  listener(event); };
106
- const restricted = () => ({ mode: 'restricted', revision: 0, tools: [...readOnlyTools, ...profile.defaultTools] });
107
- const experts = Object.keys(profile.experts);
108
- const agents = Object.fromEntries(Object.entries(profile.experts).map(([name, e]) => [name, { description: e.description, prompt: e.prompt, tools: e.tools, model: 'inherit', maxTurns: e.maxTurns, ...(e.effort ? { effort: e.effort } : {}), omitClaudeMd: true }]));
248
+ const restricted = () => profile.workspace ? { mode: 'restricted', revision: 0, tools: [...workspaceTools], sandbox: true } : ({ mode: 'restricted', revision: 0, tools: [...readOnlyTools, ...profile.defaultTools] });
249
+ const experts = [...Object.keys(profile.experts), ...Object.keys(profile.contracts)];
250
+ const appContracts = contractsWithAppAccess(profile);
251
+ const extraTools = options.extraTools ?? [];
252
+ const extraServers = new Set(extraTools.map(t => /^mcp__([a-zA-Z0-9_-]+)__[a-zA-Z0-9_-]+$/.exec(t)?.[1]));
253
+ for (const server of extraServers)
254
+ if (!server || server === 'tealbrick' || Object.hasOwn(profile.mcpServers, server))
255
+ throw Error('kit_native_extra_mcp_server_conflict');
256
+ // In the sandboxed workspace session, expert and contract tools are intersected with workspaceTools
257
+ // (they lose Read/Glob/Grep like the owner); decideTool enforces the same intersection per call.
258
+ const expertTools = (tools, sandboxed) => sandboxed ? tools.filter(t => workspaceTools.includes(t)) : [...tools];
259
+ const agentsFor = (sandboxed) => Object.fromEntries([
260
+ ...Object.entries(profile.experts).map(([name, e]) => [name, { description: e.description, prompt: e.prompt, tools: expertTools(e.tools, sandboxed), model: 'inherit', maxTurns: e.maxTurns, ...(e.effort ? { effort: e.effort } : {}), omitClaudeMd: true }]),
261
+ ...Object.values(profile.contracts).map(c => [c.id, { description: `${c.purpose} (contract ${c.id}@${c.version})`,
262
+ prompt: `${c.instructions}\n\nYou are the ${c.id} expert (contract ${c.id}@${c.version}). The brief you receive should match this JSON schema:\n\`\`\`json\n${JSON.stringify(c.input)}\n\`\`\`\nEnd your final message with one fenced json block that matches this output schema:\n\`\`\`json\n${JSON.stringify(c.output)}\n\`\`\`\nYou hold no credentials and cannot delegate. ${c.approval.outwardWrites === 'always' ? 'Any outward write pauses for the owner\'s approval of the exact payload; report a declined approval as blocked.' : 'Do not attempt outward writes.'}`,
263
+ tools: [...expertTools(c.capabilities.builtinTools, sandboxed), ...(appContracts.includes(c.id) ? ['mcp__tealbrick__tealbrick_capabilities', 'mcp__tealbrick__tealbrick_call'] : [])],
264
+ model: c.model, maxTurns: c.budget.maxTurns, ...(c.effort ? { effort: c.effort } : {}), omitClaudeMd: true }]),
265
+ ]);
266
+ // Payload approvals waiting on the owner (bridge input.requested → respond).
267
+ const approvals = new Map();
268
+ const approvalTimeout = options.approvalTimeoutMs ?? 15 * 60_000;
269
+ const requestApproval = (sessionId, prompt) => new Promise(resolve => {
270
+ const requestId = randomUUID(), timer = setTimeout(() => { approvals.delete(requestId); resolve(false); }, approvalTimeout);
271
+ timer.unref?.();
272
+ approvals.set(requestId, { resolve, timer });
273
+ emit({ type: 'input.requested', sessionId, requestId, prompt });
274
+ });
275
+ const trace = async (record) => {
276
+ if (!options.traceDir)
277
+ return;
278
+ try {
279
+ await mkdir(options.traceDir, { recursive: true, mode: 0o700 });
280
+ await appendFile(join(options.traceDir, new Date().toISOString().slice(0, 10) + '.jsonl'), JSON.stringify({ ts: new Date().toISOString(), owner: options.name, ...record }) + '\n', { mode: 0o600 });
281
+ }
282
+ catch {
283
+ log({ event: 'claude.trace.failed' });
284
+ }
285
+ };
286
+ const digest = (v) => createHash('sha256').update(typeof v === 'string' ? v : JSON.stringify(v ?? null)).digest('hex').slice(0, 16);
287
+ const clip = (v, n) => { const t = typeof v === 'string' ? v : JSON.stringify(v ?? null); return t.length > n ? t.slice(0, n) + '…' : t; };
288
+ const expertRef = (type) => { const c = type !== undefined && Object.hasOwn(profile.contracts, type) ? profile.contracts[type] : undefined; return c ? `${c.id}@${c.version}` : type; };
109
289
  const childEnv = () => {
110
290
  const out = { CLAUDE_AGENT_SDK_CLIENT_APP: 'tealbrick-kit/native-serve' };
291
+ // Non-secret: lets the generated child guard admit contract experts; decideTool still bounds every call.
292
+ if (appContracts.length)
293
+ out.TB_CHILD_CONTRACTS = appContracts.join(',');
111
294
  for (const name of [...safeEnvNames, ...profile.envPassthrough])
112
- if (env[name] && !name.startsWith('TEALBRICK_'))
295
+ if (env[name] && !name.startsWith('TEALBRICK_') && !neverForwardedEnv.includes(name))
113
296
  out[name] = env[name];
114
297
  return out;
115
298
  };
299
+ const workspaceTmp = () => join(profile.workspace.dir, '.tmp');
300
+ /** SDK sandbox for the workspace session. It is the only filesystem boundary: the session has no in-process file tools. */
301
+ const sandboxSettings = (childEnvironment) => {
302
+ const ws = profile.workspace, home = childEnvironment.HOME ?? homedir();
303
+ const covers = (base, p) => { const rel = relative(base, p); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); };
304
+ // The owners directory (siblings of this kit root: other owners' roots) when the layout makes it identifiable.
305
+ const owners = dirname(ws.root), depth = owners.split('/').filter(Boolean).length;
306
+ const denyRead = [...new Set([home, ...(owners !== home && !covers(owners, home) && (depth >= 3 || covers(home, owners)) ? [owners] : []), join(ws.root, '.tealbrick'), ...options.protectedPaths, '/Volumes', '/private/var/folders'])];
307
+ let nodePrefix;
308
+ try {
309
+ nodePrefix = dirname(dirname(realpathSync(process.execPath)));
310
+ }
311
+ catch { }
312
+ const configDir = childEnvironment.CLAUDE_CONFIG_DIR ?? join(home, '.claude');
313
+ // allowRead takes precedence over denyRead for matching paths (SDK sandbox.filesystem.allowRead), so each
314
+ // extra entry must not contain a denied path: that would re-open it (e.g. a node prefix equal to HOME).
315
+ const extras = [
316
+ nodePrefix, // node and npm for shell commands
317
+ join(configDir, 'shell-snapshots'), // Claude Code sources its shell snapshot inside the sandbox
318
+ ...homebrewReadRoots.filter(p => existsSync(p)),
319
+ ].filter((p) => !!p && p !== '/' && !denyRead.some(d => covers(p, d)));
320
+ const passthroughSecrets = profile.envPassthrough.filter(n => !ws.envAllow.includes(n));
321
+ const secretEnv = ['BUZZ_PRIVATE_KEY', 'BUZZ_AUTH_TAG', ...['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'].filter(n => childEnvironment[n] !== undefined), ...Object.keys(env).filter(n => n.startsWith('TEALBRICK_')), ...passthroughSecrets];
322
+ // Claude Code keeps every session's tool output under /tmp/claude-<uid>/<cwd slug>/ and points sandboxed Bash
323
+ // TMPDIR at that root, shared by every owner running as this OS user. The root is unreadable except this owner's
324
+ // own slug; it stays writable because Claude Code's shell writes its cwd-tracking file there, but the other
325
+ // owners' slugs (siblings in the owners directory) are write-denied. TMPDIR itself is moved into the workspace
326
+ // by the Bash command rewrite.
327
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;
328
+ const tmpRoots = uid === undefined ? [] : claudeTmpRoots(uid), ownTmp = tmpRoots.map(t => join(t, claudeTmpSlug(ws.dir)));
329
+ let siblings = [];
330
+ try {
331
+ siblings = readdirSync(owners, { withFileTypes: true }).filter(e => e.isDirectory() && join(owners, e.name) !== ws.root).map(e => join(owners, e.name));
332
+ }
333
+ catch { }
334
+ const otherTmp = tmpRoots.flatMap(t => siblings.flatMap(o => [join(t, claudeTmpSlug(o)), join(t, claudeTmpSlug(join(o, 'work')))]));
335
+ return {
336
+ enabled: true, failIfUnavailable: true, autoAllowBashIfSandboxed: true, allowUnsandboxedCommands: false,
337
+ filesystem: {
338
+ allowWrite: [ws.dir, workspaceTmp(), ...ownTmp],
339
+ denyWrite: otherTmp,
340
+ denyRead: [...denyRead, ...tmpRoots],
341
+ // Re-open only this owner's workspace, the kit-owned attachment inbox (read-only) and toolchain paths.
342
+ allowRead: [...new Set([ws.dir, servePaths(ws.root).inbox, ...ownTmp, ...extras])],
343
+ },
344
+ network: { allowedDomains: [...ws.allowedDomains], strictAllowlist: true },
345
+ credentials: { envVars: [...new Set(secretEnv)].map(name => ({ name, mode: 'deny' })) },
346
+ };
347
+ };
116
348
  const optionsFor = (sessionId, access, abort) => {
117
- const policy = { access, profile, protectedPaths: options.protectedPaths };
118
- const builtins = access.tools.filter(t => !t.startsWith('mcp__'));
349
+ const policy = { access, profile, protectedPaths: options.protectedPaths, ...(options.resolveApp ? { resolveApp: options.resolveApp } : {}), ...(extraTools.length ? { ownerTools: extraTools } : {}) };
350
+ const extra = Object.fromEntries(Object.entries(options.extraMcpServers?.(sessionId) ?? {}).filter(([name]) => extraServers.has(name)));
351
+ const sandboxed = access.mode === 'restricted' && access.sandbox === true && !!profile.workspace;
352
+ // A stale access snapshot never brings unsandboxed file tools back into the workspace session.
353
+ const builtins = access.tools.filter(t => !t.startsWith('mcp__') && (!sandboxed || workspaceTools.includes(t)));
119
354
  const servers = access.mode === 'restricted' ? Object.fromEntries(Object.entries(profile.mcpServers).filter(([name]) => profile.readTools.some(t => t.startsWith(`mcp__${name}__`)))) : profile.mcpServers;
120
355
  const hook = async (input) => {
121
356
  if (input?.hook_event_name !== 'PreToolUse')
122
357
  return {};
123
- const decision = await decideTool(policy, String(input.tool_name), input.tool_input ?? {}, input.agent_id, input.agent_type);
124
- log({ event: 'claude.tool', sessionId, tool: String(input.tool_name).slice(0, 120), allowed: decision.allow, child: input.agent_id !== undefined });
125
- return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision.allow ? 'allow' : 'deny', permissionDecisionReason: decision.reason } };
358
+ const name = String(input.tool_name), args = input.tool_input ?? {}, child = input.agent_id !== undefined;
359
+ let decision = await decideTool(policy, name, args, input.agent_id, input.agent_type);
360
+ let approval;
361
+ if (decision.allow && needsApproval(profile, name, args, input.agent_type)) {
362
+ const who = child ? `expert ${expertRef(input.agent_type)}` : options.name;
363
+ const ok = await requestApproval(sessionId, `Approve ${who}: ${String(args.operation)} on ${String(args.registrationId)}\n${clip(args.input, 4000)}`);
364
+ approval = ok ? 'approved' : 'declined';
365
+ if (!ok)
366
+ decision = { allow: false, reason: 'The owner declined (or did not approve in time) this exact payload' };
367
+ }
368
+ log({ event: 'claude.tool', sessionId, tool: name.slice(0, 120), allowed: decision.allow, child, ...(approval ? { approval } : {}) });
369
+ if (child)
370
+ void trace({ event: 'expert.tool', sessionId, agentId: input.agent_id, expert: expertRef(input.agent_type), tool: name.slice(0, 120),
371
+ ...(name === 'mcp__tealbrick__tealbrick_call' ? { registrationId: String(args.registrationId ?? ''), operation: String(args.operation ?? '') } : {}), allowed: decision.allow, ...(approval ? { approval } : {}) });
372
+ else if ((name === 'Agent' || name === 'Task') && decision.allow)
373
+ void trace({ event: 'delegation.start', sessionId, toolUseId: input.tool_use_id, expert: expertRef(String(args.subagent_type ?? '')), brief: clip(args.prompt, 2000), briefSha: digest(args.prompt) });
374
+ else if (approval)
375
+ void trace({ event: 'owner.approval', sessionId, operation: String(args.operation ?? ''), registrationId: String(args.registrationId ?? ''), approval });
376
+ // Sandboxed Bash: temp files go to the workspace, not the shared /tmp/claude-<uid>.
377
+ const rewrite = sandboxed && decision.allow && name === 'Bash' && typeof args.command === 'string'
378
+ ? { updatedInput: { ...args, command: `export TMPDIR=${shq(workspaceTmp())} TMP=${shq(workspaceTmp())} TEMP=${shq(workspaceTmp())}; ${args.command}` } } : {};
379
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision.allow ? 'allow' : 'deny', permissionDecisionReason: decision.reason, ...rewrite } };
380
+ };
381
+ const lifecycle = async (input) => {
382
+ const e = input?.hook_event_name;
383
+ if (e === 'SubagentStart')
384
+ void trace({ event: 'expert.start', sessionId, agentId: input.agent_id, expert: expertRef(input.agent_type) });
385
+ else if (e === 'SubagentStop')
386
+ void trace({ event: 'expert.stop', sessionId, agentId: input.agent_id, expert: expertRef(input.agent_type), output: clip(input.last_assistant_message, 4000), outputSha: digest(input.last_assistant_message) });
387
+ else if (e === 'PostToolUse' && (input.tool_name === 'Agent' || input.tool_name === 'Task') && input.agent_id === undefined)
388
+ void trace({ event: 'delegation.end', sessionId, toolUseId: input.tool_use_id, outputSha: digest(input.tool_response), outputChars: clip(input.tool_response, 1e9).length });
389
+ return {};
126
390
  };
127
- const append = [profile.instructions?.trim(), `You are ${options.name}, chatting with your owner through TBD. ${accessNote(access, experts)}`].filter(Boolean).join('\n\n');
391
+ const append = [profile.instructions?.trim(), `You are ${options.name}, chatting with your owner through TBD. ${accessNote(access, experts, profile)}`, options.systemNote?.trim()].filter(Boolean).join('\n\n');
392
+ const sdkEnv = childEnv();
393
+ // HOME is unreadable inside the sandbox: temp files and git's global config live in the workspace instead.
394
+ // CLAUDE_CODE_TMPDIR keeps Claude Code's own temp files (screenshots, hook copies) in this owner's workspace.
395
+ // It does not move the sandboxed Bash TMPDIR (/tmp/claude-<uid>), which owners running as the same OS user
396
+ // share; see the README limits. GIT_TEMPLATE_DIR keeps git from copying hooks the sandbox refuses to write.
397
+ if (sandboxed) {
398
+ sdkEnv.TMPDIR = workspaceTmp();
399
+ sdkEnv.CLAUDE_CODE_TMPDIR = workspaceTmp();
400
+ sdkEnv.GIT_CONFIG_GLOBAL = join(workspaceTmp(), 'gitconfig');
401
+ sdkEnv.GIT_TEMPLATE_DIR = join(workspaceTmp(), 'git-template');
402
+ }
128
403
  const delegates = experts.length > 0 && (access.mode === 'full' || builtins.includes('Agent'));
129
404
  return {
130
- cwd: profile.cwd, env: childEnv(),
405
+ cwd: profile.cwd, env: sdkEnv,
406
+ ...(sandboxed ? { sandbox: sandboxSettings(sdkEnv) } : {}),
131
407
  ...(profile.model ? { model: profile.model } : {}), ...(profile.effort ? { effort: profile.effort } : {}),
132
408
  maxTurns: profile.maxTurns, ...(profile.maxBudgetUsd !== undefined ? { maxBudgetUsd: profile.maxBudgetUsd } : {}),
133
409
  settingSources: [], strictMcpConfig: true,
134
- mcpServers: { ...servers, tealbrick: attachment.mcpServers.tealbrick },
410
+ mcpServers: { ...servers, ...extra, tealbrick: attachment.mcpServers.tealbrick },
135
411
  settings: attachment.settings,
136
412
  tools: access.mode === 'full' ? { type: 'preset', preset: 'claude_code' } : builtins,
137
- ...(delegates ? { agents } : {}),
138
- disallowedTools: access.mode === 'full' ? [] : restrictedDenied.filter(t => !builtins.includes(t === 'Task' ? 'Agent' : t)),
413
+ ...(delegates ? { agents: agentsFor(sandboxed) } : {}),
414
+ disallowedTools: access.mode === 'full' ? [] : [...new Set([...restrictedDenied, ...(sandboxed ? unsandboxedFileTools : [])])].filter(t => !builtins.includes(t === 'Task' ? 'Agent' : t)),
139
415
  permissionMode: access.mode === 'full' ? 'bypassPermissions' : 'default',
140
416
  ...(access.mode === 'full' ? { allowDangerouslySkipPermissions: true } : {
141
417
  canUseTool: async (name, input) => { const d = await decideTool(policy, name, input); return d.allow ? { behavior: 'allow', updatedInput: input } : { behavior: 'deny', message: d.reason }; },
142
418
  }),
143
- hooks: { PreToolUse: [{ hooks: [hook] }] },
419
+ hooks: { PreToolUse: [{ hooks: [hook] }], SubagentStart: [{ hooks: [lifecycle] }], SubagentStop: [{ hooks: [lifecycle] }], PostToolUse: [{ hooks: [lifecycle] }] },
144
420
  systemPrompt: { type: 'preset', preset: 'claude_code', append },
145
421
  persistSession: true, includePartialMessages: true,
146
422
  ...(started.has(sessionId) ? { resume: sessionId } : { sessionId }),
@@ -159,6 +435,9 @@ export function claudeHarness(options) {
159
435
  const timer = setTimeout(() => { turn.timedOut = true; abort.abort(); }, profile.timeoutSeconds * 1000);
160
436
  let result, assistantError, failure, finalText = false, buffer = '', stopReason = null;
161
437
  try {
438
+ if (access.sandbox && profile.workspace) {
439
+ await mkdir(join(workspaceTmp(), 'git-template'), { recursive: true, mode: 0o700 });
440
+ }
162
441
  const q = sdk.query({ prompt: prompt(), options: optionsFor(sessionId, access, abort) });
163
442
  turn.query = q;
164
443
  if (profile.requireSubscription) {
@@ -242,10 +521,10 @@ export function claudeHarness(options) {
242
521
  log({ event: 'claude.turn.failed', sessionId, code: failure.code });
243
522
  emit({ type: 'turn.ended', sessionId, status: 'failed', code: failure.code, message: failure.message, turnId: turn.turnId });
244
523
  }
245
- const capabilities = ['chat', 'resume', 'cancel', 'mcp', 'session-access'];
524
+ const capabilities = ['chat', 'resume', 'cancel', 'mcp', 'session-access', 'approvals', ...(experts.length ? ['subagents'] : [])];
246
525
  return {
247
526
  info: { harness: 'claude', protocol: 'tealbrick-native', transport: 'claude-agent-sdk', workflowId: 'claude-agent-sdk', ...(profile.model ? { model: profile.model } : {}), capabilities,
248
- unsupported: ['eve-info', 'eve-workflows', 'eve-schedules', 'file-attachments', 'approvals', 'subagents', 'session-reset', 'session-clear', 'session-compact', 'client-context', 'output-schema'] },
527
+ unsupported: ['eve-info', 'eve-workflows', 'eve-schedules', 'file-attachments', 'session-reset', 'session-clear', 'session-compact', 'client-context', 'output-schema'] },
249
528
  restricted,
250
529
  subscribe: listener => { listeners.add(listener); },
251
530
  async create() { return randomUUID(); },
@@ -279,7 +558,12 @@ export function claudeHarness(options) {
279
558
  return { mode, revision, tools: [...profile.nativeTools] };
280
559
  },
281
560
  },
282
- async close() { for (const turn of turns.values()) {
561
+ respond(requestId, optionId) { const p = approvals.get(requestId); if (!p)
562
+ return; approvals.delete(requestId); clearTimeout(p.timer); p.resolve(optionId === 'accept'); },
563
+ async close() { for (const p of approvals.values()) {
564
+ clearTimeout(p.timer);
565
+ p.resolve(false);
566
+ } approvals.clear(); for (const turn of turns.values()) {
283
567
  turn.cancelled = true;
284
568
  turn.abort?.abort();
285
569
  } },
@@ -20,6 +20,63 @@ declare const effort: z.ZodEnum<{
20
20
  }>;
21
21
  /** Tools an agent may add to its default (Restricted) session access: research and expert delegation, never shell or writes. */
22
22
  export declare const defaultAccessTools: readonly ["WebSearch", "WebFetch", "Agent", "TodoWrite"];
23
+ export declare const expertContractSchema: z.ZodObject<{
24
+ schema: z.ZodLiteral<"tealbrick.expert-contract/v1">;
25
+ id: z.ZodString;
26
+ version: z.ZodString;
27
+ purpose: z.ZodString;
28
+ instructions: z.ZodString;
29
+ input: z.ZodObject<{
30
+ type: z.ZodLiteral<"object">;
31
+ }, z.core.$loose>;
32
+ output: z.ZodObject<{
33
+ type: z.ZodLiteral<"object">;
34
+ }, z.core.$loose>;
35
+ capabilities: z.ZodObject<{
36
+ builtinTools: z.ZodArray<z.ZodEnum<{
37
+ WebSearch: "WebSearch";
38
+ WebFetch: "WebFetch";
39
+ Read: "Read";
40
+ Glob: "Glob";
41
+ Grep: "Grep";
42
+ }>>;
43
+ apps: z.ZodArray<z.ZodObject<{
44
+ appId: z.ZodString;
45
+ operations: z.ZodArray<z.ZodString>;
46
+ }, z.core.$strict>>;
47
+ marketplace: z.ZodArray<z.ZodObject<{
48
+ plugin: z.ZodString;
49
+ actions: z.ZodArray<z.ZodString>;
50
+ }, z.core.$strict>>;
51
+ }, z.core.$strict>;
52
+ approval: z.ZodObject<{
53
+ outwardWrites: z.ZodEnum<{
54
+ always: "always";
55
+ "never-allowed": "never-allowed";
56
+ }>;
57
+ operations: z.ZodArray<z.ZodString>;
58
+ }, z.core.$strict>;
59
+ model: z.ZodEnum<{
60
+ haiku: "haiku";
61
+ inherit: "inherit";
62
+ opus: "opus";
63
+ sonnet: "sonnet";
64
+ }>;
65
+ effort: z.ZodOptional<z.ZodEnum<{
66
+ low: "low";
67
+ high: "high";
68
+ medium: "medium";
69
+ }>>;
70
+ budget: z.ZodObject<{
71
+ maxTurns: z.ZodNumber;
72
+ }, z.core.$strict>;
73
+ runtime: z.ZodEnum<{
74
+ subagent: "subagent";
75
+ "desktop-operator": "desktop-operator";
76
+ }>;
77
+ changelog: z.ZodOptional<z.ZodArray<z.ZodString>>;
78
+ }, z.core.$strict>;
79
+ export type ExpertContract = z.infer<typeof expertContractSchema>;
23
80
  export declare const serveConfigSchema: z.ZodObject<{
24
81
  version: z.ZodLiteral<1>;
25
82
  port: z.ZodNumber;
@@ -75,6 +132,8 @@ export declare const serveConfigSchema: z.ZodObject<{
75
132
  max: "max";
76
133
  }>>;
77
134
  }, z.core.$strict>>>;
135
+ contracts: z.ZodOptional<z.ZodArray<z.ZodString>>;
136
+ approvalOperations: z.ZodOptional<z.ZodArray<z.ZodString>>;
78
137
  nativeTools: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>>;
79
138
  readTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
80
139
  mcpServers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -89,6 +148,13 @@ export declare const serveConfigSchema: z.ZodObject<{
89
148
  inputEquals: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
90
149
  }, z.core.$strict>>>;
91
150
  requireSubscription: z.ZodOptional<z.ZodBoolean>;
151
+ workspace: z.ZodOptional<z.ZodObject<{
152
+ dir: z.ZodString;
153
+ network: z.ZodOptional<z.ZodObject<{
154
+ allowedDomains: z.ZodArray<z.ZodString>;
155
+ }, z.core.$strict>>;
156
+ envAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
157
+ }, z.core.$strict>>;
92
158
  envPassthrough: z.ZodOptional<z.ZodArray<z.ZodString>>;
93
159
  }, z.core.$strict>>;
94
160
  codex: z.ZodOptional<z.ZodObject<{
@@ -108,12 +174,23 @@ export interface ClaudeProfile {
108
174
  timeoutSeconds: number;
109
175
  defaultTools: string[];
110
176
  experts: Record<string, ClaudeExpert>;
177
+ contracts: Record<string, ExpertContract>;
178
+ approvalOperations: string[];
111
179
  nativeTools: string[];
112
180
  readTools: string[];
113
181
  mcpServers: Record<string, z.infer<typeof stdio>>;
114
182
  tealbrickCalls: Array<z.infer<typeof tealbrickCallGrant>>;
115
183
  requireSubscription: boolean;
116
184
  envPassthrough: string[];
185
+ /** Present only when `claude.workspace` is configured; `cwd` is then the workspace directory. */
186
+ workspace?: ClaudeWorkspace;
187
+ }
188
+ export interface ClaudeWorkspace {
189
+ dir: string;
190
+ root: string;
191
+ allowedDomains: string[];
192
+ /** envPassthrough names explicitly marked non-secret (still visible to sandboxed shell commands). */
193
+ envAllow: string[];
117
194
  }
118
195
  export interface ClaudeExpert {
119
196
  description: string;
@@ -126,6 +203,8 @@ export declare const servePaths: (root: string) => {
126
203
  config: string;
127
204
  state: string;
128
205
  sdk: string;
206
+ /** Kit-owned attachment inbox: written only by the kit process, readable (never writable) by the sandboxed workspace session. */
207
+ inbox: string;
129
208
  };
130
209
  export declare function normalizeOrigin(value: string): string;
131
210
  /** Host header values a TLS-terminating proxy for `publicUrl` may present. */