From 9f6884ae18a518d6e156cebea592a9ee02520070 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:28:11 +0800 Subject: [PATCH 1/6] fix(publication): teach batching guidance on the first tool result --- docs/CHANGELOG.md | 3 + src/ptc/batching-guidance.ts | 2 + src/publication/ptc.ts | 76 +++++++++-------- test/prompt-ephemeral-teaching.test.mjs | 109 ++++++++++++++++++++++++ test/resident-switch.test.mjs | 42 ++++++--- 5 files changed, 183 insertions(+), 49 deletions(-) create mode 100644 test/prompt-ephemeral-teaching.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d66194e1..60c46475 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -15,6 +15,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Replace the `global.forceDefaultOpsPtc` switch with one explicit action: the row's detail page carries a **Make OPS (PTC) the default** button that writes `selectedDefault: ops-ptc` once and answers `applied`/`no-update`/`unavailable`/`failed`. Apply, remount and unload no longer write the default, so a preset chosen on the settings page is not overridden on the next apply, and a saved `global.forceDefaultOpsPtc` key still loads with no effect. - 用一次显式操作取代 `global.forceDefaultOpsPtc` 开关:行详情页有一个「设为 OPS (PTC) 默认」按钮,点一次写 `selectedDefault: ops-ptc`,并回报 `applied`/`no-update`/`unavailable`/`failed`。apply、重挂载与卸载都不再改写默认,设置页选定的预设不会在下一次 apply 被覆盖;已保存的 `global.forceDefaultOpsPtc` 键仍可加载但不再生效。 +- The batching lesson no longer rides the accepted user batch: a user-role lesson enters logged history, where the model reads it as fresh input and answers the lesson instead of the task, feeding its own loop (#929). The one-time full lesson now rides the first accepted root `run_code` tool result through `additionalContexts` — the same-step ephemeral inbox the host never logs as user history — under contributor `batching-guidance:lesson`, distinct from the per-violation notices that keep the base id. The lesson latches at the delivery point inside the post-execute decision, so the previous `session/event` `user/message` latch, which waited for durable history that no longer happens, is gone. +- 批量教学不再挂在被接受的 user batch 上:user 角色的教学会进入 logged history,模型把它当新输入去回应教学本身而不是任务,形成自持循环(#929)。一次性完整教学现在随第一个被接受的根 `run_code` 工具结果走 `additionalContexts`——宿主从不记为 user history 的同一步 ephemeral 通道——contributor 为 `batching-guidance:lesson`,与保持原 id 的逐违规提示区分。教学在 post-execute 决策内的投递点就地置位,原先等待 durable history 的 `session/event` `user/message` latch 随该 history 不再发生而移除。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/src/ptc/batching-guidance.ts b/src/ptc/batching-guidance.ts index ed237e6d..c0ec3db0 100644 --- a/src/ptc/batching-guidance.ts +++ b/src/ptc/batching-guidance.ts @@ -14,6 +14,8 @@ import { literalShellFileWork } from './shell-file-work.js' /** Identity of the guidance in the host message source. */ export const BATCHING_GUIDANCE_ID = 'batching-guidance' +/** Contributor of the one-time full lesson; the per-violation notices keep the base id. */ +export const BATCHING_GUIDANCE_LESSON_ID = `${BATCHING_GUIDANCE_ID}:lesson` /** Revision of the guidance text; bump it when the wording or the file format changes. */ export const BATCHING_GUIDANCE_REVISION = '4' diff --git a/src/publication/ptc.ts b/src/publication/ptc.ts index f9167c8e..3cfa46af 100644 --- a/src/publication/ptc.ts +++ b/src/publication/ptc.ts @@ -13,13 +13,12 @@ import { renderSdkDirectory } from '../projections/ptc/directory.js' import { PTC_RESIDENT_TOOLS } from '../ptc/config.js' import type { ApiName } from '../ptc/config.js' import { ownPtcScopes } from '../ptc/ownership.js' -import { BATCHING_GUIDANCE_ID, BATCHING_GUIDANCE_REVISION, createProgramLatch, loadBatchingGuidance } from '../ptc/batching-guidance.js' +import { BATCHING_GUIDANCE_ID, BATCHING_GUIDANCE_LESSON_ID, BATCHING_GUIDANCE_REVISION, createProgramLatch, loadBatchingGuidance } from '../ptc/batching-guidance.js' import { InvocationLifetime, InvocationNotStarted } from '../lifecycle/invocations.js' import { monitoredInvoke } from '../execution/monitored.js' import { record } from '../execution/boundary.js' import { failure, resolveWorker } from '../execution/jobs.js' import { WORKER_TIMEOUT_MS } from '../execution/protocol.js' -import { registerStepTailProvider } from '../prompt-injection/index.js' import { mountWorkspacePreparation } from '../workspace-preparation.js' import { mountResultLifecycle } from '../kernel/result-lifecycle.js' import { activationIsPtc, inspectPresentation, isPresentationProbe } from './presentation.js' @@ -100,11 +99,13 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al // One latch for the program-shape trigger. It observes the root run_code program, // which is the only place the whole step is visible. const shapeLatch = createProgramLatch() - const guidanceMessage = async (turn: number, text: string): Promise => { + // The one-time lesson and the per-violation notices share a revision; the + // contributor suffix lets listeners tell the full lesson from a notice. + const guidanceMessage = async (turn: number, text: string, contributor: string = BATCHING_GUIDANCE_ID): Promise => { const createUserMessage = await loadUserMessage() return createUserMessage({ - source: { kind: 'dsh-ops:step-tail', contributor: BATCHING_GUIDANCE_ID, revision: BATCHING_GUIDANCE_REVISION, turn, step: 0 }, - content: [{ type: 'text', text: `[Plugin context from ${JSON.stringify(BATCHING_GUIDANCE_ID)}; not a user instruction or authorization.]\n${text}` }], + source: { kind: 'dsh-ops:step-tail', contributor, revision: BATCHING_GUIDANCE_REVISION, turn, step: 0 }, + content: [{ type: 'text', text: `[Plugin context from ${JSON.stringify(contributor)}; not a user instruction or authorization.]\n${text}` }], }) } @@ -180,20 +181,6 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al if (payload.agent === agent) shapeLatch.noteTurn(agent, payload.turn) return next() })) - // Teach the rules once, before the model's first request: a step-tail - // message rides the first accepted user batch and enters history. - // The provider must not latch here. A batch can still be withdrawn before - // admission (cancellation, rejection), and latching on the return value - // would then skip the lesson for the whole session without a trace. - entry.disposers.push(registerStepTailProvider(entry.ctx, agent, { - id: BATCHING_GUIDANCE_ID, - revision: BATCHING_GUIDANCE_REVISION, - provide() { - if (entry.taught) return undefined - const text = loadBatchingGuidance() - return text.length > 0 ? text : undefined - }, - })) // The program-shape trigger observes the ROOT run_code call: only there is // the whole program text visible. Nested tools.ops_* calls carry a parent // token, and their arguments say nothing about the shape of the step. @@ -203,22 +190,40 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al if (exec.agent !== agent || exec.name !== 'run_code' || exec.parent !== undefined) return decision if (exec.signal.aborted) return decision const code = (exec.arguments as { code?: unknown } | undefined)?.code - const notice = shapeLatch.observe(agent, code) - if (notice === undefined) return decision + // Teach the rules once, riding the first accepted root run_code result: + // additionalContexts is the same-step ephemeral inbox, never logged + // history, so a lesson can never read as fresh user input and the + // model's answer cannot loop on its own guidance (#929). The latch is + // set at the delivery point: a post-execute decision that returns is + // the tool result the host renders, with no later admission step that + // could still withdraw it. + const contexts = [...(decision.additionalContexts ?? [])] try { - const message = await guidanceMessage(notice.turn, notice.text) - // Observation only: one line, no context, no new dependency. - if (gate.telemetry === true) { - const counts = shapeLatch.stats(agent) - ctx.logger.info('dsh-ops batching: turn=' + notice.turn + ' category=' + notice.category - + ' plan=' + counts.plan + ' bypass=' + counts.bypass + ' shape=' + counts.shape + ' total=' + counts.total) + if (!entry.taught) { + const text = loadBatchingGuidance() + if (text.length > 0) { + contexts.push(await guidanceMessage(shapeLatch.stats(agent).turn, text, BATCHING_GUIDANCE_LESSON_ID)) + entry.taught = true + } + } + const notice = shapeLatch.observe(agent, code) + if (notice !== undefined) { + const message = await guidanceMessage(notice.turn, notice.text) + // Observation only: one line, no context, no new dependency. + if (gate.telemetry === true) { + const counts = shapeLatch.stats(agent) + ctx.logger.info('dsh-ops batching: turn=' + notice.turn + ' category=' + notice.category + + ' plan=' + counts.plan + ' bypass=' + counts.bypass + ' shape=' + counts.shape + ' total=' + counts.total) + } + contexts.push(message) } // Append only: the tool result keeps its own value, content and contexts. - return { ...decision, additionalContexts: [...(decision.additionalContexts ?? []), message] } + return contexts.length > 0 ? { ...decision, additionalContexts: contexts } : decision } catch (error) { - // A delivery failure is an optimisation loss, never a tool failure. + // A delivery failure is an optimisation loss, never a tool failure: + // contexts already collected still ride this result. ctx.logger.warn('dsh-ops: batching notice delivery failed: ' + String(error)) - return decision + return contexts.length > 0 ? { ...decision, additionalContexts: contexts } : decision } })) } @@ -305,13 +310,10 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al ctx.on('session/event', (session, event) => { if ((event as { type: string }).type === 'agent-preset/selected') { refresh(); return } for (const [agent, entry] of entries) if (agent.session === session) { - // The lesson counts as taught only once it is durable history: the step-tail - // snapshot can be withdrawn before admission, and a cancelled request must - // leave the next accepted batch free to teach it again. - if (event.type === 'user/message') { - const source = (event as { data?: { source?: { kind?: string; contributor?: string } } }).data?.source - if (source?.kind === 'dsh-ops:step-tail' && source.contributor === BATCHING_GUIDANCE_ID) entry.taught = true - } else if (event.type === 'step/end') { + // The batching lesson no longer latches on user/message events: it rides + // the first accepted root run_code tool result, whose returned decision is + // the delivery point itself, so there is no admission step to wait for. + if (event.type === 'step/end') { for (const api of entry.pending) if (permitted(agent, api)) entry.selected.add(api) entry.pending.clear() rotateFiles(entry) diff --git a/test/prompt-ephemeral-teaching.test.mjs b/test/prompt-ephemeral-teaching.test.mjs new file mode 100644 index 00000000..5246460e --- /dev/null +++ b/test/prompt-ephemeral-teaching.test.mjs @@ -0,0 +1,109 @@ +/** + * The batching lesson rides a tool result, never the user batch (#929). + * + * The step-tail channel appends UserMessages to an accepted user batch, which + * the host logs as durable history: a lesson that arrives there reads as fresh + * user input, and the model answers the lesson instead of the task, looping on + * its own guidance. These checks pin the replacement contract: the user batch + * carries no guidance at all, the first accepted root `run_code` result carries + * the full lesson exactly once through the same-step ephemeral inbox + * (`additionalContexts`), and nothing re-enters the user batch afterwards. + */ +import { createScope, scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import FileSystem from '@deepseek-ai/dsh-fs-local' +import NodePtc from '@deepseek-ai/dsh-ptc-runtime-node' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { apply } from '../lib/index.js' +import { publicToolName } from '../lib/policy.js' +import { bootHost, shutdown } from './lib/host.mjs' +import { prepareStep, executeCall, selectExecutor } from './lib/executor.mjs' +import { assert, test, report, waitFor, withTempDir } from './lib/harness.mjs' +import { WORKER, requireWorker } from './lib/boundary.mjs' + +requireWorker('prompt-ephemeral-teaching') +let sequence = 0 + +const names = (ctx, agent) => ctx.get('tools').definitions(agent, agent.prepared?.toolSet).map(tool => tool.name).sort() + +async function scoped(parent, key, parentKey) { + let result + await parent.plugin({ inject: ['tools'], apply: inner => { + result = createScope(inner, key, parentKey ? { parent: parentKey } : undefined).ctx + } }) + return result +} + +/** The same merged-row fixture resident-switch uses, restricted to the ops-ptc row. */ +async function setup(cwd) { + const { ctx } = await bootHost({ withWorkingDirectory: true }) + await ctx.plugin(Subprocess); await ctx.plugin(Sandbox); await ctx.plugin(FileSystem); await ctx.plugin(NodePtc) + ctx.provide('sandboxPolicy', { resolve: ({ session } = {}) => ({ mode: session?.mode ?? 'danger-full-access', workspaceRoot: cwd, sessionId: session?.id }) }) + const presets = new Map(), agents = [] + ctx.provide('agents', { list: () => [...agents] }) + ctx.provide('agentPresets', { composedPreset: inner => presets.get(scopeParentOf(scopeOf(inner))) }) + const config = { global: {}, discovery: { binaryPath: WORKER, required: true } } + for (const id of ['minimal', 'standard', 'ptc', 'ops-ptc', 'cordis']) config[id] = { enabled: id === 'ops-ptc', + binaryPath: WORKER, required: true, ...(id === 'ops-ptc' ? { residentTools: true, dynamicTools: true, batchingGuidance: true, alwaysLoaded: ['stat'], allowedTools: ['stat'] } : {}) } + await ctx.plugin({ name: 'prompt-ephemeral-teaching-fixture', apply: inner => apply(inner, config) }) + const id = 'ephemeral-' + ++sequence, preset = await scoped(ctx, { preset: id }) + presets.set(scopeOf(preset), 'ops-ptc') + const agent = { id, session: { id, mode: 'danger-full-access', header: { cwd }, append() {}, read() { return [] } } } + agent.ctx = await scoped(preset, agent, scopeOf(preset)) + await agent.ctx.plugin({ inject: ['tools', 'systemPrompt'], apply: inner => { selectExecutor(inner, 'ptc') } }) + agents.push(agent) + await ctx.serial('agent/created', { agent }) + agent.prepared = await prepareStep(ctx, agent) + return { ctx, agent } +} + +/** Drive the real agent pre-step waterfall once, exactly as the host loop does. */ +const drivePreStep = async (agent, turn) => { + const accepted = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'Start the task.' }] }) + return agent.ctx.waterfall('agent/pre-step', { + agent, messages: [accepted], turn, step: 1, signal: new AbortController().signal, + modelSelection: { provider: 'fixture', model: 'capture' }, + }, async () => ({ kind: 'enter', messages: [accepted] })) +} + +/** The one-time full lesson the first accepted root result carries. */ +const guidedContexts = result => (result.additionalContexts ?? []).filter(context => context.source?.kind === 'dsh-ops:step-tail' && context.source?.contributor === 'batching-guidance:lesson') + +/** A compliant root program: plan line, two dispatches under Promise.all, no bypass. */ +const compliantProgram = '// plan: two checks\nconst [a, b] = await Promise.all([tools.ops_stat({ path: "x" }), tools.ops_stat({ path: "y" })])\nreturn [a.status, b.status]' + +const rootCall = (ctx, agent, callId) => executeCall(ctx, { agent, toolSet: agent.prepared.toolSet, name: 'run_code', + arguments: { description: 'Compliant fixture', code: compliantProgram }, callId, signal: new AbortController().signal }) + +await test('the user batch carries no batching guidance, before or after the lesson', () => withTempDir('ephemeral-pre', async cwd => { + const { ctx, agent } = await setup(cwd) + try { + await waitFor(() => names(ctx, agent).includes(publicToolName('stat'))) + const first = await drivePreStep(agent, 1) + const before = first.messages.filter(message => message.source?.kind === 'dsh-ops:step-tail') + assert.equal(before.length, 0, 'a user-role lesson reads as fresh user input and the model answers it (#929)') + const run = await rootCall(ctx, agent, 'ephemeral-teach-1') + assert.equal(run.isError, false, JSON.stringify(run)) + const after = (await drivePreStep(agent, 2)).messages.filter(message => message.source?.kind === 'dsh-ops:step-tail') + assert.equal(after.length, 0, 'nothing re-enters the user batch once the lesson is delivered') + } finally { await shutdown(ctx) } +})) + +await test('the first accepted root run_code result carries the full lesson exactly once', () => withTempDir('ephemeral-once', async cwd => { + const { ctx, agent } = await setup(cwd) + try { + await waitFor(() => names(ctx, agent).includes(publicToolName('stat'))) + const first = await rootCall(ctx, agent, 'ephemeral-teach-2') + assert.equal(first.isError, false, JSON.stringify(first)) + const taught = guidedContexts(first) + assert.equal(taught.length, 1, JSON.stringify(first.additionalContexts)) + assert.match(JSON.stringify(taught), /Batch tool calls/) + assert.match(JSON.stringify(taught), /not a user instruction or authorization/) + const second = await rootCall(ctx, agent, 'ephemeral-teach-3') + assert.equal(second.isError, false, JSON.stringify(second)) + assert.equal(guidedContexts(second).length, 0, 'the lesson is spent after its one delivery') + } finally { await shutdown(ctx) } +})) + +report('prompt-ephemeral-teaching') diff --git a/test/resident-switch.test.mjs b/test/resident-switch.test.mjs index 68945394..3981e418 100644 --- a/test/resident-switch.test.mjs +++ b/test/resident-switch.test.mjs @@ -184,31 +184,48 @@ const drivePreStep = async (agent, turn) => { /** Plugin-authored contexts appended to the accepted user batch. */ const stepTailMessages = decision => decision.messages.filter(message => message.source?.kind === 'dsh-ops:step-tail') -await test('ops-ptc batchingGuidance teaches until the lesson is committed to history', () => withTempDir('batching-teach', async cwd => { +/** The one-time full lesson, told from a per-violation notice by its contributor suffix. */ +const lesson = context => context.source?.kind === 'dsh-ops:step-tail' && context.source?.contributor === 'batching-guidance:lesson' + +await test('ops-ptc batchingGuidance teaches once on the first run_code result, never in the user batch', () => withTempDir('batching-teach', async cwd => { const { ctx, agent } = await setup(cwd, 'ops-ptc', { residentTools: true, dynamicTools: true, batchingGuidance: true, alwaysLoaded: ['stat'], allowedTools: ['stat'] }) try { await waitFor(() => names(ctx, agent).includes(publicToolName('stat'))) - const first = stepTailMessages(await drivePreStep(agent, 1)) + // A user-role lesson reads as fresh user input, and the model answers the + // lesson instead of the task (#929): the user batch stays free of guidance. + assert.equal(stepTailMessages(await drivePreStep(agent, 1)).length, 0) + // The lesson rides the first accepted root run_code tool result through the + // same-step ephemeral inbox, which the host never logs as user history. + const taught = async callId => { + const run = await executeCall(ctx, { agent, toolSet: agent.prepared.toolSet, name: 'run_code', + arguments: { description: 'Compliant fixture', code: '// plan: two checks\nconst [a, b] = await Promise.all([tools.ops_stat({ path: "x" }), tools.ops_stat({ path: "y" })])\nreturn [a.status, b.status]' }, + callId, signal: new AbortController().signal }) + assert.equal(run.isError, false, JSON.stringify(run)) + return (run.additionalContexts ?? []).filter(context => context.source?.kind === 'dsh-ops:step-tail' && context.source?.contributor === 'batching-guidance:lesson') + } + const first = await taught('batching-teach-1') assert.equal(first.length, 1, JSON.stringify(first)) - assert.equal(first[0].source.contributor, 'batching-guidance') assert.match(JSON.stringify(first), /Batch tool calls/) assert.match(JSON.stringify(first), /not a user instruction or authorization/) - // The pre-step decision is not the commit point: a batch withdrawn before - // admission never becomes history, so the lesson must be offered again. - assert.equal(stepTailMessages(await drivePreStep(agent, 2)).length, 1, 'an uncommitted lesson is offered again') - // Once the host reports the durable message, the lesson is spent for the session. - await ctx.serial('session/event', agent.session, { type: 'user/message', data: { source: first[0].source } }) - assert.equal(stepTailMessages(await drivePreStep(agent, 3)).length, 0, 'a committed lesson is never repeated') + // Teach once: a second root call never repeats the lesson. + assert.equal((await taught('batching-teach-2')).length, 0, 'the lesson is spent after its one delivery') + // Nothing re-enters the user batch once the lesson is delivered. + assert.equal(stepTailMessages(await drivePreStep(agent, 2)).length, 0) } finally { await shutdown(ctx) } })) -await test('ops-ptc without batchingGuidance teaches nothing on the first turn', () => withTempDir('batching-teach-off', async cwd => { +await test('ops-ptc without batchingGuidance teaches nothing at all', () => withTempDir('batching-teach-off', async cwd => { const { ctx, agent } = await setup(cwd, 'ops-ptc', { residentTools: true, dynamicTools: false, batchingGuidance: false, alwaysLoaded: ['stat'], allowedTools: ['stat'] }) try { await waitFor(() => names(ctx, agent).includes(publicToolName('stat'))) assert.equal(stepTailMessages(await drivePreStep(agent, 1)).length, 0) + const run = await executeCall(ctx, { agent, toolSet: agent.prepared.toolSet, name: 'run_code', + arguments: { description: 'Thin fixture', code: 'const r = await tools.ops_stat({ path: "a" })\nreturn r.status' }, + callId: 'batching-off-teach', signal: new AbortController().signal }) + assert.equal(run.isError, false, JSON.stringify(run)) + assert.equal((run.additionalContexts ?? []).length, 0, 'switch off: no listener, therefore no lesson and no notice') } finally { await shutdown(ctx) } })) @@ -224,12 +241,13 @@ await test('the root run_code trigger answers on its own tool result', () => wit // A compliant program earns nothing, which is what keeps the notice meaningful. const good = await run('// plan: stat one path; stat another\nconst [a, b] = await Promise.all([tools.ops_stat({ path: "a" }), tools.ops_stat({ path: "b" })])\nreturn { a, b }') assert.equal(good.isError, false, JSON.stringify(good)) - assert.equal(contexts(good).length, 0, 'a compliant program earns no notice') + assert.equal(contexts(good).filter(context => !lesson(context)).length, 0, 'a compliant program earns no notice') + assert.equal(contexts(good).filter(lesson).length, 1, 'the one-time lesson rides the first root result') // No plan line: the plan category speaks, and it says only that the comment is missing. const thin = await run('const r = await tools.ops_stat({ path: "a" })\nreturn r.status') assert.equal(thin.isError, false, JSON.stringify(thin)) assert.match(text(thin), /did not open with a plan line/, 'the plan notice rides the root result') - assert.doesNotMatch(text(thin), /Promise\.all/, 'the plan notice stays about the comment') + assert.doesNotMatch(JSON.stringify(contexts(thin).filter(context => !lesson(context))), /Promise\.all/, 'the plan notice stays about the comment') // A shell listing is a bypass; the notice names the API that replaces it. const bypass = await run('const r = await tools.ops_bash({ description: "list", command: "ls -la" })\nreturn r.stdout.text') assert.match(text(bypass), /ops_glob/, 'the bypass notice names the listing tool') From f3032dbe429ee7b9a6fe39aee8937bcfa4157fc4 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:33:32 +0800 Subject: [PATCH 2/6] fix(niubash): align the face list with winuxcmd applets --- docs/CHANGELOG.md | 3 ++ src/niubash/faces.ts | 11 +++-- src/niubash/runtime.ts | 10 ++++ test/niubash-faces-consistency.test.mjs | 65 +++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 test/niubash-faces-consistency.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 60c46475..d5db692d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -18,6 +18,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - The batching lesson no longer rides the accepted user batch: a user-role lesson enters logged history, where the model reads it as fresh input and answers the lesson instead of the task, feeding its own loop (#929). The one-time full lesson now rides the first accepted root `run_code` tool result through `additionalContexts` — the same-step ephemeral inbox the host never logs as user history — under contributor `batching-guidance:lesson`, distinct from the per-violation notices that keep the base id. The lesson latches at the delivery point inside the post-execute decision, so the previous `session/event` `user/message` latch, which waited for durable history that no longer happens, is gone. - 批量教学不再挂在被接受的 user batch 上:user 角色的教学会进入 logged history,模型把它当新输入去回应教学本身而不是任务,形成自持循环(#929)。一次性完整教学现在随第一个被接受的根 `run_code` 工具结果走 `additionalContexts`——宿主从不记为 user history 的同一步 ephemeral 通道——contributor 为 `batching-guidance:lesson`,与保持原 id 的逐违规提示区分。教学在 post-execute 决策内的投递点就地置位,原先等待 durable history 的 `session/event` `user/message` latch 随该 history 不再发生而移除。 +- The Niubash face list no longer names applets the frozen winuxcmd answers with "command not found" (measured: jq, link): a generated argv0 stub for those shadowed the system command with an entry that could not run it (#966). A prepared cache that still carries a face the list no longer declares is judged damaged and rebuilt from the pinned source, so a stale stub cannot survive a cache reuse. +- Niubash face 清单不再包含冻结 winuxcmd 以 "command not found" 回应的 applet(实测:jq、link):为它们生成的 argv0 桩会以一个无法运行的入口遮蔽系统命令(#966)。已 prepared 的缓存若仍携带清单不再声明的 face,会被判损坏并从固定源重建,旧桩无法在缓存复用中存活。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/src/niubash/faces.ts b/src/niubash/faces.ts index 413338b9..e637f467 100644 --- a/src/niubash/faces.ts +++ b/src/niubash/faces.ts @@ -1,8 +1,11 @@ -/** Exact fallback command family from official Niubash v1.5.0 - * winuxcmd/usr/bin/activate-winuxcmd.sh (compiled inventory verifies that script). - * argv0 dispatch is upstream's own activation contract; bash/sh keep their original Niubash shims. +/** Command family the frozen Niubash winuxcmd actually implements (#966). + * + * Derived from upstream's activate-winuxcmd.sh, minus the applets the frozen + * multi-call binary answers with "command not found" (measured: jq, link): a + * generated argv0 stub for those would only shadow the system command with an + * entry that cannot run it. bash/sh keep their original Niubash shims. */ -export const NIUBASH_FACES: readonly string[] = Object.freeze(["arch", "b2sum", "base32", "base64", "basename", "basenc", "cal", "cat", "chcon", "chgrp", "chmod", "chown", "chroot", "cksum", "clear", "cmp", "col", "column", "comm", "cp", "cpio", "csplit", "cut", "cygpath", "d2u", "date", "dd", "df", "diff", "diff3", "dirname", "dir", "dircolors", "dos2unix", "du", "echo", "env", "expand", "expr", "factor", "false", "file", "find", "fmt", "fold", "free", "getconf", "grep", "groups", "head", "hexdump", "hmac256", "hostid", "hostname", "id", "infocmp", "install", "join", "jq", "kill", "less", "link", "ln", "locale", "logname", "ls", "lsof", "man", "md5sum", "mkdir", "mkfifo", "mknod", "mktemp", "more", "mpicalc", "mv", "nice", "nl", "nohup", "nproc", "numfmt", "od", "paste", "patch", "pathchk", "pinky", "pr", "printenv", "printf", "ps", "ptx", "pwd", "readlink", "realpath", "reset", "rev", "rm", "rmdir", "runcon", "sdiff", "sed", "seq", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum", "shred", "shuf", "sleep", "sort", "split", "stat", "stdbuf", "strings", "stty", "sum", "sync", "tac", "tail", "tee", "test", "[", "tic", "timeout", "toe", "top", "touch", "tput", "tr", "tree", "true", "truncate", "tsort", "tty", "tzset", "u2d", "uname", "unexpand", "uniq", "unix2dos", "unlink", "uptime", "users", "vdir", "watch", "wc", "which", "who", "whoami", "xargs", "xxd", "yes"]) +export const NIUBASH_FACES: readonly string[] = Object.freeze(["arch", "b2sum", "base32", "base64", "basename", "basenc", "cal", "cat", "chcon", "chgrp", "chmod", "chown", "chroot", "cksum", "clear", "cmp", "col", "column", "comm", "cp", "cpio", "csplit", "cut", "cygpath", "d2u", "date", "dd", "df", "diff", "diff3", "dirname", "dir", "dircolors", "dos2unix", "du", "echo", "env", "expand", "expr", "factor", "false", "file", "find", "fmt", "fold", "free", "getconf", "grep", "groups", "head", "hexdump", "hmac256", "hostid", "hostname", "id", "infocmp", "install", "join", "kill", "less", "ln", "locale", "logname", "ls", "lsof", "man", "md5sum", "mkdir", "mkfifo", "mknod", "mktemp", "more", "mpicalc", "mv", "nice", "nl", "nohup", "nproc", "numfmt", "od", "paste", "patch", "pathchk", "pinky", "pr", "printenv", "printf", "ps", "ptx", "pwd", "readlink", "realpath", "reset", "rev", "rm", "rmdir", "runcon", "sdiff", "sed", "seq", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum", "shred", "shuf", "sleep", "sort", "split", "stat", "stdbuf", "strings", "stty", "sum", "sync", "tac", "tail", "tee", "test", "[", "tic", "timeout", "toe", "top", "touch", "tput", "tr", "tree", "true", "truncate", "tsort", "tty", "tzset", "u2d", "uname", "unexpand", "uniq", "unix2dos", "unlink", "uptime", "users", "vdir", "watch", "wc", "which", "who", "whoami", "xargs", "xxd", "yes"]) /** The multi-call binary every face dispatches to. */ export const NIUBASH_WINUXCMD = 'winuxcmd/usr/bin/winuxcmd.exe' /** Payload-relative path of one argv0 face. */ diff --git a/src/niubash/runtime.ts b/src/niubash/runtime.ts index 7e8a96e7..a343b433 100644 --- a/src/niubash/runtime.ts +++ b/src/niubash/runtime.ts @@ -42,6 +42,16 @@ const WINUXCMD_SIZE: number = (NIUBASH_PIN.sizes as Readonly { + // Measured against the frozen payload: winuxcmd answers "command not found" + // with exit 127 for these, so their argv0 stubs only shadow the system tools. + assert.equal(NIUBASH_FACES.includes('jq'), false, 'winuxcmd reports command not found: jq; the stub shadows a real system jq') + assert.equal(NIUBASH_FACES.includes('link'), false, 'winuxcmd reports command not found: link') +}) + +/** Live-probe base: the staged frozen tree, or the gate-provided fixture. */ +const staged = path.join(PACKAGE_ROOT, 'runtime', 'win32-x64', 'niubash') +const base = process.env.DSH_OPS_TEST_NIUBASH ? path.dirname(process.env.DSH_OPS_TEST_NIUBASH) : staged +const winuxcmd = path.join(base, 'winuxcmd', 'usr', 'bin', 'winuxcmd.exe') +const live = process.platform === 'win32' && fs.existsSync(winuxcmd) + +await test('every generated face dispatches inside winuxcmd, not to command-not-found', () => { + if (!live) { + console.log(' note: no staged winuxcmd on this host; the live probe needs the frozen payload') + return + } + const generated = NIUBASH_FACES.map(niubashFacePath).filter(name => !Object.hasOwn(NIUBASH_PIN.files, name)) + const missing = [] + for (const name of generated) { + const face = path.basename(name, '.exe') + const probe = spawnSync(winuxcmd, [face], + { timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }) + if (probe.status === 127) missing.push(face) + } + assert.deepEqual(missing, [], 'each generated face must be a real winuxcmd applet') +}) + +await test('a prepared cache carrying a stale face is retired and rebuilt, not reused', () => withTempDir('faces-cache-upgrade', async root => { + if (!live) { + console.log(' note: no staged payload on this host; the cache-upgrade probe needs the frozen tree') + return + } + const { prepareNiubashVersion } = await import('../lib/niubash/runtime.js') + const source = base + const target = path.join(root, 'prepared') + await prepareNiubashVersion(source, target) + const staleFace = path.join(target, 'winuxcmd', 'usr', 'bin', 'jq.exe') + const winuxcmdCopy = path.join(target, 'winuxcmd', 'usr', 'bin', 'winuxcmd.exe') + // Simulate a cache written by a face list that still declared jq (#966). + fs.copyFileSync(winuxcmdCopy, staleFace) + // Reuse must not bless the stale stub: it shadows the system jq. + await prepareNiubashVersion(source, target) + assert.equal(fs.existsSync(staleFace), false, 'a face the list no longer declares must not survive a cache reuse') +})) + +report('niubash-faces-consistency') From f0843dce2e089a35a0b2ed4cb38bc365c777781f Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:45:45 +0800 Subject: [PATCH 3/6] fix(integration): refuse an older host at activation with one named diagnosis (#701) An older host used to load anyway and fail later: TypeError scope errors backstage, EXECUTOR_UNAVAILABLE in front. The floor is read from the package manifest (engines.dsh), never a copy, and an unknown host version loads as before because it cannot be proven below the floor. Red/green evidence: test-results/red/host-floor-revert-red.txt, test-results/green-host-floor/. --- docs/CHANGELOG.md | 3 + src/adapter/dsh/host-floor.ts | 97 ++++++++++++++++++++++++++++ src/index.ts | 6 ++ test/integration-host-floor.test.mjs | 74 +++++++++++++++++++++ 4 files changed, 180 insertions(+) create mode 100644 src/adapter/dsh/host-floor.ts create mode 100644 test/integration-host-floor.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d5db692d..d3a99ea8 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -21,6 +21,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - The Niubash face list no longer names applets the frozen winuxcmd answers with "command not found" (measured: jq, link): a generated argv0 stub for those shadowed the system command with an entry that could not run it (#966). A prepared cache that still carries a face the list no longer declares is judged damaged and rebuilt from the pinned source, so a stale stub cannot survive a cache reuse. - Niubash face 清单不再包含冻结 winuxcmd 以 "command not found" 回应的 applet(实测:jq、link):为它们生成的 argv0 桩会以一个无法运行的入口遮蔽系统命令(#966)。已 prepared 的缓存若仍携带清单不再声明的 face,会被判损坏并从固定源重建,旧桩无法在缓存复用中存活。 +- Activation refuses an older host once, in one named diagnosis: a version below the package's own `engines.dsh` floor (`>=0.2.2-rc.1 <0.2.3-0`) fails `apply` at its first step with the floor, the host-reported version and the upgrade path, instead of loading halfway and dying in TypeError scope errors backstage with EXECUTOR_UNAVAILABLE in front (#701). An unreadable manifest or a version the host will not reveal cannot be proven below the floor, so both load as before; the range stays the single source of truth, read from the manifest beside the running build, never a copy. +- 激活期具名拒绝一次过旧宿主:低于本包自身 `engines.dsh` 下界(`>=0.2.2-rc.1 <0.2.3-0`)的版本让 `apply` 在第一步即失败,诊断给出下限、宿主实测版本与升级路径,而不是加载到一半在后场死于 TypeError scope 错误、前场只看到 EXECUTOR_UNAVAILABLE(#701)。清单不可读或宿主不肯报版本时无法证明低于下限,两者照旧加载;范围以清单为唯一事实源,从运行构建旁的 manifest 读取,绝不复制副本。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/src/adapter/dsh/host-floor.ts b/src/adapter/dsh/host-floor.ts new file mode 100644 index 00000000..578d1561 --- /dev/null +++ b/src/adapter/dsh/host-floor.ts @@ -0,0 +1,97 @@ +/** + * The host support boundary this package declares: engines.dsh in package.json + * names the floor, and activation time is where an older host must hear it (#701). + * + * A host below the floor used to load anyway and fail later - TypeError scope + * errors backstage, EXECUTOR_UNAVAILABLE in front. The host's own behaviour + * while loading an unsupported plugin remains upstream; what this package owns + * is refusing, at activation, in one named diagnosis. A version the host will + * not reveal can never be proven below the floor, so 'unknown' loads as before. + */ +import fs from 'node:fs' +import type { Context } from './types.js' +import { runtimeVersion } from './runtime-version.js' + +/** One semver triple plus prerelease identifiers; build metadata never affects precedence. */ +interface SemVer { major: number; minor: number; patch: number; pre: string[] } + +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+)?$/u +const NUMERIC = /^[0-9]+$/u + +/** Parse one strict semver; anything else is not a version this check can judge. */ +function parseSemVer(value: string): SemVer | undefined { + const match = SEMVER.exec(value) + if (match === null) return undefined + return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] === undefined ? [] : match[4].split('.') } +} + +/** Whether left sorts strictly before right under semver precedence rules. */ +function precedes(left: SemVer, right: SemVer): boolean { + if (left.major !== right.major) return left.major < right.major + if (left.minor !== right.minor) return left.minor < right.minor + if (left.patch !== right.patch) return left.patch < right.patch + if (left.pre.length === 0) return false + if (right.pre.length === 0) return true + for (let index = 0; index < Math.max(left.pre.length, right.pre.length); index++) { + const a = left.pre[index], b = right.pre[index] + if (a === undefined) return true + if (b === undefined) return false + if (a === b) continue + if (NUMERIC.test(a) && NUMERIC.test(b)) return Number(a) < Number(b) + if (NUMERIC.test(a)) return true + if (NUMERIC.test(b)) return false + return a < b + } + return false +} + +/** + * The floor this package declares for its host, from the first lower bound of + * engines.dsh; undefined when the manifest names no floor, which disables the check. + * The manifest is read once from the package root beside this module's own tree, + * so the declared range stays the single source of truth, never a copy. + * @returns the declared lower bound, or undefined. + */ +export function declaredHostFloor(): string | undefined { + if (cache === undefined) { + cache = null + try { + const manifest = JSON.parse(fs.readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')) as { engines?: { dsh?: unknown } } + const range = manifest.engines?.dsh + if (typeof range === 'string') cache = range + } catch { /* An unreadable manifest disables the floor rather than guessing one. */ } + } + if (cache === null) return undefined + const floor = />=\s*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/u.exec(cache) + return floor?.[1] +} + +/** One read of the declared engines.dsh range; null marks "no floor declared". */ +let cache: string | null | undefined + +/** + * Whether an actual host version sorts strictly below the declared floor. + * @param {string} actual - the host-reported version. + * @param {string} floor - the declared lower bound. + * @returns {boolean} true only when both parse and actual sorts below floor. + */ +export function versionBelowFloor(actual: string, floor: string): boolean { + const left = parseSemVer(actual), right = parseSemVer(floor) + return left !== undefined && right !== undefined && precedes(left, right) +} + +/** + * Refuse activation with one named diagnosis when the host is provably older + * than the declared floor; an unknown version is released, never punished. + * @param {Context} ctx - the host context the version probe reads. + * @returns {Promise} resolves when the host is at or above the floor. + */ +export async function assertHostFloor(ctx: Context): Promise { + const floor = declaredHostFloor() + if (floor === undefined) return + const { runtimeVersion: version } = await runtimeVersion(ctx) + if (version === 'unknown') return + if (versionBelowFloor(version, floor)) { + throw new Error(`This dsh-ops build requires DSH ${floor} or newer (package.json engines.dsh); the running host reports ${version}. Upgrade the host runtime instead of reloading this plugin: an older host loads it halfway at best, showing TypeError scope errors backstage and EXECUTOR_UNAVAILABLE in front.`) + } +} diff --git a/src/index.ts b/src/index.ts index cb7dec06..d8667cc1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ import * as tuiModule from './components/tui/index.js' import * as downloadGuardModule from './components/download-guard/index.js' import { configureResultCacheGc } from './kernel/result-cache-gc.js' import { registerOpsPtcPreset } from './presets/ops-ptc/register.js' +import { assertHostFloor } from './adapter/dsh/host-floor.js' export { Config } from './settings/merged.js' export { applyComponent } from './legacy/host.js' export const name = 'dsh-ops' @@ -31,6 +32,11 @@ export const name = 'dsh-ops' export async function apply(root: Context, rawConfig: unknown): Promise { const config = resolveMergedConfig(rawConfig) + // Activation-time host support boundary (#701): an older host hears one named + // diagnosis here instead of loading halfway and failing with TypeError scope + // errors backstage and EXECUTOR_UNAVAILABLE in front. An unknown host version + // cannot be proven below the floor, so it loads as before. + await assertHostFloor(root) const host = root const mount = async (module: { apply(...args: unknown[]): unknown }, state: { enabled: boolean; raw?: Record; config: unknown }, slice?: Record): Promise => { if (!state.enabled) return diff --git a/test/integration-host-floor.test.mjs b/test/integration-host-floor.test.mjs new file mode 100644 index 00000000..a48b14a8 --- /dev/null +++ b/test/integration-host-floor.test.mjs @@ -0,0 +1,74 @@ +/** + * Activation-time host support boundary (#701). + * + * A host below the declared engines.dsh floor used to load anyway and fail + * later: TypeError scope errors backstage, EXECUTOR_UNAVAILABLE in front. + * The contract pinned here: the package's own engines.dsh names the floor, an + * older host hears one explicit diagnosis at activation, and an unknown host + * version is never refused (it cannot be proven below the floor). The host's + * own behaviour while loading an unsupported plugin remains upstream. + */ +import fs from 'node:fs' +import path from 'node:path' +import { assert, test, report, withTempDir } from './lib/harness.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { apply } from '../lib/index.js' + +await test('the declared engines.dsh floor is read from the package manifest', async () => { + const { declaredHostFloor } = await import('../lib/adapter/dsh/host-floor.js') + assert.equal(declaredHostFloor(), '0.2.2-rc.1') +}) + +await test('semver precedence decides below-floor, with prerelease rules kept', async () => { + const { versionBelowFloor } = await import('../lib/adapter/dsh/host-floor.js') + const floor = '0.2.2-rc.1' + assert.equal(versionBelowFloor('0.2.1', floor), true, 'an older release is below') + assert.equal(versionBelowFloor('0.2.2-rc.0', floor), true, 'an earlier prerelease is below') + assert.equal(versionBelowFloor('0.1.9', floor), true, 'an older minor is below') + assert.equal(versionBelowFloor('0.2.2-rc.1', floor), false, 'the floor itself is not below') + assert.equal(versionBelowFloor('0.2.2', floor), false, 'a release outranks its prerelease') + assert.equal(versionBelowFloor('0.2.2-rc.2', floor), false, 'a later prerelease is not below') + assert.equal(versionBelowFloor('0.2.3', floor), false, 'a newer release is not below') + assert.equal(versionBelowFloor('1.0.0', floor), false) +}) + +/** A fake host installation whose app-boot reports a fixed runtime version. */ +function seedFakeInstallation(root, version) { + const bootDir = path.join(root, 'node_modules', '@deepseek-ai', 'dsh-app-boot') + fs.mkdirSync(bootDir, { recursive: true }) + fs.writeFileSync(path.join(bootDir, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-app-boot', main: 'index.js' })) + fs.writeFileSync(path.join(bootDir, 'index.js'), `export const getDshRuntimeVersion = () => ${JSON.stringify(version)}\n`) + fs.writeFileSync(path.join(root, 'package.json'), '{}\n') + return root +} + +await test('a host below the floor hears one named diagnosis at activation', () => withTempDir('host-floor', async root => { + const { assertHostFloor } = await import('../lib/adapter/dsh/host-floor.js') + const packageDir = seedFakeInstallation(path.join(root, 'old-host'), '0.2.1') + const { ctx } = await bootHost({ withWorkingDirectory: true }) + try { + ctx.provide('pluginPackages', { resolution: { entries: [ + { scope: 'installation', name: '@deepseek-ai/dsh-app-boot', packageDir }] } }) + await assert.rejects(assertHostFloor(ctx), /requires DSH 0\.2\.2-rc\.1 or newer/i) + // The whole row answers with the same diagnosis instead of loading. + await assert.rejects(apply(ctx, {}), /0\.2\.2-rc\.1/, 'apply must refuse an older host by the declared floor') + } finally { await shutdown(ctx) } +})) + +await test('the floor releases hosts at or above it, and an unknown version is never refused', () => withTempDir('host-floor-ok', async root => { + const { assertHostFloor } = await import('../lib/adapter/dsh/host-floor.js') + for (const version of ['0.2.2-rc.1', '0.2.3', '0.3.0']) { + const packageDir = seedFakeInstallation(path.join(root, 'host-' + version), version) + const { ctx } = await bootHost({ withWorkingDirectory: true }) + try { + ctx.provide('pluginPackages', { resolution: { entries: [ + { scope: 'installation', name: '@deepseek-ai/dsh-app-boot', packageDir }] } }) + await assertHostFloor(ctx) + } finally { await shutdown(ctx) } + } + // No readable host version: refusing it would punish hosts the probe cannot see. + const { ctx } = await bootHost({ withWorkingDirectory: true }) + try { await assertHostFloor(ctx) } finally { await shutdown(ctx) } +})) + +report('integration-host-floor') From 41f572d92de7dd1290d0efdde8122dc4bad01ba7 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:57:37 +0800 Subject: [PATCH 4/6] fix(integration): answer ops_status on built-in preset sessions (#753) The diagnosis tool was registered only behind an external preset row, while the diagnosis itself already understood mode sessions. The built-in mode row now mounts the same read-only diagnosis for exactly its own mode's sessions; the mount settles asynchronously because a synchronously resolved fiber never hears the agent/created dispatch its injection registered. Sessions of other modes stay unadmitted by that row. Red/green evidence: test-results/red/status-builtin-revert-red.txt, test-results/green-status-builtin/. --- docs/CHANGELOG.md | 3 + src/index.ts | 7 ++- src/integration/index.ts | 28 ++++++++- test/integration-status-builtin.test.mjs | 73 ++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 test/integration-status-builtin.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d3a99ea8..b358928e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -24,6 +24,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Activation refuses an older host once, in one named diagnosis: a version below the package's own `engines.dsh` floor (`>=0.2.2-rc.1 <0.2.3-0`) fails `apply` at its first step with the floor, the host-reported version and the upgrade path, instead of loading halfway and dying in TypeError scope errors backstage with EXECUTOR_UNAVAILABLE in front (#701). An unreadable manifest or a version the host will not reveal cannot be proven below the floor, so both load as before; the range stays the single source of truth, read from the manifest beside the running build, never a copy. - 激活期具名拒绝一次过旧宿主:低于本包自身 `engines.dsh` 下界(`>=0.2.2-rc.1 <0.2.3-0`)的版本让 `apply` 在第一步即失败,诊断给出下限、宿主实测版本与升级路径,而不是加载到一半在后场死于 TypeError scope 错误、前场只看到 EXECUTOR_UNAVAILABLE(#701)。清单不可读或宿主不肯报版本时无法证明低于下限,两者照旧加载;范围以清单为唯一事实源,从运行构建旁的 manifest 读取,绝不复制副本。 +- A built-in preset session now answers `ops_status` about its own scope: the diagnosis tool was registered only behind an external preset row, while the diagnosis itself already understood mode sessions, so a session on a built-in preset had no named answer at all (#753). The built-in mode row mounts the same read-only diagnosis for exactly its own mode's sessions, and the mount settles asynchronously because a fiber that resolves synchronously never hears the `agent/created` dispatch the injection registered. Sessions of other modes stay unadmitted by that row, and the external preset row keeps ownership where it exists. +- 内置 preset 会话现在能对自身作用域应答 `ops_status`:诊断工具此前只随外部 preset 行注册,而诊断本身早已理解 mode 会话,落在内置 preset 上的会话完全没有具名答案(#753)。内置 mode 行为且仅为该 mode 的会话挂载同一只读诊断;挂载特意异步落定,因为同步 resolve 的 fiber 永远收不到注入里注册的 `agent/created` 派发。其他 mode 的会话仍不被该行接纳,外部 preset 行存在时继续保持其所有权。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/src/index.ts b/src/index.ts index d8667cc1..a66b05b5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,7 @@ import { resolveModeConfig } from './presets/config.js' import { resolveMergedConfig, effectiveMode, dynamicForMode } from './settings/merged.js' import { MODE_IDS } from './presets/types.js' import { beginMergedRow, endMergedRow } from './settings/legacy.js' -import { mountIntegration } from './integration/index.js' +import { mountIntegration, mountModeDiagnostics } from './integration/index.js' import { gateConsumer } from './consumer/gates.js' import { resolveIntegrationConfig } from './consumer/options.js' import { mountRuntimeSettings } from './settings/runtime-host.js' @@ -65,10 +65,13 @@ export async function apply(root: Context, rawConfig: unknown): Promise { for (const mode of MODE_IDS) { const state = config[mode] const effective = resolveModeConfig(effectiveMode(state, config.global, typeof config.other.raw?.pwsh7Link === 'boolean' ? config.other.raw.pwsh7Link : companionVersion({ sweep: false }) !== undefined), mode) - await host.plugin({ name: `dsh-ops/consumer-${mode}`, apply(ctx: Context) { + await host.plugin({ name: `dsh-ops/consumer-${mode}`, async apply(ctx: Context) { applyResolvedMode(ctx, effective, mode, { enabled: state.enabled, discovery: { ...config.discovery.config, enabled: config.discovery.enabled }, dynamic: dynamicForMode(state, config.global) }) + // Built-in modes answer ops_status too (#753): the named diagnosis used + // to exist only behind an external preset row. + await mountModeDiagnostics(ctx, mode) } }) } for (const row of Object.values(config.presets)) { diff --git a/src/integration/index.ts b/src/integration/index.ts index 49e3ec12..a3bd3eb3 100644 --- a/src/integration/index.ts +++ b/src/integration/index.ts @@ -1,10 +1,13 @@ /** Stable opt-in preset entry. Consumers share the same assembler as built-in presets. */ -import type { Context } from '../adapter/dsh/types.js' +import type { Agent, Context } from '../adapter/dsh/types.js' import { mountConsumer } from '../consumer/mount.js' import { replacementTargets } from '../consumer/replacements.js' import { resolveIntegrationConfig, type IntegrationOptions, type IntegrationConfig } from '../consumer/options.js' import { mountDiagnostics } from './diagnostics.js' -import { joinIntegration } from '../consumer/registry.js' +import { joinIntegration, integrationFor } from '../consumer/registry.js' +import { modeOf } from '../presets/detect.js' +import { onModesChange } from '../presets/registry.js' +import type { ModeId } from '../presets/types.js' export { diagnose } from './diagnostics.js' export type { Diagnostic } from './diagnostics.js' export { registerNativeCapability } from '../discovery/providers.js' @@ -33,6 +36,27 @@ export async function mountIntegration(ctx: Context, config: IntegrationConfig): external: { allowed: config.externalTools, alwaysLoaded: config.externalAlwaysLoaded, disabled: config.externalDisabled }, }) } +/** + * One built-in mode publishes the same read-only diagnosis (#753): the status + * tool used to exist only behind an external preset row, so a built-in preset + * session could not see its own scope at all. The gate admits exactly the + * sessions of this mode without an external preset - the same row the mode's + * consumer is admitted by - so the two publications never overlap. + * + * The mount settles asynchronously on purpose: the listener this registers + * inside the tools injection has to be on a fiber that resolves after the + * synchronous apply returns, or the later `agent/created` dispatch never + * reaches it - the external preset row reaches the same point by awaiting its + * binding join, which is why only the built-in loop needed this one step. + */ +export async function mountModeDiagnostics(ctx: Context, mode: ModeId): Promise { + await Promise.resolve() + mountDiagnostics(ctx, { + allows: (agent: Agent) => integrationFor(ctx, agent) === undefined && modeOf(ctx, agent) === mode, + watch: (notify: () => void) => onModesChange(ctx, notify), + }) +} + /** Mount inside a preset composition or with an explicit preset id at the host root. */ export function integration(options: IntegrationOptions) { const captured = structuredClone(options) diff --git a/test/integration-status-builtin.test.mjs b/test/integration-status-builtin.test.mjs new file mode 100644 index 00000000..7c6a715c --- /dev/null +++ b/test/integration-status-builtin.test.mjs @@ -0,0 +1,73 @@ +/** + * Built-in preset sessions publish their own scope diagnosis (#753). + * + * The status tool used to exist only behind an external preset row: a built-in + * mode row mounted its consumer and nothing else, so a session the host ran on + * a built-in preset had no named answer about its own publication at all, + * although the diagnosis itself already understood mode sessions. Pinned here: + * the built-in mode loop mounts the diagnosis gate that admits exactly this + * mode's sessions, the tool is visible and executable there, the diagnosis + * recognises the mode as selected, and another built-in mode is not admitted. + */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { bootHost, shutdown, scopedToolNames } from './lib/host.mjs' +import { assert, test, report, withTempDir } from './lib/harness.mjs' +import { executeCall, prepareStep } from './lib/executor.mjs' +import { mountModeDiagnostics } from '../lib/integration/index.js' +import { applyResolvedMode } from '../lib/presets/builtin.js' +import { resolveModeConfig } from '../lib/presets/config.js' + +const dispatch = async (ctx, request) => { + const step = await prepareStep(ctx, request.agent) + try { return await executeCall(ctx, { ...request, toolSet: step.toolSet }) } + finally { step.dispose() } +} + +/** The exact composition the built-in loop in src/index.ts runs for one mode. */ +async function mountBuiltinMode(ctx, mode) { + await ctx.plugin({ async apply(inner) { + applyResolvedMode(inner, resolveModeConfig({}, mode), mode) + await mountModeDiagnostics(inner, mode) + } }) +} + +await test('a built-in preset session sees and executes its own status tool', () => withTempDir('status-builtin', async cwd => { + const { ctx } = await bootHost() + try { + await mountBuiltinMode(ctx, 'minimal') + const agent = { id: 'builtin', session: { id: 'builtin', mode: 'read-only', header: { cwd, agentPreset: 'minimal' } } } + await ctx.plugin({ inject: ['tools'], apply(inner) { agent.ctx = createScope(inner, agent).ctx } }) + await ctx.serial('agent/created', { agent }) + assert.notEqual(ctx.get('tools').get('ops_status', agent), undefined, 'the built-in row publishes the status tool to this agent') + const result = await dispatch(ctx, { agent, name: 'ops_status', arguments: {}, callId: 'builtin', signal: new AbortController().signal }) + assert.equal(result.isError, false, 'the status tool answers, it does not refuse') + assert.equal(result.value.state, 'ready', 'the diagnosis recognises the built-in mode as selected and sound') + assert.equal(result.value.preset, 'minimal', 'the built-in preset identity is reported, not an external row') + } finally { await shutdown(ctx) } +})) + +await test('a session of another built-in mode is not admitted by this gate', () => withTempDir('status-other-mode', async cwd => { + const { ctx } = await bootHost() + try { + await mountBuiltinMode(ctx, 'minimal') + const agent = { id: 'other', session: { id: 'other', mode: 'read-only', header: { cwd, agentPreset: 'standard' } } } + await ctx.plugin({ inject: ['tools'], apply(inner) { agent.ctx = createScope(inner, agent).ctx } }) + await ctx.serial('agent/created', { agent }) + assert.equal(scopedToolNames(ctx, agent).includes('ops_status'), false, 'another mode\'s session gets no status tool from this row') + } finally { await shutdown(ctx) } +})) + +await test('the mode row alone admits a plain built-in session and keeps answering it', () => withTempDir('status-repeat', async cwd => { + const { ctx } = await bootHost() + try { + await mountBuiltinMode(ctx, 'minimal') + const agent = { id: 'again', session: { id: 'again', mode: 'read-only', header: { cwd, agentPreset: 'minimal' } } } + await ctx.plugin({ inject: ['tools'], apply(inner) { agent.ctx = createScope(inner, agent).ctx } }) + await ctx.serial('agent/created', { agent }) + assert.notEqual(ctx.get('tools').get('ops_status', agent), undefined, 'the mode row owns the plain built-in session') + const answer = await dispatch(ctx, { agent, name: 'ops_status', arguments: {}, callId: 'again', signal: new AbortController().signal }) + assert.equal(answer.isError, false) + } finally { await shutdown(ctx) } +})) + +report('integration-status-builtin') From 4e7b6af5c7204a6634d42fa7858db563b48c7fce Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:58:50 +0800 Subject: [PATCH 5/6] docs(troubleshooting): spell out the single shell tool name (#897) The package publishes exactly one shell tool, ops_bash, and a misnamed bash call is answered by the host's own unknown-tool handling, which never reaches this package. The section names where the alias could exist (it does not) and where a did-you-mean correction belongs: upstream. --- docs/troubleshooting.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index b58646e9..3d4cecbf 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -83,6 +83,10 @@ Long scripts, heredocs and multi-layer quotes and backslashes make the model esc A key the `ops_bash` schema does not declare is refused before execution, and the error names both the unknown keys and the accepted ones. This is deliberate — nothing is silently ignored. +### The model calls `bash` instead of `ops_bash` + +This package publishes exactly one shell tool, named `ops_bash`; there is no `bash` alias. The tool table is assembled by the host from the names this package declares once (`publicToolName` in `src/policy.ts`), and a misnamed call never reaches this package: the host answers with its own unknown-tool message, so any did-you-mean correction also belongs to the host, not here. Point the model back to the real name — the tool table and the prompt both spell `ops_bash` — instead of expecting a silent alias. + ### Bash script files, PATH precedence and empty input `script_path` always selects a Bash script; the extension does not select an From 9578d98b6a8c5b7854dd90b1d6449aad6199de9d Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 09:56:09 +0800 Subject: [PATCH 6/6] test(prompt-budget): re-pin resident budgets for the ops_status mount (#753) Measured on win32, mount on: minimal 3536/8246/4710, standard 3536/12670/9134, cordis 3536/12670/9134, ptc 7553/19200/11647 (before/after/net). With the #753 mount disabled the same run reports 3536/8045/4509, 3536/12469/8933, 3536/12469/8933 and 7553/19026/11473, so the 174-201 byte difference is the ops_status schema and guidance this accepted behaviour adds. minimal and ptc carry the added allowance (8100->8300, 19200->19300); standard and cordis keep their previous, still-unused headroom. --- test/prompt-budget.test.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/prompt-budget.test.mjs b/test/prompt-budget.test.mjs index 6d9c9286..dd7ac2e2 100644 --- a/test/prompt-budget.test.mjs +++ b/test/prompt-budget.test.mjs @@ -14,7 +14,12 @@ import { assert, test, report, withTempDir } from './lib/harness.mjs' // Includes all host text/wire, not just the plugin delta. No tokenizer/cache claims. // Pre-slice win32 baseline: minimal=10516, standard=19996, cordis=19996, ptc=29639. // Windows is the largest default surface (OPS Bash); POSIX must fit the same bounds. -const budgets = { minimal: 8100, standard: 13700, cordis: 13700, ptc: 19200 } +// #753 mounts the ops_status diagnosis on built-in modes. Measured on win32 with the +// mount on: minimal=8246, standard=12670, cordis=12670, ptc=19200; with the mount +// disabled: 8045, 12469, 12469, 19026. The 174-201 byte difference is that tool's +// own schema/guidance, so minimal and ptc carry the added allowance while standard +// and cordis keep their previous, still-unused headroom. +const budgets = { minimal: 8300, standard: 13700, cordis: 13700, ptc: 19300 } await test('each default preset stays within its resident per-request byte budget', async () => { await withTempDir('prompt-budget', async root => { const { ctx } = await bootHost()