Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

- Distinguish a historical replay from a lost lesson in step-tail teaching (#998). \`registerStepTailProvider\` accepts an opt-in \`dedupe: 'visible'\` and each \`provide\` call now receives \`context.visible\` (\`{ any, current }\`) read from the agent's derived model-visible history before the batch commits. With the option, a contribution already visible at the same id and revision is skipped entirely, so a session restored from its seed adds 0 new messages instead of re-teaching what the log already shows, while a compaction \`replace\` that removes the visible message re-arms the provider; a provider without the option may still append on every batch. The ops-ptc batching lesson opts in: after a compaction removed it, the next accepted batch delivers exactly one short re-anchor (\`COMPACTED_TEACHING_REMINDER\`) instead of the whole lesson, an older visible revision re-teaches the new wording in full, a batch withdrawn before admission still leaves the lesson to the next accepted one, and the lesson text and revision are untouched. \`test/resident-switch.test.mjs\` fixture sessions gained a \`deriveMessages\` backed by their committed list, because its committed-lesson assertion must now pass on real visibility evidence.
- 区分 step-tail 教学的「历史重放」与「压缩丢失」(#998)。\`registerStepTailProvider\` 新增可选 \`dedupe: 'visible'\`,每次 \`provide\` 调用都会收到 \`context.visible\`(\`{ any, current }\`),取自该批次提交之前的 agent 派生可见历史。开启该选项后,同 id 同 revision 且已可见的贡献会被整体跳过——按 seed 恢复的会话新增 0 条消息,而不是把日志里已有的课再教一遍;压缩 \`replace\` 移除可见消息后 provider 重新武装;未开启选项的 provider 仍可每批追加。ops-ptc 批量教学已启用该选项:压缩移除课程后,下一个被接受的批次只投递一条短重锚(\`COMPACTED_TEACHING_REMINDER\`)而非整课全文;可见的是旧 revision 时按新措辞整课重教;提交前被撤回的批次不消耗教学机会;教学正文与 revision 未动。\`test/resident-switch.test.mjs\` 的假 session 补上了由 committed 列表支撑的 \`deriveMessages\`,因为其「已提交课程不重复」断言现在必须走真实可见性证据。
- Publish the explicit full PTC disclosure tier (#987): with `disclosurePolicy: 'full'` the `ptc` and `ops-ptc` rows' first round now carries the whole permitted `allowedTools` pool plus `ops_result` (the D1 sign-off item 1 decision, taken conservatively per #979 §3 so refs spilled this step stay consumable — and forced by the unified rule, since on-demand can always load `result`) with no `ops_load_sdk`. The first program can call the permitted pool directly; read-only sessions still exclude every write API, an empty cap stays at resident + `result`, `residentTools:false` drops the resident surface but not the tier, duplicated names register once, `global.dynamicTools:false` keeps its veto (the row publishes its legacy surface letter for letter) and a row that also turns its loader off keeps the tier. `PtcConfig.disclosurePolicy` stays optional because custom integrations keep the legacy on-demand default until #988; the builtin plan carries the parsed value. On-demand (default) behaviour is letter-identical; the settings-page entry is #989.
- 发布显式 PTC 全量披露档位(#987):`disclosurePolicy: 'full'` 的 `ptc` 与 `ops-ptc` 行首轮现在携带整个获准 `allowedTools` 池外加 `ops_result`(D1 签字项 1 的保守决定,依 #979 §3 让本步落盘的 ref 仍可消费——统一口径也逼出同一结论,因为按需档永远可加载 `result`),且无 `ops_load_sdk`。第一个程序即可直接调用获准池;只读会话仍排除全部写 API,空上限停在 常驻 + `result`,`residentTools:false` 丢常驻面但不丢档位,重复名只注册一次,`global.dynamicTools:false` 保持否决(该行逐字发布旧面),同时关掉 loader 的行保留档位。`PtcConfig.disclosurePolicy` 保持可选,因为自定义 integration 在 #988 之前维持旧 on-demand 缺省;内置计划携带解析值。按需档(缺省)行为逐字不变;设置页入口归 #989。
- Parse an explicit PTC disclosure policy without changing any legacy behaviour: the `ptc` and `ops-ptc` rows accept a YAML-only `disclosurePolicy` key, `'on-demand'` (default, the legacy progressive path) or `'full'`. Illegal values are errors naming the key and the received value or type, and non-PTC rows reject the key with a readable diagnostic. The choice survives read → save-unrelated-setting → read through the settings serializer, and no upgrade, settings save or `global.dynamicTools` flip ever writes or erases it. The D1 sign-off item on precedence is resolved conservatively: while `global.dynamicTools` is off the full tier is not applied — the row keeps its legacy resident/alwaysLoaded surface — and the saved choice re-applies when the switch returns on; the row-level `dynamicTools` keeps its loader-only meaning because the full tier publishes no loader. Publishing the full tier remains the D3 slice; no publication behaviour or settings UI changes (#986).
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/dsh/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type { Context, Fiber } from '@deepseek-ai/cordis'
export type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
export type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
export type { FileSystem, FsTarget, FsInfo, FsObservation } from '@deepseek-ai/dsh-fs'
export type { GenerateOptions, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm'
export type { GenerateOptions, StreamChunk, Message, UserMessage } from '@deepseek-ai/dsh-llm'
export type { Session } from '@deepseek-ai/dsh-session'
export type { SettingsPathOpView } from '@deepseek-ai/dsh-settings/types'
export type { AssembleContext, PromptAssembly, PromptPresentation, SystemPrompt } from '@deepseek-ai/dsh-system-prompt'
Expand Down
36 changes: 30 additions & 6 deletions src/prompt-injection/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Agent, Context, PreStepDecision, UserMessage } from '../adapter/dsh/types.js'
import type { Agent, Context, Message, PreStepDecision, UserMessage } from '../adapter/dsh/types.js'
import { loadUserMessage } from '../adapter/dsh/host.js'
import { PromptProviderError } from './types.js'
import type { PromptContribution, PromptDisposer, StepTailContext, StepTailProviderOptions, SystemSectionOptions } from './types.js'
export type { PromptContribution, PromptDisposer, StepTailContext, StepTailProviderOptions, SystemSectionOptions } from './types.js'
import type { PromptContribution, PromptDisposer, StepTailContext, StepTailProviderOptions, SystemSectionOptions, VisibleContribution } from './types.js'
export type { PromptContribution, PromptDisposer, StepTailContext, StepTailProviderOptions, SystemSectionOptions, VisibleContribution } from './types.js'
export { PromptProviderError } from './types.js'

interface TailEntry { options: StepTailProviderOptions; active: boolean; lifetime: AbortController }
Expand All @@ -20,6 +20,21 @@ function stateFor(agent: Agent): AgentState {
function validate(options: PromptContribution): void {
if (!options.id.trim() || !options.revision.trim()) throw new TypeError('Prompt id and revision must be nonempty strings.')
if (!Number.isFinite(options.priority ?? 0)) throw new TypeError('Prompt priority must be finite.')
if ((options as StepTailProviderOptions).dedupe !== undefined && (options as StepTailProviderOptions).dedupe !== 'visible') {
throw new TypeError('Step-tail dedupe must be "visible".')
}
}
/** Read one contribution's visibility from the derived model-visible history. */
function readVisibility(history: readonly Message[], id: string, revision: string): VisibleContribution {
let any = false, current = false
for (const message of history) {
if (message.role !== 'user') continue
const source = message.source
if (source?.kind !== 'dsh-ops:step-tail' || source.contributor !== id) continue
any = true
if (source.revision === revision) { current = true; break }
}
return { any, current }
}
function lifetime(owner: Context, agent: Agent, cleanup: PromptDisposer): PromptDisposer {
let active = true
Expand Down Expand Up @@ -71,17 +86,26 @@ function ordered(entries: Iterable<TailEntry>): TailEntry[] {
return [...entries].sort((a, b) => (a.options.priority ?? 0) - (b.options.priority ?? 0)
|| (a.options.id < b.options.id ? -1 : a.options.id > b.options.id ? 1 : 0))
}
async function appendTails(state: AgentState, payload: Omit<StepTailContext, 'messages'>, decision: PreStepDecision): Promise<PreStepDecision> {
async function appendTails(state: AgentState, payload: Omit<StepTailContext, 'messages' | 'visible'>, decision: PreStepDecision): Promise<PreStepDecision> {
if (decision.kind !== 'enter' || !decision.messages.length || payload.signal.aborted || !state.tails.size) return decision
const entries = ordered(state.tails.values())
const context: StepTailContext = Object.freeze({ ...payload, messages: freeze(structuredClone(decision.messages)) })
// The committed history is the visibility evidence for every provider: read it
// once per batch, before this batch itself commits, so a contribution replayed
// from a restored session is distinguishable from a new addition and a
// compaction that removed one is distinguishable from a fresh session.
const history = payload.agent.session.deriveMessages()
const context: Omit<StepTailContext, 'visible'> = Object.freeze({ ...payload, messages: freeze(structuredClone(decision.messages)) })
const pending: { entry: TailEntry; text: string }[] = []
for (const entry of entries) {
if (payload.signal.aborted) return decision
if (!entry.active) continue
const visible = readVisibility(history, entry.options.id, entry.options.revision)
// A same-revision message already visible is a historical replay, not a new
// addition: the provider is skipped entirely instead of re-teaching.
if (entry.options.dedupe === 'visible' && visible.current) continue
try {
const signal = AbortSignal.any([payload.signal, entry.lifetime.signal])
const text = await cancellable(Promise.resolve().then(() => entry.active && !signal.aborted ? entry.options.provide(Object.freeze({ ...context, signal })) : undefined), signal)
const text = await cancellable(Promise.resolve().then(() => entry.active && !signal.aborted ? entry.options.provide(Object.freeze({ ...context, signal, visible })) : undefined), signal)
if (payload.signal.aborted) return decision
if (text !== undefined && typeof text !== 'string') throw new TypeError('Step-tail providers must return text or undefined.')
if (text && entry.active) pending.push({ entry, text })
Expand Down
18 changes: 18 additions & 0 deletions src/prompt-injection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ export interface SystemSectionOptions extends PromptContribution {
readonly text: string | ((context: AssembleContext) => string)
}
export type ReadonlyValue<T> = T extends object ? { readonly [K in keyof T]: ReadonlyValue<T[K]> } : T
/** What the model-visible history currently shows for one step-tail contribution. */
export interface VisibleContribution {
/** A step-tail message of this contributor is visible, whatever its revision. */
readonly any: boolean
/** A visible message of this contributor carries exactly this revision. */
readonly current: boolean
}
export interface StepTailContext {
readonly agent: Agent
readonly turn: number
Expand All @@ -20,8 +27,19 @@ export interface StepTailContext {
readonly signal: AbortSignal
/** Detached, deeply frozen nonempty accepted batch, without this API's contributions. */
readonly messages: readonly ReadonlyValue<UserMessage>[]
/** Visibility of this contribution in the agent's derived history, read before this batch commits. */
readonly visible: VisibleContribution
}
export interface StepTailProviderOptions extends PromptContribution {
/**
* Opt-in restore dedupe: while a step-tail message with this id and revision
* is visible in the agent's derived history, the provider is not evaluated and
* nothing is appended. A session restored from that history therefore adds 0
* messages, while a compaction replace that removes the visible message
* re-arms the provider, whose next provide then sees visible.any === false.
* Without the option every accepted batch may append, as before.
*/
readonly dedupe?: 'visible'
/**
* Called only for accepted nonempty user-message batches, not every model request.
* The final active check before this hook returns its batch to host pre-step is
Expand Down
27 changes: 22 additions & 5 deletions src/publication/ptc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ import { publicationRegistration, publicationReady } from './reentry.js'
import { retired as retiredLegacyRow } from '../settings/legacy.js'
export { resolvePtcConfig } from '../config.js'
export const name = 'dsh-ops-ptc'
/**
* Short re-anchor delivered once when a compaction removed the full lesson from
* the visible history: the compaction summary is assumed to keep the gist, so
* one line re-points the operating rule instead of re-sending the whole lesson.
*/
export const COMPACTED_TEACHING_REMINDER = 'The batch-call guidance delivered earlier is no longer visible in this session history. Keep grouping independent tool calls in one run_code program under Promise.all, open every program with a first-line // plan:, and route file work through the ops_* APIs instead of the shell or Node IO.'

interface Entry {
agent: Agent
Expand All @@ -39,7 +45,7 @@ interface Entry {
pending: Set<ApiName>
definitions: Map<string, ToolDefinition>
disposers: (() => void)[]
/** Whether the teacher trajectory reached session history, not merely the pre-step. */
/** Whether the lesson reached this agent's durable history, not merely the pre-step. After a compaction removes it from view, this latch is what earns the short re-anchor instead of the full text. */
taught: boolean
files: Map<FileToolName | 'result', { lease: PublicationLease; revoke?: () => void; dispatch: ToolDefinition['execute']; granted?: { entitled: boolean; selected: boolean; config: object } }>
}
Expand Down Expand Up @@ -197,13 +203,24 @@ export function mountPtc(root: Context, rawConfig: unknown, gate: PtcGate = { al
// 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.
// The framework skips the provider while the same-revision lesson is
// visible, so a session restored from that history adds 0 new messages
// instead of re-teaching what the model can already see.
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
dedupe: 'visible',
provide(context) {
// Reaching here means the model cannot currently see the lesson:
// an older revision visible is a wording change, so the new text
// teaches anew; nothing visible with the latch set means a
// compaction removed it after it was taught, so one short
// re-anchor; a fresh session gets the full lesson.
if (context.visible.any || !entry.taught) {
const text = loadBatchingGuidance()
return text.length > 0 ? text : undefined
}
return COMPACTED_TEACHING_REMINDER
},
}))
// The program-shape trigger observes the ROOT run_code call: only there is
Expand Down
Loading
Loading