From 2719f6a6f501c4eb6ca9ec52386373d8096c3369 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 00:43:15 +0800 Subject: [PATCH 1/6] fix(ptc): point unselected pool APIs at the loader (#968) A registered-but-unselected pool API answered direct dispatch with PUBLICATION_GRANT_UNAVAILABLE (retry: never) on the file-lease path and a bare POLICY_DENIED on the PTC-only path, neither naming the loader. The registrar lease contract gains an optional deferred() advisor that pool publications supply; both paths now answer SDK_NOT_LOADED with a next action naming ops_load_sdk and the raw name, and stay silent when the current policy cannot load the API. Loader-less scopes still register nothing from the pool (#887). --- src/publication/ptc.ts | 14 +++++ src/publication/registrar.ts | 19 +++++- test/ptc-deferred-rejection.test.mjs | 88 ++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 test/ptc-deferred-rejection.test.mjs diff --git a/src/publication/ptc.ts b/src/publication/ptc.ts index f9167c8e..08491bf9 100644 --- a/src/publication/ptc.ts +++ b/src/publication/ptc.ts @@ -18,6 +18,7 @@ import { InvocationLifetime, InvocationNotStarted } from '../lifecycle/invocatio import { monitoredInvoke } from '../execution/monitored.js' import { record } from '../execution/boundary.js' import { failure, resolveWorker } from '../execution/jobs.js' +import type { Outcome } from '../kernel/outcome.js' import { WORKER_TIMEOUT_MS } from '../execution/protocol.js' import { registerStepTailProvider } from '../prompt-injection/index.js' import { mountWorkspacePreparation } from '../workspace-preparation.js' @@ -108,6 +109,15 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al }) } + /** Point a declared-but-unselected pool API at the loader; undefined when loading cannot help (#968). */ + const deferredRejection = (entry: Entry, api: ApiName): Outcome | undefined => { + if (gate.dynamic === false || !loadable.includes(api) || !permitted(entry.agent, api) || selected(entry, api)) return undefined + return { status: 'error', error: { + code: 'SDK_NOT_LOADED', effectState: 'none', retry: 'never', + message: `API '${api}' is in this scope's allowed pool but is not loaded into the typed SDK yet; no action was executed.`, + nextAction: `Call ${publicToolName('load_sdk')} with tools:["${api}"] and use the API on the next model step; retrying this call without loading fails the same way.`, + } } + } const execute = (entry: Entry, api: ApiName | 'load_sdk'): ToolDefinition['execute'] => async (args, exec) => { // The public assembly may finish after its executor sections changed. // Refuse that stale verdict rather than dispatching under the old text. @@ -116,6 +126,9 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al && revision === presentationRevision && permitted(entry.agent, api) && selected(entry, api) && (capability(api)?.component === 'file' || tools.executable(publicToolName(api), entry.agent, exec.toolSet) === entry.definitions.get(publicToolName(api))) if (!current() || !await isPtc(entry.agent, exec.signal).catch(() => false) || !current()) { + // A declared-but-unselected pool API points at the loader; every other admission failure keeps the generic refusal. + const deferred = api === 'load_sdk' ? undefined : deferredRejection(entry, api) + if (deferred !== undefined) return deferred return failure('POLICY_DENIED', 'This API must be admitted for the calling PTC scope; no action executed.') } if (api === 'load_sdk') { @@ -147,6 +160,7 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al present: activation => activation.agent === entry.agent && permitted(entry.agent, api) && selected(entry, api) && activationIsPtc(prompt, activation), dispatch: file.dispatch, + deferred: () => deferredRejection(entry, api), }) file.granted = { entitled, selected: selection, config } } diff --git a/src/publication/registrar.ts b/src/publication/registrar.ts index 7104aeb8..7e8267dd 100644 --- a/src/publication/registrar.ts +++ b/src/publication/registrar.ts @@ -13,6 +13,8 @@ export interface PublicationGrant { dispatch(args: unknown, exec: ToolRunContext): Promise /** Presentation may only narrow this captured grant; it never chooses dispatch. */ present?(activation: ToolActivationContext): boolean | Promise + /** Outcome for a caller whose grants exist but none is entitled: a deferred-selection pointer, not a silent dead end (#968). */ + deferred?(): Outcome | undefined cancel?(): void } export interface PublicationLease { @@ -137,7 +139,22 @@ export async function acquire(ctx: Context, scope: object | undefined, name: str return denied('PUBLICATION_IDENTITY_MISMATCH') } const matching = eligible(exec.agent) - if (!matching.length || matching.some(grant => grant.dispatch !== matching[0].dispatch)) return denied('PUBLICATION_GRANT_UNAVAILABLE') + if (!matching.length) { + // Same-agent grants with no entitled member can still explain themselves: a pool + // publication points its caller at the loader instead of a retry-never denial (#968). + const advice = [...grants].find(grant => grant.agent === exec.agent && typeof grant.deferred === 'function') + if (advice !== undefined) { + const deferred = advice.deferred + if (typeof deferred === 'function') { + try { + const outcome = deferred() + if (outcome !== undefined && 'error' in outcome) return outcome + } catch { /* an unavailable advisor falls back to the generic denial */ } + } + } + return denied('PUBLICATION_GRANT_UNAVAILABLE') + } + if (matching.some(grant => grant.dispatch !== matching[0].dispatch)) return denied('PUBLICATION_GRANT_UNAVAILABLE') const controller = new AbortController() const caller = exec.signal const abort = () => controller.abort(caller?.reason) diff --git a/test/ptc-deferred-rejection.test.mjs b/test/ptc-deferred-rejection.test.mjs new file mode 100644 index 00000000..c77aa6ae --- /dev/null +++ b/test/ptc-deferred-rejection.test.mjs @@ -0,0 +1,88 @@ +/** A registered-but-unselected pool API must point at the loader, not a dead end (#968). */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { mountPtc } from '../lib/publication/ptc.js' +import { publicToolName } from '../lib/policy.js' +import { assert, test, report, waitFor } from './lib/harness.mjs' +import { bootHost, shutdown } from './lib/host.mjs' + +const tick = () => new Promise(resolve => setImmediate(resolve)) +/** The minimal tool-set view the registry's executable check accepts for one definition. */ +const soloView = definition => ({ view: () => new Map([[definition.name, definition]]) }) + +async function setup(config, gate = { allows: () => true }) { + const { ctx } = await bootHost({ withWorkingDirectory: true, toolsMode: 'ptc' }) + const agents = [] + ctx.provide('agents', { list: () => agents }) + await ctx.plugin(inner => { + inner.provide('ptcRuntime', { language: 'typescript' }) + inner.provide('sandboxPolicy', { resolve: ({ session }) => ({ mode: session?.mode ?? 'danger-full-access', workspaceRoot: process.cwd() }) }) + inner.provide('subprocess', { spawn() { throw new Error('deferred rejection fixtures never spawn') } }) + }) + mountPtc(ctx, { binaryPath: process.execPath, required: true, ...config }, gate) + const mint = async (mode = 'danger-full-access') => { + const id = 'deferred-' + mode + const agent = { id, session: { id, mode, header: { cwd: process.cwd() }, append() {}, read() { return [] } } } + agent.ctx = createScope(ctx, agent).ctx + agents.push(agent) + await ctx.serial('agent/created', { agent }) + await tick() + return agent + } + return { ctx, mint } +} + +/** Dispatch the registered definition the way a host that ignores `when` does (#934 shape). */ +const dispatch = async (ctx, agent, raw) => { + const tools = ctx.get('tools') + const definition = tools.get(publicToolName(raw), agent) + ?? tools.definitions(agent).find(def => def.name === publicToolName(raw)) + assert.ok(definition, publicToolName(raw) + ' must be registered for this scenario') + return definition.execute({}, { agent, signal: new AbortController().signal, toolSet: soloView(definition) }) +} + +await test('an unselected shared-file pool API answers with the loader path, not a retry-never dead end', async () => { + const { ctx, mint } = await setup({ allowedTools: ['grep', 'batch', 'write_file'] }) + try { + const agent = await mint() + await waitFor(() => ctx.get('tools').get(publicToolName('grep'), agent), { what: 'PTC pool registration' }) + const result = await dispatch(ctx, agent, 'grep') + assert.equal(result.error?.code, 'SDK_NOT_LOADED') + assert.match(result.error.message, /grep/) + assert.match(result.error.nextAction ?? '', /ops_load_sdk/) + assert.match(result.error.nextAction ?? '', /next model step/) + } finally { await shutdown(ctx) } +}) + +await test('an unselected PTC-only pool API answers with the same loader path', async () => { + const { ctx, mint } = await setup({ allowedTools: ['grep', 'batch', 'write_file'] }) + try { + const agent = await mint() + await waitFor(() => ctx.get('tools').get(publicToolName('batch'), agent), { what: 'PTC pool registration' }) + const result = await dispatch(ctx, agent, 'batch') + assert.equal(result.error?.code, 'SDK_NOT_LOADED') + assert.match(result.error.message, /batch/) + assert.match(result.error.nextAction ?? '', /ops_load_sdk/) + } finally { await shutdown(ctx) } +}) + +await test('a pool API the current policy cannot load keeps the generic refusal', async () => { + const { ctx, mint } = await setup({ allowedTools: ['grep', 'batch', 'write_file'] }) + try { + const agent = await mint('read-only') + await waitFor(() => ctx.get('tools').get(publicToolName('write_file'), agent), { what: 'PTC pool registration' }) + const result = await dispatch(ctx, agent, 'write_file') + // Read-only policy can never load a mutating API, so pointing at the loader would be dishonest. + assert.notEqual(result.error?.code, 'SDK_NOT_LOADED') + } finally { await shutdown(ctx) } +}) + +await test('a loader-less scope keeps registering nothing from the pool', async () => { + const { ctx, mint } = await setup({ allowedTools: ['grep'] }, { allows: () => true, dynamic: false }) + try { + const agent = await mint() + await tick(); await tick() + assert.equal(ctx.get('tools').get(publicToolName('grep'), agent), undefined) + } finally { await shutdown(ctx) } +}) + +report('ptc-deferred-rejection') From e92e08732b0a7d90726bb4acb447f5018ecf4a1d Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 00:43:15 +0800 Subject: [PATCH 2/6] fix(discovery): point unselected capabilities at the selector (#764) An unselected discovery capability answered direct dispatch with PUBLICATION_GRANT_UNAVAILABLE on the shared-file lease path and POLICY_DENIED on the provider path, with a next action that never mentioned the selector. Both paths now answer CAPABILITY_NOT_SELECTED with a select: query pointer; read-only scopes that can never select a mutating capability keep the generic refusal, and a committed selection stops answering with the deferred rejection. --- src/discovery/controller.ts | 22 +++++ test/discovery-deferred-rejection.test.mjs | 102 +++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 test/discovery-deferred-rejection.test.mjs diff --git a/src/discovery/controller.ts b/src/discovery/controller.ts index e83af2ce..8b97a571 100644 --- a/src/discovery/controller.ts +++ b/src/discovery/controller.ts @@ -7,6 +7,7 @@ import { activationIsPtc, isNativePresentation, isPresentationProbe } from '../p import { visibleNames } from '../publication/surface.js' import { mountResultLifecycle } from '../kernel/result-lifecycle.js' import { failure, resolveWorker } from '../execution/files.js' +import type { Outcome } from '../kernel/outcome.js' import { capability, DISCOVERY_TOOL_NAME } from '../capabilities/registry.js' import { DISCOVERY_DESCRIPTION, DISCOVERY_PARAMETERS, DISCOVERY_OUTPUT } from '../capabilities/discovery.js' import { publicToolName, renderToolingPolicy } from '../policy.js' @@ -93,6 +94,23 @@ export function mountDiscovery(root: Context, raw: unknown, gate: DiscoveryGate) const api = apiByName.get(name) return api !== undefined && selectable(agent, api) && (config.alwaysLoaded.includes(api) || entry.selected.has(api)) } + /** Point a declared-but-unselected capability at the selector; undefined when discovery cannot select it (#764). */ + const deferredRejection = (agent: Agent, entry: Entry, name: string, provider?: Provider): Outcome | undefined => { + if (!selected(agent, entry, DISCOVER)) return undefined + if (provider !== undefined) { + if (!externalPool(agent).includes(provider) || !externalAvailable(provider, agent) + || gate.external?.alwaysLoaded.includes(name) || provider.capability.disclosure === 'resident' + || entry.externalSelected.has(provider.token)) return undefined + } else { + const api = apiByName.get(name) + if (api === undefined || !selectable(agent, api) || config.alwaysLoaded.includes(api) || entry.selected.has(api)) return undefined + } + return { status: 'error', error: { + code: 'CAPABILITY_NOT_SELECTED', effectState: 'none', retry: 'never', + message: `Capability '${name}' is discoverable for this scope but is not selected yet; no action was executed.`, + nextAction: `Call ${DISCOVER} with a select: query naming it (for example query: "select:${name}"); the tool becomes available on the next model step.`, + } } + } const rotateFiles = (agent: Agent, entry: Entry): void => { for (const [api, file] of entry.files) { const entitled = selected(agent, entry, publicToolName(api)) @@ -103,6 +121,7 @@ export function mountDiscovery(root: Context, raw: unknown, gate: DiscoveryGate) dispatch: async () => undefined, present: async activation => activation.agent === agent && entries.get(agent) === entry && permitted(agent, api) && !await activationIsPtc(prompt, activation), + deferred: () => deferredRejection(agent, entry, publicToolName(api)), }) file.entitled = entitled } @@ -113,6 +132,9 @@ export function mountDiscovery(root: Context, raw: unknown, gate: DiscoveryGate) const current = () => !exec.signal.aborted && entries.get(agent) === entry && exec.agent === agent && selected(agent, entry, source.name, provider) && tools.executable(source.name, agent, exec.toolSet) === definition if (!current() || !await isNativePresentation(prompt, agent, exec.signal).catch(() => false) || !current()) { + // A registered-but-unselected capability points at the selector; every other admission failure keeps the generic refusal. + const deferred = deferredRejection(agent, entry, source.name, provider) + if (deferred !== undefined) return deferred return failure('POLICY_DENIED', 'This Native capability must be admitted for the calling scope; no action executed.') } if (!provider) return source.execute(args, exec) diff --git a/test/discovery-deferred-rejection.test.mjs b/test/discovery-deferred-rejection.test.mjs new file mode 100644 index 00000000..4a24c2b9 --- /dev/null +++ b/test/discovery-deferred-rejection.test.mjs @@ -0,0 +1,102 @@ +/** Unselected discovered tools must name the selector and its select: query (#764). */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { mountDiscovery } from '../lib/discovery/controller.js' +import { registerNativeCapability } from '../lib/discovery/providers.js' +import { assert, test, report, waitFor } from './lib/harness.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { executeCall } from './lib/executor.mjs' + +const DISCOVER = 'ops_discover_tools' +const definition = (name, execute = () => ({ status: 'completed', answer: 42 })) => ({ + name, description: 'Look up project inventory.', parameters: { type: 'object', properties: {} }, + output: { schema: { type: 'object' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] }, execute, +}) +/** The minimal tool-set view the registry's executable check accepts for one definition. */ +const soloView = definition => ({ view: () => new Map([[definition.name, definition]]) }) + +async function setup() { + const { ctx, tools } = await bootHost() + const agents = [] + ctx.provide('agents', { list: () => agents }) + // Publication-only worker fixture: never invoked; no Rust runtime is needed by this suite. + ctx.provide('subprocess', { spawn() { throw new Error('deferred rejection fixtures never spawn') } }) + ctx.provide('sandboxPolicy', { resolve: ({ session }) => ({ mode: session?.mode ?? 'danger-full-access', workspaceRoot: process.cwd(), sessionId: session?.id }) }) + await ctx.plugin({ apply(inner) { + mountDiscovery(inner, { allowedTools: ['stat', 'write_file'], alwaysLoaded: [], binaryPath: process.execPath }, { + allows: () => true, residentTools: () => [], + external: { allowed: ['acme_lookup'], disabled: [], alwaysLoaded: [] }, + }) + } }) + await waitFor(() => ctx.get('tools') && ctx.get('systemPrompt')) + for (let i = 0; i < 3; i++) await new Promise(resolve => setImmediate(resolve)) + await registerNativeCapability(ctx, { + definition: definition('acme_lookup'), search: 'inventory project lookup', authorize: () => true, + }) + const mint = async (mode = 'danger-full-access') => { + const id = 'discovery-deferred-' + mode + const agent = { id, session: { id, mode, header: { cwd: process.cwd() } } } + agent.ctx = createScope(ctx, agent).ctx + agents.push(agent) + await ctx.serial('agent/created', { agent }) + await waitFor(() => tools.get(DISCOVER, agent), { what: 'discovery lifecycle initialization' }) + return agent + } + return { ctx, tools, mint } +} + +/** Dispatch the registered definition the way a host that ignores `when` does (#934 shape). */ +const dispatch = async (ctx, agent, name) => { + const definition = ctx.get('tools').get(name, agent) ?? ctx.get('tools').definitions(agent).find(def => def.name === name) + assert.ok(definition, name + ' must be registered for this scenario') + return definition.execute({}, { agent, signal: new AbortController().signal, toolSet: soloView(definition) }) +} + +await test('an unselected builtin discovery capability answers with the select: query path', async () => { + const { ctx, mint } = await setup() + try { + const agent = await mint() + const result = await dispatch(ctx, agent, 'ops_stat') + assert.equal(result.error?.code, 'CAPABILITY_NOT_SELECTED') + assert.match(result.error.message, /ops_stat/) + assert.match(result.error.nextAction ?? '', /ops_discover_tools/) + assert.match(result.error.nextAction ?? '', /select:ops_stat/) + } finally { await shutdown(ctx) } +}) + +await test('an unselected external provider capability answers with the same select: path', async () => { + const { ctx, mint } = await setup() + try { + const agent = await mint() + const result = await dispatch(ctx, agent, 'acme_lookup') + assert.equal(result.error?.code, 'CAPABILITY_NOT_SELECTED') + assert.match(result.error.message, /acme_lookup/) + assert.match(result.error.nextAction ?? '', /select:acme_lookup/) + } finally { await shutdown(ctx) } +}) + +await test('a discovered selection stops answering with the deferred rejection', async () => { + const { ctx, mint } = await setup() + try { + const agent = await mint() + // The selector itself must stay callable while its pool defers. + assert.equal((await dispatch(ctx, agent, 'ops_stat')).error?.code, 'CAPABILITY_NOT_SELECTED') + const select = await executeCall(ctx, { agent, name: DISCOVER, arguments: { query: 'select:ops_stat' }, callId: 'select-stat' }) + assert.equal(select.isError, false, JSON.stringify(select)) + assert.deepEqual(select.value.activated, ['ops_stat']) + ctx.emit('session/event', agent.session, { type: 'step/end', turn: 1, step: 1 }) + const result = await dispatch(ctx, agent, 'ops_stat') + assert.notEqual(result.error?.code, 'CAPABILITY_NOT_SELECTED') + } finally { await shutdown(ctx) } +}) + +await test('a read-only scope keeps the generic refusal for mutating capabilities', async () => { + const { ctx, mint } = await setup() + try { + const agent = await mint('read-only') + const result = await dispatch(ctx, agent, 'ops_write_file') + // Read-only policy can never select a mutating capability, so a select: pointer would be dishonest. + assert.notEqual(result.error?.code, 'CAPABILITY_NOT_SELECTED') + } finally { await shutdown(ctx) } +}) + +report('discovery-deferred-rejection') From dc3e772506d48332020ab0327aab911a30e29e04 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 00:43:15 +0800 Subject: [PATCH 3/6] fix(replacements): fail open when the counterpart executor cannot serve (#962) A pwsh shadow kept the official tool hidden even when the replacing Bash executor was dead, and a consumer whose Bash slot never resolved an executor still hid the official tools behind a foreign same-name registration. Replacement shadows now lift per agent once a counterpart call settles with an unrecoverable Bash preparation failure (runtime missing, IPC mismatch, lifecycle lock busy, cache unusable, incompatible build), and mountConsumer keeps the officials admitted when its own Bash slot never resolved. Staging interruptions that the next call repairs keep the shadow. --- src/consumer/mount.ts | 6 +- src/publication/replacements.ts | 42 +++++++++- test/publication-fail-open.test.mjs | 118 ++++++++++++++++++++++++++++ 3 files changed, 164 insertions(+), 2 deletions(-) create mode 100644 test/publication-fail-open.test.mjs diff --git a/src/consumer/mount.ts b/src/consumer/mount.ts index a8d77fbe..2f8044e6 100644 --- a/src/consumer/mount.ts +++ b/src/consumer/mount.ts @@ -19,6 +19,9 @@ export function mountConsumer(ctx: Context, plan: ConsumerPlan): void { const { gate, core } = plan let renderShellGuidance: (agent: Agent) => string = () => '' const shellOwnsGuidance = (agent: Agent): boolean => Boolean(core.extraGuidance.trim()) && Boolean(renderShellGuidance(agent)) + // A shell slot whose executor never resolved must never hide the official tools it was + // going to replace (#962): the replacement would advertise a counterpart that cannot run. + let bashUnavailable = false if (plan.shell) { // Host subprocess spills outlive the call that produced them upstream, so the // row that publishes the shell also owns one bounded retention runtime. @@ -31,6 +34,7 @@ export function mountConsumer(ctx: Context, plan: ConsumerPlan): void { // Resolved once at mount: a slot whose executor never resolved publishes no tool at all, so the // section below has to report that instead of rendering nothing for the whole session. const bashResolution = shells.bash + bashUnavailable = !bashResolution.available ctx.inject(['tools'], inner => mountSessionBash(inner, core, shells, gate)) if (core.promptPolicy) ctx.inject(['tools', 'systemPrompt'], inner => { mountJobWaitGuidance(inner, plan.id, gate) @@ -61,5 +65,5 @@ export function mountConsumer(ctx: Context, plan: ConsumerPlan): void { extraGuidanceOwner: agent => shellOwnsGuidance(agent) || nativeOwnsGuidance(agent), residentTools: () => residents.map(publicToolName), external: plan.external }) } else if (plan.files) mountPtc(ctx, plan.ptc, { ...gate, guidance: core.promptPolicy, resident: plan.residentTools, dynamic: plan.discovery }) - if (plan.replaceOfficial) mountReplacements(ctx, { id: plan.id, targets: plan.replacementTargets, gate, keepOfficial: () => false }) + if (plan.replaceOfficial) mountReplacements(ctx, { id: plan.id, targets: plan.replacementTargets, gate, keepOfficial: () => bashUnavailable }) } \ No newline at end of file diff --git a/src/publication/replacements.ts b/src/publication/replacements.ts index 71a10550..e8224d1e 100644 --- a/src/publication/replacements.ts +++ b/src/publication/replacements.ts @@ -7,6 +7,30 @@ import { publicationAdmission } from './registrar.js' import { loadScopes } from '../adapter/dsh/host.js' import type { PublicationGate } from './types.js' +/** Bash preparation stages that no retry of the same call can repair; each lifts the official fallback (#962). */ +const UNRECOVERABLE_BASH_STAGES = new Set(['bash-runtime-missing', 'bash-ipc-mismatch', 'bash-lifecycle-lock-busy', 'bash-cache-unusable']) + +/** + * Whether one settled replacement-counterpart value reports a runtime failure that + * retrying the same call cannot repair (#962). Only Bash preparation stages without a + * retry remedy qualify: a staging interruption is repaired by the next call, and lifting + * the shadow for it would flap between two tool sets. The stage is the stable second + * segment of the model-facing EXECUTOR_UNAVAILABLE text (src/bash-runtime-failure.ts); + * bash-runtime-incompatible keeps its own complete message without that prefix, so its + * stage name inside the message is its identifier. PTC Outcome failures carry a structured + * error object, never this text, so they never classify. + * @param value - one settled tool-call value. + * @returns whether the official fallback must be restored for the calling agent. + */ +export function unrecoverableCounterpartRuntime(value: unknown): boolean { + if (value === null || typeof value !== 'object') return false + const error = (value as { error?: unknown }).error + if (typeof error !== 'string') return false + const stage = /^EXECUTOR_UNAVAILABLE:\s*([a-z-]+):/.exec(error) + if (stage !== null) return UNRECOVERABLE_BASH_STAGES.has(stage[1]!) + return error.includes('bash-runtime-incompatible') +} + interface Shadow { source: ToolDefinition; definition: ToolDefinition; dispose(): void } interface Entry { shadows: Map; probe: object } @@ -30,6 +54,9 @@ export function mountReplacements(root: Context, publication: ReplacementPublica const entries = new Map() // Disposed agents and agents with unlinked host scopes must not receive shadows. const inactive = new WeakSet() + // Agents whose counterpart reported an unrecoverable runtime failure keep their official tools (#962). + const broken = new WeakSet() + const counterparts = new Set(targets.values()) let stopped = false, mutating = false let scheduled: ReturnType | undefined const defer = (): void => { @@ -74,7 +101,7 @@ export function mountReplacements(root: Context, publication: ReplacementPublica // Own registrations bypass restrictions in the host view. The empty descendant // probe makes our shadow inherited, so even agent-local restrictions still apply. if (tools.get(official, entry.probe) !== definition || sourceFor(activation.agent, official) !== source) return false - if (keepOfficial() || !gate.allows(activation.agent)) return true + if (keepOfficial() || broken.has(activation.agent) || !gate.allows(activation.agent)) return true const replacement = tools.get(counterpart, activation.agent) if (!replacement) return true const admission = publicationAdmission(replacement) @@ -127,6 +154,19 @@ export function mountReplacements(root: Context, publication: ReplacementPublica const entry = entries.get(agent) if (entry) { entries.delete(agent); lift(agent, entry) } }) + // Fail open (#962): a counterpart that settled with an unrecoverable runtime failure + // stops hiding the official tool from the agent's next model step. The latch is per + // agent: the payload is shared, but each agent's own accepted call is the evidence + // that its shadow is a dead end, and one agent's repair never guesses for another. + ctx.on('tools/post-execute', async (exec, result, next) => { + const decision = await next() + if (decision.kind !== 'accept' || !exec.agent || !counterparts.has(exec.name)) return decision + const value = (result as { value?: unknown } | undefined)?.value + if (!unrecoverableCounterpartRuntime(value) || broken.has(exec.agent)) return decision + broken.add(exec.agent) + ctx.logger.warn(`dsh-ops: ${mode} replacement counterpart ${exec.name} reported an unrecoverable runtime failure; the official tools stay available for this agent`) + return decision + }) ctx.on('session/event', (_session, event) => { if ((event as { type: string }).type === 'agent-preset/selected') reconcile() }) if (gate.watch) ctx.effect(() => gate.watch!(() => reconcile()), `dsh-ops: ${mode} replacement observer`) // A held step must lose a newly restricted fallback just as it loses an inherited official. diff --git a/test/publication-fail-open.test.mjs b/test/publication-fail-open.test.mjs new file mode 100644 index 00000000..91e52686 --- /dev/null +++ b/test/publication-fail-open.test.mjs @@ -0,0 +1,118 @@ +/** An unrecoverable replacement executor failure must fail open to the official tools (#962). */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { mountReplacements } from '../lib/publication/replacements.js' +import { mountConsumer } from '../lib/consumer/mount.js' +import { resolveConfig } from '../lib/config.js' +import { resolveShells } from '../lib/shells.js' +import { BASH_TOOL } from '../lib/policy.js' +import { assert, test, report } from './lib/harness.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { prepareStep, executeCall } from './lib/executor.mjs' + +const official = name => ({ name, description: 'fixture ' + name, parameters: { type: 'object', properties: {} }, + output: { schema: { type: 'object' }, render: () => [] }, execute: async () => ({ ran: name }) }) +/** One settled host-shaped Bash failure value for a preparation stage. */ +const bashFailureValue = stage => ({ kind: 'foreground', status: 'failed', + error: 'EXECUTOR_UNAVAILABLE: ' + stage + ': fixture payload refused. No command was executed.', + timedOut: false, timeoutMs: 120000, stdout: { text: '', truncated: false }, stderr: { text: '', truncated: false } }) + +async function fixture(counterpartValue) { + const { ctx, tools } = await bootHost() + const agents = [] + ctx.provide('agents', { list: () => agents }) + const removeOfficial = tools.register(official('pwsh')) + const bash = { ...official(BASH_TOOL), execute: async () => counterpartValue } + const removeBash = tools.register(bash) + await ctx.plugin({ apply(inner) { + mountReplacements(inner, { id: 'fail-open', targets: new Map([['pwsh', BASH_TOOL]]), gate: { allows: () => true }, keepOfficial: () => false }) + } }) + await new Promise(resolve => setImmediate(resolve)) + const agent = { id: 'fail-open', session: { id: 'fail-open', header: { cwd: process.cwd() } } } + agent.ctx = createScope(ctx, agent).ctx + agents.push(agent) + await ctx.serial('agent/created', { agent }) + return { ctx, tools, agent, dispose: () => { removeOfficial(); removeBash() } } +} + +const names = step => step.assembly.tools.map(tool => tool.name) +const dispatch = (ctx, agent, step, name) => executeCall(ctx, { agent, toolSet: step.toolSet, name, arguments: {}, callId: name }) + +await test('an unrecoverable counterpart runtime failure lifts the official fallback on the next step', async () => { + const { ctx, agent, dispose } = await fixture(bashFailureValue('bash-runtime-missing')) + try { + const first = await prepareStep(ctx, agent) + try { + assert.equal(new Set(names(first)).has('pwsh'), false, 'the replacement is active before any failure') + const result = await dispatch(ctx, agent, first, BASH_TOOL) + assert.equal(result.isError, false, JSON.stringify(result)) + assert.match(result.value.error, /EXECUTOR_UNAVAILABLE: bash-runtime-missing/) + } finally { first.dispose() } + const second = await prepareStep(ctx, agent) + try { + assert.equal(new Set(names(second)).has('pwsh'), true, 'the official fallback must return after an unrecoverable executor failure') + assert.deepEqual((await dispatch(ctx, agent, second, 'pwsh')).value, { ran: 'pwsh' }) + } finally { second.dispose() } + } finally { dispose(); await shutdown(ctx) } +}) + +await test('a retryable staging failure keeps the replacement in place', async () => { + const { ctx, agent, dispose } = await fixture(bashFailureValue('bash-staging-failed')) + try { + const first = await prepareStep(ctx, agent) + try { await dispatch(ctx, agent, first, BASH_TOOL) } finally { first.dispose() } + const second = await prepareStep(ctx, agent) + try { + assert.equal(new Set(names(second)).has('pwsh'), false, 'a staging interruption is repaired by the next call, not by lifting the shadow') + } finally { second.dispose() } + } finally { dispose(); await shutdown(ctx) } +}) + +await test('only preparation stages no retry can repair are classified unrecoverable', async () => { + const { unrecoverableCounterpartRuntime } = await import('../lib/publication/replacements.js') + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-runtime-missing')), true) + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-ipc-mismatch')), true) + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-lifecycle-lock-busy')), true) + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-cache-unusable')), true) + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-staging-failed')), false) + assert.equal(unrecoverableCounterpartRuntime(bashFailureValue('bash-generation-quarantine-failed')), false) + // The Bash tool description contract quotes remedies; a successful value never classifies. + assert.equal(unrecoverableCounterpartRuntime({ kind: 'foreground', exitCode: 0, stdout: { text: 'EXECUTOR_UNAVAILABLE: bash-runtime-missing: quoted', truncated: false } }), false) + // PTC Outcome failures carry a structured error, not the host message; they stay out of scope. + assert.equal(unrecoverableCounterpartRuntime({ status: 'error', error: { code: 'EXECUTOR_UNAVAILABLE', message: 'DSH authority is unavailable' } }), false) + // 'bash-runtime-incompatible' keeps its own complete message without the EXECUTOR_UNAVAILABLE prefix. + assert.equal(unrecoverableCounterpartRuntime({ error: 'bash-runtime-incompatible: the resolved bash is not the pinned build.' }), true) + assert.equal(unrecoverableCounterpartRuntime({ error: 'EXIT_CODE: command failed' }), false) +}) + +await test('a shell slot whose executor never resolved never hides the official tools', async () => { + const { ctx, tools } = await bootHost() + const agents = [] + try { + ctx.provide('agents', { list: () => agents }) + const removeOfficial = tools.register(official('pwsh')) + // A foreign same-name registration is the #934 host shape: the shadow used to trust its presence. + const removeForeign = tools.register({ ...official(BASH_TOOL), execute: async () => bashFailureValue('bash-runtime-missing') }) + const core = resolveConfig({ promptPolicy: true, publishBashTool: true, bashPath: process.platform === 'win32' ? 'C:/definitely-not-here/niu.exe' : '/definitely-not-here/bash' }) + const bash = resolveShells(core).bash + assert.equal(bash.available, false, 'the fixture must fail resolution') + await ctx.plugin({ inject: ['tools', 'systemPrompt'], apply(inner) { + mountConsumer(inner, { id: 'fail-open-unavailable', gate: { allows: () => true }, core, shell: true, + presentation: 'native', files: false, residentTools: false, discovery: false, + native: { alwaysLoaded: [] }, external: { allowed: [], alwaysLoaded: [], disabled: [] }, + replaceOfficial: true, replacementTargets: new Map([['pwsh', BASH_TOOL]]), section: null }) + } }) + await new Promise(resolve => setImmediate(resolve)) + const agent = { id: 'fail-open-unavailable', session: { id: 'fail-open-unavailable', header: { cwd: process.cwd() } } } + agent.ctx = createScope(ctx, agent).ctx + agents.push(agent) + await ctx.serial('agent/created', { agent }) + const step = await prepareStep(ctx, agent) + try { + assert.equal(new Set(names(step)).has('pwsh'), true, 'an unresolvable Bash executor must keep the official tool visible') + assert.deepEqual((await dispatch(ctx, agent, step, 'pwsh')).value, { ran: 'pwsh' }) + } finally { step.dispose() } + removeOfficial(); removeForeign() + } finally { await shutdown(ctx) } +}) + +report('publication-fail-open') From 6869ed38d1f86002d27a705fdf577ce823c3305d Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 00:43:15 +0800 Subject: [PATCH 4/6] fix(legacy): advertise only admitted tools in the tooling table (#934) The retained file/shell row rendered its table from the root registration view, so a registered-but-unadmitted tool - a replacement shadow on a host whose definition reads ignore when - could appear in the read_image row while the step excluded it. The row now reads the calling scope admitted view with the step tool set and falls back from context.agent to context.scope. Host-side sections that read registrations directly remain an upstream boundary. --- src/legacy/host.ts | 11 +++-- ...lication-legacy-admission-surface.test.mjs | 42 +++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 test/publication-legacy-admission-surface.test.mjs diff --git a/src/legacy/host.ts b/src/legacy/host.ts index cb26fb68..f197e03e 100644 --- a/src/legacy/host.ts +++ b/src/legacy/host.ts @@ -1,6 +1,7 @@ /** Retained pre-single-row component behavior; never part of the current composition root. */ import type { Context } from '../adapter/dsh/types.js' import type { Agent } from '../adapter/dsh/types.js' +import type { ResolvedToolSet } from '../adapter/dsh/types.js' import type {} from '../adapter/dsh/types.js' import type {} from '../adapter/dsh/types.js' import { resolveConfig } from '../config.js' @@ -31,13 +32,15 @@ function report(ctx: Context, message: string, level = 'error'): void { else if (level === 'warn') console.warn(message) else console.error(message) } -function visibleTools(ctx: Context, agent?: Agent): string[] { +function visibleTools(ctx: Context, agent?: Agent, toolSet?: ResolvedToolSet): string[] { try { const tools = ctx.get('tools') // Names only, through the view: `schemas()` projected every visible definition — // 34.2 ms for 258 tools at the published runtime's surface shape — to keep a - // handful of owned names, and this section renders once per assembly. - return tools ? visibleNames(tools, agent) : [] + // handful of owned names, and this section renders once per assembly. The toolSet + // read is the honest one: a host that ignores `when` in its definition reads would + // otherwise advertise a registered-but-unadmitted tool the step excludes (#934). + return tools ? visibleNames(tools, agent, toolSet) : [] } catch { return [] } } @@ -119,7 +122,7 @@ export function applyComponent(root: Context, rawConfig: unknown, component: Com order: SECTION_ORDERS[TOOLING_SECTION] + (component === 'shell' ? 1 : 0), interpolate: false, text: context => renderToolingPolicy({ - published: visibleTools(ctx, context.agent).filter(name => owned.includes(name)), + published: visibleTools(ctx, context.agent ?? context.scope as Agent, context.toolSet).filter(name => owned.includes(name)), shellComponent: component === 'shell', extraGuidance: config.extraGuidance, }), diff --git a/test/publication-legacy-admission-surface.test.mjs b/test/publication-legacy-admission-surface.test.mjs new file mode 100644 index 00000000..3ee615c9 --- /dev/null +++ b/test/publication-legacy-admission-surface.test.mjs @@ -0,0 +1,42 @@ +/** The retained file row must advertise admitted tools, not registered-but-unadmitted ones (#934). */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { applyComponent } from '../lib/legacy/host.js' +import { assert, test, report, waitFor } from './lib/harness.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { prepareStep } from './lib/executor.mjs' + +const SECTION = 'dsh-ops:repository-tooling:file' +const tick = () => new Promise(resolve => setImmediate(resolve)) + +await test('a registered-but-unadmitted tool stays out of the legacy tooling table until admission', async () => { + const { ctx } = await bootHost() + try { + ctx.provide('agents', { list: () => [] }) + ctx.provide('sandboxPolicy', { resolve: () => ({ mode: 'danger-full-access', workspaceRoot: process.cwd() }) }) + ctx.provide('subprocess', { spawn() { throw new Error('legacy surface fixture never spawns') } }) + applyComponent(ctx, { promptPolicy: true }, 'file') + const agent = { id: 'legacy-surface', session: { id: 'legacy-surface', header: { cwd: process.cwd() }, append() {}, read() { return [] } } } + agent.ctx = createScope(ctx, agent).ctx + // The host-bug shape from #934: a same-scope registration whose `when` fails. A host that + // ignores `when` in definitions() reads it as declared while the step excludes it. + let admitted = false + await agent.ctx.plugin({ inject: ['tools'], apply(inner) { + inner.tools.register({ name: 'read_image', description: 'fixture image reader', parameters: { type: 'object', properties: {} }, + output: { schema: { type: 'object' }, render: () => [] }, execute: async () => ({ ran: 'read_image' }) }, + { when: () => admitted }) + } }) + await tick(); await tick() + await waitFor(() => ctx.get('tools').get('ops_read_files', agent), { what: 'legacy file row publication' }) + const text = step => step.assembly.sections.find(section => section.name === SECTION)?.text ?? '' + const hidden = await prepareStep(ctx, agent) + try { + assert.doesNotMatch(text(hidden), /read_image/, 'a registered-but-unadmitted tool must not be advertised') + assert.match(text(hidden), /ops_read_files/, "the row's own admitted tools stay advertised") + } finally { hidden.dispose() } + admitted = true + const shown = await prepareStep(ctx, agent) + try { assert.match(text(shown), /read_image \(host\)/, 'admitting the tool brings the row back') } finally { shown.dispose() } + } finally { await shutdown(ctx) } +}) + +report('publication-legacy-admission-surface') From 6badb9349aaec097ec29391391c7f3eb2a9b5a44 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 00:43:16 +0800 Subject: [PATCH 5/6] docs(changelog): record deferred rejections, fail-open and admission-surface fixes --- docs/CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d66194e1..6f8c8a86 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -12,6 +12,18 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - The Bash tool description now states the parse contract of `stdout`/`stderr` where the model reads it: `text` may be a partial fragment, `truncated` marks one that must not be parsed as complete structured output, and `spillPath` is optional and not a completeness guarantee. The typed output schema is unchanged: repeating the contract there would cost every PTC request without saying anything the tool text does not. Command semantics, exit codes, result values, limits, spill files, permissions and rendering are unchanged. - Bash 工具说明现在在模型读取它的地方写明 `stdout`/`stderr` 的解析契约:文本可能只是片段,`truncated` 标记的片段不得当作完整结构化输出解析,`spillPath` 是可选项且不保证完整。输出类型 schema 保持不变:在那里重复这段契约只会让每个 PTC 请求更贵,并不会多说明什么。命令语义、退出码、结果值、上限、落盘、权限与渲染均不变。 +- A registered-but-unselected PTC pool API now answers a direct call with `SDK_NOT_LOADED` and a next action naming `ops_load_sdk` and its raw name, instead of `PUBLICATION_GRANT_UNAVAILABLE` (retry: never) on the file-lease path or a bare `POLICY_DENIED` on the PTC-only path. Hosts that render registered definitions can still declare the whole allowed pool, but the load flow now matches that declaration: the refusal says how to make the API callable (selection lands on the next model step) and stays honest when the current policy cannot load the API at all. Loader-less scopes keep registering nothing from the pool (#887 unchanged) (#968). +- 已注册但未选中的 PTC 候选池 API 被直接调用时,现在返回 `SDK_NOT_LOADED`,并在 nextAction 中点名 `ops_load_sdk` 与原始名称,不再在文件租约路径上返回 `PUBLICATION_GRANT_UNAVAILABLE`(retry: never)、在 PTC 专属路径上只返回光秃秃的 `POLICY_DENIED`。仍会渲染全部注册定义的宿主依旧可能声明整个 allowedTools 池,但加载流程与该声明现在一致:拒绝会说明如何让该 API 可调用(选择在下一模型步骤生效),且当前策略根本无法加载该 API 时保持诚实的通用拒绝。无 loader 作用域仍不注册池内任何项(#887 不变)(#968)。 + +- An unselected discovery capability, built-in or external provider, now answers a direct call with `CAPABILITY_NOT_SELECTED` and a next action naming `ops_discover_tools` with a `select:` query, instead of `PUBLICATION_GRANT_UNAVAILABLE` or a bare `POLICY_DENIED` that pointed nowhere. The pointer stays honest: a read-only scope that can never select a mutating capability keeps the generic refusal, and once a `select:` query has committed at step end the deferred rejection stops answering (#764). +- 未选中的发现能力(内置或外部 provider)被直接调用时,现在返回 `CAPABILITY_NOT_SELECTED`,并在 nextAction 中给出带 `select:` 查询的 `ops_discover_tools` 指引,不再返回无处可去的 `PUBLICATION_GRANT_UNAVAILABLE` 或光秃秃的 `POLICY_DENIED`。指引保持诚实:永远无法选中变更类能力的只读作用域仍返回通用拒绝;`select:` 查询在步骤结束提交后,延迟拒绝不再应答(#764)。 + +- Replacements fail open when the replacing executor cannot serve. A counterpart Bash call that settles with an unrecoverable preparation failure (`bash-runtime-missing`, `bash-ipc-mismatch`, `bash-lifecycle-lock-busy`, `bash-cache-unusable`, `bash-runtime-incompatible`) stops hiding the official tool from that agent's next model step, and a consumer whose Bash slot never resolved an executor keeps the official tools admitted even when a foreign same-name registration exists. Staging interruptions that the next call repairs keep the replacement in place. The lockout class of #962 — every official tool hidden behind a dead executor — is closed for these stages; a counterpart failure outside this vocabulary keeps the shadow, and the host-side rendering that ignores `when` remains upstream (#962). +- 替换在替换执行器无法服务时失效开放(fail-open):对应方 Bash 调用以不可恢复的准备失败(`bash-runtime-missing`、`bash-ipc-mismatch`、`bash-lifecycle-lock-busy`、`bash-cache-unusable`、`bash-runtime-incompatible`)结束时,该 agent 的下一模型步骤不再隐藏官方工具;Bash 槽位从未解析出执行器的消费者,即使存在同名外来注册也保持官方工具可入。下一次调用即可修复的 staging 中断不解除替换。#962 的锁死类——所有官方工具被一个死执行器挡住——对这些阶段已关闭;此词汇表之外的对应方失败仍保持影子,忽略 `when` 的宿主侧渲染仍属上游(#962)。 + +- The retained legacy file/shell row renders its tooling table from the calling scope's admitted view (`definitions` with the step tool set, falling back from `context.agent` to `context.scope`) instead of the root registration view. The host's `ctx.tools.get`/`definitions` reads ignore `when`, so a registered-but-unadmitted tool, for example a replacement shadow, could appear in the row's `read_image (host)` line while the step excluded it. The row now matches step admission; host-side sections that read registrations directly remain an upstream boundary outside this repository's control (#934). +- 保留的旧版 file/shell 行改为从调用作用域的已准入视图(带步骤 tool set 的 `definitions` 读取,并在 `context.agent` 缺席时回退 `context.scope`)渲染工具表,不再读取根注册视图。宿主的 `ctx.tools.get`/`definitions` 读取不检查 `when`,因此已注册但未准入的工具(例如替换影子)可能出现在该行的 `read_image (host)` 行里而步骤并不包含它。该行现在与步骤准入一致;直接读注册表的宿主侧提示词段落仍属上游边界,不在本仓控制范围(#934)。 + - 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` 键仍可加载但不再生效。 From c06f6e8c68c3ffed7259a65cfd363023711dcc64 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 08:18:09 +0800 Subject: [PATCH 6/6] fix(registrar): consult every deferred advisor in grant order (#968) A no-entitled-grant call consulted only the first same-agent grant carrying a deferred() advisor; when that advisor answered undefined or threw, the caller got the generic PUBLICATION_GRANT_UNAVAILABLE even though a later grant could point at ops_load_sdk or ops_discover_tools. One entry can hold several same-agent file leases (a PTC pool grant and a discovery pool grant for the same public name), so the consultation now walks every same-agent advisor in grant order, returns the first outcome that carries an error, falls through undefined and throwing advisors, and keeps the honest generic denial when none can help. Regression: publication-registrar gains a three-advisor ordering test plus first-wins and helpless controls. --- docs/CHANGELOG.md | 3 ++ src/publication/registrar.ts | 17 +++++------ test/publication-registrar.test.mjs | 45 +++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6f8c8a86..cef4011e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -27,6 +27,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` 键仍可加载但不再生效。 +- When no grant is entitled, the publication registrar consults every same-agent `deferred()` advisor in grant order instead of only the first one it finds. An advisor that answers `undefined` or throws no longer masks a later grant's pointer: one entry can hold several same-agent file leases — a PTC pool grant and a discovery pool grant for the same public name — and a host that ignores `when` used to get `PUBLICATION_GRANT_UNAVAILABLE` (retry: never) even though a later advisor could name `ops_load_sdk` or `ops_discover_tools`. The first advisor that answers wins; when none can help, the honest generic denial stays (#968 review finding). +- 无有资格 grant 时,发布 registrar 按插入顺序逐一咨询同 agent 的每个 `deferred()` advisor,不再只问找到的第一个。返回 `undefined` 或抛错的 advisor 不再遮蔽后续 grant 的指路:同一个注册项可同时持有多个同 agent 的文件租约——例如 PTC 候选池与发现池指向同一公开名——忽略 `when` 的宿主此前会拿到 `PUBLICATION_GRANT_UNAVAILABLE`(retry: never),即使后面的 advisor 本可点名 `ops_load_sdk` 或 `ops_discover_tools`。第一个给出答案的 advisor 胜出;全都无法指路时保持诚实的通用拒绝(#968 审核发现)。 + ## [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/publication/registrar.ts b/src/publication/registrar.ts index 7e8267dd..a4635229 100644 --- a/src/publication/registrar.ts +++ b/src/publication/registrar.ts @@ -142,15 +142,14 @@ export async function acquire(ctx: Context, scope: object | undefined, name: str if (!matching.length) { // Same-agent grants with no entitled member can still explain themselves: a pool // publication points its caller at the loader instead of a retry-never denial (#968). - const advice = [...grants].find(grant => grant.agent === exec.agent && typeof grant.deferred === 'function') - if (advice !== undefined) { - const deferred = advice.deferred - if (typeof deferred === 'function') { - try { - const outcome = deferred() - if (outcome !== undefined && 'error' in outcome) return outcome - } catch { /* an unavailable advisor falls back to the generic denial */ } - } + // Consult every same-agent advisor in grant order: one that cannot help — by + // answering undefined or by throwing — must not mask later grants that can. + for (const advisor of grants) { + if (advisor.agent !== exec.agent || typeof advisor.deferred !== 'function') continue + try { + const outcome = advisor.deferred() + if (outcome !== undefined && 'error' in outcome) return outcome + } catch { /* an unavailable advisor falls through to the next one */ } } return denied('PUBLICATION_GRANT_UNAVAILABLE') } diff --git a/test/publication-registrar.test.mjs b/test/publication-registrar.test.mjs index b9e4a3b2..64d077dd 100644 --- a/test/publication-registrar.test.mjs +++ b/test/publication-registrar.test.mjs @@ -121,6 +121,51 @@ await test('grant diagnostics distinguish missing or conflicting dispatch from i } finally { await shutdown(ctx) } }) +await test('no-entitled advisors answer in grant order; undefined or throwing ones do not mask later guidance', async () => { + const { ctx, tools } = await bootHost() + try { + const a = agentScope(ctx, 'advised') + const guidance = { status: 'error', error: { code: 'ADVISOR_GUIDANCE', effectState: 'none', retry: 'never', + message: 'point at the loader', nextAction: 'load the API first' } } + // One entry can hold several same-agent file grants (for example a PTC pool grant + // and a discovery pool grant for the same public name). Consultation must cover + // every grant in insertion order: an advisor that cannot help — by answering + // undefined or by throwing — must not mask a later grant's pointer with the + // generic retry-never denial (#968 review finding). + const lease = await acquire(ctx, undefined, name, canonical) + const consulted = [] + const silent = () => { consulted.push('silent'); return undefined } + const broken = () => { consulted.push('broken'); throw new Error('advisor exploded') } + const guiding = () => { consulted.push('guiding'); return guidance } + lease.grant(grant(a, 'silent', { entitled: false, deferred: silent })) + lease.grant(grant(a, 'broken', { entitled: false, deferred: broken })) + lease.grant(grant(a, 'guiding', { entitled: false, deferred: guiding })) + const definition = tools.get(name) ?? tools.definitions().find(candidate => candidate.name === name) + assert.ok(definition, 'a lease whose grants are all not-entitled still registers') + const result = await definition.execute({}, { agent: a, toolSet: { view: () => new Map([[name, definition]]) } }) + assert.deepEqual(result, guidance, 'the third advisor must answer instead of the generic denial') + assert.deepEqual(consulted, ['silent', 'broken', 'guiding'], 'every advisor is consulted once, in grant order') + // Control: the first advisor that answers wins; consultation never runs past it. + const ordered = await acquire(ctx, undefined, name + '-order', canonical) + const firstOutcome = { ...guidance, error: { ...guidance.error, code: 'FIRST_WINS' } } + let later = 0 + ordered.grant(grant(a, 'answers-first', { entitled: false, deferred: () => firstOutcome })) + ordered.grant(grant(a, 'never-asked', { entitled: false, deferred: () => { ++later; return guidance } })) + const second = tools.get(name + '-order') + assert.deepEqual(await second.execute({}, { agent: a, toolSet: { view: () => new Map([[name + '-order', second]]) } }), firstOutcome) + assert.equal(later, 0, 'consultation stops at the first advisor that answers') + // Control: no advisor able to help keeps the honest generic denial. + const helpless = await acquire(ctx, undefined, name + '-silent', canonical) + helpless.grant(grant(a, 'cannot-help', { entitled: false, deferred: () => undefined })) + helpless.grant(grant(a, 'explodes', { entitled: false, deferred: () => { throw new Error('no guidance') } })) + const third = tools.get(name + '-silent') + const denied = await third.execute({}, { agent: a, toolSet: { view: () => new Map([[name + '-silent', third]]) } }) + assert.equal(denied.status, 'rejected') + assert.equal(denied.error.code, 'PUBLICATION_GRANT_UNAVAILABLE') + lease.dispose(); ordered.dispose(); helpless.dispose() + } finally { await shutdown(ctx) } +}) + await test('late ancestor source withdraws fallback synchronously and unload stays conservative', async () => { const { ctx, tools } = await bootHost() const steps = []