Merge remote-tracking branch 'origin/master' into codex/agent-session-jsonl-location

# Conflicts:
#	docs/module-graph.md
#	docs/tool-catalog.md
#	examples/acp-agent/tests/snapshots/both-mode-turn/session.jsonl
#	examples/acp-agent/tests/snapshots/code-mode-turn/session.jsonl
#	examples/acp-agent/tests/snapshots/text-turn/session.jsonl
#	packages/bash/tool-bash/README.md
#	packages/bash/tool-bash/package.json
#	packages/bash/tool-bash/src/index.ts
#	packages/cordis/tool-cordis/src/api-catalog.ts
This commit is contained in:
Yichen Jiang
2026-07-11 22:57:27 +08:00
190 changed files with 12183 additions and 456 deletions

View File

@@ -1,11 +1,12 @@
import { mkdtempSync } from 'node:fs'
import { chmodSync, mkdirSync, mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import { CallId } from '@deepseek-ai/dsh-llm'
import { BashExecutor, BashTaskId } from '@deepseek-ai/dsh-bash'
import { BashExecutor, BashTaskId, setSandboxMode } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } from '@deepseek-ai/dsh-bash'
import { Session, SessionId } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import AgentRegistry from '@deepseek-ai/dsh-agent'
@@ -13,11 +14,29 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import SessionStore from '@deepseek-ai/dsh-session'
import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
import { SandboxProvider } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv } from '@deepseek-ai/dsh-sandbox'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import ApprovalService from '@deepseek-ai/dsh-user-approval'
import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import { renderResult } from '@deepseek-ai/dsh-tool-bash'
const spillDir = mkdtempSync(join(tmpdir(), 'dsh-tool-bash-spec-'))
// Pure-config passthrough runner (same knob the snapshot tier uses): skips the
// profile args up to `--` and execs the command unconfined — deterministic
// without a host bwrap.
const PASSTHROUGH_RUNNER = ['bash', '-c', 'while [ "$1" != "--" ]; do shift; done; shift; exec "$@"', 'passthrough-runner']
const PASSTHROUGH_RUNNER_CONFIG = {
runnerCommand: PASSTHROUGH_RUNNER,
// The script has no pre-exec failure path; the provider still requires an
// explicit dialect so a future script change cannot silently turn runner
// failure into an ordinary command result.
runnerFailureSignatures: ['passthrough-runner: profile rejected'],
}
async function setup() {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
@@ -102,6 +121,7 @@ class LossyReadBashExecutor extends BashExecutor {
timeoutMs: request.timeoutMs ?? 0,
...request.signal ? { signal: request.signal } : {},
owner: request.owner,
sandboxMode: request.sandboxMode,
}
}
@@ -896,6 +916,7 @@ describe('the model-facing bash tool builds its request from named args only (no
...request.stdin !== undefined ? { stdin: request.stdin } : {},
...request.env !== undefined ? { env: request.env } : {},
owner: request.owner,
sandboxMode: request.sandboxMode,
}
}
run(): Promise<BashRunResult> {
@@ -1067,3 +1088,512 @@ describe('the model-facing bash tool builds its request from named args only (no
expect('owner' in request).toBe(true)
})
})
describe('sandbox rendering', () => {
const sandboxResult = (denied: boolean, exitCode: number): BashRunResult => ({
exitCode,
signal: null,
timedOut: false,
aborted: false,
timeoutMs: 1000,
stdout: { text: '', truncated: false },
stderr: { text: denied ? 'bash: /x: Read-only file system' : 'boom', truncated: false },
sandbox: { mode: 'read-only', denied },
})
it('renders a denial marker BEFORE the exit-code marker (the $-anchored parse survives)', () => {
const text = renderResult(sandboxResult(true, 1))
expect(text).toMatch(/\[sandbox: file access denied under read-only mode\]\n\[exit code: 1\]$/)
})
it('appends the same-turn escalation hint to a denial exactly when the fields are advertised', () => {
const hinted = renderResult(sandboxResult(true, 1), ['workspace-write', 'danger-full-access'])
expect(hinted).toMatch(
/denied under read-only mode\]\n\[sandbox: escalation available — retry this exact command once with sandbox_permissions [^\n]+\]\n\[exit code: 1\]$/, // eslint-disable-line @stylistic/max-len -- the hint sentence is pinned verbatim
)
// Default (no advertisement): no hint — a lever the schema does not offer is never suggested.
expect(renderResult(sandboxResult(true, 1))).not.toContain('escalation available')
// A non-denied result never hints, advertised or not.
expect(renderResult(sandboxResult(false, 2), ['danger-full-access'])).not.toContain('escalation available')
})
it('renders no sandbox marker for a plain failure under a sandboxed mode', () => {
expect(renderResult(sandboxResult(false, 2))).not.toContain('[sandbox:')
})
it('bash_output reports a settled background denial with the same marker', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
const bash = ctx.bash as SandboxBashExecutor
bash.internals = { spillDir }
await ctx.plugin(ToolBash)
const started = await call(ctx, 'bash', { command: 'echo "x: Permission denied" >&2; exit 1', description: 'test command', run_in_background: true })
const id = text(started).match(/started background task (bash-\d+)/)![1]
await bash.list().find(task => task.id === id)!.done
const read = await call(ctx, 'bash_output', { task_id: id })
expect(text(read)).toMatch(
/\[status: completed, exit code: 1\]\n\[sandbox: file access denied under read-only mode\]\n\[sandbox: escalation available[^\n]+\]$/,
)
})
it('a settled background denial renders no escalation hint without a confining executor (defensive arm)', async () => {
// Structurally near-unreachable through the real stack — every confining
// default advertises the static target set — but the read path guards
// it anyway: an executor that reports no sandboxMode (fields never
// advertised) whose task nonetheless carries denial facts must render
// the marker without suggesting a lever the schema does not offer.
class FactsOnlyExecutor extends BashExecutor {
private readonly task: BashTask = {
id: BashTaskId('bash-facts'),
command: 'fake',
status: 'completed',
exitCode: 1,
signal: null,
done: Promise.resolve(),
sandbox: { mode: 'read-only', denied: true },
}
resolve(request: BashExecRequest): BashExecSpec {
return {
command: request.command,
workdir: request.workdir ?? process.cwd(),
timeoutMs: request.timeoutMs ?? 0,
...request.signal ? { signal: request.signal } : {},
owner: request.owner,
sandboxMode: request.sandboxMode,
}
}
run(): Promise<BashRunResult> { return Promise.reject(new Error('not used')) }
start(): BashTask { return this.task }
get(id: string): BashTask | undefined { return id === this.task.id ? this.task : undefined }
list(): BashTask[] { return [this.task] }
kill(): boolean { return false }
ownerOf(): OwnerToken | undefined { return undefined }
readOutput(): BashTaskRead {
return { task: this.task, delta: '', lossy: false }
}
}
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(FactsOnlyExecutor)
await ctx.plugin(ToolBash)
const read = await call(ctx, 'bash_output', { task_id: 'bash-facts' })
expect(text(read)).toMatch(/\[sandbox: file access denied under read-only mode\]$/)
expect(text(read)).not.toContain('escalation available')
})
it('bash_output reports a settled background RUNNER failure as a sandbox problem, outranking the denial marker', async () => {
// A provider whose wrap carries a runner-failure signature: the settled
// task's stderr matching it means the sandbox itself broke and the
// command never ran — even though the same stderr also carries denial
// words (a runner's error text may contain them).
class FakeProvider extends SandboxProvider {
confine(argv: readonly string[]): ConfinedArgv {
return { argv: [...argv], enforcement: 'full', denialSignatures: ['permission denied'], runnerFailureSignatures: ['fake-runner: '] }
}
}
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(FakeProvider)
await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
const bash = ctx.bash as SandboxBashExecutor
bash.internals = { spillDir }
await ctx.plugin(ToolBash)
const started = await call(ctx, 'bash', { command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125', description: 'test command', run_in_background: true })
const id = text(started).match(/started background task (bash-\d+)/)![1]
await bash.list().find(task => task.id === id)!.done
const read = await call(ctx, 'bash_output', { task_id: id })
expect(text(read)).toMatch(/\[sandbox: the sandbox runner itself failed under read-only mode — the command did not run; /)
expect(text(read)).toMatch(/this is a sandbox problem, not a command failure\]$/)
expect(text(read)).not.toContain('file access denied')
})
it('classifies an executable configured runner that refuses its profile before the command runs', async () => {
const signature = 'custom-runner-rejected'
const ctx = new Context()
await ctx.plugin(LocalSandboxProvider, {
runnerCommand: ['bash', '-c', `printf '${signature}\\n' >&2; exit 125`, 'custom-runner'],
runnerFailureSignatures: [signature],
})
await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
const bash = ctx.bash as SandboxBashExecutor
bash.internals = { spillDir }
await expect(bash.run(bash.resolve({ command: 'echo command-must-not-run' })))
.rejects.toMatchObject({ code: 'SANDBOX_UNAVAILABLE' })
const task = bash.start(bash.resolve({ command: 'echo command-must-not-run' }))
await task.done
expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
})
it('reports a real denial end-to-end through the shipping sandbox executor', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
await ctx.plugin(SandboxBashExecutor, { graceMs: 200 })
const bash = ctx.bash as SandboxBashExecutor
bash.internals = { spillDir }
await ctx.plugin(ToolBash)
const lockedDir = join(mkdtempSync(join(tmpdir(), 'dsh-tool-bash-denied-')), 'locked')
mkdirSync(lockedDir)
chmodSync(lockedDir, 0o555)
const result = await call(ctx, 'bash', { command: `echo x > ${lockedDir}/f`, description: 'Write into a locked directory' })
expect(result.isError).toBe(false)
expect(text(result)).toMatch(
/denied under read-only mode\]\n\[sandbox: escalation available[^\n]+\]\n\[exit code: \d+\]$/,
)
})
})
describe('sandbox escalation (sandbox_permissions / justification)', () => {
/** Compose the real sandbox stack (passthrough runner) at a given default mode. */
async function setupSandboxed(mode?: 'read-only' | 'workspace-write' | 'danger-full-access', opts: { approval?: boolean; policy?: 'ask' | 'never' } = {}) {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
await ctx.plugin(SandboxBashExecutor, { graceMs: 200, ...mode !== undefined ? { mode } : {} })
const bash = ctx.bash as SandboxBashExecutor
bash.internals = { spillDir }
if (opts.approval === true) await ctx.plugin(ApprovalService, opts.policy !== undefined ? { policy: opts.policy } : {})
await ctx.plugin(ToolBash)
return { ctx, bash }
}
/** The registered bash tool's wire schema (what the model actually sees). */
function bashSchema(ctx: Context) {
const schema = ctx.tools.schemas().find(s => s.name === 'bash')
if (!schema) throw new Error('bash tool not registered')
return schema as unknown as { description: string; parameters: { properties: Record<string, { enum?: string[] }> } }
}
/**
* A fake agent whose session records appends — the approval audit surface.
* Seeded mid-turn: an escalating call always runs inside one, and request()
* enforces the enclosure.
*/
function escalationAgent(events: Array<{ type: string; data: Record<string, unknown> }>): Agent {
return {
id: 'agent-esc',
session: {
header: { version: 0, id: 'sess-esc', createdAt: 0 },
events: [{ type: 'turn/start' }],
append: (type: string, data: Record<string, unknown>) => { events.push({ type, data }) },
},
} as unknown as Agent
}
let escCall = 0
function callAs(ctx: Context, agent: Agent | undefined, args: unknown) {
return ctx.tools.execute({ callId: CallId(`call-esc-${++escCall}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
}
const ESCALATE = { command: 'true', description: 'test escalation', sandbox_permissions: 'workspace-write', justification: 'the test needs it' }
it('advertises no escalation surface under a non-sandboxing executor', async () => {
const ctx = await setup()
expect(ctx.bash.sandboxMode).toBeUndefined()
const schema = bashSchema(ctx)
expect(schema.parameters.properties['sandbox_permissions']).toBeUndefined()
expect(schema.parameters.properties['justification']).toBeUndefined()
expect(schema.description).not.toContain('sanctioned exception')
})
it('advertises the full closed target vocabulary under any confining default', async () => {
// The enum is deliberately NOT default-relative: a session's effective
// mode is per-session and switchable, so every confining composition
// advertises every possible target — strict widening is checked at
// execution against the call's effective mode instead.
for (const mode of [undefined, 'workspace-write', 'danger-full-access'] as const) {
const { ctx } = await setupSandboxed(mode)
const schema = bashSchema(ctx)
expect(schema.parameters.properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
expect(schema.parameters.properties['justification']).toBeDefined()
expect(schema.description).toContain('sanctioned exception')
}
})
it('a non-widening request fails at execution with its own text and prompts no one', async () => {
const { ctx } = await setupSandboxed('danger-full-access', { approval: true })
const consulted = vi.fn()
ctx.on('approval/request', (_req, next) => { consulted(); return next() })
const result = await callAs(ctx, escalationAgent([]), { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'already wider' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('not strictly wider than this call\'s current "danger-full-access" mode')
expect(consulted).not.toHaveBeenCalled()
})
it('rejects sandbox_permissions without a justification, and vice versa, and a blank justification', async () => {
const { ctx } = await setupSandboxed()
const missing = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write' })
expect(missing.isError).toBe(true)
expect(text(missing)).toContain('sandbox_permissions requires a justification')
const orphan = await callAs(ctx, undefined, { command: 'true', description: 'd', justification: 'why not' })
expect(orphan.isError).toBe(true)
expect(text(orphan)).toContain('only valid together with sandbox_permissions')
const blank = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' })
expect(blank.isError).toBe(true)
expect(text(blank)).toContain('expected a non-empty sentence')
})
it('the schema enum rejects a mode outside the target vocabulary before execute (registry-level, any caller)', async () => {
const { ctx } = await setupSandboxed()
const result = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'read-only', justification: 'narrow' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('must be one of')
})
it('rejects an unadvertised sandbox_permissions injection under a non-sandboxing executor', async () => {
const ctx = await setup()
const result = await callAs(ctx, undefined, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'sneaky' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('not available in this composition')
})
it('fails closed with its own text when no approval service is composed', async () => {
const { ctx } = await setupSandboxed()
const result = await callAs(ctx, escalationAgent([]), ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('no approval service is composed')
})
it('fails closed with its own text for an agent-less escalating call', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
const result = await callAs(ctx, undefined, ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('no agent to route it through')
})
it('fails closed with its own text when the service has no answerer', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
const result = await callAs(ctx, escalationAgent([]), ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('no approval channel is available')
})
it('a grant runs THAT call under the wider mode — the denial marker names it — and lands the audit pair', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const events: Array<{ type: string; data: Record<string, unknown> }> = []
// A real unix denial under the passthrough runner: the marker's mode can
// only say workspace-write if the override actually rode the spec.
const lockedDir = join(mkdtempSync(join(tmpdir(), 'dsh-esc-denied-')), 'locked')
mkdirSync(lockedDir)
chmodSync(lockedDir, 0o555)
const result = await callAs(ctx, escalationAgent(events), {
command: `echo x > ${lockedDir}/f`,
description: 'write into a locked directory',
sandbox_permissions: 'workspace-write',
justification: 'must write outside the workspace',
})
expect(result.isError).toBe(false)
expect(text(result)).toMatch(/\[sandbox: file access denied under workspace-write mode\]/)
expect(events.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
expect(events[0]?.data['toolName']).toBe('bash')
expect(events[0]?.data['reason']).toBe('escalate sandbox to workspace-write: must write outside the workspace')
expect(events[1]?.data['outcome']).toBe('allowed-once')
})
it('a granted background start settles with the wider mode\'s facts', async () => {
const { ctx, bash } = await setupSandboxed('read-only', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const started = await callAs(ctx, escalationAgent([]), { ...ESCALATE, run_in_background: true })
expect(started.isError).toBe(false)
const id = text(started).match(/started background task (bash-\d+)/)?.[1]
const task = bash.list().find(t => t.id === id)
if (!task) throw new Error('escalated task not tracked')
await task.done
expect(task.sandbox).toMatchObject({ mode: 'workspace-write', denied: false })
})
it('a rejection denies with the user-said-no text and runs nothing', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
// A live (non-aborted) signal rides the execution: the gate threads it
// into the approval request so a turn cancellation can withdraw the ask.
const result = await ctx.tools.execute({
callId: CallId(`call-esc-${++escCall}`),
name: 'bash',
arguments: ESCALATE,
agent: escalationAgent([]),
signal: new AbortController().signal,
})
expect(result.isError).toBe(true)
expect(text(result)).toContain('the user rejected escalating this command to "workspace-write"')
})
it('a cancellation denies with the cancelled text', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('cancelled'))
const result = await callAs(ctx, escalationAgent([]), ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('approval for escalating to "workspace-write" was cancelled')
})
it('a rogue approval stand-in returning a non-vocabulary outcome hits the exhaustiveness backstop', async () => {
const { ctx } = await setupSandboxed()
ctx.provide('approval', { request: () => Promise.resolve('yolo') } as unknown as InstanceType<typeof ApprovalService>)
const result = await callAs(ctx, escalationAgent([]), ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('unreachable')
})
it('a never policy rejects an escalation deterministically without consulting any answerer', async () => {
// The live-session e.md case: the model requests escalation against a
// 'never' session — the prepend gate answers rejected before any
// interactive answerer, the fail-closed text is the ordinary rejection
// wording, and the audit pair still lands.
const { ctx } = await setupSandboxed('read-only', { approval: true, policy: 'never' })
const consulted = vi.fn()
ctx.on('approval/request', (_req, next) => { consulted(); return next() })
const events: Array<{ type: string; data: Record<string, unknown> }> = []
const result = await callAs(ctx, escalationAgent(events), ESCALATE)
expect(result.isError).toBe(true)
expect(text(result)).toContain('the user rejected escalating this command to "workspace-write"')
expect(consulted).not.toHaveBeenCalled()
expect(events.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
expect(events[1]?.data).toMatchObject({ outcome: 'rejected' })
})
it('a plain call under a sandboxing executor never consults approval', async () => {
const { ctx } = await setupSandboxed('read-only', { approval: true })
const asked = vi.fn()
ctx.on('approval/request', (_req, next) => { asked(); return next() })
const result = await callAs(ctx, escalationAgent([]), { command: 'echo plain', description: 'plain run' })
expect(result.isError).toBe(false)
expect(text(result)).toContain('plain')
expect(asked).not.toHaveBeenCalled()
})
})
describe('per-session sandbox mode (the bash/sandbox-mode fold)', () => {
/** Compose the real sandbox stack (passthrough runner) at a given default mode. */
async function setupModal(mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'read-only', opts: { approval?: boolean } = {}) {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(LocalSandboxProvider, PASSTHROUGH_RUNNER_CONFIG)
await ctx.plugin(SandboxBashExecutor, { graceMs: 200, mode })
;(ctx.bash as SandboxBashExecutor).internals = { spillDir }
if (opts.approval === true) await ctx.plugin(ApprovalService)
await ctx.plugin(ToolBash)
return ctx
}
/**
* An agent stand-in over a REAL Session — the stamping folds real events;
* the opened turn satisfies approval's enclosure precondition on escalating
* calls.
*/
function sessionAgent(id: string): { agent: Agent; session: Session; injected: string[] } {
const session = new Session(SessionId(id))
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
const injected: string[] = []
const agent = {
id,
session,
inject: (content: { type: string; text: string }[]) => { injected.push(content[0]?.text ?? '') },
} as unknown as Agent
return { agent, session, injected }
}
let modeCall = 0
const callAs = (ctx: Context, agent: Agent | undefined, args: unknown) =>
ctx.tools.execute({ callId: CallId(`call-mode-${++modeCall}`), name: 'bash', arguments: args, ...agent ? { agent } : {} })
it('stamps calls with grant > session override > nothing (executor default)', async () => {
const ctx = await setupModal('read-only', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const seen: (string | undefined)[] = []
const original = ctx.bash.resolve.bind(ctx.bash)
vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
seen.push(req.sandboxMode)
return original(req)
})
const { agent, session } = sessionAgent('sess-stamp-1')
const run = { command: 'true', description: 'stamp probe' }
await callAs(ctx, agent, run) // no override yet
setSandboxMode(session, 'workspace-write')
await callAs(ctx, agent, run) // standing override
await callAs(ctx, undefined, run) // agent-less caller: no session to fold
await callAs(ctx, agent, { ...run, sandbox_permissions: 'danger-full-access', justification: 'grant outranks override' })
expect(seen).toEqual([undefined, 'workspace-write', undefined, 'danger-full-access'])
})
it('escalates relative to the session effective mode, not the executor default (narrower override)', async () => {
// The blocker scenario: a workspace-write default with a read-only
// override — the sensible escalation is workspace-write, which a
// default-relative ladder could not even express. The static target
// vocabulary advertises it and the execution check accepts it as
// strictly wider than the CALL's effective (overridden) mode.
const ctx = await setupModal('workspace-write', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const seen: (string | undefined)[] = []
const original = ctx.bash.resolve.bind(ctx.bash)
vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
seen.push(req.sandboxMode)
return original(req)
})
const { agent, session } = sessionAgent('sess-esc-narrow')
setSandboxMode(session, 'read-only')
const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'the override is narrower than the default' })
expect(result.isError).toBe(false)
expect(seen).toEqual(['workspace-write'])
})
it('a danger-full-access default still offers the lever to a narrower-switched session', async () => {
// Under the default-relative ladder these fields VANISHED (nothing is
// wider than the default), stranding a read-only-overridden session
// with no escalation path at all.
const ctx = await setupModal('danger-full-access', { approval: true })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const schema = ctx.tools.schemas().find(t => t.name === 'bash') as unknown as { parameters: { properties: Record<string, { enum?: string[] }> } }
expect(schema.parameters.properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
const { agent, session } = sessionAgent('sess-esc-dfa')
setSandboxMode(session, 'read-only')
const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'confined by override under a wide default' })
expect(result.isError).toBe(false)
})
it('rejects a non-widening request against the OVERRIDDEN effective mode without prompting', async () => {
const ctx = await setupModal('read-only', { approval: true })
const consulted = vi.fn()
ctx.on('approval/request', (_req, next) => { consulted(); return next() })
const { agent, session } = sessionAgent('sess-esc-nonwide')
setSandboxMode(session, 'danger-full-access')
const result = await callAs(ctx, agent, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: 'already wider via override' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('not strictly wider than this call\'s current "danger-full-access" mode')
expect(consulted).not.toHaveBeenCalled()
})
it('never stamps an override under a non-sandboxing executor (nothing honors it)', async () => {
const ctx = await setup()
const seen: (string | undefined)[] = []
const original = ctx.bash.resolve.bind(ctx.bash)
vi.spyOn(ctx.bash, 'resolve').mockImplementation((req) => {
seen.push(req.sandboxMode)
return original(req)
})
const { agent, session } = sessionAgent('sess-stamp-2')
setSandboxMode(session, 'danger-full-access')
await callAs(ctx, agent, { command: 'true', description: 'plain probe' })
expect(seen).toEqual([undefined])
})
})