feat: expose agent session log location
This commit is contained in:
40 files changed
+526
-70
No files matched your search
@@ -20,6 +20,12 @@ The plugin also contributes the `tool:bash` prompt section (order 105) — the c
|
||||
|
||||
`command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution, so the executor seam (`BashExecSpec`) receives explicit `workdir`/`timeoutMs` values. The workdir default is applied in the tool layer (from the calling agent's `session.header.cwd`) BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`.
|
||||
|
||||
### Session identity environment
|
||||
|
||||
Every foreground and background call made for an agent receives `DSH_SESSION_ID=agent.session.header.id`. When the active persistence backend locates a JSONL artifact, the call also receives `DSH_SESSION_JSONL=<absolute target path>`; absent persistence and non-file backends still provide the id but omit the JSONL variable. The path is a location hint: lazy materialization means it may not exist on the first turn, and during an open turn it can omit buffered events that have not reached `session/flush`. Neither value is an authorization credential.
|
||||
|
||||
The overlay is computed from `ToolExecution.agent` for each call and passed through `BashExecRequest.env`; `process.env` is never modified, so concurrent parent/child agents keep separate values. The tool description names both variables so the model can inspect them without a permanent system-prompt section.
|
||||
|
||||
Result text: stdout, then a `[stderr]` section, then status markers — `[timed out after Nms]` whenever the executor's timer fired (reported independently of how the process ended, so a command that traps SIGTERM and exits 0 still shows it), `[killed by signal: …]` for a signal death, `[exit code: N]` for a non-zero exit (reported, **not** `isError`: the model decides how to react), and `[output truncated; full output: <path>]` when the tail was kept and a safe spill file is available. If the executor knows output was dropped but cannot safely advertise a complete spill file, the path is reported as `(unavailable)`. Only infrastructure failures (spawn errors, aborts) surface as `isError` results.
|
||||
|
||||
### `bash_output`
|
||||
@@ -44,7 +50,7 @@ When a background task finishes, a short notice is injected into the owning agen
|
||||
|
||||
## The tool builds its request from named args only
|
||||
|
||||
The `BashExecRequest` seam carries optional `stdin` and `env`, used by the hooks bridges to feed a hook command its JSON payload and `CLAUDE_*` env. This tool does **not** expose them as parameters: its request is built from `command`/`workdir`/`timeoutMs`/`signal`/`owner` only, so a model that includes `env` or `stdin` keys in its tool arguments has them ignored. This is not a trust boundary — a model already has equivalent power through shell syntax (`FOO=bar cmd`, a heredoc), and the real defense against leaking the harness's ambient secrets is `dsh-bash-local`'s credential scrub, which works regardless. A regression guard drives the real tool with those extra args and asserts the resulting request carries neither field — its job is to catch a future refactor that blindly spreads `...args` into the request (which would silently forward model input into the post-scrub `env` merge), not to defend a wall. See [the bash-stdin-env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
|
||||
The `BashExecRequest` seam carries optional `stdin` and `env`, used by trusted consumers. This tool does **not** expose them as model parameters: it builds the request from named schema fields and adds only the session overlay above, so model-supplied `env`/`stdin` keys are ignored and cannot replace the trusted values. This is not a trust boundary — a model already has equivalent power through shell syntax (`FOO=bar cmd`, a heredoc), and the real defense against leaking ambient secrets is `dsh-bash-local`'s credential scrub. Regression guards assert extra model fields never enter the request while the trusted overlay still does. See [the bash-stdin-env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
|
||||
|
||||
## Permissions
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-bash": "^0.0.1",
|
||||
"@deepseek-ai/dsh-llm": "^0.0.1",
|
||||
"@deepseek-ai/dsh-session-persistence": "^0.0.1",
|
||||
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
|
||||
"@deepseek-ai/dsh-tools": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
@@ -36,6 +37,8 @@
|
||||
"@deepseek-ai/dsh-bash-local": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-persistence": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:^",
|
||||
"@deepseek-ai/dsh-tools": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
|
||||
@@ -43,6 +43,7 @@ import { isAbsolute, resolve as resolvePath } from 'node:path'
|
||||
import { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import type { GenericCallView, TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-session-persistence'
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
import { BashTaskId, OwnerToken } from '@deepseek-ai/dsh-bash'
|
||||
import type { BashRunResult, BashTask, CollectedOutput } from '@deepseek-ai/dsh-bash'
|
||||
@@ -278,6 +279,22 @@ function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent
|
||||
return modelWorkdir
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the trusted per-execution session environment. Identity always comes
|
||||
* from the calling agent's immutable session header; an optional JSONL path
|
||||
* comes from the active persistence backend's side-effect-free locator. A
|
||||
* non-agent caller has no current session, so it receives neither variable.
|
||||
*/
|
||||
function sessionEnvironment(ctx: Context, exec: { agent?: Agent }): Record<string, string> | undefined {
|
||||
const agent = exec.agent
|
||||
if (agent === undefined) return undefined
|
||||
|
||||
const env: Record<string, string> = { DSH_SESSION_ID: agent.session.header.id }
|
||||
const location = ctx.get('sessionPersistence')?.locate(agent.session.header)
|
||||
if (location?.kind === 'jsonl') env.DSH_SESSION_JSONL = location.path
|
||||
return env
|
||||
}
|
||||
|
||||
/** Status line for background task reads. */
|
||||
function statusLine(task: BashTask): string {
|
||||
switch (task.status) {
|
||||
@@ -360,6 +377,8 @@ export function apply(ctx: Context): void {
|
||||
description: 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
|
||||
+ 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
|
||||
+ 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
|
||||
+ 'The current agent session id is available as `$DSH_SESSION_ID`; when JSONL persistence is configured, '
|
||||
+ '`$DSH_SESSION_JSONL` is its absolute target path and may not exist or contain the current unflushed turn yet. '
|
||||
+ 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
|
||||
+ 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
|
||||
+ 'poll it with `bash_output` and stop it with `bash_kill`.',
|
||||
@@ -385,11 +404,13 @@ export function apply(ctx: Context): void {
|
||||
// session runs in its own workspace (see resolveWorkdir); an explicit
|
||||
// model workdir still wins.
|
||||
const workdir = resolveWorkdir(args.workdir, exec)
|
||||
const env = sessionEnvironment(ctx, exec)
|
||||
const request = {
|
||||
command: args.command,
|
||||
...workdir !== undefined ? { workdir } : {},
|
||||
...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
|
||||
...exec.signal ? { signal: exec.signal } : {},
|
||||
...env !== undefined ? { env } : {},
|
||||
}
|
||||
if (args.run_in_background === true) {
|
||||
// Stamp the owner token (the agent's session id) onto the spec so the
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import LlmService from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import ToolRegistry from '@deepseek-ai/dsh-tools'
|
||||
import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
|
||||
@@ -17,10 +21,11 @@ import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent
|
||||
* through the agent loop, exercising the same seams a live model would
|
||||
* (tool/call + tool/result session events, agent.inject notifications).
|
||||
*/
|
||||
async function harness(adapter: MockAdapter) {
|
||||
async function harness(adapter: MockAdapter, sessionRoot?: string) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(LlmService)
|
||||
await ctx.plugin(SessionStore)
|
||||
if (sessionRoot !== undefined) await ctx.plugin(SessionPersistenceJsonl, { root: sessionRoot })
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(ToolRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
@@ -31,6 +36,9 @@ async function harness(adapter: MockAdapter) {
|
||||
return ctx
|
||||
}
|
||||
|
||||
const dirs: string[] = []
|
||||
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const dispose = ctx.on('agent/status', (subject, status) => {
|
||||
@@ -68,6 +76,37 @@ function resultText(event: SessionEvent): string {
|
||||
}
|
||||
|
||||
describe('bash tool through the agent loop', () => {
|
||||
it('first-turn bash receives session identity before the lazy JSONL file materializes', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
|
||||
dirs.push(root)
|
||||
const adapter = new MockAdapter([
|
||||
toolCallResponse('call-1', 'bash', {
|
||||
command: 'printf \'%s\\n%s\\n\' "$DSH_SESSION_ID" "$DSH_SESSION_JSONL"; if [ -e "$DSH_SESSION_JSONL" ]; then printf \'present\\n\'; else printf \'absent\\n\'; fi',
|
||||
description: 'inspect session environment',
|
||||
}),
|
||||
textResponse('Session environment inspected.'),
|
||||
])
|
||||
const ctx = await harness(adapter, root)
|
||||
const handle = ctx.agents.create({
|
||||
agentId: AgentId('session-env'),
|
||||
sessionId: SessionId('session-env-id'),
|
||||
agentOptions: { model: 'mock' },
|
||||
})
|
||||
const agent = handle.agent as ReactLoopAgent
|
||||
const location = ctx.sessionPersistence.locate(agent.session.header)
|
||||
expect(location?.kind).toBe('jsonl')
|
||||
|
||||
agent.send([{ type: 'text', text: 'inspect the current session' }])
|
||||
await waitForIdle(ctx, agent)
|
||||
|
||||
const result = findEvent(events(agent), 'tool/result')
|
||||
expect(resultText(result)).toBe(`session-env-id\n${location?.path}\nabsent\n`)
|
||||
expect(existsSync(location!.path)).toBe(true)
|
||||
const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
|
||||
expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
|
||||
await handle.dispose()
|
||||
})
|
||||
|
||||
it('foreground: model calls bash, sees the result, replies', async () => {
|
||||
const adapter = new MockAdapter([
|
||||
toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
|
||||
|
||||
@@ -10,6 +10,8 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import ToolRegistry from '@deepseek-ai/dsh-tools'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
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 * as ToolBash from '@deepseek-ai/dsh-tool-bash'
|
||||
import { renderResult } from '@deepseek-ai/dsh-tool-bash'
|
||||
@@ -910,16 +912,111 @@ describe('the model-facing bash tool builds its request from named args only (no
|
||||
kill(): boolean { return false }
|
||||
}
|
||||
|
||||
async function setupRecording() {
|
||||
async function setupRecording(withJsonl = false) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(ToolRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
if (withJsonl) {
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionPersistenceJsonl, { root: join(spillDir, 'jsonl') })
|
||||
}
|
||||
await ctx.plugin(RecordingBashExecutor)
|
||||
await ctx.plugin(ToolBash)
|
||||
return { ctx, bash: ctx.bash as RecordingBashExecutor }
|
||||
}
|
||||
|
||||
it('describes the trusted session variables to the model', async () => {
|
||||
const { ctx } = await setupRecording()
|
||||
const description = ctx.tools.get('bash')?.description ?? ''
|
||||
expect(description).toContain('DSH_SESSION_ID')
|
||||
expect(description).toContain('DSH_SESSION_JSONL')
|
||||
})
|
||||
|
||||
it('injects the session id and JSONL target path into a foreground request', async () => {
|
||||
const { ctx, bash } = await setupRecording(true)
|
||||
const agent = registerFakeAgent(ctx, 'request-fg', () => undefined)
|
||||
const path = ctx.sessionPersistence.locate(agent.session.header)?.path
|
||||
|
||||
await ctx.tools.execute({
|
||||
callId: CallId('session-env-fg'),
|
||||
name: 'bash',
|
||||
arguments: { command: 'true', description: 'run command' },
|
||||
agent,
|
||||
})
|
||||
|
||||
expect(bash.requests[0]?.env).toEqual({
|
||||
DSH_SESSION_ID: 'request-fg',
|
||||
DSH_SESSION_JSONL: path,
|
||||
})
|
||||
})
|
||||
|
||||
it('injects the same trusted variables into a background request without forwarding model env', async () => {
|
||||
const { ctx, bash } = await setupRecording(true)
|
||||
const agent = registerFakeAgent(ctx, 'request-bg', () => undefined)
|
||||
const path = ctx.sessionPersistence.locate(agent.session.header)?.path
|
||||
|
||||
await ctx.tools.execute({
|
||||
callId: CallId('session-env-bg'),
|
||||
name: 'bash',
|
||||
arguments: {
|
||||
command: 'sleep 1',
|
||||
description: 'run command',
|
||||
run_in_background: true,
|
||||
env: { DSH_SESSION_ID: 'spoofed', DSH_SESSION_JSONL: '/tmp/spoofed' },
|
||||
},
|
||||
agent,
|
||||
})
|
||||
|
||||
expect(bash.requests[0]?.env).toEqual({
|
||||
DSH_SESSION_ID: 'request-bg',
|
||||
DSH_SESSION_JSONL: path,
|
||||
})
|
||||
})
|
||||
|
||||
it('injects only the stable session id when no JSONL locator is available', async () => {
|
||||
const { ctx, bash } = await setupRecording()
|
||||
const agent = registerFakeAgent(ctx, 'request-id-only', () => undefined)
|
||||
const ambient = process.env.DSH_SESSION_ID
|
||||
|
||||
await ctx.tools.execute({
|
||||
callId: CallId('session-env-id-only'),
|
||||
name: 'bash',
|
||||
arguments: { command: 'true', description: 'run command' },
|
||||
agent,
|
||||
})
|
||||
|
||||
expect(bash.requests[0]?.env).toEqual({ DSH_SESSION_ID: 'request-id-only' })
|
||||
expect(process.env.DSH_SESSION_ID).toBe(ambient)
|
||||
})
|
||||
|
||||
it('keeps parent and child agent session environments isolated', async () => {
|
||||
const { ctx, bash } = await setupRecording(true)
|
||||
const parent = registerFakeAgent(ctx, 'request-parent', () => undefined)
|
||||
const child = registerFakeAgent(ctx, 'request-child', () => undefined)
|
||||
|
||||
for (const [callId, agent] of [['parent', parent], ['child', child]] as const) {
|
||||
await ctx.tools.execute({
|
||||
callId: CallId(`session-env-${callId}`),
|
||||
name: 'bash',
|
||||
arguments: { command: 'true', description: 'run command' },
|
||||
agent,
|
||||
})
|
||||
}
|
||||
|
||||
expect(bash.requests.map(request => request.env)).toEqual([
|
||||
{
|
||||
DSH_SESSION_ID: 'request-parent',
|
||||
DSH_SESSION_JSONL: ctx.sessionPersistence.locate(parent.session.header)?.path,
|
||||
},
|
||||
{
|
||||
DSH_SESSION_ID: 'request-child',
|
||||
DSH_SESSION_JSONL: ctx.sessionPersistence.locate(child.session.header)?.path,
|
||||
},
|
||||
])
|
||||
expect(bash.requests[0]?.env?.DSH_SESSION_JSONL).not.toBe(bash.requests[1]?.env?.DSH_SESSION_JSONL)
|
||||
})
|
||||
|
||||
it('does not forward env/stdin even when the model includes them as extra arguments', async () => {
|
||||
const { ctx, bash } = await setupRecording()
|
||||
// Extra args: the model includes `env` and `stdin` keys hoping they reach the
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
{
|
||||
"path": "../../core/agent"
|
||||
},
|
||||
{
|
||||
"path": "../../session-persistence/session-persistence"
|
||||
},
|
||||
{
|
||||
"path": "../../bash/bash"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user