diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index cb84236414..09a0f39b1f 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -1249,6 +1249,9 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'], ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'], ['sandbox', '@deepseek-ai/dsh-sandbox-local'], + ['filesystem', '@deepseek-ai/dsh-fs-local'], + ['working-directory', '@deepseek-ai/dsh-working-directory'], + ['tool-working-directory', '@deepseek-ai/dsh-tool-working-directory'], ['session-projection', '@deepseek-ai/dsh-session-projection'], ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'], ['subprocess', '@deepseek-ai/dsh-subprocess-local'], diff --git a/apps/cli/tests/profiles/headless/tests/coding-task.e2e.ts b/apps/cli/tests/profiles/headless/tests/coding-task.e2e.ts index bb0b4297b8..531510393e 100644 --- a/apps/cli/tests/profiles/headless/tests/coding-task.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/coding-task.e2e.ts @@ -55,7 +55,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('coding task: fix a failing test expect(before.status).not.toBe(0) ctx = await codingHarness(workdir, { personaPrefix: SYSTEM_PROMPT }) - const agent = await ctx.agentLoop.create(SessionId('e2e-task'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const agent = await ctx.agentLoop.create(SessionId('e2e-task'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) agent.followup(createUserMessage({ content: [{ diff --git a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts index bf2d550bcc..b3e5cdb79e 100644 --- a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts @@ -49,7 +49,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa }, persistenceRoot: join(workdir, '.sessions'), }) - const agent = await ctx.agentLoop.create(SessionId('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const agent = await ctx.agentLoop.create(SessionId('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) // Completed read turns cannot collapse into one retained parallel tool group. for (let i = 1; i <= 4; i++) { diff --git a/apps/cli/tests/profiles/headless/tests/full-loop.e2e.ts b/apps/cli/tests/profiles/headless/tests/full-loop.e2e.ts index bbacf9dc15..c8051b05ea 100644 --- a/apps/cli/tests/profiles/headless/tests/full-loop.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/full-loop.e2e.ts @@ -29,7 +29,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('full loop: real model + real bas it('runs a bash command on request and reports its output', async () => { workdir = await mkdtemp(join(tmpdir(), 'dsh-full-loop-e2e-')) ctx = await codingHarness(workdir, { personaPrefix: SYSTEM_PROMPT }) - const agent = await ctx.agentLoop.create(SessionId('e2e-loop'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const agent = await ctx.agentLoop.create(SessionId('e2e-loop'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Run `echo e2e-ok` with the bash tool and tell me its exact output.' }], source: { kind: 'user' } })) await waitForIdle(ctx, agent) diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index c07b4b73fd..cf51dc23a6 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -66,6 +66,7 @@ export interface CodingHarnessOptions { export async function codingHarness(workdir: string, options: CodingHarnessOptions = {}): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx, { + workingDirectory: true, systemPrompt: { personaPrefix: options.personaPrefix ?? '' }, }) await ctx.plugin(AgentLoop, { agents: [] }) diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 48e8f9fc9f..bfea4af32a 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -3,15 +3,15 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import LlmRuntime, { createUserMessage, ToolCallId, HarnessError } from '@deepseek-ai/dsh-llm' +import { createUserMessage, ToolCallId, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' +import { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' -import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' @@ -55,12 +55,11 @@ afterEach(async () => { async function ptcModeHarness(cwd: string): Promise { const harness = new Context() - await harness.plugin(LlmRuntime) - await harness.plugin(SessionStore) - await harness.plugin(SessionProjectionRegistry) - await harness.plugin(SystemPrompt, { personaPrefix: PERSONA }) - await harness.plugin(ToolRuntime, { mode: 'ptc' }) - await harness.plugin(AgentRegistry) + await mountAgentLoopTestDependencies(harness, { + workingDirectory: true, + systemPrompt: { personaPrefix: PERSONA }, + tools: { mode: 'ptc' }, + }) await harness.plugin(AgentLoop, { agents: [] }) await harness.plugin(LlmDeepSeek) if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime) @@ -73,13 +72,12 @@ async function ptcModeHarness(cwd: string): Promise { async function workspacePtcModeHarness(): Promise { const harness = new Context() - await harness.plugin(LlmRuntime) - await harness.plugin(SessionStore) - await harness.plugin(SessionProjectionRegistry) - await harness.plugin(SystemPrompt, { personaPrefix: PERSONA }) - await harness.plugin(ToolRuntime, { mode: 'ptc' }) - await harness.plugin(AgentRegistry) await harness.plugin(LocalFileSystem, { cwd: '/' }) + await mountAgentLoopTestDependencies(harness, { + workingDirectory: true, + systemPrompt: { personaPrefix: PERSONA }, + tools: { mode: 'ptc' }, + }) await harness.plugin(ToolFs) await harness.plugin(AgentInstructions, { maxBytes: 65536 }) await harness.plugin(AgentLoop, { agents: [] }) @@ -131,8 +129,7 @@ async function mountRuntime(harness: Context): Promise { /** Keyless real-process harness for direct typed-binding acceptance tests. */ async function typedPtcModeHarness(): Promise { const harness = new Context() - await harness.plugin(SystemPrompt) - await harness.plugin(ToolRuntime, { mode: 'ptc' }) + await mountAgentLoopTestDependencies(harness, { workingDirectory: true, tools: { mode: 'ptc' } }) await mountRuntime(harness) return harness } @@ -298,6 +295,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { const agent = { id: SessionId('ptc-cordis'), session: ctx.sessions.create(SessionId('ptc-cordis'), { meta: { cwd: process.cwd() } }), + ctx, } as unknown as Agent const value = completion(await runCode(ctx, ` @@ -328,7 +326,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('PTC mode: real model writes a pr it('collapses the wire tool list to [run_code], bridges sub-calls, and returns curated output', async () => { workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-e2e-')) ctx = await ptcModeHarness(workdir) - const agent = await ctx.agentLoop.create(SessionId('e2e-ptc'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const agent = await ctx.agentLoop.create(SessionId('e2e-ptc'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) agent.followup(createUserMessage({ content: [{ diff --git a/apps/cli/tests/profiles/headless/tests/todo-write.e2e.ts b/apps/cli/tests/profiles/headless/tests/todo-write.e2e.ts index 4ff5fef99c..ce688b60bd 100644 --- a/apps/cli/tests/profiles/headless/tests/todo-write.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/todo-write.e2e.ts @@ -27,7 +27,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('todo_write: real model records a it('appends a todo/write event with the model-produced task list', async () => { workdir = await mkdtemp(join(tmpdir(), 'dsh-todo-write-e2e-')) ctx = await codingHarness(workdir, { personaPrefix: TODO_SYSTEM_PROMPT }) - const agent = await ctx.agentLoop.create(SessionId('e2e-todo'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const agent = await ctx.agentLoop.create(SessionId('e2e-todo'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) agent.followup(createUserMessage({ content: [{ type: 'text', text: diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 56dec2af4b..64c1c20ab3 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -303,6 +303,7 @@ describe('Python SDK dsh profile keyless smoke', () => { expect(tools.map(tool => tool.name)).toEqual([ process.platform === 'win32' ? 'pwsh' : 'bash', ...(editorEnabled ? ['str_replace_editor'] : []), + 'working_directory', ]) expect(modelRequests).toHaveLength(editorEnabled ? 3 : 1) if (editorEnabled) { diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 079aa6dbce..03f538d20d 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -208,11 +208,9 @@ beforeAll(async () => { }, 120_000) describe('the shipped Web composition', () => { - it('leaves the global tool layer empty', () => { - // Every model-facing tool belongs to a preset, `ask_user_question` - // included: a tool in the global layer reaches EVERY agent regardless of - // which preset composed it, expanding that preset's tool list. - expect(toolNames(ctx)).toEqual([]) + it('exposes only the directory tool in the global layer', () => { + // Directory selection is global; action tools belong to their Agent presets. + expect(toolNames(ctx)).toEqual(['working_directory']) }) it('keeps the token meter and its context-meter projections on the host plane', async () => { @@ -267,7 +265,7 @@ describe('the shipped Web composition', () => { 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', - 'workflow', 'write', + 'workflow', 'working_directory', 'write', ]) expect(ctx.commands.find(handle.agent, 'goal')).toBeDefined() } finally { @@ -319,7 +317,7 @@ describe('the shipped Web composition', () => { expect(assembly.sections).toEqual([ { name: 'deployment:persona-prefix', text: MINIMAL_PROMPT }, ]) - expect(assembly.tools.map(tool => tool.name)).toEqual(['bash']) + expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'working_directory']) expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION) expect(ctx.commands.find(handle.agent, 'goal')).toBeUndefined() // serviceFor reports preset-owned providers; unisolated consumers inherit the host fs. @@ -343,14 +341,14 @@ describe('the shipped Web composition', () => { setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), }) try { - expect(toolNames(ctx, minimal.agent)).toEqual(['bash']) + expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'working_directory']) expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) await minimal.dispose() // Tearing the minimal session down leaves the full one whole. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) - expect(toolNames(ctx)).toEqual([]) + expect(toolNames(ctx)).toEqual(['working_directory']) } finally { await full.dispose() } @@ -509,7 +507,7 @@ describe('the shipped Web composition', () => { // stays the preset's choice — minimal mounts no `tool-skill`, so its // tool table has no loader even though the global layer is readable. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(toolNames(ctx, handle.agent)).toEqual(['bash']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'working_directory']) } finally { await handle.dispose() } @@ -611,7 +609,7 @@ describe('product Bundle and user-preset intersection', () => { expect(tools).toEqual(expect.arrayContaining(['job_kill', 'job_list', 'job_output'])) for (const productTool of productTools) { expect(toolParameterNames(productCtx, handle.agent, productTool)).toEqual([ - 'description', 'prompt', 'run_in_background', + 'cwd', 'description', 'prompt', 'run_in_background', ]) } } finally { @@ -864,7 +862,7 @@ describe('the default preset as a user setting', () => { try { // `mount()` with no id resolves the effective default. One tool, not // `standard`'s catalog: the setting decided the composition. - expect(toolNames(ctx, handle.agent)).toEqual(['bash']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'working_directory']) } finally { await handle.dispose() } diff --git a/benchmarks/agent-continuation/child-catalog.worker.ts b/benchmarks/agent-continuation/child-catalog.worker.ts index 831a15c1b8..52e64fabf5 100644 --- a/benchmarks/agent-continuation/child-catalog.worker.ts +++ b/benchmarks/agent-continuation/child-catalog.worker.ts @@ -2,6 +2,7 @@ import { performance } from 'node:perf_hooks' import { Context } from '@deepseek-ai/cordis' +import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -74,6 +75,7 @@ async function run(root: string, mode: string): Promise { }) it('renders the deployment persona for an ACP-created agent', async () => { - harness = await makeBridgeHarness({ persona: 'Automation persona for {{model}} in {{cwd}}.', script: [textResponse('ok')] }) + harness = await makeBridgeHarness({ persona: 'Automation persona for {{model}}.', script: [textResponse('ok')] }) await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) const head = harness.adapter.requests[0]?.messages[0] expect(head?.role).toBe('system') - expect(head?.content).toContainEqual({ type: 'text', text: expect.stringContaining(`Automation persona for mock in ${process.cwd()}.`) as unknown }) + expect(head?.content).toContainEqual({ type: 'text', text: expect.stringContaining('Automation persona for mock.') as unknown }) }) it('requires one absolute primary workspace', async () => { diff --git a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts index dda3b50ed6..4194bdf4b0 100644 --- a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts +++ b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts @@ -33,6 +33,9 @@ describe('dsh-sdk-minimal bundle', () => { ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'], ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'], ['sandbox', '@deepseek-ai/dsh-sandbox-local'], + ['filesystem', '@deepseek-ai/dsh-fs-local'], + ['working-directory', '@deepseek-ai/dsh-working-directory'], + ['tool-working-directory', '@deepseek-ai/dsh-tool-working-directory'], ['session-projection', '@deepseek-ai/dsh-session-projection'], ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'], ['subprocess', '@deepseek-ai/dsh-subprocess-local'], diff --git a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx index 7bf61f7ff3..be0c8fbeeb 100644 --- a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx @@ -274,6 +274,20 @@ describe('produced-file Turn data', () => { expect(producedForClosing(deliverablesOf(value))).toEqual([]) }) + it('opens an explicit absolute mutation target when its recorded path is unusable', () => { + const path = '/project/child/report.txt' + const value = assembler([ + at(1, 'turn/start', { turn: 1 }), + call(2, 'absolute', 'write', { file_path: path, content: 'new' }), + result(3, 'absolute', false, 1, { path: null }), + ]) + const paths = producedForClosing(deliverablesOf(value)) + expect(paths).toEqual([path]) + const opened = vi.fn() + producedFileMentions(paths, opened, target => target).resolve('report.txt')?.open() + expect(opened).toHaveBeenCalledWith(path) + }) + it('folds successful first-party mutation paths from their raw arguments', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), diff --git a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx index 9a69938fff..ce1f5b957e 100644 --- a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx +++ b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx @@ -230,7 +230,7 @@ describe('run_code sub-calls through the real chat machinery', () => { it('a file sub-row click opens the file in the Sidebar; bash sub-rows open nothing', async () => { const parent = 'call-64' const subCalls = [ - subCall(11, parent, 1, 'read', { path: 'notes/demo.txt' }, 'ok'), + { ...subCall(11, parent, 1, 'read', { path: 'notes/demo.txt' }, 'ok'), meta: { path: '/w/notes/demo.txt' } }, subCall(12, parent, 2, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'), ] const b = await bench(snapshotWith([codeResult(10, parent)], subCalls)) diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index 149bbfc4ab..70a6a3569d 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -41,6 +41,7 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl try { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime, { mode: 'both' }) + ctx.provide('workingDirectory', { ensure: async () => process.cwd() }) await ctx.plugin(MemorySpillStore) await ctx.plugin(SpillPolicy, { maxInlineTokens }) if (nested) { diff --git a/packages/context/session-reference/package.json b/packages/context/session-reference/package.json index 33b036134d..9b8572ca85 100644 --- a/packages/context/session-reference/package.json +++ b/packages/context/session-reference/package.json @@ -94,6 +94,7 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-fs": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*" + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/context/session-reference/tests/fixtures/cordis.yml b/packages/context/session-reference/tests/fixtures/cordis.yml index 265a75940b..2be7c197bb 100644 --- a/packages/context/session-reference/tests/fixtures/cordis.yml +++ b/packages/context/session-reference/tests/fixtures/cordis.yml @@ -2,6 +2,8 @@ - name: '@deepseek-ai/dsh-system-prompt' - name: '@deepseek-ai/dsh-tools' - name: '@deepseek-ai/dsh-fs-local' +- name: '@deepseek-ai/dsh-session-projection' +- name: '@deepseek-ai/dsh-working-directory' - name: '@deepseek-ai/dsh-tool-fs' - name: '@deepseek-ai/dsh-session-query-sqlite' config: diff --git a/packages/context/session-reference/tests/loader-composition.spec.ts b/packages/context/session-reference/tests/loader-composition.spec.ts index c680e393ca..3c8cfa6e15 100644 --- a/packages/context/session-reference/tests/loader-composition.spec.ts +++ b/packages/context/session-reference/tests/loader-composition.spec.ts @@ -15,6 +15,8 @@ import * as toolsPlugin from '@deepseek-ai/dsh-tools' import * as fsPlugin from '@deepseek-ai/dsh-fs-local' import * as toolFsPlugin from '@deepseek-ai/dsh-tool-fs' import * as sessionPlugin from '@deepseek-ai/dsh-session' +import * as sessionProjectionPlugin from '@deepseek-ai/dsh-session-projection' +import * as workingDirectoryPlugin from '@deepseek-ai/dsh-working-directory' import { Session, SessionId } from '@deepseek-ai/dsh-session' import * as queryPlugin from '@deepseek-ai/dsh-session-query-sqlite' import * as referencePlugin from '@deepseek-ai/dsh-session-reference' @@ -45,6 +47,8 @@ describe('session-reference real Loader composition', () => { ctx.loader.builtins.include = Include const modules = new Map([ ['@deepseek-ai/dsh-session', sessionPlugin], + ['@deepseek-ai/dsh-session-projection', sessionProjectionPlugin], + ['@deepseek-ai/dsh-working-directory', workingDirectoryPlugin], ['@deepseek-ai/dsh-system-prompt', systemPromptPlugin], ['@deepseek-ai/dsh-tools', toolsPlugin], ['@deepseek-ai/dsh-fs-local', fsPlugin], diff --git a/packages/experimental/agent-team/tests/persistence.spec.ts b/packages/experimental/agent-team/tests/persistence.spec.ts index f7ee5d41cb..0b2aacf1b2 100644 --- a/packages/experimental/agent-team/tests/persistence.spec.ts +++ b/packages/experimental/agent-team/tests/persistence.spec.ts @@ -13,6 +13,7 @@ import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentService, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts' import TeamService, { TeamId, TeamMessageId } from '../src/index.ts' import type { TeamMailbox } from '../src/mailbox.ts' import { teamProjectionDefinition } from '../src/projection.ts' @@ -107,6 +108,7 @@ async function stack( const ctx = new Context() contexts.add(ctx) await mountAgentLoopTestDependencies(ctx) + await mountWorkingDirectoryFixture(ctx) await backend.mount(ctx, root) await ctx.plugin(TestSessionQuery) await ctx.plugin(AgentLoop, { agents: [] }) diff --git a/packages/experimental/agent-team/tests/team.spec.ts b/packages/experimental/agent-team/tests/team.spec.ts index af939b0108..08e0ea6d95 100644 --- a/packages/experimental/agent-team/tests/team.spec.ts +++ b/packages/experimental/agent-team/tests/team.spec.ts @@ -14,6 +14,7 @@ import { deliverSubagentPrompt, type HostPromptDeliverer } from '@deepseek-ai/ds import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts' import TeamService, { TeamError, TeamId, TeamMessageId, TeamTaskId } from '../src/index.ts' import { TeamRuntimeLifecycle } from '../src/lifecycle.ts' import { teamProjectionDefinition } from '../src/projection.ts' @@ -64,6 +65,7 @@ async function setup( const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) + await mountWorkingDirectoryFixture(ctx) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) @@ -172,6 +174,7 @@ describe('Team identity and provisioning', () => { const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) + await mountWorkingDirectoryFixture(ctx) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-direct-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) @@ -1352,6 +1355,7 @@ describe('Team mailbox and waiting', () => { const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) + await mountWorkingDirectoryFixture(ctx) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-wait-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) diff --git a/packages/experimental/auto-review/tests/auto-review.spec.ts b/packages/experimental/auto-review/tests/auto-review.spec.ts index 321f590add..0ea1b16cf0 100644 --- a/packages/experimental/auto-review/tests/auto-review.spec.ts +++ b/packages/experimental/auto-review/tests/auto-review.spec.ts @@ -1707,7 +1707,7 @@ describe('logged-fact failures', () => { expect(probe.runs()).toBe(0) expect(adapter.requests).toHaveLength(1) - expect(JSON.stringify(adapter.requests[0]?.messages)).toContain(process.cwd()) + expect(requestSections(adapter.requests[0]!).ENVIRONMENT).toEqual({ cwd: process.cwd() }) }) it('fails closed for missing, ambiguous, or conflicting PTC facts', async () => { diff --git a/packages/experimental/tool-agent-team/tests/tool-team.spec.ts b/packages/experimental/tool-agent-team/tests/tool-team.spec.ts index c1c98c19e2..ea3ba3430f 100644 --- a/packages/experimental/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/experimental/tool-agent-team/tests/tool-team.spec.ts @@ -21,6 +21,7 @@ import { resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek' import { serialize } from '@deepseek-ai/dsh-llm-deepseek/src/serialize.ts' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts' import TeamService from '../../agent-team/src/index.ts' import * as toolTeam from '../src/index.ts' @@ -67,6 +68,7 @@ async function setup(script: ConstructorParameters[0], legac const ctx = new Context() contexts.add(ctx) await mountAgentLoopTestDependencies(ctx) + await mountWorkingDirectoryFixture(ctx) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-tool-team-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index f31f224ebb..0404fde1fd 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -101,6 +101,7 @@ The tools are the executor; policy is an event gate. The tools inject no policy | [`src/read-render.ts`](src/read-render.ts) | Cordis-free windowing and envelope formatting | | [`src/sandbox.ts`](src/sandbox.ts) | Escalation API shared by `write`/`edit`: policy resolution and denial-marker mapping | | [`src/error.ts`](src/error.ts) | Stable model-facing diagnostics for guarded-mutation failures | +| [`src/mutation-result.ts`](src/mutation-result.ts) | Successful mutation observation and canonical result paths | ### Per-tool flow diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 82d8b07c34..8e6c1622b8 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -101,6 +101,7 @@ kind: "package-reference" | [`src/read-render.ts`](src/read-render.ts) | 不依赖 Cordis 的窗口构建与信封格式化 | | [`src/sandbox.ts`](src/sandbox.ts) | `write`/`edit` 共享的升权 API:策略解析与拒绝标记映射 | | [`src/error.ts`](src/error.ts) | 防护变更失败的稳定模型侧诊断 | +| [`src/mutation-result.ts`](src/mutation-result.ts) | 成功变更的观察记录与规范化结果路径 | ### 各工具流程 diff --git a/packages/fs/tool-fs/src/edit.ts b/packages/fs/tool-fs/src/edit.ts index 309d45a96b..2dd594a37d 100644 --- a/packages/fs/tool-fs/src/edit.ts +++ b/packages/fs/tool-fs/src/edit.ts @@ -11,6 +11,7 @@ import type { DiffCallView, DiffResultView, ToolResult } from '@deepseek-ai/dsh- import type {} from '@deepseek-ai/dsh-fs' import { computeHunkDiffs, diffsFromMeta } from './diff.ts' import { remediateFsError } from './error.ts' +import { mutationResult } from './mutation-result.ts' import { sessionResolveOptions } from './session-cwd.ts' import type { FsSandboxController } from './sandbox.ts' @@ -143,12 +144,7 @@ export function applyEditTool(ctx: Context, sandbox: FsSandboxController): void // stable model-facing diagnostic; anything else passes through. throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath) } - ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec) - return { - path: ctx.fs.processPath(target), - before: outcome.before, - after: outcome.after, - } + return mutationResult(ctx, target, outcome, exec) }, // Pure display: a diff card of the literal replacement (old_string → new_string), derived // from the call args. `oldText: old_string || null` matches claude-agent-acp's Edit arm; diff --git a/packages/fs/tool-fs/src/mutation-result.ts b/packages/fs/tool-fs/src/mutation-result.ts new file mode 100644 index 0000000000..a8a16d0301 --- /dev/null +++ b/packages/fs/tool-fs/src/mutation-result.ts @@ -0,0 +1,21 @@ +/** Shared observation and result fields for successful file mutations. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { FsTarget, FsVersion } from '@deepseek-ai/dsh-fs' +import type { ToolExecution } from '@deepseek-ai/dsh-tools' + +/** + * Record the new file version and expose the mutation result with its canonical path. + * @param ctx - filesystem and observation event owner. + * @param target - resolved file that was mutated. + * @param outcome - successful provider result; its version stays in the observation event. + * @param exec - calling tool execution. + * @returns the provider's result fields without the version, plus the canonical absolute path. + */ +export function mutationResult( + ctx: Context, target: FsTarget, outcome: T, exec: ToolExecution, +): Omit & { path: string } { + const { version, ...result } = outcome + ctx.emit('fs/observed', target, { kind: 'present', version }, exec) + return { path: ctx.fs.processPath(target), ...result } +} diff --git a/packages/fs/tool-fs/src/write.ts b/packages/fs/tool-fs/src/write.ts index bf81d7f00b..1068cd9644 100644 --- a/packages/fs/tool-fs/src/write.ts +++ b/packages/fs/tool-fs/src/write.ts @@ -12,6 +12,7 @@ import type { FsWriteOutcome } from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-fs' import { computeHunkDiffs, diffsFromMeta, pathFromMeta } from './diff.ts' import { remediateFsError } from './error.ts' +import { mutationResult } from './mutation-result.ts' import { sessionResolveOptions } from './session-cwd.ts' import type { FsSandboxController } from './sandbox.ts' @@ -127,13 +128,7 @@ export function applyWriteTool(ctx: Context, sandbox: FsSandboxController): void // stable model-facing diagnostic; anything else passes through. throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath) } - ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec) - return { - path: ctx.fs.processPath(target), - operation: outcome.operation, - before: outcome.before, - after: outcome.after, - } + return mutationResult(ctx, target, outcome, exec) }, // Pure display: a diff card. A call-time presenter has no access to prior // file content, so `oldText: null` also represents an overwrite here. diff --git a/packages/hooks/hook-protocol/README.md b/packages/hooks/hook-protocol/README.md index 90c199499c..b443839fd1 100644 --- a/packages/hooks/hook-protocol/README.md +++ b/packages/hooks/hook-protocol/README.md @@ -60,6 +60,8 @@ This section explains the design decisions behind the library and points at the ### Processing pipeline +`selectHookGroups` selects nonempty matching groups in config order. Each bridge resolves the current working directory only when this selection contains commands to run. `appendHookInvoked` omits absent or undefined matchers from the recorded event. + The library is a chain of single-purpose steps, one function each: validate the matcher pattern, run the command through the `dsh-shell` executor, decode the outcome, merge every matched hook's outcome into one most-restrictive result, and record the durable `hook/*` event pair. The matcher's `mode` parameter is the single axis the dialects differ on — `claude-code` interprets a pattern as literal alternatives or a regex, `codex` always as an unanchored regex. Every step degrades to a contained outcome instead of throwing, so a hook can never crash the calling turn: an invalid regex is a non-match, an executor rejection becomes a `HookOutput` with no exit code, exit 2 blocks with stderr as the reason, and every other failure stays non-blocking. Merging applies `deny > ask > allow` precedence, keeps the first `continue: false` stop sticky, and accumulates context in hook order. Detached runs are tracked so `fiber.dispose()` reaches quiescence. The steps live in [`src/matcher.ts`](src/matcher.ts), [`src/runner.ts`](src/runner.ts), [`src/codec.ts`](src/codec.ts), [`src/merge.ts`](src/merge.ts), [`src/events.ts`](src/events.ts), and [`src/detached.ts`](src/detached.ts). ### `hook/*` session events @@ -82,7 +84,7 @@ The [hook-protocol-lib Agent Note](../../../.agents/notes/archived/feature/2026- | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | Public exports of every primitive and event helper | -| [`src/matcher.ts`](src/matcher.ts) | Match-all sentinels, literal-vs-regex mode, validation and runtime matching | +| [`src/matcher.ts`](src/matcher.ts) | Matcher validation, dialect matching, and nonempty command-group selection | | [`src/runner.ts`](src/runner.ts) | `runHook` execution through `ctx.shell` and `DEFAULT_HOOK_TIMEOUT_MS` | | [`src/codec.ts`](src/codec.ts) | Exit-code and structured-stdout decoding into `HookOutput` | | [`src/merge.ts`](src/merge.ts) | Most-restrictive merge and the `MergedHookOutcome` type | diff --git a/packages/hooks/hook-protocol/README.zh.md b/packages/hooks/hook-protocol/README.zh.md index f4f22eb512..6a7a444b65 100644 --- a/packages/hooks/hook-protocol/README.zh.md +++ b/packages/hooks/hook-protocol/README.zh.md @@ -60,6 +60,8 @@ kind: "package-library" ### 处理流水线 +`selectHookGroups` 按配置顺序选出包含命令的匹配组。仅当所选组中有待运行的命令时,各桥接才解析当前工作目录。`appendHookInvoked` 不会将缺失或值为 undefined 的 matcher 写入事件。 + 本库是一串单一用途的步骤,每个步骤一个函数:校验 matcher pattern、通过 `dsh-shell` 执行器运行命令、解码结果、把每个匹配 hook 的结果合并为最严格的一个结果,并记录持久的 `hook/*` 事件对。matcher 的 `mode` 参数是两个方言唯一的差异轴——`claude-code` 把 pattern 解释为字面量备选或正则,`codex` 始终解释为未锚定正则。每个步骤都会降级为受控结果而不是抛异常,因此钩子永远不会使调用轮次崩溃:无效正则是运行时的不匹配,执行器拒绝会变成没有退出码的 `HookOutput`,退出码 2 以 stderr 作为原因阻塞,其他失败均不阻塞。合并应用 `deny > ask > allow` 优先级,保持首个 `continue: false` 停止的粘性,并按 hook 顺序累积上下文。脱离运行会被跟踪,因此 `fiber.dispose()` 能达到完全停稳。这些步骤位于 [`src/matcher.ts`](src/matcher.ts)、[`src/runner.ts`](src/runner.ts)、[`src/codec.ts`](src/codec.ts)、[`src/merge.ts`](src/merge.ts)、[`src/events.ts`](src/events.ts) 与 [`src/detached.ts`](src/detached.ts)。 ### `hook/*` 会话事件 @@ -82,7 +84,7 @@ kind: "package-library" | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | 每个原语与事件辅助函数的公开导出 | -| [`src/matcher.ts`](src/matcher.ts) | 匹配全部哨兵、字面量或正则模式、校验与运行时匹配 | +| [`src/matcher.ts`](src/matcher.ts) | matcher 校验、方言匹配,以及包含命令的匹配组选择 | | [`src/runner.ts`](src/runner.ts) | 通过 `ctx.shell` 的 `runHook` 执行与 `DEFAULT_HOOK_TIMEOUT_MS` | | [`src/codec.ts`](src/codec.ts) | 退出码与结构化 stdout 解码为 `HookOutput` | | [`src/merge.ts`](src/merge.ts) | 最严格合并与 `MergedHookOutcome` 类型 | diff --git a/packages/hooks/hook-protocol/src/events.ts b/packages/hooks/hook-protocol/src/events.ts index 3f1a827ecc..d7c93095e9 100644 --- a/packages/hooks/hook-protocol/src/events.ts +++ b/packages/hooks/hook-protocol/src/events.ts @@ -19,8 +19,8 @@ export interface HookInvocation { dialect: HookDialect /** A stable id correlating the invoked event with its result. */ handlerId: string - /** The matcher-group pattern that selected it (absent for match-all). */ - matcher?: string + /** The matcher-group pattern; absent or `undefined` is omitted from the event. */ + matcher?: string | undefined } /** The decided outcome half of the pair. */ @@ -70,7 +70,7 @@ export function summarizeStderr(stderr: string, maxChars: number): string | unde /** * Append a `hook/invoked` event naming the handler and hook point to `session`. * @param session - the session whose open turn records the event. - * @param invocation - the invocation identity; an absent `matcher` is omitted from the payload. + * @param invocation - the invocation identity; absent or `undefined` matchers are omitted from the payload. */ export function appendHookInvoked(session: Session, invocation: HookInvocation): void { session.append('hook/invoked', { diff --git a/packages/hooks/hook-protocol/src/index.ts b/packages/hooks/hook-protocol/src/index.ts index 68ea0b37dd..f36b86b44b 100644 --- a/packages/hooks/hook-protocol/src/index.ts +++ b/packages/hooks/hook-protocol/src/index.ts @@ -13,7 +13,7 @@ export type { MatcherGroup, MatcherMode, } from './types.ts' -export { matcherDiagnostic, matchesMatcher } from './matcher.ts' +export { matcherDiagnostic, matchesMatcher, selectHookGroups } from './matcher.ts' export { parseHookOutput } from './codec.ts' export { DEFAULT_HOOK_TIMEOUT_MS, runHook } from './runner.ts' export type { RunHookOptions, RunHookResult } from './runner.ts' diff --git a/packages/hooks/hook-protocol/src/matcher.ts b/packages/hooks/hook-protocol/src/matcher.ts index 3920474300..f27c695234 100644 --- a/packages/hooks/hook-protocol/src/matcher.ts +++ b/packages/hooks/hook-protocol/src/matcher.ts @@ -1,5 +1,5 @@ /** - * Matcher shared by both hook dialects. Claude treats alphanumeric/underscore/ + * Matching and command-group selection shared by both hook dialects. Claude treats alphanumeric/underscore/ * pipe patterns as literal alternatives and other patterns as regex; Codex * treats every non-empty pattern as an unanchored regex. Missing, empty, and * `*` match all. Runtime matching contains invalid regexes as non-matches; @@ -7,7 +7,7 @@ * @module @deepseek-ai/dsh-hook-protocol/matcher */ -import type { MatcherMode } from './types.ts' +import type { MatcherGroup, MatcherMode } from './types.ts' /** True for an absent / empty / `'*'` pattern — the match-all sentinels. */ function isMatchAll(matcher: string | undefined): boolean { @@ -63,3 +63,18 @@ export function matchesMatcher(matcher: string | undefined, query: string, mode: } return compileRegex(pattern)?.test(query) ?? false } + +/** + * Select configured groups that have command hooks and match the event subject. + * @param groups - groups for one hook point; absent points select no groups. + * @param query - the event's matcher subject. + * @param mode - dialect controlling literal or regex matching. + * @returns Selected groups in config order, retaining their original references. + */ +export function selectHookGroups( + groups: readonly MatcherGroup[] | undefined, + query: string, + mode: MatcherMode, +): MatcherGroup[] { + return (groups ?? []).filter(group => group.hooks.length > 0 && matchesMatcher(group.matcher, query, mode)) +} diff --git a/packages/hooks/hook-protocol/tests/events.spec.ts b/packages/hooks/hook-protocol/tests/events.spec.ts index 45aeca1050..b8c21b3190 100644 --- a/packages/hooks/hook-protocol/tests/events.spec.ts +++ b/packages/hooks/hook-protocol/tests/events.spec.ts @@ -21,14 +21,12 @@ describe('hook/* session events', () => { expect((ev as unknown as { surfaceOp?: unknown }).surfaceOp).toBeUndefined() }) - it('omits matcher when absent (match-all hook)', () => { + it.each([{}, { matcher: undefined }])('omits an absent or undefined matcher from the event (%j)', (matcher) => { const session = Session.create(SessionId('s')) - appendHookInvoked(session, { turn: 2, point: 'Stop', dialect: 'codex', handlerId: 'h2' }) + appendHookInvoked(session, { turn: 2, point: 'Stop', dialect: 'codex', handlerId: 'h2', ...matcher }) const ev = session.snapshotEvents().find(e => e.type === 'hook/invoked') - if (ev?.type === 'hook/invoked') { - expect('matcher' in ev.data).toBe(false) - } + expect(ev?.data).toEqual({ turn: 2, point: 'Stop', dialect: 'codex', handlerId: 'h2' }) }) it('appendHookResult derives decision/exitCode/stderrSummary from the output', () => { diff --git a/packages/hooks/hook-protocol/tests/matcher.spec.ts b/packages/hooks/hook-protocol/tests/matcher.spec.ts index a46e5b8507..39fae74d14 100644 --- a/packages/hooks/hook-protocol/tests/matcher.spec.ts +++ b/packages/hooks/hook-protocol/tests/matcher.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { matcherDiagnostic, matchesMatcher } from '@deepseek-ai/dsh-hook-protocol' +import { matcherDiagnostic, matchesMatcher, selectHookGroups, type MatcherGroup } from '@deepseek-ai/dsh-hook-protocol' describe('matchesMatcher — match-all sentinels (both dialects)', () => { for (const mode of ['claude-code', 'codex'] as const) { @@ -72,3 +72,32 @@ describe('matcherDiagnostic — parse-time diagnostics', () => { expect(matcherDiagnostic('[', 'codex')).toBe('invalid codex regex matcher "["') }) }) + +describe('selectHookGroups', () => { + it.each(['claude-code', 'codex'] as const)('%s: absent and empty hook points select no commands', (mode) => { + expect(selectHookGroups(undefined, 'Bash', mode)).toEqual([]) + expect(selectHookGroups([], 'Bash', mode)).toEqual([]) + }) + + it.each(['claude-code', 'codex'] as const)('%s: selects nonempty matching groups in config order', (mode) => { + const first: MatcherGroup = { matcher: '*', hooks: [{ command: 'first' }] } + const second: MatcherGroup = { matcher: '^Bash$', hooks: [{ command: 'second' }, { command: 'third' }] } + const groups: MatcherGroup[] = [ + { matcher: '*', hooks: [] }, + first, + { matcher: 'Read', hooks: [{ command: 'unmatched' }] }, + second, + ] + const selected = selectHookGroups(groups, 'Bash', mode) + expect(selected).toEqual([first, second]) + expect(selected[0]).toBe(first) + expect(selected[1]).toBe(second) + expect(groups).toHaveLength(4) + }) + + it('keeps Claude literal matching distinct from Codex regex matching', () => { + const group: MatcherGroup = { matcher: 'Bash', hooks: [{ command: 'matched' }] } + expect(selectHookGroups([group], 'BashOutput', 'claude-code')).toEqual([]) + expect(selectHookGroups([group], 'BashOutput', 'codex')).toEqual([group]) + }) +}) diff --git a/packages/hooks/hooks-claude-code/src/index.ts b/packages/hooks/hooks-claude-code/src/index.ts index 93a18c2b58..161e32b8d4 100644 --- a/packages/hooks/hooks-claude-code/src/index.ts +++ b/packages/hooks/hooks-claude-code/src/index.ts @@ -31,11 +31,10 @@ import { createDetachedRuns, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_STDERR_SUMMARY_MAX_CHARS, - matchesMatcher, mergeHookOutputs, runHook, + selectHookGroups, type HookOutput, - type MatcherGroup, type MergedHookOutcome, } from '@deepseek-ai/dsh-hook-protocol' // Pulls in the declaration-merged subagent events and the identity pairing their @@ -147,8 +146,7 @@ export function apply(ctx: Context, config: Config): void { payload: Record, opts: { agent?: Agent; turn?: number; readonly signal: AbortSignal }, ): Promise { - const groups: MatcherGroup[] = (parsed[point] ?? []).filter(group => - group.hooks.length > 0 && matchesMatcher(group.matcher, matchQuery, 'claude-code')) + const groups = selectHookGroups(parsed[point], matchQuery, 'claude-code') if (groups.length === 0) return mergeHookOutputs([]) const outputs: HookOutput[] = [] const workdir = opts.agent === undefined ? undefined : await ctx.workingDirectory.ensure(opts.agent, opts.signal) @@ -163,7 +161,7 @@ export function apply(ctx: Context, config: Config): void { if (session && opts.turn !== undefined) { appendHookInvoked(session, { turn: opts.turn, point, dialect: 'claude-code', handlerId, - ...group.matcher !== undefined ? { matcher: group.matcher } : {}, + matcher: group.matcher, }) } const { output, durationMs } = await runHook(ctx.shell, hook, { diff --git a/packages/hooks/hooks-codex/src/index.ts b/packages/hooks/hooks-codex/src/index.ts index 66d833ad61..8dc76fef58 100644 --- a/packages/hooks/hooks-codex/src/index.ts +++ b/packages/hooks/hooks-codex/src/index.ts @@ -34,11 +34,10 @@ import { createDetachedRuns, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_STDERR_SUMMARY_MAX_CHARS, - matchesMatcher, mergeHookOutputs, runHook, + selectHookGroups, type HookOutput, - type MatcherGroup, type MergedHookOutcome, } from '@deepseek-ai/dsh-hook-protocol' import { parseCodexConfig, type CodexHookConfig } from './config.ts' @@ -128,8 +127,7 @@ export function apply(ctx: Context, config: Config): void { plainStdoutAsContext?: boolean }, ): Promise { - const groups: MatcherGroup[] = (parsed[point] ?? []).filter(group => - group.hooks.length > 0 && matchesMatcher(group.matcher, matchQuery, 'codex')) + const groups = selectHookGroups(parsed[point], matchQuery, 'codex') if (groups.length === 0) return mergeHookOutputs([]) const outputs: HookOutput[] = [] const workdir = opts.agent === undefined ? undefined : await ctx.workingDirectory.ensure(opts.agent, opts.signal) @@ -140,7 +138,7 @@ export function apply(ctx: Context, config: Config): void { if (session && opts.turn !== undefined) { appendHookInvoked(session, { turn: opts.turn, point, dialect: 'codex', handlerId, - ...group.matcher !== undefined ? { matcher: group.matcher } : {}, + matcher: group.matcher, }) } const { output, durationMs } = await runHook(ctx.shell, hook, { diff --git a/packages/plan/plan-mode/package.json b/packages/plan/plan-mode/package.json index 5038618a48..d6b6bc8f4b 100644 --- a/packages/plan/plan-mode/package.json +++ b/packages/plan/plan-mode/package.json @@ -66,6 +66,7 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*" } } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 112144c893..01309dd5d6 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { RUN_CODE_NAME, defineContentToolFixture } from '@deepseek-ai/dsh-tools' @@ -946,6 +947,7 @@ describe('exit_plan_mode', () => { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime, { mode: 'ptc' }) await ctx.plugin(ExitRuntime) + provideWorkingDirectoryFixture(ctx) await mountProjectionSeam(ctx) await ctx.plugin(PlanModeController, PLAN_CONFIG) await ctx.plugin(AgentRegistry) diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index 4edf4d87f3..c5cdf0f4f4 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -121,6 +121,11 @@ describe('HarnessSdkJsonRpcServer', () => { const transport = new FakeTransport() const server = new HarnessSdkJsonRpcServer(ctx, transport) try { + await expect(server.handleRequest('session/working-directory/get', { sessionId: 'a' })) + .rejects.toThrow('SDK server is not initialized') + await expect(server.handleRequest('session/working-directory/set', { sessionId: 'a', path: child })) + .rejects.toThrow('SDK server is not initialized') + expect(ctx.agents.list()).toEqual([]) await server.initialize({ cwd: root, provider: 'mock', model: 'mock' }) await expect(server.handleRequest('session/working-directory/get', { sessionId: 'a' })).resolves.toEqual({ cwd: root }) const selected = await realpath(child) @@ -131,7 +136,8 @@ describe('HarnessSdkJsonRpcServer', () => { await server.prompt({ sessionId: 'a', contentBlocks: [{ type: 'text', text: 'where' }] }) await agent.whenIdle() expect(agent.session.snapshotEvents().some(event => event.type === 'user/message' - && JSON.stringify(event.data.content).includes(selected))).toBe(true) + && event.data.content.some(block => block.type === 'text' + && block.text.includes(JSON.stringify(selected))))).toBe(true) await expect(server.handleRequest('session/working-directory/get', {})).rejects.toThrow('sessionId') await expect(server.handleRequest('session/working-directory/set', { sessionId: 'a', path: 3 })).rejects.toThrow('path string') } finally { diff --git a/packages/shell/tool-pwsh/tests/loader.spec.ts b/packages/shell/tool-pwsh/tests/loader.spec.ts index b9e998209b..9c13a97999 100644 --- a/packages/shell/tool-pwsh/tests/loader.spec.ts +++ b/packages/shell/tool-pwsh/tests/loader.spec.ts @@ -59,10 +59,10 @@ describe.skipIf(!hasPwsh)('tool-pwsh through a real Loader composition', () => { inspect: async (cwd) => { report = JSON.parse(await readFile(join(cwd, 'pwsh-loader-report.json'), 'utf8')) as PwshLoaderReport const expectedCwd = await realpath(cwd) - expect(report.foregroundCwd).toBe(expectedCwd) - expect(report.foregroundMeta).toEqual({ cwd: expectedCwd }) - expect(report.backgroundCwd).toBe(expectedCwd) - expect(report.backgroundMeta).toEqual({ cwd: expectedCwd }) + expect(await realpath(report.foregroundCwd)).toBe(expectedCwd) + expect(report.foregroundMeta).toEqual({ cwd: report.foregroundCwd }) + expect(await realpath(report.backgroundCwd)).toBe(expectedCwd) + expect(report.backgroundMeta).toEqual({ cwd: report.backgroundCwd }) }, }) expect(stderr).not.toContain('UNHANDLED') diff --git a/packages/spill/spill-policy/package.json b/packages/spill/spill-policy/package.json index cdff577c87..7cc70cea00 100644 --- a/packages/spill/spill-policy/package.json +++ b/packages/spill/spill-policy/package.json @@ -68,6 +68,7 @@ "@deepseek-ai/dsh-ptc-runtime": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", "@deepseek-ai/dsh-tool-fs": "workspace:*", - "sharp": "^0.35.3" + "sharp": "^0.35.3", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*" } } diff --git a/packages/spill/spill-policy/tests/spill-policy.spec.ts b/packages/spill/spill-policy/tests/spill-policy.spec.ts index 5b69856578..a3bfc70012 100644 --- a/packages/spill/spill-policy/tests/spill-policy.spec.ts +++ b/packages/spill/spill-policy/tests/spill-policy.spec.ts @@ -11,6 +11,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' +import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import { estimateContent } from '@deepseek-ai/dsh-token-meter/estimate' import type { ContentBlock } from '@deepseek-ai/dsh-llm' @@ -39,6 +40,7 @@ declare module '@deepseek-ai/dsh-llm' { async function mountRuntime(ctx: Context, config: NodeRuntimeConfig = {}): Promise { onTestFinished(async () => { await ctx.fiber.dispose() }) if (!ctx.get('sessions')) await ctx.plugin(SessionStore) + provideWorkingDirectoryFixture(ctx) if (!ctx.get('fs')) await ctx.plugin(FileSystem) if (!ctx.get('subprocess')) await ctx.plugin(Subprocess) if (!ctx.get('sandbox')) await ctx.plugin(Sandbox, {}) diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index dd12256cfa..d2dddcbbe2 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { PassThrough, type Readable } from 'node:stream' import { fileURLToPath } from 'node:url' -import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Agent } from '@deepseek-ai/dsh-agent' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -641,6 +641,14 @@ describe('dsh-subagent-acp', () => { parent, signal: controller.signal, })).rejects.toThrow('This operation was aborted') + const spawn = vi.spyOn(ctx.subprocess, 'spawn') + expect(() => ctx.subagents.getProvider('acp')!.start({ + ...request('p', controller.signal), + cwd: process.cwd(), + descriptor: snapshotSubagentDescriptor({ mode: 'one-shot', provider: 'acp', label: 'cancelled startup' }), + })).toThrow('subagent request was aborted before the ACP child started') + expect(spawn).not.toHaveBeenCalled() + await ctx.fiber.dispose() }) it('reports an initialize-stage process exit without copying the transport error', async () => { diff --git a/packages/subagent/subagent-claude-code/package.json b/packages/subagent/subagent-claude-code/package.json index 3fefa37f45..272e26b274 100644 --- a/packages/subagent/subagent-claude-code/package.json +++ b/packages/subagent/subagent-claude-code/package.json @@ -65,6 +65,7 @@ "@deepseek-ai/dsh-timeout": "workspace:*", "@deepseek-ai/dsh-tool-jobs": "workspace:*", "@deepseek-ai/dsh-tool-subagent": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*" } } diff --git a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts index c9d0aa613c..ae5bb39d8e 100644 --- a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts @@ -91,22 +91,22 @@ describe('product-provider public Loader composition', () => { tools: [ { name: 'subagent_codex', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, { name: 'subagent_claude_code', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, { name: 'subagent_claude_primary', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, { name: 'subagent_claude_secondary', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, ], diff --git a/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts b/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts index eab7445ea5..ff3a36732b 100644 --- a/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts +++ b/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts @@ -12,9 +12,9 @@ import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import SubagentRuntime from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { SessionId } from '@deepseek-ai/dsh-session' import type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as claudeCode from '../src/index.ts' @@ -105,7 +105,8 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)( } const ctx = new Context() contexts.push(ctx) - await ctx.plugin(SessionProjectionRegistry) + await mountAgentLoopTestDependencies(ctx, { workingDirectory: true }) + const harness = await mountAgentLoopTestHarness(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(LocalSubprocessRuntime) const handles: SubprocessHandle[] = [] @@ -126,10 +127,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)( expect(version.stdout.trim()).toBe('2.1.263 (Claude Code)') const nonce = `DSH_CLAUDE_DEEPSEEK_${randomUUID()}` - const parent = { - id: 'deepseek-e2e-parent', - session: { header: { cwd: workspace } }, - } as unknown as Agent + const parent = await harness.create(SessionId('deepseek-e2e-parent'), {}, { cwd: workspace }) const run = await ctx.subagents.start('claude-code', { prompt: [{ type: 'text', diff --git a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts index e70a85b664..5cac3a35e0 100644 --- a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts +++ b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts @@ -25,7 +25,7 @@ import { } from 'vitest' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { SubprocessHandle, @@ -649,7 +649,7 @@ describe('task admission and package contracts', () => { expect.any(Error), ) expect(errorCause(warn.mock.calls[0]?.[1] as unknown)?.message) - .toContain('relative/SECRET_TOKEN') + .toContain(resolve('relative/SECRET_TOKEN')) const invalidCwdAbort = new AbortController() invalidCwdAbort.abort(new Error('cancel invalid cwd startup')) @@ -657,6 +657,11 @@ describe('task admission and package contracts', () => { ...request(undefined, invalidCwdAbort.signal), parent: invalidCwdParent, })).rejects.toThrow('cancel invalid cwd startup') + await expect(ctx.subagents.getProvider('claude-diagnostic')!.start({ + ...request(undefined, invalidCwdAbort.signal), + cwd: resolve('relative/SECRET_TOKEN'), + descriptor: snapshotSubagentDescriptor({ mode: 'one-shot', provider: 'claude-diagnostic', label: 'cancelled startup' }), + })).rejects.toThrow('request was aborted before SDK startup') expect(queryMock).not.toHaveBeenCalled() warn.mockClear() diff --git a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts index 533ce2aa0a..5ab658beb9 100644 --- a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts @@ -80,17 +80,17 @@ describe('Codex provider public Loader composition', () => { tools: [ { name: 'subagent_codex', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, { name: 'subagent_codex_primary', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, { name: 'subagent_codex_secondary', - parameterNames: ['description', 'prompt', 'run_in_background'], + parameterNames: ['cwd', 'description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, ], diff --git a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts index a0cbc3e793..58b229653b 100644 --- a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts +++ b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts @@ -9,7 +9,7 @@ import * as yaml from 'js-yaml' import { describe, expect, it, vi } from 'vitest' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { @@ -2142,7 +2142,7 @@ describe('run lifecycle and quiescence', () => { expect(invalidCwdError.message).not.toContain('relative/SECRET_TOKEN') expect(invalidCwdError.cause).toBeInstanceOf(Error) expect((invalidCwdError.cause as Error).message) - .toContain('relative/SECRET_TOKEN') + .toContain(resolve('relative/SECRET_TOKEN')) expect(spawn).not.toHaveBeenCalled() const invalidCwdAbort = new AbortController() @@ -2152,6 +2152,11 @@ describe('run lifecycle and quiescence', () => { parent: invalidCwdParent, signal: invalidCwdAbort.signal, })).rejects.toThrow('cancel invalid cwd startup') + expect(() => ctx.subagents.getProvider('codex-diagnostic')!.start({ + ...request(undefined, invalidCwdAbort.signal), + cwd: resolve('relative/SECRET_TOKEN'), + descriptor: snapshotSubagentDescriptor({ mode: 'one-shot', provider: 'codex-diagnostic', label: 'cancelled startup' }), + })).toThrow('request was aborted before app-server startup') expect(spawn).not.toHaveBeenCalled() const starting = ctx.subagents.start('codex-diagnostic', { diff --git a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts index 46c750b252..dd45dace98 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts @@ -13,7 +13,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, relative } from 'node:path' import { fileURLToPath } from 'node:url' -import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import { @@ -697,9 +697,37 @@ describe('dsh-subagent-dsh-sdk provider', () => { parent, signal: controller.signal, })).rejects.toThrow('This operation was aborted') + expect(() => ctx.subagents.getProvider('dsh-sdk')!.start({ + ...request('p', controller.signal), + cwd: process.cwd(), + descriptor: snapshotSubagentDescriptor({ mode: 'one-shot', provider: 'dsh-sdk', label: 'cancelled startup' }), + })).toThrow('subagent request was aborted before the SDK child started') + expect(createdHarnessOptions).toEqual([]) await ctx.fiber.dispose() }) + it('rejects a child directory removed after resolution without starting a runtime', async () => { + const cwd = mkdtempSync(join(tmpdir(), 'subagent-dsh-sdk-removed-cwd-')) + const ctx = await setup() + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + try { + const resolved = { + ...request(), + cwd, + descriptor: snapshotSubagentDescriptor({ mode: 'one-shot', provider: 'dsh-sdk', label: 'removed directory' }), + } + rmSync(cwd, { recursive: true }) + expect(() => ctx.subagents.getProvider('dsh-sdk')!.start(resolved)) + .toThrow(expectedFailure('stage: initialize; category: configuration')) + expect(createdHarnessOptions).toEqual([]) + expect(warn).toHaveBeenCalledWith('subagent-dsh-sdk "dsh-sdk": child start failed: %o', expect.any(Error)) + } finally { + warn.mockRestore() + await ctx.fiber.dispose() + rmSync(cwd, { recursive: true, force: true }) + } + }) + it('rejects after reaping when the child dies before the handshake', async () => { const rawStderr = 'scripted boot failure at /private/path SECRET_TOKEN' const ctx = await setup({ FAKE_EXIT_BEFORE_INIT: '1', FAKE_STDERR: rawStderr }) diff --git a/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts b/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts index 17ca0b1dbc..e970b37cd5 100644 --- a/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts @@ -380,6 +380,26 @@ describe('startInProcessRun', () => { expect(ctx.sessions.list()).toHaveLength(beforeSessions) }) + it('rolls back child creation when its context has no directory service', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(AgentLoop, { agents: [] }) + const adapter = new MockAdapter([]) + ctx.llm.registerAdapter(['mock'], adapter) + const parent = await ctx.agentLoop.create(SessionId('parent-without-directory-service'), { provider: 'mock', model: 'mock' }) + const beforeAgents = ctx.agents.list().length + const beforeSessions = ctx.sessions.list().length + try { + await expect(startInProcessRun(request(parent), {})) + .rejects.toThrow('in-process subagents require the working-directory service') + expect(ctx.agents.list()).toHaveLength(beforeAgents) + expect(ctx.sessions.list()).toHaveLength(beforeSessions) + expect(adapter.requests).toEqual([]) + } finally { + await ctx.fiber.dispose() + } + }) + it('treats abort after factory publication as a cancelled run with an id', async () => { const { ctx, parent } = await setup([]) const controller = new AbortController() diff --git a/packages/subagent/subagent-spawn-in-process/tests/harness.ts b/packages/subagent/subagent-spawn-in-process/tests/harness.ts index b5a7d9dbda..276b564760 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/harness.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/harness.ts @@ -1,4 +1,3 @@ -import { mountWorkingDirectoryFixture } from '../../subagent/tests/working-directory-fixture.ts' import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' @@ -26,6 +25,7 @@ export async function spawnHarness(workdir: string): Promise { // delegation nudge lives in the e2e's user prompt and the subagent tool's // own description. await mountAgentLoopTestDependencies(ctx, { + workingDirectory: true, systemPrompt: { personaPrefix: 'You are a coding agent. Report only when the requested work is done.' }, }) await ctx.plugin(AgentLoop, { agents: [] }) @@ -34,7 +34,6 @@ export async function spawnHarness(workdir: string): Promise { await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, { cwd: workdir, timeoutMs: 30_000 }) await ctx.plugin(ToolBash) - await mountWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(Spawn, { providerName: 'spawn' }) // The model-facing subagent tool, bound to the spawn backend. diff --git a/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts b/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts index 3e764070f7..1ff111c89f 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts @@ -23,7 +23,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('spawn backend with-key smoke', ( it('a parent delegates to a child that writes a file on disk', async () => { workdir = await mkdtemp(join(tmpdir(), 'dsh-subagent-spawn-e2e-')) ctx = await spawnHarness(workdir) - const parent = await ctx.agentLoop.create(SessionId('e2e-parent'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + const parent = await ctx.agentLoop.create(SessionId('e2e-parent'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) parent.followup(createUserMessage({ content: [{ type: 'text', text: diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index 2b258a723b..ec1631420a 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -63,12 +63,12 @@ describe('subagent working directories', () => { await run.dispose() }) - it('retains an explicit relative directory when a continuable child cold-resumes', async () => { + it.each(['relative', 'absolute'])('retains an explicit %s directory when a continuable child cold-resumes', async (form) => { const { ctx, parent, origin, first, second } = await fixture() const selected = await realpath(second) const started = await ctx.subagents.startContinuable({ provider: 'spawn', label: 'directory child', - request: { parent, cwd: 'second', prompt: [{ type: 'text', text: 'child' }] }, + request: { parent, cwd: form === 'absolute' ? second : 'second', prompt: [{ type: 'text', text: 'child' }] }, signal: new AbortController().signal, }) await vi.waitFor(() => { expect(ctx.agents.get(started.childId)).toBeUndefined() }) @@ -82,4 +82,26 @@ describe('subagent working directories', () => { const last = observed.events.findLast(event => event.type === 'working-directory/change') expect(last?.data).toMatchObject({ cwd: selected }) }) + + it('rolls back a continuable child whose setup realm has no directory service', async () => { + const { ctx, parent, second } = await fixture() + const childId = SessionId('missing-directory-service') + const create = ctx.agents.create.bind(ctx.agents) + const creation = vi.spyOn(ctx.agents, 'create').mockImplementation(options => create({ + ...options, + setup: (childCtx, child) => options.setup?.(childCtx.isolate('workingDirectory'), child), + })) + try { + await expect(ctx.subagents.startContinuable({ + provider: 'spawn', label: 'unavailable directory service', childId, + request: { parent, cwd: second, prompt: [{ type: 'text', text: 'child' }] }, + signal: new AbortController().signal, + })).rejects.toThrow('continuable subagents require the working-directory service') + + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(parent.session.snapshotEvents().filter(event => event.type === 'subagent/catalog')).toEqual([]) + } finally { + creation.mockRestore() + } + }) }) diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index d0b6b8c677..96e081f9f4 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -90,6 +90,27 @@ describe('dsh-tool-subagent', () => { expect(text(result)).toBe('child says hi') }) + it('resolves an explicit child directory without changing the parent directory', async () => { + let childCwd: string | undefined + const ctx = await setup({ provider: 'mock' }, { + onStart: (request) => { childCwd = request.cwd }, + }) + const parent = fakeAgent() + const parentCwd = ctx.workingDirectory.get(parent.session) + try { + const result = await callSubagent(ctx, { + description: 'inspect packages', + prompt: 'list the packages', + cwd: 'packages', + }, { agent: parent }) + expect(result.isError).toBe(false) + expect(childCwd).toBe(path.resolve(parentCwd, 'packages')) + expect(ctx.workingDirectory.get(parent.session)).toBe(parentCwd) + } finally { + await ctx.fiber.dispose() + } + }) + it('omits run_in_background entirely when the instance disables it (schema and capability never disagree)', async () => { const ctx = await setup({ provider: 'mock', enableRunInBackground: false }) const schema = ctx.tools.schemas().find(s => s.name === 'subagent') diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index f4235aad18..932912b4e4 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' +import { mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' +import FsLocal from '@deepseek-ai/dsh-fs-local' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' @@ -36,6 +40,23 @@ describe('dsh-agent-loop-testkit', () => { await ctx.fiber.dispose() }) + it('keeps an existing filesystem when enabling working directories', async () => { + const root = await mkdtemp(join(tmpdir(), 'testkit-filesystem-')) + const ctx = new Context() + try { + await ctx.plugin(FsLocal, { cwd: root }) + await mountAgentLoopTestDependencies(ctx, { workingDirectory: true }) + const harness = await mountAgentLoopTestHarness(ctx) + const agent = await harness.create(SessionId('existing-filesystem'), {}, { cwd: root }) + + expect(ctx.fs.processPath(await ctx.fs.resolve('.'))).toBe(await realpath(root)) + await expect(ctx.workingDirectory.ensure(agent)).resolves.toBe(root) + } finally { + await ctx.fiber.dispose() + await rm(root, { recursive: true, force: true }) + } + }) + it('provides a mutable in-memory Inbox stub for structural Agent tests', () => { const inbox = createInboxStub() const firstTurn = message('first turn') diff --git a/packages/workflow/workflow-ptc/tests/built-runtime.e2e.ts b/packages/workflow/workflow-ptc/tests/built-runtime.e2e.ts index a8d61df445..31bc8b83f6 100644 --- a/packages/workflow/workflow-ptc/tests/built-runtime.e2e.ts +++ b/packages/workflow/workflow-ptc/tests/built-runtime.e2e.ts @@ -32,7 +32,7 @@ import { Context } from '@deepseek-ai/cordis' import PtcWorkflowEngine from '@deepseek-ai/dsh-workflow-ptc' const ctx = new Context() try { - for (const name of ['session', 'session-projection', 'fs-local', 'subprocess-local', 'sandbox-local']) { + for (const name of ['session', 'session-projection', 'system-prompt', 'fs-local', 'working-directory', 'subprocess-local', 'sandbox-local']) { await ctx.plugin((await import('@deepseek-ai/dsh-' + name)).default, {}) } await ctx.plugin((await import('@deepseek-ai/dsh-sandbox-policy')).default, { mode: 'read-only', workspaceRoot: process.argv[2] }) @@ -59,7 +59,7 @@ try { args: { outside: process.argv[3] }, meta: { name: 'built-smoke', description: 'built workflow runtime' }, subagentProvider: 'built-selected', - parent: { id: session.id, session, options: {} }, + parent: { id: session.id, session, options: {}, ctx }, }) try { const result = await run.result diff --git a/python/sdk/tests/test_smoke_model.py b/python/sdk/tests/test_smoke_model.py index c8f6613315..7dd706fb5d 100644 --- a/python/sdk/tests/test_smoke_model.py +++ b/python/sdk/tests/test_smoke_model.py @@ -259,6 +259,22 @@ def test_mock_model_serves_native_messages_events() -> None: assert next(event["delta"]["text"] for event in events if event["type"] == "content_block_delta") == SMOKE["EXPECTED_TEXT"] +@pytest.mark.parametrize("directory", ["/fixture/workspace", r"C:\fixture\workspace"]) +def test_minimal_snapshot_pins_quoted_working_directory(directory: str) -> None: + context = f"Current working directory: {json.dumps(directory)}." + other = json.dumps(r"C:\another\directory") + files = SMOKE["build_minimal_snapshot_files"]([{ + "system": [], + "tools": [], + "messages": [{"role": "user", "content": [{"type": "text", "text": context + "\n" + other}]}], + }], Path(directory)) + message = json.loads(files["model-visible.json"])[0]["messages"][0] + assert message == { + "role": "user", + "content": [{"type": "text", "text": 'Current working directory: "{{cwd}}".\n' + other}], + } + + def test_advanced_snapshot_normalizes_catalog_child_creation_time() -> None: value = { "type": "subagent/catalog", diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 65fd85a8b3..0eaa3cbf53 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -2328,10 +2328,18 @@ def minimal_snapshot_message(message: object, cwd: Path) -> dict[str, object]: raise AssertionError(f"minimal model request has an unexpected message role: {message}") +def snapshot_directory_replacements(directory: Path, token: str) -> list[tuple[str, str]]: + """Pin the allocated fixture path in plain fields and JSON-quoted context text.""" + path = str(directory) + return [(json.dumps(path, ensure_ascii=False)[1:-1], token), (path, token)] + + def minimal_snapshot_text(value: object, cwd: Path) -> object: """Replace the scenario's temporary working directory everywhere it appears.""" if isinstance(value, str): - return value.replace(str(cwd), "{{cwd}}") + for actual, token in snapshot_directory_replacements(cwd, "{{cwd}}"): + value = value.replace(actual, token) + return value if isinstance(value, list): return [minimal_snapshot_text(item, cwd) for item in value] if isinstance(value, dict): @@ -2346,7 +2354,7 @@ def build_snapshot_files( cwd: Path, ) -> dict[str, str]: """Render the SDK result and three persisted logs into stable expected outputs.""" - replacements = [(str(cwd), "{{cwd}}"), (SNAPSHOT_SESSION_ID, "{{parent}}")] + replacements = snapshot_directory_replacements(cwd, "{{cwd}}") + [(SNAPSHOT_SESSION_ID, "{{parent}}")] replacements.append((snapshot_workflow_run_id(result), "{{workflow-run}}")) for index, child_id in enumerate(child_ids, start=1): replacements.append((child_id, f"{{{{child-{index}}}}}")) @@ -2418,8 +2426,8 @@ def build_restart_snapshot_files( ) -> dict[str, str]: """Render two SDK processes, isolated model histories, and durable logs.""" replacements = [ - (str(sessions), "{{sessions}}"), - (str(cwd), "{{cwd}}"), + *snapshot_directory_replacements(sessions, "{{sessions}}"), + *snapshot_directory_replacements(cwd, "{{cwd}}"), (RESTART_FIRST_SESSION_ID, "{{session-1}}"), (RESTART_SECOND_SESSION_ID, "{{session-2}}"), ]