Files
deepseek-harness/packages/core/agent/src/model-selection.ts
T
_KermanandTianyi Cui fb79a944f5 refactor(llm): separate durable producer sources from request inputs
Give durable user context its producer-owned source kind instead of a generic plugin wrapper. The V3-to-V4 conversion preserves the frozen rename and collision rules, all own JSON metadata, event coordinates, and historical request-only kinds. Native catalog and JSONL admission retain source validation so unknown attribution can survive without its producer while malformed owned sources are refused.

Use an explicit user-only RequestUserInput for auxiliary LLM prompts that do not own durable message identity. Auto Review and compaction remove their request-only source registrations while retaining prompt content and freezing; provider serializers and projections keep the same wire data, assistant replay isolation, image ordering, and tool correlation. Session writes, Agent delivery, and recorded title requests continue to require identified durable messages.

Bind the saved compatibility policy only to user sources and qualify tmux location attribution without weakening fixed system, model, or tool semantics. Rebuild the current inventory and unpublished V4 acknowledgement on the actual tool-role parent, preserving its rationale and all accepted historical records. The catalog format version records tooling metadata; Session remains V4. Developer-role policy and activation belong to their own feature.

The latest-master Messages adapter, serialization, request-input typing, EpochHeader reservation, and attribution checks pass 103 tests across five files. The retained V3 Messages input-history snapshot passes through the source profile; Host/Client typechecks and all 41 documentation gates pass. The generated comparison records four changed roots and 447 unchanged type fingerprints. Latest-master ARIA changes are retained, with producer source labels applied independently; new Messages fixtures retain their producer names as declared source kinds and use the fixed system-message helper; recorded Session generations are unchanged by this regrouping.

Co-authored-by: Tianyi Cui <[email protected]>
2026-09-18 19:07:12 +08:00

133 lines
4.9 KiB
TypeScript

/**
* Agent-scoped model selection shared by runtime entry points.
* @module @deepseek-ai/dsh-agent/model-selection
*/
import type { Context } from '@deepseek-ai/cordis'
import {
boundContextSummary,
createUserMessage,
type LlmCallConfig,
type ReasoningEffortId,
} from '@deepseek-ai/dsh-llm'
import type { PreStepDecision } from './runtime-types.ts'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
declare module '@deepseek-ai/dsh-llm' {
interface MessageSourceMap {
'model-selection': { kind: 'model-selection' } & ContextFormed
}
}
/** Complete provider, model, and optional reasoning effort selected for one live Agent. */
export interface ModelSelection {
/** Registered provider route. */
provider: string
/** Provider-owned model id. */
model: string
/** Adapter-owned reasoning effort, or provider/default behavior when absent. */
reasoningEffort?: ReasoningEffortId
}
/** Mutable model selection plus the value captured for the current step. */
export interface ModelSelectionRef {
/** Model selected for the next step that enters prompt assembly. */
current: ModelSelection | undefined
/** Selection captured when the current step entered prompt assembly. */
assembled: ModelSelection | undefined
}
function sameRoute(left: ModelSelection, right: ModelSelection): boolean {
return left.provider === right.provider && left.model === right.model
}
function routeLabel(route: ModelSelection, other: ModelSelection): string {
return route.provider === other.provider ? route.model : `${route.provider}/${route.model}`
}
function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) {
const from = routeLabel(previous, selected)
const to = routeLabel(selected, previous)
return createUserMessage({
content: [{
type: 'text' as const,
text: `[model changed: assistant turns above this point were generated by ${from}; the session continues with ${to}]`,
}],
source: {
kind: 'model-selection',
form: 'notice',
summary: boundContextSummary(`${from} → ${to}`),
},
})
}
/**
* Couple one mutable selection to Agent-scoped prompt assembly and request routing.
* Prompt assembly snapshots the selected model before delegating, then applies
* its provider/model pair and effort to request config so a
* concurrent switch takes effect on a later step instead of splitting the two
* surfaces. An absent selected effort clears any inherited effort, restoring
* the selected model's provider/default behavior.
*
* A provider/model change appends a durable user-role notice to the next
* admitted request. It compares the assembled selection with the latest
* request header; effort-only changes and empty no-request decisions add no
* notice. Failure before header persistence repeats the notice on the next
* request.
*
* @param agentCtx - The selected Agent's scoped context.
* @param selection - Mutable selection owned by the calling entry point.
* @returns Disposer for all scoped waterfall listeners.
*/
export function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void {
const disposeAssembly = agentCtx.on('system-prompt/assemble', async (_assembly, _context, next) => {
const selected = selection.current
const assembled = await next()
selection.assembled = selected
if (selected === undefined) return assembled
return {
...assembled,
variables: {
...assembled.variables,
provider: selected.provider,
model: selected.model,
},
}
})
const disposeRequest = agentCtx.on(
'agent/request',
async (_payload, next): Promise<LlmCallConfig> => {
const resolved = await next()
const selected = selection.assembled
if (selected === undefined) return resolved
const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved
return {
...withoutInheritedEffort,
provider: selected.provider,
model: selected.model,
...selected.reasoningEffort === undefined
? {}
: { reasoningEffort: selected.reasoningEffort },
}
},
)
const disposeNotice = agentCtx.on(
'agent/pre-step',
async ({ agent, messages, signal, step }, next): Promise<PreStepDecision> => {
const decision = await next()
if (decision.kind === 'reject' || signal.aborted) return decision
// The loop skips an empty first step and an emptied offered continuation.
if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision
const selected = selection.assembled
const previous = agent.session.requestHeader()?.config
if (selected === undefined || previous === undefined || sameRoute(selected, previous)) return decision
return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, selected)] }
},
{ prepend: true },
)
return () => {
disposeAssembly()
disposeRequest()
disposeNotice()
}
}