Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/mms/bots/activation/BotEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7236,10 +7236,13 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
// Its question forgotten while this turn was still ending: the work has nothing to go on with, and ends saying so.
const forgotten = !reload && run.status === 'completed' && row.lane === 'run' && !question && this.store.forgottenWorkQuestion(row.id) !== undefined
// Its commands met a sandbox that can't start (`sandboxUnavailable`): it waits for the sandbox, once.
const sandboxNeeds = this.sandboxNeeds.get(row.id)
const sandboxWait = this.sandboxWaits.delete(row.id) && !reload && run.status === 'completed' && WORK_WAIT_RULES.sandbox.allows(row) &&
// The launcher that refused (its provider's, or Mousse's runner for a background or secret command) still can't start.
// Any launcher that refused (its provider's, a subagent's, or Mousse's runner) still can't start.
(this.sandboxes.resolveNow(row.botId, row.selection ? { instanceId: row.selection.instanceId } : { runner: 'mousse' }, 'work').kind === 'unavailable' ||
this.sandboxes.resolveNow(row.botId, { runner: 'mousse' }, 'watcher').kind === 'unavailable')
this.sandboxes.resolveNow(row.botId, { runner: 'mousse' }, 'watcher').kind === 'unavailable' ||
[...(sandboxNeeds ?? [])].some((need) => this.sandboxes.resolveNow(row.botId, sandboxTargetOf(need), need === RUNNER_ENTRY ? 'watcher' : 'work').kind === 'unavailable'))
if (!sandboxWait) this.sandboxNeeds.delete(row.id)
if (unknown || run.status === 'uncertain') {
this.store.moveActivation(row.id, ['running'], 'paused', { endReason: run.status === 'uncertain' && !unknown ? 'uncertain' : 'unknown_calls', ...(text !== undefined ? { result: text } : {}) })
} else if (openWalls.length) {
Expand Down
17 changes: 12 additions & 5 deletions src/mms/harness/pi/extension/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,10 @@ export function containedBashOperations(options: ContainedShellOptions) {
// Not recorded: the gate gets no go line and starts nothing.
child.stdin?.end()
kill(pid)
await exited.catch(() => {})
throw signal?.aborted ? new Error('aborted') : error
const exitCode = await exited.catch(() => null)
if (signal?.aborted) throw new Error('aborted')
if (error && typeof error === 'object' && exitCode !== null) Object.assign(error, { exitCode })
throw error
}
if (signal?.aborted) {
child.stdin?.end()
Expand Down Expand Up @@ -315,9 +317,14 @@ export function botBashOperations(options: {
result = await options.held(wrap).exec(command, cwd, { ...exec, onData })
failure = heldStartFailure({ platform, code: result.exitCode, output: head.toString('utf8'), provider: 'Pi' })
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code
// The sandbox's program could not start (not on this computer): a start failure, never the command's.
if (typeof code === 'string' && !exec.signal?.aborted) failure = heldStartFailure({ platform, code: null, output: '', provider: 'Pi', spawnError: code })
const err = error as (NodeJS.ErrnoException & { exitCode?: number | null }) | undefined
const code = err?.code
// The sandbox's program could not start (not on this computer, or exited before the gate's group could be recorded):
// a start failure, never the command's.
if (!exec.signal?.aborted) {
if (typeof code === 'string') failure = heldStartFailure({ platform, code: null, output: '', provider: 'Pi', spawnError: code })
else if (typeof err?.exitCode === 'number') failure = heldStartFailure({ platform, code: err.exitCode, output: head.toString('utf8'), provider: 'Pi' })
}
if (!failure) throw error
}
if (failure) {
Expand Down
2 changes: 1 addition & 1 deletion tests/bots/botContinuationPermission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ it('a continuation of bot work is not told the thread\'s permission mode changed
prompt: payload.dispatchN === 1 ? 'Create 30 note files, one at a time.' : '[Mousse] You reached the most steps one turn may take; what you did so far is kept. Continue.',
selection: { instanceId: 'claude', model: 'opus' },
policy: { approvals: 'grants', approve: 'host', tools: { allow: ['read', 'edit'] }, authority: { kind: 'bot', digest: 'd' } },
authority: { time: { signal: time.signal }, appTools: new Set<string>(), check: () => ({ ok: true }) } as never,
authority: { time: { signal: time.signal }, appTools: new Set<string>(), check: () => ({ ok: true }), sandbox: { policy: { kind: 'open', revision: 1 }, computer: 'Laptop', runner: async () => ({ kind: 'open', revision: 1 }) } } as never,
scratch,
skills: [],
history: payload.dispatchN === 1 ? 'none' : 'thread'
Expand Down
2 changes: 1 addition & 1 deletion tests/bots/botReplyFinalMessage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async function botTurn(script: (input: Parameters<Chat>[0], time: AbortControlle
prompt: 'Report on this computer',
selection: { instanceId: 'claude', model: 'opus' },
policy: { approvals: 'grants', approve: 'host', tools: { allow: ['read', 'shell'] }, authority: { kind: 'bot', digest: 'd' } },
authority: { time: { signal: time.signal }, appTools: new Set<string>(), check: () => ({ ok: true }) } as never,
authority: { time: { signal: time.signal }, appTools: new Set<string>(), check: () => ({ ok: true }), sandbox: { policy: { kind: 'open', revision: 1 }, computer: 'Laptop', runner: async () => ({ kind: 'open', revision: 1 }) } } as never,
scratch,
skills: [],
history: 'none',
Expand Down
4 changes: 3 additions & 1 deletion tests/bots/botSandboxSetting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ describe("a bot's command sandbox setting", () => {
})

it("after a restart, work parked for another entry's sandbox waits for that entry's own probe: not probed is not started", async () => {
// A subagent's entry (`second`) misses socat; the work's own entry and Mousse's runner start.
// A subagent's entry (`second`) misses socat; the work's own entry and Mousse's runner start (as on Linux).
f.host.platform = 'linux'
let socat = false
const second: BotSandboxSupport = { ...STARTING_SANDBOX, key: 'second', probe: async () => (socat ? undefined : missingPackages(['socat'], 'Claude Code')) }
f.host.harness.botSandbox = (instanceId) => (instanceId === 'second' ? second : support)
Expand All @@ -164,6 +165,7 @@ describe("a bot's command sandbox setting", () => {
expect(f.store.activation(turn.id)).toMatchObject({ status: 'blocked', endReason: 'sandbox' })
// The owner installs it, while the work's own entry and Mousse's runner can't start: the next look still probes
// `second` again, and the work carries on.
f.host.platform = 'win32'
support = { ...STARTING_SANDBOX, key: 'broken', probe: async () => missingPackages(['bubblewrap'], 'Claude Code') }
socat = true
const view = await f.bots.service.sandboxGet(botId)
Expand Down
14 changes: 12 additions & 2 deletions tests/harness/piBotGate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,19 @@ describe("a bot's bash runs as its command sandbox says (Pi RPC engine, real chi
}, 120_000)

it.runIf(HELD_HERE)('held: it changes its own folder, and nothing outside its folders', async () => {
const ran = await turnUnder(() => sandboxOf({ kind: 'held', revision: 3, network: { kind: 'blocked' } }), ({ root }) => `echo made > made.txt; touch "${join(root, '..', 'outside.txt')}"; echo exit=$?`)
let outside = ''
const ran = await turnUnder(
() => sandboxOf({ kind: 'held', revision: 3, network: { kind: 'blocked' } }),
({ root }) => {
// A sibling folder outside the bot's own folders (not mounted into bwrap's private `/tmp`, and not writable under Seatbelt).
outside = join(root, '..', 'outside')
mkdirSync(outside, { recursive: true })
return `echo made > made.txt; touch "${join(outside, 'outside.txt')}"; echo exit=$?`
}
)
expect(ran.bash).toMatch(/exit=[1-9]/)
expect(readFileSync(join(ran.files, 'made.txt'), 'utf8')).toBe('made\n')
expect(existsSync(join(ran.root, '..', 'outside.txt'))).toBe(false)
expect(existsSync(join(outside, 'outside.txt'))).toBe(false)
}, 120_000)

it.runIf(BWRAP !== undefined)("held, the sandbox fails to start: the owner's card (startFailed), and the model is told it did not run", async () => {
Expand Down Expand Up @@ -385,6 +394,7 @@ describe("a bot's bash, by its turn's sandbox (the extension's decision)", () =>

it.each([
['bubblewrap refuses user namespaces', async (_w: unknown, onData: (data: Buffer) => void) => { onData(Buffer.from('bwrap: setting up uid map: Permission denied\n')); return { exitCode: 1 } }, 'userns_blocked'],
['bubblewrap exits before the gate group is recorded', async (_w: unknown, onData: (data: Buffer) => void) => { onData(Buffer.from("bwrap: Can't find source path /gone: No such file or directory\n")); throw Object.assign(new Error('unverified group'), { exitCode: 1 }) }, 'start_failed'],
['bubblewrap is not there', async () => { throw Object.assign(new Error('The shell did not start'), { code: 'ENOENT' }) }, 'missing_packages']
] as const)('held, %s: a start failure reported to Mousse, never the command\'s', async (_name, heldRun, reason) => {
const ops = operations(held, heldRun)
Expand Down
22 changes: 22 additions & 0 deletions tests/harness/piShell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,26 @@ describe.runIf(runs)('contained bash operations, against pinned Pi’s bash', ()
expect(existsSync(marker)).toBe(false)
expect(killed.length).toBeGreaterThan(0)
})

it('a wrapped wrapper that exits before the group is recorded still hands back its exit code and output', async () => {
const dir = scratch()
const ops = containedBashOperations({
report: async () => {
// Give the failing wrapper time to exit first, as bwrap does before /pi/group verifies the pid.
await new Promise((done) => setTimeout(done, 150))
throw new Error('unverified group')
},
shell: bash,
gate: sh,
detached: !windows,
...(windows ? { envPath: gitEnv } : {}),
wrap: () => ({ program: sh, args: ['-c', "echo \"bwrap: Can't find source path /gone: No such file or directory\" >&2; exit 1"] }),
killGroup: (pid) => { try { process.kill(windows ? pid : -pid, 'SIGKILL') } catch { /* gone */ } }
})
const chunks: Buffer[] = []
const err = await ops.exec('echo never', dir, { onData: (data) => chunks.push(data) }).catch((error: unknown) => error)
expect(err).toBeInstanceOf(Error)
expect((err as Error & { exitCode?: number }).exitCode).toBe(1)
expect(Buffer.concat(chunks).toString('utf8')).toContain("bwrap: Can't find source path /gone")
})
})
1 change: 1 addition & 0 deletions tests/run/codexAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2869,6 +2869,7 @@ describe('a bot turn on Codex', () => {
])
const binary = join(home, 'codex')
writeFileSync(binary, '#!/bin/sh\nexit 0\n')
chmodSync(binary, 0o755)
mkdirSync(join(home, 'providers', 'codex'), { recursive: true })
writeFileSync(settingsPath(), JSON.stringify({ binaryPath: binary, models: [{ id: 'gpt-x', label: 'GPT X' }] }))
replayCodexEnv(home)
Expand Down
Loading